@jskit-ai/assistant-voice-sherpa 0.1.134 → 0.1.136
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/README.md +91 -39
- package/package.json +4 -4
- package/src/cli.js +71 -54
- package/src/recognitionProcess.js +158 -0
- package/src/recognitionSession.js +132 -0
- package/src/recognitionWorker.js +78 -0
- package/src/sherpaSpeechEngine.js +292 -134
- package/tooling/prepare-models.sh +2 -1
package/README.md
CHANGED
|
@@ -15,30 +15,81 @@ package's supported platforms before choosing another deployment target.
|
|
|
15
15
|
```sh
|
|
16
16
|
npx jskit-assistant-voice prepare --models-root /srv/speech/models --pack cori
|
|
17
17
|
npx jskit-assistant-voice verify --models-root /srv/speech/models
|
|
18
|
-
npx jskit-assistant-voice serve --models-root /srv/speech/models --
|
|
18
|
+
npx jskit-assistant-voice serve --models-root /srv/speech/models --credentials-file /srv/speech/credentials.json
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
The
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
21
|
+
The service is run by its host, and each application is a client of it with its
|
|
22
|
+
own token. The host lists its clients in the credentials file (the format is in
|
|
23
|
+
`@jskit-ai/assistant-voice`'s README, Speech service), holding each token's
|
|
24
|
+
SHA-256 only, and rewrites it to add, rotate or remove a client; the service
|
|
25
|
+
picks a change up within a second, without a restart, and ends a removed
|
|
26
|
+
token's sessions. Each client's server keeps its own token and hands it to its
|
|
27
|
+
authenticated proxy (`resolveVoiceProxyConfig({ endpoint, accessTokenFile })`);
|
|
28
|
+
no token belongs in browser configuration. `createVoiceClientToken()` and
|
|
29
|
+
`voiceTokenSha256(token)` from `@jskit-ai/assistant-voice/server` make a token
|
|
30
|
+
and its hash.
|
|
31
|
+
|
|
32
|
+
The service defaults to `127.0.0.1:3092`, with its WebSocket at `/v1/voice`, its
|
|
33
|
+
catalogue at `/v1/catalogue`, its voices at `/voices` and readiness at `/health`.
|
|
34
|
+
It writes one JSON line per connection, credentials change and refused
|
|
35
|
+
credentials file to standard output (the access log). `serve` options, each
|
|
36
|
+
also an environment variable:
|
|
37
|
+
|
|
38
|
+
| Option | Environment | Default |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| `--credentials-file PATH` (required) | `JSKIT_VOICE_CREDENTIALS_FILE` | |
|
|
41
|
+
| `--hotwords-file PATH` | `JSKIT_VOICE_HOTWORDS_FILE` | none |
|
|
42
|
+
| `--spellings-file PATH` | `JSKIT_VOICE_SPELLINGS_FILE` | none |
|
|
43
|
+
| `--workers N` | `JSKIT_VOICE_WORKERS` | one per CPU |
|
|
44
|
+
| `--recognition-workers N`, `--synthesis-workers N` | `JSKIT_VOICE_RECOGNITION_WORKERS`, `JSKIT_VOICE_SYNTHESIS_WORKERS` | `--workers` |
|
|
45
|
+
| `--max-connections N` | `JSKIT_VOICE_MAX_CONNECTIONS` | 8 per recognition worker |
|
|
46
|
+
| `--max-connections-per-client N` | `JSKIT_VOICE_MAX_CONNECTIONS_PER_CLIENT` | 2 per recognition worker |
|
|
47
|
+
| `--max-queued-speech N` | `JSKIT_VOICE_MAX_QUEUED_SPEECH` | 4 per synthesis worker |
|
|
48
|
+
| `--host ADDRESS`, `--port NUMBER` | `JSKIT_VOICE_HOST`, `JSKIT_VOICE_PORT` | `127.0.0.1`, `3092` |
|
|
49
|
+
| `--config FILE` | `JSKIT_VOICE_CONFIG` | the pack's `speech.json` |
|
|
50
|
+
| `--stt-threads N`, `--stt-active-paths N`, `--tts-threads N` | `JSKIT_VOICE_STT_THREADS`, `JSKIT_VOICE_STT_ACTIVE_PATHS`, `JSKIT_VOICE_TTS_THREADS` | 1, 16, 1 |
|
|
51
|
+
|
|
52
|
+
Recognition runs in a pool of processes, each with one recognizer, and a
|
|
53
|
+
recording stays on the process it started on. Synthesis runs in a pool of
|
|
54
|
+
processes, each keeping one voice model loaded. A worker that stops is replaced
|
|
55
|
+
for the next request, and the requests it held fail.
|
|
56
|
+
|
|
57
|
+
The hotwords file adds the host's words to JSKIT's 48, which bias recognition
|
|
58
|
+
towards them: one phrase per line (letters, digits, apostrophes and spaces, at
|
|
59
|
+
most 100 characters, optionally ` :SCORE`), blank lines and `#` comments
|
|
60
|
+
skipped, at most 1000. The spellings file says how heard phrases are written,
|
|
61
|
+
one `spoken phrase => Written form` per line:
|
|
62
|
+
|
|
63
|
+
```text
|
|
64
|
+
# Product spellings
|
|
65
|
+
vibe sixty four => Vibe64
|
|
66
|
+
merc => Merc
|
|
27
67
|
```
|
|
28
68
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
69
|
+
A spoken phrase is 1 to 100 letters, digits, apostrophes and spaces in any case;
|
|
70
|
+
a written form is 1 to 100 characters with no control characters; blank lines
|
|
71
|
+
and `#` comments are skipped; at most 1000 phrases, each once. A host's spellings
|
|
72
|
+
are added to JSKIT's own (JSKIT, Node.js, PostgreSQL, WebSocket and others) and
|
|
73
|
+
replace JSKIT's on a clash. `serve` refuses a file it cannot read, naming the
|
|
74
|
+
file, the line and why. The catalogue's recognition model counts both
|
|
75
|
+
(`hotwords`, `spellings`). Hotwords make a phrase likelier to be heard; a
|
|
76
|
+
spelling only writes it. A host checks a file before writing it with
|
|
77
|
+
`parseRecognitionHotwords(text)` and `parseRecognitionSpellings(text)` from
|
|
78
|
+
`@jskit-ai/assistant-voice/shared/protocol`, the rules `serve`, the engine and
|
|
79
|
+
the stand-in apply.
|
|
80
|
+
|
|
81
|
+
`runVoiceCli(argv, { createEngine, recognitionVocabulary })` runs the same
|
|
82
|
+
commands from code. `createEngine(options)` receives what
|
|
83
|
+
`createSherpaSpeechEngine` takes; a host's tests pass
|
|
84
|
+
`createStandInSpeechEngine` from `@jskit-ai/assistant-voice/stand-in` to run the
|
|
85
|
+
real service with no model. For `serve` it resolves to `{ address, close() }`.
|
|
35
86
|
|
|
36
87
|
Preparation verifies archive hashes, stages exact model files/configuration,
|
|
37
88
|
records file hashes and atomically replaces the model directory. Repeating the
|
|
38
89
|
same preparation reuses a verified pack. Stop the service before replacing its
|
|
39
90
|
pack, verify, then restart. Normal serving loads models without rehashing them on
|
|
40
91
|
every restart. `--download-cache PATH` and `--retain-downloads 1` permit offline
|
|
41
|
-
reuse.
|
|
92
|
+
reuse. A pack's hotwords are always JSKIT's; a host adds its own when serving.
|
|
42
93
|
|
|
43
94
|
## Models and voices
|
|
44
95
|
|
|
@@ -54,22 +105,22 @@ five Piper medium voices at 22,050 Hz:
|
|
|
54
105
|
| Bryce | Male, American English |
|
|
55
106
|
| Northern English | Male, British English |
|
|
56
107
|
|
|
57
|
-
Each Piper voice has a separate model. The service checks
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
model and native inference caches. The recognition
|
|
62
|
-
stay running. The first reply
|
|
63
|
-
|
|
64
|
-
model
|
|
65
|
-
|
|
66
|
-
also require a model change.
|
|
108
|
+
Each Piper voice has a separate model. The service checks every model's metadata
|
|
109
|
+
once at start, then each synthesis worker loads the default model. A reply goes
|
|
110
|
+
to an idle worker that already has its model, else to an idle worker that loads
|
|
111
|
+
it: that worker's process exits before its replacement loads, which releases the
|
|
112
|
+
old model and native inference caches. The recognition processes and audio
|
|
113
|
+
connections stay running. The first reply that needs a model change includes
|
|
114
|
+
model-loading time; later replies on that worker reuse it. Each worker keeps one
|
|
115
|
+
model resident, so up to one model per synthesis worker is in RAM: measure the
|
|
116
|
+
memory budget with the worker count you run. Workers serve every connection, so
|
|
117
|
+
replies from different conversations can also require a model change.
|
|
67
118
|
|
|
68
119
|
For embedded use, `await createSherpaSpeechEngine(options)` validates the models
|
|
69
120
|
and returns the engine. Call `await engine.close()` when its owner shuts down.
|
|
70
121
|
The supplied CLI handles both startup failure and shutdown. Cancellation kills
|
|
71
122
|
unfinished native synthesis, including a replacement model still loading, and
|
|
72
|
-
waits for its process to exit before
|
|
123
|
+
waits for its process to exit before the worker takes another reply. A completed
|
|
73
124
|
load no longer observes its requesting signal, so a later cancellation cannot
|
|
74
125
|
close a warm worker reused by another request. The next request recreates a
|
|
75
126
|
cancelled worker if needed.
|
|
@@ -88,7 +139,7 @@ Sherpa's required ONNX metadata; every original graph/weight byte remains intact
|
|
|
88
139
|
The installed file keeps its `model_q8f16.onnx` name and its prepared hash is
|
|
89
140
|
recorded in the existing integrity manifest. The pack retains Sherpa's pinned
|
|
90
141
|
voice table, tokenizer, lexicons, eSpeak data and licenses. It does not load the
|
|
91
|
-
full-size Kokoro model. All these English voices share one
|
|
142
|
+
full-size Kokoro model. All these English voices share one model at
|
|
92
143
|
24,000 Hz; voice selection uses the same settings catalogue and per-reply ID.
|
|
93
144
|
|
|
94
145
|
The preset ships a CPU provider configuration disabling only ONNX Runtime's
|
|
@@ -103,13 +154,13 @@ continue through the existing controller and synthesis process.
|
|
|
103
154
|
voices, then adds those 28 Kokoro voices to one catalogue (41 choices). It retains
|
|
104
155
|
Piper's Cori default, existing voice IDs and Kitten Bella's 1.15× speed. Kokoro's
|
|
105
156
|
files and CPU configuration live beneath `tts/kokoro-q8f16`; Piper and Kitten
|
|
106
|
-
files are never overwritten.
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
157
|
+
files are never overwritten. Each synthesis worker switches models between
|
|
158
|
+
replies and releases the previous model before loading another, and stays
|
|
159
|
+
loaded while idle. Replies selecting a loaded model reuse it, including another
|
|
160
|
+
speaker in the same Kitten/Kokoro model. Cancellation terminates the worker
|
|
161
|
+
immediately; its next reply loads a new one. This saves model startup time but
|
|
162
|
+
does not reduce the inference required to generate speech. Each worker keeps one
|
|
163
|
+
model resident.
|
|
113
164
|
Output keeps the existing combined pack's 22,050 Hz rate through the same
|
|
114
165
|
resampler. The standalone presets remain available.
|
|
115
166
|
|
|
@@ -121,8 +172,8 @@ accents in its voice catalogue.
|
|
|
121
172
|
`--pack piper-kitten` combines the five Piper choices with those eight Kitten voices,
|
|
122
173
|
listing Kitten first and keeping Cori as the default. It uses Sherpa's resampler inside the synthesis worker
|
|
123
174
|
to deliver every voice at 22,050 Hz. Selecting another engine does not replace the
|
|
124
|
-
audio connection.
|
|
125
|
-
between Piper and Kitten. Measure Kitten's latency on the target CPU before
|
|
175
|
+
audio connection. Each synthesis worker keeps one model resident, including when
|
|
176
|
+
switching between Piper and Kitten. Measure Kitten's latency on the target CPU before
|
|
126
177
|
choosing it as a default.
|
|
127
178
|
|
|
128
179
|
Operators may edit a separate speech configuration JSON and pass `serve --config
|
|
@@ -146,8 +197,9 @@ are forwarded to Sherpa after replacing `${MODELS_ROOT}` in paths. Other fields:
|
|
|
146
197
|
`recognitionVocabulary` maps literal recognized phrases to application spellings.
|
|
147
198
|
It applies only when making all-uppercase recognition readable; mixed-case text
|
|
148
199
|
is left intact. The CLI host may supply default vocabulary through its options;
|
|
149
|
-
an explicit speech configuration vocabulary replaces those defaults
|
|
150
|
-
|
|
200
|
+
an explicit speech configuration vocabulary replaces those defaults, and
|
|
201
|
+
`serve --spellings-file` adds to either, winning on a clash. This does not
|
|
202
|
+
change the recognizer's hotwords or load another model.
|
|
151
203
|
|
|
152
204
|
Each voice may set `speed` between `0.5` and `2` (default `1`). For example,
|
|
153
205
|
`"speed": 1.15` increases its synthesis pace by about 15% without changing the
|
|
@@ -193,8 +245,8 @@ same prepared-file integrity manifest and atomic replacement as archived models.
|
|
|
193
245
|
Paths in mappings must stay inside their extracted/staged roots. Model compatibility
|
|
194
246
|
still needs native inference validation; a matching hash is only integrity proof.
|
|
195
247
|
|
|
196
|
-
|
|
197
|
-
explicit CLI/environment options (
|
|
248
|
+
Worker and thread counts, recognition paths, connection and synthesis-queue
|
|
249
|
+
limits are explicit CLI/environment options (the table above). Configuration objects can also
|
|
198
250
|
set native thread counts. Benchmark both first audio latency and sustained audio
|
|
199
251
|
production on the deployment machine before selecting a pack. A higher quality
|
|
200
252
|
voice can consume more CPU and respond more slowly.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/assistant-voice-sherpa",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.136",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Optional native Sherpa speech engine and explicit model preparation for assistant voice.",
|
|
6
6
|
"scripts": {
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"tooling"
|
|
20
20
|
],
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@jskit-ai/assistant-voice": "0.2.
|
|
22
|
+
"@jskit-ai/assistant-voice": "0.2.89",
|
|
23
23
|
"sherpa-onnx-node": "1.13.6"
|
|
24
24
|
},
|
|
25
25
|
"jskit": {
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"surfaces": [
|
|
42
42
|
{
|
|
43
43
|
"subpath": ".",
|
|
44
|
-
"summary": "Native Sherpa recognition and synthesis with operator configuration and a named voice catalogue."
|
|
44
|
+
"summary": "Native Sherpa recognition and synthesis in pools of worker processes, with operator configuration, a host's hotwords and spellings, and a named voice catalogue."
|
|
45
45
|
},
|
|
46
46
|
{
|
|
47
47
|
"subpath": "./models",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
{
|
|
51
51
|
"subpath": "./cli",
|
|
52
|
-
"summary": "Portable prepare, verify
|
|
52
|
+
"summary": "Portable prepare, verify and serve commands; serve takes a credentials file, hotwords, spellings and worker counts, and a host may supply its own engine."
|
|
53
53
|
}
|
|
54
54
|
],
|
|
55
55
|
"capabilities": []
|
package/src/cli.js
CHANGED
|
@@ -4,9 +4,9 @@ import path from "node:path";
|
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
|
|
7
|
-
import { createSherpaSpeechEngine } from "./sherpaSpeechEngine.js";
|
|
8
|
-
import { createVoiceAccessToken } from "@jskit-ai/assistant-voice/server";
|
|
7
|
+
import { createSherpaSpeechEngine, defaultWorkerCount } from "./sherpaSpeechEngine.js";
|
|
9
8
|
import { createVoiceDaemon } from "@jskit-ai/assistant-voice/server";
|
|
9
|
+
import { parseRecognitionHotwords, parseRecognitionSpellings } from "@jskit-ai/assistant-voice/shared/protocol";
|
|
10
10
|
import { verifyVoiceModelContract } from "./voiceModelContract.js";
|
|
11
11
|
|
|
12
12
|
// Combined packs list their manifests in merge order: base, kitten, kokoro.
|
|
@@ -62,46 +62,63 @@ function requiredOption(options, key, environmentKey = "") {
|
|
|
62
62
|
return value;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
async function accessKeyFromFile(filePath) {
|
|
66
|
-
return Buffer.from((await readFile(path.resolve(filePath), "utf8")).trim(), "utf8");
|
|
67
|
-
}
|
|
68
|
-
|
|
69
65
|
function positiveInteger(value, fallback) {
|
|
70
66
|
const integer = Number.parseInt(String(value || ""), 10);
|
|
71
67
|
return Number.isInteger(integer) && integer > 0 ? integer : fallback;
|
|
72
68
|
}
|
|
73
69
|
|
|
70
|
+
function setting(options, key, environmentKey) {
|
|
71
|
+
return options[key] || process.env[environmentKey];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// A host's hotwords (one per line) or spellings ("spoken phrase => Written
|
|
75
|
+
// form" per line) file; a refusal names the file and line.
|
|
76
|
+
async function readRecognitionFile(filePath, parse, none) {
|
|
77
|
+
if (!filePath) return none;
|
|
78
|
+
const file = path.resolve(filePath);
|
|
79
|
+
try {
|
|
80
|
+
return parse(await readFile(file, "utf8"));
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error instanceof TypeError) throw new TypeError(`${file}: ${error.message}`);
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
74
87
|
function usage() {
|
|
75
88
|
return [
|
|
76
89
|
"JSKIT assistant voice service",
|
|
77
90
|
"",
|
|
78
91
|
"Commands:",
|
|
79
|
-
" serve --models-root PATH --
|
|
80
|
-
|
|
81
|
-
"
|
|
82
|
-
|
|
92
|
+
" serve --models-root PATH --credentials-file PATH [--hotwords-file PATH] [--spellings-file PATH] [--config FILE]",
|
|
93
|
+
" [--host ADDRESS] [--port NUMBER] [--workers N] [--recognition-workers N] [--synthesis-workers N]",
|
|
94
|
+
" [--max-connections N] [--max-connections-per-client N] [--max-queued-speech N]",
|
|
95
|
+
` prepare --models-root PATH [--pack ${PACK_NAMES.join("|")}] [--sources-file FILE] [--download-cache PATH]`,
|
|
96
|
+
" verify --models-root PATH"
|
|
83
97
|
].join("\n");
|
|
84
98
|
}
|
|
85
99
|
|
|
86
|
-
|
|
100
|
+
/**
|
|
101
|
+
* The voice service's commands. A host may run serve on another engine, such
|
|
102
|
+
* as a stand-in with no model for its tests: `createEngine` receives the
|
|
103
|
+
* options `createSherpaSpeechEngine` takes and answers an engine with close().
|
|
104
|
+
* @param {string[]} [argv]
|
|
105
|
+
* @param {{ createEngine?: typeof createSherpaSpeechEngine, recognitionVocabulary?: Record<string, string> }} [options]
|
|
106
|
+
* @returns {Promise<void | { address: object, close: () => Promise<void> }>} For serve, the running service.
|
|
107
|
+
*/
|
|
108
|
+
async function runVoiceCli(argv = process.argv.slice(2), { createEngine = createSherpaSpeechEngine, recognitionVocabulary = {} } = {}) {
|
|
87
109
|
const { command, options } = argumentMap(argv);
|
|
88
110
|
if (command === "help" || command === "--help" || command === "-h") {
|
|
89
111
|
process.stdout.write(`${usage()}\n`);
|
|
90
112
|
return;
|
|
91
113
|
}
|
|
92
|
-
if (
|
|
93
|
-
const key = await accessKeyFromFile(requiredOption(options, "key-file", "JSKIT_VOICE_ACCESS_KEY_FILE"));
|
|
94
|
-
const tenant = requiredOption(options, "tenant", "JSKIT_VOICE_TENANT");
|
|
95
|
-
process.stdout.write(`${createVoiceAccessToken({ key, tenant })}\n`);
|
|
96
|
-
return;
|
|
97
|
-
}
|
|
114
|
+
if (!["prepare", "serve", "verify"].includes(command)) throw new Error(`Unknown voice command: ${command}.\n\n${usage()}`);
|
|
98
115
|
const modelsRoot = path.resolve(requiredOption(options, "models-root", "JSKIT_VOICE_MODELS_ROOT"));
|
|
99
116
|
if (command === "prepare") {
|
|
100
117
|
const script = fileURLToPath(new URL("../tooling/prepare-models.sh", import.meta.url));
|
|
101
118
|
const env = { ...process.env, JSKIT_VOICE_MODELS_ROOT: modelsRoot, JSKIT_VOICE_NODE_BIN: process.execPath };
|
|
102
119
|
for (const [option, variable] of Object.entries({
|
|
103
120
|
"download-cache": "DOWNLOAD_CACHE", "archive-seed-root": "ARCHIVE_SEED_ROOT",
|
|
104
|
-
"retain-downloads": "RETAIN_DOWNLOADS"
|
|
121
|
+
"retain-downloads": "RETAIN_DOWNLOADS"
|
|
105
122
|
})) if (options[option]) env[`JSKIT_VOICE_${variable}`] = options[option];
|
|
106
123
|
const pack = options.pack || process.env.JSKIT_VOICE_PACK || "cori";
|
|
107
124
|
if (!Object.hasOwn(PACKS, pack)) throw new Error(`Choose --pack ${PACK_NAMES.slice(0, -1).join(", ")} or ${PACK_NAMES.at(-1)}, or supply --sources-file for your own model pack.`);
|
|
@@ -131,58 +148,58 @@ async function runVoiceCli(argv = process.argv.slice(2), { createDaemon = create
|
|
|
131
148
|
process.stdout.write(`Voice model contract verified at ${modelsRoot}.\n`);
|
|
132
149
|
return;
|
|
133
150
|
}
|
|
134
|
-
if (command !== "serve") {
|
|
135
|
-
throw new Error(`Unknown voice command: ${command}.\n\n${usage()}`);
|
|
136
|
-
}
|
|
137
151
|
// Installation and the explicit check command verify integrity. Native model
|
|
138
152
|
// loading reports missing/invalid files without rereading every byte to hash it.
|
|
153
|
+
const credentialsFile = path.resolve(requiredOption(options, "credentials-file", "JSKIT_VOICE_CREDENTIALS_FILE"));
|
|
139
154
|
const configFile = options.config || process.env.JSKIT_VOICE_CONFIG;
|
|
140
155
|
const configuration = await readFile(configFile ? path.resolve(configFile) : path.join(modelsRoot, "speech.json"), "utf8")
|
|
141
156
|
.then(JSON.parse).catch(error => { if (!configFile && error.code === "ENOENT") return {}; throw error; });
|
|
142
|
-
const
|
|
157
|
+
const workers = positiveInteger(setting(options, "workers", "JSKIT_VOICE_WORKERS"), defaultWorkerCount());
|
|
158
|
+
const engine = await createEngine({
|
|
143
159
|
modelsRoot,
|
|
144
160
|
configuration: { ...configuration, recognitionVocabulary: configuration.recognitionVocabulary ?? recognitionVocabulary },
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
),
|
|
149
|
-
|
|
150
|
-
|
|
161
|
+
hotwords: await readRecognitionFile(setting(options, "hotwords-file", "JSKIT_VOICE_HOTWORDS_FILE"), parseRecognitionHotwords, []),
|
|
162
|
+
spellings: await readRecognitionFile(setting(options, "spellings-file", "JSKIT_VOICE_SPELLINGS_FILE"), parseRecognitionSpellings, {}),
|
|
163
|
+
recognitionWorkers: positiveInteger(setting(options, "recognition-workers", "JSKIT_VOICE_RECOGNITION_WORKERS"), workers),
|
|
164
|
+
synthesisWorkers: positiveInteger(setting(options, "synthesis-workers", "JSKIT_VOICE_SYNTHESIS_WORKERS"), workers),
|
|
165
|
+
recognizerActivePaths: positiveInteger(setting(options, "stt-active-paths", "JSKIT_VOICE_STT_ACTIVE_PATHS"), 16),
|
|
166
|
+
recognizerThreads: positiveInteger(setting(options, "stt-threads", "JSKIT_VOICE_STT_THREADS"), 1),
|
|
167
|
+
synthesizerThreads: positiveInteger(setting(options, "tts-threads", "JSKIT_VOICE_TTS_THREADS"), 1)
|
|
151
168
|
});
|
|
152
169
|
let daemon;
|
|
153
170
|
let address;
|
|
154
171
|
try {
|
|
155
|
-
|
|
156
|
-
|
|
172
|
+
// Unset limits size themselves from the engine's pools.
|
|
173
|
+
daemon = createVoiceDaemon({
|
|
174
|
+
credentialsFile,
|
|
157
175
|
engine,
|
|
158
|
-
host: String(options
|
|
159
|
-
maximumConnections: positiveInteger(
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
),
|
|
163
|
-
maximumConnectionsPerTenant: positiveInteger(
|
|
164
|
-
options["max-connections-per-tenant"] || process.env.JSKIT_VOICE_MAX_CONNECTIONS_PER_TENANT,
|
|
165
|
-
2
|
|
166
|
-
),
|
|
167
|
-
maximumQueuedSpeech: positiveInteger(
|
|
168
|
-
options["max-queued-speech"] || process.env.JSKIT_VOICE_MAX_QUEUED_SPEECH,
|
|
169
|
-
4
|
|
170
|
-
),
|
|
171
|
-
port: positiveInteger(options.port || process.env.JSKIT_VOICE_PORT, 3092)
|
|
176
|
+
host: String(setting(options, "host", "JSKIT_VOICE_HOST") || "127.0.0.1"),
|
|
177
|
+
maximumConnections: positiveInteger(setting(options, "max-connections", "JSKIT_VOICE_MAX_CONNECTIONS"), undefined),
|
|
178
|
+
maximumConnectionsPerClient: positiveInteger(setting(options, "max-connections-per-client", "JSKIT_VOICE_MAX_CONNECTIONS_PER_CLIENT"), undefined),
|
|
179
|
+
maximumQueuedSpeech: positiveInteger(setting(options, "max-queued-speech", "JSKIT_VOICE_MAX_QUEUED_SPEECH"), undefined),
|
|
180
|
+
port: positiveInteger(setting(options, "port", "JSKIT_VOICE_PORT"), 3092)
|
|
172
181
|
});
|
|
173
182
|
address = await daemon.start();
|
|
174
|
-
} catch (error) { await engine.close(); throw error; }
|
|
183
|
+
} catch (error) { await daemon?.close(); await engine.close(); throw error; }
|
|
175
184
|
process.stdout.write(`Assistant voice ready on ${address.address}:${address.port}.\n`);
|
|
176
|
-
let stopping =
|
|
177
|
-
const stop =
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
181
|
-
stopping
|
|
182
|
-
try { await daemon.close(); } finally { await engine.close(); }
|
|
185
|
+
let stopping = null;
|
|
186
|
+
const stop = () => {
|
|
187
|
+
stopping ??= (async () => {
|
|
188
|
+
try { await daemon.close(); } finally { await engine.close(); }
|
|
189
|
+
})();
|
|
190
|
+
return stopping;
|
|
183
191
|
};
|
|
184
|
-
|
|
185
|
-
process.once("
|
|
192
|
+
const exitOnSignal = () => void stop().then(() => process.exit(0));
|
|
193
|
+
process.once("SIGINT", exitOnSignal);
|
|
194
|
+
process.once("SIGTERM", exitOnSignal);
|
|
195
|
+
return Object.freeze({
|
|
196
|
+
address,
|
|
197
|
+
async close() {
|
|
198
|
+
process.off("SIGINT", exitOnSignal);
|
|
199
|
+
process.off("SIGTERM", exitOnSignal);
|
|
200
|
+
await stop();
|
|
201
|
+
}
|
|
202
|
+
});
|
|
186
203
|
}
|
|
187
204
|
|
|
188
205
|
export {
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { fork } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
export const RECOGNITION_LOAD_TIMEOUT_MS = 60_000;
|
|
4
|
+
export const RECOGNITION_REQUEST_TIMEOUT_MS = 15_000;
|
|
5
|
+
|
|
6
|
+
/** A listener that does not follow the recognized words ignores them. */
|
|
7
|
+
function ignoreRecognizedText() {}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A recognition worker process holding one native recognizer; the engine gives
|
|
11
|
+
* it recordings. A request that takes longer than its watchdog ends the process
|
|
12
|
+
* and fails every recording on it.
|
|
13
|
+
* @param {object} configuration The native OnlineRecognizer configuration.
|
|
14
|
+
* @param {object} [options]
|
|
15
|
+
* @param {{ vocabulary?: Record<string, string>, minimumRms?: number, tailPaddingSeconds?: number }} [options.options] Each recording's settings.
|
|
16
|
+
* @param {string} [options.runtimeModule] A module standing in for sherpa-onnx-node, for tests.
|
|
17
|
+
* @param {URL} [options.workerUrl]
|
|
18
|
+
*/
|
|
19
|
+
export async function createRecognitionProcess(configuration, {
|
|
20
|
+
options = {},
|
|
21
|
+
runtimeModule = "",
|
|
22
|
+
workerUrl = new URL("./recognitionWorker.js", import.meta.url)
|
|
23
|
+
} = {}) {
|
|
24
|
+
const child = fork(workerUrl, [], { execArgv: [], serialization: "advanced", stdio: ["ignore", "ignore", "inherit", "ipc"] });
|
|
25
|
+
const pending = new Map();
|
|
26
|
+
let sequence = 0;
|
|
27
|
+
let recordings = 0;
|
|
28
|
+
let stopped = false;
|
|
29
|
+
const exited = new Promise(resolve => child.once("close", resolve));
|
|
30
|
+
|
|
31
|
+
function failAll(error) {
|
|
32
|
+
for (const operation of pending.values()) {
|
|
33
|
+
clearTimeout(operation.timer);
|
|
34
|
+
operation.reject(error);
|
|
35
|
+
}
|
|
36
|
+
pending.clear();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
child.on("error", error => { stopped = true; failAll(error); });
|
|
40
|
+
child.on("exit", (code, signal) => {
|
|
41
|
+
stopped = true;
|
|
42
|
+
failAll(new Error(`Recognition worker exited (${signal || code}).`));
|
|
43
|
+
});
|
|
44
|
+
child.on("message", message => {
|
|
45
|
+
const operation = pending.get(message?.seq);
|
|
46
|
+
if (!operation) return;
|
|
47
|
+
pending.delete(message.seq);
|
|
48
|
+
clearTimeout(operation.timer);
|
|
49
|
+
if (message.type === "error") operation.reject(new Error(message.message));
|
|
50
|
+
else operation.resolve(message.result);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
async function close() {
|
|
54
|
+
stopped = true;
|
|
55
|
+
failAll(new Error("Recognition worker closed."));
|
|
56
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
|
57
|
+
await exited;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function request(type, fields = {}, timeoutMs = RECOGNITION_REQUEST_TIMEOUT_MS) {
|
|
61
|
+
if (stopped) return Promise.reject(new Error("Recognition worker is unavailable."));
|
|
62
|
+
const seq = ++sequence;
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const timer = setTimeout(() => {
|
|
65
|
+
pending.delete(seq);
|
|
66
|
+
reject(new Error("Recognition worker timed out."));
|
|
67
|
+
void close();
|
|
68
|
+
}, timeoutMs);
|
|
69
|
+
pending.set(seq, { resolve, reject, timer });
|
|
70
|
+
child.send({ seq, type, ...fields }, error => {
|
|
71
|
+
if (!error || !pending.has(seq)) return;
|
|
72
|
+
pending.delete(seq);
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
reject(error);
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function forget(type, fields) {
|
|
80
|
+
if (!stopped) child.send({ type, ...fields }, () => null);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** One recording on this process; its steps run in the order called. */
|
|
84
|
+
function openRecording({ continuous = false, onPartial = ignoreRecognizedText, onEndpoint = ignoreRecognizedText } = {}) {
|
|
85
|
+
const id = ++sequence;
|
|
86
|
+
recordings += 1;
|
|
87
|
+
const opened = request("open", { id, continuous });
|
|
88
|
+
opened.catch(() => null);
|
|
89
|
+
let closed = false;
|
|
90
|
+
let acceptedSamples = 0;
|
|
91
|
+
let latestText = "";
|
|
92
|
+
|
|
93
|
+
function release() {
|
|
94
|
+
if (closed) return;
|
|
95
|
+
closed = true;
|
|
96
|
+
recordings -= 1;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function step(type, fields = {}) {
|
|
100
|
+
await opened;
|
|
101
|
+
const result = await request(type, { id, ...fields });
|
|
102
|
+
acceptedSamples = result.acceptedSamples;
|
|
103
|
+
if (!closed) {
|
|
104
|
+
for (const event of result.events) (event.type === "endpoint" ? onEndpoint : onPartial)(event.text);
|
|
105
|
+
}
|
|
106
|
+
if (typeof result.text === "string") latestText = result.text;
|
|
107
|
+
return result;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return Object.freeze({
|
|
111
|
+
async acceptPcm(frame) {
|
|
112
|
+
if (closed) return latestText;
|
|
113
|
+
// A copy, so only this slice crosses to the worker.
|
|
114
|
+
return (await step("accept", { pcm: Buffer.from(frame) })).text;
|
|
115
|
+
},
|
|
116
|
+
async finish() {
|
|
117
|
+
if (closed) return latestText;
|
|
118
|
+
try { return (await step("finish")).text; } finally { release(); }
|
|
119
|
+
},
|
|
120
|
+
async reset() {
|
|
121
|
+
if (closed) return latestText;
|
|
122
|
+
return (await step("reset")).text;
|
|
123
|
+
},
|
|
124
|
+
async isEndpoint() {
|
|
125
|
+
if (closed) return false;
|
|
126
|
+
return (await step("isEndpoint")).endpoint;
|
|
127
|
+
},
|
|
128
|
+
cancel() {
|
|
129
|
+
if (closed) return;
|
|
130
|
+
release();
|
|
131
|
+
forget("close", { id });
|
|
132
|
+
},
|
|
133
|
+
get acceptedSamples() {
|
|
134
|
+
return acceptedSamples;
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function warmup() {
|
|
140
|
+
return request("warmup", {}, RECOGNITION_LOAD_TIMEOUT_MS);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
try {
|
|
144
|
+
const runtime = await request("load", { configuration, options, runtimeModule: String(runtimeModule || "") }, RECOGNITION_LOAD_TIMEOUT_MS);
|
|
145
|
+
return Object.freeze({
|
|
146
|
+
close,
|
|
147
|
+
openRecording,
|
|
148
|
+
pid: child.pid,
|
|
149
|
+
get recordings() { return recordings; },
|
|
150
|
+
get running() { return !stopped; },
|
|
151
|
+
runtime: Object.freeze(runtime),
|
|
152
|
+
warmup
|
|
153
|
+
});
|
|
154
|
+
} catch (error) {
|
|
155
|
+
await close();
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
}
|