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