dsh-mobile-plugin 0.5.138 → 0.5.140
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/lib/impl.js +8 -5
- 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 +17 -17
- 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/runner.cjs +7 -4
- package/lib/zeronews/wiring.cjs +36 -43
- package/package.json +14 -15
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
// Speechmatics 适配器:整段走 Batch jobs REST(multipart + 轮询 + json-v2 转写稿),
|
|
2
|
+
// 流式走 Realtime v2 WebSocket(StartRecognition → 音频帧 → EndOfStream)。鉴权都是 Authorization: Bearer。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
const {
|
|
6
|
+
CODES,
|
|
7
|
+
VoiceError,
|
|
8
|
+
httpJson,
|
|
9
|
+
openWs,
|
|
10
|
+
baseLang,
|
|
11
|
+
cleanHotwords,
|
|
12
|
+
safeLog,
|
|
13
|
+
scrub,
|
|
14
|
+
backoff,
|
|
15
|
+
closeWs,
|
|
16
|
+
waitForClose,
|
|
17
|
+
} = require('./_common');
|
|
18
|
+
|
|
19
|
+
const DEFAULT_BASE_URL = 'https://asr.api.speechmatics.com';
|
|
20
|
+
const DEFAULT_WS_URL = 'wss://eu2.rt.speechmatics.com/v2';
|
|
21
|
+
const SAMPLE_RATE = 16000;
|
|
22
|
+
|
|
23
|
+
const LANGUAGES = [
|
|
24
|
+
'en', 'zh', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'nl', 'hi',
|
|
25
|
+
'ru', 'pl', 'tr', 'uk', 'vi', 'id', 'th', 'ar', 'he', 'fa', 'ur',
|
|
26
|
+
'sv', 'da', 'no', 'fi', 'cs', 'el', 'hu', 'ro', 'sk', 'bg',
|
|
27
|
+
'auto',
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const CONFIG_FIELDS = [
|
|
31
|
+
{ key: 'apiKey', label: 'API Key', secret: true, required: true },
|
|
32
|
+
{ key: 'baseUrl', label: 'API 地址(可选)', secret: false, required: false, placeholder: DEFAULT_BASE_URL },
|
|
33
|
+
{ key: 'wsUrl', label: '流式地址(可选)', secret: false, required: false, placeholder: DEFAULT_WS_URL },
|
|
34
|
+
{
|
|
35
|
+
key: 'operatingPoint',
|
|
36
|
+
type: 'select',
|
|
37
|
+
label: '实时精度',
|
|
38
|
+
secret: false,
|
|
39
|
+
required: false,
|
|
40
|
+
default: 'enhanced',
|
|
41
|
+
options: ['enhanced', 'standard'],
|
|
42
|
+
},
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
function trimSlash(value) {
|
|
46
|
+
return String(value || '').replace(/\/+$/, '');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function keyOf(config) {
|
|
50
|
+
return String((config && config.apiKey) || '').trim();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function baseUrlOf(config) {
|
|
54
|
+
return trimSlash((config && config.baseUrl) || DEFAULT_BASE_URL);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function wsUrlOf(config) {
|
|
58
|
+
return trimSlash((config && config.wsUrl) || DEFAULT_WS_URL);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function operatingPointOf(config) {
|
|
62
|
+
const value = String((config && config.operatingPoint) || 'enhanced').trim();
|
|
63
|
+
return value === 'standard' ? 'standard' : 'enhanced';
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function timeoutOf(config, fallback) {
|
|
67
|
+
const value = Number(config && config.timeoutMs);
|
|
68
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function ready(config) {
|
|
72
|
+
return Boolean(keyOf(config));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const CJK = '[\\u3400-\\u9fff\\uf900-\\ufaff\\u3040-\\u30ff\\uac00-\\ud7af]';
|
|
76
|
+
|
|
77
|
+
/** json-v2 的 results 是词/标点序列:拉丁语按空格拼,中日韩之间不留空格,标点前不留空格。 */
|
|
78
|
+
function joinResults(results) {
|
|
79
|
+
if (!Array.isArray(results)) return '';
|
|
80
|
+
const parts = [];
|
|
81
|
+
for (const item of results) {
|
|
82
|
+
const alternative = (item && item.alternatives && item.alternatives[0]) || {};
|
|
83
|
+
const content = String(alternative.content || '');
|
|
84
|
+
if (content) parts.push(content);
|
|
85
|
+
}
|
|
86
|
+
let text = parts.join(' ');
|
|
87
|
+
text = text.replace(new RegExp(`(${CJK})\\s+(${CJK})`, 'g'), '$1$2');
|
|
88
|
+
text = text.replace(/\s+([.,!?;:,。!?;:、)】》”’])/g, '$1');
|
|
89
|
+
text = text.replace(/([(【《“‘])\s+/g, '$1');
|
|
90
|
+
return text.trim();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 整段:建 job → 轮询 → 取 json-v2 转写稿。 */
|
|
94
|
+
async function transcribe({ config, audio, hints, signal, log } = {}) {
|
|
95
|
+
const cfg = config || {};
|
|
96
|
+
const key = keyOf(cfg);
|
|
97
|
+
if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'Speechmatics 未配置 API Key');
|
|
98
|
+
if (!audio || !audio.length) throw new VoiceError(CODES.INVALID_AUDIO, 'Speechmatics 收到空音频');
|
|
99
|
+
|
|
100
|
+
const lang = baseLang(hints && hints.lang);
|
|
101
|
+
const hotwords = cleanHotwords(hints && hints.hotwords);
|
|
102
|
+
const jobConfig = {
|
|
103
|
+
type: 'transcription',
|
|
104
|
+
transcription_config: {
|
|
105
|
+
language: lang,
|
|
106
|
+
operating_point: operatingPointOf(cfg),
|
|
107
|
+
enable_partials: false,
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
if (hotwords.length) jobConfig.transcription_config.additional_vocab = hotwords.map((content) => ({ content }));
|
|
111
|
+
|
|
112
|
+
const form = new FormData();
|
|
113
|
+
form.append('config', JSON.stringify(jobConfig));
|
|
114
|
+
form.append('data_file', new Blob([audio], { type: 'audio/wav' }), 'audio.wav');
|
|
115
|
+
|
|
116
|
+
safeLog(log, `Speechmatics 整段识别:lang=${lang} hotwords=${hotwords.length} bytes=${audio.length}`);
|
|
117
|
+
const created = await httpJson(`${baseUrlOf(cfg)}/v2/jobs`, {
|
|
118
|
+
headers: { authorization: `Bearer ${key}` },
|
|
119
|
+
body: form,
|
|
120
|
+
timeoutMs: timeoutOf(cfg, 60000),
|
|
121
|
+
label: 'Speechmatics 建立任务',
|
|
122
|
+
secrets: [key],
|
|
123
|
+
signal,
|
|
124
|
+
});
|
|
125
|
+
const jobId = created.json && created.json.id;
|
|
126
|
+
if (!jobId) throw new VoiceError(CODES.FAILED, 'Speechmatics 没有返回任务 id');
|
|
127
|
+
|
|
128
|
+
const timeoutMs = timeoutOf(cfg, 120000);
|
|
129
|
+
const pollMs = Math.max(250, Math.min(5000, Number(cfg.pollMs) || 500));
|
|
130
|
+
const deadline = Date.now() + timeoutMs;
|
|
131
|
+
for (;;) {
|
|
132
|
+
const res = await httpJson(`${baseUrlOf(cfg)}/v2/jobs/${encodeURIComponent(jobId)}`, {
|
|
133
|
+
method: 'GET',
|
|
134
|
+
headers: { authorization: `Bearer ${key}` },
|
|
135
|
+
timeoutMs: 30000,
|
|
136
|
+
label: 'Speechmatics 查询任务',
|
|
137
|
+
secrets: [key],
|
|
138
|
+
signal,
|
|
139
|
+
});
|
|
140
|
+
const body = res.json || {};
|
|
141
|
+
const job = body.job || body;
|
|
142
|
+
const status = String(job.status || '');
|
|
143
|
+
if (status === 'done') {
|
|
144
|
+
if (Array.isArray(job.errors) && job.errors.length) {
|
|
145
|
+
throw new VoiceError(CODES.FAILED, `Speechmatics 任务失败:${scrub(job.errors[0].message || job.errors[0].type || '未知错误', [key])}`);
|
|
146
|
+
}
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
if (status === 'rejected' || status === 'failed' || status === 'expired') {
|
|
150
|
+
const detail = Array.isArray(job.errors) && job.errors.length ? job.errors[0].message || job.errors[0].type : status;
|
|
151
|
+
throw new VoiceError(CODES.FAILED, `Speechmatics 任务失败:${scrub(detail, [key])}`);
|
|
152
|
+
}
|
|
153
|
+
if (Date.now() > deadline) throw new VoiceError(CODES.TIMEOUT, 'Speechmatics 任务超时');
|
|
154
|
+
await backoff(pollMs, signal);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const transcript = await httpJson(`${baseUrlOf(cfg)}/v2/jobs/${encodeURIComponent(jobId)}/transcript?format=json-v2`, {
|
|
158
|
+
method: 'GET',
|
|
159
|
+
headers: { authorization: `Bearer ${key}` },
|
|
160
|
+
timeoutMs: 30000,
|
|
161
|
+
label: 'Speechmatics 取转写稿',
|
|
162
|
+
secrets: [key],
|
|
163
|
+
signal,
|
|
164
|
+
});
|
|
165
|
+
const text = joinResults(transcript.json && transcript.json.results);
|
|
166
|
+
if (!text) throw new VoiceError(CODES.INVALID_AUDIO, 'Speechmatics 没有识别到语音内容');
|
|
167
|
+
const detected = transcript.json && transcript.json.metadata && transcript.json.metadata.language;
|
|
168
|
+
return { text, lang: detected ? baseLang(detected) : undefined };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 流式:Realtime v2;服务端只认 StartRecognition 之后的音频。 */
|
|
172
|
+
function stream({ config, hints, signal, onPartial, onFinal, onError } = {}) {
|
|
173
|
+
const cfg = config || {};
|
|
174
|
+
const key = keyOf(cfg);
|
|
175
|
+
const lang = baseLang(hints && hints.lang);
|
|
176
|
+
const hotwords = cleanHotwords(hints && hints.hotwords);
|
|
177
|
+
|
|
178
|
+
let ws = null;
|
|
179
|
+
let finished = false;
|
|
180
|
+
let cancelled = false;
|
|
181
|
+
let failed = false;
|
|
182
|
+
let started = false;
|
|
183
|
+
let ended = false;
|
|
184
|
+
const pending = [];
|
|
185
|
+
let pendingBytes = 0;
|
|
186
|
+
const PENDING_LIMIT = 4 * 1024 * 1024;
|
|
187
|
+
|
|
188
|
+
function emitPartial(text) {
|
|
189
|
+
if (cancelled || failed) return;
|
|
190
|
+
const value = String(text || '').trim();
|
|
191
|
+
if (!value) return;
|
|
192
|
+
if (typeof onPartial === 'function') {
|
|
193
|
+
try {
|
|
194
|
+
onPartial(value);
|
|
195
|
+
} catch {
|
|
196
|
+
// 回调抛错不影响连接
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function emitFinal(text) {
|
|
202
|
+
if (cancelled || failed) return;
|
|
203
|
+
const value = String(text || '').trim();
|
|
204
|
+
if (!value) return;
|
|
205
|
+
if (typeof onFinal === 'function') {
|
|
206
|
+
try {
|
|
207
|
+
onFinal(value);
|
|
208
|
+
} catch {
|
|
209
|
+
// 同上
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function emitError(err) {
|
|
215
|
+
if (cancelled || failed) return;
|
|
216
|
+
failed = true;
|
|
217
|
+
if (typeof onError === 'function') {
|
|
218
|
+
try {
|
|
219
|
+
onError(err);
|
|
220
|
+
} catch {
|
|
221
|
+
// 同上
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function startPayload() {
|
|
227
|
+
const transcriptionConfig = {
|
|
228
|
+
language: lang,
|
|
229
|
+
operating_point: operatingPointOf(cfg),
|
|
230
|
+
enable_partials: true,
|
|
231
|
+
max_delay: 1.0,
|
|
232
|
+
enable_entities: true,
|
|
233
|
+
};
|
|
234
|
+
if (hotwords.length) transcriptionConfig.additional_vocab = hotwords.map((content) => ({ content }));
|
|
235
|
+
return {
|
|
236
|
+
message: 'StartRecognition',
|
|
237
|
+
audio_format: { type: 'raw', encoding: 'pcm_s16le', sample_rate: SAMPLE_RATE },
|
|
238
|
+
transcription_config: transcriptionConfig,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function handleMessage(message) {
|
|
243
|
+
if (!message || typeof message !== 'object') return;
|
|
244
|
+
switch (message.message) {
|
|
245
|
+
case 'RecognitionStarted':
|
|
246
|
+
started = true;
|
|
247
|
+
// RecognitionStarted 之前收到的帧先在本地攒着,连上后一次补发。
|
|
248
|
+
if (ws && ws.readyState === 1) {
|
|
249
|
+
for (const chunk of pending.splice(0)) ws.send(chunk);
|
|
250
|
+
pendingBytes = 0;
|
|
251
|
+
}
|
|
252
|
+
return;
|
|
253
|
+
case 'AddPartialTranscript':
|
|
254
|
+
emitPartial(joinResults(message.results));
|
|
255
|
+
return;
|
|
256
|
+
case 'AddTranscript':
|
|
257
|
+
emitFinal(joinResults(message.results));
|
|
258
|
+
return;
|
|
259
|
+
case 'EndOfTranscript':
|
|
260
|
+
ended = true;
|
|
261
|
+
return;
|
|
262
|
+
case 'Warning':
|
|
263
|
+
return;
|
|
264
|
+
case 'Error': {
|
|
265
|
+
const type = String((message.type || (message.reason && message.reason.type) || ''));
|
|
266
|
+
const mapped = /auth|key|forbidden|unauthor/i.test(type) ? CODES.UNAVAILABLE : CODES.FAILED;
|
|
267
|
+
const detail = message.reason ? message.reason.description || message.reason.type : message.message;
|
|
268
|
+
emitError(new VoiceError(mapped, `Speechmatics 流式错误:${scrub(detail || type || '未知错误', [key])}`));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
default:
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const readyPromise = (async () => {
|
|
276
|
+
if (!key) throw new VoiceError(CODES.UNAVAILABLE, 'Speechmatics 未配置 API Key');
|
|
277
|
+
if (signal && signal.aborted) throw new VoiceError(CODES.CANCELLED, 'Speechmatics 流式已取消', { cancelled: true });
|
|
278
|
+
ws = await openWs(wsUrlOf(cfg), {
|
|
279
|
+
headers: { authorization: `Bearer ${key}` },
|
|
280
|
+
signal,
|
|
281
|
+
timeoutMs: timeoutOf(cfg, 15000),
|
|
282
|
+
label: 'Speechmatics 流式连接',
|
|
283
|
+
secrets: [key],
|
|
284
|
+
});
|
|
285
|
+
if (signal) {
|
|
286
|
+
// 契约要求 signal 能停掉已连上的会话;网关取消时还会再调一次 cancel()。
|
|
287
|
+
const onAbort = () => {
|
|
288
|
+
cancelled = true;
|
|
289
|
+
finished = true;
|
|
290
|
+
try {
|
|
291
|
+
ws.terminate();
|
|
292
|
+
} catch {
|
|
293
|
+
// 已经断了
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
297
|
+
ws.once('close', () => signal.removeEventListener('abort', onAbort));
|
|
298
|
+
}
|
|
299
|
+
ws.on('message', (data, isBinary) => {
|
|
300
|
+
if (isBinary) return;
|
|
301
|
+
let message = null;
|
|
302
|
+
try {
|
|
303
|
+
message = JSON.parse(data.toString('utf8'));
|
|
304
|
+
} catch {
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
handleMessage(message);
|
|
308
|
+
});
|
|
309
|
+
ws.on('error', (err) => {
|
|
310
|
+
emitError(new VoiceError(CODES.FAILED, `Speechmatics 流式连接中断:${scrub(err && err.message, [key])}`));
|
|
311
|
+
});
|
|
312
|
+
ws.on('close', (code, reason) => {
|
|
313
|
+
if (cancelled || failed || finished) return;
|
|
314
|
+
const detail = scrub(reason ? reason.toString('utf8') : '', [key]);
|
|
315
|
+
emitError(new VoiceError(CODES.UNAVAILABLE, `Speechmatics 流式连接被关闭(${code}${detail ? `:${detail}` : ''})`));
|
|
316
|
+
});
|
|
317
|
+
ws.send(JSON.stringify(startPayload()));
|
|
318
|
+
return true;
|
|
319
|
+
})();
|
|
320
|
+
|
|
321
|
+
readyPromise.catch((err) => {
|
|
322
|
+
if (cancelled) return;
|
|
323
|
+
emitError(err instanceof VoiceError ? err : new VoiceError(CODES.FAILED, scrub(err && err.message, [key])));
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
return {
|
|
327
|
+
ready: readyPromise,
|
|
328
|
+
push(pcm) {
|
|
329
|
+
if (cancelled || failed || finished) return;
|
|
330
|
+
if (!pcm || !pcm.length) return;
|
|
331
|
+
const chunk = Buffer.isBuffer(pcm) ? pcm : Buffer.from(pcm);
|
|
332
|
+
if (started && ws && ws.readyState === 1) {
|
|
333
|
+
ws.send(chunk);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (pendingBytes + chunk.length > PENDING_LIMIT) return;
|
|
337
|
+
pending.push(chunk);
|
|
338
|
+
pendingBytes += chunk.length;
|
|
339
|
+
},
|
|
340
|
+
async finish() {
|
|
341
|
+
if (finished) return;
|
|
342
|
+
finished = true;
|
|
343
|
+
try {
|
|
344
|
+
await readyPromise;
|
|
345
|
+
} catch {
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (!ws) return;
|
|
349
|
+
try {
|
|
350
|
+
ws.send(JSON.stringify({ message: 'EndOfStream' }));
|
|
351
|
+
} catch {
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
// 等服务端回 EndOfTranscript 再 CloseStream;超时就直接关。
|
|
355
|
+
const timeoutMs = timeoutOf(cfg, 8000);
|
|
356
|
+
const deadline = Date.now() + timeoutMs;
|
|
357
|
+
while (!ended && Date.now() < deadline) {
|
|
358
|
+
try {
|
|
359
|
+
await backoff(50, signal);
|
|
360
|
+
} catch {
|
|
361
|
+
break; // 取消 / 超时:不再等 EndOfTranscript
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
try {
|
|
365
|
+
ws.send(JSON.stringify({ message: 'CloseStream' }));
|
|
366
|
+
} catch {
|
|
367
|
+
// 已经断了
|
|
368
|
+
}
|
|
369
|
+
await waitForClose(ws, 1000, signal);
|
|
370
|
+
await closeWs(ws);
|
|
371
|
+
},
|
|
372
|
+
async cancel() {
|
|
373
|
+
if (cancelled) return;
|
|
374
|
+
cancelled = true;
|
|
375
|
+
finished = true;
|
|
376
|
+
pending.length = 0;
|
|
377
|
+
if (ws) {
|
|
378
|
+
try {
|
|
379
|
+
ws.terminate();
|
|
380
|
+
} catch {
|
|
381
|
+
// 已经断了
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
},
|
|
385
|
+
get socket() {
|
|
386
|
+
return ws;
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
module.exports = {
|
|
392
|
+
id: 'speechmatics',
|
|
393
|
+
name: 'Speechmatics',
|
|
394
|
+
kind: 'intl',
|
|
395
|
+
batch: true,
|
|
396
|
+
streaming: true,
|
|
397
|
+
languages: LANGUAGES,
|
|
398
|
+
hotwords: true,
|
|
399
|
+
maxSeconds: 600,
|
|
400
|
+
maxBytes: 25 * 1024 * 1024,
|
|
401
|
+
configFields: CONFIG_FIELDS,
|
|
402
|
+
ready,
|
|
403
|
+
transcribe,
|
|
404
|
+
stream,
|
|
405
|
+
};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// 2026-11-28:端侧 provider 适配器——能力声明与「本地优先」编排;识别本身在手机上执行。
|
|
2
|
+
// 2026-11-28:标成只读能力条目进能力表(capabilityOnly),不参与 gateway 的 provider 选择。
|
|
3
|
+
'use strict';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `ondevice` provider:端侧模型(sherpa-onnx + SenseVoice)的**能力声明**。
|
|
7
|
+
*
|
|
8
|
+
* ## 它不执行识别
|
|
9
|
+
*
|
|
10
|
+
* 模型跑在手机上:App 直连原生的 `DSHVoiceOnDevice`(见 `docs/voice-ondevice.md`),音频不出
|
|
11
|
+
* 手机。插件这侧没有手机上的模型句柄,也没有一条「把音频送回手机」的通道——网关的输入方向
|
|
12
|
+
* 只有手机 → 电脑。所以这个适配器的 `transcribe` / `stream` **明确抛不可用**,而不是假装
|
|
13
|
+
* 能调手机模型:网关据此不会把任何音频路由给它。
|
|
14
|
+
*
|
|
15
|
+
* 那它为什么还要存在:
|
|
16
|
+
* 1. `GET /voice/capabilities` 里要有 `ondevice` 这一行,App 才知道「端侧这条能力叫什么、
|
|
17
|
+
* 支持流式还是整段、语种到哪」,界面上才能画「离线识别」这个开关;
|
|
18
|
+
* 2. 把「本地优先」的规则写成可执行的 `planLocalFirst()`:端侧模型可用就直接本地出字,
|
|
19
|
+
* 不可用再按配置顺序上送云端,离线且没模型时明确告诉用户装模型——而不是静默失败;
|
|
20
|
+
* 3. 面板需要一处展示「这条 provider 不需要 key、不经网络」。
|
|
21
|
+
*
|
|
22
|
+
* 手机上真正执行的那一侧由 App 组接线:`services/voice/ondevice.ts` 负责装模型与调原生模块,
|
|
23
|
+
* `services/speech.ts` 决定这一轮走本地还是云端。插件不参与、也不该参与。
|
|
24
|
+
*
|
|
25
|
+
* 注:`registry.js` 把 `providers/local/**` 逐个读成**只读能力条目**(要求适配器自带
|
|
26
|
+
* `capabilityOnly: true`),它们只出现在 `/voice/capabilities` 与面板列表里,不进
|
|
27
|
+
* `availableIds` / `defaultId`,也不进 `transcribe` / `openStream` 的候选;网关被显式
|
|
28
|
+
* 点名选中它时会明确报「只能在手机本地执行」。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const { VOICE_ERRORS, voiceError } = require('../../protocol.js');
|
|
32
|
+
const { PROVIDER_STATUS } = require('../../voice-provider.js');
|
|
33
|
+
|
|
34
|
+
/** 端侧能干的活:SenseVoice 一份模型同时出文本、语种、标点与 ITN。 */
|
|
35
|
+
const ON_DEVICE_FEATURES = Object.freeze({
|
|
36
|
+
punctuation: true,
|
|
37
|
+
itn: true,
|
|
38
|
+
langDetect: true,
|
|
39
|
+
diarization: false,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/** 端侧能认的语种(SenseVoiceSmall 的 LID 集合);'auto' 表示不用用户先选。 */
|
|
43
|
+
const ON_DEVICE_LANGUAGES = Object.freeze(['auto', 'zh', 'en', 'ja', 'ko', 'yue']);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 本地优先的编排规则(纯函数,不碰网络、不碰配置存储)。
|
|
47
|
+
*
|
|
48
|
+
* `planLocalFirst` 只回答「这一轮按什么顺序试」,不执行任何一家:
|
|
49
|
+
* - 端侧模型在这台手机上可用 → 只走 `ondevice`,音频不出手机;
|
|
50
|
+
* - 端侧不可用但在线 → 走云端 provider 的既有顺序;
|
|
51
|
+
* - 端侧不可用且离线 → 空数组 + 一条「去装端侧模型」的说明,App 据此提示而不是干等超时。
|
|
52
|
+
*
|
|
53
|
+
* @param {{onDeviceReady?: boolean, online?: boolean, cloudProviders?: string[]}} input
|
|
54
|
+
* @returns {{ order: string[], local: boolean, notice: string|null }}
|
|
55
|
+
*/
|
|
56
|
+
function planLocalFirst(input = {}) {
|
|
57
|
+
const onDeviceReady = input.onDeviceReady === true;
|
|
58
|
+
const online = input.online !== false;
|
|
59
|
+
const cloud = Array.isArray(input.cloudProviders)
|
|
60
|
+
? input.cloudProviders.filter((id) => typeof id === 'string' && id && id !== 'ondevice')
|
|
61
|
+
: [];
|
|
62
|
+
|
|
63
|
+
if (onDeviceReady) return { order: ['ondevice'], local: true, notice: null };
|
|
64
|
+
if (online) return { order: cloud, local: false, notice: null };
|
|
65
|
+
return {
|
|
66
|
+
order: [],
|
|
67
|
+
local: false,
|
|
68
|
+
notice: '当前离线,手机上还没有安装端侧识别模型;装一次即可离线使用。',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 插件侧调用端侧执行时的统一错误:说清楚「执行在手机上」,别让人以为电脑能代跑。 */
|
|
73
|
+
function onDeviceOnlyError() {
|
|
74
|
+
return voiceError(
|
|
75
|
+
VOICE_ERRORS.PROVIDER_UNAVAILABLE,
|
|
76
|
+
'端侧识别在手机上执行,插件侧不接收也不转发音频;请由 App 直接调用本地模块',
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const onDeviceProvider = {
|
|
81
|
+
id: 'ondevice',
|
|
82
|
+
name: '本机离线识别',
|
|
83
|
+
kind: 'local',
|
|
84
|
+
/**
|
|
85
|
+
* 只读能力条目:出现在能力表 / 面板里(给 App 与用户看「手机上有这条能力」),但不是
|
|
86
|
+
* 网关可调用的远端 provider。registry 据此把它放进只读清单,`availableIds` /
|
|
87
|
+
* `defaultId` / `resolveProvider` 都不会选中它。
|
|
88
|
+
*/
|
|
89
|
+
capabilityOnly: true,
|
|
90
|
+
// 手机本地既能整段也能边说边出字;能力声明照实写,执行不在这条适配器里。
|
|
91
|
+
batch: true,
|
|
92
|
+
streaming: true,
|
|
93
|
+
languages: ON_DEVICE_LANGUAGES.slice(),
|
|
94
|
+
// SenseVoice 不带热词(声纹与词库都不在端侧这条链上),别假装支持。
|
|
95
|
+
hotwords: false,
|
|
96
|
+
// 端侧按内存划上限:单段 5 分钟、8 MiB 以内,超过由 App 分段。
|
|
97
|
+
maxSeconds: 300,
|
|
98
|
+
maxBytes: 8 * 1024 * 1024,
|
|
99
|
+
// 不需要任何配置:模型是 App 按需下载的,密钥更不存在。
|
|
100
|
+
configFields: [],
|
|
101
|
+
/** 端侧能力由 App 在手机上判断;插件侧只回答「这条能力有没有被关闭」。 */
|
|
102
|
+
ready(config) {
|
|
103
|
+
return !config || config.enabled !== false;
|
|
104
|
+
},
|
|
105
|
+
/**
|
|
106
|
+
* 面板/能力表里的状态:这条 provider 永远是 `available` —— 它声明的是「手机端有这条通道」,
|
|
107
|
+
* 不是「这台电脑现在能代跑」。手机上没有模型时由 App 的 `planLocalFirst` 判成不可用并降级;
|
|
108
|
+
* 插件这边替它判会把「换一台手机」的情况判错。
|
|
109
|
+
*/
|
|
110
|
+
status() {
|
|
111
|
+
return PROVIDER_STATUS.AVAILABLE;
|
|
112
|
+
},
|
|
113
|
+
async transcribe() {
|
|
114
|
+
throw onDeviceOnlyError();
|
|
115
|
+
},
|
|
116
|
+
stream() {
|
|
117
|
+
throw onDeviceOnlyError();
|
|
118
|
+
},
|
|
119
|
+
/** 额外的事实,给面板文案用(不是契约字段,网关不依赖它)。 */
|
|
120
|
+
execution: 'on-device',
|
|
121
|
+
features: ON_DEVICE_FEATURES,
|
|
122
|
+
planLocalFirst,
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
module.exports = onDeviceProvider;
|
|
126
|
+
module.exports.planLocalFirst = planLocalFirst;
|
|
127
|
+
module.exports.ON_DEVICE_LANGUAGES = ON_DEVICE_LANGUAGES;
|
|
128
|
+
module.exports.ON_DEVICE_FEATURES = ON_DEVICE_FEATURES;
|
|
129
|
+
module.exports.onDeviceOnlyError = onDeviceOnlyError;
|