@chatpanel/gateway 0.6.110 → 0.8.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 +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +2 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/policy.js +2 -0
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2296
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/pocket-tts-engine.js
CHANGED
|
@@ -1,520 +1 @@
|
|
|
1
|
-
// Kyutai Pocket TTS — the engine that can actually speak in YOUR voice.
|
|
2
|
-
//
|
|
3
|
-
// Kokoro's voices are fixed style banks and SpeechT5 borrows a voice print from a
|
|
4
|
-
// space it was not trained on, so neither reproduces a specific person. Pocket TTS
|
|
5
|
-
// is built for it: its Mimi encoder turns a few seconds of audio into a voice
|
|
6
|
-
// conditioning that seeds generation directly, which is why the same sample gives
|
|
7
|
-
// back the same speaker rather than a distant relative of them.
|
|
8
|
-
//
|
|
9
|
-
// Ported from the reference browser implementation in the `KevinAHM/pocket-tts-web`
|
|
10
|
-
// Hugging Face Space (Apache-2.0), adapted from a Web Worker to in-process Node:
|
|
11
|
-
// fetch → fs, postMessage → return values, and the CDN onnxruntime → the one this
|
|
12
|
-
// gateway already ships (parakeet-engine.js's getOrt() pattern, so the same code
|
|
13
|
-
// runs on native ORT and on the binary's WASM build). Model weights are
|
|
14
|
-
// CC-BY-4.0 from `KevinAHM/pocket-tts-onnx`.
|
|
15
|
-
//
|
|
16
|
-
// Five graphs, and the shape of a turn:
|
|
17
|
-
// text_conditioner text tokens → text embeddings
|
|
18
|
-
// mimi_encoder voice sample → voice conditioning (this is the cloning)
|
|
19
|
-
// flow_lm_main autoregressive step → conditioning + an end-of-speech logit
|
|
20
|
-
// flow_lm_flow flow-matching denoise of one latent frame
|
|
21
|
-
// mimi_decoder latent frames → audio
|
|
22
|
-
// flow_lm and mimi are STATEFUL: each call returns the state the next one needs,
|
|
23
|
-
// described by a manifest in bundle.json rather than hardcoded here.
|
|
24
|
-
|
|
25
|
-
import { join } from 'node:path';
|
|
26
|
-
import { existsSync, mkdirSync, readFileSync, statSync, createWriteStream, renameSync } from 'node:fs';
|
|
27
|
-
import { Readable } from 'node:stream';
|
|
28
|
-
import { modelRoot } from './ner-engine.js';
|
|
29
|
-
import { SentencePieceUnigram } from './sentencepiece.js';
|
|
30
|
-
import { getOrt, ortProviders } from './ort.js';
|
|
31
|
-
|
|
32
|
-
export const POCKET_REPO = 'KevinAHM/pocket-tts-onnx';
|
|
33
|
-
// The built-in speakers live in the demo Space, not the weights repo — the weights
|
|
34
|
-
// repo 404s on voices.bin. Same author, same licence, different HF namespace.
|
|
35
|
-
export const POCKET_VOICES_SPACE = 'KevinAHM/pocket-tts-web';
|
|
36
|
-
export const DEFAULT_BUNDLE = 'english_2026-04';
|
|
37
|
-
export const SAMPLE_RATE = 24000;
|
|
38
|
-
|
|
39
|
-
// Generation constants, carried over from the reference implementation.
|
|
40
|
-
const MAX_FRAMES = 500; // hard ceiling per chunk (~40s at 12.5 fps)
|
|
41
|
-
const LSD_STEPS = 1; // flow-matching steps per frame
|
|
42
|
-
const TEMPERATURE = 0.7;
|
|
43
|
-
const EOS_LOGIT_THRESHOLD = -4.0;
|
|
44
|
-
const FIRST_CHUNK_FRAMES = 3; // decode early so audio starts sooner
|
|
45
|
-
const NORMAL_CHUNK_FRAMES = 12;
|
|
46
|
-
// The reference resets both states per text chunk; keeping them would let one
|
|
47
|
-
// sentence's trailing state colour the next one's opening.
|
|
48
|
-
const RESET_STATE_EACH_CHUNK = true;
|
|
49
|
-
|
|
50
|
-
const FILES = (q = '_int8') => [
|
|
51
|
-
'bundle.json', 'tokenizer.model', 'bos_before_voice.npy',
|
|
52
|
-
`text_conditioner${q}.onnx`, `mimi_encoder${q}.onnx`, `mimi_decoder${q}.onnx`,
|
|
53
|
-
`flow_lm_main${q}.onnx`, `flow_lm_flow${q}.onnx`,
|
|
54
|
-
];
|
|
55
|
-
// voices.bin is a separate ~52 MB download for the eight built-in speakers, and it
|
|
56
|
-
// is OPTIONAL: cloning works without it, so a failed or skipped fetch costs the
|
|
57
|
-
// stock voices and nothing else.
|
|
58
|
-
const VOICES_FILE = 'voices.bin';
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
export function bundleDir(bundle = DEFAULT_BUNDLE) {
|
|
62
|
-
return join(modelRoot(), 'pocket-tts', bundle);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export function bundleOnDisk(bundle = DEFAULT_BUNDLE, quant = '_int8') {
|
|
66
|
-
const dir = bundleDir(bundle);
|
|
67
|
-
try {
|
|
68
|
-
return FILES(quant).every((f) => { const p = join(dir, f); return existsSync(p) && statSync(p).size > 0; });
|
|
69
|
-
} catch { return false; }
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async function downloadFile(bundle, file, dir, { onProgress, log } = {}) {
|
|
73
|
-
const url = file === VOICES_FILE
|
|
74
|
-
? `https://huggingface.co/spaces/${POCKET_VOICES_SPACE}/resolve/main/onnx/${bundle}/${file}`
|
|
75
|
-
: `https://huggingface.co/${POCKET_REPO}/resolve/main/onnx/${bundle}/${file}`;
|
|
76
|
-
const res = await fetch(url, { redirect: 'follow' });
|
|
77
|
-
if (!res.ok || !res.body) throw new Error(`fetch ${file} → HTTP ${res.status}`);
|
|
78
|
-
const total = Number(res.headers.get('content-length')) || 0;
|
|
79
|
-
const tmp = join(dir, `${file}.part`);
|
|
80
|
-
const out = createWriteStream(tmp);
|
|
81
|
-
let got = 0, lastPct = -1;
|
|
82
|
-
const src = Readable.fromWeb(res.body);
|
|
83
|
-
src.on('data', (c) => {
|
|
84
|
-
got += c.length;
|
|
85
|
-
if (total) { const pct = Math.round((got / total) * 100); if (pct !== lastPct) { lastPct = pct; onProgress?.({ file, pct }); } }
|
|
86
|
-
});
|
|
87
|
-
await new Promise((resolve, reject) => { src.pipe(out); out.on('finish', resolve); out.on('error', reject); src.on('error', reject); });
|
|
88
|
-
// .part then rename, so an interrupted fetch never reads as installed.
|
|
89
|
-
renameSync(tmp, join(dir, file));
|
|
90
|
-
log?.(`[pocket-tts] fetched ${file}`);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export async function ensureBundle(bundle = DEFAULT_BUNDLE, quant = '_int8', { onProgress, log } = {}) {
|
|
94
|
-
const dir = bundleDir(bundle);
|
|
95
|
-
mkdirSync(dir, { recursive: true });
|
|
96
|
-
for (const file of FILES(quant)) {
|
|
97
|
-
const dest = join(dir, file);
|
|
98
|
-
if (existsSync(dest) && statSync(dest).size > 0) continue;
|
|
99
|
-
log?.(`[pocket-tts] downloading ${file}…`);
|
|
100
|
-
await downloadFile(bundle, file, dir, { onProgress, log });
|
|
101
|
-
}
|
|
102
|
-
return dir;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** Fetch the built-in speakers. Optional — failure leaves cloning fully working. */
|
|
106
|
-
export async function ensureVoicesBin(bundle = DEFAULT_BUNDLE, { onProgress, log } = {}) {
|
|
107
|
-
const dir = bundleDir(bundle);
|
|
108
|
-
const dest = join(dir, VOICES_FILE);
|
|
109
|
-
if (existsSync(dest) && statSync(dest).size > 1024) return dest;
|
|
110
|
-
mkdirSync(dir, { recursive: true });
|
|
111
|
-
log?.(`[pocket-tts] downloading ${VOICES_FILE} (built-in voices, ~52 MB)…`);
|
|
112
|
-
await downloadFile(bundle, VOICES_FILE, dir, { onProgress, log });
|
|
113
|
-
return dest;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export function voicesBinOnDisk(bundle = DEFAULT_BUNDLE) {
|
|
117
|
-
try { const p = join(bundleDir(bundle), VOICES_FILE); return existsSync(p) && statSync(p).size > 1024; } catch { return false; }
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// ── .npy (float32) ──────────────────────────────────────────────────────────────
|
|
121
|
-
export function parseNpyFloat32(buf) {
|
|
122
|
-
const magic = [0x93, 0x4e, 0x55, 0x4d, 0x50, 0x59];
|
|
123
|
-
for (let i = 0; i < magic.length; i++) if (buf[i] !== magic[i]) throw new Error('not an NPY file');
|
|
124
|
-
const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
125
|
-
const major = view.getUint8(6);
|
|
126
|
-
const headerLen = major === 1 ? view.getUint16(8, true) : view.getUint32(8, true);
|
|
127
|
-
const headerOffset = major === 1 ? 10 : 12;
|
|
128
|
-
const header = new TextDecoder().decode(buf.subarray(headerOffset, headerOffset + headerLen));
|
|
129
|
-
const m = /\(\s*([0-9,\s]*)\)/.exec(header);
|
|
130
|
-
if (!m) throw new Error('could not parse NPY shape');
|
|
131
|
-
const shape = m[1].split(',').map((x) => x.trim()).filter(Boolean).map((x) => parseInt(x, 10));
|
|
132
|
-
const start = headerOffset + headerLen;
|
|
133
|
-
const data = new Float32Array((buf.byteLength - start) / 4);
|
|
134
|
-
for (let i = 0; i < data.length; i++) data[i] = view.getFloat32(start + i * 4, true);
|
|
135
|
-
return { data, shape };
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// ── state manifests ─────────────────────────────────────────────────────────────
|
|
139
|
-
// Both stateful graphs describe their own state in bundle.json: which inputs to
|
|
140
|
-
// seed, with what shape and fill, and which outputs feed them next turn. Reading
|
|
141
|
-
// it beats hardcoding 18 + 56 tensor names that differ per language bundle.
|
|
142
|
-
function filledArray(shape, dtype, fill) {
|
|
143
|
-
const size = shape.reduce((a, b) => a * b, 1);
|
|
144
|
-
if (dtype === 'int64') return new BigInt64Array(size);
|
|
145
|
-
if (dtype === 'bool') return new Uint8Array(size);
|
|
146
|
-
const d = new Float32Array(size);
|
|
147
|
-
if (fill === 'nan') d.fill(NaN);
|
|
148
|
-
else if (fill === 'ones') d.fill(1);
|
|
149
|
-
return d;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
function initState(ort, manifest) {
|
|
153
|
-
const state = {};
|
|
154
|
-
for (const e of manifest) state[e.input_name] = new ort.Tensor(e.dtype, filledArray(e.shape, e.dtype, e.fill), e.shape);
|
|
155
|
-
return state;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
function advanceState(state, result, manifest) {
|
|
159
|
-
for (const e of manifest) state[e.input_name] = result[e.output_name];
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
// ── built-in speakers ───────────────────────────────────────────────────────────
|
|
164
|
-
// voices.bin (PTVB1) is a flat table of per-voice tensor STATES — the model's
|
|
165
|
-
// internal state after it has been conditioned on that speaker — rather than
|
|
166
|
-
// audio or embeddings. Loading one is therefore not "encode a voice" but "restore
|
|
167
|
-
// the state a voice produces", which is why it takes a different path from cloning.
|
|
168
|
-
export function parseVoicesBin(buf) {
|
|
169
|
-
const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
170
|
-
const view = new DataView(ab);
|
|
171
|
-
let off = 0;
|
|
172
|
-
const magic = new TextDecoder().decode(new Uint8Array(ab, 0, 5));
|
|
173
|
-
off += 5;
|
|
174
|
-
if (magic !== 'PTVB1') throw new Error('not a voices.bin (bad header)');
|
|
175
|
-
const voices = {};
|
|
176
|
-
const count = view.getUint32(off, true); off += 4;
|
|
177
|
-
for (let v = 0; v < count; v++) {
|
|
178
|
-
const nameLen = view.getUint16(off, true); off += 2;
|
|
179
|
-
const name = new TextDecoder().decode(new Uint8Array(ab, off, nameLen)); off += nameLen;
|
|
180
|
-
const tensorCount = view.getUint16(off, true); off += 2;
|
|
181
|
-
const tensors = {};
|
|
182
|
-
for (let t = 0; t < tensorCount; t++) {
|
|
183
|
-
const keyLen = view.getUint16(off, true); off += 2;
|
|
184
|
-
const key = new TextDecoder().decode(new Uint8Array(ab, off, keyLen)); off += keyLen;
|
|
185
|
-
const dtypeCode = view.getUint8(off); off += 1;
|
|
186
|
-
const rank = view.getUint8(off); off += 1;
|
|
187
|
-
const shape = [];
|
|
188
|
-
for (let d = 0; d < rank; d++) { shape.push(view.getUint32(off, true)); off += 4; }
|
|
189
|
-
const byteLength = view.getUint32(off, true); off += 4;
|
|
190
|
-
const slice = ab.slice(off, off + byteLength);
|
|
191
|
-
const data = dtypeCode === 0 ? new Float32Array(slice)
|
|
192
|
-
: dtypeCode === 1 ? new BigInt64Array(slice)
|
|
193
|
-
: dtypeCode === 2 ? new Uint8Array(slice)
|
|
194
|
-
: (() => { throw new Error(`unsupported voices.bin dtype ${dtypeCode}`); })();
|
|
195
|
-
off += byteLength;
|
|
196
|
-
tensors[key] = { data, shape, dtype: dtypeCode === 0 ? 'float32' : dtypeCode === 1 ? 'int64' : 'bool' };
|
|
197
|
-
}
|
|
198
|
-
voices[name] = tensors;
|
|
199
|
-
}
|
|
200
|
-
return voices;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// A saved state is keyed "module/tensor"; the manifest addresses the same tensors
|
|
204
|
-
// by module + key, so the flat table is regrouped before it can be matched.
|
|
205
|
-
function groupByModule(record) {
|
|
206
|
-
const grouped = {};
|
|
207
|
-
for (const [k, v] of Object.entries(record)) {
|
|
208
|
-
const i = k.indexOf('/');
|
|
209
|
-
if (i === -1) continue;
|
|
210
|
-
(grouped[k.slice(0, i)] ||= {})[k.slice(i + 1)] = v;
|
|
211
|
-
}
|
|
212
|
-
return grouped;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// Some modules record their position under a different name (or not at all), so
|
|
216
|
-
// the manifest's `step` is derived from whichever the module actually kept.
|
|
217
|
-
function deriveStep(moduleState) {
|
|
218
|
-
if (moduleState.step) return { data: BigInt64Array.from([BigInt(moduleState.step.data[0])]), shape: [1], dtype: 'int64' };
|
|
219
|
-
if (moduleState.offset && !moduleState.end_offset) return { data: BigInt64Array.from([BigInt(moduleState.offset.data[0])]), shape: [1], dtype: 'int64' };
|
|
220
|
-
if (moduleState.current_end) return { data: BigInt64Array.from([BigInt(moduleState.current_end.shape[0])]), shape: [1], dtype: 'int64' };
|
|
221
|
-
return { data: BigInt64Array.from([0n]), shape: [1], dtype: 'int64' };
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// A saved tensor may not match the manifest's shape exactly (a shorter cache, say).
|
|
225
|
-
// Copy what overlaps into a correctly-shaped, correctly-filled target rather than
|
|
226
|
-
// handing ORT a tensor of the wrong rank.
|
|
227
|
-
function adaptTensor(source, entry) {
|
|
228
|
-
const target = filledArray(entry.shape, entry.dtype, entry.fill);
|
|
229
|
-
const targetSize = entry.shape.reduce((a, b) => a * b, 1);
|
|
230
|
-
const Ctor = entry.dtype === 'int64' ? BigInt64Array : entry.dtype === 'bool' ? Uint8Array : Float32Array;
|
|
231
|
-
const sameRank = source.shape.length === entry.shape.length;
|
|
232
|
-
if ((sameRank && source.shape.every((d, i) => d === entry.shape[i])) || source.data.length === targetSize) {
|
|
233
|
-
return new Ctor(source.data);
|
|
234
|
-
}
|
|
235
|
-
if (!sameRank) return target;
|
|
236
|
-
const strides = [];
|
|
237
|
-
let stride = 1;
|
|
238
|
-
for (let i = source.shape.length - 1; i >= 0; i--) { strides[i] = stride; stride *= source.shape[i]; }
|
|
239
|
-
const idx = new Array(source.shape.length).fill(0);
|
|
240
|
-
const max = source.shape.map((d, i) => Math.min(d, entry.shape[i]));
|
|
241
|
-
if (max.some((m) => m === 0)) return target;
|
|
242
|
-
for (;;) {
|
|
243
|
-
let si = 0;
|
|
244
|
-
for (let i = 0; i < idx.length; i++) si += idx[i] * strides[i];
|
|
245
|
-
let ti = 0, ts = 1;
|
|
246
|
-
for (let i = entry.shape.length - 1; i >= 0; i--) { ti += idx[i] * ts; ts *= entry.shape[i]; }
|
|
247
|
-
target[ti] = source.data[si];
|
|
248
|
-
let dim = idx.length - 1;
|
|
249
|
-
for (; dim >= 0; dim--) {
|
|
250
|
-
if (++idx[dim] < max[dim]) break;
|
|
251
|
-
idx[dim] = 0;
|
|
252
|
-
if (dim === 0) return target;
|
|
253
|
-
}
|
|
254
|
-
if (dim < 0) return target;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
export class PocketTTS {
|
|
259
|
-
constructor() {
|
|
260
|
-
this.ready = false;
|
|
261
|
-
this.bundle = null;
|
|
262
|
-
this.meta = null;
|
|
263
|
-
this.tok = null;
|
|
264
|
-
this.bos = null;
|
|
265
|
-
this.sessions = null;
|
|
266
|
-
this.st = null; // precomputed flow-matching s/t pairs
|
|
267
|
-
this.latentDim = 32;
|
|
268
|
-
this.condDim = 1024;
|
|
269
|
-
this.samplesPerFrame = 1920;
|
|
270
|
-
this.builtin = null; // name → saved tensor state, from voices.bin
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/** The built-in speaker names available, or [] if voices.bin was not fetched. */
|
|
274
|
-
builtinVoices() { return this.builtin ? Object.keys(this.builtin).sort() : []; }
|
|
275
|
-
|
|
276
|
-
async load(bundle = DEFAULT_BUNDLE, { quant = '_int8', onProgress, log = () => {} } = {}) {
|
|
277
|
-
const dir = await ensureBundle(bundle, quant, { onProgress, log });
|
|
278
|
-
// The built-in speakers come WITH the model. `ensureVoicesBin` existed and nothing called
|
|
279
|
-
// it: the eight names were listed as "downloads on first use", the default voice was one
|
|
280
|
-
// of them, and picking any of them failed with "unknown built-in voice" on every machine
|
|
281
|
-
// but the one where the file had been fetched by hand. Best-effort — a failed download
|
|
282
|
-
// costs the stock voices and leaves cloning untouched.
|
|
283
|
-
if (!voicesBinOnDisk(bundle)) {
|
|
284
|
-
try { await ensureVoicesBin(bundle, { onProgress, log }); } catch (e) { log(`[pocket-tts] built-in voices not downloaded (${e.message}) — cloning still works`); }
|
|
285
|
-
}
|
|
286
|
-
const ort = await getOrt();
|
|
287
|
-
this.meta = JSON.parse(readFileSync(join(dir, 'bundle.json'), 'utf8'));
|
|
288
|
-
this.tok = new SentencePieceUnigram(new Uint8Array(readFileSync(join(dir, 'tokenizer.model'))));
|
|
289
|
-
this.bos = this.meta.insert_bos_before_voice ? parseNpyFloat32(readFileSync(join(dir, 'bos_before_voice.npy'))) : null;
|
|
290
|
-
this.latentDim = Number(this.meta.latent_dim) || 32;
|
|
291
|
-
this.condDim = Number(this.meta.conditioning_dim) || 1024;
|
|
292
|
-
this.samplesPerFrame = Math.round(SAMPLE_RATE / (Number(this.meta.frame_rate) || 12.5));
|
|
293
|
-
|
|
294
|
-
const opts = { executionProviders: ortProviders(), graphOptimizationLevel: 'all', logSeverityLevel: 3 };
|
|
295
|
-
const [textConditioner, mimiEncoder, mimiDecoder, flowMain, flowFlow] = await Promise.all([
|
|
296
|
-
ort.InferenceSession.create(join(dir, `text_conditioner${quant}.onnx`), opts),
|
|
297
|
-
ort.InferenceSession.create(join(dir, `mimi_encoder${quant}.onnx`), opts),
|
|
298
|
-
ort.InferenceSession.create(join(dir, `mimi_decoder${quant}.onnx`), opts),
|
|
299
|
-
ort.InferenceSession.create(join(dir, `flow_lm_main${quant}.onnx`), opts),
|
|
300
|
-
ort.InferenceSession.create(join(dir, `flow_lm_flow${quant}.onnx`), opts),
|
|
301
|
-
]);
|
|
302
|
-
this.sessions = { ort, textConditioner, mimiEncoder, mimiDecoder, flowMain, flowFlow };
|
|
303
|
-
|
|
304
|
-
// Flow matching walks s → t in fixed steps; the tensors never change, so they
|
|
305
|
-
// are built once rather than per frame (this runs MAX_FRAMES times a chunk).
|
|
306
|
-
this.st = [];
|
|
307
|
-
const dt = 1 / LSD_STEPS;
|
|
308
|
-
for (let i = 0; i < LSD_STEPS; i++) {
|
|
309
|
-
const s = i / LSD_STEPS;
|
|
310
|
-
this.st.push({
|
|
311
|
-
s: new ort.Tensor('float32', new Float32Array([s]), [1, 1]),
|
|
312
|
-
t: new ort.Tensor('float32', new Float32Array([s + dt]), [1, 1]),
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
// Built-in speakers are optional: a missing or unreadable voices.bin costs the
|
|
316
|
-
// stock voices and leaves cloning — the reason this engine exists — untouched.
|
|
317
|
-
try {
|
|
318
|
-
if (voicesBinOnDisk(bundle)) this.builtin = parseVoicesBin(readFileSync(join(dir, 'voices.bin')));
|
|
319
|
-
} catch (e) { log(`[pocket-tts] built-in voices unavailable (${e.message})`); }
|
|
320
|
-
|
|
321
|
-
this.bundle = bundle;
|
|
322
|
-
this.ready = true;
|
|
323
|
-
log(`[pocket-tts] ready — ${bundle} (${quant.replace('_', '') || 'fp32'}, ${SAMPLE_RATE} Hz)`);
|
|
324
|
-
return true;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/**
|
|
328
|
-
* THE CLONING STEP. A few seconds of 24 kHz mono audio → the voice conditioning
|
|
329
|
-
* that seeds generation. Returns { data, shape } to be stored as the voice print.
|
|
330
|
-
*/
|
|
331
|
-
async encodeVoice(audio) {
|
|
332
|
-
if (!this.ready) throw new Error('pocket-tts not loaded');
|
|
333
|
-
const { ort, mimiEncoder } = this.sessions;
|
|
334
|
-
const pcm = audio instanceof Float32Array ? audio : Float32Array.from(audio);
|
|
335
|
-
const out = await mimiEncoder.run({ audio: new ort.Tensor('float32', pcm, [1, 1, pcm.length]) });
|
|
336
|
-
const emb = out[mimiEncoder.outputNames[0]];
|
|
337
|
-
let dims = emb.dims.slice();
|
|
338
|
-
while (dims.length > 3 && dims[0] === 1) dims = dims.slice(1);
|
|
339
|
-
if (dims.length < 3) dims = [1, dims[0], dims[1]];
|
|
340
|
-
return { data: Float32Array.from(emb.data), shape: dims };
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
// The voice conditioning is fed to flow_lm_main in the TEXT-embedding slot,
|
|
344
|
-
// preceded by the bundle's BOS frames — the model is told "this is how the
|
|
345
|
-
// speaker sounds" before it is told what to say.
|
|
346
|
-
#voiceTensor(voice) {
|
|
347
|
-
const { ort } = this.sessions;
|
|
348
|
-
let data = voice.data instanceof Float32Array ? voice.data : Float32Array.from(voice.data);
|
|
349
|
-
let dims = voice.shape.slice();
|
|
350
|
-
if (this.meta.insert_bos_before_voice && this.bos) {
|
|
351
|
-
const combined = new Float32Array(this.bos.data.length + data.length);
|
|
352
|
-
combined.set(this.bos.data, 0);
|
|
353
|
-
combined.set(data, this.bos.data.length);
|
|
354
|
-
data = combined;
|
|
355
|
-
dims = [1, dims[1] + this.bos.shape[1], dims[2]];
|
|
356
|
-
}
|
|
357
|
-
return new ort.Tensor('float32', data, dims);
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// Restore the flow-LM state a built-in speaker was saved with.
|
|
361
|
-
#builtinState(name) {
|
|
362
|
-
const record = this.builtin?.[name];
|
|
363
|
-
if (!record) throw new Error(`unknown built-in voice: ${name}`);
|
|
364
|
-
const { ort } = this.sessions;
|
|
365
|
-
const grouped = groupByModule(record);
|
|
366
|
-
const state = initState(ort, this.meta.flow_lm_state_manifest);
|
|
367
|
-
for (const e of this.meta.flow_lm_state_manifest) {
|
|
368
|
-
const moduleState = grouped[e.module] || {};
|
|
369
|
-
const source = moduleState[e.key] || (e.key === 'step' ? deriveStep(moduleState) : null);
|
|
370
|
-
if (!source) continue;
|
|
371
|
-
state[e.input_name] = new ort.Tensor(e.dtype, adaptTensor(source, e), e.shape);
|
|
372
|
-
}
|
|
373
|
-
return state;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
async #voiceState(voice) {
|
|
377
|
-
const { ort, flowMain } = this.sessions;
|
|
378
|
-
const state = initState(ort, this.meta.flow_lm_state_manifest);
|
|
379
|
-
const result = await flowMain.run({
|
|
380
|
-
sequence: new ort.Tensor('float32', new Float32Array(0), [1, 0, this.latentDim]),
|
|
381
|
-
text_embeddings: this.#voiceTensor(voice),
|
|
382
|
-
...state,
|
|
383
|
-
});
|
|
384
|
-
advanceState(state, result, this.meta.flow_lm_state_manifest);
|
|
385
|
-
return state;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
// Normalization the model expects: one line, capitalized, terminated.
|
|
389
|
-
#prepare(text) {
|
|
390
|
-
let s = String(text).replace(/[\r\n]+/g, ' ').replace(/\s+/g, ' ').trim();
|
|
391
|
-
if (!s) return { text: '', framesAfterEos: 1 };
|
|
392
|
-
if (this.meta.remove_semicolons) s = s.replace(/;/g, ',');
|
|
393
|
-
const words = s.split(/\s+/).filter(Boolean).length;
|
|
394
|
-
let framesAfterEos = words <= 4 ? 3 : 1;
|
|
395
|
-
if (this.meta.model_recommended_frames_after_eos != null) framesAfterEos = Number(this.meta.model_recommended_frames_after_eos);
|
|
396
|
-
if (!/[A-ZÀ-Þ]/.test(s[0])) s = s[0].toUpperCase() + s.slice(1);
|
|
397
|
-
if (/[0-9A-Za-zÀ-ÿ]/.test(s[s.length - 1])) s += '.';
|
|
398
|
-
if (this.meta.pad_with_spaces_for_short_inputs && words < 5) s = ` ${s}`;
|
|
399
|
-
return { text: s, framesAfterEos };
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
// One forward pass per FRAME, so a long paragraph in a single chunk is a long
|
|
403
|
-
// time before any audio. Split on sentences, then on the model's token ceiling.
|
|
404
|
-
#chunks(text) {
|
|
405
|
-
const maxTokens = Number(this.meta.max_token_per_chunk) || 50;
|
|
406
|
-
const sentences = text.match(/[^.!?]+[.!?]+|[^.!?]+$/g) || [text];
|
|
407
|
-
const out = [];
|
|
408
|
-
for (const raw of sentences) {
|
|
409
|
-
const s = raw.trim();
|
|
410
|
-
if (!s) continue;
|
|
411
|
-
const ids = this.tok.encodeIds(s);
|
|
412
|
-
if (ids.length <= maxTokens) { out.push(s); continue; }
|
|
413
|
-
for (let i = 0; i < ids.length; i += maxTokens) {
|
|
414
|
-
const part = this.tok.decodeIds(ids.slice(i, i + maxTokens)).trim();
|
|
415
|
-
if (part) out.push(part);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
return out.length ? out : [text];
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
/**
|
|
422
|
-
* Synthesize. `voice` is what encodeVoice() returned. `onAudio(pcm)` receives
|
|
423
|
-
* each decoded piece as it lands, so a caller can stream; the whole waveform is
|
|
424
|
-
* returned as well.
|
|
425
|
-
*/
|
|
426
|
-
async synth(text, { voice, onAudio = null } = {}) {
|
|
427
|
-
if (!this.ready) throw new Error('pocket-tts not loaded');
|
|
428
|
-
// Either a cloned voice ({data, shape} from encodeVoice) or a built-in name.
|
|
429
|
-
if (typeof voice === 'string') {
|
|
430
|
-
if (!this.builtin?.[voice]) throw new Error(`unknown built-in voice: ${voice}`);
|
|
431
|
-
} else if (!voice?.data?.length) {
|
|
432
|
-
throw new Error('pocket-tts needs a voice — record one, or pick a built-in');
|
|
433
|
-
}
|
|
434
|
-
const { ort, textConditioner, flowMain, flowFlow, mimiDecoder } = this.sessions;
|
|
435
|
-
const prepared = this.#prepare(text);
|
|
436
|
-
if (!prepared.text) return new Float32Array(0);
|
|
437
|
-
const chunks = this.#chunks(prepared.text);
|
|
438
|
-
const baseFlow = typeof voice === 'string' ? this.#builtinState(voice) : await this.#voiceState(voice);
|
|
439
|
-
|
|
440
|
-
const emptySeq = new ort.Tensor('float32', new Float32Array(0), [1, 0, this.latentDim]);
|
|
441
|
-
const emptyText = new ort.Tensor('float32', new Float32Array(0), [1, 0, this.condDim]);
|
|
442
|
-
let mimiState = initState(ort, this.meta.mimi_state_manifest);
|
|
443
|
-
let flowState = { ...baseFlow };
|
|
444
|
-
const pieces = [];
|
|
445
|
-
let first = true;
|
|
446
|
-
|
|
447
|
-
for (let c = 0; c < chunks.length; c++) {
|
|
448
|
-
if (RESET_STATE_EACH_CHUNK && c > 0) {
|
|
449
|
-
flowState = { ...baseFlow };
|
|
450
|
-
mimiState = initState(ort, this.meta.mimi_state_manifest);
|
|
451
|
-
}
|
|
452
|
-
const ids = this.tok.encodeIds(chunks[c]);
|
|
453
|
-
const tokens = new ort.Tensor('int64', BigInt64Array.from(ids, (t) => BigInt(t)), [1, ids.length]);
|
|
454
|
-
let textEmb = (await textConditioner.run({ token_ids: tokens }))[textConditioner.outputNames[0]];
|
|
455
|
-
if (textEmb.dims.length === 2) textEmb = new ort.Tensor('float32', Float32Array.from(textEmb.data), [1, textEmb.dims[0], textEmb.dims[1]]);
|
|
456
|
-
|
|
457
|
-
// Prime the LM with the text, then generate frames from silence.
|
|
458
|
-
advanceState(flowState, await flowMain.run({ sequence: emptySeq, text_embeddings: textEmb, ...flowState }), this.meta.flow_lm_state_manifest);
|
|
459
|
-
|
|
460
|
-
const latents = [];
|
|
461
|
-
let decoded = 0;
|
|
462
|
-
let cur = new ort.Tensor('float32', new Float32Array(this.latentDim).fill(NaN), [1, 1, this.latentDim]);
|
|
463
|
-
let eosAt = null;
|
|
464
|
-
|
|
465
|
-
for (let step = 0; step < MAX_FRAMES; step++) {
|
|
466
|
-
const ar = await flowMain.run({ sequence: cur, text_embeddings: emptyText, ...flowState });
|
|
467
|
-
const conditioning = ar.conditioning;
|
|
468
|
-
if (ar.eos_logit.data[0] > EOS_LOGIT_THRESHOLD && eosAt == null) eosAt = step;
|
|
469
|
-
const stop = eosAt != null && step >= eosAt + prepared.framesAfterEos;
|
|
470
|
-
|
|
471
|
-
// Start from Gaussian noise, then walk it along the learned flow field.
|
|
472
|
-
const std = Math.sqrt(TEMPERATURE);
|
|
473
|
-
const latent = new Float32Array(this.latentDim);
|
|
474
|
-
for (let i = 0; i < this.latentDim; i++) {
|
|
475
|
-
let u = 0, v = 0;
|
|
476
|
-
while (u === 0) u = Math.random();
|
|
477
|
-
while (v === 0) v = Math.random();
|
|
478
|
-
latent[i] = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v) * std;
|
|
479
|
-
}
|
|
480
|
-
const dt = 1 / LSD_STEPS;
|
|
481
|
-
for (let k = 0; k < LSD_STEPS; k++) {
|
|
482
|
-
const f = await flowFlow.run({ c: conditioning, s: this.st[k].s, t: this.st[k].t, x: new ort.Tensor('float32', latent, [1, this.latentDim]) });
|
|
483
|
-
const dir = f.flow_dir.data;
|
|
484
|
-
for (let i = 0; i < this.latentDim; i++) latent[i] += dir[i] * dt;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
latents.push(Float32Array.from(latent));
|
|
488
|
-
cur = new ort.Tensor('float32', latent, [1, 1, this.latentDim]);
|
|
489
|
-
advanceState(flowState, ar, this.meta.flow_lm_state_manifest);
|
|
490
|
-
|
|
491
|
-
// Decode in small batches — the first deliberately tiny so sound starts
|
|
492
|
-
// early, the rest larger because the decoder is cheaper in bulk.
|
|
493
|
-
const pending = latents.length - decoded;
|
|
494
|
-
let take = 0;
|
|
495
|
-
if (stop) take = pending;
|
|
496
|
-
else if (first && pending >= FIRST_CHUNK_FRAMES) take = FIRST_CHUNK_FRAMES;
|
|
497
|
-
else if (pending >= NORMAL_CHUNK_FRAMES) take = NORMAL_CHUNK_FRAMES;
|
|
498
|
-
|
|
499
|
-
if (take > 0) {
|
|
500
|
-
const buf = new Float32Array(take * this.latentDim);
|
|
501
|
-
for (let f = 0; f < take; f++) buf.set(latents[decoded + f], f * this.latentDim);
|
|
502
|
-
const dec = await mimiDecoder.run({ latent: new ort.Tensor('float32', buf, [1, take, this.latentDim]), ...mimiState });
|
|
503
|
-
advanceState(mimiState, dec, this.meta.mimi_state_manifest);
|
|
504
|
-
decoded += take;
|
|
505
|
-
first = false;
|
|
506
|
-
const pcm = Float32Array.from(dec[mimiDecoder.outputNames[0]].data);
|
|
507
|
-
pieces.push(pcm);
|
|
508
|
-
onAudio?.(pcm);
|
|
509
|
-
}
|
|
510
|
-
if (stop) break;
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
const total = pieces.reduce((n, p) => n + p.length, 0);
|
|
515
|
-
const out = new Float32Array(total);
|
|
516
|
-
let at = 0;
|
|
517
|
-
for (const p of pieces) { out.set(p, at); at += p.length; }
|
|
518
|
-
return out;
|
|
519
|
-
}
|
|
520
|
-
}
|
|
1
|
+
import{join as u}from"node:path";import{existsSync as O,mkdirSync as Z,readFileSync as P,statSync as L,createWriteStream as rt,renameSync as at}from"node:fs";import{Readable as ct}from"node:stream";import{modelRoot as lt}from"./ner-engine.js";import{SentencePieceUnigram as ft}from"./sentencepiece.js";import{getOrt as ht,ortProviders as mt}from"./ort.js";const dt="KevinAHM/pocket-tts-onnx",ut="KevinAHM/pocket-tts-web",F="english_2026-04",G=24e3,pt=500,v=1,wt=.7,_t=-4,J=3,X=12,gt=!0,Q=(s="_int8")=>["bundle.json","tokenizer.model","bos_before_voice.npy",`text_conditioner${s}.onnx`,`mimi_encoder${s}.onnx`,`mimi_decoder${s}.onnx`,`flow_lm_main${s}.onnx`,`flow_lm_flow${s}.onnx`],I="voices.bin";function C(s=F){return u(lt(),"pocket-tts",s)}function Ut(s=F,n="_int8"){const t=C(s);try{return Q(n).every(e=>{const o=u(t,e);return O(o)&&L(o).size>0})}catch{return!1}}async function q(s,n,t,{onProgress:e,log:o}={}){const r=n===I?`https://huggingface.co/spaces/${ut}/resolve/main/onnx/${s}/${n}`:`https://huggingface.co/${dt}/resolve/main/onnx/${s}/${n}`,i=await fetch(r,{redirect:"follow"});if(!i.ok||!i.body)throw new Error(`fetch ${n} → HTTP ${i.status}`);const a=Number(i.headers.get("content-length"))||0,h=u(t,`${n}.part`),m=rt(h);let f=0,c=-1;const w=ct.fromWeb(i.body);w.on("data",d=>{if(f+=d.length,a){const l=Math.round(f/a*100);l!==c&&(c=l,e?.({file:n,pct:l}))}}),await new Promise((d,l)=>{w.pipe(m),m.on("finish",d),m.on("error",l),w.on("error",l)}),at(h,u(t,n)),o?.(`[pocket-tts] fetched ${n}`)}async function yt(s=F,n="_int8",{onProgress:t,log:e}={}){const o=C(s);Z(o,{recursive:!0});for(const r of Q(n)){const i=u(o,r);O(i)&&L(i).size>0||(e?.(`[pocket-tts] downloading ${r}…`),await q(s,r,o,{onProgress:t,log:e}))}return o}async function bt(s=F,{onProgress:n,log:t}={}){const e=C(s),o=u(e,I);return O(o)&&L(o).size>1024||(Z(e,{recursive:!0}),t?.(`[pocket-tts] downloading ${I} (built-in voices, ~52 MB)…`),await q(s,I,e,{onProgress:n,log:t})),o}function tt(s=F){try{const n=u(C(s),I);return O(n)&&L(n).size>1024}catch{return!1}}function At(s){const n=[147,78,85,77,80,89];for(let c=0;c<n.length;c++)if(s[c]!==n[c])throw new Error("not an NPY file");const t=new DataView(s.buffer,s.byteOffset,s.byteLength),e=t.getUint8(6),o=e===1?t.getUint16(8,!0):t.getUint32(8,!0),r=e===1?10:12,i=new TextDecoder().decode(s.subarray(r,r+o)),a=/\(\s*([0-9,\s]*)\)/.exec(i);if(!a)throw new Error("could not parse NPY shape");const h=a[1].split(",").map(c=>c.trim()).filter(Boolean).map(c=>parseInt(c,10)),m=r+o,f=new Float32Array((s.byteLength-m)/4);for(let c=0;c<f.length;c++)f[c]=t.getFloat32(m+c*4,!0);return{data:f,shape:h}}function et(s,n,t){const e=s.reduce((r,i)=>r*i,1);if(n==="int64")return new BigInt64Array(e);if(n==="bool")return new Uint8Array(e);const o=new Float32Array(e);return t==="nan"?o.fill(NaN):t==="ones"&&o.fill(1),o}function R(s,n){const t={};for(const e of n)t[e.input_name]=new s.Tensor(e.dtype,et(e.shape,e.dtype,e.fill),e.shape);return t}function z(s,n,t){for(const e of t)s[e.input_name]=n[e.output_name]}function xt(s){const n=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),t=new DataView(n);let e=0;const o=new TextDecoder().decode(new Uint8Array(n,0,5));if(e+=5,o!=="PTVB1")throw new Error("not a voices.bin (bad header)");const r={},i=t.getUint32(e,!0);e+=4;for(let a=0;a<i;a++){const h=t.getUint16(e,!0);e+=2;const m=new TextDecoder().decode(new Uint8Array(n,e,h));e+=h;const f=t.getUint16(e,!0);e+=2;const c={};for(let w=0;w<f;w++){const d=t.getUint16(e,!0);e+=2;const l=new TextDecoder().decode(new Uint8Array(n,e,d));e+=d;const p=t.getUint8(e);e+=1;const S=t.getUint8(e);e+=1;const D=[];for(let _=0;_<S;_++)D.push(t.getUint32(e,!0)),e+=4;const U=t.getUint32(e,!0);e+=4;const k=n.slice(e,e+U),M=p===0?new Float32Array(k):p===1?new BigInt64Array(k):p===2?new Uint8Array(k):(()=>{throw new Error(`unsupported voices.bin dtype ${p}`)})();e+=U,c[l]={data:M,shape:D,dtype:p===0?"float32":p===1?"int64":"bool"}}r[m]=c}return r}function kt(s){const n={};for(const[t,e]of Object.entries(s)){const o=t.indexOf("/");o!==-1&&((n[t.slice(0,o)]||={})[t.slice(o+1)]=e)}return n}function Et(s){return s.step?{data:BigInt64Array.from([BigInt(s.step.data[0])]),shape:[1],dtype:"int64"}:s.offset&&!s.end_offset?{data:BigInt64Array.from([BigInt(s.offset.data[0])]),shape:[1],dtype:"int64"}:s.current_end?{data:BigInt64Array.from([BigInt(s.current_end.shape[0])]),shape:[1],dtype:"int64"}:{data:BigInt64Array.from([0n]),shape:[1],dtype:"int64"}}function Tt(s,n){const t=et(n.shape,n.dtype,n.fill),e=n.shape.reduce((f,c)=>f*c,1),o=n.dtype==="int64"?BigInt64Array:n.dtype==="bool"?Uint8Array:Float32Array,r=s.shape.length===n.shape.length;if(r&&s.shape.every((f,c)=>f===n.shape[c])||s.data.length===e)return new o(s.data);if(!r)return t;const i=[];let a=1;for(let f=s.shape.length-1;f>=0;f--)i[f]=a,a*=s.shape[f];const h=new Array(s.shape.length).fill(0),m=s.shape.map((f,c)=>Math.min(f,n.shape[c]));if(m.some(f=>f===0))return t;for(;;){let f=0;for(let l=0;l<h.length;l++)f+=h[l]*i[l];let c=0,w=1;for(let l=n.shape.length-1;l>=0;l--)c+=h[l]*w,w*=n.shape[l];t[c]=s.data[f];let d=h.length-1;for(;d>=0&&!(++h[d]<m[d]);d--)if(h[d]=0,d===0)return t;if(d<0)return t}}class Mt{constructor(){this.ready=!1,this.bundle=null,this.meta=null,this.tok=null,this.bos=null,this.sessions=null,this.st=null,this.latentDim=32,this.condDim=1024,this.samplesPerFrame=1920,this.builtin=null}builtinVoices(){return this.builtin?Object.keys(this.builtin).sort():[]}async load(n=F,{quant:t="_int8",onProgress:e,log:o=()=>{}}={}){const r=await yt(n,t,{onProgress:e,log:o});if(!tt(n))try{await bt(n,{onProgress:e,log:o})}catch(l){o(`[pocket-tts] built-in voices not downloaded (${l.message}) — cloning still works`)}const i=await ht();this.meta=JSON.parse(P(u(r,"bundle.json"),"utf8")),this.tok=new ft(new Uint8Array(P(u(r,"tokenizer.model")))),this.bos=this.meta.insert_bos_before_voice?At(P(u(r,"bos_before_voice.npy"))):null,this.latentDim=Number(this.meta.latent_dim)||32,this.condDim=Number(this.meta.conditioning_dim)||1024,this.samplesPerFrame=Math.round(G/(Number(this.meta.frame_rate)||12.5));const a={executionProviders:mt(),graphOptimizationLevel:"all",logSeverityLevel:3},[h,m,f,c,w]=await Promise.all([i.InferenceSession.create(u(r,`text_conditioner${t}.onnx`),a),i.InferenceSession.create(u(r,`mimi_encoder${t}.onnx`),a),i.InferenceSession.create(u(r,`mimi_decoder${t}.onnx`),a),i.InferenceSession.create(u(r,`flow_lm_main${t}.onnx`),a),i.InferenceSession.create(u(r,`flow_lm_flow${t}.onnx`),a)]);this.sessions={ort:i,textConditioner:h,mimiEncoder:m,mimiDecoder:f,flowMain:c,flowFlow:w},this.st=[];const d=1/v;for(let l=0;l<v;l++){const p=l/v;this.st.push({s:new i.Tensor("float32",new Float32Array([p]),[1,1]),t:new i.Tensor("float32",new Float32Array([p+d]),[1,1])})}try{tt(n)&&(this.builtin=xt(P(u(r,"voices.bin"))))}catch(l){o(`[pocket-tts] built-in voices unavailable (${l.message})`)}return this.bundle=n,this.ready=!0,o(`[pocket-tts] ready — ${n} (${t.replace("_","")||"fp32"}, ${G} Hz)`),!0}async encodeVoice(n){if(!this.ready)throw new Error("pocket-tts not loaded");const{ort:t,mimiEncoder:e}=this.sessions,o=n instanceof Float32Array?n:Float32Array.from(n),i=(await e.run({audio:new t.Tensor("float32",o,[1,1,o.length])}))[e.outputNames[0]];let a=i.dims.slice();for(;a.length>3&&a[0]===1;)a=a.slice(1);return a.length<3&&(a=[1,a[0],a[1]]),{data:Float32Array.from(i.data),shape:a}}#t(n){const{ort:t}=this.sessions;let e=n.data instanceof Float32Array?n.data:Float32Array.from(n.data),o=n.shape.slice();if(this.meta.insert_bos_before_voice&&this.bos){const r=new Float32Array(this.bos.data.length+e.length);r.set(this.bos.data,0),r.set(e,this.bos.data.length),e=r,o=[1,o[1]+this.bos.shape[1],o[2]]}return new t.Tensor("float32",e,o)}#e(n){const t=this.builtin?.[n];if(!t)throw new Error(`unknown built-in voice: ${n}`);const{ort:e}=this.sessions,o=kt(t),r=R(e,this.meta.flow_lm_state_manifest);for(const i of this.meta.flow_lm_state_manifest){const a=o[i.module]||{},h=a[i.key]||(i.key==="step"?Et(a):null);h&&(r[i.input_name]=new e.Tensor(i.dtype,Tt(h,i),i.shape))}return r}async#n(n){const{ort:t,flowMain:e}=this.sessions,o=R(t,this.meta.flow_lm_state_manifest),r=await e.run({sequence:new t.Tensor("float32",new Float32Array(0),[1,0,this.latentDim]),text_embeddings:this.#t(n),...o});return z(o,r,this.meta.flow_lm_state_manifest),o}#o(n){let t=String(n).replace(/[\r\n]+/g," ").replace(/\s+/g," ").trim();if(!t)return{text:"",framesAfterEos:1};this.meta.remove_semicolons&&(t=t.replace(/;/g,","));const e=t.split(/\s+/).filter(Boolean).length;let o=e<=4?3:1;return this.meta.model_recommended_frames_after_eos!=null&&(o=Number(this.meta.model_recommended_frames_after_eos)),/[A-ZÀ-Þ]/.test(t[0])||(t=t[0].toUpperCase()+t.slice(1)),/[0-9A-Za-zÀ-ÿ]/.test(t[t.length-1])&&(t+="."),this.meta.pad_with_spaces_for_short_inputs&&e<5&&(t=` ${t}`),{text:t,framesAfterEos:o}}#s(n){const t=Number(this.meta.max_token_per_chunk)||50,e=n.match(/[^.!?]+[.!?]+|[^.!?]+$/g)||[n],o=[];for(const r of e){const i=r.trim();if(!i)continue;const a=this.tok.encodeIds(i);if(a.length<=t){o.push(i);continue}for(let h=0;h<a.length;h+=t){const m=this.tok.decodeIds(a.slice(h,h+t)).trim();m&&o.push(m)}}return o.length?o:[n]}async synth(n,{voice:t,onAudio:e=null}={}){if(!this.ready)throw new Error("pocket-tts not loaded");if(typeof t=="string"){if(!this.builtin?.[t])throw new Error(`unknown built-in voice: ${t}`)}else if(!t?.data?.length)throw new Error("pocket-tts needs a voice — record one, or pick a built-in");const{ort:o,textConditioner:r,flowMain:i,flowFlow:a,mimiDecoder:h}=this.sessions,m=this.#o(n);if(!m.text)return new Float32Array(0);const f=this.#s(m.text),c=typeof t=="string"?this.#e(t):await this.#n(t),w=new o.Tensor("float32",new Float32Array(0),[1,0,this.latentDim]),d=new o.Tensor("float32",new Float32Array(0),[1,0,this.condDim]);let l=R(o,this.meta.mimi_state_manifest),p={...c};const S=[];let D=!0;for(let _=0;_<f.length;_++){gt&&_>0&&(p={...c},l=R(o,this.meta.mimi_state_manifest));const B=this.tok.encodeIds(f[_]),nt=new o.Tensor("int64",BigInt64Array.from(B,T=>BigInt(T)),[1,B.length]);let E=(await r.run({token_ids:nt}))[r.outputNames[0]];E.dims.length===2&&(E=new o.Tensor("float32",Float32Array.from(E.data),[1,E.dims[0],E.dims[1]])),z(p,await i.run({sequence:w,text_embeddings:E,...p}),this.meta.flow_lm_state_manifest);const H=[];let V=0,W=new o.Tensor("float32",new Float32Array(this.latentDim).fill(NaN),[1,1,this.latentDim]),N=null;for(let T=0;T<pt;T++){const K=await i.run({sequence:W,text_embeddings:d,...p}),ot=K.conditioning;K.eos_logit.data[0]>_t&&N==null&&(N=T);const Y=N!=null&&T>=N+m.framesAfterEos,st=Math.sqrt(wt),$=new Float32Array(this.latentDim);for(let g=0;g<this.latentDim;g++){let x=0,A=0;for(;x===0;)x=Math.random();for(;A===0;)A=Math.random();$[g]=Math.sqrt(-2*Math.log(x))*Math.cos(2*Math.PI*A)*st}const it=1/v;for(let g=0;g<v;g++){const A=(await a.run({c:ot,s:this.st[g].s,t:this.st[g].t,x:new o.Tensor("float32",$,[1,this.latentDim])})).flow_dir.data;for(let y=0;y<this.latentDim;y++)$[y]+=A[y]*it}H.push(Float32Array.from($)),W=new o.Tensor("float32",$,[1,1,this.latentDim]),z(p,K,this.meta.flow_lm_state_manifest);const j=H.length-V;let b=0;if(Y?b=j:D&&j>=J?b=J:j>=X&&(b=X),b>0){const g=new Float32Array(b*this.latentDim);for(let y=0;y<b;y++)g.set(H[V+y],y*this.latentDim);const x=await h.run({latent:new o.Tensor("float32",g,[1,b,this.latentDim]),...l});z(l,x,this.meta.mimi_state_manifest),V+=b,D=!1;const A=Float32Array.from(x[h.outputNames[0]].data);S.push(A),e?.(A)}if(Y)break}}const U=S.reduce((_,B)=>_+B.length,0),k=new Float32Array(U);let M=0;for(const _ of S)k.set(_,M),M+=_.length;return k}}export{F as DEFAULT_BUNDLE,dt as POCKET_REPO,ut as POCKET_VOICES_SPACE,Mt as PocketTTS,G as SAMPLE_RATE,C as bundleDir,Ut as bundleOnDisk,yt as ensureBundle,bt as ensureVoicesBin,At as parseNpyFloat32,xt as parseVoicesBin,tt as voicesBinOnDisk};
|
package/src/policy.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{existsSync as m,readFileSync as g}from"node:fs";import{join as d}from"node:path";import P from"node:os";import{normalizeOrgPolicy as w,verifyPolicyToken as E,policyHash as S,policyLabel as x,PolicyError as A}from"@chatpanel/events/policy.js";import{verifySignedToken as C}from"@chatpanel/events/entitlement.js";class u extends Error{constructor(n){super(n),this.name="PolicyLoadError"}}function f(o=process.env,n=process.platform,t=P.homedir()){const e=[];return o.CHATPANEL_POLICY&&e.push(o.CHATPANEL_POLICY),n==="win32"?e.push(d(o.ProgramData||"C:\\ProgramData","ChatPanel","policy.json")):e.push("/etc/chatpanel/policy.json"),e.push(d(t,".chatpanel","policy.json")),e}let c=null;async function N({env:o=process.env,fs:n={existsSync:m,readFileSync:g},now:t=Date.now()}={}){const e=f(o).find(s=>{try{return n.existsSync(s)}catch{return!1}});if(!e)return null;let i;try{i=n.readFileSync(e,"utf8")}catch(s){throw new u(`cannot read ${e}: ${s.message}`)}const a=String(o.CHATPANEL_POLICY_REQUIRE_SIGNATURE||"")==="1";let r;const p=i.trim();if(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(p))r={token:p};else try{r=JSON.parse(p)}catch{throw new u(`${e} is not JSON (or a signed token)`)}let l,y=!1;if(r&&typeof r.token=="string"){if(l=await E(r.token,{now:t,verify:C}),!l)throw new u(`${e}: the signed policy does not verify (wrong key, tampered, or expired)`);y=!0}else{if(a)throw new u(`${e} is unsigned and CHATPANEL_POLICY_REQUIRE_SIGNATURE=1 — refusing to run unmanaged`);try{l=w(r)}catch(s){throw new u(`${e}: ${s instanceof A?s.message:String(s)}`)}}const h=await S(l);return{policy:l,source:e,signed:y,hash:h,label:x(l)}}async function O(o){return c=await N(o),c}function $(){return c?.policy||null}function v(){return c}function R(o){c=o||null}function j(){if(!c)return null;const{policy:o,signed:n,hash:t,source:e}=c;return{org:o.org?.id||null,name:o.org?.name||null,signed:n,policyHash:t,source:e,locks:o.client?.lock||[],enforces:{endpoints:!!o.endpoints,models:!!o.models,agents:!!o.agents,routing:!!o.routing?.rules?.length,redactionFloor:o.redaction?.floor||null,egress:!!o.egress}}}function H(o,n=$()){if(!n||!o)return o;const t=n.redaction;if(t){if(o.redaction=o.redaction||{},t.floor){const e={off:0,basic:1,full:2},i=o.redaction.tier||"basic";(e[i]??1)<e[t.floor]&&(o.redaction.tier=t.floor)}if(t.dictionary?.length){const e=new Set((o.redaction.dictionary||[]).map(a=>typeof a=="string"?a:a?.term).filter(Boolean)),i=t.dictionary.filter(a=>!e.has(a));i.length&&(o.redaction.dictionary=[...o.redaction.dictionary||[],...i])}}return o}function b(o){if(!o)return"No org policy: this gateway is unmanaged (looked in: "+f().join(", ")+").";const{policy:n,source:t,signed:e,hash:i,label:a}=o,r=[];return r.push(`${a} — ${e?"signed policy":"UNSIGNED policy file"} at ${t}`),r.push(`policy hash ${i}`),r.push(""),r.push(JSON.stringify(n,null,2)),r.join(`
|
|
2
|
+
`)}export{u as PolicyLoadError,$ as activePolicy,v as activePolicyRecord,H as applyPolicyToConfig,b as formatPolicy,O as initPolicy,N as loadPolicy,j as managedSummary,f as policyPaths,R as setActivePolicyForTests};
|