dsh-watch-together 0.3.4 → 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 +76 -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/floating-chat/window.py +142 -12
- 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/scripts/check-chat-append.py +130 -0
- package/scripts/check-input-select.py +144 -0
- 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
|
@@ -164,6 +164,13 @@ TOUCHPAD_ROW_PX = 32
|
|
|
164
164
|
# 每滚一格都重建会让单格 45~60ms;推到停手后,滚动期间只重画气泡。
|
|
165
165
|
STATIC_DEFER_MS = 200
|
|
166
166
|
|
|
167
|
+
TOP_EDGE_PX = 14
|
|
168
|
+
|
|
169
|
+
CARET_COLOR = "#7cc4ff"
|
|
170
|
+
CARET_W = 2
|
|
171
|
+
CARET_HALF_H = 10
|
|
172
|
+
SEL_FILL = "#2f6fb5"
|
|
173
|
+
|
|
167
174
|
# 仅用于文档截图/CI 视觉检查:暂停抓屏并把 WDA 关掉,窗口才会出现在截图里
|
|
168
175
|
PREVIEW = os.environ.get("DSH_GLASS_PREVIEW") == "1"
|
|
169
176
|
# 文档截图:正常抓屏 2.5 秒后暂停并取消 WDA,保留最后一帧玻璃
|
|
@@ -454,10 +461,42 @@ def danmaku_options(cfg=None) -> dict:
|
|
|
454
461
|
|
|
455
462
|
|
|
456
463
|
def append_user(text: str) -> None:
|
|
464
|
+
"""把用户打的一句话追加进 `chat.jsonl`。
|
|
465
|
+
|
|
466
|
+
正常路径就是 append。**EACCES 时退一步自己修**(issue #75):社区实报
|
|
467
|
+
`Permission denied: '...chat.jsonl'` —— 同一台机器上 PowerShell 能写、Python 不能,
|
|
468
|
+
典型的"文件 ACL 坏了 / 被某个带独占语义的进程攥着"。
|
|
469
|
+
|
|
470
|
+
修法不是重试 append(同一个句柄还是会被拒),而是**整份读出来 + 新行,写成临时文件
|
|
471
|
+
再 `os.replace()` 换掉**:新文件的 ACL 由目录继承,坏 ACL 随旧 inode 一起没了。
|
|
472
|
+
并发追加的风险只在失败路径上(本来这条就写不进去),可以接受。
|
|
473
|
+
"""
|
|
457
474
|
CHAT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
475
|
+
line = json.dumps({"role": "user", "text": text, "at": int(time.time() * 1000)},
|
|
476
|
+
ensure_ascii=False) + "\n"
|
|
477
|
+
try:
|
|
478
|
+
with open(CHAT_FILE, "a", encoding="utf-8") as f:
|
|
479
|
+
f.write(line)
|
|
480
|
+
return
|
|
481
|
+
except PermissionError as exc:
|
|
482
|
+
first = exc
|
|
483
|
+
old = ""
|
|
484
|
+
try:
|
|
485
|
+
if CHAT_FILE.exists():
|
|
486
|
+
old = CHAT_FILE.read_text(encoding="utf-8")
|
|
487
|
+
except OSError:
|
|
488
|
+
old = "" # 读不出来只能丢掉历史,至少别把这一句也丢了
|
|
489
|
+
tmp = CHAT_FILE.with_name(f"{CHAT_FILE.name}.{os.getpid()}.tmp")
|
|
490
|
+
try:
|
|
491
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
492
|
+
f.write(old + line)
|
|
493
|
+
os.replace(tmp, CHAT_FILE)
|
|
494
|
+
except OSError:
|
|
495
|
+
try:
|
|
496
|
+
tmp.unlink()
|
|
497
|
+
except OSError:
|
|
498
|
+
pass
|
|
499
|
+
raise first
|
|
461
500
|
|
|
462
501
|
|
|
463
502
|
def asr_python() -> str:
|
|
@@ -988,7 +1027,9 @@ class LiveGlass:
|
|
|
988
1027
|
try:
|
|
989
1028
|
append_user(text)
|
|
990
1029
|
except Exception as exc:
|
|
991
|
-
|
|
1030
|
+
# 字**不清空**:写不进去的时候,用户最需要的就是改完环境再按一次回车。
|
|
1031
|
+
# `append_user` 里已经试过"换掉整份文件"这条路,还失败就真是权限/占用了。
|
|
1032
|
+
self.feed.status = f"写不进去:{exc}(文件被占用或权限不足;关掉多余的窗再试)"
|
|
992
1033
|
self._refresh_feed()
|
|
993
1034
|
return "break"
|
|
994
1035
|
try:
|
|
@@ -1188,24 +1229,101 @@ class LiveGlass:
|
|
|
1188
1229
|
x, y = x0 + 84, y0 + 27
|
|
1189
1230
|
maxw = max(60, x1 - x0 - 100)
|
|
1190
1231
|
cx = None
|
|
1232
|
+
sel = None
|
|
1233
|
+
try:
|
|
1234
|
+
if text and self._entry.select_present():
|
|
1235
|
+
sel = (self._entry.index("sel.first"), self._entry.index("sel.last"))
|
|
1236
|
+
except Exception:
|
|
1237
|
+
sel = None
|
|
1238
|
+
self._input_view = None
|
|
1191
1239
|
if not text and not focused:
|
|
1192
1240
|
self.text.draw(x, y, "在这里跟它说话…", anchor="w", fill="#8e9db2",
|
|
1193
1241
|
size=11, tags=("inputtext", "inputzone"))
|
|
1194
1242
|
elif text:
|
|
1195
1243
|
font = self.fonts.get(11)
|
|
1196
1244
|
shown, caret_in = self._visible_input(text, maxw, caret)
|
|
1245
|
+
lo = caret - caret_in
|
|
1246
|
+
self._input_view = (x, lo, shown)
|
|
1247
|
+
if sel and sel[1] > lo and sel[0] < lo + len(shown):
|
|
1248
|
+
a = max(0, sel[0] - lo)
|
|
1249
|
+
b = min(len(shown), sel[1] - lo)
|
|
1250
|
+
c.create_rectangle(x + font.measure(shown[:a]), y - 11,
|
|
1251
|
+
x + font.measure(shown[:b]), y + 11,
|
|
1252
|
+
fill=SEL_FILL, outline="", tags=("inputcursor", "inputzone"))
|
|
1197
1253
|
self.text.draw(x, y, shown, anchor="w", fill="#eef6ff",
|
|
1198
1254
|
size=11, tags=("inputtext", "inputzone"))
|
|
1199
|
-
if focused:
|
|
1255
|
+
if focused and not sel:
|
|
1200
1256
|
cx = x + font.measure(shown[:max(0, caret_in)])
|
|
1201
1257
|
elif focused:
|
|
1202
1258
|
cx = x
|
|
1259
|
+
self._input_view = (x, 0, "")
|
|
1203
1260
|
if cx is not None and self._caret_on:
|
|
1204
|
-
c.create_line(cx + 1, y -
|
|
1205
|
-
fill=
|
|
1261
|
+
c.create_line(cx + 1, y - CARET_HALF_H, cx + 1, y + CARET_HALF_H,
|
|
1262
|
+
fill=CARET_COLOR, width=CARET_W, capstyle="round",
|
|
1263
|
+
tags=("inputcursor",))
|
|
1264
|
+
c.tag_raise("inputtext")
|
|
1206
1265
|
self._schedule_caret(cx is not None)
|
|
1207
1266
|
self.text.refresh()
|
|
1208
1267
|
|
|
1268
|
+
def _input_index_at(self, px: int) -> int:
|
|
1269
|
+
view = getattr(self, "_input_view", None)
|
|
1270
|
+
if not view:
|
|
1271
|
+
return 0
|
|
1272
|
+
x, lo, shown = view
|
|
1273
|
+
font = self.fonts.get(11)
|
|
1274
|
+
acc = x
|
|
1275
|
+
for i, ch in enumerate(shown):
|
|
1276
|
+
w = font.measure(ch)
|
|
1277
|
+
if px < acc + w / 2:
|
|
1278
|
+
return lo + i
|
|
1279
|
+
acc += w
|
|
1280
|
+
return lo + len(shown)
|
|
1281
|
+
|
|
1282
|
+
def _input_press(self, e) -> None:
|
|
1283
|
+
self._focus_input(keep_caret=True)
|
|
1284
|
+
idx = self._input_index_at(e.x)
|
|
1285
|
+
now = time.time()
|
|
1286
|
+
double = now - getattr(self, "_input_click_at", 0.0) < 0.35
|
|
1287
|
+
self._input_click_at = now
|
|
1288
|
+
try:
|
|
1289
|
+
self._entry.selection_clear()
|
|
1290
|
+
if double:
|
|
1291
|
+
self._entry.selection_range(0, "end")
|
|
1292
|
+
self._entry.icursor("end")
|
|
1293
|
+
self._input_anchor = None
|
|
1294
|
+
else:
|
|
1295
|
+
self._entry.icursor(idx)
|
|
1296
|
+
self._input_anchor = idx
|
|
1297
|
+
except Exception:
|
|
1298
|
+
self._input_anchor = None
|
|
1299
|
+
self._caret_on = True
|
|
1300
|
+
self._render_input()
|
|
1301
|
+
|
|
1302
|
+
def _input_drag(self, e) -> None:
|
|
1303
|
+
a = getattr(self, "_input_anchor", None)
|
|
1304
|
+
if a is None:
|
|
1305
|
+
return
|
|
1306
|
+
b = self._input_index_at(e.x)
|
|
1307
|
+
try:
|
|
1308
|
+
self._entry.icursor(b)
|
|
1309
|
+
if a == b:
|
|
1310
|
+
self._entry.selection_clear()
|
|
1311
|
+
else:
|
|
1312
|
+
self._entry.selection_range(min(a, b), max(a, b))
|
|
1313
|
+
except Exception:
|
|
1314
|
+
return
|
|
1315
|
+
self._caret_on = True
|
|
1316
|
+
self._render_input()
|
|
1317
|
+
|
|
1318
|
+
def _input_select_all(self, _e=None):
|
|
1319
|
+
try:
|
|
1320
|
+
self._entry.selection_range(0, "end")
|
|
1321
|
+
self._entry.icursor("end")
|
|
1322
|
+
except Exception:
|
|
1323
|
+
pass
|
|
1324
|
+
self._render_input()
|
|
1325
|
+
return "break"
|
|
1326
|
+
|
|
1209
1327
|
def _schedule_caret(self, active: bool) -> None:
|
|
1210
1328
|
"""只有输入框拿着焦点时才跑闪烁定时器;失焦就停,不白烧 after。"""
|
|
1211
1329
|
if self._caret_job is not None:
|
|
@@ -1238,7 +1356,7 @@ class LiveGlass:
|
|
|
1238
1356
|
self._render_input()
|
|
1239
1357
|
return None
|
|
1240
1358
|
|
|
1241
|
-
def _focus_input(self, _e=None):
|
|
1359
|
+
def _focus_input(self, _e=None, keep_caret: bool = False):
|
|
1242
1360
|
# noActivate 开着时先摘掉那条样式,否则 focus_force 也拿不到键盘焦点
|
|
1243
1361
|
# (WS_EX_NOACTIVATE 的窗口本来就不接受焦点)。摘掉后本次运行不再加回,
|
|
1244
1362
|
# 理由见 `_apply_no_activate`。
|
|
@@ -1255,7 +1373,8 @@ class LiveGlass:
|
|
|
1255
1373
|
pass
|
|
1256
1374
|
try:
|
|
1257
1375
|
self._entry.focus_force()
|
|
1258
|
-
|
|
1376
|
+
if not keep_caret:
|
|
1377
|
+
self._entry.icursor("end")
|
|
1259
1378
|
except Exception:
|
|
1260
1379
|
pass
|
|
1261
1380
|
self._caret_on = True
|
|
@@ -1706,6 +1825,8 @@ class LiveGlass:
|
|
|
1706
1825
|
insertwidth=0, highlightthickness=0)
|
|
1707
1826
|
self._entry.bind("<KeyRelease>", self._on_input_key)
|
|
1708
1827
|
self._entry.bind("<Return>", self._send)
|
|
1828
|
+
for seq in ("<Control-a>", "<Control-A>"):
|
|
1829
|
+
self._entry.bind(seq, self._input_select_all)
|
|
1709
1830
|
self._entry.bind("<FocusIn>", lambda _e: self._render_input())
|
|
1710
1831
|
self._entry.bind("<FocusOut>", self._on_input_blur)
|
|
1711
1832
|
# 插入点还能被鼠标和选择改动,这些不发 KeyRelease:不补这几个,点一下
|
|
@@ -1759,7 +1880,6 @@ class LiveGlass:
|
|
|
1759
1880
|
self._draw_scrollbar()
|
|
1760
1881
|
self._bind_header()
|
|
1761
1882
|
c.tag_bind("send", "<Button-1>", self._send)
|
|
1762
|
-
c.tag_bind("inputzone", "<Button-1>", self._focus_input)
|
|
1763
1883
|
c.tag_raise("close")
|
|
1764
1884
|
c.tag_raise("send")
|
|
1765
1885
|
|
|
@@ -2301,7 +2421,7 @@ class LiveGlass:
|
|
|
2301
2421
|
if x >= w - corner and y >= h - corner:
|
|
2302
2422
|
return "se"
|
|
2303
2423
|
if y <= edge:
|
|
2304
|
-
return None
|
|
2424
|
+
return "n" if y <= TOP_EDGE_PX else None
|
|
2305
2425
|
if x <= edge:
|
|
2306
2426
|
return "w"
|
|
2307
2427
|
if x >= w - edge:
|
|
@@ -2342,7 +2462,11 @@ class LiveGlass:
|
|
|
2342
2462
|
return
|
|
2343
2463
|
x0, y0, x1, y1, _r = self._geo.input_shape
|
|
2344
2464
|
if x0 <= e.x <= x1 and y0 <= e.y <= y1:
|
|
2345
|
-
|
|
2465
|
+
if e.x >= x0 + 76:
|
|
2466
|
+
self._input_press(e)
|
|
2467
|
+
self._input_selecting = True
|
|
2468
|
+
else:
|
|
2469
|
+
self._focus_input()
|
|
2346
2470
|
return
|
|
2347
2471
|
mode = self._edge_at(e.x, e.y)
|
|
2348
2472
|
if mode:
|
|
@@ -2356,6 +2480,9 @@ class LiveGlass:
|
|
|
2356
2480
|
e.y_root - self.root.winfo_y())
|
|
2357
2481
|
|
|
2358
2482
|
def _motion(self, e):
|
|
2483
|
+
if getattr(self, "_input_selecting", False):
|
|
2484
|
+
self._input_drag(e)
|
|
2485
|
+
return
|
|
2359
2486
|
if self._resize:
|
|
2360
2487
|
mode, sx, sy, x0, y0, w0, h0 = self._resize
|
|
2361
2488
|
dx, dy = e.x_root - sx, e.y_root - sy
|
|
@@ -2393,6 +2520,9 @@ class LiveGlass:
|
|
|
2393
2520
|
self.root.geometry(f"+{nx}+{ny}")
|
|
2394
2521
|
|
|
2395
2522
|
def _release(self, e):
|
|
2523
|
+
if getattr(self, "_input_selecting", False):
|
|
2524
|
+
self._input_selecting = False
|
|
2525
|
+
return
|
|
2396
2526
|
if self._resize:
|
|
2397
2527
|
self._resize = None
|
|
2398
2528
|
self._preview_at = 0.0
|
|
@@ -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)花掉,别等第一句话。
|