dsh-watch-together 0.3.5 → 0.3.6
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/CHANGELOG.md +44 -0
- package/bin/tts.mjs +331 -232
- package/docs/CONFIG.zh.md +6 -1
- package/docs/VOICE.zh.md +2 -2
- package/docs/plugin.zh.md +1 -1
- package/dsh.plugin.json +1 -1
- package/examples/voice-edge-tts/index.mjs +15 -10
- package/examples/voice-edge-tts/stream/client.mjs +8 -7
- package/examples/voice-edge-tts/stream/daemon.py +136 -42
- package/lib/client.js +167 -4
- package/package.json +2 -2
- package/src/settings/config.js +81 -0
- package/src/settings/page.html +112 -5
- package/src/settings/server.js +13 -2
- package/src/settings/tts-test.js +243 -0
package/docs/CONFIG.zh.md
CHANGED
|
@@ -223,6 +223,8 @@ scripts/start-edge-debug.cmd 9444 # 换端口
|
|
|
223
223
|
{
|
|
224
224
|
"voice": "zh-CN-XiaoxuanNeural",
|
|
225
225
|
"rate": 0,
|
|
226
|
+
"pitch": "+0",
|
|
227
|
+
"volume": 100,
|
|
226
228
|
"edgeTts": "C:/Users/你/.workbuddy/binaries/python/envs/tts/Scripts/edge-tts.exe"
|
|
227
229
|
}
|
|
228
230
|
```
|
|
@@ -233,7 +235,10 @@ node bin/watch.mjs say "试一下声音"
|
|
|
233
235
|
node bin/watch.mjs voices # 列出可选音色(不联网的那几个是系统声音)
|
|
234
236
|
```
|
|
235
237
|
|
|
236
|
-
`rate` 是**语速偏移**(-10 ~ 10),不是"每秒几个字"
|
|
238
|
+
`rate` 是**语速偏移**(-10 ~ 10),不是"每秒几个字";`pitch` 声调(±Hz)、`volume` 音量(0-100)。
|
|
239
|
+
这些都在设置页「声音」里可调(带「试听」)。
|
|
240
|
+
**引擎默认本地 SAPI**(文本不出机器):`tts.json` 写 `{"engine":"edge"}`(或 `edgeTts` 指路径 /
|
|
241
|
+
`DSH_TTS_ENGINE=edge`)才走微软 edge-tts(文本会发给微软);写 `"sapi"` 强制本地。
|
|
237
242
|
|
|
238
243
|
### 4.3 它的节奏是怎么控制的
|
|
239
244
|
|
package/docs/VOICE.zh.md
CHANGED
|
@@ -104,11 +104,11 @@
|
|
|
104
104
|
|
|
105
105
|
并且**同时听到声音**。有这行 + 有声音,就接好了。
|
|
106
106
|
|
|
107
|
-
|
|
107
|
+
**只想立刻试一句、不想等陪看**:手动念一句(默认走**本地 SAPI**,文本不出机器;`tts.json` 写 `{"engine":"edge"}` 显式开启后才走 edge-tts —— 文本会发给微软;音色读你 `tts.json` 里的 `voice`):
|
|
108
108
|
|
|
109
109
|
```bash
|
|
110
110
|
node watch.mjs say "你好,我是晓萱"
|
|
111
|
-
#
|
|
111
|
+
# 强制用系统声音(本地;开着云端时用它强制回本地):
|
|
112
112
|
node watch.mjs say "你好" sapi
|
|
113
113
|
```
|
|
114
114
|
|
package/docs/plugin.zh.md
CHANGED
package/dsh.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-watch-together",
|
|
3
3
|
"description": "Watch a video together, in sync with the user's real playback: each segment arrives as one storyboard image plus its subtitle lines just before it ends, and the floating window carries spoken replies and live room audio.",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.6",
|
|
5
5
|
"entry": {
|
|
6
6
|
"name": "dsh-watch-together",
|
|
7
7
|
"inject": [
|
|
@@ -47,6 +47,7 @@ import { dirname, join } from 'node:path';
|
|
|
47
47
|
import { fileURLToPath } from 'node:url';
|
|
48
48
|
|
|
49
49
|
import { pythonFor, startStream } from './stream/client.mjs';
|
|
50
|
+
import { buildSpeakCommand, edgeCliArgs } from '../../bin/tts.mjs';
|
|
50
51
|
|
|
51
52
|
const run = (bin, args, timeoutMs = 60_000) => new Promise((resolve) => {
|
|
52
53
|
execFile(bin, args, { timeout: timeoutMs, windowsHide: true }, (err) => resolve(!err));
|
|
@@ -121,11 +122,10 @@ function openStream(bin) {
|
|
|
121
122
|
}
|
|
122
123
|
|
|
123
124
|
/** 只合成,不播放。预取和"到点没赶上预取"两条路共用。 */
|
|
124
|
-
async function synthEdge(text, { bin, voice, rate }) {
|
|
125
|
+
async function synthEdge(text, { bin, voice, rate, pitch = null, volume = 100 }) {
|
|
125
126
|
const out = join(tmpdir(), `voice-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.mp3`);
|
|
126
|
-
|
|
127
|
-
const args =
|
|
128
|
-
if (pct) args.push(`--rate=${pct > 0 ? '+' : ''}${pct}%`);
|
|
127
|
+
// 参数换算只写一份(bin/tts.mjs 的 edgeCliArgs):语速/音调/音量口径与 say 命令、设置页试听共用
|
|
128
|
+
const args = edgeCliArgs({ text, voice, rate, pitch, volume, out });
|
|
129
129
|
if (!(await run(bin, args))) {
|
|
130
130
|
try { unlinkSync(out); } catch { /* 没有文件正常 */ }
|
|
131
131
|
return { ok: false, reason: 'synth-failed' };
|
|
@@ -174,9 +174,9 @@ function playEdge(path, onStart = null) {
|
|
|
174
174
|
}
|
|
175
175
|
|
|
176
176
|
/** Windows 系统声音。Linux/macOS 会失败,失败就当没这个引擎。 */
|
|
177
|
-
function speakSapi(text, rate, onStart = null) {
|
|
178
|
-
|
|
179
|
-
const cmd =
|
|
177
|
+
function speakSapi(text, { rate = 0, volume = 100, pitch = null, onStart = null } = {}) {
|
|
178
|
+
// SAPI 命令的口径在 bin/tts.mjs 的 buildSpeakCommand(音量/音调/XML 转义都管,只写一份)
|
|
179
|
+
const cmd = buildSpeakCommand({ text, rate, volume, pitch });
|
|
180
180
|
// PowerShell 冷启动要几百毫秒,上报放在**起进程之前**,宁可略早也别晚(字等声音没关系,声音等字不行)
|
|
181
181
|
try { onStart?.(); } catch { /* 上报失败不影响念 */ }
|
|
182
182
|
// spawn 而不是 execFile:`SpVoice.Speak()` 是阻塞的,只有杀掉进程才能让它闭嘴 ——
|
|
@@ -221,6 +221,11 @@ export function attach(api) {
|
|
|
221
221
|
if (!cfg.voice) console.error('[voice] 未配置 voice(~/.dsh/tts.json),用中性默认 zh-CN-YunxiNeural;'
|
|
222
222
|
+ '想用晓萱等音色请在该文件加 "voice": "zh-CN-XiaoxuanNeural"');
|
|
223
223
|
const rate = Number(cfg.rate) || 0;
|
|
224
|
+
// 音调:口径和 ACT.TTS_CN 一致("+0" 这种写法),三种引擎入口共用它换算
|
|
225
|
+
const pitch = cfg.pitch ?? null;
|
|
226
|
+
// 音量:0-100(100 = 不增不减)
|
|
227
|
+
const volume = cfg.volume === undefined || cfg.volume === null || cfg.volume === ''
|
|
228
|
+
? 100 : Math.max(0, Math.min(100, Number(cfg.volume) || 0));
|
|
224
229
|
const bin = edgeBin(cfg);
|
|
225
230
|
// 常驻合成器:能起就用它(首声 170~200ms),起不来就是 null,全部逻辑退回老路。
|
|
226
231
|
const stream = openStream(bin);
|
|
@@ -279,7 +284,7 @@ export function attach(api) {
|
|
|
279
284
|
prefetched.delete(farthestKey);
|
|
280
285
|
if (old) discard(old);
|
|
281
286
|
}
|
|
282
|
-
const task = prefetchTail.then(() => synthEdge(e.text, { bin, voice, rate }));
|
|
287
|
+
const task = prefetchTail.then(() => synthEdge(e.text, { bin, voice, rate, pitch, volume }));
|
|
283
288
|
prefetchTail = task.then(() => {}, () => {});
|
|
284
289
|
const entry = { task, at: Number(e.at) };
|
|
285
290
|
prefetched.set(key, entry);
|
|
@@ -372,7 +377,7 @@ export function attach(api) {
|
|
|
372
377
|
if (ready) {
|
|
373
378
|
audio = await ready.task.catch(() => ({ ok: false, reason: 'prefetch-failed' }));
|
|
374
379
|
} else {
|
|
375
|
-
audio = await synthEdge(e.text, { bin, voice, rate });
|
|
380
|
+
audio = await synthEdge(e.text, { bin, voice, rate, pitch, volume });
|
|
376
381
|
}
|
|
377
382
|
if (audio?.ok) {
|
|
378
383
|
console.error(`[voice ${mmss(e.at)}] ${ready ? 'prefetched' : 'synth'} `
|
|
@@ -384,7 +389,7 @@ export function attach(api) {
|
|
|
384
389
|
}
|
|
385
390
|
}
|
|
386
391
|
console.error(`[voice ${mmss(e.at)}] sapi ${Date.now() - t0}ms (wait ${waited}ms): ${e.text}`);
|
|
387
|
-
if (!(await speakSapi(e.text, rate, onStart))) console.error('[voice] 系统声音也不可用,只打日志');
|
|
392
|
+
if (!(await speakSapi(e.text, { rate, volume, pitch, onStart }))) console.error('[voice] 系统声音也不可用,只打日志');
|
|
388
393
|
}).catch((err) => console.error(`[voice] ${err?.message ?? err}`));
|
|
389
394
|
});
|
|
390
395
|
|
|
@@ -32,12 +32,13 @@ export function pythonFor(edgeBin) {
|
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
/**
|
|
35
|
-
* @param {{ python: string, script: string, args?: string[], onError?: Function, log?: Function }} o
|
|
35
|
+
* @param {{ python: string, script: string, args?: string[], env?: object|null, onError?: Function, log?: Function }} o
|
|
36
|
+
* `env` 不传 = 继承当前进程环境;传了就整个替换(设置页试听用它塞临时 DSH_HOME)。
|
|
36
37
|
*/
|
|
37
|
-
export function startStream({ python, script, args = ['-u', script], onError, log = () => {} }) {
|
|
38
|
+
export function startStream({ python, script, args = ['-u', script], env = null, onError, log = () => {} }) {
|
|
38
39
|
const extra = process.platform === 'win32' ? { windowsHide: true } : {};
|
|
39
40
|
const proc = spawn(python, args, {
|
|
40
|
-
stdio: ['pipe', 'pipe', 'pipe'], ...extra,
|
|
41
|
+
stdio: ['pipe', 'pipe', 'pipe'], ...extra, ...(env ? { env } : {}),
|
|
41
42
|
});
|
|
42
43
|
|
|
43
44
|
/** id -> {resolve, reject, first} */
|
|
@@ -114,7 +115,7 @@ export function startStream({ python, script, args = ['-u', script], onError, lo
|
|
|
114
115
|
};
|
|
115
116
|
|
|
116
117
|
let seq = 0;
|
|
117
|
-
const ask = (op, text, timeoutMs, onFirst) => new Promise((resolve, reject) => {
|
|
118
|
+
const ask = (op, text, timeoutMs, onFirst, params = null) => new Promise((resolve, reject) => {
|
|
118
119
|
if (dead) { reject(new Error(dead)); return; }
|
|
119
120
|
seq += 1;
|
|
120
121
|
const id = seq;
|
|
@@ -128,7 +129,7 @@ export function startStream({ python, script, args = ['-u', script], onError, lo
|
|
|
128
129
|
resolve: (v) => { clearTimeout(timer); resolve(v); },
|
|
129
130
|
reject: (e) => { clearTimeout(timer); reject(e); },
|
|
130
131
|
});
|
|
131
|
-
if (!send({ op, id, text })) {
|
|
132
|
+
if (!send({ op, id, text, ...(params || {}) })) {
|
|
132
133
|
clearTimeout(timer);
|
|
133
134
|
pending.delete(id);
|
|
134
135
|
reject(new Error(dead || 'send-failed'));
|
|
@@ -140,8 +141,8 @@ export function startStream({ python, script, args = ['-u', script], onError, lo
|
|
|
140
141
|
get warm() { return ready; },
|
|
141
142
|
get lastError() { return lastError; },
|
|
142
143
|
warmUp() { send({ op: 'warm' }); },
|
|
143
|
-
say: (text, { timeoutMs = 30_000, onFirst = null } = {}) => ask('say', text, timeoutMs, onFirst),
|
|
144
|
-
prefetch: (text, timeoutMs = 30_000) => ask('prefetch', text, timeoutMs).catch(() => ({ failed: true })),
|
|
144
|
+
say: (text, { timeoutMs = 30_000, onFirst = null, params = null } = {}) => ask('say', text, timeoutMs, onFirst, params),
|
|
145
|
+
prefetch: (text, timeoutMs = 30_000, params = null) => ask('prefetch', text, timeoutMs, null, params).catch(() => ({ failed: true })),
|
|
145
146
|
forget: (text) => send({ op: 'forget', text }),
|
|
146
147
|
/**
|
|
147
148
|
* 截断正在念的那一句(**不停进程**)。
|
|
@@ -40,6 +40,12 @@ stdin(每行一个 JSON):
|
|
|
40
40
|
{"op":"forget","id":N} 丢掉这句的缓存
|
|
41
41
|
{"op":"stop"}
|
|
42
42
|
|
|
43
|
+
say / prefetch 可随包带**参数覆盖**(设置页试听用,滑块变化不用重启合成器):
|
|
44
|
+
voice / rate(-10..10)/ pitch("+2")/ volume(0-100) ——
|
|
45
|
+
不带就用启动时 tts.json 的默认值;缓存键含参数,参数不同不共用缓存。
|
|
46
|
+
`{"op":"interrupt"}` 会**取消正在合成的整个任务**(不只是掐播放),
|
|
47
|
+
被掐断的那句回 `{"ev":"error","reason":"interrupted"}`。
|
|
48
|
+
|
|
43
49
|
stdout(每行一个 JSON,全部是**状态**,不含音频):
|
|
44
50
|
|
|
45
51
|
{"ev":"ready"} 预热完成
|
|
@@ -250,12 +256,64 @@ class Player:
|
|
|
250
256
|
# --------------------------------------------------------------- 合成
|
|
251
257
|
|
|
252
258
|
|
|
259
|
+
def norm_pitch(pitch):
|
|
260
|
+
"""归一化音调成 edge-tts 的 "+2Hz" 写法(和 ACT.TTS_CN 的口径一致:它配的就是 "+0")。
|
|
261
|
+
|
|
262
|
+
没配 / 配了 0 / 格式不对 → "+0Hz"(行为和不带音调时完全一致)。
|
|
263
|
+
两端单位不同:edge 要赫兹,SAPI 要 `<pitch absmiddle>` 档位 —— 后者在 index.mjs 里换算。
|
|
264
|
+
"""
|
|
265
|
+
s = str(pitch if pitch is not None else "").strip().lower()
|
|
266
|
+
if s.endswith("hz"):
|
|
267
|
+
s = s[:-2].strip()
|
|
268
|
+
try:
|
|
269
|
+
n = float(s)
|
|
270
|
+
except ValueError:
|
|
271
|
+
return "+0Hz"
|
|
272
|
+
if n == 0:
|
|
273
|
+
return "+0Hz"
|
|
274
|
+
n = max(-50.0, min(50.0, n))
|
|
275
|
+
return f"{'+' if n > 0 else ''}{n:g}Hz"
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def norm_volume(volume):
|
|
279
|
+
"""0-100 的音量(100 = 不增不减)→ edge 的相对写法 "+0%"(和 bin/tts.mjs 的 edgeVolumeArg 同口径)。"""
|
|
280
|
+
try:
|
|
281
|
+
n = float(volume)
|
|
282
|
+
except (TypeError, ValueError):
|
|
283
|
+
return "+0%"
|
|
284
|
+
if n == 100:
|
|
285
|
+
return "+0%"
|
|
286
|
+
n = max(0.0, min(150.0, n))
|
|
287
|
+
d = max(-50.0, min(50.0, n - 100))
|
|
288
|
+
return f"{d:+g}%"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def job_params(req, defaults):
|
|
292
|
+
"""say/prefetch 随包带的参数覆盖(设置页试听用:滑块随便拉,合成器不用重启)。
|
|
293
|
+
|
|
294
|
+
没带的键回落到启动时 tts.json 的默认值。返回值同时是**缓存键**的一部分 ——
|
|
295
|
+
参数不同的两句不能共用一份缓存(换了音色/声调还播旧缓存就穿帮了)。
|
|
296
|
+
"""
|
|
297
|
+
voice = str(req.get("voice") or "").strip() or defaults["voice"]
|
|
298
|
+
raw_rate = req.get("rate")
|
|
299
|
+
if raw_rate is None or raw_rate == "":
|
|
300
|
+
rate = defaults["rate"]
|
|
301
|
+
else:
|
|
302
|
+
try:
|
|
303
|
+
rate = f"{'+' if float(raw_rate) >= 0 else ''}{round(float(raw_rate) * 3)}%"
|
|
304
|
+
except (TypeError, ValueError):
|
|
305
|
+
rate = defaults["rate"]
|
|
306
|
+
pitch = norm_pitch(req.get("pitch")) if req.get("pitch") not in (None, "") else defaults["pitch"]
|
|
307
|
+
volume = norm_volume(req.get("volume")) if req.get("volume") not in (None, "") else defaults["volume"]
|
|
308
|
+
return voice, rate, pitch, volume
|
|
309
|
+
|
|
310
|
+
|
|
253
311
|
class EdgeLink:
|
|
254
312
|
"""一条 WebSocket,连发多句。同一时刻只能有一个请求在飞(aiohttp 不允许并发 receive)。"""
|
|
255
313
|
|
|
256
|
-
def __init__(self, voice, rate):
|
|
257
|
-
self.conf = TTSConfig(voice=voice, rate=rate, volume=
|
|
258
|
-
pitch=
|
|
314
|
+
def __init__(self, voice, rate, pitch="+0Hz", volume="+0%"):
|
|
315
|
+
self.conf = TTSConfig(voice=voice, rate=rate, volume=volume,
|
|
316
|
+
pitch=pitch, boundary="SentenceBoundary")
|
|
259
317
|
self.ws = None
|
|
260
318
|
self.session = None
|
|
261
319
|
self.last_used = 0.0
|
|
@@ -301,30 +359,45 @@ class EdgeLink:
|
|
|
301
359
|
pass
|
|
302
360
|
self.session = None
|
|
303
361
|
|
|
304
|
-
async def synth(self, text, on_chunk):
|
|
362
|
+
async def synth(self, text, on_chunk, params=None):
|
|
305
363
|
"""合成一句。`on_chunk(bytes)` 每块调一次 —— 想边收边播就把块直接写进管道。
|
|
306
364
|
|
|
365
|
+
`params` = `job_params()` 的返回值:这一句用哪套音色/语速/声调/音量。
|
|
366
|
+
不传就用启动时 tts.json 的默认值(老行为不变)。
|
|
367
|
+
|
|
307
368
|
返回总字节数。连接中途断掉会重建并**整句重来**(半句音频已经写出去了,
|
|
308
369
|
拼接会错位;这一句宁可慢一次也要完整)。
|
|
309
370
|
"""
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
371
|
+
try:
|
|
372
|
+
for attempt in (0, 1):
|
|
373
|
+
try:
|
|
374
|
+
await self.ensure()
|
|
375
|
+
total = await self._run_turn(text, on_chunk if attempt == 0 else None, params)
|
|
376
|
+
if total is None and attempt == 0:
|
|
377
|
+
continue # 收到一半断了:重来一次,这次先收全再给
|
|
378
|
+
self.last_used = time.monotonic()
|
|
379
|
+
return total
|
|
380
|
+
except Exception as e: # noqa: BLE001
|
|
381
|
+
if attempt == 1:
|
|
382
|
+
raise
|
|
383
|
+
log(f"合成失败,重建连接重试:{e}")
|
|
384
|
+
await self.close()
|
|
385
|
+
return 0
|
|
386
|
+
except asyncio.CancelledError:
|
|
387
|
+
# 被掐断(interrupt):连接可能停在半句响应上 —— 必须重建,
|
|
388
|
+
# 否则上一句残留的响应帧会串进下一句的接收循环。
|
|
389
|
+
await self.close()
|
|
390
|
+
raise
|
|
391
|
+
|
|
392
|
+
async def _run_turn(self, text, on_chunk, params=None):
|
|
326
393
|
rid = uuid.uuid4().hex
|
|
327
|
-
|
|
394
|
+
if params is None:
|
|
395
|
+
conf = self.conf
|
|
396
|
+
else:
|
|
397
|
+
voice, rate, pitch, volume = params
|
|
398
|
+
conf = TTSConfig(voice=voice, rate=rate, volume=volume,
|
|
399
|
+
pitch=pitch, boundary="SentenceBoundary")
|
|
400
|
+
ssml = mkssml(conf, escape(text))
|
|
328
401
|
payload = (f"X-RequestId:{rid}\r\n"
|
|
329
402
|
"Content-Type:application/ssml+xml\r\n"
|
|
330
403
|
f"X-Timestamp:{date_to_string()}Z\r\n"
|
|
@@ -365,22 +438,30 @@ class Daemon:
|
|
|
365
438
|
except ValueError:
|
|
366
439
|
volume = 100
|
|
367
440
|
self.player = Player(volume=volume, loglevel=os.environ.get("DSH_TTS_FFPLAY_LOG") or "quiet")
|
|
368
|
-
self.
|
|
369
|
-
self.
|
|
441
|
+
self.pitch = norm_pitch(cfg.get("pitch"))
|
|
442
|
+
self.volume = norm_volume(cfg.get("volume"))
|
|
443
|
+
self.edge = EdgeLink(self.voice, self.rate, self.pitch, self.volume)
|
|
444
|
+
# 每请求参数的回落默认值(job_params 用)
|
|
445
|
+
self.defaults = {
|
|
446
|
+
"voice": self.voice, "rate": self.rate, "pitch": self.pitch,
|
|
447
|
+
"volume": self.volume,
|
|
448
|
+
}
|
|
449
|
+
self.cache = {} # 参数+文本的缓存键 -> bytes
|
|
370
450
|
self.order = [] # 缓存淘汰顺序
|
|
371
451
|
self.jobs = asyncio.PriorityQueue()
|
|
372
452
|
self.seq = 0
|
|
373
453
|
self.said = {} # id -> text(say 用,便于 forget 精确删)
|
|
374
454
|
self.warm_task = None
|
|
455
|
+
self.job_task = None # 正在跑的合成任务(interrupt 要取消它)
|
|
375
456
|
|
|
376
|
-
def cached(self,
|
|
377
|
-
return self.cache.get(
|
|
457
|
+
def cached(self, key):
|
|
458
|
+
return self.cache.get(key)
|
|
378
459
|
|
|
379
|
-
def remember(self,
|
|
380
|
-
if
|
|
460
|
+
def remember(self, key, data):
|
|
461
|
+
if key in self.cache:
|
|
381
462
|
return
|
|
382
|
-
self.cache[
|
|
383
|
-
self.order.append(
|
|
463
|
+
self.cache[key] = data
|
|
464
|
+
self.order.append(key)
|
|
384
465
|
while len(self.order) > MAX_CACHED:
|
|
385
466
|
old = self.order.pop(0)
|
|
386
467
|
self.cache.pop(old, None)
|
|
@@ -417,15 +498,20 @@ class Daemon:
|
|
|
417
498
|
if op == "forget":
|
|
418
499
|
text = req.get("text") or self.said.get(req.get("id"))
|
|
419
500
|
if text:
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
self.
|
|
423
|
-
|
|
424
|
-
|
|
501
|
+
# 缓存键是 [文本, 参数…]:按文本把所有参数版本一起清掉
|
|
502
|
+
for k in [k for k in self.order if json.loads(k)[0] == text]:
|
|
503
|
+
self.cache.pop(k, None)
|
|
504
|
+
try:
|
|
505
|
+
self.order.remove(k)
|
|
506
|
+
except ValueError:
|
|
507
|
+
pass
|
|
425
508
|
emit(ev="skip", id=req.get("id"))
|
|
426
509
|
return
|
|
427
510
|
if op == "interrupt":
|
|
428
|
-
#
|
|
511
|
+
# 新的一句要开口了:正在合成/念的这句**整个任务取消** ——
|
|
512
|
+
# 只掐播放是不够的:合成剩下的音频块会混进新一句里叠着响。
|
|
513
|
+
if self.job_task is not None:
|
|
514
|
+
self.job_task.cancel()
|
|
429
515
|
self.player.interrupt()
|
|
430
516
|
emit(ev="interrupted")
|
|
431
517
|
return
|
|
@@ -438,7 +524,9 @@ class Daemon:
|
|
|
438
524
|
if not text:
|
|
439
525
|
emit(ev="error", id=rid, reason="empty-text")
|
|
440
526
|
return
|
|
441
|
-
|
|
527
|
+
params = job_params(req, self.defaults)
|
|
528
|
+
key = json.dumps([text, *params], ensure_ascii=False)
|
|
529
|
+
hit = self.cached(key)
|
|
442
530
|
if hit is not None and req.get("op") == "say":
|
|
443
531
|
# 预取已经合成好了:音频直接进管道,首声就是设备延迟(~50ms)。
|
|
444
532
|
t0 = time.monotonic()
|
|
@@ -456,11 +544,11 @@ class Daemon:
|
|
|
456
544
|
buf = bytearray()
|
|
457
545
|
t0 = time.monotonic()
|
|
458
546
|
try:
|
|
459
|
-
await self.edge.synth(text, buf.extend)
|
|
547
|
+
await self.edge.synth(text, buf.extend, params)
|
|
460
548
|
except Exception as e: # noqa: BLE001
|
|
461
549
|
emit(ev="error", id=rid, reason=str(e)[:160])
|
|
462
550
|
return
|
|
463
|
-
self.remember(
|
|
551
|
+
self.remember(key, bytes(buf))
|
|
464
552
|
emit(ev="done", id=rid, ms=round((time.monotonic() - t0) * 1000), bytes=len(buf))
|
|
465
553
|
return
|
|
466
554
|
|
|
@@ -479,25 +567,31 @@ class Daemon:
|
|
|
479
567
|
self.player.play(chunk)
|
|
480
568
|
|
|
481
569
|
try:
|
|
482
|
-
await self.edge.synth(text, sink)
|
|
570
|
+
await self.edge.synth(text, sink, params)
|
|
483
571
|
except Exception as e: # noqa: BLE001
|
|
484
572
|
emit(ev="error", id=rid, reason=str(e)[:160])
|
|
485
573
|
return
|
|
486
|
-
self.remember(
|
|
574
|
+
self.remember(key, bytes(buf))
|
|
487
575
|
emit(ev="done", id=rid, ms=round((time.monotonic() - t0) * 1000))
|
|
488
576
|
|
|
489
577
|
async def worker(self):
|
|
490
578
|
while True:
|
|
491
579
|
_, _, req = await self.jobs.get()
|
|
580
|
+
# 每个任务一个 asyncio.Task:interrupt 才能整体取消(不只是掐播放)
|
|
581
|
+
self.job_task = asyncio.create_task(self.run_job(req))
|
|
492
582
|
try:
|
|
493
|
-
await self.
|
|
583
|
+
await self.job_task
|
|
584
|
+
except asyncio.CancelledError:
|
|
585
|
+
# 被掐断:立刻给对端一个交代,别让它的 ask 干等到超时
|
|
586
|
+
emit(ev="error", id=req.get("id"), reason="interrupted")
|
|
494
587
|
except Exception as e: # noqa: BLE001
|
|
495
588
|
log(f"任务异常:{e}")
|
|
496
589
|
finally:
|
|
590
|
+
self.job_task = None
|
|
497
591
|
self.jobs.task_done()
|
|
498
592
|
|
|
499
593
|
async def main(self):
|
|
500
|
-
emit(ev="boot", voice=self.voice, rate=self.rate)
|
|
594
|
+
emit(ev="boot", voice=self.voice, rate=self.rate, pitch=self.pitch)
|
|
501
595
|
asyncio.create_task(self.worker())
|
|
502
596
|
loop = asyncio.get_running_loop()
|
|
503
597
|
# 前台保持一根暖连接:进程起来就把建连(~700ms)花掉,别等第一句话。
|