videopython-chatterbox 0.1.7.post1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. chatterbox/__init__.py +14 -0
  2. chatterbox/models/__init__.py +0 -0
  3. chatterbox/models/s3gen/__init__.py +2 -0
  4. chatterbox/models/s3gen/configs.py +10 -0
  5. chatterbox/models/s3gen/const.py +2 -0
  6. chatterbox/models/s3gen/decoder.py +333 -0
  7. chatterbox/models/s3gen/f0_predictor.py +55 -0
  8. chatterbox/models/s3gen/flow.py +198 -0
  9. chatterbox/models/s3gen/flow_matching.py +246 -0
  10. chatterbox/models/s3gen/hifigan.py +474 -0
  11. chatterbox/models/s3gen/matcha/decoder.py +443 -0
  12. chatterbox/models/s3gen/matcha/flow_matching.py +129 -0
  13. chatterbox/models/s3gen/matcha/text_encoder.py +413 -0
  14. chatterbox/models/s3gen/matcha/transformer.py +316 -0
  15. chatterbox/models/s3gen/s3gen.py +362 -0
  16. chatterbox/models/s3gen/transformer/__init__.py +0 -0
  17. chatterbox/models/s3gen/transformer/activation.py +84 -0
  18. chatterbox/models/s3gen/transformer/attention.py +330 -0
  19. chatterbox/models/s3gen/transformer/convolution.py +145 -0
  20. chatterbox/models/s3gen/transformer/embedding.py +294 -0
  21. chatterbox/models/s3gen/transformer/encoder_layer.py +236 -0
  22. chatterbox/models/s3gen/transformer/positionwise_feed_forward.py +115 -0
  23. chatterbox/models/s3gen/transformer/subsampling.py +383 -0
  24. chatterbox/models/s3gen/transformer/upsample_encoder.py +318 -0
  25. chatterbox/models/s3gen/utils/class_utils.py +71 -0
  26. chatterbox/models/s3gen/utils/intmeanflow.py +36 -0
  27. chatterbox/models/s3gen/utils/mask.py +194 -0
  28. chatterbox/models/s3gen/utils/mel.py +85 -0
  29. chatterbox/models/s3gen/xvector.py +428 -0
  30. chatterbox/models/s3tokenizer/__init__.py +30 -0
  31. chatterbox/models/s3tokenizer/s3tokenizer.py +168 -0
  32. chatterbox/models/t3/__init__.py +1 -0
  33. chatterbox/models/t3/inference/alignment_stream_analyzer.py +181 -0
  34. chatterbox/models/t3/inference/t3_hf_backend.py +116 -0
  35. chatterbox/models/t3/llama_configs.py +73 -0
  36. chatterbox/models/t3/modules/cond_enc.py +97 -0
  37. chatterbox/models/t3/modules/learned_pos_emb.py +32 -0
  38. chatterbox/models/t3/modules/perceiver.py +212 -0
  39. chatterbox/models/t3/modules/t3_config.py +41 -0
  40. chatterbox/models/t3/t3.py +490 -0
  41. chatterbox/models/tokenizers/__init__.py +1 -0
  42. chatterbox/models/tokenizers/tokenizer.py +313 -0
  43. chatterbox/models/utils.py +4 -0
  44. chatterbox/models/voice_encoder/__init__.py +1 -0
  45. chatterbox/models/voice_encoder/config.py +18 -0
  46. chatterbox/models/voice_encoder/melspec.py +78 -0
  47. chatterbox/models/voice_encoder/voice_encoder.py +274 -0
  48. chatterbox/mtl_tts.py +317 -0
  49. chatterbox/tts.py +272 -0
  50. chatterbox/tts_turbo.py +296 -0
  51. chatterbox/vc.py +104 -0
  52. videopython_chatterbox-0.1.7.post1.dist-info/METADATA +154 -0
  53. videopython_chatterbox-0.1.7.post1.dist-info/RECORD +56 -0
  54. videopython_chatterbox-0.1.7.post1.dist-info/WHEEL +4 -0
  55. videopython_chatterbox-0.1.7.post1.dist-info/licenses/LICENSE +21 -0
  56. videopython_chatterbox-0.1.7.post1.dist-info/licenses/NOTICE +29 -0
chatterbox/mtl_tts.py ADDED
@@ -0,0 +1,317 @@
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
9
+ from safetensors.torch import load_file as load_safetensors
10
+ from huggingface_hub import snapshot_download
11
+
12
+ from .models.t3 import T3
13
+ from .models.t3.modules.t3_config import T3Config
14
+ from .models.s3tokenizer import S3_SR, drop_invalid_tokens
15
+ from .models.s3gen import S3GEN_SR, S3Gen
16
+ from .models.tokenizers import MTLTokenizer
17
+ from .models.voice_encoder import VoiceEncoder
18
+ from .models.t3.modules.cond_enc import T3Cond
19
+
20
+
21
+ REPO_ID = "ResembleAI/chatterbox"
22
+
23
+ # Supported languages for the multilingual model
24
+ SUPPORTED_LANGUAGES = {
25
+ "ar": "Arabic",
26
+ "da": "Danish",
27
+ "de": "German",
28
+ "el": "Greek",
29
+ "en": "English",
30
+ "es": "Spanish",
31
+ "fi": "Finnish",
32
+ "fr": "French",
33
+ "he": "Hebrew",
34
+ "hi": "Hindi",
35
+ "it": "Italian",
36
+ "ja": "Japanese",
37
+ "ko": "Korean",
38
+ "ms": "Malay",
39
+ "nl": "Dutch",
40
+ "no": "Norwegian",
41
+ "pl": "Polish",
42
+ "pt": "Portuguese",
43
+ "ru": "Russian",
44
+ "sv": "Swedish",
45
+ "sw": "Swahili",
46
+ "tr": "Turkish",
47
+ "zh": "Chinese",
48
+ }
49
+
50
+
51
+ def punc_norm(text: str) -> str:
52
+ """
53
+ Quick cleanup func for punctuation from LLMs or
54
+ containing chars not seen often in the dataset
55
+ """
56
+ if len(text) == 0:
57
+ return "You need to add some text for me to talk."
58
+
59
+ # Capitalise first letter
60
+ if text[0].islower():
61
+ text = text[0].upper() + text[1:]
62
+
63
+ # Remove multiple space chars
64
+ text = " ".join(text.split())
65
+
66
+ # Replace uncommon/llm punc
67
+ punc_to_replace = [
68
+ ("...", ", "),
69
+ ("…", ", "),
70
+ (":", ","),
71
+ (" - ", ", "),
72
+ (";", ", "),
73
+ ("—", "-"),
74
+ ("–", "-"),
75
+ (" ,", ","),
76
+ ("“", "\""),
77
+ ("”", "\""),
78
+ ("‘", "'"),
79
+ ("’", "'"),
80
+ ]
81
+ for old_char_sequence, new_char in punc_to_replace:
82
+ text = text.replace(old_char_sequence, new_char)
83
+
84
+ # Add full stop if no ending punc
85
+ text = text.rstrip(" ")
86
+ sentence_enders = {".", "!", "?", "-", ",","、",",","。","?","!"}
87
+ if not any(text.endswith(p) for p in sentence_enders):
88
+ text += "."
89
+
90
+ return text
91
+
92
+
93
+ @dataclass
94
+ class Conditionals:
95
+ """
96
+ Conditionals for T3 and S3Gen
97
+ - T3 conditionals:
98
+ - speaker_emb
99
+ - clap_emb
100
+ - cond_prompt_speech_tokens
101
+ - cond_prompt_speech_emb
102
+ - emotion_adv
103
+ - S3Gen conditionals:
104
+ - prompt_token
105
+ - prompt_token_len
106
+ - prompt_feat
107
+ - prompt_feat_len
108
+ - embedding
109
+ """
110
+ t3: T3Cond
111
+ gen: dict
112
+
113
+ def to(self, device):
114
+ self.t3 = self.t3.to(device=device)
115
+ for k, v in self.gen.items():
116
+ if torch.is_tensor(v):
117
+ self.gen[k] = v.to(device=device)
118
+ return self
119
+
120
+ def save(self, fpath: Path):
121
+ arg_dict = dict(
122
+ t3=self.t3.__dict__,
123
+ gen=self.gen
124
+ )
125
+ torch.save(arg_dict, fpath)
126
+
127
+ @classmethod
128
+ def load(cls, fpath, map_location="cpu"):
129
+ if isinstance(map_location, str):
130
+ map_location = torch.device(map_location)
131
+ kwargs = torch.load(fpath, map_location=map_location, weights_only=True)
132
+ return cls(T3Cond(**kwargs['t3']), kwargs['gen'])
133
+
134
+
135
+ class ChatterboxMultilingualTTS:
136
+ ENC_COND_LEN = 6 * S3_SR
137
+ DEC_COND_LEN = 10 * S3GEN_SR
138
+
139
+ def __init__(
140
+ self,
141
+ t3: T3,
142
+ s3gen: S3Gen,
143
+ ve: VoiceEncoder,
144
+ tokenizer: MTLTokenizer,
145
+ device: str,
146
+ conds: Conditionals = None,
147
+ ):
148
+ self.sr = S3GEN_SR # sample rate of synthesized audio
149
+ self.t3 = t3
150
+ self.s3gen = s3gen
151
+ self.ve = ve
152
+ self.tokenizer = tokenizer
153
+ self.device = device
154
+ self.conds = conds
155
+ self.watermarker = perth.PerthImplicitWatermarker()
156
+
157
+ @classmethod
158
+ def get_supported_languages(cls):
159
+ """Return dictionary of supported language codes and names."""
160
+ return SUPPORTED_LANGUAGES.copy()
161
+
162
+ @classmethod
163
+ def from_local(cls, ckpt_dir, device) -> 'ChatterboxMultilingualTTS':
164
+ ckpt_dir = Path(ckpt_dir)
165
+
166
+ # Always load to CPU first for non-CUDA devices to handle CUDA-saved models
167
+ if device in ["cpu", "mps"]:
168
+ map_location = torch.device('cpu')
169
+ else:
170
+ map_location = None
171
+
172
+ ve = VoiceEncoder()
173
+ ve.load_state_dict(
174
+ torch.load(ckpt_dir / "ve.pt", map_location=map_location, weights_only=True)
175
+ )
176
+ ve.to(device).eval()
177
+
178
+ t3 = T3(T3Config.multilingual())
179
+ t3_state = load_safetensors(ckpt_dir / "t3_mtl23ls_v2.safetensors")
180
+ if "model" in t3_state.keys():
181
+ t3_state = t3_state["model"][0]
182
+ t3.load_state_dict(t3_state)
183
+ t3.to(device).eval()
184
+
185
+ s3gen = S3Gen()
186
+ s3gen.load_state_dict(
187
+ torch.load(ckpt_dir / "s3gen.pt", map_location=map_location, weights_only=True)
188
+ )
189
+ s3gen.to(device).eval()
190
+
191
+ tokenizer = MTLTokenizer(
192
+ str(ckpt_dir / "grapheme_mtl_merged_expanded_v1.json")
193
+ )
194
+
195
+ conds = None
196
+ if (builtin_voice := ckpt_dir / "conds.pt").exists():
197
+ conds = Conditionals.load(builtin_voice, map_location=map_location).to(device)
198
+
199
+ return cls(t3, s3gen, ve, tokenizer, device, conds=conds)
200
+
201
+ @classmethod
202
+ def from_pretrained(cls, device: torch.device) -> 'ChatterboxMultilingualTTS':
203
+ # Check if MPS is available on macOS
204
+ if device == "mps" and not torch.backends.mps.is_available():
205
+ if not torch.backends.mps.is_built():
206
+ print("MPS not available because the current PyTorch install was not built with MPS enabled.")
207
+ else:
208
+ print("MPS not available because the current MacOS version is not 12.3+ and/or you do not have an MPS-enabled device on this machine.")
209
+ device = "cpu"
210
+
211
+ ckpt_dir = Path(
212
+ snapshot_download(
213
+ repo_id=REPO_ID,
214
+ repo_type="model",
215
+ revision="main",
216
+ allow_patterns=["ve.pt", "t3_mtl23ls_v2.safetensors", "s3gen.pt", "grapheme_mtl_merged_expanded_v1.json", "conds.pt", "Cangjie5_TC.json"],
217
+ token=os.getenv("HF_TOKEN"),
218
+ )
219
+ )
220
+ return cls.from_local(ckpt_dir, device)
221
+
222
+ def prepare_conditionals(self, wav_fpath, exaggeration=0.5):
223
+ ## Load reference wav
224
+ s3gen_ref_wav, _sr = librosa.load(wav_fpath, sr=S3GEN_SR)
225
+
226
+ ref_16k_wav = librosa.resample(s3gen_ref_wav, orig_sr=S3GEN_SR, target_sr=S3_SR)
227
+
228
+ s3gen_ref_wav = s3gen_ref_wav[:self.DEC_COND_LEN]
229
+ s3gen_ref_dict = self.s3gen.embed_ref(s3gen_ref_wav, S3GEN_SR, device=self.device)
230
+
231
+ # Speech cond prompt tokens
232
+ t3_cond_prompt_tokens = None
233
+ if plen := self.t3.hp.speech_cond_prompt_len:
234
+ s3_tokzr = self.s3gen.tokenizer
235
+ t3_cond_prompt_tokens, _ = s3_tokzr.forward([ref_16k_wav[:self.ENC_COND_LEN]], max_len=plen)
236
+ t3_cond_prompt_tokens = torch.atleast_2d(t3_cond_prompt_tokens).to(self.device)
237
+
238
+ # Voice-encoder speaker embedding
239
+ ve_embed = torch.from_numpy(self.ve.embeds_from_wavs([ref_16k_wav], sample_rate=S3_SR))
240
+ ve_embed = ve_embed.mean(axis=0, keepdim=True).to(self.device)
241
+
242
+ t3_cond = T3Cond(
243
+ speaker_emb=ve_embed,
244
+ cond_prompt_speech_tokens=t3_cond_prompt_tokens,
245
+ emotion_adv=exaggeration * torch.ones(1, 1, 1),
246
+ ).to(device=self.device)
247
+ self.conds = Conditionals(t3_cond, s3gen_ref_dict)
248
+
249
+ def generate(
250
+ self,
251
+ text,
252
+ language_id,
253
+ audio_prompt_path=None,
254
+ exaggeration=0.5,
255
+ cfg_weight=0.5,
256
+ temperature=0.8,
257
+ repetition_penalty=2.0,
258
+ min_p=0.05,
259
+ top_p=1.0,
260
+ ):
261
+ # Validate language_id
262
+ if language_id and language_id.lower() not in SUPPORTED_LANGUAGES:
263
+ supported_langs = ", ".join(SUPPORTED_LANGUAGES.keys())
264
+ raise ValueError(
265
+ f"Unsupported language_id '{language_id}'. "
266
+ f"Supported languages: {supported_langs}"
267
+ )
268
+
269
+ if audio_prompt_path:
270
+ self.prepare_conditionals(audio_prompt_path, exaggeration=exaggeration)
271
+ else:
272
+ assert self.conds is not None, "Please `prepare_conditionals` first or specify `audio_prompt_path`"
273
+
274
+ # Update exaggeration if needed
275
+ if float(exaggeration) != float(self.conds.t3.emotion_adv[0, 0, 0].item()):
276
+ _cond: T3Cond = self.conds.t3
277
+ self.conds.t3 = T3Cond(
278
+ speaker_emb=_cond.speaker_emb,
279
+ cond_prompt_speech_tokens=_cond.cond_prompt_speech_tokens,
280
+ emotion_adv=exaggeration * torch.ones(1, 1, 1),
281
+ ).to(device=self.device)
282
+
283
+ # Norm and tokenize text
284
+ text = punc_norm(text)
285
+ text_tokens = self.tokenizer.text_to_tokens(text, language_id=language_id.lower() if language_id else None).to(self.device)
286
+ text_tokens = torch.cat([text_tokens, text_tokens], dim=0) # Need two seqs for CFG
287
+
288
+ sot = self.t3.hp.start_text_token
289
+ eot = self.t3.hp.stop_text_token
290
+ text_tokens = F.pad(text_tokens, (1, 0), value=sot)
291
+ text_tokens = F.pad(text_tokens, (0, 1), value=eot)
292
+
293
+ with torch.inference_mode():
294
+ speech_tokens = self.t3.inference(
295
+ t3_cond=self.conds.t3,
296
+ text_tokens=text_tokens,
297
+ max_new_tokens=1000, # TODO: use the value in config
298
+ temperature=temperature,
299
+ cfg_weight=cfg_weight,
300
+ repetition_penalty=repetition_penalty,
301
+ min_p=min_p,
302
+ top_p=top_p,
303
+ )
304
+ # Extract only the conditional batch.
305
+ speech_tokens = speech_tokens[0]
306
+
307
+ # TODO: output becomes 1D
308
+ speech_tokens = drop_invalid_tokens(speech_tokens)
309
+ speech_tokens = speech_tokens.to(self.device)
310
+
311
+ wav, _ = self.s3gen.inference(
312
+ speech_tokens=speech_tokens,
313
+ ref_dict=self.conds.gen,
314
+ )
315
+ wav = wav.squeeze(0).detach().cpu().numpy()
316
+ watermarked_wav = self.watermarker.apply_watermark(wav, sample_rate=self.sr)
317
+ return torch.from_numpy(watermarked_wav).unsqueeze(0)
chatterbox/tts.py ADDED
@@ -0,0 +1,272 @@
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+
4
+ import librosa
5
+ import torch
6
+ import perth
7
+ import torch.nn.functional as F
8
+ from huggingface_hub import hf_hub_download
9
+ from safetensors.torch import load_file
10
+
11
+ from .models.t3 import T3
12
+ from .models.s3tokenizer import S3_SR, drop_invalid_tokens
13
+ from .models.s3gen import S3GEN_SR, S3Gen
14
+ from .models.tokenizers import EnTokenizer
15
+ from .models.voice_encoder import VoiceEncoder
16
+ from .models.t3.modules.cond_enc import T3Cond
17
+
18
+
19
+ REPO_ID = "ResembleAI/chatterbox"
20
+
21
+
22
+ def punc_norm(text: str) -> str:
23
+ """
24
+ Quick cleanup func for punctuation from LLMs or
25
+ containing chars not seen often in the dataset
26
+ """
27
+ if len(text) == 0:
28
+ return "You need to add some text for me to talk."
29
+
30
+ # Capitalise first letter
31
+ if text[0].islower():
32
+ text = text[0].upper() + text[1:]
33
+
34
+ # Remove multiple space chars
35
+ text = " ".join(text.split())
36
+
37
+ # Replace uncommon/llm punc
38
+ punc_to_replace = [
39
+ ("...", ", "),
40
+ ("…", ", "),
41
+ (":", ","),
42
+ (" - ", ", "),
43
+ (";", ", "),
44
+ ("—", "-"),
45
+ ("–", "-"),
46
+ (" ,", ","),
47
+ ("“", "\""),
48
+ ("”", "\""),
49
+ ("‘", "'"),
50
+ ("’", "'"),
51
+ ]
52
+ for old_char_sequence, new_char in punc_to_replace:
53
+ text = text.replace(old_char_sequence, new_char)
54
+
55
+ # Add full stop if no ending punc
56
+ text = text.rstrip(" ")
57
+ sentence_enders = {".", "!", "?", "-", ","}
58
+ if not any(text.endswith(p) for p in sentence_enders):
59
+ text += "."
60
+
61
+ return text
62
+
63
+
64
+ @dataclass
65
+ class Conditionals:
66
+ """
67
+ Conditionals for T3 and S3Gen
68
+ - T3 conditionals:
69
+ - speaker_emb
70
+ - clap_emb
71
+ - cond_prompt_speech_tokens
72
+ - cond_prompt_speech_emb
73
+ - emotion_adv
74
+ - S3Gen conditionals:
75
+ - prompt_token
76
+ - prompt_token_len
77
+ - prompt_feat
78
+ - prompt_feat_len
79
+ - embedding
80
+ """
81
+ t3: T3Cond
82
+ gen: dict
83
+
84
+ def to(self, device):
85
+ self.t3 = self.t3.to(device=device)
86
+ for k, v in self.gen.items():
87
+ if torch.is_tensor(v):
88
+ self.gen[k] = v.to(device=device)
89
+ return self
90
+
91
+ def save(self, fpath: Path):
92
+ arg_dict = dict(
93
+ t3=self.t3.__dict__,
94
+ gen=self.gen
95
+ )
96
+ torch.save(arg_dict, fpath)
97
+
98
+ @classmethod
99
+ def load(cls, fpath, map_location="cpu"):
100
+ if isinstance(map_location, str):
101
+ map_location = torch.device(map_location)
102
+ kwargs = torch.load(fpath, map_location=map_location, weights_only=True)
103
+ return cls(T3Cond(**kwargs['t3']), kwargs['gen'])
104
+
105
+
106
+ class ChatterboxTTS:
107
+ ENC_COND_LEN = 6 * S3_SR
108
+ DEC_COND_LEN = 10 * S3GEN_SR
109
+
110
+ def __init__(
111
+ self,
112
+ t3: T3,
113
+ s3gen: S3Gen,
114
+ ve: VoiceEncoder,
115
+ tokenizer: EnTokenizer,
116
+ device: str,
117
+ conds: Conditionals = None,
118
+ ):
119
+ self.sr = S3GEN_SR # sample rate of synthesized audio
120
+ self.t3 = t3
121
+ self.s3gen = s3gen
122
+ self.ve = ve
123
+ self.tokenizer = tokenizer
124
+ self.device = device
125
+ self.conds = conds
126
+ self.watermarker = perth.PerthImplicitWatermarker()
127
+
128
+ @classmethod
129
+ def from_local(cls, ckpt_dir, device) -> 'ChatterboxTTS':
130
+ ckpt_dir = Path(ckpt_dir)
131
+
132
+ # Always load to CPU first for non-CUDA devices to handle CUDA-saved models
133
+ if device in ["cpu", "mps"]:
134
+ map_location = torch.device('cpu')
135
+ else:
136
+ map_location = None
137
+
138
+ ve = VoiceEncoder()
139
+ ve.load_state_dict(
140
+ load_file(ckpt_dir / "ve.safetensors")
141
+ )
142
+ ve.to(device).eval()
143
+
144
+ t3 = T3()
145
+ t3_state = load_file(ckpt_dir / "t3_cfg.safetensors")
146
+ if "model" in t3_state.keys():
147
+ t3_state = t3_state["model"][0]
148
+ t3.load_state_dict(t3_state)
149
+ t3.to(device).eval()
150
+
151
+ s3gen = S3Gen()
152
+ s3gen.load_state_dict(
153
+ load_file(ckpt_dir / "s3gen.safetensors"), strict=False
154
+ )
155
+ s3gen.to(device).eval()
156
+
157
+ tokenizer = EnTokenizer(
158
+ str(ckpt_dir / "tokenizer.json")
159
+ )
160
+
161
+ conds = None
162
+ if (builtin_voice := ckpt_dir / "conds.pt").exists():
163
+ conds = Conditionals.load(builtin_voice, map_location=map_location).to(device)
164
+
165
+ return cls(t3, s3gen, ve, tokenizer, device, conds=conds)
166
+
167
+ @classmethod
168
+ def from_pretrained(cls, device) -> 'ChatterboxTTS':
169
+ # Check if MPS is available on macOS
170
+ if device == "mps" and not torch.backends.mps.is_available():
171
+ if not torch.backends.mps.is_built():
172
+ print("MPS not available because the current PyTorch install was not built with MPS enabled.")
173
+ else:
174
+ print("MPS not available because the current MacOS version is not 12.3+ and/or you do not have an MPS-enabled device on this machine.")
175
+ device = "cpu"
176
+
177
+ for fpath in ["ve.safetensors", "t3_cfg.safetensors", "s3gen.safetensors", "tokenizer.json", "conds.pt"]:
178
+ local_path = hf_hub_download(repo_id=REPO_ID, filename=fpath)
179
+
180
+ return cls.from_local(Path(local_path).parent, device)
181
+
182
+ def prepare_conditionals(self, wav_fpath, exaggeration=0.5):
183
+ ## Load reference wav
184
+ s3gen_ref_wav, _sr = librosa.load(wav_fpath, sr=S3GEN_SR)
185
+
186
+ ref_16k_wav = librosa.resample(s3gen_ref_wav, orig_sr=S3GEN_SR, target_sr=S3_SR)
187
+
188
+ s3gen_ref_wav = s3gen_ref_wav[:self.DEC_COND_LEN]
189
+ s3gen_ref_dict = self.s3gen.embed_ref(s3gen_ref_wav, S3GEN_SR, device=self.device)
190
+
191
+ # Speech cond prompt tokens
192
+ if plen := self.t3.hp.speech_cond_prompt_len:
193
+ s3_tokzr = self.s3gen.tokenizer
194
+ t3_cond_prompt_tokens, _ = s3_tokzr.forward([ref_16k_wav[:self.ENC_COND_LEN]], max_len=plen)
195
+ t3_cond_prompt_tokens = torch.atleast_2d(t3_cond_prompt_tokens).to(self.device)
196
+
197
+ # Voice-encoder speaker embedding
198
+ ve_embed = torch.from_numpy(self.ve.embeds_from_wavs([ref_16k_wav], sample_rate=S3_SR))
199
+ ve_embed = ve_embed.mean(axis=0, keepdim=True).to(self.device)
200
+
201
+ t3_cond = T3Cond(
202
+ speaker_emb=ve_embed,
203
+ cond_prompt_speech_tokens=t3_cond_prompt_tokens,
204
+ emotion_adv=exaggeration * torch.ones(1, 1, 1),
205
+ ).to(device=self.device)
206
+ self.conds = Conditionals(t3_cond, s3gen_ref_dict)
207
+
208
+ def generate(
209
+ self,
210
+ text,
211
+ repetition_penalty=1.2,
212
+ min_p=0.05,
213
+ top_p=1.0,
214
+ audio_prompt_path=None,
215
+ exaggeration=0.5,
216
+ cfg_weight=0.5,
217
+ temperature=0.8,
218
+ ):
219
+ if audio_prompt_path:
220
+ self.prepare_conditionals(audio_prompt_path, exaggeration=exaggeration)
221
+ else:
222
+ assert self.conds is not None, "Please `prepare_conditionals` first or specify `audio_prompt_path`"
223
+
224
+ # Update exaggeration if needed
225
+ if exaggeration != self.conds.t3.emotion_adv[0, 0, 0]:
226
+ _cond: T3Cond = self.conds.t3
227
+ self.conds.t3 = T3Cond(
228
+ speaker_emb=_cond.speaker_emb,
229
+ cond_prompt_speech_tokens=_cond.cond_prompt_speech_tokens,
230
+ emotion_adv=exaggeration * torch.ones(1, 1, 1),
231
+ ).to(device=self.device)
232
+
233
+ # Norm and tokenize text
234
+ text = punc_norm(text)
235
+ text_tokens = self.tokenizer.text_to_tokens(text).to(self.device)
236
+
237
+ if cfg_weight > 0.0:
238
+ text_tokens = torch.cat([text_tokens, text_tokens], dim=0) # Need two seqs for CFG
239
+
240
+ sot = self.t3.hp.start_text_token
241
+ eot = self.t3.hp.stop_text_token
242
+ text_tokens = F.pad(text_tokens, (1, 0), value=sot)
243
+ text_tokens = F.pad(text_tokens, (0, 1), value=eot)
244
+
245
+ with torch.inference_mode():
246
+ speech_tokens = self.t3.inference(
247
+ t3_cond=self.conds.t3,
248
+ text_tokens=text_tokens,
249
+ max_new_tokens=1000, # TODO: use the value in config
250
+ temperature=temperature,
251
+ cfg_weight=cfg_weight,
252
+ repetition_penalty=repetition_penalty,
253
+ min_p=min_p,
254
+ top_p=top_p,
255
+ )
256
+ # Extract only the conditional batch.
257
+ speech_tokens = speech_tokens[0]
258
+
259
+ # TODO: output becomes 1D
260
+ speech_tokens = drop_invalid_tokens(speech_tokens)
261
+
262
+ speech_tokens = speech_tokens[speech_tokens < 6561]
263
+
264
+ speech_tokens = speech_tokens.to(self.device)
265
+
266
+ wav, _ = self.s3gen.inference(
267
+ speech_tokens=speech_tokens,
268
+ ref_dict=self.conds.gen,
269
+ )
270
+ wav = wav.squeeze(0).detach().cpu().numpy()
271
+ watermarked_wav = self.watermarker.apply_watermark(wav, sample_rate=self.sr)
272
+ return torch.from_numpy(watermarked_wav).unsqueeze(0)