File size: 12,176 Bytes
00b6424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/* tiny-voca in-browser engine — Web Worker.
 *
 * Phonemizer: the original Python dizione package running under Pyodide
 * (there is no JS port). Source files are fetched from the pinned dizione
 * commit on jsDelivr (raw.githubusercontent fallback); its data files come
 * from the model repo's phonemizer/ directory, exactly like the server path.
 *
 * Synthesizer: onnx/model.onnx via onnxruntime-web, WebGPU execution provider
 * with a WASM fallback (and unsupported ops partitioned to CPU by ORT).
 * Sentence splitting mirrors tiny_voca/infer.py and the authors' own
 * web/public/worker.js.
 *
 * Messages in:  {type:"load"}
 *               {type:"speak", id, text, voice, speed, pitchShift, pitchRange}
 * Messages out: {type:"status", message, progress}
 *               {type:"ready", ep, voices, sampleRate}
 *               {type:"sentence", id, index, total, phonemes, audio}
 *               {type:"done", id, audio, utterances, seconds}
 *               {type:"error", id?, where, message}
 */
"use strict";

const CACHE_VERSION = "tiny-voca-web-v1";
const HF_REPO = "https://huggingface.co/n4ze3m/tiny-voca/resolve/main";
const DIZIONE_COMMIT = "8cd889e4de7be6bd1dd2e6891344a0729fa14dd4";
const DIZIONE_CDN = `https://cdn.jsdelivr.net/gh/n4ze3m/dizione@${DIZIONE_COMMIT}/src/dizione`;
const DIZIONE_RAW = `https://raw.githubusercontent.com/n4ze3m/dizione/${DIZIONE_COMMIT}/src/dizione`;
const PYODIDE_BASE = "https://cdn.jsdelivr.net/pyodide/v0.26.4/full/";
const ORT_BASE = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/";

const SAMPLE_RATE = 24000;
const PEAK = 0.99;              // the model can peak a little above 1.0 (model card)
const MAX_TOKENS = 512;         // config.json: model.max_tokens — one call reads one utterance
const TOKEN_LIMIT = MAX_TOKENS - 12;
const ENGLISH_ONLY = "tiny-voca only reads English for now";

// The dizione package at DIZIONE_COMMIT (src/dizione/**), written into Pyodide's FS.
const DIZIONE_FILES = [
  "__init__.py", "__main__.py", "align.py", "convert.py", "engine.py", "g2p.py",
  "homographs.py", "morphology.py", "normalize.py", "sentence.py", "symbols.py", "tables.py",
  "data/abbreviations.txt", "data/chat.txt", "data/endings.txt", "data/exceptions.txt",
  "data/function_words.txt", "data/homograph_fixes.txt", "data/homograph_rules.txt",
  "data/letters.txt", "data/phrases.txt", "data/units.txt",
];

// The model repo's phonemizer/ directory (DIZIONE_DATA).
const DATA_FILES = [
  "lexicon.tsv", "lexicon.json", "align.json", "g2p.json", "g2p.npz",
  "homographs.json", "sources.json",
];

importScripts(PYODIDE_BASE + "pyodide.js", ORT_BASE + "ort.webgpu.min.js");
ort.env.wasm.wasmPaths = ORT_BASE;
ort.env.wasm.numThreads = 1;  // single-threaded WASM: no COOP/COEP needed

let pyodide = null;
let phonemize = null;
let session = null;
let ep = "wasm";
let config = null;

function status(message, progress) {
  self.postMessage({ type: "status", message, progress });
}

/* Fetch with Cache Storage (repeat visits skip the network) + streamed progress. */
async function cached(url, onProgress) {
  const store = await caches.open(CACHE_VERSION);
  const hit = await store.match(url);
  if (hit) return new Uint8Array(await hit.arrayBuffer());
  const resp = await fetch(url);
  if (!resp.ok) throw new Error(`download failed (${resp.status}): ${url}`);
  const total = +resp.headers.get("content-length") || 0;
  const reader = resp.body.getReader();
  const chunks = [];
  let received = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    chunks.push(value);
    received += value.length;
    if (onProgress) onProgress(received, total);
  }
  const bytes = new Uint8Array(received);
  let offset = 0;
  for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; }
  store.put(url, new Response(bytes.slice(0))).catch(() => {});
  return bytes;
}

async function fetchText(urls) {
  let lastError = null;
  for (const url of urls) {
    try {
      const resp = await fetch(url);
      if (resp.ok) return await resp.text();
      lastError = new Error(`download failed (${resp.status}): ${url}`);
    } catch (err) { lastError = err; }
  }
  throw lastError;
}

/* --- sentence splitting, mirrored from tiny_voca/infer.py and web/public/worker.js --- */

const ABBREVIATIONS = /(?:\b(?:mr|mrs|ms|dr|prof|sr|jr|st|vs|etc|no|inc|ltd|co|e\.g|i\.e|a\.m|p\.m)|\b[A-Z])\.$/i;
const SENTENCE_END = /(?<=[.!?…]["')\]]?)\s+(?=["'(\[]?[A-Z0-9])/;
const CLAUSE_END = /(?<=[,;:—])\s+/;
const CLOSING = /["'”’)\]»]+$/;

function sentences(text) {
  const parts = [];
  let current = "";
  for (const piece of text.replace(/[\s\uFEFF]+/g, " ").trim().split(SENTENCE_END)) {
    current = current ? current + " " + piece : piece;
    if (!ABBREVIATIONS.test(current)) { parts.push(current); current = ""; }
  }
  if (current) parts.push(current);
  return parts.filter((part) => /[\p{L}\p{N}]/u.test(part));
}

function finished(text) {
  const body = text.replace(/[\s\uFEFF]+$/, "");
  if (!body) return text;
  const last = body.split(/[\s\uFEFF]+/).pop();
  let marked;
  if (/[\p{L}\p{N}]/u.test(last)) {
    marked = /[.!?…,;:]/.test(last.replace(CLOSING, "").slice(-1));
  } else {
    marked = /[.!?…]/.test(last) || last === "," || last === ";" || last === ":";
  }
  return marked ? text : body + ".";
}

function shorter(piece) {
  const clauses = piece.split(CLAUSE_END);
  if (clauses.length > 1) return clauses;
  const words = piece.split(" ");
  if (words.length < 2) return [];
  const half = Math.ceil(words.length / 2);
  return [words.slice(0, half).join(" "), words.slice(half).join(" ")];
}

function limitPeak(samples) {
  let loudest = 0;
  for (let i = 0; i < samples.length; i++) loudest = Math.max(loudest, Math.abs(samples[i]));
  if (loudest > PEAK) for (let i = 0; i < samples.length; i++) samples[i] *= PEAK / loudest;
  return samples;
}

/* --- engine --- */

function phonemizePiece(piece) {
  // The Python bridge returns a JSON string, or "null" for a piece with
  // nothing pronounceable (another script, signs only); those are skipped.
  try {
    return JSON.parse(phonemize(piece));
  } catch (err) {
    return null;
  }
}

async function synthesize(phones, voiceId, speed, pitchShift, pitchRange) {
  const count = phones.ids.length;
  const integers = (values) => new ort.Tensor("int64", BigInt64Array.from(values, BigInt), [1, count]);
  const scalar = (value) => new ort.Tensor("float32", Float32Array.from([value]), [1]);
  const output = await session.run({
    tokens: integers(phones.ids),
    stress: integers(phones.stress),
    voice: new ort.Tensor("int64", BigInt64Array.from([BigInt(voiceId)]), [1]),
    speed: scalar(speed),
    pitch_shift: scalar(pitchShift),
    pitch_range: scalar(pitchRange),
  });
  const audio = output.audio.data;  // Float32Array [1, samples]
  for (let i = 0; i < audio.length; i++) {
    if (!Number.isFinite(audio[i])) throw new Error("model produced non-finite audio");
  }
  return audio;
}

async function makeSession(modelBytes) {
  const warmup = async () => {
    const phones = phonemizePiece("Hello!");
    if (phones) await synthesize(phones, 0, 1.0, 0.0, 1.0);
  };
  if (typeof navigator !== "undefined" && navigator.gpu) {
    try {
      status("Starting the model on WebGPU…", 0.92);
      session = await ort.InferenceSession.create(modelBytes, { executionProviders: ["webgpu", "wasm"] });
      ep = "webgpu";
      await warmup();  // proves the graph actually runs on this backend
      return;
    } catch (err) {
      console.warn("WebGPU session failed, falling back to WASM:", err);
      session = null;
    }
  }
  status("Starting the model (WASM)…", 0.92);
  session = await ort.InferenceSession.create(modelBytes, { executionProviders: ["wasm"] });
  ep = "wasm";
  await warmup();
}

async function load() {
  status("Downloading the model (21 MB)…", 0.02);
  const [, modelBytes] = await Promise.all([
    (async () => { config = JSON.parse(new TextDecoder().decode(await cached(`${HF_REPO}/config.json`))); })(),
    cached(`${HF_REPO}/onnx/model.onnx`, (received, total) => {
      const frac = total ? received / total : 0;
      status(`Downloading the model… ${(received / 1e6).toFixed(0)} MB`, 0.02 + 0.5 * frac);
    }),
  ]);

  status("Downloading the phonemizer data…", 0.55);
  const dataBytes = [];
  for (let i = 0; i < DATA_FILES.length; i++) {
    dataBytes.push(await cached(`${HF_REPO}/phonemizer/${DATA_FILES[i]}`));
    status("Downloading the phonemizer data…", 0.55 + 0.12 * ((i + 1) / DATA_FILES.length));
  }

  status("Fetching the phonemizer source…", 0.68);
  const sourceTexts = [];
  for (let i = 0; i < DIZIONE_FILES.length; i++) {
    const name = DIZIONE_FILES[i];
    sourceTexts.push(await fetchText([`${DIZIONE_CDN}/${name}`, `${DIZIONE_RAW}/${name}`]));
  }

  status("Starting Python in your browser…", 0.72);
  pyodide = await loadPyodide({ indexURL: PYODIDE_BASE });
  status("Loading NumPy…", 0.80);
  await pyodide.loadPackage("numpy");

  pyodide.FS.mkdirTree("/dizione-data");
  DATA_FILES.forEach((name, i) => pyodide.FS.writeFile("/dizione-data/" + name, dataBytes[i]));
  pyodide.FS.mkdirTree("/dizione-src/dizione/data");
  DIZIONE_FILES.forEach((name, i) =>
    pyodide.FS.writeFile("/dizione-src/dizione/" + name, sourceTexts[i]));

  status("Warming up the phonemizer…", 0.86);
  pyodide.runPython(`
import json, os, sys
os.environ["DIZIONE_DATA"] = "/dizione-data"
sys.path.insert(0, "/dizione-src")
import dizione

def phonemize_json(text):
    try:
        result = dizione.phonemize(text)
    except ValueError:
        if any(word for mark, words in dizione.pieces(text) if not mark for word in words):
            raise
        return "null"
    return json.dumps({"ids": list(result.ids), "stress": list(result.stress), "text": str(result)})

phonemize_json("Warm up.")
`);
  phonemize = pyodide.globals.get("phonemize_json");

  await makeSession(modelBytes);
}

/* Split a sentence into utterances that fit one model call (as speak_text does). */
function collectPieces(piece, out) {
  const phones = phonemizePiece(piece);
  if (!phones) return;  // nothing pronounceable in this piece
  if (phones.ids.length <= TOKEN_LIMIT) {
    out.push(phones);
    return;
  }
  const pieces = shorter(piece);
  if (!pieces.length) throw new Error(`one word is too long to speak: ${piece.slice(0, 40)}`);
  for (const part of pieces) collectPieces(part, out);
}

async function speak(msg) {
  const t0 = performance.now();
  const pieces = [];
  for (const sentence of sentences(finished(msg.text))) collectPieces(sentence, pieces);
  if (!pieces.length) throw new Error(`Nothing in the text could be read — ${ENGLISH_ONLY}.`);

  const voiceId = Math.max(0, config.voices.indexOf(msg.voice));
  const all = [];
  for (let i = 0; i < pieces.length; i++) {
    if (msg.id !== latestSpeakId) return;  // a newer take superseded this one
    const audio = limitPeak(await synthesize(pieces[i], voiceId, msg.speed, msg.pitchShift, msg.pitchRange));
    all.push(audio.slice(0));
    self.postMessage(
      { type: "sentence", id: msg.id, index: i, total: pieces.length, phonemes: pieces[i].text, audio },
      [audio.buffer],
    );
  }
  const totalSamples = all.reduce((n, a) => n + a.length, 0);
  const full = new Float32Array(totalSamples);
  let offset = 0;
  for (const audio of all) { full.set(audio, offset); offset += audio.length; }
  limitPeak(full);
  self.postMessage(
    { type: "done", id: msg.id, audio: full, utterances: pieces.length,
      seconds: (performance.now() - t0) / 1000 },
    [full.buffer],
  );
}

let latestSpeakId = 0;

self.onmessage = async (event) => {
  const msg = event.data;
  try {
    if (msg.type === "load") {
      await load();
      self.postMessage({ type: "ready", ep, voices: config.voices, sampleRate: SAMPLE_RATE });
    } else if (msg.type === "speak") {
      latestSpeakId = msg.id;
      await speak(msg);
    }
  } catch (err) {
    self.postMessage({ type: "error", id: msg.id, where: msg.type,
                       message: String((err && err.message) || err) });
  }
};