Staticaliza commited on
Commit
5a466c9
1 Parent(s): 8cf83f0

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -721
app.py DELETED
@@ -1,721 +0,0 @@
1
- import spaces
2
- import re
3
- import torch
4
- import torchaudio
5
- import gradio as gr
6
- import numpy as np
7
- import tempfile
8
- from einops import rearrange
9
- from vocos import Vocos
10
- from pydub import AudioSegment, silence
11
- from model import CFM, UNetT, DiT, MMDiT
12
- from cached_path import cached_path
13
- from model.utils import (
14
- load_checkpoint,
15
- get_tokenizer,
16
- convert_char_to_pinyin,
17
- save_spectrogram,
18
- )
19
- from transformers import pipeline
20
- import click
21
- import soundfile as sf
22
-
23
- device = (
24
- "cuda"
25
- if torch.cuda.is_available()
26
- else "mps" if torch.backends.mps.is_available() else "cpu"
27
- )
28
-
29
- print(f"Using {device} device")
30
-
31
- vocos = Vocos.from_pretrained("charactr/vocos-mel-24khz")
32
-
33
- # --------------------- Settings -------------------- #
34
-
35
- target_sample_rate = 24000
36
- n_mel_channels = 100
37
- hop_length = 256
38
- target_rms = 0.1
39
- nfe_step = 32 # 16, 32
40
- cfg_strength = 2.0
41
- ode_method = "euler"
42
- sway_sampling_coef = -1.0
43
- speed = 1.0
44
- fix_duration = None
45
-
46
-
47
- def load_model(repo_name, exp_name, model_cls, model_cfg, ckpt_step):
48
- ckpt_path = str(cached_path(f"hf://SWivid/{repo_name}/{exp_name}/model_{ckpt_step}.safetensors"))
49
- # ckpt_path = f"ckpts/{exp_name}/model_{ckpt_step}.pt" # .pt | .safetensors
50
- vocab_char_map, vocab_size = get_tokenizer("Emilia_ZH_EN", "pinyin")
51
- model = CFM(
52
- transformer=model_cls(
53
- **model_cfg, text_num_embeds=vocab_size, mel_dim=n_mel_channels
54
- ),
55
- mel_spec_kwargs=dict(
56
- target_sample_rate=target_sample_rate,
57
- n_mel_channels=n_mel_channels,
58
- hop_length=hop_length,
59
- ),
60
- odeint_kwargs=dict(
61
- method=ode_method,
62
- ),
63
- vocab_char_map=vocab_char_map,
64
- ).to(device)
65
-
66
- model = load_checkpoint(model, ckpt_path, device, use_ema = True)
67
-
68
- return model
69
-
70
-
71
- # load models
72
- F5TTS_ema_model = load_model("F5-TTS", "F5TTS_Base", DiT, {"dim": 1024, "depth": 22, "heads": 16, "ff_mult": 2, "text_dim": 512, "conv_layers": 4}, 1200000)
73
- E2TTS_ema_model = load_model("E2-TTS", "E2TTS_Base", UNetT, {"dim": 1024, "depth": 24, "heads": 16, "ff_mult": 4}, 1200000)
74
-
75
- def chunk_text(text, max_chars=135):
76
- """
77
- Splits the input text into chunks, each with a maximum number of characters.
78
- Args:
79
- text (str): The text to be split.
80
- max_chars (int): The maximum number of characters per chunk.
81
- Returns:
82
- List[str]: A list of text chunks.
83
- """
84
- chunks = []
85
- current_chunk = ""
86
- # Split the text into sentences based on punctuation followed by whitespace
87
- sentences = re.split(r'(?<=[;:,.!?])\s+|(?<=[;:,。!?])', text)
88
-
89
- for sentence in sentences:
90
- if len(current_chunk.encode('utf-8')) + len(sentence.encode('utf-8')) <= max_chars:
91
- current_chunk += sentence + " " if sentence and len(sentence[-1].encode('utf-8')) == 1 else sentence
92
- else:
93
- if current_chunk:
94
- chunks.append(current_chunk.strip())
95
- current_chunk = sentence + " " if sentence and len(sentence[-1].encode('utf-8')) == 1 else sentence
96
-
97
- if current_chunk:
98
- chunks.append(current_chunk.strip())
99
-
100
- return chunks
101
-
102
- @spaces.GPU(duration=30)
103
- def infer_batch(ref_audio, ref_text, gen_text_batches, exp_name, remove_silence, cross_fade_duration=0.15, progress=gr.Progress()):
104
- if exp_name == "F5-TTS":
105
- ema_model = F5TTS_ema_model
106
- elif exp_name == "E2-TTS":
107
- ema_model = E2TTS_ema_model
108
-
109
- audio, sr = ref_audio
110
- if audio.shape[0] > 1:
111
- audio = torch.mean(audio, dim=0, keepdim=True)
112
-
113
- rms = torch.sqrt(torch.mean(torch.square(audio)))
114
- if rms < target_rms:
115
- audio = audio * target_rms / rms
116
- if sr != target_sample_rate:
117
- resampler = torchaudio.transforms.Resample(sr, target_sample_rate)
118
- audio = resampler(audio)
119
- audio = audio.to(device)
120
-
121
- generated_waves = []
122
- spectrograms = []
123
-
124
- if len(ref_text[-1].encode('utf-8')) == 1:
125
- ref_text = ref_text + " "
126
- for i, gen_text in enumerate(progress.tqdm(gen_text_batches)):
127
- # Prepare the text
128
- text_list = [ref_text + gen_text]
129
- final_text_list = convert_char_to_pinyin(text_list)
130
-
131
- # Calculate duration
132
- ref_audio_len = audio.shape[-1] // hop_length
133
- zh_pause_punc = r"。,、;:?!"
134
- ref_text_len = len(ref_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, ref_text))
135
- gen_text_len = len(gen_text.encode('utf-8')) + 3 * len(re.findall(zh_pause_punc, gen_text))
136
- duration = ref_audio_len + int(ref_audio_len / ref_text_len * gen_text_len / speed)
137
-
138
- # inference
139
- with torch.inference_mode():
140
- generated, _ = ema_model.sample(
141
- cond=audio,
142
- text=final_text_list,
143
- duration=duration,
144
- steps=nfe_step,
145
- cfg_strength=cfg_strength,
146
- sway_sampling_coef=sway_sampling_coef,
147
- )
148
-
149
- generated = generated[:, ref_audio_len:, :]
150
- generated_mel_spec = rearrange(generated, "1 n d -> 1 d n")
151
- generated_wave = vocos.decode(generated_mel_spec.cpu())
152
- if rms < target_rms:
153
- generated_wave = generated_wave * rms / target_rms
154
-
155
- # wav -> numpy
156
- generated_wave = generated_wave.squeeze().cpu().numpy()
157
-
158
- generated_waves.append(generated_wave)
159
- spectrograms.append(generated_mel_spec[0].cpu().numpy())
160
-
161
- # Combine all generated waves with cross-fading
162
- if cross_fade_duration <= 0:
163
- # Simply concatenate
164
- final_wave = np.concatenate(generated_waves)
165
- else:
166
- final_wave = generated_waves[0]
167
- for i in range(1, len(generated_waves)):
168
- prev_wave = final_wave
169
- next_wave = generated_waves[i]
170
-
171
- # Calculate cross-fade samples, ensuring it does not exceed wave lengths
172
- cross_fade_samples = int(cross_fade_duration * target_sample_rate)
173
- cross_fade_samples = min(cross_fade_samples, len(prev_wave), len(next_wave))
174
-
175
- if cross_fade_samples <= 0:
176
- # No overlap possible, concatenate
177
- final_wave = np.concatenate([prev_wave, next_wave])
178
- continue
179
-
180
- # Overlapping parts
181
- prev_overlap = prev_wave[-cross_fade_samples:]
182
- next_overlap = next_wave[:cross_fade_samples]
183
-
184
- # Fade out and fade in
185
- fade_out = np.linspace(1, 0, cross_fade_samples)
186
- fade_in = np.linspace(0, 1, cross_fade_samples)
187
-
188
- # Cross-faded overlap
189
- cross_faded_overlap = prev_overlap * fade_out + next_overlap * fade_in
190
-
191
- # Combine
192
- new_wave = np.concatenate([
193
- prev_wave[:-cross_fade_samples],
194
- cross_faded_overlap,
195
- next_wave[cross_fade_samples:]
196
- ])
197
-
198
- final_wave = new_wave
199
-
200
- # Remove silence
201
- if remove_silence:
202
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
203
- sf.write(f.name, final_wave, target_sample_rate)
204
- aseg = AudioSegment.from_file(f.name)
205
- non_silent_segs = silence.split_on_silence(aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=500)
206
- non_silent_wave = AudioSegment.silent(duration=0)
207
- for non_silent_seg in non_silent_segs:
208
- non_silent_wave += non_silent_seg
209
- aseg = non_silent_wave
210
- aseg.export(f.name, format="wav")
211
- final_wave, _ = torchaudio.load(f.name)
212
- final_wave = final_wave.squeeze().cpu().numpy()
213
-
214
- # Create a combined spectrogram
215
- combined_spectrogram = np.concatenate(spectrograms, axis=1)
216
-
217
- with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_spectrogram:
218
- spectrogram_path = tmp_spectrogram.name
219
- save_spectrogram(combined_spectrogram, spectrogram_path)
220
-
221
- return (target_sample_rate, final_wave), spectrogram_path
222
-
223
- @spaces.GPU(duration=30)
224
- def infer(ref_audio_orig, ref_text, gen_text, exp_name, remove_silence, cross_fade_duration=0.15):
225
-
226
- print(gen_text)
227
-
228
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as f:
229
- aseg = AudioSegment.from_file(ref_audio_orig)
230
-
231
- non_silent_segs = silence.split_on_silence(
232
- aseg, min_silence_len=1000, silence_thresh=-50, keep_silence=1000
233
- )
234
- non_silent_wave = AudioSegment.silent(duration=0)
235
- for non_silent_seg in non_silent_segs:
236
- non_silent_wave += non_silent_seg
237
- aseg = non_silent_wave
238
-
239
- audio_duration = len(aseg)
240
- if audio_duration > 15000:
241
- gr.Warning("Audio is over 15s, clipping to only first 15s.")
242
- aseg = aseg[:15000]
243
- aseg.export(f.name, format="wav")
244
- ref_audio = f.name
245
-
246
- # Add the functionality to ensure it ends with ". "
247
- if not ref_text.endswith(". "):
248
- if ref_text.endswith("."):
249
- ref_text += " "
250
- else:
251
- ref_text += ". "
252
-
253
- audio, sr = torchaudio.load(ref_audio)
254
-
255
- # Use the new chunk_text function to split gen_text
256
- max_chars = int(len(ref_text.encode('utf-8')) / (audio.shape[-1] / sr) * (25 - audio.shape[-1] / sr))
257
- gen_text_batches = chunk_text(gen_text, max_chars=max_chars)
258
- print('ref_text', ref_text)
259
- for i, batch_text in enumerate(gen_text_batches):
260
- print(f'gen_text {i}', batch_text)
261
-
262
- return infer_batch((audio, sr), ref_text, gen_text_batches, exp_name, remove_silence, cross_fade_duration)
263
-
264
-
265
- @spaces.GPU(duration=30)
266
- def generate_podcast(script, speaker1_name, ref_audio1, ref_text1, speaker2_name, ref_audio2, ref_text2, exp_name, remove_silence):
267
- # Split the script into speaker blocks
268
- speaker_pattern = re.compile(f"^({re.escape(speaker1_name)}|{re.escape(speaker2_name)}):", re.MULTILINE)
269
- speaker_blocks = speaker_pattern.split(script)[1:] # Skip the first empty element
270
-
271
- generated_audio_segments = []
272
-
273
- for i in range(0, len(speaker_blocks), 2):
274
- speaker = speaker_blocks[i]
275
- text = speaker_blocks[i+1].strip()
276
-
277
- # Determine which speaker is talking
278
- if speaker == speaker1_name:
279
- ref_audio = ref_audio1
280
- ref_text = ref_text1
281
- elif speaker == speaker2_name:
282
- ref_audio = ref_audio2
283
- ref_text = ref_text2
284
- else:
285
- continue # Skip if the speaker is neither speaker1 nor speaker2
286
-
287
- # Generate audio for this block
288
- audio, _ = infer(ref_audio, ref_text, text, exp_name, remove_silence)
289
-
290
- # Convert the generated audio to a numpy array
291
- sr, audio_data = audio
292
-
293
- # Save the audio data as a WAV file
294
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
295
- sf.write(temp_file.name, audio_data, sr)
296
- audio_segment = AudioSegment.from_wav(temp_file.name)
297
-
298
- generated_audio_segments.append(audio_segment)
299
-
300
- # Add a short pause between speakers
301
- pause = AudioSegment.silent(duration=500) # 500ms pause
302
- generated_audio_segments.append(pause)
303
-
304
- # Concatenate all audio segments
305
- final_podcast = sum(generated_audio_segments)
306
-
307
- # Export the final podcast
308
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_file:
309
- podcast_path = temp_file.name
310
- final_podcast.export(podcast_path, format="wav")
311
-
312
- return podcast_path
313
-
314
- def parse_speechtypes_text(gen_text):
315
- # Pattern to find (Emotion)
316
- pattern = r'\((.*?)\)'
317
-
318
- # Split the text by the pattern
319
- tokens = re.split(pattern, gen_text)
320
-
321
- segments = []
322
-
323
- current_emotion = 'Regular'
324
-
325
- for i in range(len(tokens)):
326
- if i % 2 == 0:
327
- # This is text
328
- text = tokens[i].strip()
329
- if text:
330
- segments.append({'emotion': current_emotion, 'text': text})
331
- else:
332
- # This is emotion
333
- emotion = tokens[i].strip()
334
- current_emotion = emotion
335
-
336
- return segments
337
-
338
- def update_speed(new_speed):
339
- global speed
340
- speed = new_speed
341
- return f"Speed set to: {speed}"
342
-
343
- with gr.Blocks() as app_credits:
344
- gr.Markdown("""
345
- # Credits
346
- * [mrfakename](https://github.com/fakerybakery) for the original [online demo](https://huggingface.co/spaces/mrfakename/E2-F5-TTS)
347
- * [RootingInLoad](https://github.com/RootingInLoad) for the podcast generation
348
- * [jpgallegoar](https://github.com/jpgallegoar) for multiple speech-type generation
349
- """)
350
- with gr.Blocks() as app_tts:
351
- gr.Markdown("# Batched TTS")
352
- ref_audio_input = gr.Audio(label="Reference Audio", type="filepath")
353
- gen_text_input = gr.Textbox(label="Text to Generate", lines=10)
354
- model_choice = gr.Radio(
355
- choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
356
- )
357
- generate_btn = gr.Button("Synthesize", variant="primary")
358
- with gr.Accordion("Advanced Settings", open=False):
359
- ref_text_input = gr.Textbox(
360
- label="Reference Text",
361
- info="Leave blank to automatically transcribe the reference audio. If you enter text it will override automatic transcription.",
362
- lines=2,
363
- )
364
- remove_silence = gr.Checkbox(
365
- label="Remove Silences",
366
- 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.",
367
- value=False,
368
- )
369
- speed_slider = gr.Slider(
370
- label="Speed",
371
- minimum=0.3,
372
- maximum=2.0,
373
- value=speed,
374
- step=0.1,
375
- info="Adjust the speed of the audio.",
376
- )
377
- cross_fade_duration_slider = gr.Slider(
378
- label="Cross-Fade Duration (s)",
379
- minimum=0.0,
380
- maximum=1.0,
381
- value=0.15,
382
- step=0.01,
383
- info="Set the duration of the cross-fade between audio clips.",
384
- )
385
- speed_slider.change(update_speed, inputs=speed_slider)
386
-
387
- audio_output = gr.Audio(label="Synthesized Audio")
388
- spectrogram_output = gr.Image(label="Spectrogram")
389
-
390
- generate_btn.click(
391
- infer,
392
- inputs=[
393
- ref_audio_input,
394
- ref_text_input,
395
- gen_text_input,
396
- model_choice,
397
- remove_silence,
398
- cross_fade_duration_slider,
399
- ],
400
- outputs=[audio_output, spectrogram_output],
401
- )
402
-
403
- with gr.Blocks() as app_podcast:
404
- gr.Markdown("# Podcast Generation")
405
- speaker1_name = gr.Textbox(label="Speaker 1 Name")
406
- ref_audio_input1 = gr.Audio(label="Reference Audio (Speaker 1)", type="filepath")
407
- ref_text_input1 = gr.Textbox(label="Reference Text (Speaker 1)", lines=2)
408
-
409
- speaker2_name = gr.Textbox(label="Speaker 2 Name")
410
- ref_audio_input2 = gr.Audio(label="Reference Audio (Speaker 2)", type="filepath")
411
- ref_text_input2 = gr.Textbox(label="Reference Text (Speaker 2)", lines=2)
412
-
413
- script_input = gr.Textbox(label="Podcast Script", lines=10,
414
- placeholder="Enter the script with speaker names at the start of each block, e.g.:\nSean: How did you start studying...\n\nMeghan: I came to my interest in technology...\nIt was a long journey...\n\nSean: That's fascinating. Can you elaborate...")
415
-
416
- podcast_model_choice = gr.Radio(
417
- choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
418
- )
419
- podcast_remove_silence = gr.Checkbox(
420
- label="Remove Silences",
421
- value=True,
422
- )
423
- generate_podcast_btn = gr.Button("Generate Podcast", variant="primary")
424
- podcast_output = gr.Audio(label="Generated Podcast")
425
-
426
- def podcast_generation(script, speaker1, ref_audio1, ref_text1, speaker2, ref_audio2, ref_text2, model, remove_silence):
427
- return generate_podcast(script, speaker1, ref_audio1, ref_text1, speaker2, ref_audio2, ref_text2, model, remove_silence)
428
-
429
- generate_podcast_btn.click(
430
- podcast_generation,
431
- inputs=[
432
- script_input,
433
- speaker1_name,
434
- ref_audio_input1,
435
- ref_text_input1,
436
- speaker2_name,
437
- ref_audio_input2,
438
- ref_text_input2,
439
- podcast_model_choice,
440
- podcast_remove_silence,
441
- ],
442
- outputs=podcast_output,
443
- )
444
-
445
- def parse_emotional_text(gen_text):
446
- # Pattern to find (Emotion)
447
- pattern = r'\((.*?)\)'
448
-
449
- # Split the text by the pattern
450
- tokens = re.split(pattern, gen_text)
451
-
452
- segments = []
453
-
454
- current_emotion = 'Regular'
455
-
456
- for i in range(len(tokens)):
457
- if i % 2 == 0:
458
- # This is text
459
- text = tokens[i].strip()
460
- if text:
461
- segments.append({'emotion': current_emotion, 'text': text})
462
- else:
463
- # This is emotion
464
- emotion = tokens[i].strip()
465
- current_emotion = emotion
466
-
467
- return segments
468
-
469
- with gr.Blocks() as app_emotional:
470
- # New section for emotional generation
471
- gr.Markdown(
472
- """
473
- # Multiple Speech-Type Generation
474
- This section allows you to upload different audio clips for each speech type. 'Regular' emotion is mandatory. You can add additional speech types by clicking the "Add Speech Type" button. Enter your text in the format shown below, and the system will generate speech using the appropriate emotions. If unspecified, the model will use the regular speech type. The current speech type will be used until the next speech type is specified.
475
- **Example Input:**
476
- (Regular) Hello, I'd like to order a sandwich please. (Surprised) What do you mean you're out of bread? (Sad) I really wanted a sandwich though... (Angry) You know what, darn you and your little shop, you suck! (Whisper) I'll just go back home and cry now. (Shouting) Why me?!
477
- """
478
- )
479
-
480
- gr.Markdown("Upload different audio clips for each speech type. 'Regular' emotion is mandatory. You can add additional speech types by clicking the 'Add Speech Type' button.")
481
-
482
- # Regular speech type (mandatory)
483
- with gr.Row():
484
- regular_name = gr.Textbox(value='Regular', label='Speech Type Name', interactive=False)
485
- regular_audio = gr.Audio(label='Regular Reference Audio', type='filepath')
486
- regular_ref_text = gr.Textbox(label='Reference Text (Regular)', lines=2)
487
-
488
- # Additional speech types (up to 99 more)
489
- max_speech_types = 100
490
- speech_type_names = []
491
- speech_type_audios = []
492
- speech_type_ref_texts = []
493
- speech_type_delete_btns = []
494
-
495
- for i in range(max_speech_types - 1):
496
- with gr.Row():
497
- name_input = gr.Textbox(label='Speech Type Name', visible=False)
498
- audio_input = gr.Audio(label='Reference Audio', type='filepath', visible=False)
499
- ref_text_input = gr.Textbox(label='Reference Text', lines=2, visible=False)
500
- delete_btn = gr.Button("Delete", variant="secondary", visible=False)
501
- speech_type_names.append(name_input)
502
- speech_type_audios.append(audio_input)
503
- speech_type_ref_texts.append(ref_text_input)
504
- speech_type_delete_btns.append(delete_btn)
505
-
506
- # Button to add speech type
507
- add_speech_type_btn = gr.Button("Add Speech Type")
508
-
509
- # Keep track of current number of speech types
510
- speech_type_count = gr.State(value=0)
511
-
512
- # Function to add a speech type
513
- def add_speech_type_fn(speech_type_count):
514
- if speech_type_count < max_speech_types - 1:
515
- speech_type_count += 1
516
- # Prepare updates for the components
517
- name_updates = []
518
- audio_updates = []
519
- ref_text_updates = []
520
- delete_btn_updates = []
521
- for i in range(max_speech_types - 1):
522
- if i < speech_type_count:
523
- name_updates.append(gr.update(visible=True))
524
- audio_updates.append(gr.update(visible=True))
525
- ref_text_updates.append(gr.update(visible=True))
526
- delete_btn_updates.append(gr.update(visible=True))
527
- else:
528
- name_updates.append(gr.update())
529
- audio_updates.append(gr.update())
530
- ref_text_updates.append(gr.update())
531
- delete_btn_updates.append(gr.update())
532
- else:
533
- # Optionally, show a warning
534
- # gr.Warning("Maximum number of speech types reached.")
535
- name_updates = [gr.update() for _ in range(max_speech_types - 1)]
536
- audio_updates = [gr.update() for _ in range(max_speech_types - 1)]
537
- ref_text_updates = [gr.update() for _ in range(max_speech_types - 1)]
538
- delete_btn_updates = [gr.update() for _ in range(max_speech_types - 1)]
539
- return [speech_type_count] + name_updates + audio_updates + ref_text_updates + delete_btn_updates
540
-
541
- add_speech_type_btn.click(
542
- add_speech_type_fn,
543
- inputs=speech_type_count,
544
- outputs=[speech_type_count] + speech_type_names + speech_type_audios + speech_type_ref_texts + speech_type_delete_btns
545
- )
546
-
547
- # Function to delete a speech type
548
- def make_delete_speech_type_fn(index):
549
- def delete_speech_type_fn(speech_type_count):
550
- # Prepare updates
551
- name_updates = []
552
- audio_updates = []
553
- ref_text_updates = []
554
- delete_btn_updates = []
555
-
556
- for i in range(max_speech_types - 1):
557
- if i == index:
558
- name_updates.append(gr.update(visible=False, value=''))
559
- audio_updates.append(gr.update(visible=False, value=None))
560
- ref_text_updates.append(gr.update(visible=False, value=''))
561
- delete_btn_updates.append(gr.update(visible=False))
562
- else:
563
- name_updates.append(gr.update())
564
- audio_updates.append(gr.update())
565
- ref_text_updates.append(gr.update())
566
- delete_btn_updates.append(gr.update())
567
-
568
- speech_type_count = max(0, speech_type_count - 1)
569
-
570
- return [speech_type_count] + name_updates + audio_updates + ref_text_updates + delete_btn_updates
571
-
572
- return delete_speech_type_fn
573
-
574
- for i, delete_btn in enumerate(speech_type_delete_btns):
575
- delete_fn = make_delete_speech_type_fn(i)
576
- delete_btn.click(
577
- delete_fn,
578
- inputs=speech_type_count,
579
- outputs=[speech_type_count] + speech_type_names + speech_type_audios + speech_type_ref_texts + speech_type_delete_btns
580
- )
581
-
582
- # Text input for the prompt
583
- gen_text_input_emotional = gr.Textbox(label="Text to Generate", lines=10)
584
-
585
- # Model choice
586
- model_choice_emotional = gr.Radio(
587
- choices=["F5-TTS", "E2-TTS"], label="Choose TTS Model", value="F5-TTS"
588
- )
589
-
590
- with gr.Accordion("Advanced Settings", open=False):
591
- remove_silence_emotional = gr.Checkbox(
592
- label="Remove Silences",
593
- value=True,
594
- )
595
-
596
- # Generate button
597
- generate_emotional_btn = gr.Button("Generate Emotional Speech", variant="primary")
598
-
599
- # Output audio
600
- audio_output_emotional = gr.Audio(label="Synthesized Audio")
601
-
602
- @spaces.GPU(duration=30)
603
- def generate_emotional_speech(
604
- regular_audio,
605
- regular_ref_text,
606
- gen_text,
607
- *args,
608
- ):
609
- num_additional_speech_types = max_speech_types - 1
610
- speech_type_names_list = args[:num_additional_speech_types]
611
- speech_type_audios_list = args[num_additional_speech_types:2 * num_additional_speech_types]
612
- speech_type_ref_texts_list = args[2 * num_additional_speech_types:3 * num_additional_speech_types]
613
- model_choice = args[3 * num_additional_speech_types]
614
- remove_silence = args[3 * num_additional_speech_types + 1]
615
-
616
- # Collect the speech types and their audios into a dict
617
- speech_types = {'Regular': {'audio': regular_audio, 'ref_text': regular_ref_text}}
618
-
619
- for name_input, audio_input, ref_text_input in zip(speech_type_names_list, speech_type_audios_list, speech_type_ref_texts_list):
620
- if name_input and audio_input:
621
- speech_types[name_input] = {'audio': audio_input, 'ref_text': ref_text_input}
622
-
623
- # Parse the gen_text into segments
624
- segments = parse_speechtypes_text(gen_text)
625
-
626
- # For each segment, generate speech
627
- generated_audio_segments = []
628
- current_emotion = 'Regular'
629
-
630
- for segment in segments:
631
- emotion = segment['emotion']
632
- text = segment['text']
633
-
634
- if emotion in speech_types:
635
- current_emotion = emotion
636
- else:
637
- # If emotion not available, default to Regular
638
- current_emotion = 'Regular'
639
-
640
- ref_audio = speech_types[current_emotion]['audio']
641
- ref_text = speech_types[current_emotion].get('ref_text', '')
642
-
643
- # Generate speech for this segment
644
- audio, _ = infer(ref_audio, ref_text, text, model_choice, remove_silence, 0)
645
- sr, audio_data = audio
646
-
647
- generated_audio_segments.append(audio_data)
648
-
649
- # Concatenate all audio segments
650
- if generated_audio_segments:
651
- final_audio_data = np.concatenate(generated_audio_segments)
652
- return (sr, final_audio_data)
653
- else:
654
- gr.Warning("No audio generated.")
655
- return None
656
-
657
- generate_emotional_btn.click(
658
- generate_emotional_speech,
659
- inputs=[
660
- regular_audio,
661
- regular_ref_text,
662
- gen_text_input_emotional,
663
- ] + speech_type_names + speech_type_audios + speech_type_ref_texts + [
664
- model_choice_emotional,
665
- remove_silence_emotional,
666
- ],
667
- outputs=audio_output_emotional,
668
- )
669
-
670
- # Validation function to disable Generate button if speech types are missing
671
- def validate_speech_types(
672
- gen_text,
673
- regular_name,
674
- *args
675
- ):
676
- num_additional_speech_types = max_speech_types - 1
677
- speech_type_names_list = args[:num_additional_speech_types]
678
-
679
- # Collect the speech types names
680
- speech_types_available = set()
681
- if regular_name:
682
- speech_types_available.add(regular_name)
683
- for name_input in speech_type_names_list:
684
- if name_input:
685
- speech_types_available.add(name_input)
686
-
687
- # Parse the gen_text to get the speech types used
688
- segments = parse_emotional_text(gen_text)
689
- speech_types_in_text = set(segment['emotion'] for segment in segments)
690
-
691
- # Check if all speech types in text are available
692
- missing_speech_types = speech_types_in_text - speech_types_available
693
-
694
- if missing_speech_types:
695
- # Disable the generate button
696
- return gr.update(interactive=False)
697
- else:
698
- # Enable the generate button
699
- return gr.update(interactive=True)
700
-
701
- gen_text_input_emotional.change(
702
- validate_speech_types,
703
- inputs=[gen_text_input_emotional, regular_name] + speech_type_names,
704
- outputs=generate_emotional_btn
705
- )
706
- with gr.Blocks() as app:
707
- gr.Markdown(
708
- """
709
- # E2/F5 TTS
710
- This is a local web UI for F5 TTS with advanced batch processing support. This app supports the following TTS models:
711
- * [F5-TTS](https://arxiv.org/abs/2410.06885) (A Fairytaler that Fakes Fluent and Faithful Speech with Flow Matching)
712
- * [E2 TTS](https://arxiv.org/abs/2406.18009) (Embarrassingly Easy Fully Non-Autoregressive Zero-Shot TTS)
713
- The checkpoints support English and Chinese.
714
- If you're having issues, try converting your reference audio to WAV or MP3, clipping it to 15s, and shortening your prompt.
715
- **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.**
716
- """
717
- )
718
- gr.TabbedInterface([app_tts, app_podcast, app_emotional, app_credits], ["TTS", "Podcast", "Multi-Style", "Credits"])
719
-
720
- if __name__ == "__main__":
721
- app.queue().launch()