paolosenbardi commited on
Commit
2ec623b
·
verified ·
1 Parent(s): 40eed23

Create app.py

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