@howaboua/pi-durable-dictation 0.9.1 → 0.11.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/README.md
CHANGED
|
@@ -5,7 +5,7 @@ Local Whisper dictation for Node.js 22.19 or later, using the native
|
|
|
5
5
|
This package does not capture microphone audio or register agent tools.
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.
|
|
8
|
+
npm install https://github.com/IgorWarzocha/pi-durable-components/releases/download/v0.11.0/howaboua-pi-durable-dictation-0.11.0.tgz
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
```ts
|
|
@@ -0,0 +1,983 @@
|
|
|
1
|
+
// packages/dictation/src/activation.ts
|
|
2
|
+
import { isAbsolute } from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
defineCapability,
|
|
5
|
+
isCapabilityObject,
|
|
6
|
+
networkCapability,
|
|
7
|
+
nodeExecutionCapability,
|
|
8
|
+
stateCapability
|
|
9
|
+
} from "@howaboua/pi-durable-components";
|
|
10
|
+
|
|
11
|
+
// packages/dictation/src/model-management.ts
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { createReadStream, createWriteStream, existsSync } from "node:fs";
|
|
14
|
+
import { mkdir, rename, rm, stat } from "node:fs/promises";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { Readable } from "node:stream";
|
|
17
|
+
import { pipeline } from "node:stream/promises";
|
|
18
|
+
|
|
19
|
+
// packages/dictation/src/model-download.ts
|
|
20
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
21
|
+
var MAX_DOWNLOAD_REDIRECTS = 20;
|
|
22
|
+
var sha1EtagPattern = /^[a-f0-9]{40}$/i;
|
|
23
|
+
var sha256EtagPattern = /^[a-f0-9]{64}$/i;
|
|
24
|
+
var weakEtagPrefixPattern = /^W\//;
|
|
25
|
+
var etagQuotePattern = /^"|"$/g;
|
|
26
|
+
function isHashCapableEtag(etag) {
|
|
27
|
+
return Boolean(etag && (sha1EtagPattern.test(etag) || sha256EtagPattern.test(etag)));
|
|
28
|
+
}
|
|
29
|
+
function getEtagSourcePriority(source) {
|
|
30
|
+
if (source === "x-linked-etag") {
|
|
31
|
+
return 2;
|
|
32
|
+
}
|
|
33
|
+
if (source === "etag") {
|
|
34
|
+
return 1;
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
function normalizeEtag(etag) {
|
|
39
|
+
if (!etag) {
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
return etag.replace(weakEtagPrefixPattern, "").replace(etagQuotePattern, "").trim().toLowerCase() || null;
|
|
43
|
+
}
|
|
44
|
+
function parseContentLength(value) {
|
|
45
|
+
const parsed = Number.parseInt(value ?? "", 10);
|
|
46
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
|
47
|
+
}
|
|
48
|
+
function getDownloadMetadataFromHeaders(headers) {
|
|
49
|
+
const xLinkedEtag = normalizeEtag(headers.get("x-linked-etag"));
|
|
50
|
+
const etag = normalizeEtag(headers.get("etag"));
|
|
51
|
+
return {
|
|
52
|
+
contentLength: parseContentLength(headers.get("x-linked-size")),
|
|
53
|
+
etag: isHashCapableEtag(xLinkedEtag) ? xLinkedEtag : isHashCapableEtag(etag) ? etag : null,
|
|
54
|
+
etagSource: isHashCapableEtag(xLinkedEtag) ? "x-linked-etag" : isHashCapableEtag(etag) ? "etag" : null
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function getDownloadChecksumExpectations(etag, contentLength) {
|
|
58
|
+
if (!etag) {
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
if (sha256EtagPattern.test(etag)) {
|
|
62
|
+
return [{ algorithm: "sha256", expected: etag, prefix: null }];
|
|
63
|
+
}
|
|
64
|
+
if (sha1EtagPattern.test(etag)) {
|
|
65
|
+
return [
|
|
66
|
+
{ algorithm: "sha1", expected: etag, prefix: null },
|
|
67
|
+
{
|
|
68
|
+
algorithm: "sha1",
|
|
69
|
+
expected: etag,
|
|
70
|
+
prefix: Buffer2.from(`blob ${contentLength}\x00`)
|
|
71
|
+
}
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
function mergeDownloadMetadata(current, headers, options) {
|
|
77
|
+
const next = getDownloadMetadataFromHeaders(headers);
|
|
78
|
+
const fallbackContentLength = options.includeContentLength ? parseContentLength(headers.get("content-length")) : null;
|
|
79
|
+
const shouldUseNextEtag = getEtagSourcePriority(next.etagSource) > getEtagSourcePriority(current.etagSource) || next.etag !== null && next.etagSource === current.etagSource;
|
|
80
|
+
return {
|
|
81
|
+
contentLength: current.contentLength ?? next.contentLength ?? fallbackContentLength,
|
|
82
|
+
etag: shouldUseNextEtag ? next.etag : current.etag,
|
|
83
|
+
etagSource: shouldUseNextEtag ? next.etagSource : current.etagSource
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function isRedirectStatus(status) {
|
|
87
|
+
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
88
|
+
}
|
|
89
|
+
async function fetchDownloadResponse(url, signal, fetchDownload = fetch) {
|
|
90
|
+
let currentUrl = url;
|
|
91
|
+
let metadata = {
|
|
92
|
+
contentLength: null,
|
|
93
|
+
etag: null,
|
|
94
|
+
etagSource: null
|
|
95
|
+
};
|
|
96
|
+
for (let redirectCount = 0;redirectCount <= MAX_DOWNLOAD_REDIRECTS; redirectCount += 1) {
|
|
97
|
+
const response = await fetchDownload(currentUrl, {
|
|
98
|
+
redirect: "manual",
|
|
99
|
+
...signal ? { signal } : {}
|
|
100
|
+
});
|
|
101
|
+
metadata = mergeDownloadMetadata(metadata, response.headers, {
|
|
102
|
+
includeContentLength: !isRedirectStatus(response.status)
|
|
103
|
+
});
|
|
104
|
+
if (!isRedirectStatus(response.status)) {
|
|
105
|
+
if (!response.ok) {
|
|
106
|
+
await response.body?.cancel();
|
|
107
|
+
throw new Error(`Download failed (${response.status} ${response.statusText}) for ${currentUrl}`);
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
response,
|
|
111
|
+
metadata
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
await response.body?.cancel();
|
|
115
|
+
if (redirectCount === MAX_DOWNLOAD_REDIRECTS) {
|
|
116
|
+
throw new Error(`Download failed: too many redirects for ${url}`);
|
|
117
|
+
}
|
|
118
|
+
const location = response.headers.get("location");
|
|
119
|
+
if (!location) {
|
|
120
|
+
throw new Error(`Download failed: missing redirect location for ${currentUrl}`);
|
|
121
|
+
}
|
|
122
|
+
currentUrl = new URL(location, currentUrl).toString();
|
|
123
|
+
}
|
|
124
|
+
throw new Error(`Download failed: could not resolve ${url}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// packages/dictation/src/models.ts
|
|
128
|
+
function formatDownloadSize(bytes) {
|
|
129
|
+
return `${(bytes / 1e6).toFixed(1)} MB`;
|
|
130
|
+
}
|
|
131
|
+
var dictationModelDefinitions = [
|
|
132
|
+
{
|
|
133
|
+
id: "tiny.en",
|
|
134
|
+
name: "Tiny English",
|
|
135
|
+
description: "Fastest and smallest Whisper model for quick dictation.",
|
|
136
|
+
huggingFaceRepo: "csukuangfj/sherpa-onnx-whisper-tiny.en",
|
|
137
|
+
downloadSizeBytes: 103627191,
|
|
138
|
+
files: {
|
|
139
|
+
encoder: "tiny.en-encoder.int8.onnx",
|
|
140
|
+
decoder: "tiny.en-decoder.int8.onnx",
|
|
141
|
+
tokens: "tiny.en-tokens.txt"
|
|
142
|
+
}
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
id: "base.en",
|
|
146
|
+
name: "Base English",
|
|
147
|
+
description: "Balanced default with better accuracy at moderate download size.",
|
|
148
|
+
huggingFaceRepo: "csukuangfj/sherpa-onnx-whisper-base.en",
|
|
149
|
+
downloadSizeBytes: 160626066,
|
|
150
|
+
files: {
|
|
151
|
+
encoder: "base.en-encoder.int8.onnx",
|
|
152
|
+
decoder: "base.en-decoder.int8.onnx",
|
|
153
|
+
tokens: "base.en-tokens.txt"
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
id: "small.en",
|
|
158
|
+
name: "Small English",
|
|
159
|
+
description: "Highest accuracy of the initial presets, with the biggest download.",
|
|
160
|
+
huggingFaceRepo: "csukuangfj/sherpa-onnx-whisper-small.en",
|
|
161
|
+
downloadSizeBytes: 375501079,
|
|
162
|
+
files: {
|
|
163
|
+
encoder: "small.en-encoder.int8.onnx",
|
|
164
|
+
decoder: "small.en-decoder.int8.onnx",
|
|
165
|
+
tokens: "small.en-tokens.txt"
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
];
|
|
169
|
+
function getDictationModelDefinition(modelId) {
|
|
170
|
+
return dictationModelDefinitions.find((model) => model.id === modelId) ?? null;
|
|
171
|
+
}
|
|
172
|
+
function getDictationModelDownloadSizeLabel(bytes) {
|
|
173
|
+
return formatDownloadSize(bytes);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// packages/dictation/src/model-management.ts
|
|
177
|
+
function createModelManagement(config, resolution, runtime) {
|
|
178
|
+
const {
|
|
179
|
+
findConfiguredDictationModelFiles,
|
|
180
|
+
getDictationModelDirectory,
|
|
181
|
+
getDictationModelsRootDirectory,
|
|
182
|
+
getInstalledManagedDictationModelDirectory,
|
|
183
|
+
getManagedDictationModelFiles,
|
|
184
|
+
getResolvedDictationModelFiles
|
|
185
|
+
} = resolution;
|
|
186
|
+
const { resetRecognizerCache } = runtime;
|
|
187
|
+
function emitDictationDownloadLog(modelId, message, options = {}) {
|
|
188
|
+
config.onDownloadLog?.({
|
|
189
|
+
type: "dictation-download-log",
|
|
190
|
+
modelId,
|
|
191
|
+
message,
|
|
192
|
+
at: new Date().toISOString(),
|
|
193
|
+
done: options.done ?? false,
|
|
194
|
+
isError: options.isError ?? false
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
function buildHuggingFaceResolveUrl(repo, fileName) {
|
|
198
|
+
return `https://huggingface.co/${repo}/resolve/main/${encodeURIComponent(fileName)}?download=true`;
|
|
199
|
+
}
|
|
200
|
+
async function validateDownloadedFile(targetPath, metadata) {
|
|
201
|
+
const fileStats = await stat(targetPath);
|
|
202
|
+
if (!fileStats.isFile() || fileStats.size <= 0) {
|
|
203
|
+
throw new Error(`Download failed: ${path.basename(targetPath)} is empty.`);
|
|
204
|
+
}
|
|
205
|
+
if (metadata.contentLength !== null && fileStats.size !== metadata.contentLength) {
|
|
206
|
+
throw new Error(`Download failed: ${path.basename(targetPath)} size mismatch (${fileStats.size} != ${metadata.contentLength}).`);
|
|
207
|
+
}
|
|
208
|
+
const checksumExpectations = getDownloadChecksumExpectations(metadata.etag, fileStats.size);
|
|
209
|
+
if (checksumExpectations.length === 0) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const hashes = checksumExpectations.map((expectation) => {
|
|
213
|
+
const hash = createHash(expectation.algorithm);
|
|
214
|
+
if (expectation.prefix) {
|
|
215
|
+
hash.update(expectation.prefix);
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
expected: expectation.expected,
|
|
219
|
+
hash
|
|
220
|
+
};
|
|
221
|
+
});
|
|
222
|
+
for await (const chunk of createReadStream(targetPath)) {
|
|
223
|
+
for (const candidate of hashes) {
|
|
224
|
+
candidate.hash.update(chunk);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const matchesChecksum = hashes.some((candidate) => candidate.hash.digest("hex") === candidate.expected);
|
|
228
|
+
if (!matchesChecksum) {
|
|
229
|
+
throw new Error(`Download failed: ${path.basename(targetPath)} checksum mismatch.`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async function downloadToFile(url, targetPath, signal) {
|
|
233
|
+
const { response, metadata } = await fetchDownloadResponse(url, signal, config.fetchDownload);
|
|
234
|
+
if (!response.body) {
|
|
235
|
+
throw new Error(`Download failed: missing response body for ${url}`);
|
|
236
|
+
}
|
|
237
|
+
const temporaryPath = `${targetPath}.partial`;
|
|
238
|
+
try {
|
|
239
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(temporaryPath), { signal });
|
|
240
|
+
await validateDownloadedFile(temporaryPath, metadata);
|
|
241
|
+
await rename(temporaryPath, targetPath);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
await rm(temporaryPath, { force: true }).catch(() => {
|
|
244
|
+
return;
|
|
245
|
+
});
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
function createDictationDownloadStagePath(modelId) {
|
|
250
|
+
return path.join(getDictationModelsRootDirectory(), `.${modelId}.download-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
|
|
251
|
+
}
|
|
252
|
+
function createDictationBackupPath(modelId) {
|
|
253
|
+
return path.join(getDictationModelsRootDirectory(), `.${modelId}.backup-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
|
|
254
|
+
}
|
|
255
|
+
async function listManagedAndConfiguredDictationModels() {
|
|
256
|
+
const resolvedModelId = getResolvedDictationModelFiles()?.modelId ?? null;
|
|
257
|
+
return dictationModelDefinitions.map((definition) => {
|
|
258
|
+
const managed = getManagedDictationModelFiles(definition.id) !== null;
|
|
259
|
+
const installed = managed || findConfiguredDictationModelFiles(definition.id) !== null;
|
|
260
|
+
return {
|
|
261
|
+
id: definition.id,
|
|
262
|
+
name: definition.name,
|
|
263
|
+
description: definition.description,
|
|
264
|
+
downloadSizeBytes: definition.downloadSizeBytes,
|
|
265
|
+
downloadSizeLabel: getDictationModelDownloadSizeLabel(definition.downloadSizeBytes),
|
|
266
|
+
installed,
|
|
267
|
+
managed,
|
|
268
|
+
selected: installed && resolvedModelId === definition.id
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
function getDictationInstallFiles(definition) {
|
|
273
|
+
return [
|
|
274
|
+
definition.files.encoder,
|
|
275
|
+
definition.files.decoder,
|
|
276
|
+
definition.files.tokens
|
|
277
|
+
];
|
|
278
|
+
}
|
|
279
|
+
async function downloadDictationModelFiles(input) {
|
|
280
|
+
emitDictationDownloadLog(input.modelId, `Preparing ${input.definition.name} download…`);
|
|
281
|
+
await mkdir(input.stagingDirectory, { recursive: true });
|
|
282
|
+
await getDictationInstallFiles(input.definition).reduce((pending, fileName) => pending.then(async () => {
|
|
283
|
+
emitDictationDownloadLog(input.modelId, `Downloading ${fileName}…`);
|
|
284
|
+
await downloadToFile(buildHuggingFaceResolveUrl(input.definition.huggingFaceRepo, fileName), path.join(input.stagingDirectory, fileName), input.signal);
|
|
285
|
+
emitDictationDownloadLog(input.modelId, `Validated ${fileName}.`);
|
|
286
|
+
}), Promise.resolve());
|
|
287
|
+
}
|
|
288
|
+
async function restoreDictationInstallBackup(input) {
|
|
289
|
+
try {
|
|
290
|
+
await rename(input.backupDirectory, input.modelDirectory);
|
|
291
|
+
} catch (restoreError) {
|
|
292
|
+
const installErrorMessage = input.error instanceof Error ? input.error.message : String(input.error);
|
|
293
|
+
const restoreErrorMessage = restoreError instanceof Error ? restoreError.message : String(restoreError);
|
|
294
|
+
throw new Error(`Could not finalize dictation model install (${installErrorMessage}) and failed to restore the previous model (${restoreErrorMessage}).`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
async function finalizeDictationModelInstall(input) {
|
|
298
|
+
emitDictationDownloadLog(input.modelId, "Finalizing model install…");
|
|
299
|
+
const backupDirectory = existsSync(input.modelDirectory) ? createDictationBackupPath(input.modelId) : null;
|
|
300
|
+
if (backupDirectory)
|
|
301
|
+
await rename(input.modelDirectory, backupDirectory);
|
|
302
|
+
try {
|
|
303
|
+
await rename(input.stagingDirectory, input.modelDirectory);
|
|
304
|
+
} catch (error) {
|
|
305
|
+
if (backupDirectory) {
|
|
306
|
+
await restoreDictationInstallBackup({
|
|
307
|
+
backupDirectory,
|
|
308
|
+
error,
|
|
309
|
+
modelDirectory: input.modelDirectory
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
return backupDirectory;
|
|
315
|
+
}
|
|
316
|
+
async function removeDictationInstallBackup(input) {
|
|
317
|
+
if (!input.backupDirectory)
|
|
318
|
+
return;
|
|
319
|
+
try {
|
|
320
|
+
await rm(input.backupDirectory, { recursive: true, force: true });
|
|
321
|
+
} catch (error) {
|
|
322
|
+
emitDictationDownloadLog(input.modelId, error instanceof Error ? `Installed ${input.definition.name}, but could not remove the previous backup: ${error.message}` : `Installed ${input.definition.name}, but could not remove the previous backup.`);
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
function getDictationInstallErrorMessage(error) {
|
|
326
|
+
return error instanceof Error ? error.message : "Could not download dictation model.";
|
|
327
|
+
}
|
|
328
|
+
async function installManagedDictationModel(modelId, signal) {
|
|
329
|
+
const definition = getDictationModelDefinition(modelId);
|
|
330
|
+
if (!definition) {
|
|
331
|
+
return { ok: false, modelId, error: "Unknown dictation model." };
|
|
332
|
+
}
|
|
333
|
+
const modelDirectory = getDictationModelDirectory(modelId);
|
|
334
|
+
const stagingDirectory = createDictationDownloadStagePath(modelId);
|
|
335
|
+
try {
|
|
336
|
+
await downloadDictationModelFiles({
|
|
337
|
+
definition,
|
|
338
|
+
modelId,
|
|
339
|
+
stagingDirectory,
|
|
340
|
+
signal
|
|
341
|
+
});
|
|
342
|
+
signal?.throwIfAborted();
|
|
343
|
+
const backupDirectory = await finalizeDictationModelInstall({
|
|
344
|
+
modelDirectory,
|
|
345
|
+
modelId,
|
|
346
|
+
stagingDirectory
|
|
347
|
+
});
|
|
348
|
+
await removeDictationInstallBackup({
|
|
349
|
+
backupDirectory,
|
|
350
|
+
definition,
|
|
351
|
+
modelId
|
|
352
|
+
});
|
|
353
|
+
resetRecognizerCache();
|
|
354
|
+
emitDictationDownloadLog(modelId, `${definition.name} is ready.`, {
|
|
355
|
+
done: true
|
|
356
|
+
});
|
|
357
|
+
return { ok: true, modelId, error: null };
|
|
358
|
+
} catch (error) {
|
|
359
|
+
await rm(stagingDirectory, { recursive: true, force: true }).catch(() => {
|
|
360
|
+
return;
|
|
361
|
+
});
|
|
362
|
+
emitDictationDownloadLog(modelId, getDictationInstallErrorMessage(error), {
|
|
363
|
+
done: true,
|
|
364
|
+
isError: true
|
|
365
|
+
});
|
|
366
|
+
return {
|
|
367
|
+
ok: false,
|
|
368
|
+
modelId,
|
|
369
|
+
error: getDictationInstallErrorMessage(error)
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async function removeManagedDictationModel(modelId) {
|
|
374
|
+
const definition = getDictationModelDefinition(modelId);
|
|
375
|
+
if (!definition) {
|
|
376
|
+
return {
|
|
377
|
+
ok: false,
|
|
378
|
+
modelId,
|
|
379
|
+
error: "Unknown dictation model."
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
const modelDirectory = getInstalledManagedDictationModelDirectory(modelId);
|
|
383
|
+
if (!modelDirectory) {
|
|
384
|
+
return {
|
|
385
|
+
ok: true,
|
|
386
|
+
modelId,
|
|
387
|
+
error: null
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
try {
|
|
391
|
+
emitDictationDownloadLog(modelId, `Removing ${definition.name}…`);
|
|
392
|
+
await rm(modelDirectory, { recursive: true, force: true });
|
|
393
|
+
resetRecognizerCache();
|
|
394
|
+
emitDictationDownloadLog(modelId, `${definition.name} was removed.`, {
|
|
395
|
+
done: true
|
|
396
|
+
});
|
|
397
|
+
return {
|
|
398
|
+
ok: true,
|
|
399
|
+
modelId,
|
|
400
|
+
error: null
|
|
401
|
+
};
|
|
402
|
+
} catch (error) {
|
|
403
|
+
emitDictationDownloadLog(modelId, error instanceof Error ? error.message : "Could not remove dictation model.", { done: true, isError: true });
|
|
404
|
+
return {
|
|
405
|
+
ok: false,
|
|
406
|
+
modelId,
|
|
407
|
+
error: error instanceof Error ? error.message : "Could not remove dictation model."
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return {
|
|
412
|
+
listManagedAndConfiguredDictationModels,
|
|
413
|
+
installManagedDictationModel,
|
|
414
|
+
removeManagedDictationModel
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// packages/dictation/src/model-resolution.ts
|
|
419
|
+
import { existsSync as existsSync2, readdirSync } from "node:fs";
|
|
420
|
+
import path3 from "node:path";
|
|
421
|
+
|
|
422
|
+
// packages/dictation/src/helpers.ts
|
|
423
|
+
var englishWhisperModelPattern = /(^|[._-])en($|[._-])/;
|
|
424
|
+
var languageSubtagSeparatorPattern = /[-_]/;
|
|
425
|
+
function inferWhisperLanguage(modelId) {
|
|
426
|
+
return englishWhisperModelPattern.test(modelId) ? "en" : null;
|
|
427
|
+
}
|
|
428
|
+
function normalizeWhisperLanguage(language) {
|
|
429
|
+
if (!language) {
|
|
430
|
+
return null;
|
|
431
|
+
}
|
|
432
|
+
const normalized = language.trim().toLowerCase();
|
|
433
|
+
if (!normalized) {
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
436
|
+
const primarySubtag = normalized.split(languageSubtagSeparatorPattern)[0]?.trim();
|
|
437
|
+
return primarySubtag || null;
|
|
438
|
+
}
|
|
439
|
+
function decodePcm16MonoBytes(bytes) {
|
|
440
|
+
const sampleCount = Math.floor(bytes.byteLength / 2);
|
|
441
|
+
const samples = new Float32Array(sampleCount);
|
|
442
|
+
for (let index = 0;index < sampleCount; index += 1) {
|
|
443
|
+
const lowByte = bytes[index * 2] ?? 0;
|
|
444
|
+
const highByte = bytes[index * 2 + 1] ?? 0;
|
|
445
|
+
let sample = highByte << 8 | lowByte;
|
|
446
|
+
if (sample & 32768) {
|
|
447
|
+
sample -= 65536;
|
|
448
|
+
}
|
|
449
|
+
samples[index] = sample === -32768 ? -1 : sample / 32767;
|
|
450
|
+
}
|
|
451
|
+
return samples;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// packages/dictation/src/model-files.ts
|
|
455
|
+
import path2 from "node:path";
|
|
456
|
+
var whisperEncoderFilePattern = /^(.*)-encoder(\.int8)?\.onnx$/;
|
|
457
|
+
function resolveWhisperModelFilesFromFilePaths(filePaths) {
|
|
458
|
+
const filesByDirectory = new Map;
|
|
459
|
+
for (const filePath of filePaths) {
|
|
460
|
+
const directory = path2.dirname(filePath);
|
|
461
|
+
const fileName = path2.basename(filePath);
|
|
462
|
+
const entrySet = filesByDirectory.get(directory) ?? new Set;
|
|
463
|
+
entrySet.add(fileName);
|
|
464
|
+
filesByDirectory.set(directory, entrySet);
|
|
465
|
+
}
|
|
466
|
+
const encoderCandidates = filePaths.map((filePath) => {
|
|
467
|
+
const match = path2.basename(filePath).match(whisperEncoderFilePattern);
|
|
468
|
+
if (!match) {
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
return {
|
|
472
|
+
filePath,
|
|
473
|
+
directory: path2.dirname(filePath),
|
|
474
|
+
modelId: match[1] ?? "",
|
|
475
|
+
quantized: Boolean(match[2])
|
|
476
|
+
};
|
|
477
|
+
}).filter((value) => value !== null).sort((left, right) => Number(right.quantized) - Number(left.quantized));
|
|
478
|
+
for (const candidate of encoderCandidates) {
|
|
479
|
+
const directoryFiles = filesByDirectory.get(candidate.directory);
|
|
480
|
+
if (!directoryFiles) {
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
const decoderFileName = [
|
|
484
|
+
`${candidate.modelId}-decoder.int8.onnx`,
|
|
485
|
+
`${candidate.modelId}-decoder.onnx`
|
|
486
|
+
].find((fileName) => directoryFiles.has(fileName));
|
|
487
|
+
const tokensFileName = `${candidate.modelId}-tokens.txt`;
|
|
488
|
+
if (!(decoderFileName && directoryFiles.has(tokensFileName))) {
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
return {
|
|
492
|
+
modelDirectory: candidate.directory,
|
|
493
|
+
encoderPath: candidate.filePath,
|
|
494
|
+
decoderPath: path2.join(candidate.directory, decoderFileName),
|
|
495
|
+
tokensPath: path2.join(candidate.directory, tokensFileName),
|
|
496
|
+
modelId: candidate.modelId,
|
|
497
|
+
language: inferWhisperLanguage(candidate.modelId)
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
// packages/dictation/src/model-resolution.ts
|
|
504
|
+
function createModelResolution(options) {
|
|
505
|
+
const DEFAULT_DICTATION_MODEL_DIRECTORY = path3.resolve(options.modelDirectory);
|
|
506
|
+
function getDictationModelDirectories() {
|
|
507
|
+
const configuredDirectories = (options.modelSearchDirectories ?? [
|
|
508
|
+
process.env["PI_SHERPA_ONNX_MODEL_DIR"],
|
|
509
|
+
process.env["PI_DICTATION_MODEL_DIR"]
|
|
510
|
+
]).map((directory) => directory?.trim()).filter((value) => Boolean(value));
|
|
511
|
+
return [
|
|
512
|
+
...new Set([...configuredDirectories, DEFAULT_DICTATION_MODEL_DIRECTORY])
|
|
513
|
+
];
|
|
514
|
+
}
|
|
515
|
+
function getDictationModelsRootDirectory() {
|
|
516
|
+
return DEFAULT_DICTATION_MODEL_DIRECTORY;
|
|
517
|
+
}
|
|
518
|
+
function getDictationModelDirectory(modelId) {
|
|
519
|
+
return path3.join(getDictationModelsRootDirectory(), modelId);
|
|
520
|
+
}
|
|
521
|
+
function getManagedDictationModelFiles(modelId) {
|
|
522
|
+
const definition = getDictationModelDefinition(modelId);
|
|
523
|
+
if (!definition) {
|
|
524
|
+
return null;
|
|
525
|
+
}
|
|
526
|
+
const modelDirectory = getDictationModelDirectory(modelId);
|
|
527
|
+
const encoderPath = path3.join(modelDirectory, definition.files.encoder);
|
|
528
|
+
const decoderPath = path3.join(modelDirectory, definition.files.decoder);
|
|
529
|
+
const tokensPath = path3.join(modelDirectory, definition.files.tokens);
|
|
530
|
+
if (!(existsSync2(encoderPath) && existsSync2(decoderPath) && existsSync2(tokensPath))) {
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
return {
|
|
534
|
+
modelDirectory,
|
|
535
|
+
encoderPath,
|
|
536
|
+
decoderPath,
|
|
537
|
+
tokensPath,
|
|
538
|
+
modelId,
|
|
539
|
+
language: inferWhisperLanguage(modelId) ?? normalizeWhisperLanguage(modelId)
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
function getInstalledManagedDictationModelFiles() {
|
|
543
|
+
return dictationModelDefinitions.flatMap((definition) => {
|
|
544
|
+
const modelFiles = getManagedDictationModelFiles(definition.id);
|
|
545
|
+
return modelFiles ? [modelFiles] : [];
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
function readDirectoryEntries(directoryPath) {
|
|
549
|
+
try {
|
|
550
|
+
return readdirSync(directoryPath, { withFileTypes: true });
|
|
551
|
+
} catch {
|
|
552
|
+
return [];
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
function collectCandidateFilesFromEntry({
|
|
556
|
+
entry,
|
|
557
|
+
current,
|
|
558
|
+
maxDepth,
|
|
559
|
+
pending
|
|
560
|
+
}) {
|
|
561
|
+
if (entry.name.startsWith(".")) {
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
const entryPath = path3.join(current.directoryPath, entry.name);
|
|
565
|
+
if (entry.isDirectory()) {
|
|
566
|
+
if (current.depth < maxDepth) {
|
|
567
|
+
pending.push({ directoryPath: entryPath, depth: current.depth + 1 });
|
|
568
|
+
}
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
return entry.isFile() ? entryPath : null;
|
|
572
|
+
}
|
|
573
|
+
function collectCandidateFiles(rootDirectory, maxDepth = 3) {
|
|
574
|
+
const pending = [{ directoryPath: rootDirectory, depth: 0 }];
|
|
575
|
+
const filePaths = [];
|
|
576
|
+
while (pending.length > 0) {
|
|
577
|
+
const current = pending.pop();
|
|
578
|
+
if (!current)
|
|
579
|
+
continue;
|
|
580
|
+
for (const entry of readDirectoryEntries(current.directoryPath)) {
|
|
581
|
+
const filePath = collectCandidateFilesFromEntry({
|
|
582
|
+
entry,
|
|
583
|
+
current,
|
|
584
|
+
maxDepth,
|
|
585
|
+
pending
|
|
586
|
+
});
|
|
587
|
+
if (filePath)
|
|
588
|
+
filePaths.push(filePath);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
return filePaths;
|
|
592
|
+
}
|
|
593
|
+
function resolveConfiguredDictationModelFilesFromDirectory(directoryPath, modelId) {
|
|
594
|
+
const candidateFiles = collectCandidateFiles(directoryPath);
|
|
595
|
+
if (!modelId) {
|
|
596
|
+
return resolveWhisperModelFilesFromFilePaths(candidateFiles);
|
|
597
|
+
}
|
|
598
|
+
return resolveWhisperModelFilesFromFilePaths(candidateFiles.filter((filePath) => path3.basename(filePath).startsWith(`${modelId}-`)));
|
|
599
|
+
}
|
|
600
|
+
function findConfiguredDictationModelFiles(modelId) {
|
|
601
|
+
for (const directoryPath of getDictationModelDirectories()) {
|
|
602
|
+
const modelFiles = resolveConfiguredDictationModelFilesFromDirectory(directoryPath, modelId);
|
|
603
|
+
if (!modelFiles) {
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
return modelFiles;
|
|
607
|
+
}
|
|
608
|
+
return null;
|
|
609
|
+
}
|
|
610
|
+
function getSelectedDictationModelFiles() {
|
|
611
|
+
const selectedModelId = options.getSelectedModelId();
|
|
612
|
+
const selectedModelFiles = selectedModelId ? getManagedDictationModelFiles(selectedModelId) ?? findConfiguredDictationModelFiles(selectedModelId) : null;
|
|
613
|
+
if (selectedModelFiles) {
|
|
614
|
+
return selectedModelFiles;
|
|
615
|
+
}
|
|
616
|
+
return getInstalledManagedDictationModelFiles()[0] ?? null;
|
|
617
|
+
}
|
|
618
|
+
function getResolvedDictationModelFiles() {
|
|
619
|
+
return getSelectedDictationModelFiles() ?? findConfiguredDictationModelFiles();
|
|
620
|
+
}
|
|
621
|
+
function getInstalledManagedDictationModelDirectory(modelId) {
|
|
622
|
+
return getManagedDictationModelFiles(modelId)?.modelDirectory ?? null;
|
|
623
|
+
}
|
|
624
|
+
return {
|
|
625
|
+
DEFAULT_DICTATION_MODEL_DIRECTORY,
|
|
626
|
+
getDictationModelDirectories,
|
|
627
|
+
getDictationModelsRootDirectory,
|
|
628
|
+
getDictationModelDirectory,
|
|
629
|
+
getManagedDictationModelFiles,
|
|
630
|
+
findConfiguredDictationModelFiles,
|
|
631
|
+
getResolvedDictationModelFiles,
|
|
632
|
+
getInstalledManagedDictationModelDirectory
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// packages/dictation/src/sherpa-onnx.ts
|
|
637
|
+
function createTranscriptionService(resolution, runtime, options) {
|
|
638
|
+
const {
|
|
639
|
+
DEFAULT_DICTATION_MODEL_DIRECTORY,
|
|
640
|
+
getDictationModelDirectories,
|
|
641
|
+
getResolvedDictationModelFiles
|
|
642
|
+
} = resolution;
|
|
643
|
+
const { getRecognizer, getSherpaPlatformPackageName, loadSherpaOnnxModule } = runtime;
|
|
644
|
+
function buildUnavailableDictationState(error, reason) {
|
|
645
|
+
const [modelDirectory = DEFAULT_DICTATION_MODEL_DIRECTORY] = getDictationModelDirectories();
|
|
646
|
+
return {
|
|
647
|
+
available: false,
|
|
648
|
+
reason,
|
|
649
|
+
runtime: null,
|
|
650
|
+
modelDirectory,
|
|
651
|
+
modelId: null,
|
|
652
|
+
language: null,
|
|
653
|
+
error
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function buildUnavailableTranscriptionResult(error) {
|
|
657
|
+
const [modelDirectory = DEFAULT_DICTATION_MODEL_DIRECTORY] = getDictationModelDirectories();
|
|
658
|
+
return {
|
|
659
|
+
ok: false,
|
|
660
|
+
text: "",
|
|
661
|
+
runtime: null,
|
|
662
|
+
modelDirectory,
|
|
663
|
+
modelId: null,
|
|
664
|
+
language: null,
|
|
665
|
+
error
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
function decodeBase64Pcm16Mono(audioBase64) {
|
|
669
|
+
return decodePcm16MonoBytes(Buffer.from(audioBase64, "base64"));
|
|
670
|
+
}
|
|
671
|
+
async function getDictationState() {
|
|
672
|
+
if (!getSherpaPlatformPackageName()) {
|
|
673
|
+
return buildUnavailableDictationState("Local dictation is unavailable on this platform.", "unsupported-platform");
|
|
674
|
+
}
|
|
675
|
+
const modelFiles = getResolvedDictationModelFiles();
|
|
676
|
+
if (!modelFiles) {
|
|
677
|
+
const [modelDirectory = DEFAULT_DICTATION_MODEL_DIRECTORY] = getDictationModelDirectories();
|
|
678
|
+
return buildUnavailableDictationState(`No Whisper model was found. Expected a sherpa-onnx Whisper model under ${modelDirectory}.`, "missing-model");
|
|
679
|
+
}
|
|
680
|
+
try {
|
|
681
|
+
await loadSherpaOnnxModule();
|
|
682
|
+
} catch (error) {
|
|
683
|
+
return buildUnavailableDictationState(error instanceof Error ? error.message : "Could not load sherpa-onnx-node.", "runtime-error");
|
|
684
|
+
}
|
|
685
|
+
return {
|
|
686
|
+
available: true,
|
|
687
|
+
reason: null,
|
|
688
|
+
runtime: "sherpa-onnx-node",
|
|
689
|
+
modelDirectory: modelFiles.modelDirectory,
|
|
690
|
+
modelId: modelFiles.modelId,
|
|
691
|
+
language: modelFiles.language,
|
|
692
|
+
error: null
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
async function transcribeDictation(request) {
|
|
696
|
+
const dictationState = await getDictationState();
|
|
697
|
+
if (!dictationState.available) {
|
|
698
|
+
return {
|
|
699
|
+
ok: false,
|
|
700
|
+
text: "",
|
|
701
|
+
runtime: dictationState.runtime,
|
|
702
|
+
modelDirectory: dictationState.modelDirectory,
|
|
703
|
+
modelId: dictationState.modelId,
|
|
704
|
+
language: dictationState.language,
|
|
705
|
+
error: dictationState.error
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
const modelFiles = getResolvedDictationModelFiles();
|
|
709
|
+
if (!modelFiles) {
|
|
710
|
+
return buildUnavailableTranscriptionResult("The configured Whisper model could not be resolved.");
|
|
711
|
+
}
|
|
712
|
+
if (!request.audioBase64.trim()) {
|
|
713
|
+
return {
|
|
714
|
+
ok: false,
|
|
715
|
+
text: "",
|
|
716
|
+
runtime: "sherpa-onnx-node",
|
|
717
|
+
modelDirectory: modelFiles.modelDirectory,
|
|
718
|
+
modelId: modelFiles.modelId,
|
|
719
|
+
language: modelFiles.language,
|
|
720
|
+
error: "No dictation audio was provided."
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
const samples = decodeBase64Pcm16Mono(request.audioBase64);
|
|
724
|
+
if (samples.length === 0) {
|
|
725
|
+
return {
|
|
726
|
+
ok: false,
|
|
727
|
+
text: "",
|
|
728
|
+
runtime: "sherpa-onnx-node",
|
|
729
|
+
modelDirectory: modelFiles.modelDirectory,
|
|
730
|
+
modelId: modelFiles.modelId,
|
|
731
|
+
language: modelFiles.language,
|
|
732
|
+
error: "No speech was captured."
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
const language = normalizeWhisperLanguage((options.language ?? process.env["PI_SHERPA_ONNX_LANGUAGE"])?.trim() || modelFiles.language || request.language);
|
|
736
|
+
try {
|
|
737
|
+
const recognizer = await getRecognizer(modelFiles, language);
|
|
738
|
+
const stream = recognizer.createStream();
|
|
739
|
+
stream.acceptWaveform({
|
|
740
|
+
samples,
|
|
741
|
+
sampleRate: request.sampleRate
|
|
742
|
+
});
|
|
743
|
+
const result = await recognizer.decodeAsync(stream);
|
|
744
|
+
return {
|
|
745
|
+
ok: true,
|
|
746
|
+
text: result.text?.trim() ?? "",
|
|
747
|
+
runtime: "sherpa-onnx-node",
|
|
748
|
+
modelDirectory: modelFiles.modelDirectory,
|
|
749
|
+
modelId: modelFiles.modelId,
|
|
750
|
+
language: normalizeWhisperLanguage(result.lang) ?? language,
|
|
751
|
+
error: null
|
|
752
|
+
};
|
|
753
|
+
} catch (error) {
|
|
754
|
+
return {
|
|
755
|
+
ok: false,
|
|
756
|
+
text: "",
|
|
757
|
+
runtime: "sherpa-onnx-node",
|
|
758
|
+
modelDirectory: modelFiles.modelDirectory,
|
|
759
|
+
modelId: modelFiles.modelId,
|
|
760
|
+
language,
|
|
761
|
+
error: error instanceof Error ? error.message : "Dictation transcription failed unexpectedly."
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
return { getDictationState, transcribeDictation };
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// packages/dictation/src/sherpa-runtime.ts
|
|
769
|
+
import { createRequire } from "node:module";
|
|
770
|
+
import os from "node:os";
|
|
771
|
+
import path4 from "node:path";
|
|
772
|
+
var require2 = createRequire(import.meta.url);
|
|
773
|
+
function createSherpaRuntime(options) {
|
|
774
|
+
let sherpaOnnxModulePromise = null;
|
|
775
|
+
let recognizerCache = null;
|
|
776
|
+
function getSherpaPlatformPackageName() {
|
|
777
|
+
switch (`${process.platform}-${process.arch}`) {
|
|
778
|
+
case "darwin-arm64":
|
|
779
|
+
return "sherpa-onnx-darwin-arm64";
|
|
780
|
+
case "darwin-x64":
|
|
781
|
+
return "sherpa-onnx-darwin-x64";
|
|
782
|
+
case "linux-arm64":
|
|
783
|
+
return "sherpa-onnx-linux-arm64";
|
|
784
|
+
case "linux-x64":
|
|
785
|
+
return "sherpa-onnx-linux-x64";
|
|
786
|
+
case "win32-ia32":
|
|
787
|
+
return "sherpa-onnx-win-ia32";
|
|
788
|
+
case "win32-x64":
|
|
789
|
+
return "sherpa-onnx-win-x64";
|
|
790
|
+
default:
|
|
791
|
+
return null;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
function prependLibraryPath(envKey, directoryPath) {
|
|
795
|
+
const current = process.env[envKey];
|
|
796
|
+
const entries = (current ?? "").split(path4.delimiter).map((entry) => entry.trim()).filter(Boolean);
|
|
797
|
+
if (entries.includes(directoryPath)) {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
process.env[envKey] = [directoryPath, ...entries].join(path4.delimiter);
|
|
801
|
+
}
|
|
802
|
+
function ensureSherpaLibraryPath() {
|
|
803
|
+
const packageName = getSherpaPlatformPackageName();
|
|
804
|
+
if (!packageName) {
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
try {
|
|
808
|
+
const packageJsonPath = require2.resolve(`${packageName}/package.json`);
|
|
809
|
+
const packageDirectory = path4.dirname(packageJsonPath);
|
|
810
|
+
if (process.platform === "darwin") {
|
|
811
|
+
prependLibraryPath("DYLD_LIBRARY_PATH", packageDirectory);
|
|
812
|
+
}
|
|
813
|
+
if (process.platform === "linux") {
|
|
814
|
+
prependLibraryPath("LD_LIBRARY_PATH", packageDirectory);
|
|
815
|
+
}
|
|
816
|
+
} catch {}
|
|
817
|
+
}
|
|
818
|
+
async function loadSherpaOnnxModule() {
|
|
819
|
+
if (!sherpaOnnxModulePromise) {
|
|
820
|
+
sherpaOnnxModulePromise = Promise.resolve().then(() => {
|
|
821
|
+
ensureSherpaLibraryPath();
|
|
822
|
+
return require2("sherpa-onnx-node");
|
|
823
|
+
}).catch((error) => {
|
|
824
|
+
sherpaOnnxModulePromise = null;
|
|
825
|
+
throw error;
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
return sherpaOnnxModulePromise;
|
|
829
|
+
}
|
|
830
|
+
function getRecognizerThreadCount() {
|
|
831
|
+
if (options.numThreads !== undefined)
|
|
832
|
+
return options.numThreads;
|
|
833
|
+
const configured = Number.parseInt(process.env["PI_SHERPA_ONNX_NUM_THREADS"] ?? "", 10);
|
|
834
|
+
if (Number.isFinite(configured) && configured > 0) {
|
|
835
|
+
return configured;
|
|
836
|
+
}
|
|
837
|
+
return Math.max(1, Math.min(typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length, 4));
|
|
838
|
+
}
|
|
839
|
+
function buildRecognizerConfig(modelFiles, language) {
|
|
840
|
+
return {
|
|
841
|
+
featConfig: {
|
|
842
|
+
sampleRate: 16000,
|
|
843
|
+
featureDim: 80
|
|
844
|
+
},
|
|
845
|
+
modelConfig: {
|
|
846
|
+
whisper: {
|
|
847
|
+
encoder: modelFiles.encoderPath,
|
|
848
|
+
decoder: modelFiles.decoderPath,
|
|
849
|
+
language: language ?? undefined,
|
|
850
|
+
task: "transcribe",
|
|
851
|
+
tailPaddings: -1
|
|
852
|
+
},
|
|
853
|
+
tokens: modelFiles.tokensPath,
|
|
854
|
+
numThreads: getRecognizerThreadCount(),
|
|
855
|
+
provider: (options.provider ?? process.env["PI_SHERPA_ONNX_PROVIDER"])?.trim() || "cpu",
|
|
856
|
+
debug: false
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
function buildRecognizerCacheKey(modelFiles, language) {
|
|
861
|
+
return JSON.stringify({
|
|
862
|
+
encoderPath: modelFiles.encoderPath,
|
|
863
|
+
decoderPath: modelFiles.decoderPath,
|
|
864
|
+
tokensPath: modelFiles.tokensPath,
|
|
865
|
+
language
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
async function getRecognizer(modelFiles, language) {
|
|
869
|
+
const cacheKey = buildRecognizerCacheKey(modelFiles, language);
|
|
870
|
+
if (!recognizerCache || recognizerCache.key !== cacheKey) {
|
|
871
|
+
const promise = loadSherpaOnnxModule().then((sherpaOnnx) => sherpaOnnx.OfflineRecognizer.createAsync(buildRecognizerConfig(modelFiles, language))).catch((error) => {
|
|
872
|
+
if (recognizerCache?.key === cacheKey) {
|
|
873
|
+
recognizerCache = null;
|
|
874
|
+
}
|
|
875
|
+
throw error;
|
|
876
|
+
});
|
|
877
|
+
recognizerCache = {
|
|
878
|
+
key: cacheKey,
|
|
879
|
+
promise
|
|
880
|
+
};
|
|
881
|
+
}
|
|
882
|
+
return recognizerCache.promise;
|
|
883
|
+
}
|
|
884
|
+
function resetRecognizerCache() {
|
|
885
|
+
recognizerCache = null;
|
|
886
|
+
}
|
|
887
|
+
return {
|
|
888
|
+
getRecognizer,
|
|
889
|
+
getSherpaPlatformPackageName,
|
|
890
|
+
loadSherpaOnnxModule,
|
|
891
|
+
resetRecognizerCache
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// packages/dictation/src/index.ts
|
|
896
|
+
function createDictationService(options) {
|
|
897
|
+
if (!options.modelDirectory.trim())
|
|
898
|
+
throw new Error("A dictation model directory is required.");
|
|
899
|
+
if (options.numThreads !== undefined && (!Number.isSafeInteger(options.numThreads) || options.numThreads <= 0))
|
|
900
|
+
throw new Error("Dictation numThreads must be a positive safe integer.");
|
|
901
|
+
const resolution = createModelResolution(options);
|
|
902
|
+
const runtime = createSherpaRuntime(options);
|
|
903
|
+
const models = createModelManagement(options, resolution, runtime);
|
|
904
|
+
const transcription = createTranscriptionService(resolution, runtime, options);
|
|
905
|
+
const downloads = new AbortController;
|
|
906
|
+
const pending = new Set;
|
|
907
|
+
let stopping = false;
|
|
908
|
+
let disposal;
|
|
909
|
+
let exclusive = Promise.resolve();
|
|
910
|
+
function run(evaluate, serialize = false) {
|
|
911
|
+
if (stopping)
|
|
912
|
+
return Promise.reject(new Error("Dictation service is shutting down."));
|
|
913
|
+
const task = serialize ? exclusive.then(() => {
|
|
914
|
+
downloads.signal.throwIfAborted();
|
|
915
|
+
return evaluate();
|
|
916
|
+
}) : Promise.resolve().then(evaluate);
|
|
917
|
+
if (serialize)
|
|
918
|
+
exclusive = task.catch(() => {
|
|
919
|
+
return;
|
|
920
|
+
});
|
|
921
|
+
pending.add(task);
|
|
922
|
+
task.then(() => pending.delete(task), () => pending.delete(task));
|
|
923
|
+
return task;
|
|
924
|
+
}
|
|
925
|
+
const service = {
|
|
926
|
+
getDictationState: () => run(transcription.getDictationState),
|
|
927
|
+
listDictationModels: () => run(models.listManagedAndConfiguredDictationModels),
|
|
928
|
+
installDictationModel: ({ modelId }) => run(() => models.installManagedDictationModel(modelId, downloads.signal), true),
|
|
929
|
+
removeDictationModel: ({ modelId }) => run(() => models.removeManagedDictationModel(modelId), true),
|
|
930
|
+
transcribeDictation: (request) => run(() => transcription.transcribeDictation(request), true)
|
|
931
|
+
};
|
|
932
|
+
return {
|
|
933
|
+
service,
|
|
934
|
+
isBusy: () => pending.size > 0,
|
|
935
|
+
dispose() {
|
|
936
|
+
if (!disposal) {
|
|
937
|
+
stopping = true;
|
|
938
|
+
downloads.abort();
|
|
939
|
+
disposal = Promise.allSettled(pending).then(() => {
|
|
940
|
+
runtime.resetRecognizerCache();
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
return disposal;
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// packages/dictation/src/activation.ts
|
|
949
|
+
var dictationOptions = defineCapability("howaboua.dictation.options.v1", (value) => isCapabilityObject(value) && typeof value["environmentId"] === "string" && value["environmentId"].trim().length > 0 && typeof value["modelDirectory"] === "string" && isAbsolute(value["modelDirectory"]) && Array.isArray(value["modelSearchDirectories"]) && value["modelSearchDirectories"].every((directory) => typeof directory === "string" && isAbsolute(directory)) && typeof value["language"] === "string" && typeof value["numThreads"] === "number" && Number.isSafeInteger(value["numThreads"]) && value["numThreads"] > 0 && typeof value["provider"] === "string" && typeof value["fetchDownload"] === "function" && typeof value["getSelectedModelId"] === "function");
|
|
950
|
+
function createComponent(request) {
|
|
951
|
+
const options = request.capabilities.has(dictationOptions.id) ? request.capabilities.get(dictationOptions) : baselineOptions(request);
|
|
952
|
+
const api = createDictationService(options);
|
|
953
|
+
return {
|
|
954
|
+
api,
|
|
955
|
+
retention: "idle",
|
|
956
|
+
beforeClose: () => api.dispose()
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
function baselineOptions(request) {
|
|
960
|
+
const native = request.capabilities.get(nodeExecutionCapability);
|
|
961
|
+
const network = request.capabilities.get(networkCapability);
|
|
962
|
+
const modelDirectory = request.capabilities.get(stateCapability).directory("dictation");
|
|
963
|
+
const modelId = request.configuration["modelId"] ?? null;
|
|
964
|
+
if (modelId !== null && modelId !== "tiny.en" && modelId !== "base.en" && modelId !== "small.en")
|
|
965
|
+
throw new Error("Unknown dictation model selection");
|
|
966
|
+
const language = request.configuration["language"] ?? "";
|
|
967
|
+
const provider = request.configuration["provider"] ?? "cpu";
|
|
968
|
+
const numThreads = request.configuration["numThreads"] ?? 1;
|
|
969
|
+
return dictationOptions.parse({
|
|
970
|
+
environmentId: native.environmentId,
|
|
971
|
+
modelDirectory,
|
|
972
|
+
modelSearchDirectories: [],
|
|
973
|
+
language,
|
|
974
|
+
provider,
|
|
975
|
+
numThreads,
|
|
976
|
+
fetchDownload: (url, init) => network.fetch(url, init),
|
|
977
|
+
getSelectedModelId: () => modelId
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
export {
|
|
981
|
+
createComponent,
|
|
982
|
+
dictationOptions
|
|
983
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -76,7 +76,7 @@ function mergeDownloadMetadata(current, headers, options) {
|
|
|
76
76
|
function isRedirectStatus(status) {
|
|
77
77
|
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
78
78
|
}
|
|
79
|
-
async function fetchDownloadResponse(url, signal) {
|
|
79
|
+
async function fetchDownloadResponse(url, signal, fetchDownload = fetch) {
|
|
80
80
|
let currentUrl = url;
|
|
81
81
|
let metadata = {
|
|
82
82
|
contentLength: null,
|
|
@@ -84,7 +84,7 @@ async function fetchDownloadResponse(url, signal) {
|
|
|
84
84
|
etagSource: null
|
|
85
85
|
};
|
|
86
86
|
for (let redirectCount = 0;redirectCount <= MAX_DOWNLOAD_REDIRECTS; redirectCount += 1) {
|
|
87
|
-
const response = await
|
|
87
|
+
const response = await fetchDownload(currentUrl, {
|
|
88
88
|
redirect: "manual",
|
|
89
89
|
...signal ? { signal } : {}
|
|
90
90
|
});
|
|
@@ -220,7 +220,7 @@ function createModelManagement(config, resolution, runtime) {
|
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
222
|
async function downloadToFile(url, targetPath, signal) {
|
|
223
|
-
const { response, metadata } = await fetchDownloadResponse(url, signal);
|
|
223
|
+
const { response, metadata } = await fetchDownloadResponse(url, signal, config.fetchDownload);
|
|
224
224
|
if (!response.body) {
|
|
225
225
|
throw new Error(`Download failed: missing response body for ${url}`);
|
|
226
226
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type ComponentInstance, type ComponentRequest } from "@howaboua/pi-durable-components";
|
|
2
|
+
import type { DictationServiceOptions } from "./contracts.ts";
|
|
3
|
+
import { createDictationService } from "./index.ts";
|
|
4
|
+
/** Explicit native namespace grant; paths belong to that environment, not host discovery. */
|
|
5
|
+
export type DictationComponentOptions = DictationServiceOptions & {
|
|
6
|
+
environmentId: string;
|
|
7
|
+
modelSearchDirectories: readonly string[];
|
|
8
|
+
language: string;
|
|
9
|
+
numThreads: number;
|
|
10
|
+
provider: string;
|
|
11
|
+
fetchDownload: NonNullable<DictationServiceOptions["fetchDownload"]>;
|
|
12
|
+
};
|
|
13
|
+
export declare const dictationOptions: import("@howaboua/pi-durable-components").ComponentCapability<DictationComponentOptions>;
|
|
14
|
+
export declare function createComponent(request: ComponentRequest): ComponentInstance<ReturnType<typeof createDictationService>>;
|
|
@@ -66,6 +66,8 @@ export type DictationServiceOptions = {
|
|
|
66
66
|
modelDirectory: string;
|
|
67
67
|
/** Ordered discovery roots, replacing PI_* model directories when supplied. The managed root is appended. */
|
|
68
68
|
modelSearchDirectories?: readonly string[];
|
|
69
|
+
/** Host-authorised model egress, called separately for every redirect hop. */
|
|
70
|
+
fetchDownload?: (url: string, init: RequestInit) => Promise<Response>;
|
|
69
71
|
/** Overrides PI_SHERPA_ONNX_LANGUAGE. Blank uses the model or request language. */
|
|
70
72
|
language?: string;
|
|
71
73
|
/** Positive integer overriding PI_SHERPA_ONNX_NUM_THREADS. */
|
|
@@ -10,7 +10,7 @@ export type DownloadChecksumExpectation = {
|
|
|
10
10
|
prefix: Buffer | null;
|
|
11
11
|
};
|
|
12
12
|
export declare function getDownloadChecksumExpectations(etag: string | null, contentLength: number): DownloadChecksumExpectation[];
|
|
13
|
-
export declare function fetchDownloadResponse(url: string, signal?: AbortSignal): Promise<{
|
|
13
|
+
export declare function fetchDownloadResponse(url: string, signal?: AbortSignal, fetchDownload?: (url: string, init: RequestInit) => Promise<Response>): Promise<{
|
|
14
14
|
response: Response;
|
|
15
15
|
metadata: DownloadMetadata;
|
|
16
16
|
}>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@howaboua/pi-durable-dictation",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Portable local Whisper dictation with the sherpa-onnx native runtime",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,6 +31,10 @@
|
|
|
31
31
|
"./helpers": {
|
|
32
32
|
"types": "./dist/packages/dictation/src/helpers.d.ts",
|
|
33
33
|
"import": "./dist/helpers.js"
|
|
34
|
+
},
|
|
35
|
+
"./component": {
|
|
36
|
+
"types": "./dist/packages/dictation/src/activation.d.ts",
|
|
37
|
+
"import": "./dist/activation.js"
|
|
34
38
|
}
|
|
35
39
|
},
|
|
36
40
|
"files": [
|
|
@@ -41,9 +45,28 @@
|
|
|
41
45
|
],
|
|
42
46
|
"sideEffects": false,
|
|
43
47
|
"dependencies": {
|
|
44
|
-
"sherpa-onnx-node": "1.13.8"
|
|
48
|
+
"sherpa-onnx-node": "1.13.8",
|
|
49
|
+
"@howaboua/pi-durable-components": "0.11.0"
|
|
45
50
|
},
|
|
46
51
|
"publishConfig": {
|
|
47
52
|
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"durable": {
|
|
55
|
+
"schemaVersion": 1,
|
|
56
|
+
"kind": "service",
|
|
57
|
+
"entry": "./component",
|
|
58
|
+
"runtimes": [
|
|
59
|
+
"node"
|
|
60
|
+
],
|
|
61
|
+
"requires": [
|
|
62
|
+
"durable.node-execution.v1",
|
|
63
|
+
"durable.network.v1",
|
|
64
|
+
"durable.state.v1"
|
|
65
|
+
],
|
|
66
|
+
"permissions": [
|
|
67
|
+
"filesystem",
|
|
68
|
+
"process",
|
|
69
|
+
"network"
|
|
70
|
+
]
|
|
48
71
|
}
|
|
49
72
|
}
|