-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoiceService.js
More file actions
241 lines (214 loc) · 8.01 KB
/
Copy pathvoiceService.js
File metadata and controls
241 lines (214 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
'use strict';
/**
* VoiceService — bundled whisper.cpp (offline-first) + OpenAI Whisper cloud fallback.
*/
const fs = require('fs');
const path = require('path');
const { spawn, execSync } = require('child_process');
const os = require('os');
const https = require('https');
const {
resolveWhisperModelPath,
resolveWhisperCliPath,
COMPONENT_IDS,
} = require('./optionalComponentPaths');
const MODEL_URL = 'https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.en.bin';
class VoiceService {
constructor(userDataPath, settingsManager, optionalComponentsManager = null) {
this.userDataPath = userDataPath;
this.settingsManager = settingsManager;
this.optionalComponentsManager = optionalComponentsManager;
this.modelsDir = path.join(userDataPath, 'whisper-models');
this._whisperBin = null;
this._modelPath = null;
this._detectWhisper();
}
_resourcesPath() {
try {
return process.resourcesPath || null;
} catch {
return null;
}
}
_detectWhisper() {
const isWin = process.platform === 'win32';
const binNames = isWin
? ['whisper-cli.exe', 'whisper.exe', 'main.exe']
: ['whisper-cli', 'whisper', 'main'];
const cachedCli = resolveWhisperCliPath(this.userDataPath, this._resourcesPath());
if (cachedCli) {
this._whisperBin = cachedCli;
}
if (!this._whisperBin) {
for (const name of binNames) {
try {
execSync(isWin ? `where ${name}` : `which ${name}`, { stdio: 'pipe' });
this._whisperBin = name;
break;
} catch (_) {}
}
}
const local = path.join(this.modelsDir, 'bin', isWin ? 'whisper-cli.exe' : 'whisper-cli');
if (!this._whisperBin && fs.existsSync(local)) this._whisperBin = local;
this._modelPath = this._resolveModelPath();
}
_resolveModelPath() {
const resolved = resolveWhisperModelPath(this.userDataPath, this._resourcesPath());
if (fs.existsSync(resolved)) return resolved;
return null;
}
async _ensureModel() {
if (this._modelPath && fs.existsSync(this._modelPath)) return this._modelPath;
if (this.optionalComponentsManager) {
const ok = await this.optionalComponentsManager.ensureReady(COMPONENT_IDS.WHISPER);
if (ok) {
this._detectWhisper();
if (this._modelPath && fs.existsSync(this._modelPath)) return this._modelPath;
}
}
fs.mkdirSync(this.modelsDir, { recursive: true });
const dest = path.join(this.modelsDir, 'ggml-base.en.bin');
if (fs.existsSync(dest)) {
this._modelPath = dest;
return dest;
}
await this._downloadFile(MODEL_URL, dest);
this._modelPath = dest;
return dest;
}
_downloadFile(url, dest) {
return new Promise((resolve, reject) => {
fs.mkdirSync(path.dirname(dest), { recursive: true });
const file = fs.createWriteStream(dest);
const req = (u) => {
https.get(u, { headers: { 'User-Agent': 'guIDE-voice' } }, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
file.close();
fs.unlink(dest, () => {});
return req(res.headers.location);
}
if (res.statusCode !== 200) {
file.close();
fs.unlink(dest, () => {});
return reject(new Error(`Model download HTTP ${res.statusCode}`));
}
res.pipe(file);
file.on('finish', () => file.close(() => resolve(dest)));
}).on('error', reject);
};
req(url);
});
}
_voiceProvider() {
return this.settingsManager?.get?.('voiceProvider') || 'auto';
}
async _isOnline() {
return new Promise((resolve) => {
const req = https.request(
{ hostname: 'api.openai.com', port: 443, path: '/', method: 'HEAD', timeout: 3000 },
() => resolve(true),
);
req.on('error', () => resolve(false));
req.on('timeout', () => { req.destroy(); resolve(false); });
req.end();
});
}
getStatus() {
return {
localWhisper: !!this._whisperBin,
whisperPath: this._whisperBin,
modelReady: !!(this._modelPath && fs.existsSync(this._modelPath)),
voiceProvider: this._voiceProvider(),
cloudAvailable: !!(this.settingsManager?.hasApiKey?.('openai')),
webSpeechFallback: true,
};
}
async transcribe(audioBuffer, opts = {}) {
const provider = opts.provider || this._voiceProvider();
const format = opts.format || 'wav';
const tryCloud = provider === 'cloud' || provider === 'auto';
const tryLocal = provider === 'local' || provider === 'auto';
if (tryCloud && this.settingsManager?.hasApiKey?.('openai')) {
const online = await this._isOnline();
if (online) {
try {
const cloud = await this._transcribeCloud(audioBuffer, format);
if (cloud.success) return cloud;
} catch (e) {
if (provider === 'cloud') {
return { success: false, error: e.message, useWebSpeech: true };
}
}
} else if (provider === 'cloud') {
return { success: false, error: 'Offline — cloud STT unavailable', useWebSpeech: false };
}
}
if (tryLocal) {
if (this.optionalComponentsManager && !this._whisperBin) {
await this.optionalComponentsManager.ensureReady(COMPONENT_IDS.WHISPER);
this._detectWhisper();
}
const local = await this._transcribeLocal(audioBuffer, format);
if (local.success) return local;
if (provider === 'local') return local;
}
return { success: false, error: 'Transcription unavailable', useWebSpeech: true };
}
async _transcribeCloud(audioBuffer, format) {
const key = this.settingsManager.getApiKey('openai');
if (!key) return { success: false, error: 'No OpenAI API key configured' };
const ext = format === 'webm' ? 'webm' : 'wav';
const blob = new Blob([audioBuffer], { type: ext === 'webm' ? 'audio/webm' : 'audio/wav' });
const form = new FormData();
form.append('file', blob, `audio.${ext}`);
form.append('model', 'whisper-1');
const res = await fetch('https://api.openai.com/v1/audio/transcriptions', {
method: 'POST',
headers: { Authorization: `Bearer ${key}` },
body: form,
});
if (!res.ok) {
const errText = await res.text().catch(() => '');
return { success: false, error: `Cloud STT failed (${res.status}): ${errText.slice(0, 200)}` };
}
const data = await res.json();
return { success: true, text: (data.text || '').trim(), source: 'cloud' };
}
async _transcribeLocal(audioBuffer, format) {
if (!this._whisperBin) {
return { success: false, error: 'Local Whisper binary not found', useWebSpeech: true };
}
let model;
try {
model = await this._ensureModel();
} catch (e) {
return { success: false, error: `Model download failed: ${e.message}`, useWebSpeech: true };
}
const ext = format === 'webm' ? 'webm' : 'wav';
const inFile = path.join(os.tmpdir(), `guide-voice-${Date.now()}.${ext}`);
const outBase = path.join(os.tmpdir(), `guide-voice-out-${Date.now()}`);
fs.writeFileSync(inFile, audioBuffer);
try {
const args = ['-m', model, '-f', inFile, '-otxt', '-of', outBase, '--no-timestamps'];
await new Promise((resolve, reject) => {
const proc = spawn(this._whisperBin, args, { stdio: 'pipe' });
let stderr = '';
proc.stderr?.on('data', (d) => { stderr += d.toString(); });
proc.on('error', reject);
proc.on('close', (code) => {
if (code === 0) resolve();
else reject(new Error(stderr.trim() || `whisper exit ${code}`));
});
});
const txtPath = `${outBase}.txt`;
const text = fs.existsSync(txtPath) ? fs.readFileSync(txtPath, 'utf8').trim() : '';
try { fs.unlinkSync(txtPath); } catch (_) {}
return { success: true, text, source: 'local' };
} catch (e) {
return { success: false, error: e.message, useWebSpeech: true };
} finally {
try { fs.unlinkSync(inFile); } catch (_) {}
}
}
}
module.exports = { VoiceService };