Update app.py
Browse files
app.py
CHANGED
|
@@ -1,433 +1,495 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
# -*- coding: utf-8 -*-
|
| 3 |
-
|
| 4 |
-
"""
|
| 5 |
-
Vietnamese TTS
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
import
|
| 12 |
-
import
|
| 13 |
-
import
|
| 14 |
-
import
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
import
|
| 18 |
-
import
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 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 |
-
|
| 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 |
-
self.
|
| 224 |
-
self.
|
| 225 |
-
self.
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
)
|
| 243 |
-
|
| 244 |
-
|
| 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 |
-
with gr.
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
CVNSS4.0 Vietnamese TTS Studio
|
| 6 |
+
- Architecture: Modular CSS & Component Separation
|
| 7 |
+
- UX: High Contrast Input Fields
|
| 8 |
+
- Core: Optimized Logic Flow
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import json
|
| 14 |
+
import time
|
| 15 |
+
import glob
|
| 16 |
+
import re
|
| 17 |
+
import hashlib
|
| 18 |
+
import tempfile
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import numpy as np
|
| 23 |
+
import soundfile as sf
|
| 24 |
+
import gradio as gr
|
| 25 |
+
|
| 26 |
+
# Add src to path for imports
|
| 27 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 28 |
+
|
| 29 |
+
# Import core modules
|
| 30 |
+
try:
|
| 31 |
+
from src.vietnamese.text_processor import process_vietnamese_text
|
| 32 |
+
from src.vietnamese.phonemizer import text_to_phonemes, VIPHONEME_AVAILABLE
|
| 33 |
+
from src.models.synthesizer import SynthesizerTrn
|
| 34 |
+
from src.text.symbols import symbols
|
| 35 |
+
except ImportError:
|
| 36 |
+
# Fallback for environment setup if src is missing during init
|
| 37 |
+
print("⚠️ Core modules not found. Ensure 'src' directory exists.")
|
| 38 |
+
VIPHONEME_AVAILABLE = False
|
| 39 |
+
symbols = []
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# =========================================================
|
| 43 |
+
# 1) SYSTEM CONFIGURATION & CSS (The Expert Layer)
|
| 44 |
+
# =========================================================
|
| 45 |
+
|
| 46 |
+
# Expert CSS: Definitive Z-Index Management & Neon Theme
|
| 47 |
+
NEON_CSS = r"""
|
| 48 |
+
:root {
|
| 49 |
+
--bg-dark: #0f172a;
|
| 50 |
+
--bg-panel: rgba(30, 41, 59, 0.7);
|
| 51 |
+
--line: rgba(148, 163, 184, 0.1);
|
| 52 |
+
--text-primary: #e2e8f0;
|
| 53 |
+
--neon-cyan: #06b6d4;
|
| 54 |
+
--neon-accent: #38bdf8;
|
| 55 |
+
--radius-lg: 16px;
|
| 56 |
+
--radius-sm: 8px;
|
| 57 |
+
|
| 58 |
+
/* UX Color Palette for Inputs */
|
| 59 |
+
--input-bg: #f1f5f9; /* Light Blue-Grey for readability */
|
| 60 |
+
--input-text: #0f4c81; /* Classic Blue (Dark Blue) for high contrast */
|
| 61 |
+
--input-placeholder: #64748b;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
body, .gradio-container, .app {
|
| 65 |
+
background: radial-gradient(circle at 50% 0%, #1e293b 0%, #0f172a 100%) !important;
|
| 66 |
+
color: var(--text-primary) !important;
|
| 67 |
+
font-family: 'Inter', 'Segoe UI', sans-serif;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
/* --- ISOLATION FULL: CVNSS4.0 Vietnamese TTS Studio --- */
|
| 71 |
+
.panelNeon {
|
| 72 |
+
border: 1px solid rgba(255,255,255,0.08);
|
| 73 |
+
border-radius: var(--radius-lg);
|
| 74 |
+
background: var(--bg-panel);
|
| 75 |
+
backdrop-filter: blur(12px);
|
| 76 |
+
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
|
| 77 |
+
padding: 20px;
|
| 78 |
+
position: relative;
|
| 79 |
+
isolation: isolate;
|
| 80 |
+
z-index: 1;
|
| 81 |
+
margin-bottom: 20px;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/* UX IMPROVEMENT: High Contrast Input Styling */
|
| 85 |
+
.panelNeon textarea, .panelNeon input[type="text"] {
|
| 86 |
+
background: var(--input-bg) !important;
|
| 87 |
+
color: var(--input-text) !important; /* DARK BLUE TEXT requested */
|
| 88 |
+
border: 2px solid transparent !important;
|
| 89 |
+
border-radius: var(--radius-sm) !important;
|
| 90 |
+
font-weight: 500 !important;
|
| 91 |
+
font-size: 1rem !important;
|
| 92 |
+
line-height: 1.5 !important;
|
| 93 |
+
padding: 12px !important;
|
| 94 |
+
transition: all 0.2s ease;
|
| 95 |
+
z-index: 10 !important;
|
| 96 |
+
position: relative !important;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
.panelNeon textarea::placeholder {
|
| 100 |
+
color: var(--input-placeholder) !important;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
.panelNeon textarea:focus, .panelNeon input:focus {
|
| 104 |
+
background: #ffffff !important;
|
| 105 |
+
border-color: var(--neon-cyan) !important;
|
| 106 |
+
box-shadow: 0 0 0 4px rgba(6, 182, 212, 0.15) !important;
|
| 107 |
+
color: #000000 !important; /* Even darker on focus */
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
/* Label Styling */
|
| 111 |
+
.panelNeon label span {
|
| 112 |
+
color: var(--neon-accent) !important;
|
| 113 |
+
font-weight: 600;
|
| 114 |
+
font-size: 0.85rem;
|
| 115 |
+
text-transform: uppercase;
|
| 116 |
+
letter-spacing: 0.05em;
|
| 117 |
+
margin-bottom: 8px;
|
| 118 |
+
display: block;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
/* Dropdown & Slider fixes */
|
| 122 |
+
.panelNeon .wrap, .panelNeon .range-compact {
|
| 123 |
+
z-index: 10 !important;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
/* Button Upgrades */
|
| 127 |
+
button.primary, .gr-button-primary {
|
| 128 |
+
background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%) !important;
|
| 129 |
+
border: none !important;
|
| 130 |
+
color: white !important;
|
| 131 |
+
font-weight: 700 !important;
|
| 132 |
+
transition: transform 0.1s ease, box-shadow 0.2s ease;
|
| 133 |
+
}
|
| 134 |
+
button.primary:hover, .gr-button-primary:hover {
|
| 135 |
+
box-shadow: 0 10px 15px -3px rgba(6, 182, 212, 0.3) !important;
|
| 136 |
+
transform: translateY(-1px);
|
| 137 |
+
}
|
| 138 |
+
button.primary:active {
|
| 139 |
+
transform: translateY(0px);
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
/* Status Panel */
|
| 143 |
+
.statusCard {
|
| 144 |
+
background: rgba(15, 23, 42, 0.6);
|
| 145 |
+
border-radius: var(--radius-sm);
|
| 146 |
+
padding: 16px;
|
| 147 |
+
border: 1px solid rgba(255,255,255,0.05);
|
| 148 |
+
}
|
| 149 |
+
.pill {
|
| 150 |
+
display: inline-flex;
|
| 151 |
+
align-items: center;
|
| 152 |
+
padding: 4px 12px;
|
| 153 |
+
border-radius: 99px;
|
| 154 |
+
background: rgba(56, 189, 248, 0.1);
|
| 155 |
+
color: #38bdf8;
|
| 156 |
+
border: 1px solid rgba(56, 189, 248, 0.2);
|
| 157 |
+
font-size: 0.8rem;
|
| 158 |
+
font-weight: 600;
|
| 159 |
+
margin-right: 6px;
|
| 160 |
+
margin-bottom: 6px;
|
| 161 |
+
}
|
| 162 |
+
.alert { padding: 12px; border-radius: 8px; margin-top: 12px; font-size: 0.9rem; font-weight: 500; display: flex; align-items: center; gap: 8px;}
|
| 163 |
+
.alertOk { background: rgba(34, 197, 94, 0.1); color: #4ade80; border: 1px solid rgba(34, 197, 94, 0.2); }
|
| 164 |
+
.alertWarn { background: rgba(234, 179, 8, 0.1); color: #facc15; border: 1px solid rgba(234, 179, 8, 0.2); }
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
# =========================================================
|
| 168 |
+
# 2) UTILITIES & HELPERS
|
| 169 |
+
# =========================================================
|
| 170 |
+
def check_viphoneme():
|
| 171 |
+
if not VIPHONEME_AVAILABLE:
|
| 172 |
+
print("⚠️ Viphoneme not available.")
|
| 173 |
+
return False
|
| 174 |
+
try:
|
| 175 |
+
phones, _, _ = text_to_phonemes("Test", use_viphoneme=True)
|
| 176 |
+
print("✅ Viphoneme active.")
|
| 177 |
+
return True
|
| 178 |
+
except Exception as e:
|
| 179 |
+
print(f"❌ Viphoneme error: {e}")
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
def md5_key(*parts: str) -> str:
|
| 183 |
+
return hashlib.md5("|".join(parts).encode("utf-8")).hexdigest()
|
| 184 |
+
|
| 185 |
+
def split_sentences_vi(text: str, max_chars: int):
|
| 186 |
+
# Improved splitting logic
|
| 187 |
+
if not text: return []
|
| 188 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 189 |
+
# Split by delimiters keeping delimiters
|
| 190 |
+
parts = re.split(r'([.?!;:])', text)
|
| 191 |
+
|
| 192 |
+
chunks = []
|
| 193 |
+
current_chunk = ""
|
| 194 |
+
|
| 195 |
+
for i in range(0, len(parts) - 1, 2):
|
| 196 |
+
sentence = parts[i] + parts[i+1]
|
| 197 |
+
if len(current_chunk) + len(sentence) <= max_chars:
|
| 198 |
+
current_chunk += sentence
|
| 199 |
+
else:
|
| 200 |
+
if current_chunk: chunks.append(current_chunk.strip())
|
| 201 |
+
current_chunk = sentence
|
| 202 |
+
|
| 203 |
+
if len(parts) % 2 != 0 and parts[-1]:
|
| 204 |
+
sentence = parts[-1]
|
| 205 |
+
if len(current_chunk) + len(sentence) <= max_chars:
|
| 206 |
+
current_chunk += sentence
|
| 207 |
+
else:
|
| 208 |
+
if current_chunk: chunks.append(current_chunk.strip())
|
| 209 |
+
current_chunk = sentence
|
| 210 |
+
|
| 211 |
+
if current_chunk: chunks.append(current_chunk.strip())
|
| 212 |
+
return chunks
|
| 213 |
+
|
| 214 |
+
# =========================================================
|
| 215 |
+
# 3) CORE ENGINE WRAPPER
|
| 216 |
+
# =========================================================
|
| 217 |
+
class TTSManager:
|
| 218 |
+
"""Singleton-like manager for TTS operations."""
|
| 219 |
+
def __init__(self):
|
| 220 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 221 |
+
print(f"🔧 Initializing TTS on {self.device}...")
|
| 222 |
+
|
| 223 |
+
self.model_dir = self._get_model_dir()
|
| 224 |
+
self.ckpt_path = find_latest_checkpoint(self.model_dir, "G")
|
| 225 |
+
self.cfg_path = os.path.join(self.model_dir, "config.json")
|
| 226 |
+
|
| 227 |
+
if not self.ckpt_path:
|
| 228 |
+
raise FileNotFoundError(f"No checkpoint found in {self.model_dir}")
|
| 229 |
+
|
| 230 |
+
self.tts = VietnameseTTS(self.ckpt_path, self.cfg_path, self.device)
|
| 231 |
+
self.temp_dir = Path(tempfile.gettempdir()) / "neon_tts_cache"
|
| 232 |
+
self.temp_dir.mkdir(parents=True, exist_ok=True)
|
| 233 |
+
|
| 234 |
+
def _get_model_dir(self):
|
| 235 |
+
return download_model()
|
| 236 |
+
|
| 237 |
+
def synthesize(self, text, speaker, speed, noise_scale, noise_scale_w, sdp_ratio):
|
| 238 |
+
try:
|
| 239 |
+
if not text or not text.strip():
|
| 240 |
+
return None, "⚠️ Empty input"
|
| 241 |
+
|
| 242 |
+
key = md5_key(speaker, f"{speed:.2f}", text[:20], str(len(text)))
|
| 243 |
+
out_path = self.temp_dir / f"{key}.wav"
|
| 244 |
+
|
| 245 |
+
if out_path.exists():
|
| 246 |
+
return str(out_path), "✅ Cached (From history)"
|
| 247 |
+
|
| 248 |
+
audio, sr = self.tts.synthesize(
|
| 249 |
+
text=text, speaker=speaker, length_scale=speed,
|
| 250 |
+
noise_scale=noise_scale, noise_scale_w=noise_scale_w, sdp_ratio=sdp_ratio
|
| 251 |
+
)
|
| 252 |
+
sf.write(str(out_path), audio, sr)
|
| 253 |
+
return str(out_path), "✅ Generated successfully"
|
| 254 |
+
except Exception as e:
|
| 255 |
+
# Capture full traceback if needed, but return clean msg
|
| 256 |
+
return None, f"❌ Error: {str(e)}"
|
| 257 |
+
|
| 258 |
+
# =========================================================
|
| 259 |
+
# 4) MODEL LOGIC (PRESERVED & FIXED)
|
| 260 |
+
# =========================================================
|
| 261 |
+
def find_latest_checkpoint(model_dir, prefix="G"):
|
| 262 |
+
pattern = os.path.join(model_dir, f"{prefix}*.pth")
|
| 263 |
+
checkpoints = glob.glob(pattern)
|
| 264 |
+
if not checkpoints: return None
|
| 265 |
+
checkpoints.sort(key=lambda x: int(re.search(rf"{prefix}(\d+)\.pth", x).group(1)) if re.search(rf"{prefix}(\d+)\.pth", x) else 0, reverse=True)
|
| 266 |
+
return checkpoints[0]
|
| 267 |
+
|
| 268 |
+
def download_model():
|
| 269 |
+
from huggingface_hub import snapshot_download
|
| 270 |
+
hf_repo = "valtecAI-team/valtec-tts-pretrained"
|
| 271 |
+
cache_base = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
|
| 272 |
+
if os.name == "nt": cache_base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
| 273 |
+
|
| 274 |
+
model_dir = cache_base / "valtec_tts" / "models" / "vits-vietnamese"
|
| 275 |
+
if (model_dir / "config.json").exists() and list(model_dir.glob("G_*.pth")):
|
| 276 |
+
return str(model_dir)
|
| 277 |
+
|
| 278 |
+
print(f"⬇️ Downloading {hf_repo}...")
|
| 279 |
+
snapshot_download(repo_id=hf_repo, local_dir=str(model_dir))
|
| 280 |
+
return str(model_dir)
|
| 281 |
+
|
| 282 |
+
class VietnameseTTS:
|
| 283 |
+
def __init__(self, ckpt, cfg, device="cpu"):
|
| 284 |
+
self.device = device
|
| 285 |
+
with open(cfg, "r", encoding="utf-8") as f: self.config = json.load(f)
|
| 286 |
+
self.spk2id = self.config["data"]["spk2id"]
|
| 287 |
+
self.speakers = list(self.spk2id.keys())
|
| 288 |
+
self._load(ckpt)
|
| 289 |
+
|
| 290 |
+
def _load(self, ckpt):
|
| 291 |
+
self.model = SynthesizerTrn(
|
| 292 |
+
len(symbols),
|
| 293 |
+
self.config["data"]["filter_length"] // 2 + 1,
|
| 294 |
+
self.config["train"]["segment_size"] // self.config["data"]["hop_length"],
|
| 295 |
+
n_speakers=self.config["data"]["n_speakers"],
|
| 296 |
+
**self.config["model"]
|
| 297 |
+
).to(self.device)
|
| 298 |
+
state = torch.load(ckpt, map_location=self.device)["model"]
|
| 299 |
+
self.model.load_state_dict({k.replace("module.", ""): v for k,v in state.items()}, strict=False)
|
| 300 |
+
self.model.eval()
|
| 301 |
+
|
| 302 |
+
def synthesize(self, text, speaker, **kwargs):
|
| 303 |
+
from src.text import cleaned_text_to_sequence
|
| 304 |
+
from src.nn import commons
|
| 305 |
+
|
| 306 |
+
# 1. Text Processing
|
| 307 |
+
norm_text = process_vietnamese_text(text)
|
| 308 |
+
phones, tones, _ = text_to_phonemes(norm_text, use_viphoneme=VIPHONEME_AVAILABLE)
|
| 309 |
+
phone_ids, tone_ids, lang_ids = cleaned_text_to_sequence(phones, tones, "VI")
|
| 310 |
+
|
| 311 |
+
phone_ids = commons.intersperse(phone_ids, 0)
|
| 312 |
+
tone_ids = commons.intersperse(tone_ids, 0)
|
| 313 |
+
lang_ids = commons.intersperse(lang_ids, 0)
|
| 314 |
+
|
| 315 |
+
# 2. Prepare Tensors
|
| 316 |
+
x = torch.LongTensor(phone_ids).unsqueeze(0).to(self.device)
|
| 317 |
+
x_len = torch.LongTensor([len(phone_ids)]).to(self.device)
|
| 318 |
+
tone = torch.LongTensor(tone_ids).unsqueeze(0).to(self.device)
|
| 319 |
+
lang = torch.LongTensor(lang_ids).unsqueeze(0).to(self.device)
|
| 320 |
+
sid = torch.LongTensor([self.spk2id.get(speaker, 0)]).to(self.device)
|
| 321 |
+
|
| 322 |
+
# 3. Inference with Gradient Safety (FIX IS HERE)
|
| 323 |
+
with torch.no_grad():
|
| 324 |
+
bert = torch.zeros(1024, len(phone_ids)).unsqueeze(0).to(self.device)
|
| 325 |
+
ja_bert = torch.zeros(768, len(phone_ids)).unsqueeze(0).to(self.device)
|
| 326 |
+
|
| 327 |
+
# Run inference
|
| 328 |
+
# The error "Can't call numpy() on Tensor that requires grad" means output has grad_fn.
|
| 329 |
+
# We use .detach() before .cpu() to ensure the graph is cut.
|
| 330 |
+
outputs = self.model.infer(
|
| 331 |
+
x, x_len, sid, tone, lang,
|
| 332 |
+
bert, ja_bert,
|
| 333 |
+
**kwargs
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
audio = outputs[0][0,0].detach().cpu().numpy()
|
| 337 |
+
|
| 338 |
+
return audio, self.config["data"]["sampling_rate"]
|
| 339 |
+
|
| 340 |
+
# =========================================================
|
| 341 |
+
# 5) UI CONSTRUCTION (REFACTORED)
|
| 342 |
+
# =========================================================
|
| 343 |
+
def create_ui(manager: TTSManager):
|
| 344 |
+
|
| 345 |
+
def ui_header():
|
| 346 |
+
return gr.HTML("""
|
| 347 |
+
<div style="border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 20px; margin-bottom: 25px;">
|
| 348 |
+
<h1 style="color: #38bdf8; margin:0; font-weight:800; font-size: 2rem; letter-spacing: -0.02em;">
|
| 349 |
+
🎛️ CVNSS4.0 Vietnamese TTS Studio
|
| 350 |
+
</h1>
|
| 351 |
+
<div style="color: #94a3b8; font-size: 1rem; margin-top: 5px; font-weight: 400;">
|
| 352 |
+
Công nghệ tích hợp giọng nói AI tiên tiến • Phiên bản 1.0.0 Demo • Dự án mã nguồn mở
|
| 353 |
+
</div>
|
| 354 |
+
</div>
|
| 355 |
+
""")
|
| 356 |
+
|
| 357 |
+
def ui_status_render(text, speaker, speed, chunks, dur, msg):
|
| 358 |
+
return f"""
|
| 359 |
+
<div class="statusCard">
|
| 360 |
+
<div style="margin-bottom:12px; font-weight:700; color:#38bdf8; font-size: 0.9rem; text-transform: uppercase;">
|
| 361 |
+
📟 Trạng thái hoạt động
|
| 362 |
+
</div>
|
| 363 |
+
<div style="display:flex; flex-wrap:wrap; gap:8px;">
|
| 364 |
+
<span class="pill">🎤 {speaker}</span>
|
| 365 |
+
<span class="pill">⚡ {speed}x</span>
|
| 366 |
+
<span class="pill">📄 {len(text)} ký tự</span>
|
| 367 |
+
<span class="pill">🧩 {chunks} đoạn</span>
|
| 368 |
+
</div>
|
| 369 |
+
<div class="alert {'alertOk' if '✅' in msg else 'alertWarn'}">
|
| 370 |
+
{msg}
|
| 371 |
+
</div>
|
| 372 |
+
</div>
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
with gr.Blocks(theme=gr.themes.Base(), css=NEON_CSS, title="Neon TTS Expert") as app:
|
| 376 |
+
ui_header()
|
| 377 |
+
|
| 378 |
+
with gr.Tabs():
|
| 379 |
+
# --- TAB BASIC ---
|
| 380 |
+
with gr.Tab("⚡ Chế độ Nhanh"):
|
| 381 |
+
with gr.Row():
|
| 382 |
+
# INPUT COLUMN
|
| 383 |
+
with gr.Column(scale=2):
|
| 384 |
+
# REFACTOR: Using a specific ID for the container to target with CSS isolation
|
| 385 |
+
with gr.Group(elem_classes=["panelNeon"], elem_id="input-panel-basic"):
|
| 386 |
+
gr.HTML('<div class="panelTitle">📝 Văn bản đầu vào</div>')
|
| 387 |
+
|
| 388 |
+
# THE FIX: Pure Textbox with updated styling (Dark Blue text)
|
| 389 |
+
txt_basic = gr.Textbox(
|
| 390 |
+
label="",
|
| 391 |
+
show_label=False,
|
| 392 |
+
placeholder="Nhập nội dung tiếng Việt vào... (Ví dụ: Xin chào, bạn đã học qua CVNSS4.0 chưa?)",
|
| 393 |
+
lines=6,
|
| 394 |
+
elem_id="main-input-basic"
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
with gr.Row():
|
| 398 |
+
spk_basic = gr.Dropdown(choices=manager.tts.speakers, value=manager.tts.speakers[0], label="Giọng đọc")
|
| 399 |
+
spd_basic = gr.Slider(0.5, 2.0, value=1.0, step=0.1, label="Tốc độ đọc")
|
| 400 |
+
|
| 401 |
+
btn_basic = gr.Button("🔊 Đọc ngay", variant="primary")
|
| 402 |
+
|
| 403 |
+
# OUTPUT COLUMN
|
| 404 |
+
with gr.Column(scale=1):
|
| 405 |
+
with gr.Group(elem_classes=["panelNeon"]):
|
| 406 |
+
gr.HTML('<div class="panelTitle">🔊 Kết quả</div>')
|
| 407 |
+
out_audio_basic = gr.Audio(label="Audio Output", type="filepath", interactive=False)
|
| 408 |
+
out_status_basic = gr.HTML()
|
| 409 |
+
|
| 410 |
+
# --- TAB ADVANCED ---
|
| 411 |
+
with gr.Tab("🧠 Chế độ Chuyên sâu"):
|
| 412 |
+
with gr.Row():
|
| 413 |
+
with gr.Column(scale=2):
|
| 414 |
+
with gr.Group(elem_classes=["panelNeon"], elem_id="input-panel-adv"):
|
| 415 |
+
gr.HTML('<div class="panelTitle">📝 Xử lý văn bản dài</div>')
|
| 416 |
+
txt_adv = gr.Textbox(
|
| 417 |
+
label="",
|
| 418 |
+
show_label=False,
|
| 419 |
+
lines=8,
|
| 420 |
+
placeholder="Nhập văn bản dài cần ngắt câu tự động...",
|
| 421 |
+
elem_id="main-input-adv"
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
gr.HTML('<div style="height:15px"></div>')
|
| 425 |
+
gr.HTML('<div class="panelTitle">🎚️ Tham số âm thanh</div>')
|
| 426 |
+
|
| 427 |
+
with gr.Row():
|
| 428 |
+
ns = gr.Slider(0.1, 1.5, 0.667, step=0.01, label="Noise Scale (Độ biến thiên)")
|
| 429 |
+
nsw = gr.Slider(0.1, 1.5, 0.8, step=0.01, label="Duration Noise (Độ động)")
|
| 430 |
+
|
| 431 |
+
with gr.Row():
|
| 432 |
+
sdp = gr.Slider(0.0, 1.0, 0.2, step=0.1, label="SDP Ratio (Ngẫu nhiên)")
|
| 433 |
+
max_chars = gr.Slider(50, 500, 300, step=10, label="Ngắt đoạn (ký tự)")
|
| 434 |
+
pause = gr.Slider(0, 1000, 250, step=50, label="Nghỉ câu (ms)")
|
| 435 |
+
|
| 436 |
+
btn_adv = gr.Button("🧠 Xử lý & Ghép nối", variant="primary")
|
| 437 |
+
|
| 438 |
+
with gr.Column(scale=1):
|
| 439 |
+
with gr.Group(elem_classes=["panelNeon"]):
|
| 440 |
+
out_audio_adv = gr.Audio(label="Merged Audio", type="filepath", interactive=False)
|
| 441 |
+
out_status_adv = gr.HTML()
|
| 442 |
+
|
| 443 |
+
# --- LOGIC BINDING ---
|
| 444 |
+
def run_basic(text, spk, spd):
|
| 445 |
+
path, msg = manager.synthesize(text, spk, spd, 0.667, 0.8, 0.2)
|
| 446 |
+
html = ui_status_render(text, spk, spd, 1, 0, msg)
|
| 447 |
+
return path, html
|
| 448 |
+
|
| 449 |
+
def run_adv(text, spk, spd, ns, nsw, sdp, mc, p, progress=gr.Progress()):
|
| 450 |
+
chunks = split_sentences_vi(text, int(mc))
|
| 451 |
+
audios = []
|
| 452 |
+
sr = 44100
|
| 453 |
+
|
| 454 |
+
for i, chunk in enumerate(chunks):
|
| 455 |
+
progress((i)/len(chunks), desc=f"Đang xử lý đoạn {i+1}/{len(chunks)}")
|
| 456 |
+
path, _ = manager.synthesize(chunk, spk, spd, ns, nsw, sdp)
|
| 457 |
+
if path:
|
| 458 |
+
data, rate = sf.read(path)
|
| 459 |
+
audios.append(data)
|
| 460 |
+
sr = rate
|
| 461 |
+
if p > 0:
|
| 462 |
+
audios.append(np.zeros(int(rate * p/1000)))
|
| 463 |
+
|
| 464 |
+
if not audios: return None, "❌ Không tạo được âm thanh"
|
| 465 |
+
|
| 466 |
+
full_audio = np.concatenate(audios)
|
| 467 |
+
out_path = manager.temp_dir / f"merged_{int(time.time())}.wav"
|
| 468 |
+
sf.write(str(out_path), full_audio, sr)
|
| 469 |
+
|
| 470 |
+
html = ui_status_render(text, spk, spd, len(chunks), len(full_audio)/sr, "✅ Đã ghép nối thành công")
|
| 471 |
+
return str(out_path), html
|
| 472 |
+
|
| 473 |
+
btn_basic.click(run_basic, [txt_basic, spk_basic, spd_basic], [out_audio_basic, out_status_basic])
|
| 474 |
+
btn_adv.click(run_adv, [txt_adv, spk_basic, spd_basic, ns, nsw, sdp, max_chars, pause], [out_audio_adv, out_status_adv])
|
| 475 |
+
|
| 476 |
+
return app
|
| 477 |
+
|
| 478 |
+
# =========================================================
|
| 479 |
+
# 6) ENTRY POINT
|
| 480 |
+
# =========================================================
|
| 481 |
+
if __name__ == "__main__":
|
| 482 |
+
print("🚀 Starting Expert Neon TTS...")
|
| 483 |
+
|
| 484 |
+
# Check dependencies
|
| 485 |
+
check_viphoneme()
|
| 486 |
+
|
| 487 |
+
# Init Manager & UI
|
| 488 |
+
try:
|
| 489 |
+
tts_manager = TTSManager()
|
| 490 |
+
app = create_ui(tts_manager)
|
| 491 |
+
|
| 492 |
+
port = int(os.environ.get("PORT", "7860"))
|
| 493 |
+
app.queue(max_size=10).launch(server_name="0.0.0.0", server_port=port)
|
| 494 |
+
except Exception as e:
|
| 495 |
+
print(f"❌ Fatal Error: {e}")
|