File size: 5,154 Bytes
4a58e48 daa9f5e 4a58e48 daa9f5e 4a58e48 daa9f5e 4a58e48 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | /// <reference lib="webworker" />
// Kokoro-82M text-to-speech, running fully on this device (WebGPU or WASM) inside a Web Worker.
import { env } from '@huggingface/transformers';
import { KokoroTTS } from 'kokoro-js';
import { isSilent, speechVariants } from './text';
const MODEL = 'onnx-community/Kokoro-82M-v1.0-ONNX';
const HF = `https://huggingface.co/${MODEL}/resolve/main/`;
/**
* Self-hosting: every Kokoro file (model, tokenizer, voices) is first requested from this app's own
* host under ./models/kokoro/, then from Hugging Face. Run `npm run fetch-model` to fill that folder.
*/
let localBase = '';
const missingLocal = new Set<string>();
const realFetch = self.fetch.bind(self);
self.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
if (localBase && url.startsWith(HF)) {
const rel = url.slice(HF.length).split('?')[0];
if (!missingLocal.has(rel)) {
try {
const r = await realFetch(localBase + rel, { ...init, cache: 'no-cache' });
const type = r.headers.get('content-type') || '';
if (r.ok && !type.includes('text/html')) return r;
} catch {
/* fall through to Hugging Face */
}
missingLocal.add(rel);
}
}
return realFetch(input as any, init);
}) as typeof fetch;
type InMsg =
| { type: 'load'; device: 'webgpu' | 'wasm'; ortBase: string; modelBase: string; threads: number; dtype?: string }
| { type: 'gen'; id: number; text: string; voice: string; priority?: boolean };
let tts: KokoroTTS | null = null;
let loading: Promise<void> | null = null;
const queue: Extract<InMsg, { type: 'gen' }>[] = [];
let busy = false;
function post(m: any, t?: Transferable[]) {
(self as unknown as DedicatedWorkerGlobalScope).postMessage(m, t || []);
}
async function load(device: 'webgpu' | 'wasm', dtypeOverride?: string) {
const files = new Map<string, { loaded: number; total: number }>();
const t0 = performance.now();
const progress_callback = (p: any) => {
if (p.status === 'progress' && p.file) {
files.set(p.file, { loaded: p.loaded || 0, total: p.total || 0 });
let loaded = 0,
total = 0;
for (const f of files.values()) {
loaded += f.loaded;
total += f.total;
}
post({ type: 'progress', loaded, total });
}
};
try {
tts = await KokoroTTS.from_pretrained(MODEL, {
dtype: (dtypeOverride || (device === 'webgpu' ? 'fp32' : 'fp16')) as any,
device,
progress_callback,
});
} catch (e) {
if (device === 'webgpu') {
// fall back to WASM if the GPU path fails on this device
post({ type: 'fallback', reason: String((e as Error)?.message || e) });
tts = await KokoroTTS.from_pretrained(MODEL, { dtype: 'fp16', device: 'wasm', progress_callback });
device = 'wasm';
} else throw e;
}
post({ type: 'ready', device, ms: Math.round(performance.now() - t0) });
}
async function pump() {
if (busy) return;
busy = true;
try {
while (queue.length) {
const job = queue.shift()!;
let t0 = performance.now();
try {
let out: any = await tts!.generate(job.text, { voice: job.voice as any });
// some inputs come out as pure silence: retry with rewordings that sound the same
for (const alt of isSilent(out.audio) ? speechVariants(job.text) : []) {
const t1 = performance.now();
const again: any = await tts!.generate(alt, { voice: job.voice as any });
if (!isSilent(again.audio)) {
out = again;
t0 = t1; // the speed measurement counts the generation that is used, not the retries
break;
}
}
const pcm: Float32Array = out.audio;
post({ type: 'audio', id: job.id, pcm, rate: out.sampling_rate, ms: Math.round(performance.now() - t0) }, [pcm.buffer]);
} catch (e) {
post({ type: 'error', id: job.id, message: String((e as Error)?.message || e) });
}
}
} finally {
busy = false;
}
}
self.onmessage = async (ev: MessageEvent<InMsg | { type: 'cancel'; keep: number[] }>) => {
const m = ev.data;
if (m.type === 'load') {
if (!loading) {
// Serve the ONNX runtime from our own origin so the app keeps working offline.
(env.backends.onnx as any).wasm.wasmPaths = m.ortBase;
(env.backends.onnx as any).wasm.numThreads = m.threads;
localBase = m.modelBase;
loading = load(m.device, m.dtype).catch((e) => {
loading = null;
post({ type: 'loadError', message: String((e as Error)?.message || e) });
});
}
return;
}
if (m.type === 'gen') {
// the sentence the listener is waiting for jumps the queue
if (m.priority) queue.unshift(m);
else queue.push(m);
if (loading) await loading;
if (tts) void pump();
return;
}
if (m.type === 'cancel') {
// drop queued jobs that are no longer wanted (user jumped elsewhere)
const keep = new Set(m.keep);
for (let i = queue.length - 1; i >= 0; i--) if (!keep.has(queue[i].id)) queue.splice(i, 1);
}
};
|