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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
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 re
|
24 |
+
import gc
|
25 |
+
import matplotlib.pyplot as plt
|
26 |
+
import devicetorch
|
27 |
+
|
28 |
+
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
29 |
+
|
30 |
+
gc.collect()
|
31 |
+
devicetorch.empty_cache(torch)
|
32 |
+
|
33 |
+
print(f"Using {device} device")
|
34 |
+
|
35 |
+
|
36 |
+
# --------------------- Settings -------------------- #
|
37 |
+
|
38 |
+
target_sample_rate = 24000
|
39 |
+
n_mel_channels = 100
|
40 |
+
hop_length = 256
|
41 |
+
target_rms = 0.1
|
42 |
+
nfe_step = 32 # 16, 32
|
43 |
+
cfg_strength = 2.0
|
44 |
+
ode_method = 'euler'
|
45 |
+
sway_sampling_coef = -1.0
|
46 |
+
speed = 1.0
|
47 |
+
# fix_duration = 27 # None or float (duration in seconds)
|
48 |
+
fix_duration = None
|
49 |
+
|
50 |
+
def load_model(exp_name, model_cls, model_cfg, ckpt_step):
|
51 |
+
checkpoint = torch.load(str(cached_path(f"hf://SWivid/F5-TTS/{exp_name}/model_{ckpt_step}.pt")), map_location=device)
|
52 |
+
vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
|
53 |
+
model = CFM(
|
54 |
+
transformer=model_cls(
|
55 |
+
**model_cfg,
|
56 |
+
text_num_embeds=vocab_size,
|
57 |
+
mel_dim=n_mel_channels
|
58 |
+
),
|
59 |
+
mel_spec_kwargs=dict(
|
60 |
+
target_sample_rate=target_sample_rate,
|
61 |
+
n_mel_channels=n_mel_channels,
|
62 |
+
hop_length=hop_length,
|
63 |
+
),
|
64 |
+
odeint_kwargs=dict(
|
65 |
+
method=ode_method,
|
66 |
+
),
|
67 |
+
vocab_char_map=vocab_char_map,
|
68 |
+
).to(device)
|
69 |
+
|
70 |
+
ema_model = EMA(model, include_online_model=False).to(device)
|
71 |
+
ema_model.load_state_dict(checkpoint['ema_model_state_dict'])
|
72 |
+
ema_model.copy_params_from_ema_to_model()
|
73 |
+
|
74 |
+
return ema_model, model
|
75 |
+
|
76 |
+
# load models
|
77 |
+
F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
78 |
+
E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
|
79 |
+
|
80 |
+
F5TTS_ema_model, F5TTS_base_model = load_model("F5TTS_Base", DiT, F5TTS_model_cfg, 1200000)
|
81 |
+
E2TTS_ema_model, E2TTS_base_model = load_model("E2TTS_Base", UNetT, E2TTS_model_cfg, 1200000)
|
82 |
+
|
83 |
+
def chunk_text(text, max_chars=200):
|
84 |
+
chunks = []
|
85 |
+
current_chunk = ""
|
86 |
+
sentences = re.split(r'(?<=[.!?])\s+', text)
|
87 |
+
|
88 |
+
for sentence in sentences:
|
89 |
+
if len(current_chunk) + len(sentence) <= max_chars:
|
90 |
+
current_chunk += sentence + " "
|
91 |
+
else:
|
92 |
+
if current_chunk:
|
93 |
+
chunks.append(current_chunk.strip())
|
94 |
+
current_chunk = sentence + " "
|
95 |
+
|
96 |
+
if current_chunk:
|
97 |
+
chunks.append(current_chunk.strip())
|
98 |
+
|
99 |
+
return chunks
|
100 |
+
|
101 |
+
def save_spectrogram(y, sr, path):
|
102 |
+
plt.figure(figsize=(10, 4))
|
103 |
+
D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max)
|
104 |
+
librosa.display.specshow(D, sr=sr, x_axis='time', y_axis='hz')
|
105 |
+
plt.colorbar(format='%+2.0f dB')
|
106 |
+
plt.title('Spectrogram')
|
107 |
+
plt.tight_layout()
|
108 |
+
plt.savefig(path)
|
109 |
+
plt.close()
|
110 |
+
|
111 |
+
def infer(ref_audio_orig, ref_text, gen_text, exp_name, remove_silence):
|
112 |
+
print(gen_text)
|
113 |
+
chunks = chunk_text(gen_text)
|
114 |
+
|
115 |
+
if not chunks:
|
116 |
+
raise gr.Error("Please enter some text to generate.")
|
117 |
+
|
118 |
+
# Convert reference audio
|
119 |
+
gr.Info("Converting reference audio...")
|
120 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
|
121 |
+
aseg = AudioSegment.from_file(ref_audio_orig)
|
122 |
+
aseg = aseg.set_channels(1)
|
123 |
+
audio_duration = len(aseg)
|
124 |
+
if audio_duration > 15000:
|
125 |
+
gr.Warning("Audio is over 15s, clipping to only first 15s.")
|
126 |
+
aseg = aseg[:15000]
|
127 |
+
aseg.export(f.name, format="wav")
|
128 |
+
ref_audio = f.name
|
129 |
+
|
130 |
+
# Select model
|
131 |
+
if exp_name == "F5-TTS":
|
132 |
+
ema_model = F5TTS_ema_model
|
133 |
+
base_model = F5TTS_base_model
|
134 |
+
elif exp_name == "E2-TTS":
|
135 |
+
ema_model = E2TTS_ema_model
|
136 |
+
base_model = E2TTS_base_model
|
137 |
+
|
138 |
+
# Transcribe reference audio if needed
|
139 |
+
if not ref_text.strip():
|
140 |
+
gr.Info("No reference text provided, transcribing reference audio...")
|
141 |
+
# Initialize Whisper model
|
142 |
+
pipe = pipeline(
|
143 |
+
"automatic-speech-recognition",
|
144 |
+
model="openai/whisper-large-v3-Turbo", # You can set this to large-V3 if you want better quality, but VRAM then goes to 10 GB
|
145 |
+
torch_dtype=torch.float16,
|
146 |
+
device=device,
|
147 |
+
)
|
148 |
+
ref_text = pipe(
|
149 |
+
ref_audio,
|
150 |
+
chunk_length_s=30,
|
151 |
+
batch_size=128,
|
152 |
+
generate_kwargs={"task": "transcribe"},
|
153 |
+
return_timestamps=False,
|
154 |
+
)['text'].strip()
|
155 |
+
print("\nTranscribed text: ", ref_text) # Degug transcribing quality
|
156 |
+
gr.Info("\nFinished transcription")
|
157 |
+
# Release Whisper model
|
158 |
+
del pipe
|
159 |
+
devicetorch.empty_cache(torch)
|
160 |
+
gc.collect()
|
161 |
+
else:
|
162 |
+
gr.Info("Using custom reference text...")
|
163 |
+
|
164 |
+
# Load and preprocess reference audio
|
165 |
+
audio, sr = torchaudio.load(ref_audio)
|
166 |
+
if audio.shape[0] > 1:
|
167 |
+
audio = torch.mean(audio, dim=0, keepdim=True) # convert to mono
|
168 |
+
rms = torch.sqrt(torch.mean(torch.square(audio)))
|
169 |
+
if rms < target_rms:
|
170 |
+
audio = audio * target_rms / rms
|
171 |
+
if sr != target_sample_rate:
|
172 |
+
resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
|
173 |
+
audio = resampler(audio)
|
174 |
+
audio = audio.to(device)
|
175 |
+
|
176 |
+
# Process each chunk
|
177 |
+
results = []
|
178 |
+
spectrograms = []
|
179 |
+
|
180 |
+
for i, chunk in enumerate(chunks):
|
181 |
+
gr.Info(f"Processing chunk {i+1}/{len(chunks)}: {chunk[:30]}...")
|
182 |
+
|
183 |
+
# Prepare the text
|
184 |
+
text_list = [ref_text + chunk]
|
185 |
+
final_text_list = convert_char_to_pinyin(text_list)
|
186 |
+
|
187 |
+
# Calculate duration
|
188 |
+
ref_audio_len = audio.shape[-1] // hop_length
|
189 |
+
zh_pause_punc = r"。,、;:?!"
|
190 |
+
ref_text_len = len(ref_text) + len(re.findall(zh_pause_punc, ref_text))
|
191 |
+
gen_text_len = len(chunk) + len(re.findall(zh_pause_punc, chunk))
|
192 |
+
duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
|
193 |
+
|
194 |
+
# Inference
|
195 |
+
gr.Info(f"Generating audio using {exp_name}")
|
196 |
+
with torch.inference_mode():
|
197 |
+
generated, _ = base_model.sample(
|
198 |
+
cond=audio,
|
199 |
+
text=final_text_list,
|
200 |
+
duration=duration,
|
201 |
+
steps=nfe_step,
|
202 |
+
cfg_strength=cfg_strength,
|
203 |
+
sway_sampling_coef=sway_sampling_coef,
|
204 |
+
)
|
205 |
+
|
206 |
+
generated = generated[:, ref_audio_len:, :]
|
207 |
+
generated_mel_spec = rearrange(generated, '1 n d -> 1 d n')
|
208 |
+
|
209 |
+
# Clear unnecessary tensors
|
210 |
+
del generated
|
211 |
+
devicetorch.empty_cache(torch)
|
212 |
+
|
213 |
+
gr.Info("Running vocoder")
|
214 |
+
vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
|
215 |
+
generated_wave = vocos.decode(generated_mel_spec.cpu())
|
216 |
+
if rms < target_rms:
|
217 |
+
generated_wave = generated_wave * rms / target_rms
|
218 |
+
|
219 |
+
# Convert to numpy and clear GPU tensors
|
220 |
+
generated_wave = generated_wave.squeeze().cpu().numpy()
|
221 |
+
del generated_mel_spec
|
222 |
+
devicetorch.empty_cache(torch)
|
223 |
+
|
224 |
+
results.append(generated_wave)
|
225 |
+
|
226 |
+
# Generate spectrogram
|
227 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
|
228 |
+
spectrogram_path = tmp_spectrogram.name
|
229 |
+
save_spectrogram(generated_wave, target_sample_rate, spectrogram_path)
|
230 |
+
spectrograms.append(spectrogram_path)
|
231 |
+
|
232 |
+
# Clear cache after processing each chunk
|
233 |
+
gc.collect()
|
234 |
+
devicetorch.empty_cache(torch)
|
235 |
+
|
236 |
+
# Combine all audio chunks
|
237 |
+
combined_audio = np.concatenate(results)
|
238 |
+
|
239 |
+
if remove_silence:
|
240 |
+
gr.Info("Removing audio silences... This may take a moment")
|
241 |
+
non_silent_intervals = librosa.effects.split(combined_audio, top_db=30)
|
242 |
+
non_silent_wave = np.array([])
|
243 |
+
for interval in non_silent_intervals:
|
244 |
+
start, end = interval
|
245 |
+
non_silent_wave = np.concatenate([non_silent_wave, combined_audio[start:end]])
|
246 |
+
combined_audio = non_silent_wave
|
247 |
+
|
248 |
+
# Generate final spectrogram
|
249 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
|
250 |
+
final_spectrogram_path = tmp_spectrogram.name
|
251 |
+
save_spectrogram(combined_audio, target_sample_rate, final_spectrogram_path)
|
252 |
+
|
253 |
+
# Final cleanup
|
254 |
+
gc.collect()
|
255 |
+
devicetorch.empty_cache(torch)
|
256 |
+
|
257 |
+
# Return combined audio and the final spectrogram
|
258 |
+
return (target_sample_rate, combined_audio), final_spectrogram_path
|
259 |
+
|
260 |
+
with gr.Blocks() as app:
|
261 |
+
ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
|
262 |
+
gen_text_input = gr.Textbox(label="Text to Generate (for longer than 200 chars the app uses chunking)", lines=4)
|
263 |
+
model_choice = gr.Radio(choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS")
|
264 |
+
generate_btn = gr.Button("Synthesize", variant="primary")
|
265 |
+
with gr.Accordion("Advanced Settings", open=False):
|
266 |
+
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)
|
267 |
+
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)
|
268 |
+
|
269 |
+
audio_output = gr.Audio(label="Synthesized Audio")
|
270 |
+
spectrogram_output = gr.Image(label="Spectrogram")
|
271 |
+
|
272 |
+
generate_btn.click(infer, inputs=[ref_audio_input, ref_text_input, gen_text_input, model_choice, remove_silence], outputs=[audio_output, spectrogram_output])
|
273 |
+
gr.Markdown("Unofficial demo by [mrfakename](https://x.com/realmrfakename)")
|
274 |
+
|
275 |
+
|
276 |
+
app.queue().launch()
|