mrfakename commited on
Commit
d63394d
β€’
1 Parent(s): 648ac03

Sync from GitHub repo

Browse files

This Space is synced from the GitHub repo: https://github.com/SWivid/F5-TTS. Please submit contributions to the Space there

Files changed (3) hide show
  1. README_REPO.md +3 -1
  2. finetune-cli.py +103 -0
  3. finetune_gradio.py +689 -0
README_REPO.md CHANGED
@@ -189,11 +189,13 @@ python scripts/eval_librispeech_test_clean.py
189
  - [lucidrains](https://github.com/lucidrains) initial CFM structure with also [bfs18](https://github.com/bfs18) for discussion
190
  - [SD3](https://arxiv.org/abs/2403.03206) & [Hugging Face diffusers](https://github.com/huggingface/diffusers) DiT and MMDiT code structure
191
  - [torchdiffeq](https://github.com/rtqichen/torchdiffeq) as ODE solver, [Vocos](https://huggingface.co/charactr/vocos-mel-24khz) as vocoder
192
- - [mrfakename](https://x.com/realmrfakename) huggingface space demo ~
193
  - [FunASR](https://github.com/modelscope/FunASR), [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [UniSpeech](https://github.com/microsoft/UniSpeech) for evaluation tools
194
  - [ctc-forced-aligner](https://github.com/MahmoudAshraf97/ctc-forced-aligner) for speech edit test
 
 
195
 
196
  ## Citation
 
197
  ```
198
  @article{chen-etal-2024-f5tts,
199
  title={F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching},
 
189
  - [lucidrains](https://github.com/lucidrains) initial CFM structure with also [bfs18](https://github.com/bfs18) for discussion
190
  - [SD3](https://arxiv.org/abs/2403.03206) & [Hugging Face diffusers](https://github.com/huggingface/diffusers) DiT and MMDiT code structure
191
  - [torchdiffeq](https://github.com/rtqichen/torchdiffeq) as ODE solver, [Vocos](https://huggingface.co/charactr/vocos-mel-24khz) as vocoder
 
192
  - [FunASR](https://github.com/modelscope/FunASR), [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [UniSpeech](https://github.com/microsoft/UniSpeech) for evaluation tools
193
  - [ctc-forced-aligner](https://github.com/MahmoudAshraf97/ctc-forced-aligner) for speech edit test
194
+ - [mrfakename](https://x.com/realmrfakename) huggingface space demo ~
195
+ - [f5-tts-mlx](https://github.com/lucasnewman/f5-tts-mlx/tree/main) Implementation of F5-TTS, with the MLX framework.
196
 
197
  ## Citation
198
+ If our work and codebase is useful for you, please cite as:
199
  ```
200
  @article{chen-etal-2024-f5tts,
201
  title={F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching},
finetune-cli.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from model import CFM, UNetT, DiT, MMDiT, Trainer
3
+ from model.utils import get_tokenizer
4
+ from model.dataset import load_dataset
5
+ from cached_path import cached_path
6
+ import shutil,os
7
+ # -------------------------- Dataset Settings --------------------------- #
8
+ target_sample_rate = 24000
9
+ n_mel_channels = 100
10
+ hop_length = 256
11
+
12
+ tokenizer = "pinyin" # 'pinyin', 'char', or 'custom'
13
+ tokenizer_path = None # if tokenizer = 'custom', define the path to the tokenizer you want to use (should be vocab.txt)
14
+
15
+ # -------------------------- Argument Parsing --------------------------- #
16
+ def parse_args():
17
+ parser = argparse.ArgumentParser(description='Train CFM Model')
18
+
19
+ parser.add_argument('--exp_name', type=str, default="F5TTS_Base", choices=["F5TTS_Base", "E2TTS_Base"],help='Experiment name')
20
+ parser.add_argument('--dataset_name', type=str, default="Emilia_ZH_EN", help='Name of the dataset to use')
21
+ parser.add_argument('--learning_rate', type=float, default=1e-4, help='Learning rate for training')
22
+ parser.add_argument('--batch_size_per_gpu', type=int, default=256, help='Batch size per GPU')
23
+ parser.add_argument('--batch_size_type', type=str, default="frame", choices=["frame", "sample"],help='Batch size type')
24
+ parser.add_argument('--max_samples', type=int, default=16, help='Max sequences per batch')
25
+ parser.add_argument('--grad_accumulation_steps', type=int, default=1,help='Gradient accumulation steps')
26
+ parser.add_argument('--max_grad_norm', type=float, default=1.0, help='Max gradient norm for clipping')
27
+ parser.add_argument('--epochs', type=int, default=10, help='Number of training epochs')
28
+ parser.add_argument('--num_warmup_updates', type=int, default=5, help='Warmup steps')
29
+ parser.add_argument('--save_per_updates', type=int, default=10, help='Save checkpoint every X steps')
30
+ parser.add_argument('--last_per_steps', type=int, default=10, help='Save last checkpoint every X steps')
31
+
32
+ return parser.parse_args()
33
+
34
+ # -------------------------- Training Settings -------------------------- #
35
+
36
+ def main():
37
+ args = parse_args()
38
+
39
+
40
+ # Model parameters based on experiment name
41
+ if args.exp_name == "F5TTS_Base":
42
+ wandb_resume_id = None
43
+ model_cls = DiT
44
+ model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
45
+ ckpt_path = str(cached_path(f"hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.pt"))
46
+ elif args.exp_name == "E2TTS_Base":
47
+ wandb_resume_id = None
48
+ model_cls = UNetT
49
+ model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
50
+ ckpt_path = str(cached_path(f"hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.pt"))
51
+
52
+ path_ckpt = os.path.join("ckpts",args.dataset_name)
53
+ if os.path.isdir(path_ckpt)==False:
54
+ os.makedirs(path_ckpt,exist_ok=True)
55
+ shutil.copy2(ckpt_path,os.path.join(path_ckpt,os.path.basename(ckpt_path)))
56
+ checkpoint_path=os.path.join("ckpts",args.dataset_name)
57
+
58
+ # Use the dataset_name provided in the command line
59
+ tokenizer_path = args.dataset_name if tokenizer != "custom" else tokenizer_path
60
+ vocab_char_map, vocab_size = get_tokenizer(tokenizer_path, tokenizer)
61
+
62
+ mel_spec_kwargs = dict(
63
+ target_sample_rate=target_sample_rate,
64
+ n_mel_channels=n_mel_channels,
65
+ hop_length=hop_length,
66
+ )
67
+
68
+ e2tts = CFM(
69
+ transformer=model_cls(
70
+ **model_cfg,
71
+ text_num_embeds=vocab_size,
72
+ mel_dim=n_mel_channels
73
+ ),
74
+ mel_spec_kwargs=mel_spec_kwargs,
75
+ vocab_char_map=vocab_char_map,
76
+ )
77
+
78
+ trainer = Trainer(
79
+ e2tts,
80
+ args.epochs,
81
+ args.learning_rate,
82
+ num_warmup_updates=args.num_warmup_updates,
83
+ save_per_updates=args.save_per_updates,
84
+ checkpoint_path=checkpoint_path,
85
+ batch_size=args.batch_size_per_gpu,
86
+ batch_size_type=args.batch_size_type,
87
+ max_samples=args.max_samples,
88
+ grad_accumulation_steps=args.grad_accumulation_steps,
89
+ max_grad_norm=args.max_grad_norm,
90
+ wandb_project="CFM-TTS",
91
+ wandb_run_name=args.exp_name,
92
+ wandb_resume_id=wandb_resume_id,
93
+ last_per_steps=args.last_per_steps,
94
+ )
95
+
96
+ train_dataset = load_dataset(args.dataset_name, tokenizer, mel_spec_kwargs=mel_spec_kwargs)
97
+ trainer.train(train_dataset,
98
+ resumable_with_seed=666 # seed for shuffling dataset
99
+ )
100
+
101
+
102
+ if __name__ == '__main__':
103
+ main()
finetune_gradio.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os,sys
2
+
3
+ from transformers import pipeline
4
+ import gradio as gr
5
+ import torch
6
+ import click
7
+ import torchaudio
8
+ from glob import glob
9
+ import librosa
10
+ import numpy as np
11
+ from scipy.io import wavfile
12
+ from tqdm import tqdm
13
+ import shutil
14
+ import time
15
+
16
+ import json
17
+ from datasets import Dataset
18
+ from model.utils import convert_char_to_pinyin
19
+ import signal
20
+ import psutil
21
+ import platform
22
+ import subprocess
23
+ from datasets.arrow_writer import ArrowWriter
24
+ from datasets import load_dataset, load_from_disk
25
+
26
+ import json
27
+
28
+
29
+
30
+ training_process = None
31
+ system = platform.system()
32
+ python_executable = sys.executable or "python"
33
+
34
+ path_data="data"
35
+
36
+ device = (
37
+ "cuda"
38
+ if torch.cuda.is_available()
39
+ else "mps" if torch.backends.mps.is_available() else "cpu"
40
+ )
41
+
42
+ pipe = None
43
+
44
+ # Load metadata
45
+ def get_audio_duration(audio_path):
46
+ """Calculate the duration of an audio file."""
47
+ audio, sample_rate = torchaudio.load(audio_path)
48
+ num_channels = audio.shape[0]
49
+ return audio.shape[1] / (sample_rate * num_channels)
50
+
51
+ def clear_text(text):
52
+ """Clean and prepare text by lowering the case and stripping whitespace."""
53
+ return text.lower().strip()
54
+
55
+ def get_rms(y,frame_length=2048,hop_length=512,pad_mode="constant",): # https://github.com/RVC-Boss/GPT-SoVITS/blob/main/tools/slicer2.py
56
+ padding = (int(frame_length // 2), int(frame_length // 2))
57
+ y = np.pad(y, padding, mode=pad_mode)
58
+
59
+ axis = -1
60
+ # put our new within-frame axis at the end for now
61
+ out_strides = y.strides + tuple([y.strides[axis]])
62
+ # Reduce the shape on the framing axis
63
+ x_shape_trimmed = list(y.shape)
64
+ x_shape_trimmed[axis] -= frame_length - 1
65
+ out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
66
+ xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides)
67
+ if axis < 0:
68
+ target_axis = axis - 1
69
+ else:
70
+ target_axis = axis + 1
71
+ xw = np.moveaxis(xw, -1, target_axis)
72
+ # Downsample along the target axis
73
+ slices = [slice(None)] * xw.ndim
74
+ slices[axis] = slice(0, None, hop_length)
75
+ x = xw[tuple(slices)]
76
+
77
+ # Calculate power
78
+ power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
79
+
80
+ return np.sqrt(power)
81
+
82
+ class Slicer: # https://github.com/RVC-Boss/GPT-SoVITS/blob/main/tools/slicer2.py
83
+ def __init__(
84
+ self,
85
+ sr: int,
86
+ threshold: float = -40.0,
87
+ min_length: int = 2000,
88
+ min_interval: int = 300,
89
+ hop_size: int = 20,
90
+ max_sil_kept: int = 2000,
91
+ ):
92
+ if not min_length >= min_interval >= hop_size:
93
+ raise ValueError(
94
+ "The following condition must be satisfied: min_length >= min_interval >= hop_size"
95
+ )
96
+ if not max_sil_kept >= hop_size:
97
+ raise ValueError(
98
+ "The following condition must be satisfied: max_sil_kept >= hop_size"
99
+ )
100
+ min_interval = sr * min_interval / 1000
101
+ self.threshold = 10 ** (threshold / 20.0)
102
+ self.hop_size = round(sr * hop_size / 1000)
103
+ self.win_size = min(round(min_interval), 4 * self.hop_size)
104
+ self.min_length = round(sr * min_length / 1000 / self.hop_size)
105
+ self.min_interval = round(min_interval / self.hop_size)
106
+ self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
107
+
108
+ def _apply_slice(self, waveform, begin, end):
109
+ if len(waveform.shape) > 1:
110
+ return waveform[
111
+ :, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size)
112
+ ]
113
+ else:
114
+ return waveform[
115
+ begin * self.hop_size : min(waveform.shape[0], end * self.hop_size)
116
+ ]
117
+
118
+ # @timeit
119
+ def slice(self, waveform):
120
+ if len(waveform.shape) > 1:
121
+ samples = waveform.mean(axis=0)
122
+ else:
123
+ samples = waveform
124
+ if samples.shape[0] <= self.min_length:
125
+ return [waveform]
126
+ rms_list = get_rms(
127
+ y=samples, frame_length=self.win_size, hop_length=self.hop_size
128
+ ).squeeze(0)
129
+ sil_tags = []
130
+ silence_start = None
131
+ clip_start = 0
132
+ for i, rms in enumerate(rms_list):
133
+ # Keep looping while frame is silent.
134
+ if rms < self.threshold:
135
+ # Record start of silent frames.
136
+ if silence_start is None:
137
+ silence_start = i
138
+ continue
139
+ # Keep looping while frame is not silent and silence start has not been recorded.
140
+ if silence_start is None:
141
+ continue
142
+ # Clear recorded silence start if interval is not enough or clip is too short
143
+ is_leading_silence = silence_start == 0 and i > self.max_sil_kept
144
+ need_slice_middle = (
145
+ i - silence_start >= self.min_interval
146
+ and i - clip_start >= self.min_length
147
+ )
148
+ if not is_leading_silence and not need_slice_middle:
149
+ silence_start = None
150
+ continue
151
+ # Need slicing. Record the range of silent frames to be removed.
152
+ if i - silence_start <= self.max_sil_kept:
153
+ pos = rms_list[silence_start : i + 1].argmin() + silence_start
154
+ if silence_start == 0:
155
+ sil_tags.append((0, pos))
156
+ else:
157
+ sil_tags.append((pos, pos))
158
+ clip_start = pos
159
+ elif i - silence_start <= self.max_sil_kept * 2:
160
+ pos = rms_list[
161
+ i - self.max_sil_kept : silence_start + self.max_sil_kept + 1
162
+ ].argmin()
163
+ pos += i - self.max_sil_kept
164
+ pos_l = (
165
+ rms_list[
166
+ silence_start : silence_start + self.max_sil_kept + 1
167
+ ].argmin()
168
+ + silence_start
169
+ )
170
+ pos_r = (
171
+ rms_list[i - self.max_sil_kept : i + 1].argmin()
172
+ + i
173
+ - self.max_sil_kept
174
+ )
175
+ if silence_start == 0:
176
+ sil_tags.append((0, pos_r))
177
+ clip_start = pos_r
178
+ else:
179
+ sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
180
+ clip_start = max(pos_r, pos)
181
+ else:
182
+ pos_l = (
183
+ rms_list[
184
+ silence_start : silence_start + self.max_sil_kept + 1
185
+ ].argmin()
186
+ + silence_start
187
+ )
188
+ pos_r = (
189
+ rms_list[i - self.max_sil_kept : i + 1].argmin()
190
+ + i
191
+ - self.max_sil_kept
192
+ )
193
+ if silence_start == 0:
194
+ sil_tags.append((0, pos_r))
195
+ else:
196
+ sil_tags.append((pos_l, pos_r))
197
+ clip_start = pos_r
198
+ silence_start = None
199
+ # Deal with trailing silence.
200
+ total_frames = rms_list.shape[0]
201
+ if (
202
+ silence_start is not None
203
+ and total_frames - silence_start >= self.min_interval
204
+ ):
205
+ silence_end = min(total_frames, silence_start + self.max_sil_kept)
206
+ pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start
207
+ sil_tags.append((pos, total_frames + 1))
208
+ # Apply and return slices.
209
+ ####ιŸ³ι’‘+衷始既间+η»ˆζ­’ζ—Άι—΄
210
+ if len(sil_tags) == 0:
211
+ return [[waveform,0,int(total_frames*self.hop_size)]]
212
+ else:
213
+ chunks = []
214
+ if sil_tags[0][0] > 0:
215
+ chunks.append([self._apply_slice(waveform, 0, sil_tags[0][0]),0,int(sil_tags[0][0]*self.hop_size)])
216
+ for i in range(len(sil_tags) - 1):
217
+ chunks.append(
218
+ [self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]),int(sil_tags[i][1]*self.hop_size),int(sil_tags[i + 1][0]*self.hop_size)]
219
+ )
220
+ if sil_tags[-1][1] < total_frames:
221
+ chunks.append(
222
+ [self._apply_slice(waveform, sil_tags[-1][1], total_frames),int(sil_tags[-1][1]*self.hop_size),int(total_frames*self.hop_size)]
223
+ )
224
+ return chunks
225
+
226
+ #terminal
227
+ def terminate_process_tree(pid, including_parent=True):
228
+ try:
229
+ parent = psutil.Process(pid)
230
+ except psutil.NoSuchProcess:
231
+ # Process already terminated
232
+ return
233
+
234
+ children = parent.children(recursive=True)
235
+ for child in children:
236
+ try:
237
+ os.kill(child.pid, signal.SIGTERM) # or signal.SIGKILL
238
+ except OSError:
239
+ pass
240
+ if including_parent:
241
+ try:
242
+ os.kill(parent.pid, signal.SIGTERM) # or signal.SIGKILL
243
+ except OSError:
244
+ pass
245
+
246
+ def terminate_process(pid):
247
+ if system == "Windows":
248
+ cmd = f"taskkill /t /f /pid {pid}"
249
+ os.system(cmd)
250
+ else:
251
+ terminate_process_tree(pid)
252
+
253
+ def start_training(dataset_name="",
254
+ exp_name="F5TTS_Base",
255
+ learning_rate=1e-4,
256
+ batch_size_per_gpu=400,
257
+ batch_size_type="frame",
258
+ max_samples=64,
259
+ grad_accumulation_steps=1,
260
+ max_grad_norm=1.0,
261
+ epochs=11,
262
+ num_warmup_updates=200,
263
+ save_per_updates=400,
264
+ last_per_steps=800,
265
+ finetune=True,
266
+ ):
267
+
268
+ global training_process
269
+
270
+ # Check if a training process is already running
271
+ if training_process is not None:
272
+ return "Train run already!",gr.update(interactive=False),gr.update(interactive=True)
273
+
274
+ yield "start train",gr.update(interactive=False),gr.update(interactive=False)
275
+
276
+ # Command to run the training script with the specified arguments
277
+ cmd = f"{python_executable} finetune-cli.py --exp_name {exp_name} " \
278
+ f"--learning_rate {learning_rate} " \
279
+ f"--batch_size_per_gpu {batch_size_per_gpu} " \
280
+ f"--batch_size_type {batch_size_type} " \
281
+ f"--max_samples {max_samples} " \
282
+ f"--grad_accumulation_steps {grad_accumulation_steps} " \
283
+ f"--max_grad_norm {max_grad_norm} " \
284
+ f"--epochs {epochs} " \
285
+ f"--num_warmup_updates {num_warmup_updates} " \
286
+ f"--save_per_updates {save_per_updates} " \
287
+ f"--last_per_steps {last_per_steps} " \
288
+ f"--dataset_name {dataset_name}"
289
+ if finetune:cmd += f" --finetune {finetune}"
290
+ print(cmd)
291
+ try:
292
+ # Start the training process
293
+ training_process = subprocess.Popen(cmd, shell=True)
294
+
295
+ time.sleep(5)
296
+ yield "check terminal for wandb",gr.update(interactive=False),gr.update(interactive=True)
297
+
298
+ # Wait for the training process to finish
299
+ training_process.wait()
300
+ time.sleep(1)
301
+
302
+ if training_process is None:
303
+ text_info = 'train stop'
304
+ else:
305
+ text_info = "train complete !"
306
+
307
+ except Exception as e: # Catch all exceptions
308
+ # Ensure that we reset the training process variable in case of an error
309
+ text_info=f"An error occurred: {str(e)}"
310
+
311
+ training_process=None
312
+
313
+ yield text_info,gr.update(interactive=True),gr.update(interactive=False)
314
+
315
+ def stop_training():
316
+ global training_process
317
+ if training_process is None:return f"Train not run !",gr.update(interactive=True),gr.update(interactive=False)
318
+ terminate_process_tree(training_process.pid)
319
+ training_process = None
320
+ return 'train stop',gr.update(interactive=True),gr.update(interactive=False)
321
+
322
+ def create_data_project(name):
323
+ name+="_pinyin"
324
+ os.makedirs(os.path.join(path_data,name),exist_ok=True)
325
+ os.makedirs(os.path.join(path_data,name,"dataset"),exist_ok=True)
326
+
327
+ def transcribe(file_audio,language="english"):
328
+ global pipe
329
+
330
+ if pipe is None:
331
+ pipe = pipeline("automatic-speech-recognition",model="openai/whisper-large-v3-turbo", torch_dtype=torch.float16,device=device)
332
+
333
+ text_transcribe = pipe(
334
+ file_audio,
335
+ chunk_length_s=30,
336
+ batch_size=128,
337
+ generate_kwargs={"task": "transcribe","language": language},
338
+ return_timestamps=False,
339
+ )["text"].strip()
340
+ return text_transcribe
341
+
342
+ def transcribe_all(name_project,audio_file,language,user=False,progress=gr.Progress()):
343
+ name_project+="_pinyin"
344
+ path_project= os.path.join(path_data,name_project)
345
+ path_dataset = os.path.join(path_project,"dataset")
346
+ path_project_wavs = os.path.join(path_project,"wavs")
347
+ file_metadata = os.path.join(path_project,"metadata.csv")
348
+
349
+ if os.path.isdir(path_project_wavs):
350
+ shutil.rmtree(path_project_wavs)
351
+
352
+ if os.path.isfile(file_metadata):
353
+ os.remove(file_metadata)
354
+
355
+ os.makedirs(path_project_wavs,exist_ok=True)
356
+
357
+ if user:
358
+ file_audios = [file for format in ('*.wav', '*.ogg', '*.opus', '*.mp3', '*.flac') for file in glob(os.path.join(path_dataset, format))]
359
+ else:
360
+ file_audios = [audio_file]
361
+
362
+ print([file_audios])
363
+
364
+ alpha = 0.5
365
+ _max = 1.0
366
+ slicer = Slicer(24000)
367
+
368
+ num = 0
369
+ data=""
370
+ for file_audio in progress.tqdm(file_audios, desc="transcribe files",total=len((file_audios))):
371
+
372
+ audio, _ = librosa.load(file_audio, sr=24000, mono=True)
373
+
374
+ list_slicer=slicer.slice(audio)
375
+ for chunk, start, end in progress.tqdm(list_slicer,total=len(list_slicer), desc="slicer files"):
376
+
377
+ name_segment = os.path.join(f"segment_{num}")
378
+ file_segment = os.path.join(path_project_wavs, f"{name_segment}.wav")
379
+
380
+ tmp_max = np.abs(chunk).max()
381
+ if(tmp_max>1):chunk/=tmp_max
382
+ chunk = (chunk / tmp_max * (_max * alpha)) + (1 - alpha) * chunk
383
+ wavfile.write(file_segment,24000, (chunk * 32767).astype(np.int16))
384
+
385
+ text=transcribe(file_segment,language)
386
+ text = text.lower().strip().replace('"',"")
387
+
388
+ data+= f"{name_segment}|{text}\n"
389
+
390
+ num+=1
391
+
392
+ with open(file_metadata,"w",encoding="utf-8") as f:
393
+ f.write(data)
394
+
395
+ return f"transcribe complete samples : {num} in path {path_project_wavs}"
396
+
397
+ def format_seconds_to_hms(seconds):
398
+ hours = int(seconds / 3600)
399
+ minutes = int((seconds % 3600) / 60)
400
+ seconds = seconds % 60
401
+ return "{:02d}:{:02d}:{:02d}".format(hours, minutes, int(seconds))
402
+
403
+ def create_metadata(name_project,progress=gr.Progress()):
404
+ name_project+="_pinyin"
405
+ path_project= os.path.join(path_data,name_project)
406
+ path_project_wavs = os.path.join(path_project,"wavs")
407
+ file_metadata = os.path.join(path_project,"metadata.csv")
408
+ file_raw = os.path.join(path_project,"raw.arrow")
409
+ file_duration = os.path.join(path_project,"duration.json")
410
+ file_vocab = os.path.join(path_project,"vocab.txt")
411
+
412
+ with open(file_metadata,"r",encoding="utf-8") as f:
413
+ data=f.read()
414
+
415
+ audio_path_list=[]
416
+ text_list=[]
417
+ duration_list=[]
418
+
419
+ count=data.split("\n")
420
+ lenght=0
421
+ result=[]
422
+ for line in progress.tqdm(data.split("\n"),total=count):
423
+ sp_line=line.split("|")
424
+ if len(sp_line)!=2:continue
425
+ name_audio,text = sp_line[:2]
426
+ file_audio = os.path.join(path_project_wavs, name_audio + ".wav")
427
+ duraction = get_audio_duration(file_audio)
428
+ if duraction<2 and duraction>15:continue
429
+ if len(text)<4:continue
430
+
431
+ text = clear_text(text)
432
+ text = convert_char_to_pinyin([text], polyphone = True)[0]
433
+
434
+ audio_path_list.append(file_audio)
435
+ duration_list.append(duraction)
436
+ text_list.append(text)
437
+
438
+ result.append({"audio_path": file_audio, "text": text, "duration": duraction})
439
+
440
+ lenght+=duraction
441
+
442
+ min_second = round(min(duration_list),2)
443
+ max_second = round(max(duration_list),2)
444
+
445
+ with ArrowWriter(path=file_raw, writer_batch_size=1) as writer:
446
+ for line in progress.tqdm(result,total=len(result), desc=f"prepare data"):
447
+ writer.write(line)
448
+
449
+ with open(file_duration, 'w', encoding='utf-8') as f:
450
+ json.dump({"duration": duration_list}, f, ensure_ascii=False)
451
+
452
+ file_vocab_finetune = "data/Emilia_ZH_EN_pinyin/vocab.txt"
453
+ shutil.copy2(file_vocab_finetune, file_vocab)
454
+
455
+ return 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}\n"
456
+
457
+ def check_user(value):
458
+ return gr.update(visible=not value),gr.update(visible=value)
459
+
460
+ def calculate_train(name_project,batch_size_type,max_samples,learning_rate,num_warmup_updates,save_per_updates,last_per_steps,finetune):
461
+ name_project+="_pinyin"
462
+ path_project= os.path.join(path_data,name_project)
463
+ file_duraction = os.path.join(path_project,"duration.json")
464
+
465
+ with open(file_duraction, 'r') as file:
466
+ data = json.load(file)
467
+
468
+ duration_list = data['duration']
469
+ samples = len(duration_list)
470
+
471
+ gpu_properties = torch.cuda.get_device_properties(0)
472
+ total_memory = gpu_properties.total_memory / (1024 ** 3)
473
+
474
+ if batch_size_type=="frame":
475
+ batch = int(total_memory * 0.5)
476
+ batch = (lambda num: num + 1 if num % 2 != 0 else num)(batch)
477
+ batch_size_per_gpu = int(36800 / batch )
478
+ else:
479
+ batch_size_per_gpu = int(total_memory / 8)
480
+ batch_size_per_gpu = (lambda num: num + 1 if num % 2 != 0 else num)(batch_size_per_gpu)
481
+ batch = batch_size_per_gpu
482
+
483
+ if batch_size_per_gpu<=0:batch_size_per_gpu=1
484
+
485
+ if samples<64:
486
+ max_samples = int(samples * 0.25)
487
+
488
+ num_warmup_updates = int(samples * 0.10)
489
+ save_per_updates = int(samples * 0.25)
490
+ last_per_steps =int(save_per_updates * 5)
491
+
492
+ max_samples = (lambda num: num + 1 if num % 2 != 0 else num)(max_samples)
493
+ num_warmup_updates = (lambda num: num + 1 if num % 2 != 0 else num)(num_warmup_updates)
494
+ save_per_updates = (lambda num: num + 1 if num % 2 != 0 else num)(save_per_updates)
495
+ last_per_steps = (lambda num: num + 1 if num % 2 != 0 else num)(last_per_steps)
496
+
497
+ if finetune:learning_rate=1e-4
498
+ else:learning_rate=7.5e-5
499
+
500
+ return batch_size_per_gpu,max_samples,num_warmup_updates,save_per_updates,last_per_steps,samples,learning_rate
501
+
502
+ def extract_and_save_ema_model(checkpoint_path: str, new_checkpoint_path: str) -> None:
503
+ try:
504
+ checkpoint = torch.load(checkpoint_path)
505
+ print("Original Checkpoint Keys:", checkpoint.keys())
506
+
507
+ ema_model_state_dict = checkpoint.get('ema_model_state_dict', None)
508
+
509
+ if ema_model_state_dict is not None:
510
+ new_checkpoint = {'ema_model_state_dict': ema_model_state_dict}
511
+ torch.save(new_checkpoint, new_checkpoint_path)
512
+ print(f"New checkpoint saved at: {new_checkpoint_path}")
513
+ else:
514
+ print("No 'ema_model_state_dict' found in the checkpoint.")
515
+
516
+ except Exception as e:
517
+ print(f"An error occurred: {e}")
518
+
519
+
520
+ def vocab_check(project_name):
521
+ name_project = project_name + "_pinyin"
522
+ path_project = os.path.join(path_data, name_project)
523
+
524
+ file_metadata = os.path.join(path_project, "metadata.csv")
525
+
526
+ file_vocab="data/Emilia_ZH_EN_pinyin/vocab.txt"
527
+
528
+ with open(file_vocab,"r",encoding="utf-8") as f:
529
+ data=f.read()
530
+
531
+ vocab = data.split("\n")
532
+
533
+ with open(file_metadata,"r",encoding="utf-8") as f:
534
+ data=f.read()
535
+
536
+ miss_symbols=[]
537
+ miss_symbols_keep={}
538
+ for item in data.split("\n"):
539
+ sp=item.split("|")
540
+ if len(sp)!=2:continue
541
+ text=sp[1].lower().strip()
542
+
543
+ for t in text:
544
+ if (t in vocab)==False and (t in miss_symbols_keep)==False:
545
+ miss_symbols.append(t)
546
+ miss_symbols_keep[t]=t
547
+
548
+
549
+ if miss_symbols==[]:info ="You can train using your language !"
550
+ else:info = f"The following symbols are missing in your language : {len(miss_symbols)}\n\n" + "\n".join(miss_symbols)
551
+ return info
552
+
553
+
554
+
555
+ with gr.Blocks() as app:
556
+
557
+ with gr.Row():
558
+ project_name=gr.Textbox(label="project name",value="my_speak")
559
+ bt_create=gr.Button("create new project")
560
+
561
+ bt_create.click(fn=create_data_project,inputs=[project_name])
562
+
563
+ with gr.Tabs():
564
+
565
+
566
+ with gr.TabItem("transcribe Data"):
567
+
568
+
569
+ ch_manual = gr.Checkbox(label="user",value=False)
570
+
571
+ mark_info_transcribe=gr.Markdown(
572
+ """```plaintext
573
+ Place your 'wavs' folder and 'metadata.csv' file in the {your_project_name}' directory.
574
+
575
+ my_speak/
576
+ β”‚
577
+ └── dataset/
578
+ β”œβ”€β”€ audio1.wav
579
+ └── audio2.wav
580
+ ...
581
+ ```""",visible=False)
582
+
583
+ audio_speaker = gr.Audio(label="voice",type="filepath")
584
+ txt_lang = gr.Text(label="Language",value="english")
585
+ bt_transcribe=bt_create=gr.Button("transcribe")
586
+ txt_info_transcribe=gr.Text(label="info",value="")
587
+ bt_transcribe.click(fn=transcribe_all,inputs=[project_name,audio_speaker,txt_lang,ch_manual],outputs=[txt_info_transcribe])
588
+ ch_manual.change(fn=check_user,inputs=[ch_manual],outputs=[audio_speaker,mark_info_transcribe])
589
+
590
+ with gr.TabItem("prepare Data"):
591
+ gr.Markdown(
592
+ """```plaintext
593
+ place all your wavs folder and your metadata.csv file in {your name project}
594
+ my_speak/
595
+ β”‚
596
+ β”œβ”€β”€ wavs/
597
+ β”‚ β”œβ”€β”€ audio1.wav
598
+ β”‚ └── audio2.wav
599
+ | ...
600
+ β”‚
601
+ └── metadata.csv
602
+
603
+ file format metadata.csv
604
+
605
+ audio1|text1
606
+ audio2|text1
607
+ ...
608
+
609
+ ```""")
610
+
611
+ bt_prepare=bt_create=gr.Button("prepare")
612
+ txt_info_prepare=gr.Text(label="info",value="")
613
+ bt_prepare.click(fn=create_metadata,inputs=[project_name],outputs=[txt_info_prepare])
614
+
615
+ with gr.TabItem("train Data"):
616
+
617
+ with gr.Row():
618
+ bt_calculate=bt_create=gr.Button("Auto Settings")
619
+ ch_finetune=bt_create=gr.Checkbox(label="finetune",value=True)
620
+ lb_samples = gr.Label(label="samples")
621
+ batch_size_type = gr.Radio(label="Batch Size Type", choices=["frame", "sample"], value="frame")
622
+
623
+ with gr.Row():
624
+ exp_name = gr.Radio(label="Model", choices=["F5TTS_Base", "E2TTS_Base"], value="F5TTS_Base")
625
+ learning_rate = gr.Number(label="Learning Rate", value=1e-4, step=1e-4)
626
+
627
+ with gr.Row():
628
+ batch_size_per_gpu = gr.Number(label="Batch Size per GPU", value=1000)
629
+ max_samples = gr.Number(label="Max Samples", value=16)
630
+
631
+ with gr.Row():
632
+ grad_accumulation_steps = gr.Number(label="Gradient Accumulation Steps", value=1)
633
+ max_grad_norm = gr.Number(label="Max Gradient Norm", value=1.0)
634
+
635
+ with gr.Row():
636
+ epochs = gr.Number(label="Epochs", value=10)
637
+ num_warmup_updates = gr.Number(label="Warmup Updates", value=5)
638
+
639
+ with gr.Row():
640
+ save_per_updates = gr.Number(label="Save per Updates", value=10)
641
+ last_per_steps = gr.Number(label="Last per Steps", value=50)
642
+
643
+ with gr.Row():
644
+ start_button = gr.Button("Start Training")
645
+ stop_button = gr.Button("Stop Training",interactive=False)
646
+
647
+ txt_info_train=gr.Text(label="info",value="")
648
+ start_button.click(fn=start_training,inputs=[project_name,exp_name,learning_rate,batch_size_per_gpu,batch_size_type,max_samples,grad_accumulation_steps,max_grad_norm,epochs,num_warmup_updates,save_per_updates,last_per_steps,ch_finetune],outputs=[txt_info_train,start_button,stop_button])
649
+ stop_button.click(fn=stop_training,outputs=[txt_info_train,start_button,stop_button])
650
+ bt_calculate.click(fn=calculate_train,inputs=[project_name,batch_size_type,max_samples,learning_rate,num_warmup_updates,save_per_updates,last_per_steps,ch_finetune],outputs=[batch_size_per_gpu,max_samples,num_warmup_updates,save_per_updates,last_per_steps,lb_samples,learning_rate])
651
+
652
+ with gr.TabItem("reduse checkpoint"):
653
+ txt_path_checkpoint = gr.Text(label="path checkpoint :")
654
+ txt_path_checkpoint_small = gr.Text(label="path output :")
655
+ reduse_button = gr.Button("reduse")
656
+ reduse_button.click(fn=extract_and_save_ema_model,inputs=[txt_path_checkpoint,txt_path_checkpoint_small])
657
+
658
+ with gr.TabItem("vocab check experiment"):
659
+ check_button = gr.Button("check vocab")
660
+ txt_info_check=gr.Text(label="info",value="")
661
+ check_button.click(fn=vocab_check,inputs=[project_name],outputs=[txt_info_check])
662
+
663
+
664
+ @click.command()
665
+ @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
666
+ @click.option("--host", "-H", default=None, help="Host to run the app on")
667
+ @click.option(
668
+ "--share",
669
+ "-s",
670
+ default=False,
671
+ is_flag=True,
672
+ help="Share the app via Gradio share link",
673
+ )
674
+ @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
675
+ def main(port, host, share, api):
676
+ global app
677
+ print(f"Starting app...")
678
+ app.queue(api_open=api).launch(
679
+ server_name=host, server_port=port, share=share, show_api=api
680
+ )
681
+
682
+ if __name__ == "__main__":
683
+ name="my_speak"
684
+
685
+ #create_data_project(name)
686
+ #transcribe_all(name)
687
+ #create_metadata(name)
688
+
689
+ main()