Text-to-Speech
ONNX
Vietnamese
vietnamese
flow-matching
webgpu
on-device
File size: 15,026 Bytes
531d4d5
 
511b660
 
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511b660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531d4d5
f90fb26
 
531d4d5
f90fb26
531d4d5
f90fb26
 
 
 
 
 
511b660
 
 
531d4d5
f90fb26
511b660
 
 
 
 
 
 
531d4d5
 
511b660
531d4d5
 
f90fb26
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f90fb26
 
531d4d5
f90fb26
 
 
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Trà Đá TTS inference in JavaScript, backend-agnostic: pass an `ort` module (onnxruntime-web in the browser,
// onnxruntime-node in tests). Mirrors trada_tts/text.py + trada_tts/infer.py.
import { textNormalize } from './vi_normalize.js?v=11220400';
import { fixNumbers } from './vi_fix.js?v=11220400';

const TONE_MARK = { '̀': 2, '́': 3, '̉': 4, '̃': 5, '̣': 6 };
const WORD_RE = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]/gu;          // == Python re r"\w+|[^\w\s]" on NFC text
export const isAlnum = c => /[\p{L}\p{N}]/u.test(c);

// same pre/post fixes as trada_tts/text.py: °C, decimal comma glued to a unit, lone capital letter before sentence
// punctuation (misaki drops the "."), misaki's doubled "ngày ngày <number>"
const LETTER_NAMES = { A: 'ây', B: 'bê', C: 'xê', D: 'dê', Đ: 'đê', E: 'e', F: 'ép', G: 'gờ', H: 'hát', I: 'ai', J: 'chây', K: 'kây', L: 'lờ',
  M: 'em mờ', N: 'en nờ', O: 'ô', P: 'pê', Q: 'kiu', R: 'rờ', S: 'ét', T: 'ti', U: 'u', V: 'vi', W: 'vê kép', X: 'ít', Y: 'i', Z: 'dét' };
const fixLetters = t => t.replace(/(?<![\p{L}\p{N}_.])([A-ZĐ])\s*([.!?;…]+)(?=\s|$)/gu, (m, l, p) => LETTER_NAMES[l] + p);
export const normalizePart = text => textNormalize(fixLetters(fixNumbers(text.replace(/\s*°\s*([CF])(?![\p{L}\p{N}_])/gu, ' độ $1').replace(/°/g, ' độ')
    .replace(/(\d+,\d+)(?=[^\P{L}])/gu, '$1 '))))
  .replace(/(?<![\p{L}\p{N}_])(ngày|tháng) \1 (?=(?:mùng|mồng|một|hai|ba|bốn|năm|sáu|bảy|tám|chín|mười)(?![\p{L}\p{N}_]))/gu, '$1 ');
// "_" between two words = read them joined (no pause). Each "_"-separated part is normalised on its own and the parts are
// glued with JOIN ("‿"), which encodeText turns into a join on the next word.
export const JOIN = '\u203F';
export const normalize = text => text.split('_').map(normalizePart).filter(Boolean).join(JOIN);

export function encodeText(norm, symbols) {
  const SID = new Map(symbols.map((s, i) => [s, i]));
  const ids = [], tones = [], words = [], w2c = [], joins = {};
  let join = false;
  for (const w of norm.match(WORD_RE) || []) {
    if (w === JOIN) { join = true; continue; }
    if (join && isAlnum(w[0])) { if (words.length) joins[words.length] = 'join'; join = false; }
    words.push(w); const n0 = ids.length;
    if (isAlnum(w[0])) {
      let tone = 1, base = '';
      for (const ch of w.toLowerCase().normalize('NFD')) { if (TONE_MARK[ch]) tone = TONE_MARK[ch]; else base += ch; }
      [...base.normalize('NFC')].forEach((ch, k) => { ids.push(SID.get(ch) ?? 1); tones.push(tone + (k === 0 ? 7 : 0)); });
    } else { ids.push(SID.get(w) ?? 1); tones.push(0); }
    w2c.push(ids.length - n0);
  }
  return { ids, tones, words, w2c, joins };
}

// Manual phrasing, same as trada_tts/text.py apply_breaks + join_durations. breaks: { syllable index: 'join' | ',' | '.' }
// sets the boundary BEFORE that word: existing punctuation there is removed, then ',' / '.' inserted ('join' inserts none).
export function applyBreaks(enc, breaks, symbols) {
  const { ids, tones, words, w2c } = enc, alnum = words.map(w => isAlnum(w[0])), nxt = new Array(words.length).fill(-1);
  for (let i = words.length - 1, j = -1; i >= 0; i--) { if (alnum[i]) j = i; nxt[i] = j; }
  const o = { ids: [], tones: [], words: [], w2c: [], bound: [] }; let k = 0;
  words.forEach((w, i) => {
    const n = w2c[i], sid = ids.slice(k, k + n), st = tones.slice(k, k + n); k += n;
    const b = breaks ? breaks[nxt[i]] : undefined;
    if (!alnum[i] && b !== undefined) return;
    if (alnum[i] && breaks && (breaks[i] === ',' || breaks[i] === '.')) { o.ids.push(symbols.indexOf(breaks[i])); o.tones.push(0); o.words.push(breaks[i]); o.w2c.push(1); o.bound.push(i); }
    o.ids.push(...sid); o.tones.push(...st); o.words.push(w); o.w2c.push(n); o.bound.push(alnum[i] ? i : nxt[i]);
  });
  return o;
}
// Every syllable gets at least minFrames (40 ms each), added to its vowels: stops the model from swallowing rushed
// syllables in long numbers. Same as trada_tts/text.py floor_durations.
const VOWELS = new Set('aăâeêioôơuưy');
export function floorDurations(dur, { ids, words, w2c }, symbols, minFrames) {
  if (!minFrames) return dur;
  let k = 0;
  words.forEach((w, i) => {
    const n = w2c[i]; let D = 0; for (let j = 0; j < n; j++) D += dur[k + j];
    if (isAlnum(w[0]) && D < minFrames) {
      const vow = []; for (let j = 0; j < n; j++) if (VOWELS.has(symbols[ids[k + j]])) vow.push(k + j);
      if (!vow.length) vow.push(k + n - 1);
      for (let q = 0; q < minFrames - D; q++) dur[vow[q % vow.length]]++;
    }
    k += n;
  });
  return dur;
}
export function joinDurations(dur, { words, w2c, bound }, breaks) {
  let s = 0;
  words.forEach((w, t) => {
    if (isAlnum(w[0]) && breaks && breaks[bound[t]] === 'join') {
      dur[s] = Math.min(dur[s], 1); for (let q = s + 1; q < s + w2c[t]; q++) dur[q] = Math.min(dur[q], 2);
      if (t > 0 && isAlnum(words[t - 1][0])) dur[s - 1] = Math.min(dur[s - 1], 2);
    }
    s += w2c[t];
  });
  return dur;
}

// chunks the model handles well (trained on 1-15 s utterances)
export function splitSentences(norm, maxChars = 180) {
  const parts = norm.split(/(?<=[.!?;…])\s+/u).map(s => s.trim()).filter(Boolean), out = [];
  for (const p of parts) {
    if (p.length <= maxChars) { out.push(p); continue; }
    let cur = '';
    for (const piece of p.split(/(?<=,)\s+/u)) {
      if ((cur + ' ' + piece).trim().length > maxChars && cur) { out.push(cur.trim()); cur = piece; } else cur = (cur + ' ' + piece).trim();
    }
    if (cur) out.push(cur);
  }
  return out;
}

const pyRound = x => { const f = Math.floor(x), d = x - f; return d > 0.5 || (d === 0.5 && f % 2 === 1) ? f + 1 : f; };   // == Python round()
export function rng(seed) {             // mulberry32 + Box-Muller -> standard normal
  let a = seed >>> 0;
  const u = () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  return () => { const r = Math.sqrt(-2 * Math.log(u() + 1e-12)), th = 2 * Math.PI * u(); return r * Math.cos(th); };
}

// ---- iSTFT (n_fft 1920, hop 480, periodic hann, center=True), CPU reference ----
const NF = 1920, HOP = 480, FB = 961;
let TC = null, TS = null, WIN = null;
function tables() {
  TC = new Float32Array(FB * NF); TS = new Float32Array(FB * NF); WIN = new Float32Array(NF);
  for (let n = 0; n < NF; n++) WIN[n] = 0.5 - 0.5 * Math.cos(2 * Math.PI * n / NF);
  for (let k = 0; k < FB; k++) for (let n = 0; n < NF; n++) { const a = 2 * Math.PI * k * n / NF; TC[k * NF + n] = Math.cos(a); TS[k * NF + n] = Math.sin(a); }
}
export function istftCPU(mag, phase, T) {
  if (!TC) tables();
  const len = HOP * (T - 1) + NF, out = new Float32Array(len), ws = new Float32Array(len), re = new Float32Array(FB), im = new Float32Array(FB);
  for (let f = 0; f < T; f++) {
    for (let k = 0; k < FB; k++) { const m = mag[k * T + f], p = phase[k * T + f]; re[k] = m * Math.cos(p); im[k] = m * Math.sin(p); }
    const s = f * HOP;
    for (let n = 0; n < NF; n++) {
      let acc = re[0] + re[FB - 1] * ((n & 1) ? -1 : 1);
      for (let k = 1; k < FB - 1; k++) { const b = k * NF + n; acc += 2 * (re[k] * TC[b] - im[k] * TS[b]); }
      out[s + n] += (acc / NF) * WIN[n]; ws[s + n] += WIN[n] * WIN[n];
    }
  }
  for (let i = 0; i < len; i++) out[i] = ws[i] > 1e-8 ? out[i] / ws[i] : 0;
  return out.slice(NF >> 1, len - (NF >> 1));
}

// fetch several files in parallel, streamed, reporting (bytes so far, total, got{name}, size{name}) for a progress bar
async function fetchAll(urls, onProgress = null, estimate = 0) {
  const names = Object.keys(urls), bufs = {}, got = {}, size = {};
  const report = () => { if (!onProgress) return;              // total = real sizes once every file has answered
    const a = names.reduce((s, n) => s + (got[n] || 0), 0), known = names.every(n => size[n]);
    onProgress(a, known ? names.reduce((s, n) => s + size[n], 0) : Math.max(a + 1, estimate), { ...got }, { ...size }); };
  await Promise.all(names.map(async n => {
    const r = await fetch(urls[n]); if (!r.ok) throw new Error(`${urls[n]}: HTTP ${r.status}`);
    size[n] = +r.headers.get('content-length') || 0;
    if (!r.body || !size[n]) { bufs[n] = new Uint8Array(await r.arrayBuffer()); got[n] = size[n] = bufs[n].length; report(); return; }
    const buf = new Uint8Array(size[n]), rd = r.body.getReader(); let o = 0;
    for (;;) { const { done, value } = await rd.read(); if (done) break; buf.set(value, o); o += value.length; got[n] = o; report(); }
    bufs[n] = buf;
  }));
  return bufs;
}

export class TradaTTS {
  constructor(ort, sessions, config, istft = null, root = null, opts = {}) {
    this.ort = ort; this.s = sessions; this.cfg = config; this.sr = config.sample_rate; this.root = root; this.opts = opts;
    this.istft = istft || (async (m, p, T) => istftCPU(m, p, T));
    this.hasFast = !!config.fast;
  }
  // load one more ONNX graph on demand (e.g. the 16-step flow when the user leaves fast mode)
  async ensure(name) {
    if (!this.s[name]) this.s[name] = await this.ort.InferenceSession.create(new Uint8Array(await (await fetch(`${this.root}/onnx/${name}.onnx`)).arrayBuffer()), this.opts);
    return this.s[name];
  }
  // root = repo root URL (holds config.json and onnx/). flow: 'cfm2' (2-step, default when available) or 'cfm' (16-step)
  // engine 'wgpu': the hand-written WebGPU engine (wgpu_engine.js) on int8 weights, fast model only.
  // engine 'ort' : onnxruntime-web sessions; int8 = true loads the dynamically quantized ONNX graphs (config.int8.onnx).
  static async load(ort, root, opts = {}, istft = null, onProgress = null, flow = 'auto', { engine = 'ort', int8 = false } = {}) {
    const cfg = await (await fetch(`${root}/config.json`)).json();
    if (flow === 'auto') flow = cfg.fast ? 'cfm2' : 'cfm';
    if (engine === 'wgpu') {
      const [{ GpuEngine }, bufs] = await Promise.all([import('./wgpu_engine.js?v=11220400'), fetchAll({ all: `${root}/${cfg.int8.webgpu}` }, onProgress, 10.7e6)]);
      const eng = await GpuEngine.create(bufs.all.buffer);
      const t = new TradaTTS(ort, { enc: eng.enc, cfm2: eng.cfm2, dec: eng.dec }, cfg, istft, root, opts); t.engine = 'wgpu'; return t;
    }
    const names = ['enc', flow, 'dec'], q = int8 && cfg.int8 && cfg.int8.onnx;
    const bufs = await fetchAll(Object.fromEntries(names.map(n => [n, `${root}/${q && q[n] ? q[n] : `onnx/${n}.onnx`}`])), onProgress, q ? 12.9e6 : 39.3e6);
    const s = {};
    for (const n of names) s[n] = await ort.InferenceSession.create(bufs[n], opts);
    const t = new TradaTTS(ort, s, cfg, istft, root, opts); t.engine = q ? 'ort-int8' : 'ort'; return t;
  }
  // one chunk of NORMALISED text -> Float32Array @24 kHz
  async synthChunk(norm, spk, { w = 3.0, steps = 16, speed = 1.0, seed = 0, noise = null, breaks = null, minSyllableMs = 160, fast = false, onStep = null, onTiming = null } = {}) {
    const { ort, s, cfg } = this, C = cfg.enc_dim, L = cfg.latent_dim;
    const enc0 = encodeText(norm, cfg.symbols); breaks = { ...enc0.joins, ...(breaks || {}) };     // "_" joins from the text
    const E = applyBreaks(enc0, breaks, cfg.symbols), { ids, tones, words, w2c, bound } = E; const N = ids.length;
    if (!N) return new Float32Array(0);
    const spkT = new ort.Tensor('float32', Float32Array.from(spk), [1, 192]);
    const eo = await s.enc.run({ ids: new ort.Tensor('int64', BigInt64Array.from(ids.map(BigInt)), [1, N]),
      tones: new ort.Tensor('int64', BigInt64Array.from(tones.map(BigInt)), [1, N]), spk: spkT });
    const h = eo.h.data, ld = eo.logdur.data;
    const dur0 = Array.from(ld, v => Math.max(1, Math.round((Math.exp(v) - 1) / speed)));
    const dur = joinDurations(floorDurations(dur0, E, cfg.symbols, pyRound(minSyllableMs / 40 / speed)), E, breaks);
    const T = dur.reduce((a, b) => a + b, 0);
    if (onTiming) {                      // word timeline (1 latent frame = 40 ms)
      const fr = 960 / this.sr, tl = []; let k = 0, f = 0;
      words.forEach((wd, i) => { let d = 0; for (let j = 0; j < w2c[i]; j++) d += dur[k++]; tl.push({ text: wd, start: f * fr, end: (f + d) * fr, syllable: isAlnum(wd[0]), bound: bound[i], joined: isAlnum(wd[0]) && breaks[bound[i]] === 'join' }); f += d; });
      onTiming(tl);
    }
    const cond = new Float32Array(C * T);
    for (let c = 0; c < C; c++) { let o = 0; for (let i = 0; i < N; i++) { const v = h[c * N + i]; for (let d = 0; d < dur[i]; d++) cond[c * T + o++] = v; } }
    let x;                                                         // `noise`: tests only. Noise is drawn frame by frame, so
    if (noise) x = Float32Array.from(noise.subarray(0, L * T));    // editing one word leaves the noise of earlier frames unchanged
    else { const g = rng(seed); x = new Float32Array(L * T); for (let t = 0; t < T; t++) for (let l = 0; l < L; l++) x[l * T + t] = g(); }
    const condT = new ort.Tensor('float32', cond, [1, C, T]), wT = new ort.Tensor('float32', new Float32Array([w]), [1]);
    if (fast) steps = cfg.fast.steps;                                // 2-step IntMeanFlow flow: average velocity over [t, r], CFG baked in
    const flow = await this.ensure(fast ? 'cfm2' : 'cfm');
    for (let k = 0; k < steps; k++) {
      const t = new ort.Tensor('float32', new Float32Array([k / steps]), [1]), xT = new ort.Tensor('float32', x, [1, L, T]);
      const v = (await flow.run(fast ? { x: xT, cond: condT, t, r: new ort.Tensor('float32', new Float32Array([(k + 1) / steps]), [1]), spk: spkT }
                                      : { x: xT, cond: condT, t, spk: spkT, w: wT })).v.data;
      for (let i = 0; i < x.length; i++) x[i] += v[i] / steps;
      if (onStep) onStep(k + 1, steps);
    }
    const dO = await s.dec.run({ z: new ort.Tensor('float32', x, [1, L, T]) });
    return await this.istft(dO.mag.data, dO.phase.data, dO.mag.dims[2]);
  }
  // raw text -> { audio, sr, chunks, norm, timeline }
  async synth(text, spk, opts = {}) {
    const norm = normalize(text), chunks = splitSentences(norm), parts = [], gap = new Float32Array(Math.round(0.25 * this.sr));
    const timeline = []; let offset = 0;
    for (let i = 0; i < chunks.length; i++) {
      if (opts.onChunk) opts.onChunk(i, chunks.length, chunks[i]);
      let tl = [];
      const y = await this.synthChunk(chunks[i], spk, { ...opts, seed: (opts.seed ?? 0) + i, breaks: opts.breaks ? opts.breaks[i] : null, onStep: opts.onStep ? (k, K) => opts.onStep(i, chunks.length, k, K) : null, onTiming: t => { tl = t; } });
      for (const e of tl) timeline.push({ ...e, start: e.start + offset, end: e.end + offset, chunk: i });
      parts.push(y); offset += y.length / this.sr;
      if (i < chunks.length - 1) { parts.push(gap); offset += gap.length / this.sr; }
    }
    const n = parts.reduce((a, p) => a + p.length, 0), audio = new Float32Array(n); let o = 0; for (const p of parts) { audio.set(p, o); o += p.length; }
    return { audio, sr: this.sr, chunks, norm, timeline };
  }
}