dsh-folia 4.26.0-pre.44 → 4.26.0-pre.45
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 +508 -18
- package/lib/routes/pet-chat.js +280 -92
- package/lib/tts/tts-worker.cjs +443 -99
- package/lib/tts/tts.js +355 -0
- package/lib/voice/record.js +91 -14
- package/package.json +2 -2
package/lib/client.js
CHANGED
|
@@ -20924,6 +20924,12 @@ window.__ModuleLoader__.load({
|
|
|
20924
20924
|
const onText = typeof options.onText === 'function' ? options.onText : () => {};
|
|
20925
20925
|
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
20926
20926
|
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
20927
|
+
/**
|
|
20928
|
+
* barge-in(P1):**录音一开始**先停掉正在播的朗读。
|
|
20929
|
+
* 做成注入点而不是在这里直接引用 petSpeakStop:模块在构建期被内联进同一作用域,
|
|
20930
|
+
* 直接引用会把“朗读”与“录音”焊死;注入后判据也能用假函数断言调用顺序。
|
|
20931
|
+
*/
|
|
20932
|
+
const onBeforeRecord = typeof options.onBeforeRecord === 'function' ? options.onBeforeRecord : () => {};
|
|
20927
20933
|
|
|
20928
20934
|
let active = false;
|
|
20929
20935
|
|
|
@@ -20936,6 +20942,8 @@ window.__ModuleLoader__.load({
|
|
|
20936
20942
|
async function start() {
|
|
20937
20943
|
if (active) return true;
|
|
20938
20944
|
active = true;
|
|
20945
|
+
// ⚠️ 顺序是判据:先打断朗读,再开麦(用户一说话就把桌宠的声音掐掉)
|
|
20946
|
+
try { onBeforeRecord(); } catch { /* 打断失败不能挡住录音 */ }
|
|
20939
20947
|
onState({ state: 'listening' });
|
|
20940
20948
|
let result;
|
|
20941
20949
|
try {
|
|
@@ -21021,6 +21029,40 @@ window.__ModuleLoader__.load({
|
|
|
21021
21029
|
let text = '';
|
|
21022
21030
|
let visible = false;
|
|
21023
21031
|
let fadeTimer = null;
|
|
21032
|
+
let stylesInjected = false;
|
|
21033
|
+
|
|
21034
|
+
/**
|
|
21035
|
+
* 三态与“说”的波形(P1):
|
|
21036
|
+
* listen / think / speak / idle —— 只改 `data-state`,由一小段**无颜色**的 CSS 表现:
|
|
21037
|
+
* · listen:正文前的实心点;think:省略号;speak:正文下一排四根跳动竖条。
|
|
21038
|
+
* 用伪元素而不是新增 DOM 子节点,是因为气泡正文一直用 `textContent` 整体写入
|
|
21039
|
+
* (设 textContent 会把子节点一起清掉);伪元素不会被它清掉,也不会引入第二种“文字容器”。
|
|
21040
|
+
*/
|
|
21041
|
+
const WAVE_CSS = [
|
|
21042
|
+
'.we-pet-bubble[data-state="listen"]::before{content:"●";margin-right:4px;opacity:.55;}',
|
|
21043
|
+
'.we-pet-bubble[data-state="think"]::before{content:"…";margin-right:4px;opacity:.6;}',
|
|
21044
|
+
'.we-pet-bubble[data-state="speak"]::after{content:"";display:block;width:34px;height:10px;margin-top:6px;opacity:.85;',
|
|
21045
|
+
'background:',
|
|
21046
|
+
'linear-gradient(currentColor,currentColor) 0 100%/3px 45% no-repeat,',
|
|
21047
|
+
'linear-gradient(currentColor,currentColor) 8px 100%/3px 90% no-repeat,',
|
|
21048
|
+
'linear-gradient(currentColor,currentColor) 16px 100%/3px 60% no-repeat,',
|
|
21049
|
+
'linear-gradient(currentColor,currentColor) 24px 100%/3px 100% no-repeat;',
|
|
21050
|
+
'transform-origin:0 100%;animation:we-pet-bubble-wave .8s ease-in-out infinite alternate;}',
|
|
21051
|
+
'@keyframes we-pet-bubble-wave{from{transform:scaleY(.55);opacity:.55;}to{transform:scaleY(1);opacity:.95;}}',
|
|
21052
|
+
].join('');
|
|
21053
|
+
|
|
21054
|
+
/** 只注入一次;没有 head 的环境(判据的极简 DOM)静默跳过。 */
|
|
21055
|
+
function ensureStyles() {
|
|
21056
|
+
if (stylesInjected) return;
|
|
21057
|
+
stylesInjected = true;
|
|
21058
|
+
try {
|
|
21059
|
+
if (!doc || !doc.head || typeof doc.createElement !== 'function') return;
|
|
21060
|
+
const style = doc.createElement('style');
|
|
21061
|
+
style.setAttribute('data-folia-pet-bubble', '1');
|
|
21062
|
+
style.textContent = WAVE_CSS;
|
|
21063
|
+
if (typeof doc.head.appendChild === 'function') doc.head.appendChild(style);
|
|
21064
|
+
} catch { /* 气泡是装饰层,样式失败不能影响显示 */ }
|
|
21065
|
+
}
|
|
21024
21066
|
|
|
21025
21067
|
/** 锚点 → 气泡位置:水平居中于桌宠,垂直贴在头顶上方。 */
|
|
21026
21068
|
function place() {
|
|
@@ -21115,9 +21157,10 @@ window.__ModuleLoader__.load({
|
|
|
21115
21157
|
doHide();
|
|
21116
21158
|
}
|
|
21117
21159
|
|
|
21118
|
-
/** 状态:听 / 想 /
|
|
21160
|
+
/** 状态:听 / 想 / 说(客户端据此换桌宠动作、气泡配色与波形)。 */
|
|
21119
21161
|
function setState(kind) {
|
|
21120
|
-
if (!
|
|
21162
|
+
if (!ensure()) return;
|
|
21163
|
+
ensureStyles();
|
|
21121
21164
|
el.dataset = el.dataset || {};
|
|
21122
21165
|
el.dataset.state = String(kind || '');
|
|
21123
21166
|
}
|
|
@@ -21143,14 +21186,323 @@ window.__ModuleLoader__.load({
|
|
|
21143
21186
|
};
|
|
21144
21187
|
}
|
|
21145
21188
|
|
|
21146
|
-
// ── 内联模块:src/pet-
|
|
21189
|
+
// ── 内联模块:src/pet-tts.js —— 桌宠朗读客户端:petTtsSplit 切句 / 排队播放 / 预取下一句 / stop 清队列 / 句字幕回调(构建期注入;勿手改本段)──
|
|
21147
21190
|
/**
|
|
21148
|
-
* pet-
|
|
21191
|
+
* pet-tts.js(客户端)— 桌宠朗读:**按句合成 / 排队播放 / 字幕 / barge-in**。
|
|
21192
|
+
*
|
|
21193
|
+
* 为什么不把整段文字一次合成:
|
|
21194
|
+
* · 第一句能先出声(模型刚说完第一句就开始念,不等整段);
|
|
21195
|
+
* · 一句失败只影响一句,不会“整段静音”;
|
|
21196
|
+
* · stop 时清队列即可立刻闭嘴,不需要等一个长请求。
|
|
21197
|
+
*
|
|
21198
|
+
* 依赖全部注入(apiFetch / Audio / URL / 回调),所以 Node 里能用假播放器跑判据;
|
|
21199
|
+
* 浏览器侧由 `src/pet-chat.js` 用真实 `Audio` 与 `URL.createObjectURL` 构造。
|
|
21149
21200
|
*
|
|
21150
|
-
*
|
|
21151
|
-
*
|
|
21201
|
+
* 与宿主的分工:
|
|
21202
|
+
* · 宿主负责“SAPI → Edge 系统音色 → 明确错误”的兜底链,返回 `audio/wav`;
|
|
21203
|
+
* · 客户端只负责切句、排队、播、停、把当前句交给气泡显示。
|
|
21204
|
+
*/
|
|
21205
|
+
|
|
21206
|
+
/** 单句上限:超过就在标点/字数处切开(与宿主路由的 240 字上限配合)。 */
|
|
21207
|
+
const PET_TTS_MAX_SENTENCE = 48;
|
|
21208
|
+
/** 一次最多几句:再长也只念前 8 句(防止任务提醒念一整篇)。 */
|
|
21209
|
+
const PET_TTS_MAX_PIECES = 8;
|
|
21210
|
+
/** 与宿主 `TTS_MAX_CHARS` 对齐的总上限。 */
|
|
21211
|
+
const PET_TTS_MAX_CHARS = 240;
|
|
21212
|
+
|
|
21213
|
+
/**
|
|
21214
|
+
* 纯函数:把一段文字切成“适合一句一合成”的片段。
|
|
21215
|
+
* 优先在句末标点切;长句在逗号处或硬上限处切。
|
|
21216
|
+
*/
|
|
21217
|
+
function petTtsSplit(text) {
|
|
21218
|
+
const raw = String(text == null ? '' : text).replace(/\s+/g, ' ').trim().slice(0, PET_TTS_MAX_CHARS);
|
|
21219
|
+
if (!raw) return [];
|
|
21220
|
+
const pieces = [];
|
|
21221
|
+
let buffer = '';
|
|
21222
|
+
const flush = () => {
|
|
21223
|
+
const piece = buffer.trim();
|
|
21224
|
+
buffer = '';
|
|
21225
|
+
if (piece) pieces.push(piece);
|
|
21226
|
+
};
|
|
21227
|
+
for (const ch of raw) {
|
|
21228
|
+
buffer += ch;
|
|
21229
|
+
const ends = /[。!?!?;;\n]/.test(ch);
|
|
21230
|
+
const commaCut = /[,,、]/.test(ch) && buffer.length >= PET_TTS_MAX_SENTENCE * 0.7;
|
|
21231
|
+
const hardCut = buffer.length >= PET_TTS_MAX_SENTENCE;
|
|
21232
|
+
if (ends || commaCut || hardCut) flush();
|
|
21233
|
+
if (pieces.length >= PET_TTS_MAX_PIECES) break;
|
|
21234
|
+
}
|
|
21235
|
+
flush();
|
|
21236
|
+
return pieces.slice(0, PET_TTS_MAX_PIECES);
|
|
21237
|
+
}
|
|
21238
|
+
|
|
21239
|
+
/**
|
|
21240
|
+
* 纯函数:流式场景下“已经说完的句子”与“还没说完的尾巴”。
|
|
21241
|
+
* SSE 每来一小段就调用一次,把完整句立刻入队(第一句更早出声)。
|
|
21242
|
+
*/
|
|
21243
|
+
function petTtsSentences(text) {
|
|
21244
|
+
const raw = String(text == null ? '' : text);
|
|
21245
|
+
const sentences = [];
|
|
21246
|
+
let start = 0;
|
|
21247
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
21248
|
+
if (/[。!?!?;;\n]/.test(raw[i])) {
|
|
21249
|
+
const piece = raw.slice(start, i + 1).trim();
|
|
21250
|
+
if (piece) sentences.push(piece);
|
|
21251
|
+
start = i + 1;
|
|
21252
|
+
}
|
|
21253
|
+
}
|
|
21254
|
+
let rest = raw.slice(start);
|
|
21255
|
+
// 没有标点的长句也要在安全长度切开,避免一直等到整段结束
|
|
21256
|
+
if (rest.length >= PET_TTS_MAX_SENTENCE) {
|
|
21257
|
+
const cut = rest.lastIndexOf(',', PET_TTS_MAX_SENTENCE);
|
|
21258
|
+
const at = cut > 8 ? cut + 1 : PET_TTS_MAX_SENTENCE;
|
|
21259
|
+
sentences.push(rest.slice(0, at).trim());
|
|
21260
|
+
rest = rest.slice(at);
|
|
21261
|
+
}
|
|
21262
|
+
return { sentences, rest };
|
|
21263
|
+
}
|
|
21264
|
+
|
|
21265
|
+
/**
|
|
21266
|
+
* @param {{
|
|
21267
|
+
* apiFetch: Function,
|
|
21268
|
+
* apiPostJson?: Function,
|
|
21269
|
+
* Audio?: Function,
|
|
21270
|
+
* URL?: object,
|
|
21271
|
+
* getVoice?: () => {name?: string, muted?: boolean, rate?: number},
|
|
21272
|
+
* onSentence?: (text: string) => void,
|
|
21273
|
+
* onState?: (state: 'speak'|'idle') => void,
|
|
21274
|
+
* onError?: (error: {code: string, hint?: string, status?: number}) => void,
|
|
21275
|
+
* onIdle?: () => void,
|
|
21276
|
+
* log?: (line: string) => void,
|
|
21277
|
+
* }} deps
|
|
21278
|
+
*/
|
|
21279
|
+
function petTtsCreate(deps) {
|
|
21280
|
+
const options = deps || {};
|
|
21281
|
+
const apiFetch = options.apiFetch;
|
|
21282
|
+
const apiPostJson = options.apiPostJson;
|
|
21283
|
+
const AudioCtor = typeof options.Audio === 'function' ? options.Audio : null;
|
|
21284
|
+
const UrlApi = options.URL || null;
|
|
21285
|
+
const getVoice = typeof options.getVoice === 'function' ? options.getVoice : () => ({});
|
|
21286
|
+
const onSentence = typeof options.onSentence === 'function' ? options.onSentence : () => {};
|
|
21287
|
+
const onState = typeof options.onState === 'function' ? options.onState : () => {};
|
|
21288
|
+
const onError = typeof options.onError === 'function' ? options.onError : () => {};
|
|
21289
|
+
const onIdle = typeof options.onIdle === 'function' ? options.onIdle : () => {};
|
|
21290
|
+
const log = typeof options.log === 'function' ? options.log : () => {};
|
|
21291
|
+
|
|
21292
|
+
let generation = 0;
|
|
21293
|
+
let queue = [];
|
|
21294
|
+
let busy = false;
|
|
21295
|
+
let playing = null;
|
|
21296
|
+
let prefetch = null;
|
|
21297
|
+
let disposed = false;
|
|
21298
|
+
|
|
21299
|
+
function revoke(url) {
|
|
21300
|
+
if (!url || !UrlApi || typeof UrlApi.revokeObjectURL !== 'function') return;
|
|
21301
|
+
try { UrlApi.revokeObjectURL(url); } catch { /* ignore */ }
|
|
21302
|
+
}
|
|
21303
|
+
|
|
21304
|
+
/** 取一句的 WAV:成功 `{url,size}`,失败 `{error}`,被 stop `{stopped:true}`。 */
|
|
21305
|
+
async function fetchSpeech(item, gen) {
|
|
21306
|
+
if (typeof apiFetch !== 'function') {
|
|
21307
|
+
return { error: { code: 'tts-unavailable', hint: '这个版本没有接朗读接口' } };
|
|
21308
|
+
}
|
|
21309
|
+
const query = '/pet-chat/tts?text=' + encodeURIComponent(item.text)
|
|
21310
|
+
+ '&voice=' + encodeURIComponent(item.voice || '')
|
|
21311
|
+
+ '&rate=' + encodeURIComponent(String(item.rate));
|
|
21312
|
+
let res;
|
|
21313
|
+
let blob;
|
|
21314
|
+
try {
|
|
21315
|
+
// parse:false:**二进制体**不能交给默认的 json() 解析(流会被吃掉);
|
|
21316
|
+
// 这里的 blob() 必须和它在同一个调用窗里(verify-api-client ①b 的判据)。
|
|
21317
|
+
res = await apiFetch(query, { parse: false, cache: 'no-store' });
|
|
21318
|
+
if (gen !== generation) return { stopped: true };
|
|
21319
|
+
if (!res || !res.ok || !res.response) {
|
|
21320
|
+
let hint = '';
|
|
21321
|
+
try {
|
|
21322
|
+
if (res && res.response && typeof res.response.json === 'function') {
|
|
21323
|
+
const doc = await res.response.json();
|
|
21324
|
+
hint = String((doc && doc.hint) || '');
|
|
21325
|
+
}
|
|
21326
|
+
} catch { /* 非 JSON 错误体 */ }
|
|
21327
|
+
return { error: { code: 'tts-failed', status: (res && res.status) || 0, hint: hint || '语音合成失败' } };
|
|
21328
|
+
}
|
|
21329
|
+
blob = await res.response.blob();
|
|
21330
|
+
} catch (error) {
|
|
21331
|
+
if (!res) return { error: { code: 'tts-network', hint: '连不上宿主,语音没出来' } };
|
|
21332
|
+
return { error: { code: 'tts-read-failed', hint: '读不到语音数据' } };
|
|
21333
|
+
}
|
|
21334
|
+
if (!blob || !blob.size) return { error: { code: 'tts-empty', hint: '没合成出声音' } };
|
|
21335
|
+
let url = '';
|
|
21336
|
+
if (UrlApi && typeof UrlApi.createObjectURL === 'function') {
|
|
21337
|
+
try { url = UrlApi.createObjectURL(blob); } catch { url = ''; }
|
|
21338
|
+
}
|
|
21339
|
+
if (!url) return { error: { code: 'tts-audio-unavailable', hint: '这个环境不能播放音频' } };
|
|
21340
|
+
return { url, size: blob.size };
|
|
21341
|
+
}
|
|
21342
|
+
|
|
21343
|
+
/** 播一句;stop 时由 `entry.finish` 立即结束 Promise。 */
|
|
21344
|
+
function playSpeech(item, prepared, gen) {
|
|
21345
|
+
return new Promise((resolve) => {
|
|
21346
|
+
let audio;
|
|
21347
|
+
try {
|
|
21348
|
+
audio = new AudioCtor(prepared.url);
|
|
21349
|
+
} catch (error) {
|
|
21350
|
+
resolve({ code: 'tts-audio', hint: '播放器创建失败' });
|
|
21351
|
+
return;
|
|
21352
|
+
}
|
|
21353
|
+
const entry = { audio, url: prepared.url, finish: null };
|
|
21354
|
+
let settled = false;
|
|
21355
|
+
const finish = (error) => {
|
|
21356
|
+
if (settled) return;
|
|
21357
|
+
settled = true;
|
|
21358
|
+
if (playing === entry) playing = null;
|
|
21359
|
+
revoke(prepared.url);
|
|
21360
|
+
resolve(error || null);
|
|
21361
|
+
};
|
|
21362
|
+
entry.finish = finish;
|
|
21363
|
+
playing = entry;
|
|
21364
|
+
onState('speak');
|
|
21365
|
+
onSentence(item.text);
|
|
21366
|
+
audio.onended = () => finish(null);
|
|
21367
|
+
audio.onerror = () => finish({ code: 'tts-play-failed', hint: '这条语音播放失败' });
|
|
21368
|
+
try {
|
|
21369
|
+
const ret = audio.play();
|
|
21370
|
+
if (ret && typeof ret.then === 'function') {
|
|
21371
|
+
ret.catch(() => finish({ code: 'tts-blocked', hint: '系统拦了自动播放,点一下桌宠再试' }));
|
|
21372
|
+
}
|
|
21373
|
+
} catch (error) {
|
|
21374
|
+
finish({ code: 'tts-blocked', hint: '系统拦了自动播放,点一下桌宠再试' });
|
|
21375
|
+
}
|
|
21376
|
+
if (gen !== generation) finish(null);
|
|
21377
|
+
});
|
|
21378
|
+
}
|
|
21379
|
+
|
|
21380
|
+
function startPrefetch(gen) {
|
|
21381
|
+
if (prefetch || !queue.length) return;
|
|
21382
|
+
const item = queue[0];
|
|
21383
|
+
if (item.gen !== gen) return;
|
|
21384
|
+
prefetch = { item, gen, promise: fetchSpeech(item, gen) };
|
|
21385
|
+
}
|
|
21386
|
+
|
|
21387
|
+
async function pump(gen) {
|
|
21388
|
+
if (busy || disposed) return;
|
|
21389
|
+
busy = true;
|
|
21390
|
+
try {
|
|
21391
|
+
while (queue.length) {
|
|
21392
|
+
const item = queue[0];
|
|
21393
|
+
// stop 之后的新一批有自己的 pump;旧 pump 不许动它
|
|
21394
|
+
if (item.gen !== gen) break;
|
|
21395
|
+
let prepared;
|
|
21396
|
+
if (prefetch && prefetch.item === item && prefetch.gen === gen) {
|
|
21397
|
+
prepared = await prefetch.promise;
|
|
21398
|
+
prefetch = null;
|
|
21399
|
+
} else {
|
|
21400
|
+
prepared = await fetchSpeech(item, gen);
|
|
21401
|
+
}
|
|
21402
|
+
if (item.gen !== generation) { queue.shift(); if (prepared && prepared.url) revoke(prepared.url); break; }
|
|
21403
|
+
if (!prepared || prepared.error) {
|
|
21404
|
+
queue.length = 0;
|
|
21405
|
+
onState('idle');
|
|
21406
|
+
onError((prepared && prepared.error) || { code: 'tts-failed', hint: '语音合成失败' });
|
|
21407
|
+
break;
|
|
21408
|
+
}
|
|
21409
|
+
queue.shift();
|
|
21410
|
+
startPrefetch(gen);
|
|
21411
|
+
const error = await playSpeech(item, prepared, gen);
|
|
21412
|
+
if (item.gen !== generation) break;
|
|
21413
|
+
if (error) {
|
|
21414
|
+
queue.length = 0;
|
|
21415
|
+
onState('idle');
|
|
21416
|
+
onError(error);
|
|
21417
|
+
break;
|
|
21418
|
+
}
|
|
21419
|
+
}
|
|
21420
|
+
} finally {
|
|
21421
|
+
busy = false;
|
|
21422
|
+
if (disposed) {
|
|
21423
|
+
// 已销毁:不再启动下一批,也不再回调界面
|
|
21424
|
+
} else if (queue.length && queue[0].gen === generation) {
|
|
21425
|
+
// stop 之后又来了新的一批:旧 pump 收尾时把接力棒交出去
|
|
21426
|
+
void pump(queue[0].gen);
|
|
21427
|
+
} else if (gen === generation && !queue.length && !playing) {
|
|
21428
|
+
onState('idle');
|
|
21429
|
+
onIdle();
|
|
21430
|
+
}
|
|
21431
|
+
}
|
|
21432
|
+
}
|
|
21433
|
+
|
|
21434
|
+
/** 停止:清队列 + 停当前音频 + 通知宿主作废在途合成(幂等)。 */
|
|
21435
|
+
function stop() {
|
|
21436
|
+
generation += 1;
|
|
21437
|
+
queue = [];
|
|
21438
|
+
prefetch = null;
|
|
21439
|
+
if (playing) {
|
|
21440
|
+
const entry = playing;
|
|
21441
|
+
playing = null;
|
|
21442
|
+
try { entry.audio.pause(); } catch { /* ignore */ }
|
|
21443
|
+
if (typeof entry.finish === 'function') entry.finish(null);
|
|
21444
|
+
revoke(entry.url);
|
|
21445
|
+
}
|
|
21446
|
+
onState('idle');
|
|
21447
|
+
if (typeof apiPostJson === 'function') {
|
|
21448
|
+
try {
|
|
21449
|
+
const ret = apiPostJson('/pet-chat/tts/stop', {});
|
|
21450
|
+
if (ret && typeof ret.catch === 'function') ret.catch(() => {});
|
|
21451
|
+
} catch { /* 停不下来也不能抛给界面 */ }
|
|
21452
|
+
}
|
|
21453
|
+
return true;
|
|
21454
|
+
}
|
|
21455
|
+
|
|
21456
|
+
/**
|
|
21457
|
+
* 说一段话(会按句切开排队)。
|
|
21458
|
+
* @returns {boolean} 是否入队(静音 / 空文本 / 环境不支持时 false)
|
|
21459
|
+
*/
|
|
21460
|
+
function speak(text, speech) {
|
|
21461
|
+
if (disposed) return false;
|
|
21462
|
+
const cfg = getVoice() || {};
|
|
21463
|
+
if (cfg.muted === true) { onState('idle'); return false; }
|
|
21464
|
+
const pieces = petTtsSplit(text);
|
|
21465
|
+
if (!pieces.length) return false;
|
|
21466
|
+
if (!AudioCtor) {
|
|
21467
|
+
onError({ code: 'tts-no-audio', hint: '这个环境不能播放声音' });
|
|
21468
|
+
return false;
|
|
21469
|
+
}
|
|
21470
|
+
const speechOpts = speech || {};
|
|
21471
|
+
const voice = String(speechOpts.voice || cfg.name || '');
|
|
21472
|
+
const rawRate = speechOpts.rate !== undefined ? speechOpts.rate : cfg.rate;
|
|
21473
|
+
const rate = Number.isFinite(Number(rawRate)) ? Number(rawRate) : 0;
|
|
21474
|
+
const gen = generation;
|
|
21475
|
+
for (const piece of pieces) queue.push({ text: piece, voice, rate, gen });
|
|
21476
|
+
log('[pet-tts] queue ' + pieces.length + ' sentence(s) voice=' + (voice || '(auto)'));
|
|
21477
|
+
void pump(gen);
|
|
21478
|
+
return true;
|
|
21479
|
+
}
|
|
21480
|
+
|
|
21481
|
+
function isSpeaking() {
|
|
21482
|
+
return Boolean(playing) || queue.length > 0 || busy;
|
|
21483
|
+
}
|
|
21484
|
+
|
|
21485
|
+
function state() {
|
|
21486
|
+
return { busy, playing: Boolean(playing), queued: queue.length, generation };
|
|
21487
|
+
}
|
|
21488
|
+
|
|
21489
|
+
function dispose() {
|
|
21490
|
+
if (disposed) return;
|
|
21491
|
+
stop();
|
|
21492
|
+
disposed = true;
|
|
21493
|
+
}
|
|
21494
|
+
|
|
21495
|
+
return { speak, stop, isSpeaking, state, dispose };
|
|
21496
|
+
}
|
|
21497
|
+
|
|
21498
|
+
/* 供判据从产物/源码里取纯函数;浏览器侧由 pet-chat.js 构造实例。 */
|
|
21499
|
+
|
|
21500
|
+
// ── 内联模块:src/pet-chat.js —— 桌宠语音助手客户端:点桌宠唤醒 → 气泡显示 + edge 朗读(失败回落系统音色),无面板无输入框(构建期注入;勿手改本段)──
|
|
21501
|
+
/**
|
|
21502
|
+
* pet-chat.js — 桌宠语音助手(P1:语音输入 + 朗读 + 头顶气泡 + 主动搭话)。
|
|
21152
21503
|
*
|
|
21153
|
-
* 交互:点桌宠 = 唤醒 →
|
|
21504
|
+
* 交互:点桌宠 = 唤醒 → 录音(说完自动停)→ 转写 → SSE 回答 → 按句朗读
|
|
21505
|
+
* (气泡逐句字幕 + “说”态波形);说话/点击/打字都先打断当前朗读。
|
|
21154
21506
|
* 没有聊天窗口:无输入框、无历史列表、无开关按钮。
|
|
21155
21507
|
*/
|
|
21156
21508
|
const PET_CHAT_PRESET_LINES = {
|
|
@@ -21232,8 +21584,7 @@ window.__ModuleLoader__.load({
|
|
|
21232
21584
|
* 然后轮询 /pet-chat/asr 把下载进度显示在气泡里。
|
|
21233
21585
|
* 这样用户装完插件直接说话就行,不需要去 DSH 设置里找「语音输入」开关。
|
|
21234
21586
|
*/
|
|
21235
|
-
async function ensureAsrReady() {
|
|
21236
|
-
petBubble.setState('think');
|
|
21587
|
+
async function ensureAsrReady() { petBubble.setState('think');
|
|
21237
21588
|
try {
|
|
21238
21589
|
await apiPostJson('/pet-chat/asr', {}, { parse: 'always' });
|
|
21239
21590
|
} catch { /* 触发失败也要继续轮询看状态 */ }
|
|
@@ -21265,14 +21616,72 @@ window.__ModuleLoader__.load({
|
|
|
21265
21616
|
petBubble.hide(3000);
|
|
21266
21617
|
}
|
|
21267
21618
|
|
|
21619
|
+
/**
|
|
21620
|
+
* 朗读配置(P1):`/pet-chat/state` 的 voice 字段。
|
|
21621
|
+
*
|
|
21622
|
+
* 懒加载:挂载时与每次唤醒时各刷一次(设置面板改完立刻生效,不用重启)。
|
|
21623
|
+
* 读不到就保持“不静音”,宁可多念一句,也不要让用户以为朗读坏了。
|
|
21624
|
+
*/
|
|
21625
|
+
let petChatVoice = { name: '', muted: false, rate: 0 };
|
|
21626
|
+
async function petChatRefreshVoice() {
|
|
21627
|
+
try {
|
|
21628
|
+
const resp = await apiJson('/pet-chat/state', { parse: 'always' });
|
|
21629
|
+
const doc = (resp && resp.data) || {};
|
|
21630
|
+
if (doc.voice && typeof doc.voice === 'object') {
|
|
21631
|
+
petChatVoice = {
|
|
21632
|
+
name: String(doc.voice.name || ''),
|
|
21633
|
+
muted: doc.voice.muted === true,
|
|
21634
|
+
rate: Number.isFinite(Number(doc.voice.rate)) ? Number(doc.voice.rate) : 0,
|
|
21635
|
+
};
|
|
21636
|
+
}
|
|
21637
|
+
} catch { /* 读不到就用默认(不静音) */ }
|
|
21638
|
+
return petChatVoice;
|
|
21639
|
+
}
|
|
21640
|
+
|
|
21641
|
+
/**
|
|
21642
|
+
* 朗读实例(P1):宿主负责合成兜底,这里负责切句、排队、播、停、字幕同步。
|
|
21643
|
+
* 回调全部接到气泡:说 → `speak` 态 + 当前句;停/念完 → `idle` + 3 秒后淡出。
|
|
21644
|
+
*/
|
|
21645
|
+
const petTts = petTtsCreate({
|
|
21646
|
+
// ⚠️ 包一层再传:`api-client.js` 的内联位置在 `pet-chat.js` **之后**,
|
|
21647
|
+
// 直接 `apiFetch` / `apiPostJson` 会在模块求值期触发 TDZ
|
|
21648
|
+
// (真机/冒烟统一症状:Cannot access 'apiPostJson' before initialization)。
|
|
21649
|
+
apiFetch: (path, opts) => apiFetch(path, opts),
|
|
21650
|
+
apiPostJson: (path, payload, opts) => apiPostJson(path, payload, opts),
|
|
21651
|
+
Audio: typeof Audio === 'function' ? Audio : null,
|
|
21652
|
+
URL: typeof URL === 'function' ? URL : null,
|
|
21653
|
+
getVoice: () => petChatVoice,
|
|
21654
|
+
onSentence: (text) => {
|
|
21655
|
+
petBubble.setState('speak');
|
|
21656
|
+
petBubble.show(text);
|
|
21657
|
+
},
|
|
21658
|
+
onState: (kind) => { petBubble.setState(kind); },
|
|
21659
|
+
onIdle: () => { petBubble.hide(3000); },
|
|
21660
|
+
onError: (error) => {
|
|
21661
|
+
// 失败只进气泡提示行(不弹窗);不静默 —— 用户至少知道为什么没声音
|
|
21662
|
+
const hint = (error && error.hint) || '语音没出来';
|
|
21663
|
+
petBubble.setState('idle');
|
|
21664
|
+
petBubble.show(hint);
|
|
21665
|
+
petBubble.hide(4000);
|
|
21666
|
+
},
|
|
21667
|
+
});
|
|
21668
|
+
|
|
21669
|
+
/** 对外/对内的“说一句”:按句入队,返回是否真的入队。 */
|
|
21670
|
+
function petSpeak(text, speech) { return petTts.speak(text, speech); }
|
|
21671
|
+
/** 立刻停:清队列 + 停当前音频 + 通知宿主作废在途合成(barge-in 用)。 */
|
|
21672
|
+
function petSpeakStop() { return petTts.stop(); }
|
|
21673
|
+
|
|
21268
21674
|
/** 语音输入(v0.1):前端不碰麦克风 —— 宿主用 ffmpeg 录,这里只发请求、收文本。 */
|
|
21269
21675
|
const petVoiceIn = petVoiceInputCreate({
|
|
21676
|
+
// barge-in:**一开录就先停朗读**(判据 verify-voice-tts 断言这个顺序)
|
|
21677
|
+
onBeforeRecord: () => { petSpeakStop(); },
|
|
21270
21678
|
postRecord: async () => {
|
|
21271
21679
|
const res = await apiPostJson('/pet-chat/record', { language: 'zh' }, { parse: 'always' });
|
|
21272
21680
|
return (res && res.data) || {};
|
|
21273
21681
|
},
|
|
21274
21682
|
postChat: async (text, onState) => {
|
|
21275
|
-
|
|
21683
|
+
// “想”态:模型还在回,先不给“说”的波形
|
|
21684
|
+
petBubble.setState('think');
|
|
21276
21685
|
// ⚠️ apiFetch 的返回值里**已经带上了原始 Response**(字段 `response`)。
|
|
21277
21686
|
// 上一版误写成 `res.body.getReader()`:res 是 { ok, status, data, response },
|
|
21278
21687
|
// res.body 恒为 undefined ⇒ 抛 TypeError ⇒ 读流代码一行都跑不到
|
|
@@ -21305,6 +21714,18 @@ window.__ModuleLoader__.load({
|
|
|
21305
21714
|
let rawReply = '';
|
|
21306
21715
|
let replyStarted = false;
|
|
21307
21716
|
let replyDone = false;
|
|
21717
|
+
/**
|
|
21718
|
+
* 朗读的流式切句(P1):
|
|
21719
|
+
* SSE 每来一小段就交给 `petTtsSentences`;**句末标点一到就入队**,
|
|
21720
|
+
* 不等 done —— 这是“录音停止后尽快开始播报”的关键(合成与模型生成重叠)。
|
|
21721
|
+
*/
|
|
21722
|
+
let speakBuffer = '';
|
|
21723
|
+
let queuedSpeech = 0;
|
|
21724
|
+
const enqueueSpeech = (piece) => {
|
|
21725
|
+
const line = String(piece || '').trim();
|
|
21726
|
+
if (!line) return;
|
|
21727
|
+
if (petSpeak(line)) queuedSpeech += 1;
|
|
21728
|
+
};
|
|
21308
21729
|
const reader = stream.body.getReader();
|
|
21309
21730
|
const decoder = new TextDecoder();
|
|
21310
21731
|
let buffer = '';
|
|
@@ -21319,7 +21740,7 @@ window.__ModuleLoader__.load({
|
|
|
21319
21740
|
buffer = buffer.slice(cut + 2);
|
|
21320
21741
|
const line = frame.split('\n').find((item) => item.startsWith('data:'));
|
|
21321
21742
|
if (!line) continue;
|
|
21322
|
-
let payload
|
|
21743
|
+
let payload;
|
|
21323
21744
|
try { payload = JSON.parse(line.slice(5).trim()); } catch { payload = null; }
|
|
21324
21745
|
// 防兜底:模型偶尔仍会输出 {"reply":"…","emotion":"…"} 信封,
|
|
21325
21746
|
// 这里只把 reply 的正文喂给气泡(不显示大括号/字段名/emotion)。
|
|
@@ -21338,13 +21759,25 @@ window.__ModuleLoader__.load({
|
|
|
21338
21759
|
if (piece && !replyDone) {
|
|
21339
21760
|
const cut = piece.indexOf('","emotion"');
|
|
21340
21761
|
if (cut >= 0) { piece = piece.slice(0, cut); replyDone = true; }
|
|
21341
|
-
if (piece)
|
|
21762
|
+
if (piece) {
|
|
21763
|
+
// 朗读没开始时先照旧把文字逐字填进气泡;一开始播,气泡字幕就交给
|
|
21764
|
+
// petTts 的 onSentence(逐句显示),避免两路同时写同一个气泡。
|
|
21765
|
+
if (queuedSpeech === 0) petBubble.append(piece);
|
|
21766
|
+
speakBuffer += piece;
|
|
21767
|
+
const split = petTtsSentences(speakBuffer);
|
|
21768
|
+
for (const sentence of split.sentences) enqueueSpeech(sentence);
|
|
21769
|
+
speakBuffer = split.rest;
|
|
21770
|
+
}
|
|
21342
21771
|
}
|
|
21343
21772
|
}
|
|
21344
21773
|
}
|
|
21345
21774
|
}
|
|
21775
|
+
// 最后一段没有句末标点也要念(比如“我也在”)
|
|
21776
|
+
enqueueSpeech(speakBuffer);
|
|
21346
21777
|
if (typeof onState === 'function') onState({ state: 'idle' });
|
|
21347
|
-
|
|
21778
|
+
// 没有任何一句进入朗读(静音 / 合成不可用)⇒ 沿用旧行为:整段文字 3 秒后淡出。
|
|
21779
|
+
// 有朗读时由 petTts 的 onIdle 在念完后淡出(按句字幕不会被提前清掉)。
|
|
21780
|
+
if (!queuedSpeech) petBubble.hide(3000);
|
|
21348
21781
|
},
|
|
21349
21782
|
// P4:用户自己的话**不进**气泡(那是回声);只显示 assistant 的 SSE delta
|
|
21350
21783
|
onText: () => {},
|
|
@@ -21393,6 +21826,8 @@ window.__ModuleLoader__.load({
|
|
|
21393
21826
|
const text = String(input.value || '').trim();
|
|
21394
21827
|
if (!text) return;
|
|
21395
21828
|
box.remove();
|
|
21829
|
+
// 新的一轮 = 先掐掉上一轮还在念的(与录音入口同一条 barge-in 纪律)
|
|
21830
|
+
petSpeakStop();
|
|
21396
21831
|
// 打字说的文本**不上气泡**(P4 同理:气泡只显示助手的回答)。
|
|
21397
21832
|
// 这里只把状态切成"思考中",等 SSE 的 delta 逐字填进来。
|
|
21398
21833
|
petBubble.setState('think');
|
|
@@ -21407,18 +21842,22 @@ window.__ModuleLoader__.load({
|
|
|
21407
21842
|
input.focus();
|
|
21408
21843
|
}
|
|
21409
21844
|
|
|
21410
|
-
/**
|
|
21411
|
-
*
|
|
21845
|
+
/**
|
|
21846
|
+
* 说一句:气泡显示 + 朗读(P1)。
|
|
21847
|
+
* 静音/合成不可用时退回“只显示 3 秒”,不抛错、不弹窗。
|
|
21412
21848
|
*/
|
|
21413
21849
|
function petChatSay(text) {
|
|
21414
21850
|
const line = String(text || '').trim();
|
|
21415
21851
|
if (!line) return;
|
|
21416
21852
|
petBubble.show(line);
|
|
21417
|
-
petBubble.hide(3000);
|
|
21853
|
+
if (!petSpeak(line)) petBubble.hide(3000);
|
|
21418
21854
|
}
|
|
21419
21855
|
|
|
21420
|
-
/** 点桌宠:气泡可见 ⇒
|
|
21856
|
+
/** 点桌宠:气泡可见 ⇒ 立刻收起(同时停止录音与朗读);否则唤醒并开始听。 */
|
|
21421
21857
|
function petChatWake() {
|
|
21858
|
+
// **任何一次唤醒都是 barge-in**:先把正在念的停掉,再决定是收起还是开麦。
|
|
21859
|
+
petSpeakStop();
|
|
21860
|
+
void petChatRefreshVoice();
|
|
21422
21861
|
if (petBubble.isVisible()) { petBubble.hide(0); petVoiceIn.stop(); return; }
|
|
21423
21862
|
petBubble.setState('listen');
|
|
21424
21863
|
// 先看语音模型是否就绪;没就绪就**立刻**开始下载并在气泡里显示进度,
|
|
@@ -21436,9 +21875,36 @@ window.__ModuleLoader__.load({
|
|
|
21436
21875
|
});
|
|
21437
21876
|
}
|
|
21438
21877
|
|
|
21878
|
+
/**
|
|
21879
|
+
* 工作联动反向通道(P1):宿主 `/pet-chat/speak` → SSE `/pet-chat/events` → 这里念。
|
|
21880
|
+
* 待办/提醒/其它插件可以直接 `POST /folia/pet-chat/speak`,也可以在同一渲染进程里
|
|
21881
|
+
* `window.__dshFoliaPet.speak(text)` / 派发 `we-pet-speak` 事件。
|
|
21882
|
+
* EventSource 自带重连;这里不弹任何提示。
|
|
21883
|
+
*/
|
|
21884
|
+
let petChatEventSource = null;
|
|
21885
|
+
function petChatEventsStart() {
|
|
21886
|
+
if (petChatEventSource || typeof EventSource !== 'function') return;
|
|
21887
|
+
try {
|
|
21888
|
+
const source = new EventSource(apiUrl('/pet-chat/events'));
|
|
21889
|
+
source.onmessage = (event) => {
|
|
21890
|
+
let doc;
|
|
21891
|
+
try { doc = JSON.parse((event && event.data) || ''); } catch { doc = null; }
|
|
21892
|
+
if (!doc || doc.type !== 'speak' || !doc.text) return;
|
|
21893
|
+
petSpeak(String(doc.text), { voice: doc.voice, rate: doc.rate });
|
|
21894
|
+
};
|
|
21895
|
+
source.onerror = () => { /* EventSource 自动重连;失败不打扰用户 */ };
|
|
21896
|
+
petChatEventSource = source;
|
|
21897
|
+
} catch { /* 老环境没有 EventSource:仍在渲染进程内的调用走 window.__dshFoliaPet */ }
|
|
21898
|
+
}
|
|
21899
|
+
function petChatEventsStop() {
|
|
21900
|
+
if (!petChatEventSource) return;
|
|
21901
|
+
try { petChatEventSource.close(); } catch { /* ignore */ }
|
|
21902
|
+
petChatEventSource = null;
|
|
21903
|
+
}
|
|
21904
|
+
|
|
21439
21905
|
/**
|
|
21440
21906
|
* 常驻挂载(`WE_FEATURE_MOUNTS` 的一项):绑定点桌宠 / 快捷键。
|
|
21441
|
-
* 返回 cleanup ——
|
|
21907
|
+
* 返回 cleanup —— 卸载时摘监听、断开反向通道、销毁气泡。
|
|
21442
21908
|
*/
|
|
21443
21909
|
function mountPetChat() {
|
|
21444
21910
|
if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return () => {};
|
|
@@ -21456,13 +21922,37 @@ window.__ModuleLoader__.load({
|
|
|
21456
21922
|
// 打字入口只从**右键菜单「对话」**进:pet-layer 的菜单项派发 `we-pet-talk`。
|
|
21457
21923
|
// 不再劫持 contextmenu —— 那会让右键弹不出桌宠原生菜单(试演动作/缩放…)。
|
|
21458
21924
|
const onTalkEvent = () => { petChatOpenTyping(); };
|
|
21925
|
+
|
|
21926
|
+
/** 工作联动:同一渲染进程里的待办/提醒可以直接派发这个事件。 */
|
|
21927
|
+
const onSpeakEvent = (event) => {
|
|
21928
|
+
const detail = (event && event.detail) || {};
|
|
21929
|
+
const text = detail && detail.text;
|
|
21930
|
+
if (text) petSpeak(String(text), { voice: detail.voice, rate: detail.rate });
|
|
21931
|
+
};
|
|
21932
|
+
|
|
21459
21933
|
window.addEventListener('we-pet-talk', onTalkEvent);
|
|
21934
|
+
window.addEventListener('we-pet-speak', onSpeakEvent);
|
|
21460
21935
|
document.addEventListener('click', onDocumentClick, true);
|
|
21461
21936
|
document.addEventListener('keydown', onKeyDown, true);
|
|
21937
|
+
void petChatRefreshVoice();
|
|
21938
|
+
petChatEventsStart();
|
|
21939
|
+
// 对外通道:`speak(text)` 供待办/提醒直接调用(不打开任何窗口)
|
|
21940
|
+
try {
|
|
21941
|
+
window.__dshFoliaPet = {
|
|
21942
|
+
speak: (text, speech) => petSpeak(text, speech || {}),
|
|
21943
|
+
stop: () => petSpeakStop(),
|
|
21944
|
+
chat: (text) => petVoiceIn.postChat(String(text || '')),
|
|
21945
|
+
isSpeaking: () => petTts.isSpeaking(),
|
|
21946
|
+
};
|
|
21947
|
+
} catch { /* 被别的插件占用就只保留事件通道 */ }
|
|
21462
21948
|
return () => {
|
|
21463
21949
|
window.removeEventListener('we-pet-talk', onTalkEvent);
|
|
21950
|
+
window.removeEventListener('we-pet-speak', onSpeakEvent);
|
|
21464
21951
|
document.removeEventListener('click', onDocumentClick, true);
|
|
21465
21952
|
document.removeEventListener('keydown', onKeyDown, true);
|
|
21953
|
+
petChatEventsStop();
|
|
21954
|
+
petSpeakStop();
|
|
21955
|
+
try { if (window.__dshFoliaPet) delete window.__dshFoliaPet; } catch { /* ignore */ }
|
|
21466
21956
|
petBubble.dispose();
|
|
21467
21957
|
};
|
|
21468
21958
|
}
|