Spaces:
Running
Running
Download app.js from Cis-Labs/forced-aligner: direct link, hf CLI and curl.
- Browser
- Download file 29.4 kB
-
https://huggingface.co/spaces/Cis-Labs/forced-aligner/resolve/main/app.js
- Command line
-
hf download hf://spaces/Cis-Labs/forced-aligner/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Cis-Labs/forced-aligner/resolve/main/app.js
29.4 kB
| // Forced Aligner: static, in-browser demo (UI thread). The model runs in worker.js. | |
| import { CJK_LANGS, MODEL_ID, groupCues, toJson, toSrt } from "./aligner.js"; | |
| import { decodeAudio } from "./audio.js"; | |
| const MAX_SECONDS = 180; // 3 minutes per file keeps a phone or laptop tab responsive | |
| const MAX_TRANSCRIPT_CHARS = 12000; | |
| const MAX_FILE_MB = 200; | |
| const MODEL_MB = { q8: 370, fp32: 1300 }; | |
| // Testing before release: ?model=<org/name> (a Hub repo with onnx/ weights) or ?model=/path (same-origin folder). | |
| // Optional: ?dtype=q8|fp32, ?device=wasm|webgpu. | |
| const params = new URLSearchParams(location.search); | |
| const requested = params.get("model"); | |
| const isRepoId = (v) => /^[\w.-]+\/[\w.-]+$/.test(v) && !v.includes(".."); | |
| const isLocalPath = (v) => /^\.?\/[\w./-]+$/.test(v) && !v.includes(".."); | |
| const model = requested && (isRepoId(requested) || isLocalPath(requested)) ? requested : MODEL_ID; | |
| const dtype = ["q8", "fp32"].includes(params.get("dtype")) ? params.get("dtype") : "q8"; | |
| const device = ["wasm", "webgpu"].includes(params.get("device")) ? params.get("device") : "wasm"; | |
| // ISO 639-3 codes. The model is language-agnostic; the code picks normalization rules, the default | |
| // granularity, and the flags in the pipeline snippets. | |
| const LANGUAGES = [ | |
| ["English", "eng", "en"], ["Spanish", "spa", "es"], ["French", "fra", "fr"], ["German", "deu", "de"], | |
| ["Italian", "ita", "it"], ["Portuguese", "por", "pt"], ["Dutch", "nld", "nl"], ["Polish", "pol", "pl"], | |
| ["Czech", "ces", "cs"], ["Romanian", "ron", "ro"], ["Hungarian", "hun", "hu"], ["Greek", "ell", "el"], | |
| ["Swedish", "swe", "sv"], ["Danish", "dan", "da"], ["Norwegian Bokmål", "nob", "no"], ["Finnish", "fin", "fi"], | |
| ["Catalan", "cat", "ca"], ["Russian", "rus", "ru"], ["Ukrainian", "ukr", "uk"], ["Turkish", "tur", "tr"], | |
| ["Arabic", "arb", "ar"], ["Persian", "fas", "fa"], ["Hebrew", "heb", "he"], ["Hindi", "hin", "hi"], | |
| ["Bengali", "ben", "bn"], ["Urdu", "urd", "ur"], ["Marathi", "mar", "mr"], ["Tamil", "tam", "ta"], | |
| ["Telugu", "tel", "te"], ["Mandarin Chinese", "cmn", "zh"], ["Cantonese", "yue", "yue"], ["Japanese", "jpn", "ja"], | |
| ["Korean", "kor", "ko"], ["Vietnamese", "vie", "vi"], ["Thai", "tha", "th"], ["Indonesian", "ind", "id"], | |
| ["Malay", "zsm", "ms"], ["Tagalog", "tgl", "tl"], ["Swahili", "swh", "sw"], ["Amharic", "amh", "am"], | |
| ["Yoruba", "yor", "yo"], ["Hausa", "hau", "ha"], | |
| ]; | |
| const TO_ISO1 = Object.fromEntries([...LANGUAGES.map(([, a, b]) => [a, b]), ["zho", "zh"], ["chi", "zh"], ["ara", "ar"]]); | |
| const EXAMPLES = [ | |
| { | |
| label: "English · LibriSpeech", audio: "examples/en_librispeech_1272-128104-0000.flac", | |
| text: "Mister Quilter is the apostle of the middle classes, and we are glad to welcome his gospel.", | |
| lang: "eng", gran: "words", | |
| }, | |
| { | |
| label: "Hindi · FLEURS (one word is skipped by the reader)", audio: "examples/hi_fleurs_1601.flac", | |
| text: "वैज्ञानिकों का मानना है कि ओसेलोट्स गंध के द्वारा जानवरों का पीछा करते और खाते (शिकार) हैं, " + | |
| "यह सूँघते हुए कि वे ज़मीन पर कहाँ रहे होंगे।", | |
| lang: "hin", gran: "words", | |
| }, | |
| { | |
| label: "Mandarin · FLEURS · characters", audio: "examples/cmn_fleurs_1648.flac", | |
| text: "迦南没有大森林,所以木材非常昂贵。", lang: "cmn", gran: "characters", | |
| }, | |
| ]; | |
| // --------------------------------------------------------------------------------------------- | |
| const $ = (id) => document.getElementById(id); | |
| const els = { | |
| status: $("status"), statusText: $("status-text"), statusDetail: $("status-detail"), bar: $("bar-fill"), | |
| loadBtn: $("load-btn"), file: $("file"), pick: $("pick"), record: $("record"), recordText: $("record-text"), | |
| drop: $("drop"), audioName: $("audio-name"), transcript: $("transcript"), lang: $("lang"), langs: $("langs"), | |
| maxChars: $("max-chars"), maxCharsOut: $("max-chars-out"), separators: $("separators"), run: $("run"), | |
| examples: $("examples"), audio: $("audio"), timeline: $("timeline"), head: $("head"), words: $("words"), | |
| notes: $("notes"), table: document.querySelector("#table tbody"), dlSrt: $("dl-srt"), dlJson: $("dl-json"), | |
| running: $("running"), copyTable: $("copy-table"), | |
| }; | |
| const radio = (name) => document.querySelector(`input[name="${name}"]:checked`).value; | |
| const setRadio = (name, value) => { | |
| const el = document.querySelector(`input[name="${name}"][value="${value}"]`); | |
| if (el) el.checked = true; | |
| }; | |
| const mb = (b) => (b / 1e6).toFixed(b < 1e7 ? 1 : 0); | |
| const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`; | |
| function setStatus(state, text, detail = "") { | |
| els.status.dataset.state = state; | |
| els.statusText.textContent = text; | |
| els.statusDetail.textContent = detail; | |
| } | |
| /** Accept 'hin', 'Hindi (hin)' or any typed ISO 639-3 code; fall back to generic rules. */ | |
| function parseLang(value) { | |
| const v = (value || "").trim().toLowerCase(); | |
| const m = v.match(/\(([a-z]{3})\)/) || v.match(/^([a-z]{3})$/); | |
| if (m) return m[1]; | |
| for (const [name, iso3] of LANGUAGES) if (v === name.toLowerCase()) return iso3; | |
| return "und"; | |
| } | |
| // -- worker plumbing --------------------------------------------------------------------------- | |
| const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" }); | |
| const pending = new Map(); | |
| let seq = 0; | |
| function call(type, payload = {}, onEvent = null, transfer = []) { | |
| const id = ++seq; | |
| return new Promise((resolve, reject) => { | |
| pending.set(id, { resolve, reject, onEvent }); | |
| worker.postMessage({ id, type, ...payload }, transfer); | |
| }); | |
| } | |
| const files = new Map(); | |
| worker.addEventListener("message", ({ data }) => { | |
| if (data.type === "progress") return onLoadProgress(data.p); | |
| const p = pending.get(data.id); | |
| if (!p) return; | |
| if (data.type === "window") return p.onEvent?.(data.p); | |
| pending.delete(data.id); | |
| if (data.type === "error") { | |
| const err = new Error(data.message); | |
| err.user = data.user; | |
| p.reject(err); | |
| } else p.resolve(data); | |
| }); | |
| worker.addEventListener("error", (e) => { | |
| setStatus("error", "Could not start the aligner.", e.message || "Your browser may not support module workers."); | |
| }); | |
| function onLoadProgress(p) { | |
| if (!p || !p.file) return; | |
| if (p.status === "progress" && p.total) files.set(p.file, { loaded: p.loaded, total: p.total }); | |
| if (p.status === "done" && files.has(p.file)) files.get(p.file).loaded = files.get(p.file).total; | |
| let loaded = 0; | |
| let total = 0; | |
| for (const f of files.values()) { | |
| loaded += f.loaded; | |
| total += f.total; | |
| } | |
| if (total > 0 && loaded < total) { | |
| setStatus("loading", "Downloading model…", `${mb(loaded)} / ${mb(total)} MB · cached after the first visit`); | |
| els.bar.style.width = `${Math.round((100 * loaded) / total)}%`; | |
| } else if (total > 0) { | |
| setStatus("loading", "Preparing model…", "compiling for your device"); | |
| els.bar.style.width = "100%"; | |
| } | |
| } | |
| // -- model loading ----------------------------------------------------------------------------- | |
| let ready = false; | |
| let runtime = ""; | |
| let runAfterLoad = false; | |
| async function loadModel() { | |
| els.loadBtn.hidden = true; | |
| setStatus("loading", "Loading model…", `about ${MODEL_MB[dtype]} MB, once`); | |
| try { | |
| const { info } = await call("load", { model, device, dtype }); | |
| const parts = [info.device === "webgpu" ? "WebGPU" : "WebAssembly", info.dtype === "q8" ? "int8" : info.dtype]; | |
| if (info.device === "wasm" && info.threads) parts.push(plural(info.threads, "thread")); | |
| runtime = parts.join(" · "); | |
| setStatus("ready", "Ready", runtime); | |
| // Inside the Hugging Face page the demo is an iframe and cannot use WebAssembly threads; its own tab can. | |
| if (info.device === "wasm" && (info.threads ?? 1) < 2 && window.top !== window.self && navigator.hardwareConcurrency > 2) { | |
| const a = document.createElement("a"); | |
| a.href = location.href; | |
| a.target = "_blank"; | |
| a.rel = "noopener"; | |
| a.textContent = "Faster in its own tab ↗"; | |
| els.statusDetail.append(" · ", a); | |
| } | |
| ready = true; | |
| els.run.disabled = false; | |
| if (runAfterLoad) { | |
| runAfterLoad = false; | |
| align(); | |
| } | |
| } catch (err) { | |
| const msg = String(err.message || err); | |
| setStatus("error", "The model could not be loaded.", msg.length > 220 ? `${msg.slice(0, 220)}…` : msg); | |
| } | |
| } | |
| // -- audio input ------------------------------------------------------------------------------- | |
| let source = null; // { name, url, wav, duration, error } | |
| let sourceSeq = 0; | |
| function stemOf(name) { | |
| const stem = (name || "").replace(/\.[^.]+$/, "").replace(/[^\p{L}\p{N}_-]+/gu, "_").replace(/^_+|_+$/g, ""); | |
| return (stem || "alignment").slice(0, 60); | |
| } | |
| async function setSource(name, blobOrUrl) { | |
| const my = ++sourceSeq; | |
| if (source?.url?.startsWith("blob:") && source.url !== els.audio.src) URL.revokeObjectURL(source.url); | |
| const url = typeof blobOrUrl === "string" ? blobOrUrl : URL.createObjectURL(blobOrUrl); | |
| source = { name, url, wav: null, duration: 0, error: null, decoding: null }; | |
| els.audioName.textContent = name; | |
| clearResult(); | |
| els.audio.src = url; | |
| source.decoding = (async () => { | |
| try { | |
| const buf = typeof blobOrUrl === "string" ? await (await fetch(blobOrUrl)).arrayBuffer() : await blobOrUrl.arrayBuffer(); | |
| const res = await decodeAudio(buf, MAX_SECONDS); | |
| if (my !== sourceSeq) return; | |
| source.wav = res.wav; | |
| source.duration = res.duration; | |
| els.audioName.textContent = `${name} · ${res.duration.toFixed(1)} s`; | |
| } catch (err) { | |
| if (my !== sourceSeq) return; | |
| source.error = String(err.message || err); | |
| els.audioName.textContent = name; | |
| } | |
| })(); | |
| return source.decoding; | |
| } | |
| function onFile(file) { | |
| if (!file) return; | |
| if (file.size > MAX_FILE_MB * 1e6) { | |
| showError(`This file is ${Math.round(file.size / 1e6)} MB; the demo takes files up to ${MAX_FILE_MB} MB and 3 minutes.`); | |
| return; | |
| } | |
| setSource(file.name, file); | |
| } | |
| // Recording with MediaRecorder; stops automatically at the length limit. | |
| let recorder = null; | |
| let recTimer = null; | |
| async function toggleRecord() { | |
| if (recorder) { | |
| recorder.stop(); | |
| return; | |
| } | |
| if (!navigator.mediaDevices?.getUserMedia || !globalThis.MediaRecorder) { | |
| showError("Recording is not supported in this browser. Upload a file instead."); | |
| return; | |
| } | |
| let stream; | |
| els.recordText.textContent = "Allow the microphone…"; | |
| try { | |
| stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: false } }); | |
| } catch { | |
| els.recordText.textContent = "Record"; | |
| showError("Microphone access was blocked. Allow it in your browser, or upload a file instead."); | |
| return; | |
| } | |
| const chunks = []; | |
| recorder = new MediaRecorder(stream); | |
| recorder.addEventListener("dataavailable", (e) => e.data.size && chunks.push(e.data)); | |
| recorder.addEventListener("stop", () => { | |
| stream.getTracks().forEach((t) => t.stop()); | |
| clearInterval(recTimer); | |
| els.record.classList.remove("on"); | |
| els.recordText.textContent = "Record"; | |
| const type = recorder.mimeType || "audio/webm"; | |
| recorder = null; | |
| const ext = type.includes("mp4") ? "m4a" : type.includes("ogg") ? "ogg" : "webm"; | |
| const blob = new Blob(chunks, { type }); | |
| setSource(`recording.${ext}`, blob); | |
| }); | |
| recorder.start(250); | |
| const t0 = Date.now(); | |
| els.record.classList.add("on"); | |
| const tick = () => { | |
| const s = Math.floor((Date.now() - t0) / 1000); | |
| els.recordText.textContent = `Stop · ${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; | |
| if (s >= MAX_SECONDS && recorder) recorder.stop(); | |
| }; | |
| tick(); | |
| recTimer = setInterval(tick, 500); | |
| } | |
| // -- alignment --------------------------------------------------------------------------------- | |
| let busy = false; | |
| let result = null; // { units, unknown, duration, lang, gran, text, stem, timing } | |
| function showError(msg) { | |
| els.notes.replaceChildren(); | |
| const p = document.createElement("p"); | |
| p.className = "warn"; | |
| p.textContent = msg; | |
| els.notes.append(p); | |
| } | |
| async function align() { | |
| if (busy) return; | |
| if (!source) return showError("Add an audio file or record one first."); | |
| const text = els.transcript.value.trim(); | |
| if (!text) return showError("Paste the transcript of the audio."); | |
| if (text.length > MAX_TRANSCRIPT_CHARS) { | |
| return showError(`The transcript is longer than ${MAX_TRANSCRIPT_CHARS.toLocaleString("en-US")} characters, which is more than 3 minutes of speech.`); | |
| } | |
| if (!ready) { | |
| runAfterLoad = true; | |
| if (!els.loadBtn.hidden) loadModel(); | |
| els.run.textContent = "Waiting for the model…"; | |
| return; | |
| } | |
| busy = true; | |
| els.run.disabled = true; | |
| els.run.textContent = "Decoding audio…"; | |
| try { | |
| await source.decoding; | |
| if (source.error) throw Object.assign(new Error(source.error), { user: true }); | |
| const lang = parseLang(els.lang.value); | |
| const gran = radio("gran"); | |
| const wav = source.wav.slice(); | |
| els.run.textContent = "Aligning…"; | |
| const { res } = await call( | |
| "align", | |
| { wav, text, options: { lang, granularity: gran, useSeparator: els.separators.checked } }, | |
| (p) => { | |
| if (p.total > 1) els.run.textContent = `Aligning… ${Math.round((100 * p.done) / p.total)}% · window ${Math.min(p.done + 1, p.total)} of ${p.total}`; | |
| }, | |
| [wav.buffer], | |
| ); | |
| result = { ...res, duration: source.duration, lang, gran, text, stem: stemOf(source.name) }; | |
| if (els.audio.src !== source.url) els.audio.src = source.url; | |
| render(); | |
| } catch (err) { | |
| showError(err.user ? String(err.message) : `Alignment failed: ${err.message || err}`); | |
| } finally { | |
| busy = false; | |
| els.run.disabled = false; | |
| els.run.textContent = "Align"; | |
| } | |
| } | |
| // -- rendering --------------------------------------------------------------------------------- | |
| function clearResult() { | |
| result = null; | |
| wordEls = []; | |
| blockEls = []; | |
| cur = -1; | |
| els.timeline.replaceChildren(els.head); | |
| els.head.style.left = "0"; | |
| els.words.replaceChildren(); | |
| els.table.replaceChildren(); | |
| els.notes.replaceChildren(); | |
| for (const a of [els.dlSrt, els.dlJson]) { | |
| a.removeAttribute("href"); | |
| a.setAttribute("aria-disabled", "true"); | |
| } | |
| } | |
| const scoreClass = (u) => (u.score === null ? "na" : u.score < 0.3 ? "lo" : u.score < 0.6 ? "mid" : "ok"); | |
| let wordEls = []; | |
| let blockEls = []; | |
| function render() { | |
| const { units, duration } = result; | |
| const dur = Math.max(duration, 1e-3); | |
| const tl = document.createDocumentFragment(); | |
| const ws = document.createDocumentFragment(); | |
| wordEls = []; | |
| blockEls = []; | |
| units.forEach((u, i) => { | |
| const cls = scoreClass(u); | |
| const tip = cls === "na" ? "not aligned (no characters in the model vocabulary)" | |
| : `${u.start.toFixed(2)}–${u.end.toFixed(2)} s · score ${u.score.toFixed(2)}`; | |
| let block = null; | |
| if (cls !== "na") { | |
| block = document.createElement("div"); | |
| block.className = `block ${cls}`; | |
| block.style.left = `${((100 * u.start) / dur).toFixed(3)}%`; | |
| block.style.width = `${Math.max((100 * (u.end - u.start)) / dur, 0.15).toFixed(3)}%`; | |
| block.title = `${u.text} · ${tip}`; | |
| tl.append(block); | |
| } | |
| blockEls.push(block); | |
| if (i && u.space_before) ws.append(" "); | |
| const w = document.createElement("span"); | |
| w.className = `w ${cls}`; | |
| w.dataset.i = String(i); | |
| w.title = tip; | |
| w.textContent = u.text; | |
| ws.append(w); | |
| wordEls.push(w); | |
| }); | |
| els.timeline.replaceChildren(tl, els.head); | |
| els.words.replaceChildren(ws); | |
| const rtl = units.reduce((n, u) => n + [...u.text].filter((c) => c >= "" && c <= "ࣿ").length, 0) > units.length; | |
| els.words.dir = rtl ? "rtl" : "auto"; | |
| cur = -1; | |
| updateHead(); | |
| const rows = document.createDocumentFragment(); | |
| units.forEach((u, i) => { | |
| const tr = document.createElement("tr"); | |
| tr.className = scoreClass(u); | |
| for (const v of [i + 1, u.text, u.start.toFixed(2), u.end.toFixed(2), u.score === null ? "" : u.score.toFixed(2)]) { | |
| const td = document.createElement("td"); | |
| td.textContent = String(v); | |
| tr.append(td); | |
| } | |
| tr.dataset.i = String(i); | |
| rows.append(tr); | |
| }); | |
| els.table.replaceChildren(rows); | |
| renderNotes(); | |
| updateDownloads(); | |
| } | |
| function renderNotes() { | |
| const { units, unknown, duration, lang, gran, timing } = result; | |
| const noun = (n) => (gran === "characters" ? "character" : "word") + (n === 1 ? "" : "s"); | |
| const notes = []; | |
| const nAl = units.filter((u) => u.score !== null).length; | |
| const head = [`<b>${nAl} ${noun(nAl)}</b> aligned in <b>${duration.toFixed(1)} s</b> of audio`]; | |
| if (timing) head.push(`${((timing.modelMs + timing.alignMs) / 1000).toFixed(1)} s on this device (${runtime})`); | |
| head.push(`language <code>${esc(lang)}</code>`); | |
| notes.push(["", head.join(" · ")]); | |
| if (unknown.length) { | |
| const total = unknown.reduce((s, [, n]) => s + n, 0); | |
| notes.push(["", `<b>Skipped ${total} character(s)</b> that are not in the model's vocabulary: ` + | |
| unknown.slice(0, 20).map(([c]) => `<code>${esc(c)}</code>`).join(" ")]); | |
| } | |
| const missing = units.filter((u) => u.score === null).map((u) => u.text); | |
| if (missing.length) { | |
| notes.push(["", "<b>No alignable characters</b>, given a zero-length slot: " + | |
| missing.slice(0, 15).map((w) => `<code>${esc(w)}</code>`).join(", ")]); | |
| } | |
| const low = units.filter((u) => u.score !== null && u.score < 0.3).map((u) => u.text); | |
| if (low.length) { | |
| const hint = low.some((w) => /\p{Nd}/u.test(w)) ? " Numbers align best spelled out." : ""; | |
| notes.push(["warn", `<b>${low.length} low-confidence ${noun(low.length)}</b> (score < 0.3): ` + | |
| low.slice(0, 15).map(esc).join(", ") + (low.length > 15 ? " …" : "") + | |
| `. Check that ${low.length === 1 ? "it is" : "they are"} spoken as written.${hint}`]); | |
| } | |
| if (!timing) notes.push(["muted", "Precomputed with this page's aligner. Press <b>Align</b> to run it on your device."]); | |
| els.notes.replaceChildren(...notes.map(([cls, html]) => { | |
| const p = document.createElement("p"); | |
| if (cls) p.className = cls; | |
| p.innerHTML = html; | |
| return p; | |
| })); | |
| } | |
| const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); | |
| let srtUrl = null; | |
| let jsonUrl = null; | |
| function updateDownloads() { | |
| if (!result) return; | |
| const { units, duration, lang, gran, text, stem } = result; | |
| const cues = groupCues(units, { maxChars: Number(els.maxChars.value), onePerCue: radio("cue") === "words" }); | |
| const json = toJson(units, cues, { text, language: lang, granularity: gran, duration, modelId: MODEL_ID }); | |
| if (srtUrl) URL.revokeObjectURL(srtUrl); | |
| if (jsonUrl) URL.revokeObjectURL(jsonUrl); | |
| srtUrl = URL.createObjectURL(new Blob([toSrt(cues)], { type: "application/x-subrip;charset=utf-8" })); | |
| jsonUrl = URL.createObjectURL(new Blob([JSON.stringify(json, null, 1)], { type: "application/json" })); | |
| Object.assign(els.dlSrt, { href: srtUrl, download: `${stem}.srt` }); | |
| Object.assign(els.dlJson, { href: jsonUrl, download: `${stem}.json` }); | |
| els.dlSrt.removeAttribute("aria-disabled"); | |
| els.dlJson.removeAttribute("aria-disabled"); | |
| } | |
| // -- player ------------------------------------------------------------------------------------ | |
| let cur = -1; | |
| let raf = 0; | |
| function find(t) { | |
| const units = result?.units || []; | |
| let lo = 0; | |
| let hi = units.length - 1; | |
| let ans = -1; | |
| while (lo <= hi) { | |
| const mid = (lo + hi) >> 1; | |
| if (units[mid].start <= t) { | |
| ans = mid; | |
| lo = mid + 1; | |
| } else hi = mid - 1; | |
| } | |
| while (ans >= 0 && units[ans].score === null) ans--; | |
| if (ans >= 0 && t >= units[ans].end) return -1; | |
| return ans; | |
| } | |
| function updateHead() { | |
| if (!result) return; | |
| const t = els.audio.currentTime || 0; | |
| els.head.style.left = `${Math.min(100, (100 * t) / Math.max(result.duration, 1e-3))}%`; | |
| const i = find(t); | |
| if (i === cur) return; | |
| if (cur >= 0) { | |
| wordEls[cur]?.classList.remove("on"); | |
| blockEls[cur]?.classList.remove("on"); | |
| } | |
| cur = i; | |
| if (i >= 0) { | |
| const w = wordEls[i]; | |
| w.classList.add("on"); | |
| blockEls[i]?.classList.add("on"); | |
| const l = els.words; | |
| if (w.offsetTop < l.scrollTop || w.offsetTop > l.scrollTop + l.clientHeight - 30) l.scrollTop = w.offsetTop - l.clientHeight / 3; | |
| } | |
| } | |
| function loop() { | |
| updateHead(); | |
| if (!els.audio.paused) raf = requestAnimationFrame(loop); | |
| } | |
| function playFrom(i) { | |
| const u = result?.units[i]; | |
| if (!u || u.score === null) return; | |
| els.audio.currentTime = u.start + 0.001; | |
| els.audio.play().catch(() => {}); | |
| } | |
| // -- snippets ---------------------------------------------------------------------------------- | |
| function snippets(langValue, gran) { | |
| let lang = parseLang(langValue); | |
| if (lang === "und") lang = "eng"; | |
| const chars = gran === "characters"; | |
| const iso1 = TO_ISO1[lang]; | |
| const splitCli = chars ? " --split_size char" : ""; | |
| const splitPy = chars ? ', split_size="char"' : ""; | |
| const cfaCli = `pip install git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git | |
| ctc-forced-aligner --audio_path audio.wav --text_path transcript.txt \\ | |
| --language ${lang}${splitCli} \\ | |
| --alignment_model ${MODEL_ID} | |
| # writes audio.txt and audio.json with word start/end times`; | |
| const cfaPy = `import torch | |
| from ctc_forced_aligner import (load_audio, load_alignment_model, generate_emissions, | |
| preprocess_text, get_alignments, get_spans, postprocess_results) | |
| model, tokenizer = load_alignment_model( | |
| "cpu", "${MODEL_ID}", dtype=torch.float32) | |
| audio = load_audio("audio.wav", model.dtype, model.device) # uses ffmpeg | |
| emissions, stride = generate_emissions(model, audio, batch_size=4) | |
| text = open("transcript.txt").read().replace("\\n", " ").strip() | |
| tokens_starred, text_starred = preprocess_text( | |
| text, romanize=False, language="${lang}", star_frequency="edges"${splitPy}) | |
| segments, scores, blank = get_alignments(emissions, tokens_starred, tokenizer) | |
| spans = get_spans(tokens_starred, segments, blank) | |
| words = postprocess_results(text_starred, spans, stride, scores) | |
| print(words[:3]) # [{'start': ..., 'end': ..., 'text': ..., 'score': ...}, ...]`; | |
| const wxCli = `pip install whisperx | |
| whisperx audio.wav${iso1 ? ` --language ${iso1}` : ""} --align_model ${MODEL_ID}`; | |
| const wxPy = `import whisperx | |
| device = "cpu" | |
| audio = whisperx.load_audio("audio.wav") | |
| asr = whisperx.load_model("large-v3", device, compute_type="int8") | |
| result = asr.transcribe(audio, batch_size=8) | |
| align_model, metadata = whisperx.load_align_model( | |
| language_code=${iso1 ? `"${iso1}"` : 'result["language"]'}, device=device, | |
| model_name="${MODEL_ID}") | |
| aligned = whisperx.align(result["segments"], align_model, metadata, audio, device) | |
| print(aligned["word_segments"][:3]) | |
| # Already have the transcript? Skip ASR and align it directly: | |
| segments = [{"text": open("transcript.txt").read(), "start": 0.0, "end": len(audio) / 16000}] | |
| aligned = whisperx.align(segments, align_model, metadata, audio, device)`; | |
| const js = `// aligner.js + deps.js from this Space (transformers.js 4.3.2, ONNX Runtime Web) | |
| import { ForcedAligner, groupCues, toSrt } from "./aligner.js"; | |
| const aligner = await ForcedAligner.load( | |
| "${MODEL_ID}", | |
| { dtype: "q8" }, // int8 ONNX, about 370 MB. Full precision: { dtype: "fp32" } | |
| ); | |
| // wav: Float32Array, 16 kHz mono (e.g. decoded with an OfflineAudioContext at 16000 Hz) | |
| const { units, unknown } = await aligner.align(wav, transcript, { | |
| lang: "${lang}",${chars ? '\n granularity: "characters",' : ""} | |
| }); | |
| console.log(units.map((u) => [u.text, u.start, u.end, u.score])); | |
| const srt = toSrt(groupCues(units, { maxChars: 42 }));`; | |
| return { cfaCli, cfaPy, wxCli, wxPy, js }; | |
| } | |
| function updateSnippets() { | |
| const s = snippets(els.lang.value, radio("gran")); | |
| $("code-cfa-cli").textContent = s.cfaCli; | |
| $("code-cfa-py").textContent = s.cfaPy; | |
| $("code-wx-cli").textContent = s.wxCli; | |
| $("code-wx-py").textContent = s.wxPy; | |
| $("code-js").textContent = s.js; | |
| } | |
| // -- copy helper ------------------------------------------------------------------------------- | |
| async function copyText(text, btn) { | |
| try { | |
| await navigator.clipboard.writeText(text); | |
| } catch { | |
| const ta = document.createElement("textarea"); | |
| ta.value = text; | |
| document.body.append(ta); | |
| ta.select(); | |
| document.execCommand("copy"); | |
| ta.remove(); | |
| } | |
| const old = btn.textContent; | |
| btn.textContent = "Copied"; | |
| setTimeout(() => (btn.textContent = old), 1200); | |
| } | |
| // -- wiring ------------------------------------------------------------------------------------ | |
| function loadExample(ex, run) { | |
| els.transcript.value = ex.text; | |
| els.lang.value = ex.lang; | |
| setRadio("gran", ex.gran); | |
| updateSnippets(); | |
| setSource(ex.audio.split("/").pop(), ex.audio); | |
| if (run) align(); | |
| } | |
| async function showDefault() { | |
| // First visit: show the English example's result right away, before the model has downloaded. | |
| try { | |
| const d = await (await fetch("examples/default.json")).json(); | |
| if (result) return; | |
| result = { ...d, unknown: d.unknown || [], timing: null, stem: stemOf(EXAMPLES[0].audio.split("/").pop()) }; | |
| render(); | |
| } catch { | |
| /* optional */ | |
| } | |
| } | |
| function init() { | |
| $("model-link").href = isRepoId(model) ? `https://huggingface.co/${model}` : `https://huggingface.co/${MODEL_ID}`; | |
| els.running.textContent = model + (dtype !== "q8" ? ` (${dtype})` : ""); | |
| for (const [name, iso3] of LANGUAGES) { | |
| const o = document.createElement("option"); | |
| o.value = iso3; | |
| o.label = `${name} (${iso3})`; | |
| o.textContent = `${name} (${iso3})`; | |
| els.langs.append(o); | |
| } | |
| EXAMPLES.forEach((ex) => { | |
| const b = document.createElement("button"); | |
| b.type = "button"; | |
| b.className = "chip"; | |
| b.textContent = ex.label; | |
| b.addEventListener("click", () => loadExample(ex, true)); | |
| els.examples.append(b); | |
| }); | |
| loadExample(EXAMPLES[0], false); | |
| showDefault(); | |
| els.pick.addEventListener("click", () => els.file.click()); | |
| els.file.addEventListener("change", () => onFile(els.file.files[0])); | |
| els.record.addEventListener("click", toggleRecord); | |
| for (const ev of ["dragenter", "dragover"]) { | |
| els.drop.addEventListener(ev, (e) => { | |
| e.preventDefault(); | |
| els.drop.classList.add("over"); | |
| }); | |
| } | |
| for (const ev of ["dragleave", "drop"]) els.drop.addEventListener(ev, () => els.drop.classList.remove("over")); | |
| els.drop.addEventListener("drop", (e) => { | |
| e.preventDefault(); | |
| onFile(e.dataTransfer?.files?.[0]); | |
| }); | |
| els.lang.addEventListener("change", () => { | |
| setRadio("gran", CJK_LANGS.has(parseLang(els.lang.value)) ? "characters" : "words"); | |
| updateSnippets(); | |
| }); | |
| els.lang.addEventListener("input", updateSnippets); | |
| for (const r of document.querySelectorAll('input[name="gran"]')) r.addEventListener("change", updateSnippets); | |
| for (const r of document.querySelectorAll('input[name="cue"]')) r.addEventListener("change", updateDownloads); | |
| els.maxChars.addEventListener("input", () => { | |
| els.maxCharsOut.value = els.maxChars.value; | |
| updateDownloads(); | |
| }); | |
| els.run.addEventListener("click", align); | |
| els.transcript.addEventListener("keydown", (e) => { | |
| if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { | |
| e.preventDefault(); | |
| align(); | |
| } | |
| }); | |
| els.audio.addEventListener("play", () => { | |
| cancelAnimationFrame(raf); | |
| loop(); | |
| }); | |
| els.audio.addEventListener("seeked", updateHead); | |
| els.audio.addEventListener("timeupdate", updateHead); | |
| els.words.addEventListener("click", (e) => { | |
| const w = e.target.closest(".w"); | |
| if (w) playFrom(Number(w.dataset.i)); | |
| }); | |
| els.table.addEventListener("click", (e) => { | |
| const tr = e.target.closest("tr"); | |
| if (tr) playFrom(Number(tr.dataset.i)); | |
| }); | |
| els.timeline.addEventListener("click", (e) => { | |
| if (!result) return; | |
| const r = els.timeline.getBoundingClientRect(); | |
| els.audio.currentTime = Math.max(0, (e.clientX - r.left) / r.width) * result.duration; | |
| }); | |
| els.copyTable.addEventListener("click", () => { | |
| if (!result) return; | |
| const lines = ["#\tword\tstart\tend\tscore", ...result.units.map((u, i) => | |
| [i + 1, u.text, u.start.toFixed(2), u.end.toFixed(2), u.score === null ? "" : u.score.toFixed(3)].join("\t"))]; | |
| copyText(lines.join("\n"), els.copyTable); | |
| }); | |
| for (const b of document.querySelectorAll(".copy-code")) { | |
| b.addEventListener("click", () => copyText($(b.dataset.target).textContent, b)); | |
| } | |
| const tabs = ["cfa", "wx", "js"]; | |
| for (const t of tabs) { | |
| $(`tab-${t}`).addEventListener("click", () => { | |
| for (const o of tabs) { | |
| $(`tab-${o}`).setAttribute("aria-selected", String(o === t)); | |
| $(`pane-${o}`).hidden = o !== t; | |
| } | |
| }); | |
| } | |
| updateSnippets(); | |
| // Respect data-saver / cellular connections: ask before downloading the model. | |
| const conn = navigator.connection; | |
| const metered = conn && (conn.saveData || conn.type === "cellular" || /2g|3g/.test(conn.effectiveType || "")); | |
| if (metered) { | |
| setStatus("idle", "Model not loaded", `about ${MODEL_MB[dtype]} MB download`); | |
| els.loadBtn.textContent = `Load model (about ${MODEL_MB[dtype]} MB)`; | |
| els.loadBtn.hidden = false; | |
| els.loadBtn.addEventListener("click", loadModel, { once: true }); | |
| } else loadModel(); | |
| } | |
| init(); | |