const N_FFT = 1024, HOP = 256, BINS = 513, PAD = N_FFT / 2, R = 0.9973; const PYODIDE_URL = "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/"; const WASM_PATHS = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.20.1/dist/"; const V = "?v=7"; const PKG_URLS = ["g2p/__init__.py", "g2p/english.py", "g2p/oov.py", "g2p/frontend.py", "g2p/g2p_data/us_gold.json", "g2p/g2p_data/us_silver.json", "g2p/g2p_data/oov_bart_en_us.npz"].map(u => u + V); const el = id => document.getElementById(id); const status = t => { el("status").textContent = t; }; const barEl = el("bar"); let barCur = 0, barTarget = 0, barTimer = null, idleTimer = null, boost = false; function setp(p) { if (p > barTarget) barTarget = p; if (!barTimer) barTimer = setInterval(tickBar, 120); } function setpDone() { boost = true; setp(100); } function tickBar() { const dt = 0.12; const gap = barTarget - barCur; if (Math.abs(gap) < 0.05) return; const rate = boost ? 45 : barCur < 60 ? 22 : 16; const step = Math.abs(gap) < rate * dt * 2 ? gap : Math.sign(gap) * rate * dt; barCur += step; barEl.style.width = Math.max(0, Math.min(100, barCur)) + "%"; if (barTarget >= 100 && barCur >= 99.9 && !idleTimer) { idleTimer = setTimeout(() => { barCur = 0; barTarget = 0; barEl.style.width = "0%"; clearInterval(barTimer); barTimer = null; idleTimer = null; }, 2400); } } function barReset() { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } boost = false; barCur = 0; barTarget = 0; barEl.style.width = "0%"; if (!barTimer) barTimer = setInterval(tickBar, 120); } let pyodide = null, sessDur = null, sessAc = null, sessDec = null, actx = null; function hann() { const w = new Float64Array(N_FFT); for (let k = 0; k < N_FFT; k++) w[k] = 0.5 * (1 - Math.cos(2 * Math.PI * k / N_FFT)); return w; } const WIN = hann(); function fft(re, im, n, inverse) { for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; } } for (let len = 2; len <= n; len <<= 1) { const ang = 2 * Math.PI / len * (inverse ? 1 : -1); const wr = Math.cos(ang), wi = Math.sin(ang); for (let i = 0; i < n; i += len) { let cwr = 1, cwi = 0; for (let j = 0; j < len / 2; j++) { const ur = re[i + j], ui = im[i + j]; const vr = re[i + j + len / 2] * cwr - im[i + j + len / 2] * cwi; const vi = re[i + j + len / 2] * cwi + im[i + j + len / 2] * cwr; re[i + j] = ur + vr; im[i + j] = ui + vi; re[i + j + len / 2] = ur - vr; im[i + j + len / 2] = ui - vi; const nwr = cwr * wr - cwi * wi; cwi = cwr * wi + cwi * wr; cwr = nwr; } } } if (inverse) for (let i = 0; i < n; i++) { re[i] /= n; im[i] /= n; } } function irfftFrames(spec, T) { const frames = new Float64Array(T * N_FFT); const re = new Float64Array(N_FFT), im = new Float64Array(N_FFT); for (let i = 0; i < T; i++) { re.fill(0); im.fill(0); re[0] = spec[(0 * T + i) * 2]; for (let k = 1; k < BINS - 1; k++) { const cr = spec[(k * T + i) * 2], ci = spec[(k * T + i) * 2 + 1]; re[k] = cr; im[k] = ci; re[N_FFT - k] = cr; im[N_FFT - k] = -ci; } re[N_FFT / 2] = spec[((BINS - 1) * T + i) * 2]; fft(re, im, N_FFT, true); frames.set(re.subarray(0, N_FFT), i * N_FFT); } return frames; } function istft(spec, T) { const frames = irfftFrames(spec, T); const length = (T - 1) * HOP + N_FFT; const out = new Float64Array(length), norm = new Float64Array(length); for (let i = 0; i < T; i++) { const src = i * N_FFT, dst = i * HOP; for (let k = 0; k < N_FFT; k++) { out[dst + k] += frames[src + k] * WIN[k]; norm[dst + k] += WIN[k] * WIN[k]; } } const samples = length - N_FFT, wav = new Float64Array(samples); for (let i = 0; i < samples; i++) wav[i] = norm[PAD + i] > 1e-11 ? out[PAD + i] / norm[PAD + i] : 0.0; return wav; } function dcBlock(x) { let s = 0.0; const out = new Float64Array(x.length); for (let i = 0; i < x.length; i++) { out[i] = x[i] + (R - 1) * s; s = R * s + x[i]; } return out; } function linspace(n) { const a = new Float32Array(n); if (n > 1) { const d = n - 1; for (let i = 0; i < n; i++) a[i] = i / d; } return a; } async function fetchBytes(url) { const r = await fetch(url); if (!r.ok) throw new Error("missing file " + url); const total = Number(r.headers.get("content-length")) || 0; if (!r.body || !total) return new Uint8Array(await r.arrayBuffer()); const reader = r.body.getReader(); const chunks = []; let got = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); got += value.length; setp(34 + 24 * (got / total)); } const out = new Uint8Array(got); let o = 0; for (const c of chunks) { out.set(c, o); o += c.length; } return out; } async function ensurePyodide() { if (pyodide) return pyodide; status("downloading python runtime…"); setp(10); pyodide = await loadPyodide({ indexURL: PYODIDE_URL }); status("loading numpy…"); setp(30); await pyodide.loadPackage("numpy"); pyodide.FS.mkdirTree("/pkg/g2p/g2p_data"); for (const p of PKG_URLS) { status("downloading dictionaries…"); const data = await fetchBytes(p); pyodide.FS.writeFile("/pkg/" + p.split("?")[0], data); setp(58); } status("warming up…"); setp(62); pyodide.runPython('import sys; sys.path.insert(0, "/pkg"); import g2p'); return pyodide; } async function ensureModels() { if (sessDec) return; status("loading model…"); setp(70); ort.env.wasm.wasmPaths = WASM_PATHS; const opt = { executionProviders: ["wasm"] }; sessDur = await ort.InferenceSession.create("onnx/duration.onnx" + V, opt); sessAc = await ort.InferenceSession.create("onnx/acoustic.onnx" + V, opt); sessDec = await ort.InferenceSession.create("onnx/decoder.onnx" + V, opt); setp(86); } async function phonemize(text) { const py = await ensurePyodide(); py.globals.set("TXT", text); const js = py.runPython('import json; json.dumps(g2p.phonemize(TXT)[0])'); return JSON.parse(js); } async function phonemizePieces(text) { let pieces; try { pieces = [{ ids: await phonemize(text), text }]; } catch (e) { if (!/maximum is 207/.test(String(e))) throw e; const words = text.trim().split(/\s+/); if (words.length < 2) { const t = text.trim(); const mid = Math.ceil(t.length / 2); return (await phonemizePieces(t.slice(0, mid))).concat(await phonemizePieces(t.slice(mid))); } const half = Math.ceil(words.length / 2); return (await phonemizePieces(words.slice(0, half).join(" "))).concat( await phonemizePieces(words.slice(half).join(" "))); } if (await framesOf(pieces[0].ids) > BUDGET) { const words = pieces[0].text.trim().split(/\s+/); if (words.length >= 2) { const half = Math.ceil(words.length / 2); return (await phonemizePieces(words.slice(0, half).join(" "))).concat( await phonemizePieces(words.slice(half).join(" "))); } } return pieces; } async function framesOf(ids) { const n = ids.length; if (!n) return 0; const bi = new BigInt64Array(ids.map(BigInt)); const pos = linspace(n); const feats = new Float32Array(3 * n); for (let i = 0; i < n; i++) { feats[i] = pos[i]; feats[n + i] = Math.log1p(n) / Math.log1p(207); feats[2 * n + i] = 1; } const logD = (await sessDur.run({ ids: new ort.Tensor("int64", bi, [n]), feats: new ort.Tensor("float32", feats, [3, n]) }))["log_d"].data; let s = 0; for (let i = 0; i < n; i++) { let d = Math.round(Math.exp(logD[i])); d = Math.max(1, Math.min(80, d)); s += d; } return s; } async function synthSingle(ids) { const n = ids.length; const bi = new BigInt64Array(ids.map(BigInt)); const pos = linspace(n); const feats = new Float32Array(3 * n); for (let i = 0; i < n; i++) { feats[i] = pos[i]; feats[n + i] = Math.log1p(n) / Math.log1p(207); feats[2 * n + i] = 1; } const logD = (await sessDur.run({ ids: new ort.Tensor("int64", bi, [n]), feats: new ort.Tensor("float32", feats, [3, n]) }))["log_d"].data; const durs = new BigInt64Array(n); let T = 0; for (let i = 0; i < n; i++) { let d = Math.round(Math.exp(logD[i])); d = Math.max(1, Math.min(80, d)); durs[i] = BigInt(d); T += d; } const NT = Number(T); const idx = new BigInt64Array(NT); const dursJs = Array.from(durs, Number); let acc = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < dursJs[i]; j++) idx[acc++] = BigInt(i); } const framePos = linspace(NT), tokenPosF = new Float32Array(NT), durP = new Float32Array(NT); const maxd = Math.max(Math.max(...dursJs), 1); const hintTok = new Float32Array(n); for (let i = 0; i < n; i++) hintTok[i] = Math.log1p(dursJs[i]) / Math.log1p(maxd); for (let i = 0; i < NT; i++) { tokenPosF[i] = pos[Number(idx[i])]; const tok = Number(idx[i]); let st = 0; for (let j = 0; j < tok; j++) st += dursJs[j]; const d = dursJs[tok]; durP[i] = d > 1 ? (i - st) / (d - 1) : 0; } const mel = (await sessAc.run({ ids: new ort.Tensor("int64", bi, [n]), token_pos: new ort.Tensor("float32", pos, [n]), dur_hint: new ort.Tensor("float32", hintTok, [n]), idx: new ort.Tensor("int64", idx, [NT]), frame_pos: new ort.Tensor("float32", framePos, [NT]), token_pos_f: new ort.Tensor("float32", tokenPosF, [NT]), dur_pos: new ort.Tensor("float32", durP, [NT]) }))["mel"].data; const noise = new Float32Array(4 * NT); const spec = (await sessDec.run({ mel: new ort.Tensor("float32", mel.slice(0), [100, NT]), noise: new ort.Tensor("float32", noise, [4, NT]) }))["spec"].data; return dcBlock(istft(spec, NT)); } const BUDGET = 2000, GAP = 2400; async function speak(text) { await ensurePyodide(); await ensureModels(); text = text.trim(); if (!text) throw new Error("empty text"); barReset(); let parts = text.split(/(?<=[.!?…:])\s+/).filter(s => s.trim()); if (!parts.length) parts = [text]; const keep = []; for (const part of parts) { const pcs = await phonemizePieces(part); for (const pc of pcs) keep.push(pc); } let outArr = null; for (let k = 0; k < keep.length; k++) { status("synthesizing… " + (keep.length > 1 ? (k + 1) + "/" + keep.length : "")); const piece = await synthSingle(keep[k].ids); if (!outArr) outArr = piece; else { const grown = new Float64Array(outArr.length + GAP + piece.length); grown.set(outArr, 0); grown.set(piece, outArr.length + GAP); outArr = grown; } setp(88 + (k + 1) / keep.length * 8); } let wav = outArr; let eng = 0; for (let i = 0; i < wav.length; i++) eng += wav[i] * wav[i]; const rms = Math.sqrt(eng / wav.length) + 1e-9; const norm = new Float32Array(wav.length); for (let i = 0; i < wav.length; i++) norm[i] = wav[i] / rms * 0.05; status("done"); setpDone(); if (!actx) actx = new AudioContext({ sampleRate: 24000 }); return norm; } function audioWav(f32) { const i16 = new Int16Array(f32.length); for (let i = 0; i < f32.length; i++) i16[i] = Math.max(-32767, Math.min(32767, Math.round(f32[i] * 32767))); const hdr = new ArrayBuffer(44 + i16.length * 2), dv = new DataView(hdr); const wr = (o, s) => { for (let i = 0; i < s.length; i++) dv.setUint8(o + i, s.charCodeAt(i)); }; wr(0, "RIFF"); dv.setUint32(4, 36 + i16.length * 2, true); wr(8, "WAVEfmt "); dv.setUint32(16, 16, true); dv.setUint16(20, 1, true); dv.setUint16(22, 1, true); dv.setUint32(24, 24000, true); dv.setUint32(28, 48000, true); dv.setUint16(32, 2, true); dv.setUint16(34, 16, true); wr(36, "data"); dv.setUint32(40, i16.length * 2, true); new Int16Array(hdr, 44).set(i16); return new Blob([hdr], { type: "audio/wav" }); } el("go").addEventListener("click", async () => { el("go").disabled = true; try { const wav = await speak(el("text").value); el("out").src = URL.createObjectURL(audioWav(wav)); try { const ref = await fetch("reference.wav"); if (ref.ok) { const b = new Uint8Array(await ref.arrayBuffer()); const i16 = new Int16Array(b.buffer.slice(44)); let md = 0; for (let i = 0; i < Math.min(i16.length, wav.length); i++) { const d = Math.abs(i16[i] / 32767 - wav[i]); if (d > md) md = d; } status("done — browser vs reference maxdiff " + md.toExponential(2)); } } catch (e) { status("done"); } } catch (e) { status("error: " + e.message); console.error(e); } el("go").disabled = false; }); (async () => { try { barReset(); await ensurePyodide(); await ensureModels(); status("ready — CPU inference in your browser"); setpDone(); el("go").disabled = false; } catch (e) { status("load error: " + e.message); console.error(e); } })();