@hyperwindmill/caretaker-cli 0.29.0 → 0.30.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/dist/agents/dispatch.d.ts.map +1 -1
- package/dist/agents/dispatch.js +4 -1
- package/dist/cli/web/server.d.ts.map +1 -1
- package/dist/cli/web/server.js +29 -7
- package/dist/cli/web/session_scope.d.ts +11 -0
- package/dist/cli/web/session_scope.d.ts.map +1 -0
- package/dist/cli/web/session_scope.js +13 -0
- package/dist/cli/web/turn_guard.d.ts +9 -0
- package/dist/cli/web/turn_guard.d.ts.map +1 -0
- package/dist/cli/web/turn_guard.js +18 -0
- package/dist/cli/web/voice_builtin.d.ts +3 -0
- package/dist/cli/web/voice_builtin.d.ts.map +1 -0
- package/dist/cli/web/voice_builtin.js +55 -0
- package/dist/cli/web/voice_proxy.d.ts +33 -1
- package/dist/cli/web/voice_proxy.d.ts.map +1 -1
- package/dist/cli/web/voice_proxy.js +173 -27
- package/dist/commands/loader.js +2 -2
- package/dist/harness/tools/builtin/index.d.ts.map +1 -1
- package/dist/harness/tools/builtin/index.js +4 -0
- package/dist/harness/tools/builtin/set_workspace.d.ts +3 -0
- package/dist/harness/tools/builtin/set_workspace.d.ts.map +1 -0
- package/dist/harness/tools/builtin/set_workspace.js +49 -0
- package/dist/plugins/manifest.d.ts +1 -1
- package/dist/plugins/manifest.js +1 -1
- package/dist/session/store.d.ts +6 -0
- package/dist/session/store.d.ts.map +1 -1
- package/dist/session/store.js +8 -0
- package/dist/session/types.d.ts +4 -0
- package/dist/session/types.d.ts.map +1 -1
- package/dist/voice/pocket/catalog.d.ts +24 -0
- package/dist/voice/pocket/catalog.d.ts.map +1 -0
- package/dist/voice/pocket/catalog.js +152 -0
- package/dist/voice/pocket/engine.d.ts +17 -0
- package/dist/voice/pocket/engine.d.ts.map +1 -0
- package/dist/voice/pocket/engine.js +145 -0
- package/dist/voice/pocket/inference.d.ts +36 -0
- package/dist/voice/pocket/inference.d.ts.map +1 -0
- package/dist/voice/pocket/inference.js +228 -0
- package/dist/voice/pocket/install.d.ts +54 -0
- package/dist/voice/pocket/install.d.ts.map +1 -0
- package/dist/voice/pocket/install.js +275 -0
- package/dist/voice/pocket/tokenizer.d.ts +42 -0
- package/dist/voice/pocket/tokenizer.d.ts.map +1 -0
- package/dist/voice/pocket/tokenizer.js +279 -0
- package/dist/voice/pocket/voices.d.ts +9 -0
- package/dist/voice/pocket/voices.d.ts.map +1 -0
- package/dist/voice/pocket/voices.js +88 -0
- package/dist/voice/pronunciation.d.ts +16 -0
- package/dist/voice/pronunciation.d.ts.map +1 -0
- package/dist/voice/pronunciation.js +51 -0
- package/dist/webview/standalone.js +1508 -701
- package/dist/webview/standalone.js.map +4 -4
- package/package.json +3 -3
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
// Own inference loop over one Pocket TTS schema-3 ONNX bundle (four graphs with explicit
|
|
2
|
+
// streaming state), following upstream pocket_tts at the bundle's upstream commit:
|
|
3
|
+
// tokenizer -> text conditioner -> flow LM main (prompted with the text on top of the
|
|
4
|
+
// voice's KV cache) -> per frame: flow step(s) on gaussian noise -> mimi decoder.
|
|
5
|
+
// The ONNX runtime is passed in (downloaded at runtime, never a package dependency).
|
|
6
|
+
import { readFile } from 'node:fs/promises';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { UnigramTokenizer, prepareChunks } from './tokenizer.js';
|
|
9
|
+
import { padInto, parseVoices } from './voices.js';
|
|
10
|
+
// Not named in bundle.json; these are the bundle's file names (see catalog.ts).
|
|
11
|
+
export const POCKET_GRAPHS = {
|
|
12
|
+
textConditioner: 'text_conditioner_int8.onnx',
|
|
13
|
+
flowMain: 'flow_lm_main_int8.onnx',
|
|
14
|
+
flowStep: 'flow_lm_flow_int8.onnx',
|
|
15
|
+
mimi: 'mimi_decoder_int8.onnx',
|
|
16
|
+
};
|
|
17
|
+
export const POCKET_VOICES_FILE = 'voices.bin';
|
|
18
|
+
// upstream TTSModel._TOKENS_PER_SECOND_ESTIMATE / _GEN_SECONDS_PADDING
|
|
19
|
+
const TOKENS_PER_SECOND = 3;
|
|
20
|
+
// The bundle's eos_threshold (-4, upstream's float default) is crossed by these int8
|
|
21
|
+
// graphs at random points mid-sentence, cutting the rest of it. Measured on the Italian
|
|
22
|
+
// bundle: real ends score 1.9..28, spurious crossings -3.9..-0.9 (as early as 2 s into a
|
|
23
|
+
// 6 s sentence). Only a confident crossing ends a chunk; maxGen still bounds it.
|
|
24
|
+
const CONFIDENT_EOS_LOGIT = 0;
|
|
25
|
+
// Some voices still signal the end a moment before the last syllable is out; a few
|
|
26
|
+
// more frames (80 ms each) keep it, at the cost of a slightly longer pause.
|
|
27
|
+
const EXTRA_FRAMES_AFTER_EOS = 4;
|
|
28
|
+
const GEN_SECONDS_PADDING = 2;
|
|
29
|
+
// Latent frames decoded per mimi call. A mimi call has a large fixed cost (it rewrites its
|
|
30
|
+
// whole streaming KV cache, measured ~70 ms on the reference machine against ~6 ms per
|
|
31
|
+
// extra frame), so decoding one frame at a time runs below real time; 4 frames keep
|
|
32
|
+
// generation ahead of playback from the first group on (~1.5x real time there).
|
|
33
|
+
export const DEFAULT_FRAMES_PER_DECODE = 4;
|
|
34
|
+
export async function createPocketModel(ort, bundleDir, opts) {
|
|
35
|
+
const bundle = JSON.parse(await readFile(join(bundleDir, 'bundle.json'), 'utf8'));
|
|
36
|
+
if (bundle.schema_version !== 3)
|
|
37
|
+
throw new Error(`unsupported Pocket bundle schema ${bundle.schema_version}`);
|
|
38
|
+
if (!bundle.voice_state_includes_bos)
|
|
39
|
+
throw new Error('Pocket bundle voices without BOS are not supported');
|
|
40
|
+
const tokenizer = new UnigramTokenizer(JSON.parse(await readFile(join(bundleDir, bundle.tokenizer_file), 'utf8')));
|
|
41
|
+
const voices = parseVoices(await readFile(join(bundleDir, POCKET_VOICES_FILE)));
|
|
42
|
+
const sessionOptions = {
|
|
43
|
+
intraOpNumThreads: Math.max(1, opts.threads),
|
|
44
|
+
interOpNumThreads: 1,
|
|
45
|
+
executionMode: 'sequential',
|
|
46
|
+
};
|
|
47
|
+
const sessions = [];
|
|
48
|
+
try {
|
|
49
|
+
for (const file of Object.values(POCKET_GRAPHS)) {
|
|
50
|
+
sessions.push(await ort.InferenceSession.create(join(bundleDir, file), sessionOptions));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
await Promise.allSettled(sessions.map((s) => s.release()));
|
|
55
|
+
throw err;
|
|
56
|
+
}
|
|
57
|
+
const [textConditioner, flowMain, flowStep, mimi] = sessions;
|
|
58
|
+
const framesPerDecode = Math.max(1, opts.framesPerDecode ?? DEFAULT_FRAMES_PER_DECODE);
|
|
59
|
+
return new Model(ort, bundle, tokenizer, voices, { textConditioner, flowMain, flowStep, mimi }, framesPerDecode);
|
|
60
|
+
}
|
|
61
|
+
class Model {
|
|
62
|
+
ort;
|
|
63
|
+
bundle;
|
|
64
|
+
tokenizer;
|
|
65
|
+
voices;
|
|
66
|
+
s;
|
|
67
|
+
framesPerDecode;
|
|
68
|
+
sampleRate;
|
|
69
|
+
// The padded flow state of the last voice used (~50 MB each, so only one is kept).
|
|
70
|
+
voiceFeeds = null;
|
|
71
|
+
mimiInitial;
|
|
72
|
+
closed = false;
|
|
73
|
+
constructor(ort, bundle, tokenizer, voices, s, framesPerDecode) {
|
|
74
|
+
this.ort = ort;
|
|
75
|
+
this.bundle = bundle;
|
|
76
|
+
this.tokenizer = tokenizer;
|
|
77
|
+
this.voices = voices;
|
|
78
|
+
this.s = s;
|
|
79
|
+
this.framesPerDecode = framesPerDecode;
|
|
80
|
+
this.sampleRate = bundle.sample_rate;
|
|
81
|
+
this.mimiInitial = Object.fromEntries(bundle.mimi_state_manifest.map((e) => [e.input_name, this.filled(e)]));
|
|
82
|
+
}
|
|
83
|
+
async *synthesize(text, voice, signal) {
|
|
84
|
+
if (this.closed)
|
|
85
|
+
throw new Error('Pocket model is closed');
|
|
86
|
+
const voiceState = this.voiceState(voice);
|
|
87
|
+
for (const chunk of prepareChunks(text, this.tokenizer, this.bundle)) {
|
|
88
|
+
if (signal.aborted)
|
|
89
|
+
return;
|
|
90
|
+
const framesAfterEos = (this.bundle.model_recommended_frames_after_eos ?? chunk.framesAfterEos) + EXTRA_FRAMES_AFTER_EOS;
|
|
91
|
+
for await (const frame of this.chunk(chunk.tokenIds, voiceState, framesAfterEos, signal)) {
|
|
92
|
+
yield frame;
|
|
93
|
+
if (signal.aborted)
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async close() {
|
|
99
|
+
if (this.closed)
|
|
100
|
+
return;
|
|
101
|
+
this.closed = true;
|
|
102
|
+
await Promise.allSettled(Object.values(this.s).map((s) => s.release()));
|
|
103
|
+
}
|
|
104
|
+
// One chunk, from the voice's own state (upstream copy_state=True). ORT never writes
|
|
105
|
+
// into its inputs, so the cached voice tensors are reused as is.
|
|
106
|
+
async *chunk(ids, voiceState, framesAfterEos, signal) {
|
|
107
|
+
const { ort, bundle } = this;
|
|
108
|
+
const ldim = bundle.latent_dim;
|
|
109
|
+
const tokens = new ort.Tensor('int64', BigInt64Array.from(ids, BigInt), [1, ids.length]);
|
|
110
|
+
const { text_embeddings } = await this.s.textConditioner.run({ token_ids: tokens });
|
|
111
|
+
// Prompt the text into the KV cache; the outputs other than the state are unused.
|
|
112
|
+
let out = await this.s.flowMain.run({
|
|
113
|
+
sequence: new ort.Tensor('float32', new Float32Array(0), [1, 0, ldim]),
|
|
114
|
+
text_embeddings,
|
|
115
|
+
...voiceState,
|
|
116
|
+
});
|
|
117
|
+
let flowState = nextState(out, bundle.flow_lm_state_manifest);
|
|
118
|
+
let mimiState = this.mimiInitial;
|
|
119
|
+
const noText = new ort.Tensor('float32', new Float32Array(0), [1, 0, bundle.conditioning_dim]);
|
|
120
|
+
// NaN means BOS: the graph swaps in its learned BOS latent.
|
|
121
|
+
let sequence = new ort.Tensor('float32', new Float32Array(ldim).fill(NaN), [1, 1, ldim]);
|
|
122
|
+
const maxGen = Math.ceil((ids.length / TOKENS_PER_SECOND + GEN_SECONDS_PADDING) *
|
|
123
|
+
(bundle.sample_rate / bundle.samples_per_frame));
|
|
124
|
+
let eosStep = null;
|
|
125
|
+
const eosThreshold = Math.max(bundle.eos_threshold, CONFIDENT_EOS_LOGIT);
|
|
126
|
+
const pending = [];
|
|
127
|
+
const decode = async () => {
|
|
128
|
+
const latents = new Float32Array(pending.length * ldim);
|
|
129
|
+
pending.forEach((l, i) => latents.set(l, i * ldim));
|
|
130
|
+
const latent = new ort.Tensor('float32', latents, [1, pending.length, ldim]);
|
|
131
|
+
pending.length = 0;
|
|
132
|
+
const decoded = await this.s.mimi.run({ latent, ...mimiState });
|
|
133
|
+
mimiState = nextState(decoded, bundle.mimi_state_manifest);
|
|
134
|
+
return decoded.audio.data;
|
|
135
|
+
};
|
|
136
|
+
for (let step = 0; step < maxGen; step++) {
|
|
137
|
+
if (signal.aborted)
|
|
138
|
+
return;
|
|
139
|
+
out = await this.s.flowMain.run({ sequence, text_embeddings: noText, ...flowState });
|
|
140
|
+
flowState = nextState(out, bundle.flow_lm_state_manifest);
|
|
141
|
+
const eosLogit = out.eos_logit.data;
|
|
142
|
+
const logit = eosLogit[eosLogit.length - 1];
|
|
143
|
+
if (eosStep === null && step >= bundle.min_frames_before_eos && logit > eosThreshold)
|
|
144
|
+
eosStep = step;
|
|
145
|
+
// This step's latent is not emitted.
|
|
146
|
+
if (eosStep !== null && step >= eosStep + framesAfterEos)
|
|
147
|
+
break;
|
|
148
|
+
const latent = await this.sampleLatent(out.conditioning);
|
|
149
|
+
sequence = new ort.Tensor('float32', latent, [1, 1, ldim]);
|
|
150
|
+
pending.push(latent);
|
|
151
|
+
if (pending.length >= this.framesPerDecode)
|
|
152
|
+
yield await decode();
|
|
153
|
+
}
|
|
154
|
+
if (pending.length > 0 && !signal.aborted)
|
|
155
|
+
yield await decode();
|
|
156
|
+
}
|
|
157
|
+
// lsd_decode over the flow net, starting from gaussian noise (std sqrt(temperature)).
|
|
158
|
+
async sampleLatent(conditioning) {
|
|
159
|
+
const { ort, bundle } = this;
|
|
160
|
+
const dim = bundle.conditioning_dim;
|
|
161
|
+
const all = conditioning.data;
|
|
162
|
+
// upstream keeps the last position only.
|
|
163
|
+
const c = new ort.Tensor('float32', all.subarray(all.length - dim), [1, dim]);
|
|
164
|
+
const x = gaussian(bundle.latent_dim, Math.sqrt(bundle.temperature), bundle.noise_clamp);
|
|
165
|
+
const steps = bundle.sampler_decode_steps;
|
|
166
|
+
for (let i = 0; i < steps; i++) {
|
|
167
|
+
const { flow_dir } = await this.s.flowStep.run({
|
|
168
|
+
c,
|
|
169
|
+
s: new ort.Tensor('float32', Float32Array.of(i / steps), [1, 1]),
|
|
170
|
+
t: new ort.Tensor('float32', Float32Array.of((i + 1) / steps), [1, 1]),
|
|
171
|
+
x: new ort.Tensor('float32', x.slice(), [1, bundle.latent_dim]),
|
|
172
|
+
});
|
|
173
|
+
const dir = flow_dir.data;
|
|
174
|
+
for (let k = 0; k < x.length; k++)
|
|
175
|
+
x[k] += dir[k] / steps;
|
|
176
|
+
}
|
|
177
|
+
return x;
|
|
178
|
+
}
|
|
179
|
+
voiceState(voice) {
|
|
180
|
+
if (this.voiceFeeds?.voice === voice)
|
|
181
|
+
return this.voiceFeeds.feeds;
|
|
182
|
+
const tensors = this.voices.get(voice);
|
|
183
|
+
if (!tensors)
|
|
184
|
+
throw new Error(`unknown Pocket voice "${voice}"`);
|
|
185
|
+
const feeds = {};
|
|
186
|
+
for (const e of this.bundle.flow_lm_state_manifest) {
|
|
187
|
+
const t = tensors.get(`${e.module}/${e.key}`);
|
|
188
|
+
feeds[e.input_name] = t
|
|
189
|
+
? new this.ort.Tensor(e.dtype, padInto(t, e.shape), e.shape)
|
|
190
|
+
: this.filled(e);
|
|
191
|
+
}
|
|
192
|
+
this.voiceFeeds = { voice, feeds };
|
|
193
|
+
return feeds;
|
|
194
|
+
}
|
|
195
|
+
filled(e) {
|
|
196
|
+
const n = e.shape.reduce((a, b) => a * b, 1);
|
|
197
|
+
const one = e.fill === 'ones';
|
|
198
|
+
const data = e.dtype === 'float32'
|
|
199
|
+
? new Float32Array(n).fill(one ? 1 : 0)
|
|
200
|
+
: e.dtype === 'int64'
|
|
201
|
+
? new BigInt64Array(n).fill(one ? 1n : 0n)
|
|
202
|
+
: new Uint8Array(n).fill(one ? 1 : 0);
|
|
203
|
+
return new this.ort.Tensor(e.dtype, data, e.shape);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function nextState(out, manifest) {
|
|
207
|
+
const feeds = {};
|
|
208
|
+
for (const e of manifest) {
|
|
209
|
+
const t = out[e.output_name];
|
|
210
|
+
if (!t)
|
|
211
|
+
throw new Error(`graph output ${e.output_name} is missing`);
|
|
212
|
+
feeds[e.input_name] = t;
|
|
213
|
+
}
|
|
214
|
+
return feeds;
|
|
215
|
+
}
|
|
216
|
+
// Box-Muller; a clamp resamples out-of-range draws (torch trunc_normal_ semantics).
|
|
217
|
+
function gaussian(n, std, clamp) {
|
|
218
|
+
const out = new Float32Array(n);
|
|
219
|
+
for (let i = 0; i < n; i++) {
|
|
220
|
+
let v;
|
|
221
|
+
do {
|
|
222
|
+
const u = 1 - Math.random();
|
|
223
|
+
v = std * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * Math.random());
|
|
224
|
+
} while (clamp !== null && Math.abs(v) > clamp);
|
|
225
|
+
out[i] = v;
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { PronunciationEntry } from 'caretaker-types';
|
|
2
|
+
import { ORT_TARBALLS, POCKET_LANGUAGES, type PocketLanguage } from './catalog.js';
|
|
3
|
+
export type BuiltinVoiceStatus = {
|
|
4
|
+
runtime: {
|
|
5
|
+
installed: boolean;
|
|
6
|
+
version: string;
|
|
7
|
+
loadError?: string;
|
|
8
|
+
};
|
|
9
|
+
languages: Array<{
|
|
10
|
+
id: string;
|
|
11
|
+
code: string;
|
|
12
|
+
nativeVoice: string;
|
|
13
|
+
installed: boolean;
|
|
14
|
+
bytes: number;
|
|
15
|
+
}>;
|
|
16
|
+
voices: string[];
|
|
17
|
+
defaults: Record<string, PronunciationEntry[]>;
|
|
18
|
+
};
|
|
19
|
+
export type BuiltinInstallProgress = {
|
|
20
|
+
step: 'runtime' | 'bundle';
|
|
21
|
+
file: string;
|
|
22
|
+
received: number;
|
|
23
|
+
total: number;
|
|
24
|
+
} | {
|
|
25
|
+
step: 'done';
|
|
26
|
+
status: BuiltinVoiceStatus;
|
|
27
|
+
} | {
|
|
28
|
+
step: 'error';
|
|
29
|
+
message: string;
|
|
30
|
+
};
|
|
31
|
+
type Catalog = {
|
|
32
|
+
languages: typeof POCKET_LANGUAGES;
|
|
33
|
+
tarballs: typeof ORT_TARBALLS;
|
|
34
|
+
ortVersion: string;
|
|
35
|
+
revision: string;
|
|
36
|
+
baseUrl: string;
|
|
37
|
+
};
|
|
38
|
+
export declare function __setCatalogForTest(c: Partial<Catalog>): void;
|
|
39
|
+
export declare function __setFetch(f: typeof fetch): void;
|
|
40
|
+
export declare function __resetFetch(): void;
|
|
41
|
+
export declare function runtimeDir(): string;
|
|
42
|
+
/** Absolute path of onnxruntime-node's entry file, for `createRequire(...)`. */
|
|
43
|
+
export declare function runtimeEntry(): string;
|
|
44
|
+
export declare function bundleDir(lang: PocketLanguage): string;
|
|
45
|
+
export declare function installBuiltinVoice(lang: PocketLanguage): AsyncGenerator<BuiltinInstallProgress>;
|
|
46
|
+
/** Removes the language's bundle(s); removes the runtime too once no bundle remains,
|
|
47
|
+
* unless `keepRuntime` (the native binding is loaded in this process: Windows refuses
|
|
48
|
+
* to delete it, and a half-deleted runtime would break reinstalling). */
|
|
49
|
+
export declare function deleteBuiltinVoice(lang: PocketLanguage, opts?: {
|
|
50
|
+
keepRuntime?: boolean;
|
|
51
|
+
}): Promise<void>;
|
|
52
|
+
export declare function builtinVoiceStatus(): Promise<BuiltinVoiceStatus>;
|
|
53
|
+
export {};
|
|
54
|
+
//# sourceMappingURL=install.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"install.d.ts","sourceRoot":"","sources":["../../../src/voice/pocket/install.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAG1D,OAAO,EACL,YAAY,EAGZ,gBAAgB,EAGhB,KAAK,cAAc,EACpB,MAAM,cAAc,CAAC;AAGtB,MAAM,MAAM,kBAAkB,GAAG;IAC/B,OAAO,EAAE;QAAE,SAAS,EAAE,OAAO,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACrE,SAAS,EAAE,KAAK,CAAC;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACvG,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,kBAAkB,EAAE,CAAC,CAAC;CAChD,CAAC;AACF,MAAM,MAAM,sBAAsB,GAC9B;IAAE,IAAI,EAAE,SAAS,GAAG,QAAQ,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC7E;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,kBAAkB,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvC,KAAK,OAAO,GAAG;IACb,SAAS,EAAE,OAAO,gBAAgB,CAAC;IACnC,QAAQ,EAAE,OAAO,YAAY,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AASF,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAE7D;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,OAAO,KAAK,GAAG,IAAI,CAEhD;AACD,wBAAgB,YAAY,IAAI,IAAI,CAGnC;AAGD,wBAAgB,UAAU,IAAI,MAAM,CAEnC;AACD,gFAAgF;AAChF,wBAAgB,YAAY,IAAI,MAAM,CAErC;AACD,wBAAgB,SAAS,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,CAEtD;AAgMD,wBAAuB,mBAAmB,CAAC,IAAI,EAAE,cAAc,GAAG,cAAc,CAAC,sBAAsB,CAAC,CASvG;AAMD;;0EAE0E;AAC1E,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,cAAc,EAAE,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAGlH;AAED,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAmBtE"}
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// On-demand installer for the built-in voice: the ONNX runtime (npm registry tarballs,
|
|
2
|
+
// never a package dependency, never `postinstall`) and the per-language Pocket bundles
|
|
3
|
+
// (Hugging Face, pinned revision). Every install goes through a tmp sibling dir + rename
|
|
4
|
+
// and leaves nothing behind on failure.
|
|
5
|
+
//
|
|
6
|
+
// Runtime layout (what `runtimeEntry()` points into):
|
|
7
|
+
// <runtimeDir>/node_modules/onnxruntime-node/{package.json, dist/, bin/napi-v6/<platform>/<arch>/}
|
|
8
|
+
// <runtimeDir>/node_modules/onnxruntime-common/...
|
|
9
|
+
// so `require('onnxruntime-common')` from the binding resolves by plain node resolution.
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { createReadStream, createWriteStream, existsSync } from 'node:fs';
|
|
12
|
+
import { mkdir, rename, rm } from 'node:fs/promises';
|
|
13
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
14
|
+
import { createGunzip } from 'node:zlib';
|
|
15
|
+
import { dataDir } from '../../store/json.js';
|
|
16
|
+
import { DEFAULT_PRONUNCIATION } from '../pronunciation.js';
|
|
17
|
+
import { ORT_TARBALLS, ORT_VERSION, POCKET_BASE_URL, POCKET_LANGUAGES, POCKET_REVISION, POCKET_VOICES, } from './catalog.js';
|
|
18
|
+
const REAL_CATALOG = {
|
|
19
|
+
languages: POCKET_LANGUAGES,
|
|
20
|
+
tarballs: ORT_TARBALLS,
|
|
21
|
+
ortVersion: ORT_VERSION,
|
|
22
|
+
revision: POCKET_REVISION,
|
|
23
|
+
baseUrl: POCKET_BASE_URL,
|
|
24
|
+
};
|
|
25
|
+
let cat = REAL_CATALOG;
|
|
26
|
+
export function __setCatalogForTest(c) {
|
|
27
|
+
cat = { ...REAL_CATALOG, ...c };
|
|
28
|
+
}
|
|
29
|
+
let doFetch = (i, init) => fetch(i, init);
|
|
30
|
+
export function __setFetch(f) {
|
|
31
|
+
doFetch = f;
|
|
32
|
+
}
|
|
33
|
+
export function __resetFetch() {
|
|
34
|
+
doFetch = (i, init) => fetch(i, init);
|
|
35
|
+
cat = REAL_CATALOG;
|
|
36
|
+
}
|
|
37
|
+
const runtimeRoot = () => join(dataDir(), 'voice', 'runtime', 'onnxruntime');
|
|
38
|
+
export function runtimeDir() {
|
|
39
|
+
return join(runtimeRoot(), cat.ortVersion);
|
|
40
|
+
}
|
|
41
|
+
/** Absolute path of onnxruntime-node's entry file, for `createRequire(...)`. */
|
|
42
|
+
export function runtimeEntry() {
|
|
43
|
+
return join(runtimeDir(), 'node_modules', 'onnxruntime-node', 'dist', 'index.js');
|
|
44
|
+
}
|
|
45
|
+
export function bundleDir(lang) {
|
|
46
|
+
return join(dataDir(), 'voice', 'pocket', cat.languages[lang].dir, cat.revision);
|
|
47
|
+
}
|
|
48
|
+
const tmpName = (p) => `${p}.tmp-${process.pid}`;
|
|
49
|
+
/** Streams `url` to `dest`, verifying the digest. `expected` is a sha256 hex string or an
|
|
50
|
+
* npm `sha512-<base64>` integrity string. Removes `dest` and throws on any failure. */
|
|
51
|
+
async function* download(url, dest, expected, label, knownBytes) {
|
|
52
|
+
const [algo, want, enc] = expected.startsWith('sha512-')
|
|
53
|
+
? ['sha512', expected.slice(7), 'base64']
|
|
54
|
+
: ['sha256', expected, 'hex'];
|
|
55
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
56
|
+
const out = createWriteStream(dest);
|
|
57
|
+
const failed = new Promise((_, rej) => out.once('error', rej));
|
|
58
|
+
failed.catch(() => { });
|
|
59
|
+
try {
|
|
60
|
+
const res = await doFetch(url);
|
|
61
|
+
if (!res.ok || !res.body)
|
|
62
|
+
throw new Error(`HTTP ${res.status} for ${url}`);
|
|
63
|
+
const total = Number(res.headers.get('content-length')) || knownBytes;
|
|
64
|
+
const hash = createHash(algo);
|
|
65
|
+
let received = 0;
|
|
66
|
+
let lastYield = 0;
|
|
67
|
+
yield { received, total };
|
|
68
|
+
const reader = res.body.getReader();
|
|
69
|
+
for (;;) {
|
|
70
|
+
const { done, value } = await reader.read();
|
|
71
|
+
if (done)
|
|
72
|
+
break;
|
|
73
|
+
hash.update(value);
|
|
74
|
+
received += value.length;
|
|
75
|
+
if (!out.write(value))
|
|
76
|
+
await Promise.race([new Promise((r) => out.once('drain', () => r())), failed]);
|
|
77
|
+
if (received - lastYield >= 1 << 20) {
|
|
78
|
+
lastYield = received;
|
|
79
|
+
yield { received, total };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
await Promise.race([new Promise((r) => out.end(r)), failed]);
|
|
83
|
+
if (hash.digest(enc) !== want)
|
|
84
|
+
throw new Error(`Integrity check failed for ${label}`);
|
|
85
|
+
yield { received, total: received };
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
out.destroy();
|
|
89
|
+
await rm(dest, { force: true });
|
|
90
|
+
throw e;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// ---------------------------------------------------------------- tar
|
|
94
|
+
/** Minimal ustar reader: extracts the regular files `accept` wants (names already stripped
|
|
95
|
+
* of the leading `package/`) under `dest`. Applies pax `path` and GNU long-name entries. */
|
|
96
|
+
async function untar(src, dest, accept) {
|
|
97
|
+
const it = src[Symbol.asyncIterator]();
|
|
98
|
+
let buf = Buffer.alloc(0);
|
|
99
|
+
const fill = async (n) => {
|
|
100
|
+
while (buf.length < n) {
|
|
101
|
+
const r = await it.next();
|
|
102
|
+
if (r.done)
|
|
103
|
+
return false;
|
|
104
|
+
buf = Buffer.concat([buf, r.value]);
|
|
105
|
+
}
|
|
106
|
+
return true;
|
|
107
|
+
};
|
|
108
|
+
const str = (b, o, l) => {
|
|
109
|
+
const s = b.subarray(o, o + l);
|
|
110
|
+
const z = s.indexOf(0);
|
|
111
|
+
return s.subarray(0, z < 0 ? l : z).toString('utf8');
|
|
112
|
+
};
|
|
113
|
+
const skip = async (n) => {
|
|
114
|
+
while (n > 0) {
|
|
115
|
+
if (!(await fill(1)))
|
|
116
|
+
throw new Error('Truncated tar archive');
|
|
117
|
+
const t = Math.min(n, buf.length);
|
|
118
|
+
buf = buf.subarray(t);
|
|
119
|
+
n -= t;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const root = resolve(dest) + sep;
|
|
123
|
+
let longName = null;
|
|
124
|
+
for (;;) {
|
|
125
|
+
if (!(await fill(512)))
|
|
126
|
+
return;
|
|
127
|
+
const h = buf.subarray(0, 512);
|
|
128
|
+
buf = buf.subarray(512);
|
|
129
|
+
if (h.every((x) => x === 0))
|
|
130
|
+
return;
|
|
131
|
+
const size = parseInt(str(h, 124, 12).trim() || '0', 8);
|
|
132
|
+
const type = String.fromCharCode(h[156] || 48);
|
|
133
|
+
const pad = (512 - (size % 512)) % 512;
|
|
134
|
+
if (type === 'x' || type === 'L') {
|
|
135
|
+
if (!(await fill(size)))
|
|
136
|
+
throw new Error('Truncated tar archive');
|
|
137
|
+
const body = buf.subarray(0, size).toString('utf8');
|
|
138
|
+
buf = buf.subarray(size);
|
|
139
|
+
await skip(pad);
|
|
140
|
+
if (type === 'L')
|
|
141
|
+
longName = body.replace(/\0.*$/s, '');
|
|
142
|
+
else {
|
|
143
|
+
const m = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(body);
|
|
144
|
+
if (m)
|
|
145
|
+
longName = m[1];
|
|
146
|
+
}
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
let name = longName ?? [str(h, 345, 155), str(h, 0, 100)].filter(Boolean).join('/');
|
|
150
|
+
longName = null;
|
|
151
|
+
name = name.replace(/^package\//, '');
|
|
152
|
+
const wanted = (type === '0' || type === '7') && accept(name);
|
|
153
|
+
if (!wanted) {
|
|
154
|
+
await skip(size + pad);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const target = resolve(dest, name);
|
|
158
|
+
if (!target.startsWith(root))
|
|
159
|
+
throw new Error(`Unsafe path in archive: ${name}`);
|
|
160
|
+
await mkdir(dirname(target), { recursive: true });
|
|
161
|
+
const out = createWriteStream(target);
|
|
162
|
+
const failed = new Promise((_, rej) => out.once('error', rej));
|
|
163
|
+
failed.catch(() => { });
|
|
164
|
+
let left = size;
|
|
165
|
+
while (left > 0) {
|
|
166
|
+
if (!(await fill(1)))
|
|
167
|
+
throw new Error('Truncated tar archive');
|
|
168
|
+
const t = Math.min(left, buf.length);
|
|
169
|
+
const chunk = buf.subarray(0, t);
|
|
170
|
+
buf = buf.subarray(t);
|
|
171
|
+
left -= t;
|
|
172
|
+
if (!out.write(chunk))
|
|
173
|
+
await Promise.race([new Promise((r) => out.once('drain', () => r())), failed]);
|
|
174
|
+
}
|
|
175
|
+
await Promise.race([new Promise((r) => out.end(r)), failed]);
|
|
176
|
+
await skip(pad);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function extractTgz(file, dest, accept) {
|
|
180
|
+
const gz = createReadStream(file).pipe(createGunzip());
|
|
181
|
+
await untar(gz, dest, accept);
|
|
182
|
+
}
|
|
183
|
+
// ---------------------------------------------------------------- install
|
|
184
|
+
async function* installRuntime() {
|
|
185
|
+
if (existsSync(runtimeEntry()))
|
|
186
|
+
return;
|
|
187
|
+
const dir = runtimeDir();
|
|
188
|
+
const tmp = tmpName(dir);
|
|
189
|
+
await rm(tmp, { recursive: true, force: true });
|
|
190
|
+
try {
|
|
191
|
+
const bin = `bin/napi-v6/${process.platform}/${process.arch}/`;
|
|
192
|
+
const parts = [
|
|
193
|
+
{ key: 'node', pkg: 'onnxruntime-node', accept: (r) => r === 'package.json' || r.startsWith('dist/') || r.startsWith(bin) },
|
|
194
|
+
{ key: 'common', pkg: 'onnxruntime-common', accept: (r) => r === 'package.json' || r.startsWith('dist/') },
|
|
195
|
+
];
|
|
196
|
+
for (const p of parts) {
|
|
197
|
+
const t = cat.tarballs[p.key];
|
|
198
|
+
const tgz = join(tmp, `${p.pkg}.tgz`);
|
|
199
|
+
for await (const g of download(t.url, tgz, t.integrity, p.pkg, 0)) {
|
|
200
|
+
yield { step: 'runtime', file: p.pkg, ...g };
|
|
201
|
+
}
|
|
202
|
+
await extractTgz(tgz, join(tmp, 'node_modules', p.pkg), p.accept);
|
|
203
|
+
await rm(tgz, { force: true });
|
|
204
|
+
}
|
|
205
|
+
await mkdir(dirname(dir), { recursive: true });
|
|
206
|
+
await rm(dir, { recursive: true, force: true });
|
|
207
|
+
await rename(tmp, dir);
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
await rm(tmp, { recursive: true, force: true });
|
|
211
|
+
throw e;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
async function* installBundle(lang) {
|
|
215
|
+
const dir = bundleDir(lang);
|
|
216
|
+
if (existsSync(dir))
|
|
217
|
+
return;
|
|
218
|
+
const spec = cat.languages[lang];
|
|
219
|
+
const tmp = tmpName(dir);
|
|
220
|
+
await rm(tmp, { recursive: true, force: true });
|
|
221
|
+
try {
|
|
222
|
+
for (const f of spec.files) {
|
|
223
|
+
const url = `${cat.baseUrl}/${cat.revision}/${spec.dir}/${f.name}`;
|
|
224
|
+
for await (const g of download(url, join(tmp, f.name), f.sha256, f.name, f.bytes)) {
|
|
225
|
+
yield { step: 'bundle', file: f.name, ...g };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
await rename(tmp, dir);
|
|
229
|
+
}
|
|
230
|
+
catch (e) {
|
|
231
|
+
await rm(tmp, { recursive: true, force: true });
|
|
232
|
+
throw e;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
export async function* installBuiltinVoice(lang) {
|
|
236
|
+
try {
|
|
237
|
+
if (!cat.languages[lang])
|
|
238
|
+
throw new Error(`Unknown language: ${lang}`);
|
|
239
|
+
yield* installRuntime();
|
|
240
|
+
yield* installBundle(lang);
|
|
241
|
+
yield { step: 'done', status: await builtinVoiceStatus() };
|
|
242
|
+
}
|
|
243
|
+
catch (e) {
|
|
244
|
+
yield { step: 'error', message: e instanceof Error ? e.message : String(e) };
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async function anyBundleInstalled() {
|
|
248
|
+
return Object.keys(cat.languages).some((l) => existsSync(bundleDir(l)));
|
|
249
|
+
}
|
|
250
|
+
/** Removes the language's bundle(s); removes the runtime too once no bundle remains,
|
|
251
|
+
* unless `keepRuntime` (the native binding is loaded in this process: Windows refuses
|
|
252
|
+
* to delete it, and a half-deleted runtime would break reinstalling). */
|
|
253
|
+
export async function deleteBuiltinVoice(lang, opts = {}) {
|
|
254
|
+
await rm(dirname(bundleDir(lang)), { recursive: true, force: true });
|
|
255
|
+
if (!opts.keepRuntime && !(await anyBundleInstalled()))
|
|
256
|
+
await rm(runtimeRoot(), { recursive: true, force: true });
|
|
257
|
+
}
|
|
258
|
+
export async function builtinVoiceStatus() {
|
|
259
|
+
const defaults = {};
|
|
260
|
+
for (const [code, entries] of Object.entries(DEFAULT_PRONUNCIATION)) {
|
|
261
|
+
defaults[code] = entries.map((e) => ({ ...e }));
|
|
262
|
+
}
|
|
263
|
+
return {
|
|
264
|
+
runtime: { installed: existsSync(runtimeEntry()), version: cat.ortVersion },
|
|
265
|
+
languages: Object.entries(cat.languages).map(([id, s]) => ({
|
|
266
|
+
id,
|
|
267
|
+
code: s.code,
|
|
268
|
+
nativeVoice: s.nativeVoice,
|
|
269
|
+
installed: existsSync(bundleDir(id)),
|
|
270
|
+
bytes: s.files.reduce((n, f) => n + f.bytes, 0),
|
|
271
|
+
})),
|
|
272
|
+
voices: [...POCKET_VOICES],
|
|
273
|
+
defaults,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
type TokenizerJson = {
|
|
2
|
+
model: {
|
|
3
|
+
type: string;
|
|
4
|
+
unk_id: number;
|
|
5
|
+
byte_fallback?: boolean;
|
|
6
|
+
vocab: [string, number][];
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export declare class UnigramTokenizer {
|
|
10
|
+
private readonly pieces;
|
|
11
|
+
private readonly scores;
|
|
12
|
+
private readonly byteIds;
|
|
13
|
+
private readonly unkId;
|
|
14
|
+
private readonly unkScore;
|
|
15
|
+
private readonly maxPieceLen;
|
|
16
|
+
private readonly vocab;
|
|
17
|
+
constructor(json: TokenizerJson);
|
|
18
|
+
encode(text: string): number[];
|
|
19
|
+
private encodeWord;
|
|
20
|
+
decode(ids: readonly number[]): string;
|
|
21
|
+
}
|
|
22
|
+
export type TextPrepConfig = {
|
|
23
|
+
replace_characters?: Record<string, string> | null;
|
|
24
|
+
remove_semicolons: boolean;
|
|
25
|
+
append_terminal_punctuation: boolean;
|
|
26
|
+
capitalize_first_letter: boolean;
|
|
27
|
+
pad_with_spaces_for_short_inputs: boolean;
|
|
28
|
+
max_token_per_chunk: number;
|
|
29
|
+
};
|
|
30
|
+
export declare function prepareTextPrompt(input: string, cfg: TextPrepConfig): {
|
|
31
|
+
text: string;
|
|
32
|
+
framesAfterEosGuess: number;
|
|
33
|
+
};
|
|
34
|
+
export declare function splitIntoChunks(text: string, tok: UnigramTokenizer, cfg: TextPrepConfig): string[];
|
|
35
|
+
export type PreparedChunk = {
|
|
36
|
+
text: string;
|
|
37
|
+
tokenIds: number[];
|
|
38
|
+
framesAfterEos: number;
|
|
39
|
+
};
|
|
40
|
+
export declare function prepareChunks(text: string, tok: UnigramTokenizer, cfg: TextPrepConfig): PreparedChunk[];
|
|
41
|
+
export {};
|
|
42
|
+
//# sourceMappingURL=tokenizer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokenizer.d.ts","sourceRoot":"","sources":["../../../src/voice/pocket/tokenizer.ts"],"names":[],"mappings":"AASA,KAAK,aAAa,GAAG;IACnB,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,aAAa,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAA;KAAE,CAAC;CAC7F,CAAC;AAEF,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA6B;IACpD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAW;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAW;gBAErB,IAAI,EAAE,aAAa;IAuB/B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE;IAY9B,OAAO,CAAC,UAAU;IAqDlB,MAAM,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM;CAyBvC;AAWD,MAAM,MAAM,cAAc,GAAG;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC;IACnD,iBAAiB,EAAE,OAAO,CAAC;IAC3B,2BAA2B,EAAE,OAAO,CAAC;IACrC,uBAAuB,EAAE,OAAO,CAAC;IACjC,gCAAgC,EAAE,OAAO,CAAC;IAC1C,mBAAmB,EAAE,MAAM,CAAC;CAC7B,CAAC;AAkBF,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,cAAc,GAClB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,mBAAmB,EAAE,MAAM,CAAA;CAAE,CAmB/C;AAsDD,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,gBAAgB,EACrB,GAAG,EAAE,cAAc,GAClB,MAAM,EAAE,CAqCV;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAC;IAAC,cAAc,EAAE,MAAM,CAAA;CAAE,CAAC;AAIzF,wBAAgB,aAAa,CAC3B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,gBAAgB,EACrB,GAAG,EAAE,cAAc,GAClB,aAAa,EAAE,CAKjB"}
|