dsh-total-quality 2.0.55 → 2.0.57
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/CONTRIBUTING.md +51 -47
- package/LICENSE.md +37 -37
- package/README.en.md +32 -30
- package/README.md +90 -88
- package/agent-host.cjs +277 -277
- package/client.js +199 -92
- package/cordis.patch.yml +5 -5
- package/docs/enterprise-onboarding.md +10 -10
- package/docs/technical-reference.md +223 -223
- package/host.cjs +91 -124
- package/llm-bridge.cjs +234 -234
- package/locale/en.json +5 -5
- package/locale/zh.json +5 -5
- package/package.json +3 -2
- package/public/app.css +3 -0
- package/public/app.js +6 -2
- package/public/index.html +8 -9
- package/public/js/api.js +152 -152
- package/public/js/assistant-history.js +62 -62
- package/public/js/material-library.js +100 -100
- package/public/js/mobile-preview.js +119 -0
- package/public/js/pages-company-knowledge.js +9 -32
- package/public/js/pages-core.js +232 -232
- package/public/js/pages-growth.js +148 -148
- package/public/js/pages-qms.js +1 -1
- package/public/js/pages-qtools.js +410 -410
- package/public/js/pages-thanks.js +71 -71
- package/public/js/plugin-updates.js +53 -0
- package/public/js/quality-workflow.js +205 -205
- package/public/js/survey-dates.js +41 -41
- package/public/js/survey-knowledge.js +301 -301
- package/public/js/tool-wizards.js +621 -621
- package/public/js/ui.js +467 -467
- package/public/js/voice-capture-worklet.js +30 -30
- package/public/js/xiaozhi-voice.js +264 -264
- package/public/js/xiaozhi.js +468 -468
- package/public/platform-help.html +426 -426
- package/public/platform-site/assets/0468a68574112812.css +10703 -10703
- package/public/platform-site/assets/159e086d35adfa1c.css +2094 -2094
- package/public/platform-site/assets/169e3159cade0d9f.css +98 -98
- package/public/platform-site/assets/22b917c4a3d4ae3d.svg +14 -14
- package/public/platform-site/assets/476f9254ccf723e7.css +8265 -8265
- package/public/platform-site/assets/85a0a4fb4416ded9.css +120 -120
- package/public/platform-site/assets/a3b272383226f6d9.svg +135 -135
- package/public/platform-site/assets/fd16dc5f3cc9d97e.svg +104 -104
- package/public/platform-site/assets/qip-favicon.svg +5 -5
- package/public/platform-site/index.html +279 -279
- package/public/platform-site/offline.js +261 -261
- package/public/platform-site/qip-brand.css +566 -566
- package/public/platform-site/qip-module-guides.js +237 -237
- package/public/responsive.css +103 -101
- package/public/vendor/markdown-it-15.0.3.LICENSE +22 -22
- package/public/vendor/markdown-it-15.0.3.umd.min.js +13 -13
- package/public/workbench.css +7 -7
- package/public/xiaozhi.css +292 -292
- package/resources/qms-templates/019ffb58f24ed48d.docx +0 -0
- package/resources/qms-templates/04a69165fc15143a.docx +0 -0
- package/resources/qms-templates/09af69358c989a63.docx +0 -0
- package/resources/qms-templates/0e7ac77844e45311.docx +0 -0
- package/resources/qms-templates/12446a1b5e173c71.docx +0 -0
- package/resources/qms-templates/15ae40f67f9a3efc.docx +0 -0
- package/resources/qms-templates/18a69bbebf2ece7f.docx +0 -0
- package/resources/qms-templates/1978faa989134f02.docx +0 -0
- package/resources/qms-templates/1a30e121de752f7b.docx +0 -0
- package/resources/qms-templates/1b88907969ea7d4c.docx +0 -0
- package/resources/qms-templates/1e92b808722bf90a.docx +0 -0
- package/resources/qms-templates/2091cad340dc0e7f.docx +0 -0
- package/resources/qms-templates/271ae1002c896ed7.docx +0 -0
- package/resources/qms-templates/280ce53e5d3b5fcf.docx +0 -0
- package/resources/qms-templates/28ca8e4ede0adf6d.docx +0 -0
- package/resources/qms-templates/2ac6675f3cb1f993.docx +0 -0
- package/resources/qms-templates/2c3b799389909d8b.docx +0 -0
- package/resources/qms-templates/2c51038ba2cc3264.docx +0 -0
- package/resources/qms-templates/30c888851d16d764.docx +0 -0
- package/resources/qms-templates/3459fc4daaa2743d.docx +0 -0
- package/resources/qms-templates/3751dafc335e0e80.docx +0 -0
- package/resources/qms-templates/38798cd4298cd2db.docx +0 -0
- package/resources/qms-templates/38f551f9d738ab0a.docx +0 -0
- package/resources/qms-templates/3c85a23ea17018b4.docx +0 -0
- package/resources/qms-templates/3cdb7d14caf1b852.docx +0 -0
- package/resources/qms-templates/3f23239bb6b3e1db.docx +0 -0
- package/resources/qms-templates/42a5b9efeeaa8007.docx +0 -0
- package/resources/qms-templates/47352aafe9b8dac1.docx +0 -0
- package/resources/qms-templates/495359b1e3cbb8fe.docx +0 -0
- package/resources/qms-templates/4ca6920464785166.docx +0 -0
- package/resources/qms-templates/4ce862582a7791be.docx +0 -0
- package/resources/qms-templates/54c9a02a10991b9e.docx +0 -0
- package/resources/qms-templates/5aeb8fddf5f3693f.docx +0 -0
- package/resources/qms-templates/5d7e5576b0e73be7.docx +0 -0
- package/resources/qms-templates/5db3a40edac37791.docx +0 -0
- package/resources/qms-templates/5ffa21eb78eb6f77.docx +0 -0
- package/resources/qms-templates/60d0fbcb709b7161.docx +0 -0
- package/resources/qms-templates/63e1d3a166756095.docx +0 -0
- package/resources/qms-templates/65c724c080d32f10.docx +0 -0
- package/resources/qms-templates/674bd7826c6cbac2.docx +0 -0
- package/resources/qms-templates/677e851acca1b879.docx +0 -0
- package/resources/qms-templates/6bf15feb1a0d2a8d.docx +0 -0
- package/resources/qms-templates/6c3889c7d0918db9.docx +0 -0
- package/resources/qms-templates/6c4c349eeb0a96a8.docx +0 -0
- package/resources/qms-templates/6c5befbd33f759c1.docx +0 -0
- package/resources/qms-templates/6df8367901347508.docx +0 -0
- package/resources/qms-templates/71db51997037692b.docx +0 -0
- package/resources/qms-templates/78a8ef8c76510c99.docx +0 -0
- package/resources/qms-templates/8397bfd1c0a1b013.docx +0 -0
- package/resources/qms-templates/84d750cf858b60a1.docx +0 -0
- package/resources/qms-templates/880de58a4b334533.docx +0 -0
- package/resources/qms-templates/88c37d1b87d9b78c.docx +0 -0
- package/resources/qms-templates/88e9cd42f1849462.docx +0 -0
- package/resources/qms-templates/8956597403be35b6.docx +0 -0
- package/resources/qms-templates/94675c810a233e1f.docx +0 -0
- package/resources/qms-templates/94dff59dd7ebec6e.docx +0 -0
- package/resources/qms-templates/9670b9cd02141594.docx +0 -0
- package/resources/qms-templates/98c373ebd7b5163d.docx +0 -0
- package/resources/qms-templates/a4078cf2378a9388.docx +0 -0
- package/resources/qms-templates/a5b110c7ef917139.docx +0 -0
- package/resources/qms-templates/aec75820e45774be.docx +0 -0
- package/resources/qms-templates/b31c085e281d230c.docx +0 -0
- package/resources/qms-templates/b7c1c3c72f8ffeef.docx +0 -0
- package/resources/qms-templates/b81b82eaa5c8f422.docx +0 -0
- package/resources/qms-templates/b92a2fa31f75f137.docx +0 -0
- package/resources/qms-templates/b96c54ae9cfffc54.docx +0 -0
- package/resources/qms-templates/bc47cfd626c010e7.docx +0 -0
- package/resources/qms-templates/be60792734afca69.docx +0 -0
- package/resources/qms-templates/c0018d8ae9ad19e1.docx +0 -0
- package/resources/qms-templates/c171027c964c8be3.docx +0 -0
- package/resources/qms-templates/c4b93d71f5d98b4b.docx +0 -0
- package/resources/qms-templates/c531da29fcb3090f.docx +0 -0
- package/resources/qms-templates/c88eddd43358d015.docx +0 -0
- package/resources/qms-templates/cb978da542f0d892.docx +0 -0
- package/resources/qms-templates/ccde4a94532a8d36.docx +0 -0
- package/resources/qms-templates/cf3fb1e20ae6f24d.docx +0 -0
- package/resources/qms-templates/d231b4982fc8113e.docx +0 -0
- package/resources/qms-templates/d3c55aa5ed14055c.docx +0 -0
- package/resources/qms-templates/db45c44a00a13349.docx +0 -0
- package/resources/qms-templates/db849a41210f54e0.docx +0 -0
- package/resources/qms-templates/dba9ce363d83ddc8.docx +0 -0
- package/resources/qms-templates/dca3ea4c95eb2225.docx +0 -0
- package/resources/qms-templates/dfa4220d2b6b8131.docx +0 -0
- package/resources/qms-templates/dfa51222c777734f.docx +0 -0
- package/resources/qms-templates/e07ea511507e14f5.docx +0 -0
- package/resources/qms-templates/e0a2e00c03458dfa.docx +0 -0
- package/resources/qms-templates/e0e802f46b6764d1.docx +0 -0
- package/resources/qms-templates/e53fc85717f2852b.docx +0 -0
- package/resources/qms-templates/e9dd82d5e54520e5.docx +0 -0
- package/resources/qms-templates/ea7bfc22c06d82a9.docx +0 -0
- package/resources/qms-templates/ecf0db9f37294536.docx +0 -0
- package/resources/qms-templates/f05fcfc87e82ff39.docx +0 -0
- package/resources/qms-templates/fb9e56a17c4a4f97.docx +0 -0
- package/resources/qms-templates/manifest.json +932 -0
- package/src/data/seed-sme.js +317 -317
- package/src/data/seed.js +879 -879
- package/src/lib/backup-identity.js +57 -57
- package/src/lib/chat-answer.js +225 -225
- package/src/lib/chat-context.js +99 -99
- package/src/lib/company-library.js +28 -19
- package/src/lib/data-import.js +217 -217
- package/src/lib/data-sources.js +118 -118
- package/src/lib/demo-data.js +27 -1
- package/src/lib/employee-intake.js +84 -84
- package/src/lib/growth.js +53 -53
- package/src/lib/intake-packets.js +119 -119
- package/src/lib/issue-intake.js +88 -88
- package/src/lib/kb-revision.js +214 -214
- package/src/lib/llm.js +279 -279
- package/src/lib/model-error.js +14 -14
- package/src/lib/privacy.js +26 -26
- package/src/lib/qms-drafting.js +194 -194
- package/src/lib/qms-jobs.js +11 -7
- package/src/lib/qms-manual-review.js +185 -185
- package/src/lib/qms-procedure-review.js +109 -109
- package/src/lib/qms-templates.js +358 -326
- package/src/lib/qms.js +369 -369
- package/src/lib/quality-priority.js +100 -100
- package/src/lib/quality-state.js +92 -92
- package/src/lib/quality-workflow.js +65 -65
- package/src/lib/retrieval.js +159 -159
- package/src/lib/spc.js +127 -127
- package/src/lib/voice-hotwords.txt +22 -22
- package/src/lib/voice-text.js +13 -13
- package/src/lib/voice-worker.js +72 -72
- package/src/lib/voice.js +330 -330
- package/src/lib/workbench-notices.js +49 -49
- package/src/lib/workbench.js +103 -106
- package/src/package.json +3 -3
- package/src/tools/analysis.js +306 -306
- package/src/tools/data.js +596 -596
- package/src/tools/docs.js +430 -430
- package/src/tools/registry.js +57 -57
- package/tools-dsh.cjs +153 -153
- package//345/256/211/350/243/205/350/257/264/346/230/216.md +33 -25
- package//346/234/254/346/234/272/347/213/254/347/253/213/345/256/211/350/243/205/350/257/264/346/230/216.md +17 -17
- package//350/207/252/346/243/200.cjs +88 -88
- package/public/js/remote-knowledge.js +0 -165
- package/public/js/workbench-notices.js +0 -67
- package/public/remote-knowledge-help.html +0 -35
- package/public/remote-knowledge.css +0 -40
- package/src/lib/remote-knowledge.js +0 -284
package/src/lib/voice.js
CHANGED
|
@@ -1,330 +1,330 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const { createHash, randomUUID } = require('node:crypto');
|
|
4
|
-
const { createReadStream, createWriteStream } = require('node:fs');
|
|
5
|
-
const fs = require('node:fs/promises');
|
|
6
|
-
const { homedir } = require('node:os');
|
|
7
|
-
const path = require('node:path');
|
|
8
|
-
const { Transform } = require('node:stream');
|
|
9
|
-
const https = require('node:https');
|
|
10
|
-
const { execFile } = require('node:child_process');
|
|
11
|
-
const { promisify } = require('node:util');
|
|
12
|
-
const { pipeline } = require('node:stream/promises');
|
|
13
|
-
const { Worker } = require('node:worker_threads');
|
|
14
|
-
|
|
15
|
-
const REPO = 'csukuangfj/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30';
|
|
16
|
-
const MODEL = {
|
|
17
|
-
'encoder.int8.onnx': '5ac51e27981bb4dab01bb9be4958453ba50c3b61c063ddda0eab23fd3671aa4f',
|
|
18
|
-
'decoder.onnx': '06522ad63cec0fdf6809f4e1db9bb4f7d710c34582e3b35db62ac60eccafac7e',
|
|
19
|
-
'joiner.int8.onnx': 'b34584dc6f561089e1d747fedebb3765f2caa72c927ef54d7ca55e5ae40a814b',
|
|
20
|
-
'tokens.txt': '6193c7ea1c96d0d9a1e9652789b40d13a8a913b434a5451e93158f5a09fd6652',
|
|
21
|
-
};
|
|
22
|
-
const SOURCES = ['https://huggingface.co', 'https://hf-mirror.com'];
|
|
23
|
-
const RATE = 16000;
|
|
24
|
-
const MAX_SECONDS = 45;
|
|
25
|
-
const LIMIT = RATE * MAX_SECONDS * Float32Array.BYTES_PER_ELEMENT;
|
|
26
|
-
const fail = (message, status) => Object.assign(new Error(message), { status });
|
|
27
|
-
const supportDir = (app) => process.platform === 'win32'
|
|
28
|
-
? path.join(process.env.LOCALAPPDATA || path.join(homedir(), 'AppData', 'Local'), app)
|
|
29
|
-
: path.join(process.env.XDG_CACHE_HOME || path.join(homedir(), '.cache'), app);
|
|
30
|
-
|
|
31
|
-
async function matches(file, wanted) {
|
|
32
|
-
try {
|
|
33
|
-
const stat = await fs.stat(file);
|
|
34
|
-
if (!stat.isFile() || stat.size > 180 * 1024 * 1024) return false;
|
|
35
|
-
const hash = createHash('sha256');
|
|
36
|
-
for await (const chunk of createReadStream(file,{highWaterMark:4 * 1024 * 1024})) hash.update(chunk);
|
|
37
|
-
return hash.digest('hex') === wanted;
|
|
38
|
-
} catch { return false; }
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
async function modelAgent() {
|
|
42
|
-
const proxyEnv = { ...process.env };
|
|
43
|
-
if (process.platform === 'win32' && !proxyEnv.HTTPS_PROXY && !proxyEnv.https_proxy) {
|
|
44
|
-
// Respect the Windows manual proxy for these model downloads without changing Harness networking.
|
|
45
|
-
try {
|
|
46
|
-
const key = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
|
|
47
|
-
const { stdout } = await promisify(execFile)('reg.exe',['query',key],{windowsHide:true,timeout:3000});
|
|
48
|
-
if (/ProxyEnable\s+REG_DWORD\s+0x1\s/i.test(stdout)) {
|
|
49
|
-
const raw = /ProxyServer\s+REG_SZ\s+([^\r\n]+)/i.exec(stdout)?.[1]?.trim();
|
|
50
|
-
const proxy = raw?.includes('=') ? /(?:^|;)https=([^;]+)/i.exec(raw)?.[1] : raw;
|
|
51
|
-
if (proxy) {
|
|
52
|
-
const url = new URL(proxy.includes('://') ? proxy : 'http://' + proxy);
|
|
53
|
-
if (['http:','https:'].includes(url.protocol)) proxyEnv.HTTPS_PROXY = url.href;
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
} catch { /* Proxy unavailable, use direct HTTPS. */ }
|
|
57
|
-
}
|
|
58
|
-
return new https.Agent({ proxyEnv });
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async function openModel(url, abort, agent) {
|
|
62
|
-
const allowed = (hostname) => ['huggingface.co','hf.co','hf-mirror.com'].some((name) =>
|
|
63
|
-
hostname === name || hostname.endsWith('.' + name));
|
|
64
|
-
for (let hop = 0; hop < 6; hop++) {
|
|
65
|
-
const target = new URL(url);
|
|
66
|
-
if (target.protocol !== 'https:' || !allowed(target.hostname)) throw Error('unrecognized model host');
|
|
67
|
-
const response = await new Promise((resolve,reject) => {
|
|
68
|
-
https.get(target,{agent,signal:abort.signal},resolve).once('error',reject);
|
|
69
|
-
});
|
|
70
|
-
if (![301,302,303,307,308].includes(response.statusCode)) return response;
|
|
71
|
-
const next = response.headers.location;
|
|
72
|
-
response.resume();
|
|
73
|
-
if (!next) throw Error('invalid model redirect');
|
|
74
|
-
url = new URL(next, target).href;
|
|
75
|
-
}
|
|
76
|
-
throw Error('too many model redirects');
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
async function downloadModel(file, wanted, dest, onProgress, agent, signal) {
|
|
80
|
-
const work = dest + '.' + randomUUID() + '.part';
|
|
81
|
-
for (const host of SOURCES) {
|
|
82
|
-
signal.throwIfAborted();
|
|
83
|
-
const abort = new AbortController();
|
|
84
|
-
const cancel = () => abort.abort(signal.reason);
|
|
85
|
-
signal.addEventListener('abort',cancel,{ once:true });
|
|
86
|
-
let timer;
|
|
87
|
-
const resetTimer = () => {
|
|
88
|
-
clearTimeout(timer);
|
|
89
|
-
timer = setTimeout(() => abort.abort(), 45000);
|
|
90
|
-
timer.unref();
|
|
91
|
-
};
|
|
92
|
-
try {
|
|
93
|
-
resetTimer();
|
|
94
|
-
const source = await openModel(host + '/' + REPO + '/resolve/main/' + file + '?download=true', abort, agent);
|
|
95
|
-
if (source.statusCode !== 200) {
|
|
96
|
-
source.resume();
|
|
97
|
-
throw Error('model HTTP ' + source.statusCode);
|
|
98
|
-
}
|
|
99
|
-
const total = Number(source.headers['content-length']) || 0;
|
|
100
|
-
const hash = createHash('sha256');
|
|
101
|
-
let received = 0;
|
|
102
|
-
const tap = new Transform({
|
|
103
|
-
transform(chunk, encoding, callback) {
|
|
104
|
-
resetTimer();
|
|
105
|
-
received += chunk.length;
|
|
106
|
-
if (received > 180 * 1024 * 1024) return callback(Error('unexpected model size'));
|
|
107
|
-
hash.update(chunk);
|
|
108
|
-
onProgress({ file, received, total });
|
|
109
|
-
callback(null, chunk);
|
|
110
|
-
},
|
|
111
|
-
});
|
|
112
|
-
await pipeline(source, tap, createWriteStream(work, { flags:'wx' }), { signal:abort.signal });
|
|
113
|
-
if (hash.digest('hex') !== wanted) throw Error('model checksum mismatch');
|
|
114
|
-
await fs.rename(work,dest);
|
|
115
|
-
return;
|
|
116
|
-
} catch {
|
|
117
|
-
await fs.rm(work, { force:true }).catch(() => {});
|
|
118
|
-
} finally { clearTimeout(timer); signal.removeEventListener('abort',cancel); abort.abort(); }
|
|
119
|
-
}
|
|
120
|
-
throw fail('本机语音模型下载失败,请检查网络后重试。', 503);
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
function createVoice({ directory = path.join(supportDir('qip-real-workbench'),'models','zipformer-zh-2025-06-30') } = {}) {
|
|
124
|
-
const legacy = path.join(supportDir('qip-real'),'models','zipformer-zh-2025-06-30');
|
|
125
|
-
const reference = path.join(supportDir('dsh-total-quality-v3'),'models','zipformer-zh-2025-06-30');
|
|
126
|
-
const upstream = path.join(supportDir('dsh-voice-mode'), 'models', ...REPO.split('/'));
|
|
127
|
-
let task, preparation, modelDir, worker, idleTimer, nextId = 0, receiving = 0, allowDownload = false;
|
|
128
|
-
const pending = new Map();
|
|
129
|
-
const sessions = new Map();
|
|
130
|
-
let state = { phase:'setup' };
|
|
131
|
-
|
|
132
|
-
async function verify(dir) {
|
|
133
|
-
for (const [file, wanted] of Object.entries(MODEL)) if (!await matches(path.join(dir,file),wanted)) return false;
|
|
134
|
-
return true;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function prepare(download = true) {
|
|
138
|
-
if (state.phase === 'ready') return;
|
|
139
|
-
allowDownload ||= download;
|
|
140
|
-
if (task) return;
|
|
141
|
-
state = { phase:'checking' };
|
|
142
|
-
const { signal } = preparation = new AbortController();
|
|
143
|
-
task = (async () => {
|
|
144
|
-
try {
|
|
145
|
-
require.resolve('sherpa-onnx-node');
|
|
146
|
-
for (const cached of [directory,legacy,reference,upstream]) {
|
|
147
|
-
if (modelDir) break;
|
|
148
|
-
signal.throwIfAborted();
|
|
149
|
-
if (await verify(cached)) modelDir = cached;
|
|
150
|
-
}
|
|
151
|
-
signal.throwIfAborted();
|
|
152
|
-
if (!modelDir) {
|
|
153
|
-
if (!allowDownload) {
|
|
154
|
-
state = { phase:'setup' };
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
await fs.mkdir(directory, { recursive:true });
|
|
158
|
-
const agent = await modelAgent();
|
|
159
|
-
try {
|
|
160
|
-
for (const [file, digest] of Object.entries(MODEL)) {
|
|
161
|
-
const dest = path.join(directory,file);
|
|
162
|
-
if (await matches(dest,digest)) continue;
|
|
163
|
-
state = { phase:'downloading', file, received:0, total:0 };
|
|
164
|
-
await downloadModel(file,digest,dest,(progress) => { state = { phase:'downloading', ...progress }; },agent,signal);
|
|
165
|
-
}
|
|
166
|
-
} finally { agent.destroy(); }
|
|
167
|
-
modelDir = directory;
|
|
168
|
-
}
|
|
169
|
-
signal.throwIfAborted();
|
|
170
|
-
state = { phase:'warming' };
|
|
171
|
-
await processAudio(getWorker(), {}, signal);
|
|
172
|
-
signal.throwIfAborted();
|
|
173
|
-
state = { phase:'ready' };
|
|
174
|
-
} catch (error) {
|
|
175
|
-
if (signal.aborted) return;
|
|
176
|
-
state = { phase:'error', error: error.status ? error.message :
|
|
177
|
-
'本地语音识别组件暂不可用。请检查插件安装或本机磁盘空间。' };
|
|
178
|
-
console.warn('[quality-voice] preparation:', error.code || error.message);
|
|
179
|
-
}
|
|
180
|
-
})().finally(() => { task = null; preparation = null; allowDownload = false; });
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function discard(instance, error) {
|
|
184
|
-
if (worker !== instance) return;
|
|
185
|
-
worker = null;
|
|
186
|
-
if (state.phase === 'ready') state = { phase:'setup' };
|
|
187
|
-
clearTimeout(idleTimer);
|
|
188
|
-
for (const id of sessions.keys()) closeSession(id);
|
|
189
|
-
for (const row of pending.values()) row.finish(error);
|
|
190
|
-
void instance.terminate();
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function getWorker() {
|
|
194
|
-
clearTimeout(idleTimer);
|
|
195
|
-
if (worker) return worker;
|
|
196
|
-
const instance = new Worker(path.join(__dirname, 'voice-worker.js'), { workerData:{ modelDir, rate:RATE } });
|
|
197
|
-
worker = instance;
|
|
198
|
-
instance.on('error', () => discard(instance, fail('本地识别引擎启动失败,请重试。', 502)));
|
|
199
|
-
instance.on('exit', () => discard(instance, fail('本地识别进程已退出,请重试。', 502)));
|
|
200
|
-
instance.on('message', ({ id, text, error }) => {
|
|
201
|
-
if (worker !== instance) return;
|
|
202
|
-
pending.get(id)?.finish(error ? fail('本地识别本段录音失败,请重试。', 502) : null, text);
|
|
203
|
-
});
|
|
204
|
-
instance.unref();
|
|
205
|
-
return instance;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
async function readPcm(req, limit) {
|
|
209
|
-
if (req.headers['content-type'] !== 'application/octet-stream') { req.resume(); throw fail('音频格式不正确。', 415); }
|
|
210
|
-
if (Number(req.headers['content-length']) > limit) { req.resume(); throw fail('单次录音最多 45 秒。', 413); }
|
|
211
|
-
const chunks = [];
|
|
212
|
-
let size = 0;
|
|
213
|
-
for await (const chunk of req.iterator({ destroyOnReturn:false })) {
|
|
214
|
-
size += chunk.length;
|
|
215
|
-
if (size > limit) { req.resume(); throw fail('单次录音最多 45 秒。', 413); }
|
|
216
|
-
chunks.push(chunk);
|
|
217
|
-
}
|
|
218
|
-
if (size % Float32Array.BYTES_PER_ELEMENT) throw fail('音频格式不正确。', 400);
|
|
219
|
-
const raw = Buffer.concat(chunks,size);
|
|
220
|
-
return raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
function requireReady() {
|
|
224
|
-
if (state.phase !== 'ready') throw fail('请先准备本地语音模型。', 409);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
async function transcribe(req, signal) {
|
|
228
|
-
requireReady();
|
|
229
|
-
if (pending.size + receiving >= 2) { req.resume(); throw fail('本地识别正在处理其他录音,请稍后重试。', 429); }
|
|
230
|
-
let bytes;
|
|
231
|
-
receiving++;
|
|
232
|
-
try { bytes = await readPcm(req,LIMIT); }
|
|
233
|
-
finally { receiving--; }
|
|
234
|
-
signal.throwIfAborted();
|
|
235
|
-
if (bytes.byteLength < RATE) throw fail('录音太短,请再说一次。', 400);
|
|
236
|
-
if (pending.size >= 2) throw fail('本地识别正在处理其他录音,请稍后重试。', 429);
|
|
237
|
-
requireReady();
|
|
238
|
-
return processAudio(getWorker(),{ bytes },signal);
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function refreshSession(id, row) {
|
|
242
|
-
clearTimeout(row.timer);
|
|
243
|
-
row.timer = setTimeout(() => closeSession(id), 75_000);
|
|
244
|
-
row.timer.unref();
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
function startSession(owner) {
|
|
248
|
-
requireReady();
|
|
249
|
-
if (sessions.size >= 2) throw fail('本地识别正在处理其他录音,请稍后重试。', 429);
|
|
250
|
-
const id = randomUUID();
|
|
251
|
-
const row = { owner, size:0, busy:false };
|
|
252
|
-
sessions.set(id,row);
|
|
253
|
-
refreshSession(id,row);
|
|
254
|
-
return id;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
function closeSession(id, owner) {
|
|
258
|
-
const row = sessions.get(id);
|
|
259
|
-
if (!row || (owner !== undefined && row.owner !== owner)) return;
|
|
260
|
-
sessions.delete(id);
|
|
261
|
-
clearTimeout(row.timer);
|
|
262
|
-
worker?.postMessage({ sessionId:id, cancel:true });
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
async function streamAudio(req, signal, owner, id, final) {
|
|
266
|
-
const row = sessions.get(id);
|
|
267
|
-
if (!row || row.owner !== owner) { req.resume(); throw fail('本次录音已结束,请重新录音。', 404); }
|
|
268
|
-
if (row.busy) { req.resume(); throw fail('上一段录音正在处理,请稍后重试。', 409); }
|
|
269
|
-
row.busy = true;
|
|
270
|
-
refreshSession(id,row);
|
|
271
|
-
try {
|
|
272
|
-
const bytes = await readPcm(req,LIMIT - row.size);
|
|
273
|
-
signal.throwIfAborted();
|
|
274
|
-
if (sessions.get(id) !== row) throw fail('本次录音已结束,请重新录音。', 404);
|
|
275
|
-
if (!final && !bytes.byteLength) throw fail('录音片段为空。', 400);
|
|
276
|
-
row.size += bytes.byteLength;
|
|
277
|
-
if (final && row.size < RATE) throw fail('录音太短,请再说一次。', 400);
|
|
278
|
-
requireReady();
|
|
279
|
-
return await processAudio(getWorker(),{ bytes, sessionId:id, final },signal);
|
|
280
|
-
} catch (error) {
|
|
281
|
-
closeSession(id);
|
|
282
|
-
throw error;
|
|
283
|
-
} finally {
|
|
284
|
-
if (final) closeSession(id);
|
|
285
|
-
else if (sessions.get(id) === row) { row.busy = false; refreshSession(id,row); }
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
function processAudio(instance,message,signal) {
|
|
290
|
-
signal.throwIfAborted();
|
|
291
|
-
const { bytes } = message;
|
|
292
|
-
instance.ref();
|
|
293
|
-
const id = ++nextId;
|
|
294
|
-
return new Promise((resolve,reject) => {
|
|
295
|
-
const timer = setTimeout(() => discard(instance, fail(bytes ? '本地转写超时,请说短一点再试。' : '本地识别引擎启动超时,请重试。', 504)), 60000);
|
|
296
|
-
timer.unref();
|
|
297
|
-
const cancel = () => {
|
|
298
|
-
// Keep the slot occupied until the worker finishes this utterance.
|
|
299
|
-
reject(signal.reason);
|
|
300
|
-
};
|
|
301
|
-
const finish = (error,text) => {
|
|
302
|
-
signal.removeEventListener('abort',cancel);
|
|
303
|
-
clearTimeout(timer);
|
|
304
|
-
pending.delete(id);
|
|
305
|
-
if (!pending.size && worker === instance) {
|
|
306
|
-
instance.unref();
|
|
307
|
-
idleTimer = setTimeout(() => discard(instance), 5 * 60000);
|
|
308
|
-
idleTimer.unref();
|
|
309
|
-
}
|
|
310
|
-
if (error) reject(error);
|
|
311
|
-
else resolve({ text });
|
|
312
|
-
};
|
|
313
|
-
pending.set(id,{finish});
|
|
314
|
-
signal.addEventListener('abort',cancel,{once:true});
|
|
315
|
-
try { instance.postMessage({ id, ...message }, bytes ? [bytes] : []); }
|
|
316
|
-
catch (error) { finish(error); }
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
function close() {
|
|
321
|
-
preparation?.abort();
|
|
322
|
-
if (worker) discard(worker, fail('语音服务已重新加载,请重试。',503));
|
|
323
|
-
state = { phase:'setup' };
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
return { prepare, status:() => ({ ...state, maxSeconds:MAX_SECONDS }), transcribe,
|
|
327
|
-
startSession, streamAudio, closeSession, close };
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
module.exports = { createVoice };
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createHash, randomUUID } = require('node:crypto');
|
|
4
|
+
const { createReadStream, createWriteStream } = require('node:fs');
|
|
5
|
+
const fs = require('node:fs/promises');
|
|
6
|
+
const { homedir } = require('node:os');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const { Transform } = require('node:stream');
|
|
9
|
+
const https = require('node:https');
|
|
10
|
+
const { execFile } = require('node:child_process');
|
|
11
|
+
const { promisify } = require('node:util');
|
|
12
|
+
const { pipeline } = require('node:stream/promises');
|
|
13
|
+
const { Worker } = require('node:worker_threads');
|
|
14
|
+
|
|
15
|
+
const REPO = 'csukuangfj/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30';
|
|
16
|
+
const MODEL = {
|
|
17
|
+
'encoder.int8.onnx': '5ac51e27981bb4dab01bb9be4958453ba50c3b61c063ddda0eab23fd3671aa4f',
|
|
18
|
+
'decoder.onnx': '06522ad63cec0fdf6809f4e1db9bb4f7d710c34582e3b35db62ac60eccafac7e',
|
|
19
|
+
'joiner.int8.onnx': 'b34584dc6f561089e1d747fedebb3765f2caa72c927ef54d7ca55e5ae40a814b',
|
|
20
|
+
'tokens.txt': '6193c7ea1c96d0d9a1e9652789b40d13a8a913b434a5451e93158f5a09fd6652',
|
|
21
|
+
};
|
|
22
|
+
const SOURCES = ['https://huggingface.co', 'https://hf-mirror.com'];
|
|
23
|
+
const RATE = 16000;
|
|
24
|
+
const MAX_SECONDS = 45;
|
|
25
|
+
const LIMIT = RATE * MAX_SECONDS * Float32Array.BYTES_PER_ELEMENT;
|
|
26
|
+
const fail = (message, status) => Object.assign(new Error(message), { status });
|
|
27
|
+
const supportDir = (app) => process.platform === 'win32'
|
|
28
|
+
? path.join(process.env.LOCALAPPDATA || path.join(homedir(), 'AppData', 'Local'), app)
|
|
29
|
+
: path.join(process.env.XDG_CACHE_HOME || path.join(homedir(), '.cache'), app);
|
|
30
|
+
|
|
31
|
+
async function matches(file, wanted) {
|
|
32
|
+
try {
|
|
33
|
+
const stat = await fs.stat(file);
|
|
34
|
+
if (!stat.isFile() || stat.size > 180 * 1024 * 1024) return false;
|
|
35
|
+
const hash = createHash('sha256');
|
|
36
|
+
for await (const chunk of createReadStream(file,{highWaterMark:4 * 1024 * 1024})) hash.update(chunk);
|
|
37
|
+
return hash.digest('hex') === wanted;
|
|
38
|
+
} catch { return false; }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function modelAgent() {
|
|
42
|
+
const proxyEnv = { ...process.env };
|
|
43
|
+
if (process.platform === 'win32' && !proxyEnv.HTTPS_PROXY && !proxyEnv.https_proxy) {
|
|
44
|
+
// Respect the Windows manual proxy for these model downloads without changing Harness networking.
|
|
45
|
+
try {
|
|
46
|
+
const key = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
|
|
47
|
+
const { stdout } = await promisify(execFile)('reg.exe',['query',key],{windowsHide:true,timeout:3000});
|
|
48
|
+
if (/ProxyEnable\s+REG_DWORD\s+0x1\s/i.test(stdout)) {
|
|
49
|
+
const raw = /ProxyServer\s+REG_SZ\s+([^\r\n]+)/i.exec(stdout)?.[1]?.trim();
|
|
50
|
+
const proxy = raw?.includes('=') ? /(?:^|;)https=([^;]+)/i.exec(raw)?.[1] : raw;
|
|
51
|
+
if (proxy) {
|
|
52
|
+
const url = new URL(proxy.includes('://') ? proxy : 'http://' + proxy);
|
|
53
|
+
if (['http:','https:'].includes(url.protocol)) proxyEnv.HTTPS_PROXY = url.href;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
} catch { /* Proxy unavailable, use direct HTTPS. */ }
|
|
57
|
+
}
|
|
58
|
+
return new https.Agent({ proxyEnv });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function openModel(url, abort, agent) {
|
|
62
|
+
const allowed = (hostname) => ['huggingface.co','hf.co','hf-mirror.com'].some((name) =>
|
|
63
|
+
hostname === name || hostname.endsWith('.' + name));
|
|
64
|
+
for (let hop = 0; hop < 6; hop++) {
|
|
65
|
+
const target = new URL(url);
|
|
66
|
+
if (target.protocol !== 'https:' || !allowed(target.hostname)) throw Error('unrecognized model host');
|
|
67
|
+
const response = await new Promise((resolve,reject) => {
|
|
68
|
+
https.get(target,{agent,signal:abort.signal},resolve).once('error',reject);
|
|
69
|
+
});
|
|
70
|
+
if (![301,302,303,307,308].includes(response.statusCode)) return response;
|
|
71
|
+
const next = response.headers.location;
|
|
72
|
+
response.resume();
|
|
73
|
+
if (!next) throw Error('invalid model redirect');
|
|
74
|
+
url = new URL(next, target).href;
|
|
75
|
+
}
|
|
76
|
+
throw Error('too many model redirects');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function downloadModel(file, wanted, dest, onProgress, agent, signal) {
|
|
80
|
+
const work = dest + '.' + randomUUID() + '.part';
|
|
81
|
+
for (const host of SOURCES) {
|
|
82
|
+
signal.throwIfAborted();
|
|
83
|
+
const abort = new AbortController();
|
|
84
|
+
const cancel = () => abort.abort(signal.reason);
|
|
85
|
+
signal.addEventListener('abort',cancel,{ once:true });
|
|
86
|
+
let timer;
|
|
87
|
+
const resetTimer = () => {
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
timer = setTimeout(() => abort.abort(), 45000);
|
|
90
|
+
timer.unref();
|
|
91
|
+
};
|
|
92
|
+
try {
|
|
93
|
+
resetTimer();
|
|
94
|
+
const source = await openModel(host + '/' + REPO + '/resolve/main/' + file + '?download=true', abort, agent);
|
|
95
|
+
if (source.statusCode !== 200) {
|
|
96
|
+
source.resume();
|
|
97
|
+
throw Error('model HTTP ' + source.statusCode);
|
|
98
|
+
}
|
|
99
|
+
const total = Number(source.headers['content-length']) || 0;
|
|
100
|
+
const hash = createHash('sha256');
|
|
101
|
+
let received = 0;
|
|
102
|
+
const tap = new Transform({
|
|
103
|
+
transform(chunk, encoding, callback) {
|
|
104
|
+
resetTimer();
|
|
105
|
+
received += chunk.length;
|
|
106
|
+
if (received > 180 * 1024 * 1024) return callback(Error('unexpected model size'));
|
|
107
|
+
hash.update(chunk);
|
|
108
|
+
onProgress({ file, received, total });
|
|
109
|
+
callback(null, chunk);
|
|
110
|
+
},
|
|
111
|
+
});
|
|
112
|
+
await pipeline(source, tap, createWriteStream(work, { flags:'wx' }), { signal:abort.signal });
|
|
113
|
+
if (hash.digest('hex') !== wanted) throw Error('model checksum mismatch');
|
|
114
|
+
await fs.rename(work,dest);
|
|
115
|
+
return;
|
|
116
|
+
} catch {
|
|
117
|
+
await fs.rm(work, { force:true }).catch(() => {});
|
|
118
|
+
} finally { clearTimeout(timer); signal.removeEventListener('abort',cancel); abort.abort(); }
|
|
119
|
+
}
|
|
120
|
+
throw fail('本机语音模型下载失败,请检查网络后重试。', 503);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function createVoice({ directory = path.join(supportDir('qip-real-workbench'),'models','zipformer-zh-2025-06-30') } = {}) {
|
|
124
|
+
const legacy = path.join(supportDir('qip-real'),'models','zipformer-zh-2025-06-30');
|
|
125
|
+
const reference = path.join(supportDir('dsh-total-quality-v3'),'models','zipformer-zh-2025-06-30');
|
|
126
|
+
const upstream = path.join(supportDir('dsh-voice-mode'), 'models', ...REPO.split('/'));
|
|
127
|
+
let task, preparation, modelDir, worker, idleTimer, nextId = 0, receiving = 0, allowDownload = false;
|
|
128
|
+
const pending = new Map();
|
|
129
|
+
const sessions = new Map();
|
|
130
|
+
let state = { phase:'setup' };
|
|
131
|
+
|
|
132
|
+
async function verify(dir) {
|
|
133
|
+
for (const [file, wanted] of Object.entries(MODEL)) if (!await matches(path.join(dir,file),wanted)) return false;
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function prepare(download = true) {
|
|
138
|
+
if (state.phase === 'ready') return;
|
|
139
|
+
allowDownload ||= download;
|
|
140
|
+
if (task) return;
|
|
141
|
+
state = { phase:'checking' };
|
|
142
|
+
const { signal } = preparation = new AbortController();
|
|
143
|
+
task = (async () => {
|
|
144
|
+
try {
|
|
145
|
+
require.resolve('sherpa-onnx-node');
|
|
146
|
+
for (const cached of [directory,legacy,reference,upstream]) {
|
|
147
|
+
if (modelDir) break;
|
|
148
|
+
signal.throwIfAborted();
|
|
149
|
+
if (await verify(cached)) modelDir = cached;
|
|
150
|
+
}
|
|
151
|
+
signal.throwIfAborted();
|
|
152
|
+
if (!modelDir) {
|
|
153
|
+
if (!allowDownload) {
|
|
154
|
+
state = { phase:'setup' };
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
await fs.mkdir(directory, { recursive:true });
|
|
158
|
+
const agent = await modelAgent();
|
|
159
|
+
try {
|
|
160
|
+
for (const [file, digest] of Object.entries(MODEL)) {
|
|
161
|
+
const dest = path.join(directory,file);
|
|
162
|
+
if (await matches(dest,digest)) continue;
|
|
163
|
+
state = { phase:'downloading', file, received:0, total:0 };
|
|
164
|
+
await downloadModel(file,digest,dest,(progress) => { state = { phase:'downloading', ...progress }; },agent,signal);
|
|
165
|
+
}
|
|
166
|
+
} finally { agent.destroy(); }
|
|
167
|
+
modelDir = directory;
|
|
168
|
+
}
|
|
169
|
+
signal.throwIfAborted();
|
|
170
|
+
state = { phase:'warming' };
|
|
171
|
+
await processAudio(getWorker(), {}, signal);
|
|
172
|
+
signal.throwIfAborted();
|
|
173
|
+
state = { phase:'ready' };
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (signal.aborted) return;
|
|
176
|
+
state = { phase:'error', error: error.status ? error.message :
|
|
177
|
+
'本地语音识别组件暂不可用。请检查插件安装或本机磁盘空间。' };
|
|
178
|
+
console.warn('[quality-voice] preparation:', error.code || error.message);
|
|
179
|
+
}
|
|
180
|
+
})().finally(() => { task = null; preparation = null; allowDownload = false; });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function discard(instance, error) {
|
|
184
|
+
if (worker !== instance) return;
|
|
185
|
+
worker = null;
|
|
186
|
+
if (state.phase === 'ready') state = { phase:'setup' };
|
|
187
|
+
clearTimeout(idleTimer);
|
|
188
|
+
for (const id of sessions.keys()) closeSession(id);
|
|
189
|
+
for (const row of pending.values()) row.finish(error);
|
|
190
|
+
void instance.terminate();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function getWorker() {
|
|
194
|
+
clearTimeout(idleTimer);
|
|
195
|
+
if (worker) return worker;
|
|
196
|
+
const instance = new Worker(path.join(__dirname, 'voice-worker.js'), { workerData:{ modelDir, rate:RATE } });
|
|
197
|
+
worker = instance;
|
|
198
|
+
instance.on('error', () => discard(instance, fail('本地识别引擎启动失败,请重试。', 502)));
|
|
199
|
+
instance.on('exit', () => discard(instance, fail('本地识别进程已退出,请重试。', 502)));
|
|
200
|
+
instance.on('message', ({ id, text, error }) => {
|
|
201
|
+
if (worker !== instance) return;
|
|
202
|
+
pending.get(id)?.finish(error ? fail('本地识别本段录音失败,请重试。', 502) : null, text);
|
|
203
|
+
});
|
|
204
|
+
instance.unref();
|
|
205
|
+
return instance;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function readPcm(req, limit) {
|
|
209
|
+
if (req.headers['content-type'] !== 'application/octet-stream') { req.resume(); throw fail('音频格式不正确。', 415); }
|
|
210
|
+
if (Number(req.headers['content-length']) > limit) { req.resume(); throw fail('单次录音最多 45 秒。', 413); }
|
|
211
|
+
const chunks = [];
|
|
212
|
+
let size = 0;
|
|
213
|
+
for await (const chunk of req.iterator({ destroyOnReturn:false })) {
|
|
214
|
+
size += chunk.length;
|
|
215
|
+
if (size > limit) { req.resume(); throw fail('单次录音最多 45 秒。', 413); }
|
|
216
|
+
chunks.push(chunk);
|
|
217
|
+
}
|
|
218
|
+
if (size % Float32Array.BYTES_PER_ELEMENT) throw fail('音频格式不正确。', 400);
|
|
219
|
+
const raw = Buffer.concat(chunks,size);
|
|
220
|
+
return raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function requireReady() {
|
|
224
|
+
if (state.phase !== 'ready') throw fail('请先准备本地语音模型。', 409);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function transcribe(req, signal) {
|
|
228
|
+
requireReady();
|
|
229
|
+
if (pending.size + receiving >= 2) { req.resume(); throw fail('本地识别正在处理其他录音,请稍后重试。', 429); }
|
|
230
|
+
let bytes;
|
|
231
|
+
receiving++;
|
|
232
|
+
try { bytes = await readPcm(req,LIMIT); }
|
|
233
|
+
finally { receiving--; }
|
|
234
|
+
signal.throwIfAborted();
|
|
235
|
+
if (bytes.byteLength < RATE) throw fail('录音太短,请再说一次。', 400);
|
|
236
|
+
if (pending.size >= 2) throw fail('本地识别正在处理其他录音,请稍后重试。', 429);
|
|
237
|
+
requireReady();
|
|
238
|
+
return processAudio(getWorker(),{ bytes },signal);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function refreshSession(id, row) {
|
|
242
|
+
clearTimeout(row.timer);
|
|
243
|
+
row.timer = setTimeout(() => closeSession(id), 75_000);
|
|
244
|
+
row.timer.unref();
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function startSession(owner) {
|
|
248
|
+
requireReady();
|
|
249
|
+
if (sessions.size >= 2) throw fail('本地识别正在处理其他录音,请稍后重试。', 429);
|
|
250
|
+
const id = randomUUID();
|
|
251
|
+
const row = { owner, size:0, busy:false };
|
|
252
|
+
sessions.set(id,row);
|
|
253
|
+
refreshSession(id,row);
|
|
254
|
+
return id;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function closeSession(id, owner) {
|
|
258
|
+
const row = sessions.get(id);
|
|
259
|
+
if (!row || (owner !== undefined && row.owner !== owner)) return;
|
|
260
|
+
sessions.delete(id);
|
|
261
|
+
clearTimeout(row.timer);
|
|
262
|
+
worker?.postMessage({ sessionId:id, cancel:true });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function streamAudio(req, signal, owner, id, final) {
|
|
266
|
+
const row = sessions.get(id);
|
|
267
|
+
if (!row || row.owner !== owner) { req.resume(); throw fail('本次录音已结束,请重新录音。', 404); }
|
|
268
|
+
if (row.busy) { req.resume(); throw fail('上一段录音正在处理,请稍后重试。', 409); }
|
|
269
|
+
row.busy = true;
|
|
270
|
+
refreshSession(id,row);
|
|
271
|
+
try {
|
|
272
|
+
const bytes = await readPcm(req,LIMIT - row.size);
|
|
273
|
+
signal.throwIfAborted();
|
|
274
|
+
if (sessions.get(id) !== row) throw fail('本次录音已结束,请重新录音。', 404);
|
|
275
|
+
if (!final && !bytes.byteLength) throw fail('录音片段为空。', 400);
|
|
276
|
+
row.size += bytes.byteLength;
|
|
277
|
+
if (final && row.size < RATE) throw fail('录音太短,请再说一次。', 400);
|
|
278
|
+
requireReady();
|
|
279
|
+
return await processAudio(getWorker(),{ bytes, sessionId:id, final },signal);
|
|
280
|
+
} catch (error) {
|
|
281
|
+
closeSession(id);
|
|
282
|
+
throw error;
|
|
283
|
+
} finally {
|
|
284
|
+
if (final) closeSession(id);
|
|
285
|
+
else if (sessions.get(id) === row) { row.busy = false; refreshSession(id,row); }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function processAudio(instance,message,signal) {
|
|
290
|
+
signal.throwIfAborted();
|
|
291
|
+
const { bytes } = message;
|
|
292
|
+
instance.ref();
|
|
293
|
+
const id = ++nextId;
|
|
294
|
+
return new Promise((resolve,reject) => {
|
|
295
|
+
const timer = setTimeout(() => discard(instance, fail(bytes ? '本地转写超时,请说短一点再试。' : '本地识别引擎启动超时,请重试。', 504)), 60000);
|
|
296
|
+
timer.unref();
|
|
297
|
+
const cancel = () => {
|
|
298
|
+
// Keep the slot occupied until the worker finishes this utterance.
|
|
299
|
+
reject(signal.reason);
|
|
300
|
+
};
|
|
301
|
+
const finish = (error,text) => {
|
|
302
|
+
signal.removeEventListener('abort',cancel);
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
pending.delete(id);
|
|
305
|
+
if (!pending.size && worker === instance) {
|
|
306
|
+
instance.unref();
|
|
307
|
+
idleTimer = setTimeout(() => discard(instance), 5 * 60000);
|
|
308
|
+
idleTimer.unref();
|
|
309
|
+
}
|
|
310
|
+
if (error) reject(error);
|
|
311
|
+
else resolve({ text });
|
|
312
|
+
};
|
|
313
|
+
pending.set(id,{finish});
|
|
314
|
+
signal.addEventListener('abort',cancel,{once:true});
|
|
315
|
+
try { instance.postMessage({ id, ...message }, bytes ? [bytes] : []); }
|
|
316
|
+
catch (error) { finish(error); }
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function close() {
|
|
321
|
+
preparation?.abort();
|
|
322
|
+
if (worker) discard(worker, fail('语音服务已重新加载,请重试。',503));
|
|
323
|
+
state = { phase:'setup' };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
return { prepare, status:() => ({ ...state, maxSeconds:MAX_SECONDS }), transcribe,
|
|
327
|
+
startSession, streamAudio, closeSession, close };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
module.exports = { createVoice };
|