pnnbao-ump commited on
Commit
0436f07
·
verified ·
1 Parent(s): c3a6523

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +317 -527
app.py CHANGED
@@ -1,528 +1,318 @@
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ử 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 (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 có 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", autoplay=True)
498
- status_output = gr.Textbox(label="Trạng thái", 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
  )
 
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' # Set environment variable explicitly
4
+
5
+ import gradio as gr
6
+ import soundfile as sf
7
+ import tempfile
8
+ import torch
9
+ from vieneu_tts import VieNeuTTS
10
+ import time
11
+
12
+ print("⏳ Đang khởi động VieNeu-TTS...")
13
+
14
+ # --- 1. SETUP MODEL ---
15
+ print("📦 Đang tải model...")
16
+ device = "cuda" if torch.cuda.is_available() else "cpu"
17
+ print(f"🖥️ Sử dụng thiết bị: {device.upper()}")
18
+
19
+ try:
20
+ tts = VieNeuTTS(
21
+ backbone_repo="pnnbao-ump/VieNeu-TTS",
22
+ backbone_device=device,
23
+ codec_repo="neuphonic/neucodec",
24
+ codec_device=device
25
+ )
26
+ print("✅ Model đã tải xong!")
27
+ except Exception as e:
28
+ print(f"⚠️ Không thể tải model (Chế độ UI Demo): {e}")
29
+ class MockTTS:
30
+ def encode_reference(self, path): return None
31
+ def infer(self, text, ref, ref_text):
32
+ import numpy as np
33
+ # Giả lập độ trễ để test tính năng đo thời gian
34
+ time.sleep(1.5)
35
+ return np.random.uniform(-0.5, 0.5, 24000*3)
36
+ tts = MockTTS()
37
+
38
+ # --- 2. DATA ---
39
+ VOICE_SAMPLES = {
40
+ "Tuyên (nam miền Bắc)": {"audio": "./sample/Tuyên (nam miền Bắc).wav", "text": "./sample/Tuyên (nam miền Bắc).txt"},
41
+ "Vĩnh (nam miền Nam)": {"audio": "./sample/Vĩnh (nam miền Nam).wav", "text": "./sample/Vĩnh (nam miền Nam).txt"},
42
+ "Bình (nam miền Bắc)": {"audio": "./sample/Bình (nam miền Bắc).wav", "text": "./sample/Bình (nam miền Bắc).txt"},
43
+ "Nguyên (nam miền Nam)": {"audio": "./sample/Nguyên (nam miền Nam).wav", "text": "./sample/Nguyên (nam miền Nam).txt"},
44
+ "Sơn (nam miền Nam)": {"audio": "./sample/Sơn (nam miền Nam).wav", "text": "./sample/Sơn (nam miền Nam).txt"},
45
+ "Đoan (nữ miền Nam)": {"audio": "./sample/Đoan (nữ miền Nam).wav", "text": "./sample/Đoan (nữ miền Nam).txt"},
46
+ "Ngọc (nữ miền Bắc)": {"audio": "./sample/Ngọc (nữ miền Bắc).wav", "text": "./sample/Ngọc (nữ miền Bắc).txt"},
47
+ "Ly (nữ miền Bắc)": {"audio": "./sample/Ly (nữ miền Bắc).wav", "text": "./sample/Ly (nữ miền Bắc).txt"},
48
+ "Dung (nữ miền Nam)": {"audio": "./sample/Dung (nữ miền Nam).wav", "text": "./sample/Dung (nữ miền Nam).txt"}
49
+ }
50
+
51
+ # --- 3. HELPER FUNCTIONS ---
52
+ def load_reference_info(voice_choice):
53
+ if voice_choice in VOICE_SAMPLES:
54
+ audio_path = VOICE_SAMPLES[voice_choice]["audio"]
55
+ text_path = VOICE_SAMPLES[voice_choice]["text"]
56
+ try:
57
+ if os.path.exists(text_path):
58
+ with open(text_path, "r", encoding="utf-8") as f:
59
+ ref_text = f.read()
60
+ return audio_path, ref_text
61
+ else:
62
+ return audio_path, "⚠️ Không tìm thấy file text mẫu."
63
+ except Exception as e:
64
+ return None, f"❌ Lỗi: {str(e)}"
65
+ return None, ""
66
+
67
+ @spaces.GPU(duration=120)
68
+ def synthesize_speech(text, voice_choice, custom_audio, custom_text, mode_tab):
69
+ try:
70
+ if not text or text.strip() == "":
71
+ return None, "⚠️ Vui lòng nhập văn bản cần tổng hợp!"
72
+
73
+ # --- LOGIC CHECK LIMIT 250 ---
74
+ if len(text) > 250:
75
+ return None, f" Văn bản quá dài ({len(text)}/250 ký tự)! Vui lòng cắt ngắn lại để đảm bảo chất lượng."
76
+
77
+ # Logic chọn Reference
78
+ if mode_tab == "custom_mode":
79
+ if custom_audio is None or not custom_text:
80
+ return None, "⚠️ Vui lòng tải lên Audio và nhập nội dung Audio đó."
81
+ ref_audio_path = custom_audio
82
+ ref_text_raw = custom_text
83
+ print("🎨 Mode: Custom Voice")
84
+ else: # Preset
85
+ if voice_choice not in VOICE_SAMPLES:
86
+ return None, "⚠️ Vui lòng chọn một giọng mẫu."
87
+ ref_audio_path = VOICE_SAMPLES[voice_choice]["audio"]
88
+ ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
89
+
90
+ if not os.path.exists(ref_audio_path):
91
+ return None, f"❌ Không tìm thấy file audio: {ref_audio_path}"
92
+
93
+ with open(ref_text_path, "r", encoding="utf-8") as f:
94
+ ref_text_raw = f.read()
95
+ print(f"🎤 Mode: Preset Voice ({voice_choice})")
96
+
97
+ # Inference & Đo thời gian
98
+ print(f"📝 Text: {text[:50]}...")
99
+
100
+ start_time = time.time() # <--- Bắt đầu bấm giờ
101
+
102
+ ref_codes = tts.encode_reference(ref_audio_path)
103
+ wav = tts.infer(text, ref_codes, ref_text_raw)
104
+
105
+ end_time = time.time() # <--- Kết thúc bấm giờ
106
+ process_time = end_time - start_time # <--- Tính thời gian xử lý
107
+
108
+ # Save
109
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
110
+ sf.write(tmp_file.name, wav, 24000)
111
+ output_path = tmp_file.name
112
+
113
+ # <--- Cập nhật thông báo kết quả
114
+ return output_path, f"✅ Thành công! (Mất {process_time:.2f} giây để tạo)"
115
+
116
+ except Exception as e:
117
+ import traceback
118
+ traceback.print_exc()
119
+ return None, f"❌ Lỗi hệ thống: {str(e)}"
120
+
121
+ # --- 4. UI SETUP ---
122
+ # SỬA LỖI Ở ĐÂY: Đổi gr.themes.Ocean -> gr.themes.Soft
123
+ theme = gr.themes.Soft(
124
+ primary_hue="indigo",
125
+ secondary_hue="cyan",
126
+ neutral_hue="slate",
127
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui'],
128
+ ).set(
129
+ button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #0ea5e9 100%)",
130
+ button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #0284c7 100%)",
131
+ block_shadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
132
+ )
133
+
134
+ # <--- CSS ĐÃ SỬA (Background xanh đen + Chữ sáng)
135
+ css = """
136
+ .container { max-width: 1200px; margin: auto; }
137
+ .header-box {
138
+ text-align: center;
139
+ margin-bottom: 25px;
140
+ padding: 25px;
141
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); /* Xanh đen (Slate 900 -> 800) */
142
+ border-radius: 12px;
143
+ border: 1px solid #334155;
144
+ box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
145
+ }
146
+ .header-title {
147
+ font-size: 2.5rem;
148
+ font-weight: 800;
149
+ color: white; /* Chữ trắng */
150
+ background: -webkit-linear-gradient(45deg, #60A5FA, #22D3EE); /* Gradient xanh sáng cho chữ nổi bật */
151
+ -webkit-background-clip: text;
152
+ -webkit-text-fill-color: transparent;
153
+ margin-bottom: 10px;
154
+ }
155
+ .header-desc {
156
+ font-size: 1.1rem;
157
+ color: #cbd5e1; /* Màu xám sáng (Slate-300) */
158
+ margin-bottom: 15px;
159
+ }
160
+ .link-group a {
161
+ text-decoration: none;
162
+ margin: 0 10px;
163
+ font-weight: 600;
164
+ color: #94a3b8; /* Màu link sáng hơn chút */
165
+ transition: color 0.2s;
166
+ }
167
+ .link-group a:hover { color: #38bdf8; text-shadow: 0 0 5px rgba(56, 189, 248, 0.5); }
168
+
169
+ .status-box { font-weight: bold; text-align: center; border: none; background: transparent; }
170
+ .warning-note {
171
+ background-color: #fff7ed;
172
+ border-left: 4px solid #f97316;
173
+ padding: 12px;
174
+ color: #9a3412;
175
+ font-size: 0.9rem;
176
+ border-radius: 4px;
177
+ margin-top: 10px;
178
+ margin-bottom: 10px;
179
+ }
180
+ """
181
+
182
+ EXAMPLES_LIST = [
183
+ # Nam Miền Nam
184
+ ["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)"],
185
+
186
+ # Nam Miền Bắc
187
+ ["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)"],
188
+
189
+ # Nam Miền Bắc
190
+ ["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)"],
191
+
192
+ # Nam Miền Nam
193
+ ["Sài Gòn hối hả là thế, nhưng chỉ cần tấp vào một quán cà phê ven đường, gọi ly bạc xỉu đá và ngắm nhìn dòng người qua lại, bạn sẽ thấy thành phố này cũng có những khoảng lặng thật bình yên và đáng yêu.", "Nguyên (nam miền Nam)"],
194
+
195
+ # Nam Miền Nam
196
+ ["Để đảm bảo tiến độ dự án quan trọng này, chúng ta cần tập trung tối đa nguồn lực và phối hợp chặt chẽ giữa các phòng ban. Mọi khó khăn phát sinh cần được báo cáo ngay lập tức để ban lãnh đạo xử lý kịp thời.", "Sơn (nam miền Nam)"],
197
+
198
+ # Nữ Miền Nam
199
+ ["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)"],
200
+
201
+ # Nữ Miền Bắc
202
+ ["Dạ em chào anh chị, hiện tại bên em đang có chương trình ưu đãi đặc biệt cho căn hộ hướng sông này. Với thiết kế hiện đại và không gian xanh mát, đây chắc chắn là tổ ấm lý tưởng mà gia đình mình đang tìm kiếm.", "Ly (nữ miền Bắc)"],
203
+
204
+ # Nữ Miền Bắc
205
+ ["Dưới cơn mưa phùn lất phất của những ngày cuối đông, em khẽ nép vào vai anh, cảm nhận hơi ấm lan tỏa. Những khoảnh khắc bình dị như thế này khiến em nhận ra rằng, hạnh phúc đôi khi chỉ đơn giản là được ở bên nhau.", "Ngọc (nữ miền Bắc)"],
206
+ ]
207
+
208
+ with gr.Blocks(theme=theme, css=css, title="VieNeu-TTS Studio") as demo:
209
+
210
+ with gr.Column(elem_classes="container"):
211
+ # Header - Cập nhật class cho HTML
212
+ gr.HTML("""
213
+ <div class="header-box">
214
+ <div class="header-title">🎙️ VieNeu-TTS Studio</div>
215
+ <div class="header-desc">
216
+ Phiên bản: VieNeu-TTS-1000h (model mới nhất, train trên 1000 giờ dữ liệu)
217
+ </div>
218
+ <div class="link-group">
219
+ <a href="https://huggingface.co/pnnbao-ump/VieNeu-TTS" target="_blank">🤗 Model Card</a> •
220
+ <a href="https://huggingface.co/datasets/pnnbao-ump/VieNeu-TTS-1000h" target="_blank">📖 Dataset 1000h</a> •
221
+ <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank">🦜 GitHub</a>
222
+ </div>
223
+ </div>
224
+ """)
225
+
226
+ with gr.Row(elem_classes="container", equal_height=False):
227
+
228
+ # --- LEFT: INPUT ---
229
+ with gr.Column(scale=3, variant="panel"):
230
+ gr.Markdown("### 📝 Văn bản đầu vào")
231
+ text_input = gr.Textbox(
232
+ label="Nhập văn bản",
233
+ placeholder="Nhập nội dung tiếng Việt cần chuyển thành giọng nói...",
234
+ lines=4,
235
+ 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.",
236
+ show_label=False
237
+ )
238
+
239
+ # Counter + Warning
240
+ with gr.Row():
241
+ char_count = gr.HTML("<div style='text-align: right; color: #64748B; font-size: 0.8rem;'>0 / 250 ký tự</div>")
242
+
243
+ gr.Markdown("### 🗣️ Chọn giọng đọc")
244
+ with gr.Tabs() as tabs:
245
+ with gr.TabItem("👤 Giọng có sẵn (Preset)", id="preset_mode"):
246
+ voice_select = gr.Dropdown(
247
+ choices=list(VOICE_SAMPLES.keys()),
248
+ value="Tuyên (nam miền Bắc)",
249
+ label="Danh sách giọng",
250
+ interactive=True
251
+ )
252
+ with gr.Accordion("Thông tin giọng mẫu", open=False):
253
+ ref_audio_preview = gr.Audio(label="Audio mẫu", interactive=False, type="filepath")
254
+ ref_text_preview = gr.Markdown("...")
255
+
256
+ with gr.TabItem("🎙️ Giọng tùy chỉnh (Custom)", id="custom_mode"):
257
+ gr.Markdown("Tải lên giọng của bạn (Zero-shot Cloning)")
258
+ custom_audio = gr.Audio(label="File ghi âm (.wav)", type="filepath")
259
+ custom_text = gr.Textbox(label="Nội dung ghi âm", placeholder="Nhập chính xác lời thoại...")
260
+
261
+ current_mode = gr.Textbox(visible=False, value="preset_mode")
262
+ btn_generate = gr.Button("Tổng hợp giọng nói", variant="primary", size="lg")
263
+
264
+ # --- RIGHT: OUTPUT ---
265
+ with gr.Column(scale=2):
266
+ gr.Markdown("### 🎧 Kết quả")
267
+ with gr.Group():
268
+ audio_output = gr.Audio(label="Audio đầu ra", type="filepath", show_download_button=True, autoplay=True)
269
+ status_output = gr.Textbox(label="Trạng thái", show_label=False, elem_classes="status-box", placeholder="Sẵn sàng...")
270
+
271
+ # --- EXAMPLES ---
272
+ with gr.Row(elem_classes="container"):
273
+ with gr.Column():
274
+ gr.Markdown("### 📚 Ví dụ mẫu")
275
+ gr.Examples(examples=EXAMPLES_LIST, inputs=[text_input, voice_select], label="Thử nghiệm nhanh")
276
+
277
+ # --- LOGIC ---
278
+ def update_count(text):
279
+ l = len(text)
280
+ if l > 250:
281
+ color = "#dc2626" # Red
282
+ msg = f"⚠️ <b>{l} / 250</b> - Quá giới hạn!"
283
+ elif l > 200:
284
+ color = "#ea580c" # Orange
285
+ msg = f"{l} / 250"
286
+ else:
287
+ color = "#64748B" # Gray
288
+ msg = f"{l} / 250 ký tự"
289
+ return f"<div style='text-align: right; color: {color}; font-size: 0.8rem; font-weight: bold'>{msg}</div>"
290
+
291
+ text_input.change(update_count, text_input, char_count)
292
+
293
+ def update_ref_preview(voice):
294
+ audio, text = load_reference_info(voice)
295
+ return audio, f"> *\"{text}\"*"
296
+
297
+ voice_select.change(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
298
+ demo.load(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
299
+
300
+ # Tab handling - FIXED WITH *ARGS
301
+ tab_preset = tabs.children[0]
302
+ tab_custom = tabs.children[1]
303
+
304
+ # Dùng *args để nhận bất kỳ số lượng tham số nào (0 hoặc 1), tránh lỗi Warning
305
+ tab_preset.select(fn=lambda *args: "preset_mode", inputs=None, outputs=current_mode)
306
+ tab_custom.select(fn=lambda *args: "custom_mode", inputs=None, outputs=current_mode)
307
+
308
+ btn_generate.click(
309
+ fn=synthesize_speech,
310
+ inputs=[text_input, voice_select, custom_audio, custom_text, current_mode],
311
+ outputs=[audio_output, status_output]
312
+ )
313
+
314
+ if __name__ == "__main__":
315
+ demo.queue().launch(
316
+ server_name="0.0.0.0",
317
+ server_port=7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  )