Text-to-Speech
ONNX
Vietnamese
vietnamese
flow-matching
webgpu
on-device
File size: 34,452 Bytes
531d4d5
511b660
 
 
531d4d5
deddc7b
 
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
1245e4f
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deddc7b
 
 
531d4d5
 
 
 
deddc7b
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1245e4f
 
531d4d5
 
 
 
 
 
 
 
 
 
 
 
f90fb26
531d4d5
 
 
 
 
 
511b660
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
1245e4f
531d4d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511b660
 
531d4d5
 
 
 
511b660
531d4d5
 
 
 
511b660
531d4d5
511b660
 
531d4d5
 
 
 
 
 
 
 
 
2bcfd04
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import * as ort from './ort/ort.webgpu.min.mjs';
import { TradaTTS, normalize, normalizePart, JOIN, isAlnum } from './tts.js?v=11220400';
import { resample, kaldiFbank } from './audio.js?v=11220400';
const VER = '11220400';

// model repo root (config.json, onnx/, voices/): the page's parent folder, or window.TRADA_ROOT (e.g. a Hugging Face resolve URL)
const ROOT = (window.TRADA_ROOT || new URL('..', import.meta.url).href).replace(/\/$/, '');
const $ = id => document.getElementById(id);
const css = n => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
ort.env.wasm.wasmPaths = new URL('./ort/', import.meta.url).href;
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(8, navigator.hardwareConcurrency || 4) : 1;

const EXAMPLES = [
  ['Chào hỏi', 'Xin chào, mình là Trà Đá, một mô hình đọc tiếng Việt nhỏ gọn. Mình chạy ngay trên máy của bạn, không cần máy chủ.'],
  ['Tổng đài', 'Dạ, em chào anh. Em gọi từ bộ phận chăm sóc khách hàng. Anh cho em xin ít phút để xác nhận lại đơn hàng số 4 7 2 1 được không ạ?'],
  ['Bản tin', 'Sáng nay, ngày 20-11, nhiệt độ ở Hà Nội xuống còn 18 độ C. Giá vàng trong nước tăng 1,5% so với tuần trước.'],
  ['Con số', 'Tổng giá trị đơn hàng là 2.350.000 đồng, đã bao gồm thuế. Anh vui lòng thanh toán trước 17 giờ 30 ngày mai.'],
  ['Kể chuyện', 'Chiều hôm ấy, mưa rơi lất phất trên con phố nhỏ. Bà cụ bán trà đá vẫn ngồi đó, rót cho khách quen một cốc, rồi kể chuyện ngày xưa.'],
];
const STORE = 'trada-tts.voices.v1', THEME = 'trada-tts.theme';
const S = { tts: null, camp: null, presets: [], saved: [], sel: null, backend: 'wasm', take: null, takes: [], pending: null, selG: -1, stopAt: null };

// ---------------- iSTFT on WebGPU (WGSL; validated against torch.istft) ----------------
const N = 1920, H = 480, FB = 961, MT = 2048;
const WGSL = `
struct P { T2:u32, N:u32, FB:u32, H:u32, outlen:u32 };
@group(0) @binding(0) var<storage,read> mag:array<f32>;
@group(0) @binding(1) var<storage,read> phase:array<f32>;
@group(0) @binding(2) var<storage,read_write> reim:array<f32>;
@group(0) @binding(3) var<storage,read> tcos:array<f32>;
@group(0) @binding(4) var<storage,read> tsin:array<f32>;
@group(0) @binding(5) var<storage,read> win:array<f32>;
@group(0) @binding(6) var<storage,read_write> frame:array<f32>;
@group(0) @binding(7) var<storage,read_write> outp:array<f32>;
@group(0) @binding(8) var<uniform> p:P;
@compute @workgroup_size(64) fn reim_k(@builtin(global_invocation_id) g:vec3<u32>){
  let i=g.x; if(i>=p.T2*p.FB){return;} let f=i/p.FB; let k=i%p.FB;
  let m=mag[k*p.T2+f]; let ph=phase[k*p.T2+f];
  reim[(f*p.FB+k)*2u]=m*cos(ph); reim[(f*p.FB+k)*2u+1u]=m*sin(ph);
}
@compute @workgroup_size(64) fn idft(@builtin(global_invocation_id) g:vec3<u32>){
  let idx=g.x; if(idx>=p.T2*p.N){return;} let f=idx/p.N; let n=idx%p.N;
  var acc=reim[(f*p.FB)*2u];
  let sgn=select(1.0,-1.0,(n&1u)==1u);
  acc=acc+reim[(f*p.FB+(p.FB-1u))*2u]*sgn;
  for(var k=1u;k<p.FB-1u;k++){
    let re=reim[(f*p.FB+k)*2u]; let im=reim[(f*p.FB+k)*2u+1u]; let b=k*p.N+n;
    acc=acc+2.0*(re*tcos[b]-im*tsin[b]);
  }
  frame[idx]=(acc/f32(p.N))*win[n];
}
@compute @workgroup_size(64) fn ola(@builtin(global_invocation_id) g:vec3<u32>){
  let q=g.x; if(q>=p.outlen){return;}
  var lo:u32=0u; if(q+1u>p.N){ lo=(q+1u-p.N+p.H-1u)/p.H; }
  let hi=q/p.H; var acc=0.0; var ws=0.0;
  for(var f=lo;f<=hi;f++){ if(f<p.T2){ let n=q-f*p.H; acc=acc+frame[f*p.N+n]; ws=ws+win[n]*win[n]; } }
  outp[q]=select(0.0,acc/ws,ws>1e-8);
}`;
let G = null;
async function initGPUistft() {
  const ad = await navigator.gpu.requestAdapter();
  const dev = await ad.requestDevice({ requiredLimits: { maxStorageBufferBindingSize: ad.limits.maxStorageBufferBindingSize, maxBufferSize: ad.limits.maxBufferSize } });
  const mod = dev.createShaderModule({ code: WGSL }), ents = [];
  for (let i = 0; i < 8; i++) ents.push({ binding: i, visibility: GPUShaderStage.COMPUTE, buffer: { type: i === 2 || i === 6 || i === 7 ? 'storage' : 'read-only-storage' } });
  ents.push({ binding: 8, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform' } });
  const bgl = dev.createBindGroupLayout({ entries: ents }), pl = dev.createPipelineLayout({ bindGroupLayouts: [bgl] }), P = {};
  for (const e of ['reim_k', 'idft', 'ola']) P[e] = dev.createComputePipeline({ layout: pl, compute: { module: mod, entryPoint: e } });
  const tcos = new Float32Array(FB * N), tsin = new Float32Array(FB * N), win = new Float32Array(N);
  for (let n = 0; n < N; n++) win[n] = 0.5 - 0.5 * Math.cos(2 * Math.PI * n / N);
  for (let k = 0; k < FB; k++) for (let n = 0; n < N; n++) { const a = 2 * Math.PI * k * n / N; tcos[k * N + n] = Math.cos(a); tsin[k * N + n] = Math.sin(a); }
  const ST = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, SS = ST | GPUBufferUsage.COPY_SRC;
  const mk = arr => { const b = dev.createBuffer({ size: arr.byteLength, usage: ST }); dev.queue.writeBuffer(b, 0, arr); return b; };
  const MO = H * (MT - 1) + N;
  const B = { tcos: mk(tcos), tsin: mk(tsin), win: mk(win),
    mag: dev.createBuffer({ size: MT * FB * 4, usage: SS }), phase: dev.createBuffer({ size: MT * FB * 4, usage: SS }),
    reim: dev.createBuffer({ size: MT * FB * 8, usage: SS }), frame: dev.createBuffer({ size: MT * N * 4, usage: SS }),
    out: dev.createBuffer({ size: MO * 4, usage: SS }), rb: dev.createBuffer({ size: MO * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }),
    bp: dev.createBuffer({ size: 32, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }) };
  B.bg = dev.createBindGroup({ layout: bgl, entries: [B.mag, B.phase, B.reim, B.tcos, B.tsin, B.win, B.frame, B.out, B.bp].map((b, i) => ({ binding: i, resource: { buffer: b } })) });
  G = { dev, P, B };
}
async function istftGPU(mag, phase, T2) {
  if (T2 > MT) { const { istftCPU } = await import(`./tts.js?v=${VER}`); return istftCPU(mag, phase, T2); }
  const { dev, P, B } = G, outlen = H * (T2 - 1) + N;
  dev.queue.writeBuffer(B.mag, 0, mag); dev.queue.writeBuffer(B.phase, 0, phase); dev.queue.writeBuffer(B.bp, 0, new Uint32Array([T2, N, FB, H, outlen]));
  const enc = dev.createCommandEncoder();
  const pass = (pl, n) => { const p = enc.beginComputePass(); p.setPipeline(P[pl]); p.setBindGroup(0, B.bg); p.dispatchWorkgroups(Math.ceil(n / 64)); p.end(); };
  pass('reim_k', T2 * FB); pass('idft', T2 * N); pass('ola', outlen);
  enc.copyBufferToBuffer(B.out, 0, B.rb, 0, outlen * 4); dev.queue.submit([enc.finish()]);
  await B.rb.mapAsync(GPUMapMode.READ, 0, outlen * 4);
  const full = new Float32Array(B.rb.getMappedRange(0, outlen * 4)).slice(); B.rb.unmap();
  return full.slice(N >> 1, outlen - (N >> 1));
}

// ---------------- helpers ----------------
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const secs = s => s < 10 ? s.toFixed(2) + ' s' : s.toFixed(1) + ' s';
const ICON_PLAY = '<svg viewBox="0 0 16 16" fill="currentColor"><path d="M4 2.5v11l9-5.5z"/></svg>';
const ICON_PAUSE = '<svg viewBox="0 0 16 16" fill="currentColor"><path d="M3.5 2.5h3v11h-3zM9.5 2.5h3v11h-3z"/></svg>';
function wav16(audio, sr) {
  const b = new ArrayBuffer(44 + audio.length * 2), v = new DataView(b), w = (o, s) => [...s].forEach((c, i) => v.setUint8(o + i, c.charCodeAt(0)));
  w(0, 'RIFF'); v.setUint32(4, 36 + audio.length * 2, true); w(8, 'WAVE'); w(12, 'fmt '); v.setUint32(16, 16, true); v.setUint16(20, 1, true); v.setUint16(22, 1, true);
  v.setUint32(24, sr, true); v.setUint32(28, sr * 2, true); v.setUint16(32, 2, true); v.setUint16(34, 16, true); w(36, 'data'); v.setUint32(40, audio.length * 2, true);
  let peak = 1e-6; for (const x of audio) peak = Math.max(peak, Math.abs(x)); const g = peak > 0.99 ? 0.99 / peak : 1;
  for (let i = 0; i < audio.length; i++) v.setInt16(44 + i * 2, Math.max(-1, Math.min(1, audio[i] * g)) * 32767, true);
  return new Blob([b], { type: 'audio/wav' });
}
function drawWave(progress = -1) {
  const c = $('wavecanvas'), t = S.take; c.width = c.clientWidth * devicePixelRatio; const x = c.getContext('2d'), W = c.width, Hh = c.height;
  x.clearRect(0, 0, W, Hh);
  const bw = 3 * devicePixelRatio, gap = 2 * devicePixelRatio, n = Math.floor(W / (bw + gap));
  const y = t ? t.audio : null, step = y ? Math.max(1, Math.floor(y.length / n)) : 1;
  let peak = 1e-4; if (y) for (let j = 0; j < y.length; j += 11) peak = Math.max(peak, Math.abs(y[j]));
  const cPlayed = css('--tea'), cRest = css('--line');
  for (let i = 0; i < n; i++) {
    let m = 0.02;
    if (y) { m = 0; const a = i * step; for (let j = a; j < Math.min(y.length, a + step); j += 3) m = Math.max(m, Math.abs(y[j])); m = Math.min(1, m / peak); }
    const h = Math.max(3 * devicePixelRatio, m * (Hh - 8));
    x.fillStyle = progress >= 0 && i / n <= progress ? cPlayed : cRest;
    x.beginPath(); x.roundRect(i * (bw + gap), (Hh - h) / 2, bw, h, bw / 2); x.fill();
  }
}
async function decodeToMono(blob) {
  const ac = new (window.AudioContext || window.webkitAudioContext)();
  const buf = await ac.decodeAudioData(await blob.arrayBuffer()); ac.close();
  const n = buf.length, ch = buf.numberOfChannels, y = new Float32Array(n);
  for (let c = 0; c < ch; c++) { const d = buf.getChannelData(c); for (let i = 0; i < n; i++) y[i] += d[i] / ch; }
  return { y, sr: buf.sampleRate };
}

// ---------------- voices ----------------
const allVoices = () => [...S.presets, ...S.saved, ...(S.pending ? [S.pending] : [])];
const current = () => allVoices().find(v => v.id === S.sel) || S.presets[0];
function loadSaved() { try { S.saved = JSON.parse(localStorage.getItem(STORE) || '[]').map(v => ({ ...v, emb: Float32Array.from(v.emb), kind: 'saved' })); } catch { S.saved = []; } }
function persist() { try { localStorage.setItem(STORE, JSON.stringify(S.saved.map(v => ({ ...v, emb: Array.from(v.emb, x => +x.toFixed(5)) })))); } catch {} }
let previewAudio = null;
function renderVoices() {
  const row = v => {
    const av = v.kind === 'preset' ? (v.gender === 'nữ' ? 'Nữ' : 'Nam') : '★';
    const ds = v.kind === 'preset' ? v.description : v.kind === 'pending' ? `chưa lưu · ${v.seconds.toFixed(1)} s mẫu` : `giọng của bạn · ${v.seconds.toFixed(1)} s mẫu`;
    const acts = (v.preview ? `<button data-a="play" aria-label="Nghe thử ${esc(v.name)}" title="Nghe thử">▶</button>` : '') + (v.kind === 'saved' ? `<button data-a="del" aria-label="Xoá giọng ${esc(v.name)}" title="Xoá">✕</button>` : '');
    return `<div class="voice" role="radio" tabindex="0" aria-checked="${v.id === S.sel}" data-id="${esc(v.id)}"><span class="av">${av}</span><div style="min-width:0"><div class="nm">${esc(v.name)}</div><div class="ds">${esc(ds)}</div></div><div class="acts">${acts}</div></div>`;
  };
  const mine = [...S.saved, ...(S.pending ? [S.pending] : [])];
  const base = S.presets.filter(v => v.group !== 'style'), style = S.presets.filter(v => v.group === 'style');
  $('voices').innerHTML = base.map(row).join('') + (style.length ? `<div class="vgroup">Phong cách TikTok</div>` + style.map(row).join('') : '')
    + (mine.length ? `<div class="vgroup">Giọng của bạn</div>` + mine.map(row).join('') : '');
  $('voices').querySelectorAll('.voice').forEach(el => {
    const v = allVoices().find(x => x.id === el.dataset.id), pick = () => { S.sel = v.id; renderVoices(); };
    el.onclick = e => {
      const a = e.target.dataset?.a;
      if (a === 'play') { previewAudio?.pause(); previewAudio = new Audio(); previewAudio.crossOrigin = 'anonymous'; previewAudio.src = v.preview.startsWith('blob:') ? v.preview : `${ROOT}/${v.preview}`; previewAudio.play(); return; }
      if (a === 'del') { S.saved = S.saved.filter(x => x.id !== v.id); persist(); if (S.sel === v.id) S.sel = S.presets[0].id; renderVoices(); return; }
      pick();
    };
    el.onkeydown = e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); pick(); } };
  });
}

// ---------------- voice cloning (CAM++ speaker embedding, runs locally) ----------------
async function embed(y, sr) {
  const y16 = resample(y, sr, 16000), { feats, T } = kaldiFbank(y16);
  if (!S.camp) { $('cloneStatus').textContent = 'Đang tải bộ trích đặc trưng giọng (28 MB)…'; S.camp = await ort.InferenceSession.create(`${ROOT}/onnx/campplus.onnx`, { executionProviders: ['wasm'] }); }
  const out = await S.camp.run({ [S.camp.inputNames[0]]: new ort.Tensor('float32', feats, [1, T, 80]) });
  return Float32Array.from(out[S.camp.outputNames[0]].data);
}
async function loadRef(blob, label) {
  $('cloneStatus').textContent = 'Đang đọc âm thanh…';
  try {
    const { y, sr } = await decodeToMono(blob), dur = y.length / sr;
    if (dur < 3) { $('cloneStatus').textContent = `Đoạn ghi chỉ dài ${dur.toFixed(1)} s. Cần ít nhất 3 giây giọng nói.`; return; }
    const seg = y.subarray(0, Math.floor(Math.min(dur, 15) * sr));
    const emb = await embed(seg, sr);
    S.pending = { id: 'pending', kind: 'pending', name: label.replace(/\.[a-z0-9]+$/i, '').slice(0, 40) || 'Giọng của tôi', emb, seconds: seg.length / sr, preview: URL.createObjectURL(blob) };
    S.sel = 'pending'; renderVoices();
    $('vname').value = S.pending.name; $('saveRow').hidden = false;
    $('cloneStatus').textContent = `Đã dùng ${(seg.length / sr).toFixed(1)} s đầu của “${label}”. Bấm Đọc để nghe, hoặc Lưu để giữ giọng này trong trình duyệt.`;
  } catch (e) { console.error(e); $('cloneStatus').textContent = 'Không đọc được file này. Thử WAV, MP3, M4A hoặc OGG.'; }
}


// ---------------- the iced-tea glass (button icon + big glass while generating) ----------------
const GLASS = `<path class="stream" d="M24 -8V44" stroke-width="3" stroke-dasharray="4 2" stroke-linecap="round" fill="none"></path>
  <g clip-path="url(#glassClip)"><rect class="tea" x="0" y="10" width="48" height="42"></rect>
  <rect class="ice" x="13" y="36" width="10" height="10" rx="2"></rect><rect class="ice" x="25" y="37" width="9" height="9" rx="2"></rect>
  <rect class="ice" x="18" y="26" width="9" height="9" rx="2"></rect></g>
  <path class="rim" d="M9 8h30l-3 40a3 3 0 0 1-3 3H15a3 3 0 0 1-3-3z" stroke-width="2.6"></path>`;
const setFill = f => { for (const el of document.querySelectorAll('svg.glass')) el.style.setProperty('--fill', String(f)); };
let brewOff = null;
function brewing(on, label = '') {
  clearTimeout(brewOff);
  if (on) { $('go').classList.add('brewing'); $('brew').classList.add('on'); $('brew').classList.add('brewing'); $('brewLbl').textContent = label || 'Đang pha…'; return; }
  setFill(1);                                                    // let the glass fill up, then fade away
  brewOff = setTimeout(() => { $('go').classList.remove('brewing'); $('brew').classList.remove('on', 'brewing'); setFill(0); }, 380);
}

// ---------------- editor: phrasing marks highlighted in place ----------------
const MARK_RE = /_|[;:!?…]|[,.](?!\d)|(?<!\d)[,.]/g;          // "." / "," between digits belong to a number, not a break
function renderHL() {
  const t = $('text').value; let html = '', last = 0;
  for (const m of t.matchAll(MARK_RE)) { html += esc(t.slice(last, m.index)) + `<mark class="${m[0] === '_' ? 'j' : 'p'}">${esc(m[0])}</mark>`; last = m.index + m[0].length; }
  $('hl').innerHTML = html + esc(t.slice(last)) + '\n';
  $('hl').scrollTop = $('text').scrollTop;
}
function count() {
  const t = $('text').value, n = (normalize(t).match(/[\p{L}\p{N}]+/gu) || []).length, j = (t.match(/_/g) || []).length;
  $('count').textContent = `${t.length} ký tự · ${n} âm tiết` + (j ? ` · ${j} chỗ đọc liền` : '');
}
const textChanged = () => { renderHL(); count(); };

// ---------------- mapping the spoken words back to the text (for writing a mark at a boundary) ----------------
// Each "_"-part is normalised on its own; its normalised words are aligned to the raw tokens by LCS. Words with a raw
// twin are anchors; runs without one (a number, an abbreviation) are written out as words before a mark goes inside them.
const RAW_RE = /[\p{L}\p{N}]+|[^\p{L}\p{N}\s_]/gu, WRE = /[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s]/gu;
function align(text) {
  const N = [], R = [], parts = []; let off = 0;
  for (const piece of text.split('_')) { parts.push([off, off + piece.length]); off += piece.length + 1; }
  parts.forEach(([a, b], pi) => {
    const raw = [...text.slice(a, b).matchAll(RAW_RE)].map(m => ({ t: m[0].normalize('NFC').toLowerCase(), s: a + m.index, e: a + m.index + m[0].length }));
    const nw = (normalizePart(text.slice(a, b)).match(WRE) || []).filter(w => w !== JOIN);
    const n = nw.length, m = raw.length, L = Array.from({ length: n + 1 }, () => new Int32Array(m + 1));
    for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = nw[i] === raw[j].t ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]);
    const r0 = R.length, match = new Array(n).fill(null); R.push(...raw);
    for (let i = 0, j = 0; i < n && j < m;) { if (nw[i] === raw[j].t) { match[i] = r0 + j; i++; j++; } else if (L[i + 1][j] >= L[i][j + 1]) i++; else j++; }
    nw.forEach((w, i) => N.push({ text: w, syl: isAlnum(w[0]), raw: match[i], part: pi }));
  });
  return { N, R, parts };
}
function expandGroup(text, A, k) {
  const { N, R, parts } = A, pt = N[k].part; let lo = k, hi = k;
  while (lo > 0 && N[lo - 1].raw === null && N[lo - 1].part === pt) lo--;
  while (hi < N.length - 1 && N[hi + 1].raw === null && N[hi + 1].part === pt) hi++;
  const a = lo > 0 && N[lo - 1].part === pt ? R[N[lo - 1].raw].e : parts[pt][0];
  const b = hi < N.length - 1 && N[hi + 1].part === pt ? R[N[hi + 1].raw].s : parts[pt][1];
  const out = []; for (let i = lo; i <= hi; i++) { if (!N[i].syl && out.length) out[out.length - 1] += N[i].text; else out.push(N[i].text); }
  const left = text.slice(0, a), right = text.slice(b);
  return left + (/[\p{L}\p{N},.;:!?…]$/u.test(left) ? ' ' : '') + out.join(' ') + (/^[\p{L}\p{N}]/u.test(right) ? ' ' : '') + right;
}
// write mark v ('none' | '_' | ',' | '.') at the boundary before spoken syllable g; returns the new text or null
function applyBoundary(text, g, v) {
  for (let it = 0; it < 4; it++) {
    const A = align(text), sy = []; A.N.forEach((x, i) => { if (x.syl) sy.push(i); });
    if (g <= 0 || g >= sy.length) return null;
    const wi = sy[g], pi = sy[g - 1], W = A.N[wi], P = A.N[pi];
    // a boundary at the EDGE of a number/abbreviation maps to the edge of its raw text ("17_giờ"); only one strictly
    // inside it ("năm_mươi" of 2.350.000) needs the number written out as words first
    const gr = k => { const { N, R } = A, pt = N[k].part; let lo = k, hi = k;
      while (lo > 0 && N[lo - 1].raw === null && N[lo - 1].part === pt) lo--;
      while (hi < N.length - 1 && N[hi + 1].raw === null && N[hi + 1].part === pt) hi++;
      const ra = lo > 0 && N[lo - 1].part === pt ? N[lo - 1].raw : null, rb = hi < N.length - 1 && N[hi + 1].part === pt ? N[hi + 1].raw : null;
      const own = R.map((r, j) => j).filter(j => (ra === null ? R[j].s >= A.parts[pt][0] : j > ra) && (rb === null ? R[j].e <= A.parts[pt][1] : j < rb) && !N.some(x => x.raw === j));
      return { lo, hi, s: own.length ? R[own[0]].s : null, e: own.length ? R[own[own.length - 1]].e : null }; };
    let a, b;
    if (P.raw !== null) a = A.R[P.raw].e; else { const G = gr(pi); if (G.hi !== pi || G.e === null) { text = expandGroup(text, A, pi); continue; } a = G.e; }
    if (W.raw !== null) b = A.R[W.raw].s; else { const G = gr(wi); if (G.lo !== wi || G.s === null) { text = expandGroup(text, A, wi); continue; } b = G.s; }
    if (b < a) { text = expandGroup(text, A, W.raw === null ? wi : pi); continue; }
    const region = text.slice(a, b), kept = region.replace(/[\s_,.;:!?…]/g, '');
    const end = region.includes('\n') ? '\n' : ' ';
    const rep = v === '_' ? (kept ? ` ${kept} ` : '_') : v === 'none' ? (kept ? ` ${kept}${end}` : end) : `${v}${kept ? ' ' + kept : ''}${end}`;
    return text.slice(0, a) + rep + text.slice(b);
  }
  return null;
}

// ---------------- the take: waveform, karaoke, phrasing picker ----------------
function renderKaraoke() {
  const t = S.take; let g = -1;
  $('karaoke').innerHTML = t.timeline.map((e, i) => {
    if (e.syllable) g++;
    const pre = e.syllable && e.joined ? '<b class="jn" aria-label="đọc liền">_</b>' : (i && e.syllable ? ' ' : '');
    return pre + `<span data-i="${i}" ${e.syllable ? `data-g="${g}"` : ''} class="${wordClass(t, i, 'fut')}">${esc(e.text)}</span>`;
  }).join('');
  $('karaoke').querySelectorAll('span').forEach(el => el.onclick = () => {
    const i = +el.dataset.i, e = t.timeline[i];
    let gg = el.dataset.g != null ? +el.dataset.g : -1;
    if (gg < 0) { for (let j = i + 1; j < t.timeline.length; j++) if (t.timeline[j].syllable) { gg = +$('karaoke').querySelector(`span[data-i="${j}"]`).dataset.g; break; } }
    if (gg > 0) { selectBoundary(gg); playBoundary(); }
    else { selectBoundary(-1); const p = $('player'); p.currentTime = e.start; p.play(); }
  });
}
function wordClass(t, i, state) {
  const e = t.timeline[i]; let sel = false;
  if (S.selG > 0 && e.syllable) { const el = $('karaoke').querySelector(`span[data-i="${i}"]`); sel = el ? +el.dataset.g === S.selG : false; }
  return state + (e.syllable ? '' : ' p') + (sel ? ' sel' : '');
}
const tlIndexOf = g => { let n = -1; const tl = S.take?.timeline || []; for (let i = 0; i < tl.length; i++) if (tl[i].syllable && ++n === g) return i; return -1; };
function boundaryState(ti) {
  const tl = S.take.timeline, prev = tl[ti - 1];
  if (prev && !prev.syllable) return /[.!?…;]/.test(prev.text) ? '.' : ',';
  return tl[ti].joined ? '_' : 'none';
}
function selectBoundary(g) {
  S.selG = g; const ti = g > 0 ? tlIndexOf(g) : -1;
  $('karaoke').querySelectorAll('span').forEach(el => el.classList.toggle('sel', S.selG > 0 && el.dataset.g != null && +el.dataset.g === S.selG));
  if (ti < 0) { $('brk').hidden = true; return; }
  const tl = S.take.timeline, e = tl[ti]; let pi = ti - 1; while (pi >= 0 && !tl[pi].syllable) pi--;
  const cur = boundaryState(ti), prev = tl[ti - 1];
  $('brk').hidden = false;
  $('brkWord').textContent = `Giữa “${pi >= 0 ? tl[pi].text : '…'}” và “${e.text}”`;
  const gap = prev && !prev.syllable ? Math.round((prev.end - prev.start) * 1000) : 0;
  $('brkInfo').textContent = { none: 'Đang để model tự quyết', _: 'Đang đọc liền', ',': `Đang ngắt ngắn${gap ? ` · ${gap} ms` : ''}`, '.': `Đang ngắt dài${gap ? ` · ${gap} ms` : ''}` }[cur];
  $('brkSeg').querySelectorAll('button').forEach(b => b.setAttribute('aria-checked', String(b.dataset.v === cur)));
}
function playBoundary() {
  const tl = S.take.timeline, i = tlIndexOf(S.selG); if (i < 0) return;
  let a = i; for (let n = 0; a > 0 && n < 2;) { a--; if (tl[a].syllable) n++; }
  let b = i; for (let n = 0; b < tl.length - 1 && n < 2;) { b++; if (tl[b].syllable) n++; }
  const p = $('player'); p.currentTime = tl[a].start; S.stopAt = tl[b].end + 0.1; p.play();
}
async function setBoundary(v) {
  const g = S.selG; if (g <= 0) return;
  const nt = applyBoundary($('text').value, g, v);
  if (nt == null) { $('status').textContent = 'Không ghi được dấu ở chỗ này. Thử gõ trực tiếp vào văn bản.'; return; }
  $('text').value = nt; textChanged();
  $('brkSeg').querySelectorAll('button').forEach(b => b.disabled = true);
  await generate({ replace: true, autoplay: false });
  $('brkSeg').querySelectorAll('button').forEach(b => b.disabled = false);
  selectBoundary(g); playBoundary();
}
let lastOn = -2;
function tick() {
  const t = S.take; if (!t) return; const p = $('player'), now = p.currentTime;
  drawWave(p.duration ? now / p.duration : -1);
  let on = -1; for (let i = 0; i < t.timeline.length; i++) if (now >= t.timeline[i].start) on = i;
  if (p.ended) on = t.timeline.length;
  if (on !== lastOn) {
    $('karaoke').querySelectorAll('span').forEach(el => { const i = +el.dataset.i; el.className = wordClass(t, i, i < on ? 'past' : i === on ? 'on' : 'fut'); });
    $('karaoke').querySelector('span.on')?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
    lastOn = on;
  }
  if (S.stopAt != null && now >= S.stopAt) { S.stopAt = null; p.pause(); }
  if (!p.paused) requestAnimationFrame(tick);
}
function showTake(t) {
  S.take = t; lastOn = -2; $('player').src = t.url;
  $('sDur').textContent = secs(t.dur); $('sTime').textContent = secs(t.time); $('sRtf').textContent = (t.dur / t.time).toFixed(1) + '×';
  $('sSyl').textContent = t.timeline.filter(e => e.syllable).length;
  $('play').disabled = false; $('dl').disabled = false; renderKaraoke(); drawWave(-1);
}
function renderHist() {
  $('hist').innerHTML = S.takes.length > 1 ? `<div class="vgroup">Lần đọc trước</div>` + S.takes.slice(1).map((t, i) => `<div class="h"><button class="btn" data-i="${i + 1}" aria-label="Mở lại">▶</button><div class="t">${esc(t.text)}</div><div class="m">${esc(t.voice)} · ${secs(t.dur)}</div></div>`).join('') : '';
  $('hist').querySelectorAll('button').forEach(b => b.onclick = () => { selectBoundary(-1); showTake(S.takes[+b.dataset.i]); $('player').play(); });
}

// ---------------- generate ----------------
async function generate({ replace = false, autoplay = true } = {}) {
  const text = $('text').value.trim(); if (!text || !S.tts || $('go').disabled) return;
  const fast = S.tts.hasFast;   // demo always runs the 2-step distilled flow (CFG baked in)
  const v = current(), opts = { w: 3, steps: fast ? 2 : 16, speed: +$('speed').value, seed: +$('seed').value, fast };
  $('go').disabled = true; $('goLabel').textContent = 'Đang pha…'; $('status').classList.remove('err'); $('status').textContent = '';
  setFill(0); brewing(true);
  const t0 = performance.now();
  try {
    const r = await S.tts.synth(text, v.emb, { ...opts,
      onStep: (i, n, k, K) => { setFill((i + k / K) / n); $('brewLbl').textContent = (n > 1 ? `Câu ${i + 1}/${n} · ` : '') + `bước ${k}/${K}`; } });
    const time = (performance.now() - t0) / 1000, dur = r.audio.length / r.sr, blob = wav16(r.audio, r.sr);
    const take = { text, voice: v.name, audio: r.audio, timeline: r.timeline, dur, time, url: URL.createObjectURL(blob) };
    if (replace && S.takes.length) { URL.revokeObjectURL(S.takes[0].url); S.takes[0] = take; }   // a phrasing edit replaces the current take
    else { S.takes.unshift(take); if (S.takes.length > 6) URL.revokeObjectURL(S.takes.pop().url); }
    if (!replace) S.selG = -1;
    showTake(take); renderHist(); selectBoundary(S.selG); if (autoplay) $('player').play().catch(() => {});
    $('status').textContent = `${S.backend === 'webgpu' ? 'WebGPU' : 'CPU (WASM)'} · ` + (fast ? `Nhanh · 2 bước` : `CFG ${opts.w} · ${opts.steps} bước`) + ` · seed ${opts.seed}`;
  } catch (e) { console.error(e); $('status').classList.add('err'); $('status').textContent = `Lỗi: ${e.message}. Thử câu ngắn hơn hoặc tải lại trang.`; }
  brewing(false); $('go').disabled = false; $('goLabel').textContent = 'Đọc';
}

// ---------------- init ----------------
function setPill(id, cls, text) { const p = $(id); p.className = 'pill ' + cls; p.lastElementChild.textContent = text; }
const PART_NAMES = { all: 'Trọng số int8', enc: 'Đọc chữ', cfm2: 'Sinh âm', cfm: 'Sinh âm', dec: 'Giải mã' };
async function init() {
  try { const th = localStorage.getItem(THEME); if (th) document.documentElement.dataset.theme = th; } catch {}
  for (const el of document.querySelectorAll('svg.glass')) el.innerHTML = GLASS;
  $('theme').onclick = () => {
    const d = document.documentElement, dark = d.dataset.theme ? d.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
    d.dataset.theme = dark ? 'light' : 'dark'; try { localStorage.setItem(THEME, d.dataset.theme); } catch {} drawWave(-1);
  };
  $('examples').innerHTML = EXAMPLES.map(([k], i) => `<button class="chip" data-i="${i}">${esc(k)}</button>`).join('');
  $('examples').querySelectorAll('.chip').forEach(b => b.onclick = () => { $('text').value = EXAMPLES[+b.dataset.i][1]; textChanged(); });
  let ct = null; $('text').oninput = () => { renderHL(); clearTimeout(ct); ct = setTimeout(count, 150); };
  $('text').onscroll = () => { $('hl').scrollTop = $('text').scrollTop; };
  new ResizeObserver(() => { $('hl').scrollTop = $('text').scrollTop; }).observe($('text'));
  textChanged();
  $('text').onkeydown = e => { if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); generate(); } };
  for (const [id, out, f] of [['speed', 'oSpeed', v => (+v).toFixed(2) + '×']]) { $(id).oninput = () => $(out).textContent = f($(id).value); $(id).oninput(); }
  $('dice').onclick = () => { $('seed').value = Math.floor(Math.random() * 100000); };
  $('go').onclick = () => generate();
  $('brkSeg').querySelectorAll('button').forEach(b => b.onclick = () => setBoundary(b.dataset.v));
  $('brkPlay').onclick = playBoundary;
  $('brkClose').onclick = () => selectBoundary(-1);
  const p = $('player');
  $('play').onclick = () => p.paused ? p.play() : p.pause();
  p.onplay = () => { $('play').innerHTML = ICON_PAUSE; $('play').setAttribute('aria-label', 'Tạm dừng'); requestAnimationFrame(tick); };
  p.onpause = p.onended = () => { $('play').innerHTML = ICON_PLAY; $('play').setAttribute('aria-label', 'Phát'); tick(); };
  $('wave').onclick = e => { if (!S.take) return; const r = $('wave').getBoundingClientRect(); p.currentTime = (e.clientX - r.left) / r.width * S.take.dur; p.play(); };
  $('dl').onclick = () => { if (!S.take) return; const a = document.createElement('a'); a.href = S.take.url; a.download = 'trada-tts.wav'; a.click(); };
  addEventListener('resize', () => drawWave(-1));
  // cloning
  const box = $('clone');
  $('pick').onclick = () => $('file').click();
  $('file').onchange = e => { const f = e.target.files[0]; if (f) loadRef(f, f.name); e.target.value = ''; };
  ['dragenter', 'dragover'].forEach(ev => box.addEventListener(ev, e => { e.preventDefault(); box.classList.add('drag'); }));
  ['dragleave', 'drop'].forEach(ev => box.addEventListener(ev, e => { e.preventDefault(); box.classList.remove('drag'); }));
  box.addEventListener('drop', e => { const f = e.dataTransfer.files[0]; if (f) loadRef(f, f.name); });
  $('save').onclick = () => {
    if (!S.pending) return;
    const v = { ...S.pending, id: 'v' + Date.now().toString(36), kind: 'saved', name: $('vname').value.trim() || 'Giọng của tôi', preview: null };
    S.saved.push(v); persist(); S.pending = null; S.sel = v.id; $('saveRow').hidden = true; renderVoices();
    $('cloneStatus').textContent = `Đã lưu “${v.name}” trong trình duyệt này.`;
  };
  let rec = null;
  $('rec').onclick = async () => {
    if (rec) { rec.stop(); return; }
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: false, noiseSuppression: true, autoGainControl: true } });
      const chunks = []; rec = new MediaRecorder(stream); rec.ondataavailable = e => chunks.push(e.data);
      rec.onstop = () => { stream.getTracks().forEach(t => t.stop()); $('rec').setAttribute('aria-pressed', 'false'); $('rec').textContent = '● Ghi âm'; rec = null;
        loadRef(new Blob(chunks, { type: chunks[0]?.type || 'audio/webm' }), 'Ghi âm ' + new Date().toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })); };
      rec.start(); $('rec').setAttribute('aria-pressed', 'true'); $('rec').textContent = '■ Dừng ghi';
      $('cloneStatus').textContent = 'Đang ghi. Đọc tự nhiên 5–15 giây rồi bấm Dừng ghi.';
    } catch { $('cloneStatus').textContent = 'Không mở được micro. Cho phép quyền micro, hoặc chọn file.'; }
  };
  // voices
  S.presets = (await (await fetch(`${ROOT}/voices/voices.json`)).json()).map(v => ({ ...v, kind: 'preset', emb: Float32Array.from(v.emb) }));
  loadSaved(); S.sel = S.presets[0].id; renderVoices();
  // model, with the brewing scene while it downloads
  let scene = null;
  try { const { startBrew } = await import(`./brew3d.js?v=${VER}`); scene = startBrew($('brew3d')); }
  catch (e) { console.warn('3D scene unavailable', e); $('brew3d').hidden = true; }
  const prog = (a, b, got, size) => {
    const f = b ? a / b : 0; scene?.setProgress(f);
    $('lMB').textContent = `${(a / 1e6).toFixed(0)} / ${((b || 11e6) / 1e6).toFixed(0)} MB`; $('lBar').style.width = (100 * f).toFixed(1) + '%';
    $('lParts').innerHTML = Object.keys(size).map(n => `<span><i class="${size[n] && got[n] >= size[n] ? 'done' : got[n] ? 'going' : ''}"></i>${PART_NAMES[n] || n}${size[n] ? ` · ${(size[n] / 1e6).toFixed(0)} MB` : ''}</span>`).join('');
    if (b && a >= b) $('lSub').textContent = S.backend === 'webgpu' ? 'Đang khởi động WebGPU…' : 'Đang khởi động…';
  };
  let gpu = false;
  try { gpu = !!(navigator.gpu && await navigator.gpu.requestAdapter()); } catch { gpu = false; }
  setPill('pBackend', gpu ? 'ok' : 'warn', gpu ? 'WebGPU · int8' : 'CPU · WASM · int8');
  const t0 = performance.now();
  try {
    if (!gpu) throw new Error('no webgpu');
    S.backend = 'webgpu'; await initGPUistft();
    S.tts = await TradaTTS.load(ort, ROOT, {}, istftGPU, prog, 'auto', { engine: 'wgpu' });     // hand-written WGSL kernels, int8 weights
  } catch (e) {
    if (gpu) { console.warn('WebGPU init failed, using WASM', e); setPill('pBackend', 'warn', 'CPU · WASM · int8 (WebGPU lỗi)'); }
    S.backend = 'wasm'; S.tts = await TradaTTS.load(ort, ROOT, { executionProviders: ['wasm'] }, null, prog, 'auto', { int8: true });
  }
  setPill('pLoad', '', `pha xong ${((performance.now() - t0) / 1000).toFixed(1)} s`);
  scene?.setProgress(1); $('lSub').textContent = 'Trà đã pha xong.';
  await new Promise(r => setTimeout(r, 450));
  $('loading').classList.add('out');
  await new Promise(r => setTimeout(r, 400));
  scene?.stop(); $('loading').hidden = true; $('result').hidden = false; drawWave(-1);
  $('go').disabled = false; $('goLabel').textContent = 'Đọc'; $('status').textContent = 'Sẵn sàng.';
}
init().catch(e => { console.error(e); $('loading').hidden = true; $('result').hidden = false; $('status').classList.add('err'); $('status').textContent = 'Không khởi động được: ' + e.message; });