@ds-hu/dsh-bvi-local 0.0.0-stage → 0.1.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 +505 -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 +426 -0
- package/lib/worker/runtime.js +556 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +41 -4
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the dsh-better-voice-input authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
dsh-better-voice-input
|
|
2
|
+
Copyright (c) 2026 the dsh-better-voice-input authors
|
|
3
|
+
|
|
4
|
+
The `icon.svg` and `docs/preview*.svg` artwork is original to this project and is
|
|
5
|
+
distributed under the same MIT license as the rest of the package.
|
|
6
|
+
|
|
7
|
+
This project is a plugin for DeepSeek Harness and extends the official
|
|
8
|
+
experimental voice input bundle. The DeepSeek Harness packages it integrates
|
|
9
|
+
with are licensed under the MIT License:
|
|
10
|
+
https://github.com/deepseek-ai/deepseek-harness
|
|
11
|
+
|
|
12
|
+
The local-model runtime uses sherpa-onnx through the `sherpa-onnx-node` npm
|
|
13
|
+
package. sherpa-onnx is Copyright (c) 2023-2026 k2-fsa and is licensed under the
|
|
14
|
+
Apache License, Version 2.0:
|
|
15
|
+
https://github.com/k2-fsa/sherpa-onnx
|
|
16
|
+
|
|
17
|
+
Local speech models are downloaded by the user's explicit request from the
|
|
18
|
+
upstream sherpa-onnx model releases on Hugging Face, not redistributed in this
|
|
19
|
+
package. Each model keeps its own license and attribution, which the settings
|
|
20
|
+
page links to:
|
|
21
|
+
https://huggingface.co/csukuangfj
|
|
22
|
+
|
|
23
|
+
The provider/model list follows BryceWG/BiBi-Keyboard ("说点啥"), an Android
|
|
24
|
+
voice-input project licensed under the Apache License, Version 2.0. Only its
|
|
25
|
+
public model/provider list and public vendor API facts were used as a reference;
|
|
26
|
+
no Android implementation or user-interface code was copied:
|
|
27
|
+
https://github.com/BryceWG/BiBi-Keyboard
|
|
28
|
+
|
|
29
|
+
Cloud providers are implemented against each vendor's public HTTP API; their
|
|
30
|
+
names and trademarks belong to their owners. No endorsement by any vendor is
|
|
31
|
+
implied.
|
package/icon.svg
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
|
|
2
|
+
<rect x="8" y="8" width="20" height="20" rx="4" fill="none" stroke="#3b82f6" stroke-width="2.2"/>
|
|
3
|
+
<g fill="none" stroke="#3b82f6" stroke-linecap="round" stroke-width="2">
|
|
4
|
+
<path d="M14 19.5v2"/>
|
|
5
|
+
<path d="M18 15.5v10"/>
|
|
6
|
+
<path d="M22 17.5v6"/>
|
|
7
|
+
</g>
|
|
8
|
+
<g fill="#3b82f6">
|
|
9
|
+
<rect x="6" y="12" width="4" height="2" rx="1"/>
|
|
10
|
+
<rect x="6" y="22" width="4" height="2" rx="1"/>
|
|
11
|
+
<rect x="26" y="12" width="4" height="2" rx="1"/>
|
|
12
|
+
<rect x="26" y="22" width="4" height="2" rx="1"/>
|
|
13
|
+
</g>
|
|
14
|
+
</svg>
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bvi-local` — the local half of "more speech models".
|
|
3
|
+
*
|
|
4
|
+
* Registers one official `ctx.speechToText` provider per local sherpa-onnx family (7 in total)
|
|
5
|
+
* when the row is active. The row declares `speechToText` as a hard injection, so it stays
|
|
6
|
+
* inactive while the official experimental speech-to-text row is disabled — Cordis handles that,
|
|
7
|
+
* the plugin must not swallow registration errors.
|
|
8
|
+
*
|
|
9
|
+
* Model files live under the row's `dataRoot` (cordis.patch.yml points it at
|
|
10
|
+
* `<DSH_HOME>/better-voice-input/models`). The selected variant is normally passed by the service
|
|
11
|
+
* as `prepare({ variant })`; as a fallback the provider reads the bundle configuration document
|
|
12
|
+
* (`<DSH_HOME>/better-voice-input/config.json`, the service row's default data root) so a
|
|
13
|
+
* non-default variant also works when the provider is driven directly.
|
|
14
|
+
*
|
|
15
|
+
* @module @ds-hu/dsh-bvi-local
|
|
16
|
+
*/
|
|
17
|
+
import { readConfig, resolveDataRoot } from '@ds-hu/dsh-bvi-core'
|
|
18
|
+
import { LOCAL_MODELS } from '@ds-hu/dsh-bvi-core/catalog/local.js'
|
|
19
|
+
|
|
20
|
+
import { createLocalProvider } from './provider.js'
|
|
21
|
+
|
|
22
|
+
export const name = 'bvi-local'
|
|
23
|
+
export const inject = ['speechToText']
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {any} ctx cordis context of the row.
|
|
27
|
+
* @returns {((...segments: string[]) => string)|undefined} the `dshHomePath` helper when available.
|
|
28
|
+
*/
|
|
29
|
+
function dshHomePathOf(ctx) {
|
|
30
|
+
const helper = typeof ctx.get === 'function' ? ctx.get('dshHomePath') : undefined
|
|
31
|
+
return typeof helper === 'function' ? helper : undefined
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Resolve the absolute model directory.
|
|
36
|
+
*
|
|
37
|
+
* `config.dataRoot` wins (the patch supplies `<DSH_HOME>/better-voice-input/models`); otherwise the
|
|
38
|
+
* runtime `dshHomePath` service is the authoritative source. A guessed home directory is never
|
|
39
|
+
* used, because the host process does not necessarily export `DSH_HOME`.
|
|
40
|
+
* @param {any} ctx cordis context of the row.
|
|
41
|
+
* @param {{ dataRoot?: string } | undefined} config row config.
|
|
42
|
+
* @returns {string} absolute model root.
|
|
43
|
+
* @throws {Error} when neither the row config nor `dshHomePath` provides a directory.
|
|
44
|
+
*/
|
|
45
|
+
function resolveModelsRoot(ctx, config) {
|
|
46
|
+
if (typeof config?.dataRoot === 'string' && config.dataRoot.trim() !== '') return resolveDataRoot(config.dataRoot)
|
|
47
|
+
const dshHomePath = dshHomePathOf(ctx)
|
|
48
|
+
if (dshHomePath === undefined) {
|
|
49
|
+
throw new Error('bvi-local: cannot resolve the model directory (set the row dataRoot or provide the dshHomePath service)')
|
|
50
|
+
}
|
|
51
|
+
return resolveDataRoot(dshHomePath('better-voice-input', 'models'))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Resolve the bundle state directory that holds `config.json` (the service row's default root).
|
|
56
|
+
* @param {any} ctx cordis context of the row.
|
|
57
|
+
* @returns {string|undefined} absolute state root, or undefined when only a custom model root exists.
|
|
58
|
+
*/
|
|
59
|
+
function resolveStateRoot(ctx) {
|
|
60
|
+
const dshHomePath = dshHomePathOf(ctx)
|
|
61
|
+
if (dshHomePath === undefined) return undefined
|
|
62
|
+
try {
|
|
63
|
+
return resolveDataRoot(dshHomePath('better-voice-input'))
|
|
64
|
+
} catch {
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Register the seven local providers into the official speech registry.
|
|
71
|
+
*
|
|
72
|
+
* Registration comes first and cleanup last (unregister → dispose provider → await removal), the
|
|
73
|
+
* order the official seam documents. Every provider owns its worker process; unloading the row
|
|
74
|
+
* aborts an in-flight download and stops every worker.
|
|
75
|
+
* @param {any} ctx cordis context of the row.
|
|
76
|
+
* @param {{ dataRoot?: string } | undefined} config row config from cordis.patch.yml.
|
|
77
|
+
* @returns {void}
|
|
78
|
+
*/
|
|
79
|
+
export function apply(ctx, config) {
|
|
80
|
+
const logger = typeof ctx.logger === 'function' ? ctx.logger('bvi-local') : undefined
|
|
81
|
+
const dataRoot = resolveModelsRoot(ctx, config)
|
|
82
|
+
const stateRoot = resolveStateRoot(ctx)
|
|
83
|
+
/**
|
|
84
|
+
* @param {string} message - diagnostic text.
|
|
85
|
+
* @returns {void}
|
|
86
|
+
*/
|
|
87
|
+
const log = (message) => { logger?.debug?.(message) }
|
|
88
|
+
/**
|
|
89
|
+
* Read the variant selected in the bundle configuration document. The service normally passes it
|
|
90
|
+
* through `prepare({ variant })`; this fallback keeps direct provider use working.
|
|
91
|
+
* @param {string} providerId - local provider id.
|
|
92
|
+
* @returns {Promise<string|undefined>} configured variant id, when one is saved.
|
|
93
|
+
*/
|
|
94
|
+
const readSelectedVariant = async (providerId) => {
|
|
95
|
+
if (stateRoot === undefined) return undefined
|
|
96
|
+
const document = await readConfig(stateRoot)
|
|
97
|
+
const variant = document.local?.[providerId]?.variant
|
|
98
|
+
return typeof variant === 'string' && variant !== '' ? variant : undefined
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
for (const model of LOCAL_MODELS) {
|
|
102
|
+
ctx.effect(() => {
|
|
103
|
+
const provider = createLocalProvider({ model, dataRoot, readSelectedVariant, logger: log })
|
|
104
|
+
const unregister = ctx.speechToText.register(provider)
|
|
105
|
+
return async () => {
|
|
106
|
+
const removing = unregister()
|
|
107
|
+
await provider.dispose()
|
|
108
|
+
await removing
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
}
|
package/lib/provider.js
ADDED
|
@@ -0,0 +1,505 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The official `ctx.speechToText` provider of one local model family.
|
|
3
|
+
*
|
|
4
|
+
* The provider owns everything the official seam expects for a downloadable local model:
|
|
5
|
+
*
|
|
6
|
+
* - `info` (id, display name, host-local location, languages, setup estimate, download origins),
|
|
7
|
+
* - `preparation` — an official-word-list state machine (`unprepared`, `checking`, `downloading`,
|
|
8
|
+
* `loading`, `waking`, `ready`, `standby`, `cancelled`, `failed`) with snapshot/subscribe/
|
|
9
|
+
* prepare/cancel; preparation is idempotent per variant and one task runs at a time,
|
|
10
|
+
* - `transcribe` — canonical WAV validation through the core helpers, a prepared/standby check,
|
|
11
|
+
* then one worker round-trip returning `{ text, audioSeconds, inferenceSeconds }`.
|
|
12
|
+
*
|
|
13
|
+
* The selected variant comes from the official `prepare(options)` call (`options.variant`, an
|
|
14
|
+
* extension of the official type used by our service) with a fallback to the bundle's
|
|
15
|
+
* `config.json` (`local[providerId].variant`), so a non-default variant also works when the
|
|
16
|
+
* provider is driven directly (smoke tests, scripts).
|
|
17
|
+
*
|
|
18
|
+
* All model files live under `<dataRoot>/<family>/<variant>/`; the shared Silero VAD model lives
|
|
19
|
+
* under `<dataRoot>/_shared/`. The data root is the row's `config.dataRoot` (an absolute model
|
|
20
|
+
* directory), never a guessed home directory.
|
|
21
|
+
*
|
|
22
|
+
* @module @ds-hu/dsh-bvi-local/provider
|
|
23
|
+
*/
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
import { MAX_WAV_BYTES, validateWav } from '@ds-hu/dsh-bvi-core'
|
|
26
|
+
import { SHARED_ASSETS } from '@ds-hu/dsh-bvi-core/catalog/local.js'
|
|
27
|
+
import { downloadSourcesForVariant, ensureVariantInstalled } from './provision/install.js'
|
|
28
|
+
import { WorkerRuntime } from './worker/runtime.js'
|
|
29
|
+
|
|
30
|
+
/** Official preparation phases that describe work in progress. */
|
|
31
|
+
const IN_FLIGHT_PHASES = new Set(['checking', 'downloading', 'loading', 'waking', 'cancelling'])
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {unknown} error - thrown value.
|
|
35
|
+
* @returns {string} readable message.
|
|
36
|
+
*/
|
|
37
|
+
function messageOf(error) {
|
|
38
|
+
return error instanceof Error ? error.message : String(error)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {unknown} value - candidate byte count.
|
|
43
|
+
* @returns {number|undefined} a rounded non-negative byte count.
|
|
44
|
+
*/
|
|
45
|
+
function bytesOf(value) {
|
|
46
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {{ runtime: { segmentation: string } }} model - catalog record.
|
|
51
|
+
* @returns {boolean} whether preparing this family must also install the shared VAD model.
|
|
52
|
+
*/
|
|
53
|
+
function needsVad(model) {
|
|
54
|
+
return model.runtime.segmentation === 'vad' || model.runtime.segmentation === 'vad-long'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* One local-model provider: official metadata, preparation state machine and worker-backed
|
|
59
|
+
* transcription.
|
|
60
|
+
*/
|
|
61
|
+
export class LocalProvider {
|
|
62
|
+
/** @type {{ phase: string, [key: string]: any }} */
|
|
63
|
+
#state = { phase: 'unprepared' }
|
|
64
|
+
/** @type {Set<Function>} */
|
|
65
|
+
#listeners = new Set()
|
|
66
|
+
/** @type {{ variant: Record<string, any>, variantDir: string, vadPath: string|undefined }|null} */
|
|
67
|
+
#active = null
|
|
68
|
+
/** @type {{ explicit: boolean, variantId: string|undefined, downloadSource: string|undefined, controller: AbortController, promise: Promise<void> }|null} */
|
|
69
|
+
#preparing = null
|
|
70
|
+
/** @type {Promise<void>|null} */
|
|
71
|
+
#wakePromise = null
|
|
72
|
+
/** @type {boolean} */
|
|
73
|
+
#disposed = false
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @param {{
|
|
77
|
+
* model: Record<string, any>,
|
|
78
|
+
* dataRoot: string,
|
|
79
|
+
* readSelectedVariant?: (providerId: string) => Promise<string|undefined>,
|
|
80
|
+
* fetchImpl?: typeof fetch,
|
|
81
|
+
* downloadTimeoutMs?: number,
|
|
82
|
+
* workerOptions?: Record<string, any>,
|
|
83
|
+
* logger?: (message: string) => void,
|
|
84
|
+
* }} options - catalog record, model root and transport overrides.
|
|
85
|
+
*/
|
|
86
|
+
constructor(options) {
|
|
87
|
+
this.#options = {
|
|
88
|
+
model: options.model,
|
|
89
|
+
dataRoot: options.dataRoot,
|
|
90
|
+
readSelectedVariant: options.readSelectedVariant ?? (async () => undefined),
|
|
91
|
+
fetchImpl: options.fetchImpl,
|
|
92
|
+
downloadTimeoutMs: options.downloadTimeoutMs,
|
|
93
|
+
workerOptions: options.workerOptions ?? {},
|
|
94
|
+
logger: options.logger ?? (() => undefined),
|
|
95
|
+
}
|
|
96
|
+
this.#runtime = new WorkerRuntime({
|
|
97
|
+
family: this.#options.model.family,
|
|
98
|
+
logger: this.#options.logger,
|
|
99
|
+
...this.#options.workerOptions,
|
|
100
|
+
})
|
|
101
|
+
this.#runtimeUnsubscribe = this.#runtime.subscribe(() => this.#onRuntimeChange())
|
|
102
|
+
this.info = {
|
|
103
|
+
id: this.#options.model.id,
|
|
104
|
+
name: this.#options.model.name.zh,
|
|
105
|
+
location: 'host-local',
|
|
106
|
+
languages: this.#options.model.languages,
|
|
107
|
+
setupEstimate: this.#options.model.setupEstimate,
|
|
108
|
+
downloadSources: this.#options.model.downloadSources,
|
|
109
|
+
}
|
|
110
|
+
this.preparation = {
|
|
111
|
+
snapshot: () => this.snapshot(),
|
|
112
|
+
subscribe: (listener) => this.subscribe(listener),
|
|
113
|
+
prepare: (options) => this.prepare(options),
|
|
114
|
+
cancel: () => this.cancel(),
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @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 }} */
|
|
119
|
+
#options
|
|
120
|
+
/** @type {WorkerRuntime} */
|
|
121
|
+
#runtime
|
|
122
|
+
/** @type {() => void} */
|
|
123
|
+
#runtimeUnsubscribe
|
|
124
|
+
|
|
125
|
+
/** @type {{ id: string, name: string, location: 'host-local', languages: string[], setupEstimate?: Record<string, number>, downloadSources: string[] }} */
|
|
126
|
+
info
|
|
127
|
+
|
|
128
|
+
/** @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
|
+
preparation
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Latest official preparation state (a detached copy).
|
|
133
|
+
* @returns {{ phase: string, [key: string]: any }} preparation snapshot.
|
|
134
|
+
*/
|
|
135
|
+
snapshot() {
|
|
136
|
+
return { ...this.#state }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Observe preparation-state changes.
|
|
141
|
+
* @param {() => void} listener - invalidation callback.
|
|
142
|
+
* @returns {() => void} unsubscribe function.
|
|
143
|
+
*/
|
|
144
|
+
subscribe(listener) {
|
|
145
|
+
this.#listeners.add(listener)
|
|
146
|
+
return () => { this.#listeners.delete(listener) }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {{ phase: string, [key: string]: any }} state - next official state.
|
|
151
|
+
* @returns {void}
|
|
152
|
+
*/
|
|
153
|
+
#publish(state) {
|
|
154
|
+
this.#state = state
|
|
155
|
+
for (const listener of this.#listeners) {
|
|
156
|
+
try {
|
|
157
|
+
listener()
|
|
158
|
+
} catch (error) {
|
|
159
|
+
this.#options.logger(`bvi-local: preparation listener failed: ${messageOf(error)}`)
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* React to worker lifecycle changes that happen outside a preparation task (idle reclaim and
|
|
166
|
+
* crashes), keeping the official preparation state honest.
|
|
167
|
+
* @returns {void}
|
|
168
|
+
*/
|
|
169
|
+
#onRuntimeChange() {
|
|
170
|
+
if (this.#preparing !== null || this.#wakePromise !== null) return
|
|
171
|
+
const runtime = this.#runtime.snapshot()
|
|
172
|
+
if (runtime.state === 'failed') {
|
|
173
|
+
this.#publish({
|
|
174
|
+
phase: 'failed',
|
|
175
|
+
message: runtime.message ?? 'The local speech worker stopped unexpectedly',
|
|
176
|
+
variant: this.#active?.variant.id,
|
|
177
|
+
})
|
|
178
|
+
} else if (runtime.state === 'idle' && this.#state.phase === 'ready') {
|
|
179
|
+
this.#publish({ phase: 'standby', variant: this.#active?.variant.id })
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Resolve the variant a preparation task should install.
|
|
185
|
+
* @param {{ explicit: boolean, variantId: string|undefined }} task - preparation task.
|
|
186
|
+
* @returns {Promise<Record<string, any>>} catalog variant.
|
|
187
|
+
* @throws {Error} when the explicitly requested variant does not exist.
|
|
188
|
+
*/
|
|
189
|
+
async #resolveVariant(task) {
|
|
190
|
+
const model = this.#options.model
|
|
191
|
+
if (task.explicit) {
|
|
192
|
+
const variant = model.variants.find((entry) => entry.id === task.variantId)
|
|
193
|
+
if (variant === undefined) throw new Error(`Unknown local model variant: ${model.id}/${String(task.variantId)}`)
|
|
194
|
+
return variant
|
|
195
|
+
}
|
|
196
|
+
let selected
|
|
197
|
+
try {
|
|
198
|
+
selected = await this.#options.readSelectedVariant(model.id)
|
|
199
|
+
} catch (error) {
|
|
200
|
+
this.#options.logger(`bvi-local: unable to read the selected variant of ${model.id}: ${messageOf(error)}`)
|
|
201
|
+
}
|
|
202
|
+
const found = model.variants.find((entry) => entry.id === selected)
|
|
203
|
+
return found ?? model.variants.find((entry) => entry.id === model.defaultVariant) ?? model.variants[0]
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Reject a download origin the selected variant cannot be fetched from.
|
|
208
|
+
* @param {Record<string, any>} variant - catalog variant.
|
|
209
|
+
* @param {string|undefined} source - origin chosen by the user.
|
|
210
|
+
* @returns {void}
|
|
211
|
+
* @throws {Error} when the source is unknown or cannot serve this variant.
|
|
212
|
+
*/
|
|
213
|
+
#assertDownloadSource(variant, source) {
|
|
214
|
+
if (source === undefined) return
|
|
215
|
+
if (!this.#options.model.downloadSources.includes(source)) {
|
|
216
|
+
throw new Error(`Unknown download source for ${this.#options.model.id}: ${source}`)
|
|
217
|
+
}
|
|
218
|
+
if (!downloadSourcesForVariant(this.#options.model, variant).includes(source)) {
|
|
219
|
+
throw new Error(`Variant ${variant.id} of ${this.#options.model.id} is not available from ${source}`)
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Map an installation progress event onto the official preparation state.
|
|
225
|
+
* @param {Record<string, any>} progress - installation event.
|
|
226
|
+
* @returns {void}
|
|
227
|
+
*/
|
|
228
|
+
#publishInstallProgress(progress) {
|
|
229
|
+
const variant = this.#preparing?.variantId
|
|
230
|
+
switch (progress.phase) {
|
|
231
|
+
case 'checking':
|
|
232
|
+
this.#publish({ phase: 'checking', step: progress.step ?? 'check', startedAt: Date.now(), variant })
|
|
233
|
+
return
|
|
234
|
+
case 'downloading':
|
|
235
|
+
this.#publish({
|
|
236
|
+
phase: 'downloading',
|
|
237
|
+
step: progress.step,
|
|
238
|
+
resource: typeof progress.resource === 'string' ? progress.resource : this.#options.model.name.zh,
|
|
239
|
+
completedBytes: bytesOf(progress.completedBytes) ?? 0,
|
|
240
|
+
totalBytes: bytesOf(progress.totalBytes),
|
|
241
|
+
variant,
|
|
242
|
+
})
|
|
243
|
+
return
|
|
244
|
+
case 'extracting':
|
|
245
|
+
this.#publish({
|
|
246
|
+
phase: 'loading',
|
|
247
|
+
step: 'model',
|
|
248
|
+
resource: typeof progress.resource === 'string' ? progress.resource : this.#options.model.name.zh,
|
|
249
|
+
completedBytes: bytesOf(progress.completedBytes) ?? 0,
|
|
250
|
+
totalBytes: bytesOf(progress.totalBytes),
|
|
251
|
+
startedAt: Date.now(),
|
|
252
|
+
variant,
|
|
253
|
+
})
|
|
254
|
+
return
|
|
255
|
+
case 'verifying':
|
|
256
|
+
this.#publish({ phase: 'checking', step: 'verify', startedAt: Date.now(), variant })
|
|
257
|
+
return
|
|
258
|
+
default:
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Install the variant and start its worker, publishing official phases as it goes.
|
|
265
|
+
* @param {{ explicit: boolean, variantId: string|undefined, downloadSource: string|undefined, controller: AbortController }} task - preparation task.
|
|
266
|
+
* @returns {Promise<void>} resolves when the state is terminal (`ready`, `failed` or `cancelled`).
|
|
267
|
+
*/
|
|
268
|
+
async #runPreparation(task) {
|
|
269
|
+
const model = this.#options.model
|
|
270
|
+
let variant
|
|
271
|
+
try {
|
|
272
|
+
variant = await this.#resolveVariant(task)
|
|
273
|
+
task.variantId = variant.id
|
|
274
|
+
if (task.controller.signal.aborted) throw task.controller.signal.reason
|
|
275
|
+
this.#assertDownloadSource(variant, task.downloadSource)
|
|
276
|
+
this.#publish({ phase: 'checking', step: 'check', startedAt: Date.now(), variant: variant.id })
|
|
277
|
+
if (this.#runtime.snapshot().state === 'ready' && this.#active !== null && this.#active.variant.id !== variant.id) {
|
|
278
|
+
await this.#runtime.stop('variant-switch')
|
|
279
|
+
}
|
|
280
|
+
const vadAsset = needsVad(model) ? SHARED_ASSETS.vad : undefined
|
|
281
|
+
const install = await ensureVariantInstalled({
|
|
282
|
+
root: this.#options.dataRoot,
|
|
283
|
+
model,
|
|
284
|
+
variant,
|
|
285
|
+
vadAsset,
|
|
286
|
+
downloadSource: task.downloadSource,
|
|
287
|
+
signal: task.controller.signal,
|
|
288
|
+
onProgress: (progress) => this.#publishInstallProgress(progress),
|
|
289
|
+
fetchImpl: this.#options.fetchImpl,
|
|
290
|
+
downloadTimeoutMs: this.#options.downloadTimeoutMs,
|
|
291
|
+
})
|
|
292
|
+
if (task.controller.signal.aborted) throw task.controller.signal.reason
|
|
293
|
+
this.#publish({ phase: 'loading', step: 'load', startedAt: Date.now(), variant: variant.id })
|
|
294
|
+
await this.#runtime.ensureStarted({
|
|
295
|
+
variantId: variant.id,
|
|
296
|
+
variantDir: install.variantDir,
|
|
297
|
+
threads: model.runtime.threads,
|
|
298
|
+
vadPath: install.vadPath,
|
|
299
|
+
maxAudioBytes: MAX_WAV_BYTES,
|
|
300
|
+
}, task.controller.signal)
|
|
301
|
+
if (task.controller.signal.aborted) throw task.controller.signal.reason
|
|
302
|
+
this.#active = { variant, variantDir: install.variantDir, vadPath: install.vadPath }
|
|
303
|
+
this.#publish({ phase: 'ready', variant: variant.id })
|
|
304
|
+
} catch (error) {
|
|
305
|
+
const cancelled = task.controller.signal.aborted
|
|
306
|
+
if (!cancelled) this.#options.logger(`bvi-local: preparing ${model.id} failed: ${messageOf(error)}`)
|
|
307
|
+
try {
|
|
308
|
+
await this.#runtime.stop('prepare-failed')
|
|
309
|
+
} catch {
|
|
310
|
+
// The worker is already gone; the preparation error is the useful one.
|
|
311
|
+
}
|
|
312
|
+
if (cancelled) this.#publish({ phase: 'cancelled', variant: task.variantId })
|
|
313
|
+
else this.#publish({ phase: 'failed', message: messageOf(error), variant: task.variantId })
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Start (or join) preparation of one variant.
|
|
319
|
+
*
|
|
320
|
+
* Idempotent when the requested variant is already prepared or being prepared. A second call
|
|
321
|
+
* that asks for a *different* variant while one is in flight is rejected instead of silently
|
|
322
|
+
* joining the wrong work.
|
|
323
|
+
* @param {{ variant?: string, downloadSource?: string, signal?: AbortSignal }} [options] - official options
|
|
324
|
+
* plus our `variant` extension.
|
|
325
|
+
* @returns {Promise<void>} resolves when the preparation task reaches a terminal phase; it never
|
|
326
|
+
* rejects (failures are published as the official `failed` state).
|
|
327
|
+
* @throws {Error} when the provider was disposed, the requested variant is unknown, or another
|
|
328
|
+
* variant is already being prepared.
|
|
329
|
+
*/
|
|
330
|
+
prepare(options = {}) {
|
|
331
|
+
if (this.#disposed) throw new Error(`bvi-local: provider ${this.#options.model.id} is disposed`)
|
|
332
|
+
const requested = typeof options.variant === 'string' && options.variant !== '' ? options.variant : undefined
|
|
333
|
+
if (requested !== undefined && !this.#options.model.variants.some((entry) => entry.id === requested)) {
|
|
334
|
+
throw new Error(`Unknown local model variant: ${this.#options.model.id}/${requested}`)
|
|
335
|
+
}
|
|
336
|
+
const current = this.#preparing
|
|
337
|
+
if (current !== null) {
|
|
338
|
+
if (requested !== undefined && current.variantId !== undefined && current.variantId !== requested) {
|
|
339
|
+
throw new Error(`${this.#options.model.id}: ${current.variantId} is already being prepared; cancel it first`)
|
|
340
|
+
}
|
|
341
|
+
return current.promise
|
|
342
|
+
}
|
|
343
|
+
if (this.#state.phase === 'ready' || this.#state.phase === 'standby') {
|
|
344
|
+
if (requested === undefined || requested === this.#active?.variant.id) return Promise.resolve()
|
|
345
|
+
}
|
|
346
|
+
const controller = new AbortController()
|
|
347
|
+
/** @type {{ explicit: boolean, variantId: string|undefined, downloadSource: string|undefined, controller: AbortController, promise: Promise<void> }} */
|
|
348
|
+
const task = {
|
|
349
|
+
explicit: requested !== undefined,
|
|
350
|
+
variantId: requested,
|
|
351
|
+
downloadSource: typeof options.downloadSource === 'string' && options.downloadSource !== '' ? options.downloadSource : undefined,
|
|
352
|
+
controller,
|
|
353
|
+
promise: Promise.resolve(),
|
|
354
|
+
}
|
|
355
|
+
if (options.signal !== undefined) {
|
|
356
|
+
if (options.signal.aborted) {
|
|
357
|
+
controller.abort(options.signal.reason)
|
|
358
|
+
} else {
|
|
359
|
+
options.signal.addEventListener('abort', () => { controller.abort(options.signal?.reason) }, { once: true })
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
this.#preparing = task
|
|
363
|
+
task.promise = this.#runPreparation(task).finally(() => {
|
|
364
|
+
if (this.#preparing === task) this.#preparing = null
|
|
365
|
+
})
|
|
366
|
+
return task.promise
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Cancel the active preparation task and wait until its resources settle.
|
|
371
|
+
* @returns {Promise<void>} resolves when the state is `cancelled` (or after the final failure).
|
|
372
|
+
*/
|
|
373
|
+
async cancel() {
|
|
374
|
+
const task = this.#preparing
|
|
375
|
+
if (task === null) return
|
|
376
|
+
if (IN_FLIGHT_PHASES.has(this.#state.phase)) {
|
|
377
|
+
this.#publish({ ...this.#state, phase: 'cancelling', startedAt: Date.now() })
|
|
378
|
+
}
|
|
379
|
+
task.controller.abort(new Error('Local model preparation was cancelled'))
|
|
380
|
+
try {
|
|
381
|
+
await task.promise
|
|
382
|
+
} catch {
|
|
383
|
+
// Preparation resolves instead of rejecting; this guard keeps cancel() total.
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Wake a worker that was reclaimed after the idle timeout.
|
|
389
|
+
* @param {{ variant: Record<string, any>, variantDir: string, vadPath: string|undefined }} active - installed layout.
|
|
390
|
+
* @returns {Promise<void>} resolves when the worker is ready again.
|
|
391
|
+
*/
|
|
392
|
+
async #wake(active) {
|
|
393
|
+
if (this.#wakePromise !== null) return await this.#wakePromise
|
|
394
|
+
const model = this.#options.model
|
|
395
|
+
this.#publish({ phase: 'waking', startedAt: Date.now(), variant: active.variant.id })
|
|
396
|
+
const promise = (async () => {
|
|
397
|
+
try {
|
|
398
|
+
await this.#runtime.ensureStarted({
|
|
399
|
+
variantId: active.variant.id,
|
|
400
|
+
variantDir: active.variantDir,
|
|
401
|
+
threads: model.runtime.threads,
|
|
402
|
+
vadPath: active.vadPath,
|
|
403
|
+
maxAudioBytes: MAX_WAV_BYTES,
|
|
404
|
+
})
|
|
405
|
+
this.#publish({ phase: 'ready', variant: active.variant.id })
|
|
406
|
+
} catch (error) {
|
|
407
|
+
this.#publish({ phase: 'failed', message: messageOf(error), variant: active.variant.id })
|
|
408
|
+
throw error
|
|
409
|
+
} finally {
|
|
410
|
+
this.#wakePromise = null
|
|
411
|
+
}
|
|
412
|
+
})()
|
|
413
|
+
this.#wakePromise = promise
|
|
414
|
+
return await promise
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Recognize one recording through the prepared worker.
|
|
419
|
+
* @param {{ audio: Uint8Array, language?: string }} input - official speech input.
|
|
420
|
+
* @param {AbortSignal} [signal] - caller cancellation.
|
|
421
|
+
* @returns {Promise<{ text: string, audioSeconds: number, inferenceSeconds: number }>} transcript.
|
|
422
|
+
* @throws {import('@ds-hu/dsh-bvi-core').WavError} when the audio is not canonical intake.
|
|
423
|
+
* @throws {Error} when no model is prepared or the worker cannot run.
|
|
424
|
+
*/
|
|
425
|
+
async transcribe(input, signal) {
|
|
426
|
+
const model = this.#options.model
|
|
427
|
+
// Validating here keeps every malformed payload out of the worker process.
|
|
428
|
+
validateWav(input?.audio)
|
|
429
|
+
if (this.#disposed) throw new Error(`bvi-local: provider ${model.id} is disposed`)
|
|
430
|
+
if (this.#preparing !== null) throw new Error(`${model.name.zh} is still being prepared; wait until it is ready`)
|
|
431
|
+
const active = this.#active
|
|
432
|
+
if (active === null) throw new Error(`${model.name.zh} is not prepared; download the model first`)
|
|
433
|
+
const runtime = this.#runtime.snapshot()
|
|
434
|
+
if (this.#state.phase !== 'ready' && this.#state.phase !== 'standby') {
|
|
435
|
+
throw new Error(this.#state.phase === 'failed'
|
|
436
|
+
? `${model.name.zh} is unavailable: ${typeof this.#state.message === 'string' ? this.#state.message : 'the local speech worker stopped'}`
|
|
437
|
+
: `${model.name.zh} is not prepared; download the model first`)
|
|
438
|
+
}
|
|
439
|
+
if (runtime.state !== 'ready') await this.#wake(active)
|
|
440
|
+
if (signal !== undefined) signal.throwIfAborted()
|
|
441
|
+
const language = typeof input?.language === 'string' && input.language !== '' ? input.language : 'auto'
|
|
442
|
+
const result = await this.#runtime.transcribe({ audio: /** @type {Uint8Array} */ (input?.audio), language, signal })
|
|
443
|
+
return {
|
|
444
|
+
text: result.text,
|
|
445
|
+
audioSeconds: result.audioSeconds,
|
|
446
|
+
inferenceSeconds: result.inferenceSeconds,
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Stop the worker and refuse future calls. Idempotent; called from the registration disposer.
|
|
452
|
+
* @returns {Promise<void>} resolves after every resource settled.
|
|
453
|
+
*/
|
|
454
|
+
async dispose() {
|
|
455
|
+
if (this.#disposed) return
|
|
456
|
+
this.#disposed = true
|
|
457
|
+
const task = this.#preparing
|
|
458
|
+
if (task !== null) {
|
|
459
|
+
task.controller.abort(new Error('Local speech provider unloaded'))
|
|
460
|
+
try {
|
|
461
|
+
await task.promise
|
|
462
|
+
} catch {
|
|
463
|
+
// Preparation resolves instead of rejecting.
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
if (this.#wakePromise !== null) {
|
|
467
|
+
try {
|
|
468
|
+
await this.#wakePromise
|
|
469
|
+
} catch {
|
|
470
|
+
// The worker is being torn down anyway.
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
await this.#runtime.dispose()
|
|
474
|
+
this.#runtimeUnsubscribe()
|
|
475
|
+
this.#listeners.clear()
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Build one local provider from a catalog record.
|
|
481
|
+
* @param {{
|
|
482
|
+
* model: Record<string, any>,
|
|
483
|
+
* dataRoot: string,
|
|
484
|
+
* readSelectedVariant?: (providerId: string) => Promise<string|undefined>,
|
|
485
|
+
* fetchImpl?: typeof fetch,
|
|
486
|
+
* downloadTimeoutMs?: number,
|
|
487
|
+
* workerOptions?: Record<string, any>,
|
|
488
|
+
* logger?: (message: string) => void,
|
|
489
|
+
* }} options - catalog record, model root and transport overrides.
|
|
490
|
+
* @returns {LocalProvider} provider implementing the official seam.
|
|
491
|
+
*/
|
|
492
|
+
export function createLocalProvider(options) {
|
|
493
|
+
return new LocalProvider(options)
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Directory of one variant inside the model root (exported for scripts and diagnostics).
|
|
498
|
+
* @param {string} dataRoot - model root.
|
|
499
|
+
* @param {{ family: string }} model - catalog record.
|
|
500
|
+
* @param {{ id: string }} variant - catalog variant.
|
|
501
|
+
* @returns {string} absolute variant directory.
|
|
502
|
+
*/
|
|
503
|
+
export function providerVariantDirectory(dataRoot, model, variant) {
|
|
504
|
+
return join(dataRoot, model.family, variant.id)
|
|
505
|
+
}
|