pnnbao-ump commited on
Commit
222cbc4
·
verified ·
1 Parent(s): c99405f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +346 -317
app.py CHANGED
@@ -1,318 +1,347 @@
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 đượ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 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
  )
 
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()
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()
106
+ process_time = end_time - start_time
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
+ return output_path, f"✅ Thành công! (Thời gian: {process_time:.2f}s)"
114
+
115
+ except Exception as e:
116
+ import traceback
117
+ traceback.print_exc()
118
+ return None, f"❌ Lỗi hệ thống: {str(e)}"
119
+
120
+ # --- 4. UI SETUP ---
121
+ theme = gr.themes.Soft(
122
+ primary_hue="indigo",
123
+ secondary_hue="cyan",
124
+ neutral_hue="slate",
125
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui'],
126
+ ).set(
127
+ button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #0ea5e9 100%)",
128
+ button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #0284c7 100%)",
129
+ block_shadow="0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
130
+ )
131
+
132
+ css = """
133
+ .container { max-width: 1200px; margin: auto; }
134
+ .header-box {
135
+ text-align: center;
136
+ margin-bottom: 25px;
137
+ padding: 25px;
138
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
139
+ border-radius: 12px;
140
+ border: 1px solid #334155;
141
+ box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
142
+ }
143
+ .header-title {
144
+ font-size: 2.5rem;
145
+ font-weight: 800;
146
+ color: white;
147
+ background: -webkit-linear-gradient(45deg, #60A5FA, #22D3EE);
148
+ -webkit-background-clip: text;
149
+ -webkit-text-fill-color: transparent;
150
+ margin-bottom: 10px;
151
+ }
152
+ .header-desc {
153
+ font-size: 1.1rem;
154
+ color: #cbd5e1;
155
+ margin-bottom: 15px;
156
+ }
157
+ .link-group a {
158
+ text-decoration: none;
159
+ margin: 0 10px;
160
+ font-weight: 600;
161
+ color: #94a3b8;
162
+ transition: color 0.2s;
163
+ }
164
+ .link-group a:hover { color: #38bdf8; text-shadow: 0 0 5px rgba(56, 189, 248, 0.5); }
165
+ .status-box { font-weight: bold; text-align: center; border: none; background: transparent; }
166
+ .warning-banner {
167
+ background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
168
+ border: 2px solid #f59e0b;
169
+ border-radius: 8px;
170
+ padding: 15px 20px;
171
+ margin: 15px 0;
172
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
173
+ }
174
+ .warning-banner-title {
175
+ font-size: 1.1rem;
176
+ font-weight: 700;
177
+ color: #92400e;
178
+ margin-bottom: 8px;
179
+ display: flex;
180
+ align-items: center;
181
+ gap: 8px;
182
+ }
183
+ .warning-banner-content {
184
+ color: #78350f;
185
+ font-size: 0.95rem;
186
+ line-height: 1.6;
187
+ }
188
+ .warning-banner-content strong {
189
+ color: #92400e;
190
+ font-weight: 600;
191
+ }
192
+ .warning-banner-content code {
193
+ background: #fef3c7;
194
+ padding: 2px 6px;
195
+ border-radius: 3px;
196
+ font-family: monospace;
197
+ color: #92400e;
198
+ font-weight: 500;
199
+ }
200
+ """
201
+
202
+ EXAMPLES_LIST = [
203
+ ["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)"],
204
+ ["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)"],
205
+ ["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 sinh sống. Từ xe tự lái đến trợ ảo thông minh, công nghệ đang dần xóa nhòa ranh giới giữa thực tại những bộ phim viễn tưởng.", "Tuyên (nam miền Bắc)"],
206
+ ["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)"],
207
+ ["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)"],
208
+ ["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)"],
209
+ ]
210
+
211
+ with gr.Blocks(theme=theme, css=css, title="VieNeu-TTS Studio") as demo:
212
+
213
+ with gr.Column(elem_classes="container"):
214
+ # Header
215
+ gr.HTML("""
216
+ <div class="header-box">
217
+ <div class="header-title">🦜 VieNeu-TTS Studio</div>
218
+ <div class="header-desc">
219
+ Phiên bản: VieNeu-TTS (model mới nhất, train trên 1000 giờ dữ liệu)
220
+ </div>
221
+ <div class="link-group">
222
+ <a href="https://huggingface.co/pnnbao-ump/VieNeu-TTS" target="_blank">🤗 Model Card</a>
223
+ <a href="https://huggingface.co/datasets/pnnbao-ump/VieNeu-TTS-1000h" target="_blank">📖 Dataset 1000h</a>
224
+ <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank">🦜 GitHub</a>
225
+ </div>
226
+ </div>
227
+ """)
228
+
229
+ # Performance Warning Banner
230
+ gr.HTML("""
231
+ <div class="warning-banner">
232
+ <div class="warning-banner-title">
233
+ ⚠️ Lưu ý về hiệu năng
234
+ </div>
235
+ <div class="warning-banner-content">
236
+ <strong>Demo này chạy trên HF Spaces với ZeroGPU (shared GPU)</strong> nên tốc độ sẽ <strong>chậm hơn</strong> và có thể phải <strong>chờ queue</strong>.<br><br>
237
+
238
+ 💡 <strong>Muốn tốc độ cực nhanh?</strong> Hãy clone mã nguồn từ <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank" style="color: #92400e; text-decoration: underline;">GitHub</a> và cài <code>lmdeploy</code> để chạy trên GPU của bạn:<br>
239
+
240
+ <div style="margin-top: 10px; padding: 10px; background: #fffbeb; border-radius: 5px; border-left: 3px solid #f59e0b;">
241
+ <code style="display: block; margin: 3px 0;">git clone https://github.com/pnnbao97/VieNeu-TTS.git</code>
242
+ <code style="display: block; margin: 3px 0;">cd VieNeu-TTS</code>
243
+ <code style="display: block; margin: 3px 0;">pip install -r requirements.txt</code>
244
+ <code style="display: block; margin: 3px 0;">pip install lmdeploy # Để tăng tốc với GPU</code>
245
+ <code style="display: block; margin: 3px 0;">python app.py</code>
246
+ </div>
247
+
248
+ 🚀 Với LMDeploy + GPU local, tốc độ sẽ <strong>nhanh hơn 5-10 lần</strong> so với demo này!
249
+ </div>
250
+ </div>
251
+ """)
252
+
253
+ with gr.Row(elem_classes="container", equal_height=False):
254
+
255
+ # --- LEFT: INPUT ---
256
+ with gr.Column(scale=3, variant="panel"):
257
+ gr.Markdown("### 📝 Văn bản đầu vào")
258
+ text_input = gr.Textbox(
259
+ label="Nhập văn bản",
260
+ placeholder="Nhập nội dung tiếng Việt cần chuyển thành giọng nói...",
261
+ lines=4,
262
+ 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.",
263
+ show_label=False
264
+ )
265
+
266
+ # Counter
267
+ with gr.Row():
268
+ char_count = gr.HTML("<div style='text-align: right; color: #64748B; font-size: 0.8rem;'>0 / 250 ký tự</div>")
269
+
270
+ gr.Markdown("### 🗣️ Chọn giọng đọc")
271
+ with gr.Tabs() as tabs:
272
+ with gr.TabItem("👤 Giọng có sẵn (Preset)", id="preset_mode"):
273
+ voice_select = gr.Dropdown(
274
+ choices=list(VOICE_SAMPLES.keys()),
275
+ value="Tuyên (nam miền Bắc)",
276
+ label="Danh sách giọng",
277
+ interactive=True
278
+ )
279
+ with gr.Accordion("Thông tin giọng mẫu", open=False):
280
+ ref_audio_preview = gr.Audio(label="Audio mẫu", interactive=False, type="filepath")
281
+ ref_text_preview = gr.Markdown("...")
282
+
283
+ with gr.TabItem("🎙️ Giọng tùy chỉnh (Custom)", id="custom_mode"):
284
+ gr.Markdown("Tải lên giọng của bạn (Zero-shot Cloning)")
285
+ custom_audio = gr.Audio(label="File ghi âm (.wav)", type="filepath")
286
+ custom_text = gr.Textbox(label="Nội dung ghi âm", placeholder="Nhập chính xác lời thoại...")
287
+
288
+ current_mode = gr.State(value="preset_mode")
289
+ btn_generate = gr.Button("Tổng hợp giọng nói", variant="primary", size="lg")
290
+
291
+ # --- RIGHT: OUTPUT ---
292
+ with gr.Column(scale=2):
293
+ gr.Markdown("### 🎧 Kết quả")
294
+ with gr.Group():
295
+ audio_output = gr.Audio(label="Audio đầu ra", type="filepath", show_download_button=True, autoplay=True)
296
+ status_output = gr.Textbox(label="Trạng thái", show_label=False, elem_classes="status-box", placeholder="Sẵn sàng...")
297
+
298
+ # --- EXAMPLES ---
299
+ with gr.Row(elem_classes="container"):
300
+ with gr.Column():
301
+ gr.Markdown("### 📚 Ví dụ mẫu")
302
+ gr.Examples(examples=EXAMPLES_LIST, inputs=[text_input, voice_select], label="Thử nghiệm nhanh")
303
+
304
+ # --- LOGIC ---
305
+ def update_count(text):
306
+ l = len(text)
307
+ if l > 250:
308
+ color = "#dc2626"
309
+ msg = f"⚠️ <b>{l} / 250</b> - Quá giới hạn!"
310
+ elif l > 200:
311
+ color = "#ea580c"
312
+ msg = f"{l} / 250"
313
+ else:
314
+ color = "#64748B"
315
+ msg = f"{l} / 250 ký tự"
316
+ return f"<div style='text-align: right; color: {color}; font-size: 0.8rem; font-weight: bold'>{msg}</div>"
317
+
318
+ text_input.change(update_count, text_input, char_count)
319
+
320
+ def update_ref_preview(voice):
321
+ audio, text = load_reference_info(voice)
322
+ return audio, f"> *\"{text}\"*"
323
+
324
+ voice_select.change(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
325
+ demo.load(update_ref_preview, voice_select, [ref_audio_preview, ref_text_preview])
326
+
327
+ # Tab handling
328
+ def set_preset_mode():
329
+ return "preset_mode"
330
+
331
+ def set_custom_mode():
332
+ return "custom_mode"
333
+
334
+ tabs.children[0].select(fn=set_preset_mode, outputs=current_mode)
335
+ tabs.children[1].select(fn=set_custom_mode, outputs=current_mode)
336
+
337
+ btn_generate.click(
338
+ fn=synthesize_speech,
339
+ inputs=[text_input, voice_select, custom_audio, custom_text, current_mode],
340
+ outputs=[audio_output, status_output]
341
+ )
342
+
343
+ if __name__ == "__main__":
344
+ demo.queue().launch(
345
+ server_name="0.0.0.0",
346
+ server_port=7860
347
  )