dsh-folia 4.26.0-pre.16 → 4.26.0-pre.18
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/asr/asr-local.js +166 -0
- package/lib/asr/asr-worker.cjs +169 -0
- package/lib/routes/pet-chat.js +127 -59
- package/lib/voice/record.js +6 -1
- package/package.json +3 -1
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* asr-local.js — 本地 STT 运行时:下载/校验/启动 worker(宿主侧,普通 node 进程)。
|
|
3
|
+
*
|
|
4
|
+
* 设计约束(和 tts 那套一致):
|
|
5
|
+
* · 资源不进 npm 包,放站点 R2,按 manifest 逐文件下载(带 sha256 校验、可续传)
|
|
6
|
+
* · **不能**在本进程里 require sherpa(Electron 里 native addon 会抛
|
|
7
|
+
* `External buffers are not allowed`)⇒ 一律走 node.exe 子进程 + NDJSON
|
|
8
|
+
* · 用户零操作:第一次用语音时自动下载,进度通过 onProgress 回给上层
|
|
9
|
+
*
|
|
10
|
+
* manifest 形状(站点 /media/asr/v1/manifest.json):
|
|
11
|
+
* { "version":"v1", "sampleRate":16000,
|
|
12
|
+
* "files":[ { "key":"asr/v1/models/sensevoice/model.int8.onnx", "size":123, "sha256":"…" } ] }
|
|
13
|
+
* key 同时也是相对 /media/ 的路径(便于复用别的包里的文件,例如 node.exe)。
|
|
14
|
+
*/
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import { createWriteStream, createReadStream, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
17
|
+
import { spawn } from 'node:child_process';
|
|
18
|
+
import { dirname, join } from 'node:path';
|
|
19
|
+
import { Readable } from 'node:stream';
|
|
20
|
+
import { pipeline } from 'node:stream/promises';
|
|
21
|
+
|
|
22
|
+
const MEDIA_BASE = 'https://folia-5ve.pages.dev/media/';
|
|
23
|
+
const DEFAULT_MANIFEST = MEDIA_BASE + 'asr/v1/manifest.json';
|
|
24
|
+
|
|
25
|
+
/** 下载一个文件到 dest(先写 .part,校验通过再改名;支持 Range 续传)。 */
|
|
26
|
+
async function downloadOne(url, dest, expectedSize, onBytes) {
|
|
27
|
+
const part = dest + '.part';
|
|
28
|
+
let start = 0;
|
|
29
|
+
if (existsSync(part)) start = statSync(part).size;
|
|
30
|
+
if (existsSync(dest) && expectedSize > 0 && statSync(dest).size === expectedSize) {
|
|
31
|
+
if (typeof onBytes === 'function') onBytes(expectedSize);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const headers = {};
|
|
35
|
+
if (start > 0) headers.Range = `bytes=${start}-`;
|
|
36
|
+
const resp = await fetch(url, { headers });
|
|
37
|
+
if (!resp.ok && resp.status !== 206) throw new Error(`下载失败 ${resp.status} ${url}`);
|
|
38
|
+
if (resp.status !== 206) start = 0; // 服务器不支持续传 ⇒ 重头写
|
|
39
|
+
await pipeline(Readable.fromWeb(resp.body), createWriteStream(part, { flags: start > 0 ? 'a' : 'w' }));
|
|
40
|
+
const size = statSync(part).size;
|
|
41
|
+
if (expectedSize > 0 && size !== expectedSize) {
|
|
42
|
+
throw new Error(`大小不符:${dest} 期望 ${expectedSize} 实际 ${size}`);
|
|
43
|
+
}
|
|
44
|
+
rmSync(dest, { force: true });
|
|
45
|
+
renameSync(part, dest);
|
|
46
|
+
if (typeof onBytes === 'function') onBytes(expectedSize - start);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 校验 sha256(不匹配则删掉重来一次)。 */
|
|
50
|
+
async function verifyOrDrop(file, sha256) {
|
|
51
|
+
if (!sha256) return true;
|
|
52
|
+
if (!existsSync(file)) return false;
|
|
53
|
+
const hash = createHash('sha256');
|
|
54
|
+
await pipeline(createReadStream(file), hash);
|
|
55
|
+
const actual = hash.digest('hex');
|
|
56
|
+
if (actual === String(sha256).toLowerCase()) return true;
|
|
57
|
+
rmSync(file, { force: true });
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 确保运行时完整(缺什么下什么)。
|
|
63
|
+
* @returns {Promise<{ root: string, manifest: object }>}
|
|
64
|
+
*/
|
|
65
|
+
export async function ensureInstalled(root, options = {}) {
|
|
66
|
+
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : null;
|
|
67
|
+
const manifestUrl = options.manifestUrl || DEFAULT_MANIFEST;
|
|
68
|
+
const resp = await fetch(manifestUrl, { cache: 'no-store' });
|
|
69
|
+
if (!resp.ok) throw new Error(`manifest 获取失败 ${resp.status}`);
|
|
70
|
+
const manifest = await resp.json();
|
|
71
|
+
const files = Array.isArray(manifest.files) ? manifest.files : [];
|
|
72
|
+
const total = files.reduce((sum, f) => sum + (Number(f.size) || 0), 0);
|
|
73
|
+
let done = 0;
|
|
74
|
+
for (const file of files) {
|
|
75
|
+
const dest = join(root, ...String(file.key).split('/').slice(2)); // 去掉 'asr/v1/'
|
|
76
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
77
|
+
const ok = await verifyOrDrop(dest, file.sha256);
|
|
78
|
+
if (!ok) {
|
|
79
|
+
await downloadOne(MEDIA_BASE + file.key, dest, Number(file.size) || 0, (n) => {
|
|
80
|
+
done += n;
|
|
81
|
+
if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key });
|
|
82
|
+
});
|
|
83
|
+
const verified = await verifyOrDrop(dest, file.sha256);
|
|
84
|
+
if (!verified) throw new Error(`校验失败:${file.key}`);
|
|
85
|
+
} else {
|
|
86
|
+
done += Number(file.size) || 0;
|
|
87
|
+
if (onProgress) onProgress({ doneBytes: done, totalBytes: total, file: file.key });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { root, manifest };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** worker 运行所需的路径(相对安装根)。 */
|
|
94
|
+
function workerPaths(root) {
|
|
95
|
+
return {
|
|
96
|
+
nodeExe: join(root, 'runtime', 'node.exe'),
|
|
97
|
+
worker: join(root, 'runtime', 'asr-worker.cjs'),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 启动 worker(或复用已启动的)。返回 { request(wavPath) }。
|
|
103
|
+
* 协议见 lib/asr/asr-worker.cjs;这里只做进程管理与超时。
|
|
104
|
+
*/
|
|
105
|
+
export function startWorker(root) {
|
|
106
|
+
const { nodeExe, worker } = workerPaths(root);
|
|
107
|
+
if (!existsSync(nodeExe)) throw new Error('缺少 runtime/node.exe');
|
|
108
|
+
if (!existsSync(worker)) throw new Error('缺少 runtime/asr-worker.cjs');
|
|
109
|
+
const child = spawn(nodeExe, [worker, '--model-dir', root], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
110
|
+
const pending = new Map();
|
|
111
|
+
let seq = 0;
|
|
112
|
+
let buffer = '';
|
|
113
|
+
let ready = false;
|
|
114
|
+
|
|
115
|
+
child.stdout.setEncoding('utf8');
|
|
116
|
+
child.stdout.on('data', (chunk) => {
|
|
117
|
+
buffer += chunk;
|
|
118
|
+
for (;;) {
|
|
119
|
+
const cut = buffer.indexOf('\n');
|
|
120
|
+
if (cut < 0) break;
|
|
121
|
+
const line = buffer.slice(0, cut).trim();
|
|
122
|
+
buffer = buffer.slice(cut + 1);
|
|
123
|
+
if (!line) continue;
|
|
124
|
+
let msg = null;
|
|
125
|
+
try { msg = JSON.parse(line); } catch { continue; }
|
|
126
|
+
if (msg && msg.ready) { ready = true; continue; }
|
|
127
|
+
const key = msg && msg.id !== undefined ? String(msg.id) : '';
|
|
128
|
+
if (key && pending.has(key)) {
|
|
129
|
+
const { resolve, timer } = pending.get(key);
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
pending.delete(key);
|
|
132
|
+
resolve(msg);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
child.on('error', (error) => { lastError = String((error && error.message) || error); });
|
|
137
|
+
child.stderr.setEncoding('utf8');
|
|
138
|
+
let lastError = '';
|
|
139
|
+
child.stderr.on('data', (chunk) => { lastError = (lastError + chunk).slice(-2000); });
|
|
140
|
+
|
|
141
|
+
const request = (wavPath, timeoutMs = 30000) => new Promise((resolve, reject) => {
|
|
142
|
+
const id = String(++seq);
|
|
143
|
+
const timer = setTimeout(() => {
|
|
144
|
+
pending.delete(id);
|
|
145
|
+
reject(new Error('识别超时'));
|
|
146
|
+
}, timeoutMs);
|
|
147
|
+
pending.set(id, { resolve, timer });
|
|
148
|
+
child.stdin.write(JSON.stringify({ id, wavPath }) + '\n', (err) => {
|
|
149
|
+
if (err) {
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
pending.delete(id);
|
|
152
|
+
reject(err);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
return {
|
|
158
|
+
isReady: () => ready,
|
|
159
|
+
lastError: () => lastError,
|
|
160
|
+
request,
|
|
161
|
+
stop: () => {
|
|
162
|
+
try { child.stdin.end(); } catch { /* ignore */ }
|
|
163
|
+
try { if (child && child.pid) child.kill(); } catch { /* ignore */ }
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* asr-worker.cjs — 本地 STT 子进程入口(普通 node.exe 运行,**不能**在 Electron 里跑)
|
|
3
|
+
*
|
|
4
|
+
* 为什么独立进程:与 tts-worker.cjs 同一原因 —— sherpa-onnx 的 native 扩展会创建 V8
|
|
5
|
+
* external buffer,Electron 进程里直接抛 `External buffers are not allowed`。
|
|
6
|
+
*
|
|
7
|
+
* 协议(stdin/stdout 各一行一条 JSON,stdout 只写协议、日志走 stderr):
|
|
8
|
+
* 请求:{ "id": "1", "wavPath": "C:\\...\\in.wav" }
|
|
9
|
+
* 成功:{ "id": "1", "ok": true, "text": "你好", "ms": 420 }
|
|
10
|
+
* 失败:{ "id": "1", "ok": false, "error": "原因" }
|
|
11
|
+
* 就绪:{ "ready": true, "model": "sensevoice", "sampleRate": 16000 }
|
|
12
|
+
*
|
|
13
|
+
* 用法:node asr-worker.cjs --model-dir <dir>
|
|
14
|
+
* <dir> 里要有:runtime/sherpa-onnx-node/、runtime/sherpa-onnx-win-x64/、models/sensevoice/
|
|
15
|
+
* models/sensevoice/ 需要 model.int8.onnx(或 model.onnx)+ tokens.txt
|
|
16
|
+
*/
|
|
17
|
+
'use strict';
|
|
18
|
+
|
|
19
|
+
const path = require('node:path');
|
|
20
|
+
const fs = require('node:fs');
|
|
21
|
+
const os = require('node:os');
|
|
22
|
+
const readline = require('node:readline');
|
|
23
|
+
|
|
24
|
+
function arg(name, dflt) {
|
|
25
|
+
const i = process.argv.indexOf('--' + name);
|
|
26
|
+
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : dflt;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const root = arg('model-dir', '');
|
|
30
|
+
if (!root) {
|
|
31
|
+
process.stderr.write('[asr-worker] 缺少 --model-dir\n');
|
|
32
|
+
process.exit(2);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const modelDir = path.join(root, 'models', 'sensevoice');
|
|
36
|
+
const sherpaDir = path.join(root, 'runtime', 'sherpa-onnx-node');
|
|
37
|
+
const sherpaNative = path.join(root, 'runtime', 'sherpa-onnx-win-x64');
|
|
38
|
+
|
|
39
|
+
const modelFile = fs.existsSync(path.join(modelDir, 'model.int8.onnx'))
|
|
40
|
+
? path.join(modelDir, 'model.int8.onnx')
|
|
41
|
+
: path.join(modelDir, 'model.onnx');
|
|
42
|
+
const tokensFile = path.join(modelDir, 'tokens.txt');
|
|
43
|
+
|
|
44
|
+
for (const p of [modelFile, tokensFile, sherpaDir]) {
|
|
45
|
+
if (!fs.existsSync(p)) {
|
|
46
|
+
process.stderr.write('[asr-worker] 缺少文件:' + p + '\n');
|
|
47
|
+
process.exit(3);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// native 扩展按模块名解析同目录的 sherpa-onnx-win-x64
|
|
52
|
+
process.env.PATH = sherpaNative + ';' + process.env.PATH;
|
|
53
|
+
process.env.NODE_PATH = root;
|
|
54
|
+
|
|
55
|
+
let OfflineRecognizer;
|
|
56
|
+
try {
|
|
57
|
+
({ OfflineRecognizer } = require(path.join(sherpaDir, 'non-streaming-asr.js')));
|
|
58
|
+
} catch (e) {
|
|
59
|
+
process.stderr.write('[asr-worker] 加载 sherpa 失败:' + e.message + '\n');
|
|
60
|
+
process.exit(4);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const numThreads = Math.max(1, Math.min(4, (os.cpus().length || 2) - 1));
|
|
64
|
+
let recognizer;
|
|
65
|
+
try {
|
|
66
|
+
recognizer = new OfflineRecognizer({
|
|
67
|
+
featConfig: { sampleRate: 16000, featureDim: 80 },
|
|
68
|
+
modelConfig: {
|
|
69
|
+
senseVoice: {
|
|
70
|
+
model: modelFile,
|
|
71
|
+
language: 'zh',
|
|
72
|
+
useInverseTextNormalization: 1,
|
|
73
|
+
},
|
|
74
|
+
tokens: tokensFile,
|
|
75
|
+
numThreads,
|
|
76
|
+
debug: 0,
|
|
77
|
+
provider: 'cpu',
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
} catch (e) {
|
|
81
|
+
process.stderr.write('[asr-worker] 初始化模型失败:' + e.message + '\n');
|
|
82
|
+
process.exit(5);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 读 16-bit PCM WAV → Float32Array(-1..1)。
|
|
87
|
+
* 只认 ffmpeg 产出的形态(PCM s16le、单声道);多声道取第一声道。
|
|
88
|
+
*/
|
|
89
|
+
function readWav(file) {
|
|
90
|
+
const buf = fs.readFileSync(file);
|
|
91
|
+
if (buf.length < 44 || buf.toString('ascii', 0, 4) !== 'RIFF') throw new Error('不是 WAV 文件');
|
|
92
|
+
let pos = 12;
|
|
93
|
+
let fmt = null;
|
|
94
|
+
let data = null;
|
|
95
|
+
while (pos + 8 <= buf.length) {
|
|
96
|
+
const id = buf.toString('ascii', pos, pos + 4);
|
|
97
|
+
const size = buf.readUInt32LE(pos + 4);
|
|
98
|
+
const body = pos + 8;
|
|
99
|
+
if (id === 'fmt ') {
|
|
100
|
+
fmt = {
|
|
101
|
+
channels: buf.readUInt16LE(body + 2),
|
|
102
|
+
sampleRate: buf.readUInt32LE(body + 4),
|
|
103
|
+
bits: buf.readUInt16LE(body + 14),
|
|
104
|
+
};
|
|
105
|
+
} else if (id === 'data') {
|
|
106
|
+
data = buf.subarray(body, Math.min(body + size, buf.length));
|
|
107
|
+
}
|
|
108
|
+
pos = body + size + (size % 2);
|
|
109
|
+
}
|
|
110
|
+
if (!fmt || !data) throw new Error('WAV 缺少 fmt/data 段');
|
|
111
|
+
if (fmt.bits !== 16) throw new Error('只支持 16-bit PCM,收到 ' + fmt.bits + ' bit');
|
|
112
|
+
const frames = Math.floor(data.length / (2 * fmt.channels));
|
|
113
|
+
const out = new Float32Array(frames);
|
|
114
|
+
for (let i = 0; i < frames; i += 1) {
|
|
115
|
+
out[i] = data.readInt16LE(i * 2 * fmt.channels) / 32768;
|
|
116
|
+
}
|
|
117
|
+
return { samples: out, sampleRate: fmt.sampleRate };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 采样率不是 16k 时做一次线性重采样(ffmpeg 一般已给 16k,这里兜底)。 */
|
|
121
|
+
function resample16k(samples, sampleRate) {
|
|
122
|
+
if (!sampleRate || sampleRate === 16000) return samples;
|
|
123
|
+
const ratio = 16000 / sampleRate;
|
|
124
|
+
const length = Math.max(1, Math.floor(samples.length * ratio));
|
|
125
|
+
const out = new Float32Array(length);
|
|
126
|
+
for (let i = 0; i < length; i += 1) {
|
|
127
|
+
const src = i / ratio;
|
|
128
|
+
const i0 = Math.floor(src);
|
|
129
|
+
const i1 = Math.min(samples.length - 1, i0 + 1);
|
|
130
|
+
const t = src - i0;
|
|
131
|
+
out[i] = samples[i0] * (1 - t) + samples[i1] * t;
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function transcribe(wavPath) {
|
|
137
|
+
const started = Date.now();
|
|
138
|
+
const { samples, sampleRate } = readWav(wavPath);
|
|
139
|
+
if (!samples.length) return { ok: true, text: '', ms: 0 };
|
|
140
|
+
const stream = recognizer.createStream();
|
|
141
|
+
stream.acceptWaveform({ samples: resample16k(samples, sampleRate), sampleRate: 16000 });
|
|
142
|
+
recognizer.decode(stream);
|
|
143
|
+
const result = recognizer.getResult(stream);
|
|
144
|
+
const text = String((result && result.text) || '').trim();
|
|
145
|
+
return { ok: true, text, ms: Date.now() - started };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const rl = readline.createInterface({ input: process.stdin });
|
|
149
|
+
rl.on('line', (line) => {
|
|
150
|
+
const raw = String(line || '').trim();
|
|
151
|
+
if (!raw) return;
|
|
152
|
+
let req;
|
|
153
|
+
try {
|
|
154
|
+
req = JSON.parse(raw);
|
|
155
|
+
} catch {
|
|
156
|
+
process.stdout.write(JSON.stringify({ ok: false, error: 'bad-json' }) + '\n');
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const id = req && req.id !== undefined ? req.id : null;
|
|
160
|
+
try {
|
|
161
|
+
if (!req || typeof req.wavPath !== 'string') throw new Error('缺少 wavPath');
|
|
162
|
+
const result = transcribe(req.wavPath);
|
|
163
|
+
process.stdout.write(JSON.stringify({ id, ...result }) + '\n');
|
|
164
|
+
} catch (e) {
|
|
165
|
+
process.stdout.write(JSON.stringify({ id, ok: false, error: String((e && e.message) || e) }) + '\n');
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
process.stdout.write(JSON.stringify({ ready: true, model: 'sensevoice', sampleRate: 16000 }) + '\n');
|
package/lib/routes/pet-chat.js
CHANGED
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
// 「语音输入」实验特性)—— 那种情况由路由回 `asr-not-ready`,而不是启动失败。
|
|
25
25
|
export const DEPS = ['disposers', 'base', 'log', 'readSettings', 'speechToText'];
|
|
26
26
|
|
|
27
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
28
|
-
import { homedir } from 'node:os';
|
|
27
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
28
|
+
import { homedir, tmpdir } from 'node:os';
|
|
29
29
|
import { dirname, join } from 'node:path';
|
|
30
30
|
|
|
31
31
|
import {
|
|
@@ -35,6 +35,8 @@ import {
|
|
|
35
35
|
// v0.1:旧键迁移与默认值只在 settings-schema 定义一次,路由复用同一个函数
|
|
36
36
|
import { readPetChat as normalizePetChat } from '../settings-schema.js';
|
|
37
37
|
import { createVoiceRecorder, defaultResolveFfmpeg, defaultRunFfmpeg } from '../voice/record.js';
|
|
38
|
+
// 本地 STT:资源不下发到 npm 包,首次使用时从站点 R2 下载(见 lib/asr/asr-local.js)
|
|
39
|
+
import { ensureInstalled as ensureAsrInstalled, startWorker as startAsrWorker } from '../asr/asr-local.js';
|
|
38
40
|
// v0.1「零配置」主动搭话:固定策略 + 语音指令静默(追加决定 1/2)
|
|
39
41
|
import {
|
|
40
42
|
canSpeak, markSaid, buildProactiveLine, readProactiveState, todayUsage, isSilent,
|
|
@@ -76,7 +78,74 @@ const ASR_PROVIDER_ID = 'sensevoice-local';
|
|
|
76
78
|
/** 转写语言(本功能只做中文;要别的语种先改契约)。 */
|
|
77
79
|
const ASR_LANGUAGE = 'zh';
|
|
78
80
|
/** 未就绪时给用户的一句话(两条路径共用,避免文案漂移)。 */
|
|
79
|
-
const ASR_NOT_READY_HINT = '
|
|
81
|
+
const ASR_NOT_READY_HINT = '语音输入还没就绪:模型还没下载好,稍等一下';
|
|
82
|
+
|
|
83
|
+
/* ── 本地 STT 运行时(自带 SenseVoice,不依赖 DSH 的语音实验包)─────────────── */
|
|
84
|
+
/**
|
|
85
|
+
* 安装根:`~/.dsh-folia/asr/v1`。
|
|
86
|
+
* 首次点桌宠说话时从站点下载(约 340MB;node.exe 复用 tts 包),之后完全离线。
|
|
87
|
+
*/
|
|
88
|
+
const ASR_ROOT = process.env.FOLIA_ASR_ROOT || join(homedir(), '.dsh-folia', 'asr', 'v1');
|
|
89
|
+
/** 下载/就绪状态(GET /pet-chat/asr 直接回它)。 */
|
|
90
|
+
let asrState = { phase: 'idle', doneBytes: 0, totalBytes: 0, error: null };
|
|
91
|
+
/** worker 实例(懒启动,常驻)。 */
|
|
92
|
+
let asrWorker = null;
|
|
93
|
+
/** 正在进行的安装任务(并发点击 join 同一个 Promise)。 */
|
|
94
|
+
let asrInstallPromise = null;
|
|
95
|
+
|
|
96
|
+
/** 本地运行时是否已经装在盘上(不下载、只探测)。 */
|
|
97
|
+
function asrInstalledOnDisk() {
|
|
98
|
+
try {
|
|
99
|
+
return existsSync(join(ASR_ROOT, 'runtime', 'asr-worker.cjs'))
|
|
100
|
+
&& existsSync(join(ASR_ROOT, 'runtime', 'node.exe'))
|
|
101
|
+
&& existsSync(join(ASR_ROOT, 'models', 'sensevoice', 'tokens.txt'));
|
|
102
|
+
} catch { return false; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 确保本地 STT 可用:装包 → 启 worker。返回 worker;失败抛错并记 asrState.failed。
|
|
107
|
+
* 幂等:并发调用共享同一个安装 Promise。
|
|
108
|
+
*/
|
|
109
|
+
function ensureLocalAsr() {
|
|
110
|
+
if (asrWorker) return Promise.resolve(asrWorker);
|
|
111
|
+
if (asrInstallPromise) return asrInstallPromise;
|
|
112
|
+
asrInstallPromise = (async () => {
|
|
113
|
+
if (!asrInstalledOnDisk()) {
|
|
114
|
+
asrState = { phase: 'downloading', doneBytes: 0, totalBytes: 0, error: null };
|
|
115
|
+
await ensureAsrInstalled(ASR_ROOT, {
|
|
116
|
+
onProgress: (p) => {
|
|
117
|
+
asrState = {
|
|
118
|
+
phase: 'downloading',
|
|
119
|
+
doneBytes: Number(p.doneBytes) || 0,
|
|
120
|
+
totalBytes: Number(p.totalBytes) || 0,
|
|
121
|
+
error: null,
|
|
122
|
+
};
|
|
123
|
+
},
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
asrState = { phase: 'loading', doneBytes: asrState.doneBytes, totalBytes: asrState.totalBytes, error: null };
|
|
127
|
+
asrWorker = startAsrWorker(ASR_ROOT);
|
|
128
|
+
asrState = { phase: 'ready', doneBytes: asrState.doneBytes, totalBytes: asrState.totalBytes, error: null };
|
|
129
|
+
return asrWorker;
|
|
130
|
+
})().catch((error) => {
|
|
131
|
+
asrWorker = null;
|
|
132
|
+
asrState = {
|
|
133
|
+
phase: 'failed',
|
|
134
|
+
doneBytes: asrState.doneBytes,
|
|
135
|
+
totalBytes: asrState.totalBytes,
|
|
136
|
+
error: String((error && error.message) || error),
|
|
137
|
+
};
|
|
138
|
+
asrInstallPromise = null;
|
|
139
|
+
throw error;
|
|
140
|
+
});
|
|
141
|
+
return asrInstallPromise;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 本地 STT 是否已就绪(已装或已启动)—— 决定 /transcribe 走本地还是 DSH 服务。 */
|
|
145
|
+
async function localAsrReady() {
|
|
146
|
+
if (asrWorker) return true;
|
|
147
|
+
return asrInstalledOnDisk();
|
|
148
|
+
}
|
|
80
149
|
|
|
81
150
|
/**
|
|
82
151
|
* 解析 16kHz 单声道 PCM16 WAV 的时长(秒)。
|
|
@@ -678,6 +747,24 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
678
747
|
asrLastAt.set(ip, nowMs);
|
|
679
748
|
|
|
680
749
|
// ① 服务可能压根没装(用户没启用「语音输入」实验特性)
|
|
750
|
+
// 本地 STT 优先:收到的是 WAV 字节 ⇒ 落临时文件交给 worker 识别
|
|
751
|
+
if (await localAsrReady()) {
|
|
752
|
+
try {
|
|
753
|
+
const dir = mkdtempSync(join(tmpdir(), 'folia-asr-'));
|
|
754
|
+
const wavPath = join(dir, 'input.wav');
|
|
755
|
+
writeFileSync(wavPath, Buffer.from(audio));
|
|
756
|
+
const worker = await ensureLocalAsr();
|
|
757
|
+
const spoken = await worker.request(wavPath, ASR_TIMEOUT_MS);
|
|
758
|
+
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
759
|
+
if (!spoken || !spoken.ok) { send({ ok: false, code: 'asr-failed', hint: '识别失败,再试一次' }, 502); return; }
|
|
760
|
+
const text = String(spoken.text || '').trim();
|
|
761
|
+
if (!text) { send({ ok: false, code: 'no-speech', hint: '没听清,再说一次' }, 422); return; }
|
|
762
|
+
send({ ok: true, text, ms: spoken.ms, seconds });
|
|
763
|
+
return;
|
|
764
|
+
} catch {
|
|
765
|
+
// 落到下面的 DSH 服务路径
|
|
766
|
+
}
|
|
767
|
+
}
|
|
681
768
|
const service = speechToText;
|
|
682
769
|
if (!service || typeof service.snapshot !== 'function' || typeof service.transcribe !== 'function') {
|
|
683
770
|
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT });
|
|
@@ -781,30 +868,25 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
781
868
|
send({ ok: false, code: result.code, hint: hints[result.code] || '录音失败' }, result.code === 'ffmpeg-missing' ? 503 : 422);
|
|
782
869
|
return;
|
|
783
870
|
}
|
|
784
|
-
//
|
|
785
|
-
let bytes;
|
|
786
|
-
try { bytes = new Uint8Array(readFileSync(result.audioPath)); } catch { bytes = null; }
|
|
787
|
-
if (!bytes || !bytes.byteLength) { send({ ok: false, code: 'bad-request', hint: '录音文件为空' }, 400); return; }
|
|
788
|
-
if (bytes.byteLength > ASR_MAX_BYTES) { send({ ok: false, code: 'bad-request', hint: '音频超过 2MB' }, 400); return; }
|
|
789
|
-
const service = speechToText;
|
|
790
|
-
if (!service || typeof service.snapshot !== 'function' || typeof service.transcribe !== 'function') {
|
|
791
|
-
send({ ok: false, code: 'asr-not-ready', hint: '在 DSH 设置里开启语音输入(需下载模型)' }, 422);
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
let phase = 'missing';
|
|
871
|
+
// ── 转写:本地 SenseVoice 优先;没装/没下好 ⇒ asr-not-ready,由客户端触发下载 ──
|
|
795
872
|
try {
|
|
796
|
-
const
|
|
797
|
-
const
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
const
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
873
|
+
const worker = await ensureLocalAsr();
|
|
874
|
+
const spoken = await worker.request(result.audioPath, ASR_TIMEOUT_MS);
|
|
875
|
+
if (!spoken || !spoken.ok) {
|
|
876
|
+
send({ ok: false, code: 'asr-failed', hint: '识别失败,再试一次或直接打字' }, 502);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
const text = String(spoken.text || '').trim();
|
|
880
|
+
if (!text) { send({ ok: false, code: 'no-speech', hint: '没听清,再说一次' }, 422); return; }
|
|
881
|
+
send({ ok: true, text, ms: spoken.ms, audioSeconds: result.audioSeconds });
|
|
882
|
+
} catch (error) {
|
|
883
|
+
const message = String((error && error.message) || error);
|
|
884
|
+
const notReady = /manifest|下载|ENOENT|缺少/.test(message) || asrState.phase !== 'ready';
|
|
885
|
+
if (notReady) {
|
|
886
|
+
send({ ok: false, code: 'asr-not-ready', hint: ASR_NOT_READY_HINT }, 422);
|
|
887
|
+
} else {
|
|
888
|
+
send({ ok: false, code: 'asr-failed', hint: '转写失败,重试或直接打字' }, 502);
|
|
889
|
+
}
|
|
808
890
|
} finally {
|
|
809
891
|
try {
|
|
810
892
|
const { rmSync } = await import('node:fs');
|
|
@@ -814,10 +896,9 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
814
896
|
}
|
|
815
897
|
|
|
816
898
|
/**
|
|
817
|
-
* GET /pet-chat/asr ——
|
|
818
|
-
*
|
|
819
|
-
*
|
|
820
|
-
* downloading 时带 completedBytes / totalBytes。
|
|
899
|
+
* GET /pet-chat/asr —— 本地 STT 运行时的状态 / 下载进度。
|
|
900
|
+
* phase: idle | downloading | loading | ready | failed
|
|
901
|
+
* downloading 时带 doneBytes / totalBytes(客户端用它显示"下载中 x%")。
|
|
821
902
|
*/
|
|
822
903
|
function handleAsrStatus(res) {
|
|
823
904
|
const send = (payload, status = 200) => {
|
|
@@ -825,33 +906,28 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
825
906
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
826
907
|
res.end(JSON.stringify(payload));
|
|
827
908
|
};
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
send({ ok: true, available: false, providerId: ASR_PROVIDER_ID, phase: 'unavailable', ready: false });
|
|
831
|
-
return;
|
|
909
|
+
if (!asrWorker && asrState.phase === 'idle' && asrInstalledOnDisk()) {
|
|
910
|
+
asrState = { ...asrState, phase: 'ready' };
|
|
832
911
|
}
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
const snap = service.snapshot();
|
|
836
|
-
const prov = (snap && Array.isArray(snap.providers) ? snap.providers : [])
|
|
837
|
-
.find((item) => item && item.id === ASR_PROVIDER_ID);
|
|
838
|
-
prep = (prov && prov.preparation) || { phase: 'missing' };
|
|
839
|
-
} catch { /* snapshot 失败按未就绪处理 */ }
|
|
912
|
+
const total = Number(asrState.totalBytes) || 0;
|
|
913
|
+
const done = Number(asrState.doneBytes) || 0;
|
|
840
914
|
send({
|
|
841
915
|
ok: true,
|
|
842
916
|
available: true,
|
|
917
|
+
engine: 'local-sensevoice',
|
|
843
918
|
providerId: ASR_PROVIDER_ID,
|
|
844
|
-
phase:
|
|
845
|
-
completedBytes:
|
|
846
|
-
totalBytes:
|
|
847
|
-
|
|
848
|
-
|
|
919
|
+
phase: asrState.phase,
|
|
920
|
+
completedBytes: done,
|
|
921
|
+
totalBytes: total,
|
|
922
|
+
percent: total > 0 ? Math.min(100, Math.round((done / total) * 100)) : null,
|
|
923
|
+
ready: asrState.phase === 'ready',
|
|
924
|
+
message: asrState.error || null,
|
|
849
925
|
});
|
|
850
926
|
}
|
|
851
927
|
|
|
852
928
|
/**
|
|
853
|
-
* POST /pet-chat/asr ——
|
|
854
|
-
*
|
|
929
|
+
* POST /pet-chat/asr —— 触发本地运行时下载(幂等;已在下载会 join 同一个任务)。
|
|
930
|
+
* 用户装完插件点桌宠说话就会走这里,不需要去 DSH 设置里找任何开关。
|
|
855
931
|
*/
|
|
856
932
|
function handleAsrPrepare(res) {
|
|
857
933
|
const send = (payload, status = 200) => {
|
|
@@ -859,17 +935,9 @@ export function registerPetChatRoutes(webServer, c) {
|
|
|
859
935
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
860
936
|
res.end(JSON.stringify(payload));
|
|
861
937
|
};
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
send({ ok: false, code: 'asr-
|
|
865
|
-
return;
|
|
866
|
-
}
|
|
867
|
-
try {
|
|
868
|
-
service.prepare(ASR_PROVIDER_ID);
|
|
869
|
-
send({ ok: true, started: true, providerId: ASR_PROVIDER_ID });
|
|
870
|
-
} catch (error) {
|
|
871
|
-
send({ ok: false, code: 'asr-prepare-failed', hint: String((error && error.message) || error) });
|
|
872
|
-
}
|
|
938
|
+
ensureLocalAsr()
|
|
939
|
+
.then(() => send({ ok: true, started: true, phase: 'ready', engine: 'local-sensevoice' }))
|
|
940
|
+
.catch((error) => send({ ok: false, code: 'asr-prepare-failed', hint: String((error && error.message) || error) }));
|
|
873
941
|
}
|
|
874
942
|
|
|
875
943
|
async function handleConfigGet(res) {
|
package/lib/voice/record.js
CHANGED
|
@@ -162,8 +162,13 @@ export async function defaultResolveFfmpeg() {
|
|
|
162
162
|
|
|
163
163
|
/** 默认执行器:spawn + 收集 stderr(silencedetect 的输出在这里),超时强杀。 */
|
|
164
164
|
export function defaultRunFfmpeg(ff, args, timeoutMs = 30000) {
|
|
165
|
+
/**
|
|
166
|
+
* 为什么 detached:dsh web(Electron 主进程)里 spawn 控制台程序,
|
|
167
|
+
* 子进程可能在启动阶段就死掉(本仓 transcode.js 记录过同一现象:退出码 0xFFFFFFEA)。
|
|
168
|
+
* 给它独立进程组后能正常跑;仍失败时由调用方重试/报错。
|
|
169
|
+
*/
|
|
165
170
|
return new Promise((resolve) => {
|
|
166
|
-
const child = spawn(ff, args, { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
171
|
+
const child = spawn(ff, args, { windowsHide: true, detached: true, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
167
172
|
let stderr = '';
|
|
168
173
|
const timer = setTimeout(() => {
|
|
169
174
|
// 先确认 pid 落地再 kill:spawn 失败时 pid 是 undefined,直接 kill 会抛(守卫 verify-child-kill)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-folia",
|
|
3
|
-
"version": "4.26.0-pre.
|
|
3
|
+
"version": "4.26.0-pre.18",
|
|
4
4
|
"description": "DSH 壁纸引擎:本机 WE 壁纸实时渲染,视频/网页/开机动画/桌宠皮肤,一键拉取在线素材。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -46,6 +46,8 @@
|
|
|
46
46
|
"lib/pet-chat-memory.js",
|
|
47
47
|
"lib/pet-chat-proactive.js",
|
|
48
48
|
"lib/voice/record.js",
|
|
49
|
+
"lib/asr/asr-local.js",
|
|
50
|
+
"lib/asr/asr-worker.cjs",
|
|
49
51
|
"lib/tts/tts-worker.cjs",
|
|
50
52
|
"lib/routes/pet-chat.js",
|
|
51
53
|
"lib/download-queue.js",
|