Update app.py
Browse files
app.py
CHANGED
@@ -1,146 +1,66 @@
|
|
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 |
from collections import OrderedDict
|
7 |
-
from importlib.resources import files
|
8 |
-
|
9 |
import click
|
10 |
import gradio as gr
|
11 |
import numpy as np
|
12 |
import soundfile as sf
|
13 |
import torchaudio
|
14 |
from cached_path import cached_path
|
15 |
-
from
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
try:
|
18 |
import spaces
|
19 |
-
|
20 |
USING_SPACES = True
|
21 |
except ImportError:
|
22 |
USING_SPACES = False
|
23 |
|
24 |
|
|
|
|
|
|
|
25 |
def gpu_decorator(func):
|
26 |
if USING_SPACES:
|
27 |
return spaces.GPU(func)
|
28 |
else:
|
29 |
return func
|
30 |
|
31 |
-
|
32 |
-
from f5_tts.model import DiT, UNetT
|
33 |
-
from f5_tts.infer.utils_infer import (
|
34 |
-
load_vocoder,
|
35 |
-
load_model,
|
36 |
-
preprocess_ref_audio_text,
|
37 |
-
infer_process,
|
38 |
-
remove_silence_for_generated_wav,
|
39 |
-
save_spectrogram,
|
40 |
-
)
|
41 |
-
|
42 |
-
|
43 |
-
DEFAULT_TTS_MODEL = "F5-TTS"
|
44 |
-
tts_model_choice = DEFAULT_TTS_MODEL
|
45 |
-
|
46 |
-
|
47 |
-
# load models
|
48 |
-
|
49 |
vocoder = load_vocoder()
|
50 |
|
51 |
-
|
52 |
import os
|
53 |
from huggingface_hub import hf_hub_download
|
54 |
-
|
55 |
def load_f5tts():
|
56 |
# Carrega o caminho do repositório e o nome do arquivo das variáveis de ambiente
|
57 |
repo_id = os.getenv("MODEL_REPO_ID", "SWivid/F5-TTS/F5TTS_Base")
|
58 |
filename = os.getenv("MODEL_FILENAME", "model_1200000.safetensors")
|
59 |
token = os.getenv("HUGGINGFACE_TOKEN")
|
60 |
-
|
61 |
# Valida se o token está presente
|
62 |
if not token:
|
63 |
raise ValueError("A variável de ambiente 'HUGGINGFACE_TOKEN' não foi definida.")
|
64 |
-
|
65 |
# Faz o download do modelo do repositório privado
|
66 |
ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename, use_auth_token=token)
|
67 |
|
68 |
F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
69 |
return load_model(DiT, F5TTS_model_cfg, ckpt_path)
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
def load_e2tts(ckpt_path=str(cached_path("hf://SWivid/E2-TTS/E2TTS_Base/model_1200000.safetensors"))):
|
75 |
-
E2TTS_model_cfg = dict(dim=1024, depth=24, heads=16, ff_mult=4)
|
76 |
-
return load_model(UNetT, E2TTS_model_cfg, ckpt_path)
|
77 |
-
|
78 |
-
|
79 |
-
def load_custom(ckpt_path: str, vocab_path="", model_cfg=None):
|
80 |
-
ckpt_path, vocab_path = ckpt_path.strip(), vocab_path.strip()
|
81 |
-
if ckpt_path.startswith("hf://"):
|
82 |
-
ckpt_path = str(cached_path(ckpt_path))
|
83 |
-
if vocab_path.startswith("hf://"):
|
84 |
-
vocab_path = str(cached_path(vocab_path))
|
85 |
-
if model_cfg is None:
|
86 |
-
model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
87 |
-
return load_model(DiT, model_cfg, ckpt_path, vocab_file=vocab_path)
|
88 |
-
|
89 |
-
|
90 |
F5TTS_ema_model = load_f5tts()
|
91 |
-
E2TTS_ema_model = load_e2tts() if USING_SPACES else None
|
92 |
-
custom_ema_model, pre_custom_path = None, ""
|
93 |
-
|
94 |
-
chat_model_state = None
|
95 |
-
chat_tokenizer_state = None
|
96 |
-
|
97 |
-
|
98 |
-
@gpu_decorator
|
99 |
-
def generate_response(messages, model, tokenizer):
|
100 |
-
"""Generate response using Qwen"""
|
101 |
-
text = tokenizer.apply_chat_template(
|
102 |
-
messages,
|
103 |
-
tokenize=False,
|
104 |
-
add_generation_prompt=True,
|
105 |
-
)
|
106 |
-
|
107 |
-
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
108 |
-
generated_ids = model.generate(
|
109 |
-
**model_inputs,
|
110 |
-
max_new_tokens=512,
|
111 |
-
temperature=0.7,
|
112 |
-
top_p=0.95,
|
113 |
-
)
|
114 |
-
|
115 |
-
generated_ids = [
|
116 |
-
output_ids[len(input_ids) :] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
117 |
-
]
|
118 |
-
return tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
119 |
-
|
120 |
|
121 |
@gpu_decorator
|
122 |
def infer(
|
123 |
-
ref_audio_orig, ref_text, gen_text,
|
124 |
):
|
125 |
ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
|
126 |
-
|
127 |
-
if model == "F5-TTS":
|
128 |
-
ema_model = F5TTS_ema_model
|
129 |
-
elif model == "E2-TTS":
|
130 |
-
global E2TTS_ema_model
|
131 |
-
if E2TTS_ema_model is None:
|
132 |
-
show_info("Loading E2-TTS model...")
|
133 |
-
E2TTS_ema_model = load_e2tts()
|
134 |
-
ema_model = E2TTS_ema_model
|
135 |
-
elif isinstance(model, list) and model[0] == "Custom":
|
136 |
-
assert not USING_SPACES, "Only official checkpoints allowed in Spaces."
|
137 |
-
global custom_ema_model, pre_custom_path
|
138 |
-
if pre_custom_path != model[1]:
|
139 |
-
show_info("Loading Custom TTS model...")
|
140 |
-
custom_ema_model = load_custom(model[1], vocab_path=model[2])
|
141 |
-
pre_custom_path = model[1]
|
142 |
-
ema_model = custom_ema_model
|
143 |
-
|
144 |
final_wave, final_sample_rate, combined_spectrogram = infer_process(
|
145 |
ref_audio,
|
146 |
ref_text.lower().strip(),
|
@@ -152,691 +72,326 @@ def infer(
|
|
152 |
show_info=show_info,
|
153 |
progress=gr.Progress(),
|
154 |
)
|
155 |
-
|
156 |
-
# Remove silence
|
157 |
if remove_silence:
|
158 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
|
159 |
sf.write(f.name, final_wave, final_sample_rate)
|
160 |
remove_silence_for_generated_wav(f.name)
|
161 |
final_wave, _ = torchaudio.load(f.name)
|
162 |
final_wave = final_wave.squeeze().cpu().numpy()
|
163 |
-
|
164 |
-
# Save the spectrogram
|
165 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
|
166 |
spectrogram_path = tmp_spectrogram.name
|
167 |
save_spectrogram(combined_spectrogram, spectrogram_path)
|
168 |
-
|
169 |
return (final_sample_rate, final_wave), spectrogram_path, ref_text
|
170 |
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
#
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
ref_text_input = gr.Textbox(
|
187 |
-
label="Reference Text",
|
188 |
-
info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.",
|
189 |
-
lines=2,
|
190 |
-
)
|
191 |
-
remove_silence = gr.Checkbox(
|
192 |
-
label="Remove Silences",
|
193 |
-
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.",
|
194 |
-
value=False,
|
195 |
-
)
|
196 |
-
speed_slider = gr.Slider(
|
197 |
-
label="Speed",
|
198 |
-
minimum=0.3,
|
199 |
-
maximum=2.0,
|
200 |
-
value=1.0,
|
201 |
-
step=0.1,
|
202 |
-
info="Adjust the speed of the audio.",
|
203 |
-
)
|
204 |
-
cross_fade_duration_slider = gr.Slider(
|
205 |
-
label="Cross-Fade Duration (s)",
|
206 |
-
minimum=0.0,
|
207 |
-
maximum=1.0,
|
208 |
-
value=0.15,
|
209 |
-
step=0.01,
|
210 |
-
info="Set the duration of the cross-fade between audio clips.",
|
211 |
-
)
|
212 |
-
|
213 |
-
audio_output = gr.Audio(label="Synthesized Audio")
|
214 |
-
spectrogram_output = gr.Image(label="Spectrogram")
|
215 |
-
|
216 |
-
@gpu_decorator
|
217 |
-
def basic_tts(
|
218 |
-
ref_audio_input,
|
219 |
-
ref_text_input,
|
220 |
-
gen_text_input,
|
221 |
-
remove_silence,
|
222 |
-
cross_fade_duration_slider,
|
223 |
-
speed_slider,
|
224 |
-
):
|
225 |
-
audio_out, spectrogram_path, ref_text_out = infer(
|
226 |
-
ref_audio_input,
|
227 |
-
ref_text_input,
|
228 |
-
gen_text_input,
|
229 |
-
tts_model_choice,
|
230 |
-
remove_silence,
|
231 |
-
cross_fade_duration_slider,
|
232 |
-
speed_slider,
|
233 |
-
)
|
234 |
-
return audio_out, spectrogram_path, gr.update(value=ref_text_out)
|
235 |
-
|
236 |
-
generate_btn.click(
|
237 |
-
basic_tts,
|
238 |
-
inputs=[
|
239 |
-
ref_audio_input,
|
240 |
-
ref_text_input,
|
241 |
-
gen_text_input,
|
242 |
-
remove_silence,
|
243 |
-
cross_fade_duration_slider,
|
244 |
-
speed_slider,
|
245 |
-
],
|
246 |
-
outputs=[audio_output, spectrogram_output, ref_text_input],
|
247 |
-
)
|
248 |
-
|
249 |
-
|
250 |
-
def parse_speechtypes_text(gen_text):
|
251 |
-
# Pattern to find {speechtype}
|
252 |
-
pattern = r"\{(.*?)\}"
|
253 |
-
|
254 |
-
# Split the text by the pattern
|
255 |
-
tokens = re.split(pattern, gen_text)
|
256 |
-
|
257 |
-
segments = []
|
258 |
-
|
259 |
-
current_style = "Regular"
|
260 |
-
|
261 |
-
for i in range(len(tokens)):
|
262 |
-
if i % 2 == 0:
|
263 |
-
# This is text
|
264 |
-
text = tokens[i].strip()
|
265 |
-
if text:
|
266 |
-
segments.append({"style": current_style, "text": text})
|
267 |
-
else:
|
268 |
-
# This is style
|
269 |
-
style = tokens[i].strip()
|
270 |
-
current_style = style
|
271 |
-
|
272 |
-
return segments
|
273 |
-
|
274 |
-
|
275 |
-
with gr.Blocks() as app_multistyle:
|
276 |
-
# New section for multistyle generation
|
277 |
-
gr.Markdown(
|
278 |
-
"""
|
279 |
-
# Multiple Speech-Type Generation
|
280 |
-
|
281 |
-
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.
|
282 |
-
"""
|
283 |
-
)
|
284 |
-
|
285 |
-
with gr.Row():
|
286 |
-
gr.Markdown(
|
287 |
-
"""
|
288 |
-
**Example Input:**
|
289 |
-
{Regular} Hello, I'd like to order a sandwich please.
|
290 |
-
{Surprised} What do you mean you're out of bread?
|
291 |
-
{Sad} I really wanted a sandwich though...
|
292 |
-
{Angry} You know what, darn you and your little shop!
|
293 |
-
{Whisper} I'll just go back home and cry now.
|
294 |
-
{Shouting} Why me?!
|
295 |
-
"""
|
296 |
-
)
|
297 |
-
|
298 |
-
gr.Markdown(
|
299 |
-
"""
|
300 |
-
**Example Input 2:**
|
301 |
-
{Speaker1_Happy} Hello, I'd like to order a sandwich please.
|
302 |
-
{Speaker2_Regular} Sorry, we're out of bread.
|
303 |
-
{Speaker1_Sad} I really wanted a sandwich though...
|
304 |
-
{Speaker2_Whisper} I'll give you the last one I was hiding.
|
305 |
-
"""
|
306 |
-
)
|
307 |
-
|
308 |
-
gr.Markdown(
|
309 |
-
"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."
|
310 |
-
)
|
311 |
-
|
312 |
-
# Regular speech type (mandatory)
|
313 |
-
with gr.Row():
|
314 |
-
with gr.Column():
|
315 |
-
regular_name = gr.Textbox(value="Regular", label="Speech Type Name")
|
316 |
-
regular_insert = gr.Button("Insert Label", variant="secondary")
|
317 |
-
regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath")
|
318 |
-
regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=2)
|
319 |
-
|
320 |
-
# Regular speech type (max 100)
|
321 |
-
max_speech_types = 100
|
322 |
-
speech_type_rows = [] # 99
|
323 |
-
speech_type_names = [regular_name] # 100
|
324 |
-
speech_type_audios = [regular_audio] # 100
|
325 |
-
speech_type_ref_texts = [regular_ref_text] # 100
|
326 |
-
speech_type_delete_btns = [] # 99
|
327 |
-
speech_type_insert_btns = [regular_insert] # 100
|
328 |
-
|
329 |
-
# Additional speech types (99 more)
|
330 |
-
for i in range(max_speech_types - 1):
|
331 |
-
with gr.Row(visible=False) as row:
|
332 |
-
with gr.Column():
|
333 |
-
name_input = gr.Textbox(label="Speech Type Name")
|
334 |
-
delete_btn = gr.Button("Delete Type", variant="secondary")
|
335 |
-
insert_btn = gr.Button("Insert Label", variant="secondary")
|
336 |
-
audio_input = gr.Audio(label="Reference Audio", type="filepath")
|
337 |
-
ref_text_input = gr.Textbox(label="Reference Text", lines=2)
|
338 |
-
speech_type_rows.append(row)
|
339 |
-
speech_type_names.append(name_input)
|
340 |
-
speech_type_audios.append(audio_input)
|
341 |
-
speech_type_ref_texts.append(ref_text_input)
|
342 |
-
speech_type_delete_btns.append(delete_btn)
|
343 |
-
speech_type_insert_btns.append(insert_btn)
|
344 |
-
|
345 |
-
# Button to add speech type
|
346 |
-
add_speech_type_btn = gr.Button("Add Speech Type")
|
347 |
-
|
348 |
-
# Keep track of current number of speech types
|
349 |
-
speech_type_count = gr.State(value=1)
|
350 |
-
|
351 |
-
# Function to add a speech type
|
352 |
-
def add_speech_type_fn(speech_type_count):
|
353 |
-
if speech_type_count < max_speech_types:
|
354 |
-
speech_type_count += 1
|
355 |
-
# Prepare updates for the rows
|
356 |
-
row_updates = []
|
357 |
-
for i in range(1, max_speech_types):
|
358 |
-
if i < speech_type_count:
|
359 |
-
row_updates.append(gr.update(visible=True))
|
360 |
-
else:
|
361 |
-
row_updates.append(gr.update())
|
362 |
-
else:
|
363 |
-
# Optionally, show a warning
|
364 |
-
row_updates = [gr.update() for _ in range(1, max_speech_types)]
|
365 |
-
return [speech_type_count] + row_updates
|
366 |
-
|
367 |
-
add_speech_type_btn.click(
|
368 |
-
add_speech_type_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows
|
369 |
-
)
|
370 |
-
|
371 |
-
# Function to delete a speech type
|
372 |
-
def make_delete_speech_type_fn(index):
|
373 |
-
def delete_speech_type_fn(speech_type_count):
|
374 |
-
# Prepare updates
|
375 |
-
row_updates = []
|
376 |
-
|
377 |
-
for i in range(1, max_speech_types):
|
378 |
-
if i == index:
|
379 |
-
row_updates.append(gr.update(visible=False))
|
380 |
-
else:
|
381 |
-
row_updates.append(gr.update())
|
382 |
-
|
383 |
-
speech_type_count = max(1, speech_type_count)
|
384 |
-
|
385 |
-
return [speech_type_count] + row_updates
|
386 |
-
|
387 |
-
return delete_speech_type_fn
|
388 |
-
|
389 |
-
# Update delete button clicks
|
390 |
-
for i, delete_btn in enumerate(speech_type_delete_btns):
|
391 |
-
delete_fn = make_delete_speech_type_fn(i)
|
392 |
-
delete_btn.click(delete_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows)
|
393 |
-
|
394 |
-
# Text input for the prompt
|
395 |
-
gen_text_input_multistyle = gr.Textbox(
|
396 |
-
label="Text to Generate",
|
397 |
-
lines=10,
|
398 |
-
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?!",
|
399 |
-
)
|
400 |
-
|
401 |
-
def make_insert_speech_type_fn(index):
|
402 |
-
def insert_speech_type_fn(current_text, speech_type_name):
|
403 |
-
current_text = current_text or ""
|
404 |
-
speech_type_name = speech_type_name or "None"
|
405 |
-
updated_text = current_text + f"{{{speech_type_name}}} "
|
406 |
-
return gr.update(value=updated_text)
|
407 |
-
|
408 |
-
return insert_speech_type_fn
|
409 |
-
|
410 |
-
for i, insert_btn in enumerate(speech_type_insert_btns):
|
411 |
-
insert_fn = make_insert_speech_type_fn(i)
|
412 |
-
insert_btn.click(
|
413 |
-
insert_fn,
|
414 |
-
inputs=[gen_text_input_multistyle, speech_type_names[i]],
|
415 |
-
outputs=gen_text_input_multistyle,
|
416 |
-
)
|
417 |
-
|
418 |
-
with gr.Accordion("Advanced Settings", open=False):
|
419 |
-
remove_silence_multistyle = gr.Checkbox(
|
420 |
-
label="Remove Silences",
|
421 |
-
value=True,
|
422 |
-
)
|
423 |
-
|
424 |
-
# Generate button
|
425 |
-
generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
|
426 |
-
|
427 |
-
# Output audio
|
428 |
-
audio_output_multistyle = gr.Audio(label="Synthesized Audio")
|
429 |
-
|
430 |
-
@gpu_decorator
|
431 |
-
def generate_multistyle_speech(
|
432 |
-
gen_text,
|
433 |
-
*args,
|
434 |
-
):
|
435 |
-
speech_type_names_list = args[:max_speech_types]
|
436 |
-
speech_type_audios_list = args[max_speech_types : 2 * max_speech_types]
|
437 |
-
speech_type_ref_texts_list = args[2 * max_speech_types : 3 * max_speech_types]
|
438 |
-
remove_silence = args[3 * max_speech_types]
|
439 |
-
# Collect the speech types and their audios into a dict
|
440 |
-
speech_types = OrderedDict()
|
441 |
-
|
442 |
-
ref_text_idx = 0
|
443 |
-
for name_input, audio_input, ref_text_input in zip(
|
444 |
-
speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list
|
445 |
-
):
|
446 |
-
if name_input and audio_input:
|
447 |
-
speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input}
|
448 |
-
else:
|
449 |
-
speech_types[f"@{ref_text_idx}@"] = {"audio": "", "ref_text": ""}
|
450 |
-
ref_text_idx += 1
|
451 |
-
|
452 |
-
# Parse the gen_text into segments
|
453 |
-
segments = parse_speechtypes_text(gen_text)
|
454 |
-
|
455 |
-
# For each segment, generate speech
|
456 |
-
generated_audio_segments = []
|
457 |
-
current_style = "Regular"
|
458 |
-
|
459 |
-
for segment in segments:
|
460 |
-
style = segment["style"]
|
461 |
-
text = segment["text"]
|
462 |
-
|
463 |
-
if style in speech_types:
|
464 |
-
current_style = style
|
465 |
-
else:
|
466 |
-
# If style not available, default to Regular
|
467 |
-
current_style = "Regular"
|
468 |
-
|
469 |
-
ref_audio = speech_types[current_style]["audio"]
|
470 |
-
ref_text = speech_types[current_style].get("ref_text", "")
|
471 |
-
|
472 |
-
# Generate speech for this segment
|
473 |
-
audio_out, _, ref_text_out = infer(
|
474 |
-
ref_audio, ref_text, text, tts_model_choice, remove_silence, 0, show_info=print
|
475 |
-
) # show_info=print no pull to top when generating
|
476 |
-
sr, audio_data = audio_out
|
477 |
-
|
478 |
-
generated_audio_segments.append(audio_data)
|
479 |
-
speech_types[current_style]["ref_text"] = ref_text_out
|
480 |
-
|
481 |
-
# Concatenate all audio segments
|
482 |
-
if generated_audio_segments:
|
483 |
-
final_audio_data = np.concatenate(generated_audio_segments)
|
484 |
-
return [(sr, final_audio_data)] + [
|
485 |
-
gr.update(value=speech_types[style]["ref_text"]) for style in speech_types
|
486 |
-
]
|
487 |
-
else:
|
488 |
-
gr.Warning("No audio generated.")
|
489 |
-
return [None] + [gr.update(value=speech_types[style]["ref_text"]) for style in speech_types]
|
490 |
-
|
491 |
-
generate_multistyle_btn.click(
|
492 |
-
generate_multistyle_speech,
|
493 |
-
inputs=[
|
494 |
-
gen_text_input_multistyle,
|
495 |
-
]
|
496 |
-
+ speech_type_names
|
497 |
-
+ speech_type_audios
|
498 |
-
+ speech_type_ref_texts
|
499 |
-
+ [
|
500 |
-
remove_silence_multistyle,
|
501 |
-
],
|
502 |
-
outputs=[audio_output_multistyle] + speech_type_ref_texts,
|
503 |
-
)
|
504 |
-
|
505 |
-
# Validation function to disable Generate button if speech types are missing
|
506 |
-
def validate_speech_types(gen_text, regular_name, *args):
|
507 |
-
speech_type_names_list = args[:max_speech_types]
|
508 |
-
|
509 |
-
# Collect the speech types names
|
510 |
-
speech_types_available = set()
|
511 |
-
if regular_name:
|
512 |
-
speech_types_available.add(regular_name)
|
513 |
-
for name_input in speech_type_names_list:
|
514 |
-
if name_input:
|
515 |
-
speech_types_available.add(name_input)
|
516 |
-
|
517 |
-
# Parse the gen_text to get the speech types used
|
518 |
-
segments = parse_speechtypes_text(gen_text)
|
519 |
-
speech_types_in_text = set(segment["style"] for segment in segments)
|
520 |
-
|
521 |
-
# Check if all speech types in text are available
|
522 |
-
missing_speech_types = speech_types_in_text - speech_types_available
|
523 |
-
|
524 |
-
if missing_speech_types:
|
525 |
-
# Disable the generate button
|
526 |
-
return gr.update(interactive=False)
|
527 |
-
else:
|
528 |
-
# Enable the generate button
|
529 |
-
return gr.update(interactive=True)
|
530 |
-
|
531 |
-
gen_text_input_multistyle.change(
|
532 |
-
validate_speech_types,
|
533 |
-
inputs=[gen_text_input_multistyle, regular_name] + speech_type_names,
|
534 |
-
outputs=generate_multistyle_btn,
|
535 |
-
)
|
536 |
-
|
537 |
-
|
538 |
-
with gr.Blocks() as app_chat:
|
539 |
-
gr.Markdown(
|
540 |
-
"""
|
541 |
-
# Voice Chat
|
542 |
-
Have a conversation with an AI using your reference voice!
|
543 |
-
1. Upload a reference audio clip and optionally its transcript.
|
544 |
-
2. Load the chat model.
|
545 |
-
3. Record your message through your microphone.
|
546 |
-
4. The AI will respond using the reference voice.
|
547 |
"""
|
548 |
-
)
|
549 |
-
|
550 |
-
if not USING_SPACES:
|
551 |
-
load_chat_model_btn = gr.Button("Load Chat Model", variant="primary")
|
552 |
-
|
553 |
-
chat_interface_container = gr.Column(visible=False)
|
554 |
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
564 |
)
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
load_chat_model_btn.click(load_chat_model, outputs=[load_chat_model_btn, chat_interface_container])
|
571 |
-
|
572 |
-
else:
|
573 |
-
chat_interface_container = gr.Column()
|
574 |
-
|
575 |
-
if chat_model_state is None:
|
576 |
-
model_name = "Qwen/Qwen2.5-3B-Instruct"
|
577 |
-
chat_model_state = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")
|
578 |
-
chat_tokenizer_state = AutoTokenizer.from_pretrained(model_name)
|
579 |
-
|
580 |
-
with chat_interface_container:
|
581 |
-
with gr.Row():
|
582 |
-
with gr.Column():
|
583 |
-
ref_audio_chat = gr.Audio(label="Reference Audio", type="filepath")
|
584 |
-
with gr.Column():
|
585 |
-
with gr.Accordion("Advanced Settings", open=False):
|
586 |
-
remove_silence_chat = gr.Checkbox(
|
587 |
-
label="Remove Silences",
|
588 |
-
value=True,
|
589 |
-
)
|
590 |
-
ref_text_chat = gr.Textbox(
|
591 |
-
label="Reference Text",
|
592 |
-
info="Optional: Leave blank to auto-transcribe",
|
593 |
-
lines=2,
|
594 |
-
)
|
595 |
-
system_prompt_chat = gr.Textbox(
|
596 |
-
label="System Prompt",
|
597 |
-
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.",
|
598 |
-
lines=2,
|
599 |
-
)
|
600 |
-
|
601 |
-
chatbot_interface = gr.Chatbot(label="Conversation")
|
602 |
-
|
603 |
-
with gr.Row():
|
604 |
-
with gr.Column():
|
605 |
-
audio_input_chat = gr.Microphone(
|
606 |
-
label="Speak your message",
|
607 |
-
type="filepath",
|
608 |
)
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
|
|
|
|
614 |
)
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
"
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
)
|
626 |
-
|
627 |
-
# Modify process_audio_input to use model and tokenizer from state
|
628 |
-
@gpu_decorator
|
629 |
-
def process_audio_input(audio_path, text, history, conv_state):
|
630 |
-
"""Handle audio or text input from user"""
|
631 |
-
|
632 |
-
if not audio_path and not text.strip():
|
633 |
-
return history, conv_state, ""
|
634 |
-
|
635 |
-
if audio_path:
|
636 |
-
text = preprocess_ref_audio_text(audio_path, text)[1]
|
637 |
-
|
638 |
-
if not text.strip():
|
639 |
-
return history, conv_state, ""
|
640 |
-
|
641 |
-
conv_state.append({"role": "user", "content": text})
|
642 |
-
history.append((text, None))
|
643 |
-
|
644 |
-
response = generate_response(conv_state, chat_model_state, chat_tokenizer_state)
|
645 |
-
|
646 |
-
conv_state.append({"role": "assistant", "content": response})
|
647 |
-
history[-1] = (text, response)
|
648 |
-
|
649 |
-
return history, conv_state, ""
|
650 |
-
|
651 |
-
@gpu_decorator
|
652 |
-
def generate_audio_response(history, ref_audio, ref_text, remove_silence):
|
653 |
-
"""Generate TTS audio for AI response"""
|
654 |
-
if not history or not ref_audio:
|
655 |
-
return None
|
656 |
|
657 |
-
|
658 |
-
if not last_ai_response:
|
659 |
-
return None
|
660 |
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
remove_silence,
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
generate_audio_response,
|
694 |
-
inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat],
|
695 |
-
outputs=[audio_output_chat, ref_text_chat],
|
696 |
-
).then(
|
697 |
-
lambda: None,
|
698 |
-
None,
|
699 |
-
audio_input_chat,
|
700 |
-
)
|
701 |
-
|
702 |
-
# Handle text input
|
703 |
-
text_input_chat.submit(
|
704 |
-
process_audio_input,
|
705 |
-
inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
|
706 |
-
outputs=[chatbot_interface, conversation_state],
|
707 |
-
).then(
|
708 |
-
generate_audio_response,
|
709 |
-
inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat],
|
710 |
-
outputs=[audio_output_chat, ref_text_chat],
|
711 |
-
).then(
|
712 |
-
lambda: None,
|
713 |
-
None,
|
714 |
-
text_input_chat,
|
715 |
-
)
|
716 |
-
|
717 |
-
# Handle send button
|
718 |
-
send_btn_chat.click(
|
719 |
-
process_audio_input,
|
720 |
-
inputs=[audio_input_chat, text_input_chat, chatbot_interface, conversation_state],
|
721 |
-
outputs=[chatbot_interface, conversation_state],
|
722 |
-
).then(
|
723 |
-
generate_audio_response,
|
724 |
-
inputs=[chatbot_interface, ref_audio_chat, ref_text_chat, remove_silence_chat],
|
725 |
-
outputs=[audio_output_chat, ref_text_chat],
|
726 |
-
).then(
|
727 |
-
lambda: None,
|
728 |
-
None,
|
729 |
-
text_input_chat,
|
730 |
-
)
|
731 |
-
|
732 |
-
# Handle clear button
|
733 |
-
clear_btn_chat.click(
|
734 |
-
clear_conversation,
|
735 |
-
outputs=[chatbot_interface, conversation_state],
|
736 |
-
)
|
737 |
-
|
738 |
-
# Handle system prompt change and reset conversation
|
739 |
-
system_prompt_chat.change(
|
740 |
-
update_system_prompt,
|
741 |
-
inputs=system_prompt_chat,
|
742 |
-
outputs=[chatbot_interface, conversation_state],
|
743 |
-
)
|
744 |
-
|
745 |
-
|
746 |
-
with gr.Blocks() as app:
|
747 |
-
gr.Markdown(
|
748 |
-
"""
|
749 |
-
# E2/F5 TTS
|
750 |
-
|
751 |
-
This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
|
752 |
-
|
753 |
-
* [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
|
754 |
-
* [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
|
755 |
-
|
756 |
-
The checkpoints currently support English and Chinese.
|
757 |
-
|
758 |
-
If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s with ✂ in the bottom right corner (otherwise might have non-optimal auto-trimmed result).
|
759 |
-
|
760 |
-
**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.**
|
761 |
-
"""
|
762 |
-
)
|
763 |
-
|
764 |
-
last_used_custom = files("f5_tts").joinpath("infer/.cache/last_used_custom.txt")
|
765 |
-
|
766 |
-
def load_last_used_custom():
|
767 |
-
try:
|
768 |
-
with open(last_used_custom, "r") as f:
|
769 |
-
return f.read().split(",")
|
770 |
-
except FileNotFoundError:
|
771 |
-
last_used_custom.parent.mkdir(parents=True, exist_ok=True)
|
772 |
-
return [
|
773 |
-
"hf://SWivid/F5-TTS/F5TTS_Base/model_1200000.safetensors",
|
774 |
-
"hf://SWivid/F5-TTS/F5TTS_Base/vocab.txt",
|
775 |
-
]
|
776 |
-
|
777 |
-
def switch_tts_model(new_choice):
|
778 |
-
global tts_model_choice
|
779 |
-
if new_choice == "Custom": # override in case webpage is refreshed
|
780 |
-
custom_ckpt_path, custom_vocab_path = load_last_used_custom()
|
781 |
-
tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path]
|
782 |
-
return gr.update(visible=True, value=custom_ckpt_path), gr.update(visible=True, value=custom_vocab_path)
|
783 |
-
else:
|
784 |
-
tts_model_choice = new_choice
|
785 |
-
return gr.update(visible=False), gr.update(visible=False)
|
786 |
-
|
787 |
-
def set_custom_model(custom_ckpt_path, custom_vocab_path):
|
788 |
-
global tts_model_choice
|
789 |
-
tts_model_choice = ["Custom", custom_ckpt_path, custom_vocab_path]
|
790 |
-
with open(last_used_custom, "w") as f:
|
791 |
-
f.write(f"{custom_ckpt_path},{custom_vocab_path}")
|
792 |
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
797 |
)
|
798 |
-
|
799 |
-
|
800 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
801 |
)
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
809 |
-
|
810 |
-
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
-
|
815 |
-
|
816 |
-
|
817 |
-
|
818 |
-
|
819 |
-
|
820 |
-
|
821 |
-
|
822 |
-
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
-
|
834 |
-
|
835 |
-
|
836 |
-
|
837 |
-
|
838 |
-
|
839 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
840 |
@click.command()
|
841 |
@click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
|
842 |
@click.option("--host", "-H", default=None, help="Host to run the app on")
|
@@ -853,9 +408,8 @@ def main(port, host, share, api):
|
|
853 |
print("Starting app...")
|
854 |
app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api)
|
855 |
|
856 |
-
|
857 |
if __name__ == "__main__":
|
858 |
if not USING_SPACES:
|
859 |
main()
|
860 |
else:
|
861 |
-
app.queue().launch()
|
|
|
|
|
|
|
|
|
1 |
import re
|
2 |
import tempfile
|
3 |
from collections import OrderedDict
|
|
|
|
|
4 |
import click
|
5 |
import gradio as gr
|
6 |
import numpy as np
|
7 |
import soundfile as sf
|
8 |
import torchaudio
|
9 |
from cached_path import cached_path
|
10 |
+
from sentence_analyzer import SentenceAnalyzer
|
11 |
+
from f5_tts.model import DiT
|
12 |
+
from f5_tts.infer.utils_infer import (
|
13 |
+
load_vocoder,
|
14 |
+
load_model,
|
15 |
+
preprocess_ref_audio_text,
|
16 |
+
infer_process,
|
17 |
+
remove_silence_for_generated_wav,
|
18 |
+
save_spectrogram,
|
19 |
+
)
|
20 |
try:
|
21 |
import spaces
|
|
|
22 |
USING_SPACES = True
|
23 |
except ImportError:
|
24 |
USING_SPACES = False
|
25 |
|
26 |
|
27 |
+
import nltk
|
28 |
+
nltk.download('punkt_tab')
|
29 |
+
|
30 |
def gpu_decorator(func):
|
31 |
if USING_SPACES:
|
32 |
return spaces.GPU(func)
|
33 |
else:
|
34 |
return func
|
35 |
|
36 |
+
# Carregar vocoder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
vocoder = load_vocoder()
|
38 |
|
|
|
39 |
import os
|
40 |
from huggingface_hub import hf_hub_download
|
|
|
41 |
def load_f5tts():
|
42 |
# Carrega o caminho do repositório e o nome do arquivo das variáveis de ambiente
|
43 |
repo_id = os.getenv("MODEL_REPO_ID", "SWivid/F5-TTS/F5TTS_Base")
|
44 |
filename = os.getenv("MODEL_FILENAME", "model_1200000.safetensors")
|
45 |
token = os.getenv("HUGGINGFACE_TOKEN")
|
|
|
46 |
# Valida se o token está presente
|
47 |
if not token:
|
48 |
raise ValueError("A variável de ambiente 'HUGGINGFACE_TOKEN' não foi definida.")
|
|
|
49 |
# Faz o download do modelo do repositório privado
|
50 |
ckpt_path = hf_hub_download(repo_id=repo_id, filename=filename, use_auth_token=token)
|
51 |
|
52 |
F5TTS_model_cfg = dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4)
|
53 |
return load_model(DiT, F5TTS_model_cfg, ckpt_path)
|
54 |
|
55 |
+
# Carregar modelo F5TTS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
F5TTS_ema_model = load_f5tts()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
@gpu_decorator
|
59 |
def infer(
|
60 |
+
ref_audio_orig, ref_text, gen_text, remove_silence, cross_fade_duration=0.15, speed=1, show_info=gr.Info
|
61 |
):
|
62 |
ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_orig, ref_text, show_info=show_info)
|
63 |
+
ema_model = F5TTS_ema_model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
final_wave, final_sample_rate, combined_spectrogram = infer_process(
|
65 |
ref_audio,
|
66 |
ref_text.lower().strip(),
|
|
|
72 |
show_info=show_info,
|
73 |
progress=gr.Progress(),
|
74 |
)
|
75 |
+
# Remover silêncios
|
|
|
76 |
if remove_silence:
|
77 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
|
78 |
sf.write(f.name, final_wave, final_sample_rate)
|
79 |
remove_silence_for_generated_wav(f.name)
|
80 |
final_wave, _ = torchaudio.load(f.name)
|
81 |
final_wave = final_wave.squeeze().cpu().numpy()
|
82 |
+
# Salvar espectrograma
|
|
|
83 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
|
84 |
spectrogram_path = tmp_spectrogram.name
|
85 |
save_spectrogram(combined_spectrogram, spectrogram_path)
|
|
|
86 |
return (final_sample_rate, final_wave), spectrogram_path, ref_text
|
87 |
|
88 |
+
# Estilos CSS
|
89 |
+
custom_css = """
|
90 |
+
#sentences-container {
|
91 |
+
border: 1px solid #ddd;
|
92 |
+
border-radius: 4px;
|
93 |
+
padding: 10px;
|
94 |
+
margin-bottom: 10px;
|
95 |
+
}
|
96 |
+
.sentence-box {
|
97 |
+
border: 1px solid #eee;
|
98 |
+
padding: 5px;
|
99 |
+
margin-bottom: 5px;
|
100 |
+
border-radius: 4px;
|
101 |
+
background-color: #f9f9f9;
|
102 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
+
with gr.Blocks(css=custom_css) as app:
|
106 |
+
with gr.Tabs():
|
107 |
+
with gr.Tab("TTS Básico"):
|
108 |
+
gr.Markdown("# TTS Básico com F5-TTS")
|
109 |
+
ref_audio_input = gr.Audio(label="Áudio de Referência", type="filepath")
|
110 |
+
gen_text_input = gr.Textbox(label="Texto para Gerar", lines=10)
|
111 |
+
generate_btn = gr.Button("Sintetizar", variant="primary")
|
112 |
+
|
113 |
+
# Container para as sentenças
|
114 |
+
with gr.Row(elem_id="sentences-container"):
|
115 |
+
sentences_output = gr.Textbox(label="Sentenças", lines=10, interactive=False)
|
116 |
+
|
117 |
+
with gr.Accordion("Configurações Avançadas", open=False):
|
118 |
+
ref_text_input = gr.Textbox(
|
119 |
+
label="Texto de Referência",
|
120 |
+
info="Deixe em branco para transcrever automaticamente o áudio de referência. Se você inserir texto, ele substituirá a transcrição automática.",
|
121 |
+
lines=2,
|
122 |
)
|
123 |
+
remove_silence = gr.Checkbox(
|
124 |
+
label="Remover Silêncios",
|
125 |
+
info="O modelo tende a produzir silêncios, especialmente em áudios mais longos. Podemos remover manualmente os silêncios, se necessário. Isso também aumentará o tempo de geração.",
|
126 |
+
value=False,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
)
|
128 |
+
speed_slider = gr.Slider(
|
129 |
+
label="Velocidade",
|
130 |
+
minimum=0.3,
|
131 |
+
maximum=2.0,
|
132 |
+
value=1.0,
|
133 |
+
step=0.1,
|
134 |
+
info="Ajuste a velocidade do áudio.",
|
135 |
)
|
136 |
+
cross_fade_duration_slider = gr.Slider(
|
137 |
+
label="Duração do Cross-fade (s)",
|
138 |
+
minimum=0.0,
|
139 |
+
maximum=1.0,
|
140 |
+
value=0.15,
|
141 |
+
step=0.01,
|
142 |
+
info="Defina a duração do cross-fade entre os clipes de áudio.",
|
143 |
+
)
|
144 |
+
audio_output = gr.Audio(label="Áudio Sintetizado")
|
145 |
+
spectrogram_output = gr.Image(label="Espectrograma")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
+
analyzer = SentenceAnalyzer()
|
|
|
|
|
148 |
|
149 |
+
@gpu_decorator
|
150 |
+
def basic_tts(
|
151 |
+
ref_audio_input,
|
152 |
+
ref_text_input,
|
153 |
+
gen_text_input,
|
154 |
remove_silence,
|
155 |
+
cross_fade_duration_slider,
|
156 |
+
speed_slider,
|
157 |
+
):
|
158 |
+
# Divida o texto em sentenças
|
159 |
+
sentences = analyzer.split_into_sentences(gen_text_input)
|
160 |
+
|
161 |
+
# Exiba as sentenças com formatação
|
162 |
+
formatted_sentences = "".join([
|
163 |
+
f'<div class="sentence-box">{sentence}</div>'
|
164 |
+
for sentence in sentences
|
165 |
+
])
|
166 |
+
sentences_output.update(value=formatted_sentences)
|
167 |
+
|
168 |
+
# Gere áudio para cada sentença individualmente
|
169 |
+
audio_segments = []
|
170 |
+
for sentence in sentences:
|
171 |
+
audio_out, spectrogram_path, ref_text_out = infer(
|
172 |
+
ref_audio_input,
|
173 |
+
ref_text_input,
|
174 |
+
sentence, # Gere áudio para a sentença atual
|
175 |
+
remove_silence,
|
176 |
+
cross_fade_duration_slider,
|
177 |
+
speed_slider,
|
178 |
+
)
|
179 |
+
sr, audio_data = audio_out
|
180 |
+
audio_segments.append(audio_data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
|
182 |
+
# Concatene os segmentos de áudio
|
183 |
+
if audio_segments:
|
184 |
+
final_audio_data = np.concatenate(audio_segments)
|
185 |
+
return (sr, final_audio_data), spectrogram_path, gr.update(value=ref_text_out)
|
186 |
+
else:
|
187 |
+
gr.Warning("Nenhum áudio gerado.")
|
188 |
+
return None, None, gr.update(value=ref_text_out)
|
189 |
+
|
190 |
+
generate_btn.click(
|
191 |
+
basic_tts,
|
192 |
+
inputs=[
|
193 |
+
ref_audio_input,
|
194 |
+
ref_text_input,
|
195 |
+
gen_text_input,
|
196 |
+
remove_silence,
|
197 |
+
cross_fade_duration_slider,
|
198 |
+
speed_slider,
|
199 |
+
],
|
200 |
+
outputs=[audio_output, spectrogram_output, ref_text_input],
|
201 |
)
|
202 |
+
|
203 |
+
with gr.Tab("Multi-Speech"):
|
204 |
+
gr.Markdown("# Geração Multi-Speech com F5-TTS")
|
205 |
+
|
206 |
+
# Regular speech type (mandatory)
|
207 |
+
with gr.Row():
|
208 |
+
with gr.Column():
|
209 |
+
regular_name = gr.Textbox(value="Regular", label="Speech Type Name")
|
210 |
+
regular_insert = gr.Button("Insert Label", variant="secondary")
|
211 |
+
regular_audio = gr.Audio(label="Regular Reference Audio", type="filepath")
|
212 |
+
regular_ref_text = gr.Textbox(label="Reference Text (Regular)", lines=2)
|
213 |
+
# Regular speech type (max 100)
|
214 |
+
max_speech_types = 100
|
215 |
+
speech_type_rows = [] # 99
|
216 |
+
speech_type_names = [regular_name] # 100
|
217 |
+
speech_type_audios = [regular_audio] # 100
|
218 |
+
speech_type_ref_texts = [regular_ref_text] # 100
|
219 |
+
speech_type_delete_btns = [] # 99
|
220 |
+
speech_type_insert_btns = [regular_insert] # 100
|
221 |
+
# Additional speech types (99 more)
|
222 |
+
for i in range(max_speech_types - 1):
|
223 |
+
with gr.Row(visible=False) as row:
|
224 |
+
with gr.Column():
|
225 |
+
name_input = gr.Textbox(label="Speech Type Name")
|
226 |
+
delete_btn = gr.Button("Delete Type", variant="secondary")
|
227 |
+
insert_btn = gr.Button("Insert Label", variant="secondary")
|
228 |
+
audio_input = gr.Audio(label="Reference Audio", type="filepath")
|
229 |
+
ref_text_input = gr.Textbox(label="Reference Text", lines=2)
|
230 |
+
speech_type_rows.append(row)
|
231 |
+
speech_type_names.append(name_input)
|
232 |
+
speech_type_audios.append(audio_input)
|
233 |
+
speech_type_ref_texts.append(ref_text_input)
|
234 |
+
speech_type_delete_btns.append(delete_btn)
|
235 |
+
speech_type_insert_btns.append(insert_btn)
|
236 |
+
# Button to add speech type
|
237 |
+
add_speech_type_btn = gr.Button("Add Speech Type")
|
238 |
+
# Keep track of current number of speech types
|
239 |
+
speech_type_count = gr.State(value=1)
|
240 |
+
# Function to add a speech type
|
241 |
+
def add_speech_type_fn(speech_type_count):
|
242 |
+
if speech_type_count < max_speech_types:
|
243 |
+
speech_type_count += 1
|
244 |
+
# Prepare updates for the rows
|
245 |
+
row_updates = []
|
246 |
+
for i in range(1, max_speech_types):
|
247 |
+
if i < speech_type_count:
|
248 |
+
row_updates.append(gr.update(visible=True))
|
249 |
+
else:
|
250 |
+
row_updates.append(gr.update())
|
251 |
+
else:
|
252 |
+
# Optionally, show a warning
|
253 |
+
row_updates = [gr.update() for _ in range(1, max_speech_types)]
|
254 |
+
return [speech_type_count] + row_updates
|
255 |
+
add_speech_type_btn.click(
|
256 |
+
add_speech_type_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows
|
257 |
)
|
258 |
+
# Function to delete a speech type
|
259 |
+
def make_delete_speech_type_fn(index):
|
260 |
+
def delete_speech_type_fn(speech_type_count):
|
261 |
+
# Prepare updates
|
262 |
+
row_updates = []
|
263 |
+
for i in range(1, max_speech_types):
|
264 |
+
if i == index:
|
265 |
+
row_updates.append(gr.update(visible=False))
|
266 |
+
else:
|
267 |
+
row_updates.append(gr.update())
|
268 |
+
speech_type_count = max(1, speech_type_count)
|
269 |
+
return [speech_type_count] + row_updates
|
270 |
+
return delete_speech_type_fn
|
271 |
+
# Update delete button clicks
|
272 |
+
for i, delete_btn in enumerate(speech_type_delete_btns):
|
273 |
+
delete_fn = make_delete_speech_type_fn(i)
|
274 |
+
delete_btn.click(delete_fn, inputs=speech_type_count, outputs=[speech_type_count] + speech_type_rows)
|
275 |
+
# Text input for the prompt
|
276 |
+
gen_text_input_multistyle = gr.Textbox(
|
277 |
+
label="Text to Generate",
|
278 |
+
lines=10,
|
279 |
+
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?!",
|
280 |
+
)
|
281 |
+
def make_insert_speech_type_fn(index):
|
282 |
+
def insert_speech_type_fn(current_text, speech_type_name):
|
283 |
+
current_text = current_text or ""
|
284 |
+
speech_type_name = speech_type_name or "None"
|
285 |
+
updated_text = current_text + f"{{{speech_type_name}}} "
|
286 |
+
return gr.update(value=updated_text)
|
287 |
+
return insert_speech_type_fn
|
288 |
+
for i, insert_btn in enumerate(speech_type_insert_btns):
|
289 |
+
insert_fn = make_insert_speech_type_fn(i)
|
290 |
+
insert_btn.click(
|
291 |
+
insert_fn,
|
292 |
+
inputs=[gen_text_input_multistyle, speech_type_names[i]],
|
293 |
+
outputs=gen_text_input_multistyle,
|
294 |
+
)
|
295 |
+
with gr.Accordion("Advanced Settings", open=False):
|
296 |
+
remove_silence_multistyle = gr.Checkbox(
|
297 |
+
label="Remove Silences",
|
298 |
+
value=True,
|
299 |
+
)
|
300 |
+
# Generate button
|
301 |
+
generate_multistyle_btn = gr.Button("Generate Multi-Style Speech", variant="primary")
|
302 |
+
# Output audio
|
303 |
+
audio_output_multistyle = gr.Audio(label="Synthesized Audio")
|
304 |
+
@gpu_decorator
|
305 |
+
def generate_multistyle_speech(
|
306 |
+
gen_text,
|
307 |
+
*args,
|
308 |
+
):
|
309 |
+
speech_type_names_list = args[:max_speech_types]
|
310 |
+
speech_type_audios_list = args[max_speech_types : 2 * max_speech_types]
|
311 |
+
speech_type_ref_texts_list = args[2 * max_speech_types : 3 * max_speech_types]
|
312 |
+
remove_silence = args[3 * max_speech_types]
|
313 |
+
# Collect the speech types and their audios into a dict
|
314 |
+
speech_types = OrderedDict()
|
315 |
+
ref_text_idx = 0
|
316 |
+
for name_input, audio_input, ref_text_input in zip(
|
317 |
+
speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list
|
318 |
+
):
|
319 |
+
if name_input and audio_input:
|
320 |
+
speech_types[name_input] = {"audio": audio_input, "ref_text": ref_text_input}
|
321 |
+
else:
|
322 |
+
speech_types[f"@{ref_text_idx}@"] = {"audio": "", "ref_text": ""}
|
323 |
+
ref_text_idx += 1
|
324 |
+
# Parse the gen_text into segments
|
325 |
+
segments = parse_speechtypes_text(gen_text)
|
326 |
+
# For each segment, generate speech
|
327 |
+
generated_audio_segments = []
|
328 |
+
current_style = "Regular"
|
329 |
+
for segment in segments:
|
330 |
+
style = segment["style"]
|
331 |
+
text = segment["text"]
|
332 |
+
if style in speech_types:
|
333 |
+
current_style = style
|
334 |
+
else:
|
335 |
+
# If style not available, default to Regular
|
336 |
+
current_style = "Regular"
|
337 |
+
ref_audio = speech_types[current_style]["audio"]
|
338 |
+
ref_text = speech_types[current_style].get("ref_text", "")
|
339 |
+
# Generate speech for this segment
|
340 |
+
audio_out, _, ref_text_out = infer(
|
341 |
+
ref_audio, ref_text, text, remove_silence, 0, show_info=print
|
342 |
+
) # show_info=print no pull to top when generating
|
343 |
+
sr, audio_data = audio_out
|
344 |
+
generated_audio_segments.append(audio_data)
|
345 |
+
speech_types[current_style]["ref_text"] = ref_text_out
|
346 |
+
# Concatenate all audio segments
|
347 |
+
if generated_audio_segments:
|
348 |
+
final_audio_data = np.concatenate(generated_audio_segments)
|
349 |
+
return [(sr, final_audio_data)] + [
|
350 |
+
gr.update(value=speech_types[style]["ref_text"]) for style in speech_types
|
351 |
+
]
|
352 |
+
else:
|
353 |
+
gr.Warning("No audio generated.")
|
354 |
+
return [None] + [gr.update(value=speech_types[style]["ref_text"]) for style in speech_types]
|
355 |
+
generate_multistyle_btn.click(
|
356 |
+
generate_multistyle_speech,
|
357 |
+
inputs=[
|
358 |
+
gen_text_input_multistyle,
|
359 |
+
]
|
360 |
+
+ speech_type_names
|
361 |
+
+ speech_type_audios
|
362 |
+
+ speech_type_ref_texts
|
363 |
+
+ [
|
364 |
+
remove_silence_multistyle,
|
365 |
+
],
|
366 |
+
outputs=[audio_output_multistyle] + speech_type_ref_texts,
|
367 |
+
)
|
368 |
+
# Validation function to disable Generate button if speech types are missing
|
369 |
+
def validate_speech_types(gen_text, regular_name, *args):
|
370 |
+
speech_type_names_list = args[:max_speech_types]
|
371 |
+
# Collect the speech types names
|
372 |
+
speech_types_available = set()
|
373 |
+
if regular_name:
|
374 |
+
speech_types_available.add(regular_name)
|
375 |
+
for name_input in speech_type_names_list:
|
376 |
+
if name_input:
|
377 |
+
speech_types_available.add(name_input)
|
378 |
+
# Parse the gen_text to get the speech types used
|
379 |
+
segments = parse_speechtypes_text(gen_text)
|
380 |
+
speech_types_in_text = set(segment["style"] for segment in segments)
|
381 |
+
# Check if all speech types in text are available
|
382 |
+
missing_speech_types = speech_types_in_text - speech_types_available
|
383 |
+
if missing_speech_types:
|
384 |
+
# Disable the generate button
|
385 |
+
return gr.update(interactive=False)
|
386 |
+
else:
|
387 |
+
# Enable the generate button
|
388 |
+
return gr.update(interactive=True)
|
389 |
+
gen_text_input_multistyle.change(
|
390 |
+
validate_speech_types,
|
391 |
+
inputs=[gen_text_input_multistyle, regular_name] + speech_type_names,
|
392 |
+
outputs=generate_multistyle_btn,
|
393 |
+
)
|
394 |
+
|
395 |
@click.command()
|
396 |
@click.option("--port", "-p", default=None, type=int, help="Port to run the app on")
|
397 |
@click.option("--host", "-H", default=None, help="Host to run the app on")
|
|
|
408 |
print("Starting app...")
|
409 |
app.queue(api_open=api).launch(server_name=host, server_port=port, share=share, show_api=api)
|
410 |
|
|
|
411 |
if __name__ == "__main__":
|
412 |
if not USING_SPACES:
|
413 |
main()
|
414 |
else:
|
415 |
+
app.queue().launch()
|