ai_co_discuss 0.4.13 → 0.4.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/runner.md +168 -168
- package/package.json +1 -1
- package/runner/discussion_launch.mjs +2110 -2110
- package/runner/tts.mjs +173 -172
- package/runner/tts_providers.mjs +436 -435
- package/web/modern.css +1 -1
- package/web/modern.js +3 -3
package/runner/tts_providers.mjs
CHANGED
|
@@ -1,435 +1,436 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Read-aloud providers: what each speech service offers (voices, key root, console) and how one paragraph is
|
|
3
|
-
* synthesized there. Every provider answers the same shape, `{ audio: base64 MP3, format: "mp3", marks: [{ w, t }] }`;
|
|
4
|
-
* `marks` holds per-character start times in ms when the service gives them, otherwise it is empty and the page spreads
|
|
5
|
-
* the highlight by length. The local service answers AAC in MP4 (`format: "m4a"`) instead, as its bundled converter
|
|
6
|
-
* cannot write MP3.
|
|
7
|
-
*/
|
|
8
|
-
import { execFile, spawn } from 'node:child_process';
|
|
9
|
-
import { randomUUID } from 'node:crypto';
|
|
10
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
|
|
11
|
-
import { tmpdir } from 'node:os';
|
|
12
|
-
import { join } from 'node:path';
|
|
13
|
-
import { fileURLToPath } from 'node:url';
|
|
14
|
-
import { promisify } from 'node:util';
|
|
15
|
-
|
|
16
|
-
const TTS_TIMEOUT_MS = 45_000;
|
|
17
|
-
const VOLC_ENDPOINT = 'https://openspeech.bytedance.com/api/v3/tts/unidirectional';
|
|
18
|
-
const VOLC_RESOURCE_ID = 'seed-tts-2.0';
|
|
19
|
-
const VOLC_DONE_CODE = 20000000;
|
|
20
|
-
const VOLC_MESSAGES = {
|
|
21
|
-
40402003: '文本超出单次合成长度上限',
|
|
22
|
-
45000000: '音色不可用:请确认已在火山引擎控制台开通该豆包语音合成 2.0 音色,并核对音色 ID',
|
|
23
|
-
55000000: '火山引擎语音服务暂时出错,请稍后再试',
|
|
24
|
-
};
|
|
25
|
-
const ALIYUN_SOCKET = 'wss://dashscope.aliyuncs.com/api-ws/v1/inference';
|
|
26
|
-
const ALIYUN_MODEL = 'cosyvoice-v3-flash';
|
|
27
|
-
// Its default answered 160 kbps (measured 2026-11-04); 64 kbps (8 KB/s, as Volcengine) keeps a 300-character answer under the 1 MiB relay limit.
|
|
28
|
-
const ALIYUN_BIT_RATE = 64;
|
|
29
|
-
// Aliyun and Azure answer 24 kHz mono MP3, so trailing silence is appended as silent frames of that format.
|
|
30
|
-
const SAMPLE_RATE = 24000;
|
|
31
|
-
// One silent MPEG-2 Layer III frame (24 kHz, 32 kbps, mono): a header and zeroed side info, 576 samples = 24 ms.
|
|
32
|
-
const SILENT_FRAME = Buffer.concat([Buffer.from([0xff, 0xf3, 0x44, 0xc0]), Buffer.alloc(92)]);
|
|
33
|
-
const SILENT_FRAME_MS = 24;
|
|
34
|
-
const AZURE_FORMAT = 'audio-24khz-48kbitrate-mono-mp3';
|
|
35
|
-
// Local speech: yovoice serving Qwen3-TTS CustomVoice on this computer, installed by the local-tts-setup skill into
|
|
36
|
-
// `<service home>/yovoice` (CLI in `cli/`, engine and model in `data/`). Like voice input's local service, the runner
|
|
37
|
-
// starts it through a supervisor (`local_speech_service.mjs`) and renews its lease on every request; a minute without
|
|
38
|
-
// one, or the user stopping reading, stops it, so the model does not hold graphics memory between uses, even when the
|
|
39
|
-
// runner has crashed.
|
|
40
|
-
const LOCAL_HOST = '127.0.0.1:18765';
|
|
41
|
-
const LOCAL_URL = `http://${LOCAL_HOST}`;
|
|
42
|
-
const LOCAL_MODEL = 'qwen3-tts-customvoice-q8';
|
|
43
|
-
const LOCAL_DIR = 'yovoice';
|
|
44
|
-
const LOCAL_START_MS = 30_000;
|
|
45
|
-
const LOCAL_POLL_MS = 500;
|
|
46
|
-
const LOCAL_CONVERT_MS = 30_000;
|
|
47
|
-
// 64 kbps AAC (8 KB/s, as the MP3 services) keeps a 300-character answer under the 1 MiB relay limit.
|
|
48
|
-
const LOCAL_BIT_RATE = '64k';
|
|
49
|
-
const LOCAL_EXE = process.platform === 'win32' ? '.exe' : '';
|
|
50
|
-
const run_file = promisify(execFile);
|
|
51
|
-
const LOCAL_SUPERVISOR = fileURLToPath(new URL('./local_speech_service.mjs', import.meta.url));
|
|
52
|
-
// Voice input on this computer: CrispASR serving Qwen3-ASR 0.6B, installed by the local-stt-setup skill into
|
|
53
|
-
// `<service home>/crispasr` (program in `cli/`, model in `models/`), started, renewed and stopped like the read-aloud
|
|
54
|
-
// service. Measured 2026-11-10 (RTX 5060, cuda13): about 35× realtime once loaded, a 5-minute recording in 8.5 s.
|
|
55
|
-
const LOCAL_STT_HOST = '127.0.0.1';
|
|
56
|
-
const LOCAL_STT_PORT = '18766';
|
|
57
|
-
const LOCAL_STT_URL = `http://${LOCAL_STT_HOST}:${LOCAL_STT_PORT}`;
|
|
58
|
-
const LOCAL_STT_DIR = 'crispasr';
|
|
59
|
-
const LOCAL_STT_MODEL = 'qwen3-asr-0.6b-q8_0.gguf';
|
|
60
|
-
const LOCAL_STT_TIMEOUT_MS = 120_000;
|
|
61
|
-
// While another page request is generating, ask again this often.
|
|
62
|
-
const LOCAL_BUSY_MS = 300;
|
|
63
|
-
// A released lease is dated 1970; anything before this is one.
|
|
64
|
-
const RELEASED_BEFORE_MS = 1000;
|
|
65
|
-
// The engine runs one generation at a time and answers 409 to any other, so requests wait their turn here.
|
|
66
|
-
let local_queue = Promise.resolve();
|
|
67
|
-
|
|
68
|
-
const VOLC_VOICES = [
|
|
69
|
-
['zh_female_vv_uranus_bigtts', 'Vivi · 通用女声'], ['zh_female_xiaohe_uranus_bigtts', '小何 · 通用女声'],
|
|
70
|
-
['zh_male_m191_uranus_bigtts', '云舟 · 通用男声'], ['zh_male_taocheng_uranus_bigtts', '小天 · 通用男声'],
|
|
71
|
-
['zh_male_liufei_uranus_bigtts', '刘飞 · 通用男声'], ['zh_female_sophie_uranus_bigtts', '魅力苏菲 · 女声'],
|
|
72
|
-
['zh_female_qingxinnvsheng_uranus_bigtts', '清新女声'], ['zh_female_cancan_uranus_bigtts', '知性灿灿 · 女声'],
|
|
73
|
-
['zh_female_zhixingnv_uranus_bigtts', '知性女声'], ['zh_female_wenroushunv_uranus_bigtts', '温柔淑女 · 女声'],
|
|
74
|
-
['zh_female_linjianvhai_uranus_bigtts', '邻家女孩'], ['zh_female_shuangkuaisisi_uranus_bigtts', '爽快思思 · 女声'],
|
|
75
|
-
['zh_female_gaolengyujie_uranus_bigtts', '高冷御姐 · 女声'], ['zh_female_xiaoxue_uranus_bigtts', '儿童绘本 · 女声'],
|
|
76
|
-
['zh_male_ruyaqingnian_uranus_bigtts', '儒雅青年 · 男声'], ['zh_male_yangguangqingnian_uranus_bigtts', '阳光青年 · 男声'],
|
|
77
|
-
['zh_male_yuanboxiaoshu_uranus_bigtts', '渊博小叔 · 男声'], ['zh_male_cixingjieshuonan_uranus_bigtts', '磁性解说 · 男声'],
|
|
78
|
-
['zh_male_shenyeboke_uranus_bigtts', '深夜播客 · 男声'], ['zh_male_xuanyijieshuo_uranus_bigtts', '悬疑解说 · 男声'],
|
|
79
|
-
['zh_male_baqiqingshu_uranus_bigtts', '霸气青叔 · 有声书男声'], ['zh_male_yizhipiannan_uranus_bigtts', '译制片男声'],
|
|
80
|
-
['zh_male_jieshuoxiaoming_uranus_bigtts', '解说小明 · 男声'], ['zh_male_wennuanahu_uranus_bigtts', '温暖阿虎 · 男声'],
|
|
81
|
-
];
|
|
82
|
-
// System voices of cosyvoice-v3-flash that read Mandarin and support per-character timings (voice list, 2026-11-04).
|
|
83
|
-
const ALIYUN_VOICES = [
|
|
84
|
-
['longxiaochun_v3', '龙小淳 · 知性女声'], ['longanwen_v3', '龙安温 · 优雅女声'], ['longanli_v3', '龙安莉 · 利落女声'],
|
|
85
|
-
['longyingtao_v3', '龙应桃 · 温柔女声'], ['longyuan_v3', '龙媛 · 治愈女声'], ['longyue_v3', '龙悦 · 磁性女声'],
|
|
86
|
-
['longxing_v3', '龙星 · 邻家女声'], ['longwan_v3', '龙婉 · 细腻女声'], ['longmiao_v3', '龙妙 · 抑扬顿挫女声'],
|
|
87
|
-
['longxiaoxia_v3', '龙小夏 · 沉稳女声'], ['longanyang', '龙安洋 · 阳光男声'], ['longanyun_v3', '龙安昀 · 暖男'],
|
|
88
|
-
['longanlang_v3', '龙安朗 · 清爽男声'], ['longanzhi_v3', '龙安智 · 睿智男声'], ['longcheng_v3', '龙橙 · 智慧青年'],
|
|
89
|
-
['longtian_v3', '龙天 · 磁性男声'], ['longsanshu_v3', '龙三叔 · 沉稳男声'], ['longxiu_v3', '龙修 · 说书男声'],
|
|
90
|
-
['longshu_v3', '龙书 · 沉稳青年'], ['longnan_v3', '龙楠 · 睿智青年'],
|
|
91
|
-
];
|
|
92
|
-
const AZURE_VOICES = [
|
|
93
|
-
['zh-CN-XiaoxiaoNeural', '晓晓 · 女声'], ['zh-CN-XiaoxiaoMultilingualNeural', '晓晓(多语言)· 女声'],
|
|
94
|
-
['zh-CN-XiaochenNeural', '晓辰 · 女声'], ['zh-CN-XiaoyiNeural', '晓伊 · 女声'], ['zh-CN-XiaohanNeural', '晓涵 · 女声'],
|
|
95
|
-
['zh-CN-XiaomoNeural', '晓墨 · 女声'], ['zh-CN-YunxiNeural', '云希 · 男声'],
|
|
96
|
-
['zh-CN-YunjianNeural', '云健 · 男声'], ['zh-CN-YunyangNeural', '云扬 · 新闻男声'], ['zh-CN-YunfengNeural', '云枫 · 男声'],
|
|
97
|
-
['zh-CN-YunzeNeural', '云泽 · 男声'],
|
|
98
|
-
];
|
|
99
|
-
// Qwen3-TTS CustomVoice's built-in speakers; all of them read Chinese, the last four with their own accent.
|
|
100
|
-
const LOCAL_VOICES = [
|
|
101
|
-
['Vivian', 'Vivian · 明亮女声'], ['Serena', 'Serena · 温柔女声'], ['Uncle_Fu', 'Uncle Fu · 低沉男声'],
|
|
102
|
-
['Dylan', 'Dylan · 北京青年男声'], ['Eric', 'Eric · 成都男声'], ['Ryan', 'Ryan · 英语男声'], ['Aiden', 'Aiden · 美式男声'],
|
|
103
|
-
['Ono_Anna', 'Ono Anna · 日语女声'], ['Sohee', 'Sohee · 韩语女声'],
|
|
104
|
-
];
|
|
105
|
-
const voices = (list) => list.map(([id, label]) => ({ id, label }));
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* The speech services the page can choose between. `key_base_url` is the root a saved key is bound to; `context` says
|
|
109
|
-
* whether the tone instruction applies; `region` says whether the service also needs a region; `voice_input` marks the
|
|
110
|
-
* one whose key also serves voice input; `rate: false` marks one that ignores the speech rate; `local` marks the service
|
|
111
|
-
* on this computer, whose token the setup skill saves, so the page asks for no key.
|
|
112
|
-
*/
|
|
113
|
-
export const TTS_PROVIDERS = [
|
|
114
|
-
{ id: 'volcengine', label: '火山引擎', key_base_url: 'https://openspeech.bytedance.com', console_url: 'https://console.volcengine.com/speech/new',
|
|
115
|
-
note: '约 3 元/万字,语音输入共用此 Key', voices: voices(VOLC_VOICES),
|
|
116
|
-
default_speaker: 'zh_female_vv_uranus_bigtts', context: true,
|
|
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
|
-
else if (character === '
|
|
143
|
-
|
|
144
|
-
else if (character === '
|
|
145
|
-
else if (character === '
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
const
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if (item.
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
throw new Error(
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
socket.
|
|
208
|
-
socket.
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
if (
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
socket.
|
|
223
|
-
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
if (response.status ===
|
|
241
|
-
if (
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const
|
|
253
|
-
const
|
|
254
|
-
result.
|
|
255
|
-
result.writeUInt32LE(result.length -
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
*
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
*
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
*
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
*
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
if (
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
if (response.status ===
|
|
343
|
-
if (
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
*
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
{ id: '
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
form
|
|
381
|
-
form.append('
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
*
|
|
389
|
-
* @param {{
|
|
390
|
-
* @
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
*
|
|
415
|
-
* @param {
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
419
|
-
*
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
*
|
|
430
|
-
*
|
|
431
|
-
* @param {string}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Read-aloud providers: what each speech service offers (voices, key root, console) and how one paragraph is
|
|
3
|
+
* synthesized there. Every provider answers the same shape, `{ audio: base64 MP3, format: "mp3", marks: [{ w, t }] }`;
|
|
4
|
+
* `marks` holds per-character start times in ms when the service gives them, otherwise it is empty and the page spreads
|
|
5
|
+
* the highlight by length. The local service answers AAC in MP4 (`format: "m4a"`) instead, as its bundled converter
|
|
6
|
+
* cannot write MP3.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile, spawn } from 'node:child_process';
|
|
9
|
+
import { randomUUID } from 'node:crypto';
|
|
10
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { tmpdir } from 'node:os';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { promisify } from 'node:util';
|
|
15
|
+
|
|
16
|
+
const TTS_TIMEOUT_MS = 45_000;
|
|
17
|
+
const VOLC_ENDPOINT = 'https://openspeech.bytedance.com/api/v3/tts/unidirectional';
|
|
18
|
+
const VOLC_RESOURCE_ID = 'seed-tts-2.0';
|
|
19
|
+
const VOLC_DONE_CODE = 20000000;
|
|
20
|
+
const VOLC_MESSAGES = {
|
|
21
|
+
40402003: '文本超出单次合成长度上限',
|
|
22
|
+
45000000: '音色不可用:请确认已在火山引擎控制台开通该豆包语音合成 2.0 音色,并核对音色 ID',
|
|
23
|
+
55000000: '火山引擎语音服务暂时出错,请稍后再试',
|
|
24
|
+
};
|
|
25
|
+
const ALIYUN_SOCKET = 'wss://dashscope.aliyuncs.com/api-ws/v1/inference';
|
|
26
|
+
const ALIYUN_MODEL = 'cosyvoice-v3-flash';
|
|
27
|
+
// Its default answered 160 kbps (measured 2026-11-04); 64 kbps (8 KB/s, as Volcengine) keeps a 300-character answer under the 1 MiB relay limit.
|
|
28
|
+
const ALIYUN_BIT_RATE = 64;
|
|
29
|
+
// Aliyun and Azure answer 24 kHz mono MP3, so trailing silence is appended as silent frames of that format.
|
|
30
|
+
const SAMPLE_RATE = 24000;
|
|
31
|
+
// One silent MPEG-2 Layer III frame (24 kHz, 32 kbps, mono): a header and zeroed side info, 576 samples = 24 ms.
|
|
32
|
+
const SILENT_FRAME = Buffer.concat([Buffer.from([0xff, 0xf3, 0x44, 0xc0]), Buffer.alloc(92)]);
|
|
33
|
+
const SILENT_FRAME_MS = 24;
|
|
34
|
+
const AZURE_FORMAT = 'audio-24khz-48kbitrate-mono-mp3';
|
|
35
|
+
// Local speech: yovoice serving Qwen3-TTS CustomVoice on this computer, installed by the local-tts-setup skill into
|
|
36
|
+
// `<service home>/yovoice` (CLI in `cli/`, engine and model in `data/`). Like voice input's local service, the runner
|
|
37
|
+
// starts it through a supervisor (`local_speech_service.mjs`) and renews its lease on every request; a minute without
|
|
38
|
+
// one, or the user stopping reading, stops it, so the model does not hold graphics memory between uses, even when the
|
|
39
|
+
// runner has crashed.
|
|
40
|
+
const LOCAL_HOST = '127.0.0.1:18765';
|
|
41
|
+
const LOCAL_URL = `http://${LOCAL_HOST}`;
|
|
42
|
+
const LOCAL_MODEL = 'qwen3-tts-customvoice-q8';
|
|
43
|
+
const LOCAL_DIR = 'yovoice';
|
|
44
|
+
const LOCAL_START_MS = 30_000;
|
|
45
|
+
const LOCAL_POLL_MS = 500;
|
|
46
|
+
const LOCAL_CONVERT_MS = 30_000;
|
|
47
|
+
// 64 kbps AAC (8 KB/s, as the MP3 services) keeps a 300-character answer under the 1 MiB relay limit.
|
|
48
|
+
const LOCAL_BIT_RATE = '64k';
|
|
49
|
+
const LOCAL_EXE = process.platform === 'win32' ? '.exe' : '';
|
|
50
|
+
const run_file = promisify(execFile);
|
|
51
|
+
const LOCAL_SUPERVISOR = fileURLToPath(new URL('./local_speech_service.mjs', import.meta.url));
|
|
52
|
+
// Voice input on this computer: CrispASR serving Qwen3-ASR 0.6B, installed by the local-stt-setup skill into
|
|
53
|
+
// `<service home>/crispasr` (program in `cli/`, model in `models/`), started, renewed and stopped like the read-aloud
|
|
54
|
+
// service. Measured 2026-11-10 (RTX 5060, cuda13): about 35× realtime once loaded, a 5-minute recording in 8.5 s.
|
|
55
|
+
const LOCAL_STT_HOST = '127.0.0.1';
|
|
56
|
+
const LOCAL_STT_PORT = '18766';
|
|
57
|
+
const LOCAL_STT_URL = `http://${LOCAL_STT_HOST}:${LOCAL_STT_PORT}`;
|
|
58
|
+
const LOCAL_STT_DIR = 'crispasr';
|
|
59
|
+
const LOCAL_STT_MODEL = 'qwen3-asr-0.6b-q8_0.gguf';
|
|
60
|
+
const LOCAL_STT_TIMEOUT_MS = 120_000;
|
|
61
|
+
// While another page request is generating, ask again this often.
|
|
62
|
+
const LOCAL_BUSY_MS = 300;
|
|
63
|
+
// A released lease is dated 1970; anything before this is one.
|
|
64
|
+
const RELEASED_BEFORE_MS = 1000;
|
|
65
|
+
// The engine runs one generation at a time and answers 409 to any other, so requests wait their turn here.
|
|
66
|
+
let local_queue = Promise.resolve();
|
|
67
|
+
|
|
68
|
+
const VOLC_VOICES = [
|
|
69
|
+
['zh_female_vv_uranus_bigtts', 'Vivi · 通用女声'], ['zh_female_xiaohe_uranus_bigtts', '小何 · 通用女声'],
|
|
70
|
+
['zh_male_m191_uranus_bigtts', '云舟 · 通用男声'], ['zh_male_taocheng_uranus_bigtts', '小天 · 通用男声'],
|
|
71
|
+
['zh_male_liufei_uranus_bigtts', '刘飞 · 通用男声'], ['zh_female_sophie_uranus_bigtts', '魅力苏菲 · 女声'],
|
|
72
|
+
['zh_female_qingxinnvsheng_uranus_bigtts', '清新女声'], ['zh_female_cancan_uranus_bigtts', '知性灿灿 · 女声'],
|
|
73
|
+
['zh_female_zhixingnv_uranus_bigtts', '知性女声'], ['zh_female_wenroushunv_uranus_bigtts', '温柔淑女 · 女声'],
|
|
74
|
+
['zh_female_linjianvhai_uranus_bigtts', '邻家女孩'], ['zh_female_shuangkuaisisi_uranus_bigtts', '爽快思思 · 女声'],
|
|
75
|
+
['zh_female_gaolengyujie_uranus_bigtts', '高冷御姐 · 女声'], ['zh_female_xiaoxue_uranus_bigtts', '儿童绘本 · 女声'],
|
|
76
|
+
['zh_male_ruyaqingnian_uranus_bigtts', '儒雅青年 · 男声'], ['zh_male_yangguangqingnian_uranus_bigtts', '阳光青年 · 男声'],
|
|
77
|
+
['zh_male_yuanboxiaoshu_uranus_bigtts', '渊博小叔 · 男声'], ['zh_male_cixingjieshuonan_uranus_bigtts', '磁性解说 · 男声'],
|
|
78
|
+
['zh_male_shenyeboke_uranus_bigtts', '深夜播客 · 男声'], ['zh_male_xuanyijieshuo_uranus_bigtts', '悬疑解说 · 男声'],
|
|
79
|
+
['zh_male_baqiqingshu_uranus_bigtts', '霸气青叔 · 有声书男声'], ['zh_male_yizhipiannan_uranus_bigtts', '译制片男声'],
|
|
80
|
+
['zh_male_jieshuoxiaoming_uranus_bigtts', '解说小明 · 男声'], ['zh_male_wennuanahu_uranus_bigtts', '温暖阿虎 · 男声'],
|
|
81
|
+
];
|
|
82
|
+
// System voices of cosyvoice-v3-flash that read Mandarin and support per-character timings (voice list, 2026-11-04).
|
|
83
|
+
const ALIYUN_VOICES = [
|
|
84
|
+
['longxiaochun_v3', '龙小淳 · 知性女声'], ['longanwen_v3', '龙安温 · 优雅女声'], ['longanli_v3', '龙安莉 · 利落女声'],
|
|
85
|
+
['longyingtao_v3', '龙应桃 · 温柔女声'], ['longyuan_v3', '龙媛 · 治愈女声'], ['longyue_v3', '龙悦 · 磁性女声'],
|
|
86
|
+
['longxing_v3', '龙星 · 邻家女声'], ['longwan_v3', '龙婉 · 细腻女声'], ['longmiao_v3', '龙妙 · 抑扬顿挫女声'],
|
|
87
|
+
['longxiaoxia_v3', '龙小夏 · 沉稳女声'], ['longanyang', '龙安洋 · 阳光男声'], ['longanyun_v3', '龙安昀 · 暖男'],
|
|
88
|
+
['longanlang_v3', '龙安朗 · 清爽男声'], ['longanzhi_v3', '龙安智 · 睿智男声'], ['longcheng_v3', '龙橙 · 智慧青年'],
|
|
89
|
+
['longtian_v3', '龙天 · 磁性男声'], ['longsanshu_v3', '龙三叔 · 沉稳男声'], ['longxiu_v3', '龙修 · 说书男声'],
|
|
90
|
+
['longshu_v3', '龙书 · 沉稳青年'], ['longnan_v3', '龙楠 · 睿智青年'],
|
|
91
|
+
];
|
|
92
|
+
const AZURE_VOICES = [
|
|
93
|
+
['zh-CN-XiaoxiaoNeural', '晓晓 · 女声'], ['zh-CN-XiaoxiaoMultilingualNeural', '晓晓(多语言)· 女声'],
|
|
94
|
+
['zh-CN-XiaochenNeural', '晓辰 · 女声'], ['zh-CN-XiaoyiNeural', '晓伊 · 女声'], ['zh-CN-XiaohanNeural', '晓涵 · 女声'],
|
|
95
|
+
['zh-CN-XiaomoNeural', '晓墨 · 女声'], ['zh-CN-YunxiNeural', '云希 · 男声'],
|
|
96
|
+
['zh-CN-YunjianNeural', '云健 · 男声'], ['zh-CN-YunyangNeural', '云扬 · 新闻男声'], ['zh-CN-YunfengNeural', '云枫 · 男声'],
|
|
97
|
+
['zh-CN-YunzeNeural', '云泽 · 男声'],
|
|
98
|
+
];
|
|
99
|
+
// Qwen3-TTS CustomVoice's built-in speakers; all of them read Chinese, the last four with their own accent.
|
|
100
|
+
const LOCAL_VOICES = [
|
|
101
|
+
['Vivian', 'Vivian · 明亮女声'], ['Serena', 'Serena · 温柔女声'], ['Uncle_Fu', 'Uncle Fu · 低沉男声'],
|
|
102
|
+
['Dylan', 'Dylan · 北京青年男声'], ['Eric', 'Eric · 成都男声'], ['Ryan', 'Ryan · 英语男声'], ['Aiden', 'Aiden · 美式男声'],
|
|
103
|
+
['Ono_Anna', 'Ono Anna · 日语女声'], ['Sohee', 'Sohee · 韩语女声'],
|
|
104
|
+
];
|
|
105
|
+
const voices = (list) => list.map(([id, label]) => ({ id, label }));
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The speech services the page can choose between. `key_base_url` is the root a saved key is bound to; `context` says
|
|
109
|
+
* whether the tone instruction applies and `default_context` is the tone each starts with; `region` says whether the service also needs a region; `voice_input` marks the
|
|
110
|
+
* one whose key also serves voice input; `rate: false` marks one that ignores the speech rate; `local` marks the service
|
|
111
|
+
* on this computer, whose token the setup skill saves, so the page asks for no key.
|
|
112
|
+
*/
|
|
113
|
+
export const TTS_PROVIDERS = [
|
|
114
|
+
{ id: 'volcengine', label: '火山引擎', key_base_url: 'https://openspeech.bytedance.com', console_url: 'https://console.volcengine.com/speech/new',
|
|
115
|
+
note: '约 3 元/万字,语音输入共用此 Key', voices: voices(VOLC_VOICES),
|
|
116
|
+
default_speaker: 'zh_female_vv_uranus_bigtts', context: true,
|
|
117
|
+
default_context: '请用自然放松的语气朗读,像给朋友讲故事一样,有轻重缓急,句子之间自然停顿。', region: false, voice_input: true },
|
|
118
|
+
{ id: 'aliyun', label: '阿里云百炼', key_base_url: 'https://dashscope.aliyuncs.com', console_url: 'https://bailian.console.aliyun.com/?tab=model#/api-key',
|
|
119
|
+
note: '约 2 元/万字(汉字计 2 字符)', voices: voices(ALIYUN_VOICES),
|
|
120
|
+
default_speaker: 'longxiaochun_v3', context: false, region: false, voice_input: false },
|
|
121
|
+
{ id: 'azure', label: 'Azure', key_base_url: 'https://tts.speech.microsoft.com', console_url: 'https://portal.azure.com/#create/Microsoft.CognitiveServicesSpeechServices',
|
|
122
|
+
note: '每月免费约 25 万字,超出约 2 元/万字', voices: voices(AZURE_VOICES),
|
|
123
|
+
default_speaker: 'zh-CN-XiaoxiaoNeural', context: false, region: true, voice_input: false },
|
|
124
|
+
{ id: 'local', label: '本机', key_base_url: LOCAL_URL, console_url: 'https://github.com/leemysw/yovoice',
|
|
125
|
+
note: '本机显卡运行 Qwen3-TTS,不计费;用 local-tts-setup 技能安装', voices: voices(LOCAL_VOICES),
|
|
126
|
+
default_speaker: 'Vivian', context: true, default_context: '语气平静克制,语调平稳,娓娓道来。', region: false, voice_input: false, rate: false, local: true },
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
/** Trailing silence as silent MP3 frames matching Aliyun's and Azure's output. */
|
|
130
|
+
function silence_frames(silence_ms) {
|
|
131
|
+
return Buffer.concat(Array(Math.round(silence_ms / SILENT_FRAME_MS)).fill(SILENT_FRAME));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Split a chunked answer made of concatenated JSON objects, newline-separated or not. */
|
|
135
|
+
export function split_json_objects(text) {
|
|
136
|
+
const objects = [];
|
|
137
|
+
let depth = 0, start = -1, in_string = false, escaped = false;
|
|
138
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
139
|
+
const character = text[index];
|
|
140
|
+
if (in_string) {
|
|
141
|
+
if (escaped) escaped = false;
|
|
142
|
+
else if (character === '\\') escaped = true;
|
|
143
|
+
else if (character === '"') in_string = false;
|
|
144
|
+
} else if (character === '"') in_string = true;
|
|
145
|
+
else if (character === '{') { if (depth++ === 0) start = index; }
|
|
146
|
+
else if (character === '}' && depth > 0 && --depth === 0) objects.push(JSON.parse(text.slice(start, index + 1)));
|
|
147
|
+
}
|
|
148
|
+
return objects;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Volcengine Doubao TTS 2.0: one-way chunked JSON; silence, tone and the shared section are sent as `additions`. */
|
|
152
|
+
async function volc_speak({ key, text, speaker, rate, context, silence, section_id }, request) {
|
|
153
|
+
const additions = { ...(context ? { context_texts: [context] } : {}), ...(section_id ? { section_id } : {}),
|
|
154
|
+
...(silence ? { silence_duration: silence } : {}) };
|
|
155
|
+
const body = { user: { uid: 'codiscuss' }, req_params: { text, speaker,
|
|
156
|
+
audio_params: { format: 'mp3', sample_rate: SAMPLE_RATE, speech_rate: rate, enable_subtitle: true },
|
|
157
|
+
...(Object.keys(additions).length ? { additions: JSON.stringify(additions) } : {}) } };
|
|
158
|
+
let response;
|
|
159
|
+
try {
|
|
160
|
+
response = await request(VOLC_ENDPOINT, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(TTS_TIMEOUT_MS),
|
|
161
|
+
headers: { 'Content-Type': 'application/json', 'X-Api-Key': key, 'X-Api-Resource-Id': VOLC_RESOURCE_ID, 'X-Api-Request-Id': randomUUID() },
|
|
162
|
+
body: JSON.stringify(body) });
|
|
163
|
+
} catch { throw new Error('语音合成请求超时或连接失败,请检查网络后重试'); }
|
|
164
|
+
if (response.status === 401 || response.status === 403) throw new Error('火山引擎拒绝了请求:API Key 无效或未开通豆包语音合成 2.0');
|
|
165
|
+
const objects = split_json_objects(await response.text());
|
|
166
|
+
const chunks = [];
|
|
167
|
+
for (const item of objects) {
|
|
168
|
+
if (item.code === VOLC_DONE_CODE) {
|
|
169
|
+
const marks = objects.flatMap(part => part.sentence?.words || [])
|
|
170
|
+
.map(word => ({ w: String(word.word || ''), t: Math.round(Number(word.startTime || 0) * 1000) }));
|
|
171
|
+
return { audio: Buffer.concat(chunks).toString('base64'), format: 'mp3', marks };
|
|
172
|
+
}
|
|
173
|
+
if (item.code !== 0) throw new Error(`语音合成失败(${item.code}):${VOLC_MESSAGES[item.code] || item.message || '请核对 API Key 与音色'}`);
|
|
174
|
+
if (item.data) chunks.push(Buffer.from(item.data, 'base64'));
|
|
175
|
+
}
|
|
176
|
+
if (!response.ok) throw new Error(`语音合成失败:火山引擎返回 HTTP ${response.status}`);
|
|
177
|
+
throw new Error('语音合成未完成:火山引擎没有返回结束标记');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Per-character timings over all sentences; each sentence's timings may restart at zero, so they are laid end to end. */
|
|
181
|
+
function aliyun_marks(sentences) {
|
|
182
|
+
const marks = [];
|
|
183
|
+
let base = 0, last = 0;
|
|
184
|
+
for (const [, words] of [...sentences].sort((a, b) => a[0] - b[0])) {
|
|
185
|
+
if (Number(words[0].begin_time) + base < last) base = last;
|
|
186
|
+
for (const word of words) marks.push({ w: String(word.text || ''), t: Number(word.begin_time) + base });
|
|
187
|
+
last = Number(words.at(-1).end_time) + base;
|
|
188
|
+
}
|
|
189
|
+
return marks;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Aliyun Bailian CosyVoice over its duplex WebSocket: run-task, the text, finish-task; audio arrives as binary frames. */
|
|
193
|
+
function aliyun_speak({ key, text, speaker, rate, silence }, open) {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
const task_id = randomUUID();
|
|
196
|
+
const chunks = [], sentences = new Map();
|
|
197
|
+
let settled = false;
|
|
198
|
+
const socket = open(ALIYUN_SOCKET, { headers: { Authorization: `Bearer ${key}` } });
|
|
199
|
+
const finish = (error, value) => {
|
|
200
|
+
if (settled) return;
|
|
201
|
+
settled = true; clearTimeout(timer);
|
|
202
|
+
// A close without a status code is never answered by the service, which then holds the connection open.
|
|
203
|
+
try { socket.close(1000); } catch { /* Already closed. */ }
|
|
204
|
+
if (error) reject(error); else resolve(value);
|
|
205
|
+
};
|
|
206
|
+
const timer = setTimeout(() => finish(new Error('语音合成请求超时,请检查网络后重试')), TTS_TIMEOUT_MS);
|
|
207
|
+
const send = (action, payload) => socket.send(JSON.stringify({ header: { action, task_id, streaming: 'duplex' }, payload }));
|
|
208
|
+
socket.binaryType = 'arraybuffer';
|
|
209
|
+
socket.onopen = () => send('run-task', { task_group: 'audio', task: 'tts', function: 'SpeechSynthesizer', model: ALIYUN_MODEL, input: {},
|
|
210
|
+
parameters: { text_type: 'PlainText', voice: speaker, format: 'mp3', sample_rate: SAMPLE_RATE, bit_rate: ALIYUN_BIT_RATE, rate: 1 + rate / 100,
|
|
211
|
+
word_timestamp_enabled: true } });
|
|
212
|
+
socket.onmessage = ({ data }) => {
|
|
213
|
+
if (typeof data !== 'string') { chunks.push(Buffer.from(data)); return; }
|
|
214
|
+
const { header = {}, payload = {} } = JSON.parse(data);
|
|
215
|
+
const sentence = payload.output?.sentence;
|
|
216
|
+
if (sentence?.words?.length) sentences.set(sentence.index, sentence.words);
|
|
217
|
+
if (header.event === 'task-started') { send('continue-task', { input: { text } }); send('finish-task', { input: {} }); }
|
|
218
|
+
else if (header.event === 'task-finished') {
|
|
219
|
+
finish(null, { audio: Buffer.concat([...chunks, silence_frames(silence)]).toString('base64'), format: 'mp3', marks: aliyun_marks(sentences) });
|
|
220
|
+
} else if (header.event === 'task-failed') finish(new Error(`语音合成失败(${header.error_code}):${header.error_message || '请核对 API Key 与音色'}`));
|
|
221
|
+
};
|
|
222
|
+
socket.onerror = () => finish(new Error('连接阿里云百炼失败:请核对 API Key,并确认已开通 CosyVoice 语音合成'));
|
|
223
|
+
socket.onclose = () => finish(new Error('阿里云百炼提前断开了连接,请稍后再试'));
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Escape text for SSML. */
|
|
228
|
+
const xml = (text) => text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);
|
|
229
|
+
|
|
230
|
+
/** Azure neural voices over REST with SSML; the REST answer carries no word timings. */
|
|
231
|
+
async function azure_speak({ key, region, text, speaker, rate, silence }, request) {
|
|
232
|
+
if (!region) throw new Error('尚未填写 Azure 区域:请在设置的“语音”中填写语音资源所在区域');
|
|
233
|
+
const ssml = `<speak version="1.0" xml:lang="zh-CN"><voice name="${xml(speaker)}"><prosody rate="${rate >= 0 ? '+' : ''}${rate}%">${xml(text)}</prosody></voice></speak>`;
|
|
234
|
+
let response;
|
|
235
|
+
try {
|
|
236
|
+
response = await request(`https://${region}.tts.speech.microsoft.com/cognitiveservices/v1`, { method: 'POST', redirect: 'error',
|
|
237
|
+
signal: AbortSignal.timeout(TTS_TIMEOUT_MS), headers: { 'Ocp-Apim-Subscription-Key': key, 'Content-Type': 'application/ssml+xml',
|
|
238
|
+
'X-Microsoft-OutputFormat': AZURE_FORMAT, 'User-Agent': 'codiscuss' }, body: ssml });
|
|
239
|
+
} catch { throw new Error('语音合成请求超时或连接失败,请检查网络与 Azure 区域后重试'); }
|
|
240
|
+
if (response.status === 401 || response.status === 403) throw new Error('Azure 拒绝了请求:请核对 API Key 与区域是否属于同一个语音资源');
|
|
241
|
+
if (response.status === 429) throw new Error('Azure 请求过于频繁(免费档每分钟 20 次),请稍后再试');
|
|
242
|
+
if (!response.ok) throw new Error(`语音合成失败:Azure 返回 HTTP ${response.status},请核对音色名称`);
|
|
243
|
+
const audio = Buffer.from(await response.arrayBuffer());
|
|
244
|
+
return { audio: Buffer.concat([audio, silence_frames(silence)]).toString('base64'), format: 'mp3', marks: [] };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Append trailing silence to a PCM WAV by extending its last (data) chunk with zeroed samples. */
|
|
248
|
+
export function wav_with_silence(wav, silence_ms) {
|
|
249
|
+
if (!silence_ms) return wav;
|
|
250
|
+
let offset = 12;
|
|
251
|
+
while (wav.toString('latin1', offset, offset + 4) !== 'data') offset += 8 + wav.readUInt32LE(offset + 4);
|
|
252
|
+
const block = wav.readUInt16LE(32);
|
|
253
|
+
const silence = Buffer.alloc(Math.round(wav.readUInt32LE(28) * silence_ms / 1000 / block) * block);
|
|
254
|
+
const result = Buffer.concat([wav, silence]);
|
|
255
|
+
result.writeUInt32LE(result.length - 8, 4);
|
|
256
|
+
result.writeUInt32LE(result.length - offset - 8, offset + 4);
|
|
257
|
+
return result;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Ask the local service for one paragraph; the answer is a 24 kHz mono WAV. */
|
|
261
|
+
function local_generate({ key, text, speaker, context }, request) {
|
|
262
|
+
return request(`${LOCAL_URL}/v1/generate`, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(TTS_TIMEOUT_MS),
|
|
263
|
+
headers: { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' },
|
|
264
|
+
body: JSON.stringify({ text, modelId: LOCAL_MODEL, speaker, language: 'zh', ...(context ? { voiceDescription: context } : {}) }) });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Renew a local service's lease (in its directory); its supervisor stops the service once the lease is a minute old. A
|
|
269
|
+
* renewal when a request ends keeps a release that came meanwhile (the user stopped reading), so the release still stops it.
|
|
270
|
+
*/
|
|
271
|
+
function local_renew(directory, { keep_release = false } = {}) {
|
|
272
|
+
const lease = join(directory, 'lease');
|
|
273
|
+
try {
|
|
274
|
+
if (keep_release && statSync(lease).mtimeMs < RELEASED_BEFORE_MS) return;
|
|
275
|
+
writeFileSync(lease, '');
|
|
276
|
+
} catch { /* Not installed: the request reports it. */ }
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Use stopped: date the lease back to 1970, so the supervisor stops the service at its next check (within 5 s). */
|
|
280
|
+
function local_release(directory) {
|
|
281
|
+
try { utimesSync(join(directory, 'lease'), 0, 0); } catch { /* Not running or not installed. */ }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Start an installed local service under its supervisor, detached so it outlives this process, and wait until `ready`
|
|
286
|
+
* answers 200 with the token. `skill` names the setup skill to point at when it is missing.
|
|
287
|
+
*/
|
|
288
|
+
async function local_supervise({ directory, executable, args, env, ready, key, skill, wait_ms = LOCAL_START_MS }, request) {
|
|
289
|
+
if (!existsSync(executable)) throw new Error(`本机服务尚未安装:请让本机 AI 按 ${skill} 技能安装`);
|
|
290
|
+
local_renew(directory);
|
|
291
|
+
spawn(process.execPath, [LOCAL_SUPERVISOR, directory, executable, ...args],
|
|
292
|
+
{ detached: true, windowsHide: true, stdio: 'ignore', env: { ...process.env, ...env } }).unref();
|
|
293
|
+
for (const deadline = Date.now() + wait_ms; Date.now() < deadline;) {
|
|
294
|
+
await new Promise(resolve => setTimeout(resolve, LOCAL_POLL_MS));
|
|
295
|
+
try { if ((await request(ready, { headers: { Authorization: `Bearer ${key}` } })).ok) return; } catch { /* Still starting. */ }
|
|
296
|
+
}
|
|
297
|
+
throw new Error(`本机服务启动超时,请查看 ${join(directory, 'serve.log')}`);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Start the read-aloud service (yovoice). */
|
|
301
|
+
function local_start(home, key, request) {
|
|
302
|
+
const directory = join(home, LOCAL_DIR);
|
|
303
|
+
return local_supervise({ directory, executable: join(directory, 'cli', `yovoice${LOCAL_EXE}`), key, skill: 'local-tts-setup',
|
|
304
|
+
args: ['serve', '--listen', LOCAL_HOST, '--data-dir', join(directory, 'data')], env: { YOVOICE_API_TOKEN: key },
|
|
305
|
+
ready: `${LOCAL_URL}/v1/status` }, request);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Convert the WAV to 64 kbps AAC with the converter yovoice ships, which reads and writes files only. The index (moov)
|
|
310
|
+
* goes before the audio: iPhone Safari rejects a blob with it at the end ("The operation is not supported.").
|
|
311
|
+
*/
|
|
312
|
+
async function local_convert(home, wav) {
|
|
313
|
+
const work = mkdtempSync(join(tmpdir(), 'codiscuss-tts-'));
|
|
314
|
+
try {
|
|
315
|
+
writeFileSync(join(work, 'in.wav'), wav);
|
|
316
|
+
await run_file(join(home, LOCAL_DIR, 'cli', 'tools', `ffmpeg${LOCAL_EXE}`), ['-hide_banner', '-loglevel', 'error', '-i', join(work, 'in.wav'),
|
|
317
|
+
'-c:a', 'aac', '-b:a', LOCAL_BIT_RATE, '-movflags', '+faststart', '-f', 'ipod', join(work, 'out.m4a')], { windowsHide: true, timeout: LOCAL_CONVERT_MS })
|
|
318
|
+
.catch(() => { throw new Error('本机语音转码失败:请重新运行 local-tts-setup 技能修复安装'); });
|
|
319
|
+
return readFileSync(join(work, 'out.m4a'));
|
|
320
|
+
} finally { rmSync(work, { recursive: true, force: true }); }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* One paragraph on the local service, starting it first when nothing listens. The page's requests each run in their own
|
|
325
|
+
* process, so another may be generating: the engine keeps no queue and answers 409, and this one waits its turn.
|
|
326
|
+
*/
|
|
327
|
+
async function local_once({ home, key, text, speaker, context, silence }, { request, convert, start }) {
|
|
328
|
+
const deadline = Date.now() + TTS_TIMEOUT_MS;
|
|
329
|
+
let response, started = false;
|
|
330
|
+
for (;;) {
|
|
331
|
+
try { response = await local_generate({ key, text, speaker, context }, request); }
|
|
332
|
+
catch (error) {
|
|
333
|
+
if (error.name === 'TimeoutError') throw new Error('本机语音合成超时,请稍后再试');
|
|
334
|
+
if (started) throw new Error(`本机语音服务已启动但连接失败,请查看 ${join(home, LOCAL_DIR, 'serve.log')}`);
|
|
335
|
+
await start(home, key, request);
|
|
336
|
+
started = true;
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (response.status !== 409 || Date.now() > deadline) break;
|
|
340
|
+
await new Promise(resolve => setTimeout(resolve, LOCAL_BUSY_MS));
|
|
341
|
+
}
|
|
342
|
+
if (response.status === 401) throw new Error('本机语音服务拒绝了令牌:请重新运行 local-tts-setup 技能,或结束旧的 yovoice 进程后重试');
|
|
343
|
+
if (response.status === 409) throw new Error('本机语音一直在忙,请稍后再试');
|
|
344
|
+
if (!response.ok) {
|
|
345
|
+
const code = (await response.json().catch(() => ({}))).error?.code;
|
|
346
|
+
throw new Error(`本机语音合成失败(HTTP ${response.status}${code ? ` ${code}` : ''}),请查看 ${join(home, LOCAL_DIR, 'data', 'logs')}`);
|
|
347
|
+
}
|
|
348
|
+
const audio = await convert(home, wav_with_silence(Buffer.from(await response.arrayBuffer()), silence));
|
|
349
|
+
return { audio: audio.toString('base64'), format: 'm4a', marks: [] };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** Queue this process's local requests; each renews the lease when it arrives and, unless reading was stopped, when it ends. */
|
|
353
|
+
function local_speak(input, transport) {
|
|
354
|
+
const directory = join(input.home, LOCAL_DIR);
|
|
355
|
+
local_renew(directory);
|
|
356
|
+
const result = local_queue.then(() => local_once(input, transport));
|
|
357
|
+
local_queue = result.catch(() => {}).then(() => local_renew(directory, { keep_release: true }));
|
|
358
|
+
return result;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* The voice-input services the page can choose between; `key_base_url` is the root a saved key is bound to, `local`
|
|
363
|
+
* marks the service on this computer, whose token the setup skill saves.
|
|
364
|
+
*/
|
|
365
|
+
export const STT_PROVIDERS = [
|
|
366
|
+
{ id: 'volcengine', label: '火山引擎', key_base_url: 'https://openspeech.bytedance.com', note: '用火山引擎「录音文件识别2.0」识别,单次最长 5 分钟' },
|
|
367
|
+
{ id: 'local', label: '本机', key_base_url: LOCAL_STT_URL, note: '本机显卡运行 Qwen3-ASR,不计费;用 local-stt-setup 技能安装', local: true },
|
|
368
|
+
];
|
|
369
|
+
|
|
370
|
+
/** Start the voice-input service (CrispASR); its token comes in the environment, never on the command line. */
|
|
371
|
+
function local_stt_start(home, key, request) {
|
|
372
|
+
const directory = join(home, LOCAL_STT_DIR);
|
|
373
|
+
return local_supervise({ directory, executable: join(directory, 'cli', `crispasr${LOCAL_EXE}`), key, skill: 'local-stt-setup',
|
|
374
|
+
args: ['--server', '--host', LOCAL_STT_HOST, '--port', LOCAL_STT_PORT, '--backend', 'qwen3', '-m', join(directory, 'models', LOCAL_STT_MODEL), '-l', 'zh'],
|
|
375
|
+
env: { CRISPASR_API_KEYS: key }, ready: `${LOCAL_STT_URL}/health` }, request);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** Send a recording (16 kHz mono WAV) to the local service. */
|
|
379
|
+
function local_stt_send(key, wav, request) {
|
|
380
|
+
const form = new FormData();
|
|
381
|
+
form.append('file', new Blob([wav], { type: 'audio/wav' }), 'speech.wav');
|
|
382
|
+
form.append('language', 'zh');
|
|
383
|
+
return request(`${LOCAL_STT_URL}/inference`, { method: 'POST', redirect: 'error', signal: AbortSignal.timeout(LOCAL_STT_TIMEOUT_MS),
|
|
384
|
+
headers: { Authorization: `Bearer ${key}` }, body: form });
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Recognize a finished recording on this computer, starting the service when nothing listens.
|
|
389
|
+
* @param {{ home: string, key: string, wav: Buffer }} input
|
|
390
|
+
* @param {{ request?: Function, start?: Function }} [transport] `fetch` and the starter, replaceable in tests.
|
|
391
|
+
* @returns {Promise<string>} The recognized text.
|
|
392
|
+
*/
|
|
393
|
+
export async function local_transcribe({ home, key, wav }, { request = fetch, start = local_stt_start } = {}) {
|
|
394
|
+
const directory = join(home, LOCAL_STT_DIR);
|
|
395
|
+
local_renew(directory);
|
|
396
|
+
try {
|
|
397
|
+
let response;
|
|
398
|
+
try { response = await local_stt_send(key, wav, request); }
|
|
399
|
+
catch (error) {
|
|
400
|
+
if (error.name === 'TimeoutError') throw new Error('本机语音识别超时,请稍后再试');
|
|
401
|
+
await start(home, key, request);
|
|
402
|
+
try { response = await local_stt_send(key, wav, request); }
|
|
403
|
+
catch { throw new Error(`本机语音识别服务已启动但连接失败,请查看 ${join(directory, 'serve.log')}`); }
|
|
404
|
+
}
|
|
405
|
+
if (response.status === 401) throw new Error('本机语音识别服务拒绝了令牌:请重新运行 local-stt-setup 技能,或结束旧的 crispasr 进程后重试');
|
|
406
|
+
if (!response.ok) throw new Error(`本机语音识别失败(HTTP ${response.status}),请查看 ${join(directory, 'serve.log')}`);
|
|
407
|
+
return String((await response.json()).text || '').trim();
|
|
408
|
+
} finally { local_renew(directory); }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const SPEAKERS = { volcengine: volc_speak, aliyun: aliyun_speak, azure: azure_speak };
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Synthesize one paragraph with one provider.
|
|
415
|
+
* @param {string} provider One of TTS_PROVIDERS' ids.
|
|
416
|
+
* @param {{ key: string, text: string, speaker: string, rate: number, context?: string, silence: number, section_id?: string, region?: string, home?: string }} input
|
|
417
|
+
* `rate` is -50..100 (percent faster), `silence` the trailing silence in ms; `home` (the service home) locates the local service.
|
|
418
|
+
* @param {{ request?: Function, open?: Function, convert?: Function, start?: Function }} [transport] `fetch`, WebSocket factory and
|
|
419
|
+
* the local service's converter and starter, replaceable in tests.
|
|
420
|
+
* @returns {Promise<{ audio: string, format: string, marks: { w: string, t: number }[] }>}
|
|
421
|
+
*/
|
|
422
|
+
export function provider_speak(provider, input, { request = fetch, open = (url, init) => new WebSocket(url, init), convert = local_convert,
|
|
423
|
+
start = local_start } = {}) {
|
|
424
|
+
if (provider === 'local') return local_speak(input, { request, convert, start });
|
|
425
|
+
return SPEAKERS[provider](input, provider === 'aliyun' ? open : request);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* The user stopped reading: a service that runs on this computer frees its resources now instead of after its lease;
|
|
430
|
+
* the cloud services hold nothing between requests.
|
|
431
|
+
* @param {string} provider One of TTS_PROVIDERS' ids.
|
|
432
|
+
* @param {string} home The service home.
|
|
433
|
+
*/
|
|
434
|
+
export function provider_release(provider, home) {
|
|
435
|
+
if (provider === 'local') local_release(join(home, LOCAL_DIR));
|
|
436
|
+
}
|