minhchiengod commited on
Commit
eb34cda
·
verified ·
1 Parent(s): 357c739

Upload folder using huggingface_hub

Browse files
source/qwen_app/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/__init__.py
2
+ """
3
+ Lazy __init__ — chỉ expose build_ui khi được gọi trực tiếp.
4
+ Import bất kỳ submodule nào (model_manager, omni_engine...) sẽ KHÔNG kéo gradio.
5
+ """
6
+ import os
7
+
8
+ # Vĩnh viễn ép hệ thống dùng thư mục _Qwen_Models_Cache cài sẵn nội bộ
9
+ _proj_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10
+ _cache_dir = os.path.join(_proj_root, "_Qwen_Models_Cache")
11
+ os.environ["HF_HOME"] = _cache_dir
12
+ os.makedirs(_cache_dir, exist_ok=True)
13
+ os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
14
+
15
+ def build_ui():
16
+ """Lazy import — chỉ load ui.py (và gradio) khi thực sự gọi build_ui()."""
17
+ from .ui import build_ui as _build_ui
18
+ return _build_ui()
source/qwen_app/audio_validator.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/audio_validator.py
2
+ """
3
+ Audio Integrity Validator — Bidirectional SRT ↔ Audio Cross-Reference
4
+
5
+ Vai trò TRUNG GIAN:
6
+ 1. Parse SRT → list các entry (idx, start, end, text)
7
+ 2. Phân tích energy audio theo từng window
8
+ 3. Đối chiếu 2 chiều:
9
+ SRT → Audio : mỗi dòng SRT có audio energy không? (MISSING_AUDIO)
10
+ Audio → SRT : mỗi vùng audio có SRT entry không? (UNMATCHED_AUDIO)
11
+ 4. Báo cáo chi tiết + severity rating
12
+ 5. Fallback suggestions: tự động đề xuất re-generate chunk nào bị lỗi
13
+
14
+ Sử dụng: soundfile (đã có) + numpy, không cần librosa.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import re
21
+ import sys
22
+ import subprocess
23
+ import tempfile
24
+ import uuid
25
+ from dataclasses import dataclass, field
26
+ from datetime import datetime
27
+ from typing import List, Tuple, Optional
28
+
29
+ import numpy as np
30
+
31
+ # ─── Constants ────────────────────────────────────────────────────────────────
32
+ ENERGY_WINDOW_MS = 50 # ms per energy window
33
+ SILENCE_THRESHOLD_RMS = 0.003 # below this = silent
34
+ MIN_SPEECH_COVERAGE = 0.25 # ≥25% windows must be non-silent
35
+ EDGE_TOLERANCE_MS = 150 # ms to trim from start/end of each SRT window (codec delay)
36
+ MAX_CHUNK_RETRIES = 2 # max retries per chunk before giving up
37
+ ORPHAN_MIN_DURATION_S = 0.50 # min orphan region to flag (was 0.30 → caused false positives)
38
+ ORPHAN_CONSEC_WINDOWS = 3 # consecutive non-silent windows required to start an orphan region
39
+
40
+
41
+ def check_array_energy(arr: "np.ndarray", sr: int = 24000, threshold: float = SILENCE_THRESHOLD_RMS) -> float:
42
+ """
43
+ Fast inline check: returns RMS of the array (no file I/O).
44
+ Returns 0.0 for empty/None. Use to decide if a chunk needs retry.
45
+ Compare result against SILENCE_THRESHOLD_RMS.
46
+ """
47
+ if arr is None or len(arr) == 0:
48
+ return 0.0
49
+ return float(np.sqrt(np.mean(arr.astype(np.float32) ** 2)))
50
+
51
+
52
+
53
+ # ─── Data classes ─────────────────────────────────────────────────────────────
54
+ @dataclass
55
+ class SRTEntry:
56
+ idx: int
57
+ start: float # seconds
58
+ end: float # seconds
59
+ text: str
60
+
61
+
62
+ @dataclass
63
+ class ChunkIssue:
64
+ chunk_idx: int
65
+ chunk_text: str
66
+ issue_type: str # "MISSING_AUDIO" | "LOW_ENERGY" | "UNMATCHED_AUDIO" | "SRT_OVERFLOW"
67
+ severity: str # "CRITICAL" | "WARNING" | "INFO"
68
+ detail: str
69
+ suggested_action: str
70
+
71
+
72
+ @dataclass
73
+ class ValidationReport:
74
+ audio_path: str
75
+ srt_path: str
76
+ audio_duration: float
77
+ srt_total_entries: int
78
+ issues: List[ChunkIssue] = field(default_factory=list)
79
+ passed_entries: int = 0
80
+ missing_audio: int = 0
81
+ low_energy: int = 0
82
+ unmatched_audio: int = 0
83
+ srt_overflow: int = 0
84
+ overall_status: str = "UNKNOWN" # "PASS" | "WARN" | "FAIL"
85
+
86
+ @property
87
+ def total_issues(self) -> int:
88
+ return len(self.issues)
89
+
90
+ @property
91
+ def critical_count(self) -> int:
92
+ return sum(1 for i in self.issues if i.severity == "CRITICAL")
93
+
94
+
95
+ # ─── SRT Parser ───────────────────────────────────────────────────────────────
96
+ def parse_srt(srt_path: str) -> List[SRTEntry]:
97
+ """Parse SRT file → list of SRTEntry with float timestamps."""
98
+ entries: List[SRTEntry] = []
99
+ if not os.path.exists(srt_path):
100
+ return entries
101
+
102
+ with open(srt_path, "r", encoding="utf-8") as f:
103
+ content = f.read()
104
+
105
+ blocks = re.split(r"\n\s*\n", content.strip())
106
+ for block in blocks:
107
+ lines = [l.strip() for l in block.strip().splitlines() if l.strip()]
108
+ if len(lines) < 3:
109
+ continue
110
+ try:
111
+ idx = int(lines[0])
112
+ except ValueError:
113
+ continue
114
+ m = re.match(
115
+ r"(\d{2}):(\d{2}):(\d{2})[,.](\d{3})\s*-->\s*(\d{2}):(\d{2}):(\d{2})[,.](\d{3})",
116
+ lines[1]
117
+ )
118
+ if not m:
119
+ continue
120
+ h1, m1, s1, ms1, h2, m2, s2, ms2 = [int(x) for x in m.groups()]
121
+ start = h1 * 3600 + m1 * 60 + s1 + ms1 / 1000.0
122
+ end = h2 * 3600 + m2 * 60 + s2 + ms2 / 1000.0
123
+ text = " ".join(lines[2:])
124
+ entries.append(SRTEntry(idx=idx, start=start, end=end, text=text))
125
+
126
+ return entries
127
+
128
+
129
+ # ─── Audio Energy Analyzer ────────────────────────────────────────────────────
130
+ def _load_audio_as_mono(audio_path: str) -> Tuple[np.ndarray, int]:
131
+ """
132
+ Load audio file into mono float32 array.
133
+ Supports WAV natively via soundfile. For MP3, decode via FFmpeg → temp WAV.
134
+ """
135
+ import soundfile as sf
136
+
137
+ ext = os.path.splitext(audio_path)[-1].lower()
138
+ if ext in (".wav", ".flac", ".ogg"):
139
+ data, sr = sf.read(audio_path, dtype="float32", always_2d=False)
140
+ else:
141
+ # MP3 / AAC / M4A — decode through FFmpeg
142
+ tmp = os.path.join(tempfile.gettempdir(), f"val_{uuid.uuid4().hex}.wav")
143
+ try:
144
+ ff_flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
145
+ cmd = [
146
+ "ffmpeg", "-y", "-i", audio_path,
147
+ "-ac", "1", "-ar", "24000",
148
+ "-c:a", "pcm_f32le",
149
+ "-loglevel", "error", tmp
150
+ ]
151
+ if ff_flags:
152
+ subprocess.run(cmd, check=True, creationflags=ff_flags)
153
+ else:
154
+ subprocess.run(cmd, check=True)
155
+ data, sr = sf.read(tmp, dtype="float32", always_2d=False)
156
+ finally:
157
+ if os.path.exists(tmp):
158
+ try:
159
+ os.remove(tmp)
160
+ except Exception:
161
+ pass
162
+
163
+ # Stereo → mono
164
+ if data.ndim == 2:
165
+ data = data.mean(axis=1)
166
+ return data, int(sr)
167
+
168
+
169
+ def compute_rms_windows(
170
+ data: np.ndarray, sr: int, window_ms: int = ENERGY_WINDOW_MS
171
+ ) -> Tuple[np.ndarray, np.ndarray]:
172
+ """
173
+ Compute RMS energy per window.
174
+ Returns:
175
+ times : center time of each window (seconds)
176
+ rms_arr : RMS value of each window
177
+ """
178
+ hop = max(1, int(sr * window_ms / 1000))
179
+ n_windows = max(1, len(data) // hop)
180
+ times = np.arange(n_windows) * (hop / sr) + (hop / sr) / 2
181
+ rms = np.array([
182
+ np.sqrt(np.mean(data[i * hop: i * hop + hop] ** 2))
183
+ for i in range(n_windows)
184
+ ], dtype=np.float32)
185
+ return times, rms
186
+
187
+
188
+ def _coverage_in_range(
189
+ times: np.ndarray,
190
+ rms: np.ndarray,
191
+ start: float,
192
+ end: float,
193
+ threshold: float = SILENCE_THRESHOLD_RMS,
194
+ edge_tol: float = EDGE_TOLERANCE_MS / 1000.0,
195
+ ) -> float:
196
+ """
197
+ Return fraction of non-silent windows within [start+edge, end-edge].
198
+ """
199
+ s = start + edge_tol
200
+ e = end - edge_tol
201
+ if e <= s:
202
+ s, e = start, end # fallback when window is very narrow
203
+ mask = (times >= s) & (times <= e)
204
+ if not mask.any():
205
+ return 0.0
206
+ return float(np.mean(rms[mask] > threshold))
207
+
208
+
209
+ # ─── Core Validation Logic ────────────────────────────────────────────────────
210
+ def validate_audio_vs_srt(
211
+ audio_path: str,
212
+ srt_path: str,
213
+ energy_threshold: float = SILENCE_THRESHOLD_RMS,
214
+ min_coverage: float = MIN_SPEECH_COVERAGE,
215
+ warn_multitrack_srt: bool = True,
216
+ ) -> ValidationReport:
217
+ """
218
+ Bidirectional audio-SRT validation.
219
+ FIX #6+#7: Improved orphan detection (500ms min, 3-consecutive-window rule).
220
+ FIX: warn when SRT appears to be a multi-phase FULL_MASTER used on single-phase audio.
221
+
222
+ Pass 1 (SRT -> Audio): each SRT entry must have >= min_coverage non-silent windows.
223
+ Pass 2 (Audio -> SRT): significant audio regions must map to at least one SRT entry.
224
+
225
+ Returns ValidationReport with full issue list.
226
+ """
227
+ report = ValidationReport(
228
+ audio_path=audio_path,
229
+ srt_path=srt_path,
230
+ audio_duration=0.0,
231
+ srt_total_entries=0,
232
+ )
233
+
234
+ # ── Load audio
235
+ try:
236
+ data, sr = _load_audio_as_mono(audio_path)
237
+ except Exception as e:
238
+ report.issues.append(ChunkIssue(
239
+ chunk_idx=0, chunk_text="",
240
+ issue_type="MISSING_AUDIO", severity="CRITICAL",
241
+ detail=f"Cannot load audio file: {e}",
242
+ suggested_action="Check FFmpeg is installed and audio file is not corrupted.",
243
+ ))
244
+ report.overall_status = "FAIL"
245
+ return report
246
+
247
+ report.audio_duration = len(data) / sr
248
+
249
+ # ── Parse SRT
250
+ entries = parse_srt(srt_path)
251
+ report.srt_total_entries = len(entries)
252
+ if not entries:
253
+ report.issues.append(ChunkIssue(
254
+ chunk_idx=0, chunk_text="",
255
+ issue_type="SRT_OVERFLOW", severity="CRITICAL",
256
+ detail="SRT file is empty or could not be parsed.",
257
+ suggested_action="Re-generate audio and SRT for this file.",
258
+ ))
259
+ report.overall_status = "FAIL"
260
+ return report
261
+
262
+ # Check SRT doesn't extend beyond audio
263
+ last_srt_end = max(e.end for e in entries)
264
+ overflow_delta = last_srt_end - report.audio_duration
265
+
266
+ # FIX: Detect when FULL_MASTER.srt (multi-phase) is passed for a single-phase audio
267
+ if warn_multitrack_srt and overflow_delta > 5.0:
268
+ report.issues.append(ChunkIssue(
269
+ chunk_idx=-1, chunk_text="",
270
+ issue_type="SRT_OVERFLOW", severity="WARNING",
271
+ detail=(
272
+ f"SRT ends at {last_srt_end:.2f}s but audio is only {report.audio_duration:.2f}s "
273
+ f"(Δ={overflow_delta:.1f}s). This SRT may be a multi-phase FULL_MASTER.srt "
274
+ f"— use per-phase SRTs for accurate validation."
275
+ ),
276
+ suggested_action="Pass per-phase SRT (not FULL_MASTER.srt) to validate_audio_vs_srt().",
277
+ ))
278
+ report.srt_overflow += 1
279
+ # Do NOT run per-entry validation — it will all be false positives
280
+ report.overall_status = "WARN"
281
+ return report
282
+ elif overflow_delta > 0.5:
283
+ report.issues.append(ChunkIssue(
284
+ chunk_idx=len(entries), chunk_text=entries[-1].text,
285
+ issue_type="SRT_OVERFLOW", severity="CRITICAL",
286
+ detail=(
287
+ f"SRT ends at {last_srt_end:.2f}s but audio is only {report.audio_duration:.2f}s. "
288
+ f"Δ={overflow_delta:.2f}s overflow."
289
+ ),
290
+ suggested_action=(
291
+ "Speed factor may be too high — SRT timestamps computed with wrong speed. "
292
+ "Re-generate with corrected timing."
293
+ ),
294
+ ))
295
+ report.srt_overflow += 1
296
+
297
+ # ── Compute energy windows
298
+ times, rms = compute_rms_windows(data, sr)
299
+
300
+ # ── Pass 1: SRT → Audio
301
+ for entry in entries:
302
+ coverage = _coverage_in_range(times, rms, entry.start, entry.end, energy_threshold)
303
+
304
+ # FIX: Timing drift for short sentences (they merge with adjacent or fall into pauses)
305
+ if coverage < min_coverage and (entry.end - entry.start) < 2.5:
306
+ drift_tol = 1.0 # Expand search window by +/- 1.0 second
307
+ s_exp = max(0.0, entry.start - drift_tol)
308
+ e_exp = min(report.audio_duration, entry.end + drift_tol)
309
+ mask_exp = (times >= s_exp) & (times <= e_exp)
310
+ if mask_exp.any():
311
+ # If there are at least 3 active windows (150ms) nearby, assume it merged or drifted.
312
+ if np.sum(rms[mask_exp] > energy_threshold) >= 3:
313
+ coverage = min_coverage
314
+
315
+ if coverage < min_coverage:
316
+ if coverage < 0.05:
317
+ sev = "CRITICAL"
318
+ itype = "MISSING_AUDIO"
319
+ action = (
320
+ f"Chunk {entry.idx} ('{entry.text[:60]}…') produced near-zero audio. "
321
+ "Likely a model inference failure — re-generate this chunk."
322
+ )
323
+ else:
324
+ sev = "WARNING"
325
+ itype = "LOW_ENERGY"
326
+ action = (
327
+ f"Chunk {entry.idx} has partial audio. "
328
+ "Check if FFmpeg atempo clipped this segment. "
329
+ "Try lowering speed or increasing max_new_tokens."
330
+ )
331
+ report.issues.append(ChunkIssue(
332
+ chunk_idx=entry.idx,
333
+ chunk_text=entry.text,
334
+ issue_type=itype,
335
+ severity=sev,
336
+ detail=(
337
+ f"SRT [{entry.start:.2f}s → {entry.end:.2f}s] "
338
+ f"energy coverage={coverage:.0%} (threshold={min_coverage:.0%})"
339
+ ),
340
+ suggested_action=action,
341
+ ))
342
+ if itype == "MISSING_AUDIO":
343
+ report.missing_audio += 1
344
+ else:
345
+ report.low_energy += 1
346
+ else:
347
+ report.passed_entries += 1
348
+
349
+ # ── Pass 2: Audio → SRT (detect orphaned audio)
350
+ # Build a mask of SRT-covered samples
351
+ n_samples = len(data)
352
+ covered = np.zeros(n_samples, dtype=bool)
353
+ for entry in entries:
354
+ i_start = max(0, int(entry.start * sr))
355
+ i_end = min(n_samples, int(entry.end * sr))
356
+ covered[i_start:i_end] = True
357
+
358
+ # Find continuous uncovered regions with significant energy
359
+ # FIX #6: require ORPHAN_CONSEC_WINDOWS consecutive active windows + ORPHAN_MIN_DURATION_S
360
+ not_covered = ~covered
361
+ hop = max(1, int(sr * ENERGY_WINDOW_MS / 1000))
362
+ orphan_regions = []
363
+ in_orphan = False
364
+ orphan_start = 0.0
365
+ consec_count = 0
366
+ n_check = n_samples // hop
367
+
368
+ for i in range(n_check):
369
+ seg_start = i * hop
370
+ seg_end = min(n_samples, seg_start + hop)
371
+ seg_rms = float(np.sqrt(np.mean(data[seg_start:seg_end] ** 2)))
372
+ seg_uncov = not_covered[seg_start:seg_end].all()
373
+ t_start = seg_start / sr
374
+
375
+ if seg_uncov and seg_rms > energy_threshold:
376
+ consec_count += 1
377
+ if not in_orphan and consec_count >= ORPHAN_CONSEC_WINDOWS:
378
+ in_orphan = True
379
+ orphan_start = t_start - (ORPHAN_CONSEC_WINDOWS - 1) * (hop / sr)
380
+ else:
381
+ if in_orphan:
382
+ orphan_end = t_start
383
+ if orphan_end - orphan_start >= ORPHAN_MIN_DURATION_S:
384
+ orphan_regions.append((orphan_start, orphan_end))
385
+ in_orphan = False
386
+ consec_count = 0
387
+
388
+ for (os_, oe_) in orphan_regions:
389
+ report.issues.append(ChunkIssue(
390
+ chunk_idx=-1,
391
+ chunk_text="",
392
+ issue_type="UNMATCHED_AUDIO",
393
+ severity="WARNING",
394
+ detail=(
395
+ f"Audio has speech at [{os_:.2f}s → {oe_:.2f}s] "
396
+ f"({oe_-os_:.2f}s) with no SRT entry covering it."
397
+ ),
398
+ suggested_action=(
399
+ "SRT timing might be shifted. Check global_cursor accumulation logic "
400
+ "and verify speed-scaling is applied consistently."
401
+ ),
402
+ ))
403
+ report.unmatched_audio += 1
404
+
405
+ # ── Overall status
406
+ if report.critical_count > 0 or report.srt_overflow > 0:
407
+ report.overall_status = "FAIL"
408
+ elif report.total_issues > 0:
409
+ report.overall_status = "WARN"
410
+ else:
411
+ report.overall_status = "PASS"
412
+
413
+ return report
414
+
415
+
416
+ # ─── Batch Folder Validation ──────────────────────────────────────────────────
417
+ def validate_batch_output(
418
+ out_dir: str,
419
+ master_srt: Optional[str] = None,
420
+ ) -> List[ValidationReport]:
421
+ """
422
+ Scan out_dir for all (*.mp3, matching *.srt OR FULL_MASTER.srt) pairs.
423
+ Returns list of ValidationReport, one per audio file found.
424
+ """
425
+ reports: List[ValidationReport] = []
426
+ if not os.path.isdir(out_dir):
427
+ return reports
428
+
429
+ # Try FULL_MASTER.srt for mode3_news structure
430
+ full_master = master_srt or os.path.join(out_dir, "FULL_MASTER.srt")
431
+ has_master = os.path.exists(full_master)
432
+
433
+ mp3_files = sorted(f for f in os.listdir(out_dir) if f.lower().endswith(".mp3"))
434
+
435
+ for mp3 in mp3_files:
436
+ mp3_path = os.path.join(out_dir, mp3)
437
+ # Prefer per-file SRT, fall back to FULL_MASTER.srt
438
+ srt_candidate = os.path.join(out_dir, os.path.splitext(mp3)[0] + ".srt")
439
+ if os.path.exists(srt_candidate):
440
+ srt_path = srt_candidate
441
+ elif has_master:
442
+ srt_path = full_master
443
+ else:
444
+ reports.append(ValidationReport(
445
+ audio_path=mp3_path, srt_path="(MISSING)",
446
+ audio_duration=0.0, srt_total_entries=0,
447
+ issues=[ChunkIssue(
448
+ chunk_idx=0, chunk_text="",
449
+ issue_type="MISSING_AUDIO", severity="CRITICAL",
450
+ detail=f"No SRT file found for {mp3}",
451
+ suggested_action="Re-run batch generation to recreate SRT.",
452
+ )],
453
+ overall_status="FAIL",
454
+ ))
455
+ continue
456
+ reports.append(validate_audio_vs_srt(mp3_path, srt_path))
457
+
458
+ return reports
459
+
460
+
461
+ # ─── Report Formatter ─────────────────────────────────────────────────────────
462
+ def format_validation_report(report: ValidationReport) -> str:
463
+ """Render a ValidationReport as human-readable log text."""
464
+ lines = []
465
+ ts = datetime.now().strftime("%H:%M:%S")
466
+ status_icon = {"PASS": "✅", "WARN": "⚠️", "FAIL": "❌", "UNKNOWN": "❓"}.get(report.overall_status, "❓")
467
+
468
+ lines.append(f"[{ts}] {status_icon} STATUS: {report.overall_status}")
469
+ lines.append(f" Audio : {os.path.basename(report.audio_path)} ({report.audio_duration:.2f}s)")
470
+ lines.append(f" SRT : {os.path.basename(report.srt_path)} ({report.srt_total_entries} entries)")
471
+ lines.append(f" Passed : {report.passed_entries}/{report.srt_total_entries}")
472
+
473
+ if report.missing_audio:
474
+ lines.append(f" ❌ MISSING AUDIO : {report.missing_audio} chunk(s) — SILENT where speech expected")
475
+ if report.low_energy:
476
+ lines.append(f" ⚠️ LOW ENERGY : {report.low_energy} chunk(s) — partial audio detected")
477
+ if report.unmatched_audio:
478
+ lines.append(f" ⚠️ UNMATCHED AUDIO: {report.unmatched_audio} region(s) — speech with no SRT entry")
479
+ if report.srt_overflow:
480
+ lines.append(f" ❌ SRT OVERFLOW : SRT timestamps exceed audio duration")
481
+
482
+ if report.issues:
483
+ lines.append("\n ── Issue Detail ─────────────────────────────")
484
+ for iss in report.issues:
485
+ icon = "❌" if iss.severity == "CRITICAL" else "⚠️"
486
+ lines.append(f" {icon} [{iss.issue_type}] chunk#{iss.chunk_idx}")
487
+ if iss.chunk_text:
488
+ preview = iss.chunk_text[:80] + ("…" if len(iss.chunk_text) > 80 else "")
489
+ lines.append(f" Text : {preview}")
490
+ lines.append(f" Detail : {iss.detail}")
491
+ lines.append(f" Fix : {iss.suggested_action}")
492
+ else:
493
+ lines.append(" 🎉 All SRT entries verified — audio is complete and intact.")
494
+
495
+ return "\n".join(lines)
496
+
497
+
498
+ # ─── Batch Report Formatter ───────────────────────────────────────────────────
499
+ def format_batch_reports(reports: List[ValidationReport]) -> str:
500
+ """Render a list of ValidationReports as a summary log."""
501
+ if not reports:
502
+ return "⚠️ No audio files found to validate."
503
+
504
+ total = len(reports)
505
+ passed = sum(1 for r in reports if r.overall_status == "PASS")
506
+ warned = sum(1 for r in reports if r.overall_status == "WARN")
507
+ failed = sum(1 for r in reports if r.overall_status == "FAIL")
508
+
509
+ ts = datetime.now().strftime("%H:%M:%S")
510
+ lines = [
511
+ f"[{ts}] 🔍 VALIDATION COMPLETE",
512
+ f" Total : {total} file(s)",
513
+ f" ✅ PASS : {passed}",
514
+ f" ⚠️ WARN : {warned}",
515
+ f" ❌ FAIL : {failed}",
516
+ "",
517
+ ]
518
+ for r in reports:
519
+ lines.append(format_validation_report(r))
520
+ lines.append("")
521
+
522
+ return "\n".join(lines)
source/qwen_app/config.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import gradio as gr
4
+ THEME = gr.themes.Soft(font=[gr.themes.GoogleFont("Source Sans Pro"), "Arial", "sans-serif"])
5
+
6
+ LANGUAGES = [
7
+ "Auto",
8
+ "Chinese",
9
+ "English",
10
+ "Japanese",
11
+ "Korean",
12
+ "French",
13
+ "German",
14
+ "Spanish",
15
+ "Portuguese",
16
+ "Russian",
17
+ ]
18
+ SPEAKERS = ["Aiden", "Dylan", "Eric", "Ono_anna", "Ryan", "Serena", "Sohee", "Uncle_fu", "Vivian"]
19
+
20
+ VOICE_LIB_DIR = Path("voice_library")
21
+ VOICE_DB_PATH = VOICE_LIB_DIR / "voices.json"
22
+ VOICE_AUDIO_DIR = VOICE_LIB_DIR / "audio"
source/qwen_app/downloader.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from huggingface_hub import snapshot_download
4
+ from datetime import datetime
5
+
6
+ def ts():
7
+ return datetime.now().strftime("%H:%M:%S")
8
+
9
+ MODELS_TO_CACHE = [
10
+ {"repo_id": "Qwen/Qwen3-TTS-12Hz-0.6B-Base", "allow_patterns": ["*.safetensors", "*.json", "*.txt"]},
11
+ {"repo_id": "Qwen/Qwen3-TTS-12Hz-1.7B-Base", "allow_patterns": ["*.safetensors", "*.json", "*.txt"]},
12
+ {"repo_id": "Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice", "allow_patterns": ["*.safetensors", "*.json", "*.txt"]},
13
+ {"repo_id": "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice", "allow_patterns": ["*.safetensors", "*.json", "*.txt"]},
14
+ {"repo_id": "hynt/F5-TTS-Vietnamese-ViVoice", "allow_patterns": ["model_last.pt"]},
15
+ {"repo_id": "charactr/vocos-mel-24khz", "allow_patterns": ["pytorch_model.bin", "config.yaml"]},
16
+ ]
17
+
18
+ def download_all_models(progress=gr.Progress()):
19
+ log = f"[{ts()}] 🚀 BẮT ĐẦU KIỂM TRA & TẢI MODELS OFFLINE...\n"
20
+ cache_dir = os.environ.get("HF_HOME", "Cache mặc định")
21
+ log += f"[{ts()}] 📂 Thư mục lưu trữ: {cache_dir}\n"
22
+ log += f"[{ts()}] (Lưu ý: Quá trình này có thể tốn vài phút tùy tốc độ mạng)\n\n"
23
+ yield log
24
+
25
+ total = len(MODELS_TO_CACHE)
26
+ for i, item in enumerate(MODELS_TO_CACHE):
27
+ repo_id = item["repo_id"]
28
+ patterns = item["allow_patterns"]
29
+ progress((i, total), desc=f"Đang xử lý {repo_id}...")
30
+ log += f"[{ts()}] ⏳ Kiểm tra/Tải {repo_id}...\n"
31
+ yield log
32
+
33
+ try:
34
+ path = snapshot_download(repo_id, allow_patterns=patterns, local_dir_use_symlinks=False)
35
+ log += f"[{ts()}] ✅ HOÀN TẤT {repo_id}\n └─ Path: {path}\n\n"
36
+ yield log
37
+ except Exception as e:
38
+ log += f"[{ts()}] ❌ LỖI KHI TẢI {repo_id}: {str(e)}\n\n"
39
+ yield log
40
+
41
+ progress((total, total), desc="DONE")
42
+ log += f"[{ts()}] 🎉 ĐÃ CÀI ĐẶT TOÀN BỘ MODELS XONG!\n"
43
+ log += f"Hệ thống đã sẵn sàng chạy Offline 100% tại máy mà không cần tải lại.\n"
44
+ yield log
45
+
source/qwen_app/generation.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import sys
4
+ import time
5
+ import uuid
6
+ import tempfile
7
+ import subprocess
8
+ from typing import Dict, List
9
+
10
+ import numpy as np
11
+ import soundfile as sf
12
+
13
+ import gradio as gr
14
+ import spaces
15
+
16
+ from .model_manager import model_manager
17
+ from .voice_library import normalize_audio, resolve_reference_details, set_seed
18
+ from .prosody import PauseConfig, DEFAULT_PAUSE, make_silence, detect_pause_ms
19
+
20
+
21
+ def decode_params(seed, temperature, top_p, repetition_penalty, max_new_tokens) -> Dict:
22
+ set_seed(int(seed or 0))
23
+ return dict(
24
+ do_sample=True,
25
+ temperature=float(temperature),
26
+ top_k=50,
27
+ top_p=float(top_p),
28
+ repetition_penalty=float(repetition_penalty),
29
+ max_new_tokens=int(max_new_tokens),
30
+ )
31
+
32
+
33
+ def _is_faster_backend(model) -> bool:
34
+ return model.__class__.__name__ == "FasterQwen3TTS"
35
+
36
+
37
+ def smart_chunk_text(text: str, max_words: int = 40) -> List[str]:
38
+ """Split long text into sentence-aware chunks for more stable generation."""
39
+ clean = (text or "").strip()
40
+ if not clean:
41
+ return []
42
+
43
+ def has_cjk(value: str) -> bool:
44
+ return bool(re.search(r"[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]", value))
45
+
46
+ is_cjk = has_cjk(clean)
47
+ sentence_pattern = r"(?<=[.!?。!?।؟])(?![.!?。!?।؟])\s*|\n+"
48
+ sentences = [s.strip() for s in re.split(sentence_pattern, clean) if s.strip()]
49
+
50
+ chunks: List[str] = []
51
+ current_chunk: List[str] = []
52
+ current_count = 0
53
+
54
+ for sentence in sentences:
55
+ sentence_count = len(re.sub(r"\s+", "", sentence)) if is_cjk else len(sentence.split())
56
+
57
+ if current_count + sentence_count > max_words:
58
+ if current_chunk:
59
+ chunks.append("".join(current_chunk) if is_cjk else " ".join(current_chunk))
60
+ current_chunk = []
61
+ current_count = 0
62
+
63
+ if sentence_count > max_words:
64
+ parts = [p.strip() for p in re.split(r"[,;،、;،]\s*", sentence) if p.strip()]
65
+ for part in parts:
66
+ part_count = len(re.sub(r"\s+", "", part)) if is_cjk else len(part.split())
67
+ if current_count + part_count > max_words and current_chunk:
68
+ chunks.append("".join(current_chunk) if is_cjk else " ".join(current_chunk))
69
+ current_chunk = [part]
70
+ current_count = part_count
71
+ else:
72
+ current_chunk.append(part)
73
+ current_count += part_count
74
+ else:
75
+ current_chunk.append(sentence)
76
+ current_count += sentence_count
77
+ else:
78
+ current_chunk.append(sentence)
79
+ current_count += sentence_count
80
+
81
+ if current_chunk:
82
+ chunks.append("".join(current_chunk) if is_cjk else " ".join(current_chunk))
83
+
84
+ return chunks if chunks else [clean]
85
+
86
+
87
+ def _estimate_generation_time_seconds(text_length: int, chunks: int, model_size: str | None = None) -> float:
88
+ base = max(3.0, (text_length / 70.0) * 1.8)
89
+ chunk_overhead = max(0, chunks - 1) * 0.9
90
+ size_factor = 1.0 if model_size == "0.6B" else 1.25
91
+ return (base + chunk_overhead) * size_factor
92
+
93
+
94
+ def _format_seconds(seconds: float) -> str:
95
+ if seconds < 60:
96
+ return f"{seconds:.1f}s"
97
+ m = int(seconds // 60)
98
+ s = seconds % 60
99
+ return f"{m}m {s:.1f}s"
100
+
101
+
102
+ def _elapsed_str(t0: float) -> str:
103
+ return _format_seconds(time.time() - t0)
104
+
105
+
106
+ def _build_atempo_filter_chain(speed: float) -> List[str]:
107
+ """
108
+ Build a safe FFmpeg atempo filter chain for any speed value.
109
+
110
+ FFmpeg atempo only accepts values in [0.5, 2.0]. For values outside
111
+ this range we chain multiple filters:
112
+ speed=0.3 → ["atempo=0.5", "atempo=0.6"]
113
+ speed=3.0 → ["atempo=2.0", "atempo=1.5"]
114
+ speed=0.8 → ["atempo=0.800000"]
115
+
116
+ Returns empty list if speed is effectively 1.0 (no-op).
117
+ """
118
+ if abs(speed - 1.0) < 0.01:
119
+ return []
120
+ filters: List[str] = []
121
+ s = float(speed)
122
+ while s > 2.0:
123
+ filters.append("atempo=2.0")
124
+ s /= 2.0
125
+ while s < 0.5:
126
+ filters.append("atempo=0.5")
127
+ s *= 2.0
128
+ filters.append(f"atempo={s:.6f}")
129
+ return filters
130
+
131
+
132
+ def apply_speed_post_process(audio_tuple, speed: float):
133
+ """
134
+ Apply FFmpeg atempo speed change AFTER model inference — never before.
135
+ Input: (sample_rate, np.ndarray float32)
136
+ Output: (sample_rate, np.ndarray float32) at new speed.
137
+
138
+ - Speed 1.0 → no-op, returns original immediately.
139
+ - Chains atempo filters for values outside [0.5, 2.0].
140
+ - Preserves pitch (atempo = pitch-preserving time-stretch).
141
+ - Falls back to original audio if FFmpeg fails.
142
+ """
143
+ if audio_tuple is None:
144
+ return None
145
+ sr, data = audio_tuple
146
+ if data is None or len(data) == 0:
147
+ return audio_tuple
148
+ if abs(speed - 1.0) < 0.01:
149
+ return audio_tuple # Skip FFmpeg entirely
150
+
151
+ tmp_dir = tempfile.gettempdir()
152
+ uid = uuid.uuid4().hex
153
+ tmp_in = os.path.join(tmp_dir, f"qwen_spd_in_{uid}.wav")
154
+ tmp_out = os.path.join(tmp_dir, f"qwen_spd_out_{uid}.wav")
155
+ try:
156
+ arr = data.astype(np.float32)
157
+ sf.write(tmp_in, arr, sr)
158
+
159
+ filters = _build_atempo_filter_chain(speed)
160
+ cmd = [
161
+ "ffmpeg", "-y", "-i", tmp_in,
162
+ "-filter:a", ",".join(filters),
163
+ "-c:a", "pcm_f32le",
164
+ "-loglevel", "error",
165
+ tmp_out,
166
+ ]
167
+ ff_flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
168
+ if ff_flags:
169
+ subprocess.run(cmd, check=True, creationflags=ff_flags)
170
+ else:
171
+ subprocess.run(cmd, check=True)
172
+
173
+ result, out_sr = sf.read(tmp_out, dtype="float32")
174
+ return (out_sr, result)
175
+ except Exception:
176
+ return audio_tuple # Graceful fallback
177
+ finally:
178
+ for f in [tmp_in, tmp_out]:
179
+ if os.path.exists(f):
180
+ try:
181
+ os.remove(f)
182
+ except Exception:
183
+ pass
184
+
185
+
186
+ # ─── Core generation functions ────────────────────────────────────────────────
187
+
188
+ @spaces.GPU(duration=120)
189
+ def generate_voice_design(text, language, voice_description, seed, temperature, top_p, repetition_penalty, max_new_tokens, speed=1.0, pause_config: PauseConfig | None = None, progress=gr.Progress(track_tqdm=True)):
190
+ cfg = pause_config or DEFAULT_PAUSE
191
+ try:
192
+ t0 = time.time()
193
+ if not text or not text.strip():
194
+ yield 0, None, "Error: text is required."
195
+ return
196
+ if not voice_description or not voice_description.strip():
197
+ yield 0, None, "Error: voice description is required."
198
+ return
199
+
200
+ yield 10, None, "Loading VoiceDesign 1.7B..."
201
+ progress(0.15, desc="Loading model")
202
+ model, note = model_manager.get_model("VoiceDesign", "1.7B")
203
+ yield 35, None, note
204
+
205
+ chunks = smart_chunk_text(text.strip())
206
+ total_chunks = len(chunks)
207
+ estimated = _estimate_generation_time_seconds(len(text.strip()), total_chunks, model_size="1.7B")
208
+ kwargs = decode_params(seed, temperature, top_p, repetition_penalty, max_new_tokens)
209
+ generated_chunks = []
210
+ sr = None
211
+
212
+ completed_pct = 35
213
+ yield completed_pct, None, (
214
+ f"{note} | Chunks: {total_chunks} | Estimated: {_format_seconds(estimated)} | Elapsed: {_elapsed_str(t0)}"
215
+ )
216
+ for i, chunk in enumerate(chunks):
217
+ yield completed_pct, None, f"{note} | Running chunk {i+1}/{total_chunks} | Elapsed: {_elapsed_str(t0)}"
218
+ if _is_faster_backend(model):
219
+ wavs, sr = model.generate_voice_design(text=chunk, language=language, instruct=voice_description.strip(), **kwargs)
220
+ else:
221
+ wavs, sr = model.generate_voice_design(text=chunk, language=language, instruct=voice_description.strip(), non_streaming_mode=True, **kwargs)
222
+ if wavs and len(wavs) > 0:
223
+ generated_chunks.append(normalize_audio(wavs[0]))
224
+ generated_chunks.append(make_silence(detect_pause_ms(chunk, cfg)))
225
+ completed_pct = 35 + int(((i + 1) / total_chunks) * 55)
226
+ yield completed_pct, None, f"{note} | Completed chunk {i+1}/{total_chunks} | Elapsed: {_elapsed_str(t0)}"
227
+
228
+ if not generated_chunks or sr is None:
229
+ yield 0, None, "Error: no audio generated."
230
+ return
231
+
232
+ full_audio = np.concatenate(generated_chunks) if len(generated_chunks) > 1 else generated_chunks[0]
233
+ total_time = time.time() - t0
234
+ progress(1.0, desc=f"Done | Total {_format_seconds(total_time)}")
235
+ audio_out = apply_speed_post_process((sr, full_audio), speed)
236
+ speed_note = f" | Speed: {speed:.2f}x" if abs(speed - 1.0) >= 0.01 else ""
237
+ yield 100, audio_out, (
238
+ f"Voice design completed. Chunks: {total_chunks} | Estimated: {_format_seconds(estimated)} | Total: {_format_seconds(total_time)}{speed_note}"
239
+ )
240
+ except Exception as e:
241
+ yield 0, None, f"Error: {type(e).__name__}: {e}"
242
+
243
+
244
+ @spaces.GPU(duration=120)
245
+ def generate_base(model_size, selected_voice_name, ref_audio, ref_text, target_text, language, xvector_only, seed, temperature, top_p, repetition_penalty, max_new_tokens, speed=1.0, pause_config: PauseConfig | None = None, progress=gr.Progress(track_tqdm=True)):
246
+ cfg = pause_config or DEFAULT_PAUSE
247
+ try:
248
+ t0 = time.time()
249
+ if not target_text or not target_text.strip():
250
+ yield 0, None, "Error: target text is required."
251
+ return
252
+
253
+ resolved_audio, resolved_audio_path, resolved_ref_text, src_note = resolve_reference_details(
254
+ selected_voice_name, ref_audio, ref_text, xvector_only
255
+ )
256
+ if resolved_audio is None:
257
+ yield 0, None, src_note
258
+ return
259
+
260
+ yield 10, None, f"Loading Base {model_size}..."
261
+ progress(0.15, desc="Loading model")
262
+ model, note = model_manager.get_model("Base", model_size)
263
+ yield 35, None, f"{note} | {src_note}"
264
+
265
+ chunks = smart_chunk_text(target_text.strip())
266
+ total_chunks = len(chunks)
267
+ estimated = _estimate_generation_time_seconds(len(target_text.strip()), total_chunks, model_size=model_size)
268
+ kwargs = decode_params(seed, temperature, top_p, repetition_penalty, max_new_tokens)
269
+ generated_chunks = []
270
+ sr = None
271
+
272
+ completed_pct = 35
273
+ yield completed_pct, None, (
274
+ f"{note} | {src_note} | Chunks: {total_chunks} | Estimated: {_format_seconds(estimated)} | Elapsed: {_elapsed_str(t0)}"
275
+ )
276
+ for i, chunk in enumerate(chunks):
277
+ yield completed_pct, None, (
278
+ f"{note} | {src_note} | Running chunk {i+1}/{total_chunks} | Elapsed: {_elapsed_str(t0)}"
279
+ )
280
+ if _is_faster_backend(model):
281
+ ref_audio_for_call = resolved_audio_path if resolved_audio_path else resolved_audio
282
+ wavs, sr = model.generate_voice_clone(
283
+ text=chunk, language=language,
284
+ ref_audio=ref_audio_for_call, ref_text=resolved_ref_text or "",
285
+ xvec_only=bool(xvector_only), non_streaming_mode=True, **kwargs,
286
+ )
287
+ else:
288
+ wavs, sr = model.generate_voice_clone(
289
+ text=chunk, language=language,
290
+ ref_audio=resolved_audio, ref_text=resolved_ref_text,
291
+ x_vector_only_mode=bool(xvector_only), non_streaming_mode=True, **kwargs,
292
+ )
293
+ if wavs and len(wavs) > 0:
294
+ generated_chunks.append(normalize_audio(wavs[0]))
295
+ generated_chunks.append(make_silence(detect_pause_ms(chunk, cfg)))
296
+ completed_pct = 35 + int(((i + 1) / total_chunks) * 55)
297
+ yield completed_pct, None, (
298
+ f"{note} | {src_note} | Completed chunk {i+1}/{total_chunks} | Elapsed: {_elapsed_str(t0)}"
299
+ )
300
+
301
+ if not generated_chunks or sr is None:
302
+ yield 0, None, "Error: no audio generated."
303
+ return
304
+
305
+ full_audio = np.concatenate(generated_chunks) if len(generated_chunks) > 1 else generated_chunks[0]
306
+ total_time = time.time() - t0
307
+ progress(1.0, desc=f"Done | Total {_format_seconds(total_time)}")
308
+ audio_out = apply_speed_post_process((sr, full_audio), speed)
309
+ speed_note = f" | Speed: {speed:.2f}x" if abs(speed - 1.0) >= 0.01 else ""
310
+ yield 100, audio_out, (
311
+ f"Base {model_size} generation completed. Chunks: {total_chunks} | Estimated: {_format_seconds(estimated)} | Total: {_format_seconds(total_time)}{speed_note}"
312
+ )
313
+ except Exception as e:
314
+ yield 0, None, f"Error: {type(e).__name__}: {e}"
315
+
316
+
317
+ @spaces.GPU(duration=120)
318
+ def generate_custom(model_size, text, language, speaker, instruct, seed, temperature, top_p, repetition_penalty, max_new_tokens, speed=1.0, pause_config: PauseConfig | None = None, progress=gr.Progress(track_tqdm=True)):
319
+ cfg = pause_config or DEFAULT_PAUSE
320
+ try:
321
+ t0 = time.time()
322
+ if not text or not text.strip():
323
+ yield 0, None, "Error: text is required."
324
+ return
325
+ if not speaker:
326
+ yield 0, None, "Error: speaker is required."
327
+ return
328
+
329
+ yield 10, None, f"Loading CustomVoice {model_size}..."
330
+ progress(0.15, desc="Loading model")
331
+ model, note = model_manager.get_model("CustomVoice", model_size)
332
+ yield 35, None, note
333
+
334
+ chunks = smart_chunk_text(text.strip())
335
+ total_chunks = len(chunks)
336
+ estimated = _estimate_generation_time_seconds(len(text.strip()), total_chunks, model_size=model_size)
337
+ kwargs = decode_params(seed, temperature, top_p, repetition_penalty, max_new_tokens)
338
+ generated_chunks = []
339
+ sr = None
340
+
341
+ completed_pct = 35
342
+ yield completed_pct, None, (
343
+ f"{note} | Chunks: {total_chunks} | Estimated: {_format_seconds(estimated)} | Elapsed: {_elapsed_str(t0)}"
344
+ )
345
+ for i, chunk in enumerate(chunks):
346
+ yield completed_pct, None, f"{note} | Running chunk {i+1}/{total_chunks} | Elapsed: {_elapsed_str(t0)}"
347
+ if _is_faster_backend(model):
348
+ wavs, sr = model.generate_custom_voice(
349
+ text=chunk, language=language,
350
+ speaker=speaker.lower().replace(" ", "_"),
351
+ instruct=(instruct or "").strip() if model_size == "1.7B" else None,
352
+ **kwargs,
353
+ )
354
+ else:
355
+ wavs, sr = model.generate_custom_voice(
356
+ text=chunk, language=language,
357
+ speaker=speaker.lower().replace(" ", "_"),
358
+ instruct=(instruct or "").strip() if model_size == "1.7B" else None,
359
+ non_streaming_mode=True, **kwargs,
360
+ )
361
+ if wavs and len(wavs) > 0:
362
+ generated_chunks.append(normalize_audio(wavs[0]))
363
+ generated_chunks.append(make_silence(detect_pause_ms(chunk, cfg)))
364
+ completed_pct = 35 + int(((i + 1) / total_chunks) * 55)
365
+ yield completed_pct, None, (
366
+ f"{note} | Completed chunk {i+1}/{total_chunks} | Elapsed: {_elapsed_str(t0)}"
367
+ )
368
+
369
+ if not generated_chunks or sr is None:
370
+ yield 0, None, "Error: no audio generated."
371
+ return
372
+
373
+ full_audio = np.concatenate(generated_chunks) if len(generated_chunks) > 1 else generated_chunks[0]
374
+ total_time = time.time() - t0
375
+ progress(1.0, desc=f"Done | Total {_format_seconds(total_time)}")
376
+ audio_out = apply_speed_post_process((sr, full_audio), speed)
377
+ speed_note = f" | Speed: {speed:.2f}x" if abs(speed - 1.0) >= 0.01 else ""
378
+ yield 100, audio_out, (
379
+ f"CustomVoice {model_size} generation completed. Chunks: {total_chunks} | Estimated: {_format_seconds(estimated)} | Total: {_format_seconds(total_time)}{speed_note}"
380
+ )
381
+ except Exception as e:
382
+ yield 0, None, f"Error: {type(e).__name__}: {e}"
383
+
384
+
385
+ # ── Helper to build PauseConfig from 7 flat slider values ───────────────────
386
+ def _build_cfg(ps, pc, psc, pco, pel, pnl, pdf) -> PauseConfig:
387
+ return PauseConfig(
388
+ sentence_ms=int(ps), comma_ms=int(pc),
389
+ semicolon_ms=int(psc), colon_ms=int(pco),
390
+ ellipsis_ms=int(pel), newline_ms=int(pnl),
391
+ default_ms=int(pdf),
392
+ )
393
+
394
+
395
+ # ── Tab wrapper functions ─────────────────────────────────────────────────────
396
+
397
+ def generate_base_17(
398
+ selected_voice_name, target_text, language, xvector_only,
399
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
400
+ speed=1.0,
401
+ ps=500, pc=180, psc=300, pco=250, pel=700, pnl=600, pdf=80,
402
+ ):
403
+ yield from generate_base("1.7B", selected_voice_name, None, "", target_text, language, xvector_only,
404
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
405
+ speed, _build_cfg(ps, pc, psc, pco, pel, pnl, pdf))
406
+
407
+
408
+ def generate_base_06(
409
+ selected_voice_name, target_text, language, xvector_only,
410
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
411
+ speed=1.0,
412
+ ps=500, pc=180, psc=300, pco=250, pel=700, pnl=600, pdf=80,
413
+ ):
414
+ yield from generate_base("0.6B", selected_voice_name, None, "", target_text, language, xvector_only,
415
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
416
+ speed, _build_cfg(ps, pc, psc, pco, pel, pnl, pdf))
417
+
418
+
419
+ def generate_custom_17(
420
+ text, language, speaker, instruct,
421
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
422
+ speed=1.0,
423
+ ps=500, pc=180, psc=300, pco=250, pel=700, pnl=600, pdf=80,
424
+ ):
425
+ yield from generate_custom("1.7B", text, language, speaker, instruct,
426
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
427
+ speed, _build_cfg(ps, pc, psc, pco, pel, pnl, pdf))
428
+
429
+
430
+ def generate_custom_06(
431
+ text, language, speaker,
432
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
433
+ speed=1.0,
434
+ ps=500, pc=180, psc=300, pco=250, pel=700, pnl=600, pdf=80,
435
+ ):
436
+ yield from generate_custom("0.6B", text, language, speaker, "",
437
+ seed, temperature, top_p, repetition_penalty, max_new_tokens,
438
+ speed, _build_cfg(ps, pc, psc, pco, pel, pnl, pdf))
source/qwen_app/mode3_news.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/mode3_news.py — v2.0 (Full Rewrite)
2
+ # ─── Fixes Applied ────────────────────────────────────────────────────────────
3
+ # FIX #1: Per-phase MP3 + per-phase SRT → validator chinh xac 1:1
4
+ # FIX #2: FULL_MASTER.srt tong hop (offset dung) giu lai for external use
5
+ # FIX #3: CJK-aware fallback duration (tieng Han/Viet/Korean tinh theo char)
6
+ # FIX #4: Natural sort phases (1,2,...,9,10 thay vi 1,10,11,...,2)
7
+ # FIX #5: Retry logging chi tiet (attempt#, RMS, chunk preview)
8
+ # FIX #6: Orphan audio threshold tang (>500ms) + consecutive check
9
+ # FIX #7: Validation 2 chieu chinh xac: moi phase MP3 chi validate voi SRT rieng
10
+ # FIX #8: Skip-if-done kiem tra theo phase, khong theo tong the
11
+ # ──────────────────────────────────────────────────────────────────────────────
12
+
13
+ import os
14
+ import re
15
+ import sys
16
+ import uuid
17
+ import hashlib
18
+ import traceback
19
+ import subprocess
20
+ import gc
21
+ import numpy as np
22
+ import soundfile as sf
23
+ import gradio as gr
24
+ from datetime import timedelta, datetime
25
+
26
+ try:
27
+ import torch
28
+ except ImportError:
29
+ torch = None
30
+
31
+ from .model_manager import model_manager
32
+ from .generation import decode_params, smart_chunk_text, _is_faster_backend, _build_atempo_filter_chain
33
+ from .voice_library import normalize_audio, resolve_reference_details
34
+ from .prosody import PauseConfig, DEFAULT_PAUSE, make_silence, detect_pause_ms
35
+ from .audio_validator import (
36
+ validate_audio_vs_srt, format_validation_report,
37
+ check_array_energy, SILENCE_THRESHOLD_RMS, MAX_CHUNK_RETRIES
38
+ )
39
+
40
+ AUTO_PROJECT_OUTPUT_FOLDER_NAME = "_OUTPUT_PROJECTS"
41
+
42
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
43
+ def sanitize_filename(name):
44
+ return re.sub(r'[/*?:"<>|]', "", name)
45
+
46
+ def generate_clean_guid(s):
47
+ return hashlib.sha1(s.encode('utf-8')).hexdigest()[:16]
48
+
49
+ def format_timestamp(seconds):
50
+ td = timedelta(seconds=max(0.0, seconds))
51
+ total_s = int(td.total_seconds())
52
+ h, rem = divmod(total_s, 3600)
53
+ m, s = divmod(rem, 60)
54
+ ms = int(td.microseconds / 1000)
55
+ return f"{h:02}:{m:02}:{s:02},{ms:03}"
56
+
57
+ def clean_text(text):
58
+ if not text: return ""
59
+ # 1. Remove URLs to prevent spelling out gibberish
60
+ text = re.sub(r'https?:\/\/[^\s]+', '', text)
61
+ text = re.sub(r'www\.[^\s]+', '', text)
62
+
63
+ # 2. Unify ellipsis, quotes
64
+ text = text.replace('…', '...')
65
+ text = re.sub(r'[“”]', '"', text)
66
+ text = re.sub(r'[‘’]', "'", text)
67
+
68
+ # 3. Limit repeating punctuations that cause glitches
69
+ text = re.sub(r'([!?。!?]){2,}', r'\1\1', text)
70
+ text = re.sub(r'([,;،、;:]){2,}', r'\1', text)
71
+ text = re.sub(r'\.{4,}', '...', text)
72
+
73
+ # 4. Fix missing space after punctuation before a letter
74
+ # [^\W\d_] matches any Unicode letter (Latin, Cyrillic, CJK, Hangul, etc.)
75
+ text = re.sub(r'([.,!?])([^\W\d_])', r'\1 \2', text)
76
+
77
+ # 5. Basic printable char filter
78
+ text = "".join(ch for ch in text if ch.isprintable() or ch == '\n')
79
+
80
+ # 6. Normalize spaces (flatten newlines to space like original logic)
81
+ return re.sub(r'\s+', ' ', text).strip()
82
+
83
+ def is_speakable(text):
84
+ return bool(re.search(r'[a-zA-Z0-9\u00C0-\u1EF9\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]', text))
85
+
86
+ def has_cjk(text):
87
+ """True if text contains CJK / Korean / Japanese characters."""
88
+ return bool(re.search(r'[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]', text))
89
+
90
+ def ts():
91
+ return datetime.now().strftime("%H:%M:%S")
92
+
93
+ def _natural_sort_key(s: str):
94
+ """Sort key that handles numeric parts naturally: PHASE_1 < PHASE_2 < PHASE_10."""
95
+ return [int(c) if c.isdigit() else c.lower() for c in re.split(r'(\d+)', s)]
96
+
97
+
98
+ # ─── CJK-aware fallback duration estimator ────────────────────────────────────
99
+ def _estimate_chunk_duration(chunk: str, speed: float) -> float:
100
+ """
101
+ Estimate audio duration (in seconds AFTER speed) for a chunk that failed inference.
102
+ - CJK/Korean: ~4.2 characters/second at speed=1.0 (conservative)
103
+ - Latin/Vietnamese: ~130 words/minute = ~2.17 words/second
104
+ """
105
+ s = max(speed, 0.1)
106
+ if has_cjk(chunk):
107
+ char_count = max(1, len(re.sub(r'\s+', '', chunk)))
108
+ return (char_count / 4.2) / s
109
+ else:
110
+ word_count = max(1, len(chunk.split()))
111
+ return (word_count / 130.0) * 60.0 / s
112
+
113
+
114
+ # ─── Project Parser ────────────────────────────────────────────────────────────
115
+ class ProjectParser:
116
+ @staticmethod
117
+ def parse_txt(file_path, project_folder_name):
118
+ try:
119
+ with open(file_path, 'r', encoding='utf-8') as f:
120
+ content = f.read()
121
+ if "STORY |" not in content or "END GAMES" not in content:
122
+ return None, None
123
+ core = content.split("STORY |")[1].split("END GAMES")[0].strip()
124
+ g = generate_clean_guid(
125
+ f"{sanitize_filename(project_folder_name)}_{sanitize_filename(os.path.splitext(os.path.basename(file_path))[0])}"
126
+ )
127
+ pattern = re.compile(
128
+ r'PHASE\s+(\d+)\s*\|\s*(.*?)\s*\|\s*Prompt\s*\d+\s*:\s*(.*?)(?=\n\s*PHASE|\Z)',
129
+ re.DOTALL | re.IGNORECASE
130
+ )
131
+ phases = []
132
+ for m in pattern.findall(core):
133
+ txt = clean_text(m[1].strip())
134
+ if txt:
135
+ phases.append({
136
+ "id": int(m[0].strip()),
137
+ "text": txt,
138
+ "prompt": m[2].strip(),
139
+ "prompt_name": f"{m[0].strip()}_PHASE_{g}"
140
+ })
141
+ if phases:
142
+ # FIX #4: natural sort by numeric id
143
+ return sorted(phases, key=lambda x: x['id']), None
144
+ except Exception:
145
+ pass
146
+ return None, None
147
+
148
+
149
+ # ─── Core TTS inference for one chunk ────────────────────────────────────────
150
+ def _infer_chunk(model, voice_mode, chunk_text, lang,
151
+ speaker, instruct, model_size,
152
+ ref_audio, ref_text, xvec_only, kwargs):
153
+ """Route chunk to Base or CustomVoice. Returns normalized np.float32 array or None."""
154
+ wavs = None
155
+ sr = None
156
+ if voice_mode == "Base (Voice Library)":
157
+ if _is_faster_backend(model):
158
+ wavs, sr = model.generate_voice_clone(
159
+ text=chunk_text, language=lang,
160
+ ref_audio=ref_audio, ref_text=ref_text or "",
161
+ xvec_only=bool(xvec_only), non_streaming_mode=True, **kwargs
162
+ )
163
+ else:
164
+ wavs, sr = model.generate_voice_clone(
165
+ text=chunk_text, language=lang,
166
+ ref_audio=ref_audio, ref_text=ref_text,
167
+ x_vector_only_mode=bool(xvec_only),
168
+ non_streaming_mode=True, **kwargs
169
+ )
170
+ else: # CustomVoice
171
+ spk = (speaker or "").lower().replace(" ", "_")
172
+ ins = (instruct or "").strip() if model_size == "1.7B" else None
173
+ if _is_faster_backend(model):
174
+ wavs, sr = model.generate_custom_voice(
175
+ text=chunk_text, language=lang, speaker=spk, instruct=ins, **kwargs
176
+ )
177
+ else:
178
+ wavs, sr = model.generate_custom_voice(
179
+ text=chunk_text, language=lang, speaker=spk, instruct=ins,
180
+ non_streaming_mode=True, **kwargs
181
+ )
182
+ if wavs and len(wavs) > 0:
183
+ return normalize_audio(wavs[0])
184
+ return None
185
+
186
+
187
+ def _infer_chunk_with_retry(
188
+ model, voice_mode, chunk_text, lang,
189
+ speaker, instruct, model_size,
190
+ ref_audio, ref_text, xvec_only, kwargs,
191
+ max_retries: int = MAX_CHUNK_RETRIES,
192
+ log_prefix: str = "",
193
+ ):
194
+ """
195
+ FIX #5: Enhanced retry with per-attempt RMS logging.
196
+
197
+ Returns: (arr_or_None, status_str, attempt_log_lines)
198
+ status = 'OK' → arr is good, attempt 0
199
+ status = 'RETRY_OK' → arr recovered after N retries
200
+ status = 'SILENT' → all retries failed → caller should fill silence
201
+ status = 'ERROR' → exception, arr is None
202
+ """
203
+ attempt_logs = []
204
+ last_exc = None
205
+ for attempt in range(1 + max_retries):
206
+ try:
207
+ arr = _infer_chunk(
208
+ model, voice_mode, chunk_text, lang,
209
+ speaker, instruct, model_size,
210
+ ref_audio, ref_text, xvec_only, kwargs,
211
+ )
212
+ rms = check_array_energy(arr)
213
+ attempt_logs.append(f" attempt {attempt+1}: RMS={rms:.5f} → {'✅ OK' if rms >= SILENCE_THRESHOLD_RMS else '⚠️ low'}")
214
+ if rms >= SILENCE_THRESHOLD_RMS:
215
+ status = 'OK' if attempt == 0 else 'RETRY_OK'
216
+ return arr, status, attempt_logs
217
+ last_exc = f"low energy (RMS={rms:.5f})"
218
+ except Exception as exc:
219
+ last_exc = str(exc)
220
+ attempt_logs.append(f" attempt {attempt+1}: EXCEPTION={exc}")
221
+
222
+ return None, 'SILENT', attempt_logs
223
+
224
+
225
+ # ─── FFmpeg: WAV → MP3 helper ────────────────────────────────────────────────
226
+ def _wav_to_mp3(tmp_wav: str, mp3_out: str, speed: float, do_norm: bool) -> bool:
227
+ """Convert WAV to MP3 with atempo speed change + optional loudnorm. Returns True on success."""
228
+ cmd = ["ffmpeg", "-y", "-i", tmp_wav]
229
+ filt = _build_atempo_filter_chain(speed)
230
+ if do_norm:
231
+ filt.append("loudnorm=I=-16:TP=-1.5:LRA=11")
232
+ if filt:
233
+ cmd += ["-filter:a", ",".join(filt)]
234
+ cmd += ["-c:a", "libmp3lame", "-b:a", "192k", "-loglevel", "error", mp3_out]
235
+ try:
236
+ ff_flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
237
+ subprocess.run(cmd, check=True, creationflags=ff_flags)
238
+ return os.path.exists(mp3_out) and os.path.getsize(mp3_out) >= 1024
239
+ except Exception:
240
+ return False
241
+
242
+
243
+ # ─── Per-phase SRT writer ─────────────────────────────────────────────────────
244
+ def _write_srt(path: str, entries: list):
245
+ """Write a list of {idx, start, end, text} dicts to SRT file."""
246
+ with open(path, 'w', encoding='utf-8') as f:
247
+ for s in entries:
248
+ f.write(f"{s['idx']}\n{s['start']} --> {s['end']}\n{s['text']}\n\n")
249
+
250
+
251
+ # ─── Main batch generator ──────────────────────────────────────────────────────
252
+ def process_news_batch(
253
+ txt_paths_str,
254
+ voice_mode, m3_saved_voice, m3_xvec,
255
+ model_size, speaker, lang, instruct,
256
+ speed, silence_sec, do_norm,
257
+ seed, temperature, top_p, rep_penalty, max_tokens,
258
+ pause_sentence_ms=500, pause_comma_ms=180, pause_semicolon_ms=300,
259
+ pause_colon_ms=250, pause_ellipsis_ms=700, pause_newline_ms=600, pause_default_ms=80,
260
+ progress=gr.Progress()
261
+ ):
262
+ pause_cfg = PauseConfig(
263
+ sentence_ms=int(pause_sentence_ms),
264
+ comma_ms=int(pause_comma_ms),
265
+ semicolon_ms=int(pause_semicolon_ms),
266
+ colon_ms=int(pause_colon_ms),
267
+ ellipsis_ms=int(pause_ellipsis_ms),
268
+ newline_ms=int(pause_newline_ms),
269
+ default_ms=int(pause_default_ms),
270
+ )
271
+ log = f"[{ts()}] 🚀 BẮT ĐẦU BATCH CHẾ ĐỘ 3 (v2.0)...\n"
272
+ yield log
273
+
274
+ # ── Validate paths
275
+ folders = [p.strip() for p in (txt_paths_str or "").split('\n')
276
+ if p.strip() and os.path.isdir(p.strip())]
277
+ if not folders:
278
+ log += f"[{ts()}] ❌ LỖI: Không tìm thấy thư mục hợp lệ!\n"
279
+ yield log; return
280
+
281
+ # ── Scan TXT files
282
+ log += f"[{ts()}] 🔎 Quét file .txt...\n"; yield log
283
+ valid_txts = []
284
+ for d in folders:
285
+ for root, _, files in os.walk(d):
286
+ if AUTO_PROJECT_OUTPUT_FOLDER_NAME in root:
287
+ continue
288
+ for f in sorted(files, key=_natural_sort_key):
289
+ if not f.lower().endswith(".txt"):
290
+ continue
291
+ path = os.path.join(root, f)
292
+ phases, _ = ProjectParser.parse_txt(path, os.path.basename(os.path.dirname(path)))
293
+ if phases:
294
+ valid_txts.append({
295
+ "path": path,
296
+ "group": os.path.basename(os.path.normpath(d)),
297
+ "phases": phases
298
+ })
299
+
300
+ if not valid_txts:
301
+ log += f"[{ts()}] ❌ Không tìm thấy Story nào theo chuẩn PHASE!\n"
302
+ yield log; return
303
+
304
+ log += f"[{ts()}] ✅ Tìm thấy {len(valid_txts)} story hợp lệ.\n"; yield log
305
+
306
+ # ── Resolve voice reference (Base mode)
307
+ ref_audio = None; ref_text = None; xvec_only = m3_xvec
308
+ if voice_mode == "Base (Voice Library)":
309
+ if not m3_saved_voice or m3_saved_voice == "None":
310
+ log += f"[{ts()}] ❌ LỖI: Chưa chọn Voice Library!\n"
311
+ yield log; return
312
+ resolved_audio, resolved_path, resolved_text, src_note = resolve_reference_details(
313
+ m3_saved_voice, None, None, xvec_only
314
+ )
315
+ if resolved_audio is None:
316
+ log += f"[{ts()}] ❌ Lỗi Load Voice Library: {src_note}\n"
317
+ yield log; return
318
+ ref_audio = resolved_path if resolved_path else resolved_audio
319
+ ref_text = resolved_text
320
+ log += f"[{ts()}] 🎤 Voice Library: {src_note}\n"; yield log
321
+ model_type = "Base"
322
+ else:
323
+ model_type = "CustomVoice"
324
+
325
+ # ── Load model
326
+ log += f"[{ts()}] ⚙️ Nạp Model {model_type} ({model_size})...\n"; yield log
327
+ try:
328
+ model, note = model_manager.get_model(model_type, model_size)
329
+ log += f"[{ts()}] ✅ Load xong: {note}\n"; yield log
330
+ except Exception as e:
331
+ log += f"[{ts()}] ❌ Lỗi Load Model: {e}\n"; yield log; return
332
+
333
+ kwargs = decode_params(seed=seed, temperature=temperature, top_p=top_p,
334
+ repetition_penalty=rep_penalty, max_new_tokens=max_tokens)
335
+
336
+ CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Qwen_Mode3_Cache")
337
+ os.makedirs(CACHE_DIR, exist_ok=True)
338
+ total = len(valid_txts)
339
+ batch_results = [] # (txt_name, passed: bool)
340
+
341
+ # ═══════════════════════════════════════════════════════════════════════════
342
+ for i, item in enumerate(valid_txts):
343
+ progress((i, total), desc=f"{i+1}/{total}...")
344
+ txt_path = item["path"]
345
+ phases = item["phases"] # already natural-sorted by id
346
+ txt_name = os.path.basename(txt_path)
347
+ txt_base = os.path.splitext(txt_name)[0]
348
+ proj_dir = os.path.dirname(txt_path)
349
+ out_dir = os.path.join(proj_dir, AUTO_PROJECT_OUTPUT_FOLDER_NAME, sanitize_filename(txt_base))
350
+ os.makedirs(out_dir, exist_ok=True)
351
+
352
+ # FIX #8: Per-phase skip — only check MP3s + FULL_MASTER.srt (no per-phase SRT in out_dir)
353
+ srt_master_path = os.path.join(out_dir, "FULL_MASTER.srt")
354
+ all_done = all(
355
+ os.path.exists(os.path.join(out_dir, f"{p['prompt_name']}.mp3"))
356
+ for p in phases
357
+ ) and os.path.exists(srt_master_path)
358
+
359
+ if all_done:
360
+ log += f"[{ts()}] ⏭ BỎ QUA (đã hoàn thành): {txt_name}\n"; yield log
361
+ continue
362
+
363
+ log += f"\n[{ts()}] ▶ [{item['group']}] → {txt_name}\n"; yield log
364
+
365
+ # Accumulate master SRT across all phases
366
+ master_srt_entries = []
367
+ master_srt_idx = 1
368
+ master_cursor = 0.0 # global time cursor for FULL_MASTER.srt
369
+ _phase_tmp_srts = {} # track temp per-phase SRT files for validation
370
+
371
+ story_passed = True
372
+
373
+ for phase in phases:
374
+ pt = phase['text']
375
+ if not is_speakable(pt):
376
+ continue
377
+ chunks = smart_chunk_text(pt)
378
+ if not chunks:
379
+ continue
380
+
381
+ phase_mp3 = os.path.join(out_dir, f"{phase['prompt_name']}.mp3")
382
+ # Per-phase SRT lives in CACHE_DIR (temp) — deleted after validation
383
+ # Output folder only has MP3s + FULL_MASTER.srt
384
+ phase_srt_tmp = os.path.join(CACHE_DIR, f"phase_srt_{uuid.uuid4().hex}.srt")
385
+ _phase_tmp_srts[phase['prompt_name']] = phase_srt_tmp
386
+
387
+ # FIX #8b: Skip individual phase if MP3 already exists (no need for per-phase SRT)
388
+ if os.path.exists(phase_mp3):
389
+ log += f" ⏭ Phase {phase['id']}: MP3 có sẵn, bỏ qua\n"; yield log
390
+ # Estimate local_cursor from MP3 duration to keep master_cursor accurate
391
+ try:
392
+ from .audio_validator import _load_audio_as_mono
393
+ _d, _sr = _load_audio_as_mono(phase_mp3)
394
+ master_cursor += len(_d) / _sr
395
+ except Exception:
396
+ pass
397
+ continue
398
+
399
+ log += f" ⏳ Phase {phase['id']}: {len(chunks)} chunk(s) → GPU...\n"; yield log
400
+
401
+ phase_arrays = [] # raw pre-speed arrays to be concatenated
402
+ phase_entries = [] # per-phase SRT entries (local timestamps starting at 0)
403
+ local_cursor = 0.0 # time cursor WITHIN this phase (pre-speed local)
404
+
405
+ # ── Per-chunk inference loop ──────────────────────────────────
406
+ for ci, chunk in enumerate(chunks):
407
+ if not is_speakable(chunk):
408
+ log += f" ⏭ Chunk {ci+1} chỉ chứa dấu câu — lấp silence\n"; yield log
409
+ pause_ms_f = detect_pause_ms(chunk, pause_cfg)
410
+ gap_dur_f = (pause_ms_f / 1000.0) / max(speed, 0.1)
411
+ phase_arrays.append(make_silence(pause_ms_f))
412
+ local_cursor += gap_dur_f
413
+ continue
414
+
415
+ arr, infer_status, attempt_logs = None, 'ERROR', []
416
+ try:
417
+ arr, infer_status, attempt_logs = _infer_chunk_with_retry(
418
+ model, voice_mode, chunk, lang,
419
+ speaker, instruct, model_size,
420
+ ref_audio, ref_text, xvec_only, kwargs,
421
+ )
422
+ except Exception as e:
423
+ infer_status = 'ERROR'
424
+ attempt_logs = [f" CRITICAL EXCEPTION: {e}"]
425
+ log += f" ❌ Chunk {ci+1} EXCEPTION: {e}\n"; yield log
426
+
427
+ # FIX #5: log attempt details if retried or failed
428
+ if infer_status in ('RETRY_OK', 'SILENT', 'ERROR') or len(attempt_logs) > 1:
429
+ log += f" 🔁 Chunk {ci+1} '{chunk[:30]}...':\n"
430
+ for al in attempt_logs:
431
+ log += al + "\n"
432
+ yield log
433
+
434
+ if infer_status == 'RETRY_OK':
435
+ log += f" ↻ Chunk {ci+1}: Recovered after retry ✅\n"; yield log
436
+
437
+ # ── FALLBACK: inference failed → silence placeholder ──────
438
+ if infer_status in ('SILENT', 'ERROR') and arr is None:
439
+ log += (f" ⚠️ Chunk {ci+1}: {MAX_CHUNK_RETRIES+1} lần thử thất bại"
440
+ f" — lấp silence ({chunk[:40]}...)\n"); yield log
441
+
442
+ # FIX #3: CJK-aware duration estimate
443
+ est_dur = _estimate_chunk_duration(chunk, speed)
444
+ pause_ms = detect_pause_ms(chunk, pause_cfg)
445
+ gap_dur = (pause_ms / 1000.0) / max(speed, 0.1)
446
+
447
+ sil_samples = int(est_dur * 24000)
448
+ phase_arrays.extend([np.zeros(sil_samples, dtype=np.float32),
449
+ make_silence(pause_ms)])
450
+
451
+ start_ts = local_cursor
452
+ end_ts = local_cursor + est_dur
453
+ phase_entries.append({
454
+ "idx": len(phase_entries) + 1,
455
+ "start": format_timestamp(start_ts),
456
+ "end": format_timestamp(end_ts),
457
+ "text": f"[RETRY FAILED — SILENT: {chunk[:60]}]",
458
+ })
459
+ master_srt_entries.append({
460
+ "idx": master_srt_idx,
461
+ "start": format_timestamp(master_cursor + start_ts),
462
+ "end": format_timestamp(master_cursor + end_ts),
463
+ "text": f"[RETRY FAILED — SILENT: {chunk[:60]}]",
464
+ })
465
+ master_srt_idx += 1
466
+ local_cursor += est_dur + gap_dur
467
+ continue
468
+
469
+ # ── NORMAL: good audio ────────────────────────────────────
470
+ if arr is not None and len(arr) > 0:
471
+ raw_dur = len(arr) / 24000.0
472
+ pause_ms = detect_pause_ms(chunk, pause_cfg)
473
+ sil = make_silence(pause_ms)
474
+ phase_arrays.extend([arr, sil])
475
+
476
+ speech_dur = raw_dur / max(speed, 0.1)
477
+ gap_dur = (pause_ms / 1000.0) / max(speed, 0.1)
478
+ start_ts = local_cursor
479
+ end_ts = start_ts + speech_dur
480
+
481
+ phase_entries.append({
482
+ "idx": len(phase_entries) + 1,
483
+ "start": format_timestamp(start_ts),
484
+ "end": format_timestamp(end_ts),
485
+ "text": chunk,
486
+ })
487
+ master_srt_entries.append({
488
+ "idx": master_srt_idx,
489
+ "start": format_timestamp(master_cursor + start_ts),
490
+ "end": format_timestamp(master_cursor + end_ts),
491
+ "text": chunk,
492
+ })
493
+ master_srt_idx += 1
494
+ local_cursor += speech_dur + gap_dur
495
+
496
+ # ── Write phase WAV → MP3 ─────────────────────────────────────
497
+ if phase_arrays:
498
+ tmp = os.path.join(CACHE_DIR, f"tmp_{uuid.uuid4().hex}.wav")
499
+ try:
500
+ sf.write(tmp, np.concatenate(phase_arrays), 24000)
501
+ ok = _wav_to_mp3(tmp, phase_mp3, speed, do_norm)
502
+ if not ok:
503
+ log += f" ⚠️ Phase {phase['id']}: FFmpeg thất bại hoặc MP3 rỗng!\n"; yield log
504
+ except Exception as e:
505
+ log += f" ❌ Phase {phase['id']} WAV/FFmpeg lỗi: {e}\n"; yield log
506
+ traceback.print_exc()
507
+ finally:
508
+ if os.path.exists(tmp):
509
+ try: os.remove(tmp)
510
+ except Exception: pass
511
+
512
+ # ── Write per-phase SRT to CACHE (temp) — NOT in out_dir ────
513
+ if phase_entries:
514
+ _write_srt(phase_srt_tmp, phase_entries)
515
+
516
+ # Advance master cursor by total phase duration
517
+ master_cursor += local_cursor
518
+
519
+ # ── Write FULL_MASTER.srt ─────────────────────────────────────────
520
+ if master_srt_entries:
521
+ _write_srt(srt_master_path, master_srt_entries)
522
+
523
+ # ═══ BIDIRECTIONAL VALIDATION ══════════════════════════════════════
524
+ # FIX #7: Validate each phase MP3 against its TEMP per-phase SRT (in CACHE_DIR)
525
+ # After validate → delete temp SRT. Out dir stays clean: MP3s + FULL_MASTER.srt only.
526
+ log += f"[{ts()}] 🔍 Bidirectional validation — {len(phases)} phase(s)...\n"; yield log
527
+ all_phases_ok = True
528
+
529
+ for phase in phases:
530
+ phase_mp3 = os.path.join(out_dir, f"{phase['prompt_name']}.mp3")
531
+ # Temp SRT was written to CACHE_DIR during inference; reconstruct expected path
532
+ # (We store the path in a side-channel dict built during inference)
533
+ tmp_srt_path = _phase_tmp_srts.get(phase['prompt_name'])
534
+
535
+ if not os.path.exists(phase_mp3):
536
+ log += f" ⚠️ Phase {phase['id']}: MP3 bị thiếu — bỏ qua validate\n"
537
+ all_phases_ok = False
538
+ yield log
539
+ continue
540
+
541
+ if not tmp_srt_path or not os.path.exists(tmp_srt_path):
542
+ log += f" ℹ️ Phase {phase['id']}: đã có từ session trước — bỏ qua validate\n"
543
+ yield log
544
+ continue
545
+
546
+ rpt = validate_audio_vs_srt(phase_mp3, tmp_srt_path)
547
+ pname = f"Phase {phase['id']}"
548
+
549
+ if rpt.overall_status == "PASS":
550
+ log += (f" ✅ {pname}: PASS "
551
+ f"({rpt.passed_entries}/{rpt.srt_total_entries} entries OK"
552
+ f", {rpt.audio_duration:.1f}s)\n")
553
+ elif rpt.overall_status == "WARN":
554
+ all_phases_ok = False
555
+ log += f" ⚠️ {pname}: WARN\n"
556
+ log += format_validation_report(rpt) + "\n"
557
+ else: # FAIL
558
+ all_phases_ok = False
559
+ log += f" ❌ {pname}: FAIL\n"
560
+ log += format_validation_report(rpt) + "\n"
561
+ yield log
562
+
563
+ # Delete temp SRT — output folder stays clean
564
+ try:
565
+ if os.path.exists(tmp_srt_path):
566
+ os.remove(tmp_srt_path)
567
+ except Exception:
568
+ pass
569
+
570
+ # ── Also sanity-check FULL_MASTER.srt (duration vs last entry) ───
571
+ if os.path.exists(srt_master_path) and master_srt_entries:
572
+ from .audio_validator import parse_srt as _parse_srt
573
+ master_entries = _parse_srt(srt_master_path)
574
+ if master_entries:
575
+ expected_end = master_entries[-1].end
576
+ total_mp3_dur = 0.0
577
+ for phase in phases:
578
+ ph_mp3 = os.path.join(out_dir, f"{phase['prompt_name']}.mp3")
579
+ if os.path.exists(ph_mp3):
580
+ try:
581
+ from .audio_validator import _load_audio_as_mono
582
+ d, sr_ = _load_audio_as_mono(ph_mp3)
583
+ total_mp3_dur += len(d) / sr_
584
+ except Exception:
585
+ pass
586
+ if abs(total_mp3_dur - expected_end) < 2.0:
587
+ log += (f"[{ts()}] ✅ FULL_MASTER.srt sanity: "
588
+ f"total audio={total_mp3_dur:.1f}s ≈ SRT end={expected_end:.1f}s\n")
589
+ else:
590
+ log += (f"[{ts()}] ⚠️ FULL_MASTER.srt drift: "
591
+ f"total audio={total_mp3_dur:.1f}s vs SRT end={expected_end:.1f}s "
592
+ f"(Δ={abs(total_mp3_dur-expected_end):.1f}s)\n")
593
+ all_phases_ok = False
594
+ yield log
595
+
596
+ if all_phases_ok:
597
+ log += f"[{ts()}] ✅ XÁC NHẬN XONG: {txt_name} — ĐẦY ĐỦ & TOÀN VẸN\n"
598
+ story_passed = True
599
+ else:
600
+ log += f"[{ts()}] ⚠️ NGƯỜI DÙNG CẦN KIỂM TRA: {txt_name} có một số đoạn bị thiếu!\n"
601
+ story_passed = False
602
+ yield log
603
+
604
+ batch_results.append((txt_name, story_passed))
605
+
606
+ gc.collect()
607
+ if torch and torch.cuda.is_available():
608
+ torch.cuda.empty_cache()
609
+
610
+ progress((total, total), desc="Done")
611
+
612
+ # ── FINAL BATCH SUMMARY ────────────────────────────────────────────
613
+ n_pass = sum(1 for _, ok in batch_results if ok)
614
+ n_fail = len(batch_results) - n_pass
615
+ log += f"\n{'='*60}\n"
616
+ log += f"[{ts()}] 🏁 KẾT QUẢ BATCH: {n_pass}/{len(batch_results)} story ĐÃ QUA KIỂM TRA\n"
617
+ if n_fail > 0:
618
+ log += f" ❌ {n_fail} story có vấn đề:\n"
619
+ for name, ok in batch_results:
620
+ if not ok:
621
+ log += f" • {name}\n"
622
+ else:
623
+ log += f" ✅ Tất cả {n_pass} story ĐẦY ĐỦ & TOÀN VẸN — SẢN PHẨM SẴN SÀNG GIAO!\n"
624
+ log += f"{'='*60}\n"
625
+ yield log
source/qwen_app/mode_batch_txt.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/mode_batch_txt.py
2
+ import os
3
+ import gc
4
+ import sys
5
+ import subprocess
6
+ import uuid
7
+ import numpy as np
8
+ import soundfile as sf
9
+ import gradio as gr
10
+
11
+ try:
12
+ import torch
13
+ except ImportError:
14
+ torch = None
15
+
16
+ from .model_manager import model_manager
17
+ from .generation import decode_params, smart_chunk_text, _build_atempo_filter_chain
18
+ from .voice_library import resolve_reference_details
19
+ from .mode3_news import ts, clean_text, is_speakable, format_timestamp, _infer_chunk, _infer_chunk_with_retry
20
+ from .prosody import PauseConfig, DEFAULT_PAUSE, make_silence, detect_pause_ms
21
+ from .audio_validator import validate_audio_vs_srt, format_validation_report, MAX_CHUNK_RETRIES
22
+
23
+ AUTO_TXT_OUTPUT_FOLDER_NAME = "_OUTPUT_TXT"
24
+
25
+ def process_batch_txt_pure(
26
+ txt_paths_str,
27
+ voice_mode, m3_saved_voice, m3_xvec,
28
+ model_size, speaker, lang, instruct,
29
+ speed, silence_sec, do_norm,
30
+ seed, temperature, top_p, rep_penalty, max_tokens,
31
+ # Prosodic pause config
32
+ pause_sentence_ms=500, pause_comma_ms=180, pause_semicolon_ms=300,
33
+ pause_colon_ms=250, pause_ellipsis_ms=700, pause_newline_ms=600, pause_default_ms=80,
34
+ progress=gr.Progress()
35
+ ):
36
+ pause_cfg = PauseConfig(
37
+ sentence_ms=int(pause_sentence_ms),
38
+ comma_ms=int(pause_comma_ms),
39
+ semicolon_ms=int(pause_semicolon_ms),
40
+ colon_ms=int(pause_colon_ms),
41
+ ellipsis_ms=int(pause_ellipsis_ms),
42
+ newline_ms=int(pause_newline_ms),
43
+ default_ms=int(pause_default_ms),
44
+ )
45
+ log = f"[{ts()}] 🚀 BẮT ĐẦU BATCH TXT (PURE)...\n"
46
+ yield log
47
+
48
+ folders = [p.strip() for p in (txt_paths_str or "").split('\n') if p.strip() and os.path.isdir(p.strip())]
49
+ if not folders:
50
+ log += f"[{ts()}] ❌ LỖI: Không tìm thấy thư mục hợp lệ!\n"
51
+ yield log; return
52
+
53
+ log += f"[{ts()}] 🔎 Quét file .txt...\n"; yield log
54
+ valid_txts = []
55
+ for d in folders:
56
+ for root, _, files in os.walk(d):
57
+ if AUTO_TXT_OUTPUT_FOLDER_NAME in root: continue
58
+ for f in files:
59
+ if not f.lower().endswith(".txt"): continue
60
+ path = os.path.join(root, f)
61
+ with open(path, 'r', encoding='utf-8') as file:
62
+ content = clean_text(file.read())
63
+ if content and is_speakable(content):
64
+ valid_txts.append({"path": path, "content": content, "folder": d})
65
+
66
+ if not valid_txts:
67
+ log += f"[{ts()}] ❌ Không tìm thấy file TXT có chữ hợp lệ!\n"
68
+ yield log; return
69
+
70
+ log += f"[{ts()}] ✅ Tìm thấy {len(valid_txts)} file TXT.\n"; yield log
71
+
72
+ ref_audio = None; ref_text = None; xvec_only = m3_xvec
73
+ if voice_mode == "Base (Voice Library)":
74
+ if not m3_saved_voice or m3_saved_voice == "None":
75
+ log += f"[{ts()}] ❌ LỖI: Chưa chọn Voice Library!\n"
76
+ yield log; return
77
+ resolved_audio, resolved_path, resolved_text, src_note = resolve_reference_details(
78
+ m3_saved_voice, None, None, xvec_only
79
+ )
80
+ if resolved_audio is None:
81
+ log += f"[{ts()}] ❌ Lỗi Load Voice Library: {src_note}\n"; yield log; return
82
+ ref_audio = resolved_path if resolved_path else resolved_audio
83
+ ref_text = resolved_text
84
+ log += f"[{ts()}] 🎤 Đã tải Voice Library: {src_note}\n"; yield log
85
+ model_type = "Base"
86
+ else:
87
+ model_type = "CustomVoice"
88
+
89
+ log += f"[{ts()}] ⚙️ Nạp Model {model_type} ({model_size}) lên GPU...\n"; yield log
90
+ try:
91
+ model, note = model_manager.get_model(model_type, model_size)
92
+ log += f"[{ts()}] ✅ Load xong: {note}\n"; yield log
93
+ except Exception as e:
94
+ log += f"[{ts()}] ❌ Lỗi Load Model: {e}\n"; yield log; return
95
+
96
+ kwargs = decode_params(seed=seed, temperature=temperature, top_p=top_p,
97
+ repetition_penalty=rep_penalty, max_new_tokens=max_tokens)
98
+
99
+ CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Qwen_Mode3_Cache")
100
+ os.makedirs(CACHE_DIR, exist_ok=True)
101
+ total = len(valid_txts)
102
+ batch_results = [] # (txt_name, passed: bool)
103
+
104
+ for i, item in enumerate(valid_txts):
105
+ progress((i, total), desc=f"{i+1}/{total}...")
106
+ txt_path = item["path"]
107
+ content = item["content"]
108
+ txt_name = os.path.basename(txt_path)
109
+ txt_base = os.path.splitext(txt_name)[0]
110
+
111
+ # Output directly into a subfolder _OUTPUT_TXT of the original folder
112
+ out_dir = os.path.join(item["folder"], AUTO_TXT_OUTPUT_FOLDER_NAME)
113
+ os.makedirs(out_dir, exist_ok=True)
114
+
115
+ mp3_path = os.path.join(out_dir, f"{txt_base}.mp3")
116
+ srt_path = os.path.join(out_dir, f"{txt_base}.srt")
117
+
118
+ if os.path.exists(mp3_path) and os.path.exists(srt_path):
119
+ log += f"[{ts()}] ⏭ BỎ QUA (đã có): {txt_name}\n"; yield log; continue
120
+
121
+ log += f"\n[{ts()}] ▶ Đang xử lý: {txt_name}\n"; yield log
122
+
123
+ chunks = smart_chunk_text(content)
124
+ if not chunks: continue
125
+ log += f" ⏳ {len(chunks)} chunk(s) → GPU...\n"; yield log
126
+
127
+ phase_arrays = []
128
+ srt_entries = []
129
+ srt_idx = 1
130
+ global_cursor = 0.0
131
+
132
+ for ci, chunk in enumerate(chunks):
133
+ if not is_speakable(chunk):
134
+ log += f" ⏭ Chunk {ci+1} chỉ chứa dấu câu — lấp silence\n"; yield log
135
+ pause_ms_f = detect_pause_ms(chunk, pause_cfg)
136
+ gap_dur_f = (pause_ms_f / 1000.0) / max(speed, 0.1)
137
+ phase_arrays.append(make_silence(pause_ms_f))
138
+ global_cursor += gap_dur_f
139
+ continue
140
+
141
+ arr, infer_status, attempt_logs = None, 'ERROR', []
142
+ try:
143
+ arr, infer_status, attempt_logs = _infer_chunk_with_retry(
144
+ model, voice_mode, chunk, lang, speaker, instruct,
145
+ model_size, ref_audio, ref_text, xvec_only, kwargs
146
+ )
147
+ except Exception as e:
148
+ infer_status = 'ERROR'
149
+ attempt_logs = [f" CRITICAL EXCEPTION: {e}"]
150
+ log += f" ❌ Chunk {ci+1} EXCEPTION: {e}\n"; yield log
151
+
152
+ # Log retry details when retried or failed
153
+ if infer_status in ('RETRY_OK', 'SILENT', 'ERROR') or len(attempt_logs) > 1:
154
+ log += f" 🔁 Chunk {ci+1} '{chunk[:30]}...':\n"
155
+ for al in attempt_logs:
156
+ log += al + "\n"
157
+ yield log
158
+
159
+ if infer_status == 'RETRY_OK':
160
+ log += f" ↻ Chunk {ci+1}: Recovered after retry — audio OK\n"; yield log
161
+
162
+ if infer_status == 'SILENT' or (infer_status == 'ERROR' and arr is None):
163
+ log += f" ⚠️ Chunk {ci+1}: Tất cả {MAX_CHUNK_RETRIES+1} lần thử — đặt silence lấp khoảng trống\n"; yield log
164
+ word_count = max(1, len(chunk.split()))
165
+ est_dur = (word_count / 130.0) / max(speed, 0.1)
166
+ pause_ms_f = detect_pause_ms(chunk, pause_cfg)
167
+ gap_dur_f = (pause_ms_f / 1000.0) / max(speed, 0.1)
168
+ # Lấp silence: giữ timing dòng SRT sau không bị lệch
169
+ silence_samples = int(est_dur * 24000)
170
+ phase_arrays.extend([np.zeros(silence_samples, dtype=np.float32), make_silence(pause_ms_f)])
171
+ srt_entries.append({
172
+ "idx" : srt_idx,
173
+ "start": format_timestamp(global_cursor),
174
+ "end" : format_timestamp(global_cursor + est_dur),
175
+ "text" : f"[RETRY FAILED — SILENT: {chunk[:60]}]"
176
+ })
177
+ global_cursor += est_dur + gap_dur_f
178
+ srt_idx += 1
179
+ continue
180
+
181
+ if arr is not None and len(arr) > 0:
182
+ raw_dur = len(arr) / 24000.0
183
+ # Punctuation-aware silence
184
+ pause_ms = detect_pause_ms(chunk, pause_cfg)
185
+ sil = make_silence(pause_ms)
186
+ phase_arrays.extend([arr, sil])
187
+
188
+ speech_dur = raw_dur / speed
189
+ gap_dur = (pause_ms / 1000.0) / speed
190
+ start, end = global_cursor, global_cursor + speech_dur
191
+
192
+ srt_entries.append({
193
+ "idx": srt_idx,
194
+ "start": format_timestamp(start),
195
+ "end": format_timestamp(end),
196
+ "text": chunk
197
+ })
198
+ global_cursor += (speech_dur + gap_dur)
199
+ srt_idx += 1
200
+
201
+ if phase_arrays:
202
+ tmp = os.path.join(CACHE_DIR, f"tmp_{uuid.uuid4().hex}.wav")
203
+ sf.write(tmp, np.concatenate(phase_arrays), 24000)
204
+
205
+ # BUG FIX #1 & #4: safe atempo chain — handles speed < 0.5 and > 2.0
206
+ cmd = ["ffmpeg", "-y", "-i", tmp]
207
+ filt = _build_atempo_filter_chain(speed)
208
+ if do_norm: filt.append("loudnorm=I=-16:TP=-1.5:LRA=11")
209
+ if filt: cmd += ["-filter:a", ",".join(filt)]
210
+ cmd += ["-c:a", "libmp3lame", "-b:a", "192k", "-loglevel", "error", mp3_path]
211
+ try:
212
+ ff_flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
213
+ if ff_flags:
214
+ subprocess.run(cmd, check=True, creationflags=ff_flags)
215
+ else:
216
+ subprocess.run(cmd, check=True)
217
+ # Sanity check: MP3 should exist and be non-empty
218
+ if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) < 1024:
219
+ log += f" ⚠️ {txt_name}: MP3 tạo ra bị thiếu hoặc rỗng!\n"; yield log
220
+ except Exception as e:
221
+ log += f" ❌ FFmpeg {txt_name}: {e}\n"; yield log
222
+ if os.path.exists(tmp): os.remove(tmp)
223
+
224
+ if srt_entries:
225
+ with open(srt_path, 'w', encoding='utf-8') as f:
226
+ for s in srt_entries:
227
+ f.write(f"{s['idx']}\n{s['start']} --> {s['end']}\n{s['text']}\n\n")
228
+
229
+ # ── AUTO INTEGRITY VALIDATION ──────────────────────────────────────────
230
+ # Validate ngay sau khi ghi xong — chỉ ✅ DONE nếu pass.
231
+ if os.path.exists(mp3_path) and os.path.exists(srt_path):
232
+ log += f"[{ts()}] 🔍 Auto-validating: {txt_name}...\n"; yield log
233
+ rpt = validate_audio_vs_srt(mp3_path, srt_path)
234
+ if rpt.overall_status == "PASS":
235
+ log += f"[{ts()}] ✅ XÁC NHẬN: {txt_name} — ĐẦY ĐỦ & TOÀN VẸN ({rpt.passed_entries}/{rpt.srt_total_entries} entries)\n"
236
+ batch_results.append((txt_name, True))
237
+ elif rpt.overall_status == "WARN":
238
+ log += f"[{ts()}] ⚠️ CẢNH BÁO: {txt_name}\n"
239
+ log += format_validation_report(rpt) + "\n"
240
+ batch_results.append((txt_name, False))
241
+ else:
242
+ log += f"[{ts()}] ❌ LỖI: {txt_name} — MẤT DỮ LIỆU!\n"
243
+ log += format_validation_report(rpt) + "\n"
244
+ batch_results.append((txt_name, False))
245
+ yield log
246
+ else:
247
+ log += f"[{ts()}] ⚠️ {txt_name}: MP3 hoặc SRT chưa được tạo ra!\n"; yield log
248
+ batch_results.append((txt_name, False))
249
+
250
+ gc.collect()
251
+ if torch and torch.cuda.is_available():
252
+ torch.cuda.empty_cache()
253
+
254
+ progress((total, total), desc="Done")
255
+
256
+ # ── FINAL BATCH SUMMARY ────────────────────────────────────────────
257
+ n_pass = sum(1 for _, ok in batch_results if ok)
258
+ n_fail = len(batch_results) - n_pass
259
+ log += f"\n{'='*60}\n"
260
+ log += f"[{ts()}] 🏁 KẼT QUẢ BATCH TXT: {n_pass}/{len(batch_results)} file ĐẨ QUA KIỂM TRA\n"
261
+ if n_fail > 0:
262
+ log += f" ❌ {n_fail} file có vấn đề — xem chi tiết ở trên:\n"
263
+ for name, ok in batch_results:
264
+ if not ok:
265
+ log += f" • {name}\n"
266
+ else:
267
+ log += f" ✅ Tất cả {n_pass} file ĐẦY ĐỦ & TOÀN VẸN — SẢN PHẨM SẴN SÀNG GIAO!\n"
268
+ log += f"{'='*60}\n"
269
+ yield log
source/qwen_app/mode_omni_batch.py ADDED
@@ -0,0 +1,650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/mode_omni_batch.py
2
+ """
3
+ OmniVoice Batch TXT Pipeline — VN + Global (600+ Languages)
4
+ =============================================================
5
+ Uses OmniVoice NATIVE long-form generation with Macro Chunking (3000 chars)
6
+ for memory safety (Anti-OOM) while preserving strong emotional context.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import gc
12
+ import logging
13
+ import os
14
+ import re
15
+ import sys
16
+ import subprocess
17
+ import time
18
+ import traceback
19
+ import uuid
20
+ from datetime import timedelta
21
+ from typing import Generator, List, Optional
22
+
23
+ import numpy as np
24
+ import soundfile as sf
25
+ import gradio as gr
26
+
27
+ try:
28
+ import torch
29
+ _TORCH = torch
30
+ except ImportError:
31
+ _TORCH = None # type: ignore
32
+
33
+ from .omni_engine import (
34
+ omni_engine,
35
+ SILENCE_THRESHOLD,
36
+ get_available_vram_gb,
37
+ )
38
+ from .prosody import PauseConfig, DEFAULT_PAUSE, make_silence, detect_pause_ms
39
+
40
+ try:
41
+ from .text_cleaner import preprocess_for_tts
42
+ _TEXT_CLEANER_AVAILABLE = True
43
+ except ImportError:
44
+ _TEXT_CLEANER_AVAILABLE = False
45
+
46
+ from .audio_validator import (
47
+ validate_audio_vs_srt,
48
+ format_validation_report,
49
+ check_array_energy,
50
+ )
51
+
52
+ logger = logging.getLogger("qwen_app.mode_omni_batch")
53
+
54
+ # ─── Constants ────────────────────────────────────────────────────────────────
55
+ AUTO_OUTPUT_FOLDER = "_OUTPUT_OMNI"
56
+ MAX_SRT_CHARS = 80
57
+
58
+
59
+ # ─── Helpers ─────────────────────────────────────────────────────────────────
60
+
61
+ def _ts() -> str:
62
+ return time.strftime("%H:%M:%S")
63
+
64
+
65
+ def _fmt_ts(seconds: float) -> str:
66
+ s = max(0.0, seconds)
67
+ td = timedelta(seconds=s)
68
+ total = int(td.total_seconds())
69
+ h, rem = divmod(total, 3600)
70
+ m, sec = divmod(rem, 60)
71
+ ms = int(td.microseconds / 1000)
72
+ return f"{h:02}:{m:02}:{sec:02},{ms:03}"
73
+
74
+
75
+ def _clean_text(text: str) -> str:
76
+ """Minimal cleaning: strip, collapse whitespace."""
77
+ text = text.strip()
78
+ text = re.sub(r"\r\n|\r", "\n", text)
79
+ text = re.sub(r"([.,!?…])([^\W\d_])", r"\1 \2", text)
80
+ text = re.sub(r"[ \t]+", " ", text)
81
+ return text
82
+
83
+
84
+ def _is_speakable(text: str) -> bool:
85
+ return bool(re.search(r"\w", text))
86
+
87
+
88
+ def _is_vietnamese(language: str) -> bool:
89
+ return language.lower() in ("vietnamese", "tiếng việt", "vi", "vie")
90
+
91
+
92
+ def _preprocess_text(text: str, language: str = "auto") -> str:
93
+ """Full preprocessing: universal clean + language-specific normalization."""
94
+ if _TEXT_CLEANER_AVAILABLE:
95
+ try:
96
+ return preprocess_for_tts(text, language=language)
97
+ except Exception as e:
98
+ logger.warning(f"[mode_omni_batch] text_cleaner failed: {e} — passthrough")
99
+ return text
100
+ return text
101
+
102
+
103
+ # ─── Macro Chunker ─────────────────────────────────────
104
+
105
+ def omni_smart_chunk_text(text: str, max_chars: int = 3000, language: str = "auto") -> List[str]:
106
+ """
107
+ Split text into large blocks (macro chunks) to prevent OOM
108
+ while maintaining massive emotional context.
109
+ """
110
+ clean = (text or "").strip()
111
+ if not clean:
112
+ return []
113
+
114
+ def has_cjk(value: str) -> bool:
115
+ return bool(re.search(r"[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]", value))
116
+
117
+ is_cjk = has_cjk(clean)
118
+
119
+ pattern = r'([.!?…।؟。!?]+[\"\u0027\u201c\u201d\u2018\u2019]?(?:[ \t]+|\n+|$))'
120
+ parts = re.split(pattern, clean)
121
+ raw_parts = []
122
+ for i in range(0, len(parts) - 1, 2):
123
+ sent = parts[i] + parts[i+1]
124
+ if sent.strip():
125
+ raw_parts.append(sent.strip())
126
+ if len(parts) % 2 != 0 and parts[-1].strip():
127
+ raw_parts.append(parts[-1].strip())
128
+
129
+ sentences: List[str] = []
130
+ for part in raw_parts:
131
+ sub = [s.strip() for s in part.splitlines() if s.strip()]
132
+ sentences.extend(sub if sub else [part])
133
+
134
+ chunks: List[str] = []
135
+ buffer = ""
136
+
137
+ def _len(t: str) -> int:
138
+ return len(re.sub(r"\s+", "", t)) if is_cjk else len(t)
139
+
140
+ for sent in sentences:
141
+ if not sent:
142
+ continue
143
+ sent_len = _len(sent)
144
+ if not buffer:
145
+ buffer = sent
146
+ elif _len(buffer) + sent_len + 1 <= max_chars + 50:
147
+ buffer = buffer + " " + sent
148
+ else:
149
+ chunks.append(buffer)
150
+ buffer = sent
151
+
152
+ if buffer:
153
+ chunks.append(buffer)
154
+
155
+ return chunks if chunks else ([clean] if clean else [])
156
+
157
+
158
+ # ─── Smart SRT sub-splitter ──────────────────────────────────────────────────
159
+
160
+ def _split_srt_text(text: str, max_chars: int = MAX_SRT_CHARS) -> List[str]:
161
+ text = text.strip()
162
+ if not text:
163
+ return []
164
+ if len(text) <= max_chars:
165
+ return [text]
166
+
167
+ sentence_pat = re.compile(r'([.!?…।؟。!?]+["\u2018\u2019\u201c\u201d]?(?:\s+|$))')
168
+ parts = sentence_pat.split(text)
169
+ sentences: List[str] = []
170
+ for i in range(0, len(parts) - 1, 2):
171
+ sent = (parts[i] + parts[i + 1]).strip()
172
+ if sent:
173
+ sentences.append(sent)
174
+ if len(parts) % 2 != 0 and parts[-1].strip():
175
+ sentences.append(parts[-1].strip())
176
+
177
+ if not sentences:
178
+ sentences = [text]
179
+
180
+ result: List[str] = []
181
+ buffer = ""
182
+ for sent in sentences:
183
+ if not buffer:
184
+ buffer = sent
185
+ elif len(buffer) + 1 + len(sent) <= max_chars:
186
+ buffer = buffer + " " + sent
187
+ else:
188
+ result.append(buffer)
189
+ buffer = sent
190
+
191
+ if buffer:
192
+ result.append(buffer)
193
+
194
+ final: List[str] = []
195
+ for piece in result:
196
+ if len(piece) <= max_chars:
197
+ final.append(piece)
198
+ else:
199
+ words = piece.split()
200
+ sub_lines = []
201
+ line = ""
202
+ for w in words:
203
+ if not line:
204
+ line = w
205
+ elif len(line) + 1 + len(w) <= max_chars:
206
+ line += " " + w
207
+ else:
208
+ sub_lines.append(line)
209
+ line = w
210
+ if line:
211
+ sub_lines.append(line)
212
+
213
+ # Balance trailing words to avoid completely isolated 1-2 word SRT blocks
214
+ while len(sub_lines) >= 2:
215
+ prev = sub_lines[-2].split()
216
+ curr = sub_lines[-1].split()
217
+ if len(sub_lines[-1]) < len(sub_lines[-2]) - 15 and len(prev) > 1:
218
+ word = prev.pop()
219
+ new_curr = word + " " + " ".join(curr)
220
+ new_prev = " ".join(prev)
221
+ if len(new_curr) <= max_chars:
222
+ sub_lines[-2] = new_prev
223
+ sub_lines[-1] = new_curr
224
+ continue
225
+ break
226
+
227
+ final.extend(sub_lines)
228
+
229
+ return final if final else [text]
230
+
231
+
232
+ # ─── Main batch function ──────────────────────────────────────────────────────
233
+
234
+ def process_omni_batch_txt(
235
+ txt_paths_str: str,
236
+ omni_voice_name: str,
237
+ speed: float = 1.0,
238
+ do_norm: bool = True,
239
+ num_step: int = 32,
240
+ language: str = "auto",
241
+ use_flash_attn: bool = False,
242
+ use_flash_whl: str = "",
243
+ enable_precheck: bool = True,
244
+ precheck_punct: str = ".,!?;:。?!…",
245
+ precheck_max_len: int = 400,
246
+ # Prosodic pause config
247
+ pause_sentence_ms: int = 500,
248
+ pause_comma_ms: int = 180,
249
+ pause_semicolon_ms: int = 300,
250
+ pause_colon_ms: int = 250,
251
+ pause_ellipsis_ms: int = 700,
252
+ pause_newline_ms: int = 600,
253
+ pause_default_ms: int = 80,
254
+ progress=gr.Progress(),
255
+ ) -> Generator[str, None, None]:
256
+
257
+ t_batch_start = time.perf_counter()
258
+
259
+ pause_cfg = PauseConfig(
260
+ sentence_ms=int(pause_sentence_ms),
261
+ comma_ms=int(pause_comma_ms),
262
+ semicolon_ms=int(pause_semicolon_ms),
263
+ colon_ms=int(pause_colon_ms),
264
+ ellipsis_ms=int(pause_ellipsis_ms),
265
+ newline_ms=int(pause_newline_ms),
266
+ default_ms=int(pause_default_ms),
267
+ )
268
+
269
+ is_vn = _is_vietnamese(language)
270
+ lang_label = "Tiếng Việt" if is_vn else language.upper()
271
+
272
+ log = f"[{_ts()}] 🌍 BẮT ĐẦU OMNI HYBRID BATCH ({lang_label} — OmniVoice 600+ Lang)...\n"
273
+ logger.info("[mode_omni_batch] ═══ process_omni_batch_txt START ═══")
274
+ yield log
275
+
276
+ from .voice_library_vi import resolve_vi_ref, NONE_CHOICE
277
+ if not omni_voice_name or omni_voice_name == NONE_CHOICE:
278
+ log += f"[{_ts()}] ❌ LỖI: Chưa chọn voice!\n"
279
+ yield log
280
+ return
281
+
282
+ ref_audio_path, ref_text = resolve_vi_ref(omni_voice_name)
283
+ if ref_audio_path is None:
284
+ log += f"[{_ts()}] ❌ LỖI: Voice '{omni_voice_name}' không tìm thấy file audio!\n"
285
+ yield log
286
+ return
287
+
288
+ log += f"[{_ts()}] 🎤 Voice: {omni_voice_name}\n"
289
+ log += f"[{_ts()}] 🌐 Language: {lang_label}\n"
290
+ yield log
291
+
292
+ folders = [p.strip() for p in (txt_paths_str or "").split("\n")
293
+ if p.strip() and os.path.isdir(p.strip())]
294
+ if not folders:
295
+ log += f"[{_ts()}] ❌ LỖI: Không tìm thấy thư mục hợp lệ!\n"
296
+ yield log
297
+ return
298
+
299
+ log += f"[{_ts()}] 🔎 Quét file .txt...\n"
300
+ yield log
301
+
302
+ valid_txts = []
303
+ for d in folders:
304
+ for root, _, files in os.walk(d):
305
+ if AUTO_OUTPUT_FOLDER in root:
306
+ continue
307
+ for f in sorted(files):
308
+ if not f.lower().endswith(".txt"):
309
+ continue
310
+ path = os.path.join(root, f)
311
+ try:
312
+ with open(path, "r", encoding="utf-8") as fh:
313
+ raw = fh.read()
314
+ content = _clean_text(raw)
315
+ if content and _is_speakable(content):
316
+ valid_txts.append({"path": path, "content": content, "folder": d})
317
+ except Exception as scan_err:
318
+ continue
319
+
320
+ if not valid_txts:
321
+ log += f"[{_ts()}] ❌ Không tìm thấy file TXT có chữ hợp lệ!\n"
322
+ yield log
323
+ return
324
+
325
+ log += f"[{_ts()}] ✅ Tìm thấy {len(valid_txts)} file TXT.\n"
326
+
327
+ vram = get_available_vram_gb()
328
+ if vram >= 11.9: # RTX 3060 12GB → props.total_memory/1024^3 = 11.999...
329
+ macro_chunk_size = 3000
330
+ elif vram >= 8.0:
331
+ macro_chunk_size = 2000
332
+ elif vram >= 6.0:
333
+ macro_chunk_size = 1200
334
+ elif vram > 0:
335
+ macro_chunk_size = 800
336
+ else:
337
+ macro_chunk_size = 2000
338
+
339
+ log += f"[{_ts()}] ℹ️ GPU VRAM: {vram:.1f}GB ➜ Auto Macro Chunk: {macro_chunk_size} ký tự/block.\n"
340
+ yield log
341
+
342
+ log += f"[{_ts()}] ⏳ Load OmniVoice (600+ ngôn ngữ)...\n"
343
+ yield log
344
+
345
+ def _eng_log(msg: str):
346
+ nonlocal log
347
+ clean = msg.strip()
348
+ log += f" {clean}\n"
349
+
350
+ try:
351
+ omni_engine.load(use_flash_attn=use_flash_attn, flash2_whl=use_flash_whl, log_callback=_eng_log)
352
+ except Exception as e:
353
+ tb = traceback.format_exc()
354
+ log += f"[{_ts()}] ❌ Load model thất bại: {e}\n 📋 {tb}\n"
355
+ yield log
356
+ return
357
+
358
+ total = len(valid_txts)
359
+ batch_results = []
360
+
361
+ for i, item in enumerate(valid_txts):
362
+ progress((i, total), desc=f"{i+1}/{total}...")
363
+ txt_path = item["path"]
364
+ content = item["content"]
365
+ txt_name = os.path.basename(txt_path)
366
+ txt_base = os.path.splitext(txt_name)[0]
367
+
368
+ out_dir = os.path.join(item["folder"], AUTO_OUTPUT_FOLDER)
369
+ os.makedirs(out_dir, exist_ok=True)
370
+
371
+ mp3_path = os.path.join(out_dir, f"{txt_base}.mp3")
372
+ srt_path = os.path.join(out_dir, f"{txt_base}.srt")
373
+
374
+ if os.path.exists(mp3_path) and os.path.exists(srt_path):
375
+ log += f"[{_ts()}] ⏭ BỎ QUA (đã có): {txt_name}\n"
376
+ yield log
377
+ continue
378
+
379
+ t_file_start = time.perf_counter()
380
+ log += f"\n[{_ts()}] ▶ Đang xử lý: {txt_name} ({len(content)} ký tự)\n"
381
+ yield log
382
+
383
+ # Pre-check
384
+ if enable_precheck and precheck_punct:
385
+ valid_puncts = [p for p in precheck_punct if p.strip()]
386
+ if valid_puncts:
387
+ has_any = any(p in content for p in valid_puncts)
388
+ if not has_any:
389
+ log += f" ⏭ BỎ QUA (Pre-check): Toàn bộ văn bản không chứa bất kỳ dấu câu nào trong tập [{precheck_punct}]\n"
390
+ yield log
391
+ batch_results.append((txt_name, False))
392
+ continue
393
+
394
+ import re
395
+ escaped = [re.escape(p) for p in valid_puncts]
396
+ pattern = "|".join(escaped)
397
+ segments = re.split(pattern, content)
398
+ failed_precheck = False
399
+ for seg in segments:
400
+ if len(seg.strip()) > precheck_max_len:
401
+ log += f" ⏭ BỎ QUA (Pre-check): Phát hiện đoạn văn quá dài ({len(seg.strip())} ký tự) không có dấu câu.\n"
402
+ failed_precheck = True
403
+ break
404
+
405
+ if failed_precheck:
406
+ yield log
407
+ batch_results.append((txt_name, False))
408
+ continue
409
+
410
+ # Preprocessing
411
+ normalized = _preprocess_text(content, language=language)
412
+ if normalized != content:
413
+ log += f" 🧹 Text cleaned: {len(content)} → {len(normalized)} ký tự\n"
414
+ yield log
415
+
416
+ if not normalized.strip():
417
+ log += f" ⚠️ {txt_name}: Text rỗng sau khi clean — bỏ qua!\n"
418
+ yield log
419
+ batch_results.append((txt_name, False))
420
+ continue
421
+
422
+ # Macro Chunking
423
+ blocks = omni_smart_chunk_text(normalized, max_chars=macro_chunk_size, language=language)
424
+ log += f" ✂️ Text chia làm {len(blocks)} block lớn (max {macro_chunk_size} char) để chống OOM\n"
425
+ yield log
426
+
427
+ phase_arrays: List[np.ndarray] = []
428
+ srt_entries = []
429
+ srt_idx = 1
430
+ global_cursor = 0.0
431
+
432
+ has_fatal = False
433
+
434
+ for b_idx, block_text in enumerate(blocks):
435
+ if not block_text.strip():
436
+ continue
437
+
438
+ log += f" ⏳ Generate Block {b_idx+1}/{len(blocks)} ({len(block_text)} chars)...\n"
439
+ yield log
440
+
441
+ try:
442
+ segment_arrays, sr = omni_engine.infer(
443
+ ref_audio_path=ref_audio_path,
444
+ ref_text=ref_text,
445
+ gen_text=block_text,
446
+ language=language,
447
+ speed=speed,
448
+ num_step=num_step,
449
+ )
450
+ except Exception as infer_err:
451
+ tb = traceback.format_exc()
452
+ log += f" ❌ INFER FAILED block {b_idx+1}: {infer_err}\n"
453
+ has_fatal = True
454
+ break
455
+
456
+ if not segment_arrays:
457
+ log += f" ⚠️ Block {b_idx+1}: Không có audio! Bỏ qua block.\n"
458
+ continue
459
+
460
+ seg_texts = _distribute_text_to_segments(block_text, segment_arrays, sr)
461
+
462
+ for seg_i, (arr, seg_text) in enumerate(zip(segment_arrays, seg_texts)):
463
+ arr_dur = len(arr) / sr
464
+ pause_ms = detect_pause_ms(seg_text, pause_cfg)
465
+ sil = make_silence(pause_ms)
466
+
467
+ phase_arrays.append(arr)
468
+ phase_arrays.append(sil)
469
+
470
+ seg_spd_dur = arr_dur / max(speed, 0.1)
471
+ gap_dur = (pause_ms / 1000.0) / max(speed, 0.1)
472
+
473
+ srt_lines = _split_srt_text(seg_text, MAX_SRT_CHARS)
474
+ n_lines = len(srt_lines)
475
+
476
+ if n_lines == 0:
477
+ global_cursor += seg_spd_dur + gap_dur
478
+ continue
479
+
480
+ total_chars = sum(len(line.strip()) for line in srt_lines)
481
+
482
+ if total_chars == 0:
483
+ line_dur = seg_spd_dur / n_lines
484
+ for li, line_text in enumerate(srt_lines):
485
+ line_start = global_cursor + li * line_dur
486
+ line_end = line_start + line_dur
487
+ srt_entries.append({
488
+ "idx": srt_idx,
489
+ "start": _fmt_ts(line_start),
490
+ "end": _fmt_ts(line_end),
491
+ "text": line_text,
492
+ })
493
+ srt_idx += 1
494
+ global_cursor += seg_spd_dur + gap_dur
495
+ else:
496
+ for line_text in srt_lines:
497
+ line_weight = len(line_text.strip()) / total_chars
498
+ line_dur = seg_spd_dur * line_weight
499
+
500
+ line_start = global_cursor
501
+ line_end = global_cursor + line_dur
502
+
503
+ srt_entries.append({
504
+ "idx": srt_idx,
505
+ "start": _fmt_ts(line_start),
506
+ "end": _fmt_ts(line_end),
507
+ "text": line_text,
508
+ })
509
+ srt_idx += 1
510
+ global_cursor += line_dur
511
+
512
+ global_cursor += gap_dur
513
+
514
+ if _TORCH and _TORCH.cuda.is_available():
515
+ _TORCH.cuda.empty_cache()
516
+
517
+ if has_fatal or not phase_arrays:
518
+ log += f" ❌ {txt_name}: Thất bại ở một hoặc toàn bộ block!\n"
519
+ yield log
520
+ batch_results.append((txt_name, False))
521
+ continue
522
+
523
+ # ── Write WAV → MP3 ──
524
+ cache_dir = os.path.join(out_dir, "_omni_caches", txt_base)
525
+ os.makedirs(cache_dir, exist_ok=True)
526
+ tmp_wav = os.path.join(cache_dir, f"tmp_{uuid.uuid4().hex}.wav")
527
+ try:
528
+ sf.write(tmp_wav, np.concatenate(phase_arrays), sr)
529
+ filt = _build_atempo(speed)
530
+ if do_norm:
531
+ filt.append("loudnorm=I=-16:TP=-1.5:LRA=11")
532
+
533
+ cmd = ["ffmpeg", "-y", "-i", tmp_wav]
534
+ if filt:
535
+ cmd += ["-filter:a", ",".join(filt)]
536
+ cmd += ["-c:a", "libmp3lame", "-b:a", "192k", "-loglevel", "error", mp3_path]
537
+
538
+ ff_flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
539
+ if ff_flags:
540
+ subprocess.run(cmd, check=True, creationflags=ff_flags)
541
+ else:
542
+ subprocess.run(cmd, check=True)
543
+
544
+ if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) < 1024:
545
+ log += f" ⚠️ {txt_name}: MP3 tạo ra bị thiếu hoặc rỗng!\n"
546
+ yield log
547
+ except Exception as e:
548
+ tb = traceback.format_exc()
549
+ log += f" ❌ FFmpeg {txt_name}: {e}\n 📋 {tb}\n"
550
+ yield log
551
+ finally:
552
+ if os.path.exists(tmp_wav):
553
+ try: os.remove(tmp_wav)
554
+ except Exception: pass
555
+
556
+ # ── Write SRT ──
557
+ if srt_entries:
558
+ with open(srt_path, "w", encoding="utf-8") as f:
559
+ for s in srt_entries:
560
+ f.write(f"{s['idx']}\n{s['start']} --> {s['end']}\n{s['text']}\n\n")
561
+
562
+ # ── Auto validate ──
563
+ if os.path.exists(mp3_path) and os.path.exists(srt_path):
564
+ try:
565
+ rpt = validate_audio_vs_srt(mp3_path, srt_path)
566
+ if rpt.overall_status == "PASS":
567
+ log += f"[{_ts()}] ✅ XÁC NHẬN: {txt_name} — ĐẦY ĐỦ ({rpt.passed_entries}/{rpt.srt_total_entries}) [{rpt.audio_duration:.0f}s audio]\n"
568
+ batch_results.append((txt_name, True))
569
+ elif rpt.overall_status == "WARN":
570
+ log += f"[{_ts()}] ⚠️ CẢNH BÁO: {txt_name} — (File MP3 vẫn OK! {rpt.total_issues} vấn đề nhỏ)\n"
571
+ log += format_validation_report(rpt) + "\n"
572
+ batch_results.append((txt_name, True))
573
+ else:
574
+ # FAIL ≠ audio mất — file MP3 vẫn được lưu.
575
+ # Thường là SRT_OVERFLOW (timing drift tích lũy qua nhiều blocks)
576
+ # hoặc MISSING_AUDIO coverage thấp ở vài SRT entries.
577
+ log += f"[{_ts()}] ⚠️ VALIDATION FAIL: {txt_name} — (MP3 OK, SRT timing lệch)\n"
578
+ log += format_validation_report(rpt) + "\n"
579
+ batch_results.append((txt_name, True))
580
+ except Exception as val_err:
581
+ log += f"[{_ts()}] ⚠️ {txt_name}: Validate lỗi (bỏ qua): {val_err}\n"
582
+ batch_results.append((txt_name, True))
583
+ yield log
584
+ else:
585
+ log += f"[{_ts()}] ⚠️ {txt_name}: MP3/SRT lỗi không được tạo.\n"
586
+ yield log
587
+ batch_results.append((txt_name, False))
588
+
589
+ gc.collect()
590
+
591
+ progress((total, total), desc="Done")
592
+
593
+ n_pass = sum(1 for _, ok in batch_results if ok)
594
+ batch_elapsed = time.perf_counter() - t_batch_start
595
+
596
+ log += f"\n{'='*60}\n"
597
+ log += f"[{_ts()}] 🏁 KẾT QUẢ BATCH: {n_pass}/{len(batch_results)} file ĐẠT\n"
598
+ log += f"[{_ts()}] ⏱️ Tổng thời gian: {batch_elapsed:.1f}s\n{'='*60}\n"
599
+ yield log
600
+
601
+
602
+ def _distribute_text_to_segments(full_text: str, segment_arrays: List[np.ndarray], sr: int) -> List[str]:
603
+ if len(segment_arrays) == 1:
604
+ return [full_text.strip()]
605
+ sent_pat = re.compile(r'(?<=[.!?。!?…])\s+|(?<=\n)')
606
+ sentences = [s.strip() for s in sent_pat.split(full_text) if s.strip()]
607
+ if not sentences:
608
+ sentences = [full_text.strip()]
609
+ durations = [len(arr) / sr for arr in segment_arrays]
610
+ total_dur = sum(durations)
611
+ if total_dur <= 0 or len(sentences) == 0:
612
+ return [full_text.strip()] * len(segment_arrays)
613
+
614
+ total_chars = sum(len(s) for s in sentences)
615
+ seg_char_budgets = [max(1, int(d / total_dur * total_chars)) for d in durations]
616
+ seg_texts: List[str] = []
617
+ sent_idx = 0
618
+ for bi, budget in enumerate(seg_char_budgets):
619
+ bucket: List[str] = []
620
+ chars_used = 0
621
+ if bi == len(seg_char_budgets) - 1:
622
+ bucket = sentences[sent_idx:]
623
+ else:
624
+ while sent_idx < len(sentences):
625
+ s = sentences[sent_idx]
626
+ if chars_used == 0 or chars_used + len(s) <= budget + 20:
627
+ bucket.append(s)
628
+ chars_used += len(s)
629
+ sent_idx += 1
630
+ else:
631
+ break
632
+ seg_texts.append(" ".join(bucket).strip() if bucket else "")
633
+ while len(seg_texts) < len(segment_arrays):
634
+ seg_texts.append("")
635
+ return seg_texts[:len(segment_arrays)]
636
+
637
+
638
+ def _build_atempo(speed: float) -> List[str]:
639
+ if abs(speed - 1.0) < 0.01:
640
+ return []
641
+ filters: List[str] = []
642
+ s = float(speed)
643
+ while s > 2.0:
644
+ filters.append("atempo=2.0")
645
+ s /= 2.0
646
+ while s < 0.5:
647
+ filters.append("atempo=0.5")
648
+ s *= 2.0
649
+ filters.append(f"atempo={s:.6f}")
650
+ return filters
source/qwen_app/mode_omni_news.py ADDED
@@ -0,0 +1,944 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/mode_omni_news.py — v1.0 (OmniVoice Phase Batch)
2
+ # ─── Bê nguyên logic Mode3 News Bats từ FAST source sang OMMI ─────────────────
3
+ # Chạy theo dạng PHASE: STORY | PHASE N | text | Prompt N: ...
4
+ # Thay Qwen engine → OmniVoice engine (600+ ngôn ngữ)
5
+ # Output: Per-phase MP3 + FULL_MASTER.srt (giống FAST)
6
+ # Text clean: preprocess_for_tts() (universal + vi_normalizer)
7
+ # Multi-encoding parser: utf-8, utf-8-sig, cp1258, cp1252
8
+ # ──────────────────────────────────────────────────────────────────────────────
9
+
10
+ from __future__ import annotations
11
+
12
+ import gc
13
+ import hashlib
14
+ import logging
15
+ import os
16
+ import re
17
+ import sys
18
+ import subprocess
19
+ import time
20
+ import traceback
21
+ import uuid
22
+ from datetime import timedelta
23
+ from typing import Generator, List, Optional, Tuple
24
+
25
+ import numpy as np
26
+ import soundfile as sf
27
+ import gradio as gr
28
+
29
+ try:
30
+ import torch
31
+ _TORCH = torch
32
+ except ImportError:
33
+ _TORCH = None # type: ignore
34
+
35
+ from .omni_engine import (
36
+ omni_engine,
37
+ get_available_vram_gb,
38
+ SILENCE_THRESHOLD,
39
+ )
40
+ from .prosody import PauseConfig, DEFAULT_PAUSE, make_silence, detect_pause_ms
41
+ from .audio_validator import (
42
+ validate_audio_vs_srt,
43
+ format_validation_report,
44
+ check_array_energy,
45
+ )
46
+
47
+ try:
48
+ from .text_cleaner import preprocess_for_tts
49
+ _TEXT_CLEANER_AVAILABLE = True
50
+ except ImportError:
51
+ _TEXT_CLEANER_AVAILABLE = False
52
+
53
+ logger = logging.getLogger("qwen_app.mode_omni_news")
54
+
55
+ # ─── Constants ────────────────────────────────────────────────────────────────
56
+ AUTO_PROJECT_OUTPUT_FOLDER_NAME = "_OUTPUT_PROJECTS"
57
+ MAX_SRT_CHARS = 80
58
+
59
+
60
+ # ─── Helpers ──────────────────────────────────────────────────────────────────
61
+
62
+ def _ts() -> str:
63
+ return time.strftime("%H:%M:%S")
64
+
65
+
66
+ def _fmt_ts(seconds: float) -> str:
67
+ s = max(0.0, seconds)
68
+ td = timedelta(seconds=s)
69
+ total = int(td.total_seconds())
70
+ h, rem = divmod(total, 3600)
71
+ m, sec = divmod(rem, 60)
72
+ ms = int(td.microseconds / 1000)
73
+ return f"{h:02}:{m:02}:{sec:02},{ms:03}"
74
+
75
+
76
+ def sanitize_filename(name: str) -> str:
77
+ return re.sub(r'[/*?:"<>|]', "", name)
78
+
79
+
80
+ def generate_clean_guid(s: str) -> str:
81
+ return hashlib.sha1(s.encode("utf-8")).hexdigest()[:16]
82
+
83
+
84
+ def _natural_sort_key(s: str):
85
+ return [int(c) if c.isdigit() else c.lower() for c in re.split(r"(\d+)", s)]
86
+
87
+
88
+ def _is_speakable(text: str) -> bool:
89
+ return bool(re.search(r"[a-zA-Z0-9\u00C0-\u1EF9\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]", text))
90
+
91
+
92
+ def _has_cjk(text: str) -> bool:
93
+ return bool(re.search(r"[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]", text))
94
+
95
+
96
+ # ─── Text pre-cleaner (giữ cấu trúc PHASE format, chỉ làm sạch nội dung) ─────
97
+
98
+ def _clean_phase_text(text: str) -> str:
99
+ """Minimal inline cleaner cho text trong PHASE block (trước khi gọi preprocess_for_tts)."""
100
+ if not text:
101
+ return ""
102
+ text = text.replace("…", "...")
103
+ text = re.sub(r'[""]', '"', text)
104
+ text = re.sub(r"['']", "'", text)
105
+ text = re.sub(r"([!?。!?]){2,}", r"\1\1", text)
106
+ text = re.sub(r"([,;،、;:]){2,}", r"\1", text)
107
+ text = re.sub(r"\.{4,}", "...", text)
108
+ text = re.sub(r"([.,!?])([^\W\d_])", r"\1 \2", text)
109
+ text = "".join(ch for ch in text if ch.isprintable() or ch == "\n")
110
+ return re.sub(r"\s+", " ", text).strip()
111
+
112
+
113
+ def _preprocess_phase_text(text: str, language: str = "auto") -> str:
114
+ """Full clean: minimal inline → preprocess_for_tts (text_cleaner + vi_normalizer)."""
115
+ text = _clean_phase_text(text)
116
+ if _TEXT_CLEANER_AVAILABLE:
117
+ try:
118
+ return preprocess_for_tts(text, language=language)
119
+ except Exception as e:
120
+ logger.warning(f"[mode_omni_news] text_cleaner failed: {e} — passthrough")
121
+ return text
122
+
123
+
124
+ # ─── Project Parser (FAST source, multi-encoding) ─────────────────────────────
125
+
126
+ class ProjectParser:
127
+ @staticmethod
128
+ def parse_txt(file_path: str, project_folder_name: str):
129
+ """
130
+ Parse PHASE format:
131
+ STORY | ... PHASE N | text | Prompt N: ... END GAMES
132
+ Multi-encoding: utf-8, utf-8-sig, cp1258, cp1252.
133
+ Returns (phases_list_sorted, None) or (None, None).
134
+ """
135
+ try:
136
+ content = ""
137
+ for enc in ["utf-8", "utf-8-sig", "cp1258", "cp1252"]:
138
+ try:
139
+ with open(file_path, "r", encoding=enc) as f:
140
+ content = f.read()
141
+ break
142
+ except (UnicodeDecodeError, LookupError):
143
+ continue
144
+ if not content:
145
+ with open(file_path, "r", encoding="cp1252", errors="replace") as f:
146
+ content = f.read()
147
+
148
+ if "STORY |" not in content or "END GAMES" not in content:
149
+ return None, None
150
+
151
+ core = content.split("STORY |")[1].split("END GAMES")[0].strip()
152
+ g = generate_clean_guid(
153
+ f"{sanitize_filename(project_folder_name)}_"
154
+ f"{sanitize_filename(os.path.splitext(os.path.basename(file_path))[0])}"
155
+ )
156
+ pattern = re.compile(
157
+ r"PHASE\s+(\d+)\s*\|\s*(.*?)\s*\|\s*Prompt\s*\d+\s*:\s*(.*?)(?=\n\s*PHASE|\Z)",
158
+ re.DOTALL | re.IGNORECASE,
159
+ )
160
+ phases = []
161
+ for m in pattern.findall(core):
162
+ txt = _clean_phase_text(m[1].strip())
163
+ if txt:
164
+ phases.append({
165
+ "id": int(m[0].strip()),
166
+ "text": txt,
167
+ "prompt": m[2].strip(),
168
+ "prompt_name": f"{m[0].strip()}_PHASE_{g}",
169
+ })
170
+ if phases:
171
+ return sorted(phases, key=lambda x: x["id"]), None
172
+ except Exception:
173
+ pass
174
+ return None, None
175
+
176
+
177
+ # ─── Macro Chunker (từ mode_omni_batch, VRAM-aware) ──────────────────────────
178
+
179
+ def _omni_smart_chunk_text(text: str, max_chars: int = 3000) -> List[str]:
180
+ """Split text thành macro blocks để tránh OOM khi infer OmniVoice."""
181
+ clean = (text or "").strip()
182
+ if not clean:
183
+ return []
184
+
185
+ is_cjk = _has_cjk(clean)
186
+ # Lookbehind split: cat SAU dau cau ket thuc
187
+ sentence_end = re.compile(r'(?<=[.!?])[\s]+')
188
+ raw_sents = sentence_end.split(clean)
189
+
190
+ sentences: List[str] = []
191
+ for _s in raw_sents:
192
+ _stripped = _s.strip()
193
+ if not _stripped:
194
+ continue
195
+ for sub in _stripped.splitlines():
196
+ sub = sub.strip()
197
+ if sub:
198
+ sentences.append(sub)
199
+
200
+ if not sentences:
201
+ sentences = [clean]
202
+
203
+ def _len(t: str) -> int:
204
+ return len(re.sub(r"\s+", "", t)) if is_cjk else len(t)
205
+
206
+ chunks: List[str] = []
207
+ buffer = ""
208
+ for sent in sentences:
209
+ if not sent:
210
+ continue
211
+ sent_len = _len(sent)
212
+ if not buffer:
213
+ buffer = sent
214
+ elif _len(buffer) + sent_len + 1 <= max_chars + 50:
215
+ buffer = buffer + " " + sent
216
+ else:
217
+ chunks.append(buffer)
218
+ buffer = sent
219
+ if buffer:
220
+ chunks.append(buffer)
221
+
222
+ return chunks if chunks else ([clean] if clean else [])
223
+
224
+
225
+ # ─── SRT sub-splitter (từ mode_omni_batch) ────────────────────────────────────
226
+
227
+ def _split_srt_text(text: str, max_chars: int = MAX_SRT_CHARS) -> List[str]:
228
+ text = text.strip()
229
+ if not text:
230
+ return []
231
+ if len(text) <= max_chars:
232
+ return [text]
233
+
234
+ sentence_pat = re.compile(r'([.!?…।؟。!?]+["\u2018\u2019\u201c\u201d]?(?:\s+|$))')
235
+ parts = sentence_pat.split(text)
236
+ sentences: List[str] = []
237
+ for i in range(0, len(parts) - 1, 2):
238
+ sent = (parts[i] + parts[i + 1]).strip()
239
+ if sent:
240
+ sentences.append(sent)
241
+ if len(parts) % 2 != 0 and parts[-1].strip():
242
+ sentences.append(parts[-1].strip())
243
+ if not sentences:
244
+ sentences = [text]
245
+
246
+ result: List[str] = []
247
+ buffer = ""
248
+ for sent in sentences:
249
+ if not buffer:
250
+ buffer = sent
251
+ elif len(buffer) + 1 + len(sent) <= max_chars:
252
+ buffer = buffer + " " + sent
253
+ else:
254
+ result.append(buffer)
255
+ buffer = sent
256
+ if buffer:
257
+ result.append(buffer)
258
+
259
+ final: List[str] = []
260
+ for piece in result:
261
+ if len(piece) <= max_chars:
262
+ final.append(piece)
263
+ else:
264
+ words = piece.split()
265
+ sub_lines = []
266
+ line = ""
267
+ for w in words:
268
+ if not line:
269
+ line = w
270
+ elif len(line) + 1 + len(w) <= max_chars:
271
+ line += " " + w
272
+ else:
273
+ sub_lines.append(line)
274
+ line = w
275
+ if line:
276
+ sub_lines.append(line)
277
+
278
+ # Balance trailing words to avoid completely isolated 1-2 word SRT blocks
279
+ while len(sub_lines) >= 2:
280
+ prev = sub_lines[-2].split()
281
+ curr = sub_lines[-1].split()
282
+ if len(sub_lines[-1]) < len(sub_lines[-2]) - 15 and len(prev) > 1:
283
+ word = prev.pop()
284
+ new_curr = word + " " + " ".join(curr)
285
+ new_prev = " ".join(prev)
286
+ if len(new_curr) <= max_chars:
287
+ sub_lines[-2] = new_prev
288
+ sub_lines[-1] = new_curr
289
+ continue
290
+ break
291
+
292
+ final.extend(sub_lines)
293
+
294
+ return final if final else [text]
295
+
296
+
297
+ # ─── Distribute text to OmniVoice segments (từ mode_omni_batch) ───────────────
298
+
299
+ def _distribute_text_to_segments(
300
+ full_text: str, segment_arrays: List[np.ndarray], sr: int
301
+ ) -> List[str]:
302
+ if len(segment_arrays) == 1:
303
+ return [full_text.strip()]
304
+ sent_pat = re.compile(r"(?<=[.!?。!?…])\s+|(?<=\n)")
305
+ sentences = [s.strip() for s in sent_pat.split(full_text) if s.strip()]
306
+ if not sentences:
307
+ sentences = [full_text.strip()]
308
+ durations = [len(arr) / sr for arr in segment_arrays]
309
+ total_dur = sum(durations)
310
+ if total_dur <= 0 or not sentences:
311
+ return [full_text.strip()] * len(segment_arrays)
312
+
313
+ total_chars = sum(len(s) for s in sentences)
314
+ seg_char_budgets = [max(1, int(d / total_dur * total_chars)) for d in durations]
315
+ seg_texts: List[str] = []
316
+ sent_idx = 0
317
+ for bi, budget in enumerate(seg_char_budgets):
318
+ bucket: List[str] = []
319
+ chars_used = 0
320
+ if bi == len(seg_char_budgets) - 1:
321
+ bucket = sentences[sent_idx:]
322
+ else:
323
+ while sent_idx < len(sentences):
324
+ s = sentences[sent_idx]
325
+ if chars_used == 0 or chars_used + len(s) <= budget + 20:
326
+ bucket.append(s)
327
+ chars_used += len(s)
328
+ sent_idx += 1
329
+ else:
330
+ break
331
+ seg_texts.append(" ".join(bucket).strip() if bucket else "")
332
+ while len(seg_texts) < len(segment_arrays):
333
+ seg_texts.append("")
334
+ return seg_texts[: len(segment_arrays)]
335
+
336
+
337
+ # ─── FFmpeg: WAV → MP3 ───────────────────────────────────────────────────────
338
+
339
+ def _build_atempo(speed: float) -> List[str]:
340
+ if abs(speed - 1.0) < 0.01:
341
+ return []
342
+ filters: List[str] = []
343
+ s = float(speed)
344
+ while s > 2.0:
345
+ filters.append("atempo=2.0")
346
+ s /= 2.0
347
+ while s < 0.5:
348
+ filters.append("atempo=0.5")
349
+ s *= 2.0
350
+ filters.append(f"atempo={s:.6f}")
351
+ return filters
352
+
353
+
354
+ def _wav_to_mp3(tmp_wav: str, mp3_out: str, speed: float, do_norm: bool) -> bool:
355
+ cmd = ["ffmpeg", "-y", "-i", tmp_wav]
356
+ filt = _build_atempo(speed)
357
+ if do_norm:
358
+ filt.append("loudnorm=I=-16:TP=-1.5:LRA=11")
359
+ if filt:
360
+ cmd += ["-filter:a", ",".join(filt)]
361
+ cmd += ["-c:a", "libmp3lame", "-b:a", "192k", "-loglevel", "error", mp3_out]
362
+ try:
363
+ ff_flags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
364
+ subprocess.run(cmd, check=True, creationflags=ff_flags)
365
+ return os.path.exists(mp3_out) and os.path.getsize(mp3_out) >= 1024
366
+ except Exception:
367
+ return False
368
+
369
+
370
+ # ─── SRT writer ───────────────────────────────────────────────────────────────
371
+
372
+ def _write_srt(path: str, entries: list):
373
+ with open(path, "w", encoding="utf-8") as f:
374
+ for s in entries:
375
+ f.write(f"{s['idx']}\n{s['start']} --> {s['end']}\n{s['text']}\n\n")
376
+
377
+
378
+ # ─── Main batch function ──────────────────────────────────────────────────────
379
+
380
+ def process_omni_news_batch(
381
+ txt_paths_str: str,
382
+ omni_voice_name: str,
383
+ speed: float = 1.0,
384
+ do_norm: bool = True,
385
+ num_step: int = 32,
386
+ language: str = "auto",
387
+ use_flash_attn: bool = False,
388
+ use_flash_whl: str = "",
389
+ enable_precheck: bool = True,
390
+ precheck_punct: str = ".,!?;:。?!…",
391
+ precheck_max_len: int = 400,
392
+ # Prosodic pause config
393
+ pause_sentence_ms: int = 500,
394
+ pause_comma_ms: int = 180,
395
+ pause_semicolon_ms: int = 300,
396
+ pause_colon_ms: int = 250,
397
+ pause_ellipsis_ms: int = 700,
398
+ pause_newline_ms: int = 600,
399
+ pause_default_ms: int = 80,
400
+ progress=gr.Progress(),
401
+ ) -> Generator[str, None, None]:
402
+
403
+ t_batch_start = time.perf_counter()
404
+
405
+ pause_cfg = PauseConfig(
406
+ sentence_ms=int(pause_sentence_ms),
407
+ comma_ms=int(pause_comma_ms),
408
+ semicolon_ms=int(pause_semicolon_ms),
409
+ colon_ms=int(pause_colon_ms),
410
+ ellipsis_ms=int(pause_ellipsis_ms),
411
+ newline_ms=int(pause_newline_ms),
412
+ default_ms=int(pause_default_ms),
413
+ )
414
+
415
+ lang_label = language.upper() if language and language.lower() != "auto" else "AUTO"
416
+ log = f"[{_ts()}] 🚀 BẮT ĐẦU OMNI NEWS BATCH (Phase Mode — OmniVoice 600+ Lang)...\n"
417
+ log += f"[{_ts()}] 🌐 Language: {lang_label}\n"
418
+ yield log
419
+
420
+ # ── Resolve voice ──────────────────────────────────────────────────────────
421
+ from .voice_library_vi import resolve_vi_ref, NONE_CHOICE
422
+ if not omni_voice_name or omni_voice_name == NONE_CHOICE:
423
+ log += f"[{_ts()}] ❌ LỖI: Chưa chọn voice!\n"
424
+ yield log
425
+ return
426
+
427
+ ref_audio_path, ref_text = resolve_vi_ref(omni_voice_name)
428
+ if ref_audio_path is None:
429
+ log += f"[{_ts()}] ❌ LỖI: Voice '{omni_voice_name}' không tìm thấy file audio!\n"
430
+ yield log
431
+ return
432
+
433
+ log += f"[{_ts()}] 🎤 Voice: {omni_voice_name}\n"
434
+ yield log
435
+
436
+ # ── Validate paths ─────────────────────────────────────────────────────────
437
+ folders = [p.strip() for p in (txt_paths_str or "").split("\n")
438
+ if p.strip() and os.path.isdir(p.strip())]
439
+ if not folders:
440
+ log += f"[{_ts()}] ❌ LỖI: Không tìm thấy thư mục hợp lệ!\n"
441
+ yield log
442
+ return
443
+
444
+ # ── Scan TXT files (PHASE format) ─────────────────────────────────────────
445
+ log += f"[{_ts()}] 🔎 Quét file .txt theo chuẩn PHASE...\n"
446
+ yield log
447
+
448
+ valid_txts = []
449
+ for d in folders:
450
+ for root, _, files in os.walk(d):
451
+ if AUTO_PROJECT_OUTPUT_FOLDER_NAME in root:
452
+ continue
453
+ for f in sorted(files, key=_natural_sort_key):
454
+ if not f.lower().endswith(".txt"):
455
+ continue
456
+ path = os.path.join(root, f)
457
+ phases, _ = ProjectParser.parse_txt(
458
+ path, os.path.basename(os.path.dirname(path))
459
+ )
460
+ if phases:
461
+ valid_txts.append({
462
+ "path": path,
463
+ "group": os.path.basename(os.path.normpath(d)),
464
+ "phases": phases,
465
+ })
466
+
467
+ if not valid_txts:
468
+ log += f"[{_ts()}] ❌ Không tìm thấy Story nào theo chuẩn PHASE (STORY | ... END GAMES)!\n"
469
+ log += f"[{_ts()}] ℹ️ Định dạng cần có: STORY | ... PHASE N | nội dung | Prompt N: ... END GAMES\n"
470
+ yield log
471
+ return
472
+
473
+ log += f"[{_ts()}] ✅ Tìm thấy {len(valid_txts)} story hợp lệ.\n"
474
+ yield log
475
+
476
+ # ── VRAM-aware macro chunk size ────────────────────────────────────────────
477
+ vram = get_available_vram_gb()
478
+ if vram >= 11.9:
479
+ macro_chunk_size = 3000
480
+ elif vram >= 8.0:
481
+ macro_chunk_size = 2000
482
+ elif vram >= 6.0:
483
+ macro_chunk_size = 1200
484
+ elif vram > 0:
485
+ macro_chunk_size = 800
486
+ else:
487
+ macro_chunk_size = 2000
488
+
489
+ log += f"[{_ts()}] ℹ️ GPU VRAM: {vram:.1f}GB ➜ Macro Chunk: {macro_chunk_size} ký tự/block.\n"
490
+ yield log
491
+
492
+ # ── Load OmniVoice ─────────────────────────────────────────────────────────
493
+ log += f"[{_ts()}] ⏳ Load OmniVoice (600+ ngôn ngữ)...\n"
494
+ yield log
495
+
496
+ def _eng_log(msg: str):
497
+ nonlocal log
498
+ log += f" {msg.strip()}\n"
499
+
500
+ try:
501
+ omni_engine.load(use_flash_attn=use_flash_attn, flash2_whl=use_flash_whl, log_callback=_eng_log)
502
+ yield log
503
+ except Exception as e:
504
+ tb = traceback.format_exc()
505
+ log += f"[{_ts()}] ❌ Load model thất bại: {e}\n 📋 {tb}\n"
506
+ yield log
507
+ return
508
+
509
+ log += f"[{_ts()}] ✅ OmniVoice sẵn sàng!\n"
510
+ yield log
511
+
512
+ CACHE_DIR = os.path.join(
513
+ os.path.dirname(os.path.abspath(__file__)), "..", "Qwen_Mode3_Cache"
514
+ )
515
+ os.makedirs(CACHE_DIR, exist_ok=True)
516
+
517
+ total = len(valid_txts)
518
+ batch_results = [] # (txt_name, passed: bool)
519
+
520
+ # ═══════════════════════════════════════════════════════════════════════════
521
+ for i, item in enumerate(valid_txts):
522
+ progress((i, total), desc=f"{i+1}/{total}...")
523
+ txt_path = item["path"]
524
+ phases = item["phases"]
525
+ txt_name = os.path.basename(txt_path)
526
+ txt_base = os.path.splitext(txt_name)[0]
527
+ proj_dir = os.path.dirname(txt_path)
528
+ out_dir = os.path.join(proj_dir, AUTO_PROJECT_OUTPUT_FOLDER_NAME, sanitize_filename(txt_base))
529
+ os.makedirs(out_dir, exist_ok=True)
530
+
531
+ # Skip-if-done: kiểm tra per-phase MP3 + FULL_MASTER.srt
532
+ srt_master_path = os.path.join(out_dir, "FULL_MASTER.srt")
533
+ all_done = all(
534
+ os.path.exists(os.path.join(out_dir, f"{p['prompt_name']}.mp3"))
535
+ for p in phases
536
+ ) and os.path.exists(srt_master_path)
537
+
538
+ if all_done:
539
+ log += f"[{_ts()}] ⏭ BỎ QUA (đã hoàn thành): {txt_name}\n"
540
+ yield log
541
+ continue
542
+
543
+ log += f"\n[{_ts()}] ▶ [{item['group']}] → {txt_name} ({len(phases)} phase(s))\n"
544
+ yield log
545
+
546
+ # Pre-check
547
+ if enable_precheck and precheck_punct:
548
+ valid_puncts = [p for p in precheck_punct if p.strip()]
549
+ if valid_puncts:
550
+ full_text = " ".join([p["text"] for p in phases])
551
+ has_any = any(p in full_text for p in valid_puncts)
552
+ if not has_any:
553
+ log += f" ⏭ BỎ QUA (Pre-check): Toàn bộ story không chứa bất kỳ dấu câu nào trong tập [{precheck_punct}]\n"
554
+ yield log
555
+ batch_results.append((txt_name, False))
556
+ continue
557
+
558
+ import re
559
+ escaped = [re.escape(p) for p in valid_puncts]
560
+ pattern = "|".join(escaped)
561
+ segments = re.split(pattern, full_text)
562
+ failed_precheck = False
563
+ for seg in segments:
564
+ if len(seg.strip()) > precheck_max_len:
565
+ log += f" ⏭ BỎ QUA (Pre-check): Phát hiện đoạn văn quá dài ({len(seg.strip())} ký tự) không có dấu câu.\n"
566
+ failed_precheck = True
567
+ break
568
+
569
+ if failed_precheck:
570
+ yield log
571
+ batch_results.append((txt_name, False))
572
+ continue
573
+
574
+ # Accumulate master SRT across all phases
575
+ master_srt_entries = []
576
+ master_srt_idx = 1
577
+ master_cursor = 0.0
578
+ _phase_tmp_srts = {}
579
+
580
+ story_passed = True
581
+
582
+ # ─── 1. Preprocess and filter phases ──────────────────────────────────
583
+ active_phases = []
584
+ for phase in phases:
585
+ raw_text = phase["text"]
586
+ if not _is_speakable(raw_text):
587
+ continue
588
+
589
+ phase_mp3 = os.path.join(out_dir, f"{phase['prompt_name']}.mp3")
590
+ phase_srt_tmp = os.path.join(CACHE_DIR, f"phase_srt_{uuid.uuid4().hex}.srt")
591
+ _phase_tmp_srts[phase["prompt_name"]] = phase_srt_tmp
592
+
593
+ # Skip individual phase if MP3 already exists
594
+ if os.path.exists(phase_mp3):
595
+ log += f" ⏭ Phase {phase['id']}: MP3 có sẵn, bỏ qua\n"
596
+ yield log
597
+ try:
598
+ from .audio_validator import _load_audio_as_mono
599
+ _d, _sr = _load_audio_as_mono(phase_mp3)
600
+ master_cursor += len(_d) / _sr
601
+ except Exception:
602
+ pass
603
+ continue
604
+
605
+ # Preprocess text
606
+ normalized = _preprocess_phase_text(raw_text, language=language)
607
+ if normalized != raw_text:
608
+ log += f" 🧹 Phase {phase['id']}: text cleaned {len(raw_text)} → {len(normalized)} ký tự\n"
609
+ yield log
610
+
611
+ if not normalized.strip():
612
+ log += f" ⚠️ Phase {phase['id']}: text rỗng sau clean — bỏ qua!\n"
613
+ yield log
614
+ continue
615
+
616
+ phase["normalized_text"] = normalized
617
+ phase["audio_arrays"] = []
618
+ phase["phase_entries"] = []
619
+ phase["phase_mp3"] = phase_mp3
620
+ phase["phase_srt_tmp"] = phase_srt_tmp
621
+ active_phases.append(phase)
622
+
623
+ # ─── 2. Group into macro blocks ───────────────────────────────────────
624
+ macro_blocks = []
625
+ current_group = []
626
+ current_len = 0
627
+ for phase in active_phases:
628
+ # Add 2 chars for "\n\n" separator between phases
629
+ l = len(phase["normalized_text"]) + (2 if current_group else 0)
630
+ if current_len + l > macro_chunk_size and current_group:
631
+ macro_blocks.append(current_group)
632
+ current_group = [phase]
633
+ current_len = len(phase["normalized_text"])
634
+ else:
635
+ current_group.append(phase)
636
+ current_len += l
637
+ if current_group:
638
+ macro_blocks.append(current_group)
639
+
640
+ # ─── 3. Group block inference & distribution ──────────────────────────
641
+ for b_idx, group in enumerate(macro_blocks):
642
+ block_text = "\n\n".join(p["normalized_text"] for p in group)
643
+ log += f" ⏳ Group {b_idx+1}/{len(macro_blocks)} ({len(group)} phases, {len(block_text)} chars) → GPU...\n"
644
+ yield log
645
+
646
+ try:
647
+ segment_arrays, sr = omni_engine.infer(
648
+ ref_audio_path=ref_audio_path,
649
+ ref_text=ref_text,
650
+ gen_text=block_text,
651
+ language=language,
652
+ speed=speed,
653
+ num_step=num_step,
654
+ )
655
+ except Exception as infer_err:
656
+ log += f" ❌ INFER FAILED Group {b_idx+1}: {infer_err}\n"
657
+ story_passed = False
658
+ yield log
659
+ continue
660
+
661
+ if not segment_arrays:
662
+ log += f" ⚠️ Group {b_idx+1}: Không có audio! Bỏ qua group.\n"
663
+ continue
664
+
665
+ seg_texts = _distribute_text_to_segments(block_text, segment_arrays, sr)
666
+
667
+ # Sub-distribute back to individual phases within the group
668
+ phase_idx = 0
669
+ chars_remaining = len(re.sub(r'\s+', '', group[phase_idx]["normalized_text"]))
670
+ local_cursor = 0.0
671
+
672
+ # 3a. Break into linear pieces
673
+ pieces = []
674
+
675
+ for seg_i, (arr, seg_text) in enumerate(zip(segment_arrays, seg_texts)):
676
+ pause_ms = detect_pause_ms(seg_text, pause_cfg) if seg_text.strip() else 80
677
+ sil = make_silence(pause_ms)
678
+
679
+ if not seg_text.strip():
680
+ pieces.append({"arr": arr, "sil": sil, "text": seg_text})
681
+ continue
682
+
683
+ srt_lines = _split_srt_text(seg_text, MAX_SRT_CHARS)
684
+ n_lines = len(srt_lines)
685
+
686
+ if n_lines == 0:
687
+ pieces.append({"arr": arr, "sil": sil, "text": ""})
688
+ continue
689
+
690
+ total_chars = sum(len(line.strip()) for line in srt_lines)
691
+ arr_len = len(arr)
692
+ cursor_s = 0
693
+
694
+ if total_chars == 0:
695
+ samples_per_line = arr_len // n_lines
696
+ for li, line_text in enumerate(srt_lines):
697
+ if li == n_lines - 1:
698
+ line_arr = arr[cursor_s:]
699
+ line_sil = sil
700
+ else:
701
+ line_arr = arr[cursor_s : cursor_s + samples_per_line]
702
+ line_sil = np.array([], dtype=np.float32)
703
+ pieces.append({"arr": line_arr, "sil": line_sil, "text": line_text})
704
+ cursor_s += samples_per_line
705
+ else:
706
+ for li, line_text in enumerate(srt_lines):
707
+ weight = len(line_text.strip()) / total_chars
708
+ if li == n_lines - 1:
709
+ line_arr = arr[cursor_s:]
710
+ line_sil = sil
711
+ else:
712
+ samples = int(weight * arr_len)
713
+ line_arr = arr[cursor_s : cursor_s + samples]
714
+ line_sil = np.array([], dtype=np.float32)
715
+ pieces.append({"arr": line_arr, "sil": line_sil, "text": line_text})
716
+ cursor_s += int(weight * arr_len)
717
+
718
+ # 3b. Distribute pieces to phases
719
+ for p in pieces:
720
+ target_phase = group[phase_idx]
721
+ p_arr = p["arr"]
722
+ p_sil = p["sil"]
723
+ p_text = p["text"]
724
+
725
+ target_phase["audio_arrays"].extend([p_arr, p_sil])
726
+
727
+ arr_dur_spd = (len(p_arr) / sr) / max(speed, 0.1)
728
+ sil_dur_spd = (len(p_sil) / sr) / max(speed, 0.1)
729
+
730
+ if p_text.strip():
731
+ line_start = local_cursor
732
+ line_end = local_cursor + arr_dur_spd
733
+ target_phase["phase_entries"].append({
734
+ "start": line_start,
735
+ "end": line_end,
736
+ "text": p_text
737
+ })
738
+
739
+ local_cursor += arr_dur_spd + sil_dur_spd
740
+
741
+ seg_len = len(re.sub(r'\s+', '', p_text))
742
+ chars_remaining -= seg_len
743
+
744
+ while chars_remaining <= 0 and phase_idx < len(group) - 1:
745
+ target_phase["total_phase_dur"] = local_cursor
746
+ phase_idx += 1
747
+ chars_remaining += len(re.sub(r'\s+', '', group[phase_idx]["normalized_text"]))
748
+ local_cursor = 0.0
749
+
750
+ # Store duration of the last advanced phase in group
751
+ if phase_idx < len(group):
752
+ group[phase_idx]["total_phase_dur"] = local_cursor
753
+
754
+ if _TORCH and _TORCH.cuda.is_available():
755
+ _TORCH.cuda.empty_cache()
756
+
757
+ # ─── 4. Output Phase MP3s & Build Master SRT ──────────────────────────
758
+ for phase in active_phases:
759
+ if not phase.get("audio_arrays"):
760
+ log += f" ❌ Phase {phase['id']}: thất bại — không tạo được âm thanh.\n"
761
+ story_passed = False
762
+ yield log
763
+ continue
764
+
765
+ tmp_wav = os.path.join(CACHE_DIR, f"tmp_{uuid.uuid4().hex}.wav")
766
+ # Assume 'sr' from infer() remains identical across standard models.
767
+ try:
768
+ sf.write(tmp_wav, np.concatenate(phase["audio_arrays"]), sr)
769
+ ok = _wav_to_mp3(tmp_wav, phase["phase_mp3"], speed, do_norm)
770
+ if ok:
771
+ log += f" ✅ Phase {phase['id']}: MP3 OK ({len(phase['audio_arrays']) // 2} segments)\n"
772
+ else:
773
+ log += f" ⚠️ Phase {phase['id']}: FFmpeg thất bại hoặc rỗng!\n"
774
+ story_passed = False
775
+ except Exception as e:
776
+ log += f" ❌ Phase {phase['id']} WAV/FFmpeg lỗi: {e}\n"
777
+ story_passed = False
778
+ traceback.print_exc()
779
+ finally:
780
+ if os.path.exists(tmp_wav):
781
+ try: os.remove(tmp_wav)
782
+ except Exception: pass
783
+
784
+ yield log
785
+
786
+ if phase["phase_entries"]:
787
+ formatted_phase_entries = []
788
+ for entry in phase["phase_entries"]:
789
+ line_start = entry["start"]
790
+ line_end = entry["end"]
791
+ line_text = entry["text"]
792
+ _append_srt_entry(
793
+ formatted_phase_entries, master_srt_entries, master_srt_idx,
794
+ line_text, line_start, line_end, master_cursor
795
+ )
796
+ master_srt_idx += 1
797
+
798
+ _write_srt(phase["phase_srt_tmp"], formatted_phase_entries)
799
+
800
+ phase_dur = phase.get("total_phase_dur", 0.0)
801
+ master_cursor += phase_dur
802
+
803
+ # ── Write FULL_MASTER.srt ─────────────────────────────────────────────
804
+ if master_srt_entries:
805
+ _write_srt(srt_master_path, master_srt_entries)
806
+ log += f"[{_ts()}] 📄 FULL_MASTER.srt: {len(master_srt_entries)} entries\n"
807
+ yield log
808
+
809
+ # ═══ BIDIRECTIONAL VALIDATION ════════════════════════════════════════
810
+ log += f"[{_ts()}] 🔍 Validate {len(phases)} phase(s)...\n"
811
+ yield log
812
+ all_phases_ok = True
813
+
814
+ for phase in phases:
815
+ phase_mp3 = os.path.join(out_dir, f"{phase['prompt_name']}.mp3")
816
+ tmp_srt_path = _phase_tmp_srts.get(phase["prompt_name"])
817
+
818
+ if not os.path.exists(phase_mp3):
819
+ log += f" ⚠️ Phase {phase['id']}: MP3 bị thiếu — bỏ qua validate\n"
820
+ all_phases_ok = False
821
+ yield log
822
+ continue
823
+
824
+ if not tmp_srt_path or not os.path.exists(tmp_srt_path):
825
+ log += f" ℹ️ Phase {phase['id']}: đã có từ session trước — bỏ qua validate\n"
826
+ yield log
827
+ continue
828
+
829
+ rpt = validate_audio_vs_srt(phase_mp3, tmp_srt_path)
830
+ pname = f"Phase {phase['id']}"
831
+
832
+ if rpt.overall_status == "PASS":
833
+ log += (
834
+ f" ✅ {pname}: PASS "
835
+ f"({rpt.passed_entries}/{rpt.srt_total_entries} entries OK"
836
+ f", {rpt.audio_duration:.1f}s)\n"
837
+ )
838
+ elif rpt.overall_status == "WARN":
839
+ all_phases_ok = False
840
+ log += f" ⚠️ {pname}: WARN\n"
841
+ log += format_validation_report(rpt) + "\n"
842
+ else:
843
+ all_phases_ok = False
844
+ log += f" ❌ {pname}: FAIL\n"
845
+ log += format_validation_report(rpt) + "\n"
846
+ yield log
847
+
848
+ # Delete temp SRT — output folder stays clean
849
+ try:
850
+ if os.path.exists(tmp_srt_path):
851
+ os.remove(tmp_srt_path)
852
+ except Exception:
853
+ pass
854
+
855
+ # ── Sanity-check FULL_MASTER.srt duration ────────────────────────────
856
+ if os.path.exists(srt_master_path) and master_srt_entries:
857
+ try:
858
+ from .audio_validator import parse_srt as _parse_srt, _load_audio_as_mono
859
+ master_parsed = _parse_srt(srt_master_path)
860
+ if master_parsed:
861
+ expected_end = master_parsed[-1].end
862
+ total_mp3_dur = 0.0
863
+ for phase in phases:
864
+ ph_mp3 = os.path.join(out_dir, f"{phase['prompt_name']}.mp3")
865
+ if os.path.exists(ph_mp3):
866
+ try:
867
+ d, sr_ = _load_audio_as_mono(ph_mp3)
868
+ total_mp3_dur += len(d) / sr_
869
+ except Exception:
870
+ pass
871
+ drift = abs(total_mp3_dur - expected_end)
872
+ if drift < 2.0:
873
+ log += (
874
+ f"[{_ts()}] ✅ FULL_MASTER.srt sanity: "
875
+ f"audio={total_mp3_dur:.1f}s ≈ SRT end={expected_end:.1f}s\n"
876
+ )
877
+ else:
878
+ log += (
879
+ f"[{_ts()}] ⚠️ FULL_MASTER.srt drift: "
880
+ f"audio={total_mp3_dur:.1f}s vs SRT={expected_end:.1f}s "
881
+ f"(Δ={drift:.1f}s)\n"
882
+ )
883
+ all_phases_ok = False
884
+ yield log
885
+ except Exception:
886
+ pass
887
+
888
+ if all_phases_ok:
889
+ log += f"[{_ts()}] ✅ XÁC NHẬN XONG: {txt_name} — ĐẦY ĐỦ & TOÀN VẸN\n"
890
+ story_passed = True
891
+ else:
892
+ log += f"[{_ts()}] ⚠️ NGƯỜI DÙNG CẦN KIỂM TRA: {txt_name} có một số đoạn cần xem lại!\n"
893
+ story_passed = False
894
+ yield log
895
+
896
+ batch_results.append((txt_name, story_passed))
897
+
898
+ gc.collect()
899
+ if _TORCH and _TORCH.cuda.is_available():
900
+ _TORCH.cuda.empty_cache()
901
+
902
+ progress((total, total), desc="Done")
903
+
904
+ # ── FINAL BATCH SUMMARY ────────────────────────────────────────────────────
905
+ n_pass = sum(1 for _, ok in batch_results if ok)
906
+ n_fail = len(batch_results) - n_pass
907
+ elapsed = time.perf_counter() - t_batch_start
908
+ log += f"\n{'='*60}\n"
909
+ log += f"[{_ts()}] 🏁 KẾT QUẢ BATCH: {n_pass}/{len(batch_results)} story ĐÃ QUA KIỂM TRA\n"
910
+ log += f"[{_ts()}] ⏱️ Tổng thời gian: {elapsed:.1f}s\n"
911
+ if n_fail > 0:
912
+ log += f" ❌ {n_fail} story có vấn đề:\n"
913
+ for name, ok in batch_results:
914
+ if not ok:
915
+ log += f" • {name}\n"
916
+ else:
917
+ log += f" ✅ Tất cả {n_pass} story ĐẦY ĐỦ & TOÀN VẸN — SẢN PHẨM SẴN SÀNG GIAO!\n"
918
+ log += f"{'='*60}\n"
919
+ yield log
920
+
921
+
922
+ # ─── Internal SRT entry appender ──────────────────────────────────────────────
923
+
924
+ def _append_srt_entry(
925
+ phase_entries: list,
926
+ master_srt_entries: list,
927
+ master_srt_idx: int,
928
+ text: str,
929
+ local_start: float,
930
+ local_end: float,
931
+ master_cursor: float,
932
+ ):
933
+ phase_entries.append({
934
+ "idx": len(phase_entries) + 1,
935
+ "start": _fmt_ts(local_start),
936
+ "end": _fmt_ts(local_end),
937
+ "text": text,
938
+ })
939
+ master_srt_entries.append({
940
+ "idx": master_srt_idx,
941
+ "start": _fmt_ts(master_cursor + local_start),
942
+ "end": _fmt_ts(master_cursor + local_end),
943
+ "text": text,
944
+ })
source/qwen_app/model_manager.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ qwen_app/model_manager.py
3
+ ==========================
4
+ LazyModelManager — tải torch/huggingface_hub theo yêu cầu (không import ngay khi khởi động).
5
+ Điều này giúp UI xuất hiện ngay lập tức mà không cần chờ PyTorch khởi tạo.
6
+
7
+ Tổng quan:
8
+ - get_model() : tải model lần đầu khi cần, cache lại cho lần sau
9
+ - _unload_all() : giải phóng VRAM khi chuyển model
10
+ - snapshot_paths : cache đường dẫn snapshot HuggingFace
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import time
17
+ import logging
18
+ from typing import Dict, Optional, Tuple
19
+
20
+ logger = logging.getLogger("qwen_app.model_manager")
21
+
22
+ # ─── Constants (resolved lazily) ─────────────────────────────────────────────
23
+
24
+ def _get_device_dtype():
25
+ """Lazy-resolve device and dtype — only import torch when called."""
26
+ import torch # noqa: PLC0415
27
+ device = "cuda" if torch.cuda.is_available() else "cpu"
28
+ dtype = torch.bfloat16 if device == "cuda" else torch.float32
29
+ return device, dtype, device # (device, dtype, device_map)
30
+
31
+
32
+ class LazyModelManager:
33
+ """
34
+ Lazy model loader — torch/huggingface_hub được import chỉ khi cần.
35
+ Safe to instantiate at module-level mà không block startup.
36
+ """
37
+
38
+ def __init__(self):
39
+ self.snapshot_paths: Dict[str, str] = {}
40
+ self.loaded_models: Dict[str, object] = {}
41
+ self.active_model_key: Optional[str] = None
42
+ self._faster_cls = None
43
+ self._faster_available = False
44
+ self._use_faster = os.environ.get("QWEN_USE_FASTER_BACKEND", "1") == "1"
45
+ # NOTE: _init_faster_backend() is deferred to first get_model() call
46
+ self._faster_checked = False
47
+
48
+ # ─── Internal ─────────────────────────────────────────────────────────────
49
+
50
+ def _init_faster_backend(self) -> None:
51
+ """Lazy-init faster backend — called once before first model load."""
52
+ if self._faster_checked:
53
+ return
54
+ self._faster_checked = True
55
+ try:
56
+ import torch # noqa: PLC0415
57
+ if not self._use_faster or not torch.cuda.is_available():
58
+ return
59
+ from faster_qwen3_tts import FasterQwen3TTS # type: ignore
60
+ self._faster_cls = FasterQwen3TTS
61
+ self._faster_available = True
62
+ logger.debug("[model_manager] faster_qwen3_tts backend available ✅")
63
+ except Exception as e:
64
+ self._faster_cls = None
65
+ self._faster_available = False
66
+ logger.debug(f"[model_manager] faster_qwen3_tts not available: {e}")
67
+
68
+ @staticmethod
69
+ def _repo_id(model_type: str, model_size: str) -> str:
70
+ return f"Qwen/Qwen3-TTS-12Hz-{model_size}-{model_type}"
71
+
72
+ def _snapshot_path(self, repo_id: str) -> Tuple[str, str]:
73
+ if repo_id in self.snapshot_paths:
74
+ logger.debug(f"[model_manager] snapshot cache hit: {repo_id}")
75
+ return self.snapshot_paths[repo_id], f"Cache hit: {repo_id}"
76
+ from huggingface_hub import snapshot_download # noqa: PLC0415
77
+ logger.info(f"[model_manager] Downloading snapshot: {repo_id}")
78
+ t0 = time.perf_counter()
79
+ path = snapshot_download(repo_id, local_dir_use_symlinks=False)
80
+ elapsed = time.perf_counter() - t0
81
+ self.snapshot_paths[repo_id] = path
82
+ logger.info(f"[model_manager] snapshot_download done in {elapsed:.2f}s → {path}")
83
+ return path, f"Downloaded: {repo_id}"
84
+
85
+ def _unload_all(self) -> None:
86
+ if not self.loaded_models:
87
+ return
88
+ logger.info(f"[model_manager] Unloading {list(self.loaded_models.keys())} from memory")
89
+ self.loaded_models.clear()
90
+ self.active_model_key = None
91
+ try:
92
+ import torch # noqa: PLC0415
93
+ if torch.cuda.is_available():
94
+ torch.cuda.empty_cache()
95
+ logger.debug("[model_manager] VRAM cache cleared")
96
+ except ImportError:
97
+ pass
98
+
99
+ # ─── Public API ───────────────────────────────────────────────────────────
100
+
101
+ def get_model(self, model_type: str, model_size: str) -> Tuple[object, str]:
102
+ """
103
+ Load (or return cached) model.
104
+ First call imports torch + optionally huggingface_hub.
105
+ Subsequent calls return cached model instantly.
106
+ """
107
+ import torch # noqa: PLC0415
108
+ device = "cuda" if torch.cuda.is_available() else "cpu"
109
+ dtype = torch.bfloat16 if device == "cuda" else torch.float32
110
+ dev_map = device
111
+
112
+ self._init_faster_backend() # lazy — safe to call multiple times
113
+
114
+ key = f"{model_type}:{model_size}"
115
+ if key in self.loaded_models:
116
+ self.active_model_key = key
117
+ logger.debug(f"[model_manager] Model cache hit: {key}")
118
+ return self.loaded_models[key], f"Model ready (loaded): {key}"
119
+
120
+ if self.active_model_key and self.active_model_key != key:
121
+ logger.info(f"[model_manager] Switching model: {self.active_model_key} → {key}")
122
+ self._unload_all()
123
+
124
+ repo_id = self._repo_id(model_type, model_size)
125
+ note = ""
126
+ t0 = time.perf_counter()
127
+
128
+ if self._faster_available and self._faster_cls is not None:
129
+ try:
130
+ logger.info(f"[model_manager] Loading via FasterQwen3TTS: {repo_id}")
131
+ model = self._faster_cls.from_pretrained(
132
+ repo_id,
133
+ device="cuda",
134
+ dtype=dtype,
135
+ attn_implementation="eager",
136
+ max_seq_len=4096,
137
+ )
138
+ elapsed = time.perf_counter() - t0
139
+ note = f"Loaded faster backend in {elapsed:.2f}s: {repo_id}"
140
+ logger.info(f"[model_manager] {note}")
141
+ except Exception as fast_err:
142
+ logger.warning(f"[model_manager] FasterQwen3TTS failed: {fast_err} — falling back to standard")
143
+ model_path, dl_note = self._snapshot_path(repo_id)
144
+ from qwen_tts import Qwen3TTSModel # noqa: PLC0415
145
+ model = Qwen3TTSModel.from_pretrained(
146
+ model_path,
147
+ device_map=dev_map,
148
+ dtype=dtype,
149
+ attn_implementation="sdpa",
150
+ )
151
+ elapsed = time.perf_counter() - t0
152
+ note = f"{dl_note} | Fallback standard in {elapsed:.2f}s: {repo_id}"
153
+ logger.info(f"[model_manager] {note}")
154
+ else:
155
+ model_path, dl_note = self._snapshot_path(repo_id)
156
+ from qwen_tts import Qwen3TTSModel # noqa: PLC0415
157
+ logger.info(f"[model_manager] Loading Qwen3TTSModel: {model_path}")
158
+ model = Qwen3TTSModel.from_pretrained(
159
+ model_path,
160
+ device_map=dev_map,
161
+ dtype=dtype,
162
+ attn_implementation="sdpa",
163
+ )
164
+ elapsed = time.perf_counter() - t0
165
+ note = f"{dl_note} | Standard backend in {elapsed:.2f}s: {repo_id}"
166
+ logger.info(f"[model_manager] {note}")
167
+
168
+ self.loaded_models[key] = model
169
+ self.active_model_key = key
170
+ return model, f"{note} | active={key} device={device}"
171
+
172
+
173
+ model_manager = LazyModelManager()
source/qwen_app/omni_engine.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/omni_engine.py
2
+ """
3
+ OmniVoice Engine — Singleton Wrapper
4
+ ======================================
5
+ - Lazy-load OmniVoice model from HuggingFace (k2-fsa/OmniVoice)
6
+ - Uses OmniVoice NATIVE long-form generation (audio_chunk_duration / audio_chunk_threshold)
7
+ - NO manual chunking — model handles all splitting internally for best quality
8
+ - preprocess_prompt=True + postprocess_output=True for cleaner reference and output audio
9
+ - 600+ languages supported natively
10
+ - Accepts 'num_step' from UI slider dynamically.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import gc
16
+ import logging
17
+ import os
18
+ import time
19
+ import sys
20
+ import subprocess
21
+ import traceback
22
+ from typing import List, Optional, Tuple
23
+
24
+ import numpy as np
25
+
26
+ try:
27
+ import torch
28
+ _TORCH_AVAILABLE = True
29
+ except ImportError:
30
+ torch = None # type: ignore
31
+ _TORCH_AVAILABLE = False
32
+
33
+ logger = logging.getLogger("qwen_app.omni_engine")
34
+
35
+ # ─── GPU AUTO-TUNE ────────────────────────────────────────────────────────────
36
+
37
+ class GPUProfile:
38
+ """Auto-detected GPU settings for maximum quality at maximum speed."""
39
+
40
+ def __init__(self):
41
+ self.gpu_name = "CPU"
42
+ self.vram_gb = 0.0
43
+ self.compute_cap = (0, 0)
44
+ self.tier = "cpu"
45
+ self.num_step = 32 # OmniVoice diffusion steps (auto-tuned)
46
+ self.dtype = "float16"
47
+ self.cudnn_benchmark = False
48
+ # chunk_size and batch_parallel are kept for legacy logging only
49
+ self.chunk_size = 0 # Not used — OmniVoice handles internally
50
+ self.batch_parallel = 1
51
+ self.model_vram_est = 3.0 # OmniVoice model ~3GB FP16
52
+
53
+ self.detect()
54
+
55
+ def detect(self):
56
+ if not _TORCH_AVAILABLE or not torch.cuda.is_available():
57
+ logger.info("[gpu_profile] No CUDA → CPU mode")
58
+ self.dtype = "float32"
59
+ self.num_step = 16
60
+ return
61
+
62
+ try:
63
+ props = torch.cuda.get_device_properties(0)
64
+ self.gpu_name = props.name
65
+ self.vram_gb = props.total_memory / (1024**3)
66
+ self.compute_cap = (props.major, props.minor)
67
+ major = props.major
68
+ except Exception as e:
69
+ logger.warning(f"[gpu_profile] Detection failed: {e}")
70
+ return
71
+
72
+ # ── Tier classification ──
73
+ if major >= 8:
74
+ self.tier = "high" # Ampere / Ada — FP16 Tensor Cores
75
+ self.num_step = 32 # High quality
76
+ self.dtype = "float16"
77
+ self.cudnn_benchmark = True
78
+ elif major >= 7:
79
+ self.tier = "mid" # Turing
80
+ self.num_step = 32 # Still 32 for quality
81
+ self.dtype = "float16"
82
+ self.cudnn_benchmark = True
83
+ elif major >= 6:
84
+ self.tier = "low" # Pascal
85
+ self.num_step = 16
86
+ self.dtype = "float32"
87
+ self.cudnn_benchmark = True
88
+ else:
89
+ self.tier = "legacy"
90
+ self.num_step = 16
91
+ self.dtype = "float32"
92
+ self.cudnn_benchmark = False
93
+
94
+ # ── CUDNN ──
95
+ if self.cudnn_benchmark:
96
+ torch.backends.cudnn.benchmark = True
97
+ logger.info("[gpu_profile] CUDNN benchmark enabled")
98
+
99
+ logger.info(
100
+ f"[gpu_profile] {self.gpu_name} | VRAM={self.vram_gb:.1f}GB | "
101
+ f"cap={self.compute_cap} | tier={self.tier} | "
102
+ f"num_step={self.num_step}"
103
+ )
104
+
105
+ def summary(self) -> str:
106
+ return (
107
+ f"GPU: {self.gpu_name} ({self.vram_gb:.1f}GB) | "
108
+ f"Tier: {self.tier.upper()} | "
109
+ f"Steps: {self.num_step}"
110
+ )
111
+
112
+
113
+ # Global GPU profile
114
+ gpu_profile = GPUProfile()
115
+
116
+
117
+ def get_available_vram_gb() -> float:
118
+ return gpu_profile.vram_gb
119
+
120
+
121
+ # ─── Engine Singleton ─────────────────────────────────────────────────────────
122
+
123
+ class OmniEngine:
124
+ """
125
+ Singleton OmniVoice engine.
126
+ Uses model's native long-form generation — NO manual chunking.
127
+ Supports 600+ languages with zero-shot voice cloning.
128
+ """
129
+
130
+ _instance: Optional["OmniEngine"] = None
131
+
132
+ def __new__(cls) -> "OmniEngine":
133
+ if cls._instance is None:
134
+ cls._instance = super().__new__(cls)
135
+ cls._instance._initialized = False
136
+ return cls._instance
137
+
138
+ def __init__(self):
139
+ if self._initialized:
140
+ return
141
+ self.model = None
142
+ self.device: str = "cuda" if (_TORCH_AVAILABLE and torch.cuda.is_available()) else "cpu"
143
+ self._initialized = True
144
+ self._use_flash_attn = False
145
+ logger.debug(f"[omni_engine] OmniEngine singleton created — device={self.device}")
146
+
147
+ # ── Internal helpers ──────────────────────────────────────────────────────
148
+
149
+ def _unload_qwen(self):
150
+ """Unload Qwen model_manager if it holds GPU memory."""
151
+ try:
152
+ from .model_manager import model_manager
153
+ if model_manager.loaded_models:
154
+ logger.info(f"[omni_engine] Unloading Qwen models: {list(model_manager.loaded_models.keys())}")
155
+ model_manager._unload_all()
156
+ else:
157
+ logger.debug("[omni_engine] Qwen model_manager: nothing to unload")
158
+ except Exception as ue:
159
+ logger.warning(f"[omni_engine] _unload_qwen exception (safe to ignore): {ue}")
160
+
161
+ if _TORCH_AVAILABLE and torch.cuda.is_available():
162
+ before = torch.cuda.memory_reserved() / (1024**3)
163
+ torch.cuda.empty_cache()
164
+ after = torch.cuda.memory_reserved() / (1024**3)
165
+ gc.collect()
166
+ logger.debug(f"[omni_engine] VRAM after Qwen unload: {before:.2f}→{after:.2f} GB reserved")
167
+
168
+ # ── Public API ────────────────────────────────────────────────────────────
169
+
170
+ @property
171
+ def is_loaded(self) -> bool:
172
+ return self.model is not None
173
+
174
+ def load(self, use_flash_attn: bool = False, flash2_whl: str = "", log_callback=None) -> None:
175
+ """Load OmniVoice model. Unloads Qwen first. Full timing + deep log."""
176
+ if flash2_whl is None:
177
+ flash2_whl = ""
178
+ if self.is_loaded:
179
+ if getattr(self, "_use_flash_attn", False) == use_flash_attn:
180
+ logger.debug("[omni_engine] load() called but already loaded with matched flash-attn config — skipping")
181
+ return
182
+ else:
183
+ msg = f"🔄 Thay đổi Flash Attention ({getattr(self, '_use_flash_attn', False)} -> {use_flash_attn}), reloading..."
184
+ logger.info("[omni_engine] " + msg)
185
+ if log_callback: log_callback(msg)
186
+ self.unload()
187
+
188
+ def _log(msg: str):
189
+ logger.info(f"[omni_engine] {msg.strip()}")
190
+ if log_callback:
191
+ log_callback(msg)
192
+ else:
193
+ print(msg)
194
+
195
+ _log("🔄 Unload Qwen nếu đang chiếm VRAM...")
196
+ self._unload_qwen()
197
+
198
+ _log("⏳ Load OmniVoice model (600+ ngôn ngữ)...")
199
+ t_total = time.perf_counter()
200
+
201
+ try:
202
+ import torch as _torch
203
+
204
+ # Determine dtype
205
+ if gpu_profile.dtype == "float16" and _torch.cuda.is_available():
206
+ dtype = _torch.float16
207
+ else:
208
+ dtype = _torch.float32
209
+
210
+ device_map = "cuda:0" if _torch.cuda.is_available() else "cpu"
211
+
212
+ _log(f" ⚙️ Loading OmniVoice (dtype={gpu_profile.dtype}, device={device_map})...")
213
+ t0 = time.perf_counter()
214
+
215
+ from omnivoice import OmniVoice
216
+ kwargs = {
217
+ "device_map": device_map,
218
+ "dtype": dtype,
219
+ "load_asr": True, # Enable Whisper ASR for auto ref_text transcription
220
+ }
221
+ if use_flash_attn:
222
+ try:
223
+ import flash_attn
224
+ except ImportError:
225
+ if flash2_whl and os.path.isfile(flash2_whl):
226
+ _log(f" ⚡ Flash Attention chưa cài, đang cài từ {os.path.basename(flash2_whl)}...")
227
+ try:
228
+ cmd = [sys.executable, "-m", "pip", "install", flash2_whl]
229
+ subprocess.run(cmd, check=True, capture_output=True, text=True)
230
+ _log(" ✅ Đã cài đặt xong Flash Attention 2 từ file WHL!")
231
+ except subprocess.CalledProcessError as sub_err:
232
+ _log(f" ❌ Cài đặt thất bại: {sub_err.stderr}. Sẽ thử tiếp với Flash Attention...")
233
+ else:
234
+ _log(f" ⚠️ Flash Attention chưa được cài đặt và không có file .whl. Có thể lỗi!")
235
+
236
+ kwargs["attn_implementation"] = "flash_attention_2"
237
+ _log(" ⚡ Kích hoạt thử Flash Attention 2...")
238
+
239
+ try:
240
+ self.model = OmniVoice.from_pretrained("k2-fsa/OmniVoice", **kwargs)
241
+ self._use_flash_attn = use_flash_attn
242
+ except Exception as attempt_e:
243
+ if use_flash_attn:
244
+ _log(f" ❌ Lỗi load Flash Attention 2: {attempt_e}. Đang tắt Flash Attention và thử lại...")
245
+ kwargs.pop("attn_implementation", None)
246
+ self.model = OmniVoice.from_pretrained("k2-fsa/OmniVoice", **kwargs)
247
+ self._use_flash_attn = False
248
+ else:
249
+ raise
250
+ logger.info(f"[omni_engine] OmniVoice loaded in {time.perf_counter()-t0:.2f}s")
251
+
252
+ # ── Log VRAM usage ──
253
+ if _torch.cuda.is_available():
254
+ vram_used = _torch.cuda.memory_allocated() / (1024**3)
255
+ vram_total = _torch.cuda.get_device_properties(0).total_memory / (1024**3)
256
+ _log(f" 📊 VRAM: {vram_used:.2f} / {vram_total:.2f} GB")
257
+ logger.info(f"[omni_engine] VRAM after load: {vram_used:.2f}/{vram_total:.2f} GB")
258
+
259
+ elapsed_total = time.perf_counter() - t_total
260
+ _log(f"✅ OmniVoice loaded trên [{self.device.upper()}] — total {elapsed_total:.1f}s")
261
+ _log(f" 🌍 Hỗ trợ 600+ ngôn ngữ — sẵn sàng!")
262
+
263
+ except Exception as e:
264
+ self.model = None
265
+ tb = traceback.format_exc()
266
+ logger.error(f"[omni_engine] LOAD FAILED:\n{tb}")
267
+ raise RuntimeError(f"Không thể load OmniVoice model: {e}\n\n--- TRACEBACK ---\n{tb}")
268
+
269
+ def unload(self) -> None:
270
+ """Release GPU memory held by OmniVoice."""
271
+ if self.model is not None:
272
+ del self.model
273
+ self.model = None
274
+ logger.info("[omni_engine] OmniVoice model deleted from memory")
275
+ if _TORCH_AVAILABLE and torch.cuda.is_available():
276
+ before = torch.cuda.memory_reserved() / (1024**3)
277
+ torch.cuda.empty_cache()
278
+ after = torch.cuda.memory_reserved() / (1024**3)
279
+ logger.debug(f"[omni_engine] VRAM after unload: {before:.2f}→{after:.2f} GB")
280
+ gc.collect()
281
+
282
+ def infer(
283
+ self,
284
+ ref_audio_path: str,
285
+ ref_text: str,
286
+ gen_text: str,
287
+ language: str = "auto",
288
+ speed: float = 1.0,
289
+ num_step: int = 32,
290
+ ) -> Tuple[List[np.ndarray], int]:
291
+ """
292
+ Run inference using OmniVoice's NATIVE long-form generation.
293
+
294
+ Returns (list_of_wav_arrays, sample_rate=24000).
295
+ Each array in the list corresponds to one internal audio chunk
296
+ generated by OmniVoice (for SRT alignment).
297
+
298
+ Key design decisions:
299
+ - NO manual text splitting — model handles via audio_chunk_duration param
300
+ - preprocess_prompt=True: cleans reference audio (removes silences, adds punctuation)
301
+ - postprocess_output=True: removes long silences from generated audio
302
+ - ref_text is optional: if empty, Whisper ASR auto-transcribes the reference
303
+ """
304
+ if not self.is_loaded:
305
+ raise RuntimeError("OmniVoice model chưa được load. Gọi load() trước.")
306
+
307
+ logger.debug(
308
+ f"[omni_engine.infer] START | speed={speed} num={num_step} "
309
+ f"lang={language} ref_audio={ref_audio_path} gen_chars={len(gen_text)}"
310
+ )
311
+ logger.debug(f"[omni_engine.infer] gen_text[:80]= {gen_text[:80]!r}")
312
+
313
+ t0 = time.perf_counter()
314
+
315
+ if _TORCH_AVAILABLE and torch.cuda.is_available():
316
+ vram_before = torch.cuda.memory_allocated() / (1024**3)
317
+ else:
318
+ vram_before = 0.0
319
+
320
+ try:
321
+ from omnivoice import OmniVoiceGenerationConfig
322
+
323
+ # NOTE: audio_chunk_duration + audio_chunk_threshold MUST be inside
324
+ # OmniVoiceGenerationConfig — when generation_config is passed to
325
+ # model.generate(), all **kwargs are ignored (from_dict is not called).
326
+ gen_config = OmniVoiceGenerationConfig(
327
+ num_step=num_step,
328
+ guidance_scale=2.0,
329
+ denoise=True,
330
+ preprocess_prompt=True, # Clean ref audio (remove silences, add punct)
331
+ postprocess_output=True, # Clean generated audio (remove long silences)
332
+ audio_chunk_duration=15.0, # Target segment ~15s (good for SRT)
333
+ audio_chunk_threshold=30.0, # Activate chunking if estimated > 30s
334
+ )
335
+
336
+ lang = language if (language and language.lower() not in ("auto", "")) else None
337
+
338
+ gen_kwargs = dict(
339
+ text=gen_text,
340
+ language=lang,
341
+ generation_config=gen_config,
342
+ )
343
+
344
+ if speed is not None and abs(float(speed) - 1.0) > 0.01:
345
+ gen_kwargs["speed"] = float(speed)
346
+
347
+ # Voice cloning mode if ref_audio provided
348
+ if ref_audio_path and os.path.exists(ref_audio_path):
349
+ ref_text_clean = (ref_text or "").strip() or None
350
+ gen_kwargs["voice_clone_prompt"] = self.model.create_voice_clone_prompt(
351
+ ref_audio=ref_audio_path,
352
+ ref_text=ref_text_clean,
353
+ # If ref_text is None, Whisper ASR auto-transcribes
354
+ )
355
+
356
+ audio_tensors = self.model.generate(**gen_kwargs)
357
+
358
+ except Exception as e:
359
+ tb = traceback.format_exc()
360
+ logger.error(f"[omni_engine.infer] GENERATE FAILED:\n{tb}")
361
+ raise
362
+
363
+ # ── Convert tensor list to numpy arrays ──
364
+ result_arrays: List[np.ndarray] = []
365
+ if audio_tensors and len(audio_tensors) > 0:
366
+ for audio in audio_tensors:
367
+ if hasattr(audio, 'cpu'):
368
+ arr = audio.flatten().cpu().numpy().astype(np.float32)
369
+ else:
370
+ arr = np.array(audio, dtype=np.float32).flatten()
371
+
372
+ # Sanitize NaN/Inf
373
+ nan_count = int(np.isnan(arr).sum())
374
+ inf_count = int(np.isinf(arr).sum())
375
+ if nan_count > 0 or inf_count > 0:
376
+ logger.error(
377
+ f"[omni_engine.infer] ⚠️ NUMERICAL ISSUE: "
378
+ f"NaN={nan_count} Inf={inf_count} / {len(arr)} samples"
379
+ )
380
+ arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0)
381
+
382
+ result_arrays.append(arr)
383
+ else:
384
+ logger.warning("[omni_engine.infer] model.generate returned empty list — silence fallback")
385
+ result_arrays = [np.zeros(2400, dtype=np.float32)] # 0.1s silence
386
+
387
+ sr = 24000 # OmniVoice outputs at 24kHz
388
+ elapsed = time.perf_counter() - t0
389
+ total_samples = sum(len(a) for a in result_arrays)
390
+
391
+ if _TORCH_AVAILABLE and torch.cuda.is_available():
392
+ vram_after = torch.cuda.memory_allocated() / (1024**3)
393
+ else:
394
+ vram_after = 0.0
395
+
396
+ logger.debug(
397
+ f"[omni_engine.infer] DONE | elapsed={elapsed:.2f}s "
398
+ f"segments={len(result_arrays)} total_samples={total_samples} "
399
+ f"({total_samples/sr:.2f}s) vram_alloc {vram_before:.2f}→{vram_after:.2f} GB"
400
+ )
401
+
402
+ # Energy check on full output
403
+ all_audio = np.concatenate(result_arrays)
404
+ energy = self.check_array_energy(all_audio)
405
+ if energy < SILENCE_THRESHOLD:
406
+ logger.warning(
407
+ f"[omni_engine.infer] ⚠️ LOW ENERGY OUTPUT: energy={energy:.6f} "
408
+ f"< threshold={SILENCE_THRESHOLD} — likely silent! "
409
+ f"gen_text[:60]={gen_text[:60]!r}"
410
+ )
411
+
412
+ return result_arrays, sr
413
+
414
+ @staticmethod
415
+ def check_array_energy(arr: Optional[np.ndarray]) -> float:
416
+ """Fast inline RMS check — no I/O."""
417
+ if arr is None or len(arr) == 0:
418
+ return 0.0
419
+ clean = np.nan_to_num(arr.astype(np.float32), nan=0.0, posinf=0.0, neginf=0.0)
420
+ rms = float(np.sqrt(np.mean(clean ** 2)))
421
+ return rms if np.isfinite(rms) else 0.0
422
+
423
+
424
+ # ─── Global singleton ─────────────────────────────────────────────────────────
425
+ omni_engine = OmniEngine()
426
+
427
+ SILENCE_THRESHOLD = 0.003
428
+ MAX_OMNI_RETRIES = 2
source/qwen_app/prosody.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/prosody.py
2
+ """
3
+ Prosodic Pause System
4
+ ─────────────────────
5
+ Inserts natural silence gaps between TTS chunks based on the
6
+ punctuation that ends each chunk, exactly like production TTS
7
+ APIs (Minimax, ElevenLabs, OpenAI TTS).
8
+
9
+ Default values are tuned to professional broadcast standards:
10
+ • Sentence endings (. ! ?) → 500 ms
11
+ • Clause breaks (,) → 180 ms
12
+ • Semi-colon (;) → 300 ms
13
+ • Colon (:) → 250 ms
14
+ • Ellipsis (...) → 700 ms
15
+ • Newline (paragraph) → 600 ms
16
+ • Bare chunk boundary → 80 ms
17
+ """
18
+
19
+ import re
20
+ import numpy as np
21
+ from dataclasses import dataclass
22
+
23
+
24
+ @dataclass
25
+ class PauseConfig:
26
+ sentence_ms: int = 500 # . ! ?
27
+ comma_ms: int = 180 # ,
28
+ semicolon_ms: int = 300 # ;
29
+ colon_ms: int = 250 # :
30
+ ellipsis_ms: int = 700 # ...
31
+ newline_ms: int = 600 # \n paragraph break
32
+ default_ms: int = 80 # no punctuation (bare chunk)
33
+
34
+ def to_dict(self):
35
+ return {
36
+ "sentence_ms": self.sentence_ms,
37
+ "comma_ms": self.comma_ms,
38
+ "semicolon_ms": self.semicolon_ms,
39
+ "colon_ms": self.colon_ms,
40
+ "ellipsis_ms": self.ellipsis_ms,
41
+ "newline_ms": self.newline_ms,
42
+ "default_ms": self.default_ms,
43
+ }
44
+
45
+
46
+ # Default config — same numbers used by build_pause_ui
47
+ DEFAULT_PAUSE = PauseConfig()
48
+
49
+
50
+ def detect_pause_ms(chunk_text: str, cfg: PauseConfig) -> int:
51
+ """
52
+ Inspect the last meaningful characters of a chunk and return
53
+ the appropriate pause duration in milliseconds.
54
+ Priority: ellipsis > sentence > newline > semicolon > colon > comma > default
55
+ """
56
+ text = (chunk_text or "").rstrip()
57
+ if not text:
58
+ return cfg.default_ms
59
+
60
+ # Ellipsis (Unicode … or triple dot)
61
+ if text.endswith("…") or text.endswith("..."):
62
+ return cfg.ellipsis_ms
63
+
64
+ # Sentence-ending (works for Vietnamese, CJK, Arabic, Latin)
65
+ if re.search(r"[.!?。!?।؟]$", text):
66
+ return cfg.sentence_ms
67
+
68
+ # Paragraph / newline break — the original text had a newline here
69
+ if "\n" in chunk_text:
70
+ return cfg.newline_ms
71
+
72
+ # Semicolon
73
+ if text.endswith(";") or text.endswith(";"):
74
+ return cfg.semicolon_ms
75
+
76
+ # Colon
77
+ if text.endswith(":") or text.endswith(":"):
78
+ return cfg.colon_ms
79
+
80
+ # Comma
81
+ if text.endswith(",") or text.endswith(",") or text.endswith("、"):
82
+ return cfg.comma_ms
83
+
84
+ return cfg.default_ms
85
+
86
+
87
+ def make_silence(ms: int, sample_rate: int = 24000) -> np.ndarray:
88
+ """Return a float32 silence array of given duration in milliseconds."""
89
+ n_samples = max(0, int(ms * sample_rate / 1000))
90
+ return np.zeros(n_samples, dtype=np.float32)
91
+
92
+
93
+ def pause_seconds(chunk_text: str, cfg: PauseConfig, speed: float = 1.0) -> float:
94
+ """
95
+ Return the *wall-clock* pause duration in seconds as it will appear
96
+ in the final sped-up audio. Used for SRT cursor advancement.
97
+
98
+ The silence buffer is inserted PRE-SPEED, so atempo will shorten it too.
99
+ """
100
+ ms = detect_pause_ms(chunk_text, cfg)
101
+ return (ms / 1000.0) / max(speed, 0.1)
source/qwen_app/text_cleaner.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/text_cleaner.py
2
+ """
3
+ Universal Text Cleaner for OmniVoice TTS (600+ Languages)
4
+ ===========================================================
5
+ Cleans text BEFORE passing to OmniVoice to ensure maximum speech quality.
6
+
7
+ Following OmniVoice author recommendations:
8
+ - Remove URLs, emails, file paths (model can't pronounce these)
9
+ - Remove markdown / HTML formatting tags
10
+ - Remove emojis and non-speech symbols
11
+ - Normalize punctuation (no duplicate, no unbalanced brackets)
12
+ - Normalize whitespace and line breaks
13
+ - Keep language-neutral — safe for ALL 600+ supported languages
14
+
15
+ NOTE: This is GENERATION TEXT cleaning only.
16
+ preprocess_prompt=True (in OmniVoiceGenerationConfig) handles reference audio.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ import unicodedata
23
+ from typing import Optional
24
+
25
+
26
+ # ─── URL / Email / Path patterns ─────────────────────────────────────────────
27
+
28
+ # Match full URLs (http/https/ftp/www...)
29
+ _URL_PATTERN = re.compile(
30
+ r"""(?:https?|ftp)://[^\s\]\[<>"']+"""
31
+ r"""|www\.[a-zA-Z0-9][-a-zA-Z0-9.]+\.[a-zA-Z]{2,}(?:/[^\s]*)?""",
32
+ re.IGNORECASE,
33
+ )
34
+
35
+ # Email addresses
36
+ _EMAIL_PATTERN = re.compile(
37
+ r"[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}",
38
+ re.IGNORECASE,
39
+ )
40
+
41
+ # File paths (Windows and Unix style)
42
+ _FILEPATH_PATTERN = re.compile(
43
+ r"""[a-zA-Z]:\\(?:[^\\\n/:*?"<>|]+\\)*[^\\\n/:*?"<>|]*"""
44
+ r"""|/(?:[^/\n]+/)+[^/\n]*""",
45
+ )
46
+
47
+ # Hashtags and @mentions (social media noise)
48
+ _HASHTAG_MENTION_PATTERN = re.compile(r"[@#]\w+")
49
+
50
+
51
+ # ─── Markdown / HTML ─────────────────────────────────────────────────────────
52
+
53
+ # HTML tags
54
+ _HTML_TAG_PATTERN = re.compile(r"<[^>]{1,200}>", re.IGNORECASE)
55
+
56
+ # Markdown: **bold**, *italic*, __underline__, ~~strike~~, `code`, ```code blocks```
57
+ _MARKDOWN_PATTERN = re.compile(
58
+ r"```[\s\S]*?```" # fenced code block
59
+ r"|`[^`\n]+`" # inline code
60
+ r"|_{1,2}([^_\n]+)_{1,2}" # __bold__ or _italic_
61
+ r"|\*{1,2}([^*\n]+)\*{1,2}" # **bold** or *italic*
62
+ r"|~~([^~\n]+)~~" # ~~strikethrough~~
63
+ r"|\[([^\]]+)\]\([^)]+\)" # [link text](url) → keep link text
64
+ )
65
+
66
+ # Markdown headers # ## ###
67
+ _MD_HEADER_PATTERN = re.compile(r"^#{1,6}\s+", re.MULTILINE)
68
+
69
+ # Markdown horizontal rule
70
+ _MD_HR_PATTERN = re.compile(r"^[-*_]{3,}\s*$", re.MULTILINE)
71
+
72
+ # Markdown blockquote
73
+ _MD_QUOTE_PATTERN = re.compile(r"^>\s*", re.MULTILINE)
74
+
75
+
76
+ # ─── Emoji / Special Unicode ─────────────────────────────────────────────────
77
+
78
+ # Emoji ranges (covers most emoji blocks)
79
+ _EMOJI_PATTERN = re.compile(
80
+ "["
81
+ "\U0001F600-\U0001F64F" # emoticons
82
+ "\U0001F300-\U0001F5FF" # misc symbols & pictographs
83
+ "\U0001F680-\U0001F6FF" # transport & map
84
+ "\U0001F1E0-\U0001F1FF" # flags
85
+ "\u2500-\u2bef" # box drawing, arrows, misc
86
+ "\u2702-\u27b0" # dingbats
87
+ "\u24c2\U0001F251" # specific enclosed characters (M and Accept)
88
+ "\U0001f926-\U0001f937" # facepalms, shrugs, etc
89
+ "\U0001F900-\U0001F9FF" # supplemental symbols and pictographs
90
+ "\U0001FA70-\U0001FAFF" # symbols and pictographs extended-A
91
+ "\u2640-\u2642" # gender symbols
92
+ "\u2600-\u2b55" # misc symbols and arrows
93
+ "\u200d" # zero width joiner
94
+ "\u23cf" # eject symbol
95
+ "\u23e9" # fast forward
96
+ "\u231a" # watch
97
+ "\ufe0f" # variation selector 16
98
+ "\u3030" # wavy dash
99
+ "]+",
100
+ re.UNICODE,
101
+ )
102
+
103
+ # Zero-width and invisible characters
104
+ _ZERO_WIDTH_PATTERN = re.compile(
105
+ r"[\u200b\u200c\u200d\u200e\u200f\u2028\u2029\ufeff\u00ad\u034f\u180e]"
106
+ )
107
+
108
+ # Control characters (except newline, tab, carriage return)
109
+ _CONTROL_CHAR_PATTERN = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
110
+
111
+
112
+ # ─── Punctuation normalization ────────────────────────────────────────────────
113
+
114
+ # Repeated punctuation (e.g. "!!!" → "!", "..." kept as-is for ellipsis)
115
+ _REPEAT_PUNCT_PATTERN = re.compile(r"([!?])\1+")
116
+
117
+ # Repeated dots longer than 3 → ellipsis (…)
118
+ _REPEAT_DOTS_PATTERN = re.compile(r"\.{4,}")
119
+
120
+ # Repeated commas, semicolons, colons
121
+ _REPEAT_COMMA_PATTERN = re.compile(r"[,;:]{2,}")
122
+
123
+ # Unmatched brackets/parentheses — strip the lonely bracket
124
+ _LONE_BRACKET_OPEN = re.compile(r"\(\s*\)") # () empty parens
125
+ _LONE_BRACKET_EMPTY = re.compile(r"\[\s*\]") # [] empty brackets
126
+
127
+ # Opening bracket at end of text or closing bracket at start (no pair)
128
+ _TRAILING_OPEN = re.compile(r"[\(\[\{]\s*$")
129
+ _LEADING_CLOSE = re.compile(r"^\s*[\)\]\}]")
130
+
131
+ # Mixed punctuation clutter (e.g. ".-" or ",." etc)
132
+ _PUNCT_CLUTTER = re.compile(r"[,;]\s*[.!?]") # comma/semi followed by end punct
133
+
134
+ # ─── Special character substitutions ─────────────────────────────────────────
135
+
136
+ # These are symbol-to-word mappings that are language-neutral or common
137
+ # Note: Vietnamese-specific ones go in vi_normalizer.py
138
+ _SYMBOL_MAP = [
139
+ (" & ", " and "), # ampersand mid-word → "and"
140
+ ("®", ""), # registered trademark
141
+ ("™", ""), # trademark
142
+ ("©", ""), # copyright
143
+ ("°", " degrees "),
144
+ ("±", " plus or minus "),
145
+ ("×", " times "),
146
+ ("÷", " divided by "),
147
+ ("≈", " approximately "),
148
+ ("≠", " not equal to "),
149
+ ("≤", " less than or equal to "),
150
+ ("≥", " greater than or equal to "),
151
+ ("→", " "),
152
+ ("←", " "),
153
+ ("↑", " "),
154
+ ("↓", " "),
155
+ ("↔", " "),
156
+ ("•", " "), # bullet → space
157
+ ("·", " "), # middle dot
158
+ ("–", " - "), # en dash → hyphen
159
+ ("—", " - "), # em dash → hyphen
160
+ ("„", '"'), # lower double quote → normal
161
+ ("\u201c", '"'), # left double quote → normal
162
+ ("\u201d", '"'), # right double quote → normal
163
+ ("\u2018", "'"), # left single quote → normal
164
+ ("\u2019", "'"), # right single quote → normal
165
+ ("\u0060", "'"), # backtick → normal apostrophe
166
+ ]
167
+
168
+ # Repeated stars/dashes used as decorators (e.g. "*** TITLE ***")
169
+ _DECORATOR_PATTERN = re.compile(r"[*=\-_~^]{3,}")
170
+
171
+
172
+ # ─── Main cleaner ─────────────────────────────────────────────────────────────
173
+
174
+ def clean_tts_text(text: str, language: str = "auto") -> str:
175
+ """
176
+ Universal text cleaner for OmniVoice TTS input.
177
+ Safe for ALL 600+ supported languages.
178
+
179
+ Args:
180
+ text: Raw input text
181
+ language: Language hint (e.g. "Vietnamese", "English") — used for
182
+ language-specific post-processing
183
+
184
+ Returns:
185
+ Cleaned text ready for OmniVoice model.generate()
186
+ """
187
+ if not text:
188
+ return ""
189
+
190
+ # ── Step 1: Unicode normalization ──
191
+ # NFC: compose combining characters (accents for Vietnamese, etc.)
192
+ text = unicodedata.normalize("NFC", text)
193
+
194
+ # ── Step 2: Remove control chars and zero-width chars ──
195
+ text = _ZERO_WIDTH_PATTERN.sub("", text)
196
+ text = _CONTROL_CHAR_PATTERN.sub("", text)
197
+
198
+ # (Skip aggressive Markdown/HTML/URL/ASCII parsing. User text is AI-precleaned)
199
+
200
+ # ── Step 12: Punctuation normalization ──
201
+ # Repeated ! or ? → single
202
+ text = _REPEAT_PUNCT_PATTERN.sub(r"\1", text)
203
+
204
+ # Very long dot sequences → ellipsis (3 dots)
205
+ text = _REPEAT_DOTS_PATTERN.sub("...", text)
206
+
207
+ # Repeated commas/semicolons/colons → single
208
+ text = _REPEAT_COMMA_PATTERN.sub(lambda m: m.group(0)[0], text)
209
+
210
+ # Comma/semi before sentence end → just keep end punct
211
+ text = _PUNCT_CLUTTER.sub(lambda m: m.group(0)[-1], text)
212
+
213
+ # Empty parens/brackets → remove
214
+ text = _LONE_BRACKET_OPEN.sub(" ", text)
215
+ text = _LONE_BRACKET_EMPTY.sub(" ", text)
216
+
217
+ # Trailing open bracket or leading close bracket
218
+ text = _TRAILING_OPEN.sub(" ", text)
219
+ text = _LEADING_CLOSE.sub(" ", text)
220
+
221
+ # ── Step 13: Normalize whitespace ──
222
+ # Normalize line breaks: multiple blank lines → max 1 blank line
223
+ text = re.sub(r"\n{3,}", "\n\n", text)
224
+ # Normalize spaces on each line
225
+ lines = [re.sub(r"[ \t]+", " ", line).strip() for line in text.split("\n")]
226
+ # Bỏ qua logic filter "\w" vì nó có thể tự động lược bỏ dòng chữ nước ngoài
227
+ lines = [l for l in lines if l]
228
+ text = "\n".join(lines)
229
+
230
+ # ── Step 14: Final punctuation spacing cleanup ──
231
+ # Space before punctuation (e.g. "hello ." → "hello.")
232
+ text = re.sub(r"\s+([.,!?;:])", r"\1", text)
233
+ # Multiple spaces → single
234
+ text = re.sub(r"[ \t]+", " ", text)
235
+
236
+ return text.strip()
237
+
238
+
239
+ # ─── Convenience wrapper that calls language-specific normalizer after ────────
240
+
241
+ def preprocess_for_tts(text: str, language: str = "auto") -> str:
242
+ """
243
+ Full preprocessing pipeline:
244
+ 1. Universal clean (removes URLs, emojis, HTML, markdown, etc.)
245
+ 2. Language-specific normalization (numbers, dates, symbols)
246
+
247
+ Args:
248
+ text: Raw input text
249
+ language: Language string (matches OmniVoice language param)
250
+
251
+ Returns:
252
+ Fully normalized text ready for OmniVoice.
253
+ """
254
+ # Step 1: Universal clean
255
+ cleaned = clean_tts_text(text, language=language)
256
+
257
+ # Step 2: Vietnamese-specific normalization
258
+ is_vn = language.lower() in ("vietnamese", "tiếng việt", "vi", "vie", "auto")
259
+ if is_vn:
260
+ try:
261
+ from .vi_normalizer import normalize_vi_text
262
+ cleaned = normalize_vi_text(cleaned)
263
+ except Exception:
264
+ pass
265
+
266
+ # Final whitespace cleanup after normalizer
267
+ cleaned = re.sub(r"[ \t]+", " ", cleaned).strip()
268
+
269
+ return cleaned
270
+
271
+
272
+ if __name__ == "__main__":
273
+ # Quick test
274
+ samples = [
275
+ "Xem thêm tại https://youtube.com/watch?v=abc123 nhé!!!",
276
+ "**Thời tiết hôm nay** rất đẹp 😊😊😊",
277
+ "Email: support@example.com hoặc hotline 1800-1234",
278
+ "Giá: 1.500.000 VNĐ (khuyến mãi 20%!!!)",
279
+ "Check file tại D:\\Projects\\data\\output.txt cho tôi",
280
+ "# Tiêu đề\n## Phụ đề\n> Quote này\n```code```",
281
+ "Câu 1... câu 2,,, câu 3;;;",
282
+ "Follow @mypage và #viral trên TikTok nhé !!!",
283
+ ]
284
+ for s in samples:
285
+ result = preprocess_for_tts(s, language="Vietnamese")
286
+ print(f"IN: {s!r}")
287
+ print(f"OUT: {result!r}")
288
+ print()
source/qwen_app/ui.py ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ from gradio_modal import Modal
5
+
6
+ try:
7
+ import psutil
8
+ except Exception:
9
+ psutil = None
10
+
11
+ from .config import LANGUAGES, SPEAKERS
12
+ from .voice_library import (
13
+ delete_voice,
14
+ ensure_voice_library,
15
+ preview_saved_voice,
16
+ save_voice_profile,
17
+ voice_choices,
18
+ voice_rows,
19
+ )
20
+
21
+ # Lazy-loaded wrapper functions for fast UI startup
22
+ def process_omni_batch_txt(*args, **kwargs):
23
+ from .mode_omni_batch import process_omni_batch_txt as _fn
24
+ yield from _fn(*args, **kwargs)
25
+
26
+ def process_omni_news_batch(*args, **kwargs):
27
+ from .mode_omni_news import process_omni_news_batch as _fn
28
+ yield from _fn(*args, **kwargs)
29
+
30
+ def validate_audio_vs_srt(*args, **kwargs):
31
+ from .audio_validator import validate_audio_vs_srt as _fn
32
+ return _fn(*args, **kwargs)
33
+
34
+ def validate_batch_output(*args, **kwargs):
35
+ from .audio_validator import validate_batch_output as _fn
36
+ return _fn(*args, **kwargs)
37
+
38
+ def format_validation_report(*args, **kwargs):
39
+ from .audio_validator import format_validation_report as _fn
40
+ return _fn(*args, **kwargs)
41
+
42
+ def format_batch_reports(*args, **kwargs):
43
+ from .audio_validator import format_batch_reports as _fn
44
+ return _fn(*args, **kwargs)
45
+ from .voice_library_vi import (
46
+ ensure_vi_voice_library,
47
+ vi_voice_choices,
48
+ vi_voice_rows,
49
+ save_vi_voice,
50
+ delete_vi_voice,
51
+ preview_vi_voice,
52
+ resolve_vi_ref,
53
+ NONE_CHOICE as VI_NONE_CHOICE,
54
+ )
55
+
56
+
57
+ # Silence non-fatal symlink warnings on Windows cache.
58
+ os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
59
+
60
+ VOICE_DESCRIPTION_TEMPLATES = {
61
+ "Cinematic Storyteller (Male)": "Voice type: Male. Speak as a cinematic storyteller with warm resonance, controlled pacing, and emotionally rich phrasing. Begin with calm narrative authority, then build intensity on key words with subtle breath energy and deliberate pauses. Keep articulation crisp but natural, with a polished studio tone suited for trailers, documentaries, and immersive long-form storytelling.",
62
+ "Premium Conversational Assistant (Female)": "Voice type: Female. Use a premium virtual-assistant style: clear, reassuring, and intelligent. Maintain medium pace, neutral accent, and consistently high intelligibility. Sound professional yet approachable, with slight prosodic lift on supportive phrases and gentle emphasis for instructions. Avoid overacting; prioritize trust, calm confidence, and user comfort in every sentence.",
63
+ "Energetic Product Presenter (Male)": "Voice type: Male. Deliver with upbeat product-presenter energy: bright tone, confident rhythm, and persuasive clarity. Emphasize benefits, numbers, and call-to-action phrases with controlled enthusiasm. Keep transitions smooth and momentum high without sounding rushed. The voice should feel modern, polished, and conversion-focused, like a premium launch keynote or ad campaign narration.",
64
+ "Soft Empathetic Guide (Female)": "Voice type: Female. Speak as an empathetic guide with a soft, grounded voice and compassionate pacing. Use gentle onset, smooth sentence endings, and reassuring cadence. Add subtle warmth and emotional safety, especially on sensitive words. Maintain clear diction while sounding human and caring, suitable for wellbeing apps, coaching flows, and emotionally supportive interactions.",
65
+ "Authoritative News Anchor (Male)": "Voice type: Male. Adopt a composed news-anchor style with strong diction, low emotional volatility, and high credibility. Keep pace steady and measured, with precise phrasing and disciplined pauses at clause boundaries. Emphasize facts and proper nouns cleanly. The voice should project authority, neutrality, and confidence appropriate for reports, briefings, and formal updates.",
66
+ "Luxury Brand Narrator (Female)": "Voice type: Female. Use a refined luxury-brand tone: smooth, elegant, and restrained. Maintain slower cadence, rich timbre, and highly intentional emphasis on sensory adjectives and brand values. Prioritize sophistication over energy, with tasteful pauses and velvety delivery. Suitable for premium ads, fashion films, hospitality promos, and high-end product storytelling.",
67
+ "Technical Explainer Pro (Male)": "Voice type: Male. Speak like a senior technical explainer: precise, organized, and high-clarity. Keep cadence structured with audible sectioning, clear enumeration, and firm emphasis on terms, parameters, and constraints. Maintain neutral warmth and avoid dramatic swings. The voice should feel expert and trustworthy for tutorials, onboarding guides, and developer-focused education.",
68
+ "Playful Youthful Creator (Female)": "Voice type: Female. Deliver with playful creator energy: lively, expressive, and socially engaging. Use dynamic intonation, quick but controlled pacing, and friendly emphasis on surprise or delight moments. Keep pronunciation clear while sounding spontaneous and relatable. Ideal for social clips, creator intros, community updates, and fun lifestyle narration.",
69
+ "Calm Meditation Coach (Female)": "Voice type: Female. Speak as a calm meditation coach with slow tempo, deep breath spacing, and soothing low-mid tone. Use long gentle pauses, soft transitions, and minimal sharp consonant attack. Keep guidance clear yet tranquil, with a centered emotional profile that reduces tension and promotes focus. Best for breathwork, mindfulness, and sleep content.",
70
+ "Epic Fantasy Narrator (Male)": "Voice type: Male. Use an epic fantasy narrator style: deep, textured, and atmospheric. Start with measured gravitas, then swell intensity on lore-heavy or dramatic lines. Shape phrases with cinematic contour, weighted pauses, and vivid emphasis on names, places, and stakes. Maintain intelligibility while creating a grand, immersive world-building performance.",
71
+ "Playful Comedic Performer (Male)": "Voice type: Male. Perform with lively comedic timing, bright tone, and expressive pitch movement. Add natural smile energy and punchline emphasis with short, intentional pauses before humor beats. Keep diction clear while sounding spontaneous and entertaining. Ideal for skits, banter, playful ads, and light-hearted narration that feels genuinely fun.",
72
+ "Whispered Secret Voice (Female)": "Voice type: Female. Speak in a soft close-mic whisper with delicate breath texture and intimate presence. Keep volume low but intelligible, elongate key words slightly, and use gentle pauses to create suspense. Avoid harsh consonants and maintain smooth articulation. Suitable for ASMR, secretive narration, and mysterious dramatic scenes.",
73
+ "Panic and Fear Reaction (Female)": "Voice type: Female. Deliver a fear-driven performance with tense breath support, quicker pacing on urgent phrases, and trembling emphasis on high-stakes words. Alternate short gasps with clipped phrases, then drop into hushed concern for contrast. Maintain intelligibility while conveying alarm, uncertainty, and escalating emotional pressure.",
74
+ "Psychological Horror Narrator (Male)": "Voice type: Male. Use a chilling psychological-horror tone: restrained at first, then subtly unstable as the scene evolves. Keep pace measured with uncomfortable pauses, low resonance, and precise articulation of eerie details. Build dread through controlled intensity rather than shouting. The result should feel unsettling, cinematic, and immersive.",
75
+ "Suspense Thriller Trailer (Male)": "Voice type: Male. Speak like a thriller trailer narrator with dark confidence, deliberate cadence, and dramatic rise on reveal words. Use weighted pauses and strong sentence endings to create tension. Emphasize stakes, time pressure, and conflict cues. Keep the delivery polished, cinematic, and high-impact for dramatic promo material.",
76
+ "Sinister Villain Monologue (Male)": "Voice type: Male. Adopt a calculated villain persona with deep controlled tone, slow predatory pacing, and sharp emphasis on threats or promises. Add subtle contempt and confident pauses, with occasional intensity spikes on dominant phrases. Maintain clarity while projecting menace, intelligence, and theatrical authority.",
77
+ "Over-the-Top Action Hype (Male)": "Voice type: Male. Deliver explosive action-hype energy with fast tempo, punchy stress patterns, and powerful callout emphasis. Drive momentum through short rhythmic phrasing and strong transitions. Keep articulation clean despite high intensity. Great for sports intros, game trailers, and heroic battle-style announcements.",
78
+ "Noir Detective Voice (Male)": "Voice type: Male. Use a gritty noir detective style with dry wit, low-mid rasp, and reflective pacing. Lean into moody pauses and understated emphasis, as if narrating a rain-soaked city mystery at midnight. Keep phrasing deliberate, cinematic, and character-rich while preserving clear intelligibility.",
79
+ }
80
+
81
+ # Templates for Emotion Control — no voice-type specification since the speaker is fixed.
82
+ # These describe only the emotional style and delivery.
83
+ EMOTION_STYLE_TEMPLATES = {
84
+ "Calm & Authoritative": "Speak with measured confidence and composed authority. Keep a steady pace, precise diction, and controlled pauses at clause boundaries. Project credibility and neutrality without emotional volatility.",
85
+ "Warm & Conversational": "Deliver in a friendly, natural conversational tone. Maintain an approachable cadence with slight prosodic lift on supportive phrases. Sound genuine and reassuring, like speaking to a trusted friend.",
86
+ "Upbeat & Energetic": "Speak with bright, enthusiastic energy. Use confident rhythm, punchy emphasis on key words, and high momentum. Keep articulation clean while projecting excitement and positivity.",
87
+ "Soft & Empathetic": "Use a gentle, grounded tone with compassionate pacing. Add subtle warmth on emotionally sensitive words. Keep delivery smooth and caring, creating a sense of safety and understanding.",
88
+ "Dramatic & Intense": "Deliver with cinematic gravitas. Build tension through weighted pauses, deliberate pacing, and strong emphasis on stakes and key moments. Create a sense of urgency and high emotional investment.",
89
+ "Playful & Lighthearted": "Speak with lively, expressive intonation and quick pacing. Add natural smile energy, spontaneous rhythm, and emphasis on surprise or delight moments. Keep the tone fun and relatable.",
90
+ "Melancholic & Reflective": "Use a slow, introspective pace with soft onset and gentle pauses. Add a hint of emotional weight and quiet resignation. Keep the tone sincere, thoughtful, and quietly moving.",
91
+ "Tense & Anxious": "Deliver with slightly quickened pacing on urgent phrases and subtle breath tension. Alternate short clipped phrases with hushed concern. Convey unease and building pressure without losing intelligibility.",
92
+ "Inspiring & Motivational": "Speak with rising energy and purposeful conviction. Emphasize action words, aspirations, and calls to change. Build momentum steadily, projecting hope, determination, and forward motion.",
93
+ "Cold & Detached": "Deliver in a flat, measured tone with minimal prosodic variation. Keep pacing controlled and emotionless. Project clinical precision and deliberate distance, as if reciting facts without involvement.",
94
+ "Excited & Enthusiastic": "Use rapid-fire energy with dynamic pitch variation and strong callout emphasis on highlights. Drive momentum with short rhythmic phrasing. Sound genuinely thrilled and engaged throughout.",
95
+ "Somber & Serious": "Speak in a low-key, grave tone with slow deliberate pacing and long pauses. Keep every word weighted and purposeful. Project solemnity and deep seriousness befitting difficult or important subjects.",
96
+ "Whispered & Secretive": "Use a soft, close-mic delivery with delicate breath texture and intimate presence. Elongate key words slightly and use gentle pauses to create suspense. Avoid harsh consonants while staying intelligible.",
97
+ "Sarcastic & Dry": "Deliver with flat affect and understated emphasis on ironic words. Use dry wit and slight over-enunciation on sarcastic phrases. Keep the tone deadpan while allowing subtle comedic timing.",
98
+ "Horror & Dread": "Start restrained, then build subtle instability as tension escalates. Use uncomfortable pauses, deliberate articulation of eerie details, and a low resonant tone. Create dread through controlled intensity rather than volume.",
99
+ }
100
+
101
+
102
+ def _progress_status_panel(default_status: str):
103
+ progress = gr.Slider(label="Progress", minimum=0, maximum=100, value=0, interactive=False)
104
+ status = gr.Textbox(label="Status", value=default_status, lines=3, interactive=False)
105
+ output = gr.Audio(label="Generated Audio", type="numpy")
106
+ return progress, status, output
107
+
108
+
109
+ def _advanced_decode_ui(prefix: str):
110
+ with gr.Accordion(f"Advanced Decode - {prefix}", open=False):
111
+ seed = gr.Number(value=0, precision=0, label="Seed (0=random)")
112
+ temperature = gr.Slider(0.1, 2.0, value=0.8, step=0.05, label="Temperature")
113
+ top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.01, label="Top-p")
114
+ repetition_penalty = gr.Slider(1.0, 2.0, value=1.15, step=0.05, label="Repetition Penalty")
115
+ max_new_tokens = gr.Slider(256, 4096, value=2048, step=64, label="Max New Tokens")
116
+ return seed, temperature, top_p, repetition_penalty, max_new_tokens
117
+
118
+
119
+ def _pause_ui(prefix: str):
120
+ """Prosodic Pause controls — same UX as Minimax / ElevenLabs pause settings.
121
+ Returns 7 Slider components in this order:
122
+ sentence_ms, comma_ms, semicolon_ms, colon_ms, ellipsis_ms, newline_ms, default_ms
123
+ """
124
+ with gr.Accordion(f"🎵 Prosodic Pauses — {prefix}", open=False):
125
+ gr.Markdown(
126
+ "Control silence inserted **between sentences/clauses**. "
127
+ "Applied AFTER model renders audio — does not affect voice quality. "
128
+ "All values in **milliseconds (ms)**."
129
+ )
130
+ with gr.Row():
131
+ p_sentence = gr.Slider(0, 1500, value=500, step=10, label="Sentence end . ! ?")
132
+ p_comma = gr.Slider(0, 800, value=180, step=10, label="Comma ,")
133
+ p_semi = gr.Slider(0, 1000, value=300, step=10, label="Semicolon ;")
134
+ with gr.Row():
135
+ p_colon = gr.Slider(0, 1000, value=250, step=10, label="Colon :")
136
+ p_ellipsis = gr.Slider(0, 2000, value=700, step=10, label="Ellipsis … ...")
137
+ p_newline = gr.Slider(0, 2000, value=600, step=10, label="Newline / paragraph")
138
+ p_default = gr.Slider(0, 500, value=80, step=10, label="Default (no punctuation)")
139
+ return p_sentence, p_comma, p_semi, p_colon, p_ellipsis, p_newline, p_default
140
+
141
+
142
+ def _dropdown_update(selected: str = "None"):
143
+ choices = voice_choices()
144
+ value = selected if selected in choices else "None"
145
+ return gr.update(choices=choices, value=value)
146
+
147
+
148
+ def _save_cloned_voice_profile(voice_name, language, ref_audio, ref_text):
149
+ if not (ref_text or "").strip():
150
+ return (
151
+ "Error: Reference Transcript is required for Clone Voice.",
152
+ voice_rows(),
153
+ _dropdown_update(),
154
+ _dropdown_update(),
155
+ _dropdown_update(),
156
+ _dropdown_update(),
157
+ _dropdown_update(),
158
+ gr.update(),
159
+ gr.update(),
160
+ gr.update(),
161
+ gr.update(),
162
+ )
163
+ msg = save_voice_profile(voice_name, language, ref_text, "clone", ref_audio)
164
+ return (
165
+ msg,
166
+ voice_rows(),
167
+ _dropdown_update(voice_name),
168
+ _dropdown_update(voice_name),
169
+ _dropdown_update(voice_name),
170
+ _dropdown_update(voice_name),
171
+ _dropdown_update(voice_name),
172
+ gr.update(value=""),
173
+ gr.update(value="Auto"),
174
+ gr.update(value=None),
175
+ gr.update(value=""),
176
+ )
177
+
178
+
179
+ def _save_designed_voice_profile(voice_name, language, source_text, designed_audio):
180
+ msg = save_voice_profile(voice_name, language, source_text, "voice_design", designed_audio)
181
+ return msg, voice_rows(), _dropdown_update(voice_name), _dropdown_update(voice_name), _dropdown_update(voice_name), _dropdown_update(voice_name), _dropdown_update(voice_name)
182
+
183
+
184
+ def _refresh_voice_widgets():
185
+ return voice_rows(), _dropdown_update(), _dropdown_update(), _dropdown_update(), _dropdown_update(), _dropdown_update()
186
+
187
+
188
+ def _delete_voice_ui(name: str):
189
+ msg, rows, _ = delete_voice(name)
190
+ return msg, rows, _dropdown_update(), _dropdown_update(), _dropdown_update(), _dropdown_update(), _dropdown_update()
191
+
192
+
193
+ def _preview_voice_audio(name: str):
194
+ audio, _ = preview_saved_voice(name)
195
+ return audio
196
+
197
+
198
+ def _char_count_text(text: str) -> str:
199
+ return f"Characters: {len(text or '')}"
200
+
201
+
202
+ def _template_names():
203
+ return list(VOICE_DESCRIPTION_TEMPLATES.keys())
204
+
205
+
206
+ def _template_text(name: str) -> str:
207
+ return VOICE_DESCRIPTION_TEMPLATES.get(name or "", "")
208
+
209
+
210
+ def _apply_template(name: str):
211
+ return _template_text(name), Modal(visible=False)
212
+
213
+
214
+ def _apply_template_only_text(name: str):
215
+ return _template_text(name)
216
+
217
+
218
+ def _emotion_template_names():
219
+ return list(EMOTION_STYLE_TEMPLATES.keys())
220
+
221
+
222
+ def _emotion_template_text(name: str) -> str:
223
+ return EMOTION_STYLE_TEMPLATES.get(name or "", "")
224
+
225
+
226
+ def _apply_emotion_template(name: str):
227
+ return _emotion_template_text(name), Modal(visible=False)
228
+
229
+
230
+ def _resource_monitor_values():
231
+ ram_pct = None
232
+ ram_used = None
233
+ ram_total = None
234
+ if psutil is not None:
235
+ vm = psutil.virtual_memory()
236
+ ram_pct = vm.percent
237
+ ram_used = vm.used / (1024**3)
238
+ ram_total = vm.total / (1024**3)
239
+
240
+ vram_pct = None
241
+ vram_alloc = None
242
+ vram_reserved = None
243
+ vram_total = None
244
+ import torch
245
+ if torch.cuda.is_available():
246
+ idx = torch.cuda.current_device()
247
+ props = torch.cuda.get_device_properties(idx)
248
+ vram_total = props.total_memory / (1024**3)
249
+ vram_alloc = torch.cuda.memory_allocated(idx) / (1024**3)
250
+ vram_reserved = torch.cuda.memory_reserved(idx) / (1024**3)
251
+ vram_pct = min(100.0, (vram_reserved / max(vram_total, 1e-6)) * 100.0)
252
+
253
+ ram_line = "N/A"
254
+ ram_pct_value = 0.0
255
+ if ram_pct is not None and ram_used is not None and ram_total is not None:
256
+ ram_line = f"{ram_used:.1f} / {ram_total:.1f} GB ({ram_pct:.0f}%)"
257
+ ram_pct_value = float(max(0.0, min(100.0, ram_pct)))
258
+
259
+ vram_line = "CUDA not available"
260
+ vram_pct_value = 0.0
261
+ if vram_pct is not None and vram_alloc is not None and vram_reserved is not None and vram_total is not None:
262
+ vram_line = f"{vram_alloc:.2f} GB alloc | {vram_reserved:.2f} / {vram_total:.2f} GB reserved ({vram_pct:.0f}%)"
263
+ vram_pct_value = float(max(0.0, min(100.0, vram_pct)))
264
+
265
+ return ram_line, ram_pct_value, vram_line, vram_pct_value
266
+
267
+
268
+ def _vi_dropdown_update(selected: str = VI_NONE_CHOICE):
269
+ choices = vi_voice_choices()
270
+ value = selected if selected in choices else VI_NONE_CHOICE
271
+ return gr.update(choices=choices, value=value)
272
+
273
+
274
+ def _save_vi_voice_ui(voice_name, ref_audio, ref_text, batch_voice_val, news_voice_val):
275
+ ref_ta = (ref_text or "").strip()
276
+ if not ref_ta:
277
+ return (
278
+ "❌ Lỗi: Cần nhập transcript tiếng Việt để F5-TTS clone giọng chính xác.",
279
+ vi_voice_rows(),
280
+ _vi_dropdown_update(),
281
+ _vi_dropdown_update(batch_voice_val),
282
+ _vi_dropdown_update(news_voice_val),
283
+ )
284
+ msg = save_vi_voice(voice_name, ref_audio, ref_ta)
285
+ return msg, vi_voice_rows(), _vi_dropdown_update(voice_name), _vi_dropdown_update(voice_name), _vi_dropdown_update(voice_name)
286
+
287
+
288
+ def _delete_vi_voice_ui(name: str, batch_voice_val: str, news_voice_val: str):
289
+ msg = delete_vi_voice(name)
290
+ return msg, vi_voice_rows(), _vi_dropdown_update(), _vi_dropdown_update(batch_voice_val), _vi_dropdown_update(news_voice_val)
291
+
292
+
293
+ def _preview_vi_voice_ui(name: str):
294
+ audio_tuple, ref_text = preview_vi_voice(name)
295
+ return audio_tuple, ref_text
296
+
297
+
298
+ def build_ui():
299
+ ensure_voice_library()
300
+ ensure_vi_voice_library()
301
+
302
+ custom_css = """
303
+ .gradio-container {
304
+ max-width: none !important;
305
+ padding-left: 14px !important;
306
+ padding-right: 14px !important;
307
+ --color-accent: #2f62d0 !important;
308
+ --color-accent-soft: #e8f0ff !important;
309
+ --button-primary-background-fill: #2f62d0 !important;
310
+ --button-primary-background-fill-hover: #1d4fb7 !important;
311
+ --button-primary-border-color: #1d4fb7 !important;
312
+ --button-primary-text-color: #ffffff !important;
313
+ }
314
+ .tabs {border-radius: 12px;}
315
+ .tabs button {font-weight: 600 !important;}
316
+ .block, .gr-box, .gr-group {border-radius: 12px !important;}
317
+ .gr-button-primary,
318
+ .gradio-container button.primary,
319
+ .gradio-container .primary {
320
+ background: linear-gradient(135deg, #2f62d0, #1d4fb7) !important;
321
+ border: 0 !important;
322
+ color: #fff !important;
323
+ }
324
+ .resource-card {
325
+ border-radius: 12px !important;
326
+ padding: 14px !important;
327
+ border: 1px solid #3b3f4a !important;
328
+ outline: none !important;
329
+ background: #2c2f37 !important;
330
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.28) !important;
331
+ }
332
+ .resource-card * {color: #dce8ff !important;}
333
+ .resource-title {
334
+ margin: 0 0 10px 0 !important;
335
+ font-size: 1.05rem !important;
336
+ font-weight: 700 !important;
337
+ color: #f3f6ff !important;
338
+ }
339
+ .resource-section {
340
+ border-radius: 10px !important;
341
+ border: 1px solid #4a4f5d !important;
342
+ background: #3a3d47 !important;
343
+ padding: 10px 12px !important;
344
+ margin-top: 8px !important;
345
+ }
346
+ .resource-section .resource-label {
347
+ margin: 0 !important;
348
+ font-size: 0.82rem !important;
349
+ font-weight: 700 !important;
350
+ color: #e8eeff !important;
351
+ letter-spacing: 0.2px !important;
352
+ }
353
+ .resource-section .resource-value {
354
+ margin: 4px 0 8px 0 !important;
355
+ font-size: 0.9rem !important;
356
+ color: #d3dcf2 !important;
357
+ }
358
+ .resource-card input[type="range"] {
359
+ accent-color: #6da7ff !important;
360
+ }
361
+ .resource-card .gr-block,
362
+ .resource-card .gr-box,
363
+ .resource-card .gr-form {
364
+ background: transparent !important;
365
+ border: none !important;
366
+ box-shadow: none !important;
367
+ }
368
+ .resource-card .gradio-slider {
369
+ background: transparent !important;
370
+ border: none !important;
371
+ box-shadow: none !important;
372
+ padding-left: 0 !important;
373
+ padding-right: 0 !important;
374
+ }
375
+ .resource-card input[type="number"],
376
+ .resource-card button[aria-label*="refresh"],
377
+ .resource-card button[title*="refresh"] {
378
+ display: none !important;
379
+ }
380
+ .delete-btn {
381
+ background: linear-gradient(135deg, #e63946, #bd001b) !important;
382
+ color: #fff !important;
383
+ font-weight: bold !important;
384
+ border: 1px solid #ff4d4d !important;
385
+ font-size: 1.1rem !important;
386
+ padding: 12px !important;
387
+ border-radius: 8px !important;
388
+ box-shadow: 0 4px 10px rgba(230, 57, 70, 0.4) !important;
389
+ transition: all 0.2s ease !important;
390
+ }
391
+ .delete-btn:hover {
392
+ background: linear-gradient(135deg, #bd001b, #9e0015) !important;
393
+ box-shadow: 0 4px 12px rgba(230, 57, 70, 0.6) !important;
394
+ transform: translateY(-1px) !important;
395
+ }
396
+ """
397
+
398
+ with gr.Blocks(title="Qwen3-TTS Enhanced Studio", css=custom_css) as demo:
399
+ with gr.Row():
400
+ with gr.Column(scale=5):
401
+ gr.HTML(
402
+ f"""
403
+ <div style="max-width: 1000px; margin: 0 auto 14px auto; text-align: center; padding: 16px 18px; border-radius: 12px; background: linear-gradient(135deg, #0f2347 0%, #1b3a73 45%, #2b5298 100%); box-shadow: 0 6px 18px rgba(12, 26, 53, 0.28);">
404
+ <h1 style="margin: 0; font-size: 2.15rem; font-weight: 700; letter-spacing: 0.2px; color: #f5f8ff;">Qwen3-TTS Enhanced Studio</h1>
405
+ <p style="margin: 10px 0 8px 0; font-size: 1.02rem; color: #d7e4ff;">Professional voice workflows with persistent voice library and on-demand model loading.</p>
406
+ <div style="margin: 14px auto 0 auto; max-width: 920px; display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 10px; border: 1px solid rgba(170,197,255,0.35); background: rgba(255,255,255,0.08);">
407
+ <div style="width: 46px; height: 46px; min-width: 46px; border-radius: 50%; display: grid; place-items: center; font-size: 0.9rem; font-weight: 700; background: rgba(255, 255, 255, 0.18); border: 1px solid rgba(255,255,255,0.35); color: #eef5ff;">TOG</div>
408
+ <div style="flex: 1; text-align: left;">
409
+ <div style="font-size: 1rem; font-weight: 700; color:#f3f7ff; margin-bottom: 2px;">Qwen TTS by The Oracle Guy</div>
410
+ <div style="font-size: 0.88rem; color:#dce8ff;">Subscribe for more AI voice tools, updates, and releases.</div>
411
+ </div>
412
+ <a href="https://www.youtube.com/@theoracleguy_AI?sub_confirmation=1" target="_blank" style="text-decoration: none; background: linear-gradient(135deg, #ff5f6d, #ff3d57); color: #fff; border-radius: 8px; padding: 8px 13px; font-size: 0.86rem; font-weight: 700;">Subscribe</a>
413
+ </div>
414
+ </div>
415
+ """
416
+ )
417
+ with gr.Column(scale=2):
418
+ ram_line, ram_pct, vram_line, vram_pct = _resource_monitor_values()
419
+ with gr.Group(elem_classes=["resource-card"]):
420
+ gr.Markdown("<div class='resource-title'>Resource Monitor</div>")
421
+ with gr.Group(elem_classes=["resource-section"]):
422
+ gr.Markdown("<div class='resource-label'>RAM</div>")
423
+ resource_ram_line = gr.Markdown(f"<div class='resource-value'>{ram_line}</div>")
424
+ resource_ram_bar = gr.Slider(
425
+ minimum=0,
426
+ maximum=100,
427
+ value=ram_pct,
428
+ step=0.1,
429
+ label=None,
430
+ interactive=False,
431
+ show_label=False,
432
+ container=False,
433
+ show_reset_button=False,
434
+ )
435
+ with gr.Group(elem_classes=["resource-section"]):
436
+ gr.Markdown("<div class='resource-label'>VRAM</div>")
437
+ resource_vram_line = gr.Markdown(f"<div class='resource-value'>{vram_line}</div>")
438
+ resource_vram_bar = gr.Slider(
439
+ minimum=0,
440
+ maximum=100,
441
+ value=vram_pct,
442
+ step=0.1,
443
+ label=None,
444
+ interactive=False,
445
+ show_label=False,
446
+ container=False,
447
+ show_reset_button=False,
448
+ )
449
+ gr.Timer(2.0).tick(
450
+ _resource_monitor_values,
451
+ outputs=[resource_ram_line, resource_ram_bar, resource_vram_line, resource_vram_bar],
452
+ )
453
+
454
+ with gr.Tabs():
455
+ with gr.Tab("🌏 OMNI Voice Studio (VN + Global)"):
456
+ with gr.Row():
457
+ with gr.Column(scale=2):
458
+ with gr.Tabs():
459
+ with gr.Tab("🧬 Clone / Upload Voice"):
460
+ gr.Markdown("""
461
+ ### 🌏 Lưu Voice (OmniVoice — 600+ Ngôn Ngữ)
462
+ > Upload ref audio **ngắn (< 10 giây)**, sắt nét, ít tạp âm.
463
+ > Nhập transcript — OmniVoice sẽ auto-transcribe nếu bạn bỏ trống.
464
+ """)
465
+ vi_clone_name = gr.Textbox(label="Tên voice", placeholder="e.g. Nam_Cật_Nam")
466
+ vi_clone_audio = gr.Audio(
467
+ label="Ref Audio (âm thanh mẫu)",
468
+ type="numpy",
469
+ sources=["upload", "microphone"],
470
+ )
471
+ vi_clone_text = gr.Textbox(
472
+ label="Transcript Tiếng Việt (bắt buộc)",
473
+ lines=3,
474
+ placeholder="Nhập chính xác nội dung đoạn âm thanh tham chiếu...",
475
+ )
476
+ vi_clone_btn = gr.Button("💾 Lưu Voice VN", variant="primary")
477
+ vi_clone_status = gr.Textbox(label="Trạng thái", lines=2, interactive=False)
478
+
479
+ with gr.Column(scale=3):
480
+ gr.Markdown("### 📚 Thư viện Voice Tiếng Việt")
481
+ vi_refresh_btn = gr.Button("🔄 Refresh")
482
+ vi_voice_table = gr.Dataframe(
483
+ headers=["Tên", "Có Transcript", "Ngày tạo"],
484
+ value=vi_voice_rows(),
485
+ interactive=False,
486
+ row_count=(8, "fixed"),
487
+ )
488
+ vi_manage_voice = gr.Dropdown(
489
+ label="Chọn voice để quản lý",
490
+ choices=vi_voice_choices(),
491
+ value=VI_NONE_CHOICE,
492
+ )
493
+ vi_manage_preview = gr.Audio(label="Preview Voice", type="numpy")
494
+ vi_manage_text = gr.Textbox(label="Transcript đã lưu", lines=2, interactive=False)
495
+ vi_delete_btn = gr.Button("🗑️ XÓA VOICE ĐÃ CHỌN", variant="stop", elem_classes=["delete-btn"])
496
+ vi_delete_status = gr.Textbox(label="Delete Status", lines=2, interactive=False)
497
+
498
+ with gr.Tab("🌏 OMNI Batch (VN + Global)"):
499
+ with gr.Row():
500
+ with gr.Column(scale=2):
501
+ gr.Markdown("""
502
+ ### 🌏 OmniVoice — Batch TXT (600+ Ngôn Ngữ)
503
+ Xử lý nhiều file `.txt` bằng OmniVoice — hỗ trợ **ALL** ngôn ngữ.
504
+ Output: **MP3 + SRT** (tự động validate sau mỗi file).
505
+ """)
506
+ gr.Markdown("### 📂 Input Folders")
507
+ omni_paths = gr.Textbox(
508
+ label="Thư mục (mỗi dòng 1 đường dẫn)",
509
+ lines=3,
510
+ placeholder="D:\\Kenh\\Video1\nD:\\Kenh\\Video2",
511
+ )
512
+
513
+ gr.Markdown("### 🎤 Voice & Language")
514
+ omni_voice_select = gr.Dropdown(
515
+ label="Chọn Voice (từ Voice Studio)",
516
+ choices=vi_voice_choices(),
517
+ value=VI_NONE_CHOICE,
518
+ info="Voice được quản lý tại tab OMNI Voice Studio",
519
+ )
520
+ omni_voice_preview = gr.Audio(label="Preview Voice", type="numpy")
521
+ omni_language = gr.Dropdown(
522
+ label="🌐 Ngôn Ngữ (Language)",
523
+ choices=[
524
+ "auto", "Vietnamese", "English", "Chinese", "Japanese",
525
+ "Korean", "French", "German", "Spanish", "Italian",
526
+ "Portuguese", "Russian", "Arabic", "Hindi", "Thai",
527
+ "Indonesian", "Malay", "Filipino", "Turkish", "Polish",
528
+ "Dutch", "Swedish", "Czech", "Romanian", "Hungarian",
529
+ "Greek", "Hebrew", "Persian", "Ukrainian", "Bengali",
530
+ "Tamil", "Telugu", "Urdu", "Swahili",
531
+ ],
532
+ value="auto",
533
+ info="OmniVoice hỗ trợ 600+ ngôn ngữ — chọn 'auto' để tự phát hiện",
534
+ )
535
+
536
+ gr.Markdown("### ⚙️ Cài đặt")
537
+
538
+ try:
539
+ from qwen_app.omni_engine import gpu_profile as _gp
540
+ _auto_step = _gp.num_step
541
+ _gpu_info = (
542
+ f"> 🖥️ **GPU Auto-Tune:** {_gp.gpu_name} ({_gp.vram_gb:.1f}GB) | "
543
+ f"Tier **{_gp.tier.upper()}** | "
544
+ f"Steps={_gp.num_step} | Chunk={_gp.chunk_size}\n"
545
+ )
546
+ except Exception:
547
+ _auto_step = 32
548
+ _gpu_info = ""
549
+
550
+ with gr.Row():
551
+ omni_speed = gr.Slider(0.5, 2.0, value=1.0, step=0.05, label="Speed")
552
+ omni_step = gr.Slider(8, 64, value=_auto_step, step=8,
553
+ label=f"Diffusion Steps (auto={_auto_step})")
554
+ omni_norm = gr.Checkbox(label="Normalize", value=True)
555
+
556
+ gr.Markdown("#### ⚡ Hiệu suất (Flash Attention 2)")
557
+ with gr.Row():
558
+ omni_flash2 = gr.Checkbox(label="Bật Flash-Attention 2", value=False)
559
+ omni_flash2_whl = gr.File(label="Chọn file .whl (Chỉ cần 1 lần đầu)", file_types=[".whl"], type="filepath", file_count="single")
560
+
561
+ gr.Markdown("#### 🛡️ Pre-check (Kiểm duyệt văn bản)")
562
+ with gr.Group(elem_classes=["resource-section"]):
563
+ omni_precheck = gr.Checkbox(label="Bật kiểm tra dấu câu bắt buộc", value=True)
564
+ with gr.Row():
565
+ omni_precheck_punct = gr.Textbox(label="Các dấu câu bắt buộc", value=".,!?;:。?!…", lines=1)
566
+ omni_precheck_max_len = gr.Number(label="Độ dài tối đa đoạn không có dấu câu (ký tự)", value=400, precision=0)
567
+
568
+ gr.Markdown(f"""
569
+ {_gpu_info}> ℹ️ **Auto Chunk:** Tự động theo VRAM GPU.
570
+ > 🌍 **OmniVoice** — RTF 0.025 (40x faster than real-time).
571
+ > Steps cao hơn = chất lượng cao hơn (32 khuyến nghị, 16 nếu cần nhanh).
572
+ """)
573
+
574
+ omni_ps, omni_pc, omni_psc, omni_pco, omni_pel, omni_pnl, omni_pdf = _pause_ui("OMNI Batch")
575
+ omni_btn = gr.Button("🚀 START OMNI BATCH", variant="primary")
576
+
577
+ with gr.Column(scale=2):
578
+ gr.Markdown("### 📋 Execution Log")
579
+ omni_log = gr.Textbox(
580
+ label="Status",
581
+ lines=28,
582
+ max_lines=40,
583
+ interactive=False,
584
+ value="Sẵn sàng. Chọn voice + folder + language rồi nhấn START.",
585
+ )
586
+
587
+
588
+ with gr.Tab("📰 OMNI News Batch (Phase)"):
589
+ with gr.Row():
590
+ with gr.Column(scale=2):
591
+ gr.Markdown("""
592
+ ### 📰 OmniVoice — News Batch (Phase Mode)
593
+ Xử lý hàng loạt file `.txt` theo **định dạng PHASE** (STORY | PHASE N | nội dung | Prompt N: ...)
594
+ Mỗi PHASE → **1 MP3 riêng** + `FULL_MASTER.srt` tổng hợp.
595
+ Dùng **OmniVoice 600+ ngôn ngữ** — clone giọng tự động.
596
+ """)
597
+ gr.Markdown("### 📂 Input Folders")
598
+ omni_news_paths = gr.Textbox(
599
+ label="Thư mục chứa file .txt (mỗi dòng 1 đường dẫn)",
600
+ lines=3,
601
+ placeholder="D:\\Kenh\\Video1\nD:\\Kenh\\Video2",
602
+ )
603
+
604
+ gr.Markdown("### 🎤 Voice & Language")
605
+ omni_news_voice = gr.Dropdown(
606
+ label="Chọn Voice (từ OMNI Voice Studio)",
607
+ choices=vi_voice_choices(),
608
+ value=VI_NONE_CHOICE,
609
+ info="Voice được quản lý tại tab OMNI Voice Studio",
610
+ )
611
+ omni_news_preview = gr.Audio(label="Preview Voice", type="numpy")
612
+ omni_news_language = gr.Dropdown(
613
+ label="🌐 Ngôn Ngữ (Language)",
614
+ choices=[
615
+ "auto", "Vietnamese", "English", "Chinese", "Japanese",
616
+ "Korean", "French", "German", "Spanish", "Italian",
617
+ "Portuguese", "Russian", "Arabic", "Hindi", "Thai",
618
+ "Indonesian", "Malay", "Filipino", "Turkish", "Polish",
619
+ "Dutch", "Swedish", "Czech", "Romanian", "Hungarian",
620
+ "Greek", "Hebrew", "Persian", "Ukrainian", "Bengali",
621
+ "Tamil", "Telugu", "Urdu", "Swahili",
622
+ ],
623
+ value="auto",
624
+ info="OmniVoice hỗ trợ 600+ ngôn ngữ — chọn 'auto' để tự phát hiện",
625
+ )
626
+
627
+ gr.Markdown("### ⚙️ Cài đặt")
628
+ with gr.Row():
629
+ omni_news_speed = gr.Slider(0.5, 2.0, value=1.0, step=0.05, label="Speed")
630
+ omni_news_step = gr.Slider(8, 64, value=_auto_step, step=8,
631
+ label=f"Diffusion Steps (auto={_auto_step})")
632
+ omni_news_norm = gr.Checkbox(label="Normalize", value=True)
633
+
634
+ gr.Markdown("#### ⚡ Hiệu suất (Flash Attention 2)")
635
+ with gr.Row():
636
+ omni_news_flash2 = gr.Checkbox(label="Bật Flash-Attention 2", value=False)
637
+ omni_news_flash2_whl = gr.File(label="Chọn file .whl (Chỉ cần 1 lần đầu)", file_types=[".whl"], type="filepath", file_count="single")
638
+
639
+ gr.Markdown("#### 🛡️ Pre-check (Kiểm duyệt văn bản)")
640
+ with gr.Group(elem_classes=["resource-section"]):
641
+ omni_news_precheck = gr.Checkbox(label="Bật kiểm tra dấu câu bắt buộc", value=True)
642
+ with gr.Row():
643
+ omni_news_precheck_punct = gr.Textbox(label="Các dấu câu bắt buộc", value=".,!?;:。?!…", lines=1)
644
+ omni_news_precheck_max_len = gr.Number(label="Độ dài tối đa đoạn không có dấu câu (ký tự)", value=400, precision=0)
645
+
646
+ gr.Markdown("""
647
+ > 📋 **Định dạng PHASE** yêu cầu:
648
+ > `STORY |`
649
+ > `PHASE 1 | nội dung... | Prompt 1: mô tả`
650
+ > `PHASE 2 | nội dung... | Prompt 2: mô tả`
651
+ > `END GAMES`
652
+ >
653
+ > ✅ Output: `_OUTPUT_PROJECTS/<tên file>/<phase>.mp3` + `FULL_MASTER.srt`
654
+ """)
655
+
656
+ omni_news_ps, omni_news_pc, omni_news_psc, omni_news_pco, omni_news_pel, omni_news_pnl, omni_news_pdf = _pause_ui("OMNI News")
657
+ omni_news_btn = gr.Button("🚀 START OMNI NEWS BATCH", variant="primary")
658
+
659
+ with gr.Column(scale=2):
660
+ gr.Markdown("### 📋 Execution Log")
661
+ omni_news_log = gr.Textbox(
662
+ label="Status",
663
+ lines=28,
664
+ max_lines=40,
665
+ interactive=False,
666
+ value="Sẵn sàng. Chọn voice + folder + language rồi nhấn START.",
667
+ )
668
+
669
+ with gr.Tab("🔍 Audio Validator"):
670
+ gr.Markdown("""
671
+ ### 🔍 Bidirectional Audio ↔ SRT Integrity Validator
672
+ Công cụ trung gian kiểm tra TOÀN BỘ tính toàn vẹn của output:
673
+ - **SRT → Audio**: mỗi dòng SRT có âm thanh thực sự không? (phát hiện đoạn silent)
674
+ - **Audio → SRT**: mỗi vùng có tiếng nói có SRT entry không? (phát hiện timestamp lệch)
675
+ - Báo cáo chi tiết với severity CRITICAL / WARNING và hành động khắc phục
676
+ """)
677
+ with gr.Row():
678
+ with gr.Column(scale=1):
679
+ gr.Markdown("#### 📂 Validate Output Folder (Batch)")
680
+ val_folder = gr.Textbox(
681
+ label="Output folder path",
682
+ placeholder=r"D:\Kenh\Video1\_OUTPUT_PROJECTS\story_name",
683
+ lines=1,
684
+ )
685
+ val_master_srt = gr.Textbox(
686
+ label="Custom SRT path (optional, leave blank for auto-detect FULL_MASTER.srt)",
687
+ placeholder=r"D:\...\FULL_MASTER.srt",
688
+ lines=1,
689
+ )
690
+ val_folder_btn = gr.Button("🔍 Validate Folder", variant="primary")
691
+
692
+ gr.Markdown("---")
693
+ gr.Markdown("#### 🎯 Validate Single File Pair")
694
+ val_audio_file = gr.Textbox(
695
+ label="Audio file path (.mp3 / .wav)",
696
+ placeholder=r"D:\...\phase.mp3",
697
+ lines=1,
698
+ )
699
+ val_srt_file = gr.Textbox(
700
+ label="SRT file path",
701
+ placeholder=r"D:\...\FULL_MASTER.srt",
702
+ lines=1,
703
+ )
704
+ val_single_btn = gr.Button("🔍 Validate Single Pair", variant="secondary")
705
+
706
+ with gr.Column(scale=2):
707
+ gr.Markdown("### 📋 Validation Report")
708
+ val_log = gr.Textbox(
709
+ label="Report",
710
+ lines=32,
711
+ max_lines=60,
712
+ interactive=False,
713
+ value="Chưa có kết quả. Nhấn Validate để bắt đầu.",
714
+ )
715
+
716
+ # ── Audio Validator handlers ──────────────────────────────────────────
717
+ def _run_validate_folder(folder: str, master_srt: str) -> str:
718
+ folder = (folder or "").strip()
719
+ if not folder or not os.path.isdir(folder):
720
+ return "❌ Đường dẫn folder không hợp lệ hoặc không tồn tại."
721
+ srt_override = (master_srt or "").strip() or None
722
+ reports = validate_batch_output(folder, master_srt=srt_override)
723
+ if not reports:
724
+ return "⚠️ Không tìm thấy file MP3 nào trong folder này."
725
+ return format_batch_reports(reports)
726
+
727
+ def _run_validate_single(audio_path: str, srt_path: str) -> str:
728
+ audio_path = (audio_path or "").strip()
729
+ srt_path = (srt_path or "").strip()
730
+ if not audio_path or not os.path.exists(audio_path):
731
+ return "❌ File audio không tồn tại."
732
+ if not srt_path or not os.path.exists(srt_path):
733
+ return "❌ File SRT không tồn tại."
734
+ report = validate_audio_vs_srt(audio_path, srt_path)
735
+ return format_validation_report(report)
736
+
737
+ val_folder_btn.click(
738
+ _run_validate_folder,
739
+ inputs=[val_folder, val_master_srt],
740
+ outputs=[val_log],
741
+ )
742
+
743
+ val_single_btn.click(
744
+ _run_validate_single,
745
+ inputs=[val_audio_file, val_srt_file],
746
+ outputs=[val_log],
747
+ )
748
+
749
+ # ── OMNI Voice Studio (VN + Global) ─────────────────────────────────────
750
+ vi_clone_btn.click(
751
+ _save_vi_voice_ui,
752
+ inputs=[vi_clone_name, vi_clone_audio, vi_clone_text, omni_voice_select, omni_news_voice],
753
+ outputs=[vi_clone_status, vi_voice_table, vi_manage_voice, omni_voice_select, omni_news_voice],
754
+ )
755
+
756
+ vi_refresh_btn.click(
757
+ lambda v1, v2, v3: (vi_voice_rows(), _vi_dropdown_update(v1), _vi_dropdown_update(v2), _vi_dropdown_update(v3)),
758
+ inputs=[vi_manage_voice, omni_voice_select, omni_news_voice],
759
+ outputs=[vi_voice_table, vi_manage_voice, omni_voice_select, omni_news_voice],
760
+ )
761
+
762
+ vi_manage_voice.change(
763
+ _preview_vi_voice_ui,
764
+ inputs=[vi_manage_voice],
765
+ outputs=[vi_manage_preview, vi_manage_text],
766
+ )
767
+
768
+ vi_delete_btn.click(
769
+ _delete_vi_voice_ui,
770
+ inputs=[vi_manage_voice, omni_voice_select, omni_news_voice],
771
+ outputs=[vi_delete_status, vi_voice_table, vi_manage_voice, omni_voice_select, omni_news_voice],
772
+ )
773
+
774
+ # ── OMNI Batch (VN + Global) ──────────────────────────────────────────
775
+ omni_voice_select.change(
776
+ lambda name: _preview_vi_voice_ui(name)[0],
777
+ inputs=[omni_voice_select],
778
+ outputs=[omni_voice_preview],
779
+ )
780
+
781
+ omni_btn.click(
782
+ process_omni_batch_txt,
783
+ inputs=[
784
+ omni_paths, omni_voice_select,
785
+ omni_speed, omni_norm, omni_step, omni_language,
786
+ omni_flash2, omni_flash2_whl,
787
+ omni_precheck, omni_precheck_punct, omni_precheck_max_len,
788
+ omni_ps, omni_pc, omni_psc, omni_pco, omni_pel, omni_pnl, omni_pdf,
789
+ ],
790
+ outputs=[omni_log],
791
+ )
792
+
793
+ # ── OMNI News Batch (Phase) ───────────────────────────────────────────
794
+ omni_news_voice.change(
795
+ lambda name: _preview_vi_voice_ui(name)[0],
796
+ inputs=[omni_news_voice],
797
+ outputs=[omni_news_preview],
798
+ )
799
+
800
+ omni_news_btn.click(
801
+ process_omni_news_batch,
802
+ inputs=[
803
+ omni_news_paths, omni_news_voice,
804
+ omni_news_speed, omni_news_norm, omni_news_step, omni_news_language,
805
+ omni_news_flash2, omni_news_flash2_whl,
806
+ omni_news_precheck, omni_news_precheck_punct, omni_news_precheck_max_len,
807
+ omni_news_ps, omni_news_pc, omni_news_psc, omni_news_pco,
808
+ omni_news_pel, omni_news_pnl, omni_news_pdf,
809
+ ],
810
+ outputs=[omni_news_log],
811
+ )
812
+
813
+ return demo
source/qwen_app/vi_normalizer.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/vi_normalizer.py
2
+ """
3
+ Vietnamese Pure-Python Text Normalizer
4
+ Zero pip dependencies.
5
+ Handles:
6
+ 1. Numbers (1,500,000 -> một triệu năm trăm nghìn)
7
+ 2. Dates (15/08/2023 -> mười lăm tháng tám năm hai không hai ba)
8
+ 3. Symbols ($ -> đô la, % -> phần trăm)
9
+ 4. Loanwords (Facebook -> phây búc)
10
+ """
11
+
12
+ import re
13
+
14
+ # ─── 1. LOANWORDS DICTIONARY ────────────────────────────────────────────────
15
+
16
+ LOANWORDS = {
17
+ "facebook": "phây búc",
18
+ "fb": "phây búc",
19
+ "marketing": "ma két tinh",
20
+ "smartphone": "xờ mát phôn",
21
+ "video": "vi đê ô",
22
+ "live": "lai",
23
+ "livestream": "lai chim",
24
+ "app": "áp",
25
+ "web": "oép",
26
+ "website": "oép sai",
27
+ "page": "pết",
28
+ "fanpage": "phan pết",
29
+ "tiktok": "tích tóc",
30
+ "youtube": "diu túp",
31
+ "google": "gu gồ",
32
+ "wifi": "oai phai",
33
+ "internet": "in tơ nét",
34
+ "online": "on lai",
35
+ "offline": "ọp lai",
36
+ "email": "i meo",
37
+ "mail": "meo",
38
+ "hotline": "hót lai",
39
+ "admin": "át min",
40
+ "sale": "xêu",
41
+ "sales": "xêu",
42
+ "nhân viên sale": "nhân viên xêu",
43
+ "pr": "pi a",
44
+ "ce": "xê e",
45
+ "ceo": "xi y âu",
46
+ "cfo": "xi ép âu",
47
+ "cto": "xi tê âu",
48
+ "kpi": "cây pi ai",
49
+ "okr": "âu ka rờ",
50
+ "view": "viu",
51
+ "like": "lai",
52
+ "share": "se",
53
+ "comment": "com men",
54
+ "post": "pốt",
55
+ "group": "rúp",
56
+ "update": "ấp đết",
57
+ "trend": "tren",
58
+ "hot": "hót",
59
+ "idol": "ai đồ",
60
+ "show": "xô",
61
+ "game": "gêm",
62
+ "laptop": "láp tốp",
63
+ "pc": "bê xê",
64
+ "macbook": "mác búc",
65
+ "apple": "áp pồ",
66
+ "samsung": "sam sung",
67
+ "ok": "ô kê",
68
+ "okay": "ô kê",
69
+ "vnđ": "đồng",
70
+ "vnd": "đồng",
71
+ "usd": "đô la mỹ",
72
+ }
73
+
74
+ # ─── 2. NUMBER TO TEXT ───────────────────────────────────────────────────────
75
+
76
+ DIGITS = ["không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"]
77
+ UNITS = ["", "nghìn", "triệu", "tỷ", "nghìn tỷ", "triệu tỷ"]
78
+
79
+ def _read_3_digits(n: int, read_zero_hundred: bool = False) -> str:
80
+ if n == 0:
81
+ return "không không không" if read_zero_hundred else ""
82
+
83
+ h = n // 100
84
+ rem = n % 100
85
+ t = rem // 10
86
+ u = rem % 10
87
+
88
+ words = []
89
+
90
+ if h > 0 or read_zero_hundred:
91
+ words.append(DIGITS[h])
92
+ words.append("trăm")
93
+
94
+ if t > 1:
95
+ words.append(DIGITS[t])
96
+ words.append("mươi")
97
+ if u == 1:
98
+ words.append("mốt")
99
+ elif u == 5:
100
+ words.append("lăm")
101
+ elif u > 0:
102
+ words.append(DIGITS[u])
103
+ elif t == 1:
104
+ words.append("mười")
105
+ if u == 5:
106
+ words.append("lăm")
107
+ elif u > 0:
108
+ words.append(DIGITS[u])
109
+ elif t == 0 and u > 0:
110
+ if h > 0 or read_zero_hundred:
111
+ words.append("lẻ")
112
+ words.append(DIGITS[u])
113
+
114
+ return " ".join(words)
115
+
116
+ def num_to_vi(n: int) -> str:
117
+ if n == 0:
118
+ return "không"
119
+
120
+ is_negative = n < 0
121
+ n = abs(n)
122
+
123
+ blocks = []
124
+ while n > 0:
125
+ blocks.append(n % 1000)
126
+ n //= 1000
127
+
128
+ words = []
129
+ for i, block in enumerate(blocks):
130
+ if block > 0:
131
+ read_zero = i < len(blocks) - 1 and blocks[i] < 100
132
+ if i > 0 and len(blocks) > 1 and i < len(blocks) - 1:
133
+ read_zero = True
134
+
135
+ block_str = _read_3_digits(block, read_zero_hundred=(i < len(blocks) -1))
136
+ block_str = block_str.strip()
137
+
138
+ if block_str:
139
+ if UNITS[i]:
140
+ words.insert(0, UNITS[i])
141
+ words.insert(0, block_str)
142
+
143
+ res = " ".join(words).strip()
144
+ # Cleanup edge cases
145
+ res = re.sub(r'không trăm lẻ không\s*', '', res).strip()
146
+ return "âm " + res if is_negative else res
147
+
148
+ # ─── 3. TEXT REPLACEMENTS ────────────────────────────────────────────────────
149
+
150
+ def _replace_number_match(match):
151
+ num_str = match.group(0)
152
+ # Remove dots and commas used as thousand separators
153
+ clean_num = num_str.replace('.', '').replace(',', '')
154
+ try:
155
+ val = int(clean_num)
156
+ return num_to_vi(val)
157
+ except:
158
+ return num_str
159
+
160
+ def _replace_date_match(match):
161
+ d = match.group(1)
162
+ m = match.group(2)
163
+ y = match.group(4) # group 3 is the / delimiter
164
+
165
+ res = f"ngày {num_to_vi(int(d))} tháng {num_to_vi(int(m))}"
166
+ if y:
167
+ # read year digit by digit if starts with 20 or read normally
168
+ year_val = int(y)
169
+ res += f" năm {num_to_vi(year_val)}"
170
+ return res
171
+
172
+ def normalize_vi_text(text: str) -> str:
173
+ if not text:
174
+ return text
175
+
176
+ # 1. Loanwords (Case insensitive word boundary)
177
+ for word, replacement in LOANWORDS.items():
178
+ text = re.sub(rf'\b{word}\b', replacement, text, flags=re.IGNORECASE)
179
+
180
+ # 2. Symbols
181
+ text = text.replace('%', ' phần trăm ')
182
+ text = text.replace('$', ' đô la ')
183
+ text = text.replace('&', ' và ')
184
+ text = text.replace('+', ' cộng ')
185
+
186
+ # 3. Dates (dd/mm/yyyy or dd/mm)
187
+ text = re.sub(r'\b(\d{1,2})/(\d{1,2})(/(\d{2,4}))?\b', _replace_date_match, text)
188
+
189
+ # 4. Numbers (e.g. 1.500.000 or 1500000)
190
+ text = re.sub(r'\b\d{1,3}(?:[.,]\d{3})+\b|\b\d+\b', _replace_number_match, text)
191
+
192
+ # Cleanup extra spaces
193
+ text = re.sub(r'\s+', ' ', text).strip()
194
+
195
+ return text
196
+
197
+ if __name__ == "__main__":
198
+ t = "Smartphone này giá 1.500.000 VNĐ ra mắt ngày 15/08/2023 trên Facebook"
199
+ print(normalize_vi_text(t))
source/qwen_app/vi_prosody.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/vi_prosody.py
2
+ """
3
+ Vietnamese Prosody Preprocessor — 100% Pure Python
4
+ ====================================================
5
+ ZERO external dependencies. No pip install needed.
6
+
7
+ Built-in Vietnamese word segmentation + grammar rules
8
+ to insert natural pause markers for F5-TTS.
9
+
10
+ Pipeline:
11
+ Raw text → normalize → grammar analysis → <#x#> pause markers → F5-TTS
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ import re
18
+ from typing import List, Tuple
19
+
20
+ logger = logging.getLogger("qwen_app.vi_prosody")
21
+
22
+
23
+ # ─── Built-in Vietnamese Word Database ───────────────────────────────────────
24
+ # These replace pyvi — lightweight, no dependencies
25
+
26
+ # Conjunctions → pause 0.15s BEFORE
27
+ CONJUNCTIONS = {
28
+ "và", "nhưng", "hoặc", "mà", "rồi", "nên", "vì", "do",
29
+ "tuy", "song", "bởi", "hay", "dù", "để", "nếu", "thì",
30
+ "còn", "lại", "mới", "nào", "như", "khi",
31
+ }
32
+
33
+ # Prepositions → pause 0.1s BEFORE (lighter than conjunction)
34
+ PREPOSITIONS = {
35
+ "trong", "ngoài", "trên", "dưới", "về", "từ", "với",
36
+ "bằng", "theo", "qua", "đến", "tới", "giữa", "cùng",
37
+ "trước", "sau", "bên", "gần", "xa",
38
+ }
39
+
40
+ # Sentence-opening adverbs → pause 0.3s AFTER (longest first for greedy match)
41
+ SENTENCE_ADVERBS = [
42
+ "nói cách khác", "bên cạnh đó", "chính vì thế", "thêm vào đó",
43
+ "không những", "ngoài ra", "hơn nữa", "mặt khác",
44
+ "nói chung", "tóm lại", "trước hết", "sau đó",
45
+ "tiếp theo", "cuối cùng", "đặc biệt", "tuy nhiên",
46
+ "vì vậy", "do đó", "thật ra", "thực ra", "rõ ràng",
47
+ "dĩ nhiên", "tất nhiên", "bỗng nhiên", "bất ngờ",
48
+ "đột nhiên", "thế rồi", "rồi thì", "đồng thời",
49
+ "ngược lại", "may mắn", "không may", "đáng tiếc",
50
+ "lạ thay", "thú vị", "quả thật", "đúng vậy",
51
+ "rất tiếc", "tuy vậy", "dù sao", "mặc dù",
52
+ "cho nên", "bởi vậy", "vì thế", "nhờ đó",
53
+ ]
54
+
55
+ # Time/place markers at sentence start → pause AFTER
56
+ TIME_PLACE = [
57
+ "hôm nay", "hôm qua", "ngày mai", "tối nay", "sáng nay",
58
+ "chiều nay", "lúc đó", "khi đó", "bấy giờ", "ngày xưa",
59
+ "thuở xưa", "xa xưa", "ở đây", "tại đây", "nơi đây",
60
+ "bên ngoài", "bên trong", "phía trước", "phía sau",
61
+ "ngay lúc đó", "vào lúc đó", "trong lúc đó",
62
+ "mỗi ngày", "mỗi sáng", "mỗi tối", "từ đó",
63
+ ]
64
+
65
+ # Emotion/intensity words → slight pause BEFORE for emphasis
66
+ EMPHASIS_WORDS = {
67
+ "thật", "rất", "quá", "vô_cùng", "cực_kỳ", "hết_sức",
68
+ "khủng_khiếp", "kinh_khủng", "tuyệt_vời", "tuyệt_đẹp",
69
+ }
70
+
71
+ # Common Vietnamese compound words (2-syllable) to NOT split
72
+ COMPOUNDS = {
73
+ "việt nam", "hà nội", "sài gòn", "đà nẵng", "hải phòng",
74
+ "thành phố", "đại học", "bệnh viện", "trường học",
75
+ "công nghệ", "khoa học", "xã hội", "kinh tế",
76
+ "chính trị", "văn hóa", "lịch sử", "giáo dục",
77
+ "quốc gia", "thế giới", "con người", "cuộc sống",
78
+ "tình yêu", "hạnh phúc", "gia đình", "bạn bè",
79
+ }
80
+
81
+ # Common abbreviations
82
+ ABBREVIATIONS = {
83
+ "TP.": "thành phố", "PGS.": "phó giáo sư", "GS.": "giáo sư",
84
+ "TS.": "tiến sĩ", "ThS.": "thạc sĩ", "BS.": "bác sĩ",
85
+ "KS.": "kỹ sư", "NXB.": "nhà xuất bản", "PGĐ.": "phó giám đốc",
86
+ "TPHCM": "thành phố hồ chí minh",
87
+ "VND": "việt nam đồng", "USD": "đô la mỹ",
88
+ }
89
+
90
+
91
+ # ─── Stage 1: Text Normalization ─────────────────────────────────────────────
92
+
93
+ def normalize_vietnamese(text: str) -> str:
94
+ """Normalize Vietnamese text — pure Python, zero dependencies."""
95
+ if not text or not text.strip():
96
+ return text
97
+
98
+ result = text.strip()
99
+
100
+ # Expand abbreviations
101
+ for abbr, full in ABBREVIATIONS.items():
102
+ result = result.replace(abbr, full)
103
+
104
+ # Unicode quote normalization
105
+ for old, new in [('\u201c', '"'), ('\u201d', '"'), ('\u2018', "'"), ('\u2019', "'")]:
106
+ result = result.replace(old, new)
107
+
108
+ # Normalize dots: ". . ." → "..."
109
+ result = re.sub(r'\.\s*\.\s*\.', '...', result)
110
+
111
+ # Collapse whitespace
112
+ result = re.sub(r'[ \t]+', ' ', result)
113
+ result = re.sub(r'\n+', ' ', result)
114
+
115
+ # Ensure ending punctuation
116
+ result = result.strip()
117
+ if result and result[-1] not in '.!?':
118
+ result += '.'
119
+
120
+ return result
121
+
122
+
123
+ # ─── Stage 2: Grammar-Aware Prosody ──────────────────────────────────────────
124
+
125
+ def predict_prosody(text: str) -> str:
126
+ """
127
+ Insert <#x#> pause markers using Vietnamese grammar rules.
128
+ 100% Python — no external libraries.
129
+ """
130
+ if not text or not text.strip():
131
+ return text
132
+
133
+ # Split into sentences safely (supports quotes and ellipses) without look-behind
134
+ pattern = r'([.!?…।؟。!?]+[\"\'”’]?(?:[ \t]+|\n+|$))'
135
+ parts = re.split(pattern, text)
136
+ sentences = []
137
+ for i in range(0, len(parts) - 1, 2):
138
+ sent = parts[i] + parts[i+1]
139
+ if sent.strip():
140
+ sentences.append(sent.strip())
141
+ if len(parts) % 2 != 0 and parts[-1].strip():
142
+ sentences.append(parts[-1].strip())
143
+
144
+ processed = []
145
+
146
+ for sent in sentences:
147
+ if not sent.strip():
148
+ continue
149
+ result = _process_sentence(sent)
150
+ processed.append(result)
151
+
152
+ # Join sentences with inter-sentence pause
153
+ return ' <#0.4#> '.join(processed)
154
+
155
+
156
+ def _process_sentence(sent: str) -> str:
157
+ """Process a single sentence: add pauses at grammatically correct positions."""
158
+
159
+ # 1. Handle ellipsis FIRST (dramatic pause)
160
+ result = re.sub(r'\.\.\.+\s*', '... <#0.6#> ', sent)
161
+
162
+ # 2. Handle existing punctuation
163
+ result = re.sub(r',\s+', ', <#0.2#> ', result)
164
+ result = re.sub(r':\s+', ': <#0.3#> ', result)
165
+ result = re.sub(r';\s+', '; <#0.25#> ', result)
166
+
167
+ # 3. Handle quotes (dramatic pause before/after dialogue)
168
+ result = re.sub(r'\s+"', ' <#0.3#> "', result)
169
+ result = re.sub(r'"\s+', '" <#0.3#> ', result)
170
+
171
+ # 4. Check sentence-opening adverbs
172
+ sent_lower = result.lower().lstrip()
173
+ for adverb in SENTENCE_ADVERBS:
174
+ if sent_lower.startswith(adverb):
175
+ idx = len(adverb)
176
+ rest = result[idx:].lstrip()
177
+ if not rest.startswith(',') and not rest.startswith('<#'):
178
+ result = result[:idx] + ', <#0.3#> ' + rest
179
+ break
180
+
181
+ # 5. Check time/place markers at sentence start
182
+ if not any(sent_lower.startswith(a) for a in SENTENCE_ADVERBS):
183
+ for tp in TIME_PLACE:
184
+ if sent_lower.startswith(tp):
185
+ idx = len(tp)
186
+ rest = result[idx:].lstrip()
187
+ if not rest.startswith(',') and not rest.startswith('<#'):
188
+ result = result[:idx] + ', <#0.2#> ' + rest
189
+ break
190
+
191
+ # 6. Word-level analysis: conjunctions, prepositions, long clauses
192
+ words = result.split()
193
+ new_words = []
194
+ word_count = 0 # words since last pause
195
+
196
+ for i, word in enumerate(words):
197
+ # Skip existing pause markers
198
+ if word.startswith('<#') and word.endswith('#>'):
199
+ new_words.append(word)
200
+ word_count = 0
201
+ continue
202
+
203
+ clean = word.lower().strip('.,!?;:"\'-')
204
+
205
+ # Hỗ trợ đắc lực: Chỉ ngắt trước liên từ/giới từ khi câu đang dồn quá nhiều chữ (>5 chữ)
206
+ if clean in CONJUNCTIONS and i > 2 and word_count > 4:
207
+ if not (new_words and new_words[-1].startswith('<#')):
208
+ new_words.append('<#0.15#>')
209
+ word_count = 0
210
+
211
+ elif clean in PREPOSITIONS and i > 3 and word_count > 6:
212
+ if not (new_words and new_words[-1].startswith('<#')):
213
+ new_words.append('<#0.1#>')
214
+ word_count = 0
215
+
216
+ new_words.append(word)
217
+ word_count += 1
218
+
219
+ # Reset counter after punctuation
220
+ if word.endswith((',', '.', '!', '?', ';', ':', '...')):
221
+ word_count = 0
222
+
223
+ result = ' '.join(new_words)
224
+
225
+ # 7. Cleanup: remove double markers
226
+ result = re.sub(r'(<#[\d.]+#>\s*){2,}', lambda m: m.group(0).split()[0] + ' ', result)
227
+ result = re.sub(r'^\s*<#[\d.]+#>\s*', '', result)
228
+
229
+ return result.strip()
230
+
231
+
232
+ # ─── Main API ────────────────────────────────────────────────────────────────
233
+
234
+ def preprocess_simple(text: str) -> str:
235
+ """
236
+ Full pipeline: normalize → prosody → text with <#x#> markers.
237
+ Called by mode_f5_batch.py before chunking.
238
+ """
239
+ if not text or not text.strip():
240
+ return text
241
+
242
+ normalized = normalize_vietnamese(text)
243
+ result = predict_prosody(normalized)
244
+
245
+ marker_count = result.count('<#')
246
+ logger.info(f"[vi_prosody] {len(text)} chars → {marker_count} pause markers")
247
+ return result
248
+
249
+
250
+ def split_by_pauses(text: str) -> List[Tuple[str, float]]:
251
+ """Split text with <#x#> markers into [(segment, pause_seconds)]."""
252
+ if not text:
253
+ return [("", 0.0)]
254
+ parts = re.split(r'<#(\d+\.?\d*)#>', text)
255
+ segments = []
256
+ for i in range(0, len(parts), 2):
257
+ t = parts[i].strip()
258
+ if not t:
259
+ continue
260
+ p = float(parts[i + 1]) if i + 1 < len(parts) else 0.0
261
+ segments.append((t, p))
262
+ return segments if segments else [(text, 0.0)]
source/qwen_app/voice_library.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import uuid
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+ import numpy as np
9
+ import soundfile as sf
10
+
11
+ from .config import VOICE_AUDIO_DIR, VOICE_DB_PATH, VOICE_LIB_DIR
12
+
13
+
14
+ def ensure_voice_library() -> None:
15
+ VOICE_AUDIO_DIR.mkdir(parents=True, exist_ok=True)
16
+ if not VOICE_DB_PATH.exists():
17
+ VOICE_DB_PATH.write_text(json.dumps({"voices": []}, indent=2), encoding="utf-8")
18
+
19
+
20
+ def load_voice_db() -> Dict:
21
+ ensure_voice_library()
22
+ try:
23
+ return json.loads(VOICE_DB_PATH.read_text(encoding="utf-8"))
24
+ except Exception:
25
+ return {"voices": []}
26
+
27
+
28
+ def save_voice_db(db: Dict) -> None:
29
+ ensure_voice_library()
30
+ VOICE_DB_PATH.write_text(json.dumps(db, indent=2), encoding="utf-8")
31
+
32
+
33
+ def slugify(value: str) -> str:
34
+ value = re.sub(r"[^a-zA-Z0-9_-]+", "-", value.strip()).strip("-")
35
+ return value.lower() or "voice"
36
+
37
+
38
+ def normalize_audio(wav, eps: float = 1e-12, clip: bool = True) -> np.ndarray:
39
+ x = np.asarray(wav)
40
+
41
+ if np.issubdtype(x.dtype, np.integer):
42
+ info = np.iinfo(x.dtype)
43
+ if info.min < 0:
44
+ y = x.astype(np.float32) / max(abs(info.min), info.max)
45
+ else:
46
+ mid = (info.max + 1) / 2.0
47
+ y = (x.astype(np.float32) - mid) / mid
48
+ elif np.issubdtype(x.dtype, np.floating):
49
+ y = x.astype(np.float32)
50
+ m = np.max(np.abs(y)) if y.size else 0.0
51
+ if m > 1.0 + 1e-6:
52
+ y = y / (m + eps)
53
+ else:
54
+ raise TypeError(f"Unsupported audio dtype: {x.dtype}")
55
+
56
+ if clip:
57
+ y = np.clip(y, -1.0, 1.0)
58
+
59
+ if y.ndim > 1:
60
+ y = np.mean(y, axis=-1).astype(np.float32)
61
+
62
+ return y
63
+
64
+
65
+ def audio_to_tuple(audio) -> Optional[Tuple[np.ndarray, int]]:
66
+ if audio is None:
67
+ return None
68
+
69
+ if isinstance(audio, tuple) and len(audio) == 2:
70
+ if isinstance(audio[0], int):
71
+ sr, wav = audio
72
+ return normalize_audio(wav), int(sr)
73
+ if isinstance(audio[1], int):
74
+ wav, sr = audio
75
+ return normalize_audio(wav), int(sr)
76
+
77
+ if isinstance(audio, dict) and "sampling_rate" in audio and "data" in audio:
78
+ return normalize_audio(audio["data"]), int(audio["sampling_rate"])
79
+
80
+ if isinstance(audio, str) and Path(audio).exists():
81
+ wav, sr = sf.read(audio, dtype="float32", always_2d=False)
82
+ if wav.ndim > 1:
83
+ wav = np.mean(wav, axis=-1)
84
+ return normalize_audio(wav), int(sr)
85
+
86
+ return None
87
+
88
+
89
+ def set_seed(seed: int) -> None:
90
+ if seed <= 0:
91
+ return
92
+ import torch
93
+ import numpy as np
94
+ torch.manual_seed(seed)
95
+ np.random.seed(seed)
96
+ if torch.cuda.is_available():
97
+ torch.cuda.manual_seed_all(seed)
98
+
99
+ def voice_choices() -> List[str]:
100
+ voices = load_voice_db().get("voices", [])
101
+ names = sorted(v.get("name", "") for v in voices if v.get("name"))
102
+ return ["None"] + names
103
+
104
+
105
+ def voice_rows() -> List[List[str]]:
106
+ voices = sorted(load_voice_db().get("voices", []), key=lambda x: x.get("created_at", ""), reverse=True)
107
+ return [
108
+ [
109
+ v.get("name", ""),
110
+ v.get("source", ""),
111
+ v.get("language", ""),
112
+ "yes" if v.get("ref_text") else "no",
113
+ v.get("created_at", ""),
114
+ ]
115
+ for v in voices
116
+ ]
117
+
118
+
119
+ def find_voice(name: str) -> Optional[Dict]:
120
+ if not name or name == "None":
121
+ return None
122
+ for item in load_voice_db().get("voices", []):
123
+ if item.get("name") == name:
124
+ return item
125
+ return None
126
+
127
+
128
+ def save_voice_profile(name: str, language: str, ref_text: str, source: str, audio_data) -> str:
129
+ parsed = audio_to_tuple(audio_data)
130
+ if parsed is None:
131
+ return "Error: audio is required to save voice profile."
132
+
133
+ wav, sr = parsed
134
+ if not name or not name.strip():
135
+ return "Error: voice name is required."
136
+
137
+ ensure_voice_library()
138
+ db = load_voice_db()
139
+
140
+ voice_id = f"{slugify(name)}-{uuid.uuid4().hex[:8]}"
141
+ audio_rel = Path("audio") / f"{voice_id}.wav"
142
+ audio_abs = VOICE_LIB_DIR / audio_rel
143
+ sf.write(audio_abs.as_posix(), wav, sr)
144
+
145
+ db["voices"] = [v for v in db.get("voices", []) if v.get("name") != name.strip()]
146
+ db["voices"].append(
147
+ {
148
+ "id": voice_id,
149
+ "name": name.strip(),
150
+ "language": language or "Auto",
151
+ "ref_text": (ref_text or "").strip(),
152
+ "source": source,
153
+ "audio_path": audio_rel.as_posix(),
154
+ "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
155
+ }
156
+ )
157
+ save_voice_db(db)
158
+ return f"Saved voice profile: {name.strip()}"
159
+
160
+
161
+ def delete_voice(name: str):
162
+ if not name or name == "None":
163
+ return "Select a voice to delete.", voice_rows(), None
164
+
165
+ db = load_voice_db()
166
+ voices = db.get("voices", [])
167
+ target = None
168
+ kept = []
169
+ for v in voices:
170
+ if v.get("name") == name:
171
+ target = v
172
+ else:
173
+ kept.append(v)
174
+
175
+ if target is None:
176
+ return "Voice not found.", voice_rows(), None
177
+
178
+ audio_path = VOICE_LIB_DIR / Path(target.get("audio_path", ""))
179
+ if audio_path.exists():
180
+ try:
181
+ audio_path.unlink()
182
+ except Exception:
183
+ pass
184
+
185
+ db["voices"] = kept
186
+ save_voice_db(db)
187
+ return f"Deleted voice: {name}", voice_rows(), None
188
+
189
+
190
+ def preview_saved_voice(name: str):
191
+ v = find_voice(name)
192
+ if v is None:
193
+ return None, ""
194
+ path = VOICE_LIB_DIR / Path(v.get("audio_path", ""))
195
+ if not path.exists():
196
+ return None, ""
197
+ wav, sr = sf.read(path.as_posix(), dtype="float32", always_2d=False)
198
+ if wav.ndim > 1:
199
+ wav = np.mean(wav, axis=-1)
200
+ return (int(sr), normalize_audio(wav)), v.get("ref_text", "")
201
+
202
+
203
+ def resolve_reference(selected_voice_name: str, uploaded_audio, uploaded_ref_text: str, xvector_only: bool):
204
+ ref_audio, _, ref_text, note = resolve_reference_details(
205
+ selected_voice_name=selected_voice_name,
206
+ uploaded_audio=uploaded_audio,
207
+ uploaded_ref_text=uploaded_ref_text,
208
+ xvector_only=xvector_only,
209
+ )
210
+ return ref_audio, ref_text, note
211
+
212
+
213
+ def resolve_reference_details(selected_voice_name: str, uploaded_audio, uploaded_ref_text: str, xvector_only: bool):
214
+ uploaded = audio_to_tuple(uploaded_audio)
215
+ if uploaded is not None:
216
+ ref_text = (uploaded_ref_text or "").strip()
217
+ if (not xvector_only) and not ref_text:
218
+ return None, None, None, "Error: transcript is required when x-vector-only is disabled."
219
+ return uploaded, None, ref_text if ref_text else None, "Using uploaded reference audio."
220
+
221
+ v = find_voice(selected_voice_name)
222
+ if v is None:
223
+ return None, None, None, "Error: provide reference audio or select a saved voice."
224
+
225
+ p = VOICE_LIB_DIR / Path(v.get("audio_path", ""))
226
+ if not p.exists():
227
+ return None, None, None, f"Error: saved audio file missing for voice '{selected_voice_name}'."
228
+
229
+ wav, sr = sf.read(p.as_posix(), dtype="float32", always_2d=False)
230
+ if wav.ndim > 1:
231
+ wav = np.mean(wav, axis=-1)
232
+ ref_audio = (normalize_audio(wav), int(sr))
233
+
234
+ ref_text = (v.get("ref_text") or "").strip()
235
+ if (not xvector_only) and not ref_text:
236
+ return None, None, None, f"Error: saved voice '{selected_voice_name}' has no transcript. Enable x-vector-only or provide transcript."
237
+
238
+ return ref_audio, p.as_posix(), ref_text if ref_text else None, f"Using saved voice: {selected_voice_name}"
source/qwen_app/voice_library_vi.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # qwen_app/voice_library_vi.py
2
+ """
3
+ Vietnamese Voice Library — Hoàn toàn độc lập với Qwen Voice Library
4
+ ====================================================================
5
+ Lưu trữ voice profiles tiếng Việt (ref audio + transcript) dùng cho F5-TTS.
6
+ Data folder: D:\Qwen3-TTS\Qwen3-TTS\voice_library_vi\
7
+ ├── index.json — {name: {ref_audio, ref_text, created}}
8
+ └── <name>.wav — ref audio file
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import shutil
16
+ import time
17
+ from typing import List, Optional, Tuple
18
+
19
+ import numpy as np
20
+
21
+ # ─── Constants ────────────────────────────────────────────────────────────────
22
+ _VI_LIB_DIR = os.path.join(
23
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
24
+ "voice_library_vi"
25
+ )
26
+ _INDEX_FILE = os.path.join(_VI_LIB_DIR, "index.json")
27
+
28
+ NONE_CHOICE = "None"
29
+
30
+
31
+ # ─── Internal helpers ─────────────────────────────────────────────────────────
32
+
33
+ def _ensure_dir() -> None:
34
+ os.makedirs(_VI_LIB_DIR, exist_ok=True)
35
+
36
+
37
+ def _load_index() -> dict:
38
+ _ensure_dir()
39
+ if not os.path.exists(_INDEX_FILE):
40
+ return {}
41
+ try:
42
+ with open(_INDEX_FILE, "r", encoding="utf-8") as f:
43
+ return json.load(f)
44
+ except Exception:
45
+ return {}
46
+
47
+
48
+ def _save_index(index: dict) -> None:
49
+ _ensure_dir()
50
+ with open(_INDEX_FILE, "w", encoding="utf-8") as f:
51
+ json.dump(index, f, ensure_ascii=False, indent=2)
52
+
53
+
54
+ # ─── Public API ───────────────────────────────────────────────────────────────
55
+
56
+ def ensure_vi_voice_library() -> None:
57
+ """Create voice library directory if not exists."""
58
+ _ensure_dir()
59
+
60
+
61
+ def vi_voice_choices() -> List[str]:
62
+ """Return [NONE_CHOICE, name1, name2, ...] for Gradio Dropdown."""
63
+ idx = _load_index()
64
+ return [NONE_CHOICE] + sorted(idx.keys())
65
+
66
+
67
+ def vi_voice_rows() -> List[List[str]]:
68
+ """Return rows for Gradio Dataframe: [Name, Has Transcript, Created]."""
69
+ idx = _load_index()
70
+ rows = []
71
+ for name, info in sorted(idx.items()):
72
+ has_text = "✅" if info.get("ref_text") else "❌"
73
+ created = info.get("created", "")[:19].replace("T", " ")
74
+ rows.append([name, has_text, created])
75
+ return rows if rows else [["—", "—", "—"]]
76
+
77
+
78
+ def save_vi_voice(
79
+ voice_name: str,
80
+ ref_audio, # numpy array from gr.Audio(type="numpy") OR file path str
81
+ ref_text: str,
82
+ sample_rate: int = 22050,
83
+ ) -> str:
84
+ """
85
+ Save a Vietnamese voice profile.
86
+ ref_audio can be:
87
+ - tuple (sr, np.ndarray) from Gradio Audio widget
88
+ - str file path
89
+ - np.ndarray
90
+ Returns status message.
91
+ """
92
+ name = (voice_name or "").strip()
93
+ if not name:
94
+ return "❌ Lỗi: Tên voice không được để trống."
95
+
96
+ # Validate ref_text
97
+ ref_text_clean = (ref_text or "").strip()
98
+ if not ref_text_clean:
99
+ return "❌ Lỗi: Transcript là bắt buộc để clone giọng chính xác."
100
+
101
+ _ensure_dir()
102
+
103
+ try:
104
+ import soundfile as sf
105
+
106
+ out_path = os.path.join(_VI_LIB_DIR, f"{name}.wav")
107
+
108
+ if isinstance(ref_audio, str):
109
+ # File path — copy directly
110
+ if not os.path.exists(ref_audio):
111
+ return f"❌ Lỗi: Không tìm thấy file audio: {ref_audio}"
112
+ shutil.copy2(ref_audio, out_path)
113
+
114
+ elif isinstance(ref_audio, (tuple, list)) and len(ref_audio) == 2:
115
+ # Gradio (sr, ndarray)
116
+ sr, arr = ref_audio
117
+ if arr is None or len(arr) == 0:
118
+ return "❌ Lỗi: Audio rỗng, vui lòng upload lại."
119
+ arr = arr.astype(np.float32)
120
+ if arr.ndim == 2: # stereo → mono
121
+ arr = arr.mean(axis=1)
122
+ # Normalize to [-1, 1]
123
+ peak = np.abs(arr).max()
124
+ if peak > 1e-6:
125
+ arr = arr / peak * 0.95
126
+ sf.write(out_path, arr, int(sr))
127
+
128
+ elif isinstance(ref_audio, np.ndarray):
129
+ arr = ref_audio.astype(np.float32)
130
+ if arr.ndim == 2:
131
+ arr = arr.mean(axis=1)
132
+ sf.write(out_path, arr, sample_rate)
133
+
134
+ else:
135
+ return "❌ Lỗi: Định dạng audio không hỗ trợ."
136
+
137
+ # Update index
138
+ idx = _load_index()
139
+ idx[name] = {
140
+ "ref_audio": out_path,
141
+ "ref_text": ref_text_clean,
142
+ "created": time.strftime("%Y-%m-%dT%H:%M:%S"),
143
+ }
144
+ _save_index(idx)
145
+ return f"✅ Đã lưu voice '{name}' vào Vietnamese Voice Library."
146
+
147
+ except Exception as e:
148
+ return f"❌ Lỗi khi lưu voice: {e}"
149
+
150
+
151
+ def delete_vi_voice(voice_name: str) -> str:
152
+ """Delete a voice profile and its audio file. Returns status message."""
153
+ name = (voice_name or "").strip()
154
+ if not name or name == NONE_CHOICE:
155
+ return "❌ Chọn voice cần xóa trước."
156
+
157
+ idx = _load_index()
158
+ if name not in idx:
159
+ return f"❌ Không tìm thấy voice '{name}'."
160
+
161
+ # Remove audio file
162
+ audio_path = idx[name].get("ref_audio", "")
163
+ if audio_path and os.path.exists(audio_path):
164
+ try:
165
+ os.remove(audio_path)
166
+ except Exception:
167
+ pass
168
+
169
+ del idx[name]
170
+ _save_index(idx)
171
+ return f"✅ Đã xóa voice '{name}'."
172
+
173
+
174
+ def preview_vi_voice(voice_name: str) -> Tuple[Optional[tuple], str]:
175
+ """
176
+ Load ref audio for preview.
177
+ Returns (gradio_audio_tuple, ref_text) or (None, "").
178
+ """
179
+ if not voice_name or voice_name == NONE_CHOICE:
180
+ return None, ""
181
+
182
+ idx = _load_index()
183
+ if voice_name not in idx:
184
+ return None, ""
185
+
186
+ info = idx[voice_name]
187
+ audio_path = info.get("ref_audio", "")
188
+ ref_text = info.get("ref_text", "")
189
+
190
+ if not audio_path or not os.path.exists(audio_path):
191
+ return None, ref_text
192
+
193
+ try:
194
+ import soundfile as sf
195
+ arr, sr = sf.read(audio_path, dtype="float32")
196
+ return (int(sr), arr), ref_text
197
+ except Exception:
198
+ return None, ref_text
199
+
200
+
201
+ def resolve_vi_ref(voice_name: str) -> Tuple[Optional[str], str]:
202
+ """
203
+ Resolve selected voice to (ref_audio_path, ref_text).
204
+ Returns (None, "") if not found.
205
+ """
206
+ if not voice_name or voice_name == NONE_CHOICE:
207
+ return None, ""
208
+
209
+ idx = _load_index()
210
+ if voice_name not in idx:
211
+ return None, ""
212
+
213
+ info = idx[voice_name]
214
+ audio_path = info.get("ref_audio", "")
215
+ ref_text = info.get("ref_text", "")
216
+
217
+ if not os.path.exists(audio_path):
218
+ return None, ref_text
219
+
220
+ return audio_path, ref_text