rlellep commited on
Commit
99341ef
·
verified ·
1 Parent(s): aa1f73d

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -1
  2. README.md +15 -5
  3. TTS/__init__.py +33 -0
  4. TTS/__pycache__/__init__.cpython-310.pyc +0 -0
  5. TTS/__pycache__/__init__.cpython-311.pyc +0 -0
  6. TTS/__pycache__/__init__.cpython-39.pyc +0 -0
  7. TTS/__pycache__/model.cpython-310.pyc +0 -0
  8. TTS/__pycache__/model.cpython-311.pyc +0 -0
  9. TTS/__pycache__/model.cpython-39.pyc +0 -0
  10. TTS/api.py +568 -0
  11. TTS/bin/__init__.py +0 -0
  12. TTS/bin/collect_env_info.py +49 -0
  13. TTS/bin/compute_attention_masks.py +170 -0
  14. TTS/bin/compute_embeddings.py +209 -0
  15. TTS/bin/compute_statistics.py +104 -0
  16. TTS/bin/eval_encoder.py +93 -0
  17. TTS/bin/extract_tts_spectrograms.py +304 -0
  18. TTS/bin/find_unique_chars.py +41 -0
  19. TTS/bin/find_unique_phonemes.py +87 -0
  20. TTS/bin/remove_silence_using_vad.py +129 -0
  21. TTS/bin/resample.py +90 -0
  22. TTS/bin/synthesize.py +432 -0
  23. TTS/bin/train_encoder.py +432 -0
  24. TTS/bin/train_tts.py +77 -0
  25. TTS/bin/train_vocoder.py +83 -0
  26. TTS/bin/tune_wavegrad.py +108 -0
  27. TTS/config/__init__.py +143 -0
  28. TTS/config/__pycache__/__init__.cpython-310.pyc +0 -0
  29. TTS/config/__pycache__/__init__.cpython-311.pyc +0 -0
  30. TTS/config/__pycache__/__init__.cpython-39.pyc +0 -0
  31. TTS/config/__pycache__/shared_configs.cpython-310.pyc +0 -0
  32. TTS/config/__pycache__/shared_configs.cpython-311.pyc +0 -0
  33. TTS/config/__pycache__/shared_configs.cpython-39.pyc +0 -0
  34. TTS/config/shared_configs.py +267 -0
  35. TTS/demos/xtts_ft_demo/README.md +1 -0
  36. TTS/demos/xtts_ft_demo/XTTS_finetune_colab.ipynb +176 -0
  37. TTS/demos/xtts_ft_demo/requirements.txt +2 -0
  38. TTS/demos/xtts_ft_demo/utils/formatter.py +161 -0
  39. TTS/demos/xtts_ft_demo/utils/gpt_train.py +172 -0
  40. TTS/demos/xtts_ft_demo/xtts_demo.py +442 -0
  41. TTS/encoder/README.md +18 -0
  42. TTS/encoder/__init__.py +0 -0
  43. TTS/encoder/__pycache__/__init__.cpython-310.pyc +0 -0
  44. TTS/encoder/__pycache__/__init__.cpython-311.pyc +0 -0
  45. TTS/encoder/__pycache__/__init__.cpython-39.pyc +0 -0
  46. TTS/encoder/__pycache__/losses.cpython-310.pyc +0 -0
  47. TTS/encoder/__pycache__/losses.cpython-311.pyc +0 -0
  48. TTS/encoder/__pycache__/losses.cpython-39.pyc +0 -0
  49. TTS/encoder/configs/base_encoder_config.py +60 -0
  50. TTS/encoder/configs/emotion_encoder_config.py +12 -0
.gitattributes CHANGED
@@ -32,4 +32,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.xz 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
 
32
  *.xz 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
README.md CHANGED
@@ -1,5 +1,15 @@
1
- ---
2
- license: other
3
- license_name: coqui-public-model-license
4
- license_link: https://coqui.ai/cpml
5
- ---
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: XTTSv2 Est
3
+ emoji: 🐸
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.41.0
8
+ python_version: 3.11
9
+ app_file: app.py
10
+ pinned: false
11
+ license: other
12
+ short_description: XTTS v2 finetuned on Estonian data
13
+ ---
14
+
15
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
TTS/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+
3
+ from TTS.utils.generic_utils import is_pytorch_at_least_2_4
4
+
5
+ __version__ = "0.27.1"
6
+
7
+ if "coqpit" in importlib.metadata.packages_distributions().get("coqpit", []):
8
+ msg = (
9
+ "coqui-tts switched to a forked version of Coqpit, but you still have the original "
10
+ "package installed. Run the following to avoid conflicts:\n"
11
+ " pip uninstall coqpit\n"
12
+ " pip install coqpit-config"
13
+ )
14
+ raise ImportError(msg)
15
+
16
+
17
+ if is_pytorch_at_least_2_4():
18
+ import _codecs
19
+ from collections import defaultdict
20
+
21
+ import numpy as np
22
+ import torch
23
+ from packaging import version
24
+
25
+ from TTS.config.shared_configs import BaseDatasetConfig
26
+ from TTS.tts.configs.xtts_config import XttsConfig
27
+ from TTS.tts.models.xtts import XttsArgs, XttsAudioConfig
28
+ from TTS.utils.radam import RAdam
29
+
30
+ torch.serialization.add_safe_globals([dict, defaultdict, RAdam])
31
+
32
+ # XTTS
33
+ torch.serialization.add_safe_globals([BaseDatasetConfig, XttsConfig, XttsAudioConfig, XttsArgs])
TTS/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (890 Bytes). View file
 
TTS/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (1.63 kB). View file
 
TTS/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (882 Bytes). View file
 
TTS/__pycache__/model.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
TTS/__pycache__/model.cpython-311.pyc ADDED
Binary file (3.93 kB). View file
 
TTS/__pycache__/model.cpython-39.pyc ADDED
Binary file (2.75 kB). View file
 
TTS/api.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Coqui TTS Python API."""
2
+
3
+ import logging
4
+ import os
5
+ import tempfile
6
+ import warnings
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from torch import nn
11
+
12
+ from TTS.config import load_config
13
+ from TTS.utils.manage import ModelManager
14
+ from TTS.utils.synthesizer import Synthesizer
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class TTS(nn.Module):
20
+ """Coqui Python API."""
21
+
22
+ def __init__(
23
+ self,
24
+ model_name: str = "",
25
+ *,
26
+ model_path: str | None = None,
27
+ config_path: str | None = None,
28
+ vocoder_name: str | None = None,
29
+ vocoder_path: str | None = None,
30
+ vocoder_config_path: str | None = None,
31
+ encoder_path: str | None = None,
32
+ encoder_config_path: str | None = None,
33
+ speakers_file_path: str | None = None,
34
+ language_ids_file_path: str | None = None,
35
+ progress_bar: bool = True,
36
+ gpu: bool = False,
37
+ ) -> None:
38
+ """🐸TTS python interface that allows to load and use the released models.
39
+
40
+ Example with a multi-speaker model:
41
+ >>> from TTS.api import TTS
42
+ >>> tts = TTS(TTS.list_models()[0])
43
+ >>> wav = tts.tts("This is a test! This is also a test!!", speaker=tts.speakers[0], language=tts.languages[0])
44
+ >>> tts.tts_to_file(text="Hello world!", speaker=tts.speakers[0], language=tts.languages[0], file_path="output.wav")
45
+
46
+ Example with a single-speaker model:
47
+ >>> tts = TTS(model_name="tts_models/de/thorsten/tacotron2-DDC", progress_bar=False)
48
+ >>> tts.tts_to_file(text="Ich bin eine Testnachricht.", file_path="output.wav")
49
+
50
+ Example loading a model from a path:
51
+ >>> tts = TTS(model_path="/path/to/checkpoint_100000.pth", config_path="/path/to/config.json", progress_bar=False)
52
+ >>> tts.tts_to_file(text="Ich bin eine Testnachricht.", file_path="output.wav")
53
+
54
+ Example voice cloning with YourTTS in English, French and Portuguese:
55
+ >>> tts = TTS(model_name="tts_models/multilingual/multi-dataset/your_tts", progress_bar=False).to("cuda")
56
+ >>> tts.tts_to_file("This is voice cloning.", speaker_wav="my/cloning/audio.wav", language="en", file_path="thisisit.wav")
57
+ >>> tts.tts_to_file("C'est le clonage de la voix.", speaker_wav="my/cloning/audio.wav", language="fr", file_path="thisisit.wav")
58
+ >>> tts.tts_to_file("Isso é clonagem de voz.", speaker_wav="my/cloning/audio.wav", language="pt", file_path="thisisit.wav")
59
+
60
+ Example Fairseq TTS models (uses ISO language codes in https://dl.fbaipublicfiles.com/mms/tts/all-tts-languages.html):
61
+ >>> tts = TTS(model_name="tts_models/eng/fairseq/vits", progress_bar=False).to("cuda")
62
+ >>> tts.tts_to_file("This is a test.", file_path="output.wav")
63
+
64
+ Args:
65
+ model_name (str, optional): Model name to load. You can list models by ```tts.models```. Defaults to None.
66
+ model_path (str, optional): Path to the model checkpoint. Defaults to None.
67
+ config_path (str, optional): Path to the model config. Defaults to None.
68
+ vocoder_name (str, optional): Pre-trained vocoder to use. Defaults to None, i.e. using the default vocoder.
69
+ vocoder_path (str, optional): Path to the vocoder checkpoint. Defaults to None.
70
+ vocoder_config_path (str, optional): Path to the vocoder config. Defaults to None.
71
+ encoder_path: Path to speaker encoder checkpoint. Default to None.
72
+ encoder_config_path: Path to speaker encoder config file. Defaults to None.
73
+ speakers_file_path: JSON file for multi-speaker model. Defaults to None.
74
+ language_ids_file_path: JSON file for multilingual model. Defaults to None
75
+ progress_bar (bool, optional): Whether to print a progress bar while downloading a model. Defaults to True.
76
+ gpu (bool, optional): Enable/disable GPU. Defaults to False. DEPRECATED, use TTS(...).to("cuda")
77
+ """
78
+ super().__init__()
79
+ self.manager = ModelManager(models_file=self.get_models_file_path(), progress_bar=progress_bar)
80
+ self.config = load_config(config_path) if config_path else None
81
+ self.synthesizer: Synthesizer | None = None
82
+ self.voice_converter: Synthesizer | None = None
83
+ self.model_name = ""
84
+
85
+ self.vocoder_path = vocoder_path
86
+ self.vocoder_config_path = vocoder_config_path
87
+ self.encoder_path = encoder_path
88
+ self.encoder_config_path = encoder_config_path
89
+ self.speakers_file_path = speakers_file_path
90
+ self.language_ids_file_path = language_ids_file_path
91
+
92
+ if gpu:
93
+ warnings.warn("`gpu` will be deprecated. Please use `tts.to(device)` instead.")
94
+
95
+ if model_name is not None and len(model_name) > 0:
96
+ if "tts_models" in model_name:
97
+ self.load_tts_model_by_name(model_name, vocoder_name, gpu=gpu)
98
+ elif "voice_conversion_models" in model_name:
99
+ self.load_vc_model_by_name(model_name, vocoder_name, gpu=gpu)
100
+ # To allow just TTS("xtts")
101
+ else:
102
+ self.load_model_by_name(model_name, vocoder_name, gpu=gpu)
103
+
104
+ if model_path:
105
+ self.load_tts_model_by_path(model_path, config_path, gpu=gpu)
106
+
107
+ @property
108
+ def models(self) -> list[str]:
109
+ return self.manager.list_tts_models()
110
+
111
+ @property
112
+ def is_multi_speaker(self) -> bool:
113
+ if self.synthesizer is not None:
114
+ if self.synthesizer.tts_model.config.supports_cloning:
115
+ return True
116
+ if hasattr(self.synthesizer.tts_model, "speaker_manager") and self.synthesizer.tts_model.speaker_manager:
117
+ return self.synthesizer.tts_model.speaker_manager.num_speakers > 1
118
+ return False
119
+
120
+ @property
121
+ def is_multi_lingual(self) -> bool:
122
+ # Not sure what sets this to None, but applied a fix to prevent crashing.
123
+ if (
124
+ isinstance(self.model_name, str)
125
+ and "xtts" in self.model_name
126
+ or self.config
127
+ and ("xtts" in self.config.model or "languages" in self.config and len(self.config.languages) > 1)
128
+ ):
129
+ return True
130
+ if (
131
+ self.synthesizer is not None
132
+ and hasattr(self.synthesizer.tts_model, "language_manager")
133
+ and self.synthesizer.tts_model.language_manager
134
+ ):
135
+ return self.synthesizer.tts_model.language_manager.num_languages > 1
136
+ return False
137
+
138
+ @property
139
+ def speakers(self) -> list[str] | None:
140
+ if not self.is_multi_speaker:
141
+ return None
142
+ speakers = []
143
+ if self.synthesizer.tts_model.config.supports_cloning:
144
+ speakers.extend(self.synthesizer.tts_model.get_voices(self.synthesizer.voice_dir).keys())
145
+ if self.synthesizer.tts_model.speaker_manager is not None:
146
+ speakers.extend(self.synthesizer.tts_model.speaker_manager.speaker_names)
147
+ return speakers
148
+
149
+ @property
150
+ def languages(self) -> list[str] | None:
151
+ if not self.is_multi_lingual:
152
+ return None
153
+ return self.synthesizer.tts_model.language_manager.language_names
154
+
155
+ @staticmethod
156
+ def get_models_file_path() -> Path:
157
+ return Path(__file__).parent / ".models.json"
158
+
159
+ @staticmethod
160
+ def list_models() -> list[str]:
161
+ return ModelManager(models_file=TTS.get_models_file_path(), progress_bar=False).list_models()
162
+
163
+ def download_model_by_name(
164
+ self, model_name: str, vocoder_name: str | None = None
165
+ ) -> tuple[Path | None, Path | None, Path | None, Path | None, Path | None]:
166
+ model_path, config_path, model_item = self.manager.download_model(model_name)
167
+ if (
168
+ "fairseq" in model_name
169
+ or "openvoice" in model_name
170
+ or (
171
+ model_item is not None
172
+ and isinstance(model_item["model_url"], list)
173
+ and len(model_item["model_url"]) > 2
174
+ )
175
+ ):
176
+ # return model directory if there are multiple files
177
+ # we assume that the model knows how to load itself
178
+ return None, None, None, None, model_path
179
+ if model_item.get("default_vocoder") is None:
180
+ return model_path, config_path, None, None, None
181
+ if vocoder_name is None:
182
+ vocoder_name = model_item["default_vocoder"]
183
+ vocoder_path, vocoder_config_path = None, None
184
+ # A local vocoder model will take precedence if already specified in __init__
185
+ if model_item["model_type"] == "tts_models":
186
+ vocoder_path = self.vocoder_path
187
+ vocoder_config_path = self.vocoder_config_path
188
+ if vocoder_path is None or vocoder_config_path is None:
189
+ vocoder_path, vocoder_config_path, _ = self.manager.download_model(vocoder_name)
190
+ return model_path, config_path, vocoder_path, vocoder_config_path, None
191
+
192
+ def load_model_by_name(self, model_name: str, vocoder_name: str | None = None, *, gpu: bool = False) -> None:
193
+ """Load one of the 🐸TTS models by name.
194
+
195
+ Args:
196
+ model_name (str): Model name to load. You can list models by ```tts.models```.
197
+ gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
198
+ """
199
+ self.load_tts_model_by_name(model_name, vocoder_name, gpu=gpu)
200
+
201
+ def load_vc_model_by_name(self, model_name: str, vocoder_name: str | None = None, *, gpu: bool = False) -> None:
202
+ """Load one of the voice conversion models by name.
203
+
204
+ Args:
205
+ model_name (str): Model name to load. You can list models by ```tts.models```.
206
+ gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
207
+ """
208
+ self.model_name = model_name
209
+ model_path, config_path, vocoder_path, vocoder_config_path, model_dir = self.download_model_by_name(
210
+ model_name, vocoder_name
211
+ )
212
+ self.voice_converter = Synthesizer(
213
+ vc_checkpoint=model_path,
214
+ vc_config=config_path,
215
+ vocoder_checkpoint=vocoder_path,
216
+ vocoder_config=vocoder_config_path,
217
+ model_dir=model_dir,
218
+ use_cuda=gpu,
219
+ )
220
+
221
+ def load_tts_model_by_name(self, model_name: str, vocoder_name: str | None = None, *, gpu: bool = False) -> None:
222
+ """Load one of 🐸TTS models by name.
223
+
224
+ Args:
225
+ model_name (str): Model name to load. You can list models by ```tts.models```.
226
+ gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
227
+
228
+ TODO: Add tests
229
+ """
230
+ self.model_name = model_name
231
+
232
+ model_path, config_path, vocoder_path, vocoder_config_path, model_dir = self.download_model_by_name(
233
+ model_name, vocoder_name
234
+ )
235
+
236
+ # init synthesizer
237
+ # None values are fetch from the model
238
+ self.synthesizer = Synthesizer(
239
+ tts_checkpoint=model_path,
240
+ tts_config_path=config_path,
241
+ tts_speakers_file=None,
242
+ tts_languages_file=None,
243
+ vocoder_checkpoint=vocoder_path,
244
+ vocoder_config=vocoder_config_path,
245
+ encoder_checkpoint=self.encoder_path,
246
+ encoder_config=self.encoder_config_path,
247
+ model_dir=model_dir,
248
+ use_cuda=gpu,
249
+ )
250
+
251
+ def load_tts_model_by_path(self, model_path: str, config_path: str, *, gpu: bool = False) -> None:
252
+ """Load a model from a path.
253
+
254
+ Args:
255
+ model_path (str): Path to the model checkpoint.
256
+ config_path (str): Path to the model config.
257
+ vocoder_path (str, optional): Path to the vocoder checkpoint. Defaults to None.
258
+ vocoder_config (str, optional): Path to the vocoder config. Defaults to None.
259
+ gpu (bool, optional): Enable/disable GPU. Some models might be too slow on CPU. Defaults to False.
260
+ """
261
+
262
+ self.synthesizer = Synthesizer(
263
+ tts_checkpoint=model_path,
264
+ tts_config_path=config_path,
265
+ tts_speakers_file=self.speakers_file_path,
266
+ tts_languages_file=self.language_ids_file_path,
267
+ vocoder_checkpoint=self.vocoder_path,
268
+ vocoder_config=self.vocoder_config_path,
269
+ encoder_checkpoint=self.encoder_path,
270
+ encoder_config=self.encoder_config_path,
271
+ use_cuda=gpu,
272
+ )
273
+
274
+ def _check_arguments(
275
+ self,
276
+ speaker: str | None = None,
277
+ language: str | None = None,
278
+ speaker_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]] | None = None,
279
+ emotion: str | None = None,
280
+ **kwargs,
281
+ ) -> None:
282
+ """Check if the arguments are valid for the model."""
283
+ # check for the coqui tts models
284
+ if self.is_multi_lingual and language is None:
285
+ raise ValueError("Model is multi-lingual but no `language` is provided.")
286
+ if not self.is_multi_speaker and speaker is not None:
287
+ raise ValueError("Model is not multi-speaker but `speaker` is provided.")
288
+ if not self.is_multi_lingual and language is not None:
289
+ raise ValueError("Model is not multi-lingual but `language` is provided.")
290
+ if emotion is not None:
291
+ raise ValueError("Emotion can only be used with Coqui Studio models. Which is discontinued.")
292
+
293
+ def tts(
294
+ self,
295
+ text: str,
296
+ speaker: str | None = None,
297
+ language: str | None = None,
298
+ speaker_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]] | None = None,
299
+ emotion: str | None = None,
300
+ split_sentences: bool = True,
301
+ **kwargs,
302
+ ):
303
+ """Convert text to speech.
304
+
305
+ Args:
306
+ text (str):
307
+ Input text to synthesize.
308
+ speaker (str, optional):
309
+ Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
310
+ `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
311
+ language (str): Language of the text. If None, the default language of the speaker is used. Language is only
312
+ supported by `XTTS` model.
313
+ speaker_wav (str, optional):
314
+ Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
315
+ Defaults to None.
316
+ emotion (str, optional):
317
+ Emotion to use for 🐸Coqui Studio models. If None, Studio models use "Neutral". Defaults to None.
318
+ split_sentences (bool, optional):
319
+ Split text into sentences, synthesize them separately and concatenate the file audio.
320
+ Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
321
+ applicable to the 🐸TTS models. Defaults to True.
322
+ **kwargs (optional):
323
+ Additional arguments for the model.
324
+ """
325
+ if self.synthesizer is None:
326
+ msg = "The selected model does not support speech synthesis."
327
+ raise RuntimeError(msg)
328
+ self._check_arguments(speaker=speaker, language=language, speaker_wav=speaker_wav, emotion=emotion, **kwargs)
329
+ wav = self.synthesizer.tts(
330
+ text=text,
331
+ speaker_name=speaker,
332
+ language_name=language,
333
+ speaker_wav=speaker_wav,
334
+ split_sentences=split_sentences,
335
+ **kwargs,
336
+ )
337
+ return wav
338
+
339
+ def tts_to_file(
340
+ self,
341
+ text: str,
342
+ speaker: str | None = None,
343
+ language: str | None = None,
344
+ speaker_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]] | None = None,
345
+ emotion: str | None = None,
346
+ pipe_out=None,
347
+ file_path: str = "output.wav",
348
+ split_sentences: bool = True,
349
+ **kwargs,
350
+ ) -> str:
351
+ """Convert text to speech.
352
+
353
+ Args:
354
+ text (str):
355
+ Input text to synthesize.
356
+ speaker (str, optional):
357
+ Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
358
+ `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
359
+ language (str, optional):
360
+ Language code for multi-lingual models. You can check whether loaded model is multi-lingual
361
+ `tts.is_multi_lingual` and list available languages by `tts.languages`. Defaults to None.
362
+ speaker_wav (str, optional):
363
+ Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
364
+ Defaults to None.
365
+ emotion (str, optional):
366
+ Emotion to use for 🐸Coqui Studio models. Defaults to "Neutral".
367
+ pipe_out (BytesIO, optional):
368
+ Flag to stdout the generated TTS wav file for shell pipe.
369
+ file_path (str, optional):
370
+ Output file path. Defaults to "output.wav".
371
+ split_sentences (bool, optional):
372
+ Split text into sentences, synthesize them separately and concatenate the file audio.
373
+ Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
374
+ applicable to the 🐸TTS models. Defaults to True.
375
+ **kwargs (optional):
376
+ Additional arguments for the model.
377
+ """
378
+ self._check_arguments(speaker=speaker, language=language, speaker_wav=speaker_wav, **kwargs)
379
+
380
+ wav = self.tts(
381
+ text=text,
382
+ speaker=speaker,
383
+ language=language,
384
+ speaker_wav=speaker_wav,
385
+ split_sentences=split_sentences,
386
+ **kwargs,
387
+ )
388
+ self.synthesizer.save_wav(wav=wav, path=file_path, pipe_out=pipe_out)
389
+ return file_path
390
+
391
+ def voice_conversion(
392
+ self,
393
+ source_wav: str | os.PathLike[Any],
394
+ target_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]] | None = None,
395
+ *,
396
+ speaker: str | None = None,
397
+ voice_dir: str | os.PathLike[Any] | None = None,
398
+ source_speaker: str | None = None,
399
+ **kwargs,
400
+ ):
401
+ """Convert source wav to target speaker.
402
+
403
+ Target speaker voices can be cached by assigning a ``speaker`` argument
404
+ for later reuse without ``target_wav``.
405
+
406
+ Args:
407
+ source_wav:
408
+ Path to the source wav file.
409
+ target_wav:
410
+ Path(s) to the target wav file(s).
411
+ speaker:
412
+ Custom target speaker ID to cache the cloned voice.
413
+ voice_dir:
414
+ Cache folder for cloned voices.
415
+ source_speaker:
416
+ Source speaker ID. Only needed for embedding-based models like Vits.
417
+ **kwargs:
418
+ Additional arguments for the model.
419
+ """
420
+ if self.voice_converter is not None:
421
+ return self.voice_converter.voice_conversion(
422
+ source_wav=source_wav, target_wav=target_wav, speaker_id=speaker, voice_dir=voice_dir, **kwargs
423
+ )
424
+ if self.synthesizer is not None and hasattr(self.synthesizer.tts_model, "voice_conversion"):
425
+ return self.synthesizer.tts(
426
+ source_wav=source_wav,
427
+ source_speaker_name=source_speaker,
428
+ speaker_wav=target_wav,
429
+ speaker_name=speaker,
430
+ voice_dir=voice_dir,
431
+ **kwargs,
432
+ )
433
+ msg = "The selected model does not support voice conversion."
434
+ raise RuntimeError(msg)
435
+
436
+ def voice_conversion_to_file(
437
+ self,
438
+ source_wav: str | os.PathLike[Any],
439
+ target_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]] | None = None,
440
+ *,
441
+ file_path: str = "output.wav",
442
+ speaker: str | None = None,
443
+ voice_dir: str | os.PathLike[Any] | None = None,
444
+ source_speaker: str | None = None,
445
+ pipe_out=None,
446
+ **kwargs,
447
+ ) -> str:
448
+ """Convert source wav to target speaker.
449
+
450
+ Target speaker voices can be cached by assigning a ``speaker`` argument
451
+ for later reuse without ``target_wav``.
452
+
453
+ Args:
454
+ source_wav:
455
+ Path to the source wav file.
456
+ target_wav:
457
+ Path to the target wav file.
458
+ file_path:
459
+ Output file path. Defaults to "output.wav".
460
+ speaker:
461
+ Custom speaker ID to cache the cloned voice.
462
+ voice_dir:
463
+ Cache folder for cloned voices.
464
+ source_speaker:
465
+ Source speaker ID. Only needed for embedding-based models like Vits.
466
+ pipe_out (BytesIO, optional):
467
+ Flag to stdout the generated TTS wav file for shell pipe.
468
+ **kwargs:
469
+ Additional arguments for the model.
470
+ """
471
+ wav = self.voice_conversion(
472
+ source_wav=source_wav, target_wav=target_wav, speaker=speaker, voice_dir=voice_dir, **kwargs
473
+ )
474
+ if self.voice_converter is not None:
475
+ self.voice_converter.save_wav(wav=wav, path=file_path, pipe_out=pipe_out)
476
+ else:
477
+ self.synthesizer.save_wav(wav=wav, path=file_path, pipe_out=pipe_out)
478
+ return file_path
479
+
480
+ def tts_with_vc(
481
+ self,
482
+ text: str,
483
+ *,
484
+ language: str | None = None,
485
+ speaker_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]],
486
+ speaker: str | None = None,
487
+ split_sentences: bool = True,
488
+ ):
489
+ """Convert text to speech with voice conversion.
490
+
491
+ It combines tts with voice conversion to fake voice cloning.
492
+
493
+ - Convert text to speech with tts.
494
+ - Convert the output wav to target speaker with voice conversion.
495
+
496
+ Args:
497
+ text (str):
498
+ Input text to synthesize.
499
+ language (str, optional):
500
+ Language code for multi-lingual models. You can check whether loaded model is multi-lingual
501
+ `tts.is_multi_lingual` and list available languages by `tts.languages`. Defaults to None.
502
+ speaker_wav (str, optional):
503
+ Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
504
+ Defaults to None.
505
+ speaker (str, optional):
506
+ Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
507
+ `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
508
+ split_sentences (bool, optional):
509
+ Split text into sentences, synthesize them separately and concatenate the file audio.
510
+ Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
511
+ applicable to the 🐸TTS models. Defaults to True.
512
+ """
513
+ if self.synthesizer.tts_model.config.supports_cloning:
514
+ warnings.warn(
515
+ "This TTS model directly supports voice cloning, for better quality call it with "
516
+ "tts/tts_to_file(..., speaker_wav=...) instead."
517
+ )
518
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp:
519
+ # Lazy code... save it to a temp file to resample it while reading it for VC
520
+ self.tts_to_file(
521
+ text=text, speaker=speaker, language=language, file_path=fp.name, split_sentences=split_sentences
522
+ )
523
+ if self.voice_converter is None:
524
+ self.load_vc_model_by_name("voice_conversion_models/multilingual/vctk/freevc24")
525
+ wav = self.voice_converter.voice_conversion(source_wav=fp.name, target_wav=speaker_wav)
526
+ return wav
527
+
528
+ def tts_with_vc_to_file(
529
+ self,
530
+ text: str,
531
+ *,
532
+ language: str | None = None,
533
+ speaker_wav: str | os.PathLike[Any] | list[str | os.PathLike[Any]],
534
+ file_path: str = "output.wav",
535
+ speaker: str | None = None,
536
+ split_sentences: bool = True,
537
+ pipe_out=None,
538
+ ) -> str:
539
+ """Convert text to speech with voice conversion and save to file.
540
+
541
+ Check `tts_with_vc` for more details.
542
+
543
+ Args:
544
+ text (str):
545
+ Input text to synthesize.
546
+ language (str, optional):
547
+ Language code for multi-lingual models. You can check whether loaded model is multi-lingual
548
+ `tts.is_multi_lingual` and list available languages by `tts.languages`. Defaults to None.
549
+ speaker_wav (str, optional):
550
+ Path to a reference wav file to use for voice cloning with supporting models like YourTTS.
551
+ Defaults to None.
552
+ file_path (str, optional):
553
+ Output file path. Defaults to "output.wav".
554
+ speaker (str, optional):
555
+ Speaker name for multi-speaker. You can check whether loaded model is multi-speaker by
556
+ `tts.is_multi_speaker` and list speakers by `tts.speakers`. Defaults to None.
557
+ split_sentences (bool, optional):
558
+ Split text into sentences, synthesize them separately and concatenate the file audio.
559
+ Setting it False uses more VRAM and possibly hit model specific text length or VRAM limits. Only
560
+ applicable to the 🐸TTS models. Defaults to True.
561
+ pipe_out (BytesIO, optional):
562
+ Flag to stdout the generated TTS wav file for shell pipe.
563
+ """
564
+ wav = self.tts_with_vc(
565
+ text=text, language=language, speaker_wav=speaker_wav, speaker=speaker, split_sentences=split_sentences
566
+ )
567
+ self.voice_converter.save_wav(wav=wav, path=file_path, pipe_out=pipe_out)
568
+ return file_path
TTS/bin/__init__.py ADDED
File without changes
TTS/bin/collect_env_info.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Get detailed info about the working environment."""
2
+
3
+ import json
4
+ import os
5
+ import platform
6
+ import sys
7
+
8
+ import numpy
9
+ import torch
10
+
11
+ import TTS
12
+
13
+ sys.path += [os.path.abspath(".."), os.path.abspath(".")]
14
+
15
+
16
+ def system_info():
17
+ return {
18
+ "OS": platform.system(),
19
+ "architecture": platform.architecture(),
20
+ "version": platform.version(),
21
+ "processor": platform.processor(),
22
+ "python": platform.python_version(),
23
+ }
24
+
25
+
26
+ def cuda_info():
27
+ return {
28
+ "GPU": [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())],
29
+ "available": torch.cuda.is_available(),
30
+ "version": torch.version.cuda,
31
+ }
32
+
33
+
34
+ def package_info():
35
+ return {
36
+ "numpy": numpy.__version__,
37
+ "PyTorch_version": torch.__version__,
38
+ "PyTorch_debug": torch.version.debug,
39
+ "TTS": TTS.__version__,
40
+ }
41
+
42
+
43
+ def main():
44
+ details = {"System": system_info(), "CUDA": cuda_info(), "Packages": package_info()}
45
+ print(json.dumps(details, indent=4, sort_keys=True))
46
+
47
+
48
+ if __name__ == "__main__":
49
+ main()
TTS/bin/compute_attention_masks.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import importlib
3
+ import logging
4
+ import os
5
+ import sys
6
+ from argparse import RawTextHelpFormatter
7
+
8
+ import numpy as np
9
+ import torch
10
+ from torch.utils.data import DataLoader
11
+ from tqdm import tqdm
12
+ from trainer.io import load_checkpoint
13
+
14
+ from TTS.config import load_config
15
+ from TTS.tts.datasets.TTSDataset import TTSDataset
16
+ from TTS.tts.models import setup_model
17
+ from TTS.tts.utils.text.characters import make_symbols, phonemes, symbols
18
+ from TTS.utils.audio import AudioProcessor
19
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
20
+
21
+ if __name__ == "__main__":
22
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
23
+
24
+ # pylint: disable=bad-option-value
25
+ parser = argparse.ArgumentParser(
26
+ description="""Extract attention masks from trained Tacotron/Tacotron2 models.
27
+ These masks can be used for different purposes including training a TTS model with a Duration Predictor.\n\n"""
28
+ """Each attention mask is written to the same path as the input wav file with ".npy" file extension.
29
+ (e.g. path/bla.wav (wav file) --> path/bla.npy (attention mask))\n"""
30
+ """
31
+ Example run:
32
+ CUDA_VISIBLE_DEVICE="0" python TTS/bin/compute_attention_masks.py
33
+ --model_path /data/rw/home/Models/ljspeech-dcattn-December-14-2020_11+10AM-9d0e8c7/checkpoint_200000.pth
34
+ --config_path /data/rw/home/Models/ljspeech-dcattn-December-14-2020_11+10AM-9d0e8c7/config.json
35
+ --dataset_metafile metadata.csv
36
+ --data_path /root/LJSpeech-1.1/
37
+ --batch_size 32
38
+ --dataset ljspeech
39
+ --use_cuda
40
+ """,
41
+ formatter_class=RawTextHelpFormatter,
42
+ )
43
+ parser.add_argument("--model_path", type=str, required=True, help="Path to Tacotron/Tacotron2 model file ")
44
+ parser.add_argument(
45
+ "--config_path",
46
+ type=str,
47
+ required=True,
48
+ help="Path to Tacotron/Tacotron2 config file.",
49
+ )
50
+ parser.add_argument(
51
+ "--dataset",
52
+ type=str,
53
+ default="",
54
+ required=True,
55
+ help="Target dataset processor name from TTS.tts.dataset.preprocess.",
56
+ )
57
+
58
+ parser.add_argument(
59
+ "--dataset_metafile",
60
+ type=str,
61
+ default="",
62
+ required=True,
63
+ help="Dataset metafile inclusing file paths with transcripts.",
64
+ )
65
+ parser.add_argument("--data_path", type=str, default="", help="Defines the data path. It overwrites config.json.")
66
+ parser.add_argument("--use_cuda", action=argparse.BooleanOptionalAction, default=False, help="enable/disable cuda.")
67
+
68
+ parser.add_argument(
69
+ "--batch_size", default=16, type=int, help="Batch size for the model. Use batch_size=1 if you have no CUDA."
70
+ )
71
+ args = parser.parse_args()
72
+
73
+ C = load_config(args.config_path)
74
+ ap = AudioProcessor(**C.audio)
75
+
76
+ # if the vocabulary was passed, replace the default
77
+ if "characters" in C.keys():
78
+ symbols, phonemes = make_symbols(**C.characters) # noqa: F811
79
+
80
+ # load the model
81
+ num_chars = len(phonemes) if C.use_phonemes else len(symbols)
82
+ # TODO: handle multi-speaker
83
+ model = setup_model(C)
84
+ model, _ = load_checkpoint(model, args.model_path, use_cuda=args.use_cuda, eval=True)
85
+
86
+ # data loader
87
+ preprocessor = importlib.import_module("TTS.tts.datasets.formatters")
88
+ preprocessor = getattr(preprocessor, args.dataset)
89
+ meta_data = preprocessor(args.data_path, args.dataset_metafile)
90
+ dataset = TTSDataset(
91
+ model.decoder.r,
92
+ C.text_cleaner,
93
+ compute_linear_spec=False,
94
+ ap=ap,
95
+ meta_data=meta_data,
96
+ characters=C.characters if "characters" in C.keys() else None,
97
+ add_blank=C["add_blank"] if "add_blank" in C.keys() else False,
98
+ use_phonemes=C.use_phonemes,
99
+ phoneme_cache_path=C.phoneme_cache_path,
100
+ phoneme_language=C.phoneme_language,
101
+ enable_eos_bos=C.enable_eos_bos_chars,
102
+ )
103
+
104
+ dataset.sort_and_filter_items(C.get("sort_by_audio_len", default=False))
105
+ loader = DataLoader(
106
+ dataset,
107
+ batch_size=args.batch_size,
108
+ num_workers=4,
109
+ collate_fn=dataset.collate_fn,
110
+ shuffle=False,
111
+ drop_last=False,
112
+ )
113
+
114
+ # compute attentions
115
+ file_paths = []
116
+ with torch.inference_mode():
117
+ for data in tqdm(loader):
118
+ # setup input data
119
+ text_input = data[0]
120
+ text_lengths = data[1]
121
+ linear_input = data[3]
122
+ mel_input = data[4]
123
+ mel_lengths = data[5]
124
+ stop_targets = data[6]
125
+ item_idxs = data[7]
126
+
127
+ # dispatch data to GPU
128
+ if args.use_cuda:
129
+ text_input = text_input.cuda()
130
+ text_lengths = text_lengths.cuda()
131
+ mel_input = mel_input.cuda()
132
+ mel_lengths = mel_lengths.cuda()
133
+
134
+ model_outputs = model.forward(text_input, text_lengths, mel_input)
135
+
136
+ alignments = model_outputs["alignments"].detach()
137
+ for idx, alignment in enumerate(alignments):
138
+ item_idx = item_idxs[idx]
139
+ # interpolate if r > 1
140
+ alignment = (
141
+ torch.nn.functional.interpolate(
142
+ alignment.transpose(0, 1).unsqueeze(0),
143
+ size=None,
144
+ scale_factor=model.decoder.r,
145
+ mode="nearest",
146
+ align_corners=None,
147
+ recompute_scale_factor=None,
148
+ )
149
+ .squeeze(0)
150
+ .transpose(0, 1)
151
+ )
152
+ # remove paddings
153
+ alignment = alignment[: mel_lengths[idx], : text_lengths[idx]].cpu().numpy()
154
+ # set file paths
155
+ wav_file_name = os.path.basename(item_idx)
156
+ align_file_name = os.path.splitext(wav_file_name)[0] + "_attn.npy"
157
+ file_path = item_idx.replace(wav_file_name, align_file_name)
158
+ # save output
159
+ wav_file_abs_path = os.path.abspath(item_idx)
160
+ file_abs_path = os.path.abspath(file_path)
161
+ file_paths.append([wav_file_abs_path, file_abs_path])
162
+ np.save(file_path, alignment)
163
+
164
+ # ourput metafile
165
+ metafile = os.path.join(args.data_path, "metadata_attn_mask.txt")
166
+
167
+ with open(metafile, "w", encoding="utf-8") as f:
168
+ for p in file_paths:
169
+ f.write(f"{p[0]}|{p[1]}\n")
170
+ print(f" >> Metafile created: {metafile}")
TTS/bin/compute_embeddings.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import sys
5
+ from argparse import RawTextHelpFormatter
6
+
7
+ import torch
8
+ from tqdm import tqdm
9
+
10
+ from TTS.config import load_config
11
+ from TTS.config.shared_configs import BaseDatasetConfig
12
+ from TTS.tts.datasets import load_tts_samples
13
+ from TTS.tts.utils.managers import save_file
14
+ from TTS.tts.utils.speakers import SpeakerManager
15
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
16
+
17
+
18
+ def parse_args(arg_list: list[str] | None) -> argparse.Namespace:
19
+ parser = argparse.ArgumentParser(
20
+ description="""Compute embedding vectors for each audio file in a dataset and store them keyed by `{dataset_name}#{file_path}` in a .pth file\n\n"""
21
+ """
22
+ Example runs:
23
+ python TTS/bin/compute_embeddings.py --model_path speaker_encoder_model.pth --config_path speaker_encoder_config.json --config_dataset_path dataset_config.json
24
+
25
+ python TTS/bin/compute_embeddings.py --model_path speaker_encoder_model.pth --config_path speaker_encoder_config.json --formatter_name coqui --dataset_path /path/to/vctk/dataset --dataset_name my_vctk --meta_file_train /path/to/vctk/metafile_train.csv --meta_file_val /path/to/vctk/metafile_eval.csv
26
+ """,
27
+ formatter_class=RawTextHelpFormatter,
28
+ )
29
+ parser.add_argument(
30
+ "--model_path",
31
+ type=str,
32
+ help="Path to model checkpoint file. It defaults to the released speaker encoder.",
33
+ default="https://github.com/coqui-ai/TTS/releases/download/speaker_encoder_model/model_se.pth.tar",
34
+ )
35
+ parser.add_argument(
36
+ "--config_path",
37
+ type=str,
38
+ help="Path to model config file. It defaults to the released speaker encoder config.",
39
+ default="https://github.com/coqui-ai/TTS/releases/download/speaker_encoder_model/config_se.json",
40
+ )
41
+ parser.add_argument(
42
+ "--config_dataset_path",
43
+ type=str,
44
+ help="Path to dataset config file. You either need to provide this or `formatter_name`, `dataset_name` and `dataset_path` arguments.",
45
+ default=None,
46
+ )
47
+ parser.add_argument(
48
+ "--output_path",
49
+ type=str,
50
+ help="Path for output `pth` or `json` file.",
51
+ default="speakers.pth",
52
+ )
53
+ parser.add_argument(
54
+ "--old_file",
55
+ type=str,
56
+ help="The old existing embedding file, from which the embeddings will be directly loaded for already computed audio clips.",
57
+ default=None,
58
+ )
59
+ parser.add_argument(
60
+ "--old_append",
61
+ help="Append new audio clip embeddings to the old embedding file, generate a new non-duplicated merged embedding file. Default False",
62
+ default=False,
63
+ action="store_true",
64
+ )
65
+ parser.add_argument("--disable_cuda", action="store_true", help="Flag to disable cuda.", default=False)
66
+ parser.add_argument("--no_eval", help="Do not compute eval?. Default False", default=False, action="store_true")
67
+ parser.add_argument(
68
+ "--formatter_name",
69
+ type=str,
70
+ help="Name of the formatter to use. You either need to provide this or `config_dataset_path`",
71
+ default=None,
72
+ )
73
+ parser.add_argument(
74
+ "--dataset_name",
75
+ type=str,
76
+ help="Name of the dataset to use. You either need to provide this or `config_dataset_path`",
77
+ default=None,
78
+ )
79
+ parser.add_argument(
80
+ "--dataset_path",
81
+ type=str,
82
+ help="Path to the dataset. You either need to provide this or `config_dataset_path`",
83
+ default=None,
84
+ )
85
+ parser.add_argument(
86
+ "--meta_file_train",
87
+ type=str,
88
+ help="Path to the train meta file. If not set, dataset formatter uses the default metafile if it is defined in the formatter. You either need to provide this or `config_dataset_path`",
89
+ default=None,
90
+ )
91
+ parser.add_argument(
92
+ "--meta_file_val",
93
+ type=str,
94
+ help="Path to the evaluation meta file. If not set, dataset formatter uses the default metafile if it is defined in the formatter. You either need to provide this or `config_dataset_path`",
95
+ default=None,
96
+ )
97
+ return parser.parse_args()
98
+
99
+
100
+ def compute_embeddings(
101
+ model_path,
102
+ config_path,
103
+ output_path,
104
+ old_speakers_file=None,
105
+ old_append=False,
106
+ config_dataset_path=None,
107
+ formatter_name=None,
108
+ dataset_name=None,
109
+ dataset_path=None,
110
+ meta_file_train=None,
111
+ meta_file_val=None,
112
+ disable_cuda=False,
113
+ no_eval=False,
114
+ ):
115
+ use_cuda = torch.cuda.is_available() and not disable_cuda
116
+
117
+ if config_dataset_path is not None:
118
+ c_dataset = load_config(config_dataset_path)
119
+ meta_data_train, meta_data_eval = load_tts_samples(c_dataset.datasets, eval_split=not no_eval)
120
+ else:
121
+ c_dataset = BaseDatasetConfig()
122
+ c_dataset.formatter = formatter_name
123
+ c_dataset.dataset_name = dataset_name
124
+ c_dataset.path = dataset_path
125
+ if meta_file_train is not None:
126
+ c_dataset.meta_file_train = meta_file_train
127
+ if meta_file_val is not None:
128
+ c_dataset.meta_file_val = meta_file_val
129
+ meta_data_train, meta_data_eval = load_tts_samples(c_dataset, eval_split=not no_eval)
130
+
131
+ if meta_data_eval is None:
132
+ samples = meta_data_train
133
+ else:
134
+ samples = meta_data_train + meta_data_eval
135
+
136
+ encoder_manager = SpeakerManager(
137
+ encoder_model_path=model_path,
138
+ encoder_config_path=config_path,
139
+ d_vectors_file_path=old_speakers_file,
140
+ use_cuda=use_cuda,
141
+ )
142
+
143
+ class_name_key = encoder_manager.encoder_config.class_name_key
144
+
145
+ # compute speaker embeddings
146
+ if old_speakers_file is not None and old_append:
147
+ speaker_mapping = encoder_manager.embeddings
148
+ else:
149
+ speaker_mapping = {}
150
+
151
+ for fields in tqdm(samples):
152
+ class_name = fields[class_name_key]
153
+ audio_file = fields["audio_file"]
154
+ embedding_key = fields["audio_unique_name"]
155
+
156
+ # Only update the speaker name when the embedding is already in the old file.
157
+ if embedding_key in speaker_mapping:
158
+ speaker_mapping[embedding_key]["name"] = class_name
159
+ continue
160
+
161
+ if old_speakers_file is not None and embedding_key in encoder_manager.clip_ids:
162
+ # get the embedding from the old file
163
+ embedd = encoder_manager.get_embedding_by_clip(embedding_key)
164
+ else:
165
+ # extract the embedding
166
+ embedd = encoder_manager.compute_embedding_from_clip(audio_file)
167
+
168
+ # create speaker_mapping if target dataset is defined
169
+ speaker_mapping[embedding_key] = {}
170
+ speaker_mapping[embedding_key]["name"] = class_name
171
+ speaker_mapping[embedding_key]["embedding"] = embedd
172
+
173
+ if speaker_mapping:
174
+ # save speaker_mapping if target dataset is defined
175
+ if os.path.isdir(output_path):
176
+ mapping_file_path = os.path.join(output_path, "speakers.pth")
177
+ else:
178
+ mapping_file_path = output_path
179
+
180
+ if os.path.dirname(mapping_file_path) != "":
181
+ os.makedirs(os.path.dirname(mapping_file_path), exist_ok=True)
182
+
183
+ save_file(speaker_mapping, mapping_file_path)
184
+ print("Speaker embeddings saved at:", mapping_file_path)
185
+
186
+
187
+ def main(arg_list: list[str] | None = None):
188
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
189
+ args = parse_args(arg_list)
190
+
191
+ compute_embeddings(
192
+ args.model_path,
193
+ args.config_path,
194
+ args.output_path,
195
+ old_speakers_file=args.old_file,
196
+ old_append=args.old_append,
197
+ config_dataset_path=args.config_dataset_path,
198
+ formatter_name=args.formatter_name,
199
+ dataset_name=args.dataset_name,
200
+ dataset_path=args.dataset_path,
201
+ meta_file_train=args.meta_file_train,
202
+ meta_file_val=args.meta_file_val,
203
+ disable_cuda=args.disable_cuda,
204
+ no_eval=args.no_eval,
205
+ )
206
+
207
+
208
+ if __name__ == "__main__":
209
+ main()
TTS/bin/compute_statistics.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import glob
5
+ import logging
6
+ import os
7
+ import sys
8
+
9
+ import numpy as np
10
+ from tqdm import tqdm
11
+
12
+ # from TTS.utils.io import load_config
13
+ from TTS.config import load_config
14
+ from TTS.tts.datasets import load_tts_samples
15
+ from TTS.utils.audio import AudioProcessor
16
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
17
+
18
+
19
+ def parse_args(arg_list: list[str] | None) -> tuple[argparse.Namespace, list[str]]:
20
+ parser = argparse.ArgumentParser(description="Compute mean and variance of spectrogtram features.")
21
+ parser.add_argument("config_path", type=str, help="TTS config file path to define audio processin parameters.")
22
+ parser.add_argument("out_path", type=str, help="save path (directory and filename).")
23
+ parser.add_argument(
24
+ "--data_path",
25
+ type=str,
26
+ required=False,
27
+ help="folder including the target set of wavs overriding dataset config.",
28
+ )
29
+ return parser.parse_known_args(arg_list)
30
+
31
+
32
+ def main(arg_list: list[str] | None = None):
33
+ """Run preprocessing process."""
34
+ setup_logger("TTS", level=logging.INFO, stream=sys.stderr, formatter=ConsoleFormatter())
35
+ args, overrides = parse_args(arg_list)
36
+
37
+ CONFIG = load_config(args.config_path)
38
+ CONFIG.parse_known_args(overrides, relaxed_parser=True)
39
+
40
+ # load config
41
+ CONFIG.audio.signal_norm = False # do not apply earlier normalization
42
+ CONFIG.audio.stats_path = None # discard pre-defined stats
43
+
44
+ # load audio processor
45
+ ap = AudioProcessor(**CONFIG.audio.to_dict())
46
+
47
+ # load the meta data of target dataset
48
+ if args.data_path:
49
+ dataset_items = glob.glob(os.path.join(args.data_path, "**", "*.wav"), recursive=True)
50
+ else:
51
+ dataset_items = load_tts_samples(CONFIG.datasets)[0] # take only train data
52
+ print(f" > There are {len(dataset_items)} files.")
53
+
54
+ mel_sum = 0
55
+ mel_square_sum = 0
56
+ linear_sum = 0
57
+ linear_square_sum = 0
58
+ N = 0
59
+ for item in tqdm(dataset_items):
60
+ # compute features
61
+ wav = ap.load_wav(item if isinstance(item, str) else item["audio_file"])
62
+ linear = ap.spectrogram(wav)
63
+ mel = ap.melspectrogram(wav)
64
+
65
+ # compute stats
66
+ N += mel.shape[1]
67
+ mel_sum += mel.sum(1)
68
+ linear_sum += linear.sum(1)
69
+ mel_square_sum += (mel**2).sum(axis=1)
70
+ linear_square_sum += (linear**2).sum(axis=1)
71
+
72
+ mel_mean = mel_sum / N
73
+ mel_scale = np.sqrt(mel_square_sum / N - mel_mean**2)
74
+ linear_mean = linear_sum / N
75
+ linear_scale = np.sqrt(linear_square_sum / N - linear_mean**2)
76
+
77
+ output_file_path = args.out_path
78
+ stats = {}
79
+ stats["mel_mean"] = mel_mean
80
+ stats["mel_std"] = mel_scale
81
+ stats["linear_mean"] = linear_mean
82
+ stats["linear_std"] = linear_scale
83
+
84
+ print(f" > Avg mel spec mean: {mel_mean.mean()}")
85
+ print(f" > Avg mel spec scale: {mel_scale.mean()}")
86
+ print(f" > Avg linear spec mean: {linear_mean.mean()}")
87
+ print(f" > Avg linear spec scale: {linear_scale.mean()}")
88
+
89
+ # set default config values for mean-var scaling
90
+ CONFIG.audio.stats_path = output_file_path
91
+ CONFIG.audio.signal_norm = True
92
+ # remove redundant values
93
+ del CONFIG.audio.max_norm
94
+ del CONFIG.audio.min_level_db
95
+ del CONFIG.audio.symmetric_norm
96
+ del CONFIG.audio.clip_norm
97
+ stats["audio_config"] = CONFIG.audio.to_dict()
98
+ np.save(output_file_path, stats, allow_pickle=True)
99
+ print(f" > stats saved to {output_file_path}")
100
+ sys.exit(0)
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
TTS/bin/eval_encoder.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import sys
4
+ from argparse import RawTextHelpFormatter
5
+
6
+ import torch
7
+ from tqdm import tqdm
8
+
9
+ from TTS.config import load_config
10
+ from TTS.tts.datasets import load_tts_samples
11
+ from TTS.tts.utils.speakers import SpeakerManager
12
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
13
+
14
+
15
+ def compute_encoder_accuracy(dataset_items, encoder_manager):
16
+ class_name_key = encoder_manager.encoder_config.class_name_key
17
+ map_classid_to_classname = getattr(encoder_manager.encoder_config, "map_classid_to_classname", None)
18
+
19
+ class_acc_dict = {}
20
+
21
+ # compute embeddings for all wav_files
22
+ for item in tqdm(dataset_items):
23
+ class_name = item[class_name_key]
24
+ wav_file = item["audio_file"]
25
+
26
+ # extract the embedding
27
+ embedd = encoder_manager.compute_embedding_from_clip(wav_file)
28
+ if encoder_manager.encoder_criterion is not None and map_classid_to_classname is not None:
29
+ embedding = torch.FloatTensor(embedd).unsqueeze(0)
30
+ if encoder_manager.use_cuda:
31
+ embedding = embedding.cuda()
32
+
33
+ class_id = encoder_manager.encoder_criterion.softmax.inference(embedding).item()
34
+ predicted_label = map_classid_to_classname[str(class_id)]
35
+ else:
36
+ predicted_label = None
37
+
38
+ if class_name is not None and predicted_label is not None:
39
+ is_equal = int(class_name == predicted_label)
40
+ if class_name not in class_acc_dict:
41
+ class_acc_dict[class_name] = [is_equal]
42
+ else:
43
+ class_acc_dict[class_name].append(is_equal)
44
+ else:
45
+ raise RuntimeError("Error: class_name or/and predicted_label are None")
46
+
47
+ acc_avg = 0
48
+ for key, values in class_acc_dict.items():
49
+ acc = sum(values) / len(values)
50
+ print("Class", key, "Accuracy:", acc)
51
+ acc_avg += acc
52
+
53
+ print("Average Accuracy:", acc_avg / len(class_acc_dict))
54
+
55
+
56
+ if __name__ == "__main__":
57
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
58
+
59
+ parser = argparse.ArgumentParser(
60
+ description="""Compute the accuracy of the encoder.\n\n"""
61
+ """
62
+ Example runs:
63
+ python TTS/bin/eval_encoder.py emotion_encoder_model.pth emotion_encoder_config.json dataset_config.json
64
+ """,
65
+ formatter_class=RawTextHelpFormatter,
66
+ )
67
+ parser.add_argument("model_path", type=str, help="Path to model checkpoint file.")
68
+ parser.add_argument(
69
+ "config_path",
70
+ type=str,
71
+ help="Path to model config file.",
72
+ )
73
+
74
+ parser.add_argument(
75
+ "config_dataset_path",
76
+ type=str,
77
+ help="Path to dataset config file.",
78
+ )
79
+ parser.add_argument("--use_cuda", action=argparse.BooleanOptionalAction, help="flag to set cuda.", default=True)
80
+ parser.add_argument("--eval", action=argparse.BooleanOptionalAction, help="compute eval.", default=True)
81
+
82
+ args = parser.parse_args()
83
+
84
+ c_dataset = load_config(args.config_dataset_path)
85
+
86
+ meta_data_train, meta_data_eval = load_tts_samples(c_dataset.datasets, eval_split=args.eval)
87
+ items = meta_data_train + meta_data_eval
88
+
89
+ enc_manager = SpeakerManager(
90
+ encoder_model_path=args.model_path, encoder_config_path=args.config_path, use_cuda=args.use_cuda
91
+ )
92
+
93
+ compute_encoder_accuracy(items, enc_manager)
TTS/bin/extract_tts_spectrograms.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Extract Mel spectrograms with teacher forcing."""
3
+
4
+ import argparse
5
+ import logging
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch.utils.data import DataLoader
12
+ from tqdm import tqdm
13
+ from trainer.generic_utils import count_parameters
14
+
15
+ from TTS.config import load_config
16
+ from TTS.tts.configs.shared_configs import BaseTTSConfig
17
+ from TTS.tts.datasets import TTSDataset, load_tts_samples
18
+ from TTS.tts.models import setup_model
19
+ from TTS.tts.models.base_tts import BaseTTS
20
+ from TTS.tts.utils.speakers import SpeakerManager
21
+ from TTS.tts.utils.text.tokenizer import TTSTokenizer
22
+ from TTS.utils.audio import AudioProcessor
23
+ from TTS.utils.audio.numpy_transforms import quantize
24
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
25
+
26
+ use_cuda = torch.cuda.is_available()
27
+
28
+
29
+ def parse_args(arg_list: list[str] | None) -> argparse.Namespace:
30
+ parser = argparse.ArgumentParser()
31
+ parser.add_argument("--config_path", type=str, help="Path to config file for training.", required=True)
32
+ parser.add_argument("--checkpoint_path", type=str, help="Model file to be restored.", required=True)
33
+ parser.add_argument("--output_path", type=str, help="Path to save mel specs", required=True)
34
+ parser.add_argument("--debug", default=False, action="store_true", help="Save audio files for debug")
35
+ parser.add_argument("--save_audio", default=False, action="store_true", help="Save audio files")
36
+ parser.add_argument("--quantize_bits", type=int, default=0, help="Save quantized audio files if non-zero")
37
+ parser.add_argument("--eval", action=argparse.BooleanOptionalAction, help="compute eval.", default=True)
38
+ return parser.parse_args(arg_list)
39
+
40
+
41
+ def setup_loader(config: BaseTTSConfig, ap: AudioProcessor, r, speaker_manager: SpeakerManager, samples) -> DataLoader:
42
+ tokenizer, _ = TTSTokenizer.init_from_config(config)
43
+ dataset = TTSDataset(
44
+ outputs_per_step=r,
45
+ compute_linear_spec=False,
46
+ samples=samples,
47
+ tokenizer=tokenizer,
48
+ ap=ap,
49
+ batch_group_size=0,
50
+ min_text_len=config.min_text_len,
51
+ max_text_len=config.max_text_len,
52
+ min_audio_len=config.min_audio_len,
53
+ max_audio_len=config.max_audio_len,
54
+ phoneme_cache_path=config.phoneme_cache_path,
55
+ precompute_num_workers=0,
56
+ use_noise_augment=False,
57
+ speaker_id_mapping=speaker_manager.name_to_id if config.use_speaker_embedding else None,
58
+ d_vector_mapping=speaker_manager.embeddings if config.use_d_vector_file else None,
59
+ )
60
+
61
+ if config.use_phonemes and config.compute_input_seq_cache:
62
+ # precompute phonemes to have a better estimate of sequence lengths.
63
+ dataset.compute_input_seq(config.num_loader_workers)
64
+ dataset.preprocess_samples()
65
+
66
+ return DataLoader(
67
+ dataset,
68
+ batch_size=config.batch_size,
69
+ shuffle=False,
70
+ collate_fn=dataset.collate_fn,
71
+ drop_last=False,
72
+ sampler=None,
73
+ num_workers=config.num_loader_workers,
74
+ pin_memory=False,
75
+ )
76
+
77
+
78
+ def set_filename(wav_path: str, out_path: Path) -> tuple[Path, Path, Path, Path]:
79
+ wav_name = Path(wav_path).stem
80
+ (out_path / "quant").mkdir(exist_ok=True, parents=True)
81
+ (out_path / "mel").mkdir(exist_ok=True, parents=True)
82
+ (out_path / "wav_gl").mkdir(exist_ok=True, parents=True)
83
+ (out_path / "wav").mkdir(exist_ok=True, parents=True)
84
+ wavq_path = out_path / "quant" / wav_name
85
+ mel_path = out_path / "mel" / wav_name
86
+ wav_gl_path = out_path / "wav_gl" / f"{wav_name}.wav"
87
+ out_wav_path = out_path / "wav" / f"{wav_name}.wav"
88
+ return wavq_path, mel_path, wav_gl_path, out_wav_path
89
+
90
+
91
+ def format_data(data):
92
+ # setup input data
93
+ text_input = data["token_id"]
94
+ text_lengths = data["token_id_lengths"]
95
+ mel_input = data["mel"]
96
+ mel_lengths = data["mel_lengths"]
97
+ item_idx = data["item_idxs"]
98
+ d_vectors = data["d_vectors"]
99
+ speaker_ids = data["speaker_ids"]
100
+ attn_mask = data["attns"]
101
+ avg_text_length = torch.mean(text_lengths.float())
102
+ avg_spec_length = torch.mean(mel_lengths.float())
103
+
104
+ # dispatch data to GPU
105
+ if use_cuda:
106
+ text_input = text_input.cuda(non_blocking=True)
107
+ text_lengths = text_lengths.cuda(non_blocking=True)
108
+ mel_input = mel_input.cuda(non_blocking=True)
109
+ mel_lengths = mel_lengths.cuda(non_blocking=True)
110
+ if speaker_ids is not None:
111
+ speaker_ids = speaker_ids.cuda(non_blocking=True)
112
+ if d_vectors is not None:
113
+ d_vectors = d_vectors.cuda(non_blocking=True)
114
+ if attn_mask is not None:
115
+ attn_mask = attn_mask.cuda(non_blocking=True)
116
+ return (
117
+ text_input,
118
+ text_lengths,
119
+ mel_input,
120
+ mel_lengths,
121
+ speaker_ids,
122
+ d_vectors,
123
+ avg_text_length,
124
+ avg_spec_length,
125
+ attn_mask,
126
+ item_idx,
127
+ )
128
+
129
+
130
+ @torch.inference_mode()
131
+ def inference(
132
+ model_name: str,
133
+ model: BaseTTS,
134
+ ap: AudioProcessor,
135
+ text_input,
136
+ text_lengths,
137
+ mel_input,
138
+ mel_lengths,
139
+ speaker_ids=None,
140
+ d_vectors=None,
141
+ ) -> np.ndarray:
142
+ if model_name == "glow_tts":
143
+ speaker_c = None
144
+ if speaker_ids is not None:
145
+ speaker_c = speaker_ids
146
+ elif d_vectors is not None:
147
+ speaker_c = d_vectors
148
+ outputs = model.inference_with_MAS(
149
+ text_input,
150
+ text_lengths,
151
+ mel_input,
152
+ mel_lengths,
153
+ aux_input={"d_vectors": speaker_c, "speaker_ids": speaker_ids},
154
+ )
155
+ model_output = outputs["model_outputs"]
156
+ return model_output.detach().cpu().numpy()
157
+
158
+ if "tacotron" in model_name:
159
+ aux_input = {"speaker_ids": speaker_ids, "d_vectors": d_vectors}
160
+ outputs = model(text_input, text_lengths, mel_input, mel_lengths, aux_input)
161
+ postnet_outputs = outputs["model_outputs"]
162
+ # normalize tacotron output
163
+ if model_name == "tacotron":
164
+ mel_specs = []
165
+ postnet_outputs = postnet_outputs.data.cpu().numpy()
166
+ for b in range(postnet_outputs.shape[0]):
167
+ postnet_output = postnet_outputs[b]
168
+ mel_specs.append(torch.FloatTensor(ap.out_linear_to_mel(postnet_output.T).T))
169
+ return torch.stack(mel_specs).cpu().numpy()
170
+ if model_name == "tacotron2":
171
+ return postnet_outputs.detach().cpu().numpy()
172
+ msg = f"Model not supported: {model_name}"
173
+ raise ValueError(msg)
174
+
175
+
176
+ def extract_spectrograms(
177
+ model_name: str,
178
+ data_loader: DataLoader,
179
+ model: BaseTTS,
180
+ ap: AudioProcessor,
181
+ output_path: Path,
182
+ quantize_bits: int = 0,
183
+ save_audio: bool = False,
184
+ debug: bool = False,
185
+ metadata_name: str = "metadata.txt",
186
+ ) -> None:
187
+ model.eval()
188
+ export_metadata = []
189
+ for _, data in tqdm(enumerate(data_loader), total=len(data_loader)):
190
+ # format data
191
+ (
192
+ text_input,
193
+ text_lengths,
194
+ mel_input,
195
+ mel_lengths,
196
+ speaker_ids,
197
+ d_vectors,
198
+ _,
199
+ _,
200
+ _,
201
+ item_idx,
202
+ ) = format_data(data)
203
+
204
+ model_output = inference(
205
+ model_name,
206
+ model,
207
+ ap,
208
+ text_input,
209
+ text_lengths,
210
+ mel_input,
211
+ mel_lengths,
212
+ speaker_ids,
213
+ d_vectors,
214
+ )
215
+
216
+ for idx in range(text_input.shape[0]):
217
+ wav_file_path = item_idx[idx]
218
+ wav = ap.load_wav(wav_file_path)
219
+ wavq_path, mel_path, wav_gl_path, wav_path = set_filename(wav_file_path, output_path)
220
+
221
+ # quantize and save wav
222
+ if quantize_bits > 0:
223
+ wavq = quantize(wav, quantize_bits)
224
+ np.save(wavq_path, wavq)
225
+
226
+ # save TTS mel
227
+ mel = model_output[idx]
228
+ mel_length = mel_lengths[idx]
229
+ mel = mel[:mel_length, :].T
230
+ np.save(mel_path, mel)
231
+
232
+ export_metadata.append([wav_file_path, mel_path])
233
+ if save_audio:
234
+ ap.save_wav(wav, wav_path)
235
+
236
+ if debug:
237
+ print("Audio for debug saved at:", wav_gl_path)
238
+ wav = ap.inv_melspectrogram(mel)
239
+ ap.save_wav(wav, wav_gl_path)
240
+
241
+ with (output_path / metadata_name).open("w") as f:
242
+ for data in export_metadata:
243
+ f.write(f"{data[0] / data[1]}.npy\n")
244
+
245
+
246
+ def main(arg_list: list[str] | None = None) -> None:
247
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
248
+ args = parse_args(arg_list)
249
+ config = load_config(args.config_path)
250
+ config.audio.trim_silence = False
251
+
252
+ # Audio processor
253
+ ap = AudioProcessor(**config.audio)
254
+
255
+ # load data instances
256
+ meta_data_train, meta_data_eval = load_tts_samples(
257
+ config.datasets,
258
+ eval_split=args.eval,
259
+ eval_split_max_size=config.eval_split_max_size,
260
+ eval_split_size=config.eval_split_size,
261
+ )
262
+
263
+ # use eval and training partitions
264
+ meta_data = meta_data_train + meta_data_eval
265
+
266
+ # init speaker manager
267
+ if config.use_speaker_embedding:
268
+ speaker_manager = SpeakerManager(data_items=meta_data)
269
+ elif config.use_d_vector_file:
270
+ speaker_manager = SpeakerManager(d_vectors_file_path=config.d_vector_file)
271
+ else:
272
+ speaker_manager = None
273
+
274
+ # setup model
275
+ model = setup_model(config)
276
+
277
+ # restore model
278
+ model.load_checkpoint(config, args.checkpoint_path, eval=True)
279
+
280
+ if use_cuda:
281
+ model.cuda()
282
+
283
+ num_params = count_parameters(model)
284
+ print(f"\n > Model has {num_params} parameters", flush=True)
285
+ # set r
286
+ r = 1 if config.model.lower() == "glow_tts" else model.decoder.r
287
+ own_loader = setup_loader(config, ap, r, speaker_manager, meta_data)
288
+
289
+ extract_spectrograms(
290
+ config.model.lower(),
291
+ own_loader,
292
+ model,
293
+ ap,
294
+ Path(args.output_path),
295
+ quantize_bits=args.quantize_bits,
296
+ save_audio=args.save_audio,
297
+ debug=args.debug,
298
+ metadata_name="metadata.txt",
299
+ )
300
+ sys.exit(0)
301
+
302
+
303
+ if __name__ == "__main__":
304
+ main()
TTS/bin/find_unique_chars.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Find all the unique characters in a dataset"""
2
+
3
+ import argparse
4
+ import logging
5
+ import sys
6
+ from argparse import RawTextHelpFormatter
7
+
8
+ from TTS.config import load_config
9
+ from TTS.tts.datasets import find_unique_chars, load_tts_samples
10
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
11
+
12
+
13
+ def main():
14
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
15
+
16
+ # pylint: disable=bad-option-value
17
+ parser = argparse.ArgumentParser(
18
+ description="""Find all the unique characters or phonemes in a dataset.\n\n"""
19
+ """
20
+ Example runs:
21
+
22
+ python TTS/bin/find_unique_chars.py --config_path config.json
23
+ """,
24
+ formatter_class=RawTextHelpFormatter,
25
+ )
26
+ parser.add_argument("--config_path", type=str, help="Path to dataset config file.", required=True)
27
+ args = parser.parse_args()
28
+
29
+ c = load_config(args.config_path)
30
+
31
+ # load all datasets
32
+ train_items, eval_items = load_tts_samples(
33
+ c.datasets, eval_split=True, eval_split_max_size=c.eval_split_max_size, eval_split_size=c.eval_split_size
34
+ )
35
+
36
+ items = train_items + eval_items
37
+ find_unique_chars(items)
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
TTS/bin/find_unique_phonemes.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Find all the unique characters in a dataset."""
2
+
3
+ import argparse
4
+ import logging
5
+ import multiprocessing
6
+ import sys
7
+ from argparse import RawTextHelpFormatter
8
+
9
+ from tqdm.contrib.concurrent import process_map
10
+
11
+ from TTS.config import load_config
12
+ from TTS.tts.datasets import load_tts_samples
13
+ from TTS.tts.utils.text.phonemizers import Gruut
14
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
15
+
16
+
17
+ def compute_phonemes(item: dict) -> set[str]:
18
+ text = item["text"]
19
+ ph = phonemizer.phonemize(text).replace("|", "")
20
+ return set(ph)
21
+
22
+
23
+ def parse_args(arg_list: list[str] | None) -> argparse.Namespace:
24
+ parser = argparse.ArgumentParser(
25
+ description="""Find all the unique characters or phonemes in a dataset.\n\n"""
26
+ """
27
+ Example runs:
28
+
29
+ python TTS/bin/find_unique_phonemes.py --config_path config.json
30
+ """,
31
+ formatter_class=RawTextHelpFormatter,
32
+ )
33
+ parser.add_argument("--config_path", type=str, help="Path to dataset config file.", required=True)
34
+ return parser.parse_args(arg_list)
35
+
36
+
37
+ def main(arg_list: list[str] | None = None) -> None:
38
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
39
+ global phonemizer
40
+ args = parse_args(arg_list)
41
+ config = load_config(args.config_path)
42
+
43
+ # load all datasets
44
+ train_items, eval_items = load_tts_samples(
45
+ config.datasets,
46
+ eval_split=True,
47
+ eval_split_max_size=config.eval_split_max_size,
48
+ eval_split_size=config.eval_split_size,
49
+ )
50
+ items = train_items + eval_items
51
+ print("Num items:", len(items))
52
+
53
+ language_list = [item["language"] for item in items]
54
+ is_lang_def = all(language_list)
55
+
56
+ if not config.phoneme_language or not is_lang_def:
57
+ msg = "Phoneme language must be defined in config."
58
+ raise ValueError(msg)
59
+
60
+ if language_list.count(language_list[0]) != len(language_list):
61
+ msg = (
62
+ "Currently, just one phoneme language per config file is supported !! "
63
+ "Please split the dataset config into different configs and run it individually for each language !!"
64
+ )
65
+ raise ValueError(msg)
66
+
67
+ phonemizer = Gruut(language=language_list[0], keep_puncs=True)
68
+
69
+ phonemes = process_map(compute_phonemes, items, max_workers=multiprocessing.cpu_count(), chunksize=15)
70
+ phones = []
71
+ for ph in phonemes:
72
+ phones.extend(ph)
73
+
74
+ phones = set(phones)
75
+ lower_phones = filter(lambda c: c.islower(), phones)
76
+ phones_force_lower = [c.lower() for c in phones]
77
+ phones_force_lower = set(phones_force_lower)
78
+
79
+ print(f" > Number of unique phonemes: {len(phones)}")
80
+ print(f" > Unique phonemes: {''.join(sorted(phones))}")
81
+ print(f" > Unique lower phonemes: {''.join(sorted(lower_phones))}")
82
+ print(f" > Unique all forced to lower phonemes: {''.join(sorted(phones_force_lower))}")
83
+ sys.exit(0)
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
TTS/bin/remove_silence_using_vad.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import logging
4
+ import multiprocessing
5
+ import os
6
+ import pathlib
7
+ import sys
8
+
9
+ import torch
10
+ from tqdm import tqdm
11
+
12
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
13
+ from TTS.utils.vad import get_vad_model_and_utils, remove_silence
14
+
15
+ torch.set_num_threads(1)
16
+
17
+
18
+ def adjust_path_and_remove_silence(audio_path):
19
+ output_path = audio_path.replace(os.path.join(args.input_dir, ""), os.path.join(args.output_dir, ""))
20
+ # ignore if the file exists
21
+ if os.path.exists(output_path) and not args.force:
22
+ return output_path, False
23
+
24
+ # create all directory structure
25
+ pathlib.Path(output_path).parent.mkdir(parents=True, exist_ok=True)
26
+ # remove the silence and save the audio
27
+ output_path, is_speech = remove_silence(
28
+ model_and_utils,
29
+ audio_path,
30
+ output_path,
31
+ trim_just_beginning_and_end=args.trim_just_beginning_and_end,
32
+ use_cuda=args.use_cuda,
33
+ )
34
+ return output_path, is_speech
35
+
36
+
37
+ def preprocess_audios():
38
+ files = sorted(glob.glob(os.path.join(args.input_dir, args.glob), recursive=True))
39
+ print("> Number of files: ", len(files))
40
+ if not args.force:
41
+ print("> Ignoring files that already exist in the output idrectory.")
42
+
43
+ if args.trim_just_beginning_and_end:
44
+ print("> Trimming just the beginning and the end with nonspeech parts.")
45
+ else:
46
+ print("> Trimming all nonspeech parts.")
47
+
48
+ filtered_files = []
49
+ if files:
50
+ # create threads
51
+ # num_threads = multiprocessing.cpu_count()
52
+ # process_map(adjust_path_and_remove_silence, files, max_workers=num_threads, chunksize=15)
53
+
54
+ if args.num_processes > 1:
55
+ with multiprocessing.Pool(processes=args.num_processes) as pool:
56
+ results = list(
57
+ tqdm(
58
+ pool.imap_unordered(adjust_path_and_remove_silence, files),
59
+ total=len(files),
60
+ desc="Processing audio files",
61
+ )
62
+ )
63
+ for output_path, is_speech in results:
64
+ if not is_speech:
65
+ filtered_files.append(output_path)
66
+ else:
67
+ for f in tqdm(files):
68
+ output_path, is_speech = adjust_path_and_remove_silence(f)
69
+ if not is_speech:
70
+ filtered_files.append(output_path)
71
+
72
+ # write files that do not have speech
73
+ with open(os.path.join(args.output_dir, "filtered_files.txt"), "w", encoding="utf-8") as f:
74
+ for file in filtered_files:
75
+ f.write(str(file) + "\n")
76
+ else:
77
+ print("> No files Found !")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
82
+
83
+ parser = argparse.ArgumentParser(
84
+ description="python TTS/bin/remove_silence_using_vad.py -i=VCTK-Corpus/ -o=VCTK-Corpus-removed-silence/ -g=wav48_silence_trimmed/*/*_mic1.flac --trim_just_beginning_and_end"
85
+ )
86
+ parser.add_argument("-i", "--input_dir", type=str, help="Dataset root dir", required=True)
87
+ parser.add_argument("-o", "--output_dir", type=str, help="Output Dataset dir", default="")
88
+ parser.add_argument("-f", "--force", default=False, action="store_true", help="Force the replace of exists files")
89
+ parser.add_argument(
90
+ "-g",
91
+ "--glob",
92
+ type=str,
93
+ default="**/*.wav",
94
+ help="path in glob format for acess wavs from input_dir. ex: wav48/*/*.wav",
95
+ )
96
+ parser.add_argument(
97
+ "-t",
98
+ "--trim_just_beginning_and_end",
99
+ action=argparse.BooleanOptionalAction,
100
+ default=True,
101
+ help="If True this script will trim just the beginning and end nonspeech parts. If False all nonspeech parts will be trimmed.",
102
+ )
103
+ parser.add_argument(
104
+ "-c",
105
+ "--use_cuda",
106
+ action=argparse.BooleanOptionalAction,
107
+ default=False,
108
+ help="If True use cuda",
109
+ )
110
+ parser.add_argument(
111
+ "--use_onnx",
112
+ action=argparse.BooleanOptionalAction,
113
+ default=False,
114
+ help="If True use onnx",
115
+ )
116
+ parser.add_argument(
117
+ "--num_processes",
118
+ type=int,
119
+ default=1,
120
+ help="Number of processes to use",
121
+ )
122
+ args = parser.parse_args()
123
+
124
+ if args.output_dir == "":
125
+ args.output_dir = args.input_dir
126
+
127
+ # load the model and utils
128
+ model_and_utils = get_vad_model_and_utils(use_cuda=args.use_cuda, use_onnx=args.use_onnx)
129
+ preprocess_audios()
TTS/bin/resample.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import glob
3
+ import os
4
+ from argparse import RawTextHelpFormatter
5
+ from multiprocessing import Pool
6
+ from shutil import copytree
7
+
8
+ import librosa
9
+ import soundfile as sf
10
+ from tqdm import tqdm
11
+
12
+
13
+ def resample_file(func_args):
14
+ filename, output_sr = func_args
15
+ y, sr = librosa.load(filename, sr=output_sr)
16
+ sf.write(filename, y, sr)
17
+
18
+
19
+ def resample_files(input_dir, output_sr, output_dir=None, file_ext="wav", n_jobs=10):
20
+ if output_dir:
21
+ print("Recursively copying the input folder...")
22
+ copytree(input_dir, output_dir)
23
+ input_dir = output_dir
24
+
25
+ print("Resampling the audio files...")
26
+ audio_files = glob.glob(os.path.join(input_dir, f"**/*.{file_ext}"), recursive=True)
27
+ print(f"Found {len(audio_files)} files...")
28
+ audio_files = list(zip(audio_files, len(audio_files) * [output_sr]))
29
+ with Pool(processes=n_jobs) as p:
30
+ with tqdm(total=len(audio_files)) as pbar:
31
+ for _, _ in enumerate(p.imap_unordered(resample_file, audio_files)):
32
+ pbar.update()
33
+
34
+ print("Done !")
35
+
36
+
37
+ if __name__ == "__main__":
38
+ parser = argparse.ArgumentParser(
39
+ description="""Resample a folder recusively with librosa
40
+ Can be used in place or create a copy of the folder as an output.\n\n
41
+ Example run:
42
+ python TTS/bin/resample.py
43
+ --input_dir /root/LJSpeech-1.1/
44
+ --output_sr 22050
45
+ --output_dir /root/resampled_LJSpeech-1.1/
46
+ --file_ext wav
47
+ --n_jobs 24
48
+ """,
49
+ formatter_class=RawTextHelpFormatter,
50
+ )
51
+
52
+ parser.add_argument(
53
+ "--input_dir",
54
+ type=str,
55
+ default=None,
56
+ required=True,
57
+ help="Path of the folder containing the audio files to resample",
58
+ )
59
+
60
+ parser.add_argument(
61
+ "--output_sr",
62
+ type=int,
63
+ default=22050,
64
+ required=False,
65
+ help="Samlple rate to which the audio files should be resampled",
66
+ )
67
+
68
+ parser.add_argument(
69
+ "--output_dir",
70
+ type=str,
71
+ default=None,
72
+ required=False,
73
+ help="Path of the destination folder. If not defined, the operation is done in place",
74
+ )
75
+
76
+ parser.add_argument(
77
+ "--file_ext",
78
+ type=str,
79
+ default="wav",
80
+ required=False,
81
+ help="Extension of the audio files to resample",
82
+ )
83
+
84
+ parser.add_argument(
85
+ "--n_jobs", type=int, default=None, help="Number of threads to use, by default it uses all cores"
86
+ )
87
+
88
+ args = parser.parse_args()
89
+
90
+ resample_files(args.input_dir, args.output_sr, args.output_dir, args.file_ext, args.n_jobs)
TTS/bin/synthesize.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ """Command line interface."""
4
+
5
+ import argparse
6
+ import contextlib
7
+ import logging
8
+ import sys
9
+ from argparse import RawTextHelpFormatter
10
+
11
+ # pylint: disable=redefined-outer-name, unused-argument
12
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ description = """
17
+ Synthesize speech on the command line.
18
+
19
+ You can either use your trained model or choose a model from the provided list.
20
+
21
+ - List provided models:
22
+
23
+ ```sh
24
+ tts --list_models
25
+ ```
26
+
27
+ - Get model information. Use the names obtained from `--list_models`.
28
+ ```sh
29
+ tts --model_info_by_name "<model_type>/<language>/<dataset>/<model_name>"
30
+ ```
31
+ For example:
32
+ ```sh
33
+ tts --model_info_by_name tts_models/tr/common-voice/glow-tts
34
+ tts --model_info_by_name vocoder_models/en/ljspeech/hifigan_v2
35
+ ```
36
+
37
+ #### Single speaker models
38
+
39
+ - Run TTS with the default model (`tts_models/en/ljspeech/tacotron2-DDC`):
40
+
41
+ ```sh
42
+ tts --text "Text for TTS" --out_path output/path/speech.wav
43
+ ```
44
+
45
+ - Run TTS and pipe out the generated TTS wav file data:
46
+
47
+ ```sh
48
+ tts --text "Text for TTS" --pipe_out --out_path output/path/speech.wav | aplay
49
+ ```
50
+
51
+ - Run a TTS model with its default vocoder model:
52
+
53
+ ```sh
54
+ tts --text "Text for TTS" \\
55
+ --model_name "<model_type>/<language>/<dataset>/<model_name>" \\
56
+ --out_path output/path/speech.wav
57
+ ```
58
+
59
+ For example:
60
+
61
+ ```sh
62
+ tts --text "Text for TTS" \\
63
+ --model_name "tts_models/en/ljspeech/glow-tts" \\
64
+ --out_path output/path/speech.wav
65
+ ```
66
+
67
+ - Run with specific TTS and vocoder models from the list. Note that not every vocoder is compatible with every TTS model.
68
+
69
+ ```sh
70
+ tts --text "Text for TTS" \\
71
+ --model_name "<model_type>/<language>/<dataset>/<model_name>" \\
72
+ --vocoder_name "<model_type>/<language>/<dataset>/<model_name>" \\
73
+ --out_path output/path/speech.wav
74
+ ```
75
+
76
+ For example:
77
+
78
+ ```sh
79
+ tts --text "Text for TTS" \\
80
+ --model_name "tts_models/en/ljspeech/glow-tts" \\
81
+ --vocoder_name "vocoder_models/en/ljspeech/univnet" \\
82
+ --out_path output/path/speech.wav
83
+ ```
84
+
85
+ - Run your own TTS model (using Griffin-Lim Vocoder):
86
+
87
+ ```sh
88
+ tts --text "Text for TTS" \\
89
+ --model_path path/to/model.pth \\
90
+ --config_path path/to/config.json \\
91
+ --out_path output/path/speech.wav
92
+ ```
93
+
94
+ - Run your own TTS and Vocoder models:
95
+
96
+ ```sh
97
+ tts --text "Text for TTS" \\
98
+ --model_path path/to/model.pth \\
99
+ --config_path path/to/config.json \\
100
+ --out_path output/path/speech.wav \\
101
+ --vocoder_path path/to/vocoder.pth \\
102
+ --vocoder_config_path path/to/vocoder_config.json
103
+ ```
104
+
105
+ #### Multi-speaker models
106
+
107
+ - List the available speakers and choose a `<speaker_id>` among them:
108
+
109
+ ```sh
110
+ tts --model_name "<language>/<dataset>/<model_name>" --list_speaker_idxs
111
+ ```
112
+
113
+ - Run the multi-speaker TTS model with the target speaker ID:
114
+
115
+ ```sh
116
+ tts --text "Text for TTS." --out_path output/path/speech.wav \\
117
+ --model_name "<language>/<dataset>/<model_name>" --speaker_idx <speaker_id>
118
+ ```
119
+
120
+ - Run your own multi-speaker TTS model:
121
+
122
+ ```sh
123
+ tts --text "Text for TTS" --out_path output/path/speech.wav \\
124
+ --model_path path/to/model.pth --config_path path/to/config.json \\
125
+ --speakers_file_path path/to/speaker.json --speaker_idx <speaker_id>
126
+ ```
127
+
128
+ #### Voice conversion models
129
+
130
+ ```sh
131
+ tts --out_path output/path/speech.wav --model_name "<language>/<dataset>/<model_name>" \\
132
+ --source_wav <path/to/speaker/wav> --target_wav <path/to/reference/wav>
133
+ ```
134
+ """
135
+
136
+
137
+ def parse_args(arg_list: list[str] | None) -> argparse.Namespace:
138
+ """Parse arguments."""
139
+ parser = argparse.ArgumentParser(
140
+ description=description.replace(" ```\n", ""),
141
+ formatter_class=RawTextHelpFormatter,
142
+ )
143
+
144
+ parser.add_argument(
145
+ "--list_models",
146
+ action="store_true",
147
+ help="list available pre-trained TTS and vocoder models.",
148
+ )
149
+
150
+ parser.add_argument(
151
+ "--model_info_by_idx",
152
+ type=str,
153
+ default=None,
154
+ help="model info using query format: <model_type>/<model_query_idx>",
155
+ )
156
+
157
+ parser.add_argument(
158
+ "--model_info_by_name",
159
+ type=str,
160
+ default=None,
161
+ help="model info using query format: <model_type>/<language>/<dataset>/<model_name>",
162
+ )
163
+
164
+ parser.add_argument("--text", type=str, default=None, help="Text to generate speech.")
165
+
166
+ # Args for running pre-trained TTS models.
167
+ parser.add_argument(
168
+ "--model_name",
169
+ type=str,
170
+ default="tts_models/en/ljspeech/tacotron2-DDC",
171
+ help="Name of one of the pre-trained TTS models in format <language>/<dataset>/<model_name>",
172
+ )
173
+ parser.add_argument(
174
+ "--vocoder_name",
175
+ type=str,
176
+ default=None,
177
+ help="Name of one of the pre-trained vocoder models in format <language>/<dataset>/<model_name>",
178
+ )
179
+
180
+ # Args for running custom models
181
+ parser.add_argument("--config_path", default=None, type=str, help="Path to model config file.")
182
+ parser.add_argument(
183
+ "--model_path",
184
+ type=str,
185
+ default=None,
186
+ help="Path to model file.",
187
+ )
188
+ parser.add_argument(
189
+ "--out_path",
190
+ type=str,
191
+ default="tts_output.wav",
192
+ help="Output wav file path.",
193
+ )
194
+ parser.add_argument("--use_cuda", action="store_true", help="Run model on CUDA.")
195
+ parser.add_argument("--device", type=str, help="Device to run model on.", default="cpu")
196
+ parser.add_argument(
197
+ "--vocoder_path",
198
+ type=str,
199
+ help="Path to vocoder model file. If it is not defined, model uses GL as vocoder. Please make sure that you installed vocoder library before (WaveRNN).",
200
+ default=None,
201
+ )
202
+ parser.add_argument("--vocoder_config_path", type=str, help="Path to vocoder model config file.", default=None)
203
+ parser.add_argument(
204
+ "--encoder_path",
205
+ type=str,
206
+ help="Path to speaker encoder model file.",
207
+ default=None,
208
+ )
209
+ parser.add_argument("--encoder_config_path", type=str, help="Path to speaker encoder config file.", default=None)
210
+ parser.add_argument(
211
+ "--pipe_out",
212
+ help="stdout the generated TTS wav file for shell pipe.",
213
+ action="store_true",
214
+ )
215
+
216
+ # args for multi-speaker synthesis
217
+ parser.add_argument("--speakers_file_path", type=str, help="JSON file for multi-speaker model.", default=None)
218
+ parser.add_argument("--language_ids_file_path", type=str, help="JSON file for multi-lingual model.", default=None)
219
+ parser.add_argument(
220
+ "--speaker_idx",
221
+ type=str,
222
+ help="Target speaker ID for a multi-speaker TTS model.",
223
+ default=None,
224
+ )
225
+ parser.add_argument(
226
+ "--language_idx",
227
+ type=str,
228
+ help="Target language ID for a multi-lingual TTS model.",
229
+ default=None,
230
+ )
231
+ parser.add_argument(
232
+ "--speaker_wav",
233
+ nargs="+",
234
+ help="wav file(s) to condition a multi-speaker TTS model with a Speaker Encoder. You can give multiple file paths. The d_vectors is computed as their average.",
235
+ default=None,
236
+ )
237
+ parser.add_argument("--gst_style", help="Wav path file for GST style reference.", default=None)
238
+ parser.add_argument(
239
+ "--capacitron_style_wav", type=str, help="Wav path file for Capacitron prosody reference.", default=None
240
+ )
241
+ parser.add_argument("--capacitron_style_text", type=str, help="Transcription of the reference.", default=None)
242
+ parser.add_argument(
243
+ "--list_speaker_idxs",
244
+ help="List available speaker ids for the defined multi-speaker model.",
245
+ action="store_true",
246
+ )
247
+ parser.add_argument(
248
+ "--list_language_idxs",
249
+ help="List available language ids for the defined multi-lingual model.",
250
+ action="store_true",
251
+ )
252
+ # aux args
253
+ parser.add_argument(
254
+ "--reference_wav",
255
+ type=str,
256
+ help="Reference wav file to convert in the voice of the speaker_idx or speaker_wav",
257
+ default=None,
258
+ )
259
+ parser.add_argument(
260
+ "--reference_speaker_idx",
261
+ type=str,
262
+ help="speaker ID of the reference_wav speaker (If not provided the embedding will be computed using the Speaker Encoder).",
263
+ default=None,
264
+ )
265
+ parser.add_argument(
266
+ "--progress_bar",
267
+ action=argparse.BooleanOptionalAction,
268
+ help="Show a progress bar for the model download.",
269
+ default=True,
270
+ )
271
+
272
+ # voice conversion args
273
+ parser.add_argument(
274
+ "--source_wav",
275
+ type=str,
276
+ default=None,
277
+ help="Original audio file to convert into the voice of the target_wav",
278
+ )
279
+ parser.add_argument(
280
+ "--target_wav",
281
+ type=str,
282
+ nargs="*",
283
+ default=None,
284
+ help="Audio file(s) of the target voice into which to convert the source_wav",
285
+ )
286
+
287
+ parser.add_argument(
288
+ "--voice_dir",
289
+ type=str,
290
+ default=None,
291
+ help="Voice dir for tortoise model",
292
+ )
293
+
294
+ args = parser.parse_args(arg_list)
295
+
296
+ # print the description if either text or list_models is not set
297
+ check_args = [
298
+ args.text,
299
+ args.list_models,
300
+ args.list_speaker_idxs,
301
+ args.list_language_idxs,
302
+ args.reference_wav,
303
+ args.model_info_by_idx,
304
+ args.model_info_by_name,
305
+ args.source_wav,
306
+ args.target_wav,
307
+ ]
308
+ if not any(check_args):
309
+ parser.parse_args(["-h"])
310
+ return args
311
+
312
+
313
+ def main(arg_list: list[str] | None = None) -> None:
314
+ """Entry point for `tts` command line interface."""
315
+ args = parse_args(arg_list)
316
+ stream = sys.stderr if args.pipe_out else sys.stdout
317
+ setup_logger("TTS", level=logging.INFO, stream=stream, formatter=ConsoleFormatter())
318
+
319
+ pipe_out = sys.stdout if args.pipe_out else None
320
+
321
+ with contextlib.redirect_stdout(None if args.pipe_out else sys.stdout):
322
+ # Late-import to make things load faster
323
+ from TTS.api import TTS
324
+ from TTS.utils.manage import ModelManager
325
+
326
+ # load model manager
327
+ manager = ModelManager(models_file=TTS.get_models_file_path(), progress_bar=args.progress_bar)
328
+
329
+ tts_path = None
330
+ tts_config_path = None
331
+ speakers_file_path = None
332
+ language_ids_file_path = None
333
+ vocoder_path = None
334
+ vocoder_config_path = None
335
+ encoder_path = None
336
+ encoder_config_path = None
337
+ vc_path = None
338
+ vc_config_path = None
339
+ model_dir = None
340
+
341
+ # 1) List pre-trained TTS models
342
+ if args.list_models:
343
+ manager.list_models()
344
+ sys.exit(0)
345
+
346
+ # 2) Info about pre-trained TTS models (without loading a model)
347
+ if args.model_info_by_idx:
348
+ model_query = args.model_info_by_idx
349
+ manager.model_info_by_idx(model_query)
350
+ sys.exit(0)
351
+
352
+ if args.model_info_by_name:
353
+ model_query_full_name = args.model_info_by_name
354
+ manager.model_info_by_full_name(model_query_full_name)
355
+ sys.exit(0)
356
+
357
+ # 3) Load a model for further info or TTS/VC
358
+ device = args.device
359
+ if args.use_cuda:
360
+ device = "cuda"
361
+ # A local model will take precedence if specified via modeL_path
362
+ model_name = args.model_name if args.model_path is None else None
363
+ api = TTS(
364
+ model_name=model_name,
365
+ model_path=args.model_path,
366
+ config_path=args.config_path,
367
+ vocoder_name=args.vocoder_name,
368
+ vocoder_path=args.vocoder_path,
369
+ vocoder_config_path=args.vocoder_config_path,
370
+ encoder_path=args.encoder_path,
371
+ encoder_config_path=args.encoder_config_path,
372
+ speakers_file_path=args.speakers_file_path,
373
+ language_ids_file_path=args.language_ids_file_path,
374
+ progress_bar=args.progress_bar,
375
+ ).to(device)
376
+
377
+ # query speaker ids of a multi-speaker model.
378
+ if args.list_speaker_idxs:
379
+ if not api.is_multi_speaker:
380
+ logger.info("Model only has a single speaker.")
381
+ sys.exit(0)
382
+ logger.info(
383
+ "Available speaker ids: (Set --speaker_idx flag to one of these values to use the multi-speaker model."
384
+ )
385
+ logger.info(api.speakers)
386
+ sys.exit(0)
387
+
388
+ # query language ids of a multi-lingual model.
389
+ if args.list_language_idxs:
390
+ if not api.is_multi_lingual:
391
+ logger.info("Monolingual model.")
392
+ sys.exit(0)
393
+ logger.info(
394
+ "Available language ids: (Set --language_idx flag to one of these values to use the multi-lingual model."
395
+ )
396
+ logger.info(api.languages)
397
+ sys.exit(0)
398
+
399
+ # RUN THE SYNTHESIS
400
+ if args.text:
401
+ logger.info("Text: %s", args.text)
402
+
403
+ if args.text is not None:
404
+ api.tts_to_file(
405
+ text=args.text,
406
+ speaker=args.speaker_idx,
407
+ language=args.language_idx,
408
+ speaker_wav=args.speaker_wav,
409
+ pipe_out=pipe_out,
410
+ file_path=args.out_path,
411
+ reference_wav=args.reference_wav,
412
+ style_wav=args.capacitron_style_wav,
413
+ style_text=args.capacitron_style_text,
414
+ reference_speaker_name=args.reference_speaker_idx,
415
+ voice_dir=args.voice_dir,
416
+ )
417
+ logger.info("Saved TTS output to %s", args.out_path)
418
+ elif args.source_wav is not None and args.target_wav is not None:
419
+ api.voice_conversion_to_file(
420
+ source_wav=args.source_wav,
421
+ target_wav=args.target_wav,
422
+ file_path=args.out_path,
423
+ speaker=args.speaker_idx,
424
+ voice_dir=args.voice_dir,
425
+ pipe_out=pipe_out,
426
+ )
427
+ logger.info("Saved VC output to %s", args.out_path)
428
+ sys.exit(0)
429
+
430
+
431
+ if __name__ == "__main__":
432
+ main()
TTS/bin/train_encoder.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # TODO: use Trainer
4
+
5
+ import logging
6
+ import os
7
+ import sys
8
+ import time
9
+ import warnings
10
+ from dataclasses import dataclass, field
11
+
12
+ import torch
13
+ from torch.utils.data import DataLoader
14
+ from trainer import TrainerArgs, TrainerConfig
15
+ from trainer.generic_utils import count_parameters, get_experiment_folder_path, get_git_branch
16
+ from trainer.io import copy_model_files, get_last_checkpoint, save_best_model, save_checkpoint
17
+ from trainer.logging import BaseDashboardLogger, ConsoleLogger, logger_factory
18
+ from trainer.torch import NoamLR
19
+ from trainer.trainer_utils import get_optimizer
20
+
21
+ from TTS.config import load_config, register_config
22
+ from TTS.encoder.configs.base_encoder_config import BaseEncoderConfig
23
+ from TTS.encoder.dataset import EncoderDataset
24
+ from TTS.encoder.utils.generic_utils import setup_encoder_model
25
+ from TTS.encoder.utils.visual import plot_embeddings
26
+ from TTS.tts.datasets import load_tts_samples
27
+ from TTS.tts.utils.text.characters import parse_symbols
28
+ from TTS.utils.audio import AudioProcessor
29
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
30
+ from TTS.utils.samplers import PerfectBatchSampler
31
+ from TTS.utils.training import check_update
32
+
33
+ torch.backends.cudnn.enabled = True
34
+ torch.backends.cudnn.benchmark = True
35
+ torch.manual_seed(54321)
36
+ use_cuda = torch.cuda.is_available()
37
+ num_gpus = torch.cuda.device_count()
38
+ print(" > Using CUDA: ", use_cuda)
39
+ print(" > Number of GPUs: ", num_gpus)
40
+
41
+
42
+ @dataclass
43
+ class TrainArgs(TrainerArgs):
44
+ config_path: str | None = field(default=None, metadata={"help": "Path to the config file."})
45
+
46
+
47
+ def process_args(
48
+ args, config: BaseEncoderConfig | None = None
49
+ ) -> tuple[BaseEncoderConfig, str, str, ConsoleLogger, BaseDashboardLogger | None]:
50
+ """Process parsed comand line arguments and initialize the config if not provided.
51
+ Args:
52
+ args (argparse.Namespace or dict like): Parsed input arguments.
53
+ config (Coqpit): Model config. If none, it is generated from `args`. Defaults to None.
54
+ Returns:
55
+ c (Coqpit): Config paramaters.
56
+ out_path (str): Path to save models and logging.
57
+ audio_path (str): Path to save generated test audios.
58
+ c_logger (TTS.utils.console_logger.ConsoleLogger): Class that does
59
+ logging to the console.
60
+ dashboard_logger (WandbLogger or TensorboardLogger): Class that does the dashboard Logging
61
+ TODO:
62
+ - Interactive config definition.
63
+ """
64
+ coqpit_overrides = None
65
+ if isinstance(args, tuple):
66
+ args, coqpit_overrides = args
67
+ if args.continue_path:
68
+ # continue a previous training from its output folder
69
+ experiment_path = args.continue_path
70
+ args.config_path = os.path.join(args.continue_path, "config.json")
71
+ args.restore_path, best_model = get_last_checkpoint(args.continue_path)
72
+ if not args.best_path:
73
+ args.best_path = best_model
74
+ # init config if not already defined
75
+ if config is None:
76
+ if args.config_path:
77
+ # init from a file
78
+ config = load_config(args.config_path)
79
+ else:
80
+ # init from console args
81
+ from TTS.config.shared_configs import BaseTrainingConfig # pylint: disable=import-outside-toplevel
82
+
83
+ config_base = BaseTrainingConfig()
84
+ config_base.parse_known_args(coqpit_overrides)
85
+ config = register_config(config_base.model)()
86
+ # override values from command-line args
87
+ config.parse_known_args(coqpit_overrides, relaxed_parser=True)
88
+ experiment_path = args.continue_path
89
+ if not experiment_path:
90
+ experiment_path = get_experiment_folder_path(config.output_path, config.run_name)
91
+ audio_path = os.path.join(experiment_path, "test_audios")
92
+ config.output_log_path = experiment_path
93
+ # setup rank 0 process in distributed training
94
+ dashboard_logger = None
95
+ if args.rank == 0:
96
+ new_fields = {}
97
+ if args.restore_path:
98
+ new_fields["restore_path"] = args.restore_path
99
+ new_fields["github_branch"] = get_git_branch()
100
+ # if model characters are not set in the config file
101
+ # save the default set to the config file for future
102
+ # compatibility.
103
+ if config.has("characters") and config.characters is None:
104
+ used_characters = parse_symbols()
105
+ new_fields["characters"] = used_characters
106
+ copy_model_files(config, experiment_path, new_fields)
107
+ dashboard_logger = logger_factory(config, experiment_path)
108
+ c_logger = ConsoleLogger()
109
+ return config, experiment_path, audio_path, c_logger, dashboard_logger
110
+
111
+
112
+ def setup_loader(c: TrainerConfig, ap: AudioProcessor, is_val: bool = False):
113
+ num_utter_per_class = c.num_utter_per_class if not is_val else c.eval_num_utter_per_class
114
+ num_classes_in_batch = c.num_classes_in_batch if not is_val else c.eval_num_classes_in_batch
115
+
116
+ dataset = EncoderDataset(
117
+ c,
118
+ ap,
119
+ meta_data_eval if is_val else meta_data_train,
120
+ voice_len=c.voice_len,
121
+ num_utter_per_class=num_utter_per_class,
122
+ num_classes_in_batch=num_classes_in_batch,
123
+ augmentation_config=c.audio_augmentation if not is_val else None,
124
+ use_torch_spec=c.model_params.get("use_torch_spec", False),
125
+ )
126
+ # get classes list
127
+ classes = dataset.get_class_list()
128
+
129
+ sampler = PerfectBatchSampler(
130
+ dataset.items,
131
+ classes,
132
+ batch_size=num_classes_in_batch * num_utter_per_class, # total batch size
133
+ num_classes_in_batch=num_classes_in_batch,
134
+ num_gpus=1,
135
+ shuffle=not is_val,
136
+ drop_last=True,
137
+ )
138
+
139
+ if len(classes) < num_classes_in_batch:
140
+ if is_val:
141
+ raise RuntimeError(
142
+ f"config.eval_num_classes_in_batch ({num_classes_in_batch}) need to be <= {len(classes)} (Number total of Classes in the Eval dataset) !"
143
+ )
144
+ raise RuntimeError(
145
+ f"config.num_classes_in_batch ({num_classes_in_batch}) need to be <= {len(classes)} (Number total of Classes in the Train dataset) !"
146
+ )
147
+
148
+ # set the classes to avoid get wrong class_id when the number of training and eval classes are not equal
149
+ if is_val:
150
+ dataset.set_classes(train_classes)
151
+
152
+ loader = DataLoader(
153
+ dataset,
154
+ num_workers=c.num_loader_workers,
155
+ batch_sampler=sampler,
156
+ collate_fn=dataset.collate_fn,
157
+ )
158
+
159
+ return loader, classes, dataset.get_map_classid_to_classname()
160
+
161
+
162
+ def evaluation(c: BaseEncoderConfig, model, criterion, data_loader, global_step, dashboard_logger: BaseDashboardLogger):
163
+ eval_loss = 0
164
+ for _, data in enumerate(data_loader):
165
+ with torch.inference_mode():
166
+ # setup input data
167
+ inputs, labels = data
168
+
169
+ # agroup samples of each class in the batch. perfect sampler produces [3,2,1,3,2,1] we need [3,3,2,2,1,1]
170
+ labels = torch.transpose(
171
+ labels.view(c.eval_num_utter_per_class, c.eval_num_classes_in_batch), 0, 1
172
+ ).reshape(labels.shape)
173
+ inputs = torch.transpose(
174
+ inputs.view(c.eval_num_utter_per_class, c.eval_num_classes_in_batch, -1), 0, 1
175
+ ).reshape(inputs.shape)
176
+
177
+ # dispatch data to GPU
178
+ if use_cuda:
179
+ inputs = inputs.cuda(non_blocking=True)
180
+ labels = labels.cuda(non_blocking=True)
181
+
182
+ # forward pass model
183
+ outputs = model(inputs)
184
+
185
+ # loss computation
186
+ loss = criterion(
187
+ outputs.view(c.eval_num_classes_in_batch, outputs.shape[0] // c.eval_num_classes_in_batch, -1), labels
188
+ )
189
+
190
+ eval_loss += loss.item()
191
+
192
+ eval_avg_loss = eval_loss / len(data_loader)
193
+ # save stats
194
+ dashboard_logger.eval_stats(global_step, {"loss": eval_avg_loss})
195
+ try:
196
+ # plot the last batch in the evaluation
197
+ figures = {
198
+ "UMAP Plot": plot_embeddings(outputs.detach().cpu().numpy(), c.num_classes_in_batch),
199
+ }
200
+ dashboard_logger.eval_figures(global_step, figures)
201
+ except ImportError:
202
+ warnings.warn("Install the `umap-learn` package to see embedding plots.")
203
+ return eval_avg_loss
204
+
205
+
206
+ def train(
207
+ c: BaseEncoderConfig,
208
+ model,
209
+ optimizer,
210
+ scheduler,
211
+ criterion,
212
+ data_loader,
213
+ eval_data_loader,
214
+ global_step,
215
+ dashboard_logger: BaseDashboardLogger,
216
+ ):
217
+ model.train()
218
+ best_loss = {"train_loss": None, "eval_loss": float("inf")}
219
+ avg_loader_time = 0
220
+ end_time = time.time()
221
+ for epoch in range(c.epochs):
222
+ tot_loss = 0
223
+ epoch_time = 0
224
+ for _, data in enumerate(data_loader):
225
+ start_time = time.time()
226
+
227
+ # setup input data
228
+ inputs, labels = data
229
+ # agroup samples of each class in the batch. perfect sampler produces [3,2,1,3,2,1] we need [3,3,2,2,1,1]
230
+ labels = torch.transpose(labels.view(c.num_utter_per_class, c.num_classes_in_batch), 0, 1).reshape(
231
+ labels.shape
232
+ )
233
+ inputs = torch.transpose(inputs.view(c.num_utter_per_class, c.num_classes_in_batch, -1), 0, 1).reshape(
234
+ inputs.shape
235
+ )
236
+ # ToDo: move it to a unit test
237
+ # labels_converted = torch.transpose(labels.view(c.num_utter_per_class, c.num_classes_in_batch), 0, 1).reshape(labels.shape)
238
+ # inputs_converted = torch.transpose(inputs.view(c.num_utter_per_class, c.num_classes_in_batch, -1), 0, 1).reshape(inputs.shape)
239
+ # idx = 0
240
+ # for j in range(0, c.num_classes_in_batch, 1):
241
+ # for i in range(j, len(labels), c.num_classes_in_batch):
242
+ # if not torch.all(labels[i].eq(labels_converted[idx])) or not torch.all(inputs[i].eq(inputs_converted[idx])):
243
+ # print("Invalid")
244
+ # print(labels)
245
+ # exit()
246
+ # idx += 1
247
+ # labels = labels_converted
248
+ # inputs = inputs_converted
249
+
250
+ loader_time = time.time() - end_time
251
+ global_step += 1
252
+
253
+ optimizer.zero_grad()
254
+
255
+ # dispatch data to GPU
256
+ if use_cuda:
257
+ inputs = inputs.cuda(non_blocking=True)
258
+ labels = labels.cuda(non_blocking=True)
259
+
260
+ # forward pass model
261
+ outputs = model(inputs)
262
+
263
+ # loss computation
264
+ loss = criterion(
265
+ outputs.view(c.num_classes_in_batch, outputs.shape[0] // c.num_classes_in_batch, -1), labels
266
+ )
267
+ loss.backward()
268
+ grad_norm, _ = check_update(model, c.grad_clip)
269
+ optimizer.step()
270
+
271
+ # setup lr
272
+ if c.lr_decay:
273
+ scheduler.step()
274
+
275
+ step_time = time.time() - start_time
276
+ epoch_time += step_time
277
+
278
+ # acumulate the total epoch loss
279
+ tot_loss += loss.item()
280
+
281
+ # Averaged Loader Time
282
+ num_loader_workers = c.num_loader_workers if c.num_loader_workers > 0 else 1
283
+ avg_loader_time = (
284
+ 1 / num_loader_workers * loader_time + (num_loader_workers - 1) / num_loader_workers * avg_loader_time
285
+ if avg_loader_time != 0
286
+ else loader_time
287
+ )
288
+ current_lr = optimizer.param_groups[0]["lr"]
289
+
290
+ if global_step % c.steps_plot_stats == 0:
291
+ # Plot Training Epoch Stats
292
+ train_stats = {
293
+ "loss": loss.item(),
294
+ "lr": current_lr,
295
+ "grad_norm": grad_norm,
296
+ "step_time": step_time,
297
+ "avg_loader_time": avg_loader_time,
298
+ }
299
+ dashboard_logger.train_epoch_stats(global_step, train_stats)
300
+ figures = {
301
+ "UMAP Plot": plot_embeddings(outputs.detach().cpu().numpy(), c.num_classes_in_batch),
302
+ }
303
+ dashboard_logger.train_figures(global_step, figures)
304
+
305
+ if global_step % c.print_step == 0:
306
+ print(
307
+ f" | > Step:{global_step} Loss:{loss.item():.5f} GradNorm:{grad_norm:.5f} "
308
+ f"StepTime:{step_time:.2f} LoaderTime:{loader_time:.2f} AvGLoaderTime:{avg_loader_time:.2f} LR:{current_lr:.6f}",
309
+ flush=True,
310
+ )
311
+
312
+ if global_step % c.save_step == 0:
313
+ # save model
314
+ save_checkpoint(
315
+ c,
316
+ model,
317
+ c.output_log_path,
318
+ current_step=global_step,
319
+ epoch=epoch,
320
+ optimizer=optimizer,
321
+ criterion=criterion.state_dict(),
322
+ )
323
+
324
+ end_time = time.time()
325
+
326
+ print("")
327
+ print(
328
+ f">>> Epoch:{epoch} AvgLoss: {tot_loss / len(data_loader):.5f} GradNorm:{grad_norm:.5f} "
329
+ f"EpochTime:{epoch_time:.2f} AvGLoaderTime:{avg_loader_time:.2f} ",
330
+ flush=True,
331
+ )
332
+ # evaluation
333
+ if c.run_eval:
334
+ model.eval()
335
+ eval_loss = evaluation(c, model, criterion, eval_data_loader, global_step, dashboard_logger)
336
+ print("\n\n")
337
+ print("--> EVAL PERFORMANCE")
338
+ print(
339
+ f" | > Epoch:{epoch} AvgLoss: {eval_loss:.5f} ",
340
+ flush=True,
341
+ )
342
+ # save the best checkpoint
343
+ best_loss = save_best_model(
344
+ {"train_loss": None, "eval_loss": eval_loss},
345
+ best_loss,
346
+ c,
347
+ model,
348
+ c.output_log_path,
349
+ current_step=global_step,
350
+ epoch=epoch,
351
+ optimizer=optimizer,
352
+ criterion=criterion.state_dict(),
353
+ )
354
+ model.train()
355
+
356
+ return best_loss, global_step
357
+
358
+
359
+ def main(arg_list: list[str] | None = None):
360
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
361
+
362
+ train_config = TrainArgs()
363
+ parser = train_config.init_argparse(arg_prefix="")
364
+ args, overrides = parser.parse_known_args(arg_list)
365
+ c, OUT_PATH, AUDIO_PATH, c_logger, dashboard_logger = process_args((args, overrides))
366
+ # pylint: disable=global-variable-undefined
367
+ global meta_data_train
368
+ global meta_data_eval
369
+ global train_classes
370
+
371
+ ap = AudioProcessor(**c.audio)
372
+ model = setup_encoder_model(c)
373
+
374
+ optimizer = get_optimizer(c.optimizer, c.optimizer_params, c.lr, model)
375
+
376
+ # pylint: disable=redefined-outer-name
377
+ meta_data_train, meta_data_eval = load_tts_samples(c.datasets, eval_split=True)
378
+
379
+ train_data_loader, train_classes, map_classid_to_classname = setup_loader(c, ap, is_val=False)
380
+ if c.run_eval:
381
+ eval_data_loader, _, _ = setup_loader(c, ap, is_val=True)
382
+ else:
383
+ eval_data_loader = None
384
+
385
+ num_classes = len(train_classes)
386
+ criterion = model.get_criterion(c, num_classes)
387
+
388
+ if c.loss == "softmaxproto" and c.model != "speaker_encoder":
389
+ c.map_classid_to_classname = map_classid_to_classname
390
+ copy_model_files(c, OUT_PATH, new_fields={})
391
+
392
+ if args.restore_path:
393
+ criterion, args.restore_step = model.load_checkpoint(
394
+ c, args.restore_path, eval=False, use_cuda=use_cuda, criterion=criterion
395
+ )
396
+ print(f" > Model restored from step {args.restore_step}", flush=True)
397
+ else:
398
+ args.restore_step = 0
399
+
400
+ if c.lr_decay:
401
+ scheduler = NoamLR(optimizer, warmup_steps=c.warmup_steps, last_epoch=args.restore_step - 1)
402
+ else:
403
+ scheduler = None
404
+
405
+ num_params = count_parameters(model)
406
+ print(f"\n > Model has {num_params} parameters", flush=True)
407
+
408
+ if use_cuda:
409
+ model = model.cuda()
410
+ criterion.cuda()
411
+
412
+ global_step = args.restore_step
413
+ _, global_step = train(
414
+ c, model, optimizer, scheduler, criterion, train_data_loader, eval_data_loader, global_step, dashboard_logger
415
+ )
416
+ sys.exit(0)
417
+
418
+
419
+ if __name__ == "__main__":
420
+ main()
421
+ # try:
422
+ # main()
423
+ # except KeyboardInterrupt:
424
+ # remove_experiment_folder(OUT_PATH)
425
+ # try:
426
+ # sys.exit(0)
427
+ # except SystemExit:
428
+ # os._exit(0) # pylint: disable=protected-access
429
+ # except Exception: # pylint: disable=broad-except
430
+ # remove_experiment_folder(OUT_PATH)
431
+ # traceback.print_exc()
432
+ # sys.exit(1)
TTS/bin/train_tts.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import sys
4
+ from dataclasses import dataclass, field
5
+
6
+ from trainer import Trainer, TrainerArgs
7
+
8
+ from TTS.config import load_config, register_config
9
+ from TTS.tts.datasets import load_tts_samples
10
+ from TTS.tts.models import setup_model
11
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
12
+
13
+
14
+ @dataclass
15
+ class TrainTTSArgs(TrainerArgs):
16
+ config_path: str = field(default=None, metadata={"help": "Path to the config file."})
17
+
18
+
19
+ def main(arg_list: list[str] | None = None):
20
+ """Run `tts` model training directly by a `config.json` file."""
21
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
22
+
23
+ # init trainer args
24
+ train_args = TrainTTSArgs()
25
+ parser = train_args.init_argparse(arg_prefix="")
26
+
27
+ # override trainer args from command-line args
28
+ args, config_overrides = parser.parse_known_args(arg_list)
29
+ train_args.parse_args(args)
30
+
31
+ # load config.json and register
32
+ if args.config_path or args.continue_path:
33
+ if args.config_path:
34
+ # init from a file
35
+ config = load_config(args.config_path)
36
+ if len(config_overrides) > 0:
37
+ config.parse_known_args(config_overrides, relaxed_parser=True)
38
+ elif args.continue_path:
39
+ # continue from a prev experiment
40
+ config = load_config(os.path.join(args.continue_path, "config.json"))
41
+ if len(config_overrides) > 0:
42
+ config.parse_known_args(config_overrides, relaxed_parser=True)
43
+ else:
44
+ # init from console args
45
+ from TTS.config.shared_configs import BaseTrainingConfig # pylint: disable=import-outside-toplevel
46
+
47
+ config_base = BaseTrainingConfig()
48
+ config_base.parse_known_args(config_overrides)
49
+ config = register_config(config_base.model)()
50
+
51
+ # load training samples
52
+ train_samples, eval_samples = load_tts_samples(
53
+ config.datasets,
54
+ eval_split=True,
55
+ eval_split_max_size=config.eval_split_max_size,
56
+ eval_split_size=config.eval_split_size,
57
+ )
58
+
59
+ # init the model from config
60
+ model = setup_model(config, train_samples + eval_samples)
61
+
62
+ # init the trainer and 🚀
63
+ trainer = Trainer(
64
+ train_args,
65
+ model.config,
66
+ config.output_path,
67
+ model=model,
68
+ train_samples=train_samples,
69
+ eval_samples=eval_samples,
70
+ parse_command_line_args=False,
71
+ )
72
+ trainer.fit()
73
+ sys.exit(0)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
TTS/bin/train_vocoder.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import sys
4
+ from dataclasses import dataclass, field
5
+
6
+ from trainer import Trainer, TrainerArgs
7
+
8
+ from TTS.config import load_config, register_config
9
+ from TTS.utils.audio import AudioProcessor
10
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
11
+ from TTS.vocoder.datasets.preprocess import load_wav_data, load_wav_feat_data
12
+ from TTS.vocoder.models import setup_model
13
+
14
+
15
+ @dataclass
16
+ class TrainVocoderArgs(TrainerArgs):
17
+ config_path: str = field(default=None, metadata={"help": "Path to the config file."})
18
+
19
+
20
+ def main(arg_list: list[str] | None = None):
21
+ """Run `tts` model training directly by a `config.json` file."""
22
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
23
+
24
+ # init trainer args
25
+ train_args = TrainVocoderArgs()
26
+ parser = train_args.init_argparse(arg_prefix="")
27
+
28
+ # override trainer args from comman-line args
29
+ args, config_overrides = parser.parse_known_args(arg_list)
30
+ train_args.parse_args(args)
31
+
32
+ # load config.json and register
33
+ if args.config_path or args.continue_path:
34
+ if args.config_path:
35
+ # init from a file
36
+ config = load_config(args.config_path)
37
+ if len(config_overrides) > 0:
38
+ config.parse_known_args(config_overrides, relaxed_parser=True)
39
+ elif args.continue_path:
40
+ # continue from a prev experiment
41
+ config = load_config(os.path.join(args.continue_path, "config.json"))
42
+ if len(config_overrides) > 0:
43
+ config.parse_known_args(config_overrides, relaxed_parser=True)
44
+ else:
45
+ # init from console args
46
+ from TTS.config.shared_configs import BaseTrainingConfig # pylint: disable=import-outside-toplevel
47
+
48
+ config_base = BaseTrainingConfig()
49
+ config_base.parse_known_args(config_overrides)
50
+ config = register_config(config_base.model)()
51
+
52
+ # load training samples
53
+ if "feature_path" in config and config.feature_path:
54
+ # load pre-computed features
55
+ print(f" > Loading features from: {config.feature_path}")
56
+ eval_samples, train_samples = load_wav_feat_data(config.data_path, config.feature_path, config.eval_split_size)
57
+ else:
58
+ # load data raw wav files
59
+ eval_samples, train_samples = load_wav_data(config.data_path, config.eval_split_size)
60
+
61
+ # setup audio processor
62
+ ap = AudioProcessor(**config.audio)
63
+
64
+ # init the model from config
65
+ model = setup_model(config)
66
+
67
+ # init the trainer and 🚀
68
+ trainer = Trainer(
69
+ train_args,
70
+ config,
71
+ config.output_path,
72
+ model=model,
73
+ train_samples=train_samples,
74
+ eval_samples=eval_samples,
75
+ training_assets={"audio_processor": ap},
76
+ parse_command_line_args=False,
77
+ )
78
+ trainer.fit()
79
+ sys.exit(0)
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
TTS/bin/tune_wavegrad.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Search a good noise schedule for WaveGrad for a given number of inference iterations"""
2
+
3
+ import argparse
4
+ import logging
5
+ import sys
6
+ from itertools import product as cartesian_product
7
+
8
+ import numpy as np
9
+ import torch
10
+ from torch.utils.data import DataLoader
11
+ from tqdm import tqdm
12
+
13
+ from TTS.config import load_config
14
+ from TTS.utils.audio import AudioProcessor
15
+ from TTS.utils.generic_utils import ConsoleFormatter, setup_logger
16
+ from TTS.vocoder.datasets.preprocess import load_wav_data
17
+ from TTS.vocoder.datasets.wavegrad_dataset import WaveGradDataset
18
+ from TTS.vocoder.models import setup_model
19
+
20
+ if __name__ == "__main__":
21
+ setup_logger("TTS", level=logging.INFO, stream=sys.stdout, formatter=ConsoleFormatter())
22
+
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("--model_path", type=str, help="Path to model checkpoint.")
25
+ parser.add_argument("--config_path", type=str, help="Path to model config file.")
26
+ parser.add_argument("--data_path", type=str, help="Path to data directory.")
27
+ parser.add_argument("--output_path", type=str, help="path for output file including file name and extension.")
28
+ parser.add_argument(
29
+ "--num_iter",
30
+ type=int,
31
+ help="Number of model inference iterations that you like to optimize noise schedule for.",
32
+ )
33
+ parser.add_argument("--use_cuda", action="store_true", help="enable CUDA.")
34
+ parser.add_argument("--num_samples", type=int, default=1, help="Number of datasamples used for inference.")
35
+ parser.add_argument(
36
+ "--search_depth",
37
+ type=int,
38
+ default=3,
39
+ help="Search granularity. Increasing this increases the run-time exponentially.",
40
+ )
41
+
42
+ # load config
43
+ args = parser.parse_args()
44
+ config = load_config(args.config_path)
45
+
46
+ # setup audio processor
47
+ ap = AudioProcessor(**config.audio)
48
+
49
+ # load dataset
50
+ _, train_data = load_wav_data(args.data_path, 0)
51
+ train_data = train_data[: args.num_samples]
52
+ dataset = WaveGradDataset(
53
+ ap=ap,
54
+ items=train_data,
55
+ seq_len=-1,
56
+ hop_len=ap.hop_length,
57
+ pad_short=config.pad_short,
58
+ conv_pad=config.conv_pad,
59
+ is_training=True,
60
+ return_segments=False,
61
+ use_noise_augment=False,
62
+ use_cache=False,
63
+ )
64
+ loader = DataLoader(
65
+ dataset,
66
+ batch_size=1,
67
+ shuffle=False,
68
+ collate_fn=dataset.collate_full_clips,
69
+ drop_last=False,
70
+ num_workers=config.num_loader_workers,
71
+ pin_memory=False,
72
+ )
73
+
74
+ # setup the model
75
+ model = setup_model(config)
76
+ if args.use_cuda:
77
+ model.cuda()
78
+
79
+ # setup optimization parameters
80
+ base_values = sorted(10 * np.random.uniform(size=args.search_depth))
81
+ print(f" > base values: {base_values}")
82
+ exponents = 10 ** np.linspace(-6, -1, num=args.num_iter)
83
+ best_error = float("inf")
84
+ best_schedule = None # pylint: disable=C0103
85
+ total_search_iter = len(base_values) ** args.num_iter
86
+ for base in tqdm(cartesian_product(base_values, repeat=args.num_iter), total=total_search_iter):
87
+ beta = exponents * base
88
+ model.compute_noise_level(beta)
89
+ for data in loader:
90
+ mel, audio = data
91
+ y_hat = model.inference(mel.cuda() if args.use_cuda else mel)
92
+
93
+ if args.use_cuda:
94
+ y_hat = y_hat.cpu()
95
+ y_hat = y_hat.numpy()
96
+
97
+ mel_hat = []
98
+ for i in range(y_hat.shape[0]):
99
+ m = ap.melspectrogram(y_hat[i, 0])[:, :-1]
100
+ mel_hat.append(torch.from_numpy(m))
101
+
102
+ mel_hat = torch.stack(mel_hat)
103
+ mse = torch.sum((mel - mel_hat) ** 2).mean()
104
+ if mse.item() < best_error:
105
+ best_error = mse.item()
106
+ best_schedule = {"beta": beta}
107
+ print(f" > Found a better schedule. - MSE: {mse.item()}")
108
+ np.save(args.output_path, best_schedule)
TTS/config/__init__.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ from typing import Any, Union, cast
5
+
6
+ import fsspec
7
+ import yaml
8
+ from coqpit import Coqpit
9
+
10
+ from TTS.config.shared_configs import BaseAudioConfig, BaseDatasetConfig, BaseTrainingConfig
11
+ from TTS.utils.generic_utils import find_module
12
+
13
+
14
+ def read_json_with_comments(json_path):
15
+ """for backward compat."""
16
+ # fallback to json
17
+ with fsspec.open(json_path, "r", encoding="utf-8") as f:
18
+ input_str = f.read()
19
+ # handle comments but not urls with //
20
+ input_str = re.sub(
21
+ r"(\"(?:[^\"\\]|\\.)*\")|(/\*(?:.|[\\n\\r])*?\*/)|(//.*)", lambda m: m.group(1) or m.group(2) or "", input_str
22
+ )
23
+ return json.loads(input_str)
24
+
25
+
26
+ def register_config(model_name: str) -> type[BaseTrainingConfig]:
27
+ """Find the right config for the given model name.
28
+
29
+ Args:
30
+ model_name (str): Model name.
31
+
32
+ Raises:
33
+ ModuleNotFoundError: No matching config for the model name.
34
+
35
+ Returns:
36
+ type[BaseTrainingConfig]: config class.
37
+ """
38
+ config_class = None
39
+ config_name = model_name + "_config"
40
+
41
+ # TODO: fix this
42
+ if model_name == "xtts":
43
+ from TTS.tts.configs.xtts_config import XttsConfig
44
+
45
+ config_class = XttsConfig
46
+ paths = ["TTS.tts.configs", "TTS.vocoder.configs", "TTS.encoder.configs", "TTS.vc.configs"]
47
+ for path in paths:
48
+ try:
49
+ config_class = find_module(path, config_name)
50
+ if not issubclass(config_class, BaseTrainingConfig):
51
+ msg = f"{config_class} is not a subclass of BaseTrainingConfig."
52
+ raise TypeError(msg)
53
+ except ModuleNotFoundError:
54
+ pass
55
+ if config_class is None:
56
+ raise ModuleNotFoundError(f" [!] Config for {model_name} cannot be found.")
57
+ return config_class
58
+
59
+
60
+ def _process_model_name(config_dict: dict) -> str:
61
+ """Format the model name as expected. It is a band-aid for the old `vocoder` model names.
62
+
63
+ Args:
64
+ config_dict (dict): A dictionary including the config fields.
65
+
66
+ Returns:
67
+ str: Formatted modelname.
68
+ """
69
+ model_name = config_dict["model"] if "model" in config_dict else config_dict["generator_model"]
70
+ model_name = model_name.replace("_generator", "").replace("_discriminator", "")
71
+ return model_name
72
+
73
+
74
+ def load_config(config_path: str | os.PathLike[Any]) -> BaseTrainingConfig:
75
+ """Import `json` or `yaml` files as TTS configs. First, load the input file as a `dict` and check the model name
76
+ to find the corresponding Config class. Then initialize the Config.
77
+
78
+ Args:
79
+ config_path (str): path to the config file.
80
+
81
+ Raises:
82
+ TypeError: given config file has an unknown type.
83
+
84
+ Returns:
85
+ Coqpit: TTS config object.
86
+ """
87
+ config_path = str(config_path)
88
+ config_dict = {}
89
+ ext = os.path.splitext(config_path)[1]
90
+ if ext in (".yml", ".yaml"):
91
+ with fsspec.open(config_path, "r", encoding="utf-8") as f:
92
+ data = yaml.safe_load(f)
93
+ elif ext == ".json":
94
+ try:
95
+ with fsspec.open(config_path, "r", encoding="utf-8") as f:
96
+ data = json.load(f)
97
+ except json.JSONDecodeError:
98
+ # backwards compat.
99
+ data = read_json_with_comments(config_path)
100
+ else:
101
+ msg = f" [!] Unknown config file type {ext}"
102
+ raise TypeError(msg)
103
+ config_dict.update(data)
104
+ model_name = _process_model_name(config_dict)
105
+ config_class = register_config(model_name.lower())
106
+ config = config_class()
107
+ config.from_dict(config_dict)
108
+ return config
109
+
110
+
111
+ def check_config_and_model_args(config, arg_name, value):
112
+ """Check the give argument in `config.model_args` if exist or in `config` for
113
+ the given value.
114
+
115
+ Return False if the argument does not exist in `config.model_args` or `config`.
116
+ This is to patch up the compatibility between models with and without `model_args`.
117
+
118
+ TODO: Remove this in the future with a unified approach.
119
+ """
120
+ if getattr(config, "model_args", None) is not None:
121
+ if arg_name in config.model_args:
122
+ return config.model_args[arg_name] == value
123
+ if hasattr(config, arg_name):
124
+ return config[arg_name] == value
125
+ return False
126
+
127
+
128
+ def get_from_config_or_model_args(config, arg_name):
129
+ """Get the given argument from `config.model_args` if exist or in `config`."""
130
+ if getattr(config, "model_args", None) is not None:
131
+ if arg_name in config.model_args:
132
+ return config.model_args[arg_name]
133
+ return config[arg_name]
134
+
135
+
136
+ def get_from_config_or_model_args_with_default(config, arg_name, def_val):
137
+ """Get the given argument from `config.model_args` if exist or in `config`."""
138
+ if getattr(config, "model_args", None) is not None:
139
+ if arg_name in config.model_args:
140
+ return config.model_args[arg_name]
141
+ if hasattr(config, arg_name):
142
+ return config[arg_name]
143
+ return def_val
TTS/config/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.26 kB). View file
 
TTS/config/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (7.18 kB). View file
 
TTS/config/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (4.26 kB). View file
 
TTS/config/__pycache__/shared_configs.cpython-310.pyc ADDED
Binary file (9.53 kB). View file
 
TTS/config/__pycache__/shared_configs.cpython-311.pyc ADDED
Binary file (11.8 kB). View file
 
TTS/config/__pycache__/shared_configs.cpython-39.pyc ADDED
Binary file (9.52 kB). View file
 
TTS/config/shared_configs.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass
2
+
3
+ from coqpit import Coqpit, check_argument
4
+ from trainer import TrainerConfig
5
+
6
+
7
+ @dataclass
8
+ class BaseAudioConfig(Coqpit):
9
+ """Base config to definge audio processing parameters. It is used to initialize
10
+ ```TTS.utils.audio.AudioProcessor.```
11
+
12
+ Args:
13
+ fft_size (int):
14
+ Number of STFT frequency levels aka.size of the linear spectogram frame. Defaults to 1024.
15
+
16
+ win_length (int):
17
+ Each frame of audio is windowed by window of length ```win_length``` and then padded with zeros to match
18
+ ```fft_size```. Defaults to 1024.
19
+
20
+ hop_length (int):
21
+ Number of audio samples between adjacent STFT columns. Defaults to 1024.
22
+
23
+ frame_shift_ms (int):
24
+ Set ```hop_length``` based on milliseconds and sampling rate.
25
+
26
+ frame_length_ms (int):
27
+ Set ```win_length``` based on milliseconds and sampling rate.
28
+
29
+ stft_pad_mode (str):
30
+ Padding method used in STFT. 'reflect' or 'center'. Defaults to 'reflect'.
31
+
32
+ sample_rate (int):
33
+ Audio sampling rate. Defaults to 22050.
34
+
35
+ resample (bool):
36
+ Enable / Disable resampling audio to ```sample_rate```. Defaults to ```False```.
37
+
38
+ preemphasis (float):
39
+ Preemphasis coefficient. Defaults to 0.0.
40
+
41
+ ref_level_db (int): 20
42
+ Reference Db level to rebase the audio signal and ignore the level below. 20Db is assumed the sound of air.
43
+ Defaults to 20.
44
+
45
+ do_sound_norm (bool):
46
+ Enable / Disable sound normalization to reconcile the volume differences among samples. Defaults to False.
47
+
48
+ log_func (str):
49
+ Numpy log function used for amplitude to DB conversion. Defaults to 'np.log10'.
50
+
51
+ do_trim_silence (bool):
52
+ Enable / Disable trimming silences at the beginning and the end of the audio clip. Defaults to ```True```.
53
+
54
+ do_amp_to_db_linear (bool, optional):
55
+ enable/disable amplitude to dB conversion of linear spectrograms. Defaults to True.
56
+
57
+ do_amp_to_db_mel (bool, optional):
58
+ enable/disable amplitude to dB conversion of mel spectrograms. Defaults to True.
59
+
60
+ pitch_fmax (float, optional):
61
+ Maximum frequency of the F0 frames. Defaults to ```640```.
62
+
63
+ pitch_fmin (float, optional):
64
+ Minimum frequency of the F0 frames. Defaults to ```1```.
65
+
66
+ trim_db (int):
67
+ Silence threshold used for silence trimming. Defaults to 45.
68
+
69
+ do_rms_norm (bool, optional):
70
+ enable/disable RMS volume normalization when loading an audio file. Defaults to False.
71
+
72
+ db_level (int, optional):
73
+ dB level used for rms normalization. The range is -99 to 0. Defaults to None.
74
+
75
+ power (float):
76
+ Exponent used for expanding spectrogra levels before running Griffin Lim. It helps to reduce the
77
+ artifacts in the synthesized voice. Defaults to 1.5.
78
+
79
+ griffin_lim_iters (int):
80
+ Number of Griffing Lim iterations. Defaults to 60.
81
+
82
+ num_mels (int):
83
+ Number of mel-basis frames that defines the frame lengths of each mel-spectrogram frame. Defaults to 80.
84
+
85
+ mel_fmin (float): Min frequency level used for the mel-basis filters. ~50 for male and ~95 for female voices.
86
+ It needs to be adjusted for a dataset. Defaults to 0.
87
+
88
+ mel_fmax (float):
89
+ Max frequency level used for the mel-basis filters. It needs to be adjusted for a dataset.
90
+
91
+ spec_gain (int):
92
+ Gain applied when converting amplitude to DB. Defaults to 20.
93
+
94
+ signal_norm (bool):
95
+ enable/disable signal normalization. Defaults to True.
96
+
97
+ min_level_db (int):
98
+ minimum db threshold for the computed melspectrograms. Defaults to -100.
99
+
100
+ symmetric_norm (bool):
101
+ enable/disable symmetric normalization. If set True normalization is performed in the range [-k, k] else
102
+ [0, k], Defaults to True.
103
+
104
+ max_norm (float):
105
+ ```k``` defining the normalization range. Defaults to 4.0.
106
+
107
+ clip_norm (bool):
108
+ enable/disable clipping the our of range values in the normalized audio signal. Defaults to True.
109
+
110
+ stats_path (str):
111
+ Path to the computed stats file. Defaults to None.
112
+ """
113
+
114
+ # stft parameters
115
+ fft_size: int = 1024
116
+ win_length: int = 1024
117
+ hop_length: int = 256
118
+ frame_shift_ms: int = None
119
+ frame_length_ms: int = None
120
+ stft_pad_mode: str = "reflect"
121
+ # audio processing parameters
122
+ sample_rate: int = 22050
123
+ resample: bool = False
124
+ preemphasis: float = 0.0
125
+ ref_level_db: int = 20
126
+ do_sound_norm: bool = False
127
+ log_func: str = "np.log10"
128
+ # silence trimming
129
+ do_trim_silence: bool = True
130
+ trim_db: int = 45
131
+ # rms volume normalization
132
+ do_rms_norm: bool = False
133
+ db_level: float = None
134
+ # griffin-lim params
135
+ power: float = 1.5
136
+ griffin_lim_iters: int = 60
137
+ # mel-spec params
138
+ num_mels: int = 80
139
+ mel_fmin: float = 0.0
140
+ mel_fmax: float = None
141
+ spec_gain: int = 20
142
+ do_amp_to_db_linear: bool = True
143
+ do_amp_to_db_mel: bool = True
144
+ # f0 params
145
+ pitch_fmax: float = 640.0
146
+ pitch_fmin: float = 1.0
147
+ # normalization params
148
+ signal_norm: bool = True
149
+ min_level_db: int = -100
150
+ symmetric_norm: bool = True
151
+ max_norm: float = 4.0
152
+ clip_norm: bool = True
153
+ stats_path: str = None
154
+
155
+ def check_values(
156
+ self,
157
+ ):
158
+ """Check config fields"""
159
+ c = asdict(self)
160
+ check_argument("num_mels", c, restricted=True, min_val=10, max_val=2056)
161
+ check_argument("fft_size", c, restricted=True, min_val=128, max_val=4058)
162
+ check_argument("sample_rate", c, restricted=True, min_val=512, max_val=100000)
163
+ check_argument(
164
+ "frame_length_ms",
165
+ c,
166
+ restricted=True,
167
+ min_val=10,
168
+ max_val=1000,
169
+ alternative="win_length",
170
+ )
171
+ check_argument("frame_shift_ms", c, restricted=True, min_val=1, max_val=1000, alternative="hop_length")
172
+ check_argument("preemphasis", c, restricted=True, min_val=0, max_val=1)
173
+ check_argument("min_level_db", c, restricted=True, min_val=-1000, max_val=10)
174
+ check_argument("ref_level_db", c, restricted=True, min_val=0, max_val=1000)
175
+ check_argument("power", c, restricted=True, min_val=1, max_val=5)
176
+ check_argument("griffin_lim_iters", c, restricted=True, min_val=10, max_val=1000)
177
+
178
+ # normalization parameters
179
+ check_argument("signal_norm", c, restricted=True)
180
+ check_argument("symmetric_norm", c, restricted=True)
181
+ check_argument("max_norm", c, restricted=True, min_val=0.1, max_val=1000)
182
+ check_argument("clip_norm", c, restricted=True)
183
+ check_argument("mel_fmin", c, restricted=True, min_val=0.0, max_val=1000)
184
+ check_argument("mel_fmax", c, restricted=True, min_val=500.0, allow_none=True)
185
+ check_argument("spec_gain", c, restricted=True, min_val=1, max_val=100)
186
+ check_argument("do_trim_silence", c, restricted=True)
187
+ check_argument("trim_db", c, restricted=True)
188
+
189
+
190
+ @dataclass
191
+ class BaseDatasetConfig(Coqpit):
192
+ """Base config for TTS datasets.
193
+
194
+ Args:
195
+ formatter (str):
196
+ Formatter name that defines used formatter in ```TTS.tts.datasets.formatter```. Defaults to `""`.
197
+
198
+ dataset_name (str):
199
+ Unique name for the dataset. Defaults to `""`.
200
+
201
+ path (str):
202
+ Root path to the dataset files. Defaults to `""`.
203
+
204
+ meta_file_train (str):
205
+ Name of the dataset meta file. Or a list of speakers to be ignored at training for multi-speaker datasets.
206
+ Defaults to `""`.
207
+
208
+ ignored_speakers (List):
209
+ List of speakers IDs that are not used at the training. Default None.
210
+
211
+ language (str):
212
+ Language code of the dataset. If defined, it overrides `phoneme_language`. Defaults to `""`.
213
+
214
+ phonemizer (str):
215
+ Phonemizer used for that dataset's language. By default it uses `DEF_LANG_TO_PHONEMIZER`. Defaults to `""`.
216
+
217
+ meta_file_val (str):
218
+ Name of the dataset meta file that defines the instances used at validation.
219
+
220
+ meta_file_attn_mask (str):
221
+ Path to the file that lists the attention mask files used with models that require attention masks to
222
+ train the duration predictor.
223
+ """
224
+
225
+ formatter: str = ""
226
+ dataset_name: str = ""
227
+ path: str = ""
228
+ meta_file_train: str = ""
229
+ ignored_speakers: list[str] = None
230
+ language: str = ""
231
+ phonemizer: str = ""
232
+ meta_file_val: str = ""
233
+ meta_file_attn_mask: str = ""
234
+
235
+ def check_values(
236
+ self,
237
+ ):
238
+ """Check config fields"""
239
+ c = asdict(self)
240
+ check_argument("formatter", c, restricted=True)
241
+ check_argument("path", c, restricted=True)
242
+ check_argument("meta_file_train", c, restricted=True)
243
+ check_argument("meta_file_val", c, restricted=False)
244
+ check_argument("meta_file_attn_mask", c, restricted=False)
245
+
246
+
247
+ @dataclass
248
+ class BaseTrainingConfig(TrainerConfig):
249
+ """Base config to define the basic 🐸TTS training parameters that are shared
250
+ among all the models. It is based on ```Trainer.TrainingConfig```.
251
+
252
+ Args:
253
+ model (str):
254
+ Name of the model that is used in the training.
255
+
256
+ num_loader_workers (int):
257
+ Number of workers for training time dataloader.
258
+
259
+ num_eval_loader_workers (int):
260
+ Number of workers for evaluation time dataloader.
261
+ """
262
+
263
+ model: str = None
264
+ # dataloading
265
+ num_loader_workers: int = 0
266
+ num_eval_loader_workers: int = 0
267
+ use_noise_augment: bool = False
TTS/demos/xtts_ft_demo/README.md ADDED
@@ -0,0 +1 @@
 
 
1
+ You can open the notebook in Google Colab: https://colab.research.google.com/github/idiap/coqui-ai-TTS/blob/dev/TTS/demos/xtts_ft_demo/XTTS_finetune_colab.ipynb
TTS/demos/xtts_ft_demo/XTTS_finetune_colab.ipynb ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "Th91ofnQWr8Y"
7
+ },
8
+ "source": [
9
+ "## Dataset building + XTTS finetuning and inference\n",
10
+ "\n",
11
+ "#### Running the demo\n",
12
+ "To start the demo run the first two cells (ignore pip install errors in the first one)\n",
13
+ "\n",
14
+ "Then click on the link `Running on public URL: ` when the demo is ready.\n",
15
+ "\n",
16
+ "#### Downloading the results\n",
17
+ "\n",
18
+ "You can run cell [3] to zip and download default dataset path\n",
19
+ "\n",
20
+ "You can run cell [4] to zip and download the latest model you trained"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "markdown",
25
+ "metadata": {
26
+ "id": "cdWKA_xFqkKq"
27
+ },
28
+ "source": [
29
+ "### Installing the requirements"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "execution_count": null,
35
+ "metadata": {
36
+ "id": "lmUUQqdN6BXk"
37
+ },
38
+ "outputs": [],
39
+ "source": [
40
+ "!rm -rf coqui-ai-TTS/ # delete repo to be able to reinstall if needed\n",
41
+ "!git clone -q https://github.com/idiap/coqui-ai-TTS.git\n",
42
+ "!pip install -q -e coqui-ai-TTS\n",
43
+ "!pip install -q gradio faster_whisper"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "markdown",
48
+ "metadata": {
49
+ "id": "g7rNt1e2qtDP"
50
+ },
51
+ "source": [
52
+ "### Running the gradio UI"
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "execution_count": null,
58
+ "metadata": {
59
+ "id": "zd2xo_7a8wyj"
60
+ },
61
+ "outputs": [],
62
+ "source": [
63
+ "!python -m TTS.demos.xtts_ft_demo.xtts_demo --batch_size 2 --num_epochs 6"
64
+ ]
65
+ },
66
+ {
67
+ "cell_type": "markdown",
68
+ "metadata": {
69
+ "id": "oXEBRA_kq23i"
70
+ },
71
+ "source": [
72
+ "### Downloading the dataset"
73
+ ]
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "execution_count": null,
78
+ "metadata": {
79
+ "id": "dBxgdKcvi4kO"
80
+ },
81
+ "outputs": [],
82
+ "source": [
83
+ "from google.colab import files\n",
84
+ "\n",
85
+ "!zip -q -r dataset.zip /tmp/xtts_ft/dataset\n",
86
+ "files.download('dataset.zip')"
87
+ ]
88
+ },
89
+ {
90
+ "cell_type": "markdown",
91
+ "metadata": {
92
+ "id": "ZKzoP53Nq_rJ"
93
+ },
94
+ "source": [
95
+ "### Downloading the model"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "metadata": {
102
+ "id": "NpfdzHvKaX8M"
103
+ },
104
+ "outputs": [],
105
+ "source": [
106
+ "from google.colab import files\n",
107
+ "import os\n",
108
+ "import glob\n",
109
+ "import torch\n",
110
+ "\n",
111
+ "def find_latest_best_model(folder_path):\n",
112
+ " search_path = os.path.join(folder_path, '**', 'best_model.pth')\n",
113
+ " files = glob.glob(search_path, recursive=True)\n",
114
+ " latest_file = max(files, key=os.path.getctime, default=None)\n",
115
+ " return latest_file\n",
116
+ "\n",
117
+ "model_path = find_latest_best_model(\"/tmp/xtts_ft/run/training/\")\n",
118
+ "checkpoint = torch.load(model_path, map_location=torch.device(\"cpu\"))\n",
119
+ "del checkpoint[\"optimizer\"]\n",
120
+ "for key in list(checkpoint[\"model\"].keys()):\n",
121
+ " if \"dvae\" in key:\n",
122
+ " del checkpoint[\"model\"][key]\n",
123
+ "torch.save(checkpoint, \"model.pth\")\n",
124
+ "model_dir = os.path.dirname(model_path)\n",
125
+ "files.download(os.path.join(model_dir, 'config.json'))\n",
126
+ "files.download(os.path.join(model_dir, 'vocab.json'))\n",
127
+ "files.download('model.pth')"
128
+ ]
129
+ },
130
+ {
131
+ "cell_type": "markdown",
132
+ "metadata": {
133
+ "id": "Eh9_SusYdRE4"
134
+ },
135
+ "source": [
136
+ "### Copy files to your google drive\n",
137
+ "\n",
138
+ "The two previous cells are a requirement for this step but it can be much faster"
139
+ ]
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "execution_count": null,
144
+ "metadata": {
145
+ "id": "piLAaVHSdQs5"
146
+ },
147
+ "outputs": [],
148
+ "source": [
149
+ "from google.colab import drive\n",
150
+ "import shutil\n",
151
+ "drive.mount('/content/drive')\n",
152
+ "!mkdir /content/drive/MyDrive/XTTS_ft_colab\n",
153
+ "shutil.copy(os.path.join(model_dir, 'config.json'), \"/content/drive/MyDrive/XTTS_ft_colab/config.json\")\n",
154
+ "shutil.copy(os.path.join(model_dir, 'vocab.json'), \"/content/drive/MyDrive/XTTS_ft_colab/vocab.json'\")\n",
155
+ "shutil.copy('model.pth', \"/content/drive/MyDrive/XTTS_ft_colab/model.pth\")\n",
156
+ "shutil.copy('dataset.zip', \"/content/drive/MyDrive/XTTS_ft_colab/dataset.zip\")"
157
+ ]
158
+ }
159
+ ],
160
+ "metadata": {
161
+ "accelerator": "GPU",
162
+ "colab": {
163
+ "gpuType": "T4",
164
+ "provenance": []
165
+ },
166
+ "kernelspec": {
167
+ "display_name": "Python 3",
168
+ "name": "python3"
169
+ },
170
+ "language_info": {
171
+ "name": "python"
172
+ }
173
+ },
174
+ "nbformat": 4,
175
+ "nbformat_minor": 0
176
+ }
TTS/demos/xtts_ft_demo/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ faster_whisper
2
+ gradio
TTS/demos/xtts_ft_demo/utils/formatter.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import os
3
+
4
+ import pandas
5
+ import torch
6
+ import torchaudio
7
+ from faster_whisper import WhisperModel
8
+ from tqdm import tqdm
9
+
10
+ # torch.set_num_threads(1)
11
+ from TTS.tts.layers.xtts.tokenizer import multilingual_cleaners
12
+
13
+ torch.set_num_threads(16)
14
+
15
+ audio_types = (".wav", ".mp3", ".flac")
16
+
17
+
18
+ def list_audios(basePath, contains=None):
19
+ # return the set of files that are valid
20
+ return list_files(basePath, validExts=audio_types, contains=contains)
21
+
22
+
23
+ def list_files(basePath, validExts=None, contains=None):
24
+ # loop over the directory structure
25
+ for rootDir, dirNames, filenames in os.walk(basePath):
26
+ # loop over the filenames in the current directory
27
+ for filename in filenames:
28
+ # if the contains string is not none and the filename does not contain
29
+ # the supplied string, then ignore the file
30
+ if contains is not None and filename.find(contains) == -1:
31
+ continue
32
+
33
+ # determine the file extension of the current file
34
+ ext = filename[filename.rfind(".") :].lower()
35
+
36
+ # check to see if the file is an audio and should be processed
37
+ if validExts is None or ext.endswith(validExts):
38
+ # construct the path to the audio and yield it
39
+ audioPath = os.path.join(rootDir, filename)
40
+ yield audioPath
41
+
42
+
43
+ def format_audio_list(
44
+ audio_files,
45
+ target_language="en",
46
+ out_path=None,
47
+ buffer=0.2,
48
+ eval_percentage=0.15,
49
+ speaker_name="coqui",
50
+ gradio_progress=None,
51
+ ):
52
+ audio_total_size = 0
53
+ # make sure that ooutput file exists
54
+ os.makedirs(out_path, exist_ok=True)
55
+
56
+ # Loading Whisper
57
+ device = "cuda" if torch.cuda.is_available() else "cpu"
58
+
59
+ print("Loading Whisper Model!")
60
+ asr_model = WhisperModel("large-v2", device=device, compute_type="float16")
61
+
62
+ metadata = {"audio_file": [], "text": [], "speaker_name": []}
63
+
64
+ if gradio_progress is not None:
65
+ tqdm_object = gradio_progress.tqdm(audio_files, desc="Formatting...")
66
+ else:
67
+ tqdm_object = tqdm(audio_files)
68
+
69
+ for audio_path in tqdm_object:
70
+ wav, sr = torchaudio.load(audio_path)
71
+ # stereo to mono if needed
72
+ if wav.size(0) != 1:
73
+ wav = torch.mean(wav, dim=0, keepdim=True)
74
+
75
+ wav = wav.squeeze()
76
+ audio_total_size += wav.size(-1) / sr
77
+
78
+ segments, _ = asr_model.transcribe(audio_path, word_timestamps=True, language=target_language)
79
+ segments = list(segments)
80
+ i = 0
81
+ sentence = ""
82
+ sentence_start = None
83
+ first_word = True
84
+ # added all segments words in a unique list
85
+ words_list = []
86
+ for _, segment in enumerate(segments):
87
+ words = list(segment.words)
88
+ words_list.extend(words)
89
+
90
+ # process each word
91
+ for word_idx, word in enumerate(words_list):
92
+ if first_word:
93
+ sentence_start = word.start
94
+ # If it is the first sentence, add buffer or get the begining of the file
95
+ if word_idx == 0:
96
+ sentence_start = max(sentence_start - buffer, 0) # Add buffer to the sentence start
97
+ else:
98
+ # get previous sentence end
99
+ previous_word_end = words_list[word_idx - 1].end
100
+ # add buffer or get the silence midle between the previous sentence and the current one
101
+ sentence_start = max(sentence_start - buffer, (previous_word_end + sentence_start) / 2)
102
+
103
+ sentence = word.word
104
+ first_word = False
105
+ else:
106
+ sentence += word.word
107
+
108
+ if word.word[-1] in ["!", ".", "?"]:
109
+ sentence = sentence[1:]
110
+ # Expand number and abbreviations plus normalization
111
+ sentence = multilingual_cleaners(sentence, target_language)
112
+ audio_file_name, _ = os.path.splitext(os.path.basename(audio_path))
113
+
114
+ audio_file = f"wavs/{audio_file_name}_{str(i).zfill(8)}.wav"
115
+
116
+ # Check for the next word's existence
117
+ if word_idx + 1 < len(words_list):
118
+ next_word_start = words_list[word_idx + 1].start
119
+ else:
120
+ # If don't have more words it means that it is the last sentence then use the audio len as next word start
121
+ next_word_start = (wav.shape[0] - 1) / sr
122
+
123
+ # Average the current word end and next word start
124
+ word_end = min((word.end + next_word_start) / 2, word.end + buffer)
125
+
126
+ absoulte_path = os.path.join(out_path, audio_file)
127
+ os.makedirs(os.path.dirname(absoulte_path), exist_ok=True)
128
+ i += 1
129
+ first_word = True
130
+
131
+ audio = wav[int(sr * sentence_start) : int(sr * word_end)].unsqueeze(0)
132
+ # if the audio is too short ignore it (i.e < 0.33 seconds)
133
+ if audio.size(-1) >= sr / 3:
134
+ torchaudio.save(absoulte_path, audio, sr)
135
+ else:
136
+ continue
137
+
138
+ metadata["audio_file"].append(audio_file)
139
+ metadata["text"].append(sentence)
140
+ metadata["speaker_name"].append(speaker_name)
141
+
142
+ df = pandas.DataFrame(metadata)
143
+ df = df.sample(frac=1)
144
+ num_val_samples = int(len(df) * eval_percentage)
145
+
146
+ df_eval = df[:num_val_samples]
147
+ df_train = df[num_val_samples:]
148
+
149
+ df_train = df_train.sort_values("audio_file")
150
+ train_metadata_path = os.path.join(out_path, "metadata_train.csv")
151
+ df_train.to_csv(train_metadata_path, sep="|", index=False)
152
+
153
+ eval_metadata_path = os.path.join(out_path, "metadata_eval.csv")
154
+ df_eval = df_eval.sort_values("audio_file")
155
+ df_eval.to_csv(eval_metadata_path, sep="|", index=False)
156
+
157
+ # deallocate VRAM and RAM
158
+ del asr_model, df_train, df_eval, df, metadata
159
+ gc.collect()
160
+
161
+ return train_metadata_path, eval_metadata_path, audio_total_size
TTS/demos/xtts_ft_demo/utils/gpt_train.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import os
3
+
4
+ from trainer import Trainer, TrainerArgs
5
+
6
+ from TTS.config.shared_configs import BaseDatasetConfig
7
+ from TTS.tts.datasets import load_tts_samples
8
+ from TTS.tts.layers.xtts.trainer.gpt_trainer import GPTArgs, GPTTrainer, GPTTrainerConfig
9
+ from TTS.tts.models.xtts import XttsAudioConfig
10
+ from TTS.utils.manage import ModelManager
11
+
12
+
13
+ def train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path, max_audio_length=255995):
14
+ # Logging parameters
15
+ RUN_NAME = "GPT_XTTS_FT"
16
+ PROJECT_NAME = "XTTS_trainer"
17
+ DASHBOARD_LOGGER = "tensorboard"
18
+ LOGGER_URI = None
19
+
20
+ # Set here the path that the checkpoints will be saved. Default: ./run/training/
21
+ OUT_PATH = os.path.join(output_path, "run", "training")
22
+
23
+ # Training Parameters
24
+ OPTIMIZER_WD_ONLY_ON_WEIGHTS = True # for multi-gpu training please make it False
25
+ START_WITH_EVAL = False # if True it will star with evaluation
26
+ BATCH_SIZE = batch_size # set here the batch size
27
+ GRAD_ACUMM_STEPS = grad_acumm # set here the grad accumulation steps
28
+
29
+ # Define here the dataset that you want to use for the fine-tuning on.
30
+ config_dataset = BaseDatasetConfig(
31
+ formatter="coqui",
32
+ dataset_name="ft_dataset",
33
+ path=os.path.dirname(train_csv),
34
+ meta_file_train=train_csv,
35
+ meta_file_val=eval_csv,
36
+ language=language,
37
+ )
38
+
39
+ # Add here the configs of the datasets
40
+ DATASETS_CONFIG_LIST = [config_dataset]
41
+
42
+ # Define the path where XTTS v2.0.1 files will be downloaded
43
+ CHECKPOINTS_OUT_PATH = os.path.join(OUT_PATH, "XTTS_v2.0_original_model_files/")
44
+ os.makedirs(CHECKPOINTS_OUT_PATH, exist_ok=True)
45
+
46
+ # DVAE files
47
+ DVAE_CHECKPOINT_LINK = "https://huggingface.co/coqui/XTTS-v2/resolve/main/dvae.pth"
48
+ MEL_NORM_LINK = "https://huggingface.co/coqui/XTTS-v2/resolve/main/mel_stats.pth"
49
+
50
+ # Set the path to the downloaded files
51
+ DVAE_CHECKPOINT = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(DVAE_CHECKPOINT_LINK))
52
+ MEL_NORM_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(MEL_NORM_LINK))
53
+
54
+ # download DVAE files if needed
55
+ if not os.path.isfile(DVAE_CHECKPOINT) or not os.path.isfile(MEL_NORM_FILE):
56
+ print(" > Downloading DVAE files!")
57
+ ModelManager._download_model_files(
58
+ [MEL_NORM_LINK, DVAE_CHECKPOINT_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True
59
+ )
60
+
61
+ # Download XTTS v2.0 checkpoint if needed
62
+ TOKENIZER_FILE_LINK = "https://huggingface.co/coqui/XTTS-v2/resolve/main/vocab.json"
63
+ XTTS_CHECKPOINT_LINK = "https://huggingface.co/coqui/XTTS-v2/resolve/main/model.pth"
64
+ XTTS_CONFIG_LINK = "https://huggingface.co/coqui/XTTS-v2/resolve/main/config.json"
65
+
66
+ # XTTS transfer learning parameters: You we need to provide the paths of XTTS model checkpoint that you want to do the fine tuning.
67
+ TOKENIZER_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(TOKENIZER_FILE_LINK)) # vocab.json file
68
+ XTTS_CHECKPOINT = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_CHECKPOINT_LINK)) # model.pth file
69
+ XTTS_CONFIG_FILE = os.path.join(CHECKPOINTS_OUT_PATH, os.path.basename(XTTS_CONFIG_LINK)) # config.json file
70
+
71
+ # download XTTS v2.0 files if needed
72
+ if not os.path.isfile(TOKENIZER_FILE) or not os.path.isfile(XTTS_CHECKPOINT):
73
+ print(" > Downloading XTTS v2.0 files!")
74
+ ModelManager._download_model_files(
75
+ [TOKENIZER_FILE_LINK, XTTS_CHECKPOINT_LINK, XTTS_CONFIG_LINK], CHECKPOINTS_OUT_PATH, progress_bar=True
76
+ )
77
+
78
+ # init args and config
79
+ model_args = GPTArgs(
80
+ max_conditioning_length=132300, # 6 secs
81
+ min_conditioning_length=66150, # 3 secs
82
+ debug_loading_failures=False,
83
+ max_wav_length=max_audio_length, # ~11.6 seconds
84
+ max_text_length=200,
85
+ mel_norm_file=MEL_NORM_FILE,
86
+ dvae_checkpoint=DVAE_CHECKPOINT,
87
+ xtts_checkpoint=XTTS_CHECKPOINT, # checkpoint path of the model that you want to fine-tune
88
+ tokenizer_file=TOKENIZER_FILE,
89
+ gpt_num_audio_tokens=1026,
90
+ gpt_start_audio_token=1024,
91
+ gpt_stop_audio_token=1025,
92
+ gpt_use_masking_gt_prompt_approach=True,
93
+ gpt_use_perceiver_resampler=True,
94
+ )
95
+ # define audio config
96
+ audio_config = XttsAudioConfig(sample_rate=22050, dvae_sample_rate=22050, output_sample_rate=24000)
97
+ # training parameters config
98
+ config = GPTTrainerConfig(
99
+ epochs=num_epochs,
100
+ output_path=OUT_PATH,
101
+ model_args=model_args,
102
+ run_name=RUN_NAME,
103
+ project_name=PROJECT_NAME,
104
+ run_description="""
105
+ GPT XTTS training
106
+ """,
107
+ dashboard_logger=DASHBOARD_LOGGER,
108
+ logger_uri=LOGGER_URI,
109
+ audio=audio_config,
110
+ batch_size=BATCH_SIZE,
111
+ batch_group_size=48,
112
+ eval_batch_size=BATCH_SIZE,
113
+ num_loader_workers=8,
114
+ eval_split_max_size=256,
115
+ print_step=50,
116
+ plot_step=100,
117
+ log_model_step=100,
118
+ save_step=1000,
119
+ save_n_checkpoints=1,
120
+ save_checkpoints=True,
121
+ # target_loss="loss",
122
+ print_eval=False,
123
+ # Optimizer values like tortoise, pytorch implementation with modifications to not apply WD to non-weight parameters.
124
+ optimizer="AdamW",
125
+ optimizer_wd_only_on_weights=OPTIMIZER_WD_ONLY_ON_WEIGHTS,
126
+ optimizer_params={"betas": [0.9, 0.96], "eps": 1e-8, "weight_decay": 1e-2},
127
+ lr=5e-06, # learning rate
128
+ lr_scheduler="MultiStepLR",
129
+ # it was adjusted accordly for the new step scheme
130
+ lr_scheduler_params={"milestones": [50000 * 18, 150000 * 18, 300000 * 18], "gamma": 0.5, "last_epoch": -1},
131
+ test_sentences=[],
132
+ )
133
+
134
+ # init the model from config
135
+ model = GPTTrainer.init_from_config(config)
136
+
137
+ # load training samples
138
+ train_samples, eval_samples = load_tts_samples(
139
+ DATASETS_CONFIG_LIST,
140
+ eval_split=True,
141
+ eval_split_max_size=config.eval_split_max_size,
142
+ eval_split_size=config.eval_split_size,
143
+ )
144
+
145
+ # init the trainer and 🚀
146
+ trainer = Trainer(
147
+ TrainerArgs(
148
+ restore_path=None, # xtts checkpoint is restored via xtts_checkpoint key so no need of restore it using Trainer restore_path parameter
149
+ skip_train_epoch=False,
150
+ start_with_eval=START_WITH_EVAL,
151
+ grad_accum_steps=GRAD_ACUMM_STEPS,
152
+ ),
153
+ config,
154
+ output_path=OUT_PATH,
155
+ model=model,
156
+ train_samples=train_samples,
157
+ eval_samples=eval_samples,
158
+ )
159
+ trainer.fit()
160
+
161
+ # get the longest text audio file to use as speaker reference
162
+ samples_len = [len(item["text"].split(" ")) for item in train_samples]
163
+ longest_text_idx = samples_len.index(max(samples_len))
164
+ speaker_ref = train_samples[longest_text_idx]["audio_file"]
165
+
166
+ trainer_out_path = trainer.output_path
167
+
168
+ # deallocate VRAM and RAM
169
+ del model, trainer, train_samples, eval_samples
170
+ gc.collect()
171
+
172
+ return XTTS_CONFIG_FILE, XTTS_CHECKPOINT, TOKENIZER_FILE, trainer_out_path, speaker_ref
TTS/demos/xtts_ft_demo/xtts_demo.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import sys
5
+ import tempfile
6
+ import traceback
7
+
8
+ import gradio as gr
9
+ import torch
10
+ import torchaudio
11
+
12
+ from TTS.demos.xtts_ft_demo.utils.formatter import format_audio_list
13
+ from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt
14
+ from TTS.tts.configs.xtts_config import XttsConfig
15
+ from TTS.tts.models.xtts import Xtts
16
+
17
+
18
+ def clear_gpu_cache():
19
+ # clear the GPU cache
20
+ if torch.cuda.is_available():
21
+ torch.cuda.empty_cache()
22
+
23
+
24
+ XTTS_MODEL = None
25
+
26
+
27
+ def load_model(xtts_checkpoint, xtts_config, xtts_vocab):
28
+ global XTTS_MODEL
29
+ clear_gpu_cache()
30
+ if not xtts_checkpoint or not xtts_config or not xtts_vocab:
31
+ return "You need to run the previous steps or manually set the `XTTS checkpoint path`, `XTTS config path`, and `XTTS vocab path` fields !!"
32
+ config = XttsConfig()
33
+ config.load_json(xtts_config)
34
+ XTTS_MODEL = Xtts.init_from_config(config)
35
+ print("Loading XTTS model! ")
36
+ XTTS_MODEL.load_checkpoint(config, checkpoint_path=xtts_checkpoint, vocab_path=xtts_vocab, use_deepspeed=False)
37
+ if torch.cuda.is_available():
38
+ XTTS_MODEL.cuda()
39
+
40
+ print("Model Loaded!")
41
+ return "Model Loaded!"
42
+
43
+
44
+ def run_tts(lang, tts_text, speaker_audio_file):
45
+ if XTTS_MODEL is None or not speaker_audio_file:
46
+ return "You need to run the previous step to load the model !!", None, None
47
+
48
+ gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(
49
+ audio_path=speaker_audio_file,
50
+ gpt_cond_len=XTTS_MODEL.config.gpt_cond_len,
51
+ max_ref_length=XTTS_MODEL.config.max_ref_len,
52
+ sound_norm_refs=XTTS_MODEL.config.sound_norm_refs,
53
+ )
54
+ out = XTTS_MODEL.inference(
55
+ text=tts_text,
56
+ language=lang,
57
+ gpt_cond_latent=gpt_cond_latent,
58
+ speaker_embedding=speaker_embedding,
59
+ temperature=XTTS_MODEL.config.temperature, # Add custom parameters here
60
+ length_penalty=XTTS_MODEL.config.length_penalty,
61
+ repetition_penalty=XTTS_MODEL.config.repetition_penalty,
62
+ top_k=XTTS_MODEL.config.top_k,
63
+ top_p=XTTS_MODEL.config.top_p,
64
+ )
65
+
66
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp:
67
+ out["wav"] = torch.tensor(out["wav"]).unsqueeze(0)
68
+ out_path = fp.name
69
+ torchaudio.save(out_path, out["wav"], 24000)
70
+
71
+ return "Speech generated !", out_path, speaker_audio_file
72
+
73
+
74
+ # define a logger to redirect
75
+ class Logger:
76
+ def __init__(self, filename="log.out"):
77
+ self.log_file = filename
78
+ self.terminal = sys.stdout
79
+ self.log = open(self.log_file, "w")
80
+
81
+ def write(self, message):
82
+ self.terminal.write(message)
83
+ self.log.write(message)
84
+
85
+ def flush(self):
86
+ self.terminal.flush()
87
+ self.log.flush()
88
+
89
+ def isatty(self):
90
+ return False
91
+
92
+
93
+ # redirect stdout and stderr to a file
94
+ sys.stdout = Logger()
95
+ sys.stderr = sys.stdout
96
+
97
+
98
+ # logging.basicConfig(stream=sys.stdout, level=logging.INFO)
99
+
100
+ logging.basicConfig(
101
+ level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stdout)]
102
+ )
103
+
104
+
105
+ def read_logs():
106
+ sys.stdout.flush()
107
+ with open(sys.stdout.log_file) as f:
108
+ return f.read()
109
+
110
+
111
+ if __name__ == "__main__":
112
+ parser = argparse.ArgumentParser(
113
+ description="""XTTS fine-tuning demo\n\n"""
114
+ """
115
+ Example runs:
116
+ python3 TTS/demos/xtts_ft_demo/xtts_demo.py --port
117
+ """,
118
+ formatter_class=argparse.RawTextHelpFormatter,
119
+ )
120
+ parser.add_argument(
121
+ "--port",
122
+ type=int,
123
+ help="Port to run the gradio demo. Default: 5003",
124
+ default=5003,
125
+ )
126
+ parser.add_argument(
127
+ "--out_path",
128
+ type=str,
129
+ help="Output path (where data and checkpoints will be saved) Default: /tmp/xtts_ft/",
130
+ default="/tmp/xtts_ft/",
131
+ )
132
+
133
+ parser.add_argument(
134
+ "--num_epochs",
135
+ type=int,
136
+ help="Number of epochs to train. Default: 10",
137
+ default=10,
138
+ )
139
+ parser.add_argument(
140
+ "--batch_size",
141
+ type=int,
142
+ help="Batch size. Default: 4",
143
+ default=4,
144
+ )
145
+ parser.add_argument(
146
+ "--grad_acumm",
147
+ type=int,
148
+ help="Grad accumulation steps. Default: 1",
149
+ default=1,
150
+ )
151
+ parser.add_argument(
152
+ "--max_audio_length",
153
+ type=int,
154
+ help="Max permitted audio size in seconds. Default: 11",
155
+ default=11,
156
+ )
157
+
158
+ args = parser.parse_args()
159
+
160
+ with gr.Blocks() as demo:
161
+ with gr.Tab("1 - Data processing"):
162
+ out_path = gr.Textbox(
163
+ label="Output path (where data and checkpoints will be saved):",
164
+ value=args.out_path,
165
+ )
166
+ # upload_file = gr.Audio(
167
+ # sources="upload",
168
+ # label="Select here the audio files that you want to use for XTTS trainining !",
169
+ # type="filepath",
170
+ # )
171
+ upload_file = gr.File(
172
+ file_count="multiple",
173
+ label="Select here the audio files that you want to use for XTTS trainining (Supported formats: wav, mp3, and flac)",
174
+ )
175
+ lang = gr.Dropdown(
176
+ label="Dataset Language",
177
+ value="en",
178
+ choices=[
179
+ "en",
180
+ "es",
181
+ "fr",
182
+ "de",
183
+ "it",
184
+ "pt",
185
+ "pl",
186
+ "tr",
187
+ "ru",
188
+ "nl",
189
+ "cs",
190
+ "ar",
191
+ "zh",
192
+ "hu",
193
+ "ko",
194
+ "ja",
195
+ "hi",
196
+ ],
197
+ )
198
+ progress_data = gr.Label(label="Progress:")
199
+
200
+ # Read logs every 1 second
201
+ timer = gr.Timer(1)
202
+ logs_tts_train = gr.Textbox(
203
+ value=read_logs,
204
+ every=timer,
205
+ label="Logs:",
206
+ interactive=False,
207
+ )
208
+
209
+ prompt_compute_btn = gr.Button(value="Step 1 - Create dataset")
210
+
211
+ def preprocess_dataset(audio_path, language, out_path, progress=gr.Progress(track_tqdm=True)):
212
+ clear_gpu_cache()
213
+ out_path = os.path.join(out_path, "dataset")
214
+ os.makedirs(out_path, exist_ok=True)
215
+ if audio_path is None:
216
+ return (
217
+ "You should provide one or multiple audio files! If you provided it, probably the upload of the files is not finished yet!",
218
+ "",
219
+ "",
220
+ )
221
+ else:
222
+ try:
223
+ train_meta, eval_meta, audio_total_size = format_audio_list(
224
+ audio_path, target_language=language, out_path=out_path, gradio_progress=progress
225
+ )
226
+ except:
227
+ traceback.print_exc()
228
+ error = traceback.format_exc()
229
+ return (
230
+ f"The data processing was interrupted due an error !! Please check the console to verify the full error message! \n Error summary: {error}",
231
+ "",
232
+ "",
233
+ )
234
+
235
+ clear_gpu_cache()
236
+
237
+ # if audio total len is less than 2 minutes raise an error
238
+ if audio_total_size < 120:
239
+ message = "The sum of the duration of the audios that you provided should be at least 2 minutes!"
240
+ print(message)
241
+ return message, "", ""
242
+
243
+ print("Dataset Processed!")
244
+ return "Dataset Processed!", train_meta, eval_meta
245
+
246
+ with gr.Tab("2 - Fine-tuning XTTS Encoder"):
247
+ train_csv = gr.Textbox(
248
+ label="Train CSV:",
249
+ )
250
+ eval_csv = gr.Textbox(
251
+ label="Eval CSV:",
252
+ )
253
+ num_epochs = gr.Slider(
254
+ label="Number of epochs:",
255
+ minimum=1,
256
+ maximum=100,
257
+ step=1,
258
+ value=args.num_epochs,
259
+ )
260
+ batch_size = gr.Slider(
261
+ label="Batch size:",
262
+ minimum=2,
263
+ maximum=512,
264
+ step=1,
265
+ value=args.batch_size,
266
+ )
267
+ grad_acumm = gr.Slider(
268
+ label="Grad accumulation steps:",
269
+ minimum=2,
270
+ maximum=128,
271
+ step=1,
272
+ value=args.grad_acumm,
273
+ )
274
+ max_audio_length = gr.Slider(
275
+ label="Max permitted audio size in seconds:",
276
+ minimum=2,
277
+ maximum=20,
278
+ step=1,
279
+ value=args.max_audio_length,
280
+ )
281
+ progress_train = gr.Label(label="Progress:")
282
+
283
+ # Read logs every 1 second
284
+ timer = gr.Timer(1)
285
+ logs_tts_train = gr.Textbox(
286
+ value=read_logs,
287
+ every=timer,
288
+ label="Logs:",
289
+ interactive=False,
290
+ )
291
+
292
+ train_btn = gr.Button(value="Step 2 - Run the training")
293
+
294
+ def train_model(
295
+ language, train_csv, eval_csv, num_epochs, batch_size, grad_acumm, output_path, max_audio_length
296
+ ):
297
+ clear_gpu_cache()
298
+ if not train_csv or not eval_csv:
299
+ return (
300
+ "You need to run the data processing step or manually set `Train CSV` and `Eval CSV` fields !",
301
+ "",
302
+ "",
303
+ "",
304
+ "",
305
+ )
306
+ try:
307
+ # convert seconds to waveform frames
308
+ max_audio_length = int(max_audio_length * 22050)
309
+ config_path, original_xtts_checkpoint, vocab_file, exp_path, speaker_wav = train_gpt(
310
+ language,
311
+ num_epochs,
312
+ batch_size,
313
+ grad_acumm,
314
+ train_csv,
315
+ eval_csv,
316
+ output_path=output_path,
317
+ max_audio_length=max_audio_length,
318
+ )
319
+ except:
320
+ traceback.print_exc()
321
+ error = traceback.format_exc()
322
+ return (
323
+ f"The training was interrupted due an error !! Please check the console to check the full error message! \n Error summary: {error}",
324
+ "",
325
+ "",
326
+ "",
327
+ "",
328
+ )
329
+
330
+ # copy original files to avoid parameters changes issues
331
+ os.system(f"cp {config_path} {exp_path}")
332
+ os.system(f"cp {vocab_file} {exp_path}")
333
+
334
+ ft_xtts_checkpoint = os.path.join(exp_path, "best_model.pth")
335
+ print("Model training done!")
336
+ clear_gpu_cache()
337
+ return "Model training done!", config_path, vocab_file, ft_xtts_checkpoint, speaker_wav
338
+
339
+ with gr.Tab("3 - Inference"):
340
+ with gr.Row():
341
+ with gr.Column() as col1:
342
+ xtts_checkpoint = gr.Textbox(
343
+ label="XTTS checkpoint path:",
344
+ value="",
345
+ )
346
+ xtts_config = gr.Textbox(
347
+ label="XTTS config path:",
348
+ value="",
349
+ )
350
+
351
+ xtts_vocab = gr.Textbox(
352
+ label="XTTS vocab path:",
353
+ value="",
354
+ )
355
+ progress_load = gr.Label(label="Progress:")
356
+ load_btn = gr.Button(value="Step 3 - Load Fine-tuned XTTS model")
357
+
358
+ with gr.Column() as col2:
359
+ speaker_reference_audio = gr.Textbox(
360
+ label="Speaker reference audio:",
361
+ value="",
362
+ )
363
+ tts_language = gr.Dropdown(
364
+ label="Language",
365
+ value="en",
366
+ choices=[
367
+ "en",
368
+ "es",
369
+ "fr",
370
+ "de",
371
+ "it",
372
+ "pt",
373
+ "pl",
374
+ "tr",
375
+ "ru",
376
+ "nl",
377
+ "cs",
378
+ "ar",
379
+ "zh",
380
+ "hu",
381
+ "ko",
382
+ "ja",
383
+ "hi",
384
+ ],
385
+ )
386
+ tts_text = gr.Textbox(
387
+ label="Input Text.",
388
+ value="This model sounds really good and above all, it's reasonably fast.",
389
+ )
390
+ tts_btn = gr.Button(value="Step 4 - Inference")
391
+
392
+ with gr.Column() as col3:
393
+ progress_gen = gr.Label(label="Progress:")
394
+ tts_output_audio = gr.Audio(label="Generated Audio.")
395
+ reference_audio = gr.Audio(label="Reference audio used.")
396
+
397
+ prompt_compute_btn.click(
398
+ fn=preprocess_dataset,
399
+ inputs=[
400
+ upload_file,
401
+ lang,
402
+ out_path,
403
+ ],
404
+ outputs=[
405
+ progress_data,
406
+ train_csv,
407
+ eval_csv,
408
+ ],
409
+ )
410
+
411
+ train_btn.click(
412
+ fn=train_model,
413
+ inputs=[
414
+ lang,
415
+ train_csv,
416
+ eval_csv,
417
+ num_epochs,
418
+ batch_size,
419
+ grad_acumm,
420
+ out_path,
421
+ max_audio_length,
422
+ ],
423
+ outputs=[progress_train, xtts_config, xtts_vocab, xtts_checkpoint, speaker_reference_audio],
424
+ )
425
+
426
+ load_btn.click(
427
+ fn=load_model,
428
+ inputs=[xtts_checkpoint, xtts_config, xtts_vocab],
429
+ outputs=[progress_load],
430
+ )
431
+
432
+ tts_btn.click(
433
+ fn=run_tts,
434
+ inputs=[
435
+ tts_language,
436
+ tts_text,
437
+ speaker_reference_audio,
438
+ ],
439
+ outputs=[progress_gen, tts_output_audio, reference_audio],
440
+ )
441
+
442
+ demo.launch(share=True, debug=False, server_port=args.port, server_name="0.0.0.0")
TTS/encoder/README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Speaker Encoder
2
+
3
+ This is an implementation of https://arxiv.org/abs/1710.10467. This model can be used for voice and speaker embedding.
4
+
5
+ With the code here you can generate d-vectors for both multi-speaker and single-speaker TTS datasets, then visualise and explore them along with the associated audio files in an interactive chart.
6
+
7
+ Below is an example showing embedding results of various speakers. You can generate the same plot with the provided notebook as demonstrated in [this video](https://youtu.be/KW3oO7JVa7Q).
8
+
9
+ ![](umap.png)
10
+
11
+ Download a pretrained model from [Released Models](https://github.com/mozilla/TTS/wiki/Released-Models) page.
12
+
13
+ To run the code, you need to follow the same flow as in TTS.
14
+
15
+ - Define 'config.json' for your needs. Note that, audio parameters should match your TTS model.
16
+ - Example training call ```python speaker_encoder/train.py --config_path speaker_encoder/config.json --data_path ~/Data/Libri-TTS/train-clean-360```
17
+ - Generate embedding vectors ```python speaker_encoder/compute_embeddings.py --use_cuda /model/path/best_model.pth model/config/path/config.json dataset/path/ output_path``` . This code parses all .wav files at the given dataset path and generates the same folder structure under the output path with the generated embedding files.
18
+ - Watch training on Tensorboard as in TTS
TTS/encoder/__init__.py ADDED
File without changes
TTS/encoder/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (167 Bytes). View file
 
TTS/encoder/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (200 Bytes). View file
 
TTS/encoder/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (165 Bytes). View file
 
TTS/encoder/__pycache__/losses.cpython-310.pyc ADDED
Binary file (7.88 kB). View file
 
TTS/encoder/__pycache__/losses.cpython-311.pyc ADDED
Binary file (13.9 kB). View file
 
TTS/encoder/__pycache__/losses.cpython-39.pyc ADDED
Binary file (7.91 kB). View file
 
TTS/encoder/configs/base_encoder_config.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import asdict, dataclass, field
2
+
3
+ from coqpit import MISSING
4
+
5
+ from TTS.config.shared_configs import BaseAudioConfig, BaseDatasetConfig, BaseTrainingConfig
6
+
7
+
8
+ @dataclass
9
+ class BaseEncoderConfig(BaseTrainingConfig):
10
+ """Defines parameters for a Generic Encoder model."""
11
+
12
+ model: str = None
13
+ audio: BaseAudioConfig = field(default_factory=BaseAudioConfig)
14
+ datasets: list[BaseDatasetConfig] = field(default_factory=lambda: [BaseDatasetConfig()])
15
+ # model params
16
+ model_params: dict = field(
17
+ default_factory=lambda: {
18
+ "model_name": "lstm",
19
+ "input_dim": 80,
20
+ "proj_dim": 256,
21
+ "lstm_dim": 768,
22
+ "num_lstm_layers": 3,
23
+ "use_lstm_with_projection": True,
24
+ }
25
+ )
26
+
27
+ audio_augmentation: dict = field(default_factory=dict)
28
+
29
+ # training params
30
+ epochs: int = 10000
31
+ loss: str = "angleproto"
32
+ grad_clip: float = 3.0
33
+ lr: float = 0.0001
34
+ optimizer: str = "radam"
35
+ optimizer_params: dict = field(default_factory=lambda: {"betas": [0.9, 0.999], "weight_decay": 0})
36
+ lr_decay: bool = False
37
+ warmup_steps: int = 4000
38
+
39
+ # logging params
40
+ tb_model_param_stats: bool = False
41
+ steps_plot_stats: int = 10
42
+ save_step: int = 1000
43
+ print_step: int = 20
44
+ run_eval: bool = False
45
+
46
+ # data loader
47
+ num_classes_in_batch: int = MISSING
48
+ num_utter_per_class: int = MISSING
49
+ eval_num_classes_in_batch: int = None
50
+ eval_num_utter_per_class: int = None
51
+
52
+ num_loader_workers: int = MISSING
53
+ voice_len: float = 1.6
54
+
55
+ def check_values(self):
56
+ super().check_values()
57
+ c = asdict(self)
58
+ assert c["model_params"]["input_dim"] == self.audio.num_mels, (
59
+ " [!] model input dimendion must be equal to melspectrogram dimension."
60
+ )
TTS/encoder/configs/emotion_encoder_config.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from TTS.encoder.configs.base_encoder_config import BaseEncoderConfig
4
+
5
+
6
+ @dataclass
7
+ class EmotionEncoderConfig(BaseEncoderConfig):
8
+ """Defines parameters for Emotion Encoder model."""
9
+
10
+ model: str = "emotion_encoder"
11
+ map_classid_to_classname: dict = None
12
+ class_name_key: str = "emotion_name"