@hackbuild/speak 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +198 -2
- package/dist/bellows.d.ts +126 -0
- package/dist/bellows.js +144 -0
- package/dist/clone.d.ts +13 -0
- package/dist/clone.js +38 -0
- package/dist/engines.d.ts +87 -0
- package/dist/engines.js +125 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +9 -0
- package/dist/player.d.ts +71 -0
- package/dist/player.js +77 -0
- package/dist/pocket.d.ts +61 -0
- package/dist/pocket.js +224 -0
- package/dist/records.d.ts +6 -0
- package/dist/records.js +67 -0
- package/dist/render.d.ts +79 -0
- package/dist/render.js +158 -0
- package/dist/single/index.iife.js +1899 -0
- package/dist/single/index.js +1865 -0
- package/dist/speaker.d.ts +129 -0
- package/dist/speaker.js +414 -0
- package/dist/text.d.ts +72 -0
- package/dist/text.js +170 -0
- package/dist/types.d.ts +64 -0
- package/dist/types.js +2 -0
- package/package.json +48 -4
package/dist/engines.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Engines: Kokoro through kokoro-js (or a transformers.js style module the
|
|
3
|
+
* caller passes), Web Speech, and a stub that needs no weights. Pocket TTS
|
|
4
|
+
* lives in pocket.ts.
|
|
5
|
+
*/
|
|
6
|
+
import { wordSpans } from "./text.js";
|
|
7
|
+
/** A tone engine for `?stub` pages and tests: 60 ms per character at a low level, with exact word times. */
|
|
8
|
+
export function stubEngine(o = {}) {
|
|
9
|
+
const sr = o.rate ?? 24000;
|
|
10
|
+
const spc = o.secPerChar ?? 0.06;
|
|
11
|
+
const chunkSec = o.chunkSec ?? 0.25;
|
|
12
|
+
return {
|
|
13
|
+
kind: "pcm",
|
|
14
|
+
id: o.id ?? "stub",
|
|
15
|
+
licence: "none, no weights",
|
|
16
|
+
async load() {
|
|
17
|
+
if (o.fail === "load")
|
|
18
|
+
throw new Error("stub engine refused to load");
|
|
19
|
+
},
|
|
20
|
+
async *synth(text, cfg, signal) {
|
|
21
|
+
if (o.fail === "synth")
|
|
22
|
+
throw new Error("stub engine failed to synthesize");
|
|
23
|
+
if (o.fail === "hang") {
|
|
24
|
+
await new Promise((res) => signal.addEventListener("abort", () => res(), { once: true }));
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const dur = (text.length * spc) / (cfg.rate ?? 1);
|
|
28
|
+
const total = Math.max(1, Math.round(dur * sr));
|
|
29
|
+
const words = wordSpans(text).map((w) => ({ ...w, t0: (w.start * spc) / (cfg.rate ?? 1), t1: (w.end * spc) / (cfg.rate ?? 1) }));
|
|
30
|
+
const step = Math.round(chunkSec * sr);
|
|
31
|
+
for (let off = 0; off < total; off += step) {
|
|
32
|
+
if (signal.aborted)
|
|
33
|
+
return;
|
|
34
|
+
await Promise.resolve();
|
|
35
|
+
const n = Math.min(step, total - off);
|
|
36
|
+
const samples = new Float32Array(n);
|
|
37
|
+
for (let i = 0; i < n; i++)
|
|
38
|
+
samples[i] = 0.05 * Math.sin((2 * Math.PI * 220 * (off + i)) / sr);
|
|
39
|
+
const t0 = off / sr;
|
|
40
|
+
const t1 = (off + n) / sr;
|
|
41
|
+
const inChunk = words.filter((w) => w.t0 >= t0 && w.t0 < t1).map((w) => ({ ...w, t0: w.t0 - t0, t1: w.t1 - t0 }));
|
|
42
|
+
yield { samples, sampleRate: sr, words: inChunk };
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
voices: () => ["stub"],
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** What loading kokoro-js brings in, stated before it loads. */
|
|
49
|
+
export const KOKORO_GPL_NOTICE = "kokoro-js phonemizes with the phonemizer package, which is eSpeak NG compiled to wasm under GPL-3.0-or-later. it loads from your url at run time and is never bundled into this MIT package; an app that ships kokoro-js takes on the GPL terms.";
|
|
50
|
+
/**
|
|
51
|
+
* Kokoro 82M, opt in: see KOKORO_GPL_NOTICE. Whole segments are generated at once; word times are
|
|
52
|
+
* estimated from the segment length by the speaker, since kokoro-js
|
|
53
|
+
* reports none.
|
|
54
|
+
*/
|
|
55
|
+
export function kokoroEngine(o) {
|
|
56
|
+
let tts = null;
|
|
57
|
+
const device = o.device ?? "wasm";
|
|
58
|
+
return {
|
|
59
|
+
kind: "pcm",
|
|
60
|
+
id: "kokoro",
|
|
61
|
+
licence: "Kokoro-82M weights Apache-2.0; kokoro-js phonemizer (eSpeak NG) GPL-3.0-or-later",
|
|
62
|
+
async load(ctx) {
|
|
63
|
+
if (tts)
|
|
64
|
+
return;
|
|
65
|
+
if (!o.allowGplPhonemizer)
|
|
66
|
+
throw new Error(`${KOKORO_GPL_NOTICE} pass allowGplPhonemizer: true to load it.`);
|
|
67
|
+
ctx.onStatus?.({ engine: "kokoro", kind: "licence", text: "kokoro 82m weights apache-2.0; its phonemizer, espeak ng, is gpl-3.0-or-later" });
|
|
68
|
+
const m = await o.runtime();
|
|
69
|
+
tts = await m.KokoroTTS.from_pretrained(o.model ?? "onnx-community/Kokoro-82M-v1.0-ONNX", {
|
|
70
|
+
dtype: device === "webgpu" ? "fp32" : "q8",
|
|
71
|
+
device,
|
|
72
|
+
progress_callback: (p) => ctx.onStatus?.({ engine: "kokoro", kind: "loading", text: p.status ?? "loading", ...(p.progress !== undefined ? { progress: p.progress } : {}) }),
|
|
73
|
+
});
|
|
74
|
+
ctx.onStatus?.({ engine: "kokoro", kind: "ready", text: `kokoro ready on ${device}` });
|
|
75
|
+
},
|
|
76
|
+
async *synth(text, cfg, signal) {
|
|
77
|
+
if (!tts)
|
|
78
|
+
throw new Error("kokoro is not loaded");
|
|
79
|
+
const a = await tts.generate(text, { voice: cfg.voice ?? o.voice ?? "af_heart", speed: cfg.rate ?? 1 });
|
|
80
|
+
if (signal.aborted)
|
|
81
|
+
return;
|
|
82
|
+
yield { samples: a.audio, sampleRate: a.sampling_rate };
|
|
83
|
+
},
|
|
84
|
+
voices: () => (tts?.voices ? Object.keys(tts.voices) : ["af_heart"]),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** The system voice. Plays itself; word boundaries come from the browser. */
|
|
88
|
+
export function webSpeechEngine(o = {}) {
|
|
89
|
+
const g = globalThis;
|
|
90
|
+
const synth = o.synth ?? g.speechSynthesis;
|
|
91
|
+
const U = o.Utterance ?? g.SpeechSynthesisUtterance;
|
|
92
|
+
return {
|
|
93
|
+
kind: "native",
|
|
94
|
+
id: "webspeech",
|
|
95
|
+
offline: false,
|
|
96
|
+
licence: "system voices, the browser's and platform's terms",
|
|
97
|
+
async load() {
|
|
98
|
+
if (!synth || !U)
|
|
99
|
+
throw new Error("no speechSynthesis in this browser");
|
|
100
|
+
},
|
|
101
|
+
speak(text, cfg, hooks, signal) {
|
|
102
|
+
return new Promise((resolve, reject) => {
|
|
103
|
+
if (!synth || !U)
|
|
104
|
+
return reject(new Error("no speechSynthesis in this browser"));
|
|
105
|
+
const u = new U(text);
|
|
106
|
+
u.rate = cfg.rate ?? 1;
|
|
107
|
+
u.pitch = cfg.pitch ?? 1;
|
|
108
|
+
u.voice = synth.getVoices().find((v) => v.name === cfg.voice) ?? null;
|
|
109
|
+
u.onboundary = (ev) => {
|
|
110
|
+
if (ev.name === undefined || ev.name === "word")
|
|
111
|
+
hooks.onBoundary(ev.charIndex, ev.charLength);
|
|
112
|
+
};
|
|
113
|
+
u.onstart = () => hooks.onStart?.();
|
|
114
|
+
u.onend = () => resolve();
|
|
115
|
+
u.onerror = (ev) => (ev.error === "interrupted" || ev.error === "canceled" ? resolve() : reject(new Error(`speech synthesis: ${ev.error ?? "error"}`)));
|
|
116
|
+
signal.addEventListener("abort", () => synth.cancel(), { once: true });
|
|
117
|
+
synth.speak(u);
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
stop() {
|
|
121
|
+
synth?.cancel();
|
|
122
|
+
},
|
|
123
|
+
voices: () => synth?.getVoices().map((v) => v.name) ?? [],
|
|
124
|
+
};
|
|
125
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { speakable, SegmentCutter, wordSpans, estimateWordTimes, type Speakable, type SpeakableOptions, type Segment, type CutterOptions } from "./text.js";
|
|
2
|
+
export { GaplessPlayer, type AudioContextLike, type AnalyserLike, type BufferLike, type SourceLike, type AudioNodeLike, type PlayerOptions, } from "./player.js";
|
|
3
|
+
export type { Engine, PcmEngine, NativeEngine, PcmChunk, Timed, VoiceConfig, EngineStatus, LoadContext } from "./types.js";
|
|
4
|
+
export { stubEngine, kokoroEngine, KOKORO_GPL_NOTICE, webSpeechEngine, type KokoroModule, type KokoroOptions, type SynthLike, type UtteranceLike } from "./engines.js";
|
|
5
|
+
export { bellowsEngine, renderSpeechFrom, seedFrom, spansToPhonemes, BELLOWS_VOICES, type BellowsOptions, type BellowsVoiceModule, type BellowsRender, type BellowsRenderOptions, type BellowsSpan, type BellowsParts } from "./bellows.js";
|
|
6
|
+
export { pocketEngine, pocketPrelude, pocketRewrites, POCKET_SPACE_BASE, type PocketEngine, type PocketOptions } from "./pocket.js";
|
|
7
|
+
export { prepareClone, toMono, type CloneOptions } from "./clone.js";
|
|
8
|
+
export { Speaker, createSpeaker, type SpeakerOptions, type Progress, type TimedEvent, type Timers } from "./speaker.js";
|
|
9
|
+
export { SPEAK_RECORDS } from "./records.js";
|
|
10
|
+
export { renderSpeech, canRender, renderedWav, renderedWavBytes, renderedBuffer, renderedTiming, OfflineRenderError, OFFLINE_RENDER_REFUSAL, type RenderedSpeech, type RenderedTimed, type RenderOptions } from "./render.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { speakable, SegmentCutter, wordSpans, estimateWordTimes } from "./text.js";
|
|
2
|
+
export { GaplessPlayer, } from "./player.js";
|
|
3
|
+
export { stubEngine, kokoroEngine, KOKORO_GPL_NOTICE, webSpeechEngine } from "./engines.js";
|
|
4
|
+
export { bellowsEngine, renderSpeechFrom, seedFrom, spansToPhonemes, BELLOWS_VOICES } from "./bellows.js";
|
|
5
|
+
export { pocketEngine, pocketPrelude, pocketRewrites, POCKET_SPACE_BASE } from "./pocket.js";
|
|
6
|
+
export { prepareClone, toMono } from "./clone.js";
|
|
7
|
+
export { Speaker, createSpeaker } from "./speaker.js";
|
|
8
|
+
export { SPEAK_RECORDS } from "./records.js";
|
|
9
|
+
export { renderSpeech, canRender, renderedWav, renderedWavBytes, renderedBuffer, renderedTiming, OfflineRenderError, OFFLINE_RENDER_REFUSAL } from "./render.js";
|
package/dist/player.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gapless playback on one AudioContext: chunks are scheduled back to back
|
|
3
|
+
* 40 ms ahead, every engine's audio goes through one gain and one
|
|
4
|
+
* analyser, and the analyser is the single output a lip sync driver reads.
|
|
5
|
+
*/
|
|
6
|
+
export interface AudioParamLike {
|
|
7
|
+
value: number;
|
|
8
|
+
}
|
|
9
|
+
export interface AudioNodeLike {
|
|
10
|
+
connect(n: AudioNodeLike): unknown;
|
|
11
|
+
disconnect?(): void;
|
|
12
|
+
}
|
|
13
|
+
export interface AnalyserLike extends AudioNodeLike {
|
|
14
|
+
fftSize: number;
|
|
15
|
+
getFloatTimeDomainData(a: Float32Array): void;
|
|
16
|
+
}
|
|
17
|
+
export interface BufferLike {
|
|
18
|
+
getChannelData(c: number): Float32Array;
|
|
19
|
+
}
|
|
20
|
+
export interface SourceLike extends AudioNodeLike {
|
|
21
|
+
buffer: BufferLike | null;
|
|
22
|
+
start(when: number): void;
|
|
23
|
+
stop(when?: number): void;
|
|
24
|
+
onended: ((ev: any) => unknown) | null;
|
|
25
|
+
}
|
|
26
|
+
export interface AudioContextLike {
|
|
27
|
+
readonly currentTime: number;
|
|
28
|
+
readonly sampleRate: number;
|
|
29
|
+
readonly state?: string;
|
|
30
|
+
resume?(): Promise<void>;
|
|
31
|
+
readonly destination: AudioNodeLike;
|
|
32
|
+
createBuffer(channels: number, length: number, rate: number): BufferLike;
|
|
33
|
+
createBufferSource(): SourceLike;
|
|
34
|
+
createAnalyser(): AnalyserLike;
|
|
35
|
+
createGain(): AudioNodeLike & {
|
|
36
|
+
gain: AudioParamLike;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export interface PlayerOptions {
|
|
40
|
+
/** Seconds ahead of now for a chunk that starts after a gap. Default 0.04. */
|
|
41
|
+
lead?: number;
|
|
42
|
+
/** Fade length in samples at the start and end of each segment. Default 96. */
|
|
43
|
+
fade?: number;
|
|
44
|
+
}
|
|
45
|
+
export declare class GaplessPlayer {
|
|
46
|
+
readonly ctx: AudioContextLike;
|
|
47
|
+
readonly analyser: AnalyserLike;
|
|
48
|
+
readonly gain: AudioNodeLike & {
|
|
49
|
+
gain: AudioParamLike;
|
|
50
|
+
};
|
|
51
|
+
private nextT;
|
|
52
|
+
private readonly live;
|
|
53
|
+
private readonly buf;
|
|
54
|
+
private readonly lead;
|
|
55
|
+
private readonly fadeN;
|
|
56
|
+
constructor(ctx: AudioContextLike, o?: PlayerOptions);
|
|
57
|
+
/** Context time when the last scheduled chunk ends. */
|
|
58
|
+
get endTime(): number;
|
|
59
|
+
get playing(): boolean;
|
|
60
|
+
/** Schedule one chunk. Fades are applied to a copy. Returns its context time span. */
|
|
61
|
+
schedule(samples: Float32Array, rate: number, fade?: {
|
|
62
|
+
in?: boolean;
|
|
63
|
+
out?: boolean;
|
|
64
|
+
}): {
|
|
65
|
+
start: number;
|
|
66
|
+
end: number;
|
|
67
|
+
};
|
|
68
|
+
stop(): void;
|
|
69
|
+
/** RMS of the analyser's last window (computed), 0 when silent. */
|
|
70
|
+
level(): number;
|
|
71
|
+
}
|
package/dist/player.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gapless playback on one AudioContext: chunks are scheduled back to back
|
|
3
|
+
* 40 ms ahead, every engine's audio goes through one gain and one
|
|
4
|
+
* analyser, and the analyser is the single output a lip sync driver reads.
|
|
5
|
+
*/
|
|
6
|
+
export class GaplessPlayer {
|
|
7
|
+
ctx;
|
|
8
|
+
analyser;
|
|
9
|
+
gain;
|
|
10
|
+
nextT = 0;
|
|
11
|
+
live = new Set();
|
|
12
|
+
buf;
|
|
13
|
+
lead;
|
|
14
|
+
fadeN;
|
|
15
|
+
constructor(ctx, o = {}) {
|
|
16
|
+
this.ctx = ctx;
|
|
17
|
+
this.lead = o.lead ?? 0.04;
|
|
18
|
+
this.fadeN = o.fade ?? 96;
|
|
19
|
+
this.gain = ctx.createGain();
|
|
20
|
+
this.analyser = ctx.createAnalyser();
|
|
21
|
+
this.analyser.fftSize = 1024;
|
|
22
|
+
this.gain.connect(this.analyser);
|
|
23
|
+
this.analyser.connect(ctx.destination);
|
|
24
|
+
this.buf = new Float32Array(1024);
|
|
25
|
+
}
|
|
26
|
+
/** Context time when the last scheduled chunk ends. */
|
|
27
|
+
get endTime() {
|
|
28
|
+
return this.nextT;
|
|
29
|
+
}
|
|
30
|
+
get playing() {
|
|
31
|
+
return this.ctx.currentTime < this.nextT && this.live.size > 0;
|
|
32
|
+
}
|
|
33
|
+
/** Schedule one chunk. Fades are applied to a copy. Returns its context time span. */
|
|
34
|
+
schedule(samples, rate, fade = {}) {
|
|
35
|
+
const x = Float32Array.from(samples);
|
|
36
|
+
const n = Math.min(this.fadeN, Math.floor(x.length / 2));
|
|
37
|
+
for (let i = 0; i < n; i++) {
|
|
38
|
+
const g = i / n;
|
|
39
|
+
if (fade.in)
|
|
40
|
+
x[i] *= g;
|
|
41
|
+
if (fade.out)
|
|
42
|
+
x[x.length - 1 - i] *= g;
|
|
43
|
+
}
|
|
44
|
+
const b = this.ctx.createBuffer(1, Math.max(1, x.length), rate);
|
|
45
|
+
b.getChannelData(0).set(x);
|
|
46
|
+
const s = this.ctx.createBufferSource();
|
|
47
|
+
s.buffer = b;
|
|
48
|
+
s.connect(this.gain);
|
|
49
|
+
const start = Math.max(this.ctx.currentTime + this.lead, this.nextT);
|
|
50
|
+
const end = start + x.length / rate;
|
|
51
|
+
s.onended = () => this.live.delete(s);
|
|
52
|
+
this.live.add(s);
|
|
53
|
+
s.start(start);
|
|
54
|
+
this.nextT = end;
|
|
55
|
+
return { start, end };
|
|
56
|
+
}
|
|
57
|
+
stop() {
|
|
58
|
+
for (const s of this.live) {
|
|
59
|
+
try {
|
|
60
|
+
s.stop();
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
/* already stopped */
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
this.live.clear();
|
|
67
|
+
this.nextT = 0;
|
|
68
|
+
}
|
|
69
|
+
/** RMS of the analyser's last window (computed), 0 when silent. */
|
|
70
|
+
level() {
|
|
71
|
+
this.analyser.getFloatTimeDomainData(this.buf);
|
|
72
|
+
let s = 0;
|
|
73
|
+
for (const v of this.buf)
|
|
74
|
+
s += v * v;
|
|
75
|
+
return Math.sqrt(s / this.buf.length);
|
|
76
|
+
}
|
|
77
|
+
}
|
package/dist/pocket.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pocket TTS (Kyutai, weights CC-BY-4.0) through a community browser
|
|
3
|
+
* build's inference worker (its Space card says cc-by-4.0). The build is
|
|
4
|
+
* pinned to one commit, and its two scripts are checked against SHA-256
|
|
5
|
+
* values measured at that commit before they run. The worker is fetched as text and
|
|
6
|
+
* rewritten so it runs from file:// and on one thread; every rewrite goes
|
|
7
|
+
* through @hackbuild/ai-env, which reports the ones that matched nothing.
|
|
8
|
+
* An upstream change that moves a patched string is reported as
|
|
9
|
+
* `patch-missed` and, by default, fails the load so the chain moves to the
|
|
10
|
+
* next engine instead of hanging.
|
|
11
|
+
*
|
|
12
|
+
* Worker protocol (as observed in earlier builds): in `load`,
|
|
13
|
+
* `set_voice {voiceName}`, `generate {text, voice}`, `encode_voice {audio}`,
|
|
14
|
+
* `stop`; out `model_status`, `status`, `voices_loaded`, `bundle_loaded
|
|
15
|
+
* {sampleRate}`, `loaded`, `generation_started`, `audio_chunk {data}`,
|
|
16
|
+
* `stream_ended`, `voice_encoded`, `error`.
|
|
17
|
+
*/
|
|
18
|
+
import { type Rewrite, type SpawnOptions } from "@hackbuild/ai-env";
|
|
19
|
+
import type { PcmEngine } from "./types.js";
|
|
20
|
+
/** The community build's commit, pinned 2026-11-23 (the Space's head, modified 2026-04-21). */
|
|
21
|
+
export declare const POCKET_SPACE_COMMIT = "d0c0c79b7712256a32d691c67f20b8ae2e020d00";
|
|
22
|
+
/** The community build at that commit. A caller may pass another base, with its own hashes. */
|
|
23
|
+
export declare const POCKET_SPACE_BASE = "https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/d0c0c79b7712256a32d691c67f20b8ae2e020d00/";
|
|
24
|
+
/** SHA-256 of the build's scripts at POCKET_SPACE_COMMIT (measured 2026-11-23: 33984 and 4020131 bytes). */
|
|
25
|
+
export declare const POCKET_SHA256: {
|
|
26
|
+
readonly worker: "dace0a022e17dffcf60fdb7b86e49facf093f709b352fb306c1d6641ae0f5366";
|
|
27
|
+
readonly sentencepiece: "fc802c6945931e685d82d0f601cda185bb43990870d712119caf5ea74e6e9c56";
|
|
28
|
+
};
|
|
29
|
+
/** Prelude that imports the checked sentencepiece.js text from a Blob URL, falling back to a data: URL. */
|
|
30
|
+
export declare function pocketPrelude(sentencepieceSource: string): string;
|
|
31
|
+
/** The four rewrites, in order: sentencepiece import, chunk gap, one wasm thread with no proxy, absolute relative paths. */
|
|
32
|
+
export declare function pocketRewrites(base: string, chunkGapSec?: number): Rewrite[];
|
|
33
|
+
export interface PocketOptions {
|
|
34
|
+
base?: string;
|
|
35
|
+
/** Fail the load when a rewrite matched nothing. Default true. */
|
|
36
|
+
strictPatches?: boolean;
|
|
37
|
+
chunkGapSec?: number;
|
|
38
|
+
/** How long to wait for `loaded`. Default 420 s (earlier builds' figure). */
|
|
39
|
+
loadTimeoutMs?: number;
|
|
40
|
+
voice?: string;
|
|
41
|
+
/**
|
|
42
|
+
* SHA-256 of inference-worker.js and sentencepiece.js. Default POCKET_SHA256
|
|
43
|
+
* for the default base. With another base and no hashes the scripts run
|
|
44
|
+
* unchecked, which the load reports.
|
|
45
|
+
*/
|
|
46
|
+
sha256?: {
|
|
47
|
+
worker: string;
|
|
48
|
+
sentencepiece: string;
|
|
49
|
+
};
|
|
50
|
+
/** Passed to spawnWorker: worker constructor, fetch, rung order (default classic-blob first). */
|
|
51
|
+
spawn?: Omit<SpawnOptions, "rewrites" | "prelude" | "onMissed">;
|
|
52
|
+
/** Timer for the load timeout. */
|
|
53
|
+
setTimeout?: (fn: () => void, ms: number) => unknown;
|
|
54
|
+
clearTimeout?: (h: unknown) => void;
|
|
55
|
+
}
|
|
56
|
+
export interface PocketEngine extends PcmEngine {
|
|
57
|
+
/** Encode a caller supplied reference (any rate, mono) as voice "custom". Nothing is stored or bundled here. */
|
|
58
|
+
cloneVoice(samples: Float32Array, rate: number): Promise<void>;
|
|
59
|
+
readonly sampleRate: number;
|
|
60
|
+
}
|
|
61
|
+
export declare function pocketEngine(o?: PocketOptions): PocketEngine;
|
package/dist/pocket.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pocket TTS (Kyutai, weights CC-BY-4.0) through a community browser
|
|
3
|
+
* build's inference worker (its Space card says cc-by-4.0). The build is
|
|
4
|
+
* pinned to one commit, and its two scripts are checked against SHA-256
|
|
5
|
+
* values measured at that commit before they run. The worker is fetched as text and
|
|
6
|
+
* rewritten so it runs from file:// and on one thread; every rewrite goes
|
|
7
|
+
* through @hackbuild/ai-env, which reports the ones that matched nothing.
|
|
8
|
+
* An upstream change that moves a patched string is reported as
|
|
9
|
+
* `patch-missed` and, by default, fails the load so the chain moves to the
|
|
10
|
+
* next engine instead of hanging.
|
|
11
|
+
*
|
|
12
|
+
* Worker protocol (as observed in earlier builds): in `load`,
|
|
13
|
+
* `set_voice {voiceName}`, `generate {text, voice}`, `encode_voice {audio}`,
|
|
14
|
+
* `stop`; out `model_status`, `status`, `voices_loaded`, `bundle_loaded
|
|
15
|
+
* {sampleRate}`, `loaded`, `generation_started`, `audio_chunk {data}`,
|
|
16
|
+
* `stream_ended`, `voice_encoded`, `error`.
|
|
17
|
+
*/
|
|
18
|
+
import { sha256Text, spawnWorker } from "@hackbuild/ai-env";
|
|
19
|
+
import { prepareClone } from "./clone.js";
|
|
20
|
+
/** The community build's commit, pinned 2026-11-23 (the Space's head, modified 2026-04-21). */
|
|
21
|
+
export const POCKET_SPACE_COMMIT = "d0c0c79b7712256a32d691c67f20b8ae2e020d00";
|
|
22
|
+
/** The community build at that commit. A caller may pass another base, with its own hashes. */
|
|
23
|
+
export const POCKET_SPACE_BASE = `https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/${POCKET_SPACE_COMMIT}/`;
|
|
24
|
+
/** SHA-256 of the build's scripts at POCKET_SPACE_COMMIT (measured 2026-11-23: 33984 and 4020131 bytes). */
|
|
25
|
+
export const POCKET_SHA256 = {
|
|
26
|
+
worker: "dace0a022e17dffcf60fdb7b86e49facf093f709b352fb306c1d6641ae0f5366",
|
|
27
|
+
sentencepiece: "fc802c6945931e685d82d0f601cda185bb43990870d712119caf5ea74e6e9c56",
|
|
28
|
+
};
|
|
29
|
+
/** Prelude that imports the checked sentencepiece.js text from a Blob URL, falling back to a data: URL. */
|
|
30
|
+
export function pocketPrelude(sentencepieceSource) {
|
|
31
|
+
return [
|
|
32
|
+
"self.__hbSentencepiece = async () => {",
|
|
33
|
+
` const t = ${JSON.stringify(sentencepieceSource)};`,
|
|
34
|
+
" try { return await import(URL.createObjectURL(new Blob([t], { type: 'text/javascript' }))); }",
|
|
35
|
+
" catch (e) { const u = new TextEncoder().encode(t); let s = ''; for (let i = 0; i < u.length; i += 32768) s += String.fromCharCode.apply(null, u.subarray(i, i + 32768));",
|
|
36
|
+
" return await import('data:text/javascript;base64,' + btoa(s)); }",
|
|
37
|
+
"};",
|
|
38
|
+
].join("\n");
|
|
39
|
+
}
|
|
40
|
+
/** The four rewrites, in order: sentencepiece import, chunk gap, one wasm thread with no proxy, absolute relative paths. */
|
|
41
|
+
export function pocketRewrites(base, chunkGapSec = 0.1) {
|
|
42
|
+
return [
|
|
43
|
+
[/import\(\s*(["'`])\.\/sentencepiece\.js(?:\?[^"'`]*)?\1\s*\)/, "self.__hbSentencepiece()"],
|
|
44
|
+
[/CHUNK_GAP_SEC\s*=\s*[\d.]+/, `CHUNK_GAP_SEC = ${chunkGapSec}`],
|
|
45
|
+
[/(\w+)\.env\.wasm\.wasmPaths\s*=/, "$1.env.wasm.numThreads = 1; $1.env.wasm.proxy = false; $1.env.wasm.wasmPaths ="],
|
|
46
|
+
[/(["'`])\.\/(?!\.)/, `$1${base}`],
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
export function pocketEngine(o = {}) {
|
|
50
|
+
const base = o.base ?? POCKET_SPACE_BASE;
|
|
51
|
+
const st = o.setTimeout ?? ((fn, ms) => setTimeout(fn, ms));
|
|
52
|
+
const ct = o.clearTimeout ?? ((h) => clearTimeout(h));
|
|
53
|
+
let w = null;
|
|
54
|
+
let voices = [];
|
|
55
|
+
let voice = o.voice ?? "";
|
|
56
|
+
let sr = 24000;
|
|
57
|
+
let sink = null;
|
|
58
|
+
let busy = Promise.resolve();
|
|
59
|
+
const engine = {
|
|
60
|
+
kind: "pcm",
|
|
61
|
+
id: "pocket",
|
|
62
|
+
licence: "Pocket TTS weights CC-BY-4.0 (Kyutai); the browser build's scripts per its Space card, cc-by-4.0",
|
|
63
|
+
get sampleRate() {
|
|
64
|
+
return sr;
|
|
65
|
+
},
|
|
66
|
+
async load(ctx) {
|
|
67
|
+
if (w)
|
|
68
|
+
return;
|
|
69
|
+
const say = (kind, text, progress) => ctx.onStatus?.({ engine: "pocket", kind, text, ...(progress !== undefined ? { progress } : {}) });
|
|
70
|
+
say("licence", "pocket tts weights, cc-by-4.0, kyutai");
|
|
71
|
+
const sums = o.sha256 ?? (base === POCKET_SPACE_BASE ? POCKET_SHA256 : null);
|
|
72
|
+
if (!sums)
|
|
73
|
+
say("loading", "pocket scripts from a custom base run unchecked; pass sha256 to pin them");
|
|
74
|
+
const f = o.spawn?.fetch ?? globalThis.fetch.bind(globalThis);
|
|
75
|
+
const spUrl = new URL("sentencepiece.js", base).href;
|
|
76
|
+
const spRes = await f(spUrl);
|
|
77
|
+
if (!spRes.ok)
|
|
78
|
+
throw new Error(`sentencepiece.js http ${spRes.status}`);
|
|
79
|
+
const sp = await spRes.text();
|
|
80
|
+
if (sums) {
|
|
81
|
+
const got = await sha256Text(sp);
|
|
82
|
+
if (got !== sums.sentencepiece)
|
|
83
|
+
throw new Error(`sentencepiece.js sha256 ${got}, expected ${sums.sentencepiece}`);
|
|
84
|
+
}
|
|
85
|
+
let missed = [];
|
|
86
|
+
const spawned = await spawnWorker({ url: new URL("inference-worker.js", base).href, ...(sums ? { sha256: sums.worker } : {}) }, {
|
|
87
|
+
prefer: ["classic-blob", "module-blob"],
|
|
88
|
+
...o.spawn,
|
|
89
|
+
prelude: pocketPrelude(sp),
|
|
90
|
+
rewrites: pocketRewrites(base, o.chunkGapSec),
|
|
91
|
+
onMissed: (m) => (missed = m),
|
|
92
|
+
});
|
|
93
|
+
if (missed.length) {
|
|
94
|
+
say("patch-missed", `worker patches matched nothing: ${missed.map((m) => m.pattern).join(", ")}`);
|
|
95
|
+
if (o.strictPatches !== false) {
|
|
96
|
+
spawned.worker.terminate();
|
|
97
|
+
throw new Error("pocket worker changed upstream; patches did not match");
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const worker = spawned.worker;
|
|
101
|
+
// a load that times out or errors terminates its worker, so a retry does not leave one downloading
|
|
102
|
+
const fail = (err, reject) => {
|
|
103
|
+
worker.removeEventListener("message", on);
|
|
104
|
+
worker.terminate();
|
|
105
|
+
reject(err);
|
|
106
|
+
};
|
|
107
|
+
let on = () => { };
|
|
108
|
+
await new Promise((resolve, reject) => {
|
|
109
|
+
const to = st(() => fail(new Error(`pocket did not load in ${(o.loadTimeoutMs ?? 420000) / 1000} s`), reject), o.loadTimeoutMs ?? 420000);
|
|
110
|
+
on = (ev) => {
|
|
111
|
+
const m = (ev.data ?? {});
|
|
112
|
+
if (m.type === "model_status" || m.type === "status")
|
|
113
|
+
say("loading", String(m.text ?? m.status ?? "loading").slice(0, 40));
|
|
114
|
+
else if (m.type === "voices_loaded") {
|
|
115
|
+
voices = (m.voices ?? []).map((v) => (typeof v === "string" ? v : String(v.name ?? v.id)));
|
|
116
|
+
voice ||= m.defaultVoice ?? voices[0] ?? "";
|
|
117
|
+
}
|
|
118
|
+
else if (m.type === "bundle_loaded" && m.sampleRate)
|
|
119
|
+
sr = m.sampleRate;
|
|
120
|
+
else if (m.type === "loaded") {
|
|
121
|
+
ct(to);
|
|
122
|
+
worker.removeEventListener("message", on);
|
|
123
|
+
resolve();
|
|
124
|
+
}
|
|
125
|
+
else if (m.type === "error") {
|
|
126
|
+
ct(to);
|
|
127
|
+
fail(new Error(m.error ?? "pocket worker error"), reject);
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
worker.addEventListener("message", on);
|
|
131
|
+
worker.postMessage({ type: "load" });
|
|
132
|
+
});
|
|
133
|
+
worker.addEventListener("message", (ev) => sink?.((ev.data ?? {})));
|
|
134
|
+
w = worker;
|
|
135
|
+
if (voice)
|
|
136
|
+
worker.postMessage({ type: "set_voice", data: { voiceName: voice } });
|
|
137
|
+
say("ready", `pocket ready on ${spawned.rung}`);
|
|
138
|
+
},
|
|
139
|
+
synth(text, cfg, signal) {
|
|
140
|
+
const worker = w;
|
|
141
|
+
if (!worker)
|
|
142
|
+
throw new Error("pocket is not loaded");
|
|
143
|
+
return {
|
|
144
|
+
[Symbol.asyncIterator]: async function* () {
|
|
145
|
+
// one generate at a time
|
|
146
|
+
let release;
|
|
147
|
+
const prev = busy;
|
|
148
|
+
busy = new Promise((r) => (release = r));
|
|
149
|
+
await prev;
|
|
150
|
+
const queue = [];
|
|
151
|
+
let wake = null;
|
|
152
|
+
sink = (m) => {
|
|
153
|
+
queue.push(m);
|
|
154
|
+
wake?.();
|
|
155
|
+
};
|
|
156
|
+
const onAbort = () => {
|
|
157
|
+
worker.postMessage({ type: "stop" });
|
|
158
|
+
wake?.();
|
|
159
|
+
};
|
|
160
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
161
|
+
try {
|
|
162
|
+
const v = cfg.voice ?? voice;
|
|
163
|
+
worker.postMessage({ type: "generate", data: { text, voice: v } });
|
|
164
|
+
for (;;) {
|
|
165
|
+
if (signal.aborted)
|
|
166
|
+
return;
|
|
167
|
+
const m = queue.shift();
|
|
168
|
+
if (!m) {
|
|
169
|
+
await new Promise((r) => (wake = r));
|
|
170
|
+
wake = null;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
if (m.type === "audio_chunk" && m.data instanceof Float32Array)
|
|
174
|
+
yield { samples: m.data, sampleRate: sr };
|
|
175
|
+
else if (m.type === "stream_ended")
|
|
176
|
+
return;
|
|
177
|
+
else if (m.type === "error")
|
|
178
|
+
throw new Error(m.error ?? "pocket generate error");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
finally {
|
|
182
|
+
signal.removeEventListener("abort", onAbort);
|
|
183
|
+
sink = null;
|
|
184
|
+
release();
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
},
|
|
189
|
+
async cloneVoice(samples, rate) {
|
|
190
|
+
const worker = w;
|
|
191
|
+
if (!worker)
|
|
192
|
+
throw new Error("pocket is not loaded");
|
|
193
|
+
const audio = prepareClone(samples, rate, { rate: 24000 });
|
|
194
|
+
// the worker has one message sink; wait for a running generate to finish first
|
|
195
|
+
let release;
|
|
196
|
+
const prev = busy;
|
|
197
|
+
busy = new Promise((r) => (release = r));
|
|
198
|
+
await prev;
|
|
199
|
+
try {
|
|
200
|
+
await new Promise((resolve, reject) => {
|
|
201
|
+
sink = (m) => {
|
|
202
|
+
if (m.type === "voice_encoded")
|
|
203
|
+
resolve();
|
|
204
|
+
else if (m.type === "error")
|
|
205
|
+
reject(new Error(m.error ?? "voice encode error"));
|
|
206
|
+
};
|
|
207
|
+
worker.postMessage({ type: "encode_voice", data: { audio } });
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
sink = null;
|
|
212
|
+
release();
|
|
213
|
+
}
|
|
214
|
+
voice = "custom";
|
|
215
|
+
worker.postMessage({ type: "set_voice", data: { voiceName: "custom" } });
|
|
216
|
+
},
|
|
217
|
+
voices: () => voices,
|
|
218
|
+
dispose() {
|
|
219
|
+
w?.terminate();
|
|
220
|
+
w = null;
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
return engine;
|
|
224
|
+
}
|
package/dist/records.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Voice records for pickers and the models registry. Sizes are inferred
|
|
3
|
+
* from the model repos; licences are the model cards' as of 2026-11-22.
|
|
4
|
+
*/
|
|
5
|
+
export const SPEAK_RECORDS = [
|
|
6
|
+
{
|
|
7
|
+
id: "kokoro-82m",
|
|
8
|
+
label: "kokoro 82m",
|
|
9
|
+
provides: ["speak"],
|
|
10
|
+
provider: "kokoro-js",
|
|
11
|
+
source: { modelId: "onnx-community/Kokoro-82M-v1.0-ONNX" },
|
|
12
|
+
sizeMB: 330,
|
|
13
|
+
sizeSource: "inferred",
|
|
14
|
+
ladder: [
|
|
15
|
+
{ device: "webgpu", dtype: "fp32", needs: ["http"] },
|
|
16
|
+
{ device: "wasm", dtype: "q8" },
|
|
17
|
+
],
|
|
18
|
+
licence: "Apache-2.0 (weights); the kokoro-js runtime phonemizes with eSpeak NG, GPL-3.0-or-later, loaded at run time and opt in",
|
|
19
|
+
commercial: true,
|
|
20
|
+
place: "cpu-worker",
|
|
21
|
+
runtime: "kokoro-js@1.2.1",
|
|
22
|
+
notes: ["webgpu with q8 gave garbled audio in an earlier build", "fp32 weights (about 330 MB, inferred) do not cache on file://, so webgpu needs http"],
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
id: "pocket-tts",
|
|
26
|
+
label: "pocket tts",
|
|
27
|
+
provides: ["speak"],
|
|
28
|
+
provider: "pocket-worker",
|
|
29
|
+
source: { url: "https://huggingface.co/spaces/KevinAHM/pocket-tts-web/resolve/d0c0c79b7712256a32d691c67f20b8ae2e020d00/", repo: "kyutai/pocket-tts", revision: "d0c0c79b7712256a32d691c67f20b8ae2e020d00" },
|
|
30
|
+
sizeMB: null,
|
|
31
|
+
sizeSource: "unknown",
|
|
32
|
+
ladder: [{ device: "wasm" }],
|
|
33
|
+
licence: "CC-BY-4.0 (weights), MIT (code)",
|
|
34
|
+
commercial: true,
|
|
35
|
+
place: "cpu-worker",
|
|
36
|
+
notes: ["zero shot clone from a caller supplied reference", "community browser build; its worker is patched at load and patches are reported when they stop matching"],
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
id: "bellows-voice",
|
|
40
|
+
label: "bellows voice",
|
|
41
|
+
provides: ["speak"],
|
|
42
|
+
provider: "bellows-voice",
|
|
43
|
+
source: { repo: "virgilvox/bellows-voice" },
|
|
44
|
+
sizeMB: 0,
|
|
45
|
+
sizeSource: "vendor",
|
|
46
|
+
ladder: [{ device: "wasm" }],
|
|
47
|
+
licence: "none, no weights (code MIT)",
|
|
48
|
+
commercial: true,
|
|
49
|
+
place: "cpu-worker",
|
|
50
|
+
runtime: "bellows-voice@0.8.0 on bellowsjs@0.5.0",
|
|
51
|
+
notes: ["a physical model of the vocal tract, no download beyond its code (about 65 KB gzipped, vendor)", "deterministic per seed; the seed is drawn once from the injected rng", "exact phoneme times; no word times"],
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
id: "web-speech",
|
|
55
|
+
label: "system voice",
|
|
56
|
+
provides: ["speak"],
|
|
57
|
+
provider: "system",
|
|
58
|
+
source: {},
|
|
59
|
+
sizeMB: 0,
|
|
60
|
+
sizeSource: "vendor",
|
|
61
|
+
ladder: [{ device: "browser" }],
|
|
62
|
+
licence: "system voices, the platform's terms",
|
|
63
|
+
commercial: "unknown",
|
|
64
|
+
place: "main",
|
|
65
|
+
notes: ["some browsers send text to a server for system voices"],
|
|
66
|
+
},
|
|
67
|
+
];
|