dsh-folia 4.26.0-pre.53 → 4.26.0-pre.54
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/lib/client.js +341 -144
- package/lib/routes/pet-chat.js +29 -3
- package/lib/settings-schema.js +8 -3
- package/lib/tts/catalog.js +48 -0
- package/lib/tts/tts-worker.cjs +117 -22
- package/lib/tts/tts.js +27 -3
- package/lib/voice/record.js +26 -18
- package/package.json +1 -1
package/lib/client.js
CHANGED
|
@@ -741,6 +741,23 @@ window.__ModuleLoader__.load({
|
|
|
741
741
|
// pre.49:桌宠页控制行最右侧的语音助手开关(点开才挂载设置块)。
|
|
742
742
|
"智能大肥鱼": "Smart Chubby Fish",
|
|
743
743
|
"桌宠语音助手": "Pet voice assistant",
|
|
744
|
+
// pre.54:气泡状态条三态 + 音色回落提示。
|
|
745
|
+
"在听": "Listening",
|
|
746
|
+
"在想": "Thinking",
|
|
747
|
+
"在说": "Speaking",
|
|
748
|
+
"所选音色不可用,已用系统默认:{name}": "Selected voice is unavailable — using the system default: {name}",
|
|
749
|
+
"所选音色不可用,已用系统默认音色": "Selected voice is unavailable — using the system default voice",
|
|
750
|
+
// pre.54:本机音色来源 / 可下载目录骨架。
|
|
751
|
+
"(系统音色,离线)": "(system voice, offline)",
|
|
752
|
+
"(本机未检测到,将回落)": "(not detected on this machine; will fall back)",
|
|
753
|
+
"只列本机真实可用的系统音色(离线);云端音色不随包分发。":
|
|
754
|
+
"Only voices actually available on this machine are listed (offline); cloud voices are not bundled.",
|
|
755
|
+
"正在读取本机音色…": "Reading local voices…",
|
|
756
|
+
"未检测到可用音色(系统 TTS 不可用)": "No usable voice detected (system TTS unavailable)",
|
|
757
|
+
"可下载音色(即将支持)": "Downloadable voices (coming soon)",
|
|
758
|
+
"即将支持": "coming soon",
|
|
759
|
+
"这些是开源离线方案,本版只接目录;合成接通后才会出现在上面的音色下拉里。":
|
|
760
|
+
"These are open-source offline options; this version only wires the catalogue. They will appear in the voice list above once synthesis is connected.",
|
|
744
761
|
// pre.53:朗读开关 + 音色(voice.muted / voice.name);桌宠页的音效标签同步改名。
|
|
745
762
|
"音色": "Voice",
|
|
746
763
|
"🔊 朗读回答": "🔊 Read replies aloud",
|
|
@@ -748,10 +765,6 @@ window.__ModuleLoader__.load({
|
|
|
748
765
|
"When off, replies are shown as subtitles only (no speech synthesis); takes effect as soon as you save.",
|
|
749
766
|
"填 Key、起名字、选音色,再决定要不要朗读。主动搭话与记忆是固定策略;停止/恢复对它说一声就行。":
|
|
750
767
|
"Fill in the key, give it a name, pick a voice, then decide whether it should read replies aloud. Proactive chat and memory are fixed behaviours; just tell it to stop or resume.",
|
|
751
|
-
"晓晓(女声,默认)": "Xiaoxiao (female, default)",
|
|
752
|
-
"晓伊(女声,活泼)": "Xiaoyi (female, lively)",
|
|
753
|
-
"云希(男声)": "Yunxi (male)",
|
|
754
|
-
"云健(男声,沉稳)": "Yunjian (male, calm)",
|
|
755
768
|
"已保存(朗读已关闭)": "Saved (read-aloud is off)",
|
|
756
769
|
"桌宠音效": "Pet sound effects",
|
|
757
770
|
"音效音量": "SFX volume",
|
|
@@ -8177,8 +8190,10 @@ window.__ModuleLoader__.load({
|
|
|
8177
8190
|
*/
|
|
8178
8191
|
petName: '', // 桌宠名字(空 ⇒ 用宠物包 displayName);同时是唤醒词
|
|
8179
8192
|
ownerName: '', // 用户希望被怎么称呼
|
|
8180
|
-
// 朗读:只有一个音色 + 一个静音开关(不再有 rate/pitch/volume/voiceURI
|
|
8181
|
-
|
|
8193
|
+
// 朗读:只有一个音色 + 一个静音开关(不再有 rate/pitch/volume/voiceURI 五件套)。
|
|
8194
|
+
// pre.54:默认**空串** = 由宿主选本机第一个可用中文音色(这台是 Microsoft Huihui Desktop)。
|
|
8195
|
+
// 旧默认是 Edge 云端音色,本机没有模型/许可不允许随包分发。
|
|
8196
|
+
voice: { name: '', muted: false },
|
|
8182
8197
|
// 唤醒:点一下默认开;叫名字默认关(S6 才实现,先在设置里留位)
|
|
8183
8198
|
wake: { click: true, name: false, keyword: '' },
|
|
8184
8199
|
// 对话记忆默认开启且**不暴露开关**(追加决定 1):能力常开,用户只能在右键里查看/清空
|
|
@@ -8927,7 +8942,10 @@ window.__ModuleLoader__.load({
|
|
|
8927
8942
|
const def = DEFAULTS.petChat.voice;
|
|
8928
8943
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
8929
8944
|
const old = legacy && typeof legacy === 'object' && !Array.isArray(legacy) ? legacy : {};
|
|
8930
|
-
const
|
|
8945
|
+
const picked = petChatStr(src.name, 120).trim() || petChatStr(old.voiceURI, 200).trim() || def.name;
|
|
8946
|
+
// pre.54:Edge neural 名(`zh-CN-XxxNeural` 这类)是云端音色,本机没有本地模型、
|
|
8947
|
+
// 也不允许随包分发 ⇒ 读档时迁成空串(= 宿主自动选本机第一个可用中文音色)。
|
|
8948
|
+
const name = /^[a-z]{2}-[A-Z]{2}-[A-Za-z0-9]+Neural$/.test(picked) ? '' : picked;
|
|
8931
8949
|
const muted = typeof src.muted === 'boolean' ? src.muted : old.enabled === false;
|
|
8932
8950
|
return { name, muted };
|
|
8933
8951
|
}
|
|
@@ -19020,17 +19038,11 @@ window.__ModuleLoader__.load({
|
|
|
19020
19038
|
petName: '',
|
|
19021
19039
|
ownerName: '',
|
|
19022
19040
|
// pre.53:朗读回答 = voice.muted 取反;音色 = voice.name(与 /pet-chat/config 同结构)。
|
|
19023
|
-
|
|
19041
|
+
// pre.54:默认**空串** = 宿主自动选本机第一个可用中文音色(这台是 Microsoft Huihui Desktop);
|
|
19042
|
+
// 不再写死 Edge neural(云端音色,不能随包分发,本机也没有本地模型)。
|
|
19043
|
+
voice: { name: '', muted: false },
|
|
19024
19044
|
};
|
|
19025
19045
|
|
|
19026
|
-
/** 固定可选的朗读音色(Edge neural;宿主 TTS 的 `preferredEngineForVoice` 会优先走 edge)。 */
|
|
19027
|
-
const ASSISTANT_VOICES = [
|
|
19028
|
-
{ id: 'zh-CN-XiaoxiaoNeural', label: '晓晓(女声,默认)' },
|
|
19029
|
-
{ id: 'zh-CN-XiaoyiNeural', label: '晓伊(女声,活泼)' },
|
|
19030
|
-
{ id: 'zh-CN-YunxiNeural', label: '云希(男声)' },
|
|
19031
|
-
{ id: 'zh-CN-YunjianNeural', label: '云健(男声,沉稳)' },
|
|
19032
|
-
];
|
|
19033
|
-
|
|
19034
19046
|
/**
|
|
19035
19047
|
* 设置页:模型 Key / 名字 / 称呼 / 音色 / **朗读回答开关** / 保存。
|
|
19036
19048
|
*
|
|
@@ -19041,6 +19053,12 @@ window.__ModuleLoader__.load({
|
|
|
19041
19053
|
* 各调用点各写一遍「多解一层」就是 P1 那个"保存成功却显示保存失败"的来源 —— 统一到这里解。 */
|
|
19042
19054
|
const unwrapPetChat = (resp) => (resp && resp.data && resp.data.data) || (resp && resp.data) || {};
|
|
19043
19055
|
|
|
19056
|
+
/** 本机音色里选默认:优先中文,其次第一个 usable。 */
|
|
19057
|
+
function assistantDefaultVoice(list) {
|
|
19058
|
+
const items = (Array.isArray(list) ? list : []).filter((v) => v && v.usable === true);
|
|
19059
|
+
return items.find((v) => /^zh/i.test(String(v.lang || ''))) || items[0] || null;
|
|
19060
|
+
}
|
|
19061
|
+
|
|
19044
19062
|
function PetChatSettings() {
|
|
19045
19063
|
const [draft, setDraft] = React.useState(CHAT_DEFAULTS);
|
|
19046
19064
|
const [status, setStatus] = React.useState({ ok: null, text: '' });
|
|
@@ -19048,6 +19066,9 @@ window.__ModuleLoader__.load({
|
|
|
19048
19066
|
const [busy, setBusy] = React.useState(false);
|
|
19049
19067
|
// 工作能力插件(聚合携带)的安装状态;只读展示,不加开关
|
|
19050
19068
|
const [workPlugins, setWorkPlugins] = React.useState(null);
|
|
19069
|
+
// pre.54:本机真实可用音色(/tts/voices)与可下载目录(/tts/catalog)。
|
|
19070
|
+
const [voices, setVoices] = React.useState(null);
|
|
19071
|
+
const [catalog, setCatalog] = React.useState(null);
|
|
19051
19072
|
const update = React.useCallback((patch) => setDraft((prev) => ({ ...prev, ...patch })), []);
|
|
19052
19073
|
|
|
19053
19074
|
const load = React.useCallback(async () => {
|
|
@@ -19071,6 +19092,30 @@ window.__ModuleLoader__.load({
|
|
|
19071
19092
|
setWorkPlugins(unwrapPetChat(resp));
|
|
19072
19093
|
})();
|
|
19073
19094
|
}, []);
|
|
19095
|
+
// pre.54:只列本机真实可用音色;默认选第一个可用中文音色。
|
|
19096
|
+
React.useEffect(() => {
|
|
19097
|
+
void (async () => {
|
|
19098
|
+
const resp = await apiJson('/pet-chat/tts/voices', { parse: 'always' }).catch(() => null);
|
|
19099
|
+
const doc = unwrapPetChat(resp);
|
|
19100
|
+
const items = (doc && Array.isArray(doc.voices) ? doc.voices : []).filter((v) => v && v.usable === true);
|
|
19101
|
+
setVoices(items);
|
|
19102
|
+
const firstZh = assistantDefaultVoice(items);
|
|
19103
|
+
if (firstZh) {
|
|
19104
|
+
setDraft((prev) => {
|
|
19105
|
+
const cur = prev.voice || {};
|
|
19106
|
+
if (cur.name) return prev;
|
|
19107
|
+
return { ...prev, voice: Object.assign({}, cur, { name: firstZh.id }) };
|
|
19108
|
+
});
|
|
19109
|
+
}
|
|
19110
|
+
})();
|
|
19111
|
+
}, []);
|
|
19112
|
+
React.useEffect(() => {
|
|
19113
|
+
void (async () => {
|
|
19114
|
+
const resp = await apiJson('/pet-chat/tts/catalog', { parse: 'always' }).catch(() => null);
|
|
19115
|
+
const doc = unwrapPetChat(resp);
|
|
19116
|
+
if (doc && Array.isArray(doc.items)) setCatalog(doc.items);
|
|
19117
|
+
})();
|
|
19118
|
+
}, []);
|
|
19074
19119
|
|
|
19075
19120
|
const save = async () => {
|
|
19076
19121
|
setBusy(true);
|
|
@@ -19078,6 +19123,11 @@ window.__ModuleLoader__.load({
|
|
|
19078
19123
|
// 填了 Key 就启用:面板不放"开启对话"开关,语义由 Key 的有无决定。
|
|
19079
19124
|
// pre.53:voice 必须显式带上(宿主保存时会整体替换 voice 对象)。
|
|
19080
19125
|
const voice = Object.assign({}, CHAT_DEFAULTS.voice, draft.voice || {});
|
|
19126
|
+
// pre.54:空音色 ⇒ 落成当前本机默认(列表没加载出来时仍保持空串,由宿主自动选)。
|
|
19127
|
+
if (!voice.name) {
|
|
19128
|
+
const fallback = assistantDefaultVoice(voices);
|
|
19129
|
+
if (fallback) voice.name = fallback.id;
|
|
19130
|
+
}
|
|
19081
19131
|
const body = {
|
|
19082
19132
|
...draft, voice,
|
|
19083
19133
|
apiKey: draft.apiKey || '',
|
|
@@ -19153,15 +19203,51 @@ window.__ModuleLoader__.load({
|
|
|
19153
19203
|
key: 'speak-hint', className: 'we-picker__hint', style: { margin: '0 0 4px' },
|
|
19154
19204
|
}, weT('关闭后只显示字幕、不合成语音(省算力);保存后立刻生效。')));
|
|
19155
19205
|
|
|
19156
|
-
//
|
|
19157
|
-
|
|
19158
|
-
|
|
19159
|
-
|
|
19160
|
-
|
|
19161
|
-
|
|
19162
|
-
|
|
19163
|
-
|
|
19164
|
-
|
|
19206
|
+
// pre.54(B3③):音色下拉只列**本机真实可用**(/tts/voices 的 usable=true)。
|
|
19207
|
+
// 不再有 4 个硬编码 Edge neural;默认选第一个可用中文音色(这台是 Microsoft Huihui Desktop)。
|
|
19208
|
+
const usableVoices = (Array.isArray(voices) ? voices : []).filter((v) => v && v.usable === true);
|
|
19209
|
+
const defaultVoice = assistantDefaultVoice(usableVoices);
|
|
19210
|
+
const currentVoiceName = voice.name || (defaultVoice ? defaultVoice.id : '');
|
|
19211
|
+
const voiceKnown = usableVoices.some((v) => String(v.id) === currentVoiceName);
|
|
19212
|
+
if (usableVoices.length || currentVoiceName) {
|
|
19213
|
+
child.push(row('voice', '音色', React.createElement('select', {
|
|
19214
|
+
className: 'we-picker__playlist-select',
|
|
19215
|
+
disabled: busy || !usableVoices.length,
|
|
19216
|
+
value: currentVoiceName,
|
|
19217
|
+
onChange: (e) => update({ voice: Object.assign({}, voice, { name: e.target.value }) }),
|
|
19218
|
+
},
|
|
19219
|
+
// 旧配置里的音色不在本机(或读取失败)也保留一行,避免下拉显示为空;
|
|
19220
|
+
// 真正合成时宿主会回落并在状态条提示。
|
|
19221
|
+
!voiceKnown && currentVoiceName
|
|
19222
|
+
? React.createElement('option', { key: 'stale', value: currentVoiceName }, currentVoiceName + ' ' + weT('(本机未检测到,将回落)'))
|
|
19223
|
+
: null,
|
|
19224
|
+
...usableVoices.map((v) => React.createElement('option', { key: v.id, value: v.id },
|
|
19225
|
+
v.label + (v.lang ? ' · ' + v.lang : '') + ' ' + weT('(系统音色,离线)'))),
|
|
19226
|
+
)));
|
|
19227
|
+
} else {
|
|
19228
|
+
child.push(React.createElement('div', {
|
|
19229
|
+
key: 'voice-empty', className: 'we-picker__hint', style: { margin: '4px 0' },
|
|
19230
|
+
}, voices === null ? weT('正在读取本机音色…') : weT('未检测到可用音色(系统 TTS 不可用)')));
|
|
19231
|
+
}
|
|
19232
|
+
child.push(React.createElement('div', {
|
|
19233
|
+
key: 'voice-hint', className: 'we-picker__hint', style: { margin: '0 0 4px' },
|
|
19234
|
+
}, weT('只列本机真实可用的系统音色(离线);云端音色不随包分发。')));
|
|
19235
|
+
|
|
19236
|
+
// pre.54(任务 C 骨架):可下载离线音色目录 —— 本版**只列目录,不谎称已支持**。
|
|
19237
|
+
if (Array.isArray(catalog) && catalog.length) {
|
|
19238
|
+
child.push(React.createElement('div', {
|
|
19239
|
+
key: 'catalog-head', style: { marginTop: '12px', fontSize: '12px', fontWeight: 600 },
|
|
19240
|
+
}, weT('可下载音色(即将支持)')));
|
|
19241
|
+
catalog.forEach((item) => {
|
|
19242
|
+
child.push(React.createElement('div', {
|
|
19243
|
+
key: 'cat-' + item.id, className: 'we-picker__hint', style: { margin: '2px 0' },
|
|
19244
|
+
}, (item.name || item.id) + ' · ' + (item.license || '') + ' · ' + (item.size || '')
|
|
19245
|
+
+ ' · ' + weT('即将支持')));
|
|
19246
|
+
});
|
|
19247
|
+
child.push(React.createElement('div', {
|
|
19248
|
+
key: 'catalog-hint', className: 'we-picker__hint', style: { margin: '2px 0 0' },
|
|
19249
|
+
}, weT('这些是开源离线方案,本版只接目录;合成接通后才会出现在上面的音色下拉里。')));
|
|
19250
|
+
}
|
|
19165
19251
|
|
|
19166
19252
|
child.push(React.createElement('div', { key: 'status', className: 'we-picker__hint', style: { margin: '6px 0', color: status.ok === false ? '#f87171' : undefined } },
|
|
19167
19253
|
status.text || weT('未连接')));
|
|
@@ -21229,20 +21315,24 @@ window.__ModuleLoader__.load({
|
|
|
21229
21315
|
|
|
21230
21316
|
// ── 内联模块:src/pet-bubble.js —— 头顶气泡:锚定桌宠头顶、跟随位置/缩放、逐字显示、最多 6 行、朗读结束 +3s 淡出(构建期注入;勿手改本段)──
|
|
21231
21317
|
/**
|
|
21232
|
-
* pet-bubble.js —
|
|
21318
|
+
* pet-bubble.js — 桌宠头顶的**双层气泡**(pre.54 重做)。
|
|
21233
21319
|
*
|
|
21234
|
-
*
|
|
21235
|
-
*
|
|
21236
|
-
*
|
|
21320
|
+
* 用户口径:提示/错误不能和回答挤在同一个框里。
|
|
21321
|
+
* ① 状态条(独立、细、可点、3–5 秒淡出):在听 / 在想 / 在说 / 没找到麦克风 / …
|
|
21322
|
+
* ② 回答气泡(只有回答,小尾巴指向桌宠):逐句显示、随朗读推进、长回答可滚。
|
|
21323
|
+
*
|
|
21324
|
+
* 结构:
|
|
21325
|
+
* .we-pet-wrap(固定定位、列布局、整体锚定在桌宠头顶)
|
|
21326
|
+
* ├─ .we-pet-status(状态条;自带 data-state 控制 🎤/💭/🔊 动效)
|
|
21327
|
+
* └─ .we-pet-bubble(回答气泡;内部 .we-pet-bubble-text + 关闭按钮)
|
|
21237
21328
|
*
|
|
21238
|
-
* 依赖全部注入(document / 定时器 /
|
|
21239
|
-
* 浏览器侧由 pet-chat.js 用真实 window
|
|
21329
|
+
* 依赖全部注入(document / 定时器 / 锚点),Node 里能用假 DOM 跑判据;
|
|
21330
|
+
* 浏览器侧由 pet-chat.js 用真实 window 构造。`setState` 仍同步写 bubble 的
|
|
21331
|
+
* `data-state`(既有判据与桌宠动作读它),视觉三态则落在状态条上。
|
|
21240
21332
|
*/
|
|
21241
21333
|
function petBubbleCreate(deps) {
|
|
21242
21334
|
const options = deps || {};
|
|
21243
21335
|
const doc = options.document;
|
|
21244
|
-
// 没有定时器的环境(极简 DOM 替身的冒烟测试)不能因为裸 setTimeout 直接炸:
|
|
21245
|
-
// 退化成立即执行 / 空取消,气泡仍能显示,只是没有延迟淡出。
|
|
21246
21336
|
const setTimer = typeof options.setTimeout === 'function'
|
|
21247
21337
|
? options.setTimeout
|
|
21248
21338
|
: (typeof setTimeout === 'function' ? setTimeout : (fn) => { if (typeof fn === 'function') fn(); return 0; });
|
|
@@ -21250,56 +21340,61 @@ window.__ModuleLoader__.load({
|
|
|
21250
21340
|
? options.clearTimeout
|
|
21251
21341
|
: (typeof clearTimeout === 'function' ? clearTimeout : () => {});
|
|
21252
21342
|
const getAnchor = typeof options.getAnchor === 'function' ? options.getAnchor : () => null;
|
|
21253
|
-
|
|
21343
|
+
const onStatusClick = typeof options.onStatusClick === 'function' ? options.onStatusClick : null;
|
|
21254
21344
|
const MAX_LINES = 6;
|
|
21345
|
+
const BUBBLE_MAX_WIDTH = 320;
|
|
21346
|
+
const BUBBLE_MAX_HEIGHT = 160;
|
|
21255
21347
|
|
|
21256
21348
|
const raf = typeof options.requestAnimationFrame === 'function' ? options.requestAnimationFrame : null;
|
|
21257
21349
|
const cancelRaf = typeof options.cancelAnimationFrame === 'function' ? options.cancelAnimationFrame : null;
|
|
21258
21350
|
let rafId = null;
|
|
21259
21351
|
const onClose = typeof options.onClose === 'function' ? options.onClose : () => {};
|
|
21352
|
+
/** 独立冒烟(只 eval 本文件)时没有 weT;有就用词表,没有就回落中文原文。 */
|
|
21353
|
+
const tr = (text) => {
|
|
21354
|
+
try { return typeof weT === 'function' ? weT(text) : text; } catch { return text; }
|
|
21355
|
+
};
|
|
21356
|
+
|
|
21357
|
+
const CSS = [
|
|
21358
|
+
'.we-pet-wrap{position:fixed;z-index:9999;display:flex;flex-direction:column;align-items:center;gap:6px;max-width:320px;pointer-events:none;transform-origin:50% 100%;}',
|
|
21359
|
+
// 回答气泡:半透明深色底 + 轻描边 + 14–16px 圆角;长回答 160px 内滚动。
|
|
21360
|
+
'.we-pet-bubble{position:relative;max-width:320px;max-height:160px;overflow-y:auto;padding:10px 12px;border-radius:15px;background:rgba(20,20,24,.82);color:#f2f2f5;font-size:13px;line-height:1.5;border:1px solid rgba(255,255,255,.14);box-shadow:0 8px 24px rgba(0,0,0,.28);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);white-space:pre-wrap;word-break:break-word;opacity:0;transition:opacity 150ms ease;pointer-events:auto;scrollbar-width:thin;}',
|
|
21361
|
+
'.we-pet-bubble[data-visible="1"]{opacity:1;}',
|
|
21362
|
+
// 小尾巴指向桌宠(在气泡底部中央;不挡脸)。
|
|
21363
|
+
'.we-pet-bubble::after{content:"";position:absolute;left:50%;bottom:-6px;width:12px;height:12px;background:inherit;border-right:1px solid rgba(255,255,255,.14);border-bottom:1px solid rgba(255,255,255,.14);transform:translateX(-50%) rotate(45deg);}',
|
|
21364
|
+
'.we-pet-bubble::-webkit-scrollbar{width:4px;}',
|
|
21365
|
+
'.we-pet-bubble::-webkit-scrollbar-thumb{background:rgba(255,255,255,.22);border-radius:2px;}',
|
|
21366
|
+
// 状态条:细、独立、可点、3–5 秒淡出。
|
|
21367
|
+
'.we-pet-status{max-width:320px;padding:5px 10px;border-radius:999px;background:rgba(20,20,24,.74);color:#ececf2;font-size:12px;line-height:1.4;border:1px solid rgba(255,255,255,.12);box-shadow:0 4px 14px rgba(0,0,0,.22);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);display:flex;align-items:center;gap:6px;opacity:0;transition:opacity 150ms ease;pointer-events:auto;cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}',
|
|
21368
|
+
'.we-pet-status[data-visible="1"]{opacity:1;}',
|
|
21369
|
+
'.we-pet-status[data-state="listen"]::after{content:"";width:8px;height:8px;border-radius:50%;background:currentColor;opacity:.7;animation:we-pet-status-pulse 1s ease-in-out infinite;}',
|
|
21370
|
+
'.we-pet-status[data-state="think"]::after{content:"…";margin-left:1px;opacity:.8;animation:we-pet-status-blink 1.1s steps(2,end) infinite;}',
|
|
21371
|
+
'.we-pet-status[data-state="speak"]::after{content:"";display:block;width:28px;height:10px;opacity:.85;background:linear-gradient(currentColor,currentColor) 0 100%/3px 45% no-repeat,linear-gradient(currentColor,currentColor) 7px 100%/3px 90% no-repeat,linear-gradient(currentColor,currentColor) 14px 100%/3px 60% no-repeat,linear-gradient(currentColor,currentColor) 21px 100%/3px 100% no-repeat;transform-origin:0 100%;animation:we-pet-status-wave .8s ease-in-out infinite alternate;}',
|
|
21372
|
+
'.we-pet-status[data-state="error"]{border-color:rgba(255,120,120,.45);}',
|
|
21373
|
+
'@keyframes we-pet-status-wave{from{transform:scaleY(.55);opacity:.55;}to{transform:scaleY(1);opacity:.95;}}',
|
|
21374
|
+
'@keyframes we-pet-status-pulse{0%,100%{transform:scale(.8);opacity:.45;}50%{transform:scale(1.15);opacity:.9;}}',
|
|
21375
|
+
'@keyframes we-pet-status-blink{0%,60%{opacity:.35;}100%{opacity:.9;}}',
|
|
21376
|
+
].join('');
|
|
21377
|
+
|
|
21378
|
+
let wrap = null;
|
|
21379
|
+
let el = null; // 回答气泡
|
|
21380
|
+
let textEl = null;
|
|
21381
|
+
let statusEl = null;
|
|
21382
|
+
let text = '';
|
|
21383
|
+
let visible = false;
|
|
21384
|
+
let fadeTimer = null;
|
|
21385
|
+
let statusTimer = null;
|
|
21386
|
+
let stylesInjected = false;
|
|
21260
21387
|
|
|
21261
|
-
/** P3:打开期间每帧跟一次(拖动/缩放/窗口变化都能跟上),关闭时停。 */
|
|
21262
21388
|
function startFollow() {
|
|
21263
21389
|
if (!raf || rafId != null) return;
|
|
21264
|
-
const step = () => {
|
|
21265
|
-
place();
|
|
21266
|
-
rafId = raf(step);
|
|
21267
|
-
};
|
|
21390
|
+
const step = () => { place(); rafId = raf(step); };
|
|
21268
21391
|
rafId = raf(step);
|
|
21269
21392
|
}
|
|
21270
|
-
|
|
21271
21393
|
function stopFollow() {
|
|
21272
21394
|
if (rafId != null && cancelRaf) { try { cancelRaf(rafId); } catch { /* ignore */ } }
|
|
21273
21395
|
rafId = null;
|
|
21274
21396
|
}
|
|
21275
21397
|
|
|
21276
|
-
let el = null;
|
|
21277
|
-
let text = '';
|
|
21278
|
-
let visible = false;
|
|
21279
|
-
let fadeTimer = null;
|
|
21280
|
-
let stylesInjected = false;
|
|
21281
|
-
|
|
21282
|
-
/**
|
|
21283
|
-
* 三态与“说”的波形(P1):
|
|
21284
|
-
* listen / think / speak / idle —— 只改 `data-state`,由一小段**无颜色**的 CSS 表现:
|
|
21285
|
-
* · listen:正文前的实心点;think:省略号;speak:正文下一排四根跳动竖条。
|
|
21286
|
-
* 用伪元素而不是新增 DOM 子节点,是因为气泡正文一直用 `textContent` 整体写入
|
|
21287
|
-
* (设 textContent 会把子节点一起清掉);伪元素不会被它清掉,也不会引入第二种“文字容器”。
|
|
21288
|
-
*/
|
|
21289
|
-
const WAVE_CSS = [
|
|
21290
|
-
'.we-pet-bubble[data-state="listen"]::before{content:"●";margin-right:4px;opacity:.55;}',
|
|
21291
|
-
'.we-pet-bubble[data-state="think"]::before{content:"…";margin-right:4px;opacity:.6;}',
|
|
21292
|
-
'.we-pet-bubble[data-state="speak"]::after{content:"";display:block;width:34px;height:10px;margin-top:6px;opacity:.85;',
|
|
21293
|
-
'background:',
|
|
21294
|
-
'linear-gradient(currentColor,currentColor) 0 100%/3px 45% no-repeat,',
|
|
21295
|
-
'linear-gradient(currentColor,currentColor) 8px 100%/3px 90% no-repeat,',
|
|
21296
|
-
'linear-gradient(currentColor,currentColor) 16px 100%/3px 60% no-repeat,',
|
|
21297
|
-
'linear-gradient(currentColor,currentColor) 24px 100%/3px 100% no-repeat;',
|
|
21298
|
-
'transform-origin:0 100%;animation:we-pet-bubble-wave .8s ease-in-out infinite alternate;}',
|
|
21299
|
-
'@keyframes we-pet-bubble-wave{from{transform:scaleY(.55);opacity:.55;}to{transform:scaleY(1);opacity:.95;}}',
|
|
21300
|
-
].join('');
|
|
21301
|
-
|
|
21302
|
-
/** 只注入一次;没有 head 的环境(判据的极简 DOM)静默跳过。 */
|
|
21303
21398
|
function ensureStyles() {
|
|
21304
21399
|
if (stylesInjected) return;
|
|
21305
21400
|
stylesInjected = true;
|
|
@@ -21307,73 +21402,86 @@ window.__ModuleLoader__.load({
|
|
|
21307
21402
|
if (!doc || !doc.head || typeof doc.createElement !== 'function') return;
|
|
21308
21403
|
const style = doc.createElement('style');
|
|
21309
21404
|
style.setAttribute('data-folia-pet-bubble', '1');
|
|
21310
|
-
style.textContent =
|
|
21405
|
+
style.textContent = CSS;
|
|
21311
21406
|
if (typeof doc.head.appendChild === 'function') doc.head.appendChild(style);
|
|
21312
21407
|
} catch { /* 气泡是装饰层,样式失败不能影响显示 */ }
|
|
21313
21408
|
}
|
|
21314
21409
|
|
|
21315
|
-
/** 锚点 →
|
|
21410
|
+
/** 锚点 → 整组位置:水平居中于桌宠,垂直贴在头顶上方。 */
|
|
21316
21411
|
function place() {
|
|
21317
|
-
if (!
|
|
21412
|
+
if (!wrap) return;
|
|
21318
21413
|
const anchor = getAnchor();
|
|
21319
21414
|
if (!anchor) return;
|
|
21320
21415
|
const width = Number(anchor.width) || 0;
|
|
21321
|
-
const height = Number(anchor.height) || 0;
|
|
21322
21416
|
const left = Math.round(Number(anchor.left || 0) + width / 2);
|
|
21323
21417
|
const top = Math.round(Number(anchor.top || 0) - 8);
|
|
21324
|
-
|
|
21325
|
-
|
|
21326
|
-
|
|
21327
|
-
el.style.transform = `translate(-50%, -100%) scale(${Number(anchor.scale) || 1})`;
|
|
21418
|
+
wrap.style.left = `${left}px`;
|
|
21419
|
+
wrap.style.top = `${top}px`;
|
|
21420
|
+
wrap.style.transform = `translate(-50%, -100%) scale(${Number(anchor.scale) || 1})`;
|
|
21328
21421
|
}
|
|
21329
21422
|
|
|
21330
21423
|
function ensure() {
|
|
21331
|
-
if (
|
|
21424
|
+
if (wrap || !doc || typeof doc.createElement !== 'function') return wrap;
|
|
21425
|
+
ensureStyles();
|
|
21426
|
+
wrap = doc.createElement('div');
|
|
21427
|
+
wrap.className = 'we-pet-wrap';
|
|
21428
|
+
|
|
21429
|
+
statusEl = doc.createElement('div');
|
|
21430
|
+
statusEl.className = 'we-pet-status';
|
|
21431
|
+
statusEl.dataset = statusEl.dataset || {};
|
|
21432
|
+
statusEl.setAttribute('role', 'status');
|
|
21433
|
+
statusEl.setAttribute('aria-live', 'polite');
|
|
21434
|
+
statusEl.addEventListener('click', () => {
|
|
21435
|
+
try { if (onStatusClick) onStatusClick(); else hideStatus(0); } catch { /* ignore */ }
|
|
21436
|
+
});
|
|
21437
|
+
|
|
21332
21438
|
el = doc.createElement('div');
|
|
21333
21439
|
el.className = 'we-pet-bubble';
|
|
21334
|
-
el.
|
|
21335
|
-
el.style.
|
|
21336
|
-
el.style.
|
|
21337
|
-
|
|
21338
|
-
el.
|
|
21339
|
-
|
|
21340
|
-
|
|
21341
|
-
|
|
21342
|
-
el.
|
|
21343
|
-
|
|
21344
|
-
|
|
21345
|
-
|
|
21346
|
-
|
|
21347
|
-
|
|
21348
|
-
|
|
21349
|
-
|
|
21350
|
-
|
|
21351
|
-
|
|
21352
|
-
|
|
21353
|
-
|
|
21354
|
-
|
|
21355
|
-
|
|
21356
|
-
|
|
21357
|
-
|
|
21358
|
-
|
|
21359
|
-
|
|
21360
|
-
}
|
|
21361
|
-
el.style.position = 'fixed';
|
|
21362
|
-
if (doc.body && typeof doc.body.appendChild === 'function') doc.body.appendChild(el);
|
|
21363
|
-
return el;
|
|
21440
|
+
el.dataset = el.dataset || {};
|
|
21441
|
+
el.style.position = 'relative';
|
|
21442
|
+
el.style.pointerEvents = 'auto';
|
|
21443
|
+
// 点气泡 = 收起(二选一里的“收起”;不复制,避免误触剪贴板)。拖选文字时不触发 click。
|
|
21444
|
+
el.addEventListener('click', () => { hide(0); onClose(); });
|
|
21445
|
+
|
|
21446
|
+
textEl = doc.createElement('div');
|
|
21447
|
+
textEl.className = 'we-pet-bubble-text';
|
|
21448
|
+
if (typeof el.appendChild === 'function') el.appendChild(textEl);
|
|
21449
|
+
|
|
21450
|
+
const close = doc.createElement('button');
|
|
21451
|
+
close.className = 'pet-bubble-close';
|
|
21452
|
+
close.setAttribute('aria-label', '关闭');
|
|
21453
|
+
close.textContent = '×';
|
|
21454
|
+
close.style.cssText = 'position:absolute;top:-6px;right:-6px;width:18px;height:18px;border-radius:50%;border:none;background:#333;color:#ddd;font-size:12px;line-height:1;cursor:pointer;pointer-events:auto;';
|
|
21455
|
+
close.addEventListener('click', (event) => {
|
|
21456
|
+
// 阻止冒泡到气泡(否则同一次点击会触发两次 onClose)。
|
|
21457
|
+
try { if (event && typeof event.stopPropagation === 'function') event.stopPropagation(); } catch { /* ignore */ }
|
|
21458
|
+
hide(0);
|
|
21459
|
+
onClose();
|
|
21460
|
+
});
|
|
21461
|
+
if (typeof el.appendChild === 'function') el.appendChild(close);
|
|
21462
|
+
|
|
21463
|
+
if (typeof wrap.appendChild === 'function') { wrap.appendChild(statusEl); wrap.appendChild(el); }
|
|
21464
|
+
if (doc.body && typeof doc.body.appendChild === 'function') doc.body.appendChild(wrap);
|
|
21465
|
+
return wrap;
|
|
21364
21466
|
}
|
|
21365
21467
|
|
|
21366
21468
|
function cancelFade() {
|
|
21367
21469
|
if (fadeTimer != null) { clearTimer(fadeTimer); fadeTimer = null; }
|
|
21368
21470
|
}
|
|
21471
|
+
function cancelStatus() {
|
|
21472
|
+
if (statusTimer != null) { clearTimer(statusTimer); statusTimer = null; }
|
|
21473
|
+
}
|
|
21474
|
+
function statusVisible() {
|
|
21475
|
+
return Boolean(statusEl && statusEl.style && String(statusEl.style.opacity) === '1');
|
|
21476
|
+
}
|
|
21369
21477
|
|
|
21370
|
-
/**
|
|
21478
|
+
/** 显示(或继续显示)一段**回答**;状态/错误请走 `status()`。 */
|
|
21371
21479
|
function show(nextText) {
|
|
21372
21480
|
if (!ensure()) return;
|
|
21373
21481
|
cancelFade();
|
|
21374
21482
|
text = String(nextText == null ? '' : nextText);
|
|
21375
|
-
|
|
21376
|
-
el.style.opacity = '1';
|
|
21483
|
+
if (textEl) textEl.textContent = text;
|
|
21484
|
+
if (el) { el.dataset.visible = '1'; el.style.opacity = '1'; }
|
|
21377
21485
|
visible = true;
|
|
21378
21486
|
place();
|
|
21379
21487
|
startFollow();
|
|
@@ -21384,53 +21492,120 @@ window.__ModuleLoader__.load({
|
|
|
21384
21492
|
if (!ensure()) return;
|
|
21385
21493
|
cancelFade();
|
|
21386
21494
|
text += String(chunk == null ? '' : chunk);
|
|
21387
|
-
|
|
21388
|
-
el.style.opacity = '1';
|
|
21495
|
+
if (textEl) textEl.textContent = text;
|
|
21496
|
+
if (el) { el.dataset.visible = '1'; el.style.opacity = '1'; }
|
|
21389
21497
|
visible = true;
|
|
21498
|
+
place();
|
|
21390
21499
|
startFollow();
|
|
21391
21500
|
}
|
|
21392
21501
|
|
|
21393
|
-
/**
|
|
21502
|
+
/** 隐藏回答气泡;带 delay 时先挂着,到点淡出(朗读结束后 +3s 用这个)。 */
|
|
21394
21503
|
function hide(delayMs) {
|
|
21395
21504
|
if (!el) return;
|
|
21396
21505
|
cancelFade();
|
|
21397
21506
|
const delay = Number(delayMs) || 0;
|
|
21398
21507
|
const doHide = () => {
|
|
21399
21508
|
fadeTimer = null;
|
|
21400
|
-
stopFollow();
|
|
21509
|
+
if (!statusVisible()) stopFollow();
|
|
21401
21510
|
el.style.opacity = '0';
|
|
21511
|
+
if (el.dataset) el.dataset.visible = '0';
|
|
21402
21512
|
visible = false;
|
|
21403
21513
|
};
|
|
21404
21514
|
if (delay > 0) { fadeTimer = setTimer(doHide, delay); return; }
|
|
21405
21515
|
doHide();
|
|
21406
21516
|
}
|
|
21407
21517
|
|
|
21408
|
-
/**
|
|
21518
|
+
/** 显示状态条(错误/提示/在听/在想/在说)。 */
|
|
21519
|
+
function status(kind, message, opts) {
|
|
21520
|
+
if (!ensure()) return;
|
|
21521
|
+
cancelStatus();
|
|
21522
|
+
const o = opts || {};
|
|
21523
|
+
const k = String(kind || 'info');
|
|
21524
|
+
const icon = k === 'error' ? '🔴 ' : (k === 'info' ? 'ℹ️ ' : '');
|
|
21525
|
+
if (statusEl) {
|
|
21526
|
+
statusEl.dataset.state = k;
|
|
21527
|
+
statusEl.textContent = icon + String(message == null ? '' : message);
|
|
21528
|
+
statusEl.dataset.visible = '1';
|
|
21529
|
+
statusEl.style.opacity = '1';
|
|
21530
|
+
}
|
|
21531
|
+
// 状态条可能独立于回答气泡出现(没麦克风/在听)—— 也必须锚在桌宠头顶。
|
|
21532
|
+
place();
|
|
21533
|
+
startFollow();
|
|
21534
|
+
const delay = o.delay !== undefined ? Number(o.delay) || 0 : (k === 'error' ? 6000 : 4000);
|
|
21535
|
+
if (delay > 0) statusTimer = setTimer(() => { statusTimer = null; hideStatus(0); }, delay);
|
|
21536
|
+
}
|
|
21537
|
+
|
|
21538
|
+
/** 隐藏状态条(独立于回答气泡)。 */
|
|
21539
|
+
function hideStatus(delayMs) {
|
|
21540
|
+
if (!statusEl) return;
|
|
21541
|
+
cancelStatus();
|
|
21542
|
+
const delay = Number(delayMs) || 0;
|
|
21543
|
+
const doHide = () => {
|
|
21544
|
+
statusTimer = null;
|
|
21545
|
+
statusEl.style.opacity = '0';
|
|
21546
|
+
if (statusEl.dataset) { statusEl.dataset.visible = '0'; statusEl.dataset.state = ''; }
|
|
21547
|
+
if (!visible) stopFollow();
|
|
21548
|
+
};
|
|
21549
|
+
if (delay > 0) { statusTimer = setTimer(doHide, delay); return; }
|
|
21550
|
+
doHide();
|
|
21551
|
+
}
|
|
21552
|
+
|
|
21553
|
+
/** 三态:听 / 想 / 说(落在状态条上;bubble 的 data-state 同步保留给既有判据)。 */
|
|
21409
21554
|
function setState(kind) {
|
|
21410
21555
|
if (!ensure()) return;
|
|
21411
|
-
|
|
21412
|
-
el.dataset
|
|
21413
|
-
|
|
21556
|
+
const k = String(kind || '');
|
|
21557
|
+
if (el && el.dataset) el.dataset.state = k;
|
|
21558
|
+
if (k === 'idle') {
|
|
21559
|
+
// 错误/提示正在显示时不许被 idle 抹掉(TTS 错误后常紧跟一个 idle)。
|
|
21560
|
+
const cur = statusEl && statusEl.dataset ? String(statusEl.dataset.state || '') : '';
|
|
21561
|
+
if (cur === 'error' || cur === 'info') return;
|
|
21562
|
+
cancelStatus();
|
|
21563
|
+
hideStatus(1200);
|
|
21564
|
+
return;
|
|
21565
|
+
}
|
|
21566
|
+
const labels = { listen: '🎤 ' + tr('在听'), think: '💭 ' + tr('在想'), speak: '🔊 ' + tr('在说') };
|
|
21567
|
+
const label = labels[k];
|
|
21568
|
+
if (!label) return;
|
|
21569
|
+
// 错误/提示(含音色回落)在它自己的 3–6 秒窗口内优先于三态,别被下一句“在说”立刻盖掉。
|
|
21570
|
+
const curState = statusEl && statusEl.dataset ? String(statusEl.dataset.state || '') : '';
|
|
21571
|
+
if (curState === 'error' || curState === 'info') return;
|
|
21572
|
+
cancelStatus();
|
|
21573
|
+
if (statusEl) {
|
|
21574
|
+
statusEl.dataset.state = k;
|
|
21575
|
+
statusEl.textContent = label;
|
|
21576
|
+
statusEl.dataset.visible = '1';
|
|
21577
|
+
statusEl.style.opacity = '1';
|
|
21578
|
+
}
|
|
21579
|
+
place();
|
|
21580
|
+
startFollow();
|
|
21414
21581
|
}
|
|
21415
21582
|
|
|
21416
21583
|
function isVisible() { return visible; }
|
|
21417
21584
|
|
|
21418
21585
|
function dispose() {
|
|
21419
21586
|
cancelFade();
|
|
21587
|
+
cancelStatus();
|
|
21420
21588
|
stopFollow();
|
|
21421
|
-
if (
|
|
21589
|
+
if (wrap && typeof wrap.remove === 'function') wrap.remove();
|
|
21590
|
+
wrap = null;
|
|
21422
21591
|
el = null;
|
|
21592
|
+
textEl = null;
|
|
21593
|
+
statusEl = null;
|
|
21423
21594
|
text = '';
|
|
21424
21595
|
visible = false;
|
|
21425
21596
|
}
|
|
21426
21597
|
|
|
21427
21598
|
return {
|
|
21428
|
-
show, append, hide, setState, place, isVisible, dispose,
|
|
21599
|
+
show, append, hide, setState, status, hideStatus, place, isVisible, dispose,
|
|
21429
21600
|
get following() { return rafId != null; },
|
|
21430
|
-
// 判据要读的内部状态
|
|
21431
21601
|
get text() { return text; },
|
|
21432
21602
|
get element() { return el; },
|
|
21603
|
+
get textElement() { return textEl; },
|
|
21604
|
+
get statusElement() { return statusEl; },
|
|
21605
|
+
get wrapElement() { return wrap; },
|
|
21433
21606
|
MAX_LINES,
|
|
21607
|
+
BUBBLE_MAX_WIDTH,
|
|
21608
|
+
BUBBLE_MAX_HEIGHT,
|
|
21434
21609
|
};
|
|
21435
21610
|
}
|
|
21436
21611
|
|
|
@@ -21535,6 +21710,7 @@ window.__ModuleLoader__.load({
|
|
|
21535
21710
|
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
21536
21711
|
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
21537
21712
|
const onIdle = typeof options.onIdle === 'function' ? options.onIdle : () => {};
|
|
21713
|
+
const onVoiceFallback = typeof options.onVoiceFallback === 'function' ? options.onVoiceFallback : () => {};
|
|
21538
21714
|
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
21539
21715
|
|
|
21540
21716
|
let generation = 0;
|
|
@@ -21543,6 +21719,8 @@ window.__ModuleLoader__.load({
|
|
|
21543
21719
|
let playing = null;
|
|
21544
21720
|
let prefetch = null;
|
|
21545
21721
|
let disposed = false;
|
|
21722
|
+
/** pre.54:音色回落只提示一次(每个实例),避免每句都弹状态条。 */
|
|
21723
|
+
let voiceFallbackWarned = false;
|
|
21546
21724
|
|
|
21547
21725
|
function revoke(url) {
|
|
21548
21726
|
if (!url || !UrlApi || typeof UrlApi.revokeObjectURL !== 'function') return;
|
|
@@ -21574,7 +21752,19 @@ window.__ModuleLoader__.load({
|
|
|
21574
21752
|
} catch { /* 非 JSON 错误体 */ }
|
|
21575
21753
|
return { error: { code: 'tts-failed', status: (res && res.status) || 0, hint: hint || '语音合成失败' } };
|
|
21576
21754
|
}
|
|
21755
|
+
// ⚠️ blob() 必须紧跟 apiFetch 同一个 try 调用窗(verify-api-client ①b 的判据);
|
|
21756
|
+
// 音色回落的响应头检查放在拿到 blob 之后,不隔断这层关系。
|
|
21577
21757
|
blob = await res.response.blob();
|
|
21758
|
+
try {
|
|
21759
|
+
const headers = res.response.headers;
|
|
21760
|
+
const fb = headers && typeof headers.get === 'function' ? headers.get('x-folia-tts-fallback') : '';
|
|
21761
|
+
if (fb === '1' && !voiceFallbackWarned) {
|
|
21762
|
+
voiceFallbackWarned = true;
|
|
21763
|
+
let actual = '';
|
|
21764
|
+
try { actual = decodeURIComponent(String(headers.get('x-folia-tts-voice') || '')); } catch { actual = ''; }
|
|
21765
|
+
onVoiceFallback(actual || '');
|
|
21766
|
+
}
|
|
21767
|
+
} catch { /* 头读不到不影响播放 */ }
|
|
21578
21768
|
} catch (error) {
|
|
21579
21769
|
if (!res) return { error: { code: 'tts-network', hint: '连不上宿主,语音没出来' } };
|
|
21580
21770
|
return { error: { code: 'tts-read-failed', hint: '读不到语音数据' } };
|
|
@@ -21825,6 +22015,15 @@ window.__ModuleLoader__.load({
|
|
|
21825
22015
|
return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, scale };
|
|
21826
22016
|
} catch { return null; }
|
|
21827
22017
|
},
|
|
22018
|
+
// 状态条可点:错误/提示 ⇒ 打开打字入口;在听/在想/在说 ⇒ 停止(与再点桌宠同一语义)。
|
|
22019
|
+
onStatusClick: () => {
|
|
22020
|
+
try {
|
|
22021
|
+
const st = petBubble.statusElement && petBubble.statusElement.dataset
|
|
22022
|
+
? String(petBubble.statusElement.dataset.state || '') : '';
|
|
22023
|
+
if (st === 'error' || st === 'info') petChatOpenTyping();
|
|
22024
|
+
else petVoiceIn.stop();
|
|
22025
|
+
} catch { /* 状态条点击是增强 */ }
|
|
22026
|
+
},
|
|
21828
22027
|
});
|
|
21829
22028
|
|
|
21830
22029
|
/**
|
|
@@ -21832,7 +22031,8 @@ window.__ModuleLoader__.load({
|
|
|
21832
22031
|
* 然后轮询 /pet-chat/asr 把下载进度显示在气泡里。
|
|
21833
22032
|
* 这样用户装完插件直接说话就行,不需要去 DSH 设置里找「语音输入」开关。
|
|
21834
22033
|
*/
|
|
21835
|
-
async function ensureAsrReady() {
|
|
22034
|
+
async function ensureAsrReady() {
|
|
22035
|
+
petBubble.setState('think');
|
|
21836
22036
|
try {
|
|
21837
22037
|
await apiPostJson('/pet-chat/asr', {}, { parse: 'always' });
|
|
21838
22038
|
} catch { /* 触发失败也要继续轮询看状态 */ }
|
|
@@ -21841,27 +22041,23 @@ window.__ModuleLoader__.load({
|
|
|
21841
22041
|
const resp = await apiJson('/pet-chat/asr', { parse: 'always' }).catch(() => null);
|
|
21842
22042
|
const doc = (resp && resp.data) || {};
|
|
21843
22043
|
if (doc.ready) {
|
|
21844
|
-
petBubble.
|
|
21845
|
-
petBubble.hide(3000);
|
|
22044
|
+
petBubble.status('info', '语音准备好了,点我再说一次', { delay: 3000 });
|
|
21846
22045
|
return;
|
|
21847
22046
|
}
|
|
21848
22047
|
if (doc.available === false) {
|
|
21849
|
-
petBubble.
|
|
21850
|
-
petBubble.hide(3000);
|
|
22048
|
+
petBubble.status('error', '这个 DSH 版本没有语音转写服务,先打字吧', { delay: 5000 });
|
|
21851
22049
|
return;
|
|
21852
22050
|
}
|
|
21853
22051
|
if (doc.phase === 'failed') {
|
|
21854
|
-
petBubble.
|
|
21855
|
-
petBubble.hide(3000);
|
|
22052
|
+
petBubble.status('error', '语音模型下载失败,稍后再点我试试', { delay: 5000 });
|
|
21856
22053
|
return;
|
|
21857
22054
|
}
|
|
21858
22055
|
const pct = doc.totalBytes > 0 && doc.completedBytes >= 0
|
|
21859
22056
|
? Math.max(0, Math.min(100, Math.round((doc.completedBytes / doc.totalBytes) * 100)))
|
|
21860
22057
|
: null;
|
|
21861
|
-
petBubble.
|
|
22058
|
+
petBubble.status('info', pct === null ? '语音模型准备中…' : `语音模型下载中 ${pct}%`, { delay: 0 });
|
|
21862
22059
|
}
|
|
21863
|
-
petBubble.
|
|
21864
|
-
petBubble.hide(3000);
|
|
22060
|
+
petBubble.status('info', '语音模型还没下完,过一会儿再点我', { delay: 5000 });
|
|
21865
22061
|
}
|
|
21866
22062
|
|
|
21867
22063
|
/**
|
|
@@ -21905,12 +22101,16 @@ window.__ModuleLoader__.load({
|
|
|
21905
22101
|
},
|
|
21906
22102
|
onState: (kind) => { petBubble.setState(kind); },
|
|
21907
22103
|
onIdle: () => { petBubble.hide(3000); },
|
|
22104
|
+
onVoiceFallback: (actual) => {
|
|
22105
|
+
// pre.54(B3④):宿主回落到本机默认音色时明确提示,不静默换音色。
|
|
22106
|
+
petBubble.status('info', actual
|
|
22107
|
+
? weT('所选音色不可用,已用系统默认:{name}', { name: actual })
|
|
22108
|
+
: weT('所选音色不可用,已用系统默认音色'), { delay: 5000 });
|
|
22109
|
+
},
|
|
21908
22110
|
onError: (error) => {
|
|
21909
|
-
//
|
|
22111
|
+
// 失败只进**状态条**(不污染回答气泡、不弹窗);不静默 —— 用户至少知道为什么没声音
|
|
21910
22112
|
const hint = (error && error.hint) || '语音没出来';
|
|
21911
|
-
petBubble.
|
|
21912
|
-
petBubble.show(hint);
|
|
21913
|
-
petBubble.hide(4000);
|
|
22113
|
+
petBubble.status('error', hint, { delay: 5000 });
|
|
21914
22114
|
},
|
|
21915
22115
|
});
|
|
21916
22116
|
|
|
@@ -21947,15 +22147,13 @@ window.__ModuleLoader__.load({
|
|
|
21947
22147
|
parse: 'none',
|
|
21948
22148
|
});
|
|
21949
22149
|
} catch {
|
|
21950
|
-
petBubble.
|
|
21951
|
-
petBubble.hide(3000);
|
|
22150
|
+
petBubble.status('error', '连不上宿主,稍后再试', { delay: 4000 });
|
|
21952
22151
|
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
21953
22152
|
return;
|
|
21954
22153
|
}
|
|
21955
22154
|
const stream = res && res.response;
|
|
21956
22155
|
if (!res || !res.ok || !stream || !stream.body) {
|
|
21957
|
-
petBubble.
|
|
21958
|
-
petBubble.hide(3000);
|
|
22156
|
+
petBubble.status('error', res && res.status === 401 ? '模型 Key 无效,去设置里换一把' : '这次没答上来,再试一次', { delay: 4000 });
|
|
21959
22157
|
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
21960
22158
|
return;
|
|
21961
22159
|
}
|
|
@@ -22041,16 +22239,15 @@ window.__ModuleLoader__.load({
|
|
|
22041
22239
|
network: '网络不太顺,重试或直接打字',
|
|
22042
22240
|
};
|
|
22043
22241
|
const message = map[error && error.code] || '没听清,直接打字也行';
|
|
22044
|
-
|
|
22045
|
-
// asr-not-ready:自动触发模型下载并在气泡里显示进度,用户不用去 DSH 设置里找开关
|
|
22242
|
+
// asr-not-ready:自动触发模型下载并在状态条里显示进度,用户不用去 DSH 设置里找开关
|
|
22046
22243
|
if (error && error.code === 'asr-not-ready') {
|
|
22244
|
+
petBubble.status('info', message, { delay: 0 });
|
|
22047
22245
|
void ensureAsrReady();
|
|
22048
22246
|
return;
|
|
22049
22247
|
}
|
|
22050
22248
|
// ⚠️ 失败**不要自动弹输入框**(用户会以为"点一下就变对话框")。
|
|
22051
22249
|
// 打字入口只从右键菜单「对话」进;这里只给一行提示 + 引导。
|
|
22052
|
-
petBubble.
|
|
22053
|
-
petBubble.hide(4000);
|
|
22250
|
+
petBubble.status('error', `${message}(右键 → 对话)`, { delay: 5000 });
|
|
22054
22251
|
},
|
|
22055
22252
|
});
|
|
22056
22253
|
|
|
@@ -22106,7 +22303,7 @@ window.__ModuleLoader__.load({
|
|
|
22106
22303
|
// **任何一次唤醒都是 barge-in**:先把正在念的停掉,再决定是收起还是开麦。
|
|
22107
22304
|
petSpeakStop();
|
|
22108
22305
|
void petChatRefreshVoice();
|
|
22109
|
-
if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
|
|
22306
|
+
if (petBubble.isVisible()) { petBubble.hide(0); petBubble.hideStatus(0); petVoiceIn.stop(); return; }
|
|
22110
22307
|
petBubble.setState('listen');
|
|
22111
22308
|
// 先看语音模型是否就绪;没就绪就**立刻**开始下载并在气泡里显示进度,
|
|
22112
22309
|
// 不要等用户先撞一次 asr-not-ready 才被动触发(那之前会像"没反应")。
|
|
@@ -22119,7 +22316,7 @@ window.__ModuleLoader__.load({
|
|
|
22119
22316
|
})();
|
|
22120
22317
|
void petVoiceIn.start().then((started) => {
|
|
22121
22318
|
if (!started) return; // 失败分支已经由 onError 提示(回落打字)
|
|
22122
|
-
|
|
22319
|
+
// 状态条已经由 setState('listen') 显示「🎤 在听」,这里不再往回答气泡里塞提示。
|
|
22123
22320
|
});
|
|
22124
22321
|
}
|
|
22125
22322
|
|
package/lib/routes/pet-chat.js
CHANGED
|
@@ -30,6 +30,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, wri
|
|
|
30
30
|
import { homedir, tmpdir } from 'node:os';
|
|
31
31
|
import { dirname, join } from 'node:path';
|
|
32
32
|
import { createTtsService, normalizeTtsText, TTS_MAX_CHARS } from '../tts/tts.js';
|
|
33
|
+
import { TTS_CATALOG } from '../tts/catalog.js';
|
|
33
34
|
import { CAPABILITIES } from '../capabilities-catalog.js';
|
|
34
35
|
|
|
35
36
|
import {
|
|
@@ -1148,7 +1149,8 @@ const roots = [
|
|
|
1148
1149
|
if (typeof body.ownerName === 'string') patch.ownerName = body.ownerName.trim().slice(0, 24);
|
|
1149
1150
|
if (body.voice && typeof body.voice === 'object') {
|
|
1150
1151
|
patch.voice = {
|
|
1151
|
-
|
|
1152
|
+
// pre.54:空串 = 宿主自动选本机第一个可用中文音色(不再是云端 Xiaoxiao)。
|
|
1153
|
+
name: String(body.voice.name || '').slice(0, 120),
|
|
1152
1154
|
muted: body.voice.muted === true,
|
|
1153
1155
|
};
|
|
1154
1156
|
}
|
|
@@ -1287,6 +1289,23 @@ const roots = [
|
|
|
1287
1289
|
return delivered;
|
|
1288
1290
|
}
|
|
1289
1291
|
|
|
1292
|
+
/**
|
|
1293
|
+
* GET /pet-chat/tts/voices —— 本机**真实可用**音色(pre.54)。
|
|
1294
|
+
* 只返回 `usable:true` 的条目由前端再过滤;这里保留 usable 字段便于排障。
|
|
1295
|
+
*/
|
|
1296
|
+
async function handleTtsVoices(res) {
|
|
1297
|
+
let voices = [];
|
|
1298
|
+
try {
|
|
1299
|
+
voices = typeof ttsService.voices === 'function' ? await ttsService.voices() : [];
|
|
1300
|
+
} catch { voices = []; }
|
|
1301
|
+
jsonSend(res, { ok: true, voices: Array.isArray(voices) ? voices : [] });
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
/** GET /pet-chat/tts/catalog —— 可下载离线音色目录(本版 mostly coming-soon)。 */
|
|
1305
|
+
function handleTtsCatalog(res) {
|
|
1306
|
+
jsonSend(res, { ok: true, items: TTS_CATALOG });
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1290
1309
|
/**
|
|
1291
1310
|
* GET /pet-chat/tts?text=&voice=&rate= → `audio/wav`(单句;客户端按句排队)。
|
|
1292
1311
|
* 失败一律 JSON + 明确 code:400 参数、409 已被 stop 作废、503 合成不可用。
|
|
@@ -1339,6 +1358,8 @@ const roots = [
|
|
|
1339
1358
|
requestedVoice,
|
|
1340
1359
|
actualVoice,
|
|
1341
1360
|
engine: String(result.engine || 'system'),
|
|
1361
|
+
fallback: result.fallback === true,
|
|
1362
|
+
fallbackFrom: result.fallbackFrom || '',
|
|
1342
1363
|
attempts,
|
|
1343
1364
|
code: null,
|
|
1344
1365
|
cached: Boolean(result.cached),
|
|
@@ -1355,6 +1376,7 @@ const roots = [
|
|
|
1355
1376
|
res.setHeader('X-Folia-TTS-Attempts', ttsHeaderValue(attempts));
|
|
1356
1377
|
res.setHeader('X-Folia-TTS-Ms', String(Number(result.ms) || 0));
|
|
1357
1378
|
res.setHeader('X-Folia-TTS-Cached', result.cached ? '1' : '0');
|
|
1379
|
+
res.setHeader('X-Folia-TTS-Fallback', result.fallback === true ? '1' : '0');
|
|
1358
1380
|
res.end(result.wav);
|
|
1359
1381
|
}
|
|
1360
1382
|
|
|
@@ -1373,10 +1395,12 @@ const roots = [
|
|
|
1373
1395
|
...status,
|
|
1374
1396
|
voice: config.voice,
|
|
1375
1397
|
// pre.46:把“用户要的音色 / 上次实际用的音色 / 引擎 / 每跳原因”一起回,
|
|
1376
|
-
// 排障时不用再猜为什么设置没生效。
|
|
1377
|
-
requestedVoice: String((config.voice && config.voice.name) || ''),
|
|
1398
|
+
// 排障时不用再猜为什么设置没生效。pre.54:优先用**上次请求**的音色(配置可能为空 = 自动)。
|
|
1399
|
+
requestedVoice: String((lastTts && lastTts.requestedVoice) || (config.voice && config.voice.name) || ''),
|
|
1378
1400
|
actualVoice: lastTts ? lastTts.actualVoice : null,
|
|
1379
1401
|
engine: lastTts ? lastTts.engine : null,
|
|
1402
|
+
fallback: lastTts ? lastTts.fallback === true : false,
|
|
1403
|
+
fallbackFrom: lastTts ? (lastTts.fallbackFrom || '') : '',
|
|
1380
1404
|
attempts: lastTts ? lastTts.attempts : [],
|
|
1381
1405
|
lastTts,
|
|
1382
1406
|
maxChars: TTS_MAX_CHARS,
|
|
@@ -1472,6 +1496,8 @@ const roots = [
|
|
|
1472
1496
|
if (tail === '/tts' && (method === 'GET' || method === 'HEAD')) { await handleTts(req, res, url); return; }
|
|
1473
1497
|
if (tail === '/tts/stop' && method === 'POST') { handleTtsStop(res); return; }
|
|
1474
1498
|
if (tail === '/tts/state' && (method === 'GET' || method === 'HEAD')) { handleTtsState(res); return; }
|
|
1499
|
+
if (tail === '/tts/voices' && (method === 'GET' || method === 'HEAD')) { await handleTtsVoices(res); return; }
|
|
1500
|
+
if (tail === '/tts/catalog' && (method === 'GET' || method === 'HEAD')) { handleTtsCatalog(res); return; }
|
|
1475
1501
|
if (tail === '/events' && (method === 'GET' || method === 'HEAD')) { handleEvents(req, res); return; }
|
|
1476
1502
|
if (tail === '/speak' && method === 'POST') { await handleSpeak(req, res); return; }
|
|
1477
1503
|
// 语音模型(SenseVoice)自举:用户不需要去 DSH 设置里找开关,
|
package/lib/settings-schema.js
CHANGED
|
@@ -1004,8 +1004,10 @@ const DEFAULTS = {
|
|
|
1004
1004
|
*/
|
|
1005
1005
|
petName: '', // 桌宠名字(空 ⇒ 用宠物包 displayName);同时是唤醒词
|
|
1006
1006
|
ownerName: '', // 用户希望被怎么称呼
|
|
1007
|
-
// 朗读:只有一个音色 + 一个静音开关(不再有 rate/pitch/volume/voiceURI
|
|
1008
|
-
|
|
1007
|
+
// 朗读:只有一个音色 + 一个静音开关(不再有 rate/pitch/volume/voiceURI 五件套)。
|
|
1008
|
+
// pre.54:默认**空串** = 由宿主选本机第一个可用中文音色(这台是 Microsoft Huihui Desktop)。
|
|
1009
|
+
// 旧默认是 Edge 云端音色,本机没有模型/许可不允许随包分发。
|
|
1010
|
+
voice: { name: '', muted: false },
|
|
1009
1011
|
// 唤醒:点一下默认开;叫名字默认关(S6 才实现,先在设置里留位)
|
|
1010
1012
|
wake: { click: true, name: false, keyword: '' },
|
|
1011
1013
|
// 对话记忆默认开启且**不暴露开关**(追加决定 1):能力常开,用户只能在右键里查看/清空
|
|
@@ -1754,7 +1756,10 @@ function readVoice(raw, legacy) {
|
|
|
1754
1756
|
const def = DEFAULTS.petChat.voice;
|
|
1755
1757
|
const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
|
|
1756
1758
|
const old = legacy && typeof legacy === 'object' && !Array.isArray(legacy) ? legacy : {};
|
|
1757
|
-
const
|
|
1759
|
+
const picked = petChatStr(src.name, 120).trim() || petChatStr(old.voiceURI, 200).trim() || def.name;
|
|
1760
|
+
// pre.54:Edge neural 名(`zh-CN-XxxNeural` 这类)是云端音色,本机没有本地模型、
|
|
1761
|
+
// 也不允许随包分发 ⇒ 读档时迁成空串(= 宿主自动选本机第一个可用中文音色)。
|
|
1762
|
+
const name = /^[a-z]{2}-[A-Z]{2}-[A-Za-z0-9]+Neural$/.test(picked) ? '' : picked;
|
|
1758
1763
|
const muted = typeof src.muted === 'boolean' ? src.muted : old.enabled === false;
|
|
1759
1764
|
return { name, muted };
|
|
1760
1765
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tts/catalog.js — 可下载/可打包的**离线 TTS 音色目录**(pre.54,任务 C 的骨架)。
|
|
3
|
+
*
|
|
4
|
+
* 纪律(用户硬性要求):
|
|
5
|
+
* · Edge neural(`zh-CN-XxxNeural` 这类)**是云端音色**,没有本地模型、许可不允许再分发
|
|
6
|
+
* ⇒ 不进目录、不进包、不进下拉;
|
|
7
|
+
* · 这里只列**开源、可离线、许可允许再分发**的方案;`available:false` 明示本版只接目录,
|
|
8
|
+
* 合成尚未接通 —— 界面不得写成"已支持";
|
|
9
|
+
* · 不提供假的下载地址:`homepage` 指向项目官方仓库,模型下载 URL 在接通后由实现补。
|
|
10
|
+
*
|
|
11
|
+
* 后续接 Piper/sherpa 时:把 `available` 改为 true、补 `downloadUrl`,并让 `/tts/voices`
|
|
12
|
+
* 在模型落盘后返回 `engine:'piper'|'sherpa'` 的条目;前端只认 `usable:true`。
|
|
13
|
+
*/
|
|
14
|
+
export const TTS_CATALOG = Object.freeze([
|
|
15
|
+
{
|
|
16
|
+
id: 'piper-zh',
|
|
17
|
+
name: 'Piper 中文音色',
|
|
18
|
+
engine: 'piper',
|
|
19
|
+
license: 'MIT',
|
|
20
|
+
size: '约 60–70 MB / 音色',
|
|
21
|
+
homepage: 'https://github.com/rhasspy/piper',
|
|
22
|
+
available: false,
|
|
23
|
+
status: 'coming-soon',
|
|
24
|
+
note: '离线开源;本版只接目录,合成尚未接通(会在接通后标为可用)',
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
id: 'sherpa-onnx-zh',
|
|
28
|
+
name: 'sherpa-onnx 中文 TTS',
|
|
29
|
+
engine: 'sherpa',
|
|
30
|
+
license: 'Apache-2.0',
|
|
31
|
+
size: '约 40–100 MB / 模型',
|
|
32
|
+
homepage: 'https://github.com/k2-fsa/sherpa-onnx',
|
|
33
|
+
available: false,
|
|
34
|
+
status: 'coming-soon',
|
|
35
|
+
note: '离线开源;本版只接目录,合成尚未接通',
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
id: 'melo-zh',
|
|
39
|
+
name: 'MeloTTS 中文',
|
|
40
|
+
engine: 'melo',
|
|
41
|
+
license: 'MIT',
|
|
42
|
+
size: '约 300–500 MB',
|
|
43
|
+
homepage: 'https://github.com/myshell-ai/MeloTTS',
|
|
44
|
+
available: false,
|
|
45
|
+
status: 'coming-soon',
|
|
46
|
+
note: '体积较大,计划首次使用时下载;本版只接目录',
|
|
47
|
+
},
|
|
48
|
+
]);
|
package/lib/tts/tts-worker.cjs
CHANGED
|
@@ -43,7 +43,7 @@ const readline = require('node:readline');
|
|
|
43
43
|
const ENGINES = Object.freeze(['sapi', 'edge']);
|
|
44
44
|
|
|
45
45
|
/**
|
|
46
|
-
* Edge / WinRT
|
|
46
|
+
* Edge / WinRT 的音色命名(`zh-CN-XxxNeural` 这类)。
|
|
47
47
|
* 这种名字**只存在于 Edge/OneCore 目录**,SAPI 一定没有 ⇒ 必须把 edge 排到第一跳,
|
|
48
48
|
* 否则 SAPI 找不到时会回落到 Huihui 并"成功",用户的音色设置永远不生效。
|
|
49
49
|
*/
|
|
@@ -228,6 +228,72 @@ function writeScript(dir, name, body) {
|
|
|
228
228
|
return file;
|
|
229
229
|
}
|
|
230
230
|
|
|
231
|
+
/**
|
|
232
|
+
* pre.54(B3②):枚举**本机 SAPI 音色**(System.Speech 桌面音色,离线零模型)。
|
|
233
|
+
*
|
|
234
|
+
* Edge/OneCore(WinRT)音色在这台机器上实测 503,先**不列**(宁可少列,不可列了没用);
|
|
235
|
+
* 合成链仍保留 edge 兜底,只是下拉里只出现本机真能出声的。
|
|
236
|
+
* 输出 UTF-8(无 BOM)JSON 到 `$Out`,由 Node 侧读回。
|
|
237
|
+
*/
|
|
238
|
+
const SAPI_VOICES_SCRIPT = `
|
|
239
|
+
param([string]$Req, [string]$Out)
|
|
240
|
+
$ErrorActionPreference = 'Stop'
|
|
241
|
+
Add-Type -AssemblyName System.Speech
|
|
242
|
+
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
|
|
243
|
+
$list = @()
|
|
244
|
+
try {
|
|
245
|
+
foreach ($v in $synth.GetInstalledVoices()) {
|
|
246
|
+
if (-not $v.Enabled) { continue }
|
|
247
|
+
$info = $v.VoiceInfo
|
|
248
|
+
$list += [pscustomobject]@{ Name = $info.Name; Culture = $info.Culture.Name; Gender = [string]$info.Gender }
|
|
249
|
+
}
|
|
250
|
+
} finally { $synth.Dispose() }
|
|
251
|
+
$json = $list | ConvertTo-Json -Compress
|
|
252
|
+
if (-not $json) { $json = '[]' }
|
|
253
|
+
[System.IO.File]::WriteAllText($Out, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
254
|
+
`;
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* pre.54(B3②):本机音色清单 + **逐个试合成**(usable)。
|
|
258
|
+
* 只做 SAPI;试合成用一句 2 字中文(短、快),成功后立刻删掉试听 WAV。
|
|
259
|
+
*/
|
|
260
|
+
async function listVoices(deps = {}) {
|
|
261
|
+
if (process.platform !== 'win32') return [];
|
|
262
|
+
const dir = deps.dir || fs.mkdtempSync(path.join(os.tmpdir(), 'folia-tts-voices-'));
|
|
263
|
+
const stamp = crypto.randomBytes(4).toString('hex');
|
|
264
|
+
const scriptFile = writeScript(dir, 'voices-' + stamp + '.ps1', SAPI_VOICES_SCRIPT);
|
|
265
|
+
const outFile = path.join(dir, 'voices-' + stamp + '.json');
|
|
266
|
+
let raw = [];
|
|
267
|
+
try {
|
|
268
|
+
await runPowerShellScript(scriptFile, '', outFile, Math.max(3000, Number(deps.voicesTimeoutMs) || 15000));
|
|
269
|
+
try { raw = JSON.parse(fs.readFileSync(outFile, 'utf8').replace(/^\uFEFF/, '')); } catch { raw = []; }
|
|
270
|
+
} catch { raw = []; }
|
|
271
|
+
for (const file of [scriptFile, outFile]) { try { fs.unlinkSync(file); } catch { /* ignore */ } }
|
|
272
|
+
const items = Array.isArray(raw) ? raw : (raw ? [raw] : []);
|
|
273
|
+
const out = [];
|
|
274
|
+
for (const item of items) {
|
|
275
|
+
const name = String((item && item.Name) || '').trim();
|
|
276
|
+
if (!name) continue;
|
|
277
|
+
let usable = false;
|
|
278
|
+
try {
|
|
279
|
+
const test = await runEngine('sapi', '你好', { voice: name, rate: 0 }, Object.assign({}, deps, {
|
|
280
|
+
dir, timeoutMs: Math.max(3000, Number(deps.testTimeoutMs) || 6000),
|
|
281
|
+
}));
|
|
282
|
+
usable = Boolean(test && test.ok);
|
|
283
|
+
if (test && test.file) { try { fs.unlinkSync(test.file); } catch { /* ignore */ } }
|
|
284
|
+
} catch { usable = false; }
|
|
285
|
+
out.push({
|
|
286
|
+
engine: 'sapi',
|
|
287
|
+
id: name,
|
|
288
|
+
label: name,
|
|
289
|
+
lang: String((item && item.Culture) || ''),
|
|
290
|
+
gender: String((item && item.Gender) || ''),
|
|
291
|
+
usable,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
return out;
|
|
295
|
+
}
|
|
296
|
+
|
|
231
297
|
/**
|
|
232
298
|
* 跑一次 PowerShell(stdio 全走文件;超时强杀)。
|
|
233
299
|
* @returns {Promise<{ ok: boolean, code: number|null, voice: string, stderr: string }>}
|
|
@@ -372,29 +438,43 @@ async function synthesizeOnce(text, options = {}, deps = {}) {
|
|
|
372
438
|
const runEdge = typeof deps.runEdge === 'function' ? deps.runEdge : runEdgeEngine;
|
|
373
439
|
const attempts = [];
|
|
374
440
|
for (const engine of engines) {
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
441
|
+
// pre.54(B3①):显式音色在这一跳不存在 ⇒ **先用本引擎默认中文音色再试一次**,
|
|
442
|
+
// 成功也把 requestedVoice/实际 voice 都带回去(客户端据此提示“已回落”)。
|
|
443
|
+
// 空音色(默认)只试一次,不重复。
|
|
444
|
+
const candidates = requestedVoice ? [requestedVoice, ''] : [''];
|
|
445
|
+
for (const candidate of candidates) {
|
|
446
|
+
const engineOptions = Object.assign({}, options, { voice: candidate });
|
|
447
|
+
let jumped;
|
|
448
|
+
try {
|
|
449
|
+
jumped = await (engine === 'sapi' ? runSapi : runEdge)(clean, engineOptions, deps);
|
|
450
|
+
} catch (error) {
|
|
451
|
+
jumped = { ok: false, error: String((error && error.message) || error) };
|
|
452
|
+
}
|
|
453
|
+
if (jumped && jumped.ok && jumped.file) {
|
|
454
|
+
const valid = validateWav(jumped.file);
|
|
455
|
+
if (valid.ok) {
|
|
456
|
+
const actualVoice = String(jumped.voice || candidate || '');
|
|
457
|
+
return {
|
|
458
|
+
ok: true,
|
|
459
|
+
engine,
|
|
460
|
+
file: jumped.file,
|
|
461
|
+
bytes: valid.bytes,
|
|
462
|
+
voice: actualVoice,
|
|
463
|
+
requestedVoice,
|
|
464
|
+
fallback: Boolean(requestedVoice) && actualVoice !== requestedVoice,
|
|
465
|
+
fallbackFrom: Boolean(requestedVoice) && actualVoice !== requestedVoice ? requestedVoice : '',
|
|
466
|
+
ms: Number(jumped.ms) || 0,
|
|
467
|
+
attempts,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
attempts.push({ engine, voice: candidate || '(default)', error: valid.error || 'invalid-wav' });
|
|
471
|
+
} else {
|
|
472
|
+
attempts.push({
|
|
386
473
|
engine,
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
requestedVoice,
|
|
391
|
-
ms: Number(jumped.ms) || 0,
|
|
392
|
-
attempts,
|
|
393
|
-
};
|
|
474
|
+
voice: candidate || '(default)',
|
|
475
|
+
error: String((jumped && (jumped.error || jumped.code)) || 'engine-failed').slice(0, 400),
|
|
476
|
+
});
|
|
394
477
|
}
|
|
395
|
-
attempts.push({ engine, error: valid.error || 'invalid-wav' });
|
|
396
|
-
} else {
|
|
397
|
-
attempts.push({ engine, error: String((jumped && (jumped.error || jumped.code)) || 'engine-failed').slice(0, 400) });
|
|
398
478
|
}
|
|
399
479
|
}
|
|
400
480
|
return {
|
|
@@ -464,6 +544,17 @@ function runWorker(outDir) {
|
|
|
464
544
|
return;
|
|
465
545
|
}
|
|
466
546
|
const id = req.id === undefined ? null : req.id;
|
|
547
|
+
// pre.54:音色枚举是独立操作(只在 UI 打开时跑一次,worker 内存里结果由 tts.js 缓存)。
|
|
548
|
+
if (req.op === 'voices') {
|
|
549
|
+
chain = chain.then(async () => {
|
|
550
|
+
let voices = [];
|
|
551
|
+
try { voices = await listVoices({ dir, voicesTimeoutMs: 15000, testTimeoutMs: 6000 }); } catch { voices = []; }
|
|
552
|
+
process.stdout.write(JSON.stringify({ id, ok: true, voices }) + '\n');
|
|
553
|
+
}).catch((error) => {
|
|
554
|
+
process.stdout.write(JSON.stringify({ id, ok: false, code: 'voices-failed', error: String((error && error.message) || error) }) + '\n');
|
|
555
|
+
});
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
467
558
|
chain = chain.then(async () => {
|
|
468
559
|
const started = Date.now();
|
|
469
560
|
let result;
|
|
@@ -482,6 +573,9 @@ function runWorker(outDir) {
|
|
|
482
573
|
file: result.ok ? result.file : null,
|
|
483
574
|
engine: result.ok ? result.engine : null,
|
|
484
575
|
voice: result.ok ? result.voice : null,
|
|
576
|
+
requestedVoice: result.requestedVoice || req.voice || '',
|
|
577
|
+
fallback: result.ok ? result.fallback === true : false,
|
|
578
|
+
fallbackFrom: result.ok ? (result.fallbackFrom || '') : '',
|
|
485
579
|
bytes: result.ok ? result.bytes : null,
|
|
486
580
|
ms: Number(result.ms) || (Date.now() - started),
|
|
487
581
|
attempts: result.attempts || [],
|
|
@@ -532,4 +626,5 @@ module.exports = {
|
|
|
532
626
|
runSapiEngine,
|
|
533
627
|
runEdgeEngine,
|
|
534
628
|
synthesizeOnce,
|
|
629
|
+
listVoices,
|
|
535
630
|
};
|
package/lib/tts/tts.js
CHANGED
|
@@ -27,7 +27,7 @@ export const TTS_MAX_CHARS = 240;
|
|
|
27
27
|
/** 合成链(与 worker 的 ENGINES 对齐;路由状态里会回给界面)。 */
|
|
28
28
|
export const TTS_ENGINES = Object.freeze(['sapi', 'edge']);
|
|
29
29
|
|
|
30
|
-
/** Edge / WinRT 音色命名(`zh-CN-
|
|
30
|
+
/** Edge / WinRT 音色命名(`zh-CN-XxxNeural`)—— 这类名字只存在于 Edge 目录。 */
|
|
31
31
|
export const NEURAL_VOICE_RE = /^[a-z]{2}-[A-Z]{2}-[A-Za-z0-9]+Neural$/;
|
|
32
32
|
|
|
33
33
|
export function isNeuralVoice(voice) {
|
|
@@ -234,6 +234,8 @@ export function createTtsService(options = {}) {
|
|
|
234
234
|
engine: info.engine || 'cache',
|
|
235
235
|
voice: info.voice || '',
|
|
236
236
|
requestedVoice: info.requestedVoice || String(requestedVoice || ''),
|
|
237
|
+
fallback: false,
|
|
238
|
+
fallbackFrom: '',
|
|
237
239
|
attempts: [],
|
|
238
240
|
ms: 0,
|
|
239
241
|
cached: true,
|
|
@@ -358,13 +360,17 @@ export function createTtsService(options = {}) {
|
|
|
358
360
|
rate,
|
|
359
361
|
text: clean,
|
|
360
362
|
};
|
|
361
|
-
|
|
363
|
+
const fallback = Boolean(voice) && String(info.voice || '') !== voice;
|
|
364
|
+
// pre.54:回落得到的音频**不按请求音色缓存** —— 否则下一次会拿“别人的音色”当命中。
|
|
365
|
+
if (!fallback) writeCache(key, wav, info);
|
|
362
366
|
return {
|
|
363
367
|
ok: true,
|
|
364
368
|
wav,
|
|
365
369
|
engine: info.engine,
|
|
366
370
|
voice: info.voice,
|
|
367
371
|
requestedVoice: info.requestedVoice,
|
|
372
|
+
fallback,
|
|
373
|
+
fallbackFrom: fallback ? voice : '',
|
|
368
374
|
attempts: (msg && msg.attempts) || [],
|
|
369
375
|
ms: Number(msg.ms) || 0,
|
|
370
376
|
cached: false,
|
|
@@ -379,6 +385,24 @@ export function createTtsService(options = {}) {
|
|
|
379
385
|
return { ok: true, generation };
|
|
380
386
|
}
|
|
381
387
|
|
|
388
|
+
/**
|
|
389
|
+
* pre.54(B3②):本机可用音色清单(worker 枚举 + 试合成)。
|
|
390
|
+
* 结果缓存 10 分钟:UI 每次打开不重复跑 PowerShell。
|
|
391
|
+
*/
|
|
392
|
+
let voicesCache = { at: 0, items: null };
|
|
393
|
+
async function voices() {
|
|
394
|
+
if (voicesCache.items && Date.now() - voicesCache.at < 10 * 60 * 1000) return voicesCache.items;
|
|
395
|
+
let msg;
|
|
396
|
+
try {
|
|
397
|
+
msg = await request({ op: 'voices' }, Math.max(20000, requestTimeoutMs));
|
|
398
|
+
} catch {
|
|
399
|
+
return [];
|
|
400
|
+
}
|
|
401
|
+
const items = msg && msg.ok === true && Array.isArray(msg.voices) ? msg.voices : [];
|
|
402
|
+
voicesCache = { at: Date.now(), items };
|
|
403
|
+
return items;
|
|
404
|
+
}
|
|
405
|
+
|
|
382
406
|
/** 路由 `/tts/state` 用(不触发任何合成)。 */
|
|
383
407
|
function status() {
|
|
384
408
|
return {
|
|
@@ -405,5 +429,5 @@ export function createTtsService(options = {}) {
|
|
|
405
429
|
}
|
|
406
430
|
}
|
|
407
431
|
|
|
408
|
-
return { synthesize, stop, status, dispose, cacheDir, workerPath };
|
|
432
|
+
return { synthesize, stop, status, voices, dispose, cacheDir, workerPath };
|
|
409
433
|
}
|
package/lib/voice/record.js
CHANGED
|
@@ -164,19 +164,23 @@ export function createVoiceRecorder(deps) {
|
|
|
164
164
|
const startedAt = Date.now();
|
|
165
165
|
let result;
|
|
166
166
|
let usedPlain = false;
|
|
167
|
+
let watchStopped = false;
|
|
167
168
|
try {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
169
|
+
const ff = await resolveFfmpeg(null);
|
|
170
|
+
const watch = { stopOnSpeechEnd: { silenceMs: opts.silenceMs } };
|
|
171
|
+
result = await runFfmpeg(ff, [...dshowArgs(device, opts), audioPath], opts.maxMs + 8000, watch);
|
|
172
|
+
// 自动停机(SIGTERM)会让 ffmpeg 以非 0 退出,但录到的 WAV 是有效的。
|
|
173
|
+
// 这一格必须先认,否则会被当成“设备打不开”⇒ /record 恒回 no-device。
|
|
174
|
+
watchStopped = Boolean(result && result.stoppedByWatch);
|
|
175
|
+
// 兜底:某些环境(实测 dsh web / Electron 主进程)里 ffmpeg 不接受 -af silencedetect,
|
|
176
|
+
// 会立刻非零退出。这时退化成"固定时长采集":宁可少一点智能,也不能录不到。
|
|
177
|
+
if (result && result.code !== 0 && !watchStopped) {
|
|
178
|
+
const args = dshowArgs(device, opts);
|
|
179
|
+
const cut = args.indexOf('-af');
|
|
180
|
+
const plain = cut >= 0 ? args.slice(0, cut).concat(args.slice(cut + 2)) : args;
|
|
181
|
+
const retry = await runFfmpeg(ff, [...plain, audioPath], opts.maxMs + 8000);
|
|
182
|
+
if (retry && retry.code === 0) { result = retry; usedPlain = true; }
|
|
183
|
+
}
|
|
180
184
|
} catch {
|
|
181
185
|
rmSync(dir, { recursive: true, force: true });
|
|
182
186
|
lastCode = 'ffmpeg-missing';
|
|
@@ -184,7 +188,7 @@ export function createVoiceRecorder(deps) {
|
|
|
184
188
|
}
|
|
185
189
|
const ms = Date.now() - startedAt;
|
|
186
190
|
const stderr = String((result && result.stderr) || '');
|
|
187
|
-
if (result && result.code !== 0) {
|
|
191
|
+
if (result && result.code !== 0 && !watchStopped) {
|
|
188
192
|
// 这个设备打不开(占用/驱动)⇒ 换下一个
|
|
189
193
|
rmSync(dir, { recursive: true, force: true });
|
|
190
194
|
lastCode = 'no-device';
|
|
@@ -194,7 +198,7 @@ export function createVoiceRecorder(deps) {
|
|
|
194
198
|
// 自动停机(VAD)可能发生在“一开口就说话”的场景:日志里没有前置 silence_end,
|
|
195
199
|
// 用执行器回报的 stoppedByWatch / speechEnd 兜住,不能把已经录好的话判成 no-speech。
|
|
196
200
|
if (!ended && result && result.stoppedByWatch) {
|
|
197
|
-
ended = { speechEnd: Number(result.speechEnd) ||
|
|
201
|
+
ended = { speechEnd: Number(result.speechEnd) || Number((ms / 1000).toFixed(2)), auto: true };
|
|
198
202
|
}
|
|
199
203
|
// 固定时长兜底采集里没有 silencedetect 标记 ⇒ 直接按 maxMs 当语音段,别误判成 no-speech
|
|
200
204
|
if (!ended && usedPlain) ended = { speechEnd: opts.maxMs / 1000 };
|
|
@@ -254,8 +258,9 @@ export function defaultRunFfmpeg(ff, args, timeoutMs = 30000, options = {}) {
|
|
|
254
258
|
const child = spawn(ff, args, {
|
|
255
259
|
windowsHide: true,
|
|
256
260
|
detached: true,
|
|
257
|
-
// stdin
|
|
258
|
-
|
|
261
|
+
// stdin/stdout/stderr 一律**不走管道**:DSH 沙箱下 spawn 开 pipe 会 EPERM
|
|
262
|
+
//(实测 /record 恒 no-device)。stderr 走临时文件,自动停机用 SIGTERM。
|
|
263
|
+
stdio: ['ignore', 'ignore', fd === null ? 'ignore' : fd],
|
|
259
264
|
});
|
|
260
265
|
let settled = false;
|
|
261
266
|
let stoppedByWatch = false;
|
|
@@ -265,7 +270,10 @@ export function defaultRunFfmpeg(ff, args, timeoutMs = 30000, options = {}) {
|
|
|
265
270
|
const requestStop = () => {
|
|
266
271
|
if (stopSent) return;
|
|
267
272
|
stopSent = true;
|
|
268
|
-
|
|
273
|
+
// 用 SIGTERM 结束(不依赖 stdin 管道);ffmpeg 被信号结束时通常 code!=0,
|
|
274
|
+
// 由 `stoppedByWatch=true` 在 record() 里认成成功。
|
|
275
|
+
// pid 落地才 kill:未起来时裸 kill 会让事件循环挂死(verify-child-kill 的同一条判据)。
|
|
276
|
+
try { if (child.pid !== undefined) child.kill('SIGTERM'); } catch { /* 已退出 */ }
|
|
269
277
|
};
|
|
270
278
|
if (watch) {
|
|
271
279
|
poll = setInterval(() => {
|
|
@@ -281,7 +289,7 @@ export function defaultRunFfmpeg(ff, args, timeoutMs = 30000, options = {}) {
|
|
|
281
289
|
}, 120);
|
|
282
290
|
if (typeof poll.unref === 'function') poll.unref();
|
|
283
291
|
}
|
|
284
|
-
|
|
292
|
+
// stdio[0] 是 ignore ⇒ 没有 stdin;写 `q` 的旧路径已改成 SIGTERM(见 requestStop)。
|
|
285
293
|
const finish = (code) => {
|
|
286
294
|
if (settled) return;
|
|
287
295
|
settled = true;
|