const SR = 16000;
const LANGS = ["en","zh","de","es","ru","ko","fr","ja","pt","tr","pl","ca","nl","ar","sv","it","id","hi","fi","vi","he","uk","el","ms","cs","ro","da","hu","ta","no","th","ur","hr","bg","lt","la","mi","ml","cy","sk","te","fa","lv","bn","sr","az","sl","kn","et","mk","br","eu","is","hy","ne","mn","bs","kk","sq","sw","gl","mr","pa","si","km","sn","yo","so","af","oc","ka","be","tg","sd","gu","am","yi","lo","uz","fo","ht","ps","tk","nn","mt","sa","lb","my","bo","tl","mg","as","tt","haw","ln","ha","ba","jw","su"];
const NORDIC = new Set(["no", "nn", "sv", "da"]);
const dn = (() => { try { return new Intl.DisplayNames(["en"], { type: "language" }); } catch { return null; } })();
const NAME_FIX = { jw: "Javanese", haw: "Hawaiian", nn: "Norwegian Nynorsk", no: "Norwegian", tl: "Tagalog", la: "Latin" };
const langName = (c) => NAME_FIX[c] || (dn && dn.of(c)) || c;
// Earthy categorical palette, assigned per language on first sight.
const PALETTE = ["#b5532a", "#5f7a2a", "#2f6f73", "#c08a1e", "#7a3b4e", "#3f6b45", "#8e2f2f", "#9c7a4a", "#4f5d4a", "#a8674a", "#6b6f2f", "#5a4636"];
const colorOf = new Map();
const col = (c) => { if (!colorOf.has(c)) colorOf.set(c, PALETTE[colorOf.size % PALETTE.length]); return colorOf.get(c); };
["en","fr","de","es","ja","zh","ru","hi"].forEach(col);
const $ = (id) => document.getElementById(id);
const state = { ready: false, backend: null, timings: [] };
window.__ear = state; // for automated tests
// ---------- worker ----------
const worker = new Worker("worker.js");
let reqId = 0;
const pending = new Map();
const batches = new Map();
const files = {};
worker.onmessage = (ev) => {
const d = ev.data;
if (d.type === "progress") {
files[d.file] = d;
let l = 0, t = 0; for (const f of Object.values(files)) { l += f.loaded; t += f.total || f.loaded; }
const mb = (x) => (x / 1048576).toFixed(1);
$("statusText").textContent = `Downloading model ${mb(l)} / ${mb(t)} MB${d.cached ? " (cached)" : ""}`;
$("loadBar").style.width = t ? `${(100 * l) / t}%` : "0";
} else if (d.type === "stage") {
$("statusText").textContent = d.msg;
} else if (d.type === "ready") {
state.ready = true; state.backend = d.backend; state.load = d;
$("dot").className = "dot ready";
$("status").classList.add("done");
$("statusText").textContent = `Ready in ${(d.loadMs / 1000).toFixed(1)} s`;
const chip = $("backendChip");
chip.hidden = false;
chip.textContent = d.backend === "webgpu" ? "WebGPU" : "WASM (no WebGPU)";
chip.title = `${d.adapter || ""} · download ${(d.downloadMs / 1000).toFixed(1)} s · translate ${d.convertMs.toFixed(0)} ms · compile ${(d.sessionMs / 1000).toFixed(1)} s`;
$("micBtn").disabled = false;
document.querySelectorAll(".samples button").forEach((b) => (b.disabled = false));
if (pendingFile) { const f = pendingFile; pendingFile = null; analyze(f.audio, f.name, f.url); }
} else if (d.type === "result") {
const p = pending.get(d.id); pending.delete(d.id); p && p.resolve(d);
} else if (d.type === "seg" || d.type === "batchdone") {
const b = batches.get(d.id); b && b(d);
} else if (d.type === "error") {
const p = pending.get(d.id);
if (p) { pending.delete(d.id); p.reject(new Error(d.msg)); }
else { $("dot").className = "dot err"; $("statusText").textContent = "Error: " + d.msg; }
console.error(d.msg);
} else if (d.type === "log") console.warn(d.msg);
};
const params = new URLSearchParams(location.search);
worker.postMessage({ type: "load", prefer: params.get("backend") || "webgpu", gpuFrontend: params.get("fe") !== "js" });
$("dot").className = "dot loading";
$("statusText").textContent = "Loading runtime…";
function infer(audio) {
const id = ++reqId;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
worker.postMessage({ type: "infer", id, audio }, [audio.buffer]);
});
}
// ---------- rendering helpers ----------
function renderBars(el, probs, k = 5) {
const idx = [...probs.keys()].sort((a, b) => probs[b] - probs[a]).slice(0, k);
if (el.children.length !== k) {
el.innerHTML = "";
for (let i = 0; i < k; i++) el.insertAdjacentHTML("beforeend", `
`);
}
idx.forEach((j, i) => {
const li = el.children[i], c = LANGS[j];
li.querySelector(".nm").innerHTML = `${langName(c)}${c}`;
const fl = li.querySelector(".fl");
fl.style.width = `${(probs[j] * 100).toFixed(1)}%`;
fl.style.background = i === 0 ? col(c) : "var(--muted)";
li.querySelector(".pc").textContent = `${(probs[j] * 100).toFixed(probs[j] < 0.1 ? 1 : 0)}%`;
});
return idx;
}
function verdict(probs) {
const idx = [...probs.keys()].sort((a, b) => probs[b] - probs[a]);
const top = LANGS[idx[0]], p1 = probs[idx[0]], p2 = probs[idx[1]];
const reasons = [];
if (NORDIC.has(top)) reasons.push("Norwegian/Swedish/Danish are easily confused");
if (p1 - p2 < 0.25) reasons.push(`close to ${langName(LANGS[idx[1]])}`);
return { code: top, p: p1, unsure: reasons.length > 0, reasons };
}
function langHtml(v) { return `${langName(v.code)}${v.code}`; }
function metaHtml(v, extra) {
const conf = `${(v.p * 100).toFixed(0)}% confident`;
const f = v.unsure ? ` · unsure: ${v.reasons.join(", ")}` : "";
return `${conf}${f}${extra ? " · " + extra : ""}`;
}
// ---------- tabs ----------
document.querySelectorAll(".tab").forEach((t) => t.addEventListener("click", () => {
document.querySelectorAll(".tab").forEach((x) => { x.classList.toggle("on", x === t); x.setAttribute("aria-selected", x === t); });
$("live").hidden = t.dataset.tab !== "live";
$("file").hidden = t.dataset.tab !== "file";
}));
// ---------- live mic ----------
const RING = SR * 30;
const ring = new Float32Array(RING);
let ringPos = 0, ringFill = 0, live = null, lastHop = 0, inflight = false, ema = null, liveStart = 0;
const ticks = []; // {t, code|null, p}
const TL_SPAN = 60;
const WORKLET = `class P extends AudioWorkletProcessor{process(i){const c=i[0];if(c&&c[0])this.port.postMessage(c[0].slice(0));return true}}registerProcessor('cap',P)`;
async function startMic() {
const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: true } });
let ctx;
try { ctx = new AudioContext({ sampleRate: SR }); } catch { ctx = new AudioContext(); }
const src = ctx.createMediaStreamSource(stream);
await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET], { type: "text/javascript" })));
const node = new AudioWorkletNode(ctx, "cap");
const ratio = ctx.sampleRate / SR;
let frac = 0;
node.port.onmessage = (e) => {
let x = e.data;
if (ratio !== 1) { // linear resample to 16 kHz
const out = []; let t = frac;
while (t < x.length - 1) { const i = Math.floor(t), f = t - i; out.push(x[i] * (1 - f) + x[i + 1] * f); t += ratio; }
frac = t - (x.length - 1); x = Float32Array.from(out);
}
for (let i = 0; i < x.length; i++) { ring[ringPos] = x[i]; ringPos = (ringPos + 1) % RING; }
ringFill = Math.min(RING, ringFill + x.length);
let s = 0; for (let i = 0; i < x.length; i++) s += x[i] * x[i];
const db = 10 * Math.log10(s / Math.max(1, x.length) + 1e-12);
$("lvl").style.width = `${Math.max(0, Math.min(100, (db + 60) * 1.8))}%`;
};
src.connect(node);
live = { stream, ctx, node };
liveStart = performance.now(); lastHop = 0;
$("micBtn").textContent = "Stop"; $("micBtn").classList.add("rec");
$("nowMeta").textContent = "Listening…";
requestAnimationFrame(liveLoop);
}
function stopMic() {
if (!live) return;
live.stream.getTracks().forEach((t) => t.stop());
live.ctx.close(); live = null;
$("micBtn").textContent = "Start listening"; $("micBtn").classList.remove("rec");
$("lvl").style.width = "0";
}
$("micBtn").addEventListener("click", async () => {
if (live) return stopMic();
try { await startMic(); } catch (e) { $("nowMeta").textContent = "Microphone unavailable: " + e.message; }
});
function lastSeconds(sec) {
const n = Math.min(ringFill, Math.round(sec * SR));
const out = new Float32Array(n);
let p = (ringPos - n + RING) % RING;
for (let i = 0; i < n; i++) { out[i] = ring[p]; p = (p + 1) % RING; }
return out;
}
function activity(a) {
// share of 20 ms frames above -48 dBFS and above the clip's own noise floor
const F = 320, n = Math.floor(a.length / F); if (!n) return 0;
const e = new Float32Array(n);
for (let f = 0; f < n; f++) { let s = 0; for (let i = f * F; i < f * F + F; i++) s += a[i] * a[i]; e[f] = 10 * Math.log10(s / F + 1e-12); }
const sorted = Float32Array.from(e).sort(); const floor = sorted[Math.floor(n * 0.1)];
let act = 0; for (const v of e) if (v > -48 && v > floor + 10) act++;
return act / n;
}
async function liveLoop(now) {
if (!live) return;
requestAnimationFrame(liveLoop);
const hop = +$("hopSel").value;
if (inflight || now - lastHop < hop || ringFill < SR * 0.5) return;
lastHop = now; inflight = true;
const ctxSec = +$("ctxSel").value;
const audio = lastSeconds(ctxSec);
const recent = audio.subarray(Math.max(0, audio.length - SR * 2));
const actR = activity(recent), actC = activity(audio);
const speechy = actR > 0.12 && actC > 0.08;
state.liveAct = [actR, actC, audio.length];
const t = (now - liveStart) / 1000;
try {
if (!speechy) {
ticks.push({ t, code: null });
$("nowStats").textContent = "";
if (!ema) $("nowMeta").textContent = "Listening… (no speech yet)";
else $("nowMeta").innerHTML = metaHtml(verdict(ema), "paused: silence");
} else {
const r = await infer(audio);
state.timings.push(r.runMs);
const p = r.probs;
if (!ema) ema = Float32Array.from(p);
else for (let i = 0; i < p.length; i++) ema[i] = 0.6 * ema[i] + 0.4 * p[i];
const v = verdict(ema);
$("nowLang").innerHTML = langHtml(v);
$("nowMeta").innerHTML = metaHtml(v, `last ${ctxSec} s`);
$("nowStats").textContent = `features ${r.melMs.toFixed(0)} ms\nmodel ${r.runMs.toFixed(0)} ms`;
renderBars($("liveBars"), ema);
const raw = verdict(p);
ticks.push({ t, code: raw.code, p: raw.p });
state.lastLive = v.code;
}
drawLiveTl(t);
} finally { inflight = false; }
}
function drawLiveTl(tNow) {
while (ticks.length && ticks[0].t < tNow - TL_SPAN - 2) ticks.shift();
const el = $("liveTl"); el.innerHTML = "";
const t0 = tNow - TL_SPAN;
const seen = new Set();
let run = null; const runs = [];
for (let i = 0; i < ticks.length; i++) {
const a = ticks[i], b = ticks[i + 1];
const x0 = Math.max(0, (a.t - t0) / TL_SPAN), x1 = b ? (b.t - t0) / TL_SPAN : 1;
if (x1 <= 0) continue;
const d = document.createElement("div");
d.className = "tk" + (a.code ? "" : " sil");
d.style.left = `${x0 * 100}%`; d.style.width = `${Math.max(0, x1 - x0) * 100 + 0.2}%`;
if (a.code) { d.style.background = col(a.code); d.style.opacity = (0.45 + 0.55 * a.p).toFixed(2); seen.add(a.code); }
el.appendChild(d);
if (!run || run.code !== a.code) { run = { code: a.code, x0, x1 }; runs.push(run); } else run.x1 = x1;
}
for (const r of runs) {
if (!r.code || r.x1 - r.x0 < 0.05) continue;
const l = document.createElement("span"); l.className = "lab"; l.textContent = r.code;
l.style.left = `${r.x0 * 100}%`; el.appendChild(l);
}
$("tlLegend").textContent = [...seen].join(" · ");
}
// ---------- file mode ----------
let pendingFile = null, current = null;
const SAMPLES = [["en", "English"], ["fr", "French"], ["de", "German"], ["es", "Spanish"], ["ja", "Japanese"], ["zh", "Chinese"], ["ru", "Russian"], ["hi", "Hindi"], ["mixed", "Mixed: en→de→ja→fr"]];
for (const [k, label] of SAMPLES) {
const b = document.createElement("button");
b.className = "btn sm"; b.textContent = label; b.disabled = true; b.dataset.sample = k;
b.addEventListener("click", async () => {
const url = `samples/${k}.m4a`;
const buf = await (await fetch(url)).arrayBuffer();
loadAudio(buf, label, url);
});
$("samples").appendChild(b);
}
async function decode(buf) {
const ctx = new OfflineAudioContext(1, 1, SR);
const ab = await ctx.decodeAudioData(buf);
// downmix + resample to 16 kHz mono
const off = new OfflineAudioContext(1, Math.ceil(ab.duration * SR), SR);
const s = off.createBufferSource(); s.buffer = ab; s.connect(off.destination); s.start();
const r = await off.startRendering();
return r.getChannelData(0);
}
async function loadAudio(buf, name, url) {
$("fileOut").hidden = false;
$("fileLang").textContent = "…"; $("fileMeta").textContent = "Decoding…";
try {
const audio = await decode(buf);
if (!state.ready) { pendingFile = { audio, name, url }; $("fileMeta").textContent = "Waiting for model…"; return; }
analyze(audio, name, url);
} catch (e) { $("fileMeta").textContent = "Could not decode this file: " + e.message; }
}
$("fileIn").addEventListener("change", (e) => {
const f = e.target.files[0]; if (!f) return;
f.arrayBuffer().then((b) => loadAudio(b, f.name, URL.createObjectURL(f)));
});
const drop = $("drop");
["dragenter", "dragover"].forEach((ev) => drop.addEventListener(ev, (e) => { e.preventDefault(); drop.classList.add("over"); }));
["dragleave", "drop"].forEach((ev) => drop.addEventListener(ev, () => drop.classList.remove("over")));
drop.addEventListener("drop", (e) => {
e.preventDefault(); const f = e.dataTransfer.files[0]; if (!f) return;
f.arrayBuffer().then((b) => loadAudio(b, f.name, URL.createObjectURL(f)));
});
// Pick the most speech-like 30 s windows: speech loudness rises and falls at
// syllable rate (3-6 Hz); music sustains and silence is flat.
function speechWindows(a, k = 3) {
const W = 30 * SR;
if (a.length <= W) return [[0, a.length]];
const F = 160, n = Math.floor(a.length / F), env = new Float32Array(n);
for (let f = 0; f < n; f++) { let s = 0; for (let i = f * F; i < f * F + F; i++) s += a[i] * a[i]; env[f] = 10 * Math.log10(s / F + 1e-10); }
// modulation: envelope minus its 0.4 s moving average, after 3-frame smoothing
const mod = new Float32Array(n);
let acc = 0; const M = 40;
for (let f = 0; f < n; f++) {
acc += env[f]; if (f >= M) acc -= env[f - M];
const avg = acc / Math.min(f + 1, M);
const sm = (env[Math.max(0, f - 1)] + env[f] + env[Math.min(n - 1, f + 1)]) / 3;
mod[f] = env[f] > -50 ? Math.abs(sm - avg) : 0;
}
const cand = [], step = 5 * SR, last = a.length - W;
for (let s = 0; s <= last; s += step) cand.push(s);
if (cand[cand.length - 1] !== last) cand.push(last);
const scored = cand.map((s) => { let t = 0; const f0 = s / F, f1 = (s + W) / F; for (let f = f0; f < f1; f++) t += mod[f]; return [s, t]; }).sort((x, y) => y[1] - x[1]);
const picked = [];
for (const [s] of scored) { if (picked.every((p) => Math.abs(p - s) >= W)) picked.push(s); if (picked.length === k) break; }
if (picked.length < k) for (const [s] of scored) { if (!picked.includes(s)) picked.push(s); if (picked.length === k) break; }
return picked.sort((x, y) => x - y).map((s) => [s, W]);
}
function runBatch(audio, segs, onSeg) {
const id = ++reqId;
return new Promise((resolve, reject) => {
batches.set(id, (d) => { if (d.type === "seg") onSeg(d); else { batches.delete(id); resolve(); } });
pending.set(id, { resolve() {}, reject });
worker.postMessage({ type: "batch", id, audio, segs });
});
}
async function analyze(audio, name, url) {
const token = { audio }; current = token;
const dur = audio.length / SR;
$("player").src = url;
drawWave(audio);
$("segs").innerHTML = "";
// 1. overall verdict from the most speech-like 30 s windows
const wins = speechWindows(audio);
$("fileMeta").textContent = `Reading ${wins.length} window${wins.length > 1 ? "s" : ""}…`;
const avg = new Float32Array(LANGS.length); const logits = []; let runMs = 0, melMs = 0;
const t0 = performance.now();
await runBatch(audio, wins, (d) => { for (let i = 0; i < avg.length; i++) avg[i] += d.probs[i] / wins.length; logits.push(Array.from(d.logits)); runMs += d.runMs; melMs += d.melMs; });
if (current !== token) return;
const v = verdict(avg);
$("fileLang").innerHTML = langHtml(v);
$("fileMeta").innerHTML = metaHtml(v, `${name} · ${fmt(dur)}`);
$("fileStats").textContent = `${wins.length} × 30 s window\nmodel ${(runMs / wins.length).toFixed(0)} ms/window`;
renderBars($("fileBars"), avg);
state.file = { name, code: v.code, p: v.p, logits, windows: wins, runMs: runMs / wins.length, melMs: melMs / wins.length, totalMs: performance.now() - t0 };
// 2. timeline
await timeline(audio, token);
}
async function timeline(audio, token) {
const seg = +$("segSel").value * SR, hop = Math.round(seg / 2);
const segs = [];
for (let s = 0; s < audio.length; s += hop) { segs.push([s, Math.min(seg, audio.length - s)]); if (s + seg >= audio.length) break; }
const dur = audio.length;
$("segs").innerHTML = "";
$("segInfo").textContent = `· ${segs.length} segments`;
const res = [];
const t0 = performance.now();
await runBatch(audio, segs, (d) => {
if (current !== token) return;
const [s, n] = segs[d.i];
const act = activity(audio.subarray(s, s + n));
const v = verdict(d.probs);
res.push({ s, n, code: act > 0.1 ? v.code : null, p: v.p });
// paint the non-overlapping centre of each segment
const a = d.i === 0 ? 0 : s + (seg - hop) / 2, b = d.i === segs.length - 1 ? dur : s + (seg + hop) / 2;
const el = document.createElement("div");
el.className = "sg" + (act > 0.1 ? "" : " sil");
el.style.left = `${(a / dur) * 100}%`; el.style.width = `${((b - a) / dur) * 100}%`;
el.title = act > 0.1 ? `${fmt(s / SR)}–${fmt((s + n) / SR)}: ${langName(v.code)} ${(v.p * 100).toFixed(0)}%` : "silence";
if (act > 0.1) { el.style.background = col(v.code); el.style.opacity = (0.45 + 0.55 * v.p).toFixed(2); }
$("segs").appendChild(el);
const prev = res[res.length - 2];
if (act > 0.1 && (!prev || prev.code !== v.code)) {
const l = document.createElement("span"); l.className = "lab"; l.textContent = v.code; l.style.left = `${(a / dur) * 100}%`;
$("segs").appendChild(l);
}
});
if (current === token) {
state.file.timeline = res.map((r) => r.code); state.file.timelineMs = performance.now() - t0;
const cnt = {}; for (const r of res) if (r.code) cnt[r.code] = (cnt[r.code] || 0) + 1;
const multi = Object.keys(cnt).filter((c) => cnt[c] >= 2);
if (multi.length > 1) $("fileMeta").insertAdjacentHTML("beforeend", ` · several languages: ${multi.join(", ")}`);
}
}
$("segSel").addEventListener("change", () => { if (current && current.audio) { const t = { audio: current.audio }; current = t; timeline(t.audio, t); } });
function fmt(s) { const m = Math.floor(s / 60), r = Math.floor(s % 60); return `${m}:${String(r).padStart(2, "0")}`; }
function drawWave(a) {
const c = $("wave"), w = c.clientWidth || 600, h = c.clientHeight || 44, dpr = devicePixelRatio || 1;
c.width = w * dpr; c.height = h * dpr;
const g = c.getContext("2d"); g.scale(dpr, dpr); g.clearRect(0, 0, w, h);
g.fillStyle = getComputedStyle(document.documentElement).getPropertyValue("--muted");
const per = Math.max(1, Math.floor(a.length / w));
for (let x = 0; x < w; x++) {
let mx = 0; for (let i = x * per; i < Math.min(a.length, (x + 1) * per); i++) { const v = Math.abs(a[i]); if (v > mx) mx = v; }
const bh = Math.max(1, mx * h * 0.95); g.fillRect(x, (h - bh) / 2, 1, bh);
}
}
$("fileTl").addEventListener("click", (e) => {
const r = $("fileTl").getBoundingClientRect(), p = $("player");
if (p.duration) { p.currentTime = ((e.clientX - r.left) / r.width) * p.duration; p.play(); }
});
$("player").addEventListener("timeupdate", () => {
const p = $("player"); if (p.duration) $("playhead").style.left = `${(p.currentTime / p.duration) * 100}%`;
});