Gregniuki commited on
Commit
8ec1a00
1 Parent(s): 986683c

Upload 5 files

Browse files
Files changed (5) hide show
  1. README.md +13 -171
  2. app.py +791 -0
  3. app_local.py +236 -0
  4. inference-cli.py +363 -0
  5. inference-cli.toml +10 -0
README.md CHANGED
@@ -1,171 +1,13 @@
1
- # F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching
2
-
3
- [![python](https://img.shields.io/badge/Python-3.10-brightgreen)](https://github.com/SWivid/F5-TTS)
4
- [![arXiv](https://img.shields.io/badge/arXiv-2410.06885-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2410.06885)
5
- [![demo](https://img.shields.io/badge/GitHub-Demo%20page-orange.svg)](https://swivid.github.io/F5-TTS/)
6
- [![hfspace](https://img.shields.io/badge/🤗-Space%20demo-yellow)](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
7
- [![msspace](https://img.shields.io/badge/🤖-Space%20demo-blue)](https://modelscope.cn/studios/modelscope/E2-F5-TTS)
8
- [![lab](https://img.shields.io/badge/X--LANCE-Lab-grey?labelColor=lightgrey)](https://x-lance.sjtu.edu.cn/)
9
- <img src="https://github.com/user-attachments/assets/12d7749c-071a-427c-81bf-b87b91def670" alt="Watermark" style="width: 40px; height: auto">
10
-
11
- **F5-TTS**: Diffusion Transformer with ConvNeXt V2, faster trained and inference.
12
-
13
- **E2 TTS**: Flat-UNet Transformer, closest reproduction from [paper](https://arxiv.org/abs/2406.18009).
14
-
15
- **Sway Sampling**: Inference-time flow step sampling strategy, greatly improves performance
16
-
17
- ### Thanks to all the contributors !
18
-
19
- ## News
20
- - **2024/10/08**: F5-TTS & E2 TTS base models on [🤗 Hugging Face](https://huggingface.co/SWivid/F5-TTS), [🤖 Model Scope](https://www.modelscope.cn/models/SWivid/F5-TTS_Emilia-ZH-EN), [🟣 Wisemodel](https://wisemodel.cn/models/SJTU_X-LANCE/F5-TTS_Emilia-ZH-EN).
21
-
22
- ## Installation
23
-
24
- ```bash
25
- # Create a python 3.10 conda env (you could also use virtualenv)
26
- conda create -n f5-tts python=3.10
27
- conda activate f5-tts
28
-
29
- # Install pytorch with your CUDA version, e.g.
30
- pip install torch==2.3.0+cu118 torchaudio==2.3.0+cu118 --extra-index-url https://download.pytorch.org/whl/cu118
31
- ```
32
-
33
- Then you can choose from a few options below:
34
-
35
- ### 1. As a pip package (if just for inference)
36
-
37
- ```bash
38
- pip install git+https://github.com/SWivid/F5-TTS.git
39
- ```
40
-
41
- ### 2. Local editable (if also do training, finetuning)
42
-
43
- ```bash
44
- git clone https://github.com/SWivid/F5-TTS.git
45
- cd F5-TTS
46
- # git submodule update --init --recursive # (optional, if need bigvgan)
47
- pip install -e .
48
- ```
49
- If initialize submodule, you should add the following code at the beginning of `src/third_party/BigVGAN/bigvgan.py`.
50
- ```python
51
- import os
52
- import sys
53
- sys.path.append(os.path.dirname(os.path.abspath(__file__)))
54
- ```
55
-
56
- ### 3. Docker usage
57
- ```bash
58
- # Build from Dockerfile
59
- docker build -t f5tts:v1 .
60
-
61
- # Or pull from GitHub Container Registry
62
- docker pull ghcr.io/swivid/f5-tts:main
63
- ```
64
-
65
-
66
- ## Inference
67
-
68
- ### 1. Gradio App
69
-
70
- Currently supported features:
71
-
72
- - Basic TTS with Chunk Inference
73
- - Multi-Style / Multi-Speaker Generation
74
- - Voice Chat powered by Qwen2.5-3B-Instruct
75
-
76
- ```bash
77
- # Launch a Gradio app (web interface)
78
- f5-tts_infer-gradio
79
-
80
- # Specify the port/host
81
- f5-tts_infer-gradio --port 7860 --host 0.0.0.0
82
-
83
- # Launch a share link
84
- f5-tts_infer-gradio --share
85
- ```
86
-
87
- ### 2. CLI Inference
88
-
89
- ```bash
90
- # Run with flags
91
- # Leave --ref_text "" will have ASR model transcribe (extra GPU memory usage)
92
- f5-tts_infer-cli \
93
- --model "F5-TTS" \
94
- --ref_audio "ref_audio.wav" \
95
- --ref_text "The content, subtitle or transcription of reference audio." \
96
- --gen_text "Some text you want TTS model generate for you."
97
-
98
- # Run with default setting. src/f5_tts/infer/examples/basic/basic.toml
99
- f5-tts_infer-cli
100
- # Or with your own .toml file
101
- f5-tts_infer-cli -c custom.toml
102
-
103
- # Multi voice. See src/f5_tts/infer/README.md
104
- f5-tts_infer-cli -c src/f5_tts/infer/examples/multi/story.toml
105
- ```
106
-
107
- ### 3. More instructions
108
-
109
- - In order to have better generation results, take a moment to read [detailed guidance](src/f5_tts/infer).
110
- - The [Issues](https://github.com/SWivid/F5-TTS/issues?q=is%3Aissue) are very useful, please try to find the solution by properly searching the keywords of problem encountered. If no answer found, then feel free to open an issue.
111
-
112
-
113
- ## Training
114
-
115
- ### 1. Gradio App
116
-
117
- Read [training & finetuning guidance](src/f5_tts/train) for more instructions.
118
-
119
- ```bash
120
- # Quick start with Gradio web interface
121
- f5-tts_finetune-gradio
122
- ```
123
-
124
-
125
- ## [Evaluation](src/f5_tts/eval)
126
-
127
-
128
- ## Development
129
-
130
- Use pre-commit to ensure code quality (will run linters and formatters automatically)
131
-
132
- ```bash
133
- pip install pre-commit
134
- pre-commit install
135
- ```
136
-
137
- When making a pull request, before each commit, run:
138
-
139
- ```bash
140
- pre-commit run --all-files
141
- ```
142
-
143
- Note: Some model components have linting exceptions for E722 to accommodate tensor notation
144
-
145
-
146
- ## Acknowledgements
147
-
148
- - [E2-TTS](https://arxiv.org/abs/2406.18009) brilliant work, simple and effective
149
- - [Emilia](https://arxiv.org/abs/2407.05361), [WenetSpeech4TTS](https://arxiv.org/abs/2406.05763) valuable datasets
150
- - [lucidrains](https://github.com/lucidrains) initial CFM structure with also [bfs18](https://github.com/bfs18) for discussion
151
- - [SD3](https://arxiv.org/abs/2403.03206) & [Hugging Face diffusers](https://github.com/huggingface/diffusers) DiT and MMDiT code structure
152
- - [torchdiffeq](https://github.com/rtqichen/torchdiffeq) as ODE solver, [Vocos](https://huggingface.co/charactr/vocos-mel-24khz) as vocoder
153
- - [FunASR](https://github.com/modelscope/FunASR), [faster-whisper](https://github.com/SYSTRAN/faster-whisper), [UniSpeech](https://github.com/microsoft/UniSpeech) for evaluation tools
154
- - [ctc-forced-aligner](https://github.com/MahmoudAshraf97/ctc-forced-aligner) for speech edit test
155
- - [mrfakename](https://x.com/realmrfakename) huggingface space demo ~
156
- - [f5-tts-mlx](https://github.com/lucasnewman/f5-tts-mlx/tree/main) Implementation with MLX framework by [Lucas Newman](https://github.com/lucasnewman)
157
- - [F5-TTS-ONNX](https://github.com/DakeQQ/F5-TTS-ONNX) ONNX Runtime version by [DakeQQ](https://github.com/DakeQQ)
158
-
159
- ## Citation
160
- If our work and codebase is useful for you, please cite as:
161
- ```
162
- @article{chen-etal-2024-f5tts,
163
- title={F5-TTS: A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching},
164
- author={Yushen Chen and Zhikang Niu and Ziyang Ma and Keqi Deng and Chunhui Wang and Jian Zhao and Kai Yu and Xie Chen},
165
- journal={arXiv preprint arXiv:2410.06885},
166
- year={2024},
167
- }
168
- ```
169
- ## License
170
-
171
- Our code is released under MIT License. The pre-trained models are licensed under the CC-BY-NC license due to the training data Emilia, which is an in-the-wild dataset. Sorry for any inconvenience this may cause.
 
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: 5.1.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,791 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
+ import torchaudio
4
+ import gradio as gr
5
+ import numpy as np
6
+ import tempfile
7
+ from einops import rearrange
8
+ from vocos import Vocos
9
+ from pydub import AudioSegment, silence
10
+ from model import CFM, UNetT, DiT, MMDiT
11
+ from cached_path import cached_path
12
+ from model.utils import (
13
+ load_checkpoint,
14
+ get_tokenizer,
15
+ convert_char_to_pinyin,
16
+ save_spectrogram,
17
+ )
18
+ from transformers import pipeline
19
+ import click
20
+ import soundfile as sf
21
+
22
+ try:
23
+ import spaces
24
+ USING_SPACES = True
25
+ except ImportError:
26
+ USING_SPACES = False
27
+
28
+ def gpu_decorator(func):
29
+ if USING_SPACES:
30
+ return spaces.GPU(func)
31
+ else:
32
+ return func
33
+
34
+ device = (
35
+ "cuda"
36
+ if torch.cuda.is_available()
37
+ else "mps" if torch.backends.mps.is_available() else "cpu"
38
+ )
39
+
40
+ print(f"Using {device} device")
41
+
42
+ pipe = pipeline(
43
+ "automatic-speech-recognition",
44
+ model="openai/whisper-large-v3-turbo",
45
+ torch_dtype=torch.float16,
46
+ device=device,
47
+ )
48
+ vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
49
+
50
+ # --------------------- Settings -------------------- #
51
+
52
+ target_sample_rate = 24000
53
+ n_mel_channels = 100
54
+ hop_length = 256
55
+ target_rms = 0.1
56
+ nfe_step = 32 # 16, 32
57
+ cfg_strength = 2.0
58
+ ode_method = "euler"
59
+ sway_sampling_coef = -1.0
60
+ speed = 1.0
61
+ fix_duration = None
62
+
63
+
64
+ def load_model(repo_name, exp_name, model_cls, model_cfg, ckpt_step):
65
+ ckpt_path = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
66
+ # ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors
67
+ vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
68
+ model = CFM(
69
+ transformer=model_cls(
70
+ **model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels
71
+ ),
72
+ mel_spec_kwargs=dict(
73
+ target_sample_rate=target_sample_rate,
74
+ n_mel_channels=n_mel_channels,
75
+ hop_length=hop_length,
76
+ ),
77
+ odeint_kwargs=dict(
78
+ method=ode_method,
79
+ ),
80
+ vocab_char_map=vocab_char_map,
81
+ ).to(device)
82
+
83
+ model = load_checkpoint(model, ckpt_path, device, use_ema = True)
84
+
85
+ return model
86
+
87
+
88
+ # load models
89
+ F5TTS_model_cfg = dict(
90
+ dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4
91
+ )
92
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
93
+
94
+ F5TTS_ema_model = load_model(
95
+ "F5-TTS", "F5TTS_Base", DiT, F5TTS_model_cfg, 1200000
96
+ )
97
+ E2TTS_ema_model = load_model(
98
+ "E2-TTS", "E2TTS_Base", UNetT, E2TTS_model_cfg, 1200000
99
+ )
100
+
101
+ def chunk_text(text, max_chars=135):
102
+ """
103
+ Splits the input text into chunks, each with a maximum number of characters.
104
+
105
+ Args:
106
+ text (str): The text to be split.
107
+ max_chars (int): The maximum number of characters per chunk.
108
+
109
+ Returns:
110
+ List[str]: A list of text chunks.
111
+ """
112
+ chunks = []
113
+ current_chunk = ""
114
+ # Split the text into sentences based on punctuation followed by whitespace
115
+ sentences = re.split(r'(?<=[;:,.!?])\s+|(?<=[;:,。!?])', text)
116
+
117
+ for sentence in sentences:
118
+ if len(current_chunk.encode('utf-8')) + len(sentence.encode('utf-8')) <= max_chars:
119
+ current_chunk += sentence + " " if sentence and len(sentence[-1].encode('utf-8')) == 1 else sentence
120
+ else:
121
+ if current_chunk:
122
+ chunks.append(current_chunk.strip())
123
+ current_chunk = sentence + " " if sentence and len(sentence[-1].encode('utf-8')) == 1 else sentence
124
+
125
+ if current_chunk:
126
+ chunks.append(current_chunk.strip())
127
+
128
+ return chunks
129
+
130
+ @gpu_decorator
131
+ def infer_batch(ref_audio, ref_text, gen_text_batches, exp_name, remove_silence, cross_fade_duration=0.15, progress=gr.Progress()):
132
+ if exp_name == "F5-TTS":
133
+ ema_model = F5TTS_ema_model
134
+ elif exp_name == "E2-TTS":
135
+ ema_model = E2TTS_ema_model
136
+
137
+ audio, sr = ref_audio
138
+ if audio.shape[0] > 1:
139
+ audio = torch.mean(audio, dim=0, keepdim=True)
140
+
141
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
142
+ if rms < target_rms:
143
+ audio = audio * target_rms / rms
144
+ if sr != target_sample_rate:
145
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
146
+ audio = resampler(audio)
147
+ audio = audio.to(device)
148
+
149
+ generated_waves = []
150
+ spectrograms = []
151
+
152
+ for i, gen_text in enumerate(progress.tqdm(gen_text_batches)):
153
+ # Prepare the text
154
+ if len(ref_text[-1].encode('utf-8')) == 1:
155
+ ref_text = ref_text + " "
156
+ text_list = [ref_text + gen_text]
157
+ final_text_list = convert_char_to_pinyin(text_list)
158
+
159
+ # Calculate duration
160
+ ref_audio_len = audio.shape[-1] // hop_length
161
+ zh_pause_punc = r"。,、;:?!"
162
+ ref_text_len = len(ref_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, ref_text))
163
+ gen_text_len = len(gen_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, gen_text))
164
+ duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
165
+
166
+ # inference
167
+ with torch.inference_mode():
168
+ generated, _ = ema_model.sample(
169
+ cond=audio,
170
+ text=final_text_list,
171
+ duration=duration,
172
+ steps=nfe_step,
173
+ cfg_strength=cfg_strength,
174
+ sway_sampling_coef=sway_sampling_coef,
175
+ )
176
+
177
+ generated = generated[:, ref_audio_len:, :]
178
+ generated_mel_spec = rearrange(generated, "1 n d -> 1 d n")
179
+ generated_wave = vocos.decode(generated_mel_spec.cpu())
180
+ if rms < target_rms:
181
+ generated_wave = generated_wave * rms / target_rms
182
+
183
+ # wav -> numpy
184
+ generated_wave = generated_wave.squeeze().cpu().numpy()
185
+
186
+ generated_waves.append(generated_wave)
187
+ spectrograms.append(generated_mel_spec[0].cpu().numpy())
188
+
189
+ # Combine all generated waves with cross-fading
190
+ if cross_fade_duration <= 0:
191
+ # Simply concatenate
192
+ final_wave = np.concatenate(generated_waves)
193
+ else:
194
+ final_wave = generated_waves[0]
195
+ for i in range(1, len(generated_waves)):
196
+ prev_wave = final_wave
197
+ next_wave = generated_waves[i]
198
+
199
+ # Calculate cross-fade samples, ensuring it does not exceed wave lengths
200
+ cross_fade_samples = int(cross_fade_duration * target_sample_rate)
201
+ cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
202
+
203
+ if cross_fade_samples <= 0:
204
+ # No overlap possible, concatenate
205
+ final_wave = np.concatenate([prev_wave, next_wave])
206
+ continue
207
+
208
+ # Overlapping parts
209
+ prev_overlap = prev_wave[-cross_fade_samples:]
210
+ next_overlap = next_wave[:cross_fade_samples]
211
+
212
+ # Fade out and fade in
213
+ fade_out = np.linspace(1, 0, cross_fade_samples)
214
+ fade_in = np.linspace(0, 1, cross_fade_samples)
215
+
216
+ # Cross-faded overlap
217
+ cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
218
+
219
+ # Combine
220
+ new_wave = np.concatenate([
221
+ prev_wave[:-cross_fade_samples],
222
+ cross_faded_overlap,
223
+ next_wave[cross_fade_samples:]
224
+ ])
225
+
226
+ final_wave = new_wave
227
+
228
+ # Remove silence
229
+ if remove_silence:
230
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
231
+ sf.write(f.name, final_wave, target_sample_rate)
232
+ aseg = AudioSegment.from_file(f.name)
233
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
234
+ non_silent_wave = AudioSegment.silent(duration=0)
235
+ for non_silent_seg in non_silent_segs:
236
+ non_silent_wave += non_silent_seg
237
+ aseg = non_silent_wave
238
+ aseg.export(f.name, format="wav")
239
+ final_wave, _ = torchaudio.load(f.name)
240
+ final_wave = final_wave.squeeze().cpu().numpy()
241
+
242
+ # Create a combined spectrogram
243
+ combined_spectrogram = np.concatenate(spectrograms, axis=1)
244
+
245
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
246
+ spectrogram_path = tmp_spectrogram.name
247
+ save_spectrogram(combined_spectrogram, spectrogram_path)
248
+
249
+ return (target_sample_rate, final_wave), spectrogram_path
250
+
251
+ @gpu_decorator
252
+ def infer(ref_audio_orig, ref_text, gen_text, exp_name, remove_silence, cross_fade_duration=0.15):
253
+
254
+ print(gen_text)
255
+
256
+ gr.Info("Converting audio...")
257
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
258
+ aseg = AudioSegment.from_file(ref_audio_orig)
259
+
260
+ non_silent_segs = silence.split_on_silence(
261
+ aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000
262
+ )
263
+ non_silent_wave = AudioSegment.silent(duration=0)
264
+ for non_silent_seg in non_silent_segs:
265
+ non_silent_wave += non_silent_seg
266
+ aseg = non_silent_wave
267
+
268
+ audio_duration = len(aseg)
269
+ if audio_duration > 15000:
270
+ gr.Warning("Audio is over 15s, clipping to only first 15s.")
271
+ aseg = aseg[:15000]
272
+ aseg.export(f.name, format="wav")
273
+ ref_audio = f.name
274
+
275
+ if not ref_text.strip():
276
+ gr.Info("No reference text provided, transcribing reference audio...")
277
+ ref_text = pipe(
278
+ ref_audio,
279
+ chunk_length_s=30,
280
+ batch_size=128,
281
+ generate_kwargs={"task": "transcribe"},
282
+ return_timestamps=False,
283
+ )["text"].strip()
284
+ gr.Info("Finished transcription")
285
+ else:
286
+ gr.Info("Using custom reference text...")
287
+
288
+ # Add the functionality to ensure it ends with ". "
289
+ if not ref_text.endswith(". "):
290
+ if ref_text.endswith("."):
291
+ ref_text += " "
292
+ else:
293
+ ref_text += ". "
294
+
295
+ audio, sr = torchaudio.load(ref_audio)
296
+
297
+ # Use the new chunk_text function to split gen_text
298
+ max_chars = int(len(ref_text.encode('utf-8')) / (audio.shape[-1] / sr) * (25 - audio.shape[-1] / sr))
299
+ gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
300
+ print('ref_text', ref_text)
301
+ for i, batch_text in enumerate(gen_text_batches):
302
+ print(f'gen_text {i}', batch_text)
303
+
304
+ gr.Info(f"Generating audio using {exp_name} in {len(gen_text_batches)} batches")
305
+ return infer_batch((audio, sr), ref_text, gen_text_batches, exp_name, remove_silence, cross_fade_duration)
306
+
307
+
308
+ @gpu_decorator
309
+ def generate_podcast(script, speaker1_name, ref_audio1, ref_text1, speaker2_name, ref_audio2, ref_text2, exp_name, remove_silence):
310
+ # Split the script into speaker blocks
311
+ speaker_pattern = re.compile(f"^({re.escape(speaker1_name)}|{re.escape(speaker2_name)}):", re.MULTILINE)
312
+ speaker_blocks = speaker_pattern.split(script)[1:] # Skip the first empty element
313
+
314
+ generated_audio_segments = []
315
+
316
+ for i in range(0, len(speaker_blocks), 2):
317
+ speaker = speaker_blocks[i]
318
+ text = speaker_blocks[i+1].strip()
319
+
320
+ # Determine which speaker is talking
321
+ if speaker == speaker1_name:
322
+ ref_audio = ref_audio1
323
+ ref_text = ref_text1
324
+ elif speaker == speaker2_name:
325
+ ref_audio = ref_audio2
326
+ ref_text = ref_text2
327
+ else:
328
+ continue # Skip if the speaker is neither speaker1 nor speaker2
329
+
330
+ # Generate audio for this block
331
+ audio, _ = infer(ref_audio, ref_text, text, exp_name, remove_silence)
332
+
333
+ # Convert the generated audio to a numpy array
334
+ sr, audio_data = audio
335
+
336
+ # Save the audio data as a WAV file
337
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
338
+ sf.write(temp_file.name, audio_data, sr)
339
+ audio_segment = AudioSegment.from_wav(temp_file.name)
340
+
341
+ generated_audio_segments.append(audio_segment)
342
+
343
+ # Add a short pause between speakers
344
+ pause = AudioSegment.silent(duration=500) # 500ms pause
345
+ generated_audio_segments.append(pause)
346
+
347
+ # Concatenate all audio segments
348
+ final_podcast = sum(generated_audio_segments)
349
+
350
+ # Export the final podcast
351
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
352
+ podcast_path = temp_file.name
353
+ final_podcast.export(podcast_path, format="wav")
354
+
355
+ return podcast_path
356
+
357
+ def parse_speechtypes_text(gen_text):
358
+ # Pattern to find (Emotion)
359
+ pattern = r'\((.*?)\)'
360
+
361
+ # Split the text by the pattern
362
+ tokens = re.split(pattern, gen_text)
363
+
364
+ segments = []
365
+
366
+ current_emotion = 'Regular'
367
+
368
+ for i in range(len(tokens)):
369
+ if i % 2 == 0:
370
+ # This is text
371
+ text = tokens[i].strip()
372
+ if text:
373
+ segments.append({'emotion': current_emotion, 'text': text})
374
+ else:
375
+ # This is emotion
376
+ emotion = tokens[i].strip()
377
+ current_emotion = emotion
378
+
379
+ return segments
380
+
381
+ def update_speed(new_speed):
382
+ global speed
383
+ speed = new_speed
384
+ return f"Speed set to: {speed}"
385
+
386
+ with gr.Blocks() as app_credits:
387
+ gr.Markdown("""
388
+ # Credits
389
+
390
+ * [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
391
+ * [RootingInLoad](https://github.com/RootingInLoad) for the podcast generation
392
+ * [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation
393
+ """)
394
+ with gr.Blocks() as app_tts:
395
+ gr.Markdown("# Batched TTS")
396
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
397
+ gen_text_input = gr.Textbox(label="Text to Generate", lines=10)
398
+ model_choice = gr.Radio(
399
+ choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
400
+ )
401
+ generate_btn = gr.Button("Synthesize", variant="primary")
402
+ with gr.Accordion("Advanced Settings", open=False):
403
+ ref_text_input = gr.Textbox(
404
+ label="Reference Text",
405
+ info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.",
406
+ lines=2,
407
+ )
408
+ remove_silence = gr.Checkbox(
409
+ label="Remove Silences",
410
+ 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.",
411
+ value=False,
412
+ )
413
+ speed_slider = gr.Slider(
414
+ label="Speed",
415
+ minimum=0.3,
416
+ maximum=2.0,
417
+ value=speed,
418
+ step=0.1,
419
+ info="Adjust the speed of the audio.",
420
+ )
421
+ cross_fade_duration_slider = gr.Slider(
422
+ label="Cross-Fade Duration (s)",
423
+ minimum=0.0,
424
+ maximum=1.0,
425
+ value=0.15,
426
+ step=0.01,
427
+ info="Set the duration of the cross-fade between audio clips.",
428
+ )
429
+ speed_slider.change(update_speed, inputs=speed_slider)
430
+
431
+ audio_output = gr.Audio(label="Synthesized Audio")
432
+ spectrogram_output = gr.Image(label="Spectrogram")
433
+
434
+ generate_btn.click(
435
+ infer,
436
+ inputs=[
437
+ ref_audio_input,
438
+ ref_text_input,
439
+ gen_text_input,
440
+ model_choice,
441
+ remove_silence,
442
+ cross_fade_duration_slider,
443
+ ],
444
+ outputs=[audio_output, spectrogram_output],
445
+ )
446
+
447
+ with gr.Blocks() as app_podcast:
448
+ gr.Markdown("# Podcast Generation")
449
+ speaker1_name = gr.Textbox(label="Speaker 1 Name")
450
+ ref_audio_input1 = gr.Audio(label="Reference Audio (Speaker 1)", type="filepath")
451
+ ref_text_input1 = gr.Textbox(label="Reference Text (Speaker 1)", lines=2)
452
+
453
+ speaker2_name = gr.Textbox(label="Speaker 2 Name")
454
+ ref_audio_input2 = gr.Audio(label="Reference Audio (Speaker 2)", type="filepath")
455
+ ref_text_input2 = gr.Textbox(label="Reference Text (Speaker 2)", lines=2)
456
+
457
+ script_input = gr.Textbox(label="Podcast Script", lines=10,
458
+ 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...")
459
+
460
+ podcast_model_choice = gr.Radio(
461
+ choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
462
+ )
463
+ podcast_remove_silence = gr.Checkbox(
464
+ label="Remove Silences",
465
+ value=True,
466
+ )
467
+ generate_podcast_btn = gr.Button("Generate Podcast", variant="primary")
468
+ podcast_output = gr.Audio(label="Generated Podcast")
469
+
470
+ def podcast_generation(script, speaker1, ref_audio1, ref_text1, speaker2, ref_audio2, ref_text2, model, remove_silence):
471
+ return generate_podcast(script, speaker1, ref_audio1, ref_text1, speaker2, ref_audio2, ref_text2, model, remove_silence)
472
+
473
+ generate_podcast_btn.click(
474
+ podcast_generation,
475
+ inputs=[
476
+ script_input,
477
+ speaker1_name,
478
+ ref_audio_input1,
479
+ ref_text_input1,
480
+ speaker2_name,
481
+ ref_audio_input2,
482
+ ref_text_input2,
483
+ podcast_model_choice,
484
+ podcast_remove_silence,
485
+ ],
486
+ outputs=podcast_output,
487
+ )
488
+
489
+ def parse_emotional_text(gen_text):
490
+ # Pattern to find (Emotion)
491
+ pattern = r'\((.*?)\)'
492
+
493
+ # Split the text by the pattern
494
+ tokens = re.split(pattern, gen_text)
495
+
496
+ segments = []
497
+
498
+ current_emotion = 'Regular'
499
+
500
+ for i in range(len(tokens)):
501
+ if i % 2 == 0:
502
+ # This is text
503
+ text = tokens[i].strip()
504
+ if text:
505
+ segments.append({'emotion': current_emotion, 'text': text})
506
+ else:
507
+ # This is emotion
508
+ emotion = tokens[i].strip()
509
+ current_emotion = emotion
510
+
511
+ return segments
512
+
513
+ with gr.Blocks() as app_emotional:
514
+ # New section for emotional generation
515
+ gr.Markdown(
516
+ """
517
+ # Multiple Speech-Type Generation
518
+
519
+ 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.
520
+
521
+ **Example Input:**
522
+
523
+ (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?!
524
+ """
525
+ )
526
+
527
+ 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.")
528
+
529
+ # Regular speech type (mandatory)
530
+ with gr.Row():
531
+ regular_name = gr.Textbox(value='Regular', label='Speech Type Name', interactive=False)
532
+ regular_audio = gr.Audio(label='Regular Reference Audio', type='filepath')
533
+ regular_ref_text = gr.Textbox(label='Reference Text (Regular)', lines=2)
534
+
535
+ # Additional speech types (up to 9 more)
536
+ max_speech_types = 10
537
+ speech_type_names = []
538
+ speech_type_audios = []
539
+ speech_type_ref_texts = []
540
+ speech_type_delete_btns = []
541
+
542
+ for i in range(max_speech_types - 1):
543
+ with gr.Row():
544
+ name_input = gr.Textbox(label='Speech Type Name', visible=False)
545
+ audio_input = gr.Audio(label='Reference Audio', type='filepath', visible=False)
546
+ ref_text_input = gr.Textbox(label='Reference Text', lines=2, visible=False)
547
+ delete_btn = gr.Button("Delete", variant="secondary", visible=False)
548
+ speech_type_names.append(name_input)
549
+ speech_type_audios.append(audio_input)
550
+ speech_type_ref_texts.append(ref_text_input)
551
+ speech_type_delete_btns.append(delete_btn)
552
+
553
+ # Button to add speech type
554
+ add_speech_type_btn = gr.Button("Add Speech Type")
555
+
556
+ # Keep track of current number of speech types
557
+ speech_type_count = gr.State(value=0)
558
+
559
+ # Function to add a speech type
560
+ def add_speech_type_fn(speech_type_count):
561
+ if speech_type_count < max_speech_types - 1:
562
+ speech_type_count += 1
563
+ # Prepare updates for the components
564
+ name_updates = []
565
+ audio_updates = []
566
+ ref_text_updates = []
567
+ delete_btn_updates = []
568
+ for i in range(max_speech_types - 1):
569
+ if i < speech_type_count:
570
+ name_updates.append(gr.update(visible=True))
571
+ audio_updates.append(gr.update(visible=True))
572
+ ref_text_updates.append(gr.update(visible=True))
573
+ delete_btn_updates.append(gr.update(visible=True))
574
+ else:
575
+ name_updates.append(gr.update())
576
+ audio_updates.append(gr.update())
577
+ ref_text_updates.append(gr.update())
578
+ delete_btn_updates.append(gr.update())
579
+ else:
580
+ # Optionally, show a warning
581
+ # gr.Warning("Maximum number of speech types reached.")
582
+ name_updates = [gr.update() for _ in range(max_speech_types - 1)]
583
+ audio_updates = [gr.update() for _ in range(max_speech_types - 1)]
584
+ ref_text_updates = [gr.update() for _ in range(max_speech_types - 1)]
585
+ delete_btn_updates = [gr.update() for _ in range(max_speech_types - 1)]
586
+ return [speech_type_count] + name_updates + audio_updates + ref_text_updates + delete_btn_updates
587
+
588
+ add_speech_type_btn.click(
589
+ add_speech_type_fn,
590
+ inputs=speech_type_count,
591
+ outputs=[speech_type_count] + speech_type_names + speech_type_audios + speech_type_ref_texts + speech_type_delete_btns
592
+ )
593
+
594
+ # Function to delete a speech type
595
+ def make_delete_speech_type_fn(index):
596
+ def delete_speech_type_fn(speech_type_count):
597
+ # Prepare updates
598
+ name_updates = []
599
+ audio_updates = []
600
+ ref_text_updates = []
601
+ delete_btn_updates = []
602
+
603
+ for i in range(max_speech_types - 1):
604
+ if i == index:
605
+ name_updates.append(gr.update(visible=False, value=''))
606
+ audio_updates.append(gr.update(visible=False, value=None))
607
+ ref_text_updates.append(gr.update(visible=False, value=''))
608
+ delete_btn_updates.append(gr.update(visible=False))
609
+ else:
610
+ name_updates.append(gr.update())
611
+ audio_updates.append(gr.update())
612
+ ref_text_updates.append(gr.update())
613
+ delete_btn_updates.append(gr.update())
614
+
615
+ speech_type_count = max(0, speech_type_count - 1)
616
+
617
+ return [speech_type_count] + name_updates + audio_updates + ref_text_updates + delete_btn_updates
618
+
619
+ return delete_speech_type_fn
620
+
621
+ for i, delete_btn in enumerate(speech_type_delete_btns):
622
+ delete_fn = make_delete_speech_type_fn(i)
623
+ delete_btn.click(
624
+ delete_fn,
625
+ inputs=speech_type_count,
626
+ outputs=[speech_type_count] + speech_type_names + speech_type_audios + speech_type_ref_texts + speech_type_delete_btns
627
+ )
628
+
629
+ # Text input for the prompt
630
+ gen_text_input_emotional = gr.Textbox(label="Text to Generate", lines=10)
631
+
632
+ # Model choice
633
+ model_choice_emotional = gr.Radio(
634
+ choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
635
+ )
636
+
637
+ with gr.Accordion("Advanced Settings", open=False):
638
+ remove_silence_emotional = gr.Checkbox(
639
+ label="Remove Silences",
640
+ value=True,
641
+ )
642
+
643
+ # Generate button
644
+ generate_emotional_btn = gr.Button("Generate Emotional Speech", variant="primary")
645
+
646
+ # Output audio
647
+ audio_output_emotional = gr.Audio(label="Synthesized Audio")
648
+ @gpu_decorator
649
+ def generate_emotional_speech(
650
+ regular_audio,
651
+ regular_ref_text,
652
+ gen_text,
653
+ *args,
654
+ ):
655
+ num_additional_speech_types = max_speech_types - 1
656
+ speech_type_names_list = args[:num_additional_speech_types]
657
+ speech_type_audios_list = args[num_additional_speech_types:2 * num_additional_speech_types]
658
+ speech_type_ref_texts_list = args[2 * num_additional_speech_types:3 * num_additional_speech_types]
659
+ model_choice = args[3 * num_additional_speech_types]
660
+ remove_silence = args[3 * num_additional_speech_types + 1]
661
+
662
+ # Collect the speech types and their audios into a dict
663
+ speech_types = {'Regular': {'audio': regular_audio, 'ref_text': regular_ref_text}}
664
+
665
+ for name_input, audio_input, ref_text_input in zip(speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list):
666
+ if name_input and audio_input:
667
+ speech_types[name_input] = {'audio': audio_input, 'ref_text': ref_text_input}
668
+
669
+ # Parse the gen_text into segments
670
+ segments = parse_speechtypes_text(gen_text)
671
+
672
+ # For each segment, generate speech
673
+ generated_audio_segments = []
674
+ current_emotion = 'Regular'
675
+
676
+ for segment in segments:
677
+ emotion = segment['emotion']
678
+ text = segment['text']
679
+
680
+ if emotion in speech_types:
681
+ current_emotion = emotion
682
+ else:
683
+ # If emotion not available, default to Regular
684
+ current_emotion = 'Regular'
685
+
686
+ ref_audio = speech_types[current_emotion]['audio']
687
+ ref_text = speech_types[current_emotion].get('ref_text', '')
688
+
689
+ # Generate speech for this segment
690
+ audio, _ = infer(ref_audio, ref_text, text, model_choice, remove_silence, 0)
691
+ sr, audio_data = audio
692
+
693
+ generated_audio_segments.append(audio_data)
694
+
695
+ # Concatenate all audio segments
696
+ if generated_audio_segments:
697
+ final_audio_data = np.concatenate(generated_audio_segments)
698
+ return (sr, final_audio_data)
699
+ else:
700
+ gr.Warning("No audio generated.")
701
+ return None
702
+
703
+ generate_emotional_btn.click(
704
+ generate_emotional_speech,
705
+ inputs=[
706
+ regular_audio,
707
+ regular_ref_text,
708
+ gen_text_input_emotional,
709
+ ] + speech_type_names + speech_type_audios + speech_type_ref_texts + [
710
+ model_choice_emotional,
711
+ remove_silence_emotional,
712
+ ],
713
+ outputs=audio_output_emotional,
714
+ )
715
+
716
+ # Validation function to disable Generate button if speech types are missing
717
+ def validate_speech_types(
718
+ gen_text,
719
+ regular_name,
720
+ *args
721
+ ):
722
+ num_additional_speech_types = max_speech_types - 1
723
+ speech_type_names_list = args[:num_additional_speech_types]
724
+
725
+ # Collect the speech types names
726
+ speech_types_available = set()
727
+ if regular_name:
728
+ speech_types_available.add(regular_name)
729
+ for name_input in speech_type_names_list:
730
+ if name_input:
731
+ speech_types_available.add(name_input)
732
+
733
+ # Parse the gen_text to get the speech types used
734
+ segments = parse_emotional_text(gen_text)
735
+ speech_types_in_text = set(segment['emotion'] for segment in segments)
736
+
737
+ # Check if all speech types in text are available
738
+ missing_speech_types = speech_types_in_text - speech_types_available
739
+
740
+ if missing_speech_types:
741
+ # Disable the generate button
742
+ return gr.update(interactive=False)
743
+ else:
744
+ # Enable the generate button
745
+ return gr.update(interactive=True)
746
+
747
+ gen_text_input_emotional.change(
748
+ validate_speech_types,
749
+ inputs=[gen_text_input_emotional, regular_name] + speech_type_names,
750
+ outputs=generate_emotional_btn
751
+ )
752
+ with gr.Blocks() as app:
753
+ gr.Markdown(
754
+ """
755
+ # E2/F5 TTS
756
+
757
+ This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
758
+
759
+ * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
760
+ * [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
761
+
762
+ The checkpoints support English and Chinese.
763
+
764
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt.
765
+
766
+ **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.**
767
+ """
768
+ )
769
+ gr.TabbedInterface([app_tts, app_podcast, app_emotional, app_credits], ["TTS", "Podcast", "Multi-Style", "Credits"])
770
+
771
+ @click.command()
772
+ @click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
773
+ @click.option("--host", "-H", default=None, help="Host to run the app on")
774
+ @click.option(
775
+ "--share",
776
+ "-s",
777
+ default=False,
778
+ is_flag=True,
779
+ help="Share the app via Gradio share link",
780
+ )
781
+ @click.option("--api", "-a", default=True, is_flag=True, help="Allow API access")
782
+ def main(port, host, share, api):
783
+ global app
784
+ print(f"Starting app...")
785
+ app.queue(api_open=api).launch(
786
+ server_name=host, server_port=port, share=share, show_api=api
787
+ )
788
+
789
+
790
+ if __name__ == "__main__":
791
+ main()
app_local.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("WARNING: You are running this unofficial E2/F5 TTS demo locally, it may not be as up-to-date as the hosted version (https://huggingface.co/spaces/mrfakename/E2-F5-TTS)")
2
+
3
+ import os
4
+ import re
5
+ import torch
6
+ import torchaudio
7
+ import gradio as gr
8
+ import numpy as np
9
+ import tempfile
10
+ from einops import rearrange
11
+ from ema_pytorch import EMA
12
+ from vocos import Vocos
13
+ from pydub import AudioSegment, silence
14
+ from model import CFM, UNetT, DiT, MMDiT
15
+ from cached_path import cached_path
16
+ from model.utils import (
17
+ get_tokenizer,
18
+ convert_char_to_pinyin,
19
+ save_spectrogram,
20
+ )
21
+ from transformers import pipeline
22
+ import librosa
23
+ import soundfile as sf
24
+ from txtsplit import txtsplit
25
+
26
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
27
+
28
+ pipe = pipeline(
29
+ "automatic-speech-recognition",
30
+ model="openai/whisper-large-v3-turbo",
31
+ torch_dtype=torch.float16,
32
+ device=device,
33
+ )
34
+
35
+ vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
36
+
37
+ # --------------------- Settings -------------------- #
38
+
39
+ target_sample_rate = 24000
40
+ n_mel_channels = 100
41
+ hop_length = 256
42
+ target_rms = 0.1
43
+ nfe_step = 32 # 16, 32
44
+ cfg_strength = 2.0
45
+ ode_method = 'euler'
46
+ sway_sampling_coef = -1.0
47
+ speed = 1.0
48
+ # fix_duration = 27 # None or float (duration in seconds)
49
+ fix_duration = None
50
+
51
+ def load_model(repo_name, exp_name, model_cls, model_cfg, ckpt_step):
52
+ checkpoint = torch.load(str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.pt")), map_location=device)
53
+ vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
54
+ model = CFM(
55
+ transformer=model_cls(
56
+ **model_cfg,
57
+ text_num_embeds=vocab_size,
58
+ mel_dim=n_mel_channels
59
+ ),
60
+ mel_spec_kwargs=dict(
61
+ target_sample_rate=target_sample_rate,
62
+ n_mel_channels=n_mel_channels,
63
+ hop_length=hop_length,
64
+ ),
65
+ odeint_kwargs=dict(
66
+ method=ode_method,
67
+ ),
68
+ vocab_char_map=vocab_char_map,
69
+ ).to(device)
70
+
71
+ ema_model = EMA(model, include_online_model=False).to(device)
72
+ ema_model.load_state_dict(checkpoint['ema_model_state_dict'])
73
+ ema_model.copy_params_from_ema_to_model()
74
+
75
+ return model
76
+
77
+ # load models
78
+ F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
79
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
80
+
81
+ F5TTS_ema_model = load_model("F5-TTS", "F5TTS_Base", DiT, F5TTS_model_cfg, 1200000)
82
+ E2TTS_ema_model = load_model("E2-TTS", "E2TTS_Base", UNetT, E2TTS_model_cfg, 1200000)
83
+
84
+ def infer(ref_audio_orig, ref_text, gen_text, exp_name, remove_silence, progress = gr.Progress()):
85
+ print(gen_text)
86
+ gr.Info("Converting audio...")
87
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
88
+ aseg = AudioSegment.from_file(ref_audio_orig)
89
+ # remove long silence in reference audio
90
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
91
+ non_silent_wave = AudioSegment.silent(duration=0)
92
+ for non_silent_seg in non_silent_segs:
93
+ non_silent_wave += non_silent_seg
94
+ aseg = non_silent_wave
95
+ # Convert to mono
96
+ aseg = aseg.set_channels(1)
97
+ audio_duration = len(aseg)
98
+ if audio_duration > 15000:
99
+ gr.Warning("Audio is over 15s, clipping to only first 15s.")
100
+ aseg = aseg[:15000]
101
+ aseg.export(f.name, format="wav")
102
+ ref_audio = f.name
103
+ if exp_name == "F5-TTS":
104
+ ema_model = F5TTS_ema_model
105
+ elif exp_name == "E2-TTS":
106
+ ema_model = E2TTS_ema_model
107
+
108
+ if not ref_text.strip():
109
+ gr.Info("No reference text provided, transcribing reference audio...")
110
+ ref_text = outputs = pipe(
111
+ ref_audio,
112
+ chunk_length_s=30,
113
+ batch_size=128,
114
+ generate_kwargs={"task": "transcribe"},
115
+ return_timestamps=False,
116
+ )['text'].strip()
117
+ gr.Info("Finished transcription")
118
+ else:
119
+ gr.Info("Using custom reference text...")
120
+ audio, sr = torchaudio.load(ref_audio)
121
+ max_chars = int(len(ref_text) / (audio.shape[-1] / sr) * (30 - audio.shape[-1] / sr))
122
+ # Audio
123
+ if audio.shape[0] > 1:
124
+ audio = torch.mean(audio, dim=0, keepdim=True)
125
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
126
+ if rms < target_rms:
127
+ audio = audio * target_rms / rms
128
+ if sr != target_sample_rate:
129
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
130
+ audio = resampler(audio)
131
+ audio = audio.to(device)
132
+ # Chunk
133
+ chunks = txtsplit(gen_text, 0.7*max_chars, 0.9*max_chars) # 100 chars preferred, 150 max
134
+ results = []
135
+ generated_mel_specs = []
136
+ for chunk in progress.tqdm(chunks):
137
+ # Prepare the text
138
+ text_list = [ref_text + chunk]
139
+ final_text_list = convert_char_to_pinyin(text_list)
140
+
141
+ # Calculate duration
142
+ ref_audio_len = audio.shape[-1] // hop_length
143
+ # if fix_duration is not None:
144
+ # duration = int(fix_duration * target_sample_rate / hop_length)
145
+ # else:
146
+ zh_pause_punc = r"。,、;:?!"
147
+ ref_text_len = len(ref_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, ref_text))
148
+ chunk = len(chunk.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, gen_text))
149
+ duration = ref_audio_len + int(ref_audio_len / ref_text_len * chunk / speed)
150
+
151
+ # inference
152
+ gr.Info(f"Generating audio using {exp_name}")
153
+ with torch.inference_mode():
154
+ generated, _ = ema_model.sample(
155
+ cond=audio,
156
+ text=final_text_list,
157
+ duration=duration,
158
+ steps=nfe_step,
159
+ cfg_strength=cfg_strength,
160
+ sway_sampling_coef=sway_sampling_coef,
161
+ )
162
+
163
+ generated = generated[:, ref_audio_len:, :]
164
+ generated_mel_spec = rearrange(generated, '1 n d -> 1 d n')
165
+ gr.Info("Running vocoder")
166
+ generated_wave = vocos.decode(generated_mel_spec.cpu())
167
+ if rms < target_rms:
168
+ generated_wave = generated_wave * rms / target_rms
169
+
170
+ # wav -> numpy
171
+ generated_wave = generated_wave.squeeze().cpu().numpy()
172
+ results.append(generated_wave)
173
+ generated_wave = np.concatenate(results)
174
+ if remove_silence:
175
+ gr.Info("Removing audio silences... This may take a moment")
176
+ # non_silent_intervals = librosa.effects.split(generated_wave, top_db=30)
177
+ # non_silent_wave = np.array([])
178
+ # for interval in non_silent_intervals:
179
+ # start, end = interval
180
+ # non_silent_wave = np.concatenate([non_silent_wave, generated_wave[start:end]])
181
+ # generated_wave = non_silent_wave
182
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
183
+ sf.write(f.name, generated_wave, target_sample_rate)
184
+ aseg = AudioSegment.from_file(f.name)
185
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
186
+ non_silent_wave = AudioSegment.silent(duration=0)
187
+ for non_silent_seg in non_silent_segs:
188
+ non_silent_wave += non_silent_seg
189
+ aseg = non_silent_wave
190
+ aseg.export(f.name, format="wav")
191
+ generated_wave, _ = torchaudio.load(f.name)
192
+ generated_wave = generated_wave.squeeze().cpu().numpy()
193
+
194
+ # spectogram
195
+ # with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
196
+ # spectrogram_path = tmp_spectrogram.name
197
+ # save_spectrogram(generated_mel_spec[0].cpu().numpy(), spectrogram_path)
198
+
199
+ return (target_sample_rate, generated_wave)
200
+
201
+ with gr.Blocks() as app:
202
+ gr.Markdown("""
203
+ # E2/F5 TTS
204
+
205
+ This is an unofficial E2/F5 TTS demo. This demo supports the following TTS models:
206
+
207
+ * [E2-TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
208
+ * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
209
+
210
+ This demo is based on the [F5-TTS](https://github.com/SWivid/F5-TTS) codebase, which is based on an [unofficial E2-TTS implementation](https://github.com/lucidrains/e2-tts-pytorch).
211
+
212
+ The checkpoints support English and Chinese.
213
+
214
+ If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt. If you're still running into issues, please open a [community Discussion](https://huggingface.co/spaces/mrfakename/E2-F5-TTS/discussions).
215
+
216
+ Long-form/batched inference + speech editing is coming soon!
217
+
218
+ **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.**
219
+ """)
220
+
221
+ ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
222
+ gen_text_input = gr.Textbox(label="Text to Generate (longer text will use chunking)", lines=4)
223
+ model_choice = gr.Radio(choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS")
224
+ generate_btn = gr.Button("Synthesize", variant="primary")
225
+ with gr.Accordion("Advanced Settings", open=False):
226
+ ref_text_input = gr.Textbox(label="Reference Text", info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.", lines=2)
227
+ remove_silence = gr.Checkbox(label="Remove Silences", 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.", value=True)
228
+
229
+ audio_output = gr.Audio(label="Synthesized Audio")
230
+ # spectrogram_output = gr.Image(label="Spectrogram")
231
+
232
+ generate_btn.click(infer, inputs=[ref_audio_input, ref_text_input, gen_text_input, model_choice, remove_silence], outputs=[audio_output])
233
+ gr.Markdown("Unofficial demo by [mrfakename](https://x.com/realmrfakename)")
234
+
235
+
236
+ app.queue().launch()
inference-cli.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import codecs
3
+ import re
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import soundfile as sf
9
+ import tomli
10
+ import torch
11
+ import torchaudio
12
+ import tqdm
13
+ from cached_path import cached_path
14
+ from einops import rearrange
15
+ from pydub import AudioSegment, silence
16
+ from transformers import pipeline
17
+ from vocos import Vocos
18
+
19
+ from model import CFM, DiT, MMDiT, UNetT
20
+ from model.utils import (convert_char_to_pinyin, get_tokenizer,
21
+ load_checkpoint, save_spectrogram)
22
+
23
+ parser = argparse.ArgumentParser(
24
+ prog="python3 inference-cli.py",
25
+ description="Commandline interface for E2/F5 TTS with Advanced Batch Processing.",
26
+ epilog="Specify options above to override one or more settings from config.",
27
+ )
28
+ parser.add_argument(
29
+ "-c",
30
+ "--config",
31
+ help="Configuration file. Default=cli-config.toml",
32
+ default="inference-cli.toml",
33
+ )
34
+ parser.add_argument(
35
+ "-m",
36
+ "--model",
37
+ help="F5-TTS | E2-TTS",
38
+ )
39
+ parser.add_argument(
40
+ "-r",
41
+ "--ref_audio",
42
+ type=str,
43
+ help="Reference audio file < 15 seconds."
44
+ )
45
+ parser.add_argument(
46
+ "-s",
47
+ "--ref_text",
48
+ type=str,
49
+ default="666",
50
+ help="Subtitle for the reference audio."
51
+ )
52
+ parser.add_argument(
53
+ "-t",
54
+ "--gen_text",
55
+ type=str,
56
+ help="Text to generate.",
57
+ )
58
+ parser.add_argument(
59
+ "-f",
60
+ "--gen_file",
61
+ type=str,
62
+ help="File with text to generate. Ignores --text",
63
+ )
64
+ parser.add_argument(
65
+ "-o",
66
+ "--output_dir",
67
+ type=str,
68
+ help="Path to output folder..",
69
+ )
70
+ parser.add_argument(
71
+ "--remove_silence",
72
+ help="Remove silence.",
73
+ )
74
+ parser.add_argument(
75
+ "--load_vocoder_from_local",
76
+ action="store_true",
77
+ help="load vocoder from local. Default: ../checkpoints/charactr/vocos-mel-24khz",
78
+ )
79
+ args = parser.parse_args()
80
+
81
+ config = tomli.load(open(args.config, "rb"))
82
+
83
+ ref_audio = args.ref_audio if args.ref_audio else config["ref_audio"]
84
+ ref_text = args.ref_text if args.ref_text != "666" else config["ref_text"]
85
+ gen_text = args.gen_text if args.gen_text else config["gen_text"]
86
+ gen_file = args.gen_file if args.gen_file else config["gen_file"]
87
+ if gen_file:
88
+ gen_text = codecs.open(gen_file, "r", "utf-8").read()
89
+ output_dir = args.output_dir if args.output_dir else config["output_dir"]
90
+ model = args.model if args.model else config["model"]
91
+ remove_silence = args.remove_silence if args.remove_silence else config["remove_silence"]
92
+ wave_path = Path(output_dir)/"out.wav"
93
+ spectrogram_path = Path(output_dir)/"out.png"
94
+ vocos_local_path = "../checkpoints/charactr/vocos-mel-24khz"
95
+
96
+ device = (
97
+ "cuda"
98
+ if torch.cuda.is_available()
99
+ else "mps" if torch.backends.mps.is_available() else "cpu"
100
+ )
101
+
102
+ if args.load_vocoder_from_local:
103
+ print(f"Load vocos from local path {vocos_local_path}")
104
+ vocos = Vocos.from_hparams(f"{vocos_local_path}/config.yaml")
105
+ state_dict = torch.load(f"{vocos_local_path}/pytorch_model.bin", map_location=device)
106
+ vocos.load_state_dict(state_dict)
107
+ vocos.eval()
108
+ else:
109
+ print("Donwload Vocos from huggingface charactr/vocos-mel-24khz")
110
+ vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
111
+
112
+ print(f"Using {device} device")
113
+
114
+ # --------------------- Settings -------------------- #
115
+
116
+ target_sample_rate = 24000
117
+ n_mel_channels = 100
118
+ hop_length = 256
119
+ target_rms = 0.1
120
+ nfe_step = 32 # 16, 32
121
+ cfg_strength = 2.0
122
+ ode_method = "euler"
123
+ sway_sampling_coef = -1.0
124
+ speed = 1.0
125
+ # fix_duration = 27 # None or float (duration in seconds)
126
+ fix_duration = None
127
+
128
+ def load_model(repo_name, exp_name, model_cls, model_cfg, ckpt_step):
129
+ ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors
130
+ if not Path(ckpt_path).exists():
131
+ ckpt_path = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
132
+ vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
133
+ model = CFM(
134
+ transformer=model_cls(
135
+ **model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels
136
+ ),
137
+ mel_spec_kwargs=dict(
138
+ target_sample_rate=target_sample_rate,
139
+ n_mel_channels=n_mel_channels,
140
+ hop_length=hop_length,
141
+ ),
142
+ odeint_kwargs=dict(
143
+ method=ode_method,
144
+ ),
145
+ vocab_char_map=vocab_char_map,
146
+ ).to(device)
147
+
148
+ model = load_checkpoint(model, ckpt_path, device, use_ema = True)
149
+
150
+ return model
151
+
152
+
153
+ # load models
154
+ F5TTS_model_cfg = dict(
155
+ dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4
156
+ )
157
+ E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
158
+
159
+
160
+ def chunk_text(text, max_chars=135):
161
+ """
162
+ Splits the input text into chunks, each with a maximum number of characters.
163
+ Args:
164
+ text (str): The text to be split.
165
+ max_chars (int): The maximum number of characters per chunk.
166
+ Returns:
167
+ List[str]: A list of text chunks.
168
+ """
169
+ chunks = []
170
+ current_chunk = ""
171
+ # Split the text into sentences based on punctuation followed by whitespace
172
+ sentences = re.split(r'(?<=[;:,.!?])\s+|(?<=[;:,。!?])', text)
173
+
174
+ for sentence in sentences:
175
+ if len(current_chunk.encode('utf-8')) + len(sentence.encode('utf-8')) <= max_chars:
176
+ current_chunk += sentence + " " if sentence and len(sentence[-1].encode('utf-8')) == 1 else sentence
177
+ else:
178
+ if current_chunk:
179
+ chunks.append(current_chunk.strip())
180
+ current_chunk = sentence + " " if sentence and len(sentence[-1].encode('utf-8')) == 1 else sentence
181
+
182
+ if current_chunk:
183
+ chunks.append(current_chunk.strip())
184
+
185
+ return chunks
186
+
187
+
188
+ def infer_batch(ref_audio, ref_text, gen_text_batches, model, remove_silence, cross_fade_duration=0.15):
189
+ if model == "F5-TTS":
190
+ ema_model = load_model(model, "F5TTS_Base", DiT, F5TTS_model_cfg, 1200000)
191
+ elif model == "E2-TTS":
192
+ ema_model = load_model(model, "E2TTS_Base", UNetT, E2TTS_model_cfg, 1200000)
193
+
194
+ audio, sr = ref_audio
195
+ if audio.shape[0] > 1:
196
+ audio = torch.mean(audio, dim=0, keepdim=True)
197
+
198
+ rms = torch.sqrt(torch.mean(torch.square(audio)))
199
+ if rms < target_rms:
200
+ audio = audio * target_rms / rms
201
+ if sr != target_sample_rate:
202
+ resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
203
+ audio = resampler(audio)
204
+ audio = audio.to(device)
205
+
206
+ generated_waves = []
207
+ spectrograms = []
208
+
209
+ for i, gen_text in enumerate(tqdm.tqdm(gen_text_batches)):
210
+ # Prepare the text
211
+ if len(ref_text[-1].encode('utf-8')) == 1:
212
+ ref_text = ref_text + " "
213
+ text_list = [ref_text + gen_text]
214
+ final_text_list = convert_char_to_pinyin(text_list)
215
+
216
+ # Calculate duration
217
+ ref_audio_len = audio.shape[-1] // hop_length
218
+ zh_pause_punc = r"。,、;:?!"
219
+ ref_text_len = len(ref_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, ref_text))
220
+ gen_text_len = len(gen_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, gen_text))
221
+ duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
222
+
223
+ # inference
224
+ with torch.inference_mode():
225
+ generated, _ = ema_model.sample(
226
+ cond=audio,
227
+ text=final_text_list,
228
+ duration=duration,
229
+ steps=nfe_step,
230
+ cfg_strength=cfg_strength,
231
+ sway_sampling_coef=sway_sampling_coef,
232
+ )
233
+
234
+ generated = generated[:, ref_audio_len:, :]
235
+ generated_mel_spec = rearrange(generated, "1 n d -> 1 d n")
236
+ generated_wave = vocos.decode(generated_mel_spec.cpu())
237
+ if rms < target_rms:
238
+ generated_wave = generated_wave * rms / target_rms
239
+
240
+ # wav -> numpy
241
+ generated_wave = generated_wave.squeeze().cpu().numpy()
242
+
243
+ generated_waves.append(generated_wave)
244
+ spectrograms.append(generated_mel_spec[0].cpu().numpy())
245
+
246
+ # Combine all generated waves with cross-fading
247
+ if cross_fade_duration <= 0:
248
+ # Simply concatenate
249
+ final_wave = np.concatenate(generated_waves)
250
+ else:
251
+ final_wave = generated_waves[0]
252
+ for i in range(1, len(generated_waves)):
253
+ prev_wave = final_wave
254
+ next_wave = generated_waves[i]
255
+
256
+ # Calculate cross-fade samples, ensuring it does not exceed wave lengths
257
+ cross_fade_samples = int(cross_fade_duration * target_sample_rate)
258
+ cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
259
+
260
+ if cross_fade_samples <= 0:
261
+ # No overlap possible, concatenate
262
+ final_wave = np.concatenate([prev_wave, next_wave])
263
+ continue
264
+
265
+ # Overlapping parts
266
+ prev_overlap = prev_wave[-cross_fade_samples:]
267
+ next_overlap = next_wave[:cross_fade_samples]
268
+
269
+ # Fade out and fade in
270
+ fade_out = np.linspace(1, 0, cross_fade_samples)
271
+ fade_in = np.linspace(0, 1, cross_fade_samples)
272
+
273
+ # Cross-faded overlap
274
+ cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
275
+
276
+ # Combine
277
+ new_wave = np.concatenate([
278
+ prev_wave[:-cross_fade_samples],
279
+ cross_faded_overlap,
280
+ next_wave[cross_fade_samples:]
281
+ ])
282
+
283
+ final_wave = new_wave
284
+
285
+ with open(wave_path, "wb") as f:
286
+ sf.write(f.name, final_wave, target_sample_rate)
287
+ # Remove silence
288
+ if remove_silence:
289
+ aseg = AudioSegment.from_file(f.name)
290
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
291
+ non_silent_wave = AudioSegment.silent(duration=0)
292
+ for non_silent_seg in non_silent_segs:
293
+ non_silent_wave += non_silent_seg
294
+ aseg = non_silent_wave
295
+ aseg.export(f.name, format="wav")
296
+ print(f.name)
297
+
298
+ # Create a combined spectrogram
299
+ combined_spectrogram = np.concatenate(spectrograms, axis=1)
300
+ save_spectrogram(combined_spectrogram, spectrogram_path)
301
+ print(spectrogram_path)
302
+
303
+
304
+ def infer(ref_audio_orig, ref_text, gen_text, model, remove_silence, cross_fade_duration=0.15):
305
+
306
+ print(gen_text)
307
+
308
+ print("Converting audio...")
309
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
310
+ aseg = AudioSegment.from_file(ref_audio_orig)
311
+
312
+ non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000)
313
+ non_silent_wave = AudioSegment.silent(duration=0)
314
+ for non_silent_seg in non_silent_segs:
315
+ non_silent_wave += non_silent_seg
316
+ aseg = non_silent_wave
317
+
318
+ audio_duration = len(aseg)
319
+ if audio_duration > 15000:
320
+ print("Audio is over 15s, clipping to only first 15s.")
321
+ aseg = aseg[:15000]
322
+ aseg.export(f.name, format="wav")
323
+ ref_audio = f.name
324
+
325
+ if not ref_text.strip():
326
+ print("No reference text provided, transcribing reference audio...")
327
+ pipe = pipeline(
328
+ "automatic-speech-recognition",
329
+ model="openai/whisper-large-v3-turbo",
330
+ torch_dtype=torch.float16,
331
+ device=device,
332
+ )
333
+ ref_text = pipe(
334
+ ref_audio,
335
+ chunk_length_s=30,
336
+ batch_size=128,
337
+ generate_kwargs={"task": "transcribe"},
338
+ return_timestamps=False,
339
+ )["text"].strip()
340
+ print("Finished transcription")
341
+ else:
342
+ print("Using custom reference text...")
343
+
344
+ # Add the functionality to ensure it ends with ". "
345
+ if not ref_text.endswith(". ") and not ref_text.endswith("。"):
346
+ if ref_text.endswith("."):
347
+ ref_text += " "
348
+ else:
349
+ ref_text += ". "
350
+
351
+ # Split the input text into batches
352
+ audio, sr = torchaudio.load(ref_audio)
353
+ max_chars = int(len(ref_text.encode('utf-8')) / (audio.shape[-1] / sr) * (25 - audio.shape[-1] / sr))
354
+ gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
355
+ print('ref_text', ref_text)
356
+ for i, gen_text in enumerate(gen_text_batches):
357
+ print(f'gen_text {i}', gen_text)
358
+
359
+ print(f"Generating audio using {model} in {len(gen_text_batches)} batches, loading models...")
360
+ return infer_batch((audio, sr), ref_text, gen_text_batches, model, remove_silence, cross_fade_duration)
361
+
362
+
363
+ infer(ref_audio, ref_text, gen_text, 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"