Arrcttacsrks commited on
Commit
7fd1c60
·
verified ·
1 Parent(s): 0dbb973

Upload 2 files

Browse files
Files changed (2) hide show
  1. app-11.py +701 -0
  2. app-12.py +701 -0
app-11.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import soundfile as sf
3
+ import tempfile
4
+ import os
5
+ import time
6
+ import numpy as np
7
+ import librosa
8
+ import re
9
+ import json
10
+ import shutil
11
+ from pathlib import Path
12
+ from datetime import datetime
13
+ from llama_cpp import Llama
14
+ from neucodec import NeuCodecOnnxDecoder
15
+ import torch
16
+ from utils.phonemize_text import phonemize_with_dict
17
+ import threading
18
+ from queue import Queue
19
+
20
+ print("⏳ Đang khởi động VieNeu-TTS...")
21
+
22
+ # --- CONSTANTS ---
23
+ MAX_CHARS_PER_CHUNK = 256
24
+ SAMPLE_RATE = 24000
25
+ DEVICE_INFO = "Q4 GGUF (llama-cpp) + ONNX Codec"
26
+
27
+ # Thư mục lưu lịch sử - sử dụng thư mục tạm nếu không có quyền ghi
28
+ try:
29
+ HISTORY_DIR = "./tts_history"
30
+ os.makedirs(HISTORY_DIR, exist_ok=True)
31
+ # Test write permission
32
+ test_file = os.path.join(HISTORY_DIR, ".test")
33
+ with open(test_file, 'w') as f:
34
+ f.write("test")
35
+ os.remove(test_file)
36
+ except (PermissionError, OSError):
37
+ # Fallback to temp directory
38
+ HISTORY_DIR = os.path.join(tempfile.gettempdir(), "vieneu_tts_history")
39
+ os.makedirs(HISTORY_DIR, exist_ok=True)
40
+ print(f"⚠️ Không có quyền ghi, sử dụng thư mục tạm: {HISTORY_DIR}")
41
+
42
+ HISTORY_JSON = os.path.join(HISTORY_DIR, "history.json")
43
+
44
+ # Đường dẫn model
45
+ BACKBONE_REPO = "pnnbao-ump/VieNeu-TTS-q8-gguf"
46
+ CODEC_REPO = "neuphonic/neucodec-onnx-decoder"
47
+
48
+ # Giọng mẫu
49
+ VOICE_SAMPLES = {
50
+ "Tuyên (nam miền Bắc)": {
51
+ "audio": "./sample/Tuyên (nam miền Bắc).wav",
52
+ "text": "./sample/Tuyên (nam miền Bắc).txt",
53
+ "codes": "./sample/Tuyên (nam miền Bắc).pt"
54
+ },
55
+ "Vĩnh (nam miền Nam)": {
56
+ "audio": "./sample/Vĩnh (nam miền Nam).wav",
57
+ "text": "./sample/Vĩnh (nam miền Nam).txt",
58
+ "codes": "./sample/Vĩnh (nam miền Nam).pt"
59
+ },
60
+ "Bình (nam miền Bắc)": {
61
+ "audio": "./sample/Bình (nam miền Bắc).wav",
62
+ "text": "./sample/Bình (nam miền Bắc).txt",
63
+ "codes": "./sample/Bình (nam miền Bắc).pt"
64
+ },
65
+ "Nguyên (nam miền Nam)": {
66
+ "audio": "./sample/Nguyên (nam miền Nam).wav",
67
+ "text": "./sample/Nguyên (nam miền Nam).txt",
68
+ "codes": "./sample/Nguyên (nam miền Nam).pt"
69
+ },
70
+ "Sơn (nam miền Nam)": {
71
+ "audio": "./sample/Sơn (nam miền Nam).wav",
72
+ "text": "./sample/Sơn (nam miền Nam).txt",
73
+ "codes": "./sample/Sơn (nam miền Nam).pt"
74
+ },
75
+ "Đoan (nữ miền Nam)": {
76
+ "audio": "./sample/Đoan (nữ miền Nam).wav",
77
+ "text": "./sample/Đoan (nữ miền Nam).txt",
78
+ "codes": "./sample/Đoan (nữ miền Nam).pt"
79
+ },
80
+ "Ngọc (nữ miền Bắc)": {
81
+ "audio": "./sample/Ngọc (nữ miền Bắc).wav",
82
+ "text": "./sample/Ngọc (nữ miền Bắc).txt",
83
+ "codes": "./sample/Ngọc (nữ miền Bắc).pt"
84
+ },
85
+ "Ly (nữ miền Bắc)": {
86
+ "audio": "./sample/Ly (nữ miền Bắc).wav",
87
+ "text": "./sample/Ly (nữ miền Bắc).txt",
88
+ "codes": "./sample/Ly (nữ miền Bắc).pt"
89
+ },
90
+ "Dung (nữ miền Nam)": {
91
+ "audio": "./sample/Dung (nữ miền Nam).wav",
92
+ "text": "./sample/Dung (nữ miền Nam).txt",
93
+ "codes": "./sample/Dung (nữ miền Nam).pt"
94
+ }
95
+ }
96
+
97
+ # --- HISTORY MANAGEMENT ---
98
+ def load_history():
99
+ """Tải lịch sử từ file JSON"""
100
+ if os.path.exists(HISTORY_JSON):
101
+ try:
102
+ with open(HISTORY_JSON, 'r', encoding='utf-8') as f:
103
+ return json.load(f)
104
+ except:
105
+ return []
106
+ return []
107
+
108
+ def save_history(history):
109
+ """Lưu lịch sử vào file JSON"""
110
+ with open(HISTORY_JSON, 'w', encoding='utf-8') as f:
111
+ json.dump(history, f, ensure_ascii=False, indent=2)
112
+
113
+ def add_to_history(text, voice, audio_path, duration, status):
114
+ """Thêm một bản ghi vào lịch sử"""
115
+ try:
116
+ history = load_history()
117
+
118
+ # Tạo tên file duy nhất
119
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
120
+ filename = f"tts_{timestamp}.wav"
121
+ permanent_path = os.path.join(HISTORY_DIR, filename)
122
+
123
+ # Copy file audio vào thư mục lịch sử
124
+ if audio_path and os.path.exists(audio_path):
125
+ try:
126
+ shutil.copy2(audio_path, permanent_path)
127
+ except Exception as e:
128
+ print(f"⚠️ Không thể copy file audio: {e}")
129
+ permanent_path = audio_path # Dùng file tạm nếu không copy được
130
+
131
+ record = {
132
+ "id": timestamp,
133
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
134
+ "text": text[:100] + "..." if len(text) > 100 else text,
135
+ "full_text": text,
136
+ "voice": voice,
137
+ "audio_path": permanent_path,
138
+ "duration": duration,
139
+ "status": status
140
+ }
141
+
142
+ history.insert(0, record) # Thêm vào đầu danh sách
143
+
144
+ # Giới hạn lịch sử tối đa 100 bản ghi
145
+ if len(history) > 100:
146
+ # Xóa file audio cũ
147
+ old_record = history.pop()
148
+ try:
149
+ if os.path.exists(old_record['audio_path']):
150
+ os.remove(old_record['audio_path'])
151
+ except:
152
+ pass
153
+
154
+ save_history(history)
155
+ return permanent_path
156
+ except Exception as e:
157
+ print(f"⚠️ Lỗi khi lưu lịch sử: {e}")
158
+ return audio_path if audio_path else None
159
+
160
+ def get_history_list():
161
+ """Lấy danh sách lịch sử để hiển thị"""
162
+ history = load_history()
163
+ if not history:
164
+ return "Chưa có lịch sử tổng hợp nào."
165
+
166
+ output = []
167
+ for i, record in enumerate(history[:50], 1): # Hiển thị 50 bản ghi gần nhất
168
+ output.append(f"**{i}. [{record['timestamp']}]** - {record['voice']}")
169
+ output.append(f" 📝 {record['text']}")
170
+ output.append(f" ⏱️ Thời lượng: {record['duration']:.2f}s | {record['status']}")
171
+ output.append("")
172
+
173
+ return "\n".join(output)
174
+
175
+ def delete_history_item(item_id):
176
+ """Xóa một item khỏi lịch sử"""
177
+ history = load_history()
178
+ history = [h for h in history if h['id'] != item_id]
179
+ save_history(history)
180
+
181
+ # --- BACKGROUND PROCESSING QUEUE ---
182
+ processing_queue = Queue()
183
+ is_processing = False
184
+
185
+ def background_processor():
186
+ """Xử lý queue tổng hợp trong background"""
187
+ global is_processing
188
+ while True:
189
+ task = processing_queue.get()
190
+ if task is None:
191
+ break
192
+
193
+ is_processing = True
194
+ text, voice = task
195
+
196
+ try:
197
+ print(f"[Background] Bắt đầu tổng hợp: {text[:50]}...")
198
+ result = synthesize_speech_internal(text, voice)
199
+ print(f"[Background] Hoàn thành: {result}")
200
+ except Exception as e:
201
+ print(f"[Background] Lỗi: {e}")
202
+
203
+ is_processing = False
204
+ processing_queue.task_done()
205
+
206
+ # Khởi động background thread
207
+ bg_thread = threading.Thread(target=background_processor, daemon=True)
208
+ bg_thread.start()
209
+
210
+ def split_text_into_chunks(text, max_chars=256):
211
+ """Chia text thành chunks"""
212
+ sentences = re.split(r'([.!?,;])', text)
213
+ chunks = []
214
+ current = ""
215
+
216
+ for i in range(0, len(sentences), 2):
217
+ sentence = sentences[i]
218
+ punct = sentences[i+1] if i+1 < len(sentences) else ""
219
+ segment = sentence + punct
220
+
221
+ if len(current) + len(segment) <= max_chars:
222
+ current += segment
223
+ else:
224
+ if current:
225
+ chunks.append(current.strip())
226
+ current = segment
227
+
228
+ if current:
229
+ chunks.append(current.strip())
230
+
231
+ return chunks if chunks else [text]
232
+
233
+ def decode_audio(codes_str, codec):
234
+ """Decode speech tokens to audio"""
235
+ speech_ids = [int(num) for num in re.findall(r"<\|speech_(\d+)\|>", codes_str)]
236
+
237
+ if len(speech_ids) == 0:
238
+ print("Không tìm thấy mã giọng nói hợp lệ.")
239
+ return np.array([], dtype=np.float32)
240
+
241
+ codes = np.array(speech_ids, dtype=np.int32)[np.newaxis, np.newaxis, :]
242
+ recon = codec.decode_code(codes)
243
+ return recon[0, 0, :]
244
+
245
+ # --- MODEL LOADING ---
246
+ print("📦 Đang tải model Q4 GGUF và Codec ONNX...")
247
+ model_loaded = False
248
+ backbone = None
249
+ codec = None
250
+
251
+ try:
252
+ backbone = Llama.from_pretrained(
253
+ repo_id=BACKBONE_REPO,
254
+ filename="*.gguf",
255
+ verbose=False,
256
+ n_gpu_layers=-1,
257
+ n_ctx=2048,
258
+ mlock=True,
259
+ flash_attn=True,
260
+ )
261
+
262
+ codec = NeuCodecOnnxDecoder.from_pretrained(CODEC_REPO)
263
+
264
+ print("✅ Model đã tải thành công!")
265
+ model_loaded = True
266
+ except Exception as e:
267
+ import traceback
268
+ traceback.print_exc()
269
+ print(f"❌ Lỗi khi tải model: {e}")
270
+ model_loaded = False
271
+
272
+ # --- SYNTHESIS FUNCTION (Internal) ---
273
+ def synthesize_speech_internal(text, voice_choice):
274
+ """Internal synthesis function không phụ thuộc UI"""
275
+ global backbone, codec, model_loaded
276
+
277
+ if not model_loaded:
278
+ return None
279
+
280
+ if not text or text.strip() == "":
281
+ return None
282
+
283
+ if voice_choice not in VOICE_SAMPLES:
284
+ return None
285
+
286
+ raw_text = text.strip()
287
+
288
+ # Load reference text
289
+ ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
290
+ try:
291
+ with open(ref_text_path, "r", encoding="utf-8") as f:
292
+ ref_text_raw = f.read()
293
+ except Exception as e:
294
+ print(f"❌ Lỗi đọc file text mẫu: {e}")
295
+ return None
296
+
297
+ # Tải codes
298
+ ref_codes = None
299
+ codes_path = VOICE_SAMPLES[voice_choice]["codes"]
300
+
301
+ try:
302
+ ref_codes_tensor = torch.load(codes_path, map_location="cpu")
303
+ if isinstance(ref_codes_tensor, torch.Tensor):
304
+ ref_codes = ref_codes_tensor.cpu().numpy()
305
+ else:
306
+ ref_codes = np.array(ref_codes_tensor)
307
+ except Exception as e:
308
+ print(f"❌ Lỗi khi tải codes: {e}")
309
+ return None
310
+
311
+ if ref_codes is None or len(ref_codes) == 0:
312
+ return None
313
+
314
+ # Split text
315
+ text_chunks = split_text_into_chunks(raw_text, max_chars=MAX_CHARS_PER_CHUNK)
316
+
317
+ all_audio_segments = []
318
+ silence_pad = np.zeros(int(SAMPLE_RATE * 0.15), dtype=np.float32)
319
+
320
+ start_time = time.time()
321
+
322
+ try:
323
+ for i, chunk in enumerate(text_chunks):
324
+ # Phonemize
325
+ ref_text_phoneme = phonemize_with_dict(ref_text_raw)
326
+ input_text_phoneme = phonemize_with_dict(chunk)
327
+
328
+ # Create prompt
329
+ codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
330
+
331
+ prompt = (
332
+ f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text_phoneme} {input_text_phoneme}"
333
+ f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
334
+ )
335
+
336
+ # Generate
337
+ output = backbone(
338
+ prompt,
339
+ max_tokens=2048,
340
+ temperature=1.0,
341
+ top_k=50,
342
+ stop=["<|SPEECH_GENERATION_END|>"],
343
+ )
344
+ output_str = output["choices"][0]["text"]
345
+
346
+ # Decode
347
+ chunk_wav = decode_audio(codes_str + output_str, codec)
348
+
349
+ if chunk_wav is not None and len(chunk_wav) > 0:
350
+ all_audio_segments.append(chunk_wav)
351
+ if i < len(text_chunks) - 1:
352
+ all_audio_segments.append(silence_pad)
353
+
354
+ if not all_audio_segments:
355
+ return None
356
+
357
+ final_wav = np.concatenate(all_audio_segments)
358
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
359
+ sf.write(tmp.name, final_wav, SAMPLE_RATE)
360
+ output_path = tmp.name
361
+
362
+ process_time = time.time() - start_time
363
+
364
+ # Lưu vào lịch sử
365
+ permanent_path = add_to_history(raw_text, voice_choice, output_path, process_time, "Thành công")
366
+
367
+ return permanent_path
368
+
369
+ except Exception as e:
370
+ import traceback
371
+ traceback.print_exc()
372
+ return None
373
+
374
+ # --- SYNTHESIS FUNCTION (UI) ---
375
+ def synthesize_speech(text, voice_choice):
376
+ """Main synthesis function với UI feedback"""
377
+ global backbone, codec, model_loaded
378
+
379
+ if not model_loaded:
380
+ yield None, "⚠️ Model chưa tải. Vui lòng kiểm tra lỗi console!"
381
+ return
382
+
383
+ if not text or text.strip() == "":
384
+ yield None, "⚠️ Vui lòng nhập văn bản!"
385
+ return
386
+
387
+ if voice_choice not in VOICE_SAMPLES:
388
+ yield None, "⚠️ Vui lòng chọn giọng mẫu."
389
+ return
390
+
391
+ raw_text = text.strip()
392
+
393
+ # Load reference text
394
+ ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
395
+ try:
396
+ with open(ref_text_path, "r", encoding="utf-8") as f:
397
+ ref_text_raw = f.read()
398
+ except Exception as e:
399
+ yield None, f"❌ Lỗi đọc file text mẫu: {e}"
400
+ return
401
+
402
+ yield None, "📄 Đang xử lý Reference..."
403
+
404
+ # Tải codes
405
+ ref_codes = None
406
+ codes_path = VOICE_SAMPLES[voice_choice]["codes"]
407
+
408
+ try:
409
+ ref_codes_tensor = torch.load(codes_path, map_location="cpu")
410
+ if isinstance(ref_codes_tensor, torch.Tensor):
411
+ ref_codes = ref_codes_tensor.cpu().numpy()
412
+ else:
413
+ ref_codes = np.array(ref_codes_tensor)
414
+ except Exception as e:
415
+ yield None, f"❌ Lỗi khi tải codes: {e}"
416
+ return
417
+
418
+ if ref_codes is None or len(ref_codes) == 0:
419
+ yield None, "❌ Codes tham chiếu không hợp lệ."
420
+ return
421
+
422
+ # Split text
423
+ text_chunks = split_text_into_chunks(raw_text, max_chars=MAX_CHARS_PER_CHUNK)
424
+ total_chunks = len(text_chunks)
425
+
426
+ yield None, f"🚀 Bắt đầu tổng hợp ({total_chunks} đoạn)..."
427
+
428
+ all_audio_segments = []
429
+ silence_pad = np.zeros(int(SAMPLE_RATE * 0.15), dtype=np.float32)
430
+
431
+ start_time = time.time()
432
+
433
+ try:
434
+ for i, chunk in enumerate(text_chunks):
435
+ yield None, f"⏳ Đang xử lý đoạn {i+1}/{total_chunks}..."
436
+
437
+ # Phonemize
438
+ ref_text_phoneme = phonemize_with_dict(ref_text_raw)
439
+ input_text_phoneme = phonemize_with_dict(chunk)
440
+
441
+ # Create prompt
442
+ codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
443
+
444
+ prompt = (
445
+ f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text_phoneme} {input_text_phoneme}"
446
+ f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
447
+ )
448
+
449
+ # Generate
450
+ output = backbone(
451
+ prompt,
452
+ max_tokens=2048,
453
+ temperature=1.0,
454
+ top_k=50,
455
+ stop=["<|SPEECH_GENERATION_END|>"],
456
+ )
457
+ output_str = output["choices"][0]["text"]
458
+
459
+ # Decode
460
+ chunk_wav = decode_audio(codes_str + output_str, codec)
461
+
462
+ if chunk_wav is not None and len(chunk_wav) > 0:
463
+ all_audio_segments.append(chunk_wav)
464
+ if i < total_chunks - 1:
465
+ all_audio_segments.append(silence_pad)
466
+
467
+ if not all_audio_segments:
468
+ yield None, "❌ Không sinh được audio nào."
469
+ return
470
+
471
+ yield None, "💾 Đang ghép file và lưu..."
472
+
473
+ final_wav = np.concatenate(all_audio_segments)
474
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
475
+ sf.write(tmp.name, final_wav, SAMPLE_RATE)
476
+ output_path = tmp.name
477
+
478
+ process_time = time.time() - start_time
479
+
480
+ # Lưu vào lịch sử
481
+ permanent_path = add_to_history(raw_text, voice_choice, output_path, process_time, "Thành công")
482
+
483
+ yield permanent_path, f"✅ Hoàn tất! (Tổng thời gian: {process_time:.2f}s)"
484
+
485
+ except Exception as e:
486
+ import traceback
487
+ traceback.print_exc()
488
+ add_to_history(raw_text, voice_choice, None, 0, f"Lỗi: {str(e)}")
489
+ yield None, f"❌ Lỗi tổng hợp: {str(e)}"
490
+
491
+ def refresh_history():
492
+ """Làm mới danh sách lịch sử"""
493
+ return get_history_list()
494
+
495
+ def load_history_item(history_index):
496
+ """Tải một item từ lịch sử"""
497
+ if not history_index:
498
+ return None, "", "", ""
499
+
500
+ try:
501
+ index = int(history_index.split(".")[0]) - 1
502
+ history = load_history()
503
+ if 0 <= index < len(history):
504
+ record = history[index]
505
+ return (
506
+ record['audio_path'] if os.path.exists(record['audio_path']) else None,
507
+ record['full_text'],
508
+ record['voice'],
509
+ f"📅 {record['timestamp']} | ⏱️ {record['duration']:.2f}s"
510
+ )
511
+ except:
512
+ pass
513
+
514
+ return None, "", "", ""
515
+
516
+ # --- UI SETUP ---
517
+ theme = gr.themes.Ocean(
518
+ primary_hue="indigo",
519
+ secondary_hue="cyan",
520
+ neutral_hue="slate",
521
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui'],
522
+ ).set(
523
+ button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #0ea5e9 100%)",
524
+ button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #0284c7 100%)",
525
+ )
526
+
527
+ css = """
528
+ .container { max-width: 1400px; margin: auto; }
529
+ .header-box {
530
+ text-align: center;
531
+ margin-bottom: 25px;
532
+ padding: 25px;
533
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
534
+ border-radius: 12px;
535
+ color: white;
536
+ }
537
+ .header-title {
538
+ font-size: 2.5rem;
539
+ font-weight: 800;
540
+ }
541
+ .gradient-text {
542
+ background: -webkit-linear-gradient(45deg, #60A5FA, #22D3EE);
543
+ -webkit-background-clip: text;
544
+ -webkit-text-fill-color: transparent;
545
+ }
546
+ .status-box {
547
+ font-weight: bold;
548
+ text-align: center;
549
+ border: none;
550
+ background: transparent;
551
+ }
552
+ .model-card-content {
553
+ display: flex;
554
+ flex-wrap: wrap;
555
+ justify-content: center;
556
+ align-items: center;
557
+ gap: 15px;
558
+ font-size: 0.9rem;
559
+ color: #cbd5e1;
560
+ }
561
+ .model-card-item {
562
+ display: flex;
563
+ align-items: center;
564
+ justify-content: center;
565
+ gap: 6px;
566
+ color: #94a3b8;
567
+ }
568
+ .model-card-link {
569
+ color: #3b82f6;
570
+ text-decoration: none;
571
+ font-weight: 500;
572
+ transition: color 0.2s;
573
+ }
574
+ .model-card-link:hover {
575
+ color: #2563eb;
576
+ text-decoration: underline;
577
+ }
578
+ .history-list {
579
+ max-height: 600px;
580
+ overflow-y: auto;
581
+ padding: 15px;
582
+ background: #f8fafc;
583
+ border-radius: 8px;
584
+ }
585
+ """
586
+
587
+ EXAMPLES_LIST = [
588
+ ["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.", "Vĩnh (nam miền Nam)"],
589
+ ["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.", "Bình (nam miền Bắc)"],
590
+ ["Thành phố Hồ Chí Minh luôn chuyển mình không ngừng với nhịp sống hối hả, năng động.", "Dung (nữ miền Nam)"],
591
+ ]
592
+
593
+ initial_status = f"✅ Model đã tải thành công! (Chạy trên **{DEVICE_INFO}**). Hỗ trợ xử lý background và lưu lịch sử." if model_loaded else "❌ Lỗi khi tải model."
594
+
595
+ with gr.Blocks(title="VieNeu-TTS", theme=theme, css=css) as demo:
596
+ with gr.Column(elem_classes="container"):
597
+ gr.HTML(f"""
598
+ <div class="header-box">
599
+ <h1 class="header-title">
600
+ <span class="header-icon">🦜</span>
601
+ <span class="gradient-text">VieNeu-TTS Studio</span>
602
+ </h1>
603
+ <p>Chế độ: {DEVICE_INFO} | Background Processing ✅ | History ✅</p>
604
+ <p style="font-size: 0.85rem; color: #94a3b8;">📁 Lịch sử lưu tại: {HISTORY_DIR}</p>
605
+ <div class="model-card-content">
606
+ <div class="model-card-item">
607
+ <strong>Repository:</strong>
608
+ <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank" class="model-card-link">GitHub</a>
609
+ </div>
610
+ <div class="model-card-item">
611
+ <strong>Tác giả:</strong>
612
+ <span>Phạm Nguyễn Ngọc Bảo</span>
613
+ </div>
614
+ </div>
615
+ </div>
616
+ """)
617
+
618
+ gr.Markdown(initial_status)
619
+
620
+ # --- TABS ---
621
+ with gr.Tabs():
622
+ # TAB 1: Tổng hợp
623
+ with gr.Tab("🎙️ Tổng hợp"):
624
+ with gr.Row(elem_classes="container"):
625
+ with gr.Column(scale=3):
626
+ text_input = gr.Textbox(
627
+ label=f"Văn bản (Chia chunk: {MAX_CHARS_PER_CHUNK} ký tự)",
628
+ lines=6,
629
+ value="Hà Nội, trái tim của Việt Nam, là một thành phố ngàn năm văn hiến với bề dày lịch sử và văn hóa độc đáo. Bước chân trên những con phố cổ kính quanh Hồ Hoàn Kiếm, du khách như được du hành ngược thời gian.",
630
+ )
631
+
632
+ voice_select = gr.Dropdown(
633
+ choices=list(VOICE_SAMPLES.keys()),
634
+ value=list(VOICE_SAMPLES.keys())[0],
635
+ label="👤 Chọn giọng mẫu",
636
+ )
637
+
638
+ btn_generate = gr.Button("🎵 Bắt đầu tổng hợp", variant="primary", size="lg", interactive=model_loaded)
639
+
640
+ with gr.Column(scale=2):
641
+ audio_output = gr.Audio(
642
+ label="Kết quả",
643
+ type="filepath",
644
+ autoplay=True
645
+ )
646
+ status_output = gr.Textbox(label="Trạng thái", elem_classes="status-box", value="Chờ nhập văn bản...")
647
+
648
+ gr.Examples(
649
+ examples=EXAMPLES_LIST,
650
+ inputs=[text_input, voice_select],
651
+ outputs=[audio_output, status_output],
652
+ fn=synthesize_speech,
653
+ cache_examples=False,
654
+ label="Các ví dụ nhanh"
655
+ )
656
+
657
+ # TAB 2: Lịch sử
658
+ with gr.Tab("📜 Lịch sử"):
659
+ with gr.Row():
660
+ with gr.Column(scale=1):
661
+ btn_refresh = gr.Button("🔄 Làm mới", size="sm")
662
+ history_display = gr.Markdown(
663
+ value=get_history_list(),
664
+ elem_classes="history-list"
665
+ )
666
+
667
+ with gr.Column(scale=1):
668
+ gr.Markdown("### Chi tiết")
669
+ history_audio = gr.Audio(label="Audio", type="filepath")
670
+ history_text = gr.Textbox(label="Văn bản đầy đủ", lines=5)
671
+ history_voice = gr.Textbox(label="Giọng đã dùng")
672
+ history_info = gr.Textbox(label="Thông tin")
673
+ history_select = gr.Textbox(
674
+ label="Nhập số thứ tự để xem (vd: 1)",
675
+ placeholder="Nhập số..."
676
+ )
677
+ btn_load_history = gr.Button("📂 Tải item", variant="secondary")
678
+
679
+ btn_refresh.click(
680
+ fn=refresh_history,
681
+ outputs=history_display
682
+ )
683
+
684
+ btn_load_history.click(
685
+ fn=load_history_item,
686
+ inputs=history_select,
687
+ outputs=[history_audio, history_text, history_voice, history_info]
688
+ )
689
+
690
+ # Event handlers
691
+ btn_generate.click(
692
+ fn=synthesize_speech,
693
+ inputs=[text_input, voice_select],
694
+ outputs=[audio_output, status_output]
695
+ )
696
+
697
+ if __name__ == "__main__":
698
+ demo.queue().launch(
699
+ server_name="0.0.0.0",
700
+ server_port=7860,
701
+ )
app-12.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import soundfile as sf
3
+ import tempfile
4
+ import os
5
+ import time
6
+ import numpy as np
7
+ import librosa
8
+ import re
9
+ import json
10
+ import shutil
11
+ from pathlib import Path
12
+ from datetime import datetime
13
+ from llama_cpp import Llama
14
+ from neucodec import NeuCodecOnnxDecoder
15
+ import torch
16
+ from utils.phonemize_text import phonemize_with_dict
17
+ import threading
18
+ from queue import Queue
19
+
20
+ print("⏳ Đang khởi động VieNeu-TTS...")
21
+
22
+ # --- CONSTANTS ---
23
+ MAX_CHARS_PER_CHUNK = 256
24
+ SAMPLE_RATE = 24000
25
+ DEVICE_INFO = "Q4 GGUF (llama-cpp) + ONNX Codec"
26
+
27
+ # Thư mục lưu lịch sử - sử dụng thư mục tạm nếu không có quyền ghi
28
+ try:
29
+ HISTORY_DIR = "./tts_history"
30
+ os.makedirs(HISTORY_DIR, exist_ok=True)
31
+ # Test write permission
32
+ test_file = os.path.join(HISTORY_DIR, ".test")
33
+ with open(test_file, 'w') as f:
34
+ f.write("test")
35
+ os.remove(test_file)
36
+ except (PermissionError, OSError):
37
+ # Fallback to temp directory
38
+ HISTORY_DIR = os.path.join(tempfile.gettempdir(), "vieneu_tts_history")
39
+ os.makedirs(HISTORY_DIR, exist_ok=True)
40
+ print(f"⚠️ Không có quyền ghi, sử dụng thư mục tạm: {HISTORY_DIR}")
41
+
42
+ HISTORY_JSON = os.path.join(HISTORY_DIR, "history.json")
43
+
44
+ # Đường dẫn model
45
+ BACKBONE_REPO = "pnnbao-ump/VieNeu-TTS-q8-gguf"
46
+ CODEC_REPO = "neuphonic/neucodec-onnx-decoder"
47
+
48
+ # Giọng mẫu
49
+ VOICE_SAMPLES = {
50
+ "Tuyên (nam miền Bắc)": {
51
+ "audio": "./sample/Tuyên (nam miền Bắc).wav",
52
+ "text": "./sample/Tuyên (nam miền Bắc).txt",
53
+ "codes": "./sample/Tuyên (nam miền Bắc).pt"
54
+ },
55
+ "Vĩnh (nam miền Nam)": {
56
+ "audio": "./sample/Vĩnh (nam miền Nam).wav",
57
+ "text": "./sample/Vĩnh (nam miền Nam).txt",
58
+ "codes": "./sample/Vĩnh (nam miền Nam).pt"
59
+ },
60
+ "Bình (nam miền Bắc)": {
61
+ "audio": "./sample/Bình (nam miền Bắc).wav",
62
+ "text": "./sample/Bình (nam miền Bắc).txt",
63
+ "codes": "./sample/Bình (nam miền Bắc).pt"
64
+ },
65
+ "Nguyên (nam miền Nam)": {
66
+ "audio": "./sample/Nguyên (nam miền Nam).wav",
67
+ "text": "./sample/Nguyên (nam miền Nam).txt",
68
+ "codes": "./sample/Nguyên (nam miền Nam).pt"
69
+ },
70
+ "Sơn (nam miền Nam)": {
71
+ "audio": "./sample/Sơn (nam miền Nam).wav",
72
+ "text": "./sample/Sơn (nam miền Nam).txt",
73
+ "codes": "./sample/Sơn (nam miền Nam).pt"
74
+ },
75
+ "Đoan (nữ miền Nam)": {
76
+ "audio": "./sample/Đoan (nữ miền Nam).wav",
77
+ "text": "./sample/Đoan (nữ miền Nam).txt",
78
+ "codes": "./sample/Đoan (nữ miền Nam).pt"
79
+ },
80
+ "Ngọc (nữ miền Bắc)": {
81
+ "audio": "./sample/Ngọc (nữ miền Bắc).wav",
82
+ "text": "./sample/Ngọc (nữ miền Bắc).txt",
83
+ "codes": "./sample/Ngọc (nữ miền Bắc).pt"
84
+ },
85
+ "Ly (nữ miền Bắc)": {
86
+ "audio": "./sample/Ly (nữ miền Bắc).wav",
87
+ "text": "./sample/Ly (nữ miền Bắc).txt",
88
+ "codes": "./sample/Ly (nữ miền Bắc).pt"
89
+ },
90
+ "Dung (nữ miền Nam)": {
91
+ "audio": "./sample/Dung (nữ miền Nam).wav",
92
+ "text": "./sample/Dung (nữ miền Nam).txt",
93
+ "codes": "./sample/Dung (nữ miền Nam).pt"
94
+ }
95
+ }
96
+
97
+ # --- HISTORY MANAGEMENT ---
98
+ def load_history():
99
+ """Tải lịch sử từ file JSON"""
100
+ if os.path.exists(HISTORY_JSON):
101
+ try:
102
+ with open(HISTORY_JSON, 'r', encoding='utf-8') as f:
103
+ return json.load(f)
104
+ except:
105
+ return []
106
+ return []
107
+
108
+ def save_history(history):
109
+ """Lưu lịch sử vào file JSON"""
110
+ with open(HISTORY_JSON, 'w', encoding='utf-8') as f:
111
+ json.dump(history, f, ensure_ascii=False, indent=2)
112
+
113
+ def add_to_history(text, voice, audio_path, duration, status):
114
+ """Thêm một bản ghi vào lịch sử"""
115
+ try:
116
+ history = load_history()
117
+
118
+ # Tạo tên file duy nhất
119
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
120
+ filename = f"tts_{timestamp}.wav"
121
+ permanent_path = os.path.join(HISTORY_DIR, filename)
122
+
123
+ # Copy file audio vào thư mục lịch sử
124
+ if audio_path and os.path.exists(audio_path):
125
+ try:
126
+ shutil.copy2(audio_path, permanent_path)
127
+ except Exception as e:
128
+ print(f"⚠️ Không thể copy file audio: {e}")
129
+ permanent_path = audio_path # Dùng file tạm nếu không copy được
130
+
131
+ record = {
132
+ "id": timestamp,
133
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
134
+ "text": text[:100] + "..." if len(text) > 100 else text,
135
+ "full_text": text,
136
+ "voice": voice,
137
+ "audio_path": permanent_path,
138
+ "duration": duration,
139
+ "status": status
140
+ }
141
+
142
+ history.insert(0, record) # Thêm vào đầu danh sách
143
+
144
+ # Giới hạn lịch sử tối đa 100 bản ghi
145
+ if len(history) > 100:
146
+ # Xóa file audio cũ
147
+ old_record = history.pop()
148
+ try:
149
+ if os.path.exists(old_record['audio_path']):
150
+ os.remove(old_record['audio_path'])
151
+ except:
152
+ pass
153
+
154
+ save_history(history)
155
+ return permanent_path
156
+ except Exception as e:
157
+ print(f"⚠️ Lỗi khi lưu lịch sử: {e}")
158
+ return audio_path if audio_path else None
159
+
160
+ def get_history_list():
161
+ """Lấy danh sách lịch sử để hiển thị"""
162
+ history = load_history()
163
+ if not history:
164
+ return "Chưa có lịch sử tổng hợp nào."
165
+
166
+ output = []
167
+ for i, record in enumerate(history[:50], 1): # Hiển thị 50 bản ghi gần nhất
168
+ output.append(f"**{i}. [{record['timestamp']}]** - {record['voice']}")
169
+ output.append(f" 📝 {record['text']}")
170
+ output.append(f" ⏱️ Thời lượng: {record['duration']:.2f}s | {record['status']}")
171
+ output.append("")
172
+
173
+ return "\n".join(output)
174
+
175
+ def delete_history_item(item_id):
176
+ """Xóa một item khỏi lịch sử"""
177
+ history = load_history()
178
+ history = [h for h in history if h['id'] != item_id]
179
+ save_history(history)
180
+
181
+ # --- BACKGROUND PROCESSING QUEUE ---
182
+ processing_queue = Queue()
183
+ is_processing = False
184
+
185
+ def background_processor():
186
+ """Xử lý queue tổng hợp trong background"""
187
+ global is_processing
188
+ while True:
189
+ task = processing_queue.get()
190
+ if task is None:
191
+ break
192
+
193
+ is_processing = True
194
+ text, voice = task
195
+
196
+ try:
197
+ print(f"[Background] Bắt đầu tổng hợp: {text[:50]}...")
198
+ result = synthesize_speech_internal(text, voice)
199
+ print(f"[Background] Hoàn thành: {result}")
200
+ except Exception as e:
201
+ print(f"[Background] Lỗi: {e}")
202
+
203
+ is_processing = False
204
+ processing_queue.task_done()
205
+
206
+ # Khởi động background thread
207
+ bg_thread = threading.Thread(target=background_processor, daemon=True)
208
+ bg_thread.start()
209
+
210
+ def split_text_into_chunks(text, max_chars=256):
211
+ """Chia text thành chunks"""
212
+ sentences = re.split(r'([.!?,;])', text)
213
+ chunks = []
214
+ current = ""
215
+
216
+ for i in range(0, len(sentences), 2):
217
+ sentence = sentences[i]
218
+ punct = sentences[i+1] if i+1 < len(sentences) else ""
219
+ segment = sentence + punct
220
+
221
+ if len(current) + len(segment) <= max_chars:
222
+ current += segment
223
+ else:
224
+ if current:
225
+ chunks.append(current.strip())
226
+ current = segment
227
+
228
+ if current:
229
+ chunks.append(current.strip())
230
+
231
+ return chunks if chunks else [text]
232
+
233
+ def decode_audio(codes_str, codec):
234
+ """Decode speech tokens to audio"""
235
+ speech_ids = [int(num) for num in re.findall(r"<\|speech_(\d+)\|>", codes_str)]
236
+
237
+ if len(speech_ids) == 0:
238
+ print("Không tìm thấy mã giọng nói hợp lệ.")
239
+ return np.array([], dtype=np.float32)
240
+
241
+ codes = np.array(speech_ids, dtype=np.int32)[np.newaxis, np.newaxis, :]
242
+ recon = codec.decode_code(codes)
243
+ return recon[0, 0, :]
244
+
245
+ # --- MODEL LOADING ---
246
+ print("📦 Đang tải model Q4 GGUF và Codec ONNX...")
247
+ model_loaded = False
248
+ backbone = None
249
+ codec = None
250
+
251
+ try:
252
+ backbone = Llama.from_pretrained(
253
+ repo_id=BACKBONE_REPO,
254
+ filename="*.gguf",
255
+ verbose=False,
256
+ n_gpu_layers=-1,
257
+ n_ctx=2048,
258
+ mlock=True,
259
+ flash_attn=True,
260
+ )
261
+
262
+ codec = NeuCodecOnnxDecoder.from_pretrained(CODEC_REPO)
263
+
264
+ print("✅ Model đã tải thành công!")
265
+ model_loaded = True
266
+ except Exception as e:
267
+ import traceback
268
+ traceback.print_exc()
269
+ print(f"❌ Lỗi khi tải model: {e}")
270
+ model_loaded = False
271
+
272
+ # --- SYNTHESIS FUNCTION (Internal) ---
273
+ def synthesize_speech_internal(text, voice_choice):
274
+ """Internal synthesis function không phụ thuộc UI"""
275
+ global backbone, codec, model_loaded
276
+
277
+ if not model_loaded:
278
+ return None
279
+
280
+ if not text or text.strip() == "":
281
+ return None
282
+
283
+ if voice_choice not in VOICE_SAMPLES:
284
+ return None
285
+
286
+ raw_text = text.strip()
287
+
288
+ # Load reference text
289
+ ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
290
+ try:
291
+ with open(ref_text_path, "r", encoding="utf-8") as f:
292
+ ref_text_raw = f.read()
293
+ except Exception as e:
294
+ print(f"❌ Lỗi đọc file text mẫu: {e}")
295
+ return None
296
+
297
+ # Tải codes
298
+ ref_codes = None
299
+ codes_path = VOICE_SAMPLES[voice_choice]["codes"]
300
+
301
+ try:
302
+ ref_codes_tensor = torch.load(codes_path, map_location="cpu")
303
+ if isinstance(ref_codes_tensor, torch.Tensor):
304
+ ref_codes = ref_codes_tensor.cpu().numpy()
305
+ else:
306
+ ref_codes = np.array(ref_codes_tensor)
307
+ except Exception as e:
308
+ print(f"❌ Lỗi khi tải codes: {e}")
309
+ return None
310
+
311
+ if ref_codes is None or len(ref_codes) == 0:
312
+ return None
313
+
314
+ # Split text
315
+ text_chunks = split_text_into_chunks(raw_text, max_chars=MAX_CHARS_PER_CHUNK)
316
+
317
+ all_audio_segments = []
318
+ silence_pad = np.zeros(int(SAMPLE_RATE * 0.15), dtype=np.float32)
319
+
320
+ start_time = time.time()
321
+
322
+ try:
323
+ for i, chunk in enumerate(text_chunks):
324
+ # Phonemize
325
+ ref_text_phoneme = phonemize_with_dict(ref_text_raw)
326
+ input_text_phoneme = phonemize_with_dict(chunk)
327
+
328
+ # Create prompt
329
+ codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
330
+
331
+ prompt = (
332
+ f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text_phoneme} {input_text_phoneme}"
333
+ f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
334
+ )
335
+
336
+ # Generate
337
+ output = backbone(
338
+ prompt,
339
+ max_tokens=2048,
340
+ temperature=1.0,
341
+ top_k=50,
342
+ stop=["<|SPEECH_GENERATION_END|>"],
343
+ )
344
+ output_str = output["choices"][0]["text"]
345
+
346
+ # Decode - CHỈ DECODE PHẦN OUTPUT (không bao gồm reference codes)
347
+ chunk_wav = decode_audio(output_str, codec)
348
+
349
+ if chunk_wav is not None and len(chunk_wav) > 0:
350
+ all_audio_segments.append(chunk_wav)
351
+ if i < len(text_chunks) - 1:
352
+ all_audio_segments.append(silence_pad)
353
+
354
+ if not all_audio_segments:
355
+ return None
356
+
357
+ final_wav = np.concatenate(all_audio_segments)
358
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
359
+ sf.write(tmp.name, final_wav, SAMPLE_RATE)
360
+ output_path = tmp.name
361
+
362
+ process_time = time.time() - start_time
363
+
364
+ # Lưu vào lịch sử
365
+ permanent_path = add_to_history(raw_text, voice_choice, output_path, process_time, "Thành công")
366
+
367
+ return permanent_path
368
+
369
+ except Exception as e:
370
+ import traceback
371
+ traceback.print_exc()
372
+ return None
373
+
374
+ # --- SYNTHESIS FUNCTION (UI) ---
375
+ def synthesize_speech(text, voice_choice):
376
+ """Main synthesis function với UI feedback"""
377
+ global backbone, codec, model_loaded
378
+
379
+ if not model_loaded:
380
+ yield None, "⚠️ Model chưa tải. Vui lòng kiểm tra lỗi console!"
381
+ return
382
+
383
+ if not text or text.strip() == "":
384
+ yield None, "⚠️ Vui lòng nhập văn bản!"
385
+ return
386
+
387
+ if voice_choice not in VOICE_SAMPLES:
388
+ yield None, "⚠️ Vui lòng chọn giọng mẫu."
389
+ return
390
+
391
+ raw_text = text.strip()
392
+
393
+ # Load reference text
394
+ ref_text_path = VOICE_SAMPLES[voice_choice]["text"]
395
+ try:
396
+ with open(ref_text_path, "r", encoding="utf-8") as f:
397
+ ref_text_raw = f.read()
398
+ except Exception as e:
399
+ yield None, f"❌ Lỗi đọc file text mẫu: {e}"
400
+ return
401
+
402
+ yield None, "📄 Đang xử lý Reference..."
403
+
404
+ # Tải codes
405
+ ref_codes = None
406
+ codes_path = VOICE_SAMPLES[voice_choice]["codes"]
407
+
408
+ try:
409
+ ref_codes_tensor = torch.load(codes_path, map_location="cpu")
410
+ if isinstance(ref_codes_tensor, torch.Tensor):
411
+ ref_codes = ref_codes_tensor.cpu().numpy()
412
+ else:
413
+ ref_codes = np.array(ref_codes_tensor)
414
+ except Exception as e:
415
+ yield None, f"❌ Lỗi khi tải codes: {e}"
416
+ return
417
+
418
+ if ref_codes is None or len(ref_codes) == 0:
419
+ yield None, "❌ Codes tham chiếu không hợp lệ."
420
+ return
421
+
422
+ # Split text
423
+ text_chunks = split_text_into_chunks(raw_text, max_chars=MAX_CHARS_PER_CHUNK)
424
+ total_chunks = len(text_chunks)
425
+
426
+ yield None, f"🚀 Bắt đầu tổng hợp ({total_chunks} đoạn)..."
427
+
428
+ all_audio_segments = []
429
+ silence_pad = np.zeros(int(SAMPLE_RATE * 0.15), dtype=np.float32)
430
+
431
+ start_time = time.time()
432
+
433
+ try:
434
+ for i, chunk in enumerate(text_chunks):
435
+ yield None, f"⏳ Đang xử lý đoạn {i+1}/{total_chunks}..."
436
+
437
+ # Phonemize
438
+ ref_text_phoneme = phonemize_with_dict(ref_text_raw)
439
+ input_text_phoneme = phonemize_with_dict(chunk)
440
+
441
+ # Create prompt
442
+ codes_str = "".join([f"<|speech_{idx}|>" for idx in ref_codes])
443
+
444
+ prompt = (
445
+ f"user: Convert the text to speech:<|TEXT_PROMPT_START|>{ref_text_phoneme} {input_text_phoneme}"
446
+ f"<|TEXT_PROMPT_END|>\nassistant:<|SPEECH_GENERATION_START|>{codes_str}"
447
+ )
448
+
449
+ # Generate
450
+ output = backbone(
451
+ prompt,
452
+ max_tokens=2048,
453
+ temperature=1.0,
454
+ top_k=50,
455
+ stop=["<|SPEECH_GENERATION_END|>"],
456
+ )
457
+ output_str = output["choices"][0]["text"]
458
+
459
+ # Decode - CHỈ DECODE PHẦN OUTPUT (không bao gồm reference codes)
460
+ chunk_wav = decode_audio(output_str, codec)
461
+
462
+ if chunk_wav is not None and len(chunk_wav) > 0:
463
+ all_audio_segments.append(chunk_wav)
464
+ if i < total_chunks - 1:
465
+ all_audio_segments.append(silence_pad)
466
+
467
+ if not all_audio_segments:
468
+ yield None, "❌ Không sinh được audio nào."
469
+ return
470
+
471
+ yield None, "💾 Đang ghép file và lưu..."
472
+
473
+ final_wav = np.concatenate(all_audio_segments)
474
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
475
+ sf.write(tmp.name, final_wav, SAMPLE_RATE)
476
+ output_path = tmp.name
477
+
478
+ process_time = time.time() - start_time
479
+
480
+ # Lưu vào lịch sử
481
+ permanent_path = add_to_history(raw_text, voice_choice, output_path, process_time, "Thành công")
482
+
483
+ yield permanent_path, f"✅ Hoàn tất! (Tổng thời gian: {process_time:.2f}s)"
484
+
485
+ except Exception as e:
486
+ import traceback
487
+ traceback.print_exc()
488
+ add_to_history(raw_text, voice_choice, None, 0, f"Lỗi: {str(e)}")
489
+ yield None, f"❌ Lỗi tổng hợp: {str(e)}"
490
+
491
+ def refresh_history():
492
+ """Làm mới danh sách lịch sử"""
493
+ return get_history_list()
494
+
495
+ def load_history_item(history_index):
496
+ """Tải một item từ lịch sử"""
497
+ if not history_index:
498
+ return None, "", "", ""
499
+
500
+ try:
501
+ index = int(history_index.split(".")[0]) - 1
502
+ history = load_history()
503
+ if 0 <= index < len(history):
504
+ record = history[index]
505
+ return (
506
+ record['audio_path'] if os.path.exists(record['audio_path']) else None,
507
+ record['full_text'],
508
+ record['voice'],
509
+ f"📅 {record['timestamp']} | ⏱️ {record['duration']:.2f}s"
510
+ )
511
+ except:
512
+ pass
513
+
514
+ return None, "", "", ""
515
+
516
+ # --- UI SETUP ---
517
+ theme = gr.themes.Ocean(
518
+ primary_hue="indigo",
519
+ secondary_hue="cyan",
520
+ neutral_hue="slate",
521
+ font=[gr.themes.GoogleFont('Inter'), 'ui-sans-serif', 'system-ui'],
522
+ ).set(
523
+ button_primary_background_fill="linear-gradient(90deg, #6366f1 0%, #0ea5e9 100%)",
524
+ button_primary_background_fill_hover="linear-gradient(90deg, #4f46e5 0%, #0284c7 100%)",
525
+ )
526
+
527
+ css = """
528
+ .container { max-width: 1400px; margin: auto; }
529
+ .header-box {
530
+ text-align: center;
531
+ margin-bottom: 25px;
532
+ padding: 25px;
533
+ background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
534
+ border-radius: 12px;
535
+ color: white;
536
+ }
537
+ .header-title {
538
+ font-size: 2.5rem;
539
+ font-weight: 800;
540
+ }
541
+ .gradient-text {
542
+ background: -webkit-linear-gradient(45deg, #60A5FA, #22D3EE);
543
+ -webkit-background-clip: text;
544
+ -webkit-text-fill-color: transparent;
545
+ }
546
+ .status-box {
547
+ font-weight: bold;
548
+ text-align: center;
549
+ border: none;
550
+ background: transparent;
551
+ }
552
+ .model-card-content {
553
+ display: flex;
554
+ flex-wrap: wrap;
555
+ justify-content: center;
556
+ align-items: center;
557
+ gap: 15px;
558
+ font-size: 0.9rem;
559
+ color: #cbd5e1;
560
+ }
561
+ .model-card-item {
562
+ display: flex;
563
+ align-items: center;
564
+ justify-content: center;
565
+ gap: 6px;
566
+ color: #94a3b8;
567
+ }
568
+ .model-card-link {
569
+ color: #3b82f6;
570
+ text-decoration: none;
571
+ font-weight: 500;
572
+ transition: color 0.2s;
573
+ }
574
+ .model-card-link:hover {
575
+ color: #2563eb;
576
+ text-decoration: underline;
577
+ }
578
+ .history-list {
579
+ max-height: 600px;
580
+ overflow-y: auto;
581
+ padding: 15px;
582
+ background: #f8fafc;
583
+ border-radius: 8px;
584
+ }
585
+ """
586
+
587
+ EXAMPLES_LIST = [
588
+ ["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.", "Vĩnh (nam miền Nam)"],
589
+ ["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.", "Bình (nam miền Bắc)"],
590
+ ["Thành phố Hồ Chí Minh luôn chuyển mình không ngừng với nhịp sống hối hả, năng động.", "Dung (nữ miền Nam)"],
591
+ ]
592
+
593
+ initial_status = f"✅ Model đã tải thành công! (Chạy trên **{DEVICE_INFO}**). Hỗ trợ xử lý background và lưu lịch sử." if model_loaded else "❌ Lỗi khi tải model."
594
+
595
+ with gr.Blocks(title="VieNeu-TTS", theme=theme, css=css) as demo:
596
+ with gr.Column(elem_classes="container"):
597
+ gr.HTML(f"""
598
+ <div class="header-box">
599
+ <h1 class="header-title">
600
+ <span class="header-icon">🦜</span>
601
+ <span class="gradient-text">VieNeu-TTS Studio</span>
602
+ </h1>
603
+ <p>Chế độ: {DEVICE_INFO} | Background Processing ✅ | History ✅</p>
604
+ <p style="font-size: 0.85rem; color: #94a3b8;">📁 Lịch sử lưu tại: {HISTORY_DIR}</p>
605
+ <div class="model-card-content">
606
+ <div class="model-card-item">
607
+ <strong>Repository:</strong>
608
+ <a href="https://github.com/pnnbao97/VieNeu-TTS" target="_blank" class="model-card-link">GitHub</a>
609
+ </div>
610
+ <div class="model-card-item">
611
+ <strong>Tác giả:</strong>
612
+ <span>Phạm Nguyễn Ngọc Bảo</span>
613
+ </div>
614
+ </div>
615
+ </div>
616
+ """)
617
+
618
+ gr.Markdown(initial_status)
619
+
620
+ # --- TABS ---
621
+ with gr.Tabs():
622
+ # TAB 1: Tổng hợp
623
+ with gr.Tab("🎙️ Tổng hợp"):
624
+ with gr.Row(elem_classes="container"):
625
+ with gr.Column(scale=3):
626
+ text_input = gr.Textbox(
627
+ label=f"Văn bản (Chia chunk: {MAX_CHARS_PER_CHUNK} ký tự)",
628
+ lines=6,
629
+ value="Hà Nội, trái tim của Việt Nam, là một thành phố ngàn năm văn hiến với bề dày lịch sử và văn hóa độc đáo. Bước chân trên những con phố cổ kính quanh Hồ Hoàn Kiếm, du khách như được du hành ngược thời gian.",
630
+ )
631
+
632
+ voice_select = gr.Dropdown(
633
+ choices=list(VOICE_SAMPLES.keys()),
634
+ value=list(VOICE_SAMPLES.keys())[0],
635
+ label="👤 Chọn giọng mẫu",
636
+ )
637
+
638
+ btn_generate = gr.Button("🎵 Bắt đầu tổng hợp", variant="primary", size="lg", interactive=model_loaded)
639
+
640
+ with gr.Column(scale=2):
641
+ audio_output = gr.Audio(
642
+ label="Kết quả",
643
+ type="filepath",
644
+ autoplay=True
645
+ )
646
+ status_output = gr.Textbox(label="Trạng thái", elem_classes="status-box", value="Chờ nhập văn bản...")
647
+
648
+ gr.Examples(
649
+ examples=EXAMPLES_LIST,
650
+ inputs=[text_input, voice_select],
651
+ outputs=[audio_output, status_output],
652
+ fn=synthesize_speech,
653
+ cache_examples=False,
654
+ label="Các ví dụ nhanh"
655
+ )
656
+
657
+ # TAB 2: Lịch sử
658
+ with gr.Tab("📜 Lịch sử"):
659
+ with gr.Row():
660
+ with gr.Column(scale=1):
661
+ btn_refresh = gr.Button("🔄 Làm mới", size="sm")
662
+ history_display = gr.Markdown(
663
+ value=get_history_list(),
664
+ elem_classes="history-list"
665
+ )
666
+
667
+ with gr.Column(scale=1):
668
+ gr.Markdown("### Chi tiết")
669
+ history_audio = gr.Audio(label="Audio", type="filepath")
670
+ history_text = gr.Textbox(label="Văn bản đầy đủ", lines=5)
671
+ history_voice = gr.Textbox(label="Giọng đã dùng")
672
+ history_info = gr.Textbox(label="Thông tin")
673
+ history_select = gr.Textbox(
674
+ label="Nhập số thứ tự để xem (vd: 1)",
675
+ placeholder="Nhập số..."
676
+ )
677
+ btn_load_history = gr.Button("📂 Tải item", variant="secondary")
678
+
679
+ btn_refresh.click(
680
+ fn=refresh_history,
681
+ outputs=history_display
682
+ )
683
+
684
+ btn_load_history.click(
685
+ fn=load_history_item,
686
+ inputs=history_select,
687
+ outputs=[history_audio, history_text, history_voice, history_info]
688
+ )
689
+
690
+ # Event handlers
691
+ btn_generate.click(
692
+ fn=synthesize_speech,
693
+ inputs=[text_input, voice_select],
694
+ outputs=[audio_output, status_output]
695
+ )
696
+
697
+ if __name__ == "__main__":
698
+ demo.queue().launch(
699
+ server_name="0.0.0.0",
700
+ server_port=7860,
701
+ )