versae commited on
Commit
7539f72
1 Parent(s): 6caa31c

Create app.py

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