ashishkblink commited on
Commit
b56816d
·
verified ·
1 Parent(s): 80716e0

Upload f5_tts/infer/infer_gradio.py with huggingface_hub

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