@ds-hu/dsh-bvi-local 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/NOTICE +31 -0
- package/icon.svg +14 -0
- package/lib/index.js +112 -0
- package/lib/provider.js +691 -0
- package/lib/provision/archive.js +334 -0
- package/lib/provision/download.js +344 -0
- package/lib/provision/install.js +427 -0
- package/lib/worker/adapters.js +535 -0
- package/lib/worker/entry.js +672 -0
- package/lib/worker/runtime.js +762 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +41 -4
- package/README.md +0 -3
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Private worker entry for one local model family.
|
|
3
|
+
*
|
|
4
|
+
* The Host forks this file, passes `{ family, variantId, variantDir, config }` as JSON in
|
|
5
|
+
* `argv[2]` and the bearer secret in `BVI_SPEECH_TOKEN` (removed from the environment once
|
|
6
|
+
* read). The worker loads `sherpa-onnx-node`, builds the family-specific recognizer from the
|
|
7
|
+
* catalog variant directory, then listens on an ephemeral loopback port. Its **only** stdout
|
|
8
|
+
* output is the one-line readiness frame `{"port":N}`; diagnostics go to stderr and a failure
|
|
9
|
+
* before readiness exits non-zero so the Host can surface the message in the preparation state.
|
|
10
|
+
*
|
|
11
|
+
* The loopback protocol is private: authenticated `POST /transcribe?language=<code>` with a
|
|
12
|
+
* canonical 16 kHz mono PCM16 WAV body, the live `POST /stream/start|chunk|finish|cancel` routes
|
|
13
|
+
* (X-ASR only) and `GET /health`. Requests are decoded one at a time in arrival order (native
|
|
14
|
+
* inference is synchronous and CPU-bound; the streaming routes share that serial decode tail).
|
|
15
|
+
* Audio never leaves this process, and terminating the process releases every model tensor.
|
|
16
|
+
*
|
|
17
|
+
* @module @ds-hu/dsh-bvi-local/worker/entry
|
|
18
|
+
*/
|
|
19
|
+
import { randomUUID, timingSafeEqual } from 'node:crypto'
|
|
20
|
+
import { createServer } from 'node:http'
|
|
21
|
+
import { createRequire } from 'node:module'
|
|
22
|
+
import { join } from 'node:path'
|
|
23
|
+
import { LOCAL_MODELS } from '@ds-hu/dsh-bvi-core/catalog/local.js'
|
|
24
|
+
import { MAX_WAV_BYTES, parseWav } from '@ds-hu/dsh-bvi-core/wav.js'
|
|
25
|
+
import { AdapterInputError, LONG_AUDIO_SECONDS, joinChunkTexts, adapterFor } from './adapters.js'
|
|
26
|
+
|
|
27
|
+
/** The canonical intake format every request must use. */
|
|
28
|
+
const SAMPLE_RATE = 16_000
|
|
29
|
+
/** Bytes in the fetch body window accepted from the Host (a valid WAV needs at least 44). */
|
|
30
|
+
const MIN_WAV_BYTES = 44
|
|
31
|
+
/** Silero VAD window size for 16 kHz audio (must match the model's training window). */
|
|
32
|
+
const VAD_WINDOW_SAMPLES = 512
|
|
33
|
+
/** Longest single VAD segment; longer speech is split at the next silence. */
|
|
34
|
+
const VAD_MAX_SPEECH_SECONDS = 24
|
|
35
|
+
/** Silence that separates two speech segments. */
|
|
36
|
+
const VAD_MIN_SILENCE_SECONDS = 0.5
|
|
37
|
+
/** Shortest retained speech segment. */
|
|
38
|
+
const VAD_MIN_SPEECH_SECONDS = 0.25
|
|
39
|
+
/** Silero speech probability threshold. */
|
|
40
|
+
const VAD_THRESHOLD = 0.5
|
|
41
|
+
/** Audio restored ahead of the first segment because a cold detector reports its onset late. */
|
|
42
|
+
const VAD_ONSET_PADDING_SECONDS = 0.3
|
|
43
|
+
/** X-ASR frame length: 200 ms of 16 kHz audio. */
|
|
44
|
+
const XASR_FRAME_SAMPLES = 3_200
|
|
45
|
+
/** Upper bound on decodes per accepted X-ASR frame (guards against a stuck recognizer). */
|
|
46
|
+
const XASR_MAX_DECODE_LOOPS = 8
|
|
47
|
+
/** X-ASR silence padding chunks fed before `inputFinished()` (2 × 480 ms). */
|
|
48
|
+
const XASR_TAIL_PADDING_CHUNKS = 2
|
|
49
|
+
/** One X-ASR model chunk in seconds. */
|
|
50
|
+
const XASR_MODEL_CHUNK_SECONDS = 0.480
|
|
51
|
+
/** Upper bound on final drain loops after the input is finished. */
|
|
52
|
+
const XASR_DRAIN_MAX_LOOPS = 512
|
|
53
|
+
/** Requests accepted before the worker starts answering `429` (the Host caps itself at 4). */
|
|
54
|
+
const MAX_QUEUED_REQUESTS = 8
|
|
55
|
+
/** Largest raw PCM16LE chunk accepted on a live stream (one second is 32 000 bytes). */
|
|
56
|
+
const STREAM_CHUNK_MAX_BYTES = 1024 * 1024
|
|
57
|
+
/** A live stream with no traffic for this long is dropped and its recognizer state collected. */
|
|
58
|
+
const STREAM_IDLE_TIMEOUT_MS = 120_000
|
|
59
|
+
/** PCM16LE frames are two bytes per mono 16 kHz sample. */
|
|
60
|
+
const PCM16_BYTES = 2
|
|
61
|
+
/** The only body type accepted for PCM16LE streaming chunks. */
|
|
62
|
+
const STREAM_CONTENT_TYPE = 'application/octet-stream'
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Write a fatal diagnostic to stderr and exit non-zero once flushed.
|
|
66
|
+
* @param {unknown} error - thrown value.
|
|
67
|
+
* @returns {void} the process terminates from the flush callback.
|
|
68
|
+
*/
|
|
69
|
+
function fail(error) {
|
|
70
|
+
const message = error instanceof Error ? (error.stack ?? error.message) : String(error)
|
|
71
|
+
process.exitCode = 1
|
|
72
|
+
try {
|
|
73
|
+
process.stderr.write(`${message}\n`, () => { process.exit(1) })
|
|
74
|
+
} catch {
|
|
75
|
+
process.exit(1)
|
|
76
|
+
}
|
|
77
|
+
// A broken or back-pressured stderr must never leave a half-started worker alive.
|
|
78
|
+
setTimeout(() => { process.exit(1) }, 5_000).unref()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
process.on('uncaughtException', fail)
|
|
82
|
+
process.on('unhandledRejection', fail)
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {unknown} value - candidate.
|
|
86
|
+
* @returns {value is Record<string, any>} whether the value is a plain object.
|
|
87
|
+
*/
|
|
88
|
+
function isPlainObject(value) {
|
|
89
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* @param {unknown} value - candidate.
|
|
94
|
+
* @param {string} name - field name for the error message.
|
|
95
|
+
* @returns {string} the non-empty string.
|
|
96
|
+
*/
|
|
97
|
+
function requiredString(value, name) {
|
|
98
|
+
if (typeof value !== 'string' || value === '') throw new Error(`Worker payload is missing ${name}`)
|
|
99
|
+
return value
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A streaming protocol violation that is answered with an explicit HTTP status.
|
|
104
|
+
*
|
|
105
|
+
* The Host maps the status back onto its own `WorkerError` taxonomy, so a bad stream id, a second
|
|
106
|
+
* live stream and an oversized chunk stay distinguishable from a crash.
|
|
107
|
+
*/
|
|
108
|
+
class StreamError extends Error {
|
|
109
|
+
/**
|
|
110
|
+
* @param {number} status - HTTP status to answer with.
|
|
111
|
+
* @param {string} message - human-readable explanation.
|
|
112
|
+
* @param {string} [code] - stable body code (defaults to `invalid-input`).
|
|
113
|
+
*/
|
|
114
|
+
constructor(status, message, code = 'invalid-input') {
|
|
115
|
+
super(message)
|
|
116
|
+
this.name = 'StreamError'
|
|
117
|
+
this.status = status
|
|
118
|
+
this.code = code
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Convert one raw PCM16LE block into normalized Float32 samples.
|
|
124
|
+
* @param {Uint8Array} pcm - little-endian 16-bit mono samples.
|
|
125
|
+
* @returns {Float32Array} samples in [-1, 1).
|
|
126
|
+
*/
|
|
127
|
+
function pcm16ToFloat32(pcm) {
|
|
128
|
+
const count = Math.floor(pcm.byteLength / PCM16_BYTES)
|
|
129
|
+
const view = new DataView(pcm.buffer, pcm.byteOffset, count * PCM16_BYTES)
|
|
130
|
+
const samples = new Float32Array(count)
|
|
131
|
+
for (let index = 0; index < count; index += 1) samples[index] = view.getInt16(index * PCM16_BYTES, true) / 32768
|
|
132
|
+
return samples
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Duration of a raw PCM16LE mono 16 kHz block.
|
|
137
|
+
* @param {number} bytes - accepted stream byte count.
|
|
138
|
+
* @returns {number} seconds.
|
|
139
|
+
*/
|
|
140
|
+
function pcm16Seconds(bytes) {
|
|
141
|
+
return bytes / (SAMPLE_RATE * PCM16_BYTES)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Decode the canonical WAV body into Float32 samples.
|
|
146
|
+
* @param {Uint8Array} audio - request body.
|
|
147
|
+
* @returns {{ samples: Float32Array, audioSeconds: number }} mono 16 kHz samples and duration.
|
|
148
|
+
* @throws {AdapterInputError} when the body is not the canonical intake format.
|
|
149
|
+
*/
|
|
150
|
+
function decodeInput(audio) {
|
|
151
|
+
let parsed
|
|
152
|
+
try {
|
|
153
|
+
parsed = parseWav(audio)
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw new AdapterInputError(`Invalid speech WAV: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
|
|
156
|
+
}
|
|
157
|
+
if (parsed.sampleRate !== SAMPLE_RATE) throw new AdapterInputError(`Invalid speech WAV: expected ${SAMPLE_RATE} Hz, received ${parsed.sampleRate} Hz`)
|
|
158
|
+
if (parsed.channels !== 1) throw new AdapterInputError('Invalid speech WAV: expected mono audio')
|
|
159
|
+
const samples = pcm16ToFloat32(audio.subarray(parsed.dataOffset, parsed.dataOffset + parsed.dataBytes))
|
|
160
|
+
return { samples, audioSeconds: pcm16Seconds(parsed.dataBytes) }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Build the VAD detector for families that segment audio.
|
|
165
|
+
* @param {any} sherpa - loaded sherpa-onnx-node module.
|
|
166
|
+
* @param {string} vadPath - verified Silero VAD ONNX file.
|
|
167
|
+
* @returns {any} VoiceActivityDetector instance.
|
|
168
|
+
*/
|
|
169
|
+
function createVad(sherpa, vadPath) {
|
|
170
|
+
return new sherpa.Vad({
|
|
171
|
+
sileroVad: {
|
|
172
|
+
model: vadPath,
|
|
173
|
+
threshold: VAD_THRESHOLD,
|
|
174
|
+
minSilenceDuration: VAD_MIN_SILENCE_SECONDS,
|
|
175
|
+
minSpeechDuration: VAD_MIN_SPEECH_SECONDS,
|
|
176
|
+
maxSpeechDuration: VAD_MAX_SPEECH_SECONDS,
|
|
177
|
+
windowSize: VAD_WINDOW_SAMPLES,
|
|
178
|
+
},
|
|
179
|
+
sampleRate: SAMPLE_RATE,
|
|
180
|
+
numThreads: 1,
|
|
181
|
+
provider: 'cpu',
|
|
182
|
+
debug: 0,
|
|
183
|
+
}, VAD_MAX_SPEECH_SECONDS + VAD_MIN_SILENCE_SECONDS + 1)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Decode every chunk the recognizer reports ready, bounded so a stuck recognizer cannot spin.
|
|
188
|
+
* @param {any} recognizer - OnlineRecognizer.
|
|
189
|
+
* @param {any} stream - online stream.
|
|
190
|
+
* @returns {void}
|
|
191
|
+
*/
|
|
192
|
+
function decodeReady(recognizer, stream) {
|
|
193
|
+
let loops = 0
|
|
194
|
+
while (recognizer.isReady(stream) && loops < XASR_MAX_DECODE_LOOPS) {
|
|
195
|
+
recognizer.decode(stream)
|
|
196
|
+
loops += 1
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Drain the recognizer after the last accepted frame (bounded separately from frame decodes).
|
|
202
|
+
* @param {any} recognizer - OnlineRecognizer.
|
|
203
|
+
* @param {any} stream - online stream.
|
|
204
|
+
* @returns {void}
|
|
205
|
+
*/
|
|
206
|
+
function drainReady(recognizer, stream) {
|
|
207
|
+
let loops = 0
|
|
208
|
+
while (recognizer.isReady(stream) && loops < XASR_DRAIN_MAX_LOOPS) {
|
|
209
|
+
recognizer.decode(stream)
|
|
210
|
+
loops += 1
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Incremental X-ASR session manager: one live recognizer stream per worker, driven by the Host
|
|
216
|
+
* over the private `/stream/*` loopback routes.
|
|
217
|
+
*
|
|
218
|
+
* The session keeps the exact model configuration used by the batch path; it only splits the
|
|
219
|
+
* documented shutdown protocol (drain → two 480 ms silence chunks → `inputFinished()` → drain)
|
|
220
|
+
* from the per-chunk decode loop, and reports the cumulative partial text after every chunk.
|
|
221
|
+
* A stream that receives no traffic for two minutes is silently dropped (the service also caps
|
|
222
|
+
* session idle time; this is the worker-side backstop so a vanished browser cannot pin memory).
|
|
223
|
+
* @param {any} recognizer - loaded OnlineRecognizer.
|
|
224
|
+
* @param {Record<string, any>} adapter - family adapter (sanitize/validateLanguage policy).
|
|
225
|
+
* @returns {{
|
|
226
|
+
* start: (language: string) => { streamId: string },
|
|
227
|
+
* chunk: (streamId: string, pcm: Uint8Array) => { partial: string, bytes: number },
|
|
228
|
+
* finish: (streamId: string) => { text: string, audioSeconds: number },
|
|
229
|
+
* cancel: (streamId: string) => { ok: true },
|
|
230
|
+
* release: () => void,
|
|
231
|
+
* }} streaming session manager.
|
|
232
|
+
*/
|
|
233
|
+
function createStreamingSession(recognizer, adapter) {
|
|
234
|
+
/** @type {{ id: string, stream: any, bytes: number, timer: NodeJS.Timeout|undefined }|null} */
|
|
235
|
+
let live = null
|
|
236
|
+
/** Drop the live stream and let the GC reclaim its decoder state. @returns {void} */
|
|
237
|
+
const release = () => {
|
|
238
|
+
if (live === null) return
|
|
239
|
+
if (live.timer !== undefined) clearTimeout(live.timer)
|
|
240
|
+
live = null
|
|
241
|
+
}
|
|
242
|
+
/** @returns {void} */
|
|
243
|
+
const armIdleTimer = () => {
|
|
244
|
+
if (live === null) return
|
|
245
|
+
if (live.timer !== undefined) clearTimeout(live.timer)
|
|
246
|
+
live.timer = setTimeout(release, STREAM_IDLE_TIMEOUT_MS)
|
|
247
|
+
live.timer.unref?.()
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Resolve the live stream named by the Host or throw the matching protocol error.
|
|
251
|
+
* @param {string} streamId - opaque session id returned by `start`.
|
|
252
|
+
* @returns {{ id: string, stream: any, bytes: number, timer: NodeJS.Timeout|undefined }} live session.
|
|
253
|
+
*/
|
|
254
|
+
const requireLive = (streamId) => {
|
|
255
|
+
if (typeof streamId !== 'string' || streamId === '') throw new StreamError(400, 'A stream id is required')
|
|
256
|
+
if (live === null || live.id !== streamId) throw new StreamError(404, `Unknown streaming session: ${streamId}`, 'not-found')
|
|
257
|
+
return live
|
|
258
|
+
}
|
|
259
|
+
return {
|
|
260
|
+
start(language) {
|
|
261
|
+
adapter.validateLanguage(language)
|
|
262
|
+
if (live !== null) throw new StreamError(409, 'A streaming session is already active', 'busy')
|
|
263
|
+
live = { id: randomUUID(), stream: recognizer.createStream(), bytes: 0, timer: undefined }
|
|
264
|
+
armIdleTimer()
|
|
265
|
+
return { streamId: live.id }
|
|
266
|
+
},
|
|
267
|
+
chunk(streamId, pcm) {
|
|
268
|
+
const session = requireLive(streamId)
|
|
269
|
+
session.stream.acceptWaveform({ samples: pcm16ToFloat32(pcm), sampleRate: SAMPLE_RATE })
|
|
270
|
+
decodeReady(recognizer, session.stream)
|
|
271
|
+
session.bytes += pcm.byteLength
|
|
272
|
+
armIdleTimer()
|
|
273
|
+
return { partial: adapter.sanitize(recognizer.getResult(session.stream).text), bytes: pcm.byteLength }
|
|
274
|
+
},
|
|
275
|
+
finish(streamId) {
|
|
276
|
+
const session = requireLive(streamId)
|
|
277
|
+
try {
|
|
278
|
+
drainReady(recognizer, session.stream)
|
|
279
|
+
// Two model chunks of silence stop the last characters from being dropped (docs §8.3).
|
|
280
|
+
const padding = new Float32Array(Math.round(XASR_MODEL_CHUNK_SECONDS * SAMPLE_RATE))
|
|
281
|
+
for (let index = 0; index < XASR_TAIL_PADDING_CHUNKS; index += 1) {
|
|
282
|
+
session.stream.acceptWaveform({ samples: padding, sampleRate: SAMPLE_RATE })
|
|
283
|
+
drainReady(recognizer, session.stream)
|
|
284
|
+
}
|
|
285
|
+
session.stream.inputFinished()
|
|
286
|
+
drainReady(recognizer, session.stream)
|
|
287
|
+
return { text: adapter.sanitize(recognizer.getResult(session.stream).text), audioSeconds: pcm16Seconds(session.bytes) }
|
|
288
|
+
} finally {
|
|
289
|
+
release()
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
cancel(streamId) {
|
|
293
|
+
requireLive(streamId)
|
|
294
|
+
release()
|
|
295
|
+
return { ok: true }
|
|
296
|
+
},
|
|
297
|
+
release,
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Own one loaded recognizer and the family-specific decode policy.
|
|
303
|
+
* @param {{ sherpa: any, model: Record<string, any>, variant: Record<string, any>, paths: Record<string, string>, adapter: Record<string, any>, config: Record<string, any> }} options - loaded runtime.
|
|
304
|
+
* @returns {{ transcribe: (audio: Uint8Array, language: string) => Record<string, any>, streaming?: ReturnType<typeof createStreamingSession> }} synchronous transcription handle plus the optional live-stream manager.
|
|
305
|
+
*/
|
|
306
|
+
function createTranscriber(options) {
|
|
307
|
+
const { sherpa, model, adapter, paths, config } = options
|
|
308
|
+
const threads = Number.isSafeInteger(config.threads) && config.threads > 0 ? config.threads : model.runtime.threads
|
|
309
|
+
const vadPath = typeof config.vadPath === 'string' && config.vadPath !== '' ? config.vadPath : undefined
|
|
310
|
+
const segmentation = model.runtime.segmentation
|
|
311
|
+
const vad = vadPath !== undefined && (segmentation === 'vad' || segmentation === 'vad-long')
|
|
312
|
+
? createVad(sherpa, vadPath)
|
|
313
|
+
: undefined
|
|
314
|
+
|
|
315
|
+
if (model.runtime.kind === 'online') {
|
|
316
|
+
const recognizer = new sherpa.OnlineRecognizer(adapter.configure(paths, { threads }))
|
|
317
|
+
const transcribe = (audio, language) => transcribeOnline(recognizer, adapter, audio, language)
|
|
318
|
+
// Live streaming is a documented X-ASR capability only; another online model would have to
|
|
319
|
+
// bring its own incremental shutdown protocol before it could advertise `streaming: true`.
|
|
320
|
+
return model.family === 'x-asr'
|
|
321
|
+
? { transcribe, streaming: createStreamingSession(recognizer, adapter) }
|
|
322
|
+
: { transcribe }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const recognizer = new sherpa.OfflineRecognizer(adapter.configure(paths, { threads, language: 'auto' }))
|
|
326
|
+
/**
|
|
327
|
+
* Decode one segment of samples.
|
|
328
|
+
* @param {Float32Array} samples - mono 16 kHz speech.
|
|
329
|
+
* @param {string} language - requested language code.
|
|
330
|
+
* @returns {string} sanitized segment text.
|
|
331
|
+
*/
|
|
332
|
+
const decodeSegment = (samples, language) => {
|
|
333
|
+
const stream = recognizer.createStream()
|
|
334
|
+
for (const [key, value] of adapter.streamOptions(language)) stream.setOption(key, value)
|
|
335
|
+
stream.acceptWaveform({ samples, sampleRate: SAMPLE_RATE })
|
|
336
|
+
recognizer.decode(stream)
|
|
337
|
+
return adapter.sanitize(recognizer.getResult(stream).text)
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Recognize one whole recording (no segmentation).
|
|
341
|
+
* @param {Float32Array} samples - mono 16 kHz speech.
|
|
342
|
+
* @param {string} language - requested language code.
|
|
343
|
+
* @returns {string} transcript.
|
|
344
|
+
*/
|
|
345
|
+
const decodeWhole = (samples, language) => decodeSegment(samples, language)
|
|
346
|
+
/**
|
|
347
|
+
* Recognize audio segmented by Silero VAD at natural pauses.
|
|
348
|
+
* @param {Float32Array} samples - mono 16 kHz speech.
|
|
349
|
+
* @param {string} language - requested language code.
|
|
350
|
+
* @returns {string} joined transcript.
|
|
351
|
+
*/
|
|
352
|
+
const decodeSegmented = (samples, language) => {
|
|
353
|
+
if (vad === undefined) throw new Error(`${model.family}: the shared VAD asset is not installed`)
|
|
354
|
+
vad.reset()
|
|
355
|
+
const onsetPadding = Math.round(VAD_ONSET_PADDING_SECONDS * SAMPLE_RATE)
|
|
356
|
+
/** @type {string[]} */
|
|
357
|
+
const texts = []
|
|
358
|
+
let isFirstSegment = true
|
|
359
|
+
const drain = () => {
|
|
360
|
+
while (!vad.isEmpty()) {
|
|
361
|
+
const segment = vad.front(false)
|
|
362
|
+
let speech = segment.samples
|
|
363
|
+
if (isFirstSegment) {
|
|
364
|
+
isFirstSegment = false
|
|
365
|
+
const from = Math.max(0, segment.start - onsetPadding)
|
|
366
|
+
if (from < segment.start) {
|
|
367
|
+
const restored = new Float32Array(segment.start - from + speech.length)
|
|
368
|
+
restored.set(samples.subarray(from, segment.start))
|
|
369
|
+
restored.set(speech, segment.start - from)
|
|
370
|
+
speech = restored
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
texts.push(decodeSegment(speech, language))
|
|
374
|
+
vad.pop()
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
for (let offset = 0; offset < samples.length; offset += VAD_WINDOW_SAMPLES) {
|
|
378
|
+
vad.acceptWaveform(samples.subarray(offset, offset + VAD_WINDOW_SAMPLES))
|
|
379
|
+
drain()
|
|
380
|
+
}
|
|
381
|
+
vad.flush()
|
|
382
|
+
drain()
|
|
383
|
+
return joinChunkTexts(texts)
|
|
384
|
+
}
|
|
385
|
+
return {
|
|
386
|
+
/**
|
|
387
|
+
* @param {Uint8Array} audio - canonical WAV bytes.
|
|
388
|
+
* @param {string} language - requested language code.
|
|
389
|
+
* @returns {{ text: string, audioSeconds: number }} transcript.
|
|
390
|
+
*/
|
|
391
|
+
transcribe(audio, language) {
|
|
392
|
+
const { samples, audioSeconds } = decodeInput(audio)
|
|
393
|
+
if (adapter.languageSensitive) recognizer.setConfig(adapter.configure(paths, { threads, language }))
|
|
394
|
+
adapter.validateLanguage(language)
|
|
395
|
+
let text
|
|
396
|
+
if (segmentation === 'whole') text = decodeWhole(samples, language)
|
|
397
|
+
else if (segmentation === 'vad') text = decodeSegmented(samples, language)
|
|
398
|
+
else if (segmentation === 'vad-long') {
|
|
399
|
+
text = audioSeconds <= LONG_AUDIO_SECONDS ? decodeWhole(samples, language) : decodeSegmented(samples, language)
|
|
400
|
+
} else throw new Error(`${model.family}: unsupported segmentation policy: ${String(segmentation)}`)
|
|
401
|
+
return { text, audioSeconds }
|
|
402
|
+
},
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Recognize one recording with X-ASR's streaming recognizer, including the documented shutdown
|
|
408
|
+
* protocol: drain, feed two 480 ms silence chunks, call `inputFinished()`, drain again.
|
|
409
|
+
* @param {any} recognizer - OnlineRecognizer.
|
|
410
|
+
* @param {Record<string, any>} adapter - family adapter.
|
|
411
|
+
* @param {Uint8Array} audio - canonical WAV bytes.
|
|
412
|
+
* @param {string} language - requested language code (unused by X-ASR).
|
|
413
|
+
* @returns {{ text: string, audioSeconds: number }} transcript.
|
|
414
|
+
*/
|
|
415
|
+
function transcribeOnline(recognizer, adapter, audio, language) {
|
|
416
|
+
adapter.validateLanguage(language)
|
|
417
|
+
const { samples, audioSeconds } = decodeInput(audio)
|
|
418
|
+
const stream = recognizer.createStream()
|
|
419
|
+
for (let offset = 0; offset < samples.length; offset += XASR_FRAME_SAMPLES) {
|
|
420
|
+
stream.acceptWaveform({ samples: samples.subarray(offset, offset + XASR_FRAME_SAMPLES), sampleRate: SAMPLE_RATE })
|
|
421
|
+
decodeReady(recognizer, stream)
|
|
422
|
+
}
|
|
423
|
+
drainReady(recognizer, stream)
|
|
424
|
+
// Two model chunks of silence stop the last characters from being dropped (docs §8.3).
|
|
425
|
+
const padding = new Float32Array(Math.round(XASR_MODEL_CHUNK_SECONDS * SAMPLE_RATE))
|
|
426
|
+
for (let index = 0; index < XASR_TAIL_PADDING_CHUNKS; index += 1) {
|
|
427
|
+
stream.acceptWaveform({ samples: padding, sampleRate: SAMPLE_RATE })
|
|
428
|
+
drainReady(recognizer, stream)
|
|
429
|
+
}
|
|
430
|
+
stream.inputFinished()
|
|
431
|
+
drainReady(recognizer, stream)
|
|
432
|
+
return { text: adapter.sanitize(recognizer.getResult(stream).text), audioSeconds }
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Read the complete request body (the content-length cap is checked before this runs).
|
|
437
|
+
* @param {import('node:http').IncomingMessage} request - HTTP request.
|
|
438
|
+
* @returns {Promise<Uint8Array>} body bytes.
|
|
439
|
+
*/
|
|
440
|
+
async function readBody(request) {
|
|
441
|
+
/** @type {Buffer[]} */
|
|
442
|
+
const chunks = []
|
|
443
|
+
for await (const chunk of request) chunks.push(/** @type {Buffer} */ (chunk))
|
|
444
|
+
return Buffer.concat(chunks)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Bind the authenticated loopback listener.
|
|
449
|
+
* @param {{
|
|
450
|
+
* token: string,
|
|
451
|
+
* maxAudioBytes: number,
|
|
452
|
+
* transcribe: (audio: Uint8Array, language: string) => { text: string, audioSeconds: number },
|
|
453
|
+
* streaming?: ReturnType<typeof createStreamingSession>,
|
|
454
|
+
* family: string,
|
|
455
|
+
* variantId: string,
|
|
456
|
+
* }} options - server configuration; `streaming` is present only for X-ASR.
|
|
457
|
+
* @returns {Promise<{ port: number, close: () => Promise<void> }>} listening server handle.
|
|
458
|
+
*/
|
|
459
|
+
async function startServer(options) {
|
|
460
|
+
const expected = Buffer.from(`Bearer ${options.token}`)
|
|
461
|
+
let pending = 0
|
|
462
|
+
/** @type {Promise<unknown>} */
|
|
463
|
+
let tail = Promise.resolve()
|
|
464
|
+
/**
|
|
465
|
+
* @param {(audio: Uint8Array, language: string) => { text: string, audioSeconds: number }} job - decode work.
|
|
466
|
+
* @returns {Promise<{ text: string, audioSeconds: number }>} transcript.
|
|
467
|
+
*/
|
|
468
|
+
const enqueue = (job) => {
|
|
469
|
+
const run = tail.then(() => job(), () => job())
|
|
470
|
+
tail = run.then(() => undefined, () => undefined)
|
|
471
|
+
return run
|
|
472
|
+
}
|
|
473
|
+
const server = createServer((request, response) => {
|
|
474
|
+
/**
|
|
475
|
+
* @param {number} status - HTTP status.
|
|
476
|
+
* @param {Record<string, any>} payload - JSON body.
|
|
477
|
+
* @returns {void}
|
|
478
|
+
*/
|
|
479
|
+
const reply = (status, payload) => {
|
|
480
|
+
response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' })
|
|
481
|
+
response.end(JSON.stringify(payload))
|
|
482
|
+
}
|
|
483
|
+
const authorization = Buffer.from(request.headers.authorization ?? '')
|
|
484
|
+
if (authorization.length !== expected.length || !timingSafeEqual(authorization, expected)) {
|
|
485
|
+
request.resume()
|
|
486
|
+
reply(401, { error: 'Unauthorized', code: 'unauthorized' })
|
|
487
|
+
return
|
|
488
|
+
}
|
|
489
|
+
const url = new URL(request.url ?? '/', 'http://127.0.0.1')
|
|
490
|
+
if (request.method === 'GET' && url.pathname === '/health') {
|
|
491
|
+
request.resume()
|
|
492
|
+
reply(200, { ok: true, family: options.family, variant: options.variantId })
|
|
493
|
+
return
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Answer one failed streaming request (protocol violations carry their own status).
|
|
497
|
+
* @param {unknown} error - thrown value.
|
|
498
|
+
* @returns {void}
|
|
499
|
+
*/
|
|
500
|
+
const replyStreamFailure = (error) => {
|
|
501
|
+
if (error instanceof StreamError) {
|
|
502
|
+
reply(error.status, { error: error.message, code: error.code })
|
|
503
|
+
return
|
|
504
|
+
}
|
|
505
|
+
const isInput = error instanceof AdapterInputError
|
|
506
|
+
reply(isInput ? 400 : 500, {
|
|
507
|
+
error: error instanceof Error ? error.message : String(error),
|
|
508
|
+
...isInput ? { code: 'invalid-input' } : {},
|
|
509
|
+
})
|
|
510
|
+
}
|
|
511
|
+
if (request.method === 'POST' && url.pathname.startsWith('/stream/')) {
|
|
512
|
+
const streaming = options.streaming
|
|
513
|
+
if (streaming === undefined) {
|
|
514
|
+
request.resume()
|
|
515
|
+
reply(400, { error: 'Live streaming is only available for the X-ASR family', code: 'invalid-input' })
|
|
516
|
+
return
|
|
517
|
+
}
|
|
518
|
+
if (url.pathname === '/stream/start') {
|
|
519
|
+
request.resume()
|
|
520
|
+
try {
|
|
521
|
+
reply(200, streaming.start(url.searchParams.get('language') ?? 'auto'))
|
|
522
|
+
} catch (error) {
|
|
523
|
+
replyStreamFailure(error)
|
|
524
|
+
}
|
|
525
|
+
return
|
|
526
|
+
}
|
|
527
|
+
const streamId = url.searchParams.get('stream') ?? ''
|
|
528
|
+
if (url.pathname === '/stream/chunk') {
|
|
529
|
+
const length = Number(request.headers['content-length'])
|
|
530
|
+
if (!Number.isSafeInteger(length) || length < PCM16_BYTES || length > STREAM_CHUNK_MAX_BYTES || length % PCM16_BYTES !== 0) {
|
|
531
|
+
request.resume()
|
|
532
|
+
reply(413, { error: 'Invalid streaming chunk size', code: 'invalid-input' })
|
|
533
|
+
return
|
|
534
|
+
}
|
|
535
|
+
const contentType = String(request.headers['content-type'] ?? '').split(';', 1)[0].trim().toLowerCase()
|
|
536
|
+
if (contentType !== STREAM_CONTENT_TYPE) {
|
|
537
|
+
request.resume()
|
|
538
|
+
reply(415, { error: 'Streaming chunks must be application/octet-stream', code: 'invalid-input' })
|
|
539
|
+
return
|
|
540
|
+
}
|
|
541
|
+
void (async () => {
|
|
542
|
+
try {
|
|
543
|
+
const pcm = await readBody(request)
|
|
544
|
+
if (pcm.byteLength !== length) throw new StreamError(413, 'Streaming chunk body does not match its declared size')
|
|
545
|
+
reply(200, await enqueue(() => streaming.chunk(streamId, pcm)))
|
|
546
|
+
} catch (error) {
|
|
547
|
+
replyStreamFailure(error)
|
|
548
|
+
}
|
|
549
|
+
})()
|
|
550
|
+
return
|
|
551
|
+
}
|
|
552
|
+
if (url.pathname === '/stream/finish') {
|
|
553
|
+
request.resume()
|
|
554
|
+
void (async () => {
|
|
555
|
+
try {
|
|
556
|
+
reply(200, await enqueue(() => streaming.finish(streamId)))
|
|
557
|
+
} catch (error) {
|
|
558
|
+
replyStreamFailure(error)
|
|
559
|
+
}
|
|
560
|
+
})()
|
|
561
|
+
return
|
|
562
|
+
}
|
|
563
|
+
if (url.pathname === '/stream/cancel') {
|
|
564
|
+
request.resume()
|
|
565
|
+
try {
|
|
566
|
+
reply(200, streaming.cancel(streamId))
|
|
567
|
+
} catch (error) {
|
|
568
|
+
replyStreamFailure(error)
|
|
569
|
+
}
|
|
570
|
+
return
|
|
571
|
+
}
|
|
572
|
+
request.resume()
|
|
573
|
+
reply(404, { error: 'Unknown endpoint', code: 'not-found' })
|
|
574
|
+
return
|
|
575
|
+
}
|
|
576
|
+
if (request.method !== 'POST' || url.pathname !== '/transcribe') {
|
|
577
|
+
request.resume()
|
|
578
|
+
reply(404, { error: 'Unknown endpoint', code: 'not-found' })
|
|
579
|
+
return
|
|
580
|
+
}
|
|
581
|
+
const length = Number(request.headers['content-length'])
|
|
582
|
+
if (!Number.isSafeInteger(length) || length < MIN_WAV_BYTES || length > options.maxAudioBytes) {
|
|
583
|
+
request.resume()
|
|
584
|
+
reply(413, { error: 'Invalid speech audio size', code: 'invalid-input' })
|
|
585
|
+
return
|
|
586
|
+
}
|
|
587
|
+
if (pending >= MAX_QUEUED_REQUESTS) {
|
|
588
|
+
request.resume()
|
|
589
|
+
reply(429, { error: 'Speech worker queue is full', code: 'busy' })
|
|
590
|
+
return
|
|
591
|
+
}
|
|
592
|
+
const language = url.searchParams.get('language') ?? 'auto'
|
|
593
|
+
pending += 1
|
|
594
|
+
void (async () => {
|
|
595
|
+
try {
|
|
596
|
+
const audio = await readBody(request)
|
|
597
|
+
const result = await enqueue(() => options.transcribe(audio, language))
|
|
598
|
+
reply(200, result)
|
|
599
|
+
} catch (error) {
|
|
600
|
+
const isInput = error instanceof AdapterInputError
|
|
601
|
+
reply(isInput ? 400 : 500, {
|
|
602
|
+
error: error instanceof Error ? error.message : String(error),
|
|
603
|
+
...isInput ? { code: 'invalid-input' } : {},
|
|
604
|
+
})
|
|
605
|
+
} finally {
|
|
606
|
+
pending -= 1
|
|
607
|
+
}
|
|
608
|
+
})()
|
|
609
|
+
})
|
|
610
|
+
await new Promise((resolve, reject) => {
|
|
611
|
+
server.once('error', reject)
|
|
612
|
+
server.listen(0, '127.0.0.1', () => { server.off('error', reject); resolve() })
|
|
613
|
+
})
|
|
614
|
+
const address = server.address()
|
|
615
|
+
if (address === null || typeof address !== 'object') throw new Error('Speech worker failed to bind a loopback port')
|
|
616
|
+
return {
|
|
617
|
+
port: address.port,
|
|
618
|
+
close: async () => {
|
|
619
|
+
await new Promise((resolve) => { server.close(() => { resolve() }) })
|
|
620
|
+
},
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Read and validate the Host payload, load the model and start the loopback server.
|
|
626
|
+
* @returns {Promise<void>} resolves once the readiness frame is written.
|
|
627
|
+
*/
|
|
628
|
+
async function main() {
|
|
629
|
+
if (process.argv[2] === undefined) throw new Error('Speech worker was started without a payload')
|
|
630
|
+
const payload = JSON.parse(process.argv[2])
|
|
631
|
+
if (!isPlainObject(payload)) throw new Error('Speech worker payload must be a JSON object')
|
|
632
|
+
const family = requiredString(payload.family, 'family')
|
|
633
|
+
const variantId = requiredString(payload.variantId, 'variantId')
|
|
634
|
+
const variantDir = requiredString(payload.variantDir, 'variantDir')
|
|
635
|
+
if (!isPlainObject(payload.config)) throw new Error('Speech worker payload is missing config')
|
|
636
|
+
const config = payload.config
|
|
637
|
+
const token = requiredString(process.env.BVI_SPEECH_TOKEN, 'BVI_SPEECH_TOKEN')
|
|
638
|
+
delete process.env.BVI_SPEECH_TOKEN
|
|
639
|
+
if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('Speech worker token must be 64 lowercase hex characters')
|
|
640
|
+
const maxAudioBytes = Number.isSafeInteger(config.maxAudioBytes) && config.maxAudioBytes >= MIN_WAV_BYTES
|
|
641
|
+
? config.maxAudioBytes
|
|
642
|
+
: MAX_WAV_BYTES
|
|
643
|
+
|
|
644
|
+
const model = LOCAL_MODELS.find((entry) => entry.family === family)
|
|
645
|
+
if (model === undefined) throw new Error(`Local model family is not in the catalog: ${family}`)
|
|
646
|
+
const variant = model.variants.find((entry) => entry.id === variantId)
|
|
647
|
+
if (variant === undefined) throw new Error(`Local model variant is not in the catalog: ${family}/${variantId}`)
|
|
648
|
+
/** @type {Record<string, string>} */
|
|
649
|
+
const paths = {}
|
|
650
|
+
for (const file of variant.files) paths[file.relativePath] = join(variantDir, ...file.relativePath.split('/'))
|
|
651
|
+
|
|
652
|
+
const adapter = adapterFor(family)
|
|
653
|
+
// sherpa-onnx-node is a CommonJS Node-API binding with no type declarations; load it here so the
|
|
654
|
+
// worker (never the Host) pays the native load.
|
|
655
|
+
const sherpa = createRequire(import.meta.url)('sherpa-onnx-node')
|
|
656
|
+
const transcriber = createTranscriber({ sherpa, model, variant, paths, adapter, config })
|
|
657
|
+
const server = await startServer({
|
|
658
|
+
token,
|
|
659
|
+
maxAudioBytes,
|
|
660
|
+
family,
|
|
661
|
+
variantId,
|
|
662
|
+
streaming: transcriber.streaming,
|
|
663
|
+
transcribe: (audio, language) => {
|
|
664
|
+
const started = performance.now()
|
|
665
|
+
const { text, audioSeconds } = transcriber.transcribe(audio, language)
|
|
666
|
+
return { text, audioSeconds, inferenceSeconds: (performance.now() - started) / 1000 }
|
|
667
|
+
},
|
|
668
|
+
})
|
|
669
|
+
process.stdout.write(`${JSON.stringify({ port: server.port })}\n`)
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
main().catch(fail)
|