File size: 25,589 Bytes
adcaa8e
 
 
 
 
d1bcdf2
 
 
afd62aa
 
 
 
 
 
d1bcdf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87868b8
adcaa8e
 
 
 
 
 
 
 
d1bcdf2
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1bcdf2
 
 
 
 
adcaa8e
 
 
87868b8
adcaa8e
 
 
 
 
 
 
afd62aa
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afd62aa
adcaa8e
afd62aa
adcaa8e
 
 
afd62aa
 
 
 
adcaa8e
 
 
 
 
 
 
 
 
 
 
afd62aa
adcaa8e
 
 
 
 
 
 
 
87868b8
 
 
 
 
 
 
 
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
 
 
afd62aa
adcaa8e
 
 
 
d1bcdf2
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1bcdf2
 
 
 
 
 
 
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1bcdf2
 
afd62aa
d1bcdf2
 
 
 
adcaa8e
 
 
 
 
 
 
 
afd62aa
87868b8
 
afd62aa
 
 
adcaa8e
 
afd62aa
 
 
 
adcaa8e
afd62aa
 
 
 
 
 
 
 
adcaa8e
afd62aa
 
 
adcaa8e
 
 
 
 
 
 
 
 
 
 
 
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
const SR = 16000;
const BLOCK = 1280;
const BLOCK_SEC = BLOCK / SR;
const LIVE_SPAN_SEC = 10;
const LIVE_KEEP_BLOCKS = 12.5 * 600;
const FETCH_TIMEOUT_MS = 90_000;
const LOAD_TIMEOUT_MS = 180_000;

const MODEL_BASE = "https://huggingface.co/OpenVoiceOS/wakehubert-wakewords/resolve/main/";
const CLIP_BASE = "https://raw.githubusercontent.com/OpenVoiceOS/ovos-ww-plugin-wakeforge/dev/test/clips/";
const FEATURIZERS = new Set(["wakehubert-int8", "wakehubert"]);

// The page's own files carry the __sign parameter of the page URL (see index.html); absolute URLs do not.
const signed = (path) => (/^https?:/.test(path) ? path : window.signedUrl(path));

async function fetchFile(path) {
  const ctl = new AbortController();
  const timer = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
  try {
    const r = await fetch(signed(path), {signal: ctl.signal});
    if (!r.ok) throw new Error(`${path}: HTTP ${r.status}${r.status === 401 || r.status === 403 ? " (not signed in to this Space)" : ""}`);
    return r;
  } catch (err) {
    if (err.name === "AbortError") throw new Error(`${path}: no response after ${FETCH_TIMEOUT_MS / 1000} s`);
    if (err instanceof TypeError) throw new Error(`${path}: ${err.message}`);
    throw err;
  } finally {
    clearTimeout(timer);
  }
}

function withTimeout(promise, ms, what) {
  let timer;
  return Promise.race([promise, new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`${what}: no result after ${ms / 1000} s`)), ms);
  })]).finally(() => clearTimeout(timer));
}

// Similar-sounding words each model fires on at its default threshold, from the model repository's README.
const CONFUSIONS = {
  wakehubert_jarvis: ["hey jarvis"],
  wakehubert_marvin: ["hey marvin"],
  wakehubert_hey_jarvis: ["hey chatterbox"],
  wakehubert_hello_nabu: ["hey marvin", "okay nabu"],
  wakehubert_hey_marvin: ["hello nabu", "okay nabu", "hey rhasspy", "hey robin", "marvin"],
  wakehubert_okay_nabu: ["hello nabu", "hey marvin", "hey rhasspy", "sometimes hey k9"],
  wakehubert_hey_robin: ["hey marvin", "hey rhasspy", "okay nabu"],
  wakehubert_android: ["sometimes hey floyd"],
  wakehubert_computer: ["hey computer"],
  wakehubert_hey_computer: ["computer"],
  wakehubert_sheila: ["computer"],
};

const $ = (id) => document.getElementById(id);
const els = {
  word: $("word"), wordNote: $("word-note"), facts: $("facts"), confusions: $("confusions"), say: $("say"), sayList: $("say-list"),
  thr: $("threshold"), thrValue: $("thr-value"), thrReset: $("thr-reset"),
  mic: $("mic"), file: $("file"), example: $("example"), runExample: $("run-example"),
  level: $("level"), levelBar: $("level-bar"), player: $("player"),
  plot: $("plot"), tip: $("tip"), status: $("status"), detections: $("detections"), source: $("source"),
  theme: $("theme"),
};

// ---- worker -------------------------------------------------------------------------------------
const worker = new Worker(signed("worker.js"), {type: "module"});
const pending = new Map();
let nextId = 1;
function call(msg, transfer = []) {
  return new Promise((resolve, reject) => {
    const id = nextId++;
    pending.set(id, {resolve, reject});
    worker.postMessage({...msg, id}, transfer);
  });
}
worker.onmessage = (e) => {
  const m = e.data;
  const p = pending.get(m.id);
  if (!p) return;
  pending.delete(m.id);
  if (m.ok) p.resolve(m);
  else p.reject(new Error(m.error));
};
worker.onerror = (e) => {
  setStatus(`The scoring worker failed to start (worker.js): ${e.message || "the file could not be loaded"}`, true);
  for (const p of pending.values()) p.reject(new Error("the scoring worker failed to start"));
  pending.clear();
};

// ---- state --------------------------------------------------------------------------------------
let models = [];
let phrases = {};
let entry = null;
let threshold = 0.5;
let mode = "idle";            // idle | live | clip
let clip = null;              // {samples, label, scores, detections}
let live = null;              // {scores, detections, offset, ctx, stream, node, backlog}
let loadToken = 0;

const clipOf = (name) => name.replace(/^wakehubert_/, "");
const spoken = (name) => name.replace(/^wakehubert_/, "").replace(/_/g, " ");
const fmt = (x, d = 3) => Number(x).toFixed(d);

function setStatus(text, error = false) {
  els.status.textContent = text;
  els.status.classList.toggle("error", error);
}

// ---- audio helpers ------------------------------------------------------------------------------
// The plugin receives 16-bit PCM and scales it by 1/32768; audio here goes through the same step.
function toPcmScale(x) {
  const out = new Float32Array(x.length);
  for (let i = 0; i < x.length; i++) {
    const q = Math.max(-32768, Math.min(32767, Math.round(x[i] * 32768)));
    out[i] = q / 32768;
  }
  return out;
}

// A 16 kHz PCM or float WAV is read directly: the browser's decoder rounds some 16-bit samples by one
// step, and the int8 featurizer is sensitive enough for that to move the score.
function readWav16k(arrayBuffer) {
  const v = new DataView(arrayBuffer);
  const tag = (o) => String.fromCharCode(v.getUint8(o), v.getUint8(o + 1), v.getUint8(o + 2), v.getUint8(o + 3));
  if (v.byteLength < 12 || tag(0) !== "RIFF" || tag(8) !== "WAVE") return null;
  let fmt = null, off = 12;
  while (off + 8 <= v.byteLength) {
    const id = tag(off), size = v.getUint32(off + 4, true), body = off + 8;
    if (id === "fmt ") {
      let format = v.getUint16(body, true);
      if (format === 0xfffe && size >= 26) format = v.getUint16(body + 24, true);
      fmt = {format, channels: v.getUint16(body + 2, true), rate: v.getUint32(body + 4, true),
             bits: v.getUint16(body + 14, true)};
    } else if (id === "data" && fmt) {
      const {format, channels, rate, bits} = fmt;
      if (rate !== SR || !((format === 1 && [16, 24, 32].includes(bits)) || (format === 3 && [32, 64].includes(bits)))) return null;
      const bytes = bits / 8;
      const n = Math.floor(Math.min(size, v.byteLength - body) / (bytes * channels));
      const out = new Float32Array(n);
      for (let i = 0; i < n; i++) {
        let acc = 0;
        for (let c = 0; c < channels; c++) {
          const p = body + (i * channels + c) * bytes;
          if (format === 3) acc += bits === 32 ? v.getFloat32(p, true) : v.getFloat64(p, true);
          else if (bits === 16) acc += v.getInt16(p, true) / 32768;
          else if (bits === 24) acc += ((v.getUint8(p) | (v.getUint8(p + 1) << 8) | (v.getInt8(p + 2) << 16)) / 8388608);
          else acc += v.getInt32(p, true) / 2147483648;
        }
        out[i] = acc / channels;
      }
      return toPcmScale(out);
    }
    off = body + size + (size & 1);
  }
  return null;
}

async function decodeTo16k(arrayBuffer) {
  const direct = readWav16k(arrayBuffer);
  if (direct) return direct;
  const ctx = new OfflineAudioContext(1, 1, SR);
  const buf = await ctx.decodeAudioData(arrayBuffer);
  const n = buf.length;
  const mono = new Float32Array(n);
  for (let c = 0; c < buf.numberOfChannels; c++) {
    const ch = buf.getChannelData(c);
    for (let i = 0; i < n; i++) mono[i] += ch[i] / buf.numberOfChannels;
  }
  return toPcmScale(mono);
}

// One second of silence after the audio, as the plugin's demo scores a file, so a word at the very end is heard.
function withTail(samples) {
  const out = new Float32Array(samples.length + SR);
  out.set(samples);
  return out;
}

async function scoreSamples(name, samples, thr) {
  const r = await call({type: "clip", model: name, threshold: thr, samples: withTail(samples)});
  return {scores: Array.from(r.scores), detections: r.detections, ms: r.ms, threshold: r.threshold};
}

// ---- model selection ----------------------------------------------------------------------------
function renderFacts() {
  const res = entry.measured?.default;
  const rows = [
    ["Language", entry.language],
    ["Featurizer", entry.featurizer === "wakehubert-int8" ? "WakeHuBERT int8" : "WakeHuBERT float32"],
    ["Default threshold", String(entry.default_threshold)],
  ];
  if (res) {
    rows.push(["Recall at default", `${(100 * res.recall).toFixed(1)}%`],
              ["False activations per hour", String(res.false_activations_per_hour)]);
  }
  els.facts.replaceChildren(...rows.map(([k, v]) => {
    const d = document.createElement("div");
    d.innerHTML = "<dt></dt><dd></dd>";
    d.children[0].textContent = k;
    d.children[1].textContent = v;
    return d;
  }));
  if (res) {
    const d = document.createElement("div");
    d.className = "wide";
    d.innerHTML = "<dt>Recall measured on</dt><dd></dd>";
    d.children[1].textContent = `${res.recall_test_clips} clips, ${res.recall_test_set}; false activations over ${res.negative_hours} h of speech, non-speech and household audio.`;
    els.facts.append(d);
  }
  els.wordNote.hidden = entry.calibrated;
  els.wordNote.textContent = entry.calibrated ? "" :
    "Threshold not calibrated: this model's score is not mapped to a false-activation rate, and useful values sit close to 1.";
  const conf = CONFUSIONS[entry.name];
  els.confusions.hidden = !conf;
  els.confusions.textContent = conf ? `Can also fire on similar-sounding words: ${conf.join(", ")}.` : "";
  const say = phrases[entry.name];
  els.say.hidden = !say;
  els.sayList.lang = say?.language ?? "";
  els.sayList.replaceChildren(...(say?.phrases ?? []).map((p) => {
    const li = document.createElement("li");
    li.textContent = p.text;
    return li;
  }));
}

function setThreshold(v) {
  threshold = Math.round(v * 1000) / 1000;
  els.thr.value = String(threshold);
  els.thrValue.textContent = fmt(threshold);
  els.thr.setAttribute("aria-valuetext", fmt(threshold));
}

async function selectModel(name) {
  entry = models.find((m) => m.name === name) || models[0];
  els.word.value = entry.name;
  setThreshold(entry.default_threshold);
  renderFacts();
  const clipName = clipOf(entry.name);
  if ([...els.example.options].some((o) => o.value === clipName)) els.example.value = clipName;
  const token = ++loadToken;
  setStatus(`Loading the ${spoken(entry.name)} model…`);
  try {
    await withTimeout(call({type: "load", model: entry.name}), LOAD_TIMEOUT_MS, `Loading ${entry.name}`);
    if (token !== loadToken) return;
    if (mode === "live") {
      resetLive();
      await call({type: "live-start", model: entry.name, threshold});
      setStatus(`Listening for "${spoken(entry.name)}".`);
    } else if (mode === "clip") {
      await rescoreClip();
    } else {
      setStatus(`Ready. Say "${spoken(entry.name)}" after starting the microphone, or score a file.`);
    }
  } catch (err) {
    if (token === loadToken) setStatus(`Could not load the model: ${err.message}`, true);
  }
  draw();
}

// ---- clips --------------------------------------------------------------------------------------
async function rescoreClip() {
  if (!clip) return;
  const token = ++loadToken;
  setStatus(`Scoring ${clip.label}…`);
  const r = await scoreSamples(entry.name, clip.samples, threshold);
  if (token !== loadToken) return;
  clip.scores = r.scores;
  clip.detections = r.detections;
  const secs = (clip.samples.length / SR).toFixed(1);
  setStatus(`Scored ${clip.label} (${secs} s plus 1 s of silence) with "${spoken(entry.name)}" in ${Math.round(r.ms)} ms.`);
  announceClipDetections();
  draw();
}

function announceClipDetections() {
  const d = clip.detections;
  els.detections.classList.toggle("hit", d.length > 0);
  els.detections.textContent = d.length
    ? `Detected "${spoken(entry.name)}" at ${d.map((i) => `${((i + 1) * BLOCK_SEC).toFixed(2)} s (score ${fmt(clip.scores[i], 2)})`).join(", ")}.`
    : `No detection. Highest score ${fmt(Math.max(...clip.scores), 3)}, threshold ${fmt(threshold)}.`;
}

async function loadClip(arrayBuffer, label, blob) {
  if (mode === "live") await stopMic();
  setStatus(`Decoding ${label}…`);
  let samples;
  try {
    samples = await decodeTo16k(arrayBuffer);
  } catch (err) {
    setStatus(`Could not decode ${label}. Use a WAV, FLAC or OGG file.`, true);
    return;
  }
  if (samples.length < BLOCK) {
    setStatus(`${label} is too short to score.`, true);
    return;
  }
  clip = {samples, label, scores: [], detections: []};
  mode = "clip";
  els.source.textContent = label;
  if (els.player.src) URL.revokeObjectURL(els.player.src);
  els.player.src = URL.createObjectURL(blob);
  els.player.hidden = false;
  try {
    await rescoreClip();
  } catch (err) {
    setStatus(`Scoring failed: ${err.message}`, true);
  }
}

// ---- microphone ---------------------------------------------------------------------------------
function resetLive() {
  if (!live) return;
  live.scores = [];
  live.detections = [];
  live.offset = 0;
  els.detections.textContent = "";
  els.detections.classList.remove("hit");
}

async function startMic() {
  if (!navigator.mediaDevices?.getUserMedia) {
    setStatus("This browser gives no microphone access to this page.", true);
    return;
  }
  els.mic.disabled = true;
  let stream;
  try {
    stream = await navigator.mediaDevices.getUserMedia({
      audio: {channelCount: 1, echoCancellation: false, noiseSuppression: false, autoGainControl: false},
    });
  } catch (err) {
    els.mic.disabled = false;
    setStatus(`Microphone not available: ${err.message}`, true);
    return;
  }
  const forceResampler = new URLSearchParams(location.search).get("resample") === "js";
  let ctx, src;
  try {
    if (forceResampler) throw new Error("resampler requested");
    ctx = new AudioContext({sampleRate: SR});
    src = ctx.createMediaStreamSource(stream);
  } catch {
    // Some browsers cannot connect a microphone to a 16 kHz context; the worklet resamples instead.
    if (ctx) ctx.close();
    ctx = new AudioContext();
    src = ctx.createMediaStreamSource(stream);
  }
  try {
    await ctx.audioWorklet.addModule(signed("worklet.js"));
  } catch (err) {
    stream.getTracks().forEach((t) => t.stop());
    ctx.close();
    throw new Error(`worklet.js could not be loaded: ${err.message}`);
  }
  const node = new AudioWorkletNode(ctx, "wake-capture", {numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1]});
  const sink = ctx.createGain();
  sink.gain.value = 0;
  src.connect(node);
  node.connect(sink).connect(ctx.destination);
  if (ctx.state === "suspended") await ctx.resume();

  mode = "live";
  clip = null;
  els.player.hidden = true;
  live = {ctx, stream, node, scores: [], detections: [], offset: 0, backlog: 0, sampleRate: ctx.sampleRate, blocks: 0};
  resetLive();
  await call({type: "live-start", model: entry.name, threshold});
  els.source.textContent = `microphone, ${ctx.sampleRate === SR ? "16 kHz" : `${ctx.sampleRate} Hz resampled to 16 kHz`}`;
  els.level.hidden = false;
  els.mic.textContent = "Stop microphone";
  els.mic.setAttribute("aria-pressed", "true");
  els.mic.disabled = false;
  setStatus(`Listening for "${spoken(entry.name)}".`);

  node.port.onmessage = (e) => {
    if (e.data.type !== "block" || !live || live.node !== node) return;
    const samples = toPcmScale(e.data.samples);
    let sum = 0;
    for (let i = 0; i < samples.length; i++) sum += samples[i] * samples[i];
    const db = 20 * Math.log10(Math.sqrt(sum / samples.length) + 1e-9);
    const pct = Math.max(0, Math.min(1, (db + 60) / 60));
    els.levelBar.style.width = `${(100 * pct).toFixed(0)}%`;
    els.levelBar.parentElement.setAttribute("aria-valuenow", db.toFixed(0));
    live.backlog++;
    const session = live;
    call({type: "block", samples}, [samples.buffer]).then((r) => {
      session.backlog--;
      if (live !== session || r.skipped) return;
      session.blocks++;
      session.scores.push(r.score);
      if (r.detected) {
        session.detections.push(session.offset + session.scores.length - 1);
        const t = ((session.offset + session.scores.length) * BLOCK_SEC).toFixed(1);
        els.detections.classList.add("hit");
        els.detections.textContent = `Detected "${spoken(entry.name)}" at ${t} s (score ${fmt(r.score, 2)}).`;
      }
      if (session.scores.length > LIVE_KEEP_BLOCKS) {
        const drop = session.scores.length - LIVE_KEEP_BLOCKS;
        session.scores.splice(0, drop);
        session.offset += drop;
      }
      if (session.backlog > 25) setStatus("This device is scoring slower than real time; detections lag behind.", true);
      scheduleDraw();
    }, (err) => setStatus(`Scoring failed: ${err.message}`, true));
  };
}

async function stopMic() {
  if (!live) return;
  const {ctx, stream, node} = live;
  node.port.onmessage = null;
  stream.getTracks().forEach((t) => t.stop());
  await ctx.close();
  await call({type: "live-stop"});
  els.mic.textContent = "Start microphone";
  els.mic.setAttribute("aria-pressed", "false");
  els.level.hidden = true;
  mode = "idle";
  setStatus("Microphone stopped.");
}

// ---- plot ---------------------------------------------------------------------------------------
let drawQueued = false;
function scheduleDraw() {
  if (drawQueued) return;
  drawQueued = true;
  requestAnimationFrame(() => { drawQueued = false; draw(); });
}

let view = null;   // what is on screen, for the hover readout

function draw() {
  const c = els.plot;
  const dpr = window.devicePixelRatio || 1;
  const w = c.clientWidth, h = c.clientHeight;
  if (!w || !h) return;
  if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) {
    c.width = Math.round(w * dpr);
    c.height = Math.round(h * dpr);
  }
  const g = c.getContext("2d");
  g.setTransform(dpr, 0, 0, dpr, 0, 0);
  const css = getComputedStyle(document.documentElement);
  const col = (n) => css.getPropertyValue(n).trim();
  g.fillStyle = col("--surface");
  g.fillRect(0, 0, w, h);

  let scores = [], dets = [], t0 = 0, t1 = 0, first = 0;
  if (mode === "clip" && clip) {
    scores = clip.scores; dets = clip.detections; t1 = Math.max(scores.length * BLOCK_SEC, 1);
  } else if (mode === "live" && live) {
    first = live.offset;
    scores = live.scores;
    dets = live.detections.map((i) => i - live.offset).filter((i) => i >= 0);
    const end = (live.offset + scores.length) * BLOCK_SEC;
    t1 = Math.max(end, LIVE_SPAN_SEC);
    t0 = t1 - LIVE_SPAN_SEC;
  } else {
    t1 = LIVE_SPAN_SEC;
  }
  const L = 34, R = 10, T = 8, B = 24;
  const pw = w - L - R, ph = h - T - B;
  const x = (t) => L + ((t - t0) / (t1 - t0)) * pw;
  const y = (v) => T + (1 - v) * ph;
  const tOf = (i) => (first + i + 1) * BLOCK_SEC;

  g.font = "11px system-ui, sans-serif";
  g.lineWidth = 1;
  g.strokeStyle = col("--grid");
  g.fillStyle = col("--text-2");
  g.textAlign = "right";
  g.textBaseline = "middle";
  for (const v of [0, 0.25, 0.5, 0.75, 1]) {
    g.beginPath(); g.moveTo(L, Math.round(y(v)) + 0.5); g.lineTo(L + pw, Math.round(y(v)) + 0.5); g.stroke();
    g.fillText(v.toFixed(2).replace(/0$/, ""), L - 6, y(v));
  }
  const span = t1 - t0;
  const step = span <= 4 ? 0.5 : span <= 12 ? 1 : span <= 30 ? 5 : span <= 120 ? 10 : 30;
  g.textAlign = "center";
  g.textBaseline = "top";
  for (let t = Math.ceil(t0 / step) * step; t <= t1 + 1e-9; t += step) {
    g.fillText(`${+t.toFixed(1)} s`, Math.min(Math.max(x(t), L + 10), L + pw - 10), T + ph + 6);
  }

  g.save();
  g.beginPath(); g.rect(L, T, pw, ph); g.clip();
  g.setLineDash([5, 4]);
  g.strokeStyle = col("--thr");
  g.lineWidth = 1.5;
  g.beginPath(); g.moveTo(L, y(threshold)); g.lineTo(L + pw, y(threshold)); g.stroke();
  g.setLineDash([]);

  if (scores.length) {
    g.strokeStyle = col("--series-1");
    g.lineWidth = 2;
    g.lineJoin = "round";
    g.beginPath();
    scores.forEach((s, i) => (i ? g.lineTo(x(tOf(i)), y(s)) : g.moveTo(x(tOf(i)), y(s))));
    g.stroke();
    for (const i of dets) {
      const px = x(tOf(i)), py = y(scores[i]);
      g.strokeStyle = col("--det");
      g.lineWidth = 1;
      g.beginPath(); g.moveTo(px, T); g.lineTo(px, T + ph); g.stroke();
      g.fillStyle = col("--det");
      g.strokeStyle = col("--surface");
      g.lineWidth = 2;
      g.beginPath(); g.arc(px, py, 5, 0, 2 * Math.PI); g.fill(); g.stroke();
    }
  }
  g.restore();
  view = {scores, first, x, tOf, L, pw, t0, t1};
  els.plot.setAttribute("aria-label", plotSummary(scores, dets, first));
}

function plotSummary(scores, dets, first) {
  if (!scores.length) return "Wake-word score against time: no audio scored yet.";
  const peak = Math.max(...scores);
  return `Wake-word score against time: ${scores.length} blocks of 80 ms, highest score ${fmt(peak, 2)}, ` +
    `threshold ${fmt(threshold)}, ${dets.length} detection${dets.length === 1 ? "" : "s"}.`;
}

function hover(e) {
  if (!view || !view.scores.length) { els.tip.hidden = true; return; }
  const rect = els.plot.getBoundingClientRect();
  const px = e.clientX - rect.left;
  const t = view.t0 + ((px - view.L) / view.pw) * (view.t1 - view.t0);
  const i = Math.round(t / BLOCK_SEC) - 1 - view.first;
  if (i < 0 || i >= view.scores.length) { els.tip.hidden = true; return; }
  els.tip.hidden = false;
  els.tip.textContent = `${view.tOf(i).toFixed(2)} s  score ${fmt(view.scores[i], 3)}`;
  const left = Math.min(Math.max(px + 10, 0), rect.width - els.tip.offsetWidth);
  els.tip.style.left = `${left}px`;
}

// ---- theme --------------------------------------------------------------------------------------
function themeLabel() {
  const t = document.documentElement.dataset.theme || "auto";
  els.theme.textContent = `Theme: ${t}`;
}
els.theme.addEventListener("click", () => {
  const order = ["auto", "light", "dark"];
  const cur = document.documentElement.dataset.theme || "auto";
  const next = order[(order.indexOf(cur) + 1) % order.length];
  if (next === "auto") delete document.documentElement.dataset.theme;
  else document.documentElement.dataset.theme = next;
  try { localStorage.setItem("theme", next); } catch (e) { /* not persisted */ }
  themeLabel();
  draw();
});
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", draw);

// ---- wiring -------------------------------------------------------------------------------------
let rescoreTimer = 0;
els.thr.addEventListener("input", () => {
  setThreshold(parseFloat(els.thr.value));
  if (mode === "live") call({type: "threshold", threshold});
  if (mode === "clip") {
    clearTimeout(rescoreTimer);
    rescoreTimer = setTimeout(() => rescoreClip().catch((err) => setStatus(err.message, true)), 150);
  }
  draw();
});
els.thrReset.addEventListener("click", () => {
  setThreshold(entry.default_threshold);
  els.thr.dispatchEvent(new Event("input"));
});
els.word.addEventListener("change", () => selectModel(els.word.value));
els.mic.addEventListener("click", () => (mode === "live" ? stopMic() : startMic().catch((err) => {
  els.mic.disabled = false;
  setStatus(`Microphone failed: ${err.message}`, true);
})));
els.file.addEventListener("change", async () => {
  const f = els.file.files[0];
  if (!f) return;
  await loadClip(await f.arrayBuffer(), f.name, f);
  els.file.value = "";
});
els.runExample.addEventListener("click", async () => {
  const name = els.example.value;
  let blob;
  try {
    blob = await (await fetchFile(`${CLIP_BASE}${name}.wav`)).blob();
  } catch (err) {
    setStatus(`Could not fetch the example clip: ${err.message}`, true);
    return;
  }
  await loadClip(await blob.arrayBuffer(), `example "${name.replace(/_/g, " ")}"`, blob);
});
els.plot.addEventListener("pointermove", hover);
els.plot.addEventListener("pointerleave", () => { els.tip.hidden = true; });
new ResizeObserver(() => draw()).observe(els.plot);

async function init() {
  themeLabel();
  models = (await fetchFile(`${MODEL_BASE}models.json`).then((x) => x.json())).models;
  // The page works without demo phrases.
  phrases = await fetchFile("phrases.json").then((x) => x.json(), () => ({}));
  const clips = await Promise.all(models.map((e) =>
    fetch(`${CLIP_BASE}${clipOf(e.name)}.wav`, {method: "HEAD"}).then((r) => r.ok, () => false)));
  models.forEach((e, i) => {
    const o = document.createElement("option");
    o.value = e.name;
    const unavailable = !FEATURIZERS.has(e.featurizer);
    o.disabled = unavailable;
    o.textContent = unavailable ? `${spoken(e.name)} (unavailable: featurizer ${e.featurizer} not bundled)` :
      e.calibrated ? spoken(e.name) : `${spoken(e.name)} (threshold not calibrated)`;
    els.word.append(o);
    if (clips[i] && !unavailable) {
      const x = document.createElement("option");
      x.value = clipOf(e.name);
      x.textContent = `"${spoken(e.name)}"`;
      els.example.append(x);
    }
  });
  els.runExample.disabled = els.example.disabled = !els.example.options.length;
  const wanted = new URLSearchParams(location.search).get("word");
  const usable = (n) => models.some((m) => m.name === n && FEATURIZERS.has(m.featurizer));
  const first = [`wakehubert_${wanted}`, "wakehubert_jarvis"].find(usable) || models.find((m) => FEATURIZERS.has(m.featurizer))?.name;
  await selectModel(first);
}

const ready = init().catch((err) => setStatus(`The page failed to start: ${err.message}`, true));

// For automated checks: score 16 kHz samples (int16 scaled by 1/32768) exactly as a clip is scored.
window.wakeDemo = {
  ready,
  scoreSamples: async (name, samples, thr) => scoreSamples(name, Float32Array.from(samples), thr),
  state: () => ({mode, model: entry?.name, threshold, liveBlocks: live?.blocks ?? 0,
                 liveDetections: live ? live.detections.length : 0, liveRate: live?.sampleRate,
                 clip: clip && {label: clip.label, scores: clip.scores, detections: clip.detections}}),
};