BharatYadav00 commited on
Commit
3fa2552
1 Parent(s): 749b4e8

Upload 20 files

Browse files
Files changed (20) hide show
  1. .DS_Store +0 -0
  2. .gitattributes +35 -35
  3. .gitmodules +3 -0
  4. .pre-commit-config.yaml +14 -0
  5. Dockerfile +24 -0
  6. LICENSE +21 -0
  7. README.md +13 -12
  8. api.py +132 -0
  9. app.py +730 -0
  10. finetune-cli.py +127 -0
  11. finetune_gradio.py +944 -0
  12. gradio_app.py +824 -0
  13. inference-cli.py +170 -0
  14. inference-cli.toml +10 -0
  15. pyproject.toml +61 -0
  16. requirements.txt +25 -0
  17. requirements_eval.txt +5 -0
  18. ruff.toml +10 -0
  19. speech_edit.py +189 -0
  20. train.py +92 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "src/third_party/BigVGAN"]
2
+ path = src/third_party/BigVGAN
3
+ url = https://github.com/NVIDIA/BigVGAN.git
.pre-commit-config.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ # Ruff version.
4
+ rev: v0.7.0
5
+ hooks:
6
+ # Run the linter.
7
+ - id: ruff
8
+ args: [--fix]
9
+ # Run the formatter.
10
+ - id: ruff-format
11
+ - repo: https://github.com/pre-commit/pre-commit-hooks
12
+ rev: v2.3.0
13
+ hooks:
14
+ - id: check-yaml
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM pytorch/pytorch:2.4.0-cuda12.4-cudnn9-devel
2
+
3
+ USER root
4
+
5
+ ARG DEBIAN_FRONTEND=noninteractive
6
+
7
+ LABEL github_repo="https://github.com/SWivid/F5-TTS"
8
+
9
+ RUN set -x \
10
+ && apt-get update \
11
+ && apt-get -y install wget curl man git less openssl libssl-dev unzip unar build-essential aria2 tmux vim \
12
+ && apt-get install -y openssh-server sox libsox-fmt-all libsox-fmt-mp3 libsndfile1-dev ffmpeg \
13
+ && rm -rf /var/lib/apt/lists/* \
14
+ && apt-get clean
15
+
16
+ WORKDIR /workspace
17
+
18
+ RUN git clone https://github.com/SWivid/F5-TTS.git \
19
+ && cd F5-TTS \
20
+ && pip install -e .[eval]
21
+
22
+ ENV SHELL=/bin/bash
23
+
24
+ WORKDIR /workspace/F5-TTS
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Yushen CHEN
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Voice
3
- emoji: 🐠
4
- colorFrom: indigo
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 5.5.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
+ ---
2
+ title: F5-TTS
3
+ emoji: 🗣️
4
+ colorFrom: green
5
+ colorTo: green
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: true
9
+ short_description: 'F5-TTS & E2-TTS: Zero-Shot Voice Cloning (Unofficial Demo)'
10
+ sdk_version: 4.44.1
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
api.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import soundfile as sf
2
+ import torch
3
+ import tqdm
4
+ from cached_path import cached_path
5
+
6
+ from model import DiT, UNetT
7
+ from model.utils import save_spectrogram
8
+
9
+ from model.utils_infer import load_vocoder, load_model, infer_process, remove_silence_for_generated_wav
10
+ from model.utils import seed_everything
11
+ import random
12
+ import sys
13
+
14
+
15
+ class F5TTS:
16
+ def __init__(
17
+ self,
18
+ model_type="F5-TTS",
19
+ ckpt_file="",
20
+ vocab_file="",
21
+ ode_method="euler",
22
+ use_ema=True,
23
+ local_path=None,
24
+ device=None,
25
+ ):
26
+ # Initialize parameters
27
+ self.final_wave = None
28
+ self.target_sample_rate = 24000
29
+ self.n_mel_channels = 100
30
+ self.hop_length = 256
31
+ self.target_rms = 0.1
32
+ self.seed = -1
33
+
34
+ # Set device
35
+ self.device = device or (
36
+ "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
37
+ )
38
+
39
+ # Load models
40
+ self.load_vocoder_model(local_path)
41
+ self.load_ema_model(model_type, ckpt_file, vocab_file, ode_method, use_ema)
42
+
43
+ def load_vocoder_model(self, local_path):
44
+ self.vocos = load_vocoder(local_path is not None, local_path, self.device)
45
+
46
+ def load_ema_model(self, model_type, ckpt_file, vocab_file, ode_method, use_ema):
47
+ if model_type == "F5-TTS":
48
+ if not ckpt_file:
49
+ ckpt_file = str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"))
50
+ model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
51
+ model_cls = DiT
52
+ elif model_type == "E2-TTS":
53
+ if not ckpt_file:
54
+ ckpt_file = str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))
55
+ model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
56
+ model_cls = UNetT
57
+ else:
58
+ raise ValueError(f"Unknown model type: {model_type}")
59
+
60
+ self.ema_model = load_model(model_cls, model_cfg, ckpt_file, vocab_file, ode_method, use_ema, self.device)
61
+
62
+ def export_wav(self, wav, file_wave, remove_silence=False):
63
+ sf.write(file_wave, wav, self.target_sample_rate)
64
+
65
+ if remove_silence:
66
+ remove_silence_for_generated_wav(file_wave)
67
+
68
+ def export_spectrogram(self, spect, file_spect):
69
+ save_spectrogram(spect, file_spect)
70
+
71
+ def infer(
72
+ self,
73
+ ref_file,
74
+ ref_text,
75
+ gen_text,
76
+ show_info=print,
77
+ progress=tqdm,
78
+ target_rms=0.1,
79
+ cross_fade_duration=0.15,
80
+ sway_sampling_coef=-1,
81
+ cfg_strength=2,
82
+ nfe_step=32,
83
+ speed=1.0,
84
+ fix_duration=None,
85
+ remove_silence=False,
86
+ file_wave=None,
87
+ file_spect=None,
88
+ seed=-1,
89
+ ):
90
+ if seed == -1:
91
+ seed = random.randint(0, sys.maxsize)
92
+ seed_everything(seed)
93
+ self.seed = seed
94
+ wav, sr, spect = infer_process(
95
+ ref_file,
96
+ ref_text,
97
+ gen_text,
98
+ self.ema_model,
99
+ show_info=show_info,
100
+ progress=progress,
101
+ target_rms=target_rms,
102
+ cross_fade_duration=cross_fade_duration,
103
+ nfe_step=nfe_step,
104
+ cfg_strength=cfg_strength,
105
+ sway_sampling_coef=sway_sampling_coef,
106
+ speed=speed,
107
+ fix_duration=fix_duration,
108
+ device=self.device,
109
+ )
110
+
111
+ if file_wave is not None:
112
+ self.export_wav(wav, file_wave, remove_silence)
113
+
114
+ if file_spect is not None:
115
+ self.export_spectrogram(spect, file_spect)
116
+
117
+ return wav, sr, spect
118
+
119
+
120
+ if __name__ == "__main__":
121
+ f5tts = F5TTS()
122
+
123
+ wav, sr, spect = f5tts.infer(
124
+ ref_file="tests/ref_audio/test_en_1_ref_short.wav",
125
+ ref_text="some call me nature, others call me mother nature.",
126
+ gen_text="""I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences.""",
127
+ file_wave="tests/out.wav",
128
+ file_spect="tests/out.png",
129
+ seed=-1, # random seed = -1
130
+ )
131
+
132
+ print("seed :", f5tts.seed)
app.py ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: E402
2
+ # Above allows ruff to ignore E402: module level import not at top of file
3
+
4
+ import re
5
+ import tempfile
6
+
7
+ import click
8
+ import gradio as gr
9
+ import numpy as np
10
+ import soundfile as sf
11
+ import torchaudio
12
+ from cached_path import cached_path
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer
14
+
15
+ try:
16
+ import spaces
17
+
18
+ USING_SPACES = True
19
+ except ImportError:
20
+ USING_SPACES = False
21
+
22
+
23
+ def gpu_decorator(func):
24
+ if USING_SPACES:
25
+ return spaces.GPU(func)
26
+ else:
27
+ return func
28
+
29
+
30
+ from f5_tts.model import DiT, UNetT
31
+ from f5_tts.infer.utils_infer import (
32
+ load_vocoder,
33
+ load_model,
34
+ preprocess_ref_audio_text,
35
+ infer_process,
36
+ remove_silence_for_generated_wav,
37
+ save_spectrogram,
38
+ )
39
+
40
+ vocoder = load_vocoder()
41
+
42
+
43
+ # load models
44
+ F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
45
+ F5TTS_ema_model = load_model(
46
+ DiT, F5TTS_model_cfg, str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors"))
47
+ )
48
+
49
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
50
+ E2TTS_ema_model = load_model(
51
+ UNetT, E2TTS_model_cfg, str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))
52
+ )
53
+
54
+ chat_model_state = None
55
+ chat_tokenizer_state = None
56
+
57
+
58
+ @gpu_decorator
59
+ def generate_response(messages, model, tokenizer):
60
+ """Generate response using Qwen"""
61
+ text = tokenizer.apply_chat_template(
62
+ messages,
63
+ tokenize=False,
64
+ add_generation_prompt=True,
65
+ )
66
+
67
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
68
+ generated_ids = model.generate(
69
+ **model_inputs,
70
+ max_new_tokens=512,
71
+ temperature=0.7,
72
+ top_p=0.95,
73
+ )
74
+
75
+ generated_ids = [
76
+ output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
77
+ ]
78
+ return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
79
+
80
+
81
+ @gpu_decorator
82
+ def infer(
83
+ ref_audio_orig, ref_text, gen_text, model, remove_silence, cross_fade_duration=0.15, speed=1, show_info=gr.Info
84
+ ):
85
+ ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
86
+
87
+ if model == "F5-TTS":
88
+ ema_model = F5TTS_ema_model
89
+ elif model == "E2-TTS":
90
+ ema_model = E2TTS_ema_model
91
+
92
+ final_wave, final_sample_rate, combined_spectrogram = infer_process(
93
+ ref_audio,
94
+ ref_text,
95
+ gen_text,
96
+ ema_model,
97
+ vocoder,
98
+ cross_fade_duration=cross_fade_duration,
99
+ speed=speed,
100
+ show_info=show_info,
101
+ progress=gr.Progress(),
102
+ )
103
+
104
+ # Remove silence
105
+ if remove_silence:
106
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
107
+ sf.write(f.name, final_wave, final_sample_rate)
108
+ remove_silence_for_generated_wav(f.name)
109
+ final_wave, _ = torchaudio.load(f.name)
110
+ final_wave = final_wave.squeeze().cpu().numpy()
111
+
112
+ # Save the spectrogram
113
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
114
+ spectrogram_path = tmp_spectrogram.name
115
+ save_spectrogram(combined_spectrogram, spectrogram_path)
116
+
117
+ return (final_sample_rate, final_wave), spectrogram_path
118
+
119
+
120
+ with gr.Blocks() as app_credits:
121
+ gr.Markdown("""
122
+ # Credits
123
+
124
+ * [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
125
+ * [RootingInLoad](https://github.com/RootingInLoad) for initial chunk generation and podcast app exploration
126
+ * [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation & voice chat
127
+ """)
128
+ with gr.Blocks() as app_tts:
129
+ gr.Markdown("# Batched TTS")
130
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
131
+ gen_text_input = gr.Textbox(label="Text to Generate", lines=10)
132
+ model_choice = gr.Radio(choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS")
133
+ generate_btn = gr.Button("Synthesize", variant="primary")
134
+ with gr.Accordion("Advanced Settings", open=False):
135
+ ref_text_input = gr.Textbox(
136
+ label="Reference Text",
137
+ info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.",
138
+ lines=2,
139
+ )
140
+ remove_silence = gr.Checkbox(
141
+ label="Remove Silences",
142
+ info="The model tends to produce silences, especially on longer audio. We can manually remove silences if needed. Note that this is an experimental feature and may produce strange results. This will also increase generation time.",
143
+ value=False,
144
+ )
145
+ speed_slider = gr.Slider(
146
+ label="Speed",
147
+ minimum=0.3,
148
+ maximum=2.0,
149
+ value=1.0,
150
+ step=0.1,
151
+ info="Adjust the speed of the audio.",
152
+ )
153
+ cross_fade_duration_slider = gr.Slider(
154
+ label="Cross-Fade Duration (s)",
155
+ minimum=0.0,
156
+ maximum=1.0,
157
+ value=0.15,
158
+ step=0.01,
159
+ info="Set the duration of the cross-fade between audio clips.",
160
+ )
161
+
162
+ audio_output = gr.Audio(label="Synthesized Audio")
163
+ spectrogram_output = gr.Image(label="Spectrogram")
164
+
165
+ generate_btn.click(
166
+ infer,
167
+ inputs=[
168
+ ref_audio_input,
169
+ ref_text_input,
170
+ gen_text_input,
171
+ model_choice,
172
+ remove_silence,
173
+ cross_fade_duration_slider,
174
+ speed_slider,
175
+ ],
176
+ outputs=[audio_output, spectrogram_output],
177
+ )
178
+
179
+
180
+ def parse_speechtypes_text(gen_text):
181
+ # Pattern to find {speechtype}
182
+ pattern = r"\{(.*?)\}"
183
+
184
+ # Split the text by the pattern
185
+ tokens = re.split(pattern, gen_text)
186
+
187
+ segments = []
188
+
189
+ current_style = "Regular"
190
+
191
+ for i in range(len(tokens)):
192
+ if i % 2 == 0:
193
+ # This is text
194
+ text = tokens[i].strip()
195
+ if text:
196
+ segments.append({"style": current_style, "text": text})
197
+ else:
198
+ # This is style
199
+ style = tokens[i].strip()
200
+ current_style = style
201
+
202
+ return segments
203
+
204
+
205
+ with gr.Blocks() as app_multistyle:
206
+ # New section for multistyle generation
207
+ gr.Markdown(
208
+ """
209
+ # Multiple Speech-Type Generation
210
+
211
+ This section allows you to generate multiple speech types or multiple people's voices. Enter your text in the format shown below, and the system will generate speech using the appropriate type. If unspecified, the model will use the regular speech type. The current speech type will be used until the next speech type is specified.
212
+ """
213
+ )
214
+
215
+ with gr.Row():
216
+ gr.Markdown(
217
+ """
218
+ **Example Input:**
219
+ {Regular} Hello, I'd like to order a sandwich please.
220
+ {Surprised} What do you mean you're out of bread?
221
+ {Sad} I really wanted a sandwich though...
222
+ {Angry} You know what, darn you and your little shop!
223
+ {Whisper} I'll just go back home and cry now.
224
+ {Shouting} Why me?!
225
+ """
226
+ )
227
+
228
+ gr.Markdown(
229
+ """
230
+ **Example Input 2:**
231
+ {Speaker1_Happy} Hello, I'd like to order a sandwich please.
232
+ {Speaker2_Regular} Sorry, we're out of bread.
233
+ {Speaker1_Sad} I really wanted a sandwich though...
234
+ {Speaker2_Whisper} I'll give you the last one I was hiding.
235
+ """
236
+ )
237
+
238
+ gr.Markdown(
239
+ "Upload different audio clips for each speech type. The first speech type is mandatory. You can add additional speech types by clicking the 'Add Speech Type' button."
240
+ )
241
+
242
+ # Regular speech type (mandatory)
243
+ with gr.Row():
244
+ with gr.Column():
245
+ regular_name = gr.Textbox(value="Regular", label="Speech Type Name")
246
+ regular_insert = gr.Button("Insert", variant="secondary")
247
+ regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath")
248
+ regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=2)
249
+
250
+ # Additional speech types (up to 99 more)
251
+ max_speech_types = 100
252
+ speech_type_rows = []
253
+ speech_type_names = [regular_name]
254
+ speech_type_audios = []
255
+ speech_type_ref_texts = []
256
+ speech_type_delete_btns = []
257
+ speech_type_insert_btns = []
258
+ speech_type_insert_btns.append(regular_insert)
259
+
260
+ for i in range(max_speech_types - 1):
261
+ with gr.Row(visible=False) as row:
262
+ with gr.Column():
263
+ name_input = gr.Textbox(label="Speech Type Name")
264
+ delete_btn = gr.Button("Delete", variant="secondary")
265
+ insert_btn = gr.Button("Insert", variant="secondary")
266
+ audio_input = gr.Audio(label="Reference Audio", type="filepath")
267
+ ref_text_input = gr.Textbox(label="Reference Text", lines=2)
268
+ speech_type_rows.append(row)
269
+ speech_type_names.append(name_input)
270
+ speech_type_audios.append(audio_input)
271
+ speech_type_ref_texts.append(ref_text_input)
272
+ speech_type_delete_btns.append(delete_btn)
273
+ speech_type_insert_btns.append(insert_btn)
274
+
275
+ # Button to add speech type
276
+ add_speech_type_btn = gr.Button("Add Speech Type")
277
+
278
+ # Keep track of current number of speech types
279
+ speech_type_count = gr.State(value=0)
280
+
281
+ # Function to add a speech type
282
+ def add_speech_type_fn(speech_type_count):
283
+ if speech_type_count < max_speech_types - 1:
284
+ speech_type_count += 1
285
+ # Prepare updates for the rows
286
+ row_updates = []
287
+ for i in range(max_speech_types - 1):
288
+ if i < speech_type_count:
289
+ row_updates.append(gr.update(visible=True))
290
+ else:
291
+ row_updates.append(gr.update())
292
+ else:
293
+ # Optionally, show a warning
294
+ row_updates = [gr.update() for _ in range(max_speech_types - 1)]
295
+ return [speech_type_count] + row_updates
296
+
297
+ add_speech_type_btn.click(
298
+ add_speech_type_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows
299
+ )
300
+
301
+ # Function to delete a speech type
302
+ def make_delete_speech_type_fn(index):
303
+ def delete_speech_type_fn(speech_type_count):
304
+ # Prepare updates
305
+ row_updates = []
306
+
307
+ for i in range(max_speech_types - 1):
308
+ if i == index:
309
+ row_updates.append(gr.update(visible=False))
310
+ else:
311
+ row_updates.append(gr.update())
312
+
313
+ speech_type_count = max(0, speech_type_count - 1)
314
+
315
+ return [speech_type_count] + row_updates
316
+
317
+ return delete_speech_type_fn
318
+
319
+ # Update delete button clicks
320
+ for i, delete_btn in enumerate(speech_type_delete_btns):
321
+ delete_fn = make_delete_speech_type_fn(i)
322
+ delete_btn.click(delete_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows)
323
+
324
+ # Text input for the prompt
325
+ gen_text_input_multistyle = gr.Textbox(
326
+ label="Text to Generate",
327
+ lines=10,
328
+ placeholder="Enter the script with speaker names (or emotion types) at the start of each block, e.g.:\n\n{Regular} Hello, I'd like to order a sandwich please.\n{Surprised} What do you mean you're out of bread?\n{Sad} I really wanted a sandwich though...\n{Angry} You know what, darn you and your little shop!\n{Whisper} I'll just go back home and cry now.\n{Shouting} Why me?!",
329
+ )
330
+
331
+ def make_insert_speech_type_fn(index):
332
+ def insert_speech_type_fn(current_text, speech_type_name):
333
+ current_text = current_text or ""
334
+ speech_type_name = speech_type_name or "None"
335
+ updated_text = current_text + f"{{{speech_type_name}}} "
336
+ return gr.update(value=updated_text)
337
+
338
+ return insert_speech_type_fn
339
+
340
+ for i, insert_btn in enumerate(speech_type_insert_btns):
341
+ insert_fn = make_insert_speech_type_fn(i)
342
+ insert_btn.click(
343
+ insert_fn,
344
+ inputs=[gen_text_input_multistyle, speech_type_names[i]],
345
+ outputs=gen_text_input_multistyle,
346
+ )
347
+
348
+ # Model choice
349
+ model_choice_multistyle = gr.Radio(choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS")
350
+
351
+ with gr.Accordion("Advanced Settings", open=False):
352
+ remove_silence_multistyle = gr.Checkbox(
353
+ label="Remove Silences",
354
+ value=False,
355
+ )
356
+
357
+ # Generate button
358
+ generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
359
+
360
+ # Output audio
361
+ audio_output_multistyle = gr.Audio(label="Synthesized Audio")
362
+
363
+ @gpu_decorator
364
+ def generate_multistyle_speech(
365
+ regular_audio,
366
+ regular_ref_text,
367
+ gen_text,
368
+ *args,
369
+ ):
370
+ num_additional_speech_types = max_speech_types - 1
371
+ speech_type_names_list = args[:num_additional_speech_types]
372
+ speech_type_audios_list = args[num_additional_speech_types : 2 * num_additional_speech_types]
373
+ speech_type_ref_texts_list = args[2 * num_additional_speech_types : 3 * num_additional_speech_types]
374
+ model_choice = args[3 * num_additional_speech_types + 1]
375
+ remove_silence = args[3 * num_additional_speech_types + 1]
376
+
377
+ # Collect the speech types and their audios into a dict
378
+ speech_types = {"Regular": {"audio": regular_audio, "ref_text": regular_ref_text}}
379
+
380
+ for name_input, audio_input, ref_text_input in zip(
381
+ speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list
382
+ ):
383
+ if name_input and audio_input:
384
+ speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input}
385
+
386
+ # Parse the gen_text into segments
387
+ segments = parse_speechtypes_text(gen_text)
388
+
389
+ # For each segment, generate speech
390
+ generated_audio_segments = []
391
+ current_style = "Regular"
392
+
393
+ for segment in segments:
394
+ style = segment["style"]
395
+ text = segment["text"]
396
+
397
+ if style in speech_types:
398
+ current_style = style
399
+ else:
400
+ # If style not available, default to Regular
401
+ current_style = "Regular"
402
+
403
+ ref_audio = speech_types[current_style]["audio"]
404
+ ref_text = speech_types[current_style].get("ref_text", "")
405
+
406
+ # Generate speech for this segment
407
+ audio, _ = infer(
408
+ ref_audio, ref_text, text, model_choice, remove_silence, 0, show_info=print
409
+ ) # show_info=print no pull to top when generating
410
+ sr, audio_data = audio
411
+
412
+ generated_audio_segments.append(audio_data)
413
+
414
+ # Concatenate all audio segments
415
+ if generated_audio_segments:
416
+ final_audio_data = np.concatenate(generated_audio_segments)
417
+ return (sr, final_audio_data)
418
+ else:
419
+ gr.Warning("No audio generated.")
420
+ return None
421
+
422
+ generate_multistyle_btn.click(
423
+ generate_multistyle_speech,
424
+ inputs=[
425
+ regular_audio,
426
+ regular_ref_text,
427
+ gen_text_input_multistyle,
428
+ ]
429
+ + speech_type_names
430
+ + speech_type_audios
431
+ + speech_type_ref_texts
432
+ + [
433
+ model_choice_multistyle,
434
+ remove_silence_multistyle,
435
+ ],
436
+ outputs=audio_output_multistyle,
437
+ )
438
+
439
+ # Validation function to disable Generate button if speech types are missing
440
+ def validate_speech_types(gen_text, regular_name, *args):
441
+ num_additional_speech_types = max_speech_types - 1
442
+ speech_type_names_list = args[:num_additional_speech_types]
443
+
444
+ # Collect the speech types names
445
+ speech_types_available = set()
446
+ if regular_name:
447
+ speech_types_available.add(regular_name)
448
+ for name_input in speech_type_names_list:
449
+ if name_input:
450
+ speech_types_available.add(name_input)
451
+
452
+ # Parse the gen_text to get the speech types used
453
+ segments = parse_speechtypes_text(gen_text)
454
+ speech_types_in_text = set(segment["style"] for segment in segments)
455
+
456
+ # Check if all speech types in text are available
457
+ missing_speech_types = speech_types_in_text - speech_types_available
458
+
459
+ if missing_speech_types:
460
+ # Disable the generate button
461
+ return gr.update(interactive=False)
462
+ else:
463
+ # Enable the generate button
464
+ return gr.update(interactive=True)
465
+
466
+ gen_text_input_multistyle.change(
467
+ validate_speech_types,
468
+ inputs=[gen_text_input_multistyle, regular_name] + speech_type_names,
469
+ outputs=generate_multistyle_btn,
470
+ )
471
+
472
+
473
+ with gr.Blocks() as app_chat:
474
+ gr.Markdown(
475
+ """
476
+ # Voice Chat
477
+ Have a conversation with an AI using your reference voice!
478
+ 1. Upload a reference audio clip and optionally its transcript.
479
+ 2. Load the chat model.
480
+ 3. Record your message through your microphone.
481
+ 4. The AI will respond using the reference voice.
482
+ """
483
+ )
484
+
485
+ if not USING_SPACES:
486
+ load_chat_model_btn = gr.Button("Load Chat Model", variant="primary")
487
+
488
+ chat_interface_container = gr.Column(visible=False)
489
+
490
+ @gpu_decorator
491
+ def load_chat_model():
492
+ global chat_model_state, chat_tokenizer_state
493
+ if chat_model_state is None:
494
+ show_info = gr.Info
495
+ show_info("Loading chat model...")
496
+ model_name = "Qwen/Qwen2.5-3B-Instruct"
497
+ chat_model_state = AutoModelForCausalLM.from_pretrained(
498
+ model_name, torch_dtype="auto", device_map="auto"
499
+ )
500
+ chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
501
+ show_info("Chat model loaded.")
502
+
503
+ return gr.update(visible=False), gr.update(visible=True)
504
+
505
+ load_chat_model_btn.click(load_chat_model, outputs=[load_chat_model_btn, chat_interface_container])
506
+
507
+ else:
508
+ chat_interface_container = gr.Column()
509
+
510
+ if chat_model_state is None:
511
+ model_name = "Qwen/Qwen2.5-3B-Instruct"
512
+ chat_model_state = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")
513
+ chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
514
+
515
+ with chat_interface_container:
516
+ with gr.Row():
517
+ with gr.Column():
518
+ ref_audio_chat = gr.Audio(label="Reference Audio", type="filepath")
519
+ with gr.Column():
520
+ with gr.Accordion("Advanced Settings", open=False):
521
+ model_choice_chat = gr.Radio(
522
+ choices=["F5-TTS", "E2-TTS"],
523
+ label="TTS Model",
524
+ value="F5-TTS",
525
+ )
526
+ remove_silence_chat = gr.Checkbox(
527
+ label="Remove Silences",
528
+ value=True,
529
+ )
530
+ ref_text_chat = gr.Textbox(
531
+ label="Reference Text",
532
+ info="Optional: Leave blank to auto-transcribe",
533
+ lines=2,
534
+ )
535
+ system_prompt_chat = gr.Textbox(
536
+ label="System Prompt",
537
+ value="You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.",
538
+ lines=2,
539
+ )
540
+
541
+ chatbot_interface = gr.Chatbot(label="Conversation")
542
+
543
+ with gr.Row():
544
+ with gr.Column():
545
+ audio_input_chat = gr.Microphone(
546
+ label="Speak your message",
547
+ type="filepath",
548
+ )
549
+ audio_output_chat = gr.Audio(autoplay=True)
550
+ with gr.Column():
551
+ text_input_chat = gr.Textbox(
552
+ label="Type your message",
553
+ lines=1,
554
+ )
555
+ send_btn_chat = gr.Button("Send")
556
+ clear_btn_chat = gr.Button("Clear Conversation")
557
+
558
+ conversation_state = gr.State(
559
+ value=[
560
+ {
561
+ "role": "system",
562
+ "content": "You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.",
563
+ }
564
+ ]
565
+ )
566
+
567
+ # Modify process_audio_input to use model and tokenizer from state
568
+ @gpu_decorator
569
+ def process_audio_input(audio_path, text, history, conv_state):
570
+ """Handle audio or text input from user"""
571
+
572
+ if not audio_path and not text.strip():
573
+ return history, conv_state, ""
574
+
575
+ if audio_path:
576
+ text = preprocess_ref_audio_text(audio_path, text)[1]
577
+
578
+ if not text.strip():
579
+ return history, conv_state, ""
580
+
581
+ conv_state.append({"role": "user", "content": text})
582
+ history.append((text, None))
583
+
584
+ response = generate_response(conv_state, chat_model_state, chat_tokenizer_state)
585
+
586
+ conv_state.append({"role": "assistant", "content": response})
587
+ history[-1] = (text, response)
588
+
589
+ return history, conv_state, ""
590
+
591
+ @gpu_decorator
592
+ def generate_audio_response(history, ref_audio, ref_text, model, remove_silence):
593
+ """Generate TTS audio for AI response"""
594
+ if not history or not ref_audio:
595
+ return None
596
+
597
+ last_user_message, last_ai_response = history[-1]
598
+ if not last_ai_response:
599
+ return None
600
+
601
+ audio_result, _ = infer(
602
+ ref_audio,
603
+ ref_text,
604
+ last_ai_response,
605
+ model,
606
+ remove_silence,
607
+ cross_fade_duration=0.15,
608
+ speed=1.0,
609
+ show_info=print, # show_info=print no pull to top when generating
610
+ )
611
+ return audio_result
612
+
613
+ def clear_conversation():
614
+ """Reset the conversation"""
615
+ return [], [
616
+ {
617
+ "role": "system",
618
+ "content": "You are not an AI assistant, you are whoever the user says you are. You must stay in character. Keep your responses concise since they will be spoken out loud.",
619
+ }
620
+ ]
621
+
622
+ def update_system_prompt(new_prompt):
623
+ """Update the system prompt and reset the conversation"""
624
+ new_conv_state = [{"role": "system", "content": new_prompt}]
625
+ return [], new_conv_state
626
+
627
+ # Handle audio input
628
+ audio_input_chat.stop_recording(
629
+ process_audio_input,
630
+ inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
631
+ outputs=[chatbot_interface, conversation_state],
632
+ ).then(
633
+ generate_audio_response,
634
+ inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, model_choice_chat, remove_silence_chat],
635
+ outputs=[audio_output_chat],
636
+ ).then(
637
+ lambda: None,
638
+ None,
639
+ audio_input_chat,
640
+ )
641
+
642
+ # Handle text input
643
+ text_input_chat.submit(
644
+ process_audio_input,
645
+ inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
646
+ outputs=[chatbot_interface, conversation_state],
647
+ ).then(
648
+ generate_audio_response,
649
+ inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, model_choice_chat, remove_silence_chat],
650
+ outputs=[audio_output_chat],
651
+ ).then(
652
+ lambda: None,
653
+ None,
654
+ text_input_chat,
655
+ )
656
+
657
+ # Handle send button
658
+ send_btn_chat.click(
659
+ process_audio_input,
660
+ inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
661
+ outputs=[chatbot_interface, conversation_state],
662
+ ).then(
663
+ generate_audio_response,
664
+ inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, model_choice_chat, remove_silence_chat],
665
+ outputs=[audio_output_chat],
666
+ ).then(
667
+ lambda: None,
668
+ None,
669
+ text_input_chat,
670
+ )
671
+
672
+ # Handle clear button
673
+ clear_btn_chat.click(
674
+ clear_conversation,
675
+ outputs=[chatbot_interface, conversation_state],
676
+ )
677
+
678
+ # Handle system prompt change and reset conversation
679
+ system_prompt_chat.change(
680
+ update_system_prompt,
681
+ inputs=system_prompt_chat,
682
+ outputs=[chatbot_interface, conversation_state],
683
+ )
684
+
685
+
686
+ with gr.Blocks() as app:
687
+ gr.Markdown(
688
+ """
689
+ # E2/F5 TTS
690
+
691
+ This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
692
+
693
+ * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
694
+ * [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
695
+
696
+ The checkpoints support English and Chinese.
697
+
698
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt.
699
+
700
+ **NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<15s). Ensure the audio is fully uploaded before generating.**
701
+ """
702
+ )
703
+ gr.TabbedInterface(
704
+ [app_tts, app_multistyle, app_chat, app_credits],
705
+ ["TTS", "Multi-Speech", "Voice-Chat", "Credits"],
706
+ )
707
+
708
+
709
+ @click.command()
710
+ @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
711
+ @click.option("--host", "-H", default=None, help="Host to run the app on")
712
+ @click.option(
713
+ "--share",
714
+ "-s",
715
+ default=False,
716
+ is_flag=True,
717
+ help="Share the app via Gradio share link",
718
+ )
719
+ @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
720
+ def main(port, host, share, api):
721
+ global app
722
+ print("Starting app...")
723
+ app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api)
724
+
725
+
726
+ if __name__ == "__main__":
727
+ if not USING_SPACES:
728
+ main()
729
+ else:
730
+ app.queue().launch()
finetune-cli.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from model import CFM, UNetT, DiT, 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
7
+ import os
8
+
9
+ # -------------------------- Dataset Settings --------------------------- #
10
+ target_sample_rate = 24000
11
+ n_mel_channels = 100
12
+ hop_length = 256
13
+
14
+
15
+ # -------------------------- Argument Parsing --------------------------- #
16
+ def parse_args():
17
+ parser = argparse.ArgumentParser(description="Train CFM Model")
18
+
19
+ parser.add_argument(
20
+ "--exp_name", type=str, default="F5TTS_Base", choices=["F5TTS_Base", "E2TTS_Base"], help="Experiment name"
21
+ )
22
+ parser.add_argument("--dataset_name", type=str, default="Emilia_ZH_EN", help="Name of the dataset to use")
23
+ parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate for training")
24
+ parser.add_argument("--batch_size_per_gpu", type=int, default=256, help="Batch size per GPU")
25
+ parser.add_argument(
26
+ "--batch_size_type", type=str, default="frame", choices=["frame", "sample"], help="Batch size type"
27
+ )
28
+ parser.add_argument("--max_samples", type=int, default=16, help="Max sequences per batch")
29
+ parser.add_argument("--grad_accumulation_steps", type=int, default=1, help="Gradient accumulation steps")
30
+ parser.add_argument("--max_grad_norm", type=float, default=1.0, help="Max gradient norm for clipping")
31
+ parser.add_argument("--epochs", type=int, default=10, help="Number of training epochs")
32
+ parser.add_argument("--num_warmup_updates", type=int, default=5, help="Warmup steps")
33
+ parser.add_argument("--save_per_updates", type=int, default=10, help="Save checkpoint every X steps")
34
+ parser.add_argument("--last_per_steps", type=int, default=10, help="Save last checkpoint every X steps")
35
+ parser.add_argument("--finetune", type=bool, default=True, help="Use Finetune")
36
+
37
+ parser.add_argument(
38
+ "--tokenizer", type=str, default="pinyin", choices=["pinyin", "char", "custom"], help="Tokenizer type"
39
+ )
40
+ parser.add_argument(
41
+ "--tokenizer_path",
42
+ type=str,
43
+ default=None,
44
+ help="Path to custom tokenizer vocab file (only used if tokenizer = 'custom')",
45
+ )
46
+
47
+ return parser.parse_args()
48
+
49
+
50
+ # -------------------------- Training Settings -------------------------- #
51
+
52
+
53
+ def main():
54
+ args = parse_args()
55
+
56
+ # Model parameters based on experiment name
57
+ if args.exp_name == "F5TTS_Base":
58
+ wandb_resume_id = None
59
+ model_cls = DiT
60
+ model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
61
+ if args.finetune:
62
+ ckpt_path = str(cached_path("hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.pt"))
63
+ elif args.exp_name == "E2TTS_Base":
64
+ wandb_resume_id = None
65
+ model_cls = UNetT
66
+ model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
67
+ if args.finetune:
68
+ ckpt_path = str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.pt"))
69
+
70
+ if args.finetune:
71
+ path_ckpt = os.path.join("ckpts", args.dataset_name)
72
+ if not os.path.isdir(path_ckpt):
73
+ os.makedirs(path_ckpt, exist_ok=True)
74
+ shutil.copy2(ckpt_path, os.path.join(path_ckpt, os.path.basename(ckpt_path)))
75
+
76
+ checkpoint_path = os.path.join("ckpts", args.dataset_name)
77
+
78
+ # Use the tokenizer and tokenizer_path provided in the command line arguments
79
+ tokenizer = args.tokenizer
80
+ if tokenizer == "custom":
81
+ if not args.tokenizer_path:
82
+ raise ValueError("Custom tokenizer selected, but no tokenizer_path provided.")
83
+ tokenizer_path = args.tokenizer_path
84
+ else:
85
+ tokenizer_path = args.dataset_name
86
+
87
+ vocab_char_map, vocab_size = get_tokenizer(tokenizer_path, tokenizer)
88
+
89
+ mel_spec_kwargs = dict(
90
+ target_sample_rate=target_sample_rate,
91
+ n_mel_channels=n_mel_channels,
92
+ hop_length=hop_length,
93
+ )
94
+
95
+ e2tts = CFM(
96
+ transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
97
+ mel_spec_kwargs=mel_spec_kwargs,
98
+ vocab_char_map=vocab_char_map,
99
+ )
100
+
101
+ trainer = Trainer(
102
+ e2tts,
103
+ args.epochs,
104
+ args.learning_rate,
105
+ num_warmup_updates=args.num_warmup_updates,
106
+ save_per_updates=args.save_per_updates,
107
+ checkpoint_path=checkpoint_path,
108
+ batch_size=args.batch_size_per_gpu,
109
+ batch_size_type=args.batch_size_type,
110
+ max_samples=args.max_samples,
111
+ grad_accumulation_steps=args.grad_accumulation_steps,
112
+ max_grad_norm=args.max_grad_norm,
113
+ wandb_project="CFM-TTS",
114
+ wandb_run_name=args.exp_name,
115
+ wandb_resume_id=wandb_resume_id,
116
+ last_per_steps=args.last_per_steps,
117
+ )
118
+
119
+ train_dataset = load_dataset(args.dataset_name, tokenizer, mel_spec_kwargs=mel_spec_kwargs)
120
+ trainer.train(
121
+ train_dataset,
122
+ resumable_with_seed=666, # seed for shuffling dataset
123
+ )
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
finetune_gradio.py ADDED
@@ -0,0 +1,944 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ import tempfile
5
+ import random
6
+ from transformers import pipeline
7
+ import gradio as gr
8
+ import torch
9
+ import gc
10
+ import click
11
+ import torchaudio
12
+ from glob import glob
13
+ import librosa
14
+ import numpy as np
15
+ from scipy.io import wavfile
16
+ import shutil
17
+ import time
18
+
19
+ import json
20
+ from model.utils import convert_char_to_pinyin
21
+ import signal
22
+ import psutil
23
+ import platform
24
+ import subprocess
25
+ from datasets.arrow_writer import ArrowWriter
26
+ from datasets import Dataset as Dataset_
27
+ from api import F5TTS
28
+
29
+
30
+ training_process = None
31
+ system = platform.system()
32
+ python_executable = sys.executable or "python"
33
+ tts_api = None
34
+ last_checkpoint = ""
35
+ last_device = ""
36
+
37
+ path_data = "data"
38
+
39
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
40
+
41
+ pipe = None
42
+
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
+
52
+ def clear_text(text):
53
+ """Clean and prepare text by lowering the case and stripping whitespace."""
54
+ return text.lower().strip()
55
+
56
+
57
+ def get_rms(
58
+ y,
59
+ frame_length=2048,
60
+ hop_length=512,
61
+ pad_mode="constant",
62
+ ): # https://github.com/RVC-Boss/GPT-SoVITS/blob/main/tools/slicer2.py
63
+ padding = (int(frame_length // 2), int(frame_length // 2))
64
+ y = np.pad(y, padding, mode=pad_mode)
65
+
66
+ axis = -1
67
+ # put our new within-frame axis at the end for now
68
+ out_strides = y.strides + tuple([y.strides[axis]])
69
+ # Reduce the shape on the framing axis
70
+ x_shape_trimmed = list(y.shape)
71
+ x_shape_trimmed[axis] -= frame_length - 1
72
+ out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
73
+ xw = np.lib.stride_tricks.as_strided(y, shape=out_shape, strides=out_strides)
74
+ if axis < 0:
75
+ target_axis = axis - 1
76
+ else:
77
+ target_axis = axis + 1
78
+ xw = np.moveaxis(xw, -1, target_axis)
79
+ # Downsample along the target axis
80
+ slices = [slice(None)] * xw.ndim
81
+ slices[axis] = slice(0, None, hop_length)
82
+ x = xw[tuple(slices)]
83
+
84
+ # Calculate power
85
+ power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
86
+
87
+ return np.sqrt(power)
88
+
89
+
90
+ class Slicer: # https://github.com/RVC-Boss/GPT-SoVITS/blob/main/tools/slicer2.py
91
+ def __init__(
92
+ self,
93
+ sr: int,
94
+ threshold: float = -40.0,
95
+ min_length: int = 2000,
96
+ min_interval: int = 300,
97
+ hop_size: int = 20,
98
+ max_sil_kept: int = 2000,
99
+ ):
100
+ if not min_length >= min_interval >= hop_size:
101
+ raise ValueError("The following condition must be satisfied: min_length >= min_interval >= hop_size")
102
+ if not max_sil_kept >= hop_size:
103
+ raise ValueError("The following condition must be satisfied: max_sil_kept >= hop_size")
104
+ min_interval = sr * min_interval / 1000
105
+ self.threshold = 10 ** (threshold / 20.0)
106
+ self.hop_size = round(sr * hop_size / 1000)
107
+ self.win_size = min(round(min_interval), 4 * self.hop_size)
108
+ self.min_length = round(sr * min_length / 1000 / self.hop_size)
109
+ self.min_interval = round(min_interval / self.hop_size)
110
+ self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
111
+
112
+ def _apply_slice(self, waveform, begin, end):
113
+ if len(waveform.shape) > 1:
114
+ return waveform[:, begin * self.hop_size : min(waveform.shape[1], end * self.hop_size)]
115
+ else:
116
+ return waveform[begin * self.hop_size : min(waveform.shape[0], end * self.hop_size)]
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(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
127
+ sil_tags = []
128
+ silence_start = None
129
+ clip_start = 0
130
+ for i, rms in enumerate(rms_list):
131
+ # Keep looping while frame is silent.
132
+ if rms < self.threshold:
133
+ # Record start of silent frames.
134
+ if silence_start is None:
135
+ silence_start = i
136
+ continue
137
+ # Keep looping while frame is not silent and silence start has not been recorded.
138
+ if silence_start is None:
139
+ continue
140
+ # Clear recorded silence start if interval is not enough or clip is too short
141
+ is_leading_silence = silence_start == 0 and i > self.max_sil_kept
142
+ need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
143
+ if not is_leading_silence and not need_slice_middle:
144
+ silence_start = None
145
+ continue
146
+ # Need slicing. Record the range of silent frames to be removed.
147
+ if i - silence_start <= self.max_sil_kept:
148
+ pos = rms_list[silence_start : i + 1].argmin() + silence_start
149
+ if silence_start == 0:
150
+ sil_tags.append((0, pos))
151
+ else:
152
+ sil_tags.append((pos, pos))
153
+ clip_start = pos
154
+ elif i - silence_start <= self.max_sil_kept * 2:
155
+ pos = rms_list[i - self.max_sil_kept : silence_start + self.max_sil_kept + 1].argmin()
156
+ pos += i - self.max_sil_kept
157
+ pos_l = rms_list[silence_start : silence_start + self.max_sil_kept + 1].argmin() + silence_start
158
+ pos_r = rms_list[i - self.max_sil_kept : i + 1].argmin() + i - self.max_sil_kept
159
+ if silence_start == 0:
160
+ sil_tags.append((0, pos_r))
161
+ clip_start = pos_r
162
+ else:
163
+ sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
164
+ clip_start = max(pos_r, pos)
165
+ else:
166
+ pos_l = rms_list[silence_start : silence_start + self.max_sil_kept + 1].argmin() + silence_start
167
+ pos_r = rms_list[i - self.max_sil_kept : i + 1].argmin() + i - self.max_sil_kept
168
+ if silence_start == 0:
169
+ sil_tags.append((0, pos_r))
170
+ else:
171
+ sil_tags.append((pos_l, pos_r))
172
+ clip_start = pos_r
173
+ silence_start = None
174
+ # Deal with trailing silence.
175
+ total_frames = rms_list.shape[0]
176
+ if silence_start is not None and total_frames - silence_start >= self.min_interval:
177
+ silence_end = min(total_frames, silence_start + self.max_sil_kept)
178
+ pos = rms_list[silence_start : silence_end + 1].argmin() + silence_start
179
+ sil_tags.append((pos, total_frames + 1))
180
+ # Apply and return slices.
181
+ ####音频+起始时间+终止时间
182
+ if len(sil_tags) == 0:
183
+ return [[waveform, 0, int(total_frames * self.hop_size)]]
184
+ else:
185
+ chunks = []
186
+ if sil_tags[0][0] > 0:
187
+ chunks.append([self._apply_slice(waveform, 0, sil_tags[0][0]), 0, int(sil_tags[0][0] * self.hop_size)])
188
+ for i in range(len(sil_tags) - 1):
189
+ chunks.append(
190
+ [
191
+ self._apply_slice(waveform, sil_tags[i][1], sil_tags[i + 1][0]),
192
+ int(sil_tags[i][1] * self.hop_size),
193
+ int(sil_tags[i + 1][0] * self.hop_size),
194
+ ]
195
+ )
196
+ if sil_tags[-1][1] < total_frames:
197
+ chunks.append(
198
+ [
199
+ self._apply_slice(waveform, sil_tags[-1][1], total_frames),
200
+ int(sil_tags[-1][1] * self.hop_size),
201
+ int(total_frames * self.hop_size),
202
+ ]
203
+ )
204
+ return chunks
205
+
206
+
207
+ # terminal
208
+ def terminate_process_tree(pid, including_parent=True):
209
+ try:
210
+ parent = psutil.Process(pid)
211
+ except psutil.NoSuchProcess:
212
+ # Process already terminated
213
+ return
214
+
215
+ children = parent.children(recursive=True)
216
+ for child in children:
217
+ try:
218
+ os.kill(child.pid, signal.SIGTERM) # or signal.SIGKILL
219
+ except OSError:
220
+ pass
221
+ if including_parent:
222
+ try:
223
+ os.kill(parent.pid, signal.SIGTERM) # or signal.SIGKILL
224
+ except OSError:
225
+ pass
226
+
227
+
228
+ def terminate_process(pid):
229
+ if system == "Windows":
230
+ cmd = f"taskkill /t /f /pid {pid}"
231
+ os.system(cmd)
232
+ else:
233
+ terminate_process_tree(pid)
234
+
235
+
236
+ def start_training(
237
+ dataset_name="",
238
+ exp_name="F5TTS_Base",
239
+ learning_rate=1e-4,
240
+ batch_size_per_gpu=400,
241
+ batch_size_type="frame",
242
+ max_samples=64,
243
+ grad_accumulation_steps=1,
244
+ max_grad_norm=1.0,
245
+ epochs=11,
246
+ num_warmup_updates=200,
247
+ save_per_updates=400,
248
+ last_per_steps=800,
249
+ finetune=True,
250
+ ):
251
+ global training_process, tts_api
252
+
253
+ if tts_api is not None:
254
+ del tts_api
255
+ gc.collect()
256
+ torch.cuda.empty_cache()
257
+ tts_api = None
258
+
259
+ path_project = os.path.join(path_data, dataset_name + "_pinyin")
260
+
261
+ if not os.path.isdir(path_project):
262
+ yield (
263
+ f"There is not project with name {dataset_name}",
264
+ gr.update(interactive=True),
265
+ gr.update(interactive=False),
266
+ )
267
+ return
268
+
269
+ file_raw = os.path.join(path_project, "raw.arrow")
270
+ if not os.path.isfile(file_raw):
271
+ yield f"There is no file {file_raw}", gr.update(interactive=True), gr.update(interactive=False)
272
+ return
273
+
274
+ # Check if a training process is already running
275
+ if training_process is not None:
276
+ return "Train run already!", gr.update(interactive=False), gr.update(interactive=True)
277
+
278
+ yield "start train", gr.update(interactive=False), gr.update(interactive=False)
279
+
280
+ # Command to run the training script with the specified arguments
281
+ cmd = (
282
+ f"accelerate launch finetune-cli.py --exp_name {exp_name} "
283
+ f"--learning_rate {learning_rate} "
284
+ f"--batch_size_per_gpu {batch_size_per_gpu} "
285
+ f"--batch_size_type {batch_size_type} "
286
+ f"--max_samples {max_samples} "
287
+ f"--grad_accumulation_steps {grad_accumulation_steps} "
288
+ f"--max_grad_norm {max_grad_norm} "
289
+ f"--epochs {epochs} "
290
+ f"--num_warmup_updates {num_warmup_updates} "
291
+ f"--save_per_updates {save_per_updates} "
292
+ f"--last_per_steps {last_per_steps} "
293
+ f"--dataset_name {dataset_name}"
294
+ )
295
+ if finetune:
296
+ cmd += f" --finetune {finetune}"
297
+
298
+ print(cmd)
299
+
300
+ try:
301
+ # Start the training process
302
+ training_process = subprocess.Popen(cmd, shell=True)
303
+
304
+ time.sleep(5)
305
+ yield "train start", gr.update(interactive=False), gr.update(interactive=True)
306
+
307
+ # Wait for the training process to finish
308
+ training_process.wait()
309
+ time.sleep(1)
310
+
311
+ if training_process is None:
312
+ text_info = "train stop"
313
+ else:
314
+ text_info = "train complete !"
315
+
316
+ except Exception as e: # Catch all exceptions
317
+ # Ensure that we reset the training process variable in case of an error
318
+ text_info = f"An error occurred: {str(e)}"
319
+
320
+ training_process = None
321
+
322
+ yield text_info, gr.update(interactive=True), gr.update(interactive=False)
323
+
324
+
325
+ def stop_training():
326
+ global training_process
327
+ if training_process is None:
328
+ return "Train not run !", gr.update(interactive=True), gr.update(interactive=False)
329
+ terminate_process_tree(training_process.pid)
330
+ training_process = None
331
+ return "train stop", gr.update(interactive=True), gr.update(interactive=False)
332
+
333
+
334
+ def create_data_project(name):
335
+ name += "_pinyin"
336
+ os.makedirs(os.path.join(path_data, name), exist_ok=True)
337
+ os.makedirs(os.path.join(path_data, name, "dataset"), exist_ok=True)
338
+
339
+
340
+ def transcribe(file_audio, language="english"):
341
+ global pipe
342
+
343
+ if pipe is None:
344
+ pipe = pipeline(
345
+ "automatic-speech-recognition",
346
+ model="openai/whisper-large-v3-turbo",
347
+ torch_dtype=torch.float16,
348
+ device=device,
349
+ )
350
+
351
+ text_transcribe = pipe(
352
+ file_audio,
353
+ chunk_length_s=30,
354
+ batch_size=128,
355
+ generate_kwargs={"task": "transcribe", "language": language},
356
+ return_timestamps=False,
357
+ )["text"].strip()
358
+ return text_transcribe
359
+
360
+
361
+ def transcribe_all(name_project, audio_files, language, user=False, progress=gr.Progress()):
362
+ name_project += "_pinyin"
363
+ path_project = os.path.join(path_data, name_project)
364
+ path_dataset = os.path.join(path_project, "dataset")
365
+ path_project_wavs = os.path.join(path_project, "wavs")
366
+ file_metadata = os.path.join(path_project, "metadata.csv")
367
+
368
+ if audio_files is None:
369
+ return "You need to load an audio file."
370
+
371
+ if os.path.isdir(path_project_wavs):
372
+ shutil.rmtree(path_project_wavs)
373
+
374
+ if os.path.isfile(file_metadata):
375
+ os.remove(file_metadata)
376
+
377
+ os.makedirs(path_project_wavs, exist_ok=True)
378
+
379
+ if user:
380
+ file_audios = [
381
+ file
382
+ for format in ("*.wav", "*.ogg", "*.opus", "*.mp3", "*.flac")
383
+ for file in glob(os.path.join(path_dataset, format))
384
+ ]
385
+ if file_audios == []:
386
+ return "No audio file was found in the dataset."
387
+ else:
388
+ file_audios = audio_files
389
+
390
+ alpha = 0.5
391
+ _max = 1.0
392
+ slicer = Slicer(24000)
393
+
394
+ num = 0
395
+ error_num = 0
396
+ data = ""
397
+ for file_audio in progress.tqdm(file_audios, desc="transcribe files", total=len((file_audios))):
398
+ audio, _ = librosa.load(file_audio, sr=24000, mono=True)
399
+
400
+ list_slicer = slicer.slice(audio)
401
+ for chunk, start, end in progress.tqdm(list_slicer, total=len(list_slicer), desc="slicer files"):
402
+ name_segment = os.path.join(f"segment_{num}")
403
+ file_segment = os.path.join(path_project_wavs, f"{name_segment}.wav")
404
+
405
+ tmp_max = np.abs(chunk).max()
406
+ if tmp_max > 1:
407
+ chunk /= tmp_max
408
+ chunk = (chunk / tmp_max * (_max * alpha)) + (1 - alpha) * chunk
409
+ wavfile.write(file_segment, 24000, (chunk * 32767).astype(np.int16))
410
+
411
+ try:
412
+ text = transcribe(file_segment, language)
413
+ text = text.lower().strip().replace('"', "")
414
+
415
+ data += f"{name_segment}|{text}\n"
416
+
417
+ num += 1
418
+ except: # noqa: E722
419
+ error_num += 1
420
+
421
+ with open(file_metadata, "w", encoding="utf-8") as f:
422
+ f.write(data)
423
+
424
+ if error_num != []:
425
+ error_text = f"\nerror files : {error_num}"
426
+ else:
427
+ error_text = ""
428
+
429
+ return f"transcribe complete samples : {num}\npath : {path_project_wavs}{error_text}"
430
+
431
+
432
+ def format_seconds_to_hms(seconds):
433
+ hours = int(seconds / 3600)
434
+ minutes = int((seconds % 3600) / 60)
435
+ seconds = seconds % 60
436
+ return "{:02d}:{:02d}:{:02d}".format(hours, minutes, int(seconds))
437
+
438
+
439
+ def create_metadata(name_project, progress=gr.Progress()):
440
+ name_project += "_pinyin"
441
+ path_project = os.path.join(path_data, name_project)
442
+ path_project_wavs = os.path.join(path_project, "wavs")
443
+ file_metadata = os.path.join(path_project, "metadata.csv")
444
+ file_raw = os.path.join(path_project, "raw.arrow")
445
+ file_duration = os.path.join(path_project, "duration.json")
446
+ file_vocab = os.path.join(path_project, "vocab.txt")
447
+
448
+ if not os.path.isfile(file_metadata):
449
+ return "The file was not found in " + file_metadata
450
+
451
+ with open(file_metadata, "r", encoding="utf-8") as f:
452
+ data = f.read()
453
+
454
+ audio_path_list = []
455
+ text_list = []
456
+ duration_list = []
457
+
458
+ count = data.split("\n")
459
+ lenght = 0
460
+ result = []
461
+ error_files = []
462
+ for line in progress.tqdm(data.split("\n"), total=count):
463
+ sp_line = line.split("|")
464
+ if len(sp_line) != 2:
465
+ continue
466
+ name_audio, text = sp_line[:2]
467
+
468
+ file_audio = os.path.join(path_project_wavs, name_audio + ".wav")
469
+
470
+ if not os.path.isfile(file_audio):
471
+ error_files.append(file_audio)
472
+ continue
473
+
474
+ duraction = get_audio_duration(file_audio)
475
+ if duraction < 2 and duraction > 15:
476
+ continue
477
+ if len(text) < 4:
478
+ continue
479
+
480
+ text = clear_text(text)
481
+ text = convert_char_to_pinyin([text], polyphone=True)[0]
482
+
483
+ audio_path_list.append(file_audio)
484
+ duration_list.append(duraction)
485
+ text_list.append(text)
486
+
487
+ result.append({"audio_path": file_audio, "text": text, "duration": duraction})
488
+
489
+ lenght += duraction
490
+
491
+ if duration_list == []:
492
+ error_files_text = "\n".join(error_files)
493
+ return f"Error: No audio files found in the specified path : \n{error_files_text}"
494
+
495
+ min_second = round(min(duration_list), 2)
496
+ max_second = round(max(duration_list), 2)
497
+
498
+ with ArrowWriter(path=file_raw, writer_batch_size=1) as writer:
499
+ for line in progress.tqdm(result, total=len(result), desc="prepare data"):
500
+ writer.write(line)
501
+
502
+ with open(file_duration, "w", encoding="utf-8") as f:
503
+ json.dump({"duration": duration_list}, f, ensure_ascii=False)
504
+
505
+ file_vocab_finetune = "data/Emilia_ZH_EN_pinyin/vocab.txt"
506
+ if not os.path.isfile(file_vocab_finetune):
507
+ return "Error: Vocabulary file 'Emilia_ZH_EN_pinyin' not found!"
508
+ shutil.copy2(file_vocab_finetune, file_vocab)
509
+
510
+ if error_files != []:
511
+ error_text = "error files\n" + "\n".join(error_files)
512
+ else:
513
+ error_text = ""
514
+
515
+ 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{error_text}"
516
+
517
+
518
+ def check_user(value):
519
+ return gr.update(visible=not value), gr.update(visible=value)
520
+
521
+
522
+ def calculate_train(
523
+ name_project,
524
+ batch_size_type,
525
+ max_samples,
526
+ learning_rate,
527
+ num_warmup_updates,
528
+ save_per_updates,
529
+ last_per_steps,
530
+ finetune,
531
+ ):
532
+ name_project += "_pinyin"
533
+ path_project = os.path.join(path_data, name_project)
534
+ file_duraction = os.path.join(path_project, "duration.json")
535
+
536
+ if not os.path.isfile(file_duraction):
537
+ return (
538
+ 1000,
539
+ max_samples,
540
+ num_warmup_updates,
541
+ save_per_updates,
542
+ last_per_steps,
543
+ "project not found !",
544
+ learning_rate,
545
+ )
546
+
547
+ with open(file_duraction, "r") as file:
548
+ data = json.load(file)
549
+
550
+ duration_list = data["duration"]
551
+
552
+ samples = len(duration_list)
553
+
554
+ if torch.cuda.is_available():
555
+ gpu_properties = torch.cuda.get_device_properties(0)
556
+ total_memory = gpu_properties.total_memory / (1024**3)
557
+ elif torch.backends.mps.is_available():
558
+ total_memory = psutil.virtual_memory().available / (1024**3)
559
+
560
+ if batch_size_type == "frame":
561
+ batch = int(total_memory * 0.5)
562
+ batch = (lambda num: num + 1 if num % 2 != 0 else num)(batch)
563
+ batch_size_per_gpu = int(38400 / batch)
564
+ else:
565
+ batch_size_per_gpu = int(total_memory / 8)
566
+ batch_size_per_gpu = (lambda num: num + 1 if num % 2 != 0 else num)(batch_size_per_gpu)
567
+ batch = batch_size_per_gpu
568
+
569
+ if batch_size_per_gpu <= 0:
570
+ batch_size_per_gpu = 1
571
+
572
+ if samples < 64:
573
+ max_samples = int(samples * 0.25)
574
+ else:
575
+ max_samples = 64
576
+
577
+ num_warmup_updates = int(samples * 0.05)
578
+ save_per_updates = int(samples * 0.10)
579
+ last_per_steps = int(save_per_updates * 5)
580
+
581
+ max_samples = (lambda num: num + 1 if num % 2 != 0 else num)(max_samples)
582
+ num_warmup_updates = (lambda num: num + 1 if num % 2 != 0 else num)(num_warmup_updates)
583
+ save_per_updates = (lambda num: num + 1 if num % 2 != 0 else num)(save_per_updates)
584
+ last_per_steps = (lambda num: num + 1 if num % 2 != 0 else num)(last_per_steps)
585
+
586
+ if finetune:
587
+ learning_rate = 1e-5
588
+ else:
589
+ learning_rate = 7.5e-5
590
+
591
+ return batch_size_per_gpu, max_samples, num_warmup_updates, save_per_updates, last_per_steps, samples, learning_rate
592
+
593
+
594
+ def extract_and_save_ema_model(checkpoint_path: str, new_checkpoint_path: str) -> None:
595
+ try:
596
+ checkpoint = torch.load(checkpoint_path)
597
+ print("Original Checkpoint Keys:", checkpoint.keys())
598
+
599
+ ema_model_state_dict = checkpoint.get("ema_model_state_dict", None)
600
+
601
+ if ema_model_state_dict is not None:
602
+ new_checkpoint = {"ema_model_state_dict": ema_model_state_dict}
603
+ torch.save(new_checkpoint, new_checkpoint_path)
604
+ return f"New checkpoint saved at: {new_checkpoint_path}"
605
+ else:
606
+ return "No 'ema_model_state_dict' found in the checkpoint."
607
+
608
+ except Exception as e:
609
+ return f"An error occurred: {e}"
610
+
611
+
612
+ def vocab_check(project_name):
613
+ name_project = project_name + "_pinyin"
614
+ path_project = os.path.join(path_data, name_project)
615
+
616
+ file_metadata = os.path.join(path_project, "metadata.csv")
617
+
618
+ file_vocab = "data/Emilia_ZH_EN_pinyin/vocab.txt"
619
+ if not os.path.isfile(file_vocab):
620
+ return f"the file {file_vocab} not found !"
621
+
622
+ with open(file_vocab, "r", encoding="utf-8") as f:
623
+ data = f.read()
624
+
625
+ vocab = data.split("\n")
626
+
627
+ if not os.path.isfile(file_metadata):
628
+ return f"the file {file_metadata} not found !"
629
+
630
+ with open(file_metadata, "r", encoding="utf-8") as f:
631
+ data = f.read()
632
+
633
+ miss_symbols = []
634
+ miss_symbols_keep = {}
635
+ for item in data.split("\n"):
636
+ sp = item.split("|")
637
+ if len(sp) != 2:
638
+ continue
639
+
640
+ text = sp[1].lower().strip()
641
+
642
+ for t in text:
643
+ if t not in vocab and t not in miss_symbols_keep:
644
+ miss_symbols.append(t)
645
+ miss_symbols_keep[t] = t
646
+ if miss_symbols == []:
647
+ info = "You can train using your language !"
648
+ else:
649
+ info = f"The following symbols are missing in your language : {len(miss_symbols)}\n\n" + "\n".join(miss_symbols)
650
+
651
+ return info
652
+
653
+
654
+ def get_random_sample_prepare(project_name):
655
+ name_project = project_name + "_pinyin"
656
+ path_project = os.path.join(path_data, name_project)
657
+ file_arrow = os.path.join(path_project, "raw.arrow")
658
+ if not os.path.isfile(file_arrow):
659
+ return "", None
660
+ dataset = Dataset_.from_file(file_arrow)
661
+ random_sample = dataset.shuffle(seed=random.randint(0, 1000)).select([0])
662
+ text = "[" + " , ".join(["' " + t + " '" for t in random_sample["text"][0]]) + "]"
663
+ audio_path = random_sample["audio_path"][0]
664
+ return text, audio_path
665
+
666
+
667
+ def get_random_sample_transcribe(project_name):
668
+ name_project = project_name + "_pinyin"
669
+ path_project = os.path.join(path_data, name_project)
670
+ file_metadata = os.path.join(path_project, "metadata.csv")
671
+ if not os.path.isfile(file_metadata):
672
+ return "", None
673
+
674
+ data = ""
675
+ with open(file_metadata, "r", encoding="utf-8") as f:
676
+ data = f.read()
677
+
678
+ list_data = []
679
+ for item in data.split("\n"):
680
+ sp = item.split("|")
681
+ if len(sp) != 2:
682
+ continue
683
+ list_data.append([os.path.join(path_project, "wavs", sp[0] + ".wav"), sp[1]])
684
+
685
+ if list_data == []:
686
+ return "", None
687
+
688
+ random_item = random.choice(list_data)
689
+
690
+ return random_item[1], random_item[0]
691
+
692
+
693
+ def get_random_sample_infer(project_name):
694
+ text, audio = get_random_sample_transcribe(project_name)
695
+ return (
696
+ text,
697
+ text,
698
+ audio,
699
+ )
700
+
701
+
702
+ def infer(file_checkpoint, exp_name, ref_text, ref_audio, gen_text, nfe_step):
703
+ global last_checkpoint, last_device, tts_api
704
+
705
+ if not os.path.isfile(file_checkpoint):
706
+ return None
707
+
708
+ if training_process is not None:
709
+ device_test = "cpu"
710
+ else:
711
+ device_test = None
712
+
713
+ if last_checkpoint != file_checkpoint or last_device != device_test:
714
+ if last_checkpoint != file_checkpoint:
715
+ last_checkpoint = file_checkpoint
716
+ if last_device != device_test:
717
+ last_device = device_test
718
+
719
+ tts_api = F5TTS(model_type=exp_name, ckpt_file=file_checkpoint, device=device_test)
720
+
721
+ print("update", device_test, file_checkpoint)
722
+
723
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
724
+ tts_api.infer(gen_text=gen_text, ref_text=ref_text, ref_file=ref_audio, nfe_step=nfe_step, file_wave=f.name)
725
+ return f.name
726
+
727
+
728
+ with gr.Blocks() as app:
729
+ with gr.Row():
730
+ project_name = gr.Textbox(label="project name", value="my_speak")
731
+ bt_create = gr.Button("create new project")
732
+
733
+ bt_create.click(fn=create_data_project, inputs=[project_name])
734
+
735
+ with gr.Tabs():
736
+ with gr.TabItem("transcribe Data"):
737
+ ch_manual = gr.Checkbox(label="user", value=False)
738
+
739
+ mark_info_transcribe = gr.Markdown(
740
+ """```plaintext
741
+ Place your 'wavs' folder and 'metadata.csv' file in the {your_project_name}' directory.
742
+
743
+ my_speak/
744
+
745
+ └── dataset/
746
+ ├── audio1.wav
747
+ └── audio2.wav
748
+ ...
749
+ ```""",
750
+ visible=False,
751
+ )
752
+
753
+ audio_speaker = gr.File(label="voice", type="filepath", file_count="multiple")
754
+ txt_lang = gr.Text(label="Language", value="english")
755
+ bt_transcribe = bt_create = gr.Button("transcribe")
756
+ txt_info_transcribe = gr.Text(label="info", value="")
757
+ bt_transcribe.click(
758
+ fn=transcribe_all,
759
+ inputs=[project_name, audio_speaker, txt_lang, ch_manual],
760
+ outputs=[txt_info_transcribe],
761
+ )
762
+ ch_manual.change(fn=check_user, inputs=[ch_manual], outputs=[audio_speaker, mark_info_transcribe])
763
+
764
+ random_sample_transcribe = gr.Button("random sample")
765
+
766
+ with gr.Row():
767
+ random_text_transcribe = gr.Text(label="Text")
768
+ random_audio_transcribe = gr.Audio(label="Audio", type="filepath")
769
+
770
+ random_sample_transcribe.click(
771
+ fn=get_random_sample_transcribe,
772
+ inputs=[project_name],
773
+ outputs=[random_text_transcribe, random_audio_transcribe],
774
+ )
775
+
776
+ with gr.TabItem("prepare Data"):
777
+ gr.Markdown(
778
+ """```plaintext
779
+ place all your wavs folder and your metadata.csv file in {your name project}
780
+ my_speak/
781
+
782
+ ├── wavs/
783
+ │ ├── audio1.wav
784
+ │ └── audio2.wav
785
+ | ...
786
+
787
+ └── metadata.csv
788
+
789
+ file format metadata.csv
790
+
791
+ audio1|text1
792
+ audio2|text1
793
+ ...
794
+
795
+ ```"""
796
+ )
797
+
798
+ bt_prepare = bt_create = gr.Button("prepare")
799
+ txt_info_prepare = gr.Text(label="info", value="")
800
+ bt_prepare.click(fn=create_metadata, inputs=[project_name], outputs=[txt_info_prepare])
801
+
802
+ random_sample_prepare = gr.Button("random sample")
803
+
804
+ with gr.Row():
805
+ random_text_prepare = gr.Text(label="Pinyin")
806
+ random_audio_prepare = gr.Audio(label="Audio", type="filepath")
807
+
808
+ random_sample_prepare.click(
809
+ fn=get_random_sample_prepare, inputs=[project_name], outputs=[random_text_prepare, random_audio_prepare]
810
+ )
811
+
812
+ with gr.TabItem("train Data"):
813
+ with gr.Row():
814
+ bt_calculate = bt_create = gr.Button("Auto Settings")
815
+ ch_finetune = bt_create = gr.Checkbox(label="finetune", value=True)
816
+ lb_samples = gr.Label(label="samples")
817
+ batch_size_type = gr.Radio(label="Batch Size Type", choices=["frame", "sample"], value="frame")
818
+
819
+ with gr.Row():
820
+ exp_name = gr.Radio(label="Model", choices=["F5TTS_Base", "E2TTS_Base"], value="F5TTS_Base")
821
+ learning_rate = gr.Number(label="Learning Rate", value=1e-5, step=1e-5)
822
+
823
+ with gr.Row():
824
+ batch_size_per_gpu = gr.Number(label="Batch Size per GPU", value=1000)
825
+ max_samples = gr.Number(label="Max Samples", value=64)
826
+
827
+ with gr.Row():
828
+ grad_accumulation_steps = gr.Number(label="Gradient Accumulation Steps", value=1)
829
+ max_grad_norm = gr.Number(label="Max Gradient Norm", value=1.0)
830
+
831
+ with gr.Row():
832
+ epochs = gr.Number(label="Epochs", value=10)
833
+ num_warmup_updates = gr.Number(label="Warmup Updates", value=5)
834
+
835
+ with gr.Row():
836
+ save_per_updates = gr.Number(label="Save per Updates", value=10)
837
+ last_per_steps = gr.Number(label="Last per Steps", value=50)
838
+
839
+ with gr.Row():
840
+ start_button = gr.Button("Start Training")
841
+ stop_button = gr.Button("Stop Training", interactive=False)
842
+
843
+ txt_info_train = gr.Text(label="info", value="")
844
+ start_button.click(
845
+ fn=start_training,
846
+ inputs=[
847
+ project_name,
848
+ exp_name,
849
+ learning_rate,
850
+ batch_size_per_gpu,
851
+ batch_size_type,
852
+ max_samples,
853
+ grad_accumulation_steps,
854
+ max_grad_norm,
855
+ epochs,
856
+ num_warmup_updates,
857
+ save_per_updates,
858
+ last_per_steps,
859
+ ch_finetune,
860
+ ],
861
+ outputs=[txt_info_train, start_button, stop_button],
862
+ )
863
+ stop_button.click(fn=stop_training, outputs=[txt_info_train, start_button, stop_button])
864
+ bt_calculate.click(
865
+ fn=calculate_train,
866
+ inputs=[
867
+ project_name,
868
+ batch_size_type,
869
+ max_samples,
870
+ learning_rate,
871
+ num_warmup_updates,
872
+ save_per_updates,
873
+ last_per_steps,
874
+ ch_finetune,
875
+ ],
876
+ outputs=[
877
+ batch_size_per_gpu,
878
+ max_samples,
879
+ num_warmup_updates,
880
+ save_per_updates,
881
+ last_per_steps,
882
+ lb_samples,
883
+ learning_rate,
884
+ ],
885
+ )
886
+
887
+ with gr.TabItem("reduse checkpoint"):
888
+ txt_path_checkpoint = gr.Text(label="path checkpoint :")
889
+ txt_path_checkpoint_small = gr.Text(label="path output :")
890
+ txt_info_reduse = gr.Text(label="info", value="")
891
+ reduse_button = gr.Button("reduse")
892
+ reduse_button.click(
893
+ fn=extract_and_save_ema_model,
894
+ inputs=[txt_path_checkpoint, txt_path_checkpoint_small],
895
+ outputs=[txt_info_reduse],
896
+ )
897
+
898
+ with gr.TabItem("vocab check experiment"):
899
+ check_button = gr.Button("check vocab")
900
+ txt_info_check = gr.Text(label="info", value="")
901
+ check_button.click(fn=vocab_check, inputs=[project_name], outputs=[txt_info_check])
902
+
903
+ with gr.TabItem("test model"):
904
+ exp_name = gr.Radio(label="Model", choices=["F5-TTS", "E2-TTS"], value="F5-TTS")
905
+ nfe_step = gr.Number(label="n_step", value=32)
906
+ file_checkpoint_pt = gr.Textbox(label="Checkpoint", value="")
907
+
908
+ random_sample_infer = gr.Button("random sample")
909
+
910
+ ref_text = gr.Textbox(label="ref text")
911
+ ref_audio = gr.Audio(label="audio ref", type="filepath")
912
+ gen_text = gr.Textbox(label="gen text")
913
+ random_sample_infer.click(
914
+ fn=get_random_sample_infer, inputs=[project_name], outputs=[ref_text, gen_text, ref_audio]
915
+ )
916
+ check_button_infer = gr.Button("infer")
917
+ gen_audio = gr.Audio(label="audio gen", type="filepath")
918
+
919
+ check_button_infer.click(
920
+ fn=infer,
921
+ inputs=[file_checkpoint_pt, exp_name, ref_text, ref_audio, gen_text, nfe_step],
922
+ outputs=[gen_audio],
923
+ )
924
+
925
+
926
+ @click.command()
927
+ @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
928
+ @click.option("--host", "-H", default=None, help="Host to run the app on")
929
+ @click.option(
930
+ "--share",
931
+ "-s",
932
+ default=False,
933
+ is_flag=True,
934
+ help="Share the app via Gradio share link",
935
+ )
936
+ @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
937
+ def main(port, host, share, api):
938
+ global app
939
+ print("Starting app...")
940
+ app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api)
941
+
942
+
943
+ if __name__ == "__main__":
944
+ main()
gradio_app.py ADDED
@@ -0,0 +1,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import torch
4
+ import torchaudio
5
+ import gradio as gr
6
+ import numpy as np
7
+ import tempfile
8
+ from einops import rearrange
9
+ from vocos import Vocos
10
+ from pydub import AudioSegment, silence
11
+ from model import CFM, UNetT, DiT, MMDiT
12
+ from cached_path import cached_path
13
+ from model.utils import (
14
+ load_checkpoint,
15
+ get_tokenizer,
16
+ convert_char_to_pinyin,
17
+ save_spectrogram,
18
+ )
19
+ from transformers import pipeline
20
+ import librosa
21
+ import click
22
+ import soundfile as sf
23
+
24
+ try:
25
+ import spaces
26
+ USING_SPACES = True
27
+ except ImportError:
28
+ USING_SPACES = False
29
+
30
+ def gpu_decorator(func):
31
+ if USING_SPACES:
32
+ return spaces.GPU(func)
33
+ else:
34
+ return func
35
+
36
+
37
+
38
+ SPLIT_WORDS = [
39
+ "but", "however", "nevertheless", "yet", "still",
40
+ "therefore", "thus", "hence", "consequently",
41
+ "moreover", "furthermore", "additionally",
42
+ "meanwhile", "alternatively", "otherwise",
43
+ "namely", "specifically", "for example", "such as",
44
+ "in fact", "indeed", "notably",
45
+ "in contrast", "on the other hand", "conversely",
46
+ "in conclusion", "to summarize", "finally"
47
+ ]
48
+
49
+ device = (
50
+ "cuda"
51
+ if torch.cuda.is_available()
52
+ else "mps" if torch.backends.mps.is_available() else "cpu"
53
+ )
54
+
55
+ print(f"Using {device} device")
56
+
57
+ pipe = pipeline(
58
+ "automatic-speech-recognition",
59
+ model="openai/whisper-large-v3-turbo",
60
+ torch_dtype=torch.float16,
61
+ device=device,
62
+ )
63
+ vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
64
+
65
+ # --------------------- Settings -------------------- #
66
+
67
+ target_sample_rate = 24000
68
+ n_mel_channels = 100
69
+ hop_length = 256
70
+ target_rms = 0.1
71
+ nfe_step = 32 # 16, 32
72
+ cfg_strength = 2.0
73
+ ode_method = "euler"
74
+ sway_sampling_coef = -1.0
75
+ speed = 1.0
76
+ # fix_duration = 27 # None or float (duration in seconds)
77
+ fix_duration = None
78
+
79
+
80
+ def load_model(repo_name, exp_name, model_cls, model_cfg, ckpt_step):
81
+ ckpt_path = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
82
+ # ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors
83
+ vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
84
+ model = CFM(
85
+ transformer=model_cls(
86
+ **model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels
87
+ ),
88
+ mel_spec_kwargs=dict(
89
+ target_sample_rate=target_sample_rate,
90
+ n_mel_channels=n_mel_channels,
91
+ hop_length=hop_length,
92
+ ),
93
+ odeint_kwargs=dict(
94
+ method=ode_method,
95
+ ),
96
+ vocab_char_map=vocab_char_map,
97
+ ).to(device)
98
+
99
+ model = load_checkpoint(model, ckpt_path, device, use_ema = True)
100
+
101
+ return model
102
+
103
+
104
+ # load models
105
+ F5TTS_model_cfg = dict(
106
+ dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4
107
+ )
108
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
109
+
110
+ F5TTS_ema_model = load_model(
111
+ "F5-TTS", "F5TTS_Base", DiT, F5TTS_model_cfg, 1200000
112
+ )
113
+ E2TTS_ema_model = load_model(
114
+ "E2-TTS", "E2TTS_Base", UNetT, E2TTS_model_cfg, 1200000
115
+ )
116
+
117
+ def split_text_into_batches(text, max_chars=200, split_words=SPLIT_WORDS):
118
+ if len(text.encode('utf-8')) <= max_chars:
119
+ return [text]
120
+ if text[-1] not in ['。', '.', '!', '!', '?', '?']:
121
+ text += '.'
122
+
123
+ sentences = re.split('([。.!?!?])', text)
124
+ sentences = [''.join(i) for i in zip(sentences[0::2], sentences[1::2])]
125
+
126
+ batches = []
127
+ current_batch = ""
128
+
129
+ def split_by_words(text):
130
+ words = text.split()
131
+ current_word_part = ""
132
+ word_batches = []
133
+ for word in words:
134
+ if len(current_word_part.encode('utf-8')) + len(word.encode('utf-8')) + 1 <= max_chars:
135
+ current_word_part += word + ' '
136
+ else:
137
+ if current_word_part:
138
+ # Try to find a suitable split word
139
+ for split_word in split_words:
140
+ split_index = current_word_part.rfind(' ' + split_word + ' ')
141
+ if split_index != -1:
142
+ word_batches.append(current_word_part[:split_index].strip())
143
+ current_word_part = current_word_part[split_index:].strip() + ' '
144
+ break
145
+ else:
146
+ # If no suitable split word found, just append the current part
147
+ word_batches.append(current_word_part.strip())
148
+ current_word_part = ""
149
+ current_word_part += word + ' '
150
+ if current_word_part:
151
+ word_batches.append(current_word_part.strip())
152
+ return word_batches
153
+
154
+ for sentence in sentences:
155
+ if len(current_batch.encode('utf-8')) + len(sentence.encode('utf-8')) <= max_chars:
156
+ current_batch += sentence
157
+ else:
158
+ # If adding this sentence would exceed the limit
159
+ if current_batch:
160
+ batches.append(current_batch)
161
+ current_batch = ""
162
+
163
+ # If the sentence itself is longer than max_chars, split it
164
+ if len(sentence.encode('utf-8')) > max_chars:
165
+ # First, try to split by colon
166
+ colon_parts = sentence.split(':')
167
+ if len(colon_parts) > 1:
168
+ for part in colon_parts:
169
+ if len(part.encode('utf-8')) <= max_chars:
170
+ batches.append(part)
171
+ else:
172
+ # If colon part is still too long, split by comma
173
+ comma_parts = re.split('[,,]', part)
174
+ if len(comma_parts) > 1:
175
+ current_comma_part = ""
176
+ for comma_part in comma_parts:
177
+ if len(current_comma_part.encode('utf-8')) + len(comma_part.encode('utf-8')) <= max_chars:
178
+ current_comma_part += comma_part + ','
179
+ else:
180
+ if current_comma_part:
181
+ batches.append(current_comma_part.rstrip(','))
182
+ current_comma_part = comma_part + ','
183
+ if current_comma_part:
184
+ batches.append(current_comma_part.rstrip(','))
185
+ else:
186
+ # If no comma, split by words
187
+ batches.extend(split_by_words(part))
188
+ else:
189
+ # If no colon, split by comma
190
+ comma_parts = re.split('[,,]', sentence)
191
+ if len(comma_parts) > 1:
192
+ current_comma_part = ""
193
+ for comma_part in comma_parts:
194
+ if len(current_comma_part.encode('utf-8')) + len(comma_part.encode('utf-8')) <= max_chars:
195
+ current_comma_part += comma_part + ','
196
+ else:
197
+ if current_comma_part:
198
+ batches.append(current_comma_part.rstrip(','))
199
+ current_comma_part = comma_part + ','
200
+ if current_comma_part:
201
+ batches.append(current_comma_part.rstrip(','))
202
+ else:
203
+ # If no comma, split by words
204
+ batches.extend(split_by_words(sentence))
205
+ else:
206
+ current_batch = sentence
207
+
208
+ if current_batch:
209
+ batches.append(current_batch)
210
+
211
+ return batches
212
+
213
+ def infer_batch(ref_audio, ref_text, gen_text_batches, exp_name, remove_silence, progress=gr.Progress()):
214
+ if exp_name == "F5-TTS":
215
+ ema_model = F5TTS_ema_model
216
+ elif exp_name == "E2-TTS":
217
+ ema_model = E2TTS_ema_model
218
+
219
+ audio, sr = ref_audio
220
+ if audio.shape[0] > 1:
221
+ audio = torch.mean(audio, dim=0, keepdim=True)
222
+
223
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
224
+ if rms < target_rms:
225
+ audio = audio * target_rms / rms
226
+ if sr != target_sample_rate:
227
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
228
+ audio = resampler(audio)
229
+ audio = audio.to(device)
230
+
231
+ generated_waves = []
232
+ spectrograms = []
233
+
234
+ for i, gen_text in enumerate(progress.tqdm(gen_text_batches)):
235
+ # Prepare the text
236
+ if len(ref_text[-1].encode('utf-8')) == 1:
237
+ ref_text = ref_text + " "
238
+ text_list = [ref_text + gen_text]
239
+ final_text_list = convert_char_to_pinyin(text_list)
240
+
241
+ # Calculate duration
242
+ ref_audio_len = audio.shape[-1] // hop_length
243
+ zh_pause_punc = r"。,、;:?!"
244
+ ref_text_len = len(ref_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, ref_text))
245
+ gen_text_len = len(gen_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, gen_text))
246
+ duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
247
+
248
+ # inference
249
+ with torch.inference_mode():
250
+ generated, _ = ema_model.sample(
251
+ cond=audio,
252
+ text=final_text_list,
253
+ duration=duration,
254
+ steps=nfe_step,
255
+ cfg_strength=cfg_strength,
256
+ sway_sampling_coef=sway_sampling_coef,
257
+ )
258
+
259
+ generated = generated[:, ref_audio_len:, :]
260
+ generated_mel_spec = rearrange(generated, "1 n d -> 1 d n")
261
+ generated_wave = vocos.decode(generated_mel_spec.cpu())
262
+ if rms < target_rms:
263
+ generated_wave = generated_wave * rms / target_rms
264
+
265
+ # wav -> numpy
266
+ generated_wave = generated_wave.squeeze().cpu().numpy()
267
+
268
+ generated_waves.append(generated_wave)
269
+ spectrograms.append(generated_mel_spec[0].cpu().numpy())
270
+
271
+ # Combine all generated waves
272
+ final_wave = np.concatenate(generated_waves)
273
+
274
+ # Remove silence
275
+ if remove_silence:
276
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
277
+ sf.write(f.name, final_wave, target_sample_rate)
278
+ aseg = AudioSegment.from_file(f.name)
279
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
280
+ non_silent_wave = AudioSegment.silent(duration=0)
281
+ for non_silent_seg in non_silent_segs:
282
+ non_silent_wave += non_silent_seg
283
+ aseg = non_silent_wave
284
+ aseg.export(f.name, format="wav")
285
+ final_wave, _ = torchaudio.load(f.name)
286
+ final_wave = final_wave.squeeze().cpu().numpy()
287
+
288
+ # Create a combined spectrogram
289
+ combined_spectrogram = np.concatenate(spectrograms, axis=1)
290
+
291
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
292
+ spectrogram_path = tmp_spectrogram.name
293
+ save_spectrogram(combined_spectrogram, spectrogram_path)
294
+
295
+ return (target_sample_rate, final_wave), spectrogram_path
296
+
297
+ def infer(ref_audio_orig, ref_text, gen_text, exp_name, remove_silence, custom_split_words=''):
298
+ if not custom_split_words.strip():
299
+ custom_words = [word.strip() for word in custom_split_words.split(',')]
300
+ global SPLIT_WORDS
301
+ SPLIT_WORDS = custom_words
302
+
303
+ print(gen_text)
304
+
305
+ gr.Info("Converting audio...")
306
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
307
+ aseg = AudioSegment.from_file(ref_audio_orig)
308
+
309
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
310
+ non_silent_wave = AudioSegment.silent(duration=0)
311
+ for non_silent_seg in non_silent_segs:
312
+ non_silent_wave += non_silent_seg
313
+ aseg = non_silent_wave
314
+
315
+ audio_duration = len(aseg)
316
+ if audio_duration > 15000:
317
+ gr.Warning("Audio is over 15s, clipping to only first 15s.")
318
+ aseg = aseg[:15000]
319
+ aseg.export(f.name, format="wav")
320
+ ref_audio = f.name
321
+
322
+ if not ref_text.strip():
323
+ gr.Info("No reference text provided, transcribing reference audio...")
324
+ ref_text = pipe(
325
+ ref_audio,
326
+ chunk_length_s=30,
327
+ batch_size=128,
328
+ generate_kwargs={"task": "transcribe"},
329
+ return_timestamps=False,
330
+ )["text"].strip()
331
+ gr.Info("Finished transcription")
332
+ else:
333
+ gr.Info("Using custom reference text...")
334
+
335
+ # Split the input text into batches
336
+ audio, sr = torchaudio.load(ref_audio)
337
+ max_chars = int(len(ref_text.encode('utf-8')) / (audio.shape[-1] / sr) * (30 - audio.shape[-1] / sr))
338
+ gen_text_batches = split_text_into_batches(gen_text, max_chars=max_chars)
339
+ print('ref_text', ref_text)
340
+ for i, gen_text in enumerate(gen_text_batches):
341
+ print(f'gen_text {i}', gen_text)
342
+
343
+ gr.Info(f"Generating audio using {exp_name} in {len(gen_text_batches)} batches")
344
+ return infer_batch((audio, sr), ref_text, gen_text_batches, exp_name, remove_silence)
345
+
346
+ def generate_podcast(script, speaker1_name, ref_audio1, ref_text1, speaker2_name, ref_audio2, ref_text2, exp_name, remove_silence):
347
+ # Split the script into speaker blocks
348
+ speaker_pattern = re.compile(f"^({re.escape(speaker1_name)}|{re.escape(speaker2_name)}):", re.MULTILINE)
349
+ speaker_blocks = speaker_pattern.split(script)[1:] # Skip the first empty element
350
+
351
+ generated_audio_segments = []
352
+
353
+ for i in range(0, len(speaker_blocks), 2):
354
+ speaker = speaker_blocks[i]
355
+ text = speaker_blocks[i+1].strip()
356
+
357
+ # Determine which speaker is talking
358
+ if speaker == speaker1_name:
359
+ ref_audio = ref_audio1
360
+ ref_text = ref_text1
361
+ elif speaker == speaker2_name:
362
+ ref_audio = ref_audio2
363
+ ref_text = ref_text2
364
+ else:
365
+ continue # Skip if the speaker is neither speaker1 nor speaker2
366
+
367
+ # Generate audio for this block
368
+ audio, _ = infer(ref_audio, ref_text, text, exp_name, remove_silence)
369
+
370
+ # Convert the generated audio to a numpy array
371
+ sr, audio_data = audio
372
+
373
+ # Save the audio data as a WAV file
374
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
375
+ sf.write(temp_file.name, audio_data, sr)
376
+ audio_segment = AudioSegment.from_wav(temp_file.name)
377
+
378
+ generated_audio_segments.append(audio_segment)
379
+
380
+ # Add a short pause between speakers
381
+ pause = AudioSegment.silent(duration=500) # 500ms pause
382
+ generated_audio_segments.append(pause)
383
+
384
+ # Concatenate all audio segments
385
+ final_podcast = sum(generated_audio_segments)
386
+
387
+ # Export the final podcast
388
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
389
+ podcast_path = temp_file.name
390
+ final_podcast.export(podcast_path, format="wav")
391
+
392
+ return podcast_path
393
+
394
+ def parse_speechtypes_text(gen_text):
395
+ # Pattern to find (Emotion)
396
+ pattern = r'\((.*?)\)'
397
+
398
+ # Split the text by the pattern
399
+ tokens = re.split(pattern, gen_text)
400
+
401
+ segments = []
402
+
403
+ current_emotion = 'Regular'
404
+
405
+ for i in range(len(tokens)):
406
+ if i % 2 == 0:
407
+ # This is text
408
+ text = tokens[i].strip()
409
+ if text:
410
+ segments.append({'emotion': current_emotion, 'text': text})
411
+ else:
412
+ # This is emotion
413
+ emotion = tokens[i].strip()
414
+ current_emotion = emotion
415
+
416
+ return segments
417
+
418
+ def update_speed(new_speed):
419
+ global speed
420
+ speed = new_speed
421
+ return f"Speed set to: {speed}"
422
+
423
+ with gr.Blocks() as app_credits:
424
+ gr.Markdown("""
425
+ # Credits
426
+
427
+ * [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
428
+ * [RootingInLoad](https://github.com/RootingInLoad) for the podcast generation
429
+ """)
430
+ with gr.Blocks() as app_tts:
431
+ gr.Markdown("# Batched TTS")
432
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
433
+ gen_text_input = gr.Textbox(label="Text to Generate", lines=10)
434
+ model_choice = gr.Radio(
435
+ choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
436
+ )
437
+ generate_btn = gr.Button("Synthesize", variant="primary")
438
+ with gr.Accordion("Advanced Settings", open=False):
439
+ ref_text_input = gr.Textbox(
440
+ label="Reference Text",
441
+ info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.",
442
+ lines=2,
443
+ )
444
+ remove_silence = gr.Checkbox(
445
+ label="Remove Silences",
446
+ info="The model tends to produce silences, especially on longer audio. We can manually remove silences if needed. Note that this is an experimental feature and may produce strange results. This will also increase generation time.",
447
+ value=True,
448
+ )
449
+ split_words_input = gr.Textbox(
450
+ label="Custom Split Words",
451
+ info="Enter custom words to split on, separated by commas. Leave blank to use default list.",
452
+ lines=2,
453
+ )
454
+ speed_slider = gr.Slider(
455
+ label="Speed",
456
+ minimum=0.3,
457
+ maximum=2.0,
458
+ value=speed,
459
+ step=0.1,
460
+ info="Adjust the speed of the audio.",
461
+ )
462
+ speed_slider.change(update_speed, inputs=speed_slider)
463
+
464
+ audio_output = gr.Audio(label="Synthesized Audio")
465
+ spectrogram_output = gr.Image(label="Spectrogram")
466
+
467
+ generate_btn.click(
468
+ infer,
469
+ inputs=[
470
+ ref_audio_input,
471
+ ref_text_input,
472
+ gen_text_input,
473
+ model_choice,
474
+ remove_silence,
475
+ split_words_input,
476
+ ],
477
+ outputs=[audio_output, spectrogram_output],
478
+ )
479
+
480
+ with gr.Blocks() as app_podcast:
481
+ gr.Markdown("# Podcast Generation")
482
+ speaker1_name = gr.Textbox(label="Speaker 1 Name")
483
+ ref_audio_input1 = gr.Audio(label="Reference Audio (Speaker 1)", type="filepath")
484
+ ref_text_input1 = gr.Textbox(label="Reference Text (Speaker 1)", lines=2)
485
+
486
+ speaker2_name = gr.Textbox(label="Speaker 2 Name")
487
+ ref_audio_input2 = gr.Audio(label="Reference Audio (Speaker 2)", type="filepath")
488
+ ref_text_input2 = gr.Textbox(label="Reference Text (Speaker 2)", lines=2)
489
+
490
+ script_input = gr.Textbox(label="Podcast Script", lines=10,
491
+ placeholder="Enter the script with speaker names at the start of each block, e.g.:\nSean: How did you start studying...\n\nMeghan: I came to my interest in technology...\nIt was a long journey...\n\nSean: That's fascinating. Can you elaborate...")
492
+
493
+ podcast_model_choice = gr.Radio(
494
+ choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
495
+ )
496
+ podcast_remove_silence = gr.Checkbox(
497
+ label="Remove Silences",
498
+ value=True,
499
+ )
500
+ generate_podcast_btn = gr.Button("Generate Podcast", variant="primary")
501
+ podcast_output = gr.Audio(label="Generated Podcast")
502
+
503
+ def podcast_generation(script, speaker1, ref_audio1, ref_text1, speaker2, ref_audio2, ref_text2, model, remove_silence):
504
+ return generate_podcast(script, speaker1, ref_audio1, ref_text1, speaker2, ref_audio2, ref_text2, model, remove_silence)
505
+
506
+ generate_podcast_btn.click(
507
+ podcast_generation,
508
+ inputs=[
509
+ script_input,
510
+ speaker1_name,
511
+ ref_audio_input1,
512
+ ref_text_input1,
513
+ speaker2_name,
514
+ ref_audio_input2,
515
+ ref_text_input2,
516
+ podcast_model_choice,
517
+ podcast_remove_silence,
518
+ ],
519
+ outputs=podcast_output,
520
+ )
521
+
522
+ def parse_emotional_text(gen_text):
523
+ # Pattern to find (Emotion)
524
+ pattern = r'\((.*?)\)'
525
+
526
+ # Split the text by the pattern
527
+ tokens = re.split(pattern, gen_text)
528
+
529
+ segments = []
530
+
531
+ current_emotion = 'Regular'
532
+
533
+ for i in range(len(tokens)):
534
+ if i % 2 == 0:
535
+ # This is text
536
+ text = tokens[i].strip()
537
+ if text:
538
+ segments.append({'emotion': current_emotion, 'text': text})
539
+ else:
540
+ # This is emotion
541
+ emotion = tokens[i].strip()
542
+ current_emotion = emotion
543
+
544
+ return segments
545
+
546
+ with gr.Blocks() as app_emotional:
547
+ # New section for emotional generation
548
+ gr.Markdown(
549
+ """
550
+ # Multiple Speech-Type Generation
551
+
552
+ This section allows you to upload different audio clips for each speech type. 'Regular' emotion is mandatory. You can add additional speech types by clicking the "Add Speech Type" button. Enter your text in the format shown below, and the system will generate speech using the appropriate emotions. If unspecified, the model will use the regular speech type. The current speech type will be used until the next speech type is specified.
553
+
554
+ **Example Input:**
555
+
556
+ (Regular) Hello, I'd like to order a sandwich please. (Surprised) What do you mean you're out of bread? (Sad) I really wanted a sandwich though... (Angry) You know what, darn you and your little shop, you suck! (Whisper) I'll just go back home and cry now. (Shouting) Why me?!
557
+ """
558
+ )
559
+
560
+ gr.Markdown("Upload different audio clips for each speech type. 'Regular' emotion is mandatory. You can add additional speech types by clicking the 'Add Speech Type' button.")
561
+
562
+ # Regular speech type (mandatory)
563
+ with gr.Row():
564
+ regular_name = gr.Textbox(value='Regular', label='Speech Type Name', interactive=False)
565
+ regular_audio = gr.Audio(label='Regular Reference Audio', type='filepath')
566
+ regular_ref_text = gr.Textbox(label='Reference Text (Regular)', lines=2)
567
+
568
+ # Additional speech types (up to 9 more)
569
+ max_speech_types = 10
570
+ speech_type_names = []
571
+ speech_type_audios = []
572
+ speech_type_ref_texts = []
573
+ speech_type_delete_btns = []
574
+
575
+ for i in range(max_speech_types - 1):
576
+ with gr.Row():
577
+ name_input = gr.Textbox(label='Speech Type Name', visible=False)
578
+ audio_input = gr.Audio(label='Reference Audio', type='filepath', visible=False)
579
+ ref_text_input = gr.Textbox(label='Reference Text', lines=2, visible=False)
580
+ delete_btn = gr.Button("Delete", variant="secondary", visible=False)
581
+ speech_type_names.append(name_input)
582
+ speech_type_audios.append(audio_input)
583
+ speech_type_ref_texts.append(ref_text_input)
584
+ speech_type_delete_btns.append(delete_btn)
585
+
586
+ # Button to add speech type
587
+ add_speech_type_btn = gr.Button("Add Speech Type")
588
+
589
+ # Keep track of current number of speech types
590
+ speech_type_count = gr.State(value=0)
591
+
592
+ # Function to add a speech type
593
+ def add_speech_type_fn(speech_type_count):
594
+ if speech_type_count < max_speech_types - 1:
595
+ speech_type_count += 1
596
+ # Prepare updates for the components
597
+ name_updates = []
598
+ audio_updates = []
599
+ ref_text_updates = []
600
+ delete_btn_updates = []
601
+ for i in range(max_speech_types - 1):
602
+ if i < speech_type_count:
603
+ name_updates.append(gr.update(visible=True))
604
+ audio_updates.append(gr.update(visible=True))
605
+ ref_text_updates.append(gr.update(visible=True))
606
+ delete_btn_updates.append(gr.update(visible=True))
607
+ else:
608
+ name_updates.append(gr.update())
609
+ audio_updates.append(gr.update())
610
+ ref_text_updates.append(gr.update())
611
+ delete_btn_updates.append(gr.update())
612
+ else:
613
+ # Optionally, show a warning
614
+ # gr.Warning("Maximum number of speech types reached.")
615
+ name_updates = [gr.update() for _ in range(max_speech_types - 1)]
616
+ audio_updates = [gr.update() for _ in range(max_speech_types - 1)]
617
+ ref_text_updates = [gr.update() for _ in range(max_speech_types - 1)]
618
+ delete_btn_updates = [gr.update() for _ in range(max_speech_types - 1)]
619
+ return [speech_type_count] + name_updates + audio_updates + ref_text_updates + delete_btn_updates
620
+
621
+ add_speech_type_btn.click(
622
+ add_speech_type_fn,
623
+ inputs=speech_type_count,
624
+ outputs=[speech_type_count] + speech_type_names + speech_type_audios + speech_type_ref_texts + speech_type_delete_btns
625
+ )
626
+
627
+ # Function to delete a speech type
628
+ def make_delete_speech_type_fn(index):
629
+ def delete_speech_type_fn(speech_type_count):
630
+ # Prepare updates
631
+ name_updates = []
632
+ audio_updates = []
633
+ ref_text_updates = []
634
+ delete_btn_updates = []
635
+
636
+ for i in range(max_speech_types - 1):
637
+ if i == index:
638
+ name_updates.append(gr.update(visible=False, value=''))
639
+ audio_updates.append(gr.update(visible=False, value=None))
640
+ ref_text_updates.append(gr.update(visible=False, value=''))
641
+ delete_btn_updates.append(gr.update(visible=False))
642
+ else:
643
+ name_updates.append(gr.update())
644
+ audio_updates.append(gr.update())
645
+ ref_text_updates.append(gr.update())
646
+ delete_btn_updates.append(gr.update())
647
+
648
+ speech_type_count = max(0, speech_type_count - 1)
649
+
650
+ return [speech_type_count] + name_updates + audio_updates + ref_text_updates + delete_btn_updates
651
+
652
+ return delete_speech_type_fn
653
+
654
+ for i, delete_btn in enumerate(speech_type_delete_btns):
655
+ delete_fn = make_delete_speech_type_fn(i)
656
+ delete_btn.click(
657
+ delete_fn,
658
+ inputs=speech_type_count,
659
+ outputs=[speech_type_count] + speech_type_names + speech_type_audios + speech_type_ref_texts + speech_type_delete_btns
660
+ )
661
+
662
+ # Text input for the prompt
663
+ gen_text_input_emotional = gr.Textbox(label="Text to Generate", lines=10)
664
+
665
+ # Model choice
666
+ model_choice_emotional = gr.Radio(
667
+ choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
668
+ )
669
+
670
+ with gr.Accordion("Advanced Settings", open=False):
671
+ remove_silence_emotional = gr.Checkbox(
672
+ label="Remove Silences",
673
+ value=True,
674
+ )
675
+
676
+ # Generate button
677
+ generate_emotional_btn = gr.Button("Generate Emotional Speech", variant="primary")
678
+
679
+ # Output audio
680
+ audio_output_emotional = gr.Audio(label="Synthesized Audio")
681
+
682
+ def generate_emotional_speech(
683
+ regular_audio,
684
+ regular_ref_text,
685
+ gen_text,
686
+ *args,
687
+ ):
688
+ num_additional_speech_types = max_speech_types - 1
689
+ speech_type_names_list = args[:num_additional_speech_types]
690
+ speech_type_audios_list = args[num_additional_speech_types:2 * num_additional_speech_types]
691
+ speech_type_ref_texts_list = args[2 * num_additional_speech_types:3 * num_additional_speech_types]
692
+ model_choice = args[3 * num_additional_speech_types]
693
+ remove_silence = args[3 * num_additional_speech_types + 1]
694
+
695
+ # Collect the speech types and their audios into a dict
696
+ speech_types = {'Regular': {'audio': regular_audio, 'ref_text': regular_ref_text}}
697
+
698
+ for name_input, audio_input, ref_text_input in zip(speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list):
699
+ if name_input and audio_input:
700
+ speech_types[name_input] = {'audio': audio_input, 'ref_text': ref_text_input}
701
+
702
+ # Parse the gen_text into segments
703
+ segments = parse_speechtypes_text(gen_text)
704
+
705
+ # For each segment, generate speech
706
+ generated_audio_segments = []
707
+ current_emotion = 'Regular'
708
+
709
+ for segment in segments:
710
+ emotion = segment['emotion']
711
+ text = segment['text']
712
+
713
+ if emotion in speech_types:
714
+ current_emotion = emotion
715
+ else:
716
+ # If emotion not available, default to Regular
717
+ current_emotion = 'Regular'
718
+
719
+ ref_audio = speech_types[current_emotion]['audio']
720
+ ref_text = speech_types[current_emotion].get('ref_text', '')
721
+
722
+ # Generate speech for this segment
723
+ audio, _ = infer(ref_audio, ref_text, text, model_choice, remove_silence, "")
724
+ sr, audio_data = audio
725
+
726
+ generated_audio_segments.append(audio_data)
727
+
728
+ # Concatenate all audio segments
729
+ if generated_audio_segments:
730
+ final_audio_data = np.concatenate(generated_audio_segments)
731
+ return (sr, final_audio_data)
732
+ else:
733
+ gr.Warning("No audio generated.")
734
+ return None
735
+
736
+ generate_emotional_btn.click(
737
+ generate_emotional_speech,
738
+ inputs=[
739
+ regular_audio,
740
+ regular_ref_text,
741
+ gen_text_input_emotional,
742
+ ] + speech_type_names + speech_type_audios + speech_type_ref_texts + [
743
+ model_choice_emotional,
744
+ remove_silence_emotional,
745
+ ],
746
+ outputs=audio_output_emotional,
747
+ )
748
+
749
+ # Validation function to disable Generate button if speech types are missing
750
+ def validate_speech_types(
751
+ gen_text,
752
+ regular_name,
753
+ *args
754
+ ):
755
+ num_additional_speech_types = max_speech_types - 1
756
+ speech_type_names_list = args[:num_additional_speech_types]
757
+
758
+ # Collect the speech types names
759
+ speech_types_available = set()
760
+ if regular_name:
761
+ speech_types_available.add(regular_name)
762
+ for name_input in speech_type_names_list:
763
+ if name_input:
764
+ speech_types_available.add(name_input)
765
+
766
+ # Parse the gen_text to get the speech types used
767
+ segments = parse_emotional_text(gen_text)
768
+ speech_types_in_text = set(segment['emotion'] for segment in segments)
769
+
770
+ # Check if all speech types in text are available
771
+ missing_speech_types = speech_types_in_text - speech_types_available
772
+
773
+ if missing_speech_types:
774
+ # Disable the generate button
775
+ return gr.update(interactive=False)
776
+ else:
777
+ # Enable the generate button
778
+ return gr.update(interactive=True)
779
+
780
+ gen_text_input_emotional.change(
781
+ validate_speech_types,
782
+ inputs=[gen_text_input_emotional, regular_name] + speech_type_names,
783
+ outputs=generate_emotional_btn
784
+ )
785
+ with gr.Blocks() as app:
786
+ gr.Markdown(
787
+ """
788
+ # E2/F5 TTS
789
+
790
+ This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
791
+
792
+ * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
793
+ * [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
794
+
795
+ The checkpoints support English and Chinese.
796
+
797
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt.
798
+
799
+ **NOTE: Reference text will be automatically transcribed with Whisper if not provided. For best results, keep your reference clips short (<15s). Ensure the audio is fully uploaded before generating.**
800
+ """
801
+ )
802
+ gr.TabbedInterface([app_tts, app_podcast, app_emotional, app_credits], ["TTS", "Podcast", "Multi-Style", "Credits"])
803
+
804
+ @click.command()
805
+ @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
806
+ @click.option("--host", "-H", default=None, help="Host to run the app on")
807
+ @click.option(
808
+ "--share",
809
+ "-s",
810
+ default=False,
811
+ is_flag=True,
812
+ help="Share the app via Gradio share link",
813
+ )
814
+ @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
815
+ def main(port, host, share, api):
816
+ global app
817
+ print(f"Starting app...")
818
+ app.queue(api_open=api).launch(
819
+ server_name=host, server_port=port, share=share, show_api=api
820
+ )
821
+
822
+
823
+ if __name__ == "__main__":
824
+ main()
inference-cli.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import codecs
3
+ import re
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import soundfile as sf
8
+ import tomli
9
+ from cached_path import cached_path
10
+
11
+ from model import DiT, UNetT
12
+ from model.utils_infer import (
13
+ load_vocoder,
14
+ load_model,
15
+ preprocess_ref_audio_text,
16
+ infer_process,
17
+ remove_silence_for_generated_wav,
18
+ )
19
+
20
+
21
+ parser = argparse.ArgumentParser(
22
+ prog="python3 inference-cli.py",
23
+ description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.",
24
+ epilog="Specify options above to override one or more settings from config.",
25
+ )
26
+ parser.add_argument(
27
+ "-c",
28
+ "--config",
29
+ help="Configuration file. Default=cli-config.toml",
30
+ default="inference-cli.toml",
31
+ )
32
+ parser.add_argument(
33
+ "-m",
34
+ "--model",
35
+ help="F5-TTS | E2-TTS",
36
+ )
37
+ parser.add_argument(
38
+ "-p",
39
+ "--ckpt_file",
40
+ help="The Checkpoint .pt",
41
+ )
42
+ parser.add_argument(
43
+ "-v",
44
+ "--vocab_file",
45
+ help="The vocab .txt",
46
+ )
47
+ parser.add_argument("-r", "--ref_audio", type=str, help="Reference audio file < 15 seconds.")
48
+ parser.add_argument("-s", "--ref_text", type=str, default="666", help="Subtitle for the reference audio.")
49
+ parser.add_argument(
50
+ "-t",
51
+ "--gen_text",
52
+ type=str,
53
+ help="Text to generate.",
54
+ )
55
+ parser.add_argument(
56
+ "-f",
57
+ "--gen_file",
58
+ type=str,
59
+ help="File with text to generate. Ignores --text",
60
+ )
61
+ parser.add_argument(
62
+ "-o",
63
+ "--output_dir",
64
+ type=str,
65
+ help="Path to output folder..",
66
+ )
67
+ parser.add_argument(
68
+ "--remove_silence",
69
+ help="Remove silence.",
70
+ )
71
+ parser.add_argument(
72
+ "--load_vocoder_from_local",
73
+ action="store_true",
74
+ help="load vocoder from local. Default: ../checkpoints/charactr/vocos-mel-24khz",
75
+ )
76
+ args = parser.parse_args()
77
+
78
+ config = tomli.load(open(args.config, "rb"))
79
+
80
+ ref_audio = args.ref_audio if args.ref_audio else config["ref_audio"]
81
+ ref_text = args.ref_text if args.ref_text != "666" else config["ref_text"]
82
+ gen_text = args.gen_text if args.gen_text else config["gen_text"]
83
+ gen_file = args.gen_file if args.gen_file else config["gen_file"]
84
+ if gen_file:
85
+ gen_text = codecs.open(gen_file, "r", "utf-8").read()
86
+ output_dir = args.output_dir if args.output_dir else config["output_dir"]
87
+ model = args.model if args.model else config["model"]
88
+ ckpt_file = args.ckpt_file if args.ckpt_file else ""
89
+ vocab_file = args.vocab_file if args.vocab_file else ""
90
+ remove_silence = args.remove_silence if args.remove_silence else config["remove_silence"]
91
+ wave_path = Path(output_dir) / "out.wav"
92
+ spectrogram_path = Path(output_dir) / "out.png"
93
+ vocos_local_path = "../checkpoints/charactr/vocos-mel-24khz"
94
+
95
+ vocos = load_vocoder(is_local=args.load_vocoder_from_local, local_path=vocos_local_path)
96
+
97
+
98
+ # load models
99
+ if model == "F5-TTS":
100
+ model_cls = DiT
101
+ model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
102
+ if ckpt_file == "":
103
+ repo_name = "F5-TTS"
104
+ exp_name = "F5TTS_Base"
105
+ ckpt_step = 1200000
106
+ ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
107
+ # ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
108
+
109
+ elif model == "E2-TTS":
110
+ model_cls = UNetT
111
+ model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
112
+ if ckpt_file == "":
113
+ repo_name = "E2-TTS"
114
+ exp_name = "E2TTS_Base"
115
+ ckpt_step = 1200000
116
+ ckpt_file = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
117
+ # ckpt_file = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors; local path
118
+
119
+ print(f"Using {model}...")
120
+ ema_model = load_model(model_cls, model_cfg, ckpt_file, vocab_file)
121
+
122
+
123
+ def main_process(ref_audio, ref_text, text_gen, model_obj, remove_silence):
124
+ main_voice = {"ref_audio": ref_audio, "ref_text": ref_text}
125
+ if "voices" not in config:
126
+ voices = {"main": main_voice}
127
+ else:
128
+ voices = config["voices"]
129
+ voices["main"] = main_voice
130
+ for voice in voices:
131
+ voices[voice]["ref_audio"], voices[voice]["ref_text"] = preprocess_ref_audio_text(
132
+ voices[voice]["ref_audio"], voices[voice]["ref_text"]
133
+ )
134
+ print("Voice:", voice)
135
+ print("Ref_audio:", voices[voice]["ref_audio"])
136
+ print("Ref_text:", voices[voice]["ref_text"])
137
+
138
+ generated_audio_segments = []
139
+ reg1 = r"(?=\[\w+\])"
140
+ chunks = re.split(reg1, text_gen)
141
+ reg2 = r"\[(\w+)\]"
142
+ for text in chunks:
143
+ match = re.match(reg2, text)
144
+ if match:
145
+ voice = match[1]
146
+ else:
147
+ print("No voice tag found, using main.")
148
+ voice = "main"
149
+ if voice not in voices:
150
+ print(f"Voice {voice} not found, using main.")
151
+ voice = "main"
152
+ text = re.sub(reg2, "", text)
153
+ gen_text = text.strip()
154
+ ref_audio = voices[voice]["ref_audio"]
155
+ ref_text = voices[voice]["ref_text"]
156
+ print(f"Voice: {voice}")
157
+ audio, final_sample_rate, spectragram = infer_process(ref_audio, ref_text, gen_text, model_obj)
158
+ generated_audio_segments.append(audio)
159
+
160
+ if generated_audio_segments:
161
+ final_wave = np.concatenate(generated_audio_segments)
162
+ with open(wave_path, "wb") as f:
163
+ sf.write(f.name, final_wave, final_sample_rate)
164
+ # Remove silence
165
+ if remove_silence:
166
+ remove_silence_for_generated_wav(f.name)
167
+ print(f.name)
168
+
169
+
170
+ main_process(ref_audio, ref_text, gen_text, ema_model, remove_silence)
inference-cli.toml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # F5-TTS | E2-TTS
2
+ model = "F5-TTS"
3
+ ref_audio = "tests/ref_audio/test_en_1_ref_short.wav"
4
+ # If an empty "", transcribes the reference audio automatically.
5
+ ref_text = "Some call me nature, others call me mother nature."
6
+ gen_text = "I don't really care what you call me. I've been a silent spectator, watching species evolve, empires rise and fall. But always remember, I am mighty and enduring. Respect me and I'll nurture you; ignore me and you shall face the consequences."
7
+ # File with text to generate. Ignores the text above.
8
+ gen_file = ""
9
+ remove_silence = false
10
+ output_dir = "tests"
pyproject.toml ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools >= 61.0", "setuptools-scm>=8.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "f5-tts"
7
+ dynamic = ["version"]
8
+ description = "F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching"
9
+ readme = "README.md"
10
+ license = {text = "MIT License"}
11
+ classifiers = [
12
+ "License :: OSI Approved :: MIT License",
13
+ "Operating System :: OS Independent",
14
+ "Programming Language :: Python :: 3",
15
+ ]
16
+ dependencies = [
17
+ "accelerate>=0.33.0",
18
+ "bitsandbytes>0.37.0",
19
+ "cached_path",
20
+ "click",
21
+ "datasets",
22
+ "ema_pytorch>=0.5.2",
23
+ "gradio>=3.45.2",
24
+ "jieba",
25
+ "librosa",
26
+ "matplotlib",
27
+ "numpy<=1.26.4",
28
+ "pydub",
29
+ "pypinyin",
30
+ "safetensors",
31
+ "soundfile",
32
+ "tomli",
33
+ "torch>=2.0.0",
34
+ "torchaudio>=2.0.0",
35
+ "torchdiffeq",
36
+ "tqdm>=4.65.0",
37
+ "transformers",
38
+ "transformers_stream_generator",
39
+ "vocos",
40
+ "wandb",
41
+ "x_transformers>=1.31.14",
42
+ ]
43
+
44
+ [project.optional-dependencies]
45
+ eval = [
46
+ "faster_whisper==0.10.1",
47
+ "funasr",
48
+ "jiwer",
49
+ "modelscope",
50
+ "zhconv",
51
+ "zhon",
52
+ ]
53
+
54
+ [project.urls]
55
+ Homepage = "https://github.com/SWivid/F5-TTS"
56
+
57
+ [project.scripts]
58
+ "f5-tts_infer-cli" = "f5_tts.infer.infer_cli:main"
59
+ "f5-tts_infer-gradio" = "f5_tts.infer.infer_gradio:main"
60
+ "f5-tts_finetune-cli" = "f5_tts.train.finetune_cli:main"
61
+ "f5-tts_finetune-gradio" = "f5_tts.train.finetune_gradio:main"
requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchaudio
3
+ accelerate>=0.33.0
4
+ bitsandbytes>0.37.0
5
+ cached_path
6
+ click
7
+ datasets
8
+ ema_pytorch>=0.5.2
9
+ gradio
10
+ jieba
11
+ librosa
12
+ matplotlib
13
+ numpy<=1.26.4
14
+ pydub
15
+ pypinyin
16
+ safetensors
17
+ soundfile
18
+ tomli
19
+ torchdiffeq
20
+ tqdm>=4.65.0
21
+ transformers
22
+ vocos
23
+ wandb
24
+ x_transformers>=1.31.14
25
+ f5_tts @ git+https://huggingface.co/spaces/mrfakename/E2-F5-TTS
requirements_eval.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ faster_whisper
2
+ funasr
3
+ jiwer
4
+ zhconv
5
+ zhon
ruff.toml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ line-length = 120
2
+ target-version = "py310"
3
+
4
+ [lint]
5
+ # Only ignore variables with names starting with "_".
6
+ dummy-variable-rgx = "^_.*$"
7
+
8
+ [lint.isort]
9
+ force-single-line = true
10
+ lines-after-imports = 2
speech_edit.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import torchaudio
6
+ from vocos import Vocos
7
+
8
+ from model import CFM, UNetT, DiT
9
+ from model.utils import (
10
+ load_checkpoint,
11
+ get_tokenizer,
12
+ convert_char_to_pinyin,
13
+ save_spectrogram,
14
+ )
15
+
16
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
17
+
18
+
19
+ # --------------------- Dataset Settings -------------------- #
20
+
21
+ target_sample_rate = 24000
22
+ n_mel_channels = 100
23
+ hop_length = 256
24
+ target_rms = 0.1
25
+
26
+ tokenizer = "pinyin"
27
+ dataset_name = "Emilia_ZH_EN"
28
+
29
+
30
+ # ---------------------- infer setting ---------------------- #
31
+
32
+ seed = None # int | None
33
+
34
+ exp_name = "F5TTS_Base" # F5TTS_Base | E2TTS_Base
35
+ ckpt_step = 1200000
36
+
37
+ nfe_step = 32 # 16, 32
38
+ cfg_strength = 2.0
39
+ ode_method = "euler" # euler | midpoint
40
+ sway_sampling_coef = -1.0
41
+ speed = 1.0
42
+
43
+ if exp_name == "F5TTS_Base":
44
+ model_cls = DiT
45
+ model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
46
+
47
+ elif exp_name == "E2TTS_Base":
48
+ model_cls = UNetT
49
+ model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
50
+
51
+ ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.safetensors"
52
+ output_dir = "tests"
53
+
54
+ # [leverage https://github.com/MahmoudAshraf97/ctc-forced-aligner to get char level alignment]
55
+ # pip install git+https://github.com/MahmoudAshraf97/ctc-forced-aligner.git
56
+ # [write the origin_text into a file, e.g. tests/test_edit.txt]
57
+ # ctc-forced-aligner --audio_path "tests/ref_audio/test_en_1_ref_short.wav" --text_path "tests/test_edit.txt" --language "zho" --romanize --split_size "char"
58
+ # [result will be saved at same path of audio file]
59
+ # [--language "zho" for Chinese, "eng" for English]
60
+ # [if local ckpt, set --alignment_model "../checkpoints/mms-300m-1130-forced-aligner"]
61
+
62
+ audio_to_edit = "tests/ref_audio/test_en_1_ref_short.wav"
63
+ origin_text = "Some call me nature, others call me mother nature."
64
+ target_text = "Some call me optimist, others call me realist."
65
+ parts_to_edit = [
66
+ [1.42, 2.44],
67
+ [4.04, 4.9],
68
+ ] # stard_ends of "nature" & "mother nature", in seconds
69
+ fix_duration = [
70
+ 1.2,
71
+ 1,
72
+ ] # fix duration for "optimist" & "realist", in seconds
73
+
74
+ # audio_to_edit = "tests/ref_audio/test_zh_1_ref_short.wav"
75
+ # origin_text = "对,这就是我,万人敬仰的太乙真人。"
76
+ # target_text = "对,那就是你,万人敬仰的太白金星。"
77
+ # parts_to_edit = [[0.84, 1.4], [1.92, 2.4], [4.26, 6.26], ]
78
+ # fix_duration = None # use origin text duration
79
+
80
+
81
+ # -------------------------------------------------#
82
+
83
+ use_ema = True
84
+
85
+ if not os.path.exists(output_dir):
86
+ os.makedirs(output_dir)
87
+
88
+ # Vocoder model
89
+ local = False
90
+ if local:
91
+ vocos_local_path = "../checkpoints/charactr/vocos-mel-24khz"
92
+ vocos = Vocos.from_hparams(f"{vocos_local_path}/config.yaml")
93
+ state_dict = torch.load(f"{vocos_local_path}/pytorch_model.bin", weights_only=True, map_location=device)
94
+ vocos.load_state_dict(state_dict)
95
+
96
+ vocos.eval()
97
+ else:
98
+ vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
99
+
100
+ # Tokenizer
101
+ vocab_char_map, vocab_size = get_tokenizer(dataset_name, tokenizer)
102
+
103
+ # Model
104
+ model = CFM(
105
+ transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
106
+ mel_spec_kwargs=dict(
107
+ target_sample_rate=target_sample_rate,
108
+ n_mel_channels=n_mel_channels,
109
+ hop_length=hop_length,
110
+ ),
111
+ odeint_kwargs=dict(
112
+ method=ode_method,
113
+ ),
114
+ vocab_char_map=vocab_char_map,
115
+ ).to(device)
116
+
117
+ model = load_checkpoint(model, ckpt_path, device, use_ema=use_ema)
118
+
119
+ # Audio
120
+ audio, sr = torchaudio.load(audio_to_edit)
121
+ if audio.shape[0] > 1:
122
+ audio = torch.mean(audio, dim=0, keepdim=True)
123
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
124
+ if rms < target_rms:
125
+ audio = audio * target_rms / rms
126
+ if sr != target_sample_rate:
127
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
128
+ audio = resampler(audio)
129
+ offset = 0
130
+ audio_ = torch.zeros(1, 0)
131
+ edit_mask = torch.zeros(1, 0, dtype=torch.bool)
132
+ for part in parts_to_edit:
133
+ start, end = part
134
+ part_dur = end - start if fix_duration is None else fix_duration.pop(0)
135
+ part_dur = part_dur * target_sample_rate
136
+ start = start * target_sample_rate
137
+ audio_ = torch.cat((audio_, audio[:, round(offset) : round(start)], torch.zeros(1, round(part_dur))), dim=-1)
138
+ edit_mask = torch.cat(
139
+ (
140
+ edit_mask,
141
+ torch.ones(1, round((start - offset) / hop_length), dtype=torch.bool),
142
+ torch.zeros(1, round(part_dur / hop_length), dtype=torch.bool),
143
+ ),
144
+ dim=-1,
145
+ )
146
+ offset = end * target_sample_rate
147
+ # audio = torch.cat((audio_, audio[:, round(offset):]), dim = -1)
148
+ edit_mask = F.pad(edit_mask, (0, audio.shape[-1] // hop_length - edit_mask.shape[-1] + 1), value=True)
149
+ audio = audio.to(device)
150
+ edit_mask = edit_mask.to(device)
151
+
152
+ # Text
153
+ text_list = [target_text]
154
+ if tokenizer == "pinyin":
155
+ final_text_list = convert_char_to_pinyin(text_list)
156
+ else:
157
+ final_text_list = [text_list]
158
+ print(f"text : {text_list}")
159
+ print(f"pinyin: {final_text_list}")
160
+
161
+ # Duration
162
+ ref_audio_len = 0
163
+ duration = audio.shape[-1] // hop_length
164
+
165
+ # Inference
166
+ with torch.inference_mode():
167
+ generated, trajectory = model.sample(
168
+ cond=audio,
169
+ text=final_text_list,
170
+ duration=duration,
171
+ steps=nfe_step,
172
+ cfg_strength=cfg_strength,
173
+ sway_sampling_coef=sway_sampling_coef,
174
+ seed=seed,
175
+ edit_mask=edit_mask,
176
+ )
177
+ print(f"Generated mel: {generated.shape}")
178
+
179
+ # Final result
180
+ generated = generated.to(torch.float32)
181
+ generated = generated[:, ref_audio_len:, :]
182
+ generated_mel_spec = generated.permute(0, 2, 1)
183
+ generated_wave = vocos.decode(generated_mel_spec.cpu())
184
+ if rms < target_rms:
185
+ generated_wave = generated_wave * rms / target_rms
186
+
187
+ save_spectrogram(generated_mel_spec[0].cpu().numpy(), f"{output_dir}/speech_edit_out.png")
188
+ torchaudio.save(f"{output_dir}/speech_edit_out.wav", generated_wave, target_sample_rate)
189
+ print(f"Generated wav: {generated_wave.shape}")
train.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from model import CFM, UNetT, DiT, Trainer
2
+ from model.utils import get_tokenizer
3
+ from model.dataset import load_dataset
4
+
5
+
6
+ # -------------------------- Dataset Settings --------------------------- #
7
+
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
+ dataset_name = "Emilia_ZH_EN"
15
+
16
+ # -------------------------- Training Settings -------------------------- #
17
+
18
+ exp_name = "F5TTS_Base" # F5TTS_Base | E2TTS_Base
19
+
20
+ learning_rate = 7.5e-5
21
+
22
+ batch_size_per_gpu = 38400 # 8 GPUs, 8 * 38400 = 307200
23
+ batch_size_type = "frame" # "frame" or "sample"
24
+ max_samples = 64 # max sequences per batch if use frame-wise batch_size. we set 32 for small models, 64 for base models
25
+ grad_accumulation_steps = 1 # note: updates = steps / grad_accumulation_steps
26
+ max_grad_norm = 1.0
27
+
28
+ epochs = 11 # use linear decay, thus epochs control the slope
29
+ num_warmup_updates = 20000 # warmup steps
30
+ save_per_updates = 50000 # save checkpoint per steps
31
+ last_per_steps = 5000 # save last checkpoint per steps
32
+
33
+ # model params
34
+ if exp_name == "F5TTS_Base":
35
+ wandb_resume_id = None
36
+ model_cls = DiT
37
+ model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
38
+ elif exp_name == "E2TTS_Base":
39
+ wandb_resume_id = None
40
+ model_cls = UNetT
41
+ model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
42
+
43
+
44
+ # ----------------------------------------------------------------------- #
45
+
46
+
47
+ def main():
48
+ if tokenizer == "custom":
49
+ tokenizer_path = tokenizer_path
50
+ else:
51
+ tokenizer_path = dataset_name
52
+ vocab_char_map, vocab_size = get_tokenizer(tokenizer_path, tokenizer)
53
+
54
+ mel_spec_kwargs = dict(
55
+ target_sample_rate=target_sample_rate,
56
+ n_mel_channels=n_mel_channels,
57
+ hop_length=hop_length,
58
+ )
59
+
60
+ model = CFM(
61
+ transformer=model_cls(**model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels),
62
+ mel_spec_kwargs=mel_spec_kwargs,
63
+ vocab_char_map=vocab_char_map,
64
+ )
65
+
66
+ trainer = Trainer(
67
+ model,
68
+ epochs,
69
+ learning_rate,
70
+ num_warmup_updates=num_warmup_updates,
71
+ save_per_updates=save_per_updates,
72
+ checkpoint_path=f"ckpts/{exp_name}",
73
+ batch_size=batch_size_per_gpu,
74
+ batch_size_type=batch_size_type,
75
+ max_samples=max_samples,
76
+ grad_accumulation_steps=grad_accumulation_steps,
77
+ max_grad_norm=max_grad_norm,
78
+ wandb_project="CFM-TTS",
79
+ wandb_run_name=exp_name,
80
+ wandb_resume_id=wandb_resume_id,
81
+ last_per_steps=last_per_steps,
82
+ )
83
+
84
+ train_dataset = load_dataset(dataset_name, tokenizer, mel_spec_kwargs=mel_spec_kwargs)
85
+ trainer.train(
86
+ train_dataset,
87
+ resumable_with_seed=666, # seed for shuffling dataset
88
+ )
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()