Zihan428 commited on
Commit
419beb8
·
1 Parent(s): c800305

Clean reference audio conditioning

Browse files
Files changed (1) hide show
  1. chatterbox/src/chatterbox/tts.py +81 -2
chatterbox/src/chatterbox/tts.py CHANGED
@@ -1,8 +1,11 @@
1
  from dataclasses import dataclass
2
  from pathlib import Path
 
3
  import os
 
4
 
5
  import librosa
 
6
  import torch
7
  import perth
8
  import torch.nn.functional as F
@@ -26,6 +29,10 @@ TOKENIZER_FILENAME = "grapheme_mtl_merged_expanded_v1.json"
26
  CANGJIE_FILENAME = "Cangjie5_TC.json"
27
  T3_TEXT_VOCAB_SIZE = 2454
28
 
 
 
 
 
29
 
30
  def punc_norm(text: str) -> str:
31
  """
@@ -65,6 +72,74 @@ def punc_norm(text: str) -> str:
65
  return text
66
 
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  @dataclass
69
  class Conditionals:
70
  """
@@ -111,7 +186,7 @@ class ChatterboxTTS:
111
  This model uses English tokenization internally and accepts text in any language without requiring language specification.
112
  """
113
  ENC_COND_LEN = 6 * S3_SR
114
- DEC_COND_LEN = 10 * S3GEN_SR
115
 
116
  def __init__(
117
  self,
@@ -216,10 +291,14 @@ class ChatterboxTTS:
216
  def prepare_conditionals(self, wav_fpath, exaggeration=0.5):
217
  ## Load reference wav
218
  s3gen_ref_wav, _sr = librosa.load(wav_fpath, sr=S3GEN_SR)
 
 
 
 
 
219
 
220
  ref_16k_wav = librosa.resample(s3gen_ref_wav, orig_sr=S3GEN_SR, target_sr=S3_SR)
221
 
222
- s3gen_ref_wav = s3gen_ref_wav[:self.DEC_COND_LEN]
223
  s3gen_ref_dict = self.s3gen.embed_ref(s3gen_ref_wav, S3GEN_SR, device=self.device)
224
 
225
  # Speech cond prompt tokens
 
1
  from dataclasses import dataclass
2
  from pathlib import Path
3
+ import logging
4
  import os
5
+ import threading
6
 
7
  import librosa
8
+ import numpy as np
9
  import torch
10
  import perth
11
  import torch.nn.functional as F
 
29
  CANGJIE_FILENAME = "Cangjie5_TC.json"
30
  T3_TEXT_VOCAB_SIZE = 2454
31
 
32
+ logger = logging.getLogger(__name__)
33
+ _reference_vad_model = None
34
+ _reference_vad_lock = threading.Lock()
35
+
36
 
37
  def punc_norm(text: str) -> str:
38
  """
 
72
  return text
73
 
74
 
75
+ def prepare_reference_audio(
76
+ wav: np.ndarray,
77
+ sample_rate: int,
78
+ max_duration_s: float = 6.0,
79
+ speech_pad_ms: int = 100,
80
+ fade_ms: int = 10,
81
+ ) -> np.ndarray:
82
+ """Keep up to `max_duration_s` of detected speech for model conditioning."""
83
+ wav = np.asarray(wav, dtype=np.float32).reshape(-1)
84
+ max_samples = int(max_duration_s * sample_rate)
85
+ fallback = wav[:max_samples].copy()
86
+
87
+ try:
88
+ from silero_vad import get_speech_timestamps, load_silero_vad
89
+
90
+ vad_sample_rate = 16_000
91
+ vad_wav = wav
92
+ if sample_rate != vad_sample_rate:
93
+ vad_wav = librosa.resample(wav, orig_sr=sample_rate, target_sr=vad_sample_rate)
94
+ vad_wav = np.asarray(vad_wav, dtype=np.float32)
95
+
96
+ global _reference_vad_model
97
+ with _reference_vad_lock:
98
+ if _reference_vad_model is None:
99
+ _reference_vad_model = load_silero_vad()
100
+ timestamps = get_speech_timestamps(
101
+ torch.from_numpy(vad_wav),
102
+ _reference_vad_model,
103
+ sampling_rate=vad_sample_rate,
104
+ speech_pad_ms=0,
105
+ )
106
+
107
+ pad_samples = int(speech_pad_ms * sample_rate / 1000)
108
+ intervals = []
109
+ for timestamp in timestamps:
110
+ start = max(0, int(timestamp["start"] * sample_rate / vad_sample_rate) - pad_samples)
111
+ end = min(len(wav), int(timestamp["end"] * sample_rate / vad_sample_rate) + pad_samples)
112
+ if end <= start:
113
+ continue
114
+ if intervals and start <= intervals[-1][1]:
115
+ intervals[-1] = (intervals[-1][0], max(intervals[-1][1], end))
116
+ else:
117
+ intervals.append((start, end))
118
+
119
+ segments = []
120
+ remaining = max_samples
121
+ for start, end in intervals:
122
+ segment = wav[start:end]
123
+ segments.append(segment[:remaining])
124
+ remaining -= min(len(segment), remaining)
125
+ if remaining <= 0:
126
+ break
127
+
128
+ if segments:
129
+ fallback = np.concatenate(segments)
130
+ else:
131
+ logger.warning("No speech detected in reference audio; using its untrimmed prefix")
132
+ except Exception:
133
+ logger.warning("Reference VAD failed; using the untrimmed reference prefix", exc_info=True)
134
+
135
+ fade_samples = min(int(fade_ms * sample_rate / 1000), len(fallback) // 2)
136
+ if fade_samples > 0:
137
+ fade_in = np.linspace(0.0, 1.0, fade_samples, dtype=np.float32)
138
+ fallback[:fade_samples] *= fade_in
139
+ fallback[-fade_samples:] *= fade_in[::-1]
140
+ return np.ascontiguousarray(fallback, dtype=np.float32)
141
+
142
+
143
  @dataclass
144
  class Conditionals:
145
  """
 
186
  This model uses English tokenization internally and accepts text in any language without requiring language specification.
187
  """
188
  ENC_COND_LEN = 6 * S3_SR
189
+ REF_COND_DURATION_S = 6
190
 
191
  def __init__(
192
  self,
 
291
  def prepare_conditionals(self, wav_fpath, exaggeration=0.5):
292
  ## Load reference wav
293
  s3gen_ref_wav, _sr = librosa.load(wav_fpath, sr=S3GEN_SR)
294
+ s3gen_ref_wav = prepare_reference_audio(
295
+ s3gen_ref_wav,
296
+ S3GEN_SR,
297
+ max_duration_s=self.REF_COND_DURATION_S,
298
+ )
299
 
300
  ref_16k_wav = librosa.resample(s3gen_ref_wav, orig_sr=S3GEN_SR, target_sr=S3_SR)
301
 
 
302
  s3gen_ref_dict = self.s3gen.embed_ref(s3gen_ref_wav, S3GEN_SR, device=self.device)
303
 
304
  # Speech cond prompt tokens