/// // 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(); 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 | null = null; const queue: Extract[] = []; 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(); 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) => { 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); } };