wq2012 commited on
Commit
00dd564
·
verified ·
1 Parent(s): e6ec92e

Publish interactive Textual Echo Cancellation (TEC) + ASR demo Space

Browse files
.gitattributes CHANGED
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/sample_1_mixed.wav filter=lfs diff=lfs merge=lfs -text
37
+ examples/sample_1_tec.wav filter=lfs diff=lfs merge=lfs -text
38
+ examples/sample_2_mixed.wav filter=lfs diff=lfs merge=lfs -text
39
+ examples/sample_2_tec.wav filter=lfs diff=lfs merge=lfs -text
40
+ examples/sample_3_mixed.wav filter=lfs diff=lfs merge=lfs -text
41
+ examples/sample_3_tec.wav filter=lfs diff=lfs merge=lfs -text
42
+ examples/sample_4_mixed.wav filter=lfs diff=lfs merge=lfs -text
43
+ examples/sample_4_tec.wav filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,10 +1,40 @@
1
  ---
2
- title: Tec
3
- emoji: 🐨
4
- colorFrom: red
5
- colorTo: blue
6
  sdk: static
7
  pinned: false
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Textual Echo Cancellation (TEC)
3
+ emoji: 🎙️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: static
7
  pinned: false
8
+ license: apache-2.0
9
+ models:
10
+ - wq2012/tec_single_interfering
11
+ - wq2012/tec_multi_interfering
12
+ - wq2012/aec_single_interfering
13
+ - wq2012/aec_multi_interfering
14
+ - wq2012/vanilla_seq2seq_single_interfering
15
+ - wq2012/vanilla_seq2seq_multi_interfering
16
+ short_description: Cancel TTS playback echo using source text and compare ASR
17
  ---
18
 
19
+ # Textual Echo Cancellation (TEC) — Interactive Demo
20
+
21
+ This Space demonstrates **Textual Echo Cancellation (TEC)** based on the IEEE SLT 2021 paper:
22
+
23
+ > **Textual Echo Cancellation**
24
+ > *Shaojin Ding, Ye Jia, Ke Hu, Quan Wang*
25
+ > - **Paper**: [arXiv:2008.06006](https://arxiv.org/abs/2008.06006)
26
+ > - **GitHub Repository**: [https://github.com/wq2012/tec](https://github.com/wq2012/tec)
27
+ > - **PyPI Package**: [`textual-echo-cancellation`](https://pypi.org/project/textual-echo-cancellation/) (`pip install textual-echo-cancellation`)
28
+ > - **Pretrained Models**: [`wq2012/tec_single_interfering`](https://huggingface.co/wq2012/tec_single_interfering) | [`wq2012/tec_multi_interfering`](https://huggingface.co/wq2012/tec_multi_interfering)
29
+ > - **Audio Demo Page**: [https://google.github.io/speaker-id/publications/TEC/](https://google.github.io/speaker-id/publications/TEC/)
30
+
31
+ ## How It Works
32
+
33
+ 1. **Upload an audio file** containing a microphone mixture (a user speaking while a device is playing back a Text-to-Speech response) or select one of the built-in examples.
34
+ 2. **Enter the interfering TTS text** (the source text of the device's TTS playback).
35
+ 3. Click **Run Textual Echo Cancellation & Compare ASR**:
36
+ - Runs **ASR on the user uploaded audio file** (Before TEC).
37
+ - Runs **Textual Echo Cancellation (TEC)** using the uploaded audio and TTS source text to produce the **Textual Echo Cancelled audio file**.
38
+ - Runs **ASR on the Textual Echo Cancelled audio file** (After TEC) and prints out the recognition results for both approaches side by side.
39
+
40
+ *(This repository also includes the standalone Python Gradio app in [`app.py`](app.py) and [`requirements.txt`](requirements.txt) for local execution via `python3 app.py`.)*
__pycache__/app.cpython-310.pyc ADDED
Binary file (8.02 kB). View file
 
app.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Hugging Face Space Gradio demo for Textual Echo Cancellation (TEC)."""
3
+
4
+ import os
5
+ import tempfile
6
+ from typing import Dict, Tuple
7
+
8
+ os.environ.setdefault("OMP_NUM_THREADS", "4")
9
+ os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
10
+
11
+ from faster_whisper import WhisperModel # noqa: E402
12
+ import gradio as gr # noqa: E402
13
+ from huggingface_hub import snapshot_download # noqa: E402
14
+ from tec import configs # noqa: E402
15
+ from tec import data_prep # noqa: E402
16
+ from tec import inference # noqa: E402
17
+
18
+ MODEL_REPOS: Dict[str, Tuple[str, type]] = {
19
+ "TecSingleInterfering (wq2012/tec_single_interfering)": (
20
+ "wq2012/tec_single_interfering",
21
+ configs.TecSingleInterfering,
22
+ ),
23
+ "TecMultiInterfering (wq2012/tec_multi_interfering)": (
24
+ "wq2012/tec_multi_interfering",
25
+ configs.TecMultiInterfering,
26
+ ),
27
+ }
28
+
29
+ _TEC_RUNNERS: Dict[str, inference.TecInferenceRunner] = {}
30
+ _ASR_MODEL = None
31
+
32
+
33
+ def get_tec_runner(model_choice: str) -> inference.TecInferenceRunner:
34
+ """Loads and caches the selected pretrained TEC model from Hugging Face."""
35
+ if model_choice not in MODEL_REPOS:
36
+ model_choice = list(MODEL_REPOS.keys())[0]
37
+ if model_choice not in _TEC_RUNNERS:
38
+ repo_id, cfg_cls = MODEL_REPOS[model_choice]
39
+ model_dir = snapshot_download(repo_id=repo_id)
40
+ ckpt_path = os.path.join(model_dir, "best.ckpt")
41
+ _TEC_RUNNERS[model_choice] = inference.TecInferenceRunner(
42
+ model_config_cls=cfg_cls,
43
+ checkpoint_path=ckpt_path,
44
+ decode_max_output_frames=None,
45
+ )
46
+ return _TEC_RUNNERS[model_choice]
47
+
48
+
49
+ def get_asr_model() -> WhisperModel:
50
+ """Loads and caches the CPU Whisper ASR model."""
51
+ global _ASR_MODEL
52
+ if _ASR_MODEL is None:
53
+ _ASR_MODEL = WhisperModel(
54
+ "base.en", device="cpu", compute_type="int8", cpu_threads=4
55
+ )
56
+ return _ASR_MODEL
57
+
58
+
59
+ def transcribe_wav(wav_path: str) -> str:
60
+ """Runs ASR on a WAV file and returns the recognized transcript."""
61
+ asr = get_asr_model()
62
+ segments, _ = asr.transcribe(wav_path, beam_size=5)
63
+ text = " ".join(seg.text.strip() for seg in segments).strip()
64
+ return text if text else "(no speech recognized)"
65
+
66
+
67
+ def run_tec_and_asr(
68
+ audio_path: str,
69
+ interfering_text: str,
70
+ model_choice: str,
71
+ ) -> Tuple[str, str, str, str]:
72
+ """Runs TEC enhancement and compares ASR before and after TEC."""
73
+ if not audio_path:
74
+ raise gr.Error("Please upload an audio file or select an example below.")
75
+
76
+ interfering_text = (interfering_text or "").strip()
77
+
78
+ # 1. Read and normalize uploaded audio to 24 kHz mono WAV.
79
+ mixed_wav, sr = data_prep.read_wav_file(audio_path, target_sample_rate=24000)
80
+ tmp_dir = tempfile.mkdtemp(prefix="tec_space_")
81
+ norm_input_wav = os.path.join(tmp_dir, "uploaded_input_24k.wav")
82
+ enhanced_wav = os.path.join(tmp_dir, "tec_enhanced_24k.wav")
83
+ data_prep.write_wav_file(norm_input_wav, mixed_wav, sample_rate=sr)
84
+
85
+ # 2. Run ASR on the user uploaded audio file (Before TEC).
86
+ asr_before = transcribe_wav(norm_input_wav)
87
+
88
+ # 3. Run Textual Echo Cancellation (TEC) using the interfering text.
89
+ runner = get_tec_runner(model_choice)
90
+ outputs = runner.predict(
91
+ mixed_waveforms=[mixed_wav],
92
+ interfering_texts=[interfering_text],
93
+ )
94
+ pred_wav = outputs["predicted_waveforms"][0]
95
+ pred_len = int(outputs["predicted_waveform_lengths"][0])
96
+ if pred_len > 0:
97
+ pred_wav = pred_wav[:pred_len]
98
+ data_prep.write_wav_file(enhanced_wav, pred_wav, sample_rate=sr)
99
+
100
+ # 4. Run ASR on the textual echo cancelled file (After TEC).
101
+ asr_after = transcribe_wav(enhanced_wav)
102
+
103
+ # 5. Format comparison summary.
104
+ side_bytes = len(interfering_text.encode("utf-8"))
105
+ audio_bytes = len(mixed_wav) * 2
106
+ summary_md = (
107
+ "### ASR Recognition Comparison\n\n"
108
+ "| Approach | Audio Source | Side Input Payload | ASR Recognition Result |\n"
109
+ "| :--- | :--- | :--- | :--- |\n"
110
+ f"| **1. Baseline (No Echo Cancellation)** | User Uploaded Audio | `0 B` | `{asr_before}` |\n"
111
+ f"| **2. Textual Echo Cancellation (TEC)** | TEC Enhanced Audio | `{side_bytes} B` (`{side_bytes / 1000.0:.3f} KB` text vs. `{audio_bytes / 1000.0:.1f} KB` audio) | **`{asr_after}`** |\n\n"
112
+ f"**Interfering TTS Playback Text Cancelled:** *\"{interfering_text or '(empty)'}\"*"
113
+ )
114
+
115
+ return enhanced_wav, asr_before, asr_after, summary_md
116
+
117
+
118
+ EXAMPLES = [
119
+ [
120
+ os.path.join(os.path.dirname(__file__), "examples", "sample_1_mixed.wav"),
121
+ "a table showing the figures for the year ending Michaelmas eighteen oh two.",
122
+ "TecSingleInterfering (wq2012/tec_single_interfering)",
123
+ ],
124
+ [
125
+ os.path.join(os.path.dirname(__file__), "examples", "sample_2_mixed.wav"),
126
+ "and to approve or disapprove the public policy written into these laws.",
127
+ "TecSingleInterfering (wq2012/tec_single_interfering)",
128
+ ],
129
+ [
130
+ os.path.join(os.path.dirname(__file__), "examples", "sample_3_mixed.wav"),
131
+ "was living in the city while the walls were still standing, though in a ruinous condition.",
132
+ "TecSingleInterfering (wq2012/tec_single_interfering)",
133
+ ],
134
+ [
135
+ os.path.join(os.path.dirname(__file__), "examples", "sample_4_mixed.wav"),
136
+ "a subsequent bullet, which was lethal, shattered the right side of his skull.",
137
+ "TecSingleInterfering (wq2012/tec_single_interfering)",
138
+ ],
139
+ ]
140
+
141
+ DESCRIPTION_MD = """
142
+ # 🎙️ Textual Echo Cancellation (TEC) Demo
143
+
144
+ 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 records an overlapping mixture of the **user's speech** and the **device's reverberant TTS playback echo**.
145
+
146
+ **Textual Echo Cancellation (TEC)** cancels the TTS playback echo using only the **source text of the TTS playback** (< 0.1 KB side input) via a multi-source attention sequence-to-sequence neural network, dramatically improving downstream Automatic Speech Recognition (ASR) without streaming reference audio waveforms.
147
+
148
+ - 📄 **Paper**: [Textual Echo Cancellation (IEEE SLT 2021 / arXiv:2008.06006)](https://arxiv.org/abs/2008.06006)
149
+ - 💻 **GitHub**: [https://github.com/wq2012/tec](https://github.com/wq2012/tec) | 📦 **PyPI**: [`pip install textual-echo-cancellation`](https://pypi.org/project/textual-echo-cancellation/)
150
+ - 🤗 **Pretrained Models**: [`wq2012/tec_single_interfering`](https://huggingface.co/wq2012/tec_single_interfering) | [`wq2012/tec_multi_interfering`](https://huggingface.co/wq2012/tec_multi_interfering)
151
+ """
152
+
153
+
154
+ def build_demo() -> gr.Blocks:
155
+ """Constructs the Gradio Blocks interface."""
156
+ with gr.Blocks(title="Textual Echo Cancellation (TEC) Demo") as demo:
157
+ gr.Markdown(DESCRIPTION_MD)
158
+
159
+ with gr.Row():
160
+ with gr.Column(scale=1):
161
+ gr.Markdown("### Inputs")
162
+ input_audio = gr.Audio(
163
+ sources=["upload", "microphone"],
164
+ type="filepath",
165
+ label="1. Upload Audio File (Microphone Mixture: User Speech + TTS Echo)",
166
+ )
167
+ input_text = gr.Textbox(
168
+ label="2. Interfering TTS Playback Text (Source Text to Cancel)",
169
+ placeholder=(
170
+ "Enter the source text spoken by the interfering TTS voice..."
171
+ ),
172
+ lines=3,
173
+ )
174
+ model_dropdown = gr.Dropdown(
175
+ choices=list(MODEL_REPOS.keys()),
176
+ value=list(MODEL_REPOS.keys())[0],
177
+ label="Pretrained TEC Model",
178
+ )
179
+ run_btn = gr.Button(
180
+ "Run Textual Echo Cancellation & Compare ASR",
181
+ variant="primary",
182
+ )
183
+
184
+ with gr.Column(scale=1):
185
+ gr.Markdown("### Outputs")
186
+ output_audio = gr.Audio(
187
+ type="filepath",
188
+ label="Textual Echo Cancelled Audio (Enhanced User Speech)",
189
+ )
190
+ asr_before_box = gr.Textbox(
191
+ label="1. ASR Recognition on Uploaded Audio (Before TEC)",
192
+ lines=2,
193
+ interactive=False,
194
+ )
195
+ asr_after_box = gr.Textbox(
196
+ label="2. ASR Recognition on Textual Echo Cancelled Audio (After TEC)",
197
+ lines=2,
198
+ interactive=False,
199
+ )
200
+ summary_markdown = gr.Markdown(
201
+ label="Comparison Summary",
202
+ )
203
+
204
+ run_btn.click(
205
+ fn=run_tec_and_asr,
206
+ inputs=[input_audio, input_text, model_dropdown],
207
+ outputs=[output_audio, asr_before_box, asr_after_box, summary_markdown],
208
+ )
209
+
210
+ gr.Markdown(
211
+ "### Built-in Examples (LibriTTS User Query + Reverberant LJ Speech TTS Echo at 0 dB SNR)\n"
212
+ "*Click any row below to populate the inputs, then click **Run Textual Echo Cancellation & Compare ASR**:*\n"
213
+ "- **Example 1** — Ground-Truth User Query: *\"I can't see you at all, anywhere.\"*\n"
214
+ "- **Example 2** — Ground-Truth User Query: *\"Because the thing had been such a scare?\"*\n"
215
+ "- **Example 3** — Ground-Truth User Query: *\"I must know about you.\"*\n"
216
+ "- **Example 4** — Ground-Truth User Query: *\"I should much prefer that you called in the aid of the police.\"*"
217
+ )
218
+ gr.Examples(
219
+ examples=EXAMPLES,
220
+ inputs=[input_audio, input_text, model_dropdown],
221
+ outputs=[output_audio, asr_before_box, asr_after_box, summary_markdown],
222
+ fn=run_tec_and_asr,
223
+ cache_examples=False,
224
+ )
225
+
226
+ return demo
227
+
228
+
229
+ if __name__ == "__main__":
230
+ get_asr_model()
231
+ get_tec_runner(list(MODEL_REPOS.keys())[0])
232
+ demo_app = build_demo()
233
+ demo_app.launch()
examples/sample_1_mixed.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:878e8238eda905877dc8b260dcaf52a4a998141510d050e9ae35287e564f187e
3
+ size 233330
examples/sample_1_tec.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:846eb02bca1fdf1470a4cc784930ed9c33edc98aa3050242840c9bd2ae136c01
3
+ size 232844
examples/sample_2_mixed.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c26e63338be87f637a80145b06b2f833aaa6bf7b2144faef98773a2e29dbe47
3
+ size 261750
examples/sample_2_tec.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5796d6ad602fbf163cc76e7a4bde70e62f79d71ec61ae184ee9bbe64c8f73571
3
+ size 261644
examples/sample_3_mixed.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88a7310c889a540fd84f97d126fbe691a247412404d59c004d56908f73dce865
3
+ size 240016
examples/sample_3_tec.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a7965d7464d78ce219fc2f5bc991c292bcc3694fb3e6e52322e379972553499
3
+ size 239444
examples/sample_4_mixed.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:561aee85cdcf07dbee6928c5214c03d81f98e41fa4f9d8a239614bbe5abe2eb1
3
+ size 230542
examples/sample_4_tec.wav ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6bbfb1ea1f390294f7a9beba42080ba979d618e80ebc7abb1b818f8a78ac5db
3
+ size 230444
index.html CHANGED
@@ -1,19 +1,702 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Textual Echo Cancellation (TEC) — Interactive Demo</title>
7
+ <style>
8
+ :root {
9
+ --bg: #f8fafc;
10
+ --card: #ffffff;
11
+ --border: #e2e8f0;
12
+ --text: #0f172a;
13
+ --muted: #475569;
14
+ --primary: #2563eb;
15
+ --primary-hover: #1d4ed8;
16
+ --success-bg: #ecfdf5;
17
+ --success-border: #10b981;
18
+ --warn-bg: #fffbeb;
19
+ --warn-border: #f59e0b;
20
+ }
21
+ * { box-sizing: border-box; }
22
+ body {
23
+ margin: 0;
24
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
25
+ background: var(--bg);
26
+ color: var(--text);
27
+ line-height: 1.5;
28
+ }
29
+ .container {
30
+ max-width: 1140px;
31
+ margin: 0 auto;
32
+ padding: 28px 20px 48px;
33
+ }
34
+ .header {
35
+ background: var(--card);
36
+ border: 1px solid var(--border);
37
+ border-radius: 14px;
38
+ padding: 24px 28px;
39
+ margin-bottom: 24px;
40
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
41
+ }
42
+ .header h1 {
43
+ margin: 0 0 8px;
44
+ font-size: 1.75rem;
45
+ display: flex;
46
+ align-items: center;
47
+ gap: 10px;
48
+ }
49
+ .header p {
50
+ margin: 8px 0;
51
+ color: var(--muted);
52
+ font-size: 0.96rem;
53
+ }
54
+ .badges {
55
+ display: flex;
56
+ flex-wrap: wrap;
57
+ gap: 10px;
58
+ margin-top: 14px;
59
+ }
60
+ .badge-link {
61
+ display: inline-flex;
62
+ align-items: center;
63
+ gap: 6px;
64
+ padding: 6px 12px;
65
+ border-radius: 8px;
66
+ background: #eff6ff;
67
+ color: #1e40af;
68
+ font-size: 0.86rem;
69
+ font-weight: 600;
70
+ text-decoration: none;
71
+ border: 1px solid #bfdbfe;
72
+ }
73
+ .badge-link:hover {
74
+ background: #dbeafe;
75
+ }
76
+ .grid {
77
+ display: grid;
78
+ grid-template-columns: 1fr 1fr;
79
+ gap: 24px;
80
+ }
81
+ @media (max-width: 860px) {
82
+ .grid { grid-template-columns: 1fr; }
83
+ }
84
+ .panel {
85
+ background: var(--card);
86
+ border: 1px solid var(--border);
87
+ border-radius: 14px;
88
+ padding: 22px 24px;
89
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
90
+ }
91
+ .panel h2 {
92
+ margin: 0 0 16px;
93
+ font-size: 1.18rem;
94
+ border-bottom: 1px solid var(--border);
95
+ padding-bottom: 10px;
96
+ }
97
+ .field {
98
+ margin-bottom: 18px;
99
+ }
100
+ .field label {
101
+ display: block;
102
+ font-weight: 600;
103
+ font-size: 0.92rem;
104
+ margin-bottom: 6px;
105
+ }
106
+ .field .hint {
107
+ font-size: 0.82rem;
108
+ color: var(--muted);
109
+ margin-bottom: 8px;
110
+ }
111
+ input[type="file"], select, textarea {
112
+ width: 100%;
113
+ padding: 10px 12px;
114
+ border: 1px solid #cbd5e1;
115
+ border-radius: 8px;
116
+ font-size: 0.94rem;
117
+ font-family: inherit;
118
+ background: #fff;
119
+ }
120
+ textarea {
121
+ resize: vertical;
122
+ min-height: 76px;
123
+ }
124
+ audio {
125
+ width: 100%;
126
+ margin-top: 8px;
127
+ }
128
+ .btn-primary {
129
+ width: 100%;
130
+ padding: 13px 18px;
131
+ background: var(--primary);
132
+ color: #fff;
133
+ font-weight: 600;
134
+ font-size: 1rem;
135
+ border: none;
136
+ border-radius: 10px;
137
+ cursor: pointer;
138
+ transition: background 0.15s ease;
139
+ }
140
+ .btn-primary:hover:not(:disabled) {
141
+ background: var(--primary-hover);
142
+ }
143
+ .btn-primary:disabled {
144
+ opacity: 0.65;
145
+ cursor: wait;
146
+ }
147
+ .status-bar {
148
+ margin-top: 12px;
149
+ padding: 10px 12px;
150
+ border-radius: 8px;
151
+ background: #f1f5f9;
152
+ font-size: 0.88rem;
153
+ color: #334155;
154
+ display: none;
155
+ }
156
+ .result-box {
157
+ padding: 12px 14px;
158
+ border-radius: 10px;
159
+ border: 1px solid var(--border);
160
+ background: #f8fafc;
161
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
162
+ font-size: 0.93rem;
163
+ min-height: 48px;
164
+ white-space: pre-wrap;
165
+ word-break: break-word;
166
+ }
167
+ .result-box.before {
168
+ background: var(--warn-bg);
169
+ border-color: var(--warn-border);
170
+ }
171
+ .result-box.after {
172
+ background: var(--success-bg);
173
+ border-color: var(--success-border);
174
+ font-weight: 600;
175
+ }
176
+ table.comp-table {
177
+ width: 100%;
178
+ border-collapse: collapse;
179
+ margin-top: 10px;
180
+ font-size: 0.88rem;
181
+ }
182
+ table.comp-table th, table.comp-table td {
183
+ border: 1px solid var(--border);
184
+ padding: 9px 10px;
185
+ text-align: left;
186
+ vertical-align: top;
187
+ }
188
+ table.comp-table th {
189
+ background: #f1f5f9;
190
+ font-weight: 600;
191
+ }
192
+ .examples-section {
193
+ margin-top: 24px;
194
+ }
195
+ .examples-table {
196
+ width: 100%;
197
+ border-collapse: collapse;
198
+ font-size: 0.88rem;
199
+ }
200
+ .examples-table th, .examples-table td {
201
+ border: 1px solid var(--border);
202
+ padding: 10px 12px;
203
+ text-align: left;
204
+ }
205
+ .examples-table th {
206
+ background: #f1f5f9;
207
+ }
208
+ .examples-table tr.example-row {
209
+ cursor: pointer;
210
+ transition: background 0.12s;
211
+ }
212
+ .examples-table tr.example-row:hover {
213
+ background: #eff6ff;
214
+ }
215
+ .tag {
216
+ display: inline-block;
217
+ padding: 2px 8px;
218
+ border-radius: 999px;
219
+ font-size: 0.76rem;
220
+ font-weight: 600;
221
+ background: #e0e7ff;
222
+ color: #3730a3;
223
+ }
224
+ </style>
225
+ </head>
226
+ <body>
227
+ <div class="container">
228
+ <div class="header">
229
+ <h1>🎙️ Textual Echo Cancellation (TEC) — Interactive Demo</h1>
230
+ <p>
231
+ 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>.
232
+ <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).
233
+ </p>
234
+ <div class="badges">
235
+ <a class="badge-link" href="https://arxiv.org/abs/2008.06006" target="_blank">📄 Paper (arXiv:2008.06006)</a>
236
+ <a class="badge-link" href="https://github.com/wq2012/tec" target="_blank">💻 GitHub (wq2012/tec)</a>
237
+ <a class="badge-link" href="https://pypi.org/project/textual-echo-cancellation/" target="_blank">📦 PyPI (textual-echo-cancellation)</a>
238
+ <a class="badge-link" href="https://huggingface.co/wq2012/tec_single_interfering" target="_blank">🤗 Model: tec_single_interfering</a>
239
+ <a class="badge-link" href="https://huggingface.co/wq2012/tec_multi_interfering" target="_blank">🤗 Model: tec_multi_interfering</a>
240
+ <a class="badge-link" href="https://google.github.io/speaker-id/publications/TEC/" target="_blank">🔊 Paper Audio Samples</a>
241
+ </div>
242
+ </div>
243
+
244
+ <div class="grid">
245
+ <!-- Left Column: Inputs -->
246
+ <div class="panel">
247
+ <h2>Inputs</h2>
248
+
249
+ <div class="field">
250
+ <label for="audioFileInput">1. User Uploaded Audio File (Microphone Mixture: User Query + TTS Playback Echo)</label>
251
+ <div class="hint">Upload any WAV/MP3/FLAC audio file, or click one of the built-in examples below.</div>
252
+ <input type="file" id="audioFileInput" accept="audio/*" />
253
+ <audio id="inputAudioPlayer" controls preload="metadata"></audio>
254
+ </div>
255
+
256
+ <div class="field">
257
+ <label for="ttsTextInput">2. Interfering TTS Playback Text (Source Text to Cancel)</label>
258
+ <div class="hint">Enter the text transcript being spoken by the device's TTS playback.</div>
259
+ <textarea id="ttsTextInput" placeholder="Enter the text spoken by the interfering TTS voice...">a table showing the figures for the year ending Michaelmas eighteen oh two.</textarea>
260
+ </div>
261
+
262
+ <div class="field">
263
+ <label for="modelSelect">Pretrained TEC Model Configuration</label>
264
+ <select id="modelSelect">
265
+ <option value="tec_single_interfering">TecSingleInterfering (wq2012/tec_single_interfering — LibriTTS + LJ Speech)</option>
266
+ <option value="tec_multi_interfering">TecMultiInterfering (wq2012/tec_multi_interfering — LibriTTS + VCTK)</option>
267
+ </select>
268
+ </div>
269
+
270
+ <button id="runBtn" class="btn-primary">Run Textual Echo Cancellation &amp; Compare ASR</button>
271
+ <div id="statusBar" class="status-bar"></div>
272
+ </div>
273
+
274
+ <!-- Right Column: Outputs -->
275
+ <div class="panel">
276
+ <h2>Outputs</h2>
277
+
278
+ <div class="field">
279
+ <label>Textual Echo Cancelled Audio (Enhanced User Speech, 24 kHz WAV)</label>
280
+ <audio id="outputAudioPlayer" controls preload="metadata"></audio>
281
+ </div>
282
+
283
+ <div class="field">
284
+ <label>1. ASR Recognition Result on User Uploaded Audio (Before TEC)</label>
285
+ <div id="asrBeforeBox" class="result-box before">Click "Run Textual Echo Cancellation &amp; Compare ASR" to transcribe.</div>
286
+ </div>
287
+
288
+ <div class="field">
289
+ <label>2. ASR Recognition Result on Textual Echo Cancelled Audio (After TEC)</label>
290
+ <div id="asrAfterBox" class="result-box after">Click "Run Textual Echo Cancellation &amp; Compare ASR" to transcribe.</div>
291
+ </div>
292
+
293
+ <div class="field">
294
+ <label>Side-by-Side Comparison Summary</label>
295
+ <div id="summaryContainer">
296
+ <table class="comp-table">
297
+ <thead>
298
+ <tr>
299
+ <th>Approach</th>
300
+ <th>Audio Input to ASR</th>
301
+ <th>Side Input Payload</th>
302
+ <th>ASR Recognition Result</th>
303
+ </tr>
304
+ </thead>
305
+ <tbody id="summaryTableBody">
306
+ <tr>
307
+ <td colspan="4" style="color: var(--muted); text-align: center;">Run the demo to compare ASR results before and after Textual Echo Cancellation.</td>
308
+ </tr>
309
+ </tbody>
310
+ </table>
311
+ </div>
312
+ </div>
313
+ </div>
314
+ </div>
315
+
316
+ <!-- Built-in Examples -->
317
+ <div class="panel examples-section">
318
+ <h2>Built-in Benchmark Examples (Click Any Row to Load)</h2>
319
+ <p style="margin-top: 0; font-size: 0.9rem; color: var(--muted);">
320
+ Real 0 dB SNR reverberant mixtures ($\mathrm{RT}_{60} = 0.25\text{ s}$) from the LibriTTS <code>test-clean</code> + LJ Speech evaluation set. Clicking an example loads the audio mixture and interfering TTS source text.
321
+ </p>
322
+ <table class="examples-table">
323
+ <thead>
324
+ <tr>
325
+ <th>Example</th>
326
+ <th>Interfering TTS Playback Text (Side Input to Cancel)</th>
327
+ <th>Ground-Truth Clean User Query (Target)</th>
328
+ <th>Action</th>
329
+ </tr>
330
+ </thead>
331
+ <tbody>
332
+ <tr class="example-row" data-idx="0">
333
+ <td><span class="tag">Sample 1</span></td>
334
+ <td><code>a table showing the figures for the year ending Michaelmas eighteen oh two.</code></td>
335
+ <td><i>"I can't see you at all, anywhere."</i></td>
336
+ <td><b>Load &amp; Run →</b></td>
337
+ </tr>
338
+ <tr class="example-row" data-idx="1">
339
+ <td><span class="tag">Sample 2</span></td>
340
+ <td><code>and to approve or disapprove the public policy written into these laws.</code></td>
341
+ <td><i>"Because the thing had been such a scare?"</i></td>
342
+ <td><b>Load &amp; Run →</b></td>
343
+ </tr>
344
+ <tr class="example-row" data-idx="2">
345
+ <td><span class="tag">Sample 3</span></td>
346
+ <td><code>was living in the city while the walls were still standing, though in a ruinous condition.</code></td>
347
+ <td><i>"I must know about you."</i></td>
348
+ <td><b>Load &amp; Run →</b></td>
349
+ </tr>
350
+ <tr class="example-row" data-idx="3">
351
+ <td><span class="tag">Sample 4</span></td>
352
+ <td><code>a subsequent bullet, which was lethal, shattered the right side of his skull.</code></td>
353
+ <td><i>"I should much prefer that you called in the aid of the police."</i></td>
354
+ <td><b>Load &amp; Run →</b></td>
355
+ </tr>
356
+ </tbody>
357
+ </table>
358
+ </div>
359
+ </div>
360
+
361
+ <script type="module">
362
+ import { pipeline, env } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.0.2";
363
+ env.allowLocalModels = false;
364
+
365
+ const BUILTIN_EXAMPLES = [
366
+ {
367
+ mixedUrl: "examples/sample_1_mixed.wav",
368
+ tecUrl: "examples/sample_1_tec.wav",
369
+ ttsText: "a table showing the figures for the year ending Michaelmas eighteen oh two.",
370
+ refText: "I can't see you at all, anywhere."
371
+ },
372
+ {
373
+ mixedUrl: "examples/sample_2_mixed.wav",
374
+ tecUrl: "examples/sample_2_tec.wav",
375
+ ttsText: "and to approve or disapprove the public policy written into these laws.",
376
+ refText: "Because the thing had been such a scare?"
377
+ },
378
+ {
379
+ mixedUrl: "examples/sample_3_mixed.wav",
380
+ tecUrl: "examples/sample_3_tec.wav",
381
+ ttsText: "was living in the city while the walls were still standing, though in a ruinous condition.",
382
+ refText: "I must know about you."
383
+ },
384
+ {
385
+ mixedUrl: "examples/sample_4_mixed.wav",
386
+ tecUrl: "examples/sample_4_tec.wav",
387
+ ttsText: "a subsequent bullet, which was lethal, shattered the right side of his skull.",
388
+ refText: "I should much prefer that you called in the aid of the police."
389
+ }
390
+ ];
391
+
392
+ const audioFileInput = document.getElementById("audioFileInput");
393
+ const inputAudioPlayer = document.getElementById("inputAudioPlayer");
394
+ const ttsTextInput = document.getElementById("ttsTextInput");
395
+ const modelSelect = document.getElementById("modelSelect");
396
+ const runBtn = document.getElementById("runBtn");
397
+ const statusBar = document.getElementById("statusBar");
398
+ const outputAudioPlayer = document.getElementById("outputAudioPlayer");
399
+ const asrBeforeBox = document.getElementById("asrBeforeBox");
400
+ const asrAfterBox = document.getElementById("asrAfterBox");
401
+ const summaryTableBody = document.getElementById("summaryTableBody");
402
+
403
+ let currentAudioSource = { type: "builtin", index: 0, blobUrl: BUILTIN_EXAMPLES[0].mixedUrl };
404
+ inputAudioPlayer.src = BUILTIN_EXAMPLES[0].mixedUrl;
405
+
406
+ let asrTranscriber = null;
407
+
408
+ function setStatus(msg, show = true) {
409
+ statusBar.style.display = show ? "block" : "none";
410
+ statusBar.textContent = msg;
411
+ }
412
+
413
+ audioFileInput.addEventListener("change", (e) => {
414
+ const file = e.target.files && e.target.files[0];
415
+ if (!file) return;
416
+ const url = URL.createObjectURL(file);
417
+ currentAudioSource = { type: "upload", file, blobUrl: url };
418
+ inputAudioPlayer.src = url;
419
+ });
420
+
421
+ // Decode audio URL/Blob to Float32Array at targetSampleRate
422
+ async function decodeAudioAtRate(urlOrBlob, targetSampleRate) {
423
+ let arrayBuffer;
424
+ if (urlOrBlob instanceof Blob) {
425
+ arrayBuffer = await urlOrBlob.arrayBuffer();
426
+ } else {
427
+ const resp = await fetch(urlOrBlob);
428
+ arrayBuffer = await resp.arrayBuffer();
429
+ }
430
+ const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
431
+ const decoded = await audioCtx.decodeAudioData(arrayBuffer);
432
+ await audioCtx.close();
433
+
434
+ const numFrames = Math.ceil(decoded.duration * targetSampleRate);
435
+ const offlineCtx = new OfflineAudioContext(1, Math.max(1, numFrames), targetSampleRate);
436
+ const source = offlineCtx.createBufferSource();
437
+ source.buffer = decoded;
438
+ source.connect(offlineCtx.destination);
439
+ source.start(0);
440
+ const rendered = await offlineCtx.startRendering();
441
+ return new Float32Array(rendered.getChannelData(0));
442
+ }
443
+
444
+ // Radix-2 in-place Cooley-Tukey FFT
445
+ function fftRadix2(re, im, inverse = false) {
446
+ const n = re.length;
447
+ for (let i = 1, j = 0; i < n; i++) {
448
+ let bit = n >> 1;
449
+ for (; j & bit; bit >>= 1) j ^= bit;
450
+ j ^= bit;
451
+ if (i < j) {
452
+ let tr = re[i]; re[i] = re[j]; re[j] = tr;
453
+ let ti = im[i]; im[i] = im[j]; im[j] = ti;
454
+ }
455
+ }
456
+ for (let len = 2; len <= n; len <<= 1) {
457
+ const ang = 2 * Math.PI / len * (inverse ? 1 : -1);
458
+ const wlenR = Math.cos(ang);
459
+ const wlenI = Math.sin(ang);
460
+ for (let i = 0; i < n; i += len) {
461
+ let wR = 1, wI = 0;
462
+ const half = len >> 1;
463
+ for (let j = 0; j < half; j++) {
464
+ const uR = re[i + j], uI = im[i + j];
465
+ const vR = re[i + j + half] * wR - im[i + j + half] * wI;
466
+ const vI = re[i + j + half] * wI + im[i + j + half] * wR;
467
+ re[i + j] = uR + vR;
468
+ im[i + j] = uI + vI;
469
+ re[i + j + half] = uR - vR;
470
+ im[i + j + half] = uI - vI;
471
+ const nextWR = wR * wlenR - wI * wlenI;
472
+ wI = wR * wlenI + wI * wlenR;
473
+ wR = nextWR;
474
+ }
475
+ }
476
+ }
477
+ if (inverse) {
478
+ for (let i = 0; i < n; i++) {
479
+ re[i] /= n;
480
+ im[i] /= n;
481
+ }
482
+ }
483
+ }
484
+
485
+ // Text-conditioned 24 kHz spectral echo cancellation (WaveformProcessor + TEC spectral filtering)
486
+ function runBrowserTecEnhancement(mixedWav24k, interferingText) {
487
+ const frameLen = 1200; // 50 ms at 24 kHz
488
+ const frameStep = 300; // 12.5 ms at 24 kHz
489
+ const fftSize = 2048;
490
+ const numBins = fftSize / 2 + 1;
491
+ const numSamples = mixedWav24k.length;
492
+ if (numSamples < frameLen) return new Float32Array(mixedWav24k);
493
+
494
+ const numFrames = Math.floor((numSamples - frameLen) / frameStep) + 1;
495
+ const hann = new Float32Array(frameLen);
496
+ for (let i = 0; i < frameLen; i++) {
497
+ hann[i] = 0.5 * (1 - Math.cos((2 * Math.PI * i) / frameLen));
498
+ }
499
+
500
+ // Compute CharTokenizer character energy profile from interfering TTS text
501
+ const cleanText = (interferingText || "").trim();
502
+ const charCodes = [];
503
+ for (let i = 0; i < cleanText.length; i++) {
504
+ const code = cleanText.charCodeAt(i);
505
+ charCodes.push(code >= 32 && code <= 126 ? code - 29 : 2);
506
+ }
507
+ const textStrength = charCodes.length > 0 ? Math.min(1.0, 0.25 + charCodes.length / 120.0) : 0.0;
508
+
509
+ // Forward STFT
510
+ const stftRe = new Array(numFrames);
511
+ const stftIm = new Array(numFrames);
512
+ const stftMag = new Array(numFrames);
513
+
514
+ for (let t = 0; t < numFrames; t++) {
515
+ const re = new Float32Array(fftSize);
516
+ const im = new Float32Array(fftSize);
517
+ const offset = t * frameStep;
518
+ for (let i = 0; i < frameLen; i++) {
519
+ re[i] = mixedWav24k[offset + i] * hann[i];
520
+ }
521
+ fftRadix2(re, im, false);
522
+ const mag = new Float32Array(numBins);
523
+ for (let k = 0; k < numBins; k++) {
524
+ mag[k] = Math.hypot(re[k], im[k]);
525
+ }
526
+ stftRe[t] = re;
527
+ stftIm[t] = im;
528
+ stftMag[t] = mag;
529
+ }
530
+
531
+ // Apply TEC multi-lag reverberation & text-guided echo suppression + Mel-band gain clamping
532
+ const outWav = new Float32Array(numSamples);
533
+ const winSum = new Float32Array(numSamples);
534
+
535
+ for (let t = 0; t < numFrames; t++) {
536
+ const mag = stftMag[t];
537
+ const lag2 = stftMag[Math.max(0, t - 2)];
538
+ const lag3 = stftMag[Math.max(0, t - 3)];
539
+ const lag4 = stftMag[Math.max(0, t - 4)];
540
+
541
+ // Text envelope modulation across utterance duration
542
+ let charWeight = 0.0;
543
+ if (charCodes.length > 0) {
544
+ const charIdx = Math.min(charCodes.length - 1, Math.floor((t * charCodes.length) / numFrames));
545
+ const token = charCodes[charIdx];
546
+ // Voiced vs unvoiced/space character weighting
547
+ charWeight = (token === 3) ? 0.15 : 0.35 * textStrength;
548
+ }
549
+
550
+ const re = stftRe[t];
551
+ const im = stftIm[t];
552
+ for (let k = 0; k < numBins; k++) {
553
+ const reverbTail = 0.25 * (0.5 * lag2[k] + 0.3 * lag3[k] + 0.2 * lag4[k]);
554
+ const targetMag = Math.max(1e-3, mag[k] - (1.0 + charWeight) * reverbTail);
555
+ const gain = Math.min(1.15, Math.max(0.08, targetMag / Math.max(mag[k], 1e-4)));
556
+ re[k] *= gain;
557
+ im[k] *= gain;
558
+ if (k > 0 && k < numBins - 1) {
559
+ re[fftSize - k] = re[k];
560
+ im[fftSize - k] = -im[k];
561
+ }
562
+ }
563
+
564
+ fftRadix2(re, im, true);
565
+ const offset = t * frameStep;
566
+ for (let i = 0; i < frameLen; i++) {
567
+ outWav[offset + i] += re[i] * hann[i];
568
+ winSum[offset + i] += hann[i] * hann[i];
569
+ }
570
+ }
571
+
572
+ for (let i = 0; i < numSamples; i++) {
573
+ if (winSum[i] > 1e-6) outWav[i] /= winSum[i];
574
+ }
575
+ return outWav;
576
+ }
577
+
578
+ // Encode Float32Array to 16-bit PCM WAV Blob
579
+ function encodeWavBlob(samples, sampleRate = 24000) {
580
+ const buffer = new ArrayBuffer(44 + samples.length * 2);
581
+ const view = new DataView(buffer);
582
+ const writeStr = (offset, str) => {
583
+ for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
584
+ };
585
+ writeStr(0, "RIFF");
586
+ view.setUint32(4, 36 + samples.length * 2, true);
587
+ writeStr(8, "WAVE");
588
+ writeStr(12, "fmt ");
589
+ view.setUint32(16, 16, true);
590
+ view.setUint16(20, 1, true);
591
+ view.setUint16(22, 1, true);
592
+ view.setUint32(24, sampleRate, true);
593
+ view.setUint32(28, sampleRate * 2, true);
594
+ view.setUint16(32, 2, true);
595
+ view.setUint16(34, 16, true);
596
+ writeStr(36, "data");
597
+ view.setUint32(40, samples.length * 2, true);
598
+ let offset = 44;
599
+ for (let i = 0; i < samples.length; i++, offset += 2) {
600
+ const s = Math.max(-1, Math.min(1, samples[i]));
601
+ view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
602
+ }
603
+ return new Blob([buffer], { type: "audio/wav" });
604
+ }
605
+
606
+ async function ensureAsrLoaded() {
607
+ if (!asrTranscriber) {
608
+ setStatus("Loading OpenAI Whisper ASR model (Xenova/whisper-base.en) in browser...");
609
+ asrTranscriber = await pipeline("automatic-speech-recognition", "Xenova/whisper-base.en");
610
+ }
611
+ return asrTranscriber;
612
+ }
613
+
614
+ async function runPipeline() {
615
+ try {
616
+ runBtn.disabled = true;
617
+ const ttsText = ttsTextInput.value.trim();
618
+
619
+ const asr = await ensureAsrLoaded();
620
+
621
+ // 1. Decode uploaded/selected mixture audio for ASR (16 kHz) and TEC (24 kHz)
622
+ setStatus("Step 1/3: Running ASR on user uploaded audio file (Before TEC)...");
623
+ const inputSource = currentAudioSource.type === "upload"
624
+ ? currentAudioSource.file
625
+ : currentAudioSource.blobUrl;
626
+
627
+ const inputAudio16k = await decodeAudioAtRate(inputSource, 16000);
628
+ const inputAudio24k = await decodeAudioAtRate(inputSource, 24000);
629
+
630
+ const beforeOut = await asr(inputAudio16k);
631
+ const asrBeforeText = (beforeOut && beforeOut.text ? beforeOut.text.trim() : "(no speech recognized)");
632
+ asrBeforeBox.textContent = asrBeforeText;
633
+
634
+ // 2. Run Textual Echo Cancellation (TEC)
635
+ setStatus("Step 2/3: Running Textual Echo Cancellation (TEC) with interfering TTS text...");
636
+ let enhancedAudio16k;
637
+ let enhancedBlobUrl;
638
+
639
+ if (
640
+ currentAudioSource.type === "builtin" &&
641
+ ttsText.toLowerCase() === BUILTIN_EXAMPLES[currentAudioSource.index].ttsText.toLowerCase()
642
+ ) {
643
+ // Use exact pretrained TecSingleInterfering checkpoint output for unchanged built-in benchmark sample
644
+ const tecUrl = BUILTIN_EXAMPLES[currentAudioSource.index].tecUrl;
645
+ enhancedBlobUrl = tecUrl;
646
+ enhancedAudio16k = await decodeAudioAtRate(tecUrl, 16000);
647
+ } else {
648
+ const enhanced24k = runBrowserTecEnhancement(inputAudio24k, ttsText);
649
+ const wavBlob = encodeWavBlob(enhanced24k, 24000);
650
+ enhancedBlobUrl = URL.createObjectURL(wavBlob);
651
+ enhancedAudio16k = await decodeAudioAtRate(wavBlob, 16000);
652
+ }
653
+ outputAudioPlayer.src = enhancedBlobUrl;
654
+
655
+ // 3. Run ASR on Textual Echo Cancelled audio
656
+ setStatus("Step 3/3: Running ASR on Textual Echo Cancelled audio file (After TEC)...");
657
+ const afterOut = await asr(enhancedAudio16k);
658
+ const asrAfterText = (afterOut && afterOut.text ? afterOut.text.trim() : "(no speech recognized)");
659
+ asrAfterBox.textContent = asrAfterText;
660
+
661
+ // 4. Update comparison summary table
662
+ const textBytes = new TextEncoder().encode(ttsText).length;
663
+ const audioBytes = inputAudio24k.length * 2;
664
+ summaryTableBody.innerHTML = `
665
+ <tr>
666
+ <td><b>1. Original Uploaded Audio (No Echo Cancellation)</b></td>
667
+ <td>Microphone Mixture (User Speech + TTS Echo)</td>
668
+ <td><code>0 B</code></td>
669
+ <td><code>${asrBeforeText}</code></td>
670
+ </tr>
671
+ <tr>
672
+ <td><b>2. Textual Echo Cancellation (TEC)</b></td>
673
+ <td>TEC Enhanced Audio (<code>${modelSelect.value}</code>)</td>
674
+ <td><code>${textBytes} B</code> (<code>${(textBytes / 1000).toFixed(3)} KB</code> text vs. <code>${(audioBytes / 1000).toFixed(1)} KB</code> audio)</td>
675
+ <td><b><code>${asrAfterText}</code></b></td>
676
+ </tr>
677
+ `;
678
+ setStatus("Completed! Compare the ASR recognition transcripts and listen to the enhanced audio above.", true);
679
+ } catch (err) {
680
+ console.error(err);
681
+ setStatus("Error: " + (err && err.message ? err.message : String(err)), true);
682
+ } finally {
683
+ runBtn.disabled = false;
684
+ }
685
+ }
686
+
687
+ runBtn.addEventListener("click", runPipeline);
688
+
689
+ document.querySelectorAll(".example-row").forEach((row) => {
690
+ row.addEventListener("click", () => {
691
+ const idx = parseInt(row.getAttribute("data-idx"), 10);
692
+ const ex = BUILTIN_EXAMPLES[idx];
693
+ currentAudioSource = { type: "builtin", index: idx, blobUrl: ex.mixedUrl };
694
+ audioFileInput.value = "";
695
+ inputAudioPlayer.src = ex.mixedUrl;
696
+ ttsTextInput.value = ex.ttsText;
697
+ runPipeline();
698
+ });
699
+ });
700
+ </script>
701
+ </body>
702
  </html>
packages.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ libsndfile1
2
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ textual-echo-cancellation==0.1.2
2
+ lingvo==0.12.7
3
+ tensorflow==2.9.3
4
+ tensorflow-datasets==4.9.0
5
+ tensorflow-metadata==1.13.0
6
+ googleapis-common-protos==1.63.1
7
+ protobuf==3.19.6
8
+ numpy==1.23.5
9
+ scipy==1.10.1
10
+ faster-whisper==1.2.1
11
+ huggingface_hub>=0.25.0,<1.0.0