返回 F5-TTS
finetune_gradio.py
根目录 / src / f5_tts / train / finetune_gradio.py
1 import gc
2 import json
3 import os
4 import platform
5 import queue
6 import random
7 import re
8 import shutil
9 import signal
10 import subprocess
11 import sys
12 import tempfile
13 import threading
14 import time
15 from glob import glob
16 from importlib.resources import files
17
18 import click
19 import gradio as gr
20 import librosa
21 import numpy as np
22 import psutil
23 import torch
24 import torchaudio
25 from cached_path import cached_path
26 from datasets import Dataset as Dataset_
27 from datasets.arrow_writer import ArrowWriter
28 from safetensors.torch import load_file, save_file
29 from scipy.io import wavfile
30
31 from f5_tts.api import F5TTS
32 from f5_tts.device_utils import get_default_device
33 from f5_tts.infer.utils_infer import transcribe
34 from f5_tts.model.utils import convert_char_to_pinyin
35
36
37 def _safe_project_path(base: str, name: str) -> str:
38 """Return the resolved absolute path of base/name, raising ValueError if name
39 is absolute, contains a null byte, or resolves outside base."""
40 if not name or os.path.isabs(name) or "\x00" in name:
41 raise ValueError(f"invalid project_name: {name!r}")
42 # Strip path separators and control characters to a plain filename component.
43 name = re.sub(r"[/\\]", "", name).strip()
44 if not name or name in (".", ".."):
45 raise ValueError(f"invalid project_name: {name!r}")
46 candidate = os.path.realpath(os.path.join(base, name))
47 base_real = os.path.realpath(base)
48 if not (candidate + os.sep).startswith(base_real + os.sep):
49 raise ValueError(f"project_name escapes base directory: {name!r}")
50 return candidate
51
52
53 training_process = None
54 system = platform.system()
55 python_executable = sys.executable or "python"
56 tts_api = None
57 last_checkpoint = ""
58 last_device = ""
59 last_ema = None
60
61
62 path_data = str(files("f5_tts").joinpath("../../data"))
63 path_project_ckpts = str(files("f5_tts").joinpath("../../ckpts"))
64 file_train = str(files("f5_tts").joinpath("train/finetune_cli.py"))
65
66 device = get_default_device()
67
68
69 # Save settings from a JSON file
70 def save_settings(
71 project_name,
72 exp_name,
73 learning_rate,
74 batch_size_per_gpu,
75 batch_size_type,
76 max_samples,
77 grad_accumulation_steps,
78 max_grad_norm,
79 epochs,
80 num_warmup_updates,
81 save_per_updates,
82 keep_last_n_checkpoints,
83 last_per_updates,
84 finetune,
85 file_checkpoint_train,
86 tokenizer_type,
87 tokenizer_file,
88 mixed_precision,
89 logger,
90 ch_8bit_adam,
91 ):
92 path_project = _safe_project_path(path_project_ckpts, project_name)
93 os.makedirs(path_project, exist_ok=True)
94 file_setting = os.path.join(path_project, "setting.json")
95
96 settings = {
97 "exp_name": exp_name,
98 "learning_rate": learning_rate,
99 "batch_size_per_gpu": batch_size_per_gpu,
100 "batch_size_type": batch_size_type,
101 "max_samples": max_samples,
102 "grad_accumulation_steps": grad_accumulation_steps,
103 "max_grad_norm": max_grad_norm,
104 "epochs": epochs,
105 "num_warmup_updates": num_warmup_updates,
106 "save_per_updates": save_per_updates,
107 "keep_last_n_checkpoints": keep_last_n_checkpoints,
108 "last_per_updates": last_per_updates,
109 "finetune": finetune,
110 "file_checkpoint_train": file_checkpoint_train,
111 "tokenizer_type": tokenizer_type,
112 "tokenizer_file": tokenizer_file,
113 "mixed_precision": mixed_precision,
114 "logger": logger,
115 "bnb_optimizer": ch_8bit_adam,
116 }
117 with open(file_setting, "w") as f:
118 json.dump(settings, f, indent=4)
119 return "Settings saved!"
120
121
122 # Load settings from a JSON file
123 def load_settings(project_name):
124 project_name = project_name.replace("_pinyin", "").replace("_char", "")
125 path_project = _safe_project_path(path_project_ckpts, project_name)
126 file_setting = os.path.join(path_project, "setting.json")
127
128 # Default settings
129 default_settings = {
130 "exp_name": "F5TTS_v1_Base",
131 "learning_rate": 1e-5,
132 "batch_size_per_gpu": 3200,
133 "batch_size_type": "frame",
134 "max_samples": 64,
135 "grad_accumulation_steps": 1,
136 "max_grad_norm": 1.0,
137 "epochs": 100,
138 "num_warmup_updates": 100,
139 "save_per_updates": 500,
140 "keep_last_n_checkpoints": -1,
141 "last_per_updates": 100,
142 "finetune": True,
143 "file_checkpoint_train": "",
144 "tokenizer_type": "pinyin",
145 "tokenizer_file": "",
146 "mixed_precision": "fp16",
147 "logger": "none",
148 "bnb_optimizer": False,
149 }
150 if device == "mps":
151 default_settings["mixed_precision"] = "none"
152
153 # Load settings from file if it exists
154 if os.path.isfile(file_setting):
155 with open(file_setting, "r") as f:
156 file_settings = json.load(f)
157 default_settings.update(file_settings)
158
159 # Return as a tuple in the correct order
160 return (
161 default_settings["exp_name"],
162 default_settings["learning_rate"],
163 default_settings["batch_size_per_gpu"],
164 default_settings["batch_size_type"],
165 default_settings["max_samples"],
166 default_settings["grad_accumulation_steps"],
167 default_settings["max_grad_norm"],
168 default_settings["epochs"],
169 default_settings["num_warmup_updates"],
170 default_settings["save_per_updates"],
171 default_settings["keep_last_n_checkpoints"],
172 default_settings["last_per_updates"],
173 default_settings["finetune"],
174 default_settings["file_checkpoint_train"],
175 default_settings["tokenizer_type"],
176 default_settings["tokenizer_file"],
177 default_settings["mixed_precision"],
178 default_settings["logger"],
179 default_settings["bnb_optimizer"],
180 )
181
182
183 # Load metadata
184 def get_audio_duration(audio_path):
185 """Calculate the duration mono of an audio file."""
186 audio, sample_rate = torchaudio.load(audio_path)
187 return audio.shape[1] / sample_rate
188
189
190 class Slicer: # https://github.com/RVC-Boss/GPT-SoVITS/blob/main/tools/slicer2.py
191 def __init__(
192 self,
193 sr: int,
194 threshold: float = -40.0,
195 min_length: int = 20000, # 20 seconds
196 min_interval: int = 300,
197 hop_size: int = 20,
198 max_sil_kept: int = 2000,
199 ):
200 if not min_length >= min_interval >= hop_size:
201 raise ValueError("The following condition must be satisfied: min_length >= min_interval >= hop_size")
202 if not max_sil_kept >= hop_size:
203 raise ValueError("The following condition must be satisfied: max_sil_kept >= hop_size")
204 min_interval = sr * min_interval / 1000
205 self.threshold = 10 ** (threshold / 20.0)
206 self.hop_size = round(sr * hop_size / 1000)
207 self.win_size = min(round(min_interval), 4 * self.hop_size)
208 self.min_length = round(sr * min_length / 1000 / self.hop_size)
209 self.min_interval = round(min_interval / self.hop_size)
210 self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
211
212 def _apply_slice(self, waveform, begin, end):
213 if len(waveform.shape) > 1:
214 return waveform[:, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size)]
215 else:
216 return waveform[begin * self.hop_size : min(waveform.shape[0], end * self.hop_size)]
217
218 # @timeit
219 def slice(self, waveform):
220 if len(waveform.shape) > 1:
221 samples = waveform.mean(axis=0)
222 else:
223 samples = waveform
224 if samples.shape[0] <= self.min_length:
225 return [waveform]
226 rms_list = librosa.feature.rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
227 sil_tags = []
228 silence_start = None
229 clip_start = 0
230 for i, rms in enumerate(rms_list):
231 # Keep looping while frame is silent.
232 if rms < self.threshold:
233 # Record start of silent frames.
234 if silence_start is None:
235 silence_start = i
236 continue
237 # Keep looping while frame is not silent and silence start has not been recorded.
238 if silence_start is None:
239 continue
240 # Clear recorded silence start if interval is not enough or clip is too short
241 is_leading_silence = silence_start == 0 and i > self.max_sil_kept
242 need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
243 if not is_leading_silence and not need_slice_middle:
244 silence_start = None
245 continue
246 # Need slicing. Record the range of silent frames to be removed.
247 if i - silence_start <= self.max_sil_kept:
248 pos = rms_list[silence_start : i + 1].argmin() + silence_start
249 if silence_start == 0:
250 sil_tags.append((0, pos))
251 else:
252 sil_tags.append((pos, pos))
253 clip_start = pos
254 elif i - silence_start <= self.max_sil_kept * 2:
255 pos = rms_list[i - self.max_sil_kept : silence_start + self.max_sil_kept + 1].argmin()
256 pos += i - self.max_sil_kept
257 pos_l = rms_list[silence_start : silence_start + self.max_sil_kept + 1].argmin() + silence_start
258 pos_r = rms_list[i - self.max_sil_kept : i + 1].argmin() + i - self.max_sil_kept
259 if silence_start == 0:
260 sil_tags.append((0, pos_r))
261 clip_start = pos_r
262 else:
263 sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
264 clip_start = max(pos_r, pos)
265 else:
266 pos_l = rms_list[silence_start : silence_start + self.max_sil_kept + 1].argmin() + silence_start
267 pos_r = rms_list[i - self.max_sil_kept : i + 1].argmin() + i - self.max_sil_kept
268 if silence_start == 0:
269 sil_tags.append((0, pos_r))
270 else:
271 sil_tags.append((pos_l, pos_r))
272 clip_start = pos_r
273 silence_start = None
274 # Deal with trailing silence.
275 total_frames = rms_list.shape[0]
276 if silence_start is not None and total_frames - silence_start >= self.min_interval:
277 silence_end = min(total_frames, silence_start + self.max_sil_kept)
278 pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start
279 sil_tags.append((pos, total_frames + 1))
280 # Apply and return slices: [chunk, start, end]
281 if len(sil_tags) == 0:
282 return [[waveform, 0, int(total_frames * self.hop_size)]]
283 else:
284 chunks = []
285 if sil_tags[0][0] > 0:
286 chunks.append([self._apply_slice(waveform, 0, sil_tags[0][0]), 0, int(sil_tags[0][0] * self.hop_size)])
287 for i in range(len(sil_tags) - 1):
288 chunks.append(
289 [
290 self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]),
291 int(sil_tags[i][1] * self.hop_size),
292 int(sil_tags[i + 1][0] * self.hop_size),
293 ]
294 )
295 if sil_tags[-1][1] < total_frames:
296 chunks.append(
297 [
298 self._apply_slice(waveform, sil_tags[-1][1], total_frames),
299 int(sil_tags[-1][1] * self.hop_size),
300 int(total_frames * self.hop_size),
301 ]
302 )
303 return chunks
304
305
306 # terminal
307 def terminate_process_tree(pid, including_parent=True):
308 try:
309 parent = psutil.Process(pid)
310 except psutil.NoSuchProcess:
311 # Process already terminated
312 return
313
314 children = parent.children(recursive=True)
315 for child in children:
316 try:
317 os.kill(child.pid, signal.SIGTERM) # or signal.SIGKILL
318 except OSError:
319 pass
320 if including_parent:
321 try:
322 os.kill(parent.pid, signal.SIGTERM) # or signal.SIGKILL
323 except OSError:
324 pass
325
326
327 def terminate_process(pid):
328 if system == "Windows":
329 cmd = f"taskkill /t /f /pid {pid}"
330 os.system(cmd)
331 else:
332 terminate_process_tree(pid)
333
334
335 def start_training(
336 dataset_name,
337 exp_name,
338 learning_rate,
339 batch_size_per_gpu,
340 batch_size_type,
341 max_samples,
342 grad_accumulation_steps,
343 max_grad_norm,
344 epochs,
345 num_warmup_updates,
346 save_per_updates,
347 keep_last_n_checkpoints,
348 last_per_updates,
349 finetune,
350 file_checkpoint_train,
351 tokenizer_type,
352 tokenizer_file,
353 mixed_precision,
354 stream,
355 logger,
356 ch_8bit_adam,
357 ):
358 global training_process, tts_api, stop_signal
359
360 if tts_api is not None:
361 if tts_api is not None:
362 del tts_api
363
364 gc.collect()
365 torch.cuda.empty_cache()
366 tts_api = None
367
368 path_project = _safe_project_path(path_data, dataset_name)
369
370 if not os.path.isdir(path_project):
371 yield (
372 f"There is not project with name {dataset_name}",
373 gr.update(interactive=True),
374 gr.update(interactive=False),
375 )
376 return
377
378 file_raw = os.path.join(path_project, "raw.arrow")
379 if not os.path.isfile(file_raw):
380 yield f"There is no file {file_raw}", gr.update(interactive=True), gr.update(interactive=False)
381 return
382
383 # Check if a training process is already running
384 if training_process is not None:
385 return "Train run already!", gr.update(interactive=False), gr.update(interactive=True)
386
387 yield "start train", gr.update(interactive=False), gr.update(interactive=False)
388
389 # Command to run the training script with the specified arguments
390
391 if tokenizer_file == "":
392 if dataset_name.endswith("_pinyin"):
393 tokenizer_type = "pinyin"
394 elif dataset_name.endswith("_char"):
395 tokenizer_type = "char"
396 else:
397 tokenizer_type = "custom"
398
399 dataset_name = dataset_name.replace("_pinyin", "").replace("_char", "")
400
401 if mixed_precision != "none":
402 fp16 = f"--mixed_precision={mixed_precision}"
403 else:
404 fp16 = ""
405
406 cmd = (
407 f'accelerate launch {fp16} "{file_train}" --exp_name {exp_name}'
408 f" --learning_rate {learning_rate}"
409 f" --batch_size_per_gpu {batch_size_per_gpu}"
410 f" --batch_size_type {batch_size_type}"
411 f" --max_samples {max_samples}"
412 f" --grad_accumulation_steps {grad_accumulation_steps}"
413 f" --max_grad_norm {max_grad_norm}"
414 f" --epochs {epochs}"
415 f" --num_warmup_updates {num_warmup_updates}"
416 f" --save_per_updates {save_per_updates}"
417 f" --keep_last_n_checkpoints {keep_last_n_checkpoints}"
418 f" --last_per_updates {last_per_updates}"
419 f" --dataset_name {dataset_name}"
420 )
421
422 if finetune:
423 cmd += " --finetune"
424
425 if file_checkpoint_train != "":
426 cmd += f' --pretrain "{file_checkpoint_train}"'
427
428 if tokenizer_file != "":
429 cmd += f" --tokenizer_path {tokenizer_file}"
430
431 cmd += f" --tokenizer {tokenizer_type}"
432
433 if logger != "none":
434 cmd += f" --logger {logger}"
435
436 cmd += " --log_samples"
437
438 if ch_8bit_adam:
439 cmd += " --bnb_optimizer"
440
441 print("run command : \n" + cmd + "\n")
442
443 save_settings(
444 dataset_name,
445 exp_name,
446 learning_rate,
447 batch_size_per_gpu,
448 batch_size_type,
449 max_samples,
450 grad_accumulation_steps,
451 max_grad_norm,
452 epochs,
453 num_warmup_updates,
454 save_per_updates,
455 keep_last_n_checkpoints,
456 last_per_updates,
457 finetune,
458 file_checkpoint_train,
459 tokenizer_type,
460 tokenizer_file,
461 mixed_precision,
462 logger,
463 ch_8bit_adam,
464 )
465
466 try:
467 if not stream:
468 # Start the training process
469 training_process = subprocess.Popen(cmd, shell=True)
470
471 time.sleep(5)
472 yield "train start", gr.update(interactive=False), gr.update(interactive=True)
473
474 # Wait for the training process to finish
475 training_process.wait()
476 else:
477
478 def stream_output(pipe, output_queue):
479 try:
480 for line in iter(pipe.readline, ""):
481 output_queue.put(line)
482 except Exception as e:
483 output_queue.put(f"Error reading pipe: {str(e)}")
484 finally:
485 pipe.close()
486
487 env = os.environ.copy()
488 env["PYTHONUNBUFFERED"] = "1"
489
490 training_process = subprocess.Popen(
491 cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, env=env
492 )
493 yield "Training started ...", gr.update(interactive=False), gr.update(interactive=True)
494
495 stdout_queue = queue.Queue()
496 stderr_queue = queue.Queue()
497
498 stdout_thread = threading.Thread(target=stream_output, args=(training_process.stdout, stdout_queue))
499 stderr_thread = threading.Thread(target=stream_output, args=(training_process.stderr, stderr_queue))
500 stdout_thread.daemon = True
501 stderr_thread.daemon = True
502 stdout_thread.start()
503 stderr_thread.start()
504 stop_signal = False
505 while True:
506 if stop_signal:
507 training_process.terminate()
508 time.sleep(0.5)
509 if training_process.poll() is None:
510 training_process.kill()
511 yield "Training stopped by user.", gr.update(interactive=True), gr.update(interactive=False)
512 break
513
514 process_status = training_process.poll()
515
516 # Handle stdout
517 try:
518 while True:
519 output = stdout_queue.get_nowait()
520 print(output, end="")
521 match = re.search(
522 r"Epoch (\d+)/(\d+):\s+(\d+)%\|.*\[(\d+:\d+)<.*?loss=(\d+\.\d+), update=(\d+)", output
523 )
524 if match:
525 current_epoch = match.group(1)
526 total_epochs = match.group(2)
527 percent_complete = match.group(3)
528 elapsed_time = match.group(4)
529 loss = match.group(5)
530 current_update = match.group(6)
531 message = (
532 f"Epoch: {current_epoch}/{total_epochs}, "
533 f"Progress: {percent_complete}%, "
534 f"Elapsed Time: {elapsed_time}, "
535 f"Loss: {loss}, "
536 f"Update: {current_update}"
537 )
538 yield message, gr.update(interactive=False), gr.update(interactive=True)
539 elif output.strip():
540 yield output, gr.update(interactive=False), gr.update(interactive=True)
541 except queue.Empty:
542 pass
543
544 # Handle stderr
545 try:
546 while True:
547 error_output = stderr_queue.get_nowait()
548 print(error_output, end="")
549 if error_output.strip():
550 yield f"{error_output.strip()}", gr.update(interactive=False), gr.update(interactive=True)
551 except queue.Empty:
552 pass
553
554 if process_status is not None and stdout_queue.empty() and stderr_queue.empty():
555 if process_status != 0:
556 yield (
557 f"Process crashed with exit code {process_status}!",
558 gr.update(interactive=False),
559 gr.update(interactive=True),
560 )
561 else:
562 yield (
563 "Training complete or paused ...",
564 gr.update(interactive=False),
565 gr.update(interactive=True),
566 )
567 break
568
569 # Small sleep to prevent CPU thrashing
570 time.sleep(0.1)
571
572 # Clean up
573 training_process.stdout.close()
574 training_process.stderr.close()
575 training_process.wait()
576
577 time.sleep(1)
578
579 if training_process is None:
580 text_info = "Train stopped !"
581 else:
582 text_info = "Train complete at end !"
583
584 except Exception as e: # Catch all exceptions
585 # Ensure that we reset the training process variable in case of an error
586 text_info = f"An error occurred: {str(e)}"
587
588 training_process = None
589
590 yield text_info, gr.update(interactive=True), gr.update(interactive=False)
591
592
593 def stop_training():
594 global training_process, stop_signal
595
596 if training_process is None:
597 return "Train not running !", gr.update(interactive=True), gr.update(interactive=False)
598 terminate_process_tree(training_process.pid)
599 # training_process = None
600 stop_signal = True
601 return "Train stopped !", gr.update(interactive=True), gr.update(interactive=False)
602
603
604 def get_list_projects():
605 project_list = []
606 for folder in os.listdir(path_data):
607 path_folder = os.path.join(path_data, folder)
608 if not os.path.isdir(path_folder):
609 continue
610 folder = folder.lower()
611 if folder == "emilia_zh_en_pinyin":
612 continue
613 project_list.append(folder)
614
615 projects_selelect = None if not project_list else project_list[-1]
616
617 return project_list, projects_selelect
618
619
620 def create_data_project(name, tokenizer_type):
621 name += "_" + tokenizer_type
622 project_dir = _safe_project_path(path_data, name)
623 os.makedirs(project_dir, exist_ok=True)
624 os.makedirs(os.path.join(project_dir, "dataset"), exist_ok=True)
625 project_list, projects_selelect = get_list_projects()
626 return gr.update(choices=project_list, value=name)
627
628
629 def transcribe_all(name_project, audio_files, language, user=False, progress=gr.Progress()):
630 path_project = _safe_project_path(path_data, name_project)
631 path_dataset = os.path.join(path_project, "dataset")
632 path_project_wavs = os.path.join(path_project, "wavs")
633 file_metadata = os.path.join(path_project, "metadata.csv")
634
635 if not user:
636 if audio_files is None:
637 return "You need to load an audio file."
638
639 if os.path.isdir(path_project_wavs):
640 shutil.rmtree(path_project_wavs)
641
642 if os.path.isfile(file_metadata):
643 os.remove(file_metadata)
644
645 os.makedirs(path_project_wavs, exist_ok=True)
646
647 if user:
648 file_audios = [
649 file
650 for format in ("*.wav", "*.ogg", "*.opus", "*.mp3", "*.flac")
651 for file in glob(os.path.join(path_dataset, format))
652 ]
653 if file_audios == []:
654 return "No audio file was found in the dataset."
655 else:
656 file_audios = audio_files
657
658 alpha = 0.5
659 _max = 1.0
660 slicer = Slicer(24000)
661
662 num = 0
663 error_num = 0
664 data = ""
665 for file_audio in progress.tqdm(file_audios, desc="transcribe files", total=len((file_audios))):
666 audio, _ = librosa.load(file_audio, sr=24000, mono=True)
667
668 list_slicer = slicer.slice(audio)
669 for chunk, start, end in progress.tqdm(list_slicer, total=len(list_slicer), desc="slicer files"):
670 name_segment = os.path.join(f"segment_{num}")
671 file_segment = os.path.join(path_project_wavs, f"{name_segment}.wav")
672
673 tmp_max = np.abs(chunk).max()
674 if tmp_max > 1:
675 chunk /= tmp_max
676 chunk = (chunk / tmp_max * (_max * alpha)) + (1 - alpha) * chunk
677 wavfile.write(file_segment, 24000, (chunk * 32767).astype(np.int16))
678
679 try:
680 text = transcribe(file_segment, language)
681 text = text.strip()
682
683 data += f"{name_segment}|{text}\n"
684
685 num += 1
686 except: # noqa: E722
687 error_num += 1
688
689 with open(file_metadata, "w", encoding="utf-8-sig") as f:
690 f.write(data)
691
692 if error_num != []:
693 error_text = f"\nerror files : {error_num}"
694 else:
695 error_text = ""
696
697 return f"transcribe complete samples : {num}\npath : {path_project_wavs}{error_text}"
698
699
700 def format_seconds_to_hms(seconds):
701 hours = int(seconds / 3600)
702 minutes = int((seconds % 3600) / 60)
703 seconds = seconds % 60
704 return "{:02d}:{:02d}:{:02d}".format(hours, minutes, int(seconds))
705
706
707 def get_correct_audio_path(
708 audio_input,
709 base_path="wavs",
710 supported_formats=("wav", "mp3", "aac", "flac", "m4a", "alac", "ogg", "aiff", "wma", "amr"),
711 ):
712 file_audio = None
713
714 # Helper function to check if file has a supported extension
715 def has_supported_extension(file_name):
716 return any(file_name.endswith(f".{ext}") for ext in supported_formats)
717
718 # Case 1: If it's a full path with a valid extension, use it directly
719 if os.path.isabs(audio_input) and has_supported_extension(audio_input):
720 file_audio = audio_input
721
722 # Case 2: If it has a supported extension but is not a full path
723 elif has_supported_extension(audio_input) and not os.path.isabs(audio_input):
724 file_audio = os.path.join(base_path, audio_input)
725
726 # Case 3: If only the name is given (no extension and not a full path)
727 elif not has_supported_extension(audio_input) and not os.path.isabs(audio_input):
728 for ext in supported_formats:
729 potential_file = os.path.join(base_path, f"{audio_input}.{ext}")
730 if os.path.exists(potential_file):
731 file_audio = potential_file
732 break
733 else:
734 file_audio = os.path.join(base_path, f"{audio_input}.{supported_formats[0]}")
735 return file_audio
736
737
738 def create_metadata(name_project, ch_tokenizer, progress=gr.Progress()):
739 path_project = _safe_project_path(path_data, name_project)
740 path_project_wavs = os.path.join(path_project, "wavs")
741 file_metadata = os.path.join(path_project, "metadata.csv")
742 file_raw = os.path.join(path_project, "raw.arrow")
743 file_duration = os.path.join(path_project, "duration.json")
744 file_vocab = os.path.join(path_project, "vocab.txt")
745
746 if not os.path.isfile(file_metadata):
747 return "The file was not found in " + file_metadata, ""
748
749 with open(file_metadata, "r", encoding="utf-8-sig") as f:
750 data = f.read()
751
752 audio_path_list = []
753 text_list = []
754 duration_list = []
755
756 count = data.split("\n")
757 lenght = 0
758 result = []
759 error_files = []
760 text_vocab_set = set()
761 for line in progress.tqdm(data.split("\n"), total=count):
762 sp_line = line.split("|")
763 if len(sp_line) != 2:
764 continue
765 name_audio, text = sp_line[:2]
766
767 file_audio = get_correct_audio_path(name_audio, path_project_wavs)
768
769 if not os.path.isfile(file_audio):
770 error_files.append([file_audio, "error path"])
771 continue
772
773 try:
774 duration = get_audio_duration(file_audio)
775 except Exception as e:
776 error_files.append([file_audio, "duration"])
777 print(f"Error processing {file_audio}: {e}")
778 continue
779
780 if duration < 1 or duration > 30:
781 if duration > 30:
782 error_files.append([file_audio, "duration > 30 sec"])
783 if duration < 1:
784 error_files.append([file_audio, "duration < 1 sec "])
785 continue
786 if len(text) < 3:
787 error_files.append([file_audio, "very short text length 3"])
788 continue
789
790 text = text.strip()
791 text = convert_char_to_pinyin([text], polyphone=True)[0]
792
793 audio_path_list.append(file_audio)
794 duration_list.append(duration)
795 text_list.append(text)
796
797 result.append({"audio_path": file_audio, "text": text, "duration": duration})
798 if ch_tokenizer:
799 text_vocab_set.update(list(text))
800
801 lenght += duration
802
803 if duration_list == []:
804 return f"Error: No audio files found in the specified path : {path_project_wavs}", ""
805
806 min_second = round(min(duration_list), 2)
807 max_second = round(max(duration_list), 2)
808
809 with ArrowWriter(path=file_raw) as writer:
810 for line in progress.tqdm(result, total=len(result), desc="prepare data"):
811 writer.write(line)
812 writer.finalize()
813
814 with open(file_duration, "w") as f:
815 json.dump({"duration": duration_list}, f, ensure_ascii=False)
816
817 new_vocal = ""
818 if not ch_tokenizer:
819 if not os.path.isfile(file_vocab):
820 file_vocab_finetune = os.path.join(path_data, "Emilia_ZH_EN_pinyin/vocab.txt")
821 if not os.path.isfile(file_vocab_finetune):
822 return "Error: Vocabulary file 'Emilia_ZH_EN_pinyin' not found!", ""
823 shutil.copy2(file_vocab_finetune, file_vocab)
824
825 with open(file_vocab, "r", encoding="utf-8-sig") as f:
826 vocab_char_map = {}
827 for i, char in enumerate(f):
828 vocab_char_map[char[:-1]] = i
829 vocab_size = len(vocab_char_map)
830
831 else:
832 with open(file_vocab, "w", encoding="utf-8-sig") as f:
833 for vocab in sorted(text_vocab_set):
834 f.write(vocab + "\n")
835 new_vocal += vocab + "\n"
836 vocab_size = len(text_vocab_set)
837
838 if error_files != []:
839 error_text = "\n".join([" = ".join(item) for item in error_files])
840 else:
841 error_text = ""
842
843 return (
844 f"prepare complete \nsamples : {len(text_list)}\ntime data : {format_seconds_to_hms(lenght)}\nmin sec : {min_second}\nmax sec : {max_second}\nfile_arrow : {file_raw}\nvocab : {vocab_size}\n{error_text}",
845 new_vocal,
846 )
847
848
849 def check_user(value):
850 return gr.update(visible=not value), gr.update(visible=value)
851
852
853 def calculate_train(
854 name_project,
855 epochs,
856 learning_rate,
857 batch_size_per_gpu,
858 batch_size_type,
859 max_samples,
860 num_warmup_updates,
861 finetune,
862 ):
863 path_project = _safe_project_path(path_data, name_project)
864 file_duration = os.path.join(path_project, "duration.json")
865
866 hop_length = 256
867 sampling_rate = 24000
868
869 if not os.path.isfile(file_duration):
870 return (
871 epochs,
872 learning_rate,
873 batch_size_per_gpu,
874 max_samples,
875 num_warmup_updates,
876 "project not found !",
877 )
878
879 with open(file_duration, "r") as file:
880 data = json.load(file)
881
882 duration_list = data["duration"]
883 max_sample_length = max(duration_list) * sampling_rate / hop_length
884 total_samples = len(duration_list)
885 total_duration = sum(duration_list)
886
887 if torch.cuda.is_available():
888 gpu_count = torch.cuda.device_count()
889 total_memory = 0
890 for i in range(gpu_count):
891 gpu_properties = torch.cuda.get_device_properties(i)
892 total_memory += gpu_properties.total_memory / (1024**3) # in GB
893 elif torch.xpu.is_available():
894 gpu_count = torch.xpu.device_count()
895 total_memory = 0
896 for i in range(gpu_count):
897 gpu_properties = torch.xpu.get_device_properties(i)
898 total_memory += gpu_properties.total_memory / (1024**3)
899 elif torch.backends.mps.is_available():
900 gpu_count = 1
901 total_memory = psutil.virtual_memory().available / (1024**3)
902
903 avg_gpu_memory = total_memory / gpu_count
904
905 # rough estimate of batch size
906 if batch_size_type == "frame":
907 batch_size_per_gpu = max(int(38400 * (avg_gpu_memory - 5) / 75), int(max_sample_length))
908 elif batch_size_type == "sample":
909 batch_size_per_gpu = int(200 / (total_duration / total_samples))
910
911 if total_samples < 64:
912 max_samples = int(total_samples * 0.25)
913
914 num_warmup_updates = max(num_warmup_updates, int(total_samples * 0.05))
915
916 # take 1.2M updates as the maximum
917 max_updates = 1200000
918
919 if batch_size_type == "frame":
920 mini_batch_duration = batch_size_per_gpu * gpu_count * hop_length / sampling_rate
921 updates_per_epoch = total_duration / mini_batch_duration
922 elif batch_size_type == "sample":
923 updates_per_epoch = total_samples / batch_size_per_gpu / gpu_count
924
925 epochs = int(max_updates / updates_per_epoch)
926
927 if finetune:
928 learning_rate = 1e-5
929 else:
930 learning_rate = 7.5e-5
931
932 return (
933 epochs,
934 learning_rate,
935 batch_size_per_gpu,
936 max_samples,
937 num_warmup_updates,
938 total_samples,
939 )
940
941
942 def prune_checkpoint(checkpoint_path: str, new_checkpoint_path: str, save_ema: bool, safetensors: bool) -> str:
943 try:
944 checkpoint = torch.load(checkpoint_path, weights_only=True)
945 print("Original Checkpoint Keys:", checkpoint.keys())
946
947 to_retain = "ema_model_state_dict" if save_ema else "model_state_dict"
948 try:
949 model_state_dict_to_retain = checkpoint[to_retain]
950 except KeyError:
951 return f"{to_retain} not found in the checkpoint."
952
953 if safetensors:
954 new_checkpoint_path = new_checkpoint_path.replace(".pt", ".safetensors")
955 save_file(model_state_dict_to_retain, new_checkpoint_path)
956 else:
957 new_checkpoint_path = new_checkpoint_path.replace(".safetensors", ".pt")
958 new_checkpoint = {"ema_model_state_dict": model_state_dict_to_retain}
959 torch.save(new_checkpoint, new_checkpoint_path)
960
961 return f"New checkpoint saved at: {new_checkpoint_path}"
962
963 except Exception as e:
964 return f"An error occurred: {e}"
965
966
967 def expand_model_embeddings(ckpt_path, new_ckpt_path, num_new_tokens=42):
968 seed = 666
969 random.seed(seed)
970 os.environ["PYTHONHASHSEED"] = str(seed)
971 torch.manual_seed(seed)
972 torch.cuda.manual_seed(seed)
973 torch.cuda.manual_seed_all(seed)
974 torch.backends.cudnn.deterministic = True
975 torch.backends.cudnn.benchmark = False
976
977 if ckpt_path.endswith(".safetensors"):
978 ckpt = load_file(ckpt_path, device="cpu")
979 ckpt = {"ema_model_state_dict": ckpt}
980 elif ckpt_path.endswith(".pt"):
981 ckpt = torch.load(ckpt_path, map_location="cpu")
982
983 ema_sd = ckpt.get("ema_model_state_dict", {})
984 embed_key_ema = "ema_model.transformer.text_embed.text_embed.weight"
985 old_embed_ema = ema_sd[embed_key_ema]
986
987 vocab_old = old_embed_ema.size(0)
988 embed_dim = old_embed_ema.size(1)
989 vocab_new = vocab_old + num_new_tokens
990
991 def expand_embeddings(old_embeddings):
992 new_embeddings = torch.zeros((vocab_new, embed_dim))
993 new_embeddings[:vocab_old] = old_embeddings
994 new_embeddings[vocab_old:] = torch.randn((num_new_tokens, embed_dim))
995 return new_embeddings
996
997 ema_sd[embed_key_ema] = expand_embeddings(ema_sd[embed_key_ema])
998
999 if new_ckpt_path.endswith(".safetensors"):
1000 save_file(ema_sd, new_ckpt_path)
1001 elif new_ckpt_path.endswith(".pt"):
1002 torch.save(ckpt, new_ckpt_path)
1003
1004 return vocab_new
1005
1006
1007 def vocab_count(text):
1008 return str(len(text.split(",")))
1009
1010
1011 def vocab_extend(project_name, symbols, model_type):
1012 if symbols == "":
1013 return "Symbols empty!"
1014
1015 name_project = project_name
1016 path_project = _safe_project_path(path_data, name_project)
1017 file_vocab_project = os.path.join(path_project, "vocab.txt")
1018
1019 file_vocab = os.path.join(path_data, "Emilia_ZH_EN_pinyin/vocab.txt")
1020 if not os.path.isfile(file_vocab):
1021 return f"the file {file_vocab} not found !"
1022
1023 symbols = symbols.split(",")
1024 if symbols == []:
1025 return "Symbols to extend not found."
1026
1027 with open(file_vocab, "r", encoding="utf-8-sig") as f:
1028 data = f.read()
1029 vocab = data.split("\n")
1030 vocab_check = set(vocab)
1031
1032 miss_symbols = []
1033 for item in symbols:
1034 item = item.replace(" ", "")
1035 if item in vocab_check:
1036 continue
1037 miss_symbols.append(item)
1038
1039 if miss_symbols == []:
1040 return "Symbols are okay no need to extend."
1041
1042 size_vocab = len(vocab)
1043 vocab.pop()
1044 for item in miss_symbols:
1045 vocab.append(item)
1046
1047 vocab.append("")
1048
1049 with open(file_vocab_project, "w", encoding="utf-8") as f:
1050 f.write("\n".join(vocab))
1051
1052 if model_type == "F5TTS_v1_Base":
1053 ckpt_path = str(cached_path("hf://SWivid/F5-TTS/F5TTS_v1_Base/model_1250000.safetensors"))
1054 elif model_type == "F5TTS_Base":
1055 ckpt_path = str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.pt"))
1056 elif model_type == "E2TTS_Base":
1057 ckpt_path = str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.pt"))
1058
1059 vocab_size_new = len(miss_symbols)
1060
1061 dataset_name = name_project.replace("_pinyin", "").replace("_char", "")
1062 new_ckpt_path = _safe_project_path(path_project_ckpts, dataset_name)
1063 os.makedirs(new_ckpt_path, exist_ok=True)
1064
1065 # Add pretrained_ prefix to model when copying for consistency with finetune_cli.py
1066 new_ckpt_file = os.path.join(new_ckpt_path, "pretrained_" + os.path.basename(ckpt_path))
1067
1068 size = expand_model_embeddings(ckpt_path, new_ckpt_file, num_new_tokens=vocab_size_new)
1069
1070 vocab_new = "\n".join(miss_symbols)
1071 return f"vocab old size : {size_vocab}\nvocab new size : {size}\nvocab add : {vocab_size_new}\nnew symbols :\n{vocab_new}"
1072
1073
1074 def vocab_check(project_name, tokenizer_type):
1075 name_project = project_name
1076 path_project = _safe_project_path(path_data, name_project)
1077
1078 file_metadata = os.path.join(path_project, "metadata.csv")
1079
1080 file_vocab = os.path.join(path_data, "Emilia_ZH_EN_pinyin/vocab.txt")
1081 if not os.path.isfile(file_vocab):
1082 return f"the file {file_vocab} not found !", ""
1083
1084 with open(file_vocab, "r", encoding="utf-8-sig") as f:
1085 data = f.read()
1086 vocab = data.split("\n")
1087 vocab = set(vocab)
1088
1089 if not os.path.isfile(file_metadata):
1090 return f"the file {file_metadata} not found !", ""
1091
1092 with open(file_metadata, "r", encoding="utf-8-sig") as f:
1093 data = f.read()
1094
1095 miss_symbols = []
1096 miss_symbols_keep = {}
1097 for item in data.split("\n"):
1098 sp = item.split("|")
1099 if len(sp) != 2:
1100 continue
1101
1102 text = sp[1].strip()
1103 if tokenizer_type == "pinyin":
1104 text = convert_char_to_pinyin([text], polyphone=True)[0]
1105
1106 for t in text:
1107 if t not in vocab and t not in miss_symbols_keep:
1108 miss_symbols.append(t)
1109 miss_symbols_keep[t] = t
1110
1111 if miss_symbols == []:
1112 vocab_miss = ""
1113 info = "You can train using your language !"
1114 else:
1115 vocab_miss = ",".join(miss_symbols)
1116 info = f"The following {len(miss_symbols)} symbols are missing in your language\n\n"
1117
1118 return info, vocab_miss
1119
1120
1121 def get_random_sample_prepare(project_name):
1122 name_project = project_name
1123 path_project = _safe_project_path(path_data, name_project)
1124 file_arrow = os.path.join(path_project, "raw.arrow")
1125 if not os.path.isfile(file_arrow):
1126 return "", None
1127 dataset = Dataset_.from_file(file_arrow)
1128 random_sample = dataset.shuffle(seed=random.randint(0, 1000)).select([0])
1129 text = "[" + " , ".join(["' " + t + " '" for t in random_sample["text"][0]]) + "]"
1130 audio_path = random_sample["audio_path"][0]
1131 return text, audio_path
1132
1133
1134 def get_random_sample_transcribe(project_name):
1135 name_project = project_name
1136 path_project = _safe_project_path(path_data, name_project)
1137 file_metadata = os.path.join(path_project, "metadata.csv")
1138 if not os.path.isfile(file_metadata):
1139 return "", None
1140
1141 data = ""
1142 with open(file_metadata, "r", encoding="utf-8-sig") as f:
1143 data = f.read()
1144
1145 list_data = []
1146 for item in data.split("\n"):
1147 sp = item.split("|")
1148 if len(sp) != 2:
1149 continue
1150
1151 # fixed audio when it is absolute
1152 file_audio = get_correct_audio_path(sp[0], os.path.join(path_project, "wavs"))
1153 list_data.append([file_audio, sp[1]])
1154
1155 if list_data == []:
1156 return "", None
1157
1158 random_item = random.choice(list_data)
1159
1160 return random_item[1], random_item[0]
1161
1162
1163 def get_random_sample_infer(project_name):
1164 text, audio = get_random_sample_transcribe(project_name)
1165 return (
1166 text,
1167 text,
1168 audio,
1169 )
1170
1171
1172 def infer(
1173 project, file_checkpoint, exp_name, ref_text, ref_audio, gen_text, nfe_step, use_ema, speed, seed, remove_silence
1174 ):
1175 global last_checkpoint, last_device, tts_api, last_ema
1176
1177 if not os.path.isfile(file_checkpoint):
1178 return None, "checkpoint not found!"
1179
1180 if training_process is not None:
1181 device_test = "cpu"
1182 else:
1183 device_test = None
1184
1185 if last_checkpoint != file_checkpoint or last_device != device_test or last_ema != use_ema or tts_api is None:
1186 if last_checkpoint != file_checkpoint:
1187 last_checkpoint = file_checkpoint
1188
1189 if last_device != device_test:
1190 last_device = device_test
1191
1192 if last_ema != use_ema:
1193 last_ema = use_ema
1194
1195 vocab_file = os.path.join(path_data, project, "vocab.txt")
1196
1197 tts_api = F5TTS(
1198 model=exp_name, ckpt_file=file_checkpoint, vocab_file=vocab_file, device=device_test, use_ema=use_ema
1199 )
1200
1201 print("update >> ", device_test, file_checkpoint, use_ema)
1202
1203 if seed == -1: # -1 used for random
1204 seed = None
1205
1206 with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
1207 tts_api.infer(
1208 ref_file=ref_audio,
1209 ref_text=ref_text.strip(),
1210 gen_text=gen_text.strip(),
1211 nfe_step=nfe_step,
1212 speed=speed,
1213 remove_silence=remove_silence,
1214 file_wave=f.name,
1215 seed=seed,
1216 )
1217 return f.name, tts_api.device, str(tts_api.seed)
1218
1219
1220 def check_finetune(finetune):
1221 return gr.update(interactive=finetune), gr.update(interactive=finetune), gr.update(interactive=finetune)
1222
1223
1224 def get_checkpoints_project(project_name, is_gradio=True):
1225 if project_name is None:
1226 return [], ""
1227 project_name = project_name.replace("_pinyin", "").replace("_char", "")
1228
1229 if os.path.isdir(path_project_ckpts):
1230 files_checkpoints = glob(os.path.join(path_project_ckpts, project_name, "*.pt"))
1231 # Separate pretrained and regular checkpoints
1232 pretrained_checkpoints = [f for f in files_checkpoints if "pretrained_" in os.path.basename(f)]
1233 regular_checkpoints = [
1234 f
1235 for f in files_checkpoints
1236 if "pretrained_" not in os.path.basename(f) and "model_last.pt" not in os.path.basename(f)
1237 ]
1238 last_checkpoint = [f for f in files_checkpoints if "model_last.pt" in os.path.basename(f)]
1239
1240 # Sort regular checkpoints by number
1241 regular_checkpoints = sorted(
1242 regular_checkpoints, key=lambda x: int(os.path.basename(x).split("_")[1].split(".")[0])
1243 )
1244
1245 # Combine in order: pretrained, regular, last
1246 files_checkpoints = pretrained_checkpoints + regular_checkpoints + last_checkpoint
1247 else:
1248 files_checkpoints = []
1249
1250 selelect_checkpoint = None if not files_checkpoints else files_checkpoints[0]
1251
1252 if is_gradio:
1253 return gr.update(choices=files_checkpoints, value=selelect_checkpoint)
1254
1255 return files_checkpoints, selelect_checkpoint
1256
1257
1258 def get_audio_project(project_name, is_gradio=True):
1259 if project_name is None:
1260 return [], ""
1261 project_name = project_name.replace("_pinyin", "").replace("_char", "")
1262
1263 if os.path.isdir(path_project_ckpts):
1264 files_audios = glob(os.path.join(path_project_ckpts, project_name, "samples", "*.wav"))
1265 files_audios = sorted(files_audios, key=lambda x: int(os.path.basename(x).split("_")[1].split(".")[0]))
1266
1267 files_audios = [item.replace("_gen.wav", "") for item in files_audios if item.endswith("_gen.wav")]
1268 else:
1269 files_audios = []
1270
1271 selelect_checkpoint = None if not files_audios else files_audios[0]
1272
1273 if is_gradio:
1274 return gr.update(choices=files_audios, value=selelect_checkpoint)
1275
1276 return files_audios, selelect_checkpoint
1277
1278
1279 def get_gpu_stats():
1280 gpu_stats = ""
1281
1282 if torch.cuda.is_available():
1283 gpu_count = torch.cuda.device_count()
1284 for i in range(gpu_count):
1285 gpu_name = torch.cuda.get_device_name(i)
1286 gpu_properties = torch.cuda.get_device_properties(i)
1287 total_memory = gpu_properties.total_memory / (1024**3) # in GB
1288 allocated_memory = torch.cuda.memory_allocated(i) / (1024**2) # in MB
1289 reserved_memory = torch.cuda.memory_reserved(i) / (1024**2) # in MB
1290
1291 gpu_stats += (
1292 f"GPU {i} Name: {gpu_name}\n"
1293 f"Total GPU memory (GPU {i}): {total_memory:.2f} GB\n"
1294 f"Allocated GPU memory (GPU {i}): {allocated_memory:.2f} MB\n"
1295 f"Reserved GPU memory (GPU {i}): {reserved_memory:.2f} MB\n\n"
1296 )
1297 elif torch.xpu.is_available():
1298 gpu_count = torch.xpu.device_count()
1299 for i in range(gpu_count):
1300 gpu_name = torch.xpu.get_device_name(i)
1301 gpu_properties = torch.xpu.get_device_properties(i)
1302 total_memory = gpu_properties.total_memory / (1024**3) # in GB
1303 allocated_memory = torch.xpu.memory_allocated(i) / (1024**2) # in MB
1304 reserved_memory = torch.xpu.memory_reserved(i) / (1024**2) # in MB
1305
1306 gpu_stats += (
1307 f"GPU {i} Name: {gpu_name}\n"
1308 f"Total GPU memory (GPU {i}): {total_memory:.2f} GB\n"
1309 f"Allocated GPU memory (GPU {i}): {allocated_memory:.2f} MB\n"
1310 f"Reserved GPU memory (GPU {i}): {reserved_memory:.2f} MB\n\n"
1311 )
1312 elif torch.backends.mps.is_available():
1313 gpu_count = 1
1314 gpu_stats += "MPS GPU\n"
1315 total_memory = psutil.virtual_memory().total / (
1316 1024**3
1317 ) # Total system memory (MPS doesn't have its own memory)
1318 allocated_memory = 0
1319 reserved_memory = 0
1320
1321 gpu_stats += (
1322 f"Total system memory: {total_memory:.2f} GB\n"
1323 f"Allocated GPU memory (MPS): {allocated_memory:.2f} MB\n"
1324 f"Reserved GPU memory (MPS): {reserved_memory:.2f} MB\n"
1325 )
1326
1327 else:
1328 gpu_stats = "No GPU available"
1329
1330 return gpu_stats
1331
1332
1333 def get_cpu_stats():
1334 cpu_usage = psutil.cpu_percent(interval=1)
1335 memory_info = psutil.virtual_memory()
1336 memory_used = memory_info.used / (1024**2)
1337 memory_total = memory_info.total / (1024**2)
1338 memory_percent = memory_info.percent
1339
1340 pid = os.getpid()
1341 process = psutil.Process(pid)
1342 nice_value = process.nice()
1343
1344 cpu_stats = (
1345 f"CPU Usage: {cpu_usage:.2f}%\n"
1346 f"System Memory: {memory_used:.2f} MB used / {memory_total:.2f} MB total ({memory_percent}% used)\n"
1347 f"Process Priority (Nice value): {nice_value}"
1348 )
1349
1350 return cpu_stats
1351
1352
1353 def get_combined_stats():
1354 gpu_stats = get_gpu_stats()
1355 cpu_stats = get_cpu_stats()
1356 combined_stats = f"### GPU Stats\n{gpu_stats}\n\n### CPU Stats\n{cpu_stats}"
1357 return combined_stats
1358
1359
1360 def get_audio_select(file_sample):
1361 select_audio_ref = file_sample
1362 select_audio_gen = file_sample
1363
1364 if file_sample is not None:
1365 select_audio_ref += "_ref.wav"
1366 select_audio_gen += "_gen.wav"
1367
1368 return select_audio_ref, select_audio_gen
1369
1370
1371 with gr.Blocks() as app:
1372 gr.Markdown(
1373 """
1374 # F5 TTS Automatic Finetune
1375
1376 This is a local web UI for F5 TTS finetuning support. This app supports the following TTS models:
1377
1378 * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
1379 * [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
1380
1381 The pretrained checkpoints support English and Chinese.
1382
1383 For tutorial and updates check here (https://github.com/SWivid/F5-TTS/discussions/143)
1384 """
1385 )
1386
1387 with gr.Row():
1388 projects, projects_selelect = get_list_projects()
1389 tokenizer_type = gr.Radio(label="Tokenizer Type", choices=["pinyin", "char", "custom"], value="pinyin")
1390 project_name = gr.Textbox(label="Project Name", value="my_speak")
1391 bt_create = gr.Button("Create a New Project")
1392
1393 with gr.Row():
1394 cm_project = gr.Dropdown(
1395 choices=projects, value=projects_selelect, label="Project", allow_custom_value=True, scale=6
1396 )
1397 ch_refresh_project = gr.Button("Refresh", scale=1)
1398
1399 bt_create.click(fn=create_data_project, inputs=[project_name, tokenizer_type], outputs=[cm_project])
1400
1401 with gr.Tabs():
1402 with gr.TabItem("Transcribe Data"):
1403 gr.Markdown("""```plaintext
1404 Skip this step if you have your dataset, metadata.csv, and a folder wavs with all the audio files.
1405 ```""")
1406
1407 ch_manual = gr.Checkbox(label="Audio from Path", value=False)
1408
1409 mark_info_transcribe = gr.Markdown(
1410 """```plaintext
1411 Place your 'wavs' folder and 'metadata.csv' file in the '{your_project_name}' directory.
1412
1413 my_speak/
1414 │
1415 └── dataset/
1416 ├── audio1.wav
1417 └── audio2.wav
1418 ...
1419 ```""",
1420 visible=False,
1421 )
1422
1423 audio_speaker = gr.File(label="Voice", type="filepath", file_count="multiple")
1424 txt_lang = gr.Textbox(label="Language", value="English")
1425 bt_transcribe = bt_create = gr.Button("Transcribe")
1426 txt_info_transcribe = gr.Textbox(label="Info", value="")
1427 bt_transcribe.click(
1428 fn=transcribe_all,
1429 inputs=[cm_project, audio_speaker, txt_lang, ch_manual],
1430 outputs=[txt_info_transcribe],
1431 )
1432 ch_manual.change(fn=check_user, inputs=[ch_manual], outputs=[audio_speaker, mark_info_transcribe])
1433
1434 random_sample_transcribe = gr.Button("Random Sample")
1435
1436 with gr.Row():
1437 random_text_transcribe = gr.Textbox(label="Text")
1438 random_audio_transcribe = gr.Audio(label="Audio", type="filepath")
1439
1440 random_sample_transcribe.click(
1441 fn=get_random_sample_transcribe,
1442 inputs=[cm_project],
1443 outputs=[random_text_transcribe, random_audio_transcribe],
1444 )
1445
1446 with gr.TabItem("Vocab Check"):
1447 gr.Markdown("""```plaintext
1448 Check the vocabulary for fine-tuning Emilia_ZH_EN to ensure all symbols are included. For fine-tuning a new language.
1449 ```""")
1450
1451 check_button = gr.Button("Check Vocab")
1452 txt_info_check = gr.Textbox(label="Info", value="")
1453
1454 gr.Markdown("""```plaintext
1455 Using the extended model, you can finetune to a new language that is missing symbols in the vocab. This creates a new model with a new vocabulary size and saves it in your ckpts/project folder.
1456 ```""")
1457
1458 exp_name_extend = gr.Radio(
1459 label="Model", choices=["F5TTS_v1_Base", "F5TTS_Base", "E2TTS_Base"], value="F5TTS_v1_Base"
1460 )
1461
1462 with gr.Row():
1463 txt_extend = gr.Textbox(
1464 label="Symbols",
1465 value="",
1466 placeholder="To add new symbols, make sure to use ',' for each symbol",
1467 scale=6,
1468 )
1469 txt_count_symbol = gr.Textbox(label="New Vocab Size", value="", scale=1)
1470
1471 extend_button = gr.Button("Extend")
1472 txt_info_extend = gr.Textbox(label="Info", value="")
1473
1474 txt_extend.change(vocab_count, inputs=[txt_extend], outputs=[txt_count_symbol])
1475 check_button.click(
1476 fn=vocab_check, inputs=[cm_project, tokenizer_type], outputs=[txt_info_check, txt_extend]
1477 )
1478 extend_button.click(
1479 fn=vocab_extend, inputs=[cm_project, txt_extend, exp_name_extend], outputs=[txt_info_extend]
1480 )
1481
1482 with gr.TabItem("Prepare Data"):
1483 gr.Markdown("""```plaintext
1484 Skip this step if you have your dataset, raw.arrow, duration.json, and vocab.txt
1485 ```""")
1486
1487 gr.Markdown(
1488 """```plaintext
1489 Place all your "wavs" folder and your "metadata.csv" file in your project name directory.
1490
1491 Supported audio formats: "wav", "mp3", "aac", "flac", "m4a", "alac", "ogg", "aiff", "wma", "amr"
1492
1493 Example wav format:
1494 my_speak/
1495 │
1496 ├── wavs/
1497 │ ├── audio1.wav
1498 │ └── audio2.wav
1499 | ...
1500 │
1501 └── metadata.csv
1502
1503 File format metadata.csv:
1504
1505 audio1|text1 or audio1.wav|text1 or your_path/audio1.wav|text1
1506 audio2|text1 or audio2.wav|text1 or your_path/audio2.wav|text1
1507 ...
1508
1509 ```"""
1510 )
1511 ch_tokenizern = gr.Checkbox(label="Create Vocabulary", value=False, visible=False)
1512
1513 bt_prepare = bt_create = gr.Button("Prepare")
1514 txt_info_prepare = gr.Textbox(label="Info", value="")
1515 txt_vocab_prepare = gr.Textbox(label="Vocab", value="")
1516
1517 bt_prepare.click(
1518 fn=create_metadata, inputs=[cm_project, ch_tokenizern], outputs=[txt_info_prepare, txt_vocab_prepare]
1519 )
1520
1521 random_sample_prepare = gr.Button("Random Sample")
1522
1523 with gr.Row():
1524 random_text_prepare = gr.Textbox(label="Tokenizer")
1525 random_audio_prepare = gr.Audio(label="Audio", type="filepath")
1526
1527 random_sample_prepare.click(
1528 fn=get_random_sample_prepare, inputs=[cm_project], outputs=[random_text_prepare, random_audio_prepare]
1529 )
1530
1531 with gr.TabItem("Train Model"):
1532 gr.Markdown("""```plaintext
1533 The auto-setting is still experimental. Set a large value of epoch if not sure; and keep last N checkpoints if limited disk space.
1534 If you encounter a memory error, try reducing the batch size per GPU to a smaller number.
1535 ```""")
1536 with gr.Row():
1537 exp_name = gr.Radio(label="Model", choices=["F5TTS_v1_Base", "F5TTS_Base", "E2TTS_Base"])
1538 tokenizer_file = gr.Textbox(label="Tokenizer File")
1539 file_checkpoint_train = gr.Textbox(label="Path to the Pretrained Checkpoint")
1540
1541 with gr.Row():
1542 ch_finetune = bt_create = gr.Checkbox(label="Finetune")
1543 lb_samples = gr.Label(label="Samples")
1544 bt_calculate = bt_create = gr.Button("Auto Settings")
1545
1546 with gr.Row():
1547 epochs = gr.Number(label="Epochs")
1548 learning_rate = gr.Number(label="Learning Rate", step=0.5e-5)
1549 max_grad_norm = gr.Number(label="Max Gradient Norm")
1550 num_warmup_updates = gr.Number(label="Warmup Updates")
1551
1552 with gr.Row():
1553 batch_size_type = gr.Radio(
1554 label="Batch Size Type",
1555 choices=["frame", "sample"],
1556 info="frame is calculated as seconds * sampling_rate / hop_length",
1557 )
1558 batch_size_per_gpu = gr.Number(label="Batch Size per GPU", info="N frames or N samples")
1559 grad_accumulation_steps = gr.Number(
1560 label="Gradient Accumulation Steps", info="Effective batch size is multiplied by this value"
1561 )
1562 max_samples = gr.Number(label="Max Samples", info="Maximum number of samples per single GPU batch")
1563
1564 with gr.Row():
1565 save_per_updates = gr.Number(
1566 label="Save per Updates",
1567 info="Save intermediate checkpoints every N updates",
1568 minimum=10,
1569 )
1570 keep_last_n_checkpoints = gr.Number(
1571 label="Keep Last N Checkpoints",
1572 step=1,
1573 precision=0,
1574 info="-1 to keep all, 0 to not save intermediate, > 0 to keep last N",
1575 minimum=-1,
1576 )
1577 last_per_updates = gr.Number(
1578 label="Last per Updates",
1579 info="Save latest checkpoint with suffix _last.pt every N updates",
1580 minimum=10,
1581 )
1582 gr.Radio(label="") # placeholder
1583
1584 with gr.Row():
1585 ch_8bit_adam = gr.Checkbox(label="Use 8-bit Adam optimizer")
1586 mixed_precision = gr.Radio(label="Mixed Precision", choices=["none", "fp16", "bf16"])
1587 cd_logger = gr.Radio(label="Logger", choices=["none", "wandb", "tensorboard"])
1588 with gr.Column():
1589 start_button = gr.Button("Start Training")
1590 stop_button = gr.Button("Stop Training", interactive=False)
1591
1592 if projects_selelect is not None:
1593 (
1594 exp_name_value,
1595 learning_rate_value,
1596 batch_size_per_gpu_value,
1597 batch_size_type_value,
1598 max_samples_value,
1599 grad_accumulation_steps_value,
1600 max_grad_norm_value,
1601 epochs_value,
1602 num_warmup_updates_value,
1603 save_per_updates_value,
1604 keep_last_n_checkpoints_value,
1605 last_per_updates_value,
1606 finetune_value,
1607 file_checkpoint_train_value,
1608 tokenizer_type_value,
1609 tokenizer_file_value,
1610 mixed_precision_value,
1611 logger_value,
1612 bnb_optimizer_value,
1613 ) = load_settings(projects_selelect)
1614
1615 # Assigning values to the respective components
1616 exp_name.value = exp_name_value
1617 learning_rate.value = learning_rate_value
1618 batch_size_per_gpu.value = batch_size_per_gpu_value
1619 batch_size_type.value = batch_size_type_value
1620 max_samples.value = max_samples_value
1621 grad_accumulation_steps.value = grad_accumulation_steps_value
1622 max_grad_norm.value = max_grad_norm_value
1623 epochs.value = epochs_value
1624 num_warmup_updates.value = num_warmup_updates_value
1625 save_per_updates.value = save_per_updates_value
1626 keep_last_n_checkpoints.value = keep_last_n_checkpoints_value
1627 last_per_updates.value = last_per_updates_value
1628 ch_finetune.value = finetune_value
1629 file_checkpoint_train.value = file_checkpoint_train_value
1630 tokenizer_type.value = tokenizer_type_value
1631 tokenizer_file.value = tokenizer_file_value
1632 mixed_precision.value = mixed_precision_value
1633 cd_logger.value = logger_value
1634 ch_8bit_adam.value = bnb_optimizer_value
1635
1636 ch_stream = gr.Checkbox(label="Stream Output Experiment", value=True)
1637 txt_info_train = gr.Textbox(label="Info", value="")
1638
1639 list_audios, select_audio = get_audio_project(projects_selelect, False)
1640
1641 select_audio_ref = select_audio
1642 select_audio_gen = select_audio
1643
1644 if select_audio is not None:
1645 select_audio_ref += "_ref.wav"
1646 select_audio_gen += "_gen.wav"
1647
1648 with gr.Row():
1649 ch_list_audio = gr.Dropdown(
1650 choices=list_audios,
1651 value=select_audio,
1652 label="Audios",
1653 allow_custom_value=True,
1654 scale=6,
1655 interactive=True,
1656 )
1657 bt_stream_audio = gr.Button("Refresh", scale=1)
1658 bt_stream_audio.click(fn=get_audio_project, inputs=[cm_project], outputs=[ch_list_audio])
1659 cm_project.change(fn=get_audio_project, inputs=[cm_project], outputs=[ch_list_audio])
1660
1661 with gr.Row():
1662 audio_ref_stream = gr.Audio(label="Original", type="filepath", value=select_audio_ref)
1663 audio_gen_stream = gr.Audio(label="Generate", type="filepath", value=select_audio_gen)
1664
1665 ch_list_audio.change(
1666 fn=get_audio_select,
1667 inputs=[ch_list_audio],
1668 outputs=[audio_ref_stream, audio_gen_stream],
1669 )
1670
1671 start_button.click(
1672 fn=start_training,
1673 inputs=[
1674 cm_project,
1675 exp_name,
1676 learning_rate,
1677 batch_size_per_gpu,
1678 batch_size_type,
1679 max_samples,
1680 grad_accumulation_steps,
1681 max_grad_norm,
1682 epochs,
1683 num_warmup_updates,
1684 save_per_updates,
1685 keep_last_n_checkpoints,
1686 last_per_updates,
1687 ch_finetune,
1688 file_checkpoint_train,
1689 tokenizer_type,
1690 tokenizer_file,
1691 mixed_precision,
1692 ch_stream,
1693 cd_logger,
1694 ch_8bit_adam,
1695 ],
1696 outputs=[txt_info_train, start_button, stop_button],
1697 )
1698 stop_button.click(fn=stop_training, outputs=[txt_info_train, start_button, stop_button])
1699
1700 bt_calculate.click(
1701 fn=calculate_train,
1702 inputs=[
1703 cm_project,
1704 epochs,
1705 learning_rate,
1706 batch_size_per_gpu,
1707 batch_size_type,
1708 max_samples,
1709 num_warmup_updates,
1710 ch_finetune,
1711 ],
1712 outputs=[
1713 epochs,
1714 learning_rate,
1715 batch_size_per_gpu,
1716 max_samples,
1717 num_warmup_updates,
1718 lb_samples,
1719 ],
1720 )
1721
1722 ch_finetune.change(
1723 check_finetune, inputs=[ch_finetune], outputs=[file_checkpoint_train, tokenizer_file, tokenizer_type]
1724 )
1725
1726 def setup_load_settings():
1727 output_components = [
1728 exp_name,
1729 learning_rate,
1730 batch_size_per_gpu,
1731 batch_size_type,
1732 max_samples,
1733 grad_accumulation_steps,
1734 max_grad_norm,
1735 epochs,
1736 num_warmup_updates,
1737 save_per_updates,
1738 keep_last_n_checkpoints,
1739 last_per_updates,
1740 ch_finetune,
1741 file_checkpoint_train,
1742 tokenizer_type,
1743 tokenizer_file,
1744 mixed_precision,
1745 cd_logger,
1746 ch_8bit_adam,
1747 ]
1748 return output_components
1749
1750 outputs = setup_load_settings()
1751
1752 cm_project.change(
1753 fn=load_settings,
1754 inputs=[cm_project],
1755 outputs=outputs,
1756 )
1757
1758 ch_refresh_project.click(
1759 fn=load_settings,
1760 inputs=[cm_project],
1761 outputs=outputs,
1762 )
1763
1764 with gr.TabItem("Test Model"):
1765 gr.Markdown("""```plaintext
1766 Check the use_ema setting (True or False) for your model to see what works best for you. Set seed to -1 for random.
1767 ```""")
1768 exp_name = gr.Radio(
1769 label="Model", choices=["F5TTS_v1_Base", "F5TTS_Base", "E2TTS_Base"], value="F5TTS_v1_Base"
1770 )
1771 list_checkpoints, checkpoint_select = get_checkpoints_project(projects_selelect, False)
1772
1773 with gr.Row():
1774 nfe_step = gr.Number(label="NFE Step", value=32)
1775 speed = gr.Slider(label="Speed", value=1.0, minimum=0.3, maximum=2.0, step=0.1)
1776 seed = gr.Number(label="Random Seed", value=-1, minimum=-1)
1777 remove_silence = gr.Checkbox(label="Remove Silence")
1778
1779 with gr.Row():
1780 ch_use_ema = gr.Checkbox(
1781 label="Use EMA", value=True, info="Turn off at early stage might offer better results"
1782 )
1783 cm_checkpoint = gr.Dropdown(
1784 choices=list_checkpoints, value=checkpoint_select, label="Checkpoints", allow_custom_value=True
1785 )
1786 bt_checkpoint_refresh = gr.Button("Refresh")
1787
1788 random_sample_infer = gr.Button("Random Sample")
1789
1790 ref_text = gr.Textbox(label="Reference Text")
1791 ref_audio = gr.Audio(label="Reference Audio", type="filepath")
1792 gen_text = gr.Textbox(label="Text to Generate")
1793
1794 random_sample_infer.click(
1795 fn=get_random_sample_infer, inputs=[cm_project], outputs=[ref_text, gen_text, ref_audio]
1796 )
1797
1798 with gr.Row():
1799 txt_info_gpu = gr.Textbox("", label="Inference on Device :")
1800 seed_info = gr.Textbox(label="Used Random Seed :")
1801 check_button_infer = gr.Button("Inference")
1802
1803 gen_audio = gr.Audio(label="Generated Audio", type="filepath")
1804
1805 check_button_infer.click(
1806 fn=infer,
1807 inputs=[
1808 cm_project,
1809 cm_checkpoint,
1810 exp_name,
1811 ref_text,
1812 ref_audio,
1813 gen_text,
1814 nfe_step,
1815 ch_use_ema,
1816 speed,
1817 seed,
1818 remove_silence,
1819 ],
1820 outputs=[gen_audio, txt_info_gpu, seed_info],
1821 )
1822
1823 bt_checkpoint_refresh.click(fn=get_checkpoints_project, inputs=[cm_project], outputs=[cm_checkpoint])
1824 cm_project.change(fn=get_checkpoints_project, inputs=[cm_project], outputs=[cm_checkpoint])
1825
1826 with gr.TabItem("Prune Checkpoint"):
1827 gr.Markdown("""```plaintext
1828 Reduce the Base model size from 5GB to 1.3GB. The new checkpoint file prunes out optimizer and etc., can be used for inference or finetuning afterward, but not able to resume pretraining.
1829 ```""")
1830 txt_path_checkpoint = gr.Textbox(label="Path to Checkpoint:")
1831 txt_path_checkpoint_small = gr.Textbox(label="Path to Output:")
1832 with gr.Row():
1833 ch_save_ema = gr.Checkbox(label="Save EMA checkpoint", value=True)
1834 ch_safetensors = gr.Checkbox(label="Save with safetensors format", value=True)
1835 txt_info_reduse = gr.Textbox(label="Info", value="")
1836 reduse_button = gr.Button("Prune")
1837 reduse_button.click(
1838 fn=prune_checkpoint,
1839 inputs=[txt_path_checkpoint, txt_path_checkpoint_small, ch_save_ema, ch_safetensors],
1840 outputs=[txt_info_reduse],
1841 )
1842
1843 with gr.TabItem("System Info"):
1844 output_box = gr.Textbox(label="GPU and CPU Information", lines=20)
1845
1846 def update_stats():
1847 return get_combined_stats()
1848
1849 update_button = gr.Button("Update Stats")
1850 update_button.click(fn=update_stats, outputs=output_box)
1851
1852 def auto_update():
1853 yield gr.update(value=update_stats())
1854
1855 gr.update(fn=auto_update, inputs=[], outputs=output_box)
1856
1857
1858 @click.command()
1859 @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
1860 @click.option("--host", "-H", default=None, help="Host to run the app on")
1861 @click.option(
1862 "--share",
1863 "-s",
1864 default=False,
1865 is_flag=True,
1866 help="Share the app via Gradio share link",
1867 )
1868 @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
1869 def main(port, host, share, api):
1870 global app
1871 print("Starting app...")
1872 app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api)
1873
1874
1875 if __name__ == "__main__":
1876 main()
1877
1877 lines PYTHON