// One module worker per role: 'stream' (live first pass) or 'correct' (full-context second pass + LM). import * as ort from 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.29.0/dist/ort.webgpu.min.mjs'; import { Engine, parseTokens } from './asr.js'; import { NgramLM } from './lm.js'; import { fbankAll, frameAt, readyFrames, numFrames } from './fbank.js'; const HF = 'https://huggingface.co/Reza2kn/Shenava-Rizeh-v1.5-sherpa-onnx/resolve/main/'; const FILES = { stream: HF + 'streaming/encoder.int4.onnx', offline: HF + 'encoder.int4.onnx', dec: HF + 'decoder.onnx', joi: HF + 'joiner.onnx', tokens: HF + 'tokens.txt', lm: './shenava-web-3gram.bin', }; ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.29.0/dist/'; let role, eng, lm, backend = 'wasm'; const post = (m, t) => self.postMessage(m, t || []); async function fetchCached(key, url) { let cache = null; try { cache = await caches.open('shenava-rizeh-v1.5'); const hit = await cache.match(url); if (hit) { post({ type: 'progress', key, loaded: 1, total: 1 }); return await hit.arrayBuffer(); } } catch (e) {} const r = await fetch(url, { mode: 'cors' }); if (!r.ok) throw new Error(`download failed ${r.status}: ${url}`); const total = +r.headers.get('content-length') || 0, reader = r.body.getReader(), parts = []; let loaded = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; parts.push(value); loaded += value.length; post({ type: 'progress', key, loaded, total }); } const buf = new Uint8Array(loaded); let o = 0; for (const p of parts) { buf.set(p, o); o += p.length; } try { if (cache) await cache.put(url, new Response(buf.slice().buffer, { headers: { 'content-type': 'application/octet-stream' } })); } catch (e) {} return buf.buffer; } async function session(buf, gpu) { const threads = self.crossOriginIsolated ? Math.max(1, Math.min(4, (navigator.hardwareConcurrency || 4) >> 1)) : 1; ort.env.wasm.numThreads = threads; const base = { graphOptimizationLevel: 'all' }; if (gpu && 'gpu' in navigator) { try { const s = await ort.InferenceSession.create(buf, { ...base, executionProviders: ['webgpu'] }); backend = 'webgpu'; return s; } catch (e) { post({ type: 'log', msg: 'WebGPU unavailable for this model, using WASM: ' + e.message }); } } return ort.InferenceSession.create(buf, { ...base, executionProviders: ['wasm'] }); } // ---------- streaming state ---------- let st, audio = new Float32Array(16000 * 60), nAudio = 0, feats = new Float32Array(80 * 6000), nFeat = 0, chunk = 0, busy = false, finished = false; function append(x) { if (nAudio + x.length > audio.length) { const a = new Float32Array(Math.max(audio.length * 2, nAudio + x.length)); a.set(audio.subarray(0, nAudio)); audio = a; } audio.set(x, nAudio); nAudio += x.length; } function computeFrames() { const target = finished ? numFrames(nAudio) : readyFrames(nAudio); if (target * 80 > feats.length) { const f = new Float32Array(Math.max(feats.length * 2, target * 80)); f.set(feats.subarray(0, nFeat * 80)); feats = f; } for (; nFeat < target; nFeat++) frameAt(audio, finished ? nAudio : Math.max(nAudio, 1), nFeat, feats, nFeat * 80); } async function pump() { if (busy || !st) return; busy = true; try { for (;;) { computeFrames(); const s0 = chunk * eng.hop; if (s0 + eng.T > nFeat && !(finished && s0 < nFeat)) break; const x = new Float32Array(eng.T * 80); x.set(feats.subarray(s0 * 80, Math.min(nFeat, s0 + eng.T) * 80)); const k0 = st.toks.length, t0 = performance.now(); await eng.streamChunk(st, x); chunk++; post({ type: 'tokens', toks: st.toks.slice(k0), frames: st.frames.slice(k0), chunk, ms: performance.now() - t0, audioSec: Math.min(nAudio, chunk * eng.hop * 160) / 16000 }); } if (finished) post({ type: 'flushed', audioSec: nAudio / 16000 }); } catch (e) { post({ type: 'error', msg: String(e && e.message || e) }); } busy = false; } let chain = Promise.resolve(); self.onmessage = ({ data: m }) => { chain = chain.then(() => handle(m)); }; async function handle(m) { try { if (m.type === 'init') { role = m.role; const need = role === 'stream' ? ['stream', 'dec', 'joi', 'tokens'] : ['offline', 'dec', 'joi', 'tokens', 'lm']; const bufs = Object.fromEntries(await Promise.all(need.map(async k => [k, await fetchCached(k, FILES[k])]))); const pieces = parseTokens(new TextDecoder().decode(bufs.tokens)); const cfg = await (await fetch('./stream_config.json')).json(); const sess = { streamEnc: role === 'stream' ? await session(bufs.stream, false) : null, // small 320 ms chunks: WASM has lower latency than WebGPU here offEnc: role === 'correct' ? await session(bufs.offline, m.gpu) : null, dec: await session(bufs.dec, false), joi: await session(bufs.joi, false), }; // WebGPU can reject individual kernels at run time: fall back to WASM for that model once, transparently const guard = (key, buf) => { const s = sess[key]; if (!s) return; let cur = s, fellBack = false; sess[key] = { run: async (feeds) => { try { return await cur.run(feeds); } catch (e) { if (fellBack || backend !== 'webgpu') throw e; fellBack = true; post({ type: 'log', msg: key + ' on WebGPU failed (' + e.message + '); switching to WASM' }); cur = await ort.InferenceSession.create(buf, { graphOptimizationLevel: 'all', executionProviders: ['wasm'] }); backend = 'wasm'; post({ type: 'backend', backend }); return cur.run(feeds); } } }; }; guard('streamEnc', bufs.stream); guard('offEnc', bufs.offline); eng = new Engine(ort, sess, pieces, cfg); if (bufs.lm) lm = new NgramLM(bufs.lm); if (role === 'stream') st = await eng.newStream(); post({ type: 'ready', backend, pieces, threads: ort.env.wasm.numThreads }); } else if (m.type === 'audio') { append(m.samples); pump(); } else if (m.type === 'end') { finished = true; pump(); } else if (m.type === 'reset') { audio = new Float32Array(16000 * 60); nAudio = 0; nFeat = 0; chunk = 0; finished = false; while (busy) await new Promise(r => setTimeout(r, 10)); st = await eng.newStream(); post({ type: 'reset-done' }); } else if (m.type === 'correct') { const t0 = performance.now(), F = fbankAll(m.samples), T = F.length / 80; if (T < 12) { post({ type: 'corrected', id: m.id, gen: m.gen, toks: [], text: '', ms: 0, final: m.final }); return; } const { enc, n } = await eng.encodeFull(F, T); const r = await eng.beam(enc, n, { beam: m.beam || 4, lm: m.useLM ? lm : null, alpha: m.alpha, beta: m.beta }); post({ type: 'corrected', id: m.id, gen: m.gen, toks: r.toks, text: r.text, ms: performance.now() - t0, upto: m.upto, final: m.final }); } } catch (e) { post({ type: 'error', msg: String(e && e.message || e), stack: e && e.stack }); } }