kale-tts-1 / ttsWorker.js
NERDDISCO's picture
kale-tts-1
624a22c
Raw History Blame Contribute Delete
5.92 kB
// The model in its own worker: loading, the text front end and every synthesis run happen here, so the page (and the waterfall)
// never waits on them. One worker per loaded model; the page keeps it for switching back (desktops), or ends it to free everything
// (onnxruntime, GPU memory) at once (phones).
import { KaleTTS } from "./js/kale-tts.mjs";
let tts = null, chain = Promise.resolve();
// the model graph's download, as it arrives (the JS API fetches it): bytes so far and the total, for the page's progress bar
let report = null, cachedHit = null;
// The graphs go into the browser's Cache API once downloaded, so a reload (or this model again after the page dropped its
// worker) doesn't fetch them again. The space's file links are signed per request with "no-store", so the plain HTTP cache can't
// keep them. Each entry is keyed by the file's sha256 (the page's MODELS table): a new build of a graph is a new key, and bytes that
// don't match the table are used but never stored.
const CACHE = "kale-tts-1-graphs";
let shas = {}; // file name in the model folder -> sha256
const hex = (b) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("");
const realFetch = self.fetch.bind(self);
self.fetch = async (input, init) => {
const url = String(input?.url ?? input);
if (!/\.onnx(\?|$)/.test(url)) return realFetch(input, init);
const path = new URL(url, location.href).href.split("?")[0], sha = shas[path.split("/").pop()];
const key = sha ? `${path}?sha256=${sha}` : null;
let cache = null; try { cache = key && self.caches ? await caches.open(CACHE) : null; } catch { cache = null; }
if (cache) { const hit = await cache.match(key).catch(() => null); if (hit) { cachedHit?.(); return hit; } }
const r = await realFetch(input, init);
if (!r.ok || !r.body) return r;
const total = Number(r.headers.get("content-length")) || 0, tell = report; let got = 0;
if (!cache) { // no cache here (or no sha for this file): stream it through, as before
if (!tell) return r;
const body = r.body.pipeThrough(new TransformStream({ transform(chunk, c) { got += chunk.byteLength; tell(got, total); c.enqueue(chunk); } }));
return new Response(body, { status: r.status, statusText: r.statusText, headers: r.headers });
}
// read it whole (the JS API reads it into one buffer anyway), check it, store it, hand it on
const parts = [], reader = r.body.getReader();
for (;;) { const { done, value } = await reader.read(); if (done) break; parts.push(value); got += value.byteLength; tell?.(got, total); }
const buf = new Uint8Array(got); let at = 0; for (const p of parts) { buf.set(p, at); at += p.byteLength; } parts.length = 0;
const headers = { "content-type": "application/octet-stream", "content-length": String(got) };
try {
if (hex(await crypto.subtle.digest("SHA-256", buf)) === sha) {
await cache.put(key, new Response(buf, { headers }));
for (const old of await cache.keys()) if (old.url.split("?")[0] === path && old.url !== key) await cache.delete(old);
} else console.warn(`${path}: sha256 differs from the page's table, not cached`);
} catch (e) { console.warn("graph not cached:", e?.message ?? e); } // a full or blocked storage: it still runs
return new Response(buf, { status: 200, headers });
};
const cancelled = new Set(), active = new Set();
onmessage = async ({ data: m }) => {
const send = (x) => postMessage({ ...x, id: m.id });
try {
if (m.type === "load") {
const ort = await import(m.b === "webgpu" ? "./ort/ort.webgpu.min.mjs" : "./ort/ort.wasm.min.mjs");
ort.env.wasm.wasmPaths = new URL("./ort/", location.href).href; ort.env.logLevel = "error"; ort.env.wasm.numThreads = m.threads;
// ["webgpu"] keeps the LSTM layers on the CPU (the release API's own setting)
let last = 0, done = false;
report = (got, total) => { // at most every 100 ms, and once when the download is complete
const now = performance.now(), full = total && got >= total;
if (done || (!full && now - last < 100)) return; last = now; done = full;
send({ type: "progress", got, total });
if (full) send({ type: "status", text: m.b === "webgpu" ? "loading into WebGPU…" : "loading into the CPU…" });
};
shas = m.shas ?? {};
cachedHit = () => { done = true; send({ type: "status", text: m.b === "webgpu" ? "loading into WebGPU…" : "loading into the CPU…" }); };
tts = await KaleTTS.load(m.name, { ort, graph: m.graph, executionProviders: [m.b], sessionOptions: m.sessionOptions });
report = null; cachedHit = null;
send({ type: "status", text: "getting the voices ready…" });
await tts.preload();
await tts.speak("Hello there.", { voice: tts.voices[0].id }); // warm up (and the WebGPU test run)
send({ type: "loaded", graph: tts.backend.graph, threads: ort.env.wasm.numThreads,
voices: tts.voices.map(({ id, name, order, accent, description }) => ({ id, name, order, accent, description })) });
} else if (m.type === "stream") {
// one run at a time on the session: a new request stops the one before (between chunks) and waits for it. Several runs
// at once on one WebGPU session piled up GPU work and memory when voices were switched quickly.
for (const id of active) cancelled.add(id);
active.add(m.id);
const run = chain.then(async () => {
try {
if (cancelled.has(m.id)) return;
for await (const ch of tts.stream(m.text, { voice: m.voice })) { if (cancelled.has(m.id)) break; send({ type: "chunk", audio: ch.audio }); }
} finally { active.delete(m.id); cancelled.delete(m.id); send({ type: "end" }); }
});
chain = run.catch(() => {});
await run;
} else if (m.type === "cancel") cancelled.add(m.id);
} catch (e) { send({ type: "error", message: e?.message ?? String(e) }); }
};