Staticaliza commited on
Commit
ac08618
1 Parent(s): 3469434

Update app.py

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