dsh-mobile-plugin 0.5.137 → 0.5.139
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/config/agent-presets/standard/skills/dsh-mobile-kb/references/pairing.md +2 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/port-conflict.md +4 -4
- package/lib/impl.js +10 -6
- package/lib/mobile/permissions.js +10 -0
- package/lib/mobile/session-step.js +17 -11
- package/lib/mobile/voice/frames.js +198 -0
- package/lib/mobile/voice/gateway.js +746 -0
- package/lib/mobile/voice/lang.js +347 -0
- package/lib/mobile/voice/lexicon-store.js +189 -0
- package/lib/mobile/voice/lexicon.js +508 -0
- package/lib/mobile/voice/panel-api.js +88 -0
- package/lib/mobile/voice/postprocess.js +551 -0
- package/lib/mobile/voice/protocol.js +306 -0
- package/lib/mobile/voice/providers/cn/aliyun.js +401 -0
- package/lib/mobile/voice/providers/cn/tencent.js +402 -0
- package/lib/mobile/voice/providers/cn/volc.js +328 -0
- package/lib/mobile/voice/providers/cn/xfyun.js +290 -0
- package/lib/mobile/voice/providers/host.js +190 -0
- package/lib/mobile/voice/providers/intl/_common.js +346 -0
- package/lib/mobile/voice/providers/intl/assemblyai.js +353 -0
- package/lib/mobile/voice/providers/intl/azure.js +444 -0
- package/lib/mobile/voice/providers/intl/deepgram.js +366 -0
- package/lib/mobile/voice/providers/intl/openai.js +389 -0
- package/lib/mobile/voice/providers/intl/speechmatics.js +405 -0
- package/lib/mobile/voice/providers/local/ondevice.js +129 -0
- package/lib/mobile/voice/providers/registry.js +277 -0
- package/lib/mobile/voice/routes.js +278 -0
- package/lib/mobile/voice/runtime.js +84 -0
- package/lib/mobile/voice/settings.js +206 -0
- package/lib/mobile/voice/stream.js +415 -0
- package/lib/mobile/voice/voice-provider.js +268 -0
- package/lib/panel/index.html +22 -22
- package/lib/routes/control-plane.js +19 -0
- package/lib/routes/mobile-api.js +33 -1
- package/lib/sidecar-facade-worker.cjs +1 -1
- package/lib/zeronews/wiring.cjs +17 -6
- package/package.json +14 -15
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 语言判断:只回答「这段字是什么语言」,不碰 provider、不碰网络。
|
|
5
|
+
*
|
|
6
|
+
* 口径见 `docs/voice-input-contract.md` 第四节与 `docs/voice-input-plan.md` 5.3:
|
|
7
|
+
* ① provider 自带的自动判断优先 —— 网关拿得到就别再判,那比任何本地启发式都准;
|
|
8
|
+
* ② 拿不到就按**文字脚本比例**判:数汉字 / 假名 / 谚文 / 拉丁字母的个数,标点、数字、空白不算;
|
|
9
|
+
* ③ 混说不硬塞成「整段一个语言」:按句给结论,`mixed` 标出来,后处理再按句选规则。
|
|
10
|
+
*
|
|
11
|
+
* 判不出来(纯数字、纯符号、只有 emoji)返回 `unknown`,让调用方去问 provider,
|
|
12
|
+
* 不在这里猜一个默认值 —— 猜错的语言标记会被 provider 当成硬约束,比 `auto` 更糟。
|
|
13
|
+
*
|
|
14
|
+
* 端侧 LID(SenseVoice 之类)只留**注入点**,不硬依赖:注入了也只在本地脚本判不出
|
|
15
|
+
* (`unknown`)或调用方点名 `preferLid` 时才用;注入的东西抛错或形状不对,一律当没注。
|
|
16
|
+
*
|
|
17
|
+
* `pickProviderLang` 的取舍:provider 明说自己能自动检测就给 `auto`(它的模型见过声学特征,
|
|
18
|
+
* 比拿文本反推准);不能自动检测就只给**它声明支持**的标记,绝不把不支持的语言硬塞过去 ——
|
|
19
|
+
* 塞过去的结果通常是识别出乱码而不是报错。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** 汉字(含扩展 A、兼容区)。 */
|
|
23
|
+
const HAN = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/;
|
|
24
|
+
/** 平假名 / 片假名(含片假名长音与半角片假名)。 */
|
|
25
|
+
const KANA = /[\u3040-\u309f\u30a0-\u30ff\uff66-\uff9f]/;
|
|
26
|
+
/** 谚文(音节 + 字母 + 兼容字母)。 */
|
|
27
|
+
const HANGUL = /[\u1100-\u11ff\u3130-\u318f\uac00-\ud7af]/;
|
|
28
|
+
/** 拉丁字母,带变音符的也算。 */
|
|
29
|
+
const LATIN = /[A-Za-z\u00c0-\u024f]/;
|
|
30
|
+
|
|
31
|
+
/** 句末标点。分号、省略号、换行都当断句,和手机侧上屏的观感一致。 */
|
|
32
|
+
const SENTENCE_PUNCT = new Set(['。', '!', '?', '!', '?', '…', ';', ';', '\n']);
|
|
33
|
+
|
|
34
|
+
/** 拉丁句点不断句的缩写。 */
|
|
35
|
+
const ABBREVIATIONS = new Set([
|
|
36
|
+
'mr', 'mrs', 'ms', 'dr', 'prof', 'st', 'vs', 'etc', 'e.g', 'i.e', 'fig', 'no', 'approx',
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
/** 取拉丁句点前面那个「词」(含内部和末尾的点),用来认缩写。 */
|
|
40
|
+
function wordBefore(text, index) {
|
|
41
|
+
const match = text.slice(0, index).match(/[A-Za-z.]+$/);
|
|
42
|
+
return match ? match[0].replace(/\.$/, '').toLowerCase() : '';
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 认可「自动检测」的标记写法:不同 provider 用词不一样。 */
|
|
46
|
+
const AUTO_TAGS = new Set(['auto', 'automatic', 'multilingual', 'multi', 'detect', 'mixed']);
|
|
47
|
+
|
|
48
|
+
/** provider 没声明语言时,按请求的 ISO 639-2/3 写法折算回常用两字母标记。 */
|
|
49
|
+
const LANG_ALIASES = { cmn: 'zh', zho: 'zh', chi: 'zh', eng: 'en', jpn: 'ja', kor: 'ko' };
|
|
50
|
+
|
|
51
|
+
/** 主语言判定时认的三字母顺序:票数打平时靠它定,保证结果稳定。 */
|
|
52
|
+
const LANG_ORDER = ['zh', 'en', 'ja', 'ko'];
|
|
53
|
+
|
|
54
|
+
let injectedLid = null;
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 拆分句子:中英文标点都认,句末标点与紧随的引号/括号留在句子里,拼回去就是原文。
|
|
58
|
+
*
|
|
59
|
+
* 拉丁句点只在「后面是空白 + 大写/引号」或句尾时断句:`file.js`、`e.g. foo` 这类
|
|
60
|
+
* 开发场景里高频的写法不能被切碎;常见缩写(Mr. / etc.)也放过。
|
|
61
|
+
*
|
|
62
|
+
* @param {string} text
|
|
63
|
+
* @returns {string[]} 去掉首尾空白的句子;空输入返回空数组。
|
|
64
|
+
*/
|
|
65
|
+
function splitSentences(text) {
|
|
66
|
+
if (typeof text !== 'string' || !text) return [];
|
|
67
|
+
const out = [];
|
|
68
|
+
const push = (start, end) => {
|
|
69
|
+
const piece = text.slice(start, end).trim();
|
|
70
|
+
if (piece) out.push(piece);
|
|
71
|
+
};
|
|
72
|
+
let start = 0;
|
|
73
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
74
|
+
const ch = text[i];
|
|
75
|
+
let cut = false;
|
|
76
|
+
if (SENTENCE_PUNCT.has(ch)) cut = true;
|
|
77
|
+
else if (ch === '.') {
|
|
78
|
+
if (!ABBREVIATIONS.has(wordBefore(text, i))) {
|
|
79
|
+
const next = text[i + 1];
|
|
80
|
+
const nextVisible = next === ' ' ? text[i + 2] : next;
|
|
81
|
+
cut = i === text.length - 1
|
|
82
|
+
|| (next === ' ' && nextVisible !== undefined
|
|
83
|
+
&& /[A-Z"'“\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/.test(nextVisible));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (!cut) continue;
|
|
87
|
+
// 连续标点(「你好?!」「等等……」)并进同一句。
|
|
88
|
+
let j = i + 1;
|
|
89
|
+
while (j < text.length && '。!?!?…;;.,,、'.includes(text[j])) j += 1;
|
|
90
|
+
// 句末引号 / 括号归上一句。
|
|
91
|
+
while (j < text.length && '”"』」))'.includes(text[j])) j += 1;
|
|
92
|
+
push(start, j);
|
|
93
|
+
start = j;
|
|
94
|
+
i = j - 1;
|
|
95
|
+
}
|
|
96
|
+
push(start, text.length);
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 数脚本个数;标点、数字、emoji 都不计入任何一类。 */
|
|
101
|
+
function countScripts(text) {
|
|
102
|
+
const counts = { han: 0, kana: 0, hangul: 0, latin: 0 };
|
|
103
|
+
for (const ch of text) {
|
|
104
|
+
if (KANA.test(ch)) counts.kana += 1;
|
|
105
|
+
else if (HANGUL.test(ch)) counts.hangul += 1;
|
|
106
|
+
else if (HAN.test(ch)) counts.han += 1;
|
|
107
|
+
else if (LATIN.test(ch)) counts.latin += 1;
|
|
108
|
+
}
|
|
109
|
+
return counts;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 比例保留两位小数,不做花哨的置信度模型 —— 这就是脚本占比,别叫得更玄。 */
|
|
113
|
+
function ratio(part, total) {
|
|
114
|
+
if (!total) return 0;
|
|
115
|
+
return Math.round((part / total) * 100) / 100;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 单句判定。
|
|
120
|
+
*
|
|
121
|
+
* 三条规则:
|
|
122
|
+
* - 有假名就是日语(日语里夹汉字是常态,汉字数不能压过假名的存在);
|
|
123
|
+
* - 有谚文就是韩语;
|
|
124
|
+
* - 只有汉字就是中文;纯拉丁按英文处理(其他拉丁语言这里分不出来,见文件尾的局限说明)。
|
|
125
|
+
* 拉丁字母占到绝对多数(>80% 且 ≥6 个字母)时主语言翻成英文 ——「deploy 到 production」
|
|
126
|
+
* 这种句子主语言其实是英语,硬判成中文会让标点和 ITN 走错规则。
|
|
127
|
+
*
|
|
128
|
+
* @param {string} sentence
|
|
129
|
+
* @returns {{lang:string, confidence:number, mixed:boolean, total:number}}
|
|
130
|
+
*/
|
|
131
|
+
function analyzeSentence(sentence) {
|
|
132
|
+
const counts = countScripts(sentence);
|
|
133
|
+
const cjk = counts.han + counts.kana + counts.hangul;
|
|
134
|
+
const total = cjk + counts.latin;
|
|
135
|
+
if (!total) return { lang: 'unknown', confidence: 0, mixed: false, total: 0 };
|
|
136
|
+
|
|
137
|
+
let lang = 'en';
|
|
138
|
+
if (counts.kana > 0) lang = 'ja';
|
|
139
|
+
else if (counts.hangul > 0) lang = 'ko';
|
|
140
|
+
else if (counts.han > 0) lang = 'zh';
|
|
141
|
+
|
|
142
|
+
const latinShare = counts.latin / total;
|
|
143
|
+
if (cjk > 0 && latinShare > 0.8 && counts.latin >= 6) lang = 'en';
|
|
144
|
+
|
|
145
|
+
let dominant;
|
|
146
|
+
if (lang === 'ja') dominant = counts.kana + counts.han;
|
|
147
|
+
else if (lang === 'ko') dominant = counts.hangul + counts.han;
|
|
148
|
+
else if (lang === 'zh') dominant = counts.han;
|
|
149
|
+
else dominant = counts.latin;
|
|
150
|
+
|
|
151
|
+
const confidence = ratio(dominant, total);
|
|
152
|
+
const minorShare = 1 - dominant / total;
|
|
153
|
+
const mixed = lang === 'en' ? cjk > 0 : latinShare >= 0.2 && counts.latin >= 2;
|
|
154
|
+
return { lang, confidence, mixed: mixed && minorShare > 0, total };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 把注入的 LID 结果收拾成统一形状;认不出来就返回 null,绝不让形状问题冒到调用方。 */
|
|
158
|
+
function applyLid(lid, text, lang) {
|
|
159
|
+
if (typeof lid !== 'function') return null;
|
|
160
|
+
let raw;
|
|
161
|
+
try {
|
|
162
|
+
raw = lid(text);
|
|
163
|
+
} catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
if (raw && typeof raw.then === 'function') return null; // 同步管线里不等 promise,异步结果留给调用方自己接
|
|
167
|
+
const candidate = typeof raw === 'string' ? { lang: raw } : raw && typeof raw === 'object' ? raw : null;
|
|
168
|
+
if (!candidate) return null;
|
|
169
|
+
const tag = typeof candidate.lang === 'string' ? candidate.lang : candidate.language;
|
|
170
|
+
if (typeof tag !== 'string' || !tag.trim()) return null;
|
|
171
|
+
const confidence = typeof candidate.confidence === 'number' && Number.isFinite(candidate.confidence)
|
|
172
|
+
? Math.max(0, Math.min(1, Math.round(candidate.confidence * 100) / 100))
|
|
173
|
+
: 0.5;
|
|
174
|
+
return { lang: tag.trim().toLowerCase(), confidence, mixed: false, total: 0, source: 'lid' };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* 注册端侧 LID 注入点(宿主有 SenseVoice 之类时由网关调)。
|
|
179
|
+
* 传 `null` 撤销注入。只在本地判不出或调用方点名 `preferLid` 时被用到。
|
|
180
|
+
*
|
|
181
|
+
* @param {((text:string)=>string|{lang?:string, language?:string, confidence?:number})|null} detector
|
|
182
|
+
*/
|
|
183
|
+
function setLidDetector(detector) {
|
|
184
|
+
injectedLid = typeof detector === 'function' ? detector : null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* 判语言。返回契约里的 `{ lang, confidence, mixed }`,另附按句结论 `sentences`,
|
|
189
|
+
* 后处理拿它按句选规则(契约字段是下限,多的字段只增不改)。
|
|
190
|
+
*
|
|
191
|
+
* @param {string} text
|
|
192
|
+
* @param {{lid?:Function, preferLid?:boolean, defaultLang?:string}} [options]
|
|
193
|
+
* @returns {{lang:string, confidence:number, mixed:boolean, source:string,
|
|
194
|
+
* sentences:Array<{text:string, lang:string, confidence:number, mixed:boolean}>}}
|
|
195
|
+
*/
|
|
196
|
+
function detectLang(text, options = {}) {
|
|
197
|
+
const source = typeof text === 'string' ? text : '';
|
|
198
|
+
const pieces = splitSentences(source);
|
|
199
|
+
const list = pieces.length ? pieces : source.trim() ? [source.trim()] : [];
|
|
200
|
+
const analysed = list.map((sentence) => ({ sentence, ...analyzeSentence(sentence) }));
|
|
201
|
+
|
|
202
|
+
const mass = { zh: 0, en: 0, ja: 0, ko: 0 };
|
|
203
|
+
for (const item of analysed) {
|
|
204
|
+
if (item.lang !== 'unknown') mass[item.lang] += item.total;
|
|
205
|
+
}
|
|
206
|
+
const sum = LANG_ORDER.reduce((acc, lang) => acc + mass[lang], 0);
|
|
207
|
+
|
|
208
|
+
let lang = 'unknown';
|
|
209
|
+
let confidence = 0;
|
|
210
|
+
for (const code of LANG_ORDER) {
|
|
211
|
+
if (mass[code] > (mass[lang] || 0)) {
|
|
212
|
+
lang = code;
|
|
213
|
+
confidence = ratio(mass[code], sum);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (!sum) lang = 'unknown';
|
|
217
|
+
|
|
218
|
+
const knownLangs = new Set(analysed.map((item) => item.lang).filter((code) => code !== 'unknown'));
|
|
219
|
+
const mixed = analysed.some((item) => item.mixed) || knownLangs.size > 1;
|
|
220
|
+
|
|
221
|
+
const lid = options.lid !== undefined ? options.lid : injectedLid;
|
|
222
|
+
const wanted = typeof options.defaultLang === 'string' && options.defaultLang.trim()
|
|
223
|
+
? options.defaultLang.trim().toLowerCase()
|
|
224
|
+
: '';
|
|
225
|
+
let sourceTag = 'script';
|
|
226
|
+
if (lang === 'unknown' && wanted) {
|
|
227
|
+
lang = wanted;
|
|
228
|
+
confidence = 0.3;
|
|
229
|
+
sourceTag = 'default';
|
|
230
|
+
}
|
|
231
|
+
const lidHit = applyLid(lid, source, lang);
|
|
232
|
+
if (lidHit && (options.preferLid === true || lang === 'unknown')) {
|
|
233
|
+
return {
|
|
234
|
+
lang: lidHit.lang,
|
|
235
|
+
confidence: lidHit.confidence,
|
|
236
|
+
mixed: false,
|
|
237
|
+
source: 'lid',
|
|
238
|
+
sentences: analysed.map((item) => ({
|
|
239
|
+
text: item.sentence, lang: item.lang, confidence: item.confidence, mixed: item.mixed,
|
|
240
|
+
})),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
return {
|
|
245
|
+
lang,
|
|
246
|
+
confidence: lang === 'unknown' ? 0 : confidence,
|
|
247
|
+
mixed: lang === 'unknown' ? false : mixed,
|
|
248
|
+
source: sourceTag,
|
|
249
|
+
sentences: analysed.map((item) => ({
|
|
250
|
+
text: item.sentence, lang: item.lang, confidence: item.confidence, mixed: item.mixed,
|
|
251
|
+
})),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* 取声明的语言列表:字符串、`languages` / `language` / `lang` 三种键都认。
|
|
257
|
+
* 传**一组 provider 能力**(网关的 `capabilities()` 就是这种形状)时取并集 ——
|
|
258
|
+
* 调用方拿整张能力表来问,问的是「这些 provider 合起来能不能满足」。
|
|
259
|
+
*/
|
|
260
|
+
function languageListOf(capabilities) {
|
|
261
|
+
if (!capabilities) return [];
|
|
262
|
+
if (typeof capabilities === 'string') {
|
|
263
|
+
return capabilities.split(',').map((tag) => tag.trim()).filter(Boolean);
|
|
264
|
+
}
|
|
265
|
+
if (Array.isArray(capabilities)) {
|
|
266
|
+
const out = [];
|
|
267
|
+
for (const item of capabilities) out.push(...languageListOf(item));
|
|
268
|
+
return [...new Set(out)];
|
|
269
|
+
}
|
|
270
|
+
const raw = capabilities.languages !== undefined
|
|
271
|
+
? capabilities.languages
|
|
272
|
+
: capabilities.language !== undefined ? capabilities.language : capabilities.lang;
|
|
273
|
+
if (Array.isArray(raw)) return raw.filter((tag) => typeof tag === 'string' && tag.trim());
|
|
274
|
+
if (typeof raw === 'string') return raw.split(',').map((tag) => tag.trim()).filter(Boolean);
|
|
275
|
+
return [];
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** provider 是否声称能自动检测(不同适配器写法不一,都认成同一件事)。 */
|
|
279
|
+
function supportsAuto(capabilities) {
|
|
280
|
+
if (!capabilities) return false;
|
|
281
|
+
if (Array.isArray(capabilities)) return capabilities.some((item) => supportsAuto(item));
|
|
282
|
+
if (typeof capabilities === 'string') {
|
|
283
|
+
return capabilities.split(',').some((tag) => AUTO_TAGS.has(tag.trim().toLowerCase()));
|
|
284
|
+
}
|
|
285
|
+
if (typeof capabilities !== 'object') return false;
|
|
286
|
+
if (languageListOf(capabilities).some((tag) => AUTO_TAGS.has(tag.toLowerCase()))) return true;
|
|
287
|
+
return capabilities.autoDetect === true
|
|
288
|
+
|| capabilities.langDetect === true
|
|
289
|
+
|| capabilities.lid === true
|
|
290
|
+
|| capabilities.multilingual === true;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** 请求的语言标记归一:`auto` / 空 / 非字符串都当「没点名」,交给 provider 自己判。 */
|
|
294
|
+
function normalizeRequested(requested) {
|
|
295
|
+
if (typeof requested !== 'string') return '';
|
|
296
|
+
const tag = requested.trim();
|
|
297
|
+
if (!tag || AUTO_TAGS.has(tag.toLowerCase())) return '';
|
|
298
|
+
return tag;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 在 provider 的语言表里找准标记:先精确、再按主语言前缀(`zh-CN` ↔ `zh`)、最后折算别名。 */
|
|
302
|
+
function findSupportedTag(list, wanted) {
|
|
303
|
+
const lower = wanted.toLowerCase();
|
|
304
|
+
const exact = list.find((tag) => tag.toLowerCase() === lower);
|
|
305
|
+
if (exact) return exact;
|
|
306
|
+
const base = lower.split(/[-_]/)[0];
|
|
307
|
+
const prefix = list.find((tag) => tag.toLowerCase().split(/[-_]/)[0] === base);
|
|
308
|
+
if (prefix) return prefix;
|
|
309
|
+
const alias = LANG_ALIASES[base];
|
|
310
|
+
if (alias) {
|
|
311
|
+
const hit = list.find((tag) => tag.toLowerCase().split(/[-_]/)[0] === alias);
|
|
312
|
+
if (hit) return hit;
|
|
313
|
+
}
|
|
314
|
+
return '';
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* 选出该 provider 能接受的语言标记:能接受请求的就用它自己声明的写法,
|
|
319
|
+
* 不能就 `auto`(它自己判),再不行用它列表里的第一个 —— 绝不返回它没声明的标记。
|
|
320
|
+
*
|
|
321
|
+
* @param {object|string[]|string} capabilities provider 能力对象(或语言列表)
|
|
322
|
+
* @param {string} [requested] 调用方想要的语言,`auto` / 空表示不限
|
|
323
|
+
* @returns {string} provider 的语言标记,或 `'auto'`
|
|
324
|
+
*/
|
|
325
|
+
function pickProviderLang(capabilities, requested) {
|
|
326
|
+
const list = languageListOf(capabilities);
|
|
327
|
+
const auto = supportsAuto(capabilities);
|
|
328
|
+
const wanted = normalizeRequested(requested);
|
|
329
|
+
if (!wanted) {
|
|
330
|
+
if (auto) return 'auto';
|
|
331
|
+
if (!list.length) return 'auto';
|
|
332
|
+
return findSupportedTag(list, 'zh') || list[0] || 'auto';
|
|
333
|
+
}
|
|
334
|
+
const hit = findSupportedTag(list, wanted);
|
|
335
|
+
if (hit) return hit;
|
|
336
|
+
if (auto) return 'auto';
|
|
337
|
+
// provider 没声明语言列表 = 不限制语言,按请求原样转;声明了但不支持,用它列表里的第一个。
|
|
338
|
+
if (!list.length) return wanted;
|
|
339
|
+
return list[0] || 'auto';
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
module.exports = {
|
|
343
|
+
detectLang,
|
|
344
|
+
splitSentences,
|
|
345
|
+
pickProviderLang,
|
|
346
|
+
setLidDetector,
|
|
347
|
+
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// 2026-11-29:语音词库的电脑侧落盘——自动学到的热词与「听错→改对」映射,供识别后纠正用。
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 语音词库的电脑侧存储(自动学习的那一层)。
|
|
6
|
+
*
|
|
7
|
+
* 词的来源全部在本机:用户实际说/发出去的内容里整理出的术语(热词),以及明确的
|
|
8
|
+
* 「听错 → 改对」映射。**不往外传整份词库**:网关每次只把当次用得上的前若干条并进 hints,
|
|
9
|
+
* 交给 provider / 后处理(见 `gateway.js` 的 `buildHints` 与 `postprocess.correctTerms`)。
|
|
10
|
+
*
|
|
11
|
+
* 落点与语音配置同一处:`<DSH_HOME>/storages/mobile-plugin/voice-lexicon.json`,0600,
|
|
12
|
+
* 写临时文件再 rename。形状只许加字段、不许改含义:
|
|
13
|
+
*
|
|
14
|
+
* ```json
|
|
15
|
+
* { "version": 1, "hotwords": ["dsh-mobile", "火山引擎"], "corrections": [{ "heard": "火山", "corrected": "火山引擎" }] }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* 上限写死在这里,不靠调用方自觉:热词与映射都各有条数上限,超过就丢最旧的 —— 学习是长跑,
|
|
19
|
+
* 不能让词库无限长,否则每句话都要带上千条热词,性能反而拖垮(这正是需求里提醒的那点)。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('node:fs');
|
|
23
|
+
const path = require('node:path');
|
|
24
|
+
|
|
25
|
+
const { dshHome } = require('../../shared/paths.js');
|
|
26
|
+
|
|
27
|
+
const LEXICON_VERSION = 1;
|
|
28
|
+
const MAX_HOTWORDS = 200;
|
|
29
|
+
const MAX_CORRECTIONS = 200;
|
|
30
|
+
const MAX_WORD_CHARS = 32;
|
|
31
|
+
|
|
32
|
+
function isPlainObject(value) {
|
|
33
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function defaultFile() {
|
|
37
|
+
return path.join(dshHome(), 'storages', 'mobile-plugin', 'voice-lexicon.json');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cleanWord(value) {
|
|
41
|
+
if (typeof value !== 'string') return '';
|
|
42
|
+
const word = value.trim();
|
|
43
|
+
if (!word || word.length > MAX_WORD_CHARS) return '';
|
|
44
|
+
return word;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function cleanCorrection(pair) {
|
|
48
|
+
if (!isPlainObject(pair)) return null;
|
|
49
|
+
const heard = cleanWord(pair.heard);
|
|
50
|
+
const corrected = cleanWord(pair.corrected);
|
|
51
|
+
if (!heard || !corrected || heard === corrected) return null;
|
|
52
|
+
return { heard, corrected };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 把盘上读到的任意形状收敛成可用状态;脏值就地丢弃,不报错。 */
|
|
56
|
+
function normalizeState(raw) {
|
|
57
|
+
const state = { version: LEXICON_VERSION, hotwords: [], corrections: [] };
|
|
58
|
+
if (!isPlainObject(raw)) return state;
|
|
59
|
+
const seen = new Set();
|
|
60
|
+
for (const item of Array.isArray(raw.hotwords) ? raw.hotwords : []) {
|
|
61
|
+
const word = cleanWord(item);
|
|
62
|
+
if (!word) continue;
|
|
63
|
+
const key = word.toLowerCase();
|
|
64
|
+
if (seen.has(key)) continue;
|
|
65
|
+
seen.add(key);
|
|
66
|
+
state.hotwords.push(word);
|
|
67
|
+
if (state.hotwords.length >= MAX_HOTWORDS) break;
|
|
68
|
+
}
|
|
69
|
+
const seenPairs = new Set();
|
|
70
|
+
for (const item of Array.isArray(raw.corrections) ? raw.corrections : []) {
|
|
71
|
+
const pair = cleanCorrection(item);
|
|
72
|
+
if (!pair) continue;
|
|
73
|
+
const key = `${pair.heard.toLowerCase()}\u0000${pair.corrected.toLowerCase()}`;
|
|
74
|
+
if (seenPairs.has(key)) continue;
|
|
75
|
+
seenPairs.add(key);
|
|
76
|
+
state.corrections.push(pair);
|
|
77
|
+
if (state.corrections.length >= MAX_CORRECTIONS) break;
|
|
78
|
+
}
|
|
79
|
+
return state;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 按 key 去重,保留首次出现(调用方已把顺序摆好)。 */
|
|
83
|
+
function dedupeBy(items, keyOf) {
|
|
84
|
+
const seen = new Set();
|
|
85
|
+
const out = [];
|
|
86
|
+
for (const item of items) {
|
|
87
|
+
const key = keyOf(item);
|
|
88
|
+
if (seen.has(key)) continue;
|
|
89
|
+
seen.add(key);
|
|
90
|
+
out.push(item);
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 建一个词库存储。
|
|
97
|
+
*
|
|
98
|
+
* @param {{ file?: string }} [options] `file` 只给测试指到临时目录。
|
|
99
|
+
*/
|
|
100
|
+
function createVoiceLexiconStore(options = {}) {
|
|
101
|
+
const file = typeof options.file === 'string' && options.file ? options.file : defaultFile();
|
|
102
|
+
let cached = null;
|
|
103
|
+
|
|
104
|
+
function read() {
|
|
105
|
+
if (!cached) {
|
|
106
|
+
let raw = null;
|
|
107
|
+
try {
|
|
108
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
109
|
+
} catch { /* 没文件 / 读坏都从空词库开始 */ }
|
|
110
|
+
cached = normalizeState(raw);
|
|
111
|
+
}
|
|
112
|
+
return cached;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function save() {
|
|
116
|
+
const state = read();
|
|
117
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
118
|
+
const tmp = `${file}.tmp`;
|
|
119
|
+
fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
|
|
120
|
+
fs.renameSync(tmp, file);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 新词进、老词出:已有的先去掉(大小写不敏感),新的放最前,最后按上限截断。 */
|
|
124
|
+
function addHotwords(words) {
|
|
125
|
+
const state = read();
|
|
126
|
+
const incoming = dedupeBy((Array.isArray(words) ? words : []).map(cleanWord).filter(Boolean).reverse(), (word) => word.toLowerCase());
|
|
127
|
+
if (!incoming.length) return state.hotwords.slice();
|
|
128
|
+
const incomingKeys = new Set(incoming.map((word) => word.toLowerCase()));
|
|
129
|
+
const kept = state.hotwords.filter((word) => !incomingKeys.has(word.toLowerCase()));
|
|
130
|
+
state.hotwords = incoming.concat(kept).slice(0, MAX_HOTWORDS);
|
|
131
|
+
save();
|
|
132
|
+
return state.hotwords.slice();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function addCorrections(pairs) {
|
|
136
|
+
const state = read();
|
|
137
|
+
const incoming = dedupeBy(
|
|
138
|
+
(Array.isArray(pairs) ? pairs : []).map(cleanCorrection).filter(Boolean).reverse(),
|
|
139
|
+
(pair) => pair.heard.toLowerCase(),
|
|
140
|
+
);
|
|
141
|
+
if (!incoming.length) return state.corrections.slice();
|
|
142
|
+
const incomingKeys = new Set(incoming.map((pair) => pair.heard.toLowerCase()));
|
|
143
|
+
const kept = state.corrections.filter((pair) => !incomingKeys.has(pair.heard.toLowerCase()));
|
|
144
|
+
state.corrections = incoming.concat(kept).slice(0, MAX_CORRECTIONS);
|
|
145
|
+
save();
|
|
146
|
+
return state.corrections.slice();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
file,
|
|
151
|
+
/** 给识别用的那一份(只是内存拷贝,落盘时机由写操作决定)。 */
|
|
152
|
+
snapshot() {
|
|
153
|
+
const state = read();
|
|
154
|
+
return { hotwords: state.hotwords.slice(), corrections: state.corrections.map((pair) => ({ ...pair })) };
|
|
155
|
+
},
|
|
156
|
+
addHotwords,
|
|
157
|
+
addCorrections,
|
|
158
|
+
/** 一次写入热词与映射(学习接口用)。 */
|
|
159
|
+
learn({ hotwords, corrections } = {}) {
|
|
160
|
+
if (Array.isArray(hotwords) && hotwords.length) addHotwords(hotwords);
|
|
161
|
+
if (Array.isArray(corrections) && corrections.length) addCorrections(corrections);
|
|
162
|
+
return this.snapshot();
|
|
163
|
+
},
|
|
164
|
+
reset() {
|
|
165
|
+
cached = null;
|
|
166
|
+
try { fs.unlinkSync(file); } catch { /* 没文件就算了 */ }
|
|
167
|
+
},
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 进程内单例:网关与学习接口共用同一份(都读同一个文件,分两份会互相盖掉)。 */
|
|
172
|
+
let singleton = null;
|
|
173
|
+
function lexiconStore() {
|
|
174
|
+
if (!singleton) singleton = createVoiceLexiconStore();
|
|
175
|
+
return singleton;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** 只给测试:丢掉单例,下一次 `lexiconStore()` 重建(可先设 DSH_HOME 指到临时目录)。 */
|
|
179
|
+
function resetLexiconStoreForTests() {
|
|
180
|
+
singleton = null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
module.exports = {
|
|
184
|
+
createVoiceLexiconStore,
|
|
185
|
+
lexiconStore,
|
|
186
|
+
resetLexiconStoreForTests,
|
|
187
|
+
MAX_HOTWORDS,
|
|
188
|
+
MAX_CORRECTIONS,
|
|
189
|
+
};
|