pnnbao-ump commited on
Commit
6f4a656
·
verified ·
1 Parent(s): 5cb5027

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +527 -513
app.py CHANGED
@@ -1,514 +1,528 @@
1
- import spaces # PHẢI import TRƯỚC mọi thứ trên HF Spaces ZeroGPU
2
- import os
3
- os.environ['SPACES_ZERO_GPU'] = '1'
4
-
5
- import gradio as gr
6
- import soundfile as sf
7
- import tempfile
8
- import torch
9
- from vieneu_tts import VieNeuTTS, FastVieNeuTTS
10
- import time
11
- import numpy as np
12
- import yaml
13
- from utils.core_utils import split_text_into_chunks
14
- import queue
15
- import threading
16
-
17
- print("⏳ Đang khởi động VieNeu-TTS...")
18
-
19
- # --- LOAD CONFIG ---
20
- CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.yaml")
21
- try:
22
- with open(CONFIG_PATH, "r", encoding="utf-8") as f:
23
- _config = yaml.safe_load(f) or {}
24
- except Exception as e:
25
- raise RuntimeError(f"Không thể đọc config.yaml: {e}")
26
-
27
- BACKBONE_CONFIGS = _config.get("backbone_configs", {})
28
- CODEC_CONFIGS = _config.get("codec_configs", {})
29
- VOICE_SAMPLES = _config.get("voice_samples", {})
30
-
31
- _text_settings = _config.get("text_settings", {})
32
- MAX_CHARS_PER_CHUNK = _text_settings.get("max_chars_per_chunk", 256)
33
- MAX_TOTAL_CHARS_STREAMING = _text_settings.get("max_total_chars_streaming", 3000)
34
-
35
- # --- KHỞI TẠO MODEL MẶC ĐỊNH ---
36
- print("📦 Đang tải model...")
37
- device = "cuda" if torch.cuda.is_available() else "cpu"
38
- print(f"🖥️ Sử dụng thiết bị: {device.upper()}")
39
-
40
- tts = None
41
- using_fast_backend = False
42
-
43
- try:
44
- backbone_config = BACKBONE_CONFIGS["VieNeu-TTS (GPU)"]
45
- codec_config = CODEC_CONFIGS["NeuCodec (Standard)"]
46
-
47
- # Thử dùng FastVieNeuTTS nếu GPU và đã cài LMDeploy
48
- if device == "cuda":
49
- try:
50
- print("🚀 Thử tải FastVieNeuTTS (LMDeploy backend)...")
51
- tts = FastVieNeuTTS(
52
- backbone_repo=backbone_config["repo"],
53
- backbone_device="cuda",
54
- codec_repo=codec_config["repo"],
55
- codec_device="cuda",
56
- memory_util=0.3,
57
- tp=1,
58
- enable_prefix_caching=True,
59
- quant_policy=8,
60
- enable_triton=True,
61
- max_batch_size=8,
62
- )
63
- using_fast_backend = True
64
- print("✅ FastVieNeuTTS đã tải thành công!")
65
-
66
- # Pre-cache voices
67
- print("📝 Pre-caching voices...")
68
- for voice_name, voice_info in VOICE_SAMPLES.items():
69
- audio_path = voice_info["audio"]
70
- text_path = voice_info["text"]
71
- if os.path.exists(audio_path) and os.path.exists(text_path):
72
- with open(text_path, "r", encoding="utf-8") as f:
73
- ref_text = f.read()
74
- tts.get_cached_reference(voice_name, audio_path, ref_text)
75
- print(f" Cached {len(VOICE_SAMPLES)} voices")
76
-
77
- except ImportError:
78
- print("⚠️ LMDeploy không có, fallback về VieNeuTTS standard...")
79
- using_fast_backend = False
80
-
81
- # Fallback về standard VieNeuTTS
82
- if tts is None:
83
- print("📦 Đang tải VieNeuTTS (Standard backend)...")
84
- tts = VieNeuTTS(
85
- backbone_repo=backbone_config["repo"],
86
- backbone_device=device,
87
- codec_repo=codec_config["repo"],
88
- codec_device=device
89
- )
90
- using_fast_backend = False
91
-
92
- print("✅ Model đã tải xong!")
93
-
94
- except Exception as e:
95
- print(f"⚠️ Không thể tải model (Chế độ UI Demo): {e}")
96
- class MockTTS:
97
- def encode_reference(self, path): return None
98
- def get_cached_reference(self, name, path, text): return None
99
- def infer(self, text, ref, ref_text):
100
- time.sleep(1.5)
101
- return np.random.uniform(-0.5, 0.5, 24000*3)
102
- def infer_batch(self, texts, ref, ref_text):
103
- return [self.infer(t, ref, ref_text) for t in texts]
104
- tts = MockTTS()
105
- using_fast_backend = False
106
-
107
- # --- HELPER FUNCTIONS ---
108
- def load_reference_info(voice_choice):
109
- if voice_choice in VOICE_SAMPLES:
110
- audio_path = VOICE_SAMPLES[voice_choice]["audio"]
111
- text_path = VOICE_SAMPLES[voice_choice]["text"]
112
- try:
113
- if os.path.exists(text_path):
114
- with open(text_path, "r", encoding="utf-8") as f:
115
- ref_text = f.read()
116
- return audio_path, ref_text
117
- else:
118
- return audio_path, "⚠️ Không tìm thấy file text mẫu."
119
- except Exception as e:
120
- return None, f"❌ Lỗi: {str(e)}"
121
- return None, ""
122
-
123
- @spaces.GPU(duration=120)
124
- def synthesize_speech(text, voice_choice, custom_audio, custom_text, mode_tab, generation_mode, use_batch):
125
- """Tổng hợp giọng nói với GPU acceleration"""
126
- global tts, using_fast_backend
127
-
128
- if tts is None:
129
- yield None, "⚠️ Model chưa được tải!"
130
- return
131
-
132
- if not text or text.strip() == "":
133
- yield None, "⚠️ Vui lòng nhập văn bản!"
134
- return
135
-
136
- raw_text = text.strip()
137
-
138
- # Setup Reference
139
- if mode_tab == "custom_mode":
140
- if custom_audio is None or not custom_text:
141
- yield None, "⚠️ Thiếu Audio hoặc Text mẫu custom."
142
- return
143
- ref_audio_path = custom_audio
144
- ref_text_raw = custom_text
145
- use_cached = False
146
- else:
147
- if voice_choice not in VOICE_SAMPLES:
148
- yield None, "⚠️ Vui lòng chọn giọng mẫu."
149
- return
150
- ref_audio_path = VOICE_SAMPLES[voice_choice]["audio"]
151
- ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
152
-
153
- if not os.path.exists(ref_audio_path):
154
- yield None, "❌ Không tìm thấy file audio mẫu."
155
- return
156
-
157
- with open(ref_text_path, "r", encoding="utf-8") as f:
158
- ref_text_raw = f.read()
159
- use_cached = True
160
-
161
- yield None, "📄 Đang xử lý Reference..."
162
-
163
- # Encode reference
164
- try:
165
- if use_cached and using_fast_backend and hasattr(tts, 'get_cached_reference'):
166
- ref_codes = tts.get_cached_reference(voice_choice, ref_audio_path, ref_text_raw)
167
- else:
168
- ref_codes = tts.encode_reference(ref_audio_path)
169
-
170
- if isinstance(ref_codes, torch.Tensor):
171
- ref_codes = ref_codes.cpu().numpy()
172
- except Exception as e:
173
- yield None, f"❌ Lỗi xử lý reference: {e}"
174
- return
175
-
176
- # Split text
177
- text_chunks = split_text_into_chunks(raw_text, max_chars=MAX_CHARS_PER_CHUNK)
178
- total_chunks = len(text_chunks)
179
-
180
- # === STANDARD MODE ===
181
- if generation_mode == "Standard (Một lần)":
182
- backend_name = "🚀 LMDeploy" if using_fast_backend else "📦 Standard"
183
- batch_info = " (Batch Mode)" if use_batch and using_fast_backend and total_chunks > 1 else ""
184
-
185
- yield None, f"{backend_name} Đang tổng hợp{batch_info} ({total_chunks} đoạn)..."
186
-
187
- all_audio_segments = []
188
- sr = 24000
189
- silence_pad = np.zeros(int(sr * 0.15), dtype=np.float32)
190
-
191
- start_time = time.time()
192
-
193
- try:
194
- # Batch processing nếu có FastVieNeuTTS
195
- if use_batch and using_fast_backend and hasattr(tts, 'infer_batch') and total_chunks > 1:
196
- yield None, f" Xử lý batch ({total_chunks} đoạn cùng lúc)..."
197
- chunk_wavs = tts.infer_batch(text_chunks, ref_codes, ref_text_raw)
198
-
199
- for i, chunk_wav in enumerate(chunk_wavs):
200
- if chunk_wav is not None and len(chunk_wav) > 0:
201
- all_audio_segments.append(chunk_wav)
202
- if i < total_chunks - 1:
203
- all_audio_segments.append(silence_pad)
204
- else:
205
- # Sequential processing
206
- for i, chunk in enumerate(text_chunks):
207
- yield None, f"⏳ Đang xử lý đoạn {i+1}/{total_chunks}..."
208
- chunk_wav = tts.infer(chunk, ref_codes, ref_text_raw)
209
-
210
- if chunk_wav is not None and len(chunk_wav) > 0:
211
- all_audio_segments.append(chunk_wav)
212
- if i < total_chunks - 1:
213
- all_audio_segments.append(silence_pad)
214
-
215
- if not all_audio_segments:
216
- yield None, "❌ Không sinh được audio nào."
217
- return
218
-
219
- yield None, "💾 Đang ghép file và lưu..."
220
-
221
- final_wav = np.concatenate(all_audio_segments)
222
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
223
- sf.write(tmp.name, final_wav, sr)
224
- output_path = tmp.name
225
-
226
- process_time = time.time() - start_time
227
- speed_info = f", Tốc độ: {len(final_wav)/sr/process_time:.2f}x realtime" if process_time > 0 else ""
228
-
229
- yield output_path, f"✅ Hoàn tất! (Thời gian: {process_time:.2f}s{speed_info}) {backend_name}"
230
-
231
- # Cleanup memory
232
- if using_fast_backend and hasattr(tts, 'cleanup_memory'):
233
- tts.cleanup_memory()
234
-
235
- except torch.cuda.OutOfMemoryError as e:
236
- yield None, f"❌ GPU hết VRAM! Hãy thử giảm độ dài văn bản.\n\nChi tiết: {str(e)}"
237
- if torch.cuda.is_available():
238
- torch.cuda.empty_cache()
239
- return
240
-
241
- except Exception as e:
242
- import traceback
243
- traceback.print_exc()
244
- yield None, f" Lỗi: {str(e)}"
245
- return
246
-
247
- # === STREAMING MODE ===
248
- else:
249
- sr = 24000
250
- crossfade_samples = int(sr * 0.03)
251
- audio_queue = queue.Queue(maxsize=100)
252
- PRE_BUFFER_SIZE = 3
253
-
254
- end_event = threading.Event()
255
- error_event = threading.Event()
256
- error_msg = ""
257
-
258
- def producer_thread():
259
- nonlocal error_msg
260
- try:
261
- previous_tail = None
262
-
263
- for i, chunk_text in enumerate(text_chunks):
264
- stream_gen = tts.infer_stream(chunk_text, ref_codes, ref_text_raw)
265
-
266
- for part_idx, audio_part in enumerate(stream_gen):
267
- if audio_part is None or len(audio_part) == 0:
268
- continue
269
-
270
- if previous_tail is not None and len(previous_tail) > 0:
271
- overlap = min(len(previous_tail), len(audio_part), crossfade_samples)
272
- if overlap > 0:
273
- fade_out = np.linspace(1.0, 0.0, overlap, dtype=np.float32)
274
- fade_in = np.linspace(0.0, 1.0, overlap, dtype=np.float32)
275
-
276
- blended = (audio_part[:overlap] * fade_in +
277
- previous_tail[-overlap:] * fade_out)
278
-
279
- processed = np.concatenate([
280
- previous_tail[:-overlap] if len(previous_tail) > overlap else np.array([]),
281
- blended,
282
- audio_part[overlap:]
283
- ])
284
- else:
285
- processed = np.concatenate([previous_tail, audio_part])
286
-
287
- tail_size = min(crossfade_samples, len(processed))
288
- previous_tail = processed[-tail_size:].copy()
289
- output_chunk = processed[:-tail_size] if len(processed) > tail_size else processed
290
- else:
291
- tail_size = min(crossfade_samples, len(audio_part))
292
- previous_tail = audio_part[-tail_size:].copy()
293
- output_chunk = audio_part[:-tail_size] if len(audio_part) > tail_size else audio_part
294
-
295
- if len(output_chunk) > 0:
296
- audio_queue.put((sr, output_chunk))
297
-
298
- if previous_tail is not None and len(previous_tail) > 0:
299
- audio_queue.put((sr, previous_tail))
300
-
301
- except Exception as e:
302
- import traceback
303
- traceback.print_exc()
304
- error_msg = str(e)
305
- error_event.set()
306
- finally:
307
- end_event.set()
308
- audio_queue.put(None)
309
-
310
- threading.Thread(target=producer_thread, daemon=True).start()
311
-
312
- yield (sr, np.zeros(int(sr * 0.05))), "📄 Đang buffering..."
313
-
314
- pre_buffer = []
315
- while len(pre_buffer) < PRE_BUFFER_SIZE:
316
- try:
317
- item = audio_queue.get(timeout=5.0)
318
- if item is None:
319
- break
320
- pre_buffer.append(item)
321
- except queue.Empty:
322
- if error_event.is_set():
323
- yield None, f"❌ Lỗi: {error_msg}"
324
- return
325
- break
326
-
327
- full_audio_buffer = []
328
- backend_info = "🚀 LMDeploy" if using_fast_backend else "📦 Standard"
329
- for sr, audio_data in pre_buffer:
330
- full_audio_buffer.append(audio_data)
331
- yield (sr, audio_data), f"🔊 Đang phát ({backend_info})..."
332
-
333
- while True:
334
- try:
335
- item = audio_queue.get(timeout=0.05)
336
- if item is None:
337
- break
338
- sr, audio_data = item
339
- full_audio_buffer.append(audio_data)
340
- yield (sr, audio_data), f"🔊 Đang phát ({backend_info})..."
341
- except queue.Empty:
342
- if error_event.is_set():
343
- yield None, f" Lỗi: {error_msg}"
344
- break
345
- if end_event.is_set() and audio_queue.empty():
346
- break
347
- continue
348
-
349
- if full_audio_buffer:
350
- final_wav = np.concatenate(full_audio_buffer)
351
- with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
352
- sf.write(tmp.name, final_wav, sr)
353
- yield tmp.name, f"✅ Hoàn tất Streaming! ({backend_info})"
354
-
355
- if using_fast_backend and hasattr(tts, 'cleanup_memory'):
356
- tts.cleanup_memory()
357
-
358
- # --- UI SETUP ---
359
- theme = gr.themes.Soft(
360
- primary_hue="indigo",
361
- secondary_hue="cyan",
362
- neutral_hue="slate",
363
- font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui'],
364
- ).set(
365
- button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #0ea5e9 100%)",
366
- button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #0284c7 100%)",
367
- block_shadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
368
- )
369
-
370
- css = """
371
- .container { max-width: 1200px; margin: auto; }
372
- .header-box {
373
- text-align: center;
374
- margin-bottom: 25px;
375
- padding: 25px;
376
- background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
377
- border-radius: 12px;
378
- border: 1px solid #334155;
379
- box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
380
- }
381
- .header-title {
382
- font-size: 2.5rem;
383
- font-weight: 800;
384
- color: white;
385
- background: -webkit-linear-gradient(45deg, #60A5FA, #22D3EE);
386
- -webkit-background-clip: text;
387
- -webkit-text-fill-color: transparent;
388
- margin-bottom: 10px;
389
- }
390
- .header-desc {
391
- font-size: 1.1rem;
392
- color: #cbd5e1;
393
- margin-bottom: 15px;
394
- }
395
- .link-group a {
396
- text-decoration: none;
397
- margin: 0 10px;
398
- font-weight: 600;
399
- color: #94a3b8;
400
- transition: color 0.2s;
401
- }
402
- .link-group a:hover { color: #38bdf8; text-shadow: 0 0 5px rgba(56, 189, 248, 0.5); }
403
- .status-box { font-weight: bold; text-align: center; border: none; background: transparent; }
404
- """
405
-
406
- EXAMPLES_LIST = [
407
- ["Về miền Tây không chỉ để ngắm nhìn sông nước hữu tình, mà còn để cảm nhận tấm chân tình của người dân nơi đây. Cùng ngồi xuồng ba lá len lỏi qua rặng dừa nước, nghe câu vọng cổ ngọt ngào thì còn gì bằng.", "Vĩnh (nam miền Nam)"],
408
- ["Hà Nội những ngày vào thu mang một vẻ đẹp trầm mặc và cổ kính đến lạ thường. Đi dạo quanh Hồ Gươm vào sáng sớm, hít hà mùi hoa sữa nồng nàn và thưởng thức chút cốm làng Vòng là trải nghiệm khó quên.", "Bình (nam miền Bắc)"],
409
- ["Sự bùng nổ của trí tuệ nhân tạo đang định hình lại cách chúng ta làm việc và sinh sống. Từ xe tự lái đến trợ lý ảo thông minh, công nghệ đang dần xóa nhòa ranh giới giữa thực tại và những bộ phim viễn tưởng.", "Tuyên (nam miền Bắc)"],
410
- ["Ngày xửa ngày xưa, ở một ngôi làng nọ có cô Tấm xinh đẹp, nết na nhưng sớm mồ côi mẹ. Dù bị mẹ kế và Cám hãm hại đủ đường, Tấm vẫn giữ được tấm lòng lương thiện và cuối cùng tìm được hạnh phúc xứng đáng.", "Đoan (nữ miền Nam)"],
411
- ]
412
-
413
- with gr.Blocks(theme=theme, css=css, title="VieNeu-TTS Studio") as demo:
414
- with gr.Column(elem_classes="container"):
415
- # Header
416
- gr.HTML("""
417
- <div class="header-box">
418
- <div class="header-title">🎙️ VieNeu-TTS Studio</div>
419
- <div class="header-desc">
420
- Phiên bản: VieNeu-TTS-1000h (GPU-optimized với LMDeploy)
421
- </div>
422
- <div class="link-group">
423
- <a href="https://huggingface.co/pnnbao-ump/VieNeu-TTS" target="_blank">🤗 Model Card</a>
424
- <a href="https://huggingface.co/datasets/pnnbao-ump/VieNeu-TTS-1000h" target="_blank">📖 Dataset 1000h</a>
425
- <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank">🦜 GitHub</a>
426
- </div>
427
- </div>
428
- """)
429
-
430
- # Status info
431
- backend_status = "🚀 LMDeploy (GPU-optimized)" if using_fast_backend else "📦 Standard Backend"
432
- gr.Markdown(f"**Backend hiện tại:** {backend_status}")
433
-
434
- with gr.Row(elem_classes="container", equal_height=False):
435
- # --- LEFT: INPUT ---
436
- with gr.Column(scale=3, variant="panel"):
437
- gr.Markdown("### 📝 Văn bản đầu vào")
438
- text_input = gr.Textbox(
439
- label="Nhập văn bản",
440
- placeholder="Nhập nội dung tiếng Việt cần chuyển thành giọng nói...",
441
- lines=4,
442
- value="Sự bùng nổ của trí tuệ nhân tạo đang định hình lại cách chúng ta làm việc và sinh sống. Từ xe tự lái đến trợ lý ảo thông minh, công nghệ đang dần xóa nhòa ranh giới giữa thực tại và những bộ phim viễn tưởng.",
443
- show_label=False
444
- )
445
-
446
- gr.Markdown("### 🗣️ Chọn giọng đọc")
447
- with gr.Tabs() as tabs:
448
- with gr.TabItem("👤 Giọng có sẵn (Preset)", id="preset_mode"):
449
- voice_select = gr.Dropdown(
450
- choices=list(VOICE_SAMPLES.keys()),
451
- value=list(VOICE_SAMPLES.keys())[0] if VOICE_SAMPLES else None,
452
- label="Danh sách giọng",
453
- interactive=True
454
- )
455
- with gr.Accordion("Thông tin giọng mẫu", open=False):
456
- ref_audio_preview = gr.Audio(label="Audio mẫu", interactive=False, type="filepath")
457
- ref_text_preview = gr.Markdown("...")
458
-
459
- with gr.TabItem("🎙️ Giọng tùy chỉnh (Custom)", id="custom_mode"):
460
- gr.Markdown("Tải lên giọng của bạn (Zero-shot Cloning)")
461
- custom_audio = gr.Audio(label="File ghi âm (.wav)", type="filepath")
462
- custom_text = gr.Textbox(label="Nội dung ghi âm", placeholder="Nhập chính xác lời thoại...")
463
-
464
- gr.Markdown("### ⚙️ Cài đặt tổng hợp")
465
- generation_mode = gr.Radio(
466
- ["Standard (Một lần)", "Streaming (Thời gian thực)"],
467
- value="Standard (Một lần)",
468
- label="Chế độ sinh"
469
- )
470
- use_batch = gr.Checkbox(
471
- value=True,
472
- label="⚡ Batch Processing (chỉ có hiệu lực khi dùng LMDeploy backend)",
473
- info="Xử nhiều đoạn cùng lúc để tăng tốc"
474
- )
475
-
476
- current_mode = gr.Textbox(visible=False, value="preset_mode")
477
- btn_generate = gr.Button("Tổng hợp giọng nói", variant="primary", size="lg")
478
-
479
- # --- RIGHT: OUTPUT ---
480
- with gr.Column(scale=2):
481
- gr.Markdown("### 🎧 Kết quả")
482
- with gr.Group():
483
- audio_output = gr.Audio(label="Audio đầu ra", type="filepath", show_download_button=True, autoplay=True)
484
- status_output = gr.Textbox(label="Trạng thái", show_label=False, elem_classes="status-box", placeholder="Sẵn sàng...")
485
-
486
- # --- EXAMPLES ---
487
- with gr.Row(elem_classes="container"):
488
- with gr.Column():
489
- gr.Markdown("### 📚 Ví dụ mẫu")
490
- gr.Examples(examples=EXAMPLES_LIST, inputs=[text_input, voice_select], label="Thử nghiệm nhanh")
491
-
492
- # --- EVENT HANDLERS ---
493
- def update_ref_preview(voice):
494
- audio, text = load_reference_info(voice)
495
- return audio, f"> *\"{text}\"*"
496
-
497
- voice_select.change(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
498
- demo.load(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
499
-
500
- # Tab handling
501
- tabs.children[0].select(fn=lambda: "preset_mode", outputs=current_mode)
502
- tabs.children[1].select(fn=lambda: "custom_mode", outputs=current_mode)
503
-
504
- btn_generate.click(
505
- fn=synthesize_speech,
506
- inputs=[text_input, voice_select, custom_audio, custom_text, current_mode, generation_mode, use_batch],
507
- outputs=[audio_output, status_output]
508
- )
509
-
510
- if __name__ == "__main__":
511
- demo.queue().launch(
512
- server_name="0.0.0.0",
513
- server_port=7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
514
  )
 
1
+ import spaces # PHẢI import TRƯỚC mọi thứ trên HF Spaces ZeroGPU
2
+ import os
3
+ os.environ['SPACES_ZERO_GPU'] = '1'
4
+
5
+ import gradio as gr
6
+ import soundfile as sf
7
+ import tempfile
8
+ import torch
9
+ from vieneu_tts import VieNeuTTS, FastVieNeuTTS
10
+ import time
11
+ import numpy as np
12
+ import yaml
13
+ from utils.core_utils import split_text_into_chunks
14
+ import queue
15
+ import threading
16
+
17
+ print("⏳ Đang khởi động VieNeu-TTS...")
18
+
19
+ # --- LOAD CONFIG ---
20
+ CONFIG_PATH = os.path.join(os.path.dirname(__file__), "config.yaml")
21
+ try:
22
+ with open(CONFIG_PATH, "r", encoding="utf-8") as f:
23
+ _config = yaml.safe_load(f) or {}
24
+ except Exception as e:
25
+ raise RuntimeError(f"Không thể đọc config.yaml: {e}")
26
+
27
+ BACKBONE_CONFIGS = _config.get("backbone_configs", {})
28
+ CODEC_CONFIGS = _config.get("codec_configs", {})
29
+ VOICE_SAMPLES = _config.get("voice_samples", {})
30
+
31
+ _text_settings = _config.get("text_settings", {})
32
+ MAX_CHARS_PER_CHUNK = _text_settings.get("max_chars_per_chunk", 256)
33
+ MAX_TOTAL_CHARS_STREAMING = _text_settings.get("max_total_chars_streaming", 3000)
34
+
35
+ # --- KHỞI TẠO MODEL - LAZY LOADING ---
36
+ print(" Chuẩn bị khởi tạo model (lazy loading cho ZeroGPU)...")
37
+
38
+ tts = None
39
+ using_fast_backend = False
40
+ model_loaded = False
41
+
42
+ @spaces.GPU(duration=60)
43
+ def initialize_model():
44
+ """Load model với GPU - chỉ gọi khi cần"""
45
+ global tts, using_fast_backend, model_loaded
46
+
47
+ if model_loaded and tts is not None:
48
+ return "✅ Model đã được tải sẵn!"
49
+
50
+ print("📦 Đang tải model với GPU...")
51
+ device = "cuda" if torch.cuda.is_available() else "cpu"
52
+ print(f"🖥️ Sử dụng thiết bị: {device.upper()}")
53
+
54
+ try:
55
+ backbone_config = BACKBONE_CONFIGS["VieNeu-TTS (GPU)"]
56
+ codec_config = CODEC_CONFIGS["NeuCodec (Standard)"]
57
+
58
+ # Thử dùng FastVieNeuTTS nếu có GPU và đã cài LMDeploy
59
+ if device == "cuda":
60
+ try:
61
+ print("🚀 Thử tải FastVieNeuTTS (LMDeploy backend)...")
62
+ tts = FastVieNeuTTS(
63
+ backbone_repo=backbone_config["repo"],
64
+ backbone_device="cuda",
65
+ codec_repo=codec_config["repo"],
66
+ codec_device="cuda",
67
+ memory_util=0.3,
68
+ tp=1,
69
+ enable_prefix_caching=True,
70
+ quant_policy=8,
71
+ enable_triton=True,
72
+ max_batch_size=8,
73
+ )
74
+ using_fast_backend = True
75
+ print("✅ FastVieNeuTTS đã tải thành công!")
76
+
77
+ # Pre-cache voices
78
+ print("📝 Pre-caching voices...")
79
+ for voice_name, voice_info in VOICE_SAMPLES.items():
80
+ audio_path = voice_info["audio"]
81
+ text_path = voice_info["text"]
82
+ if os.path.exists(audio_path) and os.path.exists(text_path):
83
+ with open(text_path, "r", encoding="utf-8") as f:
84
+ ref_text = f.read()
85
+ tts.get_cached_reference(voice_name, audio_path, ref_text)
86
+ print(f" ✅ Cached {len(VOICE_SAMPLES)} voices")
87
+
88
+ except (ImportError, Exception) as e:
89
+ print(f"⚠️ LMDeploy không khả dụng ({e}), fallback về VieNeuTTS standard...")
90
+ using_fast_backend = False
91
+
92
+ # Fallback về standard VieNeuTTS
93
+ if tts is None:
94
+ print("📦 Đang tải VieNeuTTS (Standard backend)...")
95
+ tts = VieNeuTTS(
96
+ backbone_repo=backbone_config["repo"],
97
+ backbone_device=device,
98
+ codec_repo=codec_config["repo"],
99
+ codec_device=device
100
+ )
101
+ using_fast_backend = False
102
+
103
+ model_loaded = True
104
+ print("✅ Model đã tải xong!")
105
+ backend = "🚀 LMDeploy (GPU-optimized)" if using_fast_backend else "📦 Standard Backend"
106
+ return f"✅ Model đã tải thành công!\n\n**Backend:** {backend}"
107
+
108
+ except Exception as e:
109
+ print(f"⚠️ Lỗi khi tải model: {e}")
110
+ import traceback
111
+ traceback.print_exc()
112
+ return f"❌ Lỗi: {str(e)}"
113
+
114
+ # Không tải model ngay lúc start - chỉ tải khi user bắt đầu synthesize
115
+ print("✅ Sẵn sàng! Model sẽ được tải khi bạn bắt đầu tổng hợp.")
116
+
117
+ # --- HELPER FUNCTIONS ---
118
+ def load_reference_info(voice_choice):
119
+ if voice_choice in VOICE_SAMPLES:
120
+ audio_path = VOICE_SAMPLES[voice_choice]["audio"]
121
+ text_path = VOICE_SAMPLES[voice_choice]["text"]
122
+ try:
123
+ if os.path.exists(text_path):
124
+ with open(text_path, "r", encoding="utf-8") as f:
125
+ ref_text = f.read()
126
+ return audio_path, ref_text
127
+ else:
128
+ return audio_path, "⚠️ Không tìm thấy file text mẫu."
129
+ except Exception as e:
130
+ return None, f"❌ Lỗi: {str(e)}"
131
+ return None, ""
132
+
133
+ @spaces.GPU(duration=120)
134
+ def synthesize_speech(text, voice_choice, custom_audio, custom_text, mode_tab, generation_mode, use_batch):
135
+ """Tổng hợp giọng nói với GPU acceleration"""
136
+ global tts, using_fast_backend, model_loaded
137
+
138
+ # Auto-load model nếu chưa có
139
+ if not model_loaded or tts is None:
140
+ yield None, "⏳ Đang tải model lần đầu..."
141
+ result = initialize_model()
142
+ if "❌" in result:
143
+ yield None, result
144
+ return
145
+ yield None, "✅ Model đã tải! Bắt đầu tổng hợp..."
146
+
147
+ if not text or text.strip() == "":
148
+ yield None, "⚠️ Vui lòng nhập văn bản!"
149
+ return
150
+
151
+ raw_text = text.strip()
152
+
153
+ # Setup Reference
154
+ if mode_tab == "custom_mode":
155
+ if custom_audio is None or not custom_text:
156
+ yield None, "⚠️ Thiếu Audio hoặc Text mẫu custom."
157
+ return
158
+ ref_audio_path = custom_audio
159
+ ref_text_raw = custom_text
160
+ use_cached = False
161
+ else:
162
+ if voice_choice not in VOICE_SAMPLES:
163
+ yield None, "⚠️ Vui lòng chọn giọng mẫu."
164
+ return
165
+ ref_audio_path = VOICE_SAMPLES[voice_choice]["audio"]
166
+ ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
167
+
168
+ if not os.path.exists(ref_audio_path):
169
+ yield None, "❌ Không tìm thấy file audio mẫu."
170
+ return
171
+
172
+ with open(ref_text_path, "r", encoding="utf-8") as f:
173
+ ref_text_raw = f.read()
174
+ use_cached = True
175
+
176
+ yield None, "📄 Đang xử lý Reference..."
177
+
178
+ # Encode reference
179
+ try:
180
+ if use_cached and using_fast_backend and hasattr(tts, 'get_cached_reference'):
181
+ ref_codes = tts.get_cached_reference(voice_choice, ref_audio_path, ref_text_raw)
182
+ else:
183
+ ref_codes = tts.encode_reference(ref_audio_path)
184
+
185
+ if isinstance(ref_codes, torch.Tensor):
186
+ ref_codes = ref_codes.cpu().numpy()
187
+ except Exception as e:
188
+ yield None, f"❌ Lỗi xử lý reference: {e}"
189
+ return
190
+
191
+ # Split text
192
+ text_chunks = split_text_into_chunks(raw_text, max_chars=MAX_CHARS_PER_CHUNK)
193
+ total_chunks = len(text_chunks)
194
+
195
+ # === STANDARD MODE ===
196
+ if generation_mode == "Standard (Một lần)":
197
+ backend_name = "🚀 LMDeploy" if using_fast_backend else "📦 Standard"
198
+ batch_info = " (Batch Mode)" if use_batch and using_fast_backend and total_chunks > 1 else ""
199
+
200
+ yield None, f"{backend_name} Đang tổng hợp{batch_info} ({total_chunks} đoạn)..."
201
+
202
+ all_audio_segments = []
203
+ sr = 24000
204
+ silence_pad = np.zeros(int(sr * 0.15), dtype=np.float32)
205
+
206
+ start_time = time.time()
207
+
208
+ try:
209
+ # Batch processing nếu có FastVieNeuTTS
210
+ if use_batch and using_fast_backend and hasattr(tts, 'infer_batch') and total_chunks > 1:
211
+ yield None, f"⚡ Xử lý batch ({total_chunks} đoạn cùng lúc)..."
212
+ chunk_wavs = tts.infer_batch(text_chunks, ref_codes, ref_text_raw)
213
+
214
+ for i, chunk_wav in enumerate(chunk_wavs):
215
+ if chunk_wav is not None and len(chunk_wav) > 0:
216
+ all_audio_segments.append(chunk_wav)
217
+ if i < total_chunks - 1:
218
+ all_audio_segments.append(silence_pad)
219
+ else:
220
+ # Sequential processing
221
+ for i, chunk in enumerate(text_chunks):
222
+ yield None, f" Đang xử lý đoạn {i+1}/{total_chunks}..."
223
+ chunk_wav = tts.infer(chunk, ref_codes, ref_text_raw)
224
+
225
+ if chunk_wav is not None and len(chunk_wav) > 0:
226
+ all_audio_segments.append(chunk_wav)
227
+ if i < total_chunks - 1:
228
+ all_audio_segments.append(silence_pad)
229
+
230
+ if not all_audio_segments:
231
+ yield None, "❌ Không sinh được audio nào."
232
+ return
233
+
234
+ yield None, "💾 Đang ghép file và lưu..."
235
+
236
+ final_wav = np.concatenate(all_audio_segments)
237
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
238
+ sf.write(tmp.name, final_wav, sr)
239
+ output_path = tmp.name
240
+
241
+ process_time = time.time() - start_time
242
+ speed_info = f", Tốc độ: {len(final_wav)/sr/process_time:.2f}x realtime" if process_time > 0 else ""
243
+
244
+ yield output_path, f" Hoàn tất! (Thời gian: {process_time:.2f}s{speed_info}) {backend_name}"
245
+
246
+ # Cleanup memory
247
+ if using_fast_backend and hasattr(tts, 'cleanup_memory'):
248
+ tts.cleanup_memory()
249
+
250
+ except torch.cuda.OutOfMemoryError as e:
251
+ yield None, f"❌ GPU hết VRAM! Hãy thử giảm độ dài văn bản.\n\nChi tiết: {str(e)}"
252
+ if torch.cuda.is_available():
253
+ torch.cuda.empty_cache()
254
+ return
255
+
256
+ except Exception as e:
257
+ import traceback
258
+ traceback.print_exc()
259
+ yield None, f"❌ Lỗi: {str(e)}"
260
+ return
261
+
262
+ # === STREAMING MODE ===
263
+ else:
264
+ sr = 24000
265
+ crossfade_samples = int(sr * 0.03)
266
+ audio_queue = queue.Queue(maxsize=100)
267
+ PRE_BUFFER_SIZE = 3
268
+
269
+ end_event = threading.Event()
270
+ error_event = threading.Event()
271
+ error_msg = ""
272
+
273
+ def producer_thread():
274
+ nonlocal error_msg
275
+ try:
276
+ previous_tail = None
277
+
278
+ for i, chunk_text in enumerate(text_chunks):
279
+ stream_gen = tts.infer_stream(chunk_text, ref_codes, ref_text_raw)
280
+
281
+ for part_idx, audio_part in enumerate(stream_gen):
282
+ if audio_part is None or len(audio_part) == 0:
283
+ continue
284
+
285
+ if previous_tail is not None and len(previous_tail) > 0:
286
+ overlap = min(len(previous_tail), len(audio_part), crossfade_samples)
287
+ if overlap > 0:
288
+ fade_out = np.linspace(1.0, 0.0, overlap, dtype=np.float32)
289
+ fade_in = np.linspace(0.0, 1.0, overlap, dtype=np.float32)
290
+
291
+ blended = (audio_part[:overlap] * fade_in +
292
+ previous_tail[-overlap:] * fade_out)
293
+
294
+ processed = np.concatenate([
295
+ previous_tail[:-overlap] if len(previous_tail) > overlap else np.array([]),
296
+ blended,
297
+ audio_part[overlap:]
298
+ ])
299
+ else:
300
+ processed = np.concatenate([previous_tail, audio_part])
301
+
302
+ tail_size = min(crossfade_samples, len(processed))
303
+ previous_tail = processed[-tail_size:].copy()
304
+ output_chunk = processed[:-tail_size] if len(processed) > tail_size else processed
305
+ else:
306
+ tail_size = min(crossfade_samples, len(audio_part))
307
+ previous_tail = audio_part[-tail_size:].copy()
308
+ output_chunk = audio_part[:-tail_size] if len(audio_part) > tail_size else audio_part
309
+
310
+ if len(output_chunk) > 0:
311
+ audio_queue.put((sr, output_chunk))
312
+
313
+ if previous_tail is not None and len(previous_tail) > 0:
314
+ audio_queue.put((sr, previous_tail))
315
+
316
+ except Exception as e:
317
+ import traceback
318
+ traceback.print_exc()
319
+ error_msg = str(e)
320
+ error_event.set()
321
+ finally:
322
+ end_event.set()
323
+ audio_queue.put(None)
324
+
325
+ threading.Thread(target=producer_thread, daemon=True).start()
326
+
327
+ yield (sr, np.zeros(int(sr * 0.05))), "📄 Đang buffering..."
328
+
329
+ pre_buffer = []
330
+ while len(pre_buffer) < PRE_BUFFER_SIZE:
331
+ try:
332
+ item = audio_queue.get(timeout=5.0)
333
+ if item is None:
334
+ break
335
+ pre_buffer.append(item)
336
+ except queue.Empty:
337
+ if error_event.is_set():
338
+ yield None, f"❌ Lỗi: {error_msg}"
339
+ return
340
+ break
341
+
342
+ full_audio_buffer = []
343
+ backend_info = "🚀 LMDeploy" if using_fast_backend else "📦 Standard"
344
+ for sr, audio_data in pre_buffer:
345
+ full_audio_buffer.append(audio_data)
346
+ yield (sr, audio_data), f"🔊 Đang phát ({backend_info})..."
347
+
348
+ while True:
349
+ try:
350
+ item = audio_queue.get(timeout=0.05)
351
+ if item is None:
352
+ break
353
+ sr, audio_data = item
354
+ full_audio_buffer.append(audio_data)
355
+ yield (sr, audio_data), f"🔊 Đang phát ({backend_info})..."
356
+ except queue.Empty:
357
+ if error_event.is_set():
358
+ yield None, f"❌ Lỗi: {error_msg}"
359
+ break
360
+ if end_event.is_set() and audio_queue.empty():
361
+ break
362
+ continue
363
+
364
+ if full_audio_buffer:
365
+ final_wav = np.concatenate(full_audio_buffer)
366
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
367
+ sf.write(tmp.name, final_wav, sr)
368
+ yield tmp.name, f"✅ Hoàn tất Streaming! ({backend_info})"
369
+
370
+ if using_fast_backend and hasattr(tts, 'cleanup_memory'):
371
+ tts.cleanup_memory()
372
+
373
+ # --- UI SETUP ---
374
+ theme = gr.themes.Soft(
375
+ primary_hue="indigo",
376
+ secondary_hue="cyan",
377
+ neutral_hue="slate",
378
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui'],
379
+ ).set(
380
+ button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #0ea5e9 100%)",
381
+ button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #0284c7 100%)",
382
+ block_shadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
383
+ )
384
+
385
+ css = """
386
+ .container { max-width: 1200px; margin: auto; }
387
+ .header-box {
388
+ text-align: center;
389
+ margin-bottom: 25px;
390
+ padding: 25px;
391
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
392
+ border-radius: 12px;
393
+ border: 1px solid #334155;
394
+ box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
395
+ }
396
+ .header-title {
397
+ font-size: 2.5rem;
398
+ font-weight: 800;
399
+ color: white;
400
+ background: -webkit-linear-gradient(45deg, #60A5FA, #22D3EE);
401
+ -webkit-background-clip: text;
402
+ -webkit-text-fill-color: transparent;
403
+ margin-bottom: 10px;
404
+ }
405
+ .header-desc {
406
+ font-size: 1.1rem;
407
+ color: #cbd5e1;
408
+ margin-bottom: 15px;
409
+ }
410
+ .link-group a {
411
+ text-decoration: none;
412
+ margin: 0 10px;
413
+ font-weight: 600;
414
+ color: #94a3b8;
415
+ transition: color 0.2s;
416
+ }
417
+ .link-group a:hover { color: #38bdf8; text-shadow: 0 0 5px rgba(56, 189, 248, 0.5); }
418
+ .status-box { font-weight: bold; text-align: center; border: none; background: transparent; }
419
+ """
420
+
421
+ EXAMPLES_LIST = [
422
+ ["Về miền Tây không chỉ để ngắm nhìn sông nước hữu tình, mà còn để cảm nhận tấm chân tình của ngư��i dân nơi đây. Cùng ngồi xuồng ba lá len lỏi qua rặng dừa nước, nghe câu vọng cổ ngọt ngào thì còn gì bằng.", "Vĩnh (nam miền Nam)"],
423
+ ["Hà Nội những ngày vào thu mang một vẻ đẹp trầm mặc và cổ kính đến lạ thường. Đi dạo quanh Hồ Gươm vào sáng sớm, hít hà mùi hoa sữa nồng nàn và thưởng thức chút cốm làng Vòng là trải nghiệm khó quên.", "Bình (nam miền Bắc)"],
424
+ ["Sự bùng nổ của trí tuệ nhân tạo đang định hình lại cách chúng ta làm việc và sinh sống. Từ xe tự lái đến trợ lý ảo thông minh, công nghệ đang dần xóa nhòa ranh giới giữa thực tại và những bộ phim viễn tưởng.", "Tuyên (nam miền Bắc)"],
425
+ ["Ngày xửa ngày xưa, ở một ngôi làng nọ có cô Tấm xinh đẹp, nết na nhưng sớm mồ côi mẹ. Dù bị mẹ kế và Cám hãm hại đủ đường, Tấm vẫn giữ được tấm lòng lương thiện và cuối cùng tìm được hạnh phúc xứng đáng.", "Đoan (nữ miền Nam)"],
426
+ ]
427
+
428
+ with gr.Blocks(theme=theme, css=css, title="VieNeu-TTS Studio") as demo:
429
+ with gr.Column(elem_classes="container"):
430
+ # Header
431
+ gr.HTML("""
432
+ <div class="header-box">
433
+ <div class="header-title">🎙️ VieNeu-TTS Studio</div>
434
+ <div class="header-desc">
435
+ Phiên bản: VieNeu-TTS-1000h (GPU-optimized với LMDeploy)
436
+ </div>
437
+ <div class="link-group">
438
+ <a href="https://huggingface.co/pnnbao-ump/VieNeu-TTS" target="_blank">🤗 Model Card</a> •
439
+ <a href="https://huggingface.co/datasets/pnnbao-ump/VieNeu-TTS-1000h" target="_blank">📖 Dataset 1000h</a> •
440
+ <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank">🦜 GitHub</a>
441
+ </div>
442
+ </div>
443
+ """)
444
+
445
+ # Status info
446
+ gr.Markdown("ℹ️ **Model sẽ tự động tải khi bạn bắt đầu tổng hợp giọng nói (lần đầu sẽ mất ~30-60 giây)**")
447
+
448
+ with gr.Row(elem_classes="container", equal_height=False):
449
+ # --- LEFT: INPUT ---
450
+ with gr.Column(scale=3, variant="panel"):
451
+ gr.Markdown("### 📝 Văn bản đầu vào")
452
+ text_input = gr.Textbox(
453
+ label="Nhập văn bản",
454
+ placeholder="Nhập nội dung tiếng Việt cần chuyển thành giọng nói...",
455
+ lines=4,
456
+ value="Sự bùng nổ của trí tuệ nhân tạo đang định hình lại cách chúng ta làm việc và sinh sống. Từ xe tự lái đến trợ lý ảo thông minh, công nghệ đang dần xóa nhòa ranh giới giữa thực tại và những bộ phim viễn tưởng.",
457
+ show_label=False
458
+ )
459
+
460
+ gr.Markdown("### 🗣️ Chọn giọng đọc")
461
+ with gr.Tabs() as tabs:
462
+ with gr.TabItem("👤 Giọng sẵn (Preset)", id="preset_mode"):
463
+ voice_select = gr.Dropdown(
464
+ choices=list(VOICE_SAMPLES.keys()),
465
+ value=list(VOICE_SAMPLES.keys())[0] if VOICE_SAMPLES else None,
466
+ label="Danh sách giọng",
467
+ interactive=True
468
+ )
469
+ with gr.Accordion("Thông tin giọng mẫu", open=False):
470
+ ref_audio_preview = gr.Audio(label="Audio mẫu", interactive=False, type="filepath")
471
+ ref_text_preview = gr.Markdown("...")
472
+
473
+ with gr.TabItem("🎙️ Giọng tùy chỉnh (Custom)", id="custom_mode"):
474
+ gr.Markdown("Tải lên giọng của bạn (Zero-shot Cloning)")
475
+ custom_audio = gr.Audio(label="File ghi âm (.wav)", type="filepath")
476
+ custom_text = gr.Textbox(label="Nội dung ghi âm", placeholder="Nhập chính xác lời thoại...")
477
+
478
+ gr.Markdown("### ⚙️ Cài đặt tổng hợp")
479
+ generation_mode = gr.Radio(
480
+ ["Standard (Một lần)", "Streaming (Thời gian thực)"],
481
+ value="Standard (Một lần)",
482
+ label="Chế độ sinh"
483
+ )
484
+ use_batch = gr.Checkbox(
485
+ value=True,
486
+ label="⚡ Batch Processing (chỉ có hiệu lực khi dùng LMDeploy backend)",
487
+ info="Xử lý nhiều đoạn cùng lúc để tăng tốc"
488
+ )
489
+
490
+ current_mode = gr.Textbox(visible=False, value="preset_mode")
491
+ btn_generate = gr.Button("Tổng hợp giọng nói", variant="primary", size="lg")
492
+
493
+ # --- RIGHT: OUTPUT ---
494
+ with gr.Column(scale=2):
495
+ gr.Markdown("### 🎧 Kết quả")
496
+ with gr.Group():
497
+ audio_output = gr.Audio(label="Audio đầu ra", type="filepath", show_download_button=True, autoplay=True)
498
+ status_output = gr.Textbox(label="Trạng thái", show_label=False, elem_classes="status-box", placeholder="Sẵn sàng...")
499
+
500
+ # --- EXAMPLES ---
501
+ with gr.Row(elem_classes="container"):
502
+ with gr.Column():
503
+ gr.Markdown("### 📚 Ví dụ mẫu")
504
+ gr.Examples(examples=EXAMPLES_LIST, inputs=[text_input, voice_select], label="Thử nghiệm nhanh")
505
+
506
+ # --- EVENT HANDLERS ---
507
+ def update_ref_preview(voice):
508
+ audio, text = load_reference_info(voice)
509
+ return audio, f"> *\"{text}\"*"
510
+
511
+ voice_select.change(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
512
+ demo.load(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
513
+
514
+ # Tab handling
515
+ tabs.children[0].select(fn=lambda: "preset_mode", outputs=current_mode)
516
+ tabs.children[1].select(fn=lambda: "custom_mode", outputs=current_mode)
517
+
518
+ btn_generate.click(
519
+ fn=synthesize_speech,
520
+ inputs=[text_input, voice_select, custom_audio, custom_text, current_mode, generation_mode, use_batch],
521
+ outputs=[audio_output, status_output]
522
+ )
523
+
524
+ if __name__ == "__main__":
525
+ demo.queue().launch(
526
+ server_name="0.0.0.0",
527
+ server_port=7860
528
  )