/* Reading Coach: Su-śrotā known-text tracker, in JavaScript. A line-by-line port of helper/engine.py (features, tokenizer, CTC Viterbi trellis, Tracker) so the browser gives the same word events as the local helper. Runs in a Web Worker (importScripts) or Node. */ (function (root) { 'use strict'; const SR = 16000, HOP = 160, FRAME = 0.04, NEG = -1e30; /* ---------- Python-compatible rounding (round half to even on exact ties) ---------- */ function pyRound(x, nd) { const m = Math.pow(10, nd), y = x * m, f = Math.floor(y), d = y - f; let r; if (Math.abs(d - 0.5) < 1e-9) { // possible tie: decide on the exact decimal value const s = x.toFixed(nd + 12), q = s.slice(-12); if (/^50*$/.test(q)) r = (f % 2 === 0) ? f : f + 1; else r = Math.round(y); } else r = Math.round(y); return r / m; } const pyRoundInt = x => { const f = Math.floor(x), d = x - f; return d > 0.5 ? f + 1 : d < 0.5 ? f : (f % 2 === 0 ? f : f + 1); }; /* ---------- features (same maths as engine.features / NeMo preprocessor) ---------- */ let FB = null, FBR = null, W512 = null; function setFrontend(melFb, window400) { // melFb: Float32Array 80*257, window400: Float32Array 400 FB = melFb; W512 = new Float32Array(512); W512.set(window400, 56); FBR = []; // non-zero range of each mel triangle (speed) for (let m = 0; m < 80; m++) { let a = 257, b = -1; for (let k = 0; k < 257; k++) if (FB[m * 257 + k] !== 0) { if (k < a) a = k; b = k; } FBR.push([a, b + 1]); } } const N = 512, RE = new Float64Array(N), IM = new Float64Array(N), REV = new Uint16Array(N), COS = new Float64Array(N / 2), SIN = new Float64Array(N / 2); (function () { for (let i = 0; i < N; i++) { let r = 0; for (let b = 0, v = i; b < 9; b++, v >>= 1) r = (r << 1) | (v & 1); REV[i] = r; } for (let i = 0; i < N / 2; i++) { COS[i] = Math.cos(-2 * Math.PI * i / N); SIN[i] = Math.sin(-2 * Math.PI * i / N); } })(); function fft() { for (let i = 0; i < N; i++) { const j = REV[i]; if (j > i) { let t = RE[i]; RE[i] = RE[j]; RE[j] = t; t = IM[i]; IM[i] = IM[j]; IM[j] = t; } } for (let size = 2; size <= N; size <<= 1) { const half = size >> 1, step = N / size; for (let i = 0; i < N; i += size) for (let j = 0; j < half; j++) { const c = COS[j * step], s = SIN[j * step], a = i + j, b = a + half; const tr = RE[b] * c - IM[b] * s, ti = RE[b] * s + IM[b] * c; RE[b] = RE[a] - tr; IM[b] = IM[a] - ti; RE[a] += tr; IM[a] += ti; } } } function features(x) { // x: Float32Array (16 kHz) → {data: Float32Array 80*nfr (row-major), nfr} const n = x.length, seq = Math.floor(n / HOP) + 1; const pe = new Float32Array(n); pe[0] = x[0]; for (let i = 1; i < n; i++) pe[i] = Math.fround(x[i] - Math.fround(0.97 * x[i - 1])); const L = n + 512, xp = new Float32Array(L); for (let i = 0; i < 256; i++) xp[i] = pe[256 - i]; // numpy 'reflect' padding xp.set(pe, 256); for (let i = 0; i < 256; i++) xp[256 + n + i] = pe[n - 2 - i]; const nfr = Math.floor((L - 512) / HOP) + 1, out = new Float32Array(80 * nfr), pw = new Float32Array(257); for (let f = 0; f < nfr; f++) { const o = f * HOP; for (let k = 0; k < N; k++) { RE[k] = Math.fround(xp[o + k] * W512[k]); IM[k] = 0; } fft(); for (let k = 0; k < 257; k++) pw[k] = Math.fround(RE[k] * RE[k] + IM[k] * IM[k]); for (let m = 0; m < 80; m++) { const [a, b] = FBR[m]; let s = 0; for (let k = a; k < b; k++) s += FB[m * 257 + k] * pw[k]; out[m * nfr + f] = Math.fround(Math.log(Math.fround(s) + 5.960464477539063e-8)); } } for (let m = 0; m < 80; m++) { // per-feature normalisation over the first seq frames let mu = 0; for (let f = 0; f < seq; f++) mu += out[m * nfr + f]; mu /= seq; let v = 0; for (let f = 0; f < seq; f++) { const d = out[m * nfr + f] - mu; v += d * d; } const sd = Math.sqrt(v / Math.max(seq - 1, 1)) + 1e-5; for (let f = 0; f < nfr; f++) out[m * nfr + f] = Math.fround((out[m * nfr + f] - mu) / sd); } return { data: out, nfr }; } /* ---------- text ---------- */ const KEEP = /[^\u0900-\u0963\u0971-\u097F\u1CD0-\u1CFF\uA8E0-\uA8FF]/g; function normWord(w) { w = String(w).normalize('NFC').replace(/ॐ/g, 'ओम्'); w = w.replace(/[\u0951-\u0954\u1CD0-\u1CFF\uA8E0-\uA8F1]/g, '').replace(/ऽ/g, ''); return w.replace(KEEP, ''); } function lev(a, b) { a = Array.from(a); b = Array.from(b); if (a.join('') === b.join('')) return 0; let prev = []; for (let j = 0; j <= b.length; j++) prev.push(j); for (let i = 1; i <= a.length; i++) { const cur = [i]; for (let j = 1; j <= b.length; j++) cur.push(Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] !== b[j - 1] ? 1 : 0))); prev = cur; } return prev[b.length]; } function sim(a, b) { if (!a && !b) return 1.0; return 1 - lev(a, b) / Math.max(Array.from(a).length, Array.from(b).length); } /* ---------- SentencePiece BPE (model_type BPE, nmt_nfkc, add_dummy_prefix) ---------- */ class SP { constructor(j) { this.pieces = j.pieces.map(p => p[0]); this.score = j.pieces.map(p => p[1]); this.type = j.pieces.map(p => p[2]); this.id = new Map(); this.pieces.forEach((p, i) => { if (this.type[i] === 1 || this.type[i] === 4) this.id.set(p, i); }); this.unk = j.unk || 0; } encode(text) { text = String(text).normalize('NFKC').replace(/\s+/g, ' ').trim(); if (!text) return []; const sym = Array.from('▁' + text.replace(/ /g, '▁')); for (;;) { // merge the best-scoring adjacent pair (leftmost on ties) let best = -1, bs = -Infinity; for (let i = 0; i + 1 < sym.length; i++) { const id = this.id.get(sym[i] + sym[i + 1]); if (id !== undefined && this.score[id] > bs) { bs = this.score[id]; best = i; } } if (best < 0) break; sym.splice(best, 2, sym[best] + sym[best + 1]); } const out = []; for (const s of sym) { const id = this.id.get(s); if (id !== undefined) out.push(id); else out.push(this.unk); } return out; } decode(ids) { let s = ids.map(i => i === this.unk ? ' \u2047 ' : this.pieces[i]).join('').replace(/▁/g, ' '); if (s.startsWith(' ')) s = s.slice(1); return s; } } /* ---------- model wrapper (session = onnxruntime-web InferenceSession) ---------- */ class Model { constructor(ort, session, sp) { this.ort = ort; this.sess = session; this.sp = sp; this.name = 'sushrota_sa_ctc.int8.onnx'; } async logprobs(wav) { // → {P: Float32Array T*257, T} const f = features(wav); const feeds = { features: new this.ort.Tensor('float32', f.data, [1, 80, f.nfr]), length: new this.ort.Tensor('int64', BigInt64Array.from([BigInt(f.nfr)]), [1]) }; const r = await this.sess.run(feeds); const lp = r[this.sess.outputNames[0]]; return { P: lp.data, T: lp.dims[1] }; } tokens(word) { const w = normWord(word); return w ? this.sp.encode(w).map(i => i + 1) : []; } decode(cols) { const ids = cols.filter(c => c > 0).map(c => c - 1); return ids.length ? this.sp.decode(ids) : ''; } wordStart(cols) { for (let i = 0; i < cols.length; i++) if (cols[i] > 0 && this.sp.pieces[cols[i] - 1].startsWith('▁')) return cols.slice(i); return []; } } /* ---------- CTC Viterbi ---------- */ // P is a view: rows [r0, r0+T) of a Float32Array with 257 columns function trellis(P, r0, T, toks) { const S = [0]; for (const t of toks) S.push(t, 0); const L = S.length, skip = new Uint8Array(L); for (let s = 2; s < L; s++) skip[s] = (S[s] !== 0 && S[s] !== S[s - 2]) ? 1 : 0; let D = new Float64Array(L).fill(NEG), Dn = new Float64Array(L); D[0] = P[r0 * 257 + S[0]]; if (L > 1) D[1] = P[r0 * 257 + S[1]]; const B = new Int8Array(T * L); for (let t = 1; t < T; t++) { const row = (r0 + t) * 257; for (let s = 0; s < L; s++) { const c0 = D[s], c1 = s >= 1 ? D[s - 1] : NEG, c2 = (skip[s] && s >= 2) ? D[s - 2] : NEG; let b = 0, v = c0; if (c1 > v) { b = 1; v = c1; } if (c2 > v) { b = 2; v = c2; } Dn[s] = v + P[row + S[s]]; B[t * L + s] = b; } const tmp = D; D = Dn; Dn = tmp; } return { S, D, B, L }; } function backtrack(B, L, s, T) { const path = new Int32Array(T); for (let t = T - 1; t >= 0; t--) { path[t] = s; s -= B[t * L + s]; } return path; } const argmaxArr = a => { let b = 0; for (let i = 1; i < a.length; i++) if (a[i] > a[b]) b = i; return b; }; const meanF = a => { if (!a.length) return NaN; let s = 0; for (const v of a) s += v; return s / a.length; }; /* ---------- Tracker (see engine.Tracker for the reasoning behind each step) ---------- */ class Tracker { constructor(model, words, pos, onMisread) { this.m = model; this.words = words.map(String); this.toks = this.words.map(w => model.tokens(w)); this.onMisread = onMisread || 'stay'; this.audio = new Float32Array(0); this.t0 = 0; this.total = 0; this.reset(pos || 0); } reset(pos) { this.pos = Math.max(0, Math.min(Math.trunc(pos), this.words.length)); this.anchor = this.total; this.frozen = false; this.audio = new Float32Array(0); this.t0 = this.total; this.skipEmpty([]); } push(pcm) { const a = new Float32Array(this.audio.length + pcm.length); a.set(this.audio); a.set(pcm, this.audio.length); this.audio = a; this.total = this.t0 + this.audio.length / SR; } skipEmpty(ev) { while (this.pos < this.words.length && !this.toks[this.pos].length) { ev.push({ type: 'word', idx: this.pos, status: 'matched', gop: 0.0, heard: '', start: this.anchor, end: this.anchor }); this.pos++; } return ev; } progress(tentative, finished, partial, speaking) { return { type: 'progress', pos: this.pos, tentative: Math.trunc(tentative), partial: pyRound(partial, 2), speaking, frozen: this.frozen, audio_t: pyRound(this.total, 2) }; } status(gop, agree, hk) { if (gop >= Tracker.GOP_OK || (agree >= 0.8 && gop >= Tracker.GOP_BAD * 2)) return 'matched'; if (gop < Tracker.GOP_BAD && agree < 0.6 && (Array.from(hk).length >= 2 || gop < 2 * Tracker.GOP_BAD)) return 'misread'; return 'unclear'; } async update() { const ev = []; if (this.pos >= this.words.length || this.frozen) return [ev, { type: 'progress', pos: this.pos, tentative: this.pos, partial: 0.0, speaking: false, frozen: this.frozen }]; if (this.total - this.anchor > Tracker.MAX_WIN) this.anchor = this.total - Tracker.MAX_WIN * 0.6; const keepFrom = Math.max(this.t0, this.anchor - Tracker.CTX); const cut = pyRoundInt((keepFrom - this.t0) * SR); if (cut > 0) { this.audio = this.audio.slice(cut); this.t0 += cut / SR; } if (this.audio.length < SR * 0.3) return [ev, this.progress(this.pos, 0, 0.0, false)]; const { P, T: TT } = await this.m.logprobs(this.audio); this.lastFrames = TT; const fA = Math.trunc(Math.max(0.0, this.anchor - this.t0) / FRAME); const T = TT - fA; if (T < 3) return [ev, this.progress(this.pos, 0, 0.0, false)]; const row = t => (fA + t) * 257; const nW = Math.min(Tracker.LOOKAHEAD, this.words.length - this.pos); const toks = [], owner = []; for (let k = 0; k < nW; k++) for (const x of this.toks[this.pos + k]) { toks.push(x); owner.push(k); } const { S, D, B, L } = trellis(P, fA, T, toks); const sEnd = argmaxArr(D); const path = backtrack(B, L, sEnd, T); const lastTok = sEnd % 2 === 1 ? (sEnd - 1) / 2 : sEnd / 2 - 1; const ntok = lastTok + 1; const ends = []; let n = 0; for (let k = 0; k < nW; k++) { n += this.toks[this.pos + k].length; ends.push(n); } const finished = ends.filter(e => e <= ntok).length; const curStart = finished ? ends[finished - 1] : 0; let partial = 0.0; if (finished < nW) partial = (ntok - curStart) / Math.max(1, ends[finished] - curStart); const tokspan = new Map(); for (let t = 0; t < T; t++) { const s = path[t]; if (s % 2 === 1) { const i = (s - 1) / 2; if (!tokspan.has(i)) tokspan.set(i, []); tokspan.get(i).push(t); } } const free = new Float32Array(T), amax = new Int32Array(T), blankP = new Float32Array(T); for (let t = 0; t < T; t++) { const r = row(t); let b = 0; for (let c = 1; c < 257; c++) if (P[r + c] > P[r + b]) b = c; free[t] = P[r + b]; amax[t] = b; blankP[t] = Math.fround(Math.exp(P[r])); } const speaking = T >= 12 && meanF(blankP.slice(T - 12)) < 0.75; let commit = 0; const tokIdx = k => { const r = []; owner.forEach((o, i) => { if (o === k) r.push(i); }); return r; }; for (let k = 0; k < finished; k++) { const fr = []; for (const i of tokIdx(k)) for (const t of (tokspan.get(i) || [])) fr.push(t); fr.sort((a, b) => a - b); const wend = fr.length ? fr[fr.length - 1] + 1 : 0; let ok; if (k < finished - 1) ok = true; else { const after = blankP.slice(wend), ns = Math.trunc(Tracker.SIL_COMMIT / FRAME); const tail = after.slice(Math.max(0, after.length - ns)); const sil = after.length * FRAME >= Tracker.SIL_COMMIT && meanF(Array.from(tail, v => v > 0.5 ? 1 : 0)) >= 0.8; ok = sil || (finished < nW && partial >= 0.5 && (ntok - curStart) >= 2) || (this.pos + k === this.words.length - 1 && sil); } if (!ok) break; commit = k + 1; } const base = this.t0 + fA * FRAME; for (let k = 0; k < commit; k++) { const wi = this.pos + k; if (!this.toks[wi].length) { const e0 = ev.length ? ev[ev.length - 1].end : pyRound(base, 2); ev.push({ type: 'word', idx: wi, status: 'matched', gop: 0.0, agree: 1.0, heard: '', start: e0, end: e0 }); continue; } const frs = []; for (const i of tokIdx(k)) for (const t of (tokspan.get(i) || [])) frs.push([i, t]); const ts = frs.map(x => x[1]).sort((a, b) => a - b); const gop = frs.length ? meanF(frs.map(([i, t]) => Math.fround(P[row(t) + toks[i]] - free[t]))) : -20.0; const a = ts.length ? ts[0] : 0, b = ts.length ? ts[ts.length - 1] + 1 : 0; const cols = []; let prev = -1; for (let t = a; t < Math.min(T, b + 1); t++) { const c = amax[t]; if (c !== prev && c !== 0) cols.push(c); prev = c; } const ws = this.m.wordStart(cols); const heard = this.m.decode(ws.length ? ws : cols).trim(); const agree = sim(normWord(heard), normWord(this.words[wi])); const status = this.status(gop, agree, normWord(heard)); ev.push({ type: 'word', idx: wi, status, gop: pyRound(gop, 2), agree: pyRound(agree, 2), heard, start: pyRound(base + a * FRAME, 2), end: pyRound(base + b * FRAME, 2) }); if (status === 'misread' && this.onMisread === 'stay') { commit = k + 1; this.frozen = true; break; } } if (!commit && finished === 0) { const att = this.attempt(P, fA, T, base, blankP, amax); if (att && att.status === 'misread') { const hk = normWord(att.heard), wi = att.idx; const prev = wi > 0 ? normWord(this.words[wi - 1]) : '', nxt = wi + 1 < this.words.length ? normWord(this.words[wi + 1]) : ''; if (prev && sim(hk, Array.from(prev).slice(0, Array.from(hk).length).join('')) >= 0.75 && Array.from(hk).length >= 2) { ev.push(Object.assign({}, att, { idx: wi - 1, status: 'matched', repeat: true })); this.anchor = att.end; return [ev, this.progress(this.pos, 0, 0.0, speaking)]; } if (nxt && sim(hk, nxt) >= 0.75) att.skipped = true; } if (att) { ev.push(att); commit = 1; } if (att && att.status === 'misread' && this.onMisread === 'stay') this.frozen = true; if (att && att.skipped && !this.frozen) { this.pos = att.idx + 1; this.anchor = att.start; return [ev, this.progress(this.pos, 0, 0.0, speaking)]; } } if (commit) { const last = ev[ev.length - 1]; this.anchor = last.end; if (this.frozen) this.pos = last.idx; else { this.pos = last.idx + 1; this.skipEmpty(ev); } return [ev, this.progress(this.pos, 0, 0.0, speaking)]; } return [ev, this.progress(this.pos + finished, finished, partial, speaking)]; } attempt(P, fA, T, base, blankP, amax) { const ns = Math.trunc(Tracker.SIL_ATTEMPT / FRAME); if (T < ns + 4 || meanF(Array.from(blankP.slice(T - ns), v => v > 0.5 ? 1 : 0)) < 0.9) return null; const nb = []; for (let t = 0; t < T - ns; t++) if (amax[t] !== 0) nb.push(t); if (nb.length < 2) return null; let cols = [], prev = -1; const first = new Map(); for (let t = nb[0]; t <= nb[nb.length - 1]; t++) { const c = amax[t]; if (c !== prev && c !== 0) { cols.push(c); if (!first.has(cols.length - 1)) first.set(cols.length - 1, t); } prev = c; } const ws = this.m.wordStart(cols); if (!ws.length) return null; const a = first.get(cols.length - ws.length), b = nb[nb.length - 1] + 1; cols = ws; const heard = this.m.decode(cols).trim(), hk = normWord(heard); const wi = this.pos, exp = normWord(this.words[wi]); const hl = Array.from(hk).length, el = Array.from(exp).length; if (hl < 2) return null; if (hl <= el - 2 && sim(hk, Array.from(exp).slice(0, hl).join('')) >= 0.75) return null; const lo = Math.max(0, a - 2), hi = Math.min(T, b + 12); const toks = this.toks[wi]; const { S, D, B, L } = trellis(P, fA + lo, hi - lo, toks); const sEnd = D[L - 1] >= D[L - 2] ? L - 1 : L - 2; const path = backtrack(B, L, sEnd, hi - lo); const vals = []; for (let t = 0; t < hi - lo; t++) { const s = path[t]; if (s % 2 !== 1) continue; const r = (fA + lo + t) * 257; let mx = P[r]; for (let c = 1; c < 257; c++) if (P[r + c] > mx) mx = P[r + c]; vals.push(Math.fround(P[r + S[s]] - mx)); } const gop = vals.length ? meanF(vals) : -20.0; const agree = sim(hk, exp); const status = this.status(gop, agree, hk); return { type: 'word', idx: wi, status, gop: pyRound(gop, 2), agree: pyRound(agree, 2), heard, start: pyRound(base + a * FRAME, 2), end: pyRound(base + b * FRAME, 2), attempt: true }; } } Object.assign(Tracker, { LOOKAHEAD: 8, CTX: 1.0, MAX_WIN: 18.0, SIL_COMMIT: 0.45, GOP_OK: -1.5, GOP_BAD: -4.0, SIL_ATTEMPT: 1.0 }); const api = { SR, FRAME, setFrontend, features, normWord, sim, lev, SP, Model, Tracker, trellis, backtrack, pyRound }; if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.RCE = api; })(typeof self !== 'undefined' ? self : this);