ZeroPointMonkey commited on
Commit
c0b00e8
·
verified ·
1 Parent(s): 5a4878b

Faithful-cloning defaults + sliders + optional background-audio removal (demucs-onnx)

Browse files
Files changed (3) hide show
  1. README.md +22 -6
  2. app.py +156 -12
  3. requirements.txt +5 -0
README.md CHANGED
@@ -19,14 +19,23 @@ which beats ElevenLabs in independent blind preference tests.
19
 
20
  ## How to use (manual A/B)
21
  1. Upload a **reference audio** clip of the voice to clone (5–20 s of clean speech is ideal).
22
- 2. Pick the **language** (default: English).
23
- 3. Type the **text** to speak (long scripts are auto-chunked at sentence boundaries).
24
- 4. Click **Clone & Speak** → you get audio in the cloned voice.
 
 
 
25
 
26
  Tip: leave the reference empty to hear a built-in sample voice for the selected language.
27
 
 
 
 
 
 
28
  ## API (for bot integration later)
29
- Gradio exposes a programmatic endpoint named **`clone`**:
 
30
 
31
  ```python
32
  from gradio_client import Client, handle_file
@@ -36,13 +45,20 @@ sr_path = client.predict(
36
  text="Hey, it's good to finally hear your voice.",
37
  language_id="en",
38
  audio_prompt_path=handle_file("reference.wav"),
39
- exaggeration=0.5,
40
  cfg_weight=0.5,
41
- temperature=0.8,
42
  seed=0,
 
 
 
 
43
  api_name="/clone",
44
  )
45
  print(sr_path) # path to generated wav
 
 
 
46
  ```
47
 
48
  ## Notes
 
19
 
20
  ## How to use (manual A/B)
21
  1. Upload a **reference audio** clip of the voice to clone (5–20 s of clean speech is ideal).
22
+ 2. (Optional) Tick **🧹 Remove background audio from reference** to isolate the voice
23
+ (HT-Demucs) before cloning if the clip has music/noise. Use **Preview cleaned reference**
24
+ to hear the isolated result first.
25
+ 3. Pick the **language** (default: English).
26
+ 4. Type the **text** to speak (long scripts are auto-chunked at sentence boundaries).
27
+ 5. Click **Clone & Speak** → you get audio in the cloned voice.
28
 
29
  Tip: leave the reference empty to hear a built-in sample voice for the selected language.
30
 
31
+ ### Cloning defaults (tuned for faithful cloning)
32
+ Tuned for **speaker similarity**, not expressiveness:
33
+ `exaggeration=0.4` (neutral), `cfg_weight=0.5` (balanced; ~0.3 faster pace, 0.0 cross-lingual),
34
+ `temperature=0.7` (consistent). All knobs are exposed as sliders.
35
+
36
  ## API (for bot integration later)
37
+ Gradio exposes a programmatic endpoint named **`clone`** (plus **`isolate_voice`** for
38
+ standalone background-audio removal):
39
 
40
  ```python
41
  from gradio_client import Client, handle_file
 
45
  text="Hey, it's good to finally hear your voice.",
46
  language_id="en",
47
  audio_prompt_path=handle_file("reference.wav"),
48
+ exaggeration=0.4,
49
  cfg_weight=0.5,
50
+ temperature=0.7,
51
  seed=0,
52
+ clean_reference=False, # True = strip background music/noise first
53
+ repetition_penalty=2.0,
54
+ min_p=0.05,
55
+ top_p=1.0,
56
  api_name="/clone",
57
  )
58
  print(sr_path) # path to generated wav
59
+
60
+ # Just clean a reference clip (returns isolated-voice wav):
61
+ cleaned = client.predict(handle_file("noisy_reference.wav"), api_name="/isolate_voice")
62
  ```
63
 
64
  ## Notes
app.py CHANGED
@@ -9,10 +9,13 @@ Mirrors the official ResembleAI/Chatterbox-Multilingual-TTS inference path, with
9
  - long-text sentence chunking (so JOI-length scripts work, not just 300 chars),
10
  - a clean programmatic endpoint (api_name="/clone") for later bot integration.
11
  """
 
12
  import random
13
  import re
 
14
 
15
  import numpy as np
 
16
  import torch
17
  import gradio as gr
18
  import spaces
@@ -24,6 +27,22 @@ print(f"Running on device: {DEVICE}")
24
 
25
  MODEL = None
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # Built-in sample reference voices per language (used when no reference is uploaded).
28
  LANGUAGE_CONFIG = {
29
  "en": {
@@ -76,6 +95,69 @@ def set_seed(seed: int):
76
  np.random.seed(seed)
77
 
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  def default_audio_for_ui(lang: str):
80
  return LANGUAGE_CONFIG.get(lang, {}).get("audio")
81
 
@@ -111,15 +193,30 @@ def split_into_chunks(text: str, max_chars: int = CHUNK_CHARS):
111
  return [c for c in chunks if c]
112
 
113
 
 
 
 
 
 
 
 
 
 
 
 
114
  @spaces.GPU(duration=120)
115
  def clone_and_speak(
116
  text: str,
117
  language_id: str = "en",
118
  audio_prompt_path: str = None,
119
- exaggeration: float = 0.5,
120
- cfg_weight: float = 0.5,
121
- temperature: float = 0.8,
122
  seed: int = 0,
 
 
 
 
123
  ):
124
  """
125
  Clone the voice in `audio_prompt_path` and speak `text` in language `language_id`.
@@ -129,10 +226,16 @@ def clone_and_speak(
129
  language_id: language code (en, fr, de, es, it, pt, hi, ja, zh, ...).
130
  audio_prompt_path: path/URL to a reference voice clip. If omitted, a
131
  built-in sample voice for the language is used.
132
- exaggeration: expressiveness (0.25-2.0, neutral 0.5).
133
- cfg_weight: CFG / pacing (0.2-1.0; set ~0.3 for cross-lingual transfer).
134
- temperature: sampling randomness (0.05-5.0).
 
135
  seed: 0 for random, otherwise reproducible.
 
 
 
 
 
136
 
137
  Returns:
138
  (sample_rate, waveform) tuple consumable by gr.Audio.
@@ -151,9 +254,14 @@ def clone_and_speak(
151
  if not ref:
152
  raise gr.Error("Upload a reference audio clip to clone (or pick a language with a built-in sample).")
153
 
 
 
 
 
 
154
  lang = (language_id or "en").lower()
155
  chunks = split_into_chunks(text)
156
- print(f"Cloning voice | lang={lang} | chunks={len(chunks)} | ref={ref}")
157
 
158
  # Prepare speaker conditionals ONCE from the reference, then reuse across chunks
159
  # so the cloned identity stays consistent for the whole script.
@@ -170,6 +278,9 @@ def clone_and_speak(
170
  exaggeration=exaggeration,
171
  cfg_weight=cfg_weight,
172
  temperature=temperature,
 
 
 
173
  )
174
  arr = wav.squeeze(0).detach().cpu().numpy().astype(np.float32)
175
  pieces.append(arr)
@@ -201,6 +312,13 @@ with gr.Blocks(title="Voice Clone Bench") as demo:
201
  label="① Reference voice to clone (5–20s clean speech). Empty = built-in sample.",
202
  value=default_audio_for_ui("en"),
203
  )
 
 
 
 
 
 
 
204
  language_id = gr.Dropdown(
205
  choices=list(ChatterboxMultilingualTTS.get_supported_languages().keys()),
206
  value="en",
@@ -212,20 +330,46 @@ with gr.Blocks(title="Voice Clone Bench") as demo:
212
  lines=5,
213
  max_lines=20,
214
  )
215
- with gr.Accordion("Advanced", open=False):
216
- exaggeration = gr.Slider(0.25, 2.0, step=0.05, value=0.5, label="Exaggeration (neutral 0.5)")
217
- cfg_weight = gr.Slider(0.2, 1.0, step=0.05, value=0.5, label="CFG / Pace (≈0.3 for cross-lingual)")
218
- temperature = gr.Slider(0.05, 2.0, step=0.05, value=0.8, label="Temperature")
 
 
 
 
 
 
 
 
 
219
  seed = gr.Number(value=0, label="Seed (0 = random)")
 
 
 
 
 
 
 
220
  run_btn = gr.Button("Clone & Speak", variant="primary")
221
  with gr.Column():
222
  audio_output = gr.Audio(label="Cloned speech output")
223
 
224
  language_id.change(fn=on_language_change, inputs=[language_id], outputs=[ref_wav, text], show_progress=False)
225
 
 
 
 
 
 
 
 
226
  run_btn.click(
227
  fn=clone_and_speak,
228
- inputs=[text, language_id, ref_wav, exaggeration, cfg_weight, temperature, seed],
 
 
 
229
  outputs=[audio_output],
230
  api_name="clone",
231
  )
 
9
  - long-text sentence chunking (so JOI-length scripts work, not just 300 chars),
10
  - a clean programmatic endpoint (api_name="/clone") for later bot integration.
11
  """
12
+ import os
13
  import random
14
  import re
15
+ import tempfile
16
 
17
  import numpy as np
18
+ import soundfile as sf
19
  import torch
20
  import gradio as gr
21
  import spaces
 
27
 
28
  MODEL = None
29
 
30
+ # ── Faithful-cloning defaults ────────────────────────────────────────────────
31
+ # Tuned for SPEAKER SIMILARITY (clean identity match), not expressiveness.
32
+ # Rationale (Resemble AI Chatterbox guidance + community cloning presets):
33
+ # - exaggeration LOW (~0.4): keeps delivery neutral/professional so the model
34
+ # reproduces the reference identity instead of "acting" it.
35
+ # - cfg_weight 0.5: balanced default; lower (~0.3) speeds pacing, 0.0 helps
36
+ # cross-lingual transfer avoid inheriting the reference-language accent.
37
+ # - temperature 0.7: slightly below the 0.8 default for steadier, more
38
+ # consistent output across chunked long scripts (less random drift).
39
+ DEFAULT_EXAGGERATION = 0.4
40
+ DEFAULT_CFG_WEIGHT = 0.5
41
+ DEFAULT_TEMPERATURE = 0.7
42
+ DEFAULT_REPETITION_PENALTY = 2.0
43
+ DEFAULT_MIN_P = 0.05
44
+ DEFAULT_TOP_P = 1.0
45
+
46
  # Built-in sample reference voices per language (used when no reference is uploaded).
47
  LANGUAGE_CONFIG = {
48
  "en": {
 
95
  np.random.seed(seed)
96
 
97
 
98
+ # ── Audio cleanup (background-audio removal) ─────────────────────────────────
99
+ # Optional preprocessing: isolate the spoken voice from a noisy/musical
100
+ # reference clip BEFORE cloning, so the speaker conditionals are built from
101
+ # clean speech. Uses HT-Demucs (htdemucs_ft vocals stem, #1 open-source vocal
102
+ # SDR) via the pure-numpy + onnxruntime `demucs-onnx` package — no torch/
103
+ # torchaudio dependency, so it can't disturb the pinned Chatterbox stack.
104
+ # Runs on CPU so it does NOT consume the ZeroGPU budget. Designed as the first
105
+ # member of a future "audio cleanup" feature group (denoise, trim, normalize…).
106
+ _SEPARATOR_READY = None
107
+
108
+
109
+ def _ensure_separator():
110
+ """Lazy-import demucs-onnx. Returns the callable or None if unavailable."""
111
+ global _SEPARATOR_READY
112
+ if _SEPARATOR_READY is None:
113
+ try:
114
+ from demucs_onnx import separate_stem # noqa: PLC0415
115
+ _SEPARATOR_READY = separate_stem
116
+ except Exception as e: # noqa: BLE001
117
+ print(f"WARNING: demucs-onnx unavailable, voice isolation disabled: {e}")
118
+ _SEPARATOR_READY = False
119
+ return _SEPARATOR_READY or None
120
+
121
+
122
+ def isolate_voice(audio_path: str) -> str:
123
+ """Return a path to a cleaned WAV with background music/noise removed.
124
+
125
+ Falls back to the original clip (and warns) if separation is unavailable
126
+ or fails, so cloning never hard-breaks on a cleanup error.
127
+ """
128
+ if not audio_path:
129
+ return audio_path
130
+ separate_stem = _ensure_separator()
131
+ if separate_stem is None:
132
+ raise gr.Error("Voice isolation is unavailable (demucs-onnx not installed).")
133
+
134
+ try:
135
+ sr = sf.info(audio_path).samplerate
136
+ except Exception: # noqa: BLE001
137
+ sr = 44100
138
+
139
+ # htdemucs_ft vocals specialist (CPU keeps this off the ZeroGPU budget).
140
+ vocals = separate_stem(audio_path, "vocals", providers="cpu") # (channels, samples)
141
+ vocals = np.asarray(vocals, dtype=np.float32)
142
+ if vocals.ndim == 2:
143
+ vocals = vocals.mean(axis=0) # downmix to mono for the speaker encoder
144
+ peak = float(np.max(np.abs(vocals))) if vocals.size else 0.0
145
+ if peak > 1.0:
146
+ vocals = vocals / peak
147
+
148
+ out_path = os.path.join(tempfile.gettempdir(), f"isolated_{random.randint(0, 1_000_000)}.wav")
149
+ sf.write(out_path, vocals, sr)
150
+ print(f"Isolated voice -> {out_path} ({len(vocals)/sr:.1f}s @ {sr}Hz)")
151
+ return out_path
152
+
153
+
154
+ def isolate_voice_ui(audio_path: str):
155
+ """UI/endpoint wrapper: preview the cleaned reference (api_name=/isolate_voice)."""
156
+ if not audio_path:
157
+ raise gr.Error("Upload a reference clip first.")
158
+ return isolate_voice(audio_path)
159
+
160
+
161
  def default_audio_for_ui(lang: str):
162
  return LANGUAGE_CONFIG.get(lang, {}).get("audio")
163
 
 
193
  return [c for c in chunks if c]
194
 
195
 
196
+ def _maybe_clean_reference(ref: str, clean_reference: bool) -> str:
197
+ """Optionally strip background music/noise from a user-supplied reference."""
198
+ if not (clean_reference and ref):
199
+ return ref
200
+ try:
201
+ return isolate_voice(ref)
202
+ except Exception as e: # noqa: BLE001
203
+ gr.Warning(f"Background-audio removal failed, using raw reference: {e}")
204
+ return ref
205
+
206
+
207
  @spaces.GPU(duration=120)
208
  def clone_and_speak(
209
  text: str,
210
  language_id: str = "en",
211
  audio_prompt_path: str = None,
212
+ exaggeration: float = DEFAULT_EXAGGERATION,
213
+ cfg_weight: float = DEFAULT_CFG_WEIGHT,
214
+ temperature: float = DEFAULT_TEMPERATURE,
215
  seed: int = 0,
216
+ clean_reference: bool = False,
217
+ repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
218
+ min_p: float = DEFAULT_MIN_P,
219
+ top_p: float = DEFAULT_TOP_P,
220
  ):
221
  """
222
  Clone the voice in `audio_prompt_path` and speak `text` in language `language_id`.
 
226
  language_id: language code (en, fr, de, es, it, pt, hi, ja, zh, ...).
227
  audio_prompt_path: path/URL to a reference voice clip. If omitted, a
228
  built-in sample voice for the language is used.
229
+ exaggeration: expressiveness (0.25-2.0; ~0.4 = neutral/faithful clone).
230
+ cfg_weight: CFG / pacing (0.0-1.0; lower ~0.3 = faster pace, 0.0 for
231
+ cross-lingual transfer; 0.5 = balanced default).
232
+ temperature: sampling randomness (0.05-2.0; lower = more consistent).
233
  seed: 0 for random, otherwise reproducible.
234
+ clean_reference: if True, isolate the voice (remove background music/
235
+ noise) from the uploaded reference before cloning.
236
+ repetition_penalty: discourages repeated tokens (model default 2.0).
237
+ min_p: min-p nucleus floor (model default 0.05).
238
+ top_p: top-p nucleus threshold (model default 1.0).
239
 
240
  Returns:
241
  (sample_rate, waveform) tuple consumable by gr.Audio.
 
254
  if not ref:
255
  raise gr.Error("Upload a reference audio clip to clone (or pick a language with a built-in sample).")
256
 
257
+ # Optional preprocessing: clean the reference so conditionals are built from
258
+ # isolated speech (only applies to a user-uploaded clip, not built-in samples).
259
+ if audio_prompt_path:
260
+ ref = _maybe_clean_reference(ref, clean_reference)
261
+
262
  lang = (language_id or "en").lower()
263
  chunks = split_into_chunks(text)
264
+ print(f"Cloning voice | lang={lang} | chunks={len(chunks)} | clean_ref={clean_reference} | ref={ref}")
265
 
266
  # Prepare speaker conditionals ONCE from the reference, then reuse across chunks
267
  # so the cloned identity stays consistent for the whole script.
 
278
  exaggeration=exaggeration,
279
  cfg_weight=cfg_weight,
280
  temperature=temperature,
281
+ repetition_penalty=repetition_penalty,
282
+ min_p=min_p,
283
+ top_p=top_p,
284
  )
285
  arr = wav.squeeze(0).detach().cpu().numpy().astype(np.float32)
286
  pieces.append(arr)
 
312
  label="① Reference voice to clone (5–20s clean speech). Empty = built-in sample.",
313
  value=default_audio_for_ui("en"),
314
  )
315
+ clean_reference = gr.Checkbox(
316
+ value=False,
317
+ label="🧹 Remove background audio from reference (isolate voice before cloning)",
318
+ info="Strips music/noise with HT-Demucs so the clone is built from clean speech.",
319
+ )
320
+ preview_btn = gr.Button("🧹 Preview cleaned reference", size="sm")
321
+ cleaned_preview = gr.Audio(label="Isolated voice (preview)", visible=True)
322
  language_id = gr.Dropdown(
323
  choices=list(ChatterboxMultilingualTTS.get_supported_languages().keys()),
324
  value="en",
 
330
  lines=5,
331
  max_lines=20,
332
  )
333
+ with gr.Accordion("Cloning controls (tuned for faithful voice cloning)", open=True):
334
+ exaggeration = gr.Slider(
335
+ 0.0, 2.0, step=0.05, value=DEFAULT_EXAGGERATION,
336
+ label="Exaggeration lower = more neutral/faithful (≈0.4); 0.7+ = expressive",
337
+ )
338
+ cfg_weight = gr.Slider(
339
+ 0.0, 1.0, step=0.05, value=DEFAULT_CFG_WEIGHT,
340
+ label="CFG / Pace — 0.5 balanced; ~0.3 faster; 0.0 for cross-lingual",
341
+ )
342
+ temperature = gr.Slider(
343
+ 0.05, 2.0, step=0.05, value=DEFAULT_TEMPERATURE,
344
+ label="Temperature �� lower = more consistent/faithful (≈0.7)",
345
+ )
346
  seed = gr.Number(value=0, label="Seed (0 = random)")
347
+ with gr.Accordion("Sampling (advanced)", open=False):
348
+ repetition_penalty = gr.Slider(
349
+ 1.0, 2.5, step=0.05, value=DEFAULT_REPETITION_PENALTY,
350
+ label="Repetition penalty (default 2.0)",
351
+ )
352
+ min_p = gr.Slider(0.0, 0.5, step=0.01, value=DEFAULT_MIN_P, label="min_p (default 0.05)")
353
+ top_p = gr.Slider(0.1, 1.0, step=0.05, value=DEFAULT_TOP_P, label="top_p (default 1.0)")
354
  run_btn = gr.Button("Clone & Speak", variant="primary")
355
  with gr.Column():
356
  audio_output = gr.Audio(label="Cloned speech output")
357
 
358
  language_id.change(fn=on_language_change, inputs=[language_id], outputs=[ref_wav, text], show_progress=False)
359
 
360
+ preview_btn.click(
361
+ fn=isolate_voice_ui,
362
+ inputs=[ref_wav],
363
+ outputs=[cleaned_preview],
364
+ api_name="isolate_voice",
365
+ )
366
+
367
  run_btn.click(
368
  fn=clone_and_speak,
369
+ inputs=[
370
+ text, language_id, ref_wav, exaggeration, cfg_weight, temperature, seed,
371
+ clean_reference, repetition_penalty, min_p, top_p,
372
+ ],
373
  outputs=[audio_output],
374
  api_name="clone",
375
  )
requirements.txt CHANGED
@@ -14,6 +14,11 @@ silero-vad==5.1.2
14
  conformer==0.3.2
15
  safetensors
16
 
 
 
 
 
 
17
  # Optional language-specific normalizers (disabled for build reliability — English-first prototype).
18
  # Re-enable only if you need advanced zh / ja / ru text normalization:
19
  # spacy_pkuseg # Chinese text segmentation
 
14
  conformer==0.3.2
15
  safetensors
16
 
17
+ # Audio cleanup: HT-Demucs (htdemucs_ft vocals stem) via pure numpy + onnxruntime.
18
+ # No torch/torchaudio at inference, so it can't disturb the pinned Chatterbox stack.
19
+ # Used for optional background-audio removal from reference clips before cloning.
20
+ demucs-onnx==0.3.4
21
+
22
  # Optional language-specific normalizers (disabled for build reliability — English-first prototype).
23
  # Re-enable only if you need advanced zh / ja / ru text normalization:
24
  # spacy_pkuseg # Chinese text segmentation