Spaces:
Running

File size: 18,421 Bytes
74fea63
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb961d
 
 
 
 
 
 
 
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f30da
 
48842af
 
 
 
 
 
46f30da
31cfba2
adb961d
 
 
48842af
 
 
 
 
 
 
 
adb961d
 
 
 
 
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f30da
 
 
 
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f30da
48842af
 
 
 
 
 
 
 
 
 
adb961d
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adb961d
48842af
adb961d
 
 
 
 
 
 
 
 
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46f30da
48842af
 
 
 
 
 
adb961d
 
 
 
 
 
 
 
 
 
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
adb961d
48842af
 
 
46f30da
48842af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74fea63
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
<!doctype html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>TinyVoca-Vi — In-Browser Vietnamese TTS (WASM 1-Thread)</title>
<style>
  :root { --bg: #0f1117; --card: #181c25; --border: #2a3040; --text: #eef1f7; --muted: #9aa4b8; --accent: #5b8cff; --ok: #3ddc97; --warn: #ffb86c; }
  * { box-sizing: border-box; }
  body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); line-height: 1.5; }
  .wrap { max-width: 860px; margin: 0 auto; padding: 24px 16px 48px; }
  h1 { margin: 0 0 6px; font-size: 24px; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
  .badge { font-size: 12px; font-weight: 600; padding: 3px 9px; border-radius: 999px; background: #232a3b; color: var(--accent); border: 1px solid #33405c; }
  .sub { color: var(--muted); margin: 0 0 20px; font-size: 14px; }
  .card { background: var(--card); border: 1px solid var(--border); border-radius: 12px; padding: 18px; margin-bottom: 16px; }
  .status-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; font-size: 14px; flex-wrap: wrap; }
  .dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 8px; background: var(--warn); }
  .dot.ready { background: var(--ok); }
  .progress { height: 4px; background: #252b3b; border-radius: 4px; overflow: hidden; margin-top: 10px; }
  .progress > div { height: 100%; background: var(--accent); width: 0%; transition: width 0.15s; }
  textarea { width: 100%; min-height: 108px; background: #10141c; color: var(--text); border: 1px solid var(--border); border-radius: 8px; padding: 12px; font-size: 16px; font-family: inherit; resize: vertical; }
  textarea:focus { outline: 2px solid var(--accent); border-color: transparent; }
  .presets { display: flex; flex-wrap: wrap; gap: 8px; margin: 10px 0 14px; }
  .chip { background: #222838; color: var(--text); border: 1px solid var(--border); border-radius: 999px; padding: 5px 12px; font-size: 13px; cursor: pointer; }
  .chip:hover { border-color: var(--accent); color: #fff; }
  .voice-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; align-items: center; }
  .voice-btn { background: #121620; color: var(--muted); border: 1px solid var(--border); border-radius: 10px; padding: 8px 14px; font-size: 14px; cursor: pointer; display: flex; flex-direction: column; align-items: flex-start; min-width: 148px; transition: all 0.12s; }
  .voice-btn:hover { border-color: var(--accent); color: var(--text); }
  .voice-btn.active { background: #1d2842; border-color: var(--accent); color: #fff; box-shadow: 0 0 0 1px var(--accent); }
  .voice-btn .vname { font-weight: 600; font-size: 14px; }
  .voice-btn .vdesc { font-size: 11px; color: var(--muted); margin-top: 2px; }
  .voice-btn.active .vdesc { color: #b8cdfc; }
  .voice-btn:disabled { opacity: 0.4; cursor: not-allowed; }
  .controls { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 14px; margin: 14px 0; }
  .ctrl label { display: flex; justify-content: space-between; font-size: 13px; color: var(--muted); margin-bottom: 4px; }
  .ctrl label b { color: var(--text); }
  input[type=range] { width: 100%; accent-color: var(--accent); }
  .actions { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; margin-top: 14px; }
  button.primary { background: var(--accent); color: #fff; border: none; border-radius: 8px; padding: 10px 20px; font-size: 15px; font-weight: 600; cursor: pointer; }
  button.primary:disabled { opacity: 0.45; cursor: not-allowed; }
  button.secondary { background: #242a3a; color: var(--text); border: 1px solid var(--border); border-radius: 8px; padding: 10px 16px; font-size: 14px; cursor: pointer; }
  button.secondary:disabled { opacity: 0.45; cursor: not-allowed; }
  .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; }
  .metric { background: #121620; border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; }
  .metric .k { font-size: 12px; color: var(--muted); }
  .metric .v { font-size: 19px; font-weight: 700; margin-top: 2px; }
  .mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--muted); background: #10141c; padding: 10px; border-radius: 8px; overflow-x: auto; white-space: pre-wrap; word-break: break-word; }
  audio { width: 100%; margin-top: 10px; }
  .chk { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--muted); margin-left: auto; }
</style>
</head>
<body>
<div class="wrap">
  <h1>TinyVoca-Vi <span class="badge">v0.2.2 · 4.77M params</span> <span class="badge">3 Voices</span> <span class="badge">24 kHz</span> <span class="badge">WASM 1-Thread · 100% Offline</span></h1>
  <p class="sub">Northern Vietnamese neural TTS (3 female voices in 1 ONNX file, voicing-gated pitch-locked HN-Vocos) running directly in your browser via ONNX Runtime Web + rule-based G2P (~15 KB) and an English word list (~250 KB gzipped). No server, no Python.</p>

  <div class="card">
    <div class="status-bar">
      <div><span id="dot" class="dot"></span><span id="statusText">Starting worker...</span></div>
      <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
        <select id="modelSelect" style="background:#10141c;color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 8px;font-size:13px;">
          <option value="./assets/tiny-voca-vi-v0.2.2.onnx">v0.2.2 (foreign words with stress · 14.3 MB)</option>
          <option value="./assets/tiny-voca-vi-v0.2.1.onnx">v0.2.1 (better pauses and p sounds · 14.3 MB)</option>
          <option value="./assets/tiny-voca-vi-v0.2.onnx">v0.2 HN-Vocos (3 voices · echo-free · 14.3 MB)</option>
          <option value="./assets/tiny-voca-vi.onnx">v0.1 Vocos-1M (Mai Anh only · 13.8 MB)</option>
          <option value="./assets/tiny-voca-vi-512.onnx">v0.1 512-pt Vocos (Mai Anh only · 10.5 MB)</option>
        </select>
        <div style="font-size:12px;color:var(--muted)" id="runtimeInfo"></div>
      </div>
    </div>
    <div class="progress"><div id="progBar"></div></div>
  </div>

  <div class="card">
    <div class="voice-row" id="voiceRow">
      <button class="voice-btn active" data-voice="1"><span class="vname">Quỳnh Anh</span><span class="vdesc">Storytelling · clearest tones</span></button>
      <button class="voice-btn" data-voice="2"><span class="vname">Trúc Ly</span><span class="vdesc">Youngest · expressive</span></button>
      <button class="voice-btn" data-voice="0"><span class="vname">Mai Anh</span><span class="vdesc">News anchor · crisp</span></button>
    </div>
    <textarea id="textInput">Mỗi ngày, em đều dậy sớm, chạy bộ quanh hồ Hoàn Kiếm khoảng ba mươi phút.</textarea>
    <div class="presets">
      <button class="chip" data-text="Mỗi ngày, em đều dậy sớm, chạy bộ quanh hồ Hoàn Kiếm khoảng ba mươi phút.">Rhythm &amp; pauses</button>
      <button class="chip" data-text="Giá cổ phiếu hôm nay tăng 4,5% đạt 1.250 điểm.">Numbers &amp; %</button>
      <button class="chip" data-text="Ngày 29/11/2026, chiếc áo này có giá 50.000đ.">Date &amp; VND</button>
      <button class="chip" data-text="Từ tiếp theo là ma. Từ tiếp theo là mà. Từ tiếp theo là má. Từ tiếp theo là mả. Từ tiếp theo là mã. Từ tiếp theo là mạ.">6 Tones (ma)</button>
      <button class="chip" data-text="Tiếng Việt có sáu thanh điệu rất rõ ràng, đặc biệt là thanh ngã và thanh nặng. Sau cơn mưa rào buổi chiều, bầu không khí Hà Nội trở nên trong lành và dễ chịu hơn hẳn. Công nghệ trí tuệ nhân tạo đang giúp mô hình tổng hợp giọng nói chạy mượt mà ngay trên trình duyệt, không cần kết nối mạng.">Long paragraph (streaming)</button>
    </div>

    <div class="controls">
      <div class="ctrl">
        <label>Speed <b id="speedVal">1.00×</b></label>
        <input id="speed" type="range" min="0.7" max="1.5" step="0.05" value="1.0">
      </div>
      <div class="ctrl">
        <label>Pitch Shift <b id="pitchVal">0.0 st</b></label>
        <input id="pitch" type="range" min="-4" max="4" step="0.5" value="0">
      </div>
      <div class="ctrl">
        <label>Pause Scale <b id="pauseVal">1.00×</b></label>
        <input id="pause" type="range" min="0.5" max="2.0" step="0.1" value="1.0">
      </div>
      <div class="ctrl">
        <label>Foreign-word Stress <b id="stressVal">1.0×</b></label>
        <input id="stress" type="range" min="0" max="1.5" step="0.1" value="1">
      </div>
    </div>

    <div class="actions">
      <button id="speakBtn" class="primary" disabled>Speak</button>
      <button id="stopBtn" class="secondary" disabled>Stop</button>
      <button id="dlBtn" class="secondary" disabled>Download WAV</button>
      <button id="clearCacheBtn" class="secondary" title="Clear browser Cache Storage">Clear Cache</button>
      <label class="chk"><input id="shortFirst" type="checkbox" checked> Short first chunk (fast TTFA)</label>
    </div>
    <audio id="replayAudio" controls style="display:none"></audio>
  </div>

  <div class="card">
    <div class="metrics">
      <div class="metric"><div class="k">Cold Start</div><div class="v" id="mCold">—</div></div>
      <div class="metric"><div class="k">Warm TTFA</div><div class="v" id="mTtfa">—</div></div>
      <div class="metric"><div class="k">Overall RTF</div><div class="v" id="mRtf">—</div></div>
      <div class="metric"><div class="k">Synth / Audio</div><div class="v" id="mTime">—</div></div>
      <div class="metric"><div class="k">G2P Time</div><div class="v" id="mG2p">—</div></div>
    </div>
  </div>

  <div class="card">
    <div style="font-size:13px;color:var(--muted);margin-bottom:6px;">Front-end Inspection (Normalized + Phonemes/Tones)</div>
    <div id="debugOut" class="mono">Waiting for synthesis...</div>
  </div>
</div>

<script>
const $ = (id) => document.getElementById(id);
const worker = new Worker("./worker.js?v=0.2.2");

let audioCtx = null;
let workletNode = null;
let useWorklet = false;
let nextPlayTime = 0;
let activeSources = [];
let runId = 0;
let collectedChunks = [];
let lastSampleRate = 24000;
let lastWavUrl = null;
let selectedVoiceId = 1; // default: Quỳnh Anh (clearest tones)

async function ensureAudio() {
  if (!audioCtx) {
    const AudioContextCtor = window.AudioContext || window.webkitAudioContext;
    audioCtx = new AudioContextCtor({ sampleRate: 24000 });
    if (audioCtx.audioWorklet && window.isSecureContext) {
      try {
        await audioCtx.audioWorklet.addModule("./worklet.js");
        workletNode = new AudioWorkletNode(audioCtx, "pcm-queue-processor");
        workletNode.connect(audioCtx.destination);
        useWorklet = true;
      } catch (e) {
        console.warn("AudioWorklet fallback to BufferSource:", e);
        useWorklet = false;
      }
    }
    $("runtimeInfo").textContent += ` · Audio: ${useWorklet ? "AudioWorklet" : "BufferSource"} (${audioCtx.sampleRate} Hz)`;
  }
  if (audioCtx.state === "suspended") await audioCtx.resume();
}

function stopPlayback() {
  runId++;
  worker.postMessage({ type: "stop" });
  if (useWorklet && workletNode) {
    workletNode.port.postMessage({ type: "clear" });
  }
  for (const s of activeSources) { try { s.stop(); } catch (_) {} }
  activeSources = [];
  nextPlayTime = 0;
  $("stopBtn").disabled = true;
}

function enqueueAudio(samples, sampleRate) {
  if (useWorklet && workletNode && audioCtx.sampleRate === sampleRate) {
    const copy = new Float32Array(samples);
    workletNode.port.postMessage({ type: "push", samples: copy }, [copy.buffer]);
    return;
  }
  // Gapless AudioBufferSourceNode scheduling (works on any sample rate & non-HTTPS LAN IPs)
  const buf = audioCtx.createBuffer(1, samples.length, sampleRate);
  buf.getChannelData(0).set(samples);
  const src = audioCtx.createBufferSource();
  src.buffer = buf;
  src.connect(audioCtx.destination);
  const now = audioCtx.currentTime;
  const startAt = Math.max(now + 0.015, nextPlayTime);
  src.start(startAt);
  nextPlayTime = startAt + buf.duration;
  activeSources.push(src);
  src.onended = () => { activeSources = activeSources.filter((x) => x !== src); };
}

function encodeWav(chunks, sampleRate) {
  const totalLen = chunks.reduce((a, b) => a + b.length, 0);
  const buffer = new ArrayBuffer(44 + totalLen * 2);
  const view = new DataView(buffer);
  const writeStr = (off, s) => { for (let i = 0; i < s.length; i++) view.setUint8(off + i, s.charCodeAt(i)); };
  writeStr(0, "RIFF");
  view.setUint32(4, 36 + totalLen * 2, true);
  writeStr(8, "WAVE");
  writeStr(12, "fmt ");
  view.setUint32(16, 16, true);
  view.setUint16(20, 1, true);
  view.setUint16(22, 1, true);
  view.setUint32(24, sampleRate, true);
  view.setUint32(28, sampleRate * 2, true);
  view.setUint16(32, 2, true);
  view.setUint16(34, 16, true);
  writeStr(36, "data");
  view.setUint32(40, totalLen * 2, true);
  let off = 44;
  for (const ch of chunks) {
    for (let i = 0; i < ch.length; i++) {
      const s = Math.max(-1, Math.min(1, ch[i]));
      view.setInt16(off, s < 0 ? s * 0x8000 : s * 0x7fff, true);
      off += 2;
    }
  }
  return new Blob([buffer], { type: "audio/wav" });
}

worker.onmessage = ({ data }) => {
  if (data.type === "status") {
    $("statusText").textContent = data.text;
    if (data.progress !== null) $("progBar").style.width = `${Math.round(data.progress * 100)}%`;
  } else if (data.type === "ready") {
    $("dot").classList.add("ready");
    $("progBar").style.width = "100%";
    $("statusText").textContent = `Ready (${data.fromCache ? "cached" : "downloaded"}: fetch ${(data.fetchMs / 1000).toFixed(2)}s · session ${(data.sessionMs / 1000).toFixed(2)}s · warmup ${(data.warmupMs / 1000).toFixed(2)}s)`;
    $("runtimeInfo").textContent = `Model: ${(data.modelBytes / 1e6).toFixed(2)} MB · ${data.hasVoiceId ? "3 Voices" : "1 Voice (v0.1)"} · WASM 1T`;
    $("mCold").textContent = `${(data.loadMs / 1000).toFixed(2)} s`;
    for (const btn of document.querySelectorAll(".voice-btn")) {
      btn.disabled = !data.hasVoiceId && Number(btn.dataset.voice) !== 0;
    }
    if (!data.hasVoiceId) {
      selectedVoiceId = 0;
      for (const btn of document.querySelectorAll(".voice-btn")) {
        btn.classList.toggle("active", Number(btn.dataset.voice) === 0);
      }
    }
    $("speakBtn").disabled = false;
  } else if (data.type === "chunk") {
    if (data.id !== runId) return;
    lastSampleRate = data.sampleRate;
    collectedChunks.push(data.audio);
    enqueueAudio(data.audio, data.sampleRate);
    $("mTtfa").textContent = `${Math.round(data.ttfaMs)} ms`;
    $("mG2p").textContent = `${data.g2pMs.toFixed(1)} ms`;
    const pairStr = data.symbols.map((s, i) => data.toneIds[i] ? `${s}${data.toneIds[i]}` : s).join(" ");
    const line = `[Chunk ${data.index + 1}/${data.total}] ${data.inferMs.toFixed(0)} ms / ${data.audioSec.toFixed(2)}s (RTF ${data.rtf.toFixed(3)})\n  Norm: ${data.normalizedText}\n  IPA : ${pairStr}\n`;
    $("debugOut").textContent = (data.index === 0 ? "" : $("debugOut").textContent + "\n") + line;
  } else if (data.type === "done") {
    if (data.id !== runId) return;
    $("mRtf").textContent = data.overallRtf ? data.overallRtf.toFixed(3) : "—";
    $("mTime").textContent = `${Math.round(data.totalInferMs)}ms / ${data.totalAudioSec.toFixed(2)}s`;
    if (collectedChunks.length) {
      if (lastWavUrl) URL.revokeObjectURL(lastWavUrl);
      const blob = encodeWav(collectedChunks, lastSampleRate);
      lastWavUrl = URL.createObjectURL(blob);
      $("replayAudio").src = lastWavUrl;
      $("replayAudio").style.display = "block";
      $("dlBtn").disabled = false;
    }
    $("speakBtn").disabled = false;
  } else if (data.type === "cacheCleared") {
    $("statusText").textContent = "Cache cleared — reload page to re-download.";
  } else if (data.type === "error") {
    $("statusText").textContent = "Error: " + data.message;
    $("speakBtn").disabled = false;
  }
};

$("speed").oninput = () => { $("speedVal").textContent = `${Number($("speed").value).toFixed(2)}×`; };
$("pitch").oninput = () => { const v = Number($("pitch").value); $("pitchVal").textContent = `${v >= 0 ? "+" : ""}${v.toFixed(1)} st`; };
$("stress").oninput = () => { $("stressVal").textContent = `${Number($("stress").value).toFixed(1)}×`; };
$("pause").oninput = () => { $("pauseVal").textContent = `${Number($("pause").value).toFixed(2)}×`; };

for (const chip of document.querySelectorAll(".chip")) {
  chip.onclick = () => { $("textInput").value = chip.dataset.text; };
}

for (const btn of document.querySelectorAll(".voice-btn")) {
  btn.onclick = () => {
    if (btn.disabled) return;
    selectedVoiceId = Number(btn.dataset.voice);
    for (const b of document.querySelectorAll(".voice-btn")) {
      b.classList.toggle("active", b === btn);
    }
  };
}

$("speakBtn").onclick = async () => {
  await ensureAudio();
  stopPlayback();
  runId++;
  collectedChunks = [];
  nextPlayTime = audioCtx.currentTime + 0.02;
  $("speakBtn").disabled = true;
  $("stopBtn").disabled = false;
  $("dlBtn").disabled = true;
  $("debugOut").textContent = "Synthesizing...";
  worker.postMessage({
    type: "speak",
    id: runId,
    text: $("textInput").value,
    voiceId: selectedVoiceId,
    speed: Number($("speed").value),
    pitchShift: Number($("pitch").value),
    pause: Number($("pause").value),
    stress: Number($("stress").value),
    shortFirst: $("shortFirst").checked,
  });
};

$("stopBtn").onclick = () => {
  stopPlayback();
  $("speakBtn").disabled = false;
};

$("dlBtn").onclick = () => {
  if (!lastWavUrl) return;
  const a = document.createElement("a");
  a.href = lastWavUrl;
  a.download = "tiny-voca-vi.wav";
  a.click();
};

$("clearCacheBtn").onclick = () => worker.postMessage({ type: "clearCache" });

$("modelSelect").onchange = () => {
  stopPlayback();
  $("dot").classList.remove("ready");
  $("speakBtn").disabled = true;
  $("progBar").style.width = "0%";
  worker.postMessage({ type: "init", modelUrl: $("modelSelect").value });
};

worker.postMessage({ type: "init", modelUrl: $("modelSelect").value });
</script>
</body>
</html>