emirhanno commited on
Commit
b2f157c
·
1 Parent(s): 7396ed5

Add application file

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