File size: 30,543 Bytes
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b657f
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd21b55
00dd564
 
 
44b657f
6c979df
44b657f
6c979df
00dd564
 
 
44b657f
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b657f
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
bd21b55
 
00dd564
 
 
 
bd21b55
 
00dd564
 
 
 
bd21b55
 
00dd564
 
 
 
bd21b55
 
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b657f
 
 
 
 
bd21b55
 
00dd564
 
 
 
44b657f
 
 
 
 
bd21b55
 
00dd564
 
 
 
44b657f
 
 
 
 
bd21b55
 
00dd564
 
 
 
44b657f
 
 
 
 
bd21b55
 
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e07934c
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c979df
44b657f
 
 
00dd564
6c979df
00dd564
 
 
6c979df
00dd564
 
 
 
 
 
 
 
 
 
6c979df
00dd564
6c979df
 
 
00dd564
6c979df
00dd564
 
 
 
 
e07934c
44b657f
 
 
 
6c979df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00dd564
 
44b657f
00dd564
 
 
6c979df
00dd564
 
 
44b657f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00dd564
 
 
 
44b657f
 
6c979df
44b657f
6c979df
 
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b657f
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44b657f
00dd564
44b657f
00dd564
44b657f
 
00dd564
44b657f
 
00dd564
 
44b657f
00dd564
 
 
 
 
44b657f
00dd564
 
 
 
 
 
 
 
 
 
 
 
44b657f
 
 
00dd564
 
 
 
 
 
 
 
44b657f
 
 
00dd564
 
 
44b657f
00dd564
 
 
 
 
 
 
 
 
44b657f
 
 
 
 
00dd564
 
 
 
 
 
 
 
 
 
 
 
 
 
e6ec92e
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Textual Echo Cancellation (TEC) — Interactive Demo</title>
  <style>
    :root {
      --bg: #f8fafc;
      --card: #ffffff;
      --border: #e2e8f0;
      --text: #0f172a;
      --muted: #475569;
      --primary: #2563eb;
      --primary-hover: #1d4ed8;
      --success-bg: #ecfdf5;
      --success-border: #10b981;
      --warn-bg: #fffbeb;
      --warn-border: #f59e0b;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
      background: var(--bg);
      color: var(--text);
      line-height: 1.5;
    }
    .container {
      max-width: 1140px;
      margin: 0 auto;
      padding: 28px 20px 48px;
    }
    .header {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 14px;
      padding: 24px 28px;
      margin-bottom: 24px;
      box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
    }
    .header h1 {
      margin: 0 0 8px;
      font-size: 1.75rem;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    .header p {
      margin: 8px 0;
      color: var(--muted);
      font-size: 0.96rem;
    }
    .badges {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin-top: 14px;
    }
    .badge-link {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 6px 12px;
      border-radius: 8px;
      background: #eff6ff;
      color: #1e40af;
      font-size: 0.86rem;
      font-weight: 600;
      text-decoration: none;
      border: 1px solid #bfdbfe;
    }
    .badge-link:hover {
      background: #dbeafe;
    }
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 24px;
    }
    @media (max-width: 860px) {
      .grid { grid-template-columns: 1fr; }
    }
    .panel {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 14px;
      padding: 22px 24px;
      box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
    }
    .panel h2 {
      margin: 0 0 16px;
      font-size: 1.18rem;
      border-bottom: 1px solid var(--border);
      padding-bottom: 10px;
    }
    .field {
      margin-bottom: 18px;
    }
    .field label {
      display: block;
      font-weight: 600;
      font-size: 0.92rem;
      margin-bottom: 6px;
    }
    .field .hint {
      font-size: 0.82rem;
      color: var(--muted);
      margin-bottom: 8px;
    }
    input[type="file"], select, textarea {
      width: 100%;
      padding: 10px 12px;
      border: 1px solid #cbd5e1;
      border-radius: 8px;
      font-size: 0.94rem;
      font-family: inherit;
      background: #fff;
    }
    textarea {
      resize: vertical;
      min-height: 76px;
    }
    audio {
      width: 100%;
      margin-top: 8px;
    }
    .btn-primary {
      width: 100%;
      padding: 13px 18px;
      background: var(--primary);
      color: #fff;
      font-weight: 600;
      font-size: 1rem;
      border: none;
      border-radius: 10px;
      cursor: pointer;
      transition: background 0.15s ease;
    }
    .btn-primary:hover:not(:disabled) {
      background: var(--primary-hover);
    }
    .btn-primary:disabled {
      opacity: 0.65;
      cursor: wait;
    }
    .status-bar {
      margin-top: 12px;
      padding: 10px 12px;
      border-radius: 8px;
      background: #f1f5f9;
      font-size: 0.88rem;
      color: #334155;
      display: none;
    }
    .result-box {
      padding: 12px 14px;
      border-radius: 10px;
      border: 1px solid var(--border);
      background: #f8fafc;
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
      font-size: 0.93rem;
      min-height: 48px;
      white-space: pre-wrap;
      word-break: break-word;
    }
    .result-box.before {
      background: var(--warn-bg);
      border-color: var(--warn-border);
    }
    .result-box.after {
      background: var(--success-bg);
      border-color: var(--success-border);
      font-weight: 600;
    }
    table.comp-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 10px;
      font-size: 0.88rem;
    }
    table.comp-table th, table.comp-table td {
      border: 1px solid var(--border);
      padding: 9px 10px;
      text-align: left;
      vertical-align: top;
    }
    table.comp-table th {
      background: #f1f5f9;
      font-weight: 600;
    }
    .examples-section {
      margin-top: 24px;
    }
    .examples-table {
      width: 100%;
      border-collapse: collapse;
      font-size: 0.88rem;
    }
    .examples-table th, .examples-table td {
      border: 1px solid var(--border);
      padding: 10px 12px;
      text-align: left;
    }
    .examples-table th {
      background: #f1f5f9;
    }
    .examples-table tr.example-row {
      cursor: pointer;
      transition: background 0.12s;
    }
    .examples-table tr.example-row:hover {
      background: #eff6ff;
    }
    .tag {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 999px;
      font-size: 0.76rem;
      font-weight: 600;
      background: #e0e7ff;
      color: #3730a3;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>🎙️ Textual Echo Cancellation (TEC) — Interactive Demo</h1>
      <p>
        When a user speaks to a smart speaker or voice assistant while the device is playing back a Text-to-Speech (TTS) response, the microphone captures an overlapping mixture of the <b>user's speech</b> and the <b>reverberant TTS playback echo</b>.
        <b>Textual Echo Cancellation (TEC)</b> cancels the TTS echo using the <b>source text of the TTS playback</b> (&lt; 0.1 KB side input) and reconstructs the clean user speech for Automatic Speech Recognition (ASR).
      </p>
      <div class="badges">
        <a class="badge-link" href="https://arxiv.org/abs/2008.06006" target="_blank">📄 Paper (arXiv:2008.06006)</a>
        <a class="badge-link" href="https://github.com/wq2012/tec" target="_blank">💻 GitHub (wq2012/tec)</a>
        <a class="badge-link" href="https://pypi.org/project/textual-echo-cancellation/" target="_blank">📦 PyPI (textual-echo-cancellation)</a>
        <a class="badge-link" href="https://huggingface.co/wq2012/tec_single_interfering" target="_blank">🤗 Model: tec_single_interfering</a>
        <a class="badge-link" href="https://huggingface.co/wq2012/tec_multi_interfering" target="_blank">🤗 Model: tec_multi_interfering</a>
        <a class="badge-link" href="https://huggingface.co/wq2012/aec_single_interfering" target="_blank">🤗 Model: aec_single_interfering</a>
        <a class="badge-link" href="https://google.github.io/speaker-id/publications/TEC/" target="_blank">🔊 Paper Audio Samples</a>
      </div>
    </div>

    <div class="grid">
      <!-- Left Column: Inputs -->
      <div class="panel">
        <h2>Inputs</h2>

        <div class="field">
          <label for="audioFileInput">1. User Uploaded Audio File (Microphone Mixture: User Query + TTS Playback Echo)</label>
          <div class="hint">Upload any WAV/MP3/FLAC audio file, or click one of the built-in examples below.</div>
          <input type="file" id="audioFileInput" accept="audio/*" />
          <audio id="inputAudioPlayer" controls preload="metadata"></audio>
        </div>

        <div class="field">
          <label for="ttsTextInput">2. Interfering TTS Playback Text (Source Text to Cancel)</label>
          <div class="hint">Enter the text transcript being spoken by the device's TTS playback.</div>
          <textarea id="ttsTextInput" placeholder="Enter the text spoken by the interfering TTS voice...">To obtain possession of this, Thurtell with his two associates resolved to kill him.</textarea>
        </div>

        <div class="field">
          <label for="modelSelect">Pretrained Model Configuration</label>
          <div class="hint">
            Built-in benchmark examples load exact neural checkpoint outputs (<code>examples/sample_1..4_{tec_single,tec_multi,aec_single}.wav</code>) for each selected model. Custom uploads or modified text in this static browser page run an in-browser WebAudio text-conditioned spectral canceller; run <code>python3 app.py</code> or <code>scripts/inference.py</code> locally for full Lingvo/TensorFlow checkpoint inference on arbitrary files.
          </div>
          <select id="modelSelect">
            <option value="tec_single_interfering">TecSingleInterfering (wq2012/tec_single_interfering — LibriTTS + LJ Speech)</option>
            <option value="tec_multi_interfering">TecMultiInterfering (wq2012/tec_multi_interfering — LibriTTS + VCTK)</option>
            <option value="aec_single_interfering">AecSingleInterfering (wq2012/aec_single_interfering — Audio Reference Baseline)</option>
          </select>
        </div>

        <button id="runBtn" class="btn-primary">Run Textual Echo Cancellation &amp; Compare ASR</button>
        <div id="statusBar" class="status-bar"></div>
      </div>

      <!-- Right Column: Outputs -->
      <div class="panel">
        <h2>Outputs</h2>

        <div class="field">
          <label>Textual Echo Cancelled Audio (Enhanced User Speech, 24 kHz WAV)</label>
          <audio id="outputAudioPlayer" controls preload="metadata"></audio>
        </div>

        <div class="field">
          <label>1. ASR Recognition Result on User Uploaded Audio (Before TEC)</label>
          <div id="asrBeforeBox" class="result-box before">Click "Run Textual Echo Cancellation &amp; Compare ASR" to transcribe.</div>
        </div>

        <div class="field">
          <label>2. ASR Recognition Result on Textual Echo Cancelled Audio (After TEC)</label>
          <div id="asrAfterBox" class="result-box after">Click "Run Textual Echo Cancellation &amp; Compare ASR" to transcribe.</div>
        </div>

        <div class="field">
          <label>Side-by-Side Comparison Summary</label>
          <div id="summaryContainer">
            <table class="comp-table">
              <thead>
                <tr>
                  <th>Approach</th>
                  <th>Audio Input to ASR</th>
                  <th>Side Input Payload</th>
                  <th>ASR Recognition Result</th>
                </tr>
              </thead>
              <tbody id="summaryTableBody">
                <tr>
                  <td colspan="4" style="color: var(--muted); text-align: center;">Run the demo to compare ASR results before and after Textual Echo Cancellation.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Built-in Examples -->
    <div class="panel examples-section">
      <h2>Built-in Benchmark Examples (Click Any Row to Load)</h2>
      <p style="margin-top: 0; font-size: 0.9rem; color: var(--muted);">
        Real 0 dB SNR reverberant mixtures (RT<sub>60</sub> = 0.25 s) from the LibriTTS <code>test-clean</code> + LJ Speech evaluation set. Clicking an example loads the audio mixture and interfering TTS source text.
      </p>
      <table class="examples-table">
        <thead>
          <tr>
            <th>Example</th>
            <th>Interfering TTS Playback Text (Side Input to Cancel)</th>
            <th>Ground-Truth Clean User Query (Target)</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          <tr class="example-row" data-idx="0">
            <td><span class="tag">Sample 1</span></td>
            <td><code>To obtain possession of this, Thurtell with his two associates resolved to kill him.</code></td>
            <td><i>"\"We've tortured each other enough for tonight."</i></td>
            <td><b>Load &amp; Run →</b></td>
          </tr>
          <tr class="example-row" data-idx="1">
            <td><span class="tag">Sample 2</span></td>
            <td><code>As he told the driver, quote, Let's get out of here; we are hit, end quote,</code></td>
            <td><i>"The chair was empty; but he knew."</i></td>
            <td><b>Load &amp; Run →</b></td>
          </tr>
          <tr class="example-row" data-idx="2">
            <td><span class="tag">Sample 3</span></td>
            <td><code>Carro reported that when questioned about his mother Lee said, quote,</code></td>
            <td><i>"Have we followed that road?"</i></td>
            <td><b>Load &amp; Run →</b></td>
          </tr>
          <tr class="example-row" data-idx="3">
            <td><span class="tag">Sample 4</span></td>
            <td><code>The Commission has concluded that on April ten, nineteen sixty-three,</code></td>
            <td><i>"The parliament and the Scots laid their proposals before the king."</i></td>
            <td><b>Load &amp; Run →</b></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <script type="module">
    import { pipeline, env } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.0.2";
    env.allowLocalModels = false;

    const BUILTIN_EXAMPLES = [
      {
        mixedUrl: "examples/sample_1_mixed.wav",
        tecUrl: "examples/sample_1_tec.wav",
        outputs: {
          tec_single_interfering: "examples/sample_1_tec_single.wav",
          tec_multi_interfering: "examples/sample_1_tec_multi.wav",
          aec_single_interfering: "examples/sample_1_aec_single.wav"
        },
        ttsText: "To obtain possession of this, Thurtell with his two associates resolved to kill him.",
        refText: "\"We've tortured each other enough for tonight."
      },
      {
        mixedUrl: "examples/sample_2_mixed.wav",
        tecUrl: "examples/sample_2_tec.wav",
        outputs: {
          tec_single_interfering: "examples/sample_2_tec_single.wav",
          tec_multi_interfering: "examples/sample_2_tec_multi.wav",
          aec_single_interfering: "examples/sample_2_aec_single.wav"
        },
        ttsText: "As he told the driver, quote, Let's get out of here; we are hit, end quote,",
        refText: "The chair was empty; but he knew."
      },
      {
        mixedUrl: "examples/sample_3_mixed.wav",
        tecUrl: "examples/sample_3_tec.wav",
        outputs: {
          tec_single_interfering: "examples/sample_3_tec_single.wav",
          tec_multi_interfering: "examples/sample_3_tec_multi.wav",
          aec_single_interfering: "examples/sample_3_aec_single.wav"
        },
        ttsText: "Carro reported that when questioned about his mother Lee said, quote,",
        refText: "Have we followed that road?"
      },
      {
        mixedUrl: "examples/sample_4_mixed.wav",
        tecUrl: "examples/sample_4_tec.wav",
        outputs: {
          tec_single_interfering: "examples/sample_4_tec_single.wav",
          tec_multi_interfering: "examples/sample_4_tec_multi.wav",
          aec_single_interfering: "examples/sample_4_aec_single.wav"
        },
        ttsText: "The Commission has concluded that on April ten, nineteen sixty-three,",
        refText: "The parliament and the Scots laid their proposals before the king."
      }
    ];

    const audioFileInput = document.getElementById("audioFileInput");
    const inputAudioPlayer = document.getElementById("inputAudioPlayer");
    const ttsTextInput = document.getElementById("ttsTextInput");
    const modelSelect = document.getElementById("modelSelect");
    const runBtn = document.getElementById("runBtn");
    const statusBar = document.getElementById("statusBar");
    const outputAudioPlayer = document.getElementById("outputAudioPlayer");
    const asrBeforeBox = document.getElementById("asrBeforeBox");
    const asrAfterBox = document.getElementById("asrAfterBox");
    const summaryTableBody = document.getElementById("summaryTableBody");

    let currentAudioSource = { type: "builtin", index: 0, blobUrl: BUILTIN_EXAMPLES[0].mixedUrl };
    inputAudioPlayer.src = BUILTIN_EXAMPLES[0].mixedUrl;

    let asrTranscriber = null;

    function setStatus(msg, show = true) {
      statusBar.style.display = show ? "block" : "none";
      statusBar.textContent = msg;
    }

    audioFileInput.addEventListener("change", (e) => {
      const file = e.target.files && e.target.files[0];
      if (!file) return;
      const url = URL.createObjectURL(file);
      currentAudioSource = { type: "upload", file, blobUrl: url };
      inputAudioPlayer.src = url;
    });

    // Decode audio URL/Blob to Float32Array at targetSampleRate
    async function decodeAudioAtRate(urlOrBlob, targetSampleRate) {
      let arrayBuffer;
      if (urlOrBlob instanceof Blob) {
        arrayBuffer = await urlOrBlob.arrayBuffer();
      } else {
        const resp = await fetch(urlOrBlob);
        arrayBuffer = await resp.arrayBuffer();
      }
      const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
      const decoded = await audioCtx.decodeAudioData(arrayBuffer);
      await audioCtx.close();

      const numFrames = Math.ceil(decoded.duration * targetSampleRate);
      const offlineCtx = new OfflineAudioContext(1, Math.max(1, numFrames), targetSampleRate);
      const source = offlineCtx.createBufferSource();
      source.buffer = decoded;
      source.connect(offlineCtx.destination);
      source.start(0);
      const rendered = await offlineCtx.startRendering();
      return new Float32Array(rendered.getChannelData(0));
    }

    // Radix-2 in-place Cooley-Tukey FFT
    function fftRadix2(re, im, inverse = false) {
      const n = re.length;
      for (let i = 1, j = 0; i < n; i++) {
        let bit = n >> 1;
        for (; j & bit; bit >>= 1) j ^= bit;
        j ^= bit;
        if (i < j) {
          let tr = re[i]; re[i] = re[j]; re[j] = tr;
          let ti = im[i]; im[i] = im[j]; im[j] = ti;
        }
      }
      for (let len = 2; len <= n; len <<= 1) {
        const ang = 2 * Math.PI / len * (inverse ? 1 : -1);
        const wlenR = Math.cos(ang);
        const wlenI = Math.sin(ang);
        for (let i = 0; i < n; i += len) {
          let wR = 1, wI = 0;
          const half = len >> 1;
          for (let j = 0; j < half; j++) {
            const uR = re[i + j], uI = im[i + j];
            const vR = re[i + j + half] * wR - im[i + j + half] * wI;
            const vI = re[i + j + half] * wI + im[i + j + half] * wR;
            re[i + j] = uR + vR;
            im[i + j] = uI + vI;
            re[i + j + half] = uR - vR;
            im[i + j + half] = uI - vI;
            const nextWR = wR * wlenR - wI * wlenI;
            wI = wR * wlenI + wI * wlenR;
            wR = nextWR;
          }
        }
      }
      if (inverse) {
        for (let i = 0; i < n; i++) {
          re[i] /= n;
          im[i] /= n;
        }
      }
    }

    // Text-conditioned 24 kHz spectral echo cancellation (stop-token boundary + character-phonetic profile + reverberant tail suppression)
    function runBrowserTecEnhancement(mixedWav24k, interferingText) {
      const frameLen = 1200; // 50 ms at 24 kHz
      const frameStep = 300; // 12.5 ms at 24 kHz
      const fftSize = 2048;
      const numBins = fftSize / 2 + 1;
      const numSamples = mixedWav24k.length;
      if (numSamples < frameLen) return new Float32Array(mixedWav24k);

      const numFrames = Math.floor((numSamples - frameLen) / frameStep) + 1;
      const hann = new Float32Array(frameLen);
      for (let i = 0; i < frameLen; i++) {
        hann[i] = 0.5 * (1 - Math.cos((2 * Math.PI * i) / frameLen));
      }

      const cleanText = (interferingText || "").trim();
      const charCount = cleanText.length;
      const selectedModel = modelSelect ? modelSelect.value : "tec_single_interfering";
      const isMulti = selectedModel === "tec_multi_interfering";
      const isAec = selectedModel === "aec_single_interfering";

      // Forward STFT & frame log-energy
      const stftRe = new Array(numFrames);
      const stftIm = new Array(numFrames);
      const stftMag = new Array(numFrames);
      const frameLogE = new Float32Array(numFrames);

      for (let t = 0; t < numFrames; t++) {
        const re = new Float32Array(fftSize);
        const im = new Float32Array(fftSize);
        const offset = t * frameStep;
        for (let i = 0; i < frameLen; i++) {
          re[i] = mixedWav24k[offset + i] * hann[i];
        }
        fftRadix2(re, im, false);
        const mag = new Float32Array(numBins);
        let sumLog = 0.0;
        for (let k = 0; k < numBins; k++) {
          const m = Math.hypot(re[k], im[k]);
          mag[k] = m;
          sumLog += Math.log(Math.max(1e-3, m));
        }
        frameLogE[t] = sumLog / numBins;
        stftRe[t] = re;
        stftIm[t] = im;
        stftMag[t] = mag;
      }

      // Frame-level stop-token boundary detection modulated by text character rate
      const charRate = charCount / Math.max(1, numFrames);
      const rateWeight = charCount > 0 ? Math.exp(-0.5 * Math.pow((charRate - 0.19) / 0.12, 2)) : 0.0;
      const kMinRatio = isMulti ? 0.74 : (isAec ? 0.65 : 0.68);
      const kMaxRatio = isMulti ? 0.87 : (isAec ? 0.96 : 0.95);
      const kMin = Math.max(1, Math.floor(kMinRatio * numFrames));
      const kMax = Math.max(kMin + 1, Math.floor(kMaxRatio * numFrames));
      let kStar = numFrames;
      if (charCount > 0 && numFrames > 8) {
        let bestScore = -1e9;
        for (let k = kMin; k < Math.min(numFrames - 1, kMax); k++) {
          let sumBefore = 0.0;
          for (let i = 0; i < k; i++) sumBefore += frameLogE[i];
          let sumAfter = 0.0;
          for (let i = k; i < numFrames; i++) sumAfter += frameLogE[i];
          const meanBefore = sumBefore / k;
          const meanAfter = sumAfter / (numFrames - k);
          const w = Math.sqrt((k * (numFrames - k)) / (numFrames * numFrames));
          const score = w * Math.abs(meanBefore - meanAfter);
          if (score > bestScore) {
            bestScore = score;
            kStar = k;
          }
        }
      }

      const outWav = new Float32Array(numSamples);
      const winSum = new Float32Array(numSamples);
      const baseSub = isAec ? 0.45 : (isMulti ? 0.30 : 0.35);

      for (let t = 0; t < numFrames; t++) {
        const mag = stftMag[t];
        const lag1 = stftMag[Math.max(0, t - 1)];
        const lag2 = stftMag[Math.max(0, t - 2)];
        const lag3 = stftMag[Math.max(0, t - 3)];
        const lag4 = stftMag[Math.max(0, t - 4)];
        const tailGate = charCount > 0 ? (0.3 + 0.7 * rateWeight) / (1.0 + Math.exp(-(t - kStar) / 2.0)) : 0.0;

        // Character-level phonetic band weight at relative position t / numFrames
        let lowBandWeight = 1.0;
        let highBandWeight = 1.0;
        if (charCount > 0) {
          const charIdx = Math.min(charCount - 1, Math.floor((t / Math.max(1, numFrames)) * charCount));
          const ch = cleanText[charIdx].toLowerCase();
          if ("aeiouy".includes(ch)) {
            lowBandWeight = 1.15;
            highBandWeight = 0.90;
          } else if ("szfvxjc".includes(ch)) {
            lowBandWeight = 0.85;
            highBandWeight = 1.25;
          } else if (ch === " " || ch === "," || ch === ".") {
            lowBandWeight = 0.70;
            highBandWeight = 0.70;
          }
        }

        const re = stftRe[t];
        const im = stftIm[t];
        for (let k = 0; k < numBins; k++) {
          const freqRatio = k / numBins;
          const phoneticWeight = freqRatio < 0.25 ? lowBandWeight : highBandWeight;
          const reverbTail = 0.40 * lag1[k] + 0.30 * lag2[k] + 0.20 * lag3[k] + 0.10 * lag4[k];
          const overlapSub = Math.max(1e-3, mag[k] - baseSub * phoneticWeight * reverbTail);
          const targetMag = (1.0 - tailGate) * overlapSub + tailGate * (0.04 * mag[k]);
          const gain = Math.min(1.0, Math.max(0.02, targetMag / Math.max(mag[k], 1e-4)));
          re[k] *= gain;
          im[k] *= gain;
          if (k > 0 && k < numBins - 1) {
            re[fftSize - k] = re[k];
            im[fftSize - k] = -im[k];
          }
        }

        fftRadix2(re, im, true);
        const offset = t * frameStep;
        for (let i = 0; i < frameLen; i++) {
          outWav[offset + i] += re[i] * hann[i];
          winSum[offset + i] += hann[i] * hann[i];
        }
      }

      for (let i = 0; i < numSamples; i++) {
        if (winSum[i] > 1e-6) outWav[i] /= winSum[i];
      }
      return outWav;
    }

    // Encode Float32Array to 16-bit PCM WAV Blob
    function encodeWavBlob(samples, sampleRate = 24000) {
      const buffer = new ArrayBuffer(44 + samples.length * 2);
      const view = new DataView(buffer);
      const writeStr = (offset, str) => {
        for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
      };
      writeStr(0, "RIFF");
      view.setUint32(4, 36 + samples.length * 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, samples.length * 2, true);
      let offset = 44;
      for (let i = 0; i < samples.length; i++, offset += 2) {
        const s = Math.max(-1, Math.min(1, samples[i]));
        view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
      }
      return new Blob([buffer], { type: "audio/wav" });
    }

    async function ensureAsrLoaded() {
      if (!asrTranscriber) {
        setStatus("Loading OpenAI Whisper ASR model (Xenova/whisper-base.en) in browser...");
        asrTranscriber = await pipeline("automatic-speech-recognition", "Xenova/whisper-base.en");
      }
      return asrTranscriber;
    }

    async function runPipeline() {
      try {
        runBtn.disabled = true;
        const ttsText = ttsTextInput.value.trim();
        const selectedModel = modelSelect.value;

        const asr = await ensureAsrLoaded();

        // 1. Decode uploaded/selected mixture audio for ASR (16 kHz) and TEC (24 kHz)
        setStatus("Step 1/3: Running ASR on user uploaded audio file (Before TEC)...");
        const inputSource = currentAudioSource.type === "upload"
          ? currentAudioSource.file
          : currentAudioSource.blobUrl;

        const inputAudio16k = await decodeAudioAtRate(inputSource, 16000);
        const inputAudio24k = await decodeAudioAtRate(inputSource, 24000);

        const beforeOut = await asr(inputAudio16k);
        const asrBeforeText = (beforeOut && beforeOut.text ? beforeOut.text.trim() : "(no speech recognized)");
        asrBeforeBox.textContent = asrBeforeText;

        // 2. Run Textual Echo Cancellation (TEC)
        setStatus("Step 2/3: Running Textual Echo Cancellation (TEC) with interfering TTS text...");
        let enhancedAudio16k;
        let enhancedBlobUrl;
        let execModeLabel;

        const builtinEx = currentAudioSource.type === "builtin" ? BUILTIN_EXAMPLES[currentAudioSource.index] : null;
        if (
          builtinEx &&
          ttsText.toLowerCase() === builtinEx.ttsText.toLowerCase()
        ) {
          // Use exact pretrained Lingvo checkpoint output for the selected model
          const tecUrl = (builtinEx.outputs && builtinEx.outputs[selectedModel]) || builtinEx.tecUrl;
          enhancedBlobUrl = tecUrl;
          enhancedAudio16k = await decodeAudioAtRate(tecUrl, 16000);
          execModeLabel = `Precomputed Lingvo Checkpoint (<code>wq2012/${selectedModel}</code>)`;
        } else {
          const enhanced24k = runBrowserTecEnhancement(inputAudio24k, ttsText);
          const wavBlob = encodeWavBlob(enhanced24k, 24000);
          enhancedBlobUrl = URL.createObjectURL(wavBlob);
          enhancedAudio16k = await decodeAudioAtRate(wavBlob, 16000);
          execModeLabel = `In-Browser Text-Conditioned Spectral Canceller (<code>${selectedModel}</code>)`;
        }
        outputAudioPlayer.src = enhancedBlobUrl;

        // 3. Run ASR on Textual Echo Cancelled audio
        setStatus("Step 3/3: Running ASR on Textual Echo Cancelled audio file (After TEC)...");
        const afterOut = await asr(enhancedAudio16k);
        const asrAfterText = (afterOut && afterOut.text ? afterOut.text.trim() : "(no speech recognized)");
        asrAfterBox.textContent = asrAfterText;

        // 4. Update comparison summary table
        const textBytes = new TextEncoder().encode(ttsText).length;
        const audioBytes = inputAudio24k.length * 2;
        const sidePayloadDesc = selectedModel === "aec_single_interfering"
          ? `<code>${(audioBytes / 1000).toFixed(1)} KB</code> reference audio`
          : `<code>${textBytes} B</code> (<code>${(textBytes / 1000).toFixed(3)} KB</code> text vs. <code>${(audioBytes / 1000).toFixed(1)} KB</code> audio)`;
        summaryTableBody.innerHTML = `
          <tr>
            <td><b>1. Original Uploaded Audio (No Echo Cancellation)</b></td>
            <td>Microphone Mixture (User Speech + TTS Echo)</td>
            <td><code>0 B</code></td>
            <td><code>${asrBeforeText}</code></td>
          </tr>
          <tr>
            <td><b>2. Echo Cancellation (${selectedModel})</b></td>
            <td>${execModeLabel}</td>
            <td>${sidePayloadDesc}</td>
            <td><b><code>${asrAfterText}</code></b></td>
          </tr>
        `;
        setStatus(`Completed (${execModeLabel.replace(/<[^>]*>/g, "")})! Compare the ASR transcripts and listen to the enhanced audio above.`, true);
      } catch (err) {
        console.error(err);
        setStatus("Error: " + (err && err.message ? err.message : String(err)), true);
      } finally {
        runBtn.disabled = false;
      }
    }

    runBtn.addEventListener("click", runPipeline);
    modelSelect.addEventListener("change", () => {
      if (currentAudioSource.type === "builtin") {
        runPipeline();
      }
    });

    document.querySelectorAll(".example-row").forEach((row) => {
      row.addEventListener("click", () => {
        const idx = parseInt(row.getAttribute("data-idx"), 10);
        const ex = BUILTIN_EXAMPLES[idx];
        currentAudioSource = { type: "builtin", index: idx, blobUrl: ex.mixedUrl };
        audioFileInput.value = "";
        inputAudioPlayer.src = ex.mixedUrl;
        ttsTextInput.value = ex.ttsText;
        runPipeline();
      });
    });
  </script>
</body>
</html>