Spaces:
Running

File size: 14,526 Bytes
9b81ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ec514e
9b81ca9
 
 
 
8ec514e
9b81ca9
 
8ec514e
9b81ca9
 
 
 
 
 
 
 
 
 
 
 
8ec514e
 
 
 
 
9b81ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e67b001
9b81ca9
 
 
 
 
 
 
 
 
 
 
 
1ec5849
9b81ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ec5849
 
9b81ca9
 
1ec5849
9b81ca9
 
 
 
 
 
 
 
 
1ec5849
9b81ca9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ec5849
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b81ca9
 
 
 
 
 
 
 
 
1ec5849
 
 
 
 
 
e67b001
1ec5849
 
9b81ca9
 
 
 
e67b001
9b81ca9
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// Main thread: audio in, two inference workers, segmentation + endpointing, rendering.
const $ = s => document.querySelector(s);
const SR = 16000, ENC_SEC = 0.04;           // encoder frame = 40 ms
const ENDPOINT_SIL = 0.9, MAX_SEG = 22, INTERIM_EVERY = 1.1;
const state = { pieces: null, ready: { stream: false, correct: false }, backend: {}, mode: null,
  useLM: true, correct: true, audio: new Float32Array(SR * 120), n: 0, segs: [], seq: 0,
  corrBusy: false, accept: true, corrQueue: [], audioSec: 0, chunkMs: [], corrMs: [], t0: 0, lastInterim: 0, fileSec: 0 };
const stream = new Worker('./worker.js', { type: 'module' });
const corr = new Worker('./worker.js', { type: 'module' });
const progress = {};
const gpu = 'gpu' in navigator;

function setStatus(t, cls = '') { const s = $('#status'); s.textContent = t; s.className = 'pill ' + cls; }
function renderProgress() {
  let l = 0, t = 0; for (const p of Object.values(progress)) { l += p.loaded; t += p.total || p.loaded; }
  const f = t ? l / t : 0; $('#bar').style.width = (f * 100).toFixed(1) + '%';
  $('#loadtxt').textContent = t ? `${(l / 1e6).toFixed(0)} / ${(t / 1e6).toFixed(0)} MB` : '';
}
for (const [name, w] of [['stream', stream], ['correct', corr]]) {
  w.onmessage = ({ data: m }) => {
    if (m.type === 'progress') { progress[name + m.key] = m; renderProgress(); }
    else if (m.type === 'ready') {
      state.ready[name] = true; state.backend[name] = m.backend; state.pieces = state.pieces || m.pieces;
      if (state.ready.stream && state.ready.correct) onReady();
    } else if (m.type === 'reset-done') state.accept = true;
    else if (m.type === 'tokens') { if (state.accept) onTokens(m); }
    else if (m.type === 'flushed') { if (state.accept) onFlushed(m); }
    else if (m.type === 'corrected') onCorrected(m);
    else if (m.type === 'log') console.log(m.msg);
    else if (m.type === 'backend') { state.backend[name] = m.backend; $('#backend').textContent = beLabel(); setStatus('آماده · ' + beLabel(), 'ok'); }
    else if (m.type === 'error') { console.error(m.msg, m.stack || ''); setStatus('⚠ ' + m.msg, 'err'); }
  };
  w.postMessage({ type: 'init', role: name, gpu });
}
const beLabel = () => 'live: ' + (state.backend.stream === 'webgpu' ? 'WebGPU' : 'WASM') + ' · fix: ' + (state.backend.correct === 'webgpu' ? 'WebGPU ⚡' : 'WASM');
function onReady() {
  $('#loader').classList.add('done');
  setStatus('آماده · ' + beLabel(), 'ok'); $('#backend').textContent = beLabel();
  document.body.classList.add('ready');
}

// ---------- text helpers ----------
const words = toks => toks.map(k => state.pieces[k]).join('').replace(/▁/g, ' ').trim().split(/\s+/).filter(Boolean);
function cur() { let s = state.segs[state.segs.length - 1]; if (!s || s.final) { s = { id: state.seq++, start: s ? s.end : 0, end: null, toks: [], frames: [], corr: null, final: false, gen: 0, shown: [] }; state.segs.push(s); } return s; }

// ---------- streaming results ----------
function onTokens(m) {
  state.chunkMs.push(m.ms); if (state.chunkMs.length > 50) state.chunkMs.shift();
  state.audioSec = m.audioSec;
  let s = cur();
  for (let i = 0; i < m.toks.length; i++) {
    // punctuation that trails an endpoint belongs to the previous (already corrected) phrase
    if (!s.toks.length && state.segs.length > 1 && !/[\p{L}\p{N}]/u.test(state.pieces[m.toks[i]])) continue;
    s.toks.push(m.toks[i]); s.frames.push(m.frames[i]);
  }
  endpointCheck(false);
  render(); stats();
}
function lastTokSec(s) { return s.frames.length ? s.frames[s.frames.length - 1] * ENC_SEC : null; }
function endpointCheck(flush) {
  const s = cur(), now = state.audioSec, lt = lastTokSec(s);
  if (!s.toks.length) { if (now - s.start / SR > 3) s.start = Math.max(0, Math.round((now - 1) * SR)); return; }
  if (flush || now - lt > ENDPOINT_SIL || now - s.start / SR > MAX_SEG) {
    s.end = Math.min(state.n, Math.round((flush ? now : Math.min(now, lt + 0.45)) * SR));
    s.final = true; requestCorrection(s, true);
  } else if (state.mode === 'mic' && state.correct && !state.corrBusy && !state.corrQueue.length && performance.now() - state.lastInterim > INTERIM_EVERY * 1000 && s.toks.length > (s.corrToks || 0) + 1) {
    state.lastInterim = performance.now(); s.corrToks = s.toks.length;
    requestCorrection(s, false);
  }
}
function onFlushed(m) { state.audioSec = m.audioSec; endpointCheck(true); render(); stats(); if (state.mode === 'file') { state.mode = null; $('#rec').classList.remove('busy'); } }

// ---------- correction pass ----------
function requestCorrection(s, final) {
  if (!state.correct) { render(); return; }
  const a = Math.max(0, s.start - Math.round(0.25 * SR)), b = final ? Math.min(state.n, s.end + Math.round(0.25 * SR)) : state.n;
  const job = { type: 'correct', id: s.id, gen: ++s.gen, samples: state.audio.slice(a, b), upto: (b - a) / SR + a / SR, final, useLM: state.useLM, alpha: 0.15, beta: 1, beam: 4 };
  if (final) state.corrQueue.push(job); else if (!state.corrBusy) state.corrQueue.unshift(job);
  pumpCorr();
}
function pumpCorr() {
  if (state.corrBusy || !state.corrQueue.length) return;
  const job = state.corrQueue.shift(); state.corrBusy = true;
  corr.postMessage(job, [job.samples.buffer]);
}
function onCorrected(m) {
  state.corrBusy = false; state.corrMs.push(m.ms); if (state.corrMs.length > 20) state.corrMs.shift();
  const s = state.segs.find(x => x.id === m.id);
  if (s && m.gen >= (s.corrGen || 0)) { s.corrGen = m.gen; s.corr = { toks: m.toks, upto: m.upto, final: m.final }; }
  if (s && s.file) { state.audioSec = s.end / SR; if (--state.filePending <= 0) { state.mode = null; $('#rec').classList.remove('busy'); } }
  pumpCorr(); render(); stats();
}

// ---------- rendering ----------
function segWords(s) {
  if (s.corr && (s.corr.final || !state.correct)) return s.corr.toks ? words(s.corr.toks).map(w => [w, 'final']) : [];
  if (s.corr) {
    const tail = []; for (let i = 0; i < s.toks.length; i++) if (s.frames[i] * ENC_SEC > s.corr.upto) tail.push(s.toks[i]);
    return [...words(s.corr.toks).map(w => [w, 'fixed']), ...words(tail).map(w => [w, 'live'])];
  }
  return words(s.toks).map(w => [w, s.final ? (state.correct ? 'pending' : 'final') : 'live']);
}
function render() {
  const box = $('#transcript');
  for (const s of state.segs) {
    let el = document.getElementById('seg' + s.id);
    if (!el) { el = document.createElement('span'); el.id = 'seg' + s.id; el.className = 'seg'; box.appendChild(el); }
    const ws = segWords(s), prev = s.shown;
    if (ws.length === prev.length && ws.every((w, i) => w[0] === prev[i][0] && w[1] === prev[i][1])) continue;
    const frag = document.createDocumentFragment();
    ws.forEach(([w, cls], i) => {
      const sp = document.createElement('span'); sp.textContent = w + ' ';
      let c = 'w ' + cls;
      if (i >= prev.length) c += ' new';
      else if (prev[i][0] !== w && (cls === 'final' || cls === 'fixed')) c += ' changed';
      sp.className = c; frag.appendChild(sp);
    });
    el.replaceChildren(frag); s.shown = ws;
  }
  $('#placeholder').style.display = state.segs.some(s => s.toks.length) ? 'none' : '';
  const sc = $('#scroller'); sc.scrollTop = sc.scrollHeight;
}
function stats() {
  const avg = a => a.length ? a.reduce((x, y) => x + y, 0) / a.length : 0;
  const c = avg(state.chunkMs);
  $('#st-chunk').textContent = c ? c.toFixed(0) + ' ms' : '–';
  const wall = state.t0 ? (performance.now() - state.t0) / 1000 : 0;
  $('#st-rtf').textContent = state.segs.some(s => s.file) && wall ? (state.audioSec / wall).toFixed(0) + '×' : c ? (320 / c).toFixed(1) + '×' : '–';
  $('#st-corr').textContent = state.corrMs.length ? avg(state.corrMs).toFixed(0) + ' ms' : '–';
  $('#st-audio').textContent = state.audioSec.toFixed(1) + ' s';
  if (state.t0 && state.segs.some(s => s.file)) $('#st-wall').textContent = ((performance.now() - state.t0) / 1000).toFixed(1) + ' s';
}

// ---------- audio ----------
function pushAudio(x) {
  if (state.n + x.length > state.audio.length) { const a = new Float32Array(Math.max(state.audio.length * 2, state.n + x.length)); a.set(state.audio.subarray(0, state.n)); state.audio = a; }
  state.audio.set(x, state.n); state.n += x.length;
  stream.postMessage({ type: 'audio', samples: x });
}
function resetAll() {
  state.audio = new Float32Array(SR * 120); state.n = 0; state.segs = []; state.t0 = 0; state.audioSec = 0; state.corrQueue = []; state.chunkMs = []; state.corrMs = [];
  $('#transcript').replaceChildren(); state.accept = false; stream.postMessage({ type: 'reset' }); render(); stats();
}
let ac = null, mic = null, node = null;
const WORKLET = `class Cap extends AudioWorkletProcessor{constructor(o){super();this.r=o.processorOptions.ratio;this.b=new Float32Array(1600);this.n=0;this.p=0;this.e=0}
process(i){const c=i[0][0];if(!c)return true;const r=this.r;
if(r===1){for(let k=0;k<c.length;k++)this.put(c[k])}else{while(this.p<c.length){const j=Math.floor(this.p),f=this.p-j;const a=c[j],b=j+1<c.length?c[j+1]:a;this.put(a+(b-a)*f);this.p+=r}this.p-=c.length}return true}
put(v){this.b[this.n++]=v;this.e+=v*v;if(this.n===1600){this.port.postMessage({x:this.b.slice(),rms:Math.sqrt(this.e/1600)});this.n=0;this.e=0}}}
registerProcessor('cap',Cap);`;
async function startMic() {
  if (state.mode) return;
  resetAll(); state.mode = 'mic';
  mic = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
  try { ac = new AudioContext({ sampleRate: SR }); } catch (e) { ac = new AudioContext(); }
  let src;
  try { src = ac.createMediaStreamSource(mic); } catch (e) { await ac.close(); ac = new AudioContext(); src = ac.createMediaStreamSource(mic); }
  await ac.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET], { type: 'text/javascript' })));
  node = new AudioWorkletNode(ac, 'cap', { processorOptions: { ratio: ac.sampleRate / SR } });
  node.port.onmessage = ({ data }) => { pushAudio(data.x); level(data.rms); };
  src.connect(node);
  document.body.classList.add('recording'); $('#rec').setAttribute('aria-pressed', 'true');
}
async function stopMic() {
  if (state.mode !== 'mic') return;
  node && node.disconnect(); mic && mic.getTracks().forEach(t => t.stop()); ac && await ac.close();
  pushAudio(new Float32Array(Math.round(0.8 * SR))); stream.postMessage({ type: 'end' });
  state.mode = null; document.body.classList.remove('recording'); $('#rec').setAttribute('aria-pressed', 'false'); level(0);
}
function level(r) { const v = Math.min(1, r * 9); document.documentElement.style.setProperty('--lvl', v.toFixed(3)); }
// Files go "turbo": energy-VAD cut into phrases (<=20 s), each decoded straight away by the full-context
// encoder (WebGPU when available) + beam + LM. The live streaming pass is for the microphone.
function vadCuts(x) {
  const F = 320, n = Math.floor(x.length / F), e = new Float32Array(n);
  for (let i = 0; i < n; i++) { let s = 0; for (let j = i * F; j < (i + 1) * F; j++) s += x[j] * x[j]; e[i] = Math.sqrt(s / F); }
  const sorted = Float32Array.from(e).sort(), floor = sorted[Math.floor(n * 0.1)] || 0, thr = Math.max(floor * 3, 0.003);
  const cuts = [0]; let segStart = 0, sil = 0;
  for (let i = 0; i < n; i++) {
    sil = e[i] < thr ? sil + 1 : 0;
    const len = (i - segStart) * F / SR;
    if ((sil >= 15 && len > 4) || (sil >= 8 && len > 12)) { const c = i - Math.floor(sil / 2); cuts.push(c * F); segStart = c; sil = 0; }
    else if (len > 20) { let best = i, bv = Infinity; for (let k = i - 250; k < i; k++) if (e[k] < bv) { bv = e[k]; best = k; } cuts.push(best * F); segStart = best; }
  }
  cuts.push(x.length);
  return cuts;
}
async function runFile(file) {
  if (state.mode === 'mic') await stopMic();
  resetAll(); state.mode = 'file'; $('#rec').classList.add('busy');
  $('#filename').textContent = file.name;
  const raw = await file.arrayBuffer();
  const tmp = new AudioContext(); const buf = await tmp.decodeAudioData(raw); tmp.close();
  const off = new OfflineAudioContext(1, Math.ceil(buf.duration * SR), SR);
  const s = off.createBufferSource(); s.buffer = buf; s.connect(off.destination); s.start();
  const x = (await off.startRendering()).getChannelData(0);
  state.audio = x; state.n = x.length; state.fileSec = x.length / SR; state.t0 = performance.now();
  const cuts = vadCuts(x); state.filePending = cuts.length - 1;
  for (let k = 0; k + 1 < cuts.length; k++) {
    const seg = { id: state.seq++, start: cuts[k], end: cuts[k + 1], toks: [], frames: [], corr: null, final: true, gen: 1, shown: [], file: true };
    state.segs.push(seg);
    const lo = Math.max(0, cuts[k] - 1600), hi = Math.min(x.length, cuts[k + 1] + 1600);
    state.corrQueue.push({ type: 'correct', id: seg.id, gen: 1, samples: x.slice(lo, hi), upto: hi / SR, final: true, useLM: state.useLM, alpha: 0.15, beta: 1, beam: 4 });
  }
  pumpCorr();
}
// ---------- UI wiring ----------
$('#rec').onclick = () => { if (!document.body.classList.contains('ready')) return; state.mode === 'mic' ? stopMic() : startMic().catch(e => { state.mode = null; setStatus('⚠ ' + e.message, 'err'); }); };
$('#file').onchange = e => { const f = e.target.files[0]; if (f) runFile(f).catch(err => setStatus('⚠ ' + err.message, 'err')); e.target.value = ''; };
$('#sample').onclick = async () => { if (!document.body.classList.contains('ready') || state.mode) return; const b = await (await fetch('./samples/fleurs_fa_sample.wav')).blob(); runFile(new File([b], 'FLEURS fa · 6 sentences', { type: 'audio/wav' })).catch(err => setStatus('⚠ ' + err.message, 'err')); };
$('#clear').onclick = () => { if (state.mode !== 'mic') resetAll(); };
$('#lm').onchange = e => { state.useLM = e.target.checked; };
$('#fix').onchange = e => { state.correct = e.target.checked; render(); };
$('#copy').onclick = () => navigator.clipboard.writeText(state.segs.map(s => segWords(s).map(w => w[0]).join(' ')).join(' ').trim());
const drop = $('#scroller');
drop.ondragover = e => { e.preventDefault(); drop.classList.add('drag'); };
drop.ondragleave = () => drop.classList.remove('drag');
drop.ondrop = e => { e.preventDefault(); drop.classList.remove('drag'); const f = e.dataTransfer.files[0]; if (f && document.body.classList.contains('ready')) runFile(f); };
document.addEventListener('keydown', e => { if (e.code === 'Space' && e.target === document.body) { e.preventDefault(); $('#rec').click(); } });
setStatus(gpu ? 'در حال بارگذاری · WebGPU' : 'در حال بارگذاری · WASM');