@ds-hu/dsh-bvi-local 0.1.0 → 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/lib/provider.js +188 -2
- package/lib/worker/entry.js +273 -27
- package/lib/worker/runtime.js +244 -38
- package/package.json +2 -2
package/lib/provider.js
CHANGED
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
* prepare/cancel; preparation is idempotent per variant and one task runs at a time,
|
|
10
10
|
* - `transcribe` — canonical WAV validation through the core helpers, a prepared/standby check,
|
|
11
11
|
* then one worker round-trip returning `{ text, audioSeconds, inferenceSeconds }`.
|
|
12
|
+
* - `bviStreaming` — only on families whose catalog record declares `streaming: true` (X-ASR):
|
|
13
|
+
* a service-facing live session (`start({ language })` → `push/finish/cancel`) backed by the
|
|
14
|
+
* worker's private `/stream/*` routes. The batch `transcribe` path is untouched.
|
|
12
15
|
*
|
|
13
16
|
* The selected variant comes from the official `prepare(options)` call (`options.variant`, an
|
|
14
17
|
* extension of the official type used by our service) with a fallback to the bundle's
|
|
@@ -22,10 +25,10 @@
|
|
|
22
25
|
* @module @ds-hu/dsh-bvi-local/provider
|
|
23
26
|
*/
|
|
24
27
|
import { join } from 'node:path'
|
|
25
|
-
import { MAX_WAV_BYTES, validateWav } from '@ds-hu/dsh-bvi-core'
|
|
28
|
+
import { MAX_WAV_BYTES, ProviderError, validateWav } from '@ds-hu/dsh-bvi-core'
|
|
26
29
|
import { SHARED_ASSETS } from '@ds-hu/dsh-bvi-core/catalog/local.js'
|
|
27
30
|
import { downloadSourcesForVariant, ensureVariantInstalled } from './provision/install.js'
|
|
28
|
-
import { WorkerRuntime } from './worker/runtime.js'
|
|
31
|
+
import { MAX_STREAM_CHUNK_BYTES, WorkerError, WorkerRuntime } from './worker/runtime.js'
|
|
29
32
|
|
|
30
33
|
/** Official preparation phases that describe work in progress. */
|
|
31
34
|
const IN_FLIGHT_PHASES = new Set(['checking', 'downloading', 'loading', 'waking', 'cancelling'])
|
|
@@ -46,6 +49,127 @@ function bytesOf(value) {
|
|
|
46
49
|
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : undefined
|
|
47
50
|
}
|
|
48
51
|
|
|
52
|
+
/**
|
|
53
|
+
* Map a worker/runtime failure onto the ProviderError taxonomy the service relays to the client.
|
|
54
|
+
* @param {unknown} error - thrown value.
|
|
55
|
+
* @returns {import('@ds-hu/dsh-bvi-core').ProviderError} stable provider failure.
|
|
56
|
+
*/
|
|
57
|
+
function streamFailureOf(error) {
|
|
58
|
+
if (error instanceof ProviderError) return error
|
|
59
|
+
const message = messageOf(error)
|
|
60
|
+
const code = error instanceof WorkerError ? error.code : undefined
|
|
61
|
+
switch (code) {
|
|
62
|
+
case 'timeout':
|
|
63
|
+
return new ProviderError('timeout', message, { cause: error })
|
|
64
|
+
case 'http':
|
|
65
|
+
return new ProviderError('http', message, { cause: error })
|
|
66
|
+
case 'protocol':
|
|
67
|
+
return new ProviderError('parse', message, { cause: error })
|
|
68
|
+
case 'invalid-input':
|
|
69
|
+
case 'not-ready':
|
|
70
|
+
case 'queue-full':
|
|
71
|
+
case 'disposed':
|
|
72
|
+
return new ProviderError('unsupported', message, { cause: error })
|
|
73
|
+
default:
|
|
74
|
+
return new ProviderError('network', message, { cause: error })
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** One live streaming session; the service relay forwards its three methods. */
|
|
79
|
+
class LocalStreamingSession {
|
|
80
|
+
/** @type {'live'|'finishing'|'finished'|'failed'|'cancelled'} */
|
|
81
|
+
#state = 'live'
|
|
82
|
+
/** @type {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>|null} */
|
|
83
|
+
#finishPromise = null
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {WorkerRuntime} runtime - parent runtime of the prepared worker.
|
|
87
|
+
* @param {string} streamId - opaque worker session id.
|
|
88
|
+
* @param {() => void} onEnd - invoked once when the session stops holding the provider slot.
|
|
89
|
+
*/
|
|
90
|
+
constructor(runtime, streamId, onEnd) {
|
|
91
|
+
this.#runtime = runtime
|
|
92
|
+
this.#streamId = streamId
|
|
93
|
+
this.#onEnd = onEnd
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @type {WorkerRuntime} */
|
|
97
|
+
#runtime
|
|
98
|
+
/** @type {string} */
|
|
99
|
+
#streamId
|
|
100
|
+
/** @type {() => void} */
|
|
101
|
+
#onEnd
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Append one PCM16LE mono 16 kHz chunk.
|
|
105
|
+
* @param {Uint8Array} pcm - raw little-endian samples.
|
|
106
|
+
* @returns {Promise<{ partial: string }>} cumulative transcript so far.
|
|
107
|
+
* @throws {ProviderError} when the session is closed or the chunk is invalid.
|
|
108
|
+
*/
|
|
109
|
+
async push(pcm) {
|
|
110
|
+
if (this.#state !== 'live') throw new ProviderError('unsupported', 'The streaming session is not live')
|
|
111
|
+
if (!(pcm instanceof Uint8Array) || pcm.byteLength < 2 || pcm.byteLength % 2 !== 0) {
|
|
112
|
+
throw new ProviderError('unsupported', 'Streaming audio must be a non-empty Uint8Array of whole PCM16LE samples')
|
|
113
|
+
}
|
|
114
|
+
if (pcm.byteLength > MAX_STREAM_CHUNK_BYTES) {
|
|
115
|
+
throw new ProviderError('unsupported', `Streaming audio chunks must not exceed ${MAX_STREAM_CHUNK_BYTES} bytes`)
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
return await this.#runtime.pushStream(this.#streamId, pcm)
|
|
119
|
+
} catch (error) {
|
|
120
|
+
throw streamFailureOf(error)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Finish the session. The first call settles the transcript; later calls join that settlement.
|
|
126
|
+
* @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} final transcript.
|
|
127
|
+
* @throws {ProviderError} when the session is closed or the worker failed.
|
|
128
|
+
*/
|
|
129
|
+
finish() {
|
|
130
|
+
if (this.#finishPromise !== null) return this.#finishPromise
|
|
131
|
+
if (this.#state !== 'live') return Promise.reject(new ProviderError('unsupported', 'The streaming session is not live'))
|
|
132
|
+
this.#state = 'finishing'
|
|
133
|
+
this.#finishPromise = (async () => {
|
|
134
|
+
try {
|
|
135
|
+
const result = await this.#runtime.finishStream(this.#streamId)
|
|
136
|
+
this.#state = 'finished'
|
|
137
|
+
return result
|
|
138
|
+
} catch (error) {
|
|
139
|
+
this.#state = 'failed'
|
|
140
|
+
throw streamFailureOf(error)
|
|
141
|
+
} finally {
|
|
142
|
+
this.#onEnd()
|
|
143
|
+
}
|
|
144
|
+
})()
|
|
145
|
+
return this.#finishPromise
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Abort the session and release the worker stream. Idempotent; a finished session is untouched.
|
|
150
|
+
* @returns {Promise<void>} resolves after the worker acknowledged (or after a failure was swallowed).
|
|
151
|
+
*/
|
|
152
|
+
async cancel() {
|
|
153
|
+
if (this.#state === 'cancelled' || this.#state === 'finished' || this.#state === 'failed') return
|
|
154
|
+
if (this.#state === 'finishing') {
|
|
155
|
+
try {
|
|
156
|
+
await this.#finishPromise
|
|
157
|
+
} catch {
|
|
158
|
+
// A finish that already failed is reported to its caller, not to the cancelling one.
|
|
159
|
+
}
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
this.#state = 'cancelled'
|
|
163
|
+
try {
|
|
164
|
+
await this.#runtime.cancelStream(this.#streamId)
|
|
165
|
+
} catch {
|
|
166
|
+
// The worker may be gone; cancelling must still release the provider slot.
|
|
167
|
+
} finally {
|
|
168
|
+
this.#onEnd()
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
49
173
|
/**
|
|
50
174
|
* @param {{ runtime: { segmentation: string } }} model - catalog record.
|
|
51
175
|
* @returns {boolean} whether preparing this family must also install the shared VAD model.
|
|
@@ -69,6 +193,8 @@ export class LocalProvider {
|
|
|
69
193
|
#preparing = null
|
|
70
194
|
/** @type {Promise<void>|null} */
|
|
71
195
|
#wakePromise = null
|
|
196
|
+
/** @type {LocalStreamingSession|null} */
|
|
197
|
+
#stream = null
|
|
72
198
|
/** @type {boolean} */
|
|
73
199
|
#disposed = false
|
|
74
200
|
|
|
@@ -113,6 +239,11 @@ export class LocalProvider {
|
|
|
113
239
|
prepare: (options) => this.prepare(options),
|
|
114
240
|
cancel: () => this.cancel(),
|
|
115
241
|
}
|
|
242
|
+
// Our own extension object: only the families that declare `streaming: true` get one, and
|
|
243
|
+
// official consumers ignore it. The service checks it before accepting /stream/start.
|
|
244
|
+
this.bviStreaming = this.#options.model.streaming === true
|
|
245
|
+
? { start: (options) => this.#startStream(options) }
|
|
246
|
+
: undefined
|
|
116
247
|
}
|
|
117
248
|
|
|
118
249
|
/** @type {{ model: Record<string, any>, dataRoot: string, readSelectedVariant: (providerId: string) => Promise<string|undefined>, fetchImpl?: typeof fetch, downloadTimeoutMs?: number, workerOptions: Record<string, any>, logger: (message: string) => void }} */
|
|
@@ -128,6 +259,9 @@ export class LocalProvider {
|
|
|
128
259
|
/** @type {{ snapshot: () => { phase: string, [key: string]: any }, subscribe: (listener: () => void) => () => void, prepare: (options?: { variant?: string, downloadSource?: string, signal?: AbortSignal }) => Promise<void>, cancel: () => Promise<void> }} */
|
|
129
260
|
preparation
|
|
130
261
|
|
|
262
|
+
/** @type {{ start: (options?: { language?: string }) => Promise<{ push: (pcm: Uint8Array) => Promise<{ partial: string }>, finish: () => Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>, cancel: () => Promise<void> }> }|undefined} */
|
|
263
|
+
bviStreaming
|
|
264
|
+
|
|
131
265
|
/**
|
|
132
266
|
* Latest official preparation state (a detached copy).
|
|
133
267
|
* @returns {{ phase: string, [key: string]: any }} preparation snapshot.
|
|
@@ -414,6 +548,49 @@ export class LocalProvider {
|
|
|
414
548
|
return await promise
|
|
415
549
|
}
|
|
416
550
|
|
|
551
|
+
/**
|
|
552
|
+
* Open a live streaming session for the service relay.
|
|
553
|
+
*
|
|
554
|
+
* The catalog flag `streaming: true` is what lets the service offer this; an unprepared
|
|
555
|
+
* provider, an in-flight preparation or a second concurrent session are rejected with the
|
|
556
|
+
* ProviderError taxonomy. A reclaimed (standby) worker is woken exactly like the batch path.
|
|
557
|
+
* @param {{ language?: string }} [options] - selected language, already validated by the caller.
|
|
558
|
+
* @returns {Promise<{ push: (pcm: Uint8Array) => Promise<{ partial: string }>, finish: () => Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>, cancel: () => Promise<void> }>} live session handle.
|
|
559
|
+
* @throws {ProviderError} when streaming cannot start.
|
|
560
|
+
*/
|
|
561
|
+
async #startStream(options = {}) {
|
|
562
|
+
const model = this.#options.model
|
|
563
|
+
if (this.#disposed) throw new ProviderError('unsupported', `bvi-local: provider ${model.id} is disposed`)
|
|
564
|
+
if (this.#preparing !== null) throw new ProviderError('unsupported', `${model.name.zh} is still being prepared; wait until it is ready`)
|
|
565
|
+
if (this.#stream !== null) throw new ProviderError('unsupported', `${model.name.zh} already has an active streaming session`)
|
|
566
|
+
const active = this.#active
|
|
567
|
+
if (active === null) throw new ProviderError('unsupported', `${model.name.zh} is not prepared; download the model first`)
|
|
568
|
+
if (this.#state.phase !== 'ready' && this.#state.phase !== 'standby') {
|
|
569
|
+
throw new ProviderError('unsupported', this.#state.phase === 'failed'
|
|
570
|
+
? `${model.name.zh} is unavailable: ${typeof this.#state.message === 'string' ? this.#state.message : 'the local speech worker stopped'}`
|
|
571
|
+
: `${model.name.zh} is not prepared; download the model first`)
|
|
572
|
+
}
|
|
573
|
+
const language = typeof options.language === 'string' && options.language !== '' ? options.language : 'auto'
|
|
574
|
+
if (!model.languages.includes(language)) {
|
|
575
|
+
throw new ProviderError('unsupported', `${model.name.zh} does not support language: ${language}`)
|
|
576
|
+
}
|
|
577
|
+
try {
|
|
578
|
+
if (this.#runtime.snapshot().state !== 'ready') await this.#wake(active)
|
|
579
|
+
const { streamId } = await this.#runtime.startStream({ language })
|
|
580
|
+
const session = new LocalStreamingSession(this.#runtime, streamId, () => {
|
|
581
|
+
if (this.#stream === session) this.#stream = null
|
|
582
|
+
})
|
|
583
|
+
this.#stream = session
|
|
584
|
+
return {
|
|
585
|
+
push: (pcm) => session.push(pcm),
|
|
586
|
+
finish: () => session.finish(),
|
|
587
|
+
cancel: () => session.cancel(),
|
|
588
|
+
}
|
|
589
|
+
} catch (error) {
|
|
590
|
+
throw streamFailureOf(error)
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
417
594
|
/**
|
|
418
595
|
* Recognize one recording through the prepared worker.
|
|
419
596
|
* @param {{ audio: Uint8Array, language?: string }} input - official speech input.
|
|
@@ -470,6 +647,15 @@ export class LocalProvider {
|
|
|
470
647
|
// The worker is being torn down anyway.
|
|
471
648
|
}
|
|
472
649
|
}
|
|
650
|
+
const stream = this.#stream
|
|
651
|
+
if (stream !== null) {
|
|
652
|
+
try {
|
|
653
|
+
await stream.cancel()
|
|
654
|
+
} catch {
|
|
655
|
+
// The worker is being torn down anyway.
|
|
656
|
+
}
|
|
657
|
+
this.#stream = null
|
|
658
|
+
}
|
|
473
659
|
await this.#runtime.dispose()
|
|
474
660
|
this.#runtimeUnsubscribe()
|
|
475
661
|
this.#listeners.clear()
|
package/lib/worker/entry.js
CHANGED
|
@@ -9,13 +9,14 @@
|
|
|
9
9
|
* before readiness exits non-zero so the Host can surface the message in the preparation state.
|
|
10
10
|
*
|
|
11
11
|
* The loopback protocol is private: authenticated `POST /transcribe?language=<code>` with a
|
|
12
|
-
* canonical 16 kHz mono PCM16 WAV body
|
|
13
|
-
*
|
|
14
|
-
* and
|
|
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.
|
|
15
16
|
*
|
|
16
17
|
* @module @ds-hu/dsh-bvi-local/worker/entry
|
|
17
18
|
*/
|
|
18
|
-
import { timingSafeEqual } from 'node:crypto'
|
|
19
|
+
import { randomUUID, timingSafeEqual } from 'node:crypto'
|
|
19
20
|
import { createServer } from 'node:http'
|
|
20
21
|
import { createRequire } from 'node:module'
|
|
21
22
|
import { join } from 'node:path'
|
|
@@ -51,6 +52,14 @@ const XASR_MODEL_CHUNK_SECONDS = 0.480
|
|
|
51
52
|
const XASR_DRAIN_MAX_LOOPS = 512
|
|
52
53
|
/** Requests accepted before the worker starts answering `429` (the Host caps itself at 4). */
|
|
53
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'
|
|
54
63
|
|
|
55
64
|
/**
|
|
56
65
|
* Write a fatal diagnostic to stderr and exit non-zero once flushed.
|
|
@@ -90,6 +99,48 @@ function requiredString(value, name) {
|
|
|
90
99
|
return value
|
|
91
100
|
}
|
|
92
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
|
+
|
|
93
144
|
/**
|
|
94
145
|
* Decode the canonical WAV body into Float32 samples.
|
|
95
146
|
* @param {Uint8Array} audio - request body.
|
|
@@ -105,11 +156,8 @@ function decodeInput(audio) {
|
|
|
105
156
|
}
|
|
106
157
|
if (parsed.sampleRate !== SAMPLE_RATE) throw new AdapterInputError(`Invalid speech WAV: expected ${SAMPLE_RATE} Hz, received ${parsed.sampleRate} Hz`)
|
|
107
158
|
if (parsed.channels !== 1) throw new AdapterInputError('Invalid speech WAV: expected mono audio')
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
const view = new DataView(audio.buffer, audio.byteOffset + parsed.dataOffset, count * 2)
|
|
111
|
-
for (let index = 0; index < count; index += 1) samples[index] = view.getInt16(index * 2, true) / 32768
|
|
112
|
-
return { samples, audioSeconds: parsed.dataBytes / (SAMPLE_RATE * 2) }
|
|
159
|
+
const samples = pcm16ToFloat32(audio.subarray(parsed.dataOffset, parsed.dataOffset + parsed.dataBytes))
|
|
160
|
+
return { samples, audioSeconds: pcm16Seconds(parsed.dataBytes) }
|
|
113
161
|
}
|
|
114
162
|
|
|
115
163
|
/**
|
|
@@ -135,10 +183,125 @@ function createVad(sherpa, vadPath) {
|
|
|
135
183
|
}, VAD_MAX_SPEECH_SECONDS + VAD_MIN_SILENCE_SECONDS + 1)
|
|
136
184
|
}
|
|
137
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
|
+
|
|
138
301
|
/**
|
|
139
302
|
* Own one loaded recognizer and the family-specific decode policy.
|
|
140
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.
|
|
141
|
-
* @returns {{ transcribe: (audio: Uint8Array, language: string) => Record<string, any> }} synchronous transcription handle.
|
|
304
|
+
* @returns {{ transcribe: (audio: Uint8Array, language: string) => Record<string, any>, streaming?: ReturnType<typeof createStreamingSession> }} synchronous transcription handle plus the optional live-stream manager.
|
|
142
305
|
*/
|
|
143
306
|
function createTranscriber(options) {
|
|
144
307
|
const { sherpa, model, adapter, paths, config } = options
|
|
@@ -151,7 +314,12 @@ function createTranscriber(options) {
|
|
|
151
314
|
|
|
152
315
|
if (model.runtime.kind === 'online') {
|
|
153
316
|
const recognizer = new sherpa.OnlineRecognizer(adapter.configure(paths, { threads }))
|
|
154
|
-
|
|
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 }
|
|
155
323
|
}
|
|
156
324
|
|
|
157
325
|
const recognizer = new sherpa.OfflineRecognizer(adapter.configure(paths, { threads, language: 'auto' }))
|
|
@@ -248,30 +416,19 @@ function transcribeOnline(recognizer, adapter, audio, language) {
|
|
|
248
416
|
adapter.validateLanguage(language)
|
|
249
417
|
const { samples, audioSeconds } = decodeInput(audio)
|
|
250
418
|
const stream = recognizer.createStream()
|
|
251
|
-
const drain = () => {
|
|
252
|
-
let loops = 0
|
|
253
|
-
while (recognizer.isReady(stream) && loops < XASR_DRAIN_MAX_LOOPS) {
|
|
254
|
-
recognizer.decode(stream)
|
|
255
|
-
loops += 1
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
419
|
for (let offset = 0; offset < samples.length; offset += XASR_FRAME_SAMPLES) {
|
|
259
420
|
stream.acceptWaveform({ samples: samples.subarray(offset, offset + XASR_FRAME_SAMPLES), sampleRate: SAMPLE_RATE })
|
|
260
|
-
|
|
261
|
-
while (recognizer.isReady(stream) && loops < XASR_MAX_DECODE_LOOPS) {
|
|
262
|
-
recognizer.decode(stream)
|
|
263
|
-
loops += 1
|
|
264
|
-
}
|
|
421
|
+
decodeReady(recognizer, stream)
|
|
265
422
|
}
|
|
266
|
-
|
|
423
|
+
drainReady(recognizer, stream)
|
|
267
424
|
// Two model chunks of silence stop the last characters from being dropped (docs §8.3).
|
|
268
425
|
const padding = new Float32Array(Math.round(XASR_MODEL_CHUNK_SECONDS * SAMPLE_RATE))
|
|
269
426
|
for (let index = 0; index < XASR_TAIL_PADDING_CHUNKS; index += 1) {
|
|
270
427
|
stream.acceptWaveform({ samples: padding, sampleRate: SAMPLE_RATE })
|
|
271
|
-
|
|
428
|
+
drainReady(recognizer, stream)
|
|
272
429
|
}
|
|
273
430
|
stream.inputFinished()
|
|
274
|
-
|
|
431
|
+
drainReady(recognizer, stream)
|
|
275
432
|
return { text: adapter.sanitize(recognizer.getResult(stream).text), audioSeconds }
|
|
276
433
|
}
|
|
277
434
|
|
|
@@ -289,7 +446,14 @@ async function readBody(request) {
|
|
|
289
446
|
|
|
290
447
|
/**
|
|
291
448
|
* Bind the authenticated loopback listener.
|
|
292
|
-
* @param {{
|
|
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.
|
|
293
457
|
* @returns {Promise<{ port: number, close: () => Promise<void> }>} listening server handle.
|
|
294
458
|
*/
|
|
295
459
|
async function startServer(options) {
|
|
@@ -328,6 +492,87 @@ async function startServer(options) {
|
|
|
328
492
|
reply(200, { ok: true, family: options.family, variant: options.variantId })
|
|
329
493
|
return
|
|
330
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
|
+
}
|
|
331
576
|
if (request.method !== 'POST' || url.pathname !== '/transcribe') {
|
|
332
577
|
request.resume()
|
|
333
578
|
reply(404, { error: 'Unknown endpoint', code: 'not-found' })
|
|
@@ -414,6 +659,7 @@ async function main() {
|
|
|
414
659
|
maxAudioBytes,
|
|
415
660
|
family,
|
|
416
661
|
variantId,
|
|
662
|
+
streaming: transcriber.streaming,
|
|
417
663
|
transcribe: (audio, language) => {
|
|
418
664
|
const started = performance.now()
|
|
419
665
|
const { text, audioSeconds } = transcriber.transcribe(audio, language)
|
package/lib/worker/runtime.js
CHANGED
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
* start a fresh process without re-downloading anything. `dispose()` synchronously withdraws the
|
|
13
13
|
* worker and joins its exit, so unloading the provider never leaves an orphan process.
|
|
14
14
|
*
|
|
15
|
+
* The streaming client (`startStream/pushStream/finishStream/cancelStream`) speaks the worker's
|
|
16
|
+
* X-ASR `/stream/*` routes over the same transport. One live stream is tracked per runtime: it
|
|
17
|
+
* suppresses the idle reclaim, keeps ordinary transcriptions waiting until it is released (the
|
|
18
|
+
* native recognizer is shared), and is dropped when the worker crashes or the runtime is stopped.
|
|
19
|
+
*
|
|
15
20
|
* @module @ds-hu/dsh-bvi-local/worker/runtime
|
|
16
21
|
*/
|
|
17
22
|
import { fork } from 'node:child_process'
|
|
@@ -35,6 +40,10 @@ export const DEFAULT_MAX_PENDING = 4
|
|
|
35
40
|
const DEFAULT_GRACE_MS = 1_000
|
|
36
41
|
/** Default worker entry next to this module. */
|
|
37
42
|
const DEFAULT_ENTRY_PATH = fileURLToPath(new URL('./entry.js', import.meta.url))
|
|
43
|
+
/** Largest raw PCM16LE chunk forwarded to a streaming worker (the service matches this bound). */
|
|
44
|
+
export const MAX_STREAM_CHUNK_BYTES = 1024 * 1024
|
|
45
|
+
/** Smallest meaningful streaming chunk (one mono 16 kHz PCM16 sample). */
|
|
46
|
+
const MIN_STREAM_CHUNK_BYTES = 2
|
|
38
47
|
|
|
39
48
|
/** A worker that is unavailable, crashed, timed out or rejected input, with a stable code. */
|
|
40
49
|
export class WorkerError extends Error {
|
|
@@ -111,6 +120,10 @@ export class WorkerRuntime {
|
|
|
111
120
|
#lifetime = new AbortController()
|
|
112
121
|
/** @type {boolean} */
|
|
113
122
|
#stopping = false
|
|
123
|
+
/** @type {{ id: string, language: string }|null} */
|
|
124
|
+
#stream = null
|
|
125
|
+
/** @type {Set<() => void>} */
|
|
126
|
+
#streamWaiters = new Set()
|
|
114
127
|
|
|
115
128
|
/**
|
|
116
129
|
* @param {{
|
|
@@ -155,10 +168,11 @@ export class WorkerRuntime {
|
|
|
155
168
|
}
|
|
156
169
|
|
|
157
170
|
/**
|
|
158
|
-
* @returns {{ state: 'idle'|'starting'|'ready'|'failed', message?: string }} latest runtime state.
|
|
171
|
+
* @returns {{ state: 'idle'|'starting'|'ready'|'failed', message?: string, streaming: boolean }} latest runtime state.
|
|
159
172
|
*/
|
|
160
173
|
snapshot() {
|
|
161
|
-
|
|
174
|
+
const snapshot = { state: this.#state, streaming: this.#stream !== null }
|
|
175
|
+
return this.#message === undefined ? snapshot : { ...snapshot, message: this.#message }
|
|
162
176
|
}
|
|
163
177
|
|
|
164
178
|
/**
|
|
@@ -189,7 +203,7 @@ export class WorkerRuntime {
|
|
|
189
203
|
#scheduleIdle() {
|
|
190
204
|
this.#clearIdle()
|
|
191
205
|
const { idleTimeoutMs } = this.#options
|
|
192
|
-
if (!(idleTimeoutMs > 0) || this.#disposed || this.#state !== 'ready' || this.#pending > 0) return
|
|
206
|
+
if (!(idleTimeoutMs > 0) || this.#disposed || this.#state !== 'ready' || this.#pending > 0 || this.#stream !== null) return
|
|
193
207
|
this.#idleTimer = setTimeout(() => {
|
|
194
208
|
this.#idleTimer = undefined
|
|
195
209
|
if (this.#state !== 'ready' || this.#pending > 0) return
|
|
@@ -198,6 +212,107 @@ export class WorkerRuntime {
|
|
|
198
212
|
this.#idleTimer.unref?.()
|
|
199
213
|
}
|
|
200
214
|
|
|
215
|
+
/**
|
|
216
|
+
* Release the live streaming session and wake the transcriptions waiting on it.
|
|
217
|
+
* @returns {void}
|
|
218
|
+
*/
|
|
219
|
+
#releaseStream() {
|
|
220
|
+
this.#stream = null
|
|
221
|
+
for (const resolve of this.#streamWaiters) resolve()
|
|
222
|
+
this.#streamWaiters.clear()
|
|
223
|
+
this.#scheduleIdle()
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Resolve once no streaming session is live.
|
|
228
|
+
* @param {AbortSignal|undefined} signal - caller cancellation.
|
|
229
|
+
* @returns {Promise<void>} resolves when the stream was released.
|
|
230
|
+
*/
|
|
231
|
+
#streamIdle(signal) {
|
|
232
|
+
if (this.#stream === null) return Promise.resolve()
|
|
233
|
+
return raceWithAbort(new Promise((resolve) => { this.#streamWaiters.add(resolve) }), signal)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Validate that a known live stream is being addressed on a ready worker.
|
|
238
|
+
* @param {string} streamId - opaque session id returned by `startStream`.
|
|
239
|
+
* @returns {{ id: string, language: string }} the live session.
|
|
240
|
+
* @throws {WorkerError} when the runtime, worker or session is not in the expected state.
|
|
241
|
+
*/
|
|
242
|
+
#requireStream(streamId) {
|
|
243
|
+
if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
|
|
244
|
+
if (this.#state !== 'ready' || this.#worker === null) {
|
|
245
|
+
throw new WorkerError('not-ready', this.#state === 'failed' && this.#message !== undefined
|
|
246
|
+
? this.#message
|
|
247
|
+
: 'The local speech worker is not running; prepare the model first')
|
|
248
|
+
}
|
|
249
|
+
const stream = this.#stream
|
|
250
|
+
if (stream === null) throw new WorkerError('not-ready', 'No local streaming session is active')
|
|
251
|
+
if (stream.id !== streamId) throw new WorkerError('invalid-input', `Unknown local streaming session: ${String(streamId)}`)
|
|
252
|
+
return stream
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Map a non-200 streaming answer onto the runtime error taxonomy.
|
|
257
|
+
* @param {number} status - HTTP status.
|
|
258
|
+
* @param {Record<string, any>} payload - parsed body.
|
|
259
|
+
* @param {string} action - short infinitive for the fallback message.
|
|
260
|
+
* @returns {WorkerError} the mapped failure.
|
|
261
|
+
*/
|
|
262
|
+
#streamFailure(status, payload, action) {
|
|
263
|
+
const detail = typeof payload.error === 'string' ? payload.error : `Local speech worker returned HTTP ${status}`
|
|
264
|
+
if (status === 400 || status === 404 || status === 413 || status === 415) return new WorkerError('invalid-input', detail)
|
|
265
|
+
if (status === 409 || status === 429) return new WorkerError('queue-full', detail)
|
|
266
|
+
return new WorkerError('http', `${detail} (while trying to ${action})`)
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* POST one authenticated loopback request and parse the JSON answer.
|
|
271
|
+
* @param {string} path - route with query string.
|
|
272
|
+
* @param {{ body?: Uint8Array, contentType?: string, signal?: AbortSignal, timeoutMs?: number, label?: string }} [options] - body, headers and cancellation.
|
|
273
|
+
* @returns {Promise<{ status: number, payload: Record<string, any> }>} response status and parsed body.
|
|
274
|
+
* @throws {WorkerError} when the worker is not ready, timed out or the transport failed.
|
|
275
|
+
*/
|
|
276
|
+
async #request(path, options = {}) {
|
|
277
|
+
const info = this.#worker
|
|
278
|
+
if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
|
|
279
|
+
if (this.#state !== 'ready' || info === null) {
|
|
280
|
+
throw new WorkerError('not-ready', this.#state === 'failed' && this.#message !== undefined
|
|
281
|
+
? this.#message
|
|
282
|
+
: 'The local speech worker is not running; prepare the model first')
|
|
283
|
+
}
|
|
284
|
+
const label = options.label ?? 'Local speech worker request'
|
|
285
|
+
const timeoutMs = options.timeoutMs ?? this.#options.inferenceTimeoutMs
|
|
286
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
287
|
+
let timedOut = false
|
|
288
|
+
timeout.addEventListener('abort', () => { timedOut = true }, { once: true })
|
|
289
|
+
const combined = options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
|
|
290
|
+
/** @type {Record<string, string>} */
|
|
291
|
+
const headers = { authorization: `Bearer ${info.token}` }
|
|
292
|
+
if (options.contentType !== undefined) headers['content-type'] = options.contentType
|
|
293
|
+
if (options.body !== undefined) headers['content-length'] = String(options.body.byteLength)
|
|
294
|
+
/** @type {Response} */
|
|
295
|
+
let response
|
|
296
|
+
try {
|
|
297
|
+
response = await this.#options.fetchImpl(`http://127.0.0.1:${info.port}${path}`, {
|
|
298
|
+
method: 'POST',
|
|
299
|
+
headers,
|
|
300
|
+
body: options.body,
|
|
301
|
+
signal: combined,
|
|
302
|
+
})
|
|
303
|
+
} catch (error) {
|
|
304
|
+
if (options.signal !== undefined && options.signal.aborted) throw abortReasonOf(options.signal)
|
|
305
|
+
if (timedOut) {
|
|
306
|
+
await this.stop('timeout').catch(() => undefined)
|
|
307
|
+
throw new WorkerError('timeout', `${label} timed out after ${timeoutMs} ms`)
|
|
308
|
+
}
|
|
309
|
+
throw new WorkerError('crash', `${label} failed: ${messageOf(error)}`, { cause: error })
|
|
310
|
+
}
|
|
311
|
+
const payload = await response.json().catch(() => ({}))
|
|
312
|
+
if (!isPlainObject(payload)) return { status: response.status, payload: {} }
|
|
313
|
+
return { status: response.status, payload }
|
|
314
|
+
}
|
|
315
|
+
|
|
201
316
|
/**
|
|
202
317
|
* Wait for the worker's single readiness line, its exit, or cancellation.
|
|
203
318
|
* @param {import('node:child_process').ChildProcess} child - running worker.
|
|
@@ -332,13 +447,18 @@ export class WorkerRuntime {
|
|
|
332
447
|
this.#clearIdle()
|
|
333
448
|
if (this.#disposed) {
|
|
334
449
|
this.#setState('idle')
|
|
450
|
+
this.#releaseStream()
|
|
451
|
+
return
|
|
452
|
+
}
|
|
453
|
+
if (this.#stopping) {
|
|
454
|
+
this.#releaseStream()
|
|
335
455
|
return
|
|
336
456
|
}
|
|
337
|
-
if (this.#stopping) return
|
|
338
457
|
const tail = stderrTail.trim()
|
|
339
458
|
const detail = `Local speech worker exited (${signalName ?? `code ${code}`})${tail === '' ? '' : `: ${tail}`}`
|
|
340
459
|
this.#options.logger(detail)
|
|
341
460
|
this.#setState('failed', detail)
|
|
461
|
+
this.#releaseStream()
|
|
342
462
|
})
|
|
343
463
|
this.#setState('ready')
|
|
344
464
|
this.#scheduleIdle()
|
|
@@ -403,6 +523,9 @@ export class WorkerRuntime {
|
|
|
403
523
|
|
|
404
524
|
/**
|
|
405
525
|
* Recognize one canonical WAV recording.
|
|
526
|
+
*
|
|
527
|
+
* A live streaming session owns the recognizer until it finishes or is cancelled, so a batch
|
|
528
|
+
* transcription issued meanwhile waits for it instead of racing the same native model.
|
|
406
529
|
* @param {{ audio: Uint8Array, language: string, signal?: AbortSignal }} request - audio and language hint.
|
|
407
530
|
* @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} transcript.
|
|
408
531
|
* @throws {WorkerError} when the worker is unavailable, busy, timed out or rejected the audio.
|
|
@@ -410,55 +533,33 @@ export class WorkerRuntime {
|
|
|
410
533
|
async transcribe(request) {
|
|
411
534
|
const { audio, language, signal } = request
|
|
412
535
|
if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
|
|
413
|
-
|
|
414
|
-
if (this.#state !== 'ready' || info === null) {
|
|
536
|
+
if (this.#state !== 'ready' || this.#worker === null) {
|
|
415
537
|
throw new WorkerError('not-ready', this.#state === 'failed' && this.#message !== undefined
|
|
416
538
|
? this.#message
|
|
417
539
|
: 'The local speech worker is not running; prepare the model first')
|
|
418
540
|
}
|
|
541
|
+
if (this.#stream !== null) await this.#streamIdle(signal)
|
|
419
542
|
if (this.#pending >= this.#options.maxPending) {
|
|
420
543
|
throw new WorkerError('queue-full', `The local speech worker already has ${this.#pending} pending transcriptions`)
|
|
421
544
|
}
|
|
422
545
|
this.#pending += 1
|
|
423
546
|
this.#clearIdle()
|
|
424
|
-
const timeout = AbortSignal.timeout(this.#options.inferenceTimeoutMs)
|
|
425
|
-
let timedOut = false
|
|
426
|
-
timeout.addEventListener('abort', () => { timedOut = true }, { once: true })
|
|
427
|
-
const combined = signal === undefined ? timeout : AbortSignal.any([signal, timeout])
|
|
428
|
-
const url = `http://127.0.0.1:${info.port}/transcribe?language=${encodeURIComponent(language)}`
|
|
429
547
|
const job = async () => {
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
'content-type': 'audio/wav',
|
|
438
|
-
'content-length': String(audio.byteLength),
|
|
439
|
-
},
|
|
440
|
-
body: audio,
|
|
441
|
-
signal: combined,
|
|
442
|
-
})
|
|
443
|
-
} catch (error) {
|
|
444
|
-
if (signal !== undefined && signal.aborted) throw abortReasonOf(signal)
|
|
445
|
-
if (timedOut) {
|
|
446
|
-
await this.stop('timeout').catch(() => undefined)
|
|
447
|
-
throw new WorkerError('timeout', `Local transcription timed out after ${this.#options.inferenceTimeoutMs} ms`)
|
|
448
|
-
}
|
|
449
|
-
throw new WorkerError('crash', `Local speech worker request failed: ${messageOf(error)}`, { cause: error })
|
|
450
|
-
}
|
|
451
|
-
/** @type {Record<string, any>} */
|
|
452
|
-
const payload = await response.json().catch(() => ({}))
|
|
453
|
-
if (response.status === 200) {
|
|
548
|
+
const { status, payload } = await this.#request(`/transcribe?language=${encodeURIComponent(language)}`, {
|
|
549
|
+
body: audio,
|
|
550
|
+
contentType: 'audio/wav',
|
|
551
|
+
signal,
|
|
552
|
+
label: 'Local transcription',
|
|
553
|
+
})
|
|
554
|
+
if (status === 200) {
|
|
454
555
|
if (typeof payload.text !== 'string' || typeof payload.audioSeconds !== 'number' || typeof payload.inferenceSeconds !== 'number') {
|
|
455
556
|
throw new WorkerError('protocol', 'Local speech worker returned an invalid transcript payload')
|
|
456
557
|
}
|
|
457
558
|
return { text: payload.text, audioSeconds: payload.audioSeconds, inferenceSeconds: payload.inferenceSeconds }
|
|
458
559
|
}
|
|
459
|
-
const detail = typeof payload.error === 'string' ? payload.error : `Local speech worker returned HTTP ${
|
|
460
|
-
if (
|
|
461
|
-
if (
|
|
560
|
+
const detail = typeof payload.error === 'string' ? payload.error : `Local speech worker returned HTTP ${status}`
|
|
561
|
+
if (status === 400 || status === 413) throw new WorkerError('invalid-input', detail)
|
|
562
|
+
if (status === 429) throw new WorkerError('queue-full', detail)
|
|
462
563
|
throw new WorkerError('http', detail)
|
|
463
564
|
}
|
|
464
565
|
const run = this.#tail.then(job, job)
|
|
@@ -471,6 +572,109 @@ export class WorkerRuntime {
|
|
|
471
572
|
}
|
|
472
573
|
}
|
|
473
574
|
|
|
575
|
+
/**
|
|
576
|
+
* Open one live streaming session on the X-ASR worker.
|
|
577
|
+
* @param {{ language?: string, signal?: AbortSignal }} [request] - selected language and cancellation.
|
|
578
|
+
* @returns {Promise<{ streamId: string }>} opaque worker session id.
|
|
579
|
+
* @throws {WorkerError} when the worker is not ready or already has a live stream.
|
|
580
|
+
*/
|
|
581
|
+
async startStream(request = {}) {
|
|
582
|
+
const language = typeof request.language === 'string' && request.language !== '' ? request.language : 'auto'
|
|
583
|
+
if (this.#disposed) throw new WorkerError('disposed', 'The local speech worker runtime is disposed')
|
|
584
|
+
if (this.#stream !== null) throw new WorkerError('queue-full', 'A local streaming session is already active')
|
|
585
|
+
const { status, payload } = await this.#request(`/stream/start?language=${encodeURIComponent(language)}`, {
|
|
586
|
+
signal: request.signal,
|
|
587
|
+
label: 'Local streaming start',
|
|
588
|
+
})
|
|
589
|
+
if (status !== 200) throw this.#streamFailure(status, payload, 'start the streaming session')
|
|
590
|
+
if (typeof payload.streamId !== 'string' || payload.streamId === '') {
|
|
591
|
+
throw new WorkerError('protocol', 'Local speech worker returned an invalid streaming session')
|
|
592
|
+
}
|
|
593
|
+
this.#stream = { id: payload.streamId, language }
|
|
594
|
+
this.#clearIdle()
|
|
595
|
+
return { streamId: payload.streamId }
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Push one raw PCM16LE mono 16 kHz chunk into the live session.
|
|
600
|
+
* @param {string} streamId - opaque session id returned by `startStream`.
|
|
601
|
+
* @param {Uint8Array} pcm - PCM16LE bytes.
|
|
602
|
+
* @param {{ signal?: AbortSignal }} [request] - caller cancellation.
|
|
603
|
+
* @returns {Promise<{ partial: string }>} cumulative transcript so far (may be empty).
|
|
604
|
+
* @throws {WorkerError} when the session is gone or the chunk is invalid.
|
|
605
|
+
*/
|
|
606
|
+
async pushStream(streamId, pcm, request = {}) {
|
|
607
|
+
this.#requireStream(streamId)
|
|
608
|
+
if (!(pcm instanceof Uint8Array) || pcm.byteLength < MIN_STREAM_CHUNK_BYTES || pcm.byteLength % 2 !== 0) {
|
|
609
|
+
throw new WorkerError('invalid-input', 'Streaming audio must be a non-empty Uint8Array of whole PCM16LE samples')
|
|
610
|
+
}
|
|
611
|
+
if (pcm.byteLength > MAX_STREAM_CHUNK_BYTES) {
|
|
612
|
+
throw new WorkerError('invalid-input', `Streaming audio chunks must not exceed ${MAX_STREAM_CHUNK_BYTES} bytes`)
|
|
613
|
+
}
|
|
614
|
+
const { status, payload } = await this.#request(`/stream/chunk?stream=${encodeURIComponent(streamId)}`, {
|
|
615
|
+
body: pcm,
|
|
616
|
+
contentType: 'application/octet-stream',
|
|
617
|
+
signal: request.signal,
|
|
618
|
+
label: 'Local streaming chunk',
|
|
619
|
+
})
|
|
620
|
+
if (status !== 200) throw this.#streamFailure(status, payload, 'push streaming audio')
|
|
621
|
+
if (typeof payload.partial !== 'string') {
|
|
622
|
+
throw new WorkerError('protocol', 'Local speech worker returned an invalid streaming partial')
|
|
623
|
+
}
|
|
624
|
+
return { partial: payload.partial }
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Finish the live session with the documented drain protocol and return the final transcript.
|
|
629
|
+
* @param {string} streamId - opaque session id returned by `startStream`.
|
|
630
|
+
* @param {{ signal?: AbortSignal }} [request] - caller cancellation.
|
|
631
|
+
* @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} final transcript.
|
|
632
|
+
* @throws {WorkerError} when the session is gone or the worker failed.
|
|
633
|
+
*/
|
|
634
|
+
async finishStream(streamId, request = {}) {
|
|
635
|
+
const stream = this.#requireStream(streamId)
|
|
636
|
+
const started = performance.now()
|
|
637
|
+
try {
|
|
638
|
+
const { status, payload } = await this.#request(`/stream/finish?stream=${encodeURIComponent(streamId)}`, {
|
|
639
|
+
signal: request.signal,
|
|
640
|
+
label: 'Local streaming finish',
|
|
641
|
+
})
|
|
642
|
+
if (status !== 200) throw this.#streamFailure(status, payload, 'finish the streaming session')
|
|
643
|
+
if (typeof payload.text !== 'string' || typeof payload.audioSeconds !== 'number' || !Number.isFinite(payload.audioSeconds)) {
|
|
644
|
+
throw new WorkerError('protocol', 'Local speech worker returned an invalid streaming transcript')
|
|
645
|
+
}
|
|
646
|
+
return {
|
|
647
|
+
text: payload.text,
|
|
648
|
+
audioSeconds: payload.audioSeconds,
|
|
649
|
+
inferenceSeconds: (performance.now() - started) / 1000,
|
|
650
|
+
}
|
|
651
|
+
} finally {
|
|
652
|
+
if (this.#stream === stream) this.#releaseStream()
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Cancel the live session. Tolerant: a session that is already gone answers `{ ok: false }`.
|
|
658
|
+
* @param {string} streamId - opaque session id returned by `startStream`.
|
|
659
|
+
* @param {{ signal?: AbortSignal }} [request] - caller cancellation.
|
|
660
|
+
* @returns {Promise<{ ok: boolean }>} whether the worker acknowledged the cancel.
|
|
661
|
+
* @throws {WorkerError} when the worker itself is not running.
|
|
662
|
+
*/
|
|
663
|
+
async cancelStream(streamId, request = {}) {
|
|
664
|
+
const stream = this.#stream
|
|
665
|
+
if (stream === null || stream.id !== streamId) return { ok: false }
|
|
666
|
+
try {
|
|
667
|
+
const { status, payload } = await this.#request(`/stream/cancel?stream=${encodeURIComponent(streamId)}`, {
|
|
668
|
+
signal: request.signal,
|
|
669
|
+
label: 'Local streaming cancel',
|
|
670
|
+
})
|
|
671
|
+
if (status !== 200) throw this.#streamFailure(status, payload, 'cancel the streaming session')
|
|
672
|
+
return { ok: true }
|
|
673
|
+
} finally {
|
|
674
|
+
if (this.#stream === stream) this.#releaseStream()
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
474
678
|
/**
|
|
475
679
|
* Stop the worker process (idle reclaim, variant switch, timeout or dispose).
|
|
476
680
|
* @param {string} [reason] - diagnostic reason passed to the logger.
|
|
@@ -478,6 +682,7 @@ export class WorkerRuntime {
|
|
|
478
682
|
*/
|
|
479
683
|
async stop(reason = 'stop') {
|
|
480
684
|
this.#clearIdle()
|
|
685
|
+
this.#releaseStream()
|
|
481
686
|
const info = this.#worker
|
|
482
687
|
if (info === null) {
|
|
483
688
|
if (!this.#disposed && this.#state === 'starting') this.#setState('idle')
|
|
@@ -510,6 +715,7 @@ export class WorkerRuntime {
|
|
|
510
715
|
this.#disposed = true
|
|
511
716
|
this.#lifetime.abort(new Error('The local speech worker runtime was disposed'))
|
|
512
717
|
this.#clearIdle()
|
|
718
|
+
this.#releaseStream()
|
|
513
719
|
const starting = this.#starting
|
|
514
720
|
if (starting !== null) {
|
|
515
721
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ds-hu/dsh-bvi-local",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "More speech models, local: SenseVoice, FunASR Nano, Qwen3-ASR, Parakeet, GigaAM, FireRedASR and X-ASR run on this machine through sherpa-onnx; models download and verify on first use.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
},
|
|
13
13
|
"icon": "./icon.svg",
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@ds-hu/dsh-bvi-core": "0.
|
|
15
|
+
"@ds-hu/dsh-bvi-core": "0.2.0",
|
|
16
16
|
"sherpa-onnx-node": "^1.13.8"
|
|
17
17
|
},
|
|
18
18
|
"peerDependencies": {
|