922CA commited on
Commit
9730154
·
verified ·
1 Parent(s): 7af9f59

Upload 4 files

Browse files
Files changed (4) hide show
  1. 1/best_model.pth +3 -0
  2. 1/config.json +159 -0
  3. 1/vocab.json +0 -0
  4. 1/xtts_demo.py +415 -0
1/best_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36c51edb6b337fe3c2cc91dbf555d0d4785a6aa45c6207c7cc103adc618903b0
3
+ size 5607926933
1/config.json ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "output_path": "output",
3
+ "logger_uri": null,
4
+ "run_name": "run",
5
+ "project_name": null,
6
+ "run_description": "\ud83d\udc38Coqui trainer run.",
7
+ "print_step": 25,
8
+ "plot_step": 100,
9
+ "model_param_stats": false,
10
+ "wandb_entity": null,
11
+ "dashboard_logger": "tensorboard",
12
+ "save_on_interrupt": true,
13
+ "log_model_step": null,
14
+ "save_step": 10000,
15
+ "save_n_checkpoints": 5,
16
+ "save_checkpoints": true,
17
+ "save_all_best": false,
18
+ "save_best_after": 10000,
19
+ "target_loss": null,
20
+ "print_eval": false,
21
+ "test_delay_epochs": 0,
22
+ "run_eval": true,
23
+ "run_eval_steps": null,
24
+ "distributed_backend": "nccl",
25
+ "distributed_url": "tcp://localhost:54321",
26
+ "mixed_precision": false,
27
+ "precision": "fp16",
28
+ "epochs": 1000,
29
+ "batch_size": 32,
30
+ "eval_batch_size": 16,
31
+ "grad_clip": 0.0,
32
+ "scheduler_after_epoch": true,
33
+ "lr": 0.001,
34
+ "optimizer": "radam",
35
+ "optimizer_params": null,
36
+ "lr_scheduler": null,
37
+ "lr_scheduler_params": {},
38
+ "use_grad_scaler": false,
39
+ "allow_tf32": false,
40
+ "cudnn_enable": true,
41
+ "cudnn_deterministic": false,
42
+ "cudnn_benchmark": false,
43
+ "training_seed": 54321,
44
+ "model": "xtts",
45
+ "num_loader_workers": 0,
46
+ "num_eval_loader_workers": 0,
47
+ "use_noise_augment": false,
48
+ "audio": {
49
+ "sample_rate": 22050,
50
+ "output_sample_rate": 24000
51
+ },
52
+ "use_phonemes": false,
53
+ "phonemizer": null,
54
+ "phoneme_language": null,
55
+ "compute_input_seq_cache": false,
56
+ "text_cleaner": null,
57
+ "enable_eos_bos_chars": false,
58
+ "test_sentences_file": "",
59
+ "phoneme_cache_path": null,
60
+ "characters": null,
61
+ "add_blank": false,
62
+ "batch_group_size": 0,
63
+ "loss_masking": null,
64
+ "min_audio_len": 1,
65
+ "max_audio_len": Infinity,
66
+ "min_text_len": 1,
67
+ "max_text_len": Infinity,
68
+ "compute_f0": false,
69
+ "compute_energy": false,
70
+ "compute_linear_spec": false,
71
+ "precompute_num_workers": 0,
72
+ "start_by_longest": false,
73
+ "shuffle": false,
74
+ "drop_last": false,
75
+ "datasets": [
76
+ {
77
+ "formatter": "",
78
+ "dataset_name": "",
79
+ "path": "",
80
+ "meta_file_train": "",
81
+ "ignored_speakers": null,
82
+ "language": "",
83
+ "phonemizer": "",
84
+ "meta_file_val": "",
85
+ "meta_file_attn_mask": ""
86
+ }
87
+ ],
88
+ "test_sentences": [],
89
+ "eval_split_max_size": null,
90
+ "eval_split_size": 0.01,
91
+ "use_speaker_weighted_sampler": false,
92
+ "speaker_weighted_sampler_alpha": 1.0,
93
+ "use_language_weighted_sampler": false,
94
+ "language_weighted_sampler_alpha": 1.0,
95
+ "use_length_weighted_sampler": false,
96
+ "length_weighted_sampler_alpha": 1.0,
97
+ "model_args": {
98
+ "gpt_batch_size": 1,
99
+ "enable_redaction": false,
100
+ "kv_cache": true,
101
+ "gpt_checkpoint": null,
102
+ "clvp_checkpoint": null,
103
+ "decoder_checkpoint": null,
104
+ "num_chars": 255,
105
+ "tokenizer_file": "",
106
+ "gpt_max_audio_tokens": 605,
107
+ "gpt_max_text_tokens": 402,
108
+ "gpt_max_prompt_tokens": 70,
109
+ "gpt_layers": 30,
110
+ "gpt_n_model_channels": 1024,
111
+ "gpt_n_heads": 16,
112
+ "gpt_number_text_tokens": 6681,
113
+ "gpt_start_text_token": null,
114
+ "gpt_stop_text_token": null,
115
+ "gpt_num_audio_tokens": 1026,
116
+ "gpt_start_audio_token": 1024,
117
+ "gpt_stop_audio_token": 1025,
118
+ "gpt_code_stride_len": 1024,
119
+ "gpt_use_masking_gt_prompt_approach": true,
120
+ "gpt_use_perceiver_resampler": true,
121
+ "input_sample_rate": 22050,
122
+ "output_sample_rate": 24000,
123
+ "output_hop_length": 256,
124
+ "decoder_input_dim": 1024,
125
+ "d_vector_dim": 512,
126
+ "cond_d_vector_in_each_upsampling_layer": true,
127
+ "duration_const": 102400
128
+ },
129
+ "model_dir": null,
130
+ "languages": [
131
+ "en",
132
+ "es",
133
+ "fr",
134
+ "de",
135
+ "it",
136
+ "pt",
137
+ "pl",
138
+ "tr",
139
+ "ru",
140
+ "nl",
141
+ "cs",
142
+ "ar",
143
+ "zh-cn",
144
+ "hu",
145
+ "ko",
146
+ "ja",
147
+ "hi"
148
+ ],
149
+ "temperature": 0.75,
150
+ "length_penalty": 1.0,
151
+ "repetition_penalty": 5.0,
152
+ "top_k": 50,
153
+ "top_p": 0.85,
154
+ "num_gpt_outputs": 1,
155
+ "gpt_cond_len": 30,
156
+ "gpt_cond_chunk_len": 4,
157
+ "max_ref_len": 30,
158
+ "sound_norm_refs": false
159
+ }
1/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
1/xtts_demo.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import tempfile
5
+
6
+ import gradio as gr
7
+ import librosa.display
8
+ import numpy as np
9
+
10
+ import os
11
+ import torch
12
+ import torchaudio
13
+ import traceback
14
+ from TTS.demos.xtts_ft_demo.utils.formatter import format_audio_list
15
+ from TTS.demos.xtts_ft_demo.utils.gpt_train import train_gpt
16
+
17
+ from TTS.tts.configs.xtts_config import XttsConfig
18
+ from TTS.tts.models.xtts import Xtts
19
+
20
+
21
+ def clear_gpu_cache():
22
+ # clear the GPU cache
23
+ if torch.cuda.is_available():
24
+ torch.cuda.empty_cache()
25
+
26
+ XTTS_MODEL = None
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
+ def run_tts(lang, tts_text, speaker_audio_file):
44
+ if XTTS_MODEL is None or not speaker_audio_file:
45
+ return "You need to run the previous step to load the model !!", None, None
46
+
47
+ gpt_cond_latent, speaker_embedding = XTTS_MODEL.get_conditioning_latents(audio_path=speaker_audio_file, gpt_cond_len=XTTS_MODEL.config.gpt_cond_len, max_ref_length=XTTS_MODEL.config.max_ref_len, sound_norm_refs=XTTS_MODEL.config.sound_norm_refs)
48
+ out = XTTS_MODEL.inference(
49
+ text=tts_text,
50
+ language=lang,
51
+ gpt_cond_latent=gpt_cond_latent,
52
+ speaker_embedding=speaker_embedding,
53
+ temperature=XTTS_MODEL.config.temperature, # Add custom parameters here
54
+ length_penalty=XTTS_MODEL.config.length_penalty,
55
+ repetition_penalty=XTTS_MODEL.config.repetition_penalty,
56
+ top_k=XTTS_MODEL.config.top_k,
57
+ top_p=XTTS_MODEL.config.top_p,
58
+ )
59
+
60
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp:
61
+ out["wav"] = torch.tensor(out["wav"]).unsqueeze(0)
62
+ out_path = fp.name
63
+ torchaudio.save(out_path, out["wav"], 24000)
64
+
65
+ return "Speech generated !", out_path, speaker_audio_file
66
+
67
+
68
+
69
+
70
+ # define a logger to redirect
71
+ class Logger:
72
+ def __init__(self, filename="log.out"):
73
+ self.log_file = filename
74
+ self.terminal = sys.stdout
75
+ self.log = open(self.log_file, "w")
76
+
77
+ def write(self, message):
78
+ self.terminal.write(message)
79
+ self.log.write(message)
80
+
81
+ def flush(self):
82
+ self.terminal.flush()
83
+ self.log.flush()
84
+
85
+ def isatty(self):
86
+ return False
87
+
88
+ # redirect stdout and stderr to a file
89
+ sys.stdout = Logger()
90
+ sys.stderr = sys.stdout
91
+
92
+
93
+ # logging.basicConfig(stream=sys.stdout, level=logging.INFO)
94
+ import logging
95
+ logging.basicConfig(
96
+ level=logging.INFO,
97
+ format="%(asctime)s [%(levelname)s] %(message)s",
98
+ handlers=[
99
+ logging.StreamHandler(sys.stdout)
100
+ ]
101
+ )
102
+
103
+ def read_logs():
104
+ sys.stdout.flush()
105
+ with open(sys.stdout.log_file, "r") as f:
106
+ return f.read()
107
+
108
+
109
+ if __name__ == "__main__":
110
+
111
+ parser = argparse.ArgumentParser(
112
+ description="""XTTS fine-tuning demo\n\n"""
113
+ """
114
+ Example runs:
115
+ python3 TTS/demos/xtts_ft_demo/xtts_demo.py --port
116
+ """,
117
+ formatter_class=argparse.RawTextHelpFormatter,
118
+ )
119
+ parser.add_argument(
120
+ "--port",
121
+ type=int,
122
+ help="Port to run the gradio demo. Default: 5003",
123
+ default=5003,
124
+ )
125
+ parser.add_argument(
126
+ "--out_path",
127
+ type=str,
128
+ help="Output path (where data and checkpoints will be saved) Default: /tmp/xtts_ft/",
129
+ default="/tmp/xtts_ft/",
130
+ )
131
+
132
+ parser.add_argument(
133
+ "--num_epochs",
134
+ type=int,
135
+ help="Number of epochs to train. Default: 10",
136
+ default=10,
137
+ )
138
+ parser.add_argument(
139
+ "--batch_size",
140
+ type=int,
141
+ help="Batch size. Default: 4",
142
+ default=4,
143
+ )
144
+ parser.add_argument(
145
+ "--grad_acumm",
146
+ type=int,
147
+ help="Grad accumulation steps. Default: 1",
148
+ default=1,
149
+ )
150
+ parser.add_argument(
151
+ "--max_audio_length",
152
+ type=int,
153
+ help="Max permitted audio size in seconds. Default: 11",
154
+ default=11,
155
+ )
156
+
157
+ args = parser.parse_args()
158
+
159
+ with gr.Blocks() as demo:
160
+ with gr.Tab("1 - Data processing"):
161
+ out_path = gr.Textbox(
162
+ label="Output path (where data and checkpoints will be saved):",
163
+ value=args.out_path,
164
+ )
165
+ # upload_file = gr.Audio(
166
+ # sources="upload",
167
+ # label="Select here the audio files that you want to use for XTTS trainining !",
168
+ # type="filepath",
169
+ # )
170
+ upload_file = gr.File(
171
+ file_count="multiple",
172
+ label="Select here the audio files that you want to use for XTTS trainining (Supported formats: wav, mp3, and flac)",
173
+ )
174
+ lang = gr.Dropdown(
175
+ label="Dataset Language",
176
+ value="en",
177
+ choices=[
178
+ "en",
179
+ "es",
180
+ "fr",
181
+ "de",
182
+ "it",
183
+ "pt",
184
+ "pl",
185
+ "tr",
186
+ "ru",
187
+ "nl",
188
+ "cs",
189
+ "ar",
190
+ "zh",
191
+ "hu",
192
+ "ko",
193
+ "ja"
194
+ ],
195
+ )
196
+ progress_data = gr.Label(
197
+ label="Progress:"
198
+ )
199
+ logs = gr.Textbox(
200
+ label="Logs:",
201
+ interactive=False,
202
+ )
203
+ demo.load(read_logs, None, logs, every=1)
204
+
205
+ prompt_compute_btn = gr.Button(value="Step 1 - Create dataset")
206
+
207
+ def preprocess_dataset(audio_path, language, out_path, progress=gr.Progress(track_tqdm=True)):
208
+ clear_gpu_cache()
209
+ out_path = os.path.join(out_path, "dataset")
210
+ os.makedirs(out_path, exist_ok=True)
211
+ if audio_path is None:
212
+ return "You should provide one or multiple audio files! If you provided it, probably the upload of the files is not finished yet!", "", ""
213
+ else:
214
+ try:
215
+ train_meta, eval_meta, audio_total_size = format_audio_list(audio_path, target_language=language, out_path=out_path, gradio_progress=progress)
216
+ except:
217
+ traceback.print_exc()
218
+ error = traceback.format_exc()
219
+ return f"The data processing was interrupted due an error !! Please check the console to verify the full error message! \n Error summary: {error}", "", ""
220
+
221
+ clear_gpu_cache()
222
+
223
+ # if audio total len is less than 2 minutes raise an error
224
+ if audio_total_size < 120:
225
+ message = "The sum of the duration of the audios that you provided should be at least 2 minutes!"
226
+ print(message)
227
+ return message, "", ""
228
+
229
+ print("Dataset Processed!")
230
+ return "Dataset Processed!", train_meta, eval_meta
231
+
232
+ with gr.Tab("2 - Fine-tuning XTTS Encoder"):
233
+ train_csv = gr.Textbox(
234
+ label="Train CSV:",
235
+ )
236
+ eval_csv = gr.Textbox(
237
+ label="Eval CSV:",
238
+ )
239
+ num_epochs = gr.Slider(
240
+ label="Number of epochs:",
241
+ minimum=1,
242
+ maximum=100,
243
+ step=1,
244
+ value=args.num_epochs,
245
+ )
246
+ batch_size = gr.Slider(
247
+ label="Batch size:",
248
+ minimum=2,
249
+ maximum=512,
250
+ step=1,
251
+ value=args.batch_size,
252
+ )
253
+ grad_acumm = gr.Slider(
254
+ label="Grad accumulation steps:",
255
+ minimum=2,
256
+ maximum=128,
257
+ step=1,
258
+ value=args.grad_acumm,
259
+ )
260
+ max_audio_length = gr.Slider(
261
+ label="Max permitted audio size in seconds:",
262
+ minimum=2,
263
+ maximum=20,
264
+ step=1,
265
+ value=args.max_audio_length,
266
+ )
267
+ progress_train = gr.Label(
268
+ label="Progress:"
269
+ )
270
+ logs_tts_train = gr.Textbox(
271
+ label="Logs:",
272
+ interactive=False,
273
+ )
274
+ demo.load(read_logs, None, logs_tts_train, every=1)
275
+ train_btn = gr.Button(value="Step 2 - Run the training")
276
+
277
+ def train_model(language, train_csv, eval_csv, num_epochs, batch_size, grad_acumm, output_path, max_audio_length):
278
+ clear_gpu_cache()
279
+ if not train_csv or not eval_csv:
280
+ return "You need to run the data processing step or manually set `Train CSV` and `Eval CSV` fields !", "", "", "", ""
281
+ try:
282
+ # convert seconds to waveform frames
283
+ max_audio_length = int(max_audio_length * 22050)
284
+ config_path, original_xtts_checkpoint, vocab_file, exp_path, speaker_wav = train_gpt(language, num_epochs, batch_size, grad_acumm, train_csv, eval_csv, output_path=output_path, max_audio_length=max_audio_length)
285
+ except:
286
+ traceback.print_exc()
287
+ error = traceback.format_exc()
288
+ return f"The training was interrupted due an error !! Please check the console to check the full error message! \n Error summary: {error}", "", "", "", ""
289
+
290
+ # copy original files to avoid parameters changes issues
291
+ os.system(f"cp {config_path} {exp_path}")
292
+ os.system(f"cp {vocab_file} {exp_path}")
293
+
294
+ ft_xtts_checkpoint = os.path.join(exp_path, "best_model.pth")
295
+ print("Model training done!")
296
+ clear_gpu_cache()
297
+ return "Model training done!", config_path, vocab_file, ft_xtts_checkpoint, speaker_wav
298
+
299
+ with gr.Tab("3 - Inference"):
300
+ with gr.Row():
301
+ with gr.Column() as col1:
302
+ xtts_checkpoint = gr.Textbox(
303
+ label="XTTS checkpoint path:",
304
+ value="",
305
+ )
306
+ xtts_config = gr.Textbox(
307
+ label="XTTS config path:",
308
+ value="",
309
+ )
310
+
311
+ xtts_vocab = gr.Textbox(
312
+ label="XTTS vocab path:",
313
+ value="",
314
+ )
315
+ progress_load = gr.Label(
316
+ label="Progress:"
317
+ )
318
+ load_btn = gr.Button(value="Step 3 - Load Fine-tuned XTTS model")
319
+
320
+ with gr.Column() as col2:
321
+ speaker_reference_audio = gr.Textbox(
322
+ label="Speaker reference audio:",
323
+ value="",
324
+ )
325
+ tts_language = gr.Dropdown(
326
+ label="Language",
327
+ value="en",
328
+ choices=[
329
+ "en",
330
+ "es",
331
+ "fr",
332
+ "de",
333
+ "it",
334
+ "pt",
335
+ "pl",
336
+ "tr",
337
+ "ru",
338
+ "nl",
339
+ "cs",
340
+ "ar",
341
+ "zh",
342
+ "hu",
343
+ "ko",
344
+ "ja",
345
+ ]
346
+ )
347
+ tts_text = gr.Textbox(
348
+ label="Input Text.",
349
+ value="This model sounds really good and above all, it's reasonably fast.",
350
+ )
351
+ tts_btn = gr.Button(value="Step 4 - Inference")
352
+
353
+ with gr.Column() as col3:
354
+ progress_gen = gr.Label(
355
+ label="Progress:"
356
+ )
357
+ tts_output_audio = gr.Audio(label="Generated Audio.")
358
+ reference_audio = gr.Audio(label="Reference audio used.")
359
+
360
+ prompt_compute_btn.click(
361
+ fn=preprocess_dataset,
362
+ inputs=[
363
+ upload_file,
364
+ lang,
365
+ out_path,
366
+ ],
367
+ outputs=[
368
+ progress_data,
369
+ train_csv,
370
+ eval_csv,
371
+ ],
372
+ )
373
+
374
+
375
+ train_btn.click(
376
+ fn=train_model,
377
+ inputs=[
378
+ lang,
379
+ train_csv,
380
+ eval_csv,
381
+ num_epochs,
382
+ batch_size,
383
+ grad_acumm,
384
+ out_path,
385
+ max_audio_length,
386
+ ],
387
+ outputs=[progress_train, xtts_config, xtts_vocab, xtts_checkpoint, speaker_reference_audio],
388
+ )
389
+
390
+ load_btn.click(
391
+ fn=load_model,
392
+ inputs=[
393
+ xtts_checkpoint,
394
+ xtts_config,
395
+ xtts_vocab
396
+ ],
397
+ outputs=[progress_load],
398
+ )
399
+
400
+ tts_btn.click(
401
+ fn=run_tts,
402
+ inputs=[
403
+ tts_language,
404
+ tts_text,
405
+ speaker_reference_audio,
406
+ ],
407
+ outputs=[progress_gen, tts_output_audio, reference_audio],
408
+ )
409
+
410
+ demo.launch(
411
+ share=True,
412
+ debug=False,
413
+ server_port=args.port,
414
+ server_name="0.0.0.0"
415
+ )