File size: 21,800 Bytes
5f6a457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxi Lite Console</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@400;500;600&family=Noto+Sans+Devanagari:wght@400;500&family=Noto+Sans+Tamil:wght@400;500&display=swap">
<style>
:root {
  --bg: #f3f4f1; --panel: #ffffff; --ink: #1d2430; --ink2: #4f5866; --muted: #808897; --line: #dfe2dc;
  --accent: #c2410c; --accent-ink: #ffffff; --accent-soft: #fbe9df; --good: #2f7d4f; --bad: #b42318;
  --wave: #c2410c; --wave2: #e7b9a0; --field: #fafaf8;
  color-scheme: light;
}
@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #14171c; --panel: #1c2027; --ink: #e8eaee; --ink2: #b4bac4; --muted: #868d99; --line: #2c323b;
    --accent: #f08a4b; --accent-ink: #1b1208; --accent-soft: #3a2518; --good: #5cc28a; --bad: #f2786b;
    --wave: #f08a4b; --wave2: #6b4430; --field: #171a20; color-scheme: dark;
  }
}
:root[data-theme="dark"] {
  --bg: #14171c; --panel: #1c2027; --ink: #e8eaee; --ink2: #b4bac4; --muted: #868d99; --line: #2c323b;
  --accent: #f08a4b; --accent-ink: #1b1208; --accent-soft: #3a2518; --good: #5cc28a; --bad: #f2786b;
  --wave: #f08a4b; --wave2: #6b4430; --field: #171a20; color-scheme: dark;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--bg); color: var(--ink);
  font: 15px/1.5 "IBM Plex Sans", "Noto Sans Devanagari", "Noto Sans Tamil", system-ui, sans-serif; }
.wrap { max-width: 1080px; margin: 0 auto; padding: 24px 16px 48px; display: grid; gap: 16px; }
header { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 16px; justify-content: space-between; }
h1 { font-size: 20px; font-weight: 600; margin: 0; letter-spacing: -0.01em; }
h1 small { font-weight: 400; color: var(--muted); font-size: 14px; margin-left: 6px; }
.status { font: 13px "IBM Plex Mono", monospace; color: var(--ink2); display: flex; gap: 6px; align-items: center; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); }
.dot.ok { background: var(--good); } .dot.bad { background: var(--bad); }
.grid { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 16px; align-items: start; }
@media (max-width: 820px) { .grid { grid-template-columns: 1fr; } }
.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; display: grid; gap: 14px; }
label, .lbl { font-size: 12px; font-weight: 500; color: var(--ink2); text-transform: uppercase; letter-spacing: 0.06em; }
.row { display: flex; flex-wrap: wrap; gap: 12px; }
.row > .f { flex: 1 1 160px; display: grid; gap: 6px; }
select, input[type=password], input[type=text], textarea {
  width: 100%; font: inherit; color: var(--ink); background: var(--field); border: 1px solid var(--line);
  border-radius: 7px; padding: 8px 10px; }
select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
textarea { min-height: 132px; resize: vertical; font-size: 16px; line-height: 1.6; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; }
.chip { font: 13px "IBM Plex Mono", monospace; border: 1px solid var(--line); background: var(--field); color: var(--ink2);
  border-radius: 999px; padding: 3px 10px; cursor: pointer; }
.chip:hover { border-color: var(--accent); color: var(--ink); }
.samples .chip { font-family: inherit; }
.count { font: 12px "IBM Plex Mono", monospace; color: var(--muted); justify-self: end; margin-top: -8px; }
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; }
.seg button { font: inherit; font-size: 14px; border: 0; background: var(--field); color: var(--ink2); padding: 7px 12px; cursor: pointer; }
.seg button[aria-pressed=true] { background: var(--accent-soft); color: var(--ink); font-weight: 500; }
.actions { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
.btn { font: inherit; font-weight: 600; border: 0; border-radius: 8px; padding: 10px 20px; cursor: pointer;
  background: var(--accent); color: var(--accent-ink); }
.btn:disabled { opacity: 0.5; cursor: default; }
.btn.ghost { background: transparent; color: var(--ink2); border: 1px solid var(--line); font-weight: 500; }
.hint { font-size: 13px; color: var(--muted); }
.err { color: var(--bad); font-size: 14px; min-height: 1.2em; }
canvas { width: 100%; height: 72px; display: block; background: var(--field); border: 1px solid var(--line); border-radius: 7px; }
.metrics { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; }
@media (max-width: 480px) { .metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.m { border: 1px solid var(--line); border-radius: 7px; padding: 8px 10px; background: var(--field); }
.m b { display: block; font: 500 20px "IBM Plex Mono", monospace; font-variant-numeric: tabular-nums; color: var(--ink); }
.m span { font-size: 12px; color: var(--muted); }
.hist { display: grid; gap: 10px; max-height: 560px; overflow: auto; }
.take { border-top: 1px solid var(--line); padding-top: 10px; display: grid; gap: 6px; }
.take:first-child { border-top: 0; padding-top: 0; }
.take .meta { font: 12px "IBM Plex Mono", monospace; color: var(--muted); display: flex; flex-wrap: wrap; gap: 4px 10px; }
.take .txt { font-size: 14px; color: var(--ink2); overflow-wrap: anywhere; }
.take audio { width: 100%; height: 34px; }
.take a { font-size: 12px; color: var(--accent); }
.tags td { padding: 2px 10px 2px 0; vertical-align: top; font-size: 13px; color: var(--ink2); }
.tags td:first-child { font-family: "IBM Plex Mono", monospace; color: var(--ink); white-space: nowrap; }
</style>
</head>
<body>
<div class="wrap">
  <header>
    <h1>Voxi Lite <small>endpoint console</small></h1>
    <div class="status"><span class="dot" id="dot"></span><span id="health">checking…</span></div>
  </header>

  <div class="grid">
    <section class="panel">
      <div class="row">
        <div class="f" style="flex-basis:260px">
          <label for="key">API key</label>
          <input id="key" type="password" autocomplete="off" placeholder="paste the test key">
        </div>
        <div class="f">
          <label for="lang">Language</label>
          <select id="lang">
            <option value="en">English (Indian)</option>
            <option value="hi">Hindi</option>
            <option value="hinglish">Hinglish (Latin script)</option>
            <option value="ta">Tamil</option>
            <option value="tanglish">Tanglish (Latin script)</option>
          </select>
        </div>
        <div class="f">
          <label for="voice">Voice</label>
          <select id="voice"><option>payal</option></select>
        </div>
      </div>

      <div style="display:grid;gap:6px">
        <label for="text">Text</label>
        <textarea id="text" maxlength="2000"></textarea>
        <div class="count" id="count">0 / 2000</div>
      </div>

      <div style="display:grid;gap:6px">
        <span class="lbl">Insert a sound</span>
        <div class="chips" id="tags"></div>
      </div>
      <div style="display:grid;gap:6px">
        <span class="lbl">Sample lines</span>
        <div class="chips samples" id="samples"></div>
      </div>

      <div class="actions">
        <div class="seg" role="group" aria-label="Mode">
          <button id="mStream" aria-pressed="true">Stream (WebSocket)</button>
          <button id="mWhole" aria-pressed="false">Whole file (HTTP)</button>
        </div>
        <button class="btn" id="speak">Speak</button>
        <button class="btn ghost" id="stop" disabled>Stop</button>
        <span class="hint">Ctrl + Enter to speak</span>
      </div>
      <div class="err" id="err"></div>

      <canvas id="wave" width="1000" height="144" aria-label="waveform of the last take"></canvas>
      <div class="metrics">
        <div class="m"><b id="mFirst">–</b><span>first audio</span></div>
        <div class="m"><b id="mTotal">–</b><span>total time</span></div>
        <div class="m"><b id="mAudio">–</b><span>audio length</span></div>
        <div class="m"><b id="mRtf">–</b><span>faster than real time</span></div>
      </div>
      <p class="hint" style="margin:0">First audio is measured in this browser, so it includes the network round trip to the
        server. Stream mode plays audio as it arrives, the way a phone call would hear it.</p>
    </section>

    <aside class="panel">
      <span class="lbl">Takes</span>
      <div class="hist" id="hist"><p class="hint" style="margin:0">Takes you make appear here, newest first, to replay or download.</p></div>
      <span class="lbl" style="margin-top:6px">Sounds Voxi understands</span>
      <table class="tags"><tbody>
        <tr><td>[laughs]</td><td>short laugh (also [chuckles])</td></tr>
        <tr><td>[laughs hard]</td><td>longer laugh</td></tr>
        <tr><td>[coughs]</td><td>cough</td></tr>
        <tr><td>[sighs]</td><td>sigh (male voices)</td></tr>
        <tr><td>hmm · mm-hmm · umm</td><td>written plainly, played as recorded fillers; also उम्म, हम्म</td></tr>
        <tr><td>voice@style</td><td>styles: warm, cheerful, calm, sorry, firm (pick in Voice)</td></tr>
      </tbody></table>
    </aside>
  </div>
</div>

<script>
(() => {
  const $ = id => document.getElementById(id);
  const SR = 24000;
  const store = { get(k) { try { return localStorage.getItem(k) || ""; } catch (e) { return ""; } },
                  set(k, v) { try { localStorage.setItem(k, v); } catch (e) {} } };
  const SAMPLES = {
    en: ["Hmm, let me check that for you. [laughs] Okay, your booking for tomorrow at 10 AM is confirmed.",
         "Thank you for calling. Your refund of rupees 2,400 has been processed and will reach you in three to five days.",
         "Mm-hmm. And what is your order number? You can read it out slowly.",
         "I am really sorry about the delay. [sighs] Let me fix this for you right now."],
    hi: ["नमस्ते, मैं Voxi से बोल रही हूँ। आपका बकाया ₹1,250 है, जो 15 तारीख़ तक भरना है।",
         "हम्म, एक मिनट रुकिए। आपका ऑर्डर कल शाम तक पहुँच जाएगा।",
         "जी, बिल्कुल। मैं अभी चेक करती हूँ। [laughs] हाँ, आपका टिकट कन्फर्म है।"],
    hinglish: ["Umm, aapka refund process ho gaya hai, aur paise teen se paanch din mein aa jayenge.",
               "Ji, main abhi check karti hoon. Aapka payment successful hai."],
    ta: ["உங்கள் ஆர்டர் நாளை மாலைக்குள் வந்துவிடும். வேறு ஏதாவது உதவி வேண்டுமா?"],
    tanglish: ["Ungal order naalaikku saayangaalam vandhudum, tracking link SMS-la anuppirukkom."],
  };
  const TAGS = ["[laughs]", "[laughs hard]", "[coughs]", "[sighs]", "Hmm,", "Mm-hmm.", "Umm,"];
  const EN_ONLY = new Set(["harper", "ethan", "amelia", "oliver"]);

  let mode = "stream", ctx = null, sources = [], ws = null, busy = false, voices = [];

  // ---------- setup ----------
  $("key").value = store.get("voxiKey");
  $("lang").value = store.get("voxiLang") || "en";
  const keyHdr = () => ({ "X-API-Key": $("key").value.trim() });

  function renderSamples() {
    const box = $("samples"); box.innerHTML = "";
    (SAMPLES[$("lang").value] || []).forEach((s, i) => {
      const b = document.createElement("button"); b.className = "chip"; b.textContent = `Sample ${i + 1}`; b.title = s;
      b.onclick = () => { $("text").value = s; count(); }; box.appendChild(b);
    });
  }
  TAGS.forEach(t => {
    const b = document.createElement("button"); b.className = "chip"; b.textContent = t;
    b.onclick = () => {
      const ta = $("text"), a = ta.selectionStart, z = ta.selectionEnd, v = ta.value;
      const pre = a > 0 && !/\s$/.test(v.slice(0, a)) ? " " : "", post = " ";
      ta.value = v.slice(0, a) + pre + t + post + v.slice(z); ta.focus();
      ta.selectionStart = ta.selectionEnd = a + pre.length + t.length + post.length; count();
    };
    $("tags").appendChild(b);
  });
  const count = () => { $("count").textContent = `${$("text").value.length} / 2000`; };
  $("text").addEventListener("input", count);
  $("text").addEventListener("keydown", e => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); speak(); } });
  $("lang").onchange = () => { store.set("voxiLang", $("lang").value); renderSamples(); fillVoices(); };
  $("key").onchange = () => { store.set("voxiKey", $("key").value.trim()); loadVoices(); };
  $("mStream").onclick = () => setMode("stream"); $("mWhole").onclick = () => setMode("whole");
  function setMode(m) { mode = m; $("mStream").setAttribute("aria-pressed", m === "stream"); $("mWhole").setAttribute("aria-pressed", m === "whole"); }
  $("speak").onclick = () => speak(); $("stop").onclick = () => stop();

  async function health() {
    try {
      const r = await fetch("/health"); const j = await r.json();
      $("dot").className = "dot ok"; $("health").textContent = `up · v${j.version} · ${j.voices} voices`;
    } catch (e) { $("dot").className = "dot bad"; $("health").textContent = "server not reachable"; }
  }
  async function loadVoices() {
    if (!$("key").value.trim()) { $("err").textContent = "Paste the API key to load the voice list."; return; }
    try {
      const r = await fetch("/v1/voices", { headers: keyHdr() });
      if (r.status === 401) { $("err").textContent = "That API key was rejected."; return; }
      voices = (await r.json()).voices; $("err").textContent = ""; fillVoices();
    } catch (e) { $("err").textContent = "Could not load voices: " + e.message; }
  }
  function fillVoices() {
    if (!voices.length) return;
    const sel = $("voice"), keep = sel.value || store.get("voxiVoice") || "payal", lang = $("lang").value;
    sel.innerHTML = "";
    const bases = [...new Set(voices.map(v => v.split("@")[0]))];
    bases.forEach(b => {
      if (EN_ONLY.has(b) && lang !== "en") return;
      const g = document.createElement("optgroup"); g.label = b + (EN_ONLY.has(b) ? " (English only)" : "");
      voices.filter(v => v.split("@")[0] === b).forEach(v => {
        const o = document.createElement("option"); o.value = v; o.textContent = v.includes("@") ? "  " + v : v; g.appendChild(o);
      });
      sel.appendChild(g);
    });
    sel.value = [...sel.options].some(o => o.value === keep) ? keep : "payal";
  }
  $("voice").onchange = () => store.set("voxiVoice", $("voice").value);

  // ---------- audio ----------
  const pcm16ToF32 = buf => { const i = new Int16Array(buf), f = new Float32Array(i.length); for (let k = 0; k < i.length; k++) f[k] = i[k] / 32768; return f; };
  function wavBlob(f32) {
    const n = f32.length, b = new ArrayBuffer(44 + n * 2), d = new DataView(b);
    const w = (o, s) => { for (let k = 0; k < s.length; k++) d.setUint8(o + k, s.charCodeAt(k)); };
    w(0, "RIFF"); d.setUint32(4, 36 + n * 2, true); w(8, "WAVE"); w(12, "fmt "); d.setUint32(16, 16, true);
    d.setUint16(20, 1, true); d.setUint16(22, 1, true); d.setUint32(24, SR, true); d.setUint32(28, SR * 2, true);
    d.setUint16(32, 2, true); d.setUint16(34, 16, true); w(36, "data"); d.setUint32(40, n * 2, true);
    for (let k = 0; k < n; k++) d.setInt16(44 + k * 2, Math.max(-1, Math.min(1, f32[k])) * 32767, true);
    return new Blob([b], { type: "audio/wav" });
  }
  function draw(chunks, marks) {
    const c = $("wave"), g = c.getContext("2d"), W = c.width, H = c.height, cs = getComputedStyle(document.documentElement);
    g.clearRect(0, 0, W, H);
    const all = chunks.reduce((a, x) => a + x.length, 0); if (!all) return;
    const per = Math.max(1, Math.ceil(all / W)); let x = 0, acc = 0, mx = 0, idx = 0;
    g.fillStyle = cs.getPropertyValue("--wave").trim();
    for (const ch of chunks) for (let k = 0; k < ch.length; k++) {
      mx = Math.max(mx, Math.abs(ch[k])); if (++acc === per) { const h = Math.max(1, mx * H * 0.95); g.fillRect(x, (H - h) / 2, 1, h); x++; acc = 0; mx = 0; }
      idx++;
    }
    g.fillStyle = cs.getPropertyValue("--wave2").trim();          // chunk boundaries: where each streamed piece began
    let pos = 0; for (const ch of chunks.slice(0, -1)) { pos += ch.length; g.fillRect(Math.round(pos / per), 0, 2, H); }
  }
  function metrics(first, total, audioS) {
    $("mFirst").textContent = first == null ? "–" : `${Math.round(first)} ms`;
    $("mTotal").textContent = total == null ? "–" : `${(total / 1000).toFixed(2)} s`;
    $("mAudio").textContent = audioS == null ? "–" : `${audioS.toFixed(2)} s`;
    $("mRtf").textContent = total && audioS ? `${(audioS / (total / 1000)).toFixed(1)}×` : "–";
  }
  function addTake(f32, info) {
    const box = $("hist"); if (box.querySelector("p")) box.innerHTML = "";
    const url = URL.createObjectURL(wavBlob(f32)), d = document.createElement("div"); d.className = "take";
    d.innerHTML = `<div class="meta"><span>${info.voice}</span><span>${info.lang}</span><span>${info.mode}</span>` +
      `<span>first ${info.first == null ? "–" : Math.round(info.first) + " ms"}</span><span>${info.audioS.toFixed(2)} s audio</span></div>` +
      `<div class="txt"></div><audio controls preload="metadata"></audio>` +
      `<a download="voxi_${info.voice.replace("@", "-")}_${Date.now()}.wav">download wav</a>`;
    d.querySelector(".txt").textContent = info.text; d.querySelector("audio").src = url; d.querySelector("a").href = url;
    box.prepend(d);
  }
  function setBusy(b) { busy = b; $("speak").disabled = b; $("stop").disabled = !b; }
  function stop() {
    sources.forEach(s => { try { s.stop(); } catch (e) {} }); sources = [];
    if (ws && ws.readyState === 1) ws.send(JSON.stringify({ event: "cancel" }));
    setBusy(false);
  }

  async function speak() {
    if (busy) return;
    const text = $("text").value.trim(), lang = $("lang").value, voice = $("voice").value, key = $("key").value.trim();
    $("err").textContent = "";
    if (!key) { $("err").textContent = "Paste the API key first."; return; }
    if (!text) { $("err").textContent = "Type something to say."; return; }
    store.set("voxiKey", key);
    if (!ctx) ctx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: SR });
    if (ctx.state === "suspended") await ctx.resume();
    sources = []; setBusy(true); metrics(null, null, null);
    const info = { text, lang, voice, mode: mode === "stream" ? "stream" : "whole" };
    const t0 = performance.now();
    if (mode === "whole") {
      try {
        const r = await fetch("/v1/tts", { method: "POST", headers: { ...keyHdr(), "Content-Type": "application/json" },
                                           body: JSON.stringify({ text, lang, voice, format: "pcm16", sample_rate: SR }) });
        if (!r.ok) { const j = await r.json().catch(() => ({})); throw new Error(j.error || `HTTP ${r.status}`); }
        const f = pcm16ToF32(await r.arrayBuffer()), total = performance.now() - t0;
        const b = ctx.createBuffer(1, f.length, SR); b.copyToChannel(f, 0);
        const s = ctx.createBufferSource(); s.buffer = b; s.connect(ctx.destination); s.onended = () => setBusy(false); s.start(); sources.push(s);
        draw([f]); metrics(total, total, f.length / SR); addTake(f, { ...info, first: total, audioS: f.length / SR });
      } catch (e) { $("err").textContent = e.message; setBusy(false); }
      return;
    }
    const chunks = []; let first = null, playAt = 0;
    ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/v1/tts/ws?key=${encodeURIComponent(key)}`);
    ws.binaryType = "arraybuffer";
    ws.onopen = () => ws.send(JSON.stringify({ text, lang, voice, format: "pcm16", sample_rate: SR, request_id: String(Date.now()) }));
    ws.onmessage = ev => {
      if (typeof ev.data !== "string") {
        const f = pcm16ToF32(ev.data); if (!f.length) return;
        if (first == null) { first = performance.now() - t0; playAt = ctx.currentTime + 0.05; $("mFirst").textContent = `${Math.round(first)} ms`; }
        chunks.push(f);
        const b = ctx.createBuffer(1, f.length, SR); b.copyToChannel(f, 0);
        const s = ctx.createBufferSource(); s.buffer = b; s.connect(ctx.destination);
        playAt = Math.max(playAt, ctx.currentTime); s.start(playAt); playAt += b.duration; sources.push(s);
        draw(chunks);
        return;
      }
      const m = JSON.parse(ev.data);
      if (m.event === "error") { $("err").textContent = m.error; setBusy(false); ws.close(); return; }
      if (m.event === "done") {
        const total = performance.now() - t0, all = new Float32Array(chunks.reduce((a, x) => a + x.length, 0));
        let o = 0; for (const c of chunks) { all.set(c, o); o += c.length; }
        metrics(first, total, all.length / SR);
        if (all.length) addTake(all, { ...info, first, audioS: all.length / SR });
        const left = Math.max(0, playAt - ctx.currentTime) * 1000; setTimeout(() => { if (busy) setBusy(false); }, left);
        ws.close();
      }
    };
    ws.onclose = ev => { if (ev.code === 1008) { $("err").textContent = "That API key was rejected."; setBusy(false); } };
    ws.onerror = () => { $("err").textContent = "WebSocket refused: wrong API key, or the server is down."; setBusy(false); };
  }

  renderSamples(); count(); health(); if ($("key").value) loadVoices();
  if (!$("text").value) { $("text").value = SAMPLES[$("lang").value][0]; count(); }
})();
</script>
</body>
</html>