README.md CHANGED
@@ -34,23 +34,22 @@ Mỗi giọng gồm `profile.json`, `voice.pt` (prompt cache), audio mẫu và `
34
 
35
  ## Chạy trên Colab
36
 
37
- 1. **Lồng tiếng SRT:** mở `colab/Omivoice_VI_Colab.ipynb`
38
- 2. **Clone giọng mới:** mở `colab/Omivoice_VI_Clone_Colab.ipynb`
39
- 3. Đặt `HF_REPO = "<repo-này>"`
40
- 4. Runtime → GPU → chạy từng cell
41
 
42
  ## Cấu trúc
43
 
44
  ```
45
  ├── voices/<slug>/ # profile + voice.pt + ref audio
46
  ├── tools/speak.py # TTS + SRT pipeline
47
- └── colab/ # Notebook Colab (SRT + Clone)
48
  ```
49
 
50
  ## SRT merge modes
51
 
52
- - **`native`** (mặc định, khuyến nghị): native ≤cap dùng gap tới cue sau → stretch ≤x1.1 → chồng nhẹ đuôi (crossfade). **Không đẩy timestamp SRT** — mỗi cue neo đúng `start` gốc. Rút gọn câu: tự sửa trên file SRT.
53
- - **`cascade`**: giữ tốc độ tự nhiên, cue dài đẩy cue sau (lệch timeline)
54
  - **`fit`**: kéo nén tín hiệu vừa khung SRT
55
  - **`strict`**: ghép theo timestamp (có thể cắt audio)
56
 
 
34
 
35
  ## Chạy trên Colab
36
 
37
+ 1. Mở notebook `colab/Omivoice_VI_Colab.ipynb`
38
+ 2. Đặt `HF_REPO = "<repo-này>"`
39
+ 3. Runtime GPU → chạy từng cell
 
40
 
41
  ## Cấu trúc
42
 
43
  ```
44
  ├── voices/<slug>/ # profile + voice.pt + ref audio
45
  ├── tools/speak.py # TTS + SRT pipeline
46
+ └── colab/ # Notebook Colab
47
  ```
48
 
49
  ## SRT merge modes
50
 
51
+ - **`native`** (mặc định): model nói nhanh native, tràn vào khoảng trống sau cue, không cắt ngắt
52
+ - **`cascade`**: giữ tốc độ tự nhiên, cue dài đẩy cue sau
53
  - **`fit`**: kéo nén tín hiệu vừa khung SRT
54
  - **`strict`**: ghép theo timestamp (có thể cắt audio)
55
 
colab/Omivoice_VI_Clone_Colab.ipynb DELETED
@@ -1,505 +0,0 @@
1
- {
2
- "nbformat": 4,
3
- "nbformat_minor": 5,
4
- "metadata": {
5
- "kernelspec": {
6
- "display_name": "Python 3",
7
- "language": "python",
8
- "name": "python3"
9
- },
10
- "language_info": {
11
- "name": "python",
12
- "version": "3.10.0"
13
- },
14
- "accelerator": "GPU",
15
- "colab": {
16
- "provenance": [],
17
- "gpuType": "L4"
18
- }
19
- },
20
- "cells": [
21
- {
22
- "cell_type": "markdown",
23
- "metadata": {},
24
- "source": [
25
- "# OmniVoice — Clone giọng tiếng Việt trên Colab\n",
26
- "\n",
27
- "Notebook **tạo voice profile** (`voice.pt`) từ audio mẫu trên Google Drive, cùng stack với [Omivoice_VI_Colab.ipynb](Omivoice_VI_Colab.ipynb).\n",
28
- "\n",
29
- "**Luồng Drive:**\n",
30
- "1. Đặt file audio mẫu vào **`MyDrive/Omivoice/`** (vd. `0709.WAV`)\n",
31
- "2. Cấu hình slug / đoạn cắt / transcript ở **mục 0**\n",
32
- "3. Chạy notebook → ghi `voices/<slug>/` lên Drive (`ref.wav`, `ref_text.txt`, `profile.json`, `voice.pt`)\n",
33
- "\n",
34
- "**Quan trọng:** cắt audio **đủ hết câu** (đừng cắt giữa câu — dễ hụt chữ/hụt âm khi clone).\n",
35
- "\n",
36
- "**Yêu cầu:** Runtime **GPU L4** (Runtime → Change runtime type → L4)."
37
- ],
38
- "id": "md_intro"
39
- },
40
- {
41
- "cell_type": "markdown",
42
- "metadata": {},
43
- "source": [
44
- "## 0. Cấu hình"
45
- ],
46
- "id": "md_cfg"
47
- },
48
- {
49
- "cell_type": "code",
50
- "metadata": {},
51
- "source": [
52
- "# Hugging Face (tools/speak.py + giọng mẫu nếu cần)\n",
53
- "HF_REPO = \"STBack23/omnivoice-vi\"\n",
54
- "\n",
55
- "# Google Drive — MyDrive/Omivoice/\n",
56
- "DRIVE_FOLDER = \"Omivoice\"\n",
57
- "SRC_AUDIO = \"0709.WAV\" # file audio mẫu trong MyDrive/Omivoice/\n",
58
- "\n",
59
- "# Giọng mới\n",
60
- "VOICE_SLUG = \"injoyreel\" # thư mục voices/<slug>/\n",
61
- "VOICE_NAME = \"InjoyReel\"\n",
62
- "LANGUAGE = \"Vietnamese\"\n",
63
- "\n",
64
- "# Cắt đoạn mẫu (giây) — PHẢI đủ hết câu\n",
65
- "# Ví dụ InjoyReel: câu dẫn chuyện cue 1–8 → ~0.13 đến ~13.93\n",
66
- "CUT_START = 0.130\n",
67
- "CUT_END = 13.929\n",
68
- "\n",
69
- "# Transcript khớp đúng đoạn cắt (bắt buộc nếu AUTO_TRANSCRIBE=False)\n",
70
- "REF_TEXT = (\n",
71
- " \"Hôm nay tập đoàn Hoắc thị tổ chức tiệc đón người thừa kế trở về tại dinh thự. \"\n",
72
- " \"Được biết người thừa kế bí ẩn này Hoắc Cảnh Chu chưa từng xuất hiện trước công chúng bao giờ. \"\n",
73
- " \"Sự trở về đề phô trương này không biết có phải mang ý nghĩa ảnh đã nắm toàn quyền phát ngôn của tập đoàn không.\"\n",
74
- ")\n",
75
- "\n",
76
- "# True = Whisper tự nhận transcript (bỏ REF_TEXT). False = dùng REF_TEXT.\n",
77
- "AUTO_TRANSCRIBE = False\n",
78
- "\n",
79
- "# True = model tự bỏ silence khi build. False = giữ nguyên đoạn đã cắt tay.\n",
80
- "PREPROCESS_PROMPT = False\n",
81
- "\n",
82
- "# Test nhanh sau khi clone\n",
83
- "TEST_TEXT = REF_TEXT\n",
84
- "RUN_TEST = True"
85
- ],
86
- "execution_count": null,
87
- "outputs": [],
88
- "id": "cfg"
89
- },
90
- {
91
- "cell_type": "markdown",
92
- "metadata": {},
93
- "source": [
94
- "## 1. Kiểm tra GPU & cài đặt"
95
- ],
96
- "id": "md_gpu"
97
- },
98
- {
99
- "cell_type": "code",
100
- "metadata": {},
101
- "source": [
102
- "import torch\n",
103
- "\n",
104
- "assert torch.cuda.is_available(), (\n",
105
- " \"Bật GPU L4: Runtime → Change runtime type → Hardware accelerator → L4\"\n",
106
- ")\n",
107
- "gpu = torch.cuda.get_device_name(0)\n",
108
- "print(f\"GPU: {gpu}\")\n",
109
- "if \"L4\" not in gpu.upper():\n",
110
- " print(\n",
111
- " f\"⚠ Đang dùng {gpu}, không phải L4 — đổi runtime sang L4 để nhanh hơn.\"\n",
112
- " )"
113
- ],
114
- "execution_count": null,
115
- "outputs": [],
116
- "id": "gpu"
117
- },
118
- {
119
- "cell_type": "code",
120
- "metadata": {},
121
- "source": [
122
- "# Tắt XET — thường gây treo download ~89% trên Colab.\n",
123
- "# PHẢI chạy cell này TRƯỚC mọi `from huggingface_hub import ...`\n",
124
- "import os\n",
125
- "\n",
126
- "os.environ[\"HF_HUB_DISABLE_XET\"] = \"1\"\n",
127
- "os.environ[\"HF_HUB_DOWNLOAD_TIMEOUT\"] = \"300\"\n",
128
- "\n",
129
- "print(\"HF: HF_HUB_DISABLE_XET=1, timeout 300s\")"
130
- ],
131
- "execution_count": null,
132
- "outputs": [],
133
- "id": "xet"
134
- },
135
- {
136
- "cell_type": "code",
137
- "metadata": {},
138
- "source": [
139
- "!pip install -q omnivoice audiotsm huggingface_hub soundfile librosa"
140
- ],
141
- "execution_count": null,
142
- "outputs": [],
143
- "id": "pip"
144
- },
145
- {
146
- "cell_type": "markdown",
147
- "metadata": {},
148
- "source": [
149
- "### Repo private — đăng nhập Hugging Face (một lần)\n",
150
- "\n",
151
- "1. Tạo token **Read** tại [hf.co/settings/tokens](https://huggingface.co/settings/tokens)\n",
152
- "2. Colab → **🔑 Khóa bí mật** (Manage secrets) → thêm tên `HF_TOKEN`, dán token → **Lưu**\n",
153
- "3. Chỉ cần làm **một lần** — các lần chạy sau notebook tự lấy token"
154
- ],
155
- "id": "md_hf_login"
156
- },
157
- {
158
- "cell_type": "code",
159
- "metadata": {},
160
- "source": [
161
- "from huggingface_hub import login\n",
162
- "from google.colab import userdata\n",
163
- "\n",
164
- "try:\n",
165
- " token = userdata.get(\"HF_TOKEN\")\n",
166
- "except userdata.SecretNotFoundError as e:\n",
167
- " raise RuntimeError(\n",
168
- " \"Chưa có khóa bí mật HF_TOKEN.\\n\"\n",
169
- " \"Colab → 🔑 Khóa bí mật → Thêm secret tên HF_TOKEN \"\n",
170
- " \"(token Read từ hf.co/settings/tokens).\\n\"\n",
171
- " \"Lưu một lần, lần sau không cần nhập lại.\"\n",
172
- " ) from e\n",
173
- "\n",
174
- "if not token or not str(token).strip():\n",
175
- " raise RuntimeError(\"HF_TOKEN trong Khóa bí mật đang trống — hãy cập nhật lại.\")\n",
176
- "\n",
177
- "login(token.strip())\n",
178
- "print(\"Đã login Hugging Face (HF_TOKEN từ Khóa bí mật)\")"
179
- ],
180
- "execution_count": null,
181
- "outputs": [],
182
- "id": "hf_login"
183
- },
184
- {
185
- "cell_type": "markdown",
186
- "metadata": {},
187
- "source": [
188
- "## 2. Tải công cụ từ Hugging Face"
189
- ],
190
- "id": "md_tools"
191
- },
192
- {
193
- "cell_type": "code",
194
- "metadata": {},
195
- "source": [
196
- "from pathlib import Path\n",
197
- "from huggingface_hub import snapshot_download\n",
198
- "\n",
199
- "ROOT = Path(\n",
200
- " snapshot_download(HF_REPO, repo_type=\"dataset\", local_dir=\"/content/omnivoice-vi\")\n",
201
- ")\n",
202
- "print(f\"Đã tải: {ROOT}\")\n",
203
- "print(\"Giọng có sẵn:\", [p.parent.name for p in sorted((ROOT / \"voices\").glob(\"*/profile.json\"))])"
204
- ],
205
- "execution_count": null,
206
- "outputs": [],
207
- "id": "hf_dl"
208
- },
209
- {
210
- "cell_type": "code",
211
- "metadata": {},
212
- "source": [
213
- "import importlib.util\n",
214
- "import sys\n",
215
- "\n",
216
- "speak_path = ROOT / \"tools\" / \"speak.py\"\n",
217
- "spec = importlib.util.spec_from_file_location(\"speak\", speak_path)\n",
218
- "speak = importlib.util.module_from_spec(spec)\n",
219
- "sys.modules[\"speak\"] = speak\n",
220
- "spec.loader.exec_module(speak)\n",
221
- "print(\"Đã load speak.py\")"
222
- ],
223
- "execution_count": null,
224
- "outputs": [],
225
- "id": "load_speak"
226
- },
227
- {
228
- "cell_type": "markdown",
229
- "metadata": {},
230
- "source": [
231
- "## 3. Tải & nạp model (~3–8 phút lần đầu)\n",
232
- "\n",
233
- "Lần đầu tải **~3.3 GB**. Treo ở ~89% → **Runtime → Restart session**, chạy lại từ **mục 1** (cell tắt XET phải chạy trước login HF)."
234
- ],
235
- "id": "md_model"
236
- },
237
- {
238
- "cell_type": "code",
239
- "metadata": {},
240
- "source": [
241
- "from huggingface_hub import hf_hub_download\n",
242
- "\n",
243
- "OMNI_MODEL = \"k2-fsa/OmniVoice\"\n",
244
- "\n",
245
- "for relpath, label in [\n",
246
- " (\"model.safetensors\", \"LLM ~2.4 GB\"),\n",
247
- " (\"audio_tokenizer/model.safetensors\", \"Audio tokenizer ~770 MB\"),\n",
248
- "]:\n",
249
- " print(f\"\\n>>> {label}\")\n",
250
- " path = hf_hub_download(OMNI_MODEL, relpath)\n",
251
- " print(f\" OK: {path}\")\n",
252
- "\n",
253
- "for relpath in (\n",
254
- " \"config.json\",\n",
255
- " \"tokenizer.json\",\n",
256
- " \"tokenizer_config.json\",\n",
257
- " \"chat_template.jinja\",\n",
258
- " \"audio_tokenizer/config.json\",\n",
259
- " \"audio_tokenizer/preprocessor_config.json\",\n",
260
- "):\n",
261
- " hf_hub_download(OMNI_MODEL, relpath)\n",
262
- "\n",
263
- "print(\"\\n✓ Model k2-fsa/OmniVoice đã cache xong.\")"
264
- ],
265
- "execution_count": null,
266
- "outputs": [],
267
- "id": "model_cache"
268
- },
269
- {
270
- "cell_type": "markdown",
271
- "metadata": {},
272
- "source": [
273
- "## 4. Mount Drive & cắt audio mẫu\n",
274
- "\n",
275
- "Đặt file audio vào **`MyDrive/Omivoice/`**. Notebook cắt đoạn `[CUT_START, CUT_END]` rồi ghi profile lên Drive."
276
- ],
277
- "id": "md_drive"
278
- },
279
- {
280
- "cell_type": "code",
281
- "metadata": {},
282
- "source": [
283
- "import json\n",
284
- "import re\n",
285
- "import numpy as np\n",
286
- "import soundfile as sf\n",
287
- "from google.colab import drive\n",
288
- "\n",
289
- "drive.mount(\"/content/drive\")\n",
290
- "\n",
291
- "DRIVE_OMIVOICE = Path(\"/content/drive/MyDrive\") / DRIVE_FOLDER\n",
292
- "DRIVE_OMIVOICE.mkdir(parents=True, exist_ok=True)\n",
293
- "\n",
294
- "SRC_PATH = DRIVE_OMIVOICE / SRC_AUDIO\n",
295
- "if not SRC_PATH.exists():\n",
296
- " existing = sorted(\n",
297
- " list(DRIVE_OMIVOICE.glob(\"*.wav\"))\n",
298
- " + list(DRIVE_OMIVOICE.glob(\"*.WAV\"))\n",
299
- " + list(DRIVE_OMIVOICE.glob(\"*.mp3\"))\n",
300
- " )\n",
301
- " hint = \"\\n \".join(p.name for p in existing) if existing else \"(chưa có audio)\"\n",
302
- " raise FileNotFoundError(\n",
303
- " f\"Không thấy {SRC_PATH}\\n\"\n",
304
- " f\"Đặt file vào MyDrive/{DRIVE_FOLDER}/ hoặc sửa SRC_AUDIO.\\n\"\n",
305
- " f\"Các file audio hiện có:\\n {hint}\"\n",
306
- " )\n",
307
- "\n",
308
- "slug = re.sub(r\"[^a-z0-9_]+\", \"_\", VOICE_SLUG.strip().lower()).strip(\"_\")\n",
309
- "if not slug:\n",
310
- " raise ValueError(\"VOICE_SLUG không hợp lệ\")\n",
311
- "\n",
312
- "VOICE_DIR = DRIVE_OMIVOICE / \"voices\" / slug\n",
313
- "VOICE_DIR.mkdir(parents=True, exist_ok=True)\n",
314
- "\n",
315
- "if CUT_END <= CUT_START:\n",
316
- " raise ValueError(f\"CUT_END ({CUT_END}) phải > CUT_START ({CUT_START})\")\n",
317
- "\n",
318
- "audio, sr = sf.read(str(SRC_PATH), always_2d=False)\n",
319
- "if getattr(audio, \"ndim\", 1) > 1:\n",
320
- " audio = audio.mean(axis=1)\n",
321
- "audio = np.asarray(audio, dtype=np.float32)\n",
322
- "\n",
323
- "dur = len(audio) / sr\n",
324
- "if CUT_END > dur:\n",
325
- " raise ValueError(f\"CUT_END={CUT_END}s vượt độ dài audio ({dur:.2f}s)\")\n",
326
- "\n",
327
- "seg = audio[int(CUT_START * sr) : int(CUT_END * sr)].copy()\n",
328
- "ref_wav = VOICE_DIR / \"ref.wav\"\n",
329
- "sf.write(str(ref_wav), seg, sr)\n",
330
- "\n",
331
- "ref_text = (REF_TEXT or \"\").strip()\n",
332
- "if not AUTO_TRANSCRIBE:\n",
333
- " if not ref_text:\n",
334
- " raise ValueError(\"REF_TEXT trống — điền transcript hoặc bật AUTO_TRANSCRIBE=True\")\n",
335
- " (VOICE_DIR / \"ref_text.txt\").write_text(ref_text, encoding=\"utf-8\")\n",
336
- "\n",
337
- "profile = {\n",
338
- " \"name\": VOICE_NAME.strip() or slug,\n",
339
- " \"language\": LANGUAGE,\n",
340
- " \"ref_audio\": \"ref.wav\",\n",
341
- " \"ref_text_file\": \"ref_text.txt\",\n",
342
- " \"voice_prompt\": \"voice.pt\",\n",
343
- " \"model\": \"k2-fsa/OmniVoice\",\n",
344
- " \"device\": \"cuda:0\",\n",
345
- " \"preprocess_prompt\": bool(PREPROCESS_PROMPT),\n",
346
- " \"auto_transcribe\": bool(AUTO_TRANSCRIBE),\n",
347
- "}\n",
348
- "profile_path = VOICE_DIR / \"profile.json\"\n",
349
- "profile_path.write_text(\n",
350
- " json.dumps(profile, ensure_ascii=False, indent=2) + \"\\n\", encoding=\"utf-8\"\n",
351
- ")\n",
352
- "\n",
353
- "print(f\"Drive: {DRIVE_OMIVOICE}\")\n",
354
- "print(f\"SRC: {SRC_PATH} ({dur:.2f}s)\")\n",
355
- "print(f\"Cut: {CUT_START:.3f}s → {CUT_END:.3f}s ({len(seg)/sr:.2f}s)\")\n",
356
- "print(f\"Voice dir: {VOICE_DIR}\")\n",
357
- "print(f\"ref.wav: {ref_wav}\")\n",
358
- "print(f\"profile: {profile_path}\")\n",
359
- "if not AUTO_TRANSCRIBE:\n",
360
- " print(f\"ref_text: {ref_text[:80]}...\")"
361
- ],
362
- "execution_count": null,
363
- "outputs": [],
364
- "id": "cut_audio"
365
- },
366
- {
367
- "cell_type": "markdown",
368
- "metadata": {},
369
- "source": [
370
- "## 5. Build `voice.pt`\n",
371
- "\n",
372
- "Tạo prompt clone và lưu lên Drive. Có thể nghe thử ngay sau đó."
373
- ],
374
- "id": "md_build"
375
- },
376
- {
377
- "cell_type": "code",
378
- "metadata": {},
379
- "source": [
380
- "from IPython.display import Audio, display\n",
381
- "\n",
382
- "PROFILE = speak.load_profile(profile_path)\n",
383
- "MODEL = speak.load_model(PROFILE)\n",
384
- "\n",
385
- "voice_pt = Path(PROFILE[\"voice_prompt_path\"])\n",
386
- "if voice_pt.exists():\n",
387
- " voice_pt.unlink()\n",
388
- " print(f\"Đã xóa voice.pt cũ: {voice_pt}\")\n",
389
- "\n",
390
- "print(\"Đang tạo voice.pt ...\")\n",
391
- "PROMPT = speak.build_voice_prompt(MODEL, PROFILE)\n",
392
- "speak.save_voice_prompt(PROMPT, voice_pt)\n",
393
- "\n",
394
- "print(f\"✓ Đã lưu: {voice_pt}\")\n",
395
- "print(f\" ref_text trong prompt: {PROMPT.ref_text[:100]}...\")\n",
396
- "print(f\" tokens: {tuple(PROMPT.ref_audio_tokens.shape)}\")\n",
397
- "\n",
398
- "display(Audio(str(VOICE_DIR / \"ref.wav\")))"
399
- ],
400
- "execution_count": null,
401
- "outputs": [],
402
- "id": "build_voice"
403
- },
404
- {
405
- "cell_type": "code",
406
- "metadata": {},
407
- "source": [
408
- "if RUN_TEST:\n",
409
- " test_text = (TEST_TEXT or REF_TEXT or \"Xin chào, đây là giọng mới.\").strip()\n",
410
- " out_wav = DRIVE_OMIVOICE / f\"test_clone_{slug}.wav\"\n",
411
- " print(f\"Test TTS: {test_text[:80]}...\")\n",
412
- " audio = speak.synthesize(\n",
413
- " MODEL,\n",
414
- " PROMPT,\n",
415
- " test_text,\n",
416
- " PROFILE[\"language\"],\n",
417
- " num_step=32,\n",
418
- " )\n",
419
- " sf.write(str(out_wav), audio, MODEL.sampling_rate)\n",
420
- " print(f\"✓ Test WAV: {out_wav}\")\n",
421
- " display(Audio(str(out_wav)))\n",
422
- "else:\n",
423
- " print(\"Bỏ qua test (RUN_TEST=False)\")"
424
- ],
425
- "execution_count": null,
426
- "outputs": [],
427
- "id": "test_tts"
428
- },
429
- {
430
- "cell_type": "markdown",
431
- "metadata": {},
432
- "source": [
433
- "## 6. Tóm tắt & tải về máy local\n",
434
- "\n",
435
- "Trên Drive đã có:\n",
436
- "\n",
437
- "```\n",
438
- "MyDrive/Omivoice/voices/<slug>/\n",
439
- " profile.json\n",
440
- " ref.wav\n",
441
- " ref_text.txt\n",
442
- " voice.pt\n",
443
- "```\n",
444
- "\n",
445
- "Copy cả thư mục về máy local `Omivoice/voices/<slug>/`, rồi dùng:\n",
446
- "\n",
447
- "```powershell\n",
448
- ".\\speak.ps1 srt-merge \"input.srt\" -Voice injoyreel\n",
449
- "```\n",
450
- "\n",
451
- "Hoặc chạy notebook lồng tiếng `Omivoice_VI_Colab.ipynb` với `DEFAULT_VOICE = \"injoyreel\"` (sau khi upload giọng lên HF hoặc copy vào dataset)."
452
- ],
453
- "id": "md_summary"
454
- },
455
- {
456
- "cell_type": "code",
457
- "metadata": {},
458
- "source": [
459
- "print(\"=== Clone xong ===\")\n",
460
- "for p in sorted(VOICE_DIR.iterdir()):\n",
461
- " print(f\" {p.name:16s} {p.stat().st_size:>10,} bytes\")\n",
462
- "print(f\"\\nThư mục Drive: {VOICE_DIR}\")"
463
- ],
464
- "execution_count": null,
465
- "outputs": [],
466
- "id": "summary"
467
- },
468
- {
469
- "cell_type": "markdown",
470
- "metadata": {},
471
- "source": [
472
- "## 7. Giải phóng VRAM & tắt runtime\n",
473
- "\n",
474
- "Giải phóng bộ nhớ GPU rồi **ngắt session Colab**. Chạy cell này sau khi clone xong."
475
- ],
476
- "id": "md_unload"
477
- },
478
- {
479
- "cell_type": "code",
480
- "metadata": {},
481
- "source": [
482
- "import gc\n",
483
- "import torch\n",
484
- "from google.colab import runtime\n",
485
- "\n",
486
- "try:\n",
487
- " del MODEL, PROMPT, PROFILE, audio\n",
488
- "except NameError:\n",
489
- " pass\n",
490
- "\n",
491
- "gc.collect()\n",
492
- "if torch.cuda.is_available():\n",
493
- " torch.cuda.empty_cache()\n",
494
- " torch.cuda.ipc_collect()\n",
495
- "\n",
496
- "print(\"Đã giải phóng VRAM\")\n",
497
- "print(\"Đang tắt runtime Colab...\")\n",
498
- "runtime.unassign()"
499
- ],
500
- "execution_count": null,
501
- "outputs": [],
502
- "id": "unload"
503
- }
504
- ]
505
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
colab/Omivoice_VI_Colab.ipynb CHANGED
@@ -8,13 +8,6 @@
8
  "\n",
9
  "Notebook chạy [OmniVoice](https://huggingface.co/k2-fsa/OmniVoice) với pipeline **SRT lồng tiếng** (`native`).\n",
10
  "\n",
11
- "**Mode `native` (khuyến nghị):**\n",
12
- "1. Model nói nhanh native ≤ `NATIVE_SPEED_CAP` (giữ nhấn nhá)\n",
13
- "2. Dùng hết khoảng lặng tới cue sau\n",
14
- "3. Stretch nhẹ ≤ x1.1 nếu còn lệch nhỏ\n",
15
- "4. Phần dư chồng nhẹ vào đầu cue sau (crossfade) — **không đẩy timestamp SRT**\n",
16
- "5. Rút gọn câu: tự sửa trên file SRT (hệ thống không tự rewrite)\n",
17
- "\n",
18
  "**Luồng Drive:**\n",
19
  "1. Cấu hình giọng + tên file SRT ở **mục 0**\n",
20
  "2. Đặt file `.srt` vào **`MyDrive/Omivoice/`** (tên = `SRT_FILE` + `.srt`, vd. `input` → `input.srt`)\n",
@@ -46,8 +39,6 @@
46
  "# Giọng: ban_mai | lan_trinh | ngan_ha | ngoc_huyen | thao_trinh | tuong_vy\n",
47
  "DEFAULT_VOICE = \"tuong_vy\"\n",
48
  "MERGE_MODE = \"native\" # native | cascade | fit | strict\n",
49
- "# native: trần tốc độ nói lúc sinh (2.0 = tối đa gấp đôi). Cao hơn = chắc đủ chữ, dễ nhanh.\n",
50
- "NATIVE_SPEED_CAP = 2.0\n",
51
  "NUM_STEP = 32"
52
  ],
53
  "execution_count": null,
@@ -323,7 +314,6 @@
323
  " merge=True,\n",
324
  " merge_output=MERGE_OUT,\n",
325
  " merge_mode=MERGE_MODE,\n",
326
- " native_speed_cap=NATIVE_SPEED_CAP,\n",
327
  " num_step=NUM_STEP,\n",
328
  " model=MODEL,\n",
329
  " prompt=PROMPT,\n",
@@ -345,10 +335,7 @@
345
  "print(\n",
346
  " f\"Thống kê: {stats.get('generated', 0)} cue mới, \"\n",
347
  " f\"{stats.get('skipped', 0)} bỏ qua, \"\n",
348
- " f\"{stats.get('speed_fitted', 0)} native, \"\n",
349
- " f\"{stats.get('stretch', 0)} stretch, \"\n",
350
- " f\"{stats.get('cascade_soft', 0)} chồng nhẹ, \"\n",
351
- " f\"{stats.get('overflow', 0)} tràn >50ms\"\n",
352
  ")"
353
  ],
354
  "execution_count": null,
 
8
  "\n",
9
  "Notebook chạy [OmniVoice](https://huggingface.co/k2-fsa/OmniVoice) với pipeline **SRT lồng tiếng** (`native`).\n",
10
  "\n",
 
 
 
 
 
 
 
11
  "**Luồng Drive:**\n",
12
  "1. Cấu hình giọng + tên file SRT ở **mục 0**\n",
13
  "2. Đặt file `.srt` vào **`MyDrive/Omivoice/`** (tên = `SRT_FILE` + `.srt`, vd. `input` → `input.srt`)\n",
 
39
  "# Giọng: ban_mai | lan_trinh | ngan_ha | ngoc_huyen | thao_trinh | tuong_vy\n",
40
  "DEFAULT_VOICE = \"tuong_vy\"\n",
41
  "MERGE_MODE = \"native\" # native | cascade | fit | strict\n",
 
 
42
  "NUM_STEP = 32"
43
  ],
44
  "execution_count": null,
 
314
  " merge=True,\n",
315
  " merge_output=MERGE_OUT,\n",
316
  " merge_mode=MERGE_MODE,\n",
 
317
  " num_step=NUM_STEP,\n",
318
  " model=MODEL,\n",
319
  " prompt=PROMPT,\n",
 
335
  "print(\n",
336
  " f\"Thống kê: {stats.get('generated', 0)} cue mới, \"\n",
337
  " f\"{stats.get('skipped', 0)} bỏ qua, \"\n",
338
+ " f\"{stats.get('overflow', 0)} tràn\"\n",
 
 
 
339
  ")"
340
  ],
341
  "execution_count": null,
tools/speak.py CHANGED
@@ -35,11 +35,6 @@ DEFAULT_PROFILE = VOICES_DIR / DEFAULT_VOICE_SLUG / "profile.json"
35
  # Greedy khiến ngữ điệu phẳng, "máy móc"; 0.4 cho nhấn nhá vừa phải, ổn định.
36
  DEFAULT_CLASS_TEMPERATURE = 0.4
37
  DEFAULT_GUIDANCE_SCALE = 2.0
38
- # Industry ladder: native TTS → spill gap → stretch nhẹ → chồng nhẹ (không đẩy SRT).
39
- # Stretch >~1.1–1.15 dễ làm giọng kém tự nhiên (WSOLA vẫn méo nhẹ).
40
- # Rút gọn text: người dùng tự chỉnh SRT — hệ thống không tự rewrite.
41
- LIGHT_STRETCH_CAP = 1.1
42
- NATIVE_MARGIN_SEC = 0.05
43
 
44
 
45
  @dataclass
@@ -392,84 +387,41 @@ def plan_native_placements(
392
  cues: List[SrtCue],
393
  segments: List[np.ndarray],
394
  sample_rate: int,
395
- light_stretch_cap: float = LIGHT_STRETCH_CAP,
396
- min_gap_sec: float = 0.05,
397
- ) -> tuple[List[dict], List[np.ndarray]]:
398
- """Ladder hậu kỳ sau native TTS: gap stretch nhẹ chồng nhẹ (không đẩy).
399
-
400
- Neo cứng mỗi cue đúng ``cue.start_sec`` SRT timestamp đầu không bao giờ
401
- lệch/cộng dồn. Nếu vẫn dài hơn room tới cue sau:
402
- 1) dùng khoảng lặng (gap) tới cue kế
403
- 2) stretch nhẹ ≤ light_stretch_cap (WSOLA)
404
- 3) phần dư chồng nhẹ vào đầu cue sau (crossfade lúc merge), KHÔNG đẩy
405
- ``actual_start`` của cue sau → tránh lệch timeline.
406
  """
407
  placements: List[dict] = []
408
- fitted: List[np.ndarray] = []
409
  n = len(cues)
410
 
411
  for i, (cue, audio) in enumerate(zip(cues, segments)):
412
- audio = np.asarray(audio, dtype=np.float32).reshape(-1)
413
  audio_sec = len(audio) / sample_rate
414
- # Cố định mốc đầu = SRT gốc — không dùng cursor đẩy.
415
- start = cue.start_sec
416
-
417
- if i + 1 < n:
418
- room_sec = max(min_gap_sec, cues[i + 1].start_sec - start)
419
- else:
420
- room_sec = max(audio_sec, cue.end_sec - start)
421
-
422
- stretch_factor = 1.0
423
- stretch_applied = False
424
- soft_overlap = False
425
-
426
- if audio_sec > room_sec + 1e-3:
427
- required = audio_sec / room_sec
428
- if required <= light_stretch_cap + 1e-6:
429
- stretch_factor = required
430
- audio = time_stretch_speech(audio, stretch_factor)
431
- target = int(round(room_sec * sample_rate))
432
- if len(audio) > target:
433
- audio = audio[:target]
434
- stretch_applied = True
435
- else:
436
- # Stretch nhẹ tối đa; phần dư chồng vào cue sau (không đẩy).
437
- stretch_factor = light_stretch_cap
438
- audio = time_stretch_speech(audio, stretch_factor)
439
- stretch_applied = True
440
-
441
- seg_sec = len(audio) / sample_rate
442
- actual_end = start + seg_sec
443
  next_start = cues[i + 1].start_sec if i + 1 < n else actual_end
444
  overflow = max(0.0, actual_end - next_start)
445
- soft_overlap = overflow > 0.05
446
 
447
  placements.append(
448
  {
449
- "actual_start_sec": round(start, 3),
450
  "actual_end_sec": round(actual_end, 3),
451
  "overflow_sec": round(overflow, 3),
452
  "pushed_by_previous": False,
453
- "light_stretch_factor": round(stretch_factor, 3),
454
- "light_stretch_applied": stretch_applied,
455
- "soft_cascade": soft_overlap,
456
  }
457
  )
458
- fitted.append(audio)
459
-
460
- if stretch_applied or soft_overlap:
461
  logging.info(
462
- "Cue %s smart: %.2fs room=%.2fs stretch=x%.2f overlap=%s "
463
- "(start cố định %.3fs)",
464
  cue.index,
465
- audio_sec,
466
- room_sec,
467
- stretch_factor,
468
- soft_overlap,
469
- start,
470
  )
471
 
472
- return placements, fitted
473
 
474
 
475
  def write_shifted_srt(
@@ -498,44 +450,32 @@ def write_manifest(
498
  rows = []
499
  for cue, wav, fit_meta in zip(cues, wav_paths, fit_metas):
500
  slot_sec = max(0.0, cue.end_sec - cue.start_sec)
501
- row = {
502
- "index": cue.index,
503
- "start_sec": cue.start_sec,
504
- "end_sec": cue.end_sec,
505
- "slot_sec": round(slot_sec, 3),
506
- "actual_start_sec": fit_meta.get("actual_start_sec"),
507
- "actual_end_sec": fit_meta.get("actual_end_sec"),
508
- "overflow_sec": fit_meta.get("overflow_sec", 0.0),
509
- "pushed_by_previous": fit_meta.get("pushed_by_previous", False),
510
- "fit_applied": fit_meta.get("fit_applied", False),
511
- "fit_speed_factor": fit_meta.get("fit_speed_factor", 1.0),
512
- "generated_sec": fit_meta.get("generated_sec"),
513
- "audio_sec": fit_meta.get("audio_sec"),
514
- "required_speed_factor": fit_meta.get("required_speed_factor", 1.0),
515
- "speed_factor": fit_meta.get("speed_factor", 1.0),
516
- "speed_mode": fit_meta.get("speed_mode"),
517
- "gentle_threshold": fit_meta.get("gentle_threshold"),
518
- "speed_fitted": fit_meta.get("speed_fitted", False),
519
- "speed_skipped": fit_meta.get("speed_skipped", False),
520
- "speed_skip_reason": fit_meta.get("speed_skip_reason"),
521
- "text": cue.text,
522
- "wav": str(wav),
523
- "wav_relative": wav.name,
524
- }
525
- # Smart ladder metadata (nếu có).
526
- for key in (
527
- "natural_sec",
528
- "budget_sec",
529
- "native_duration_sec",
530
- "native_speed_factor",
531
- "native_capped",
532
- "light_stretch_factor",
533
- "light_stretch_applied",
534
- "soft_cascade",
535
- ):
536
- if key in fit_meta:
537
- row[key] = fit_meta[key]
538
- rows.append(row)
539
  payload = {
540
  "voice": profile.get("name", profile["slug"]),
541
  "voice_slug": profile["slug"],
@@ -570,43 +510,17 @@ def merge_timeline_cascade(
570
  audio_segments: List[np.ndarray],
571
  sample_rate: int,
572
  tail_sec: float = 0.5,
573
- crossfade_sec: float = 0.08,
574
  ) -> np.ndarray:
575
- """Ghép timeline; vùng chồng cue dùng crossfade để tránh mất chữ cuối.
576
-
577
- Native/cascade đôi khi để đuôi cue trước tràn nhẹ vào mốc cue sau. Ghi đè
578
- cứng sẽ cắt âm tiết cuối; crossfade ngắn giữ đuôi cũ và hòa vào câu mới.
579
- """
580
  if not placements:
581
  raise ValueError("Không có cue SRT để gộp.")
582
  total_sec = placements[-1]["actual_end_sec"] + tail_sec
583
  merged = np.zeros(int(total_sec * sample_rate), dtype=np.float32)
584
- fade_n = max(1, int(round(crossfade_sec * sample_rate)))
585
-
586
  for placement, audio in zip(placements, audio_segments):
587
- audio = np.asarray(audio, dtype=np.float32).reshape(-1)
588
  start = int(placement["actual_start_sec"] * sample_rate)
589
  end = start + len(audio)
590
  if end > len(merged):
591
  merged = np.pad(merged, (0, end - len(merged)))
592
-
593
- # Phần đã có tiếng (đuôi cue trước) → crossfade với đầu cue mới.
594
- existing = merged[start:end]
595
- occupied = np.flatnonzero(np.abs(existing) > 1e-5)
596
- if occupied.size > 0:
597
- overlap = int(occupied[-1]) + 1
598
- overlap = min(overlap, len(audio), fade_n)
599
- if overlap > 0:
600
- fade_out = np.linspace(1.0, 0.0, overlap, dtype=np.float32)
601
- fade_in = np.linspace(0.0, 1.0, overlap, dtype=np.float32)
602
- mixed = existing[:overlap] * fade_out + audio[:overlap] * fade_in
603
- merged[start : start + overlap] = mixed
604
- if overlap < len(audio):
605
- merged[start + overlap : end] = audio[overlap:]
606
- else:
607
- merged[start:end] = audio
608
- else:
609
- merged[start:end] = audio
610
  return _normalize_audio(merged)
611
 
612
 
@@ -879,18 +793,18 @@ def run_srt_pipeline(
879
  native_meta: Optional[dict] = None
880
  gen_duration: Optional[float] = None
881
  if merge_mode == "native":
882
- # Ngân sách = thời gian tới cue kế (slot + khoảng lặng sau).
883
- # Ladder: native ≤ cap → gap/stretch/cascade hậu kỳ.
884
- # Rút gọn text do người dùng tự chỉnh trên SRT.
885
  if idx + 1 < total:
886
  budget = max(0.05, cues[idx + 1].start_sec - cue.start_sec)
887
  else:
888
  budget = None
889
  if budget is not None and budget > 0:
890
- fit_target = max(0.1, budget - NATIVE_MARGIN_SEC)
 
 
891
  natural_sec = estimate_natural_duration_sec(model, prompt, cue.text)
892
  if natural_sec > fit_target + 1e-3:
893
- # Ép native tối đa native_speed_cap; phần xử lý hậu kỳ.
894
  gen_duration = round(
895
  max(fit_target, natural_sec / native_speed_cap), 3
896
  )
@@ -945,8 +859,7 @@ def run_srt_pipeline(
945
  log_lines,
946
  f" Cue {cue.index}: native {native_meta['natural_sec']}s "
947
  f"-> {native_meta['native_duration_sec']}s "
948
- f"(x{native_meta['native_speed_factor']}, chạm trần - "
949
- f"gap/stretch/cascade sau)",
950
  on_log,
951
  )
952
  elif slot_sec > 0 and merge_mode != "fit":
@@ -988,10 +901,7 @@ def run_srt_pipeline(
988
  progress(0.9, desc="Đang canh giờ & ghi manifest")
989
  fitted_segments: Optional[List[np.ndarray]] = None
990
  if merge_mode == "native":
991
- placements, fitted_segments = plan_native_placements(
992
- cues, segments, model.sampling_rate
993
- )
994
- segments = fitted_segments
995
  elif merge_mode == "cascade":
996
  placements = plan_cascade_placements(cues, segments, model.sampling_rate)
997
  elif merge_mode == "fit":
@@ -1011,12 +921,10 @@ def run_srt_pipeline(
1011
  for cue, audio in zip(cues, segments)
1012
  ]
1013
 
1014
- overflow_count = sum(1 for p in placements if p["overflow_sec"] > 0.05)
1015
  pushed_count = sum(1 for p in placements if p["pushed_by_previous"])
1016
  fit_count = sum(1 for p in placements if p.get("fit_applied"))
1017
  capped_count = sum(1 for p in placements if p.get("fit_capped"))
1018
- stretch_count = sum(1 for p in placements if p.get("light_stretch_applied"))
1019
- cascade_soft = sum(1 for p in placements if p.get("soft_cascade"))
1020
 
1021
  for fit_meta, placement in zip(fit_metas, placements):
1022
  fit_meta.update(placement)
@@ -1045,12 +953,10 @@ def run_srt_pipeline(
1045
  elif merge_mode == "native":
1046
  native_capped = sum(1 for m in fit_metas if m.get("native_capped"))
1047
  summary = (
1048
- f"Hoàn tất [{profile['slug']}] (native/smart): {generated} cue mới, "
1049
- f"{speed_fitted_count} native "
1050
- f"({native_capped} chạm trần x{native_speed_cap}), "
1051
- f"{stretch_count} stretch ≤x{LIGHT_STRETCH_CAP}, "
1052
- f"{cascade_soft} chồng nhẹ (không đẩy SRT), "
1053
- f"{overflow_count} tràn >50ms, {skipped} bỏ qua"
1054
  )
1055
  else:
1056
  summary = (
@@ -1103,8 +1009,6 @@ def run_srt_pipeline(
1103
  "generated": generated,
1104
  "overflow": overflow_count,
1105
  "pushed": pushed_count,
1106
- "stretch": stretch_count,
1107
- "cascade_soft": cascade_soft,
1108
  "speed_fitted": speed_fitted_count,
1109
  "speed_skipped": speed_skipped_count,
1110
  "skipped": skipped,
@@ -1208,8 +1112,8 @@ def get_parser() -> argparse.ArgumentParser:
1208
  "--merge-mode",
1209
  choices=["native", "fit", "cascade", "strict"],
1210
  default="native",
1211
- help="native: ladder tối ưu (native ≤cap gap stretch ≤1.1 "
1212
- "chồng nhẹ đuôi vào cue sau, KHÔNG đẩy timestamp SRT) - khuyến nghị; "
1213
  "fit: sinh dài rồi kéo nén tín hiệu vừa khung SRT (khít giờ, dễ mất nhấn nhá); "
1214
  "cascade: cue dài tràn/đẩy cue sau (giữ chất giọng, lệch SRT); "
1215
  "strict: ghép theo timestamp gốc (có thể cắt audio)",
 
35
  # Greedy khiến ngữ điệu phẳng, "máy móc"; 0.4 cho nhấn nhá vừa phải, ổn định.
36
  DEFAULT_CLASS_TEMPERATURE = 0.4
37
  DEFAULT_GUIDANCE_SCALE = 2.0
 
 
 
 
 
38
 
39
 
40
  @dataclass
 
387
  cues: List[SrtCue],
388
  segments: List[np.ndarray],
389
  sample_rate: int,
390
+ ) -> List[dict]:
391
+ """Neo cứng mỗi cue đúng mốc SRT gốc — lỗi lệch KHÔNG bao giờ cộng dồn.
392
+
393
+ Kiểu lồng tiếng chuyên nghiệp: câu dài hơn khung đã được nói nhanh native
394
+ vừa đủ chứa hết chữ (xử lý lúc sinh audio), nên ở đây chỉ cần đặt từng câu
395
+ đúng vị trí thời gian của nó. Mỗi câu độc lập theo mốc SRT, câu này không
396
+ đẩy câu kia đồng bộ tiếng/hình ổn định suốt video.
 
 
 
 
397
  """
398
  placements: List[dict] = []
 
399
  n = len(cues)
400
 
401
  for i, (cue, audio) in enumerate(zip(cues, segments)):
 
402
  audio_sec = len(audio) / sample_rate
403
+ actual_start = cue.start_sec
404
+ actual_end = actual_start + audio_sec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  next_start = cues[i + 1].start_sec if i + 1 < n else actual_end
406
  overflow = max(0.0, actual_end - next_start)
 
407
 
408
  placements.append(
409
  {
410
+ "actual_start_sec": round(actual_start, 3),
411
  "actual_end_sec": round(actual_end, 3),
412
  "overflow_sec": round(overflow, 3),
413
  "pushed_by_previous": False,
 
 
 
414
  }
415
  )
416
+ if overflow > 0.05:
 
 
417
  logging.info(
418
+ "Cue %s: vẫn vượt khung %.2fs sau khi tăng tốc (cân nhắc tăng "
419
+ "--native-speed-cap để chứa hết chữ)",
420
  cue.index,
421
+ overflow,
 
 
 
 
422
  )
423
 
424
+ return placements
425
 
426
 
427
  def write_shifted_srt(
 
450
  rows = []
451
  for cue, wav, fit_meta in zip(cues, wav_paths, fit_metas):
452
  slot_sec = max(0.0, cue.end_sec - cue.start_sec)
453
+ rows.append(
454
+ {
455
+ "index": cue.index,
456
+ "start_sec": cue.start_sec,
457
+ "end_sec": cue.end_sec,
458
+ "slot_sec": round(slot_sec, 3),
459
+ "actual_start_sec": fit_meta.get("actual_start_sec"),
460
+ "actual_end_sec": fit_meta.get("actual_end_sec"),
461
+ "overflow_sec": fit_meta.get("overflow_sec", 0.0),
462
+ "pushed_by_previous": fit_meta.get("pushed_by_previous", False),
463
+ "fit_applied": fit_meta.get("fit_applied", False),
464
+ "fit_speed_factor": fit_meta.get("fit_speed_factor", 1.0),
465
+ "generated_sec": fit_meta.get("generated_sec"),
466
+ "audio_sec": fit_meta.get("audio_sec"),
467
+ "required_speed_factor": fit_meta.get("required_speed_factor", 1.0),
468
+ "speed_factor": fit_meta.get("speed_factor", 1.0),
469
+ "speed_mode": fit_meta.get("speed_mode"),
470
+ "gentle_threshold": fit_meta.get("gentle_threshold"),
471
+ "speed_fitted": fit_meta.get("speed_fitted", False),
472
+ "speed_skipped": fit_meta.get("speed_skipped", False),
473
+ "speed_skip_reason": fit_meta.get("speed_skip_reason"),
474
+ "text": cue.text,
475
+ "wav": str(wav),
476
+ "wav_relative": wav.name,
477
+ }
478
+ )
 
 
 
 
 
 
 
 
 
 
 
 
479
  payload = {
480
  "voice": profile.get("name", profile["slug"]),
481
  "voice_slug": profile["slug"],
 
510
  audio_segments: List[np.ndarray],
511
  sample_rate: int,
512
  tail_sec: float = 0.5,
 
513
  ) -> np.ndarray:
 
 
 
 
 
514
  if not placements:
515
  raise ValueError("Không có cue SRT để gộp.")
516
  total_sec = placements[-1]["actual_end_sec"] + tail_sec
517
  merged = np.zeros(int(total_sec * sample_rate), dtype=np.float32)
 
 
518
  for placement, audio in zip(placements, audio_segments):
 
519
  start = int(placement["actual_start_sec"] * sample_rate)
520
  end = start + len(audio)
521
  if end > len(merged):
522
  merged = np.pad(merged, (0, end - len(merged)))
523
+ merged[start:end] = audio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
524
  return _normalize_audio(merged)
525
 
526
 
 
793
  native_meta: Optional[dict] = None
794
  gen_duration: Optional[float] = None
795
  if merge_mode == "native":
796
+ # Ngân sách = thời gian tới khi cue kế bắt đầu (slot + khoảng lặng sau).
 
 
797
  if idx + 1 < total:
798
  budget = max(0.05, cues[idx + 1].start_sec - cue.start_sec)
799
  else:
800
  budget = None
801
  if budget is not None and budget > 0:
802
+ # Chừa biên an toàn nhỏ để phần đệm fade/pad ở đuôi không đè
803
+ # sang cue sau (tránh cảm giác mất chữ/đè đuôi).
804
+ fit_target = max(0.1, budget - 0.12)
805
  natural_sec = estimate_natural_duration_sec(model, prompt, cue.text)
806
  if natural_sec > fit_target + 1e-3:
807
+ # Ép native vừa khít, không vượt trần tốc độ.
808
  gen_duration = round(
809
  max(fit_target, natural_sec / native_speed_cap), 3
810
  )
 
859
  log_lines,
860
  f" Cue {cue.index}: native {native_meta['natural_sec']}s "
861
  f"-> {native_meta['native_duration_sec']}s "
862
+ f"(x{native_meta['native_speed_factor']}, chạm trần - tràn nhẹ)",
 
863
  on_log,
864
  )
865
  elif slot_sec > 0 and merge_mode != "fit":
 
901
  progress(0.9, desc="Đang canh giờ & ghi manifest")
902
  fitted_segments: Optional[List[np.ndarray]] = None
903
  if merge_mode == "native":
904
+ placements = plan_native_placements(cues, segments, model.sampling_rate)
 
 
 
905
  elif merge_mode == "cascade":
906
  placements = plan_cascade_placements(cues, segments, model.sampling_rate)
907
  elif merge_mode == "fit":
 
921
  for cue, audio in zip(cues, segments)
922
  ]
923
 
924
+ overflow_count = sum(1 for p in placements if p["overflow_sec"] > 0)
925
  pushed_count = sum(1 for p in placements if p["pushed_by_previous"])
926
  fit_count = sum(1 for p in placements if p.get("fit_applied"))
927
  capped_count = sum(1 for p in placements if p.get("fit_capped"))
 
 
928
 
929
  for fit_meta, placement in zip(fit_metas, placements):
930
  fit_meta.update(placement)
 
953
  elif merge_mode == "native":
954
  native_capped = sum(1 for m in fit_metas if m.get("native_capped"))
955
  summary = (
956
+ f"Hoàn tất [{profile['slug']}] (native): {generated} cue mới, "
957
+ f"{speed_fitted_count} cue nói nhanh native cho vừa khung "
958
+ f"({native_capped} câu chạm trần x{native_speed_cap}, còn vượt khung; "
959
+ f"neo cứng SRT - không cộng dồn lệch), {skipped} bỏ qua"
 
 
960
  )
961
  else:
962
  summary = (
 
1009
  "generated": generated,
1010
  "overflow": overflow_count,
1011
  "pushed": pushed_count,
 
 
1012
  "speed_fitted": speed_fitted_count,
1013
  "speed_skipped": speed_skipped_count,
1014
  "skipped": skipped,
 
1112
  "--merge-mode",
1113
  choices=["native", "fit", "cascade", "strict"],
1114
  default="native",
1115
+ help="native: model nói nhanh native (giữ nhấn nhá) trần tốc độ, "
1116
+ "phần tràn nhẹ/cascade - khuyến nghị cho lồng tiếng; "
1117
  "fit: sinh dài rồi kéo nén tín hiệu vừa khung SRT (khít giờ, dễ mất nhấn nhá); "
1118
  "cascade: cue dài tràn/đẩy cue sau (giữ chất giọng, lệch SRT); "
1119
  "strict: ghép theo timestamp gốc (có thể cắt audio)",
voices/ban_mai/profile.json CHANGED
@@ -1,12 +1,11 @@
1
- {
2
- "name": "Ban Mai",
3
- "slug": "ban_mai",
4
- "language": "Vietnamese",
5
- "ref_audio": "ref.mp3",
6
- "ref_text_file": "ref_text.txt",
7
- "voice_prompt": "voice.pt",
8
- "model": "k2-fsa/OmniVoice",
9
- "device": "cuda:0",
10
- "preprocess_prompt": true,
11
- "auto_transcribe": false
12
- }
 
1
+ {
2
+ "name": "Ban Mai",
3
+ "language": "Vietnamese",
4
+ "ref_audio": "ref.mp3",
5
+ "ref_text_file": "ref_text.txt",
6
+ "voice_prompt": "voice.pt",
7
+ "model": "k2-fsa/OmniVoice",
8
+ "device": "cuda:0",
9
+ "preprocess_prompt": false,
10
+ "auto_transcribe": true
11
+ }
 
voices/injoyreel/profile.json DELETED
@@ -1,11 +0,0 @@
1
- {
2
- "name": "InjoyReel",
3
- "language": "Vietnamese",
4
- "ref_audio": "ref.wav",
5
- "ref_text_file": "ref_text.txt",
6
- "voice_prompt": "voice.pt",
7
- "model": "k2-fsa/OmniVoice",
8
- "device": "cuda:0",
9
- "preprocess_prompt": false,
10
- "auto_transcribe": false
11
- }
 
 
 
 
 
 
 
 
 
 
 
 
voices/injoyreel/ref.wav DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:d6a83fe9f5fee4976c430dc754557da0ea6d2aa9ad295fa202cfa141cb2c3fb2
3
- size 1217126
 
 
 
 
voices/injoyreel/ref_text.txt DELETED
@@ -1 +0,0 @@
1
- Hôm nay tập đoàn Hoắc thị tổ chức tiệc đón người thừa kế trở về tại dinh thự. Được biết người thừa kế bí ẩn này Hoắc Cảnh Chu chưa từng xuất hiện trước công chúng bao giờ. Sự trở về đề phô trương này không biết có phải mang ý nghĩa ảnh đã nắm toàn quyền phát ngôn của tập đoàn không.
 
 
voices/injoyreel/voice.pt DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:888b591c97299b084773cb418614561c55b1e9076be091c9152e111c5f002738
3
- size 23963
 
 
 
 
voices/lan_trinh/profile.json CHANGED
@@ -1,12 +1,11 @@
1
- {
2
- "name": "Lan Trinh",
3
- "slug": "lan_trinh",
4
- "language": "Vietnamese",
5
- "ref_audio": "ref.wav",
6
- "ref_text_file": "ref_text.txt",
7
- "voice_prompt": "voice.pt",
8
- "model": "k2-fsa/OmniVoice",
9
- "device": "cuda:0",
10
- "preprocess_prompt": true,
11
- "auto_transcribe": false
12
- }
 
1
+ {
2
+ "name": "Lan Trinh",
3
+ "language": "Vietnamese",
4
+ "ref_audio": "ref.wav",
5
+ "ref_text_file": "ref_text.txt",
6
+ "voice_prompt": "voice.pt",
7
+ "model": "k2-fsa/OmniVoice",
8
+ "device": "cuda:0",
9
+ "preprocess_prompt": false,
10
+ "auto_transcribe": false
11
+ }
 
voices/ngan_ha/profile.json CHANGED
@@ -1,12 +1,11 @@
1
- {
2
- "name": "Ngan Ha",
3
- "slug": "ngan_ha",
4
- "language": "Vietnamese",
5
- "ref_audio": "ref.wav",
6
- "ref_text_file": "ref_text.txt",
7
- "voice_prompt": "voice.pt",
8
- "model": "k2-fsa/OmniVoice",
9
- "device": "cuda:0",
10
- "preprocess_prompt": true,
11
- "auto_transcribe": false
12
- }
 
1
+ {
2
+ "name": "Ngân ",
3
+ "language": "Vietnamese",
4
+ "ref_audio": "ref.wav",
5
+ "ref_text_file": "ref_text.txt",
6
+ "voice_prompt": "voice.pt",
7
+ "model": "k2-fsa/OmniVoice",
8
+ "device": "cuda:0",
9
+ "preprocess_prompt": false,
10
+ "auto_transcribe": false
11
+ }
 
voices/ngoc_huyen/profile.json CHANGED
@@ -1,12 +1,9 @@
1
- {
2
- "name": "Ngoc Huyen",
3
- "slug": "ngoc_huyen",
4
- "language": "Vietnamese",
5
- "ref_audio": "ref.mp3",
6
- "ref_text_file": "ref_text.txt",
7
- "voice_prompt": "voice.pt",
8
- "model": "k2-fsa/OmniVoice",
9
- "device": "cuda:0",
10
- "preprocess_prompt": true,
11
- "auto_transcribe": false
12
- }
 
1
+ {
2
+ "name": "Ngoc Huyen",
3
+ "language": "Vietnamese",
4
+ "ref_audio": "ref.mp3",
5
+ "ref_text_file": "ref_text.txt",
6
+ "voice_prompt": "voice.pt",
7
+ "model": "k2-fsa/OmniVoice",
8
+ "device": "cuda:0"
9
+ }
 
 
 
voices/thao_trinh/profile.json CHANGED
@@ -1,12 +1,11 @@
1
- {
2
- "name": "Thao Trinh",
3
- "slug": "thao_trinh",
4
- "language": "Vietnamese",
5
- "ref_audio": "ref.wav",
6
- "ref_text_file": "ref_text.txt",
7
- "voice_prompt": "voice.pt",
8
- "model": "k2-fsa/OmniVoice",
9
- "device": "cuda:0",
10
- "preprocess_prompt": true,
11
- "auto_transcribe": false
12
- }
 
1
+ {
2
+ "name": "Thảo Trinh",
3
+ "language": "Vietnamese",
4
+ "ref_audio": "ref.wav",
5
+ "ref_text_file": "ref_text.txt",
6
+ "voice_prompt": "voice.pt",
7
+ "model": "k2-fsa/OmniVoice",
8
+ "device": "cuda:0",
9
+ "preprocess_prompt": false,
10
+ "auto_transcribe": false
11
+ }
 
voices/tuong_vy/profile.json CHANGED
@@ -1,12 +1,11 @@
1
- {
2
- "name": "Tuong Vy",
3
- "slug": "tuong_vy",
4
- "language": "Vietnamese",
5
- "ref_audio": "ref.wav",
6
- "ref_text_file": "ref_text.txt",
7
- "voice_prompt": "voice.pt",
8
- "model": "k2-fsa/OmniVoice",
9
- "device": "cuda:0",
10
- "preprocess_prompt": true,
11
- "auto_transcribe": false
12
- }
 
1
+ {
2
+ "name": "Tường Vy",
3
+ "language": "Vietnamese",
4
+ "ref_audio": "ref.wav",
5
+ "ref_text_file": "ref_text.txt",
6
+ "voice_prompt": "voice.pt",
7
+ "model": "k2-fsa/OmniVoice",
8
+ "device": "cuda:0",
9
+ "preprocess_prompt": false,
10
+ "auto_transcribe": false
11
+ }