Spaces:
Running

File size: 7,764 Bytes
5ad985a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Phonon-2 in the browser: onnxruntime-web, encoder on WebGPU, greedy TDT decode in JS.
// Weights: https://huggingface.co/tiyuvta/Phonon-2-ONNX (onnx-asr nemo-conformer-tdt layout).
const ORT_VERSION = "1.30.0";
const ORT_BASE = `https://cdn.jsdelivr.net/npm/onnxruntime-web@${ORT_VERSION}/dist/`;
const REPO = "https://huggingface.co/tiyuvta/Phonon-2-ONNX/resolve/main/";
const FILES = {
  pre: "preprocessor-model.onnx",
  enc: "encoder-model.exact4x2.onnx",
  dec: "decoder_joint-model.onnx",
  vocab: "vocab.txt",
};
const CACHE_NAME = "phonon2-onnx-v1";

const SR = 16000;
const BLANK = 8192;
const N_DUR = 5; // durations 0..4
const MAX_SYMBOLS = 10;
const FRAME_SEC = 0.08; // 10 ms hop x 8 subsampling
const CHUNK_SEC = 30; // cut long audio at pauses, <= 30 s per chunk

let ort = null;
let sessions = null;
let vocab = null;
let backend = "wasm";

const post = (type, data = {}) => self.postMessage({ type, ...data });

async function fetchWithProgress(name, onBytes) {
  const url = REPO + name;
  let cache = null;
  try {
    cache = await caches.open(CACHE_NAME);
    const hit = await cache.match(url);
    if (hit) {
      const buf = new Uint8Array(await hit.arrayBuffer());
      onBytes(buf.byteLength, buf.byteLength, true);
      return buf;
    }
  } catch (_) {
    cache = null;
  }
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status} for ${name}`);
  const total = Number(res.headers.get("content-length")) || 0;
  const reader = res.body.getReader();
  const parts = [];
  let got = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    parts.push(value);
    got += value.byteLength;
    onBytes(got, total || got, false);
  }
  const buf = new Uint8Array(got);
  let off = 0;
  for (const p of parts) {
    buf.set(p, off);
    off += p.byteLength;
  }
  if (cache) {
    try {
      await cache.put(url, new Response(buf, { headers: { "content-type": "application/octet-stream" } }));
    } catch (_) {
      /* quota or private mode: ignore */
    }
  }
  return buf;
}

async function load(useWebGPU) {
  post("status", { text: "Loading runtime" });
  ort = await import(ORT_BASE + "ort.webgpu.min.mjs");
  ort.env.wasm.wasmPaths = ORT_BASE;
  ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1;

  const names = Object.keys(FILES);
  const progress = Object.fromEntries(names.map((k) => [k, { got: 0, total: 0 }]));
  const report = () => {
    let got = 0, total = 0;
    for (const k of names) {
      got += progress[k].got;
      total += progress[k].total;
    }
    post("progress", { got, total, files: progress });
  };
  const bufs = await Promise.all(
    names.map((k) =>
      fetchWithProgress(FILES[k], (got, total) => {
        progress[k] = { got, total };
        report();
      }).then((b) => [k, b])
    )
  );
  const b = Object.fromEntries(bufs);

  vocab = new TextDecoder().decode(b.vocab).split("\n").reduce((acc, line) => {
    const i = line.lastIndexOf(" ");
    if (i > 0) acc[Number(line.slice(i + 1))] = line.slice(0, i);
    return acc;
  }, []);

  post("status", { text: "Creating sessions" });
  const wasmOpts = { executionProviders: ["wasm"], graphOptimizationLevel: "all" };
  let enc = null;
  if (useWebGPU) {
    try {
      enc = await ort.InferenceSession.create(b.enc, { executionProviders: ["webgpu"], graphOptimizationLevel: "all" });
      backend = "webgpu";
    } catch (e) {
      post("warn", { text: `WebGPU session failed (${e.message || e}); falling back to WASM.` });
    }
  }
  if (!enc) {
    enc = await ort.InferenceSession.create(b.enc, wasmOpts);
    backend = "wasm";
  }
  const pre = await ort.InferenceSession.create(b.pre, wasmOpts);
  const dec = await ort.InferenceSession.create(b.dec, wasmOpts);
  sessions = { pre, enc, dec };
  post("ready", { backend, threads: ort.env.wasm.numThreads });
}

function splitChunks(wav) {
  const max = CHUNK_SEC * SR;
  const out = [];
  let start = 0;
  const win = SR / 10;
  while (wav.length - start > max) {
    const lo = start + max - 5 * SR;
    let best = lo, bestE = Infinity;
    for (let s = lo; s + win <= start + max; s += win / 2) {
      let e = 0;
      for (let i = s; i < s + win; i++) e += wav[i] * wav[i];
      if (e < bestE) {
        bestE = e;
        best = s + win / 2;
      }
    }
    out.push([start, best]);
    start = best;
  }
  out.push([start, wav.length]);
  return out;
}

function argmax(arr, from, to) {
  let bi = from, bv = arr[from];
  for (let i = from + 1; i < to; i++) if (arr[i] > bv) { bv = arr[i]; bi = i; }
  return bi - from;
}

async function transcribeChunk(wav, offsetSec) {
  const { pre, enc, dec } = sessions;
  const T = ort.Tensor;
  const p = await pre.run({
    waveforms: new T("float32", wav, [1, wav.length]),
    waveforms_lens: new T("int64", BigInt64Array.from([BigInt(wav.length)]), [1]),
  });
  const e = await enc.run({ audio_signal: p.features, length: p.features_lens });
  const encOut = e.outputs; // [1, 1024, T']
  const D = encOut.dims[1];
  const Tp = Number(e.encoded_lengths.data[0]);
  const stride = encOut.dims[2];
  const encData = encOut.data instanceof Float32Array ? encOut.data : await encOut.getData();

  const frame = new Float32Array(D);
  let s1 = new T("float32", new Float32Array(2 * 640), [2, 1, 640]);
  let s2 = new T("float32", new Float32Array(2 * 640), [2, 1, 640]);
  let prev = BLANK;
  const tokens = [];
  let t = 0, onFrame = 0;
  const tl = new T("int32", Int32Array.from([1]), [1]);
  while (t < Tp) {
    for (let d = 0; d < D; d++) frame[d] = encData[d * stride + t];
    const out = await dec.run({
      encoder_outputs: new T("float32", frame, [1, D, 1]),
      targets: new T("int32", Int32Array.from([prev]), [1, 1]),
      target_length: tl,
      input_states_1: s1,
      input_states_2: s2,
    });
    const logits = out.outputs.data;
    const tok = argmax(logits, 0, BLANK + 1);
    let dur = argmax(logits, BLANK + 1, BLANK + 1 + N_DUR);
    if (tok !== BLANK) {
      tokens.push({ id: tok, t });
      prev = tok;
      s1 = out.output_states_1;
      s2 = out.output_states_2;
      onFrame++;
    }
    if (tok === BLANK && dur === 0) dur = 1;
    if (dur === 0 && onFrame >= MAX_SYMBOLS) dur = 1;
    if (dur > 0) onFrame = 0;
    t += dur;
  }

  const words = [];
  let text = "";
  for (const { id, t: ft } of tokens) {
    const piece = vocab[id] || "";
    if (piece === "<unk>" || piece === "<pad>" || /^<\|.*\|>$/.test(piece)) continue;
    const s = piece.replace(/▁/g, " ");
    text += s;
    const time = offsetSec + ft * FRAME_SEC;
    if (s.startsWith(" ") || !words.length) words.push({ w: s.trim(), t: time });
    else words[words.length - 1].w += s;
  }
  return { text: text.trim(), words: words.filter((w) => w.w) };
}

async function transcribe(wav) {
  const t0 = performance.now();
  const chunks = splitChunks(wav);
  const texts = [];
  const words = [];
  for (let i = 0; i < chunks.length; i++) {
    const [a, b] = chunks[i];
    post("status", { text: chunks.length > 1 ? `Transcribing chunk ${i + 1}/${chunks.length}` : "Transcribing" });
    const r = await transcribeChunk(wav.subarray(a, b), a / SR);
    texts.push(r.text);
    words.push(...r.words);
    post("partial", { text: texts.filter(Boolean).join(" ") });
  }
  const secs = (performance.now() - t0) / 1000;
  post("result", { text: texts.filter(Boolean).join(" "), words, secs, audioSecs: wav.length / SR, backend });
}

self.onmessage = async ({ data }) => {
  try {
    if (data.type === "load") await load(data.webgpu);
    else if (data.type === "transcribe") await transcribe(data.audio);
  } catch (e) {
    post("error", { text: String((e && e.message) || e) });
  }
};