File size: 13,496 Bytes
c292bfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# OmniVoice — Lồng tiếng tiếng Việt trên Colab\n",
        "\n",
        "Notebook chạy [OmniVoice](https://huggingface.co/k2-fsa/OmniVoice) với pipeline **SRT lồng tiếng** (`native`).\n",
        "\n",
        "**Luồng Drive:**\n",
        "1. Cấu hình giọng + tên file SRT ở **mục 0**\n",
        "2. Đặt file `.srt` vào **`MyDrive/Omivoice/`** (tên = `SRT_FILE` + `.srt`, vd. `input` → `input.srt`)\n",
        "3. Chạy notebook → kết quả ghi lại **`MyDrive/Omivoice/`**\n",
        "\n",
        "**Yêu cầu:** Runtime **GPU L4** (Runtime → Change runtime type → L4)."
      ],
      "id": "4027962a"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 0. Cấu hình"
      ],
      "id": "02fceea2"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Hugging Face (giọng + speak.py)\n",
        "HF_REPO = \"STBack23/omnivoice-vi\"\n",
        "\n",
        "# Google Drive — MyDrive/Omivoice/\n",
        "DRIVE_FOLDER = \"Omivoice\"\n",
        "SRT_FILE = \"input\"   # tên file (không cần .srt) -> input.srt\n",
        "\n",
        "# Giọng: ban_mai | lan_trinh | ngan_ha | ngoc_huyen | thao_trinh | tuong_vy\n",
        "DEFAULT_VOICE = \"tuong_vy\"\n",
        "MERGE_MODE = \"native\"  # native | cascade | fit | strict\n",
        "NUM_STEP = 32"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "1d36167e"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. Kiểm tra GPU & cài đặt"
      ],
      "id": "342cf199"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import torch\n",
        "\n",
        "assert torch.cuda.is_available(), (\n",
        "    \"Bật GPU L4: Runtime → Change runtime type → Hardware accelerator → L4\"\n",
        ")\n",
        "gpu = torch.cuda.get_device_name(0)\n",
        "print(f\"GPU: {gpu}\")\n",
        "if \"L4\" not in gpu.upper():\n",
        "    print(\n",
        "        f\"⚠ Đang dùng {gpu}, không phải L4 — đổi runtime sang L4 để nhanh hơn.\"\n",
        "    )"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "9372766b"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Tắt XET — thường gây treo download ~89% trên Colab.\n",
        "# PHẢI chạy cell này TRƯỚC mọi `from huggingface_hub import ...`\n",
        "import os\n",
        "\n",
        "os.environ[\"HF_HUB_DISABLE_XET\"] = \"1\"\n",
        "os.environ[\"HF_HUB_DOWNLOAD_TIMEOUT\"] = \"300\"\n",
        "\n",
        "print(\"HF: HF_HUB_DISABLE_XET=1, timeout 300s\")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "109256f6"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "!pip install -q omnivoice audiotsm huggingface_hub soundfile librosa"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "f320297d"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### Repo private — đăng nhập Hugging Face (một lần)\n",
        "\n",
        "1. Tạo token **Read** tại [hf.co/settings/tokens](https://huggingface.co/settings/tokens)\n",
        "2. Colab → **🔑 Khóa bí mật** (Manage secrets) → thêm tên `HF_TOKEN`, dán token → **Lưu**\n",
        "3. Chỉ cần làm **một lần** — các lần chạy sau notebook tự lấy token, không cần nhập lại"
      ],
      "id": "dd112ce5"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from huggingface_hub import login\n",
        "from google.colab import userdata\n",
        "\n",
        "try:\n",
        "    token = userdata.get(\"HF_TOKEN\")\n",
        "except userdata.SecretNotFoundError as e:\n",
        "    raise RuntimeError(\n",
        "        \"Chưa có khóa bí mật HF_TOKEN.\\n\"\n",
        "        \"Colab → 🔑 Khóa bí mật → Thêm secret tên HF_TOKEN \"\n",
        "        \"(token Read từ hf.co/settings/tokens).\\n\"\n",
        "        \"Lưu một lần, lần sau không cần nhập lại.\"\n",
        "    ) from e\n",
        "\n",
        "if not token or not str(token).strip():\n",
        "    raise RuntimeError(\"HF_TOKEN trong Khóa bí mật đang trống — hãy cập nhật lại.\")\n",
        "\n",
        "login(token.strip())\n",
        "print(\"Đã login Hugging Face (HF_TOKEN từ Khóa bí mật)\")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "7093f8b8"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. Tải giọng & công cụ từ Hugging Face"
      ],
      "id": "cf360488"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from pathlib import Path\n",
        "from huggingface_hub import snapshot_download\n",
        "\n",
        "ROOT = Path(snapshot_download(HF_REPO, repo_type=\"dataset\", local_dir=\"/content/omnivoice-vi\"))\n",
        "print(f\"Đã tải: {ROOT}\")\n",
        "print(\"Giọng:\", [p.parent.name for p in sorted((ROOT / \"voices\").glob(\"*/profile.json\"))])"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "db3a8b3d"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import importlib.util\n",
        "import sys\n",
        "\n",
        "speak_path = ROOT / \"tools\" / \"speak.py\"\n",
        "spec = importlib.util.spec_from_file_location(\"speak\", speak_path)\n",
        "speak = importlib.util.module_from_spec(spec)\n",
        "sys.modules[\"speak\"] = speak\n",
        "spec.loader.exec_module(speak)\n",
        "print(\"Đã load speak.py\")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "15179395"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. Tải & nạp model (~3–8 phút lần đầu)\n",
        "\n",
        "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)."
      ],
      "id": "1098d631"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from huggingface_hub import hf_hub_download\n",
        "\n",
        "OMNI_MODEL = \"k2-fsa/OmniVoice\"\n",
        "\n",
        "# Tải từng file lớn (tránh treo snapshot_download trên Colab)\n",
        "for relpath, label in [\n",
        "    (\"model.safetensors\", \"LLM ~2.4 GB\"),\n",
        "    (\"audio_tokenizer/model.safetensors\", \"Audio tokenizer ~770 MB\"),\n",
        "]:\n",
        "    print(f\"\\n>>> {label}\")\n",
        "    path = hf_hub_download(OMNI_MODEL, relpath)\n",
        "    print(f\"    OK: {path}\")\n",
        "\n",
        "for relpath in (\n",
        "    \"config.json\",\n",
        "    \"tokenizer.json\",\n",
        "    \"tokenizer_config.json\",\n",
        "    \"chat_template.jinja\",\n",
        "    \"audio_tokenizer/config.json\",\n",
        "    \"audio_tokenizer/preprocessor_config.json\",\n",
        "):\n",
        "    hf_hub_download(OMNI_MODEL, relpath)\n",
        "\n",
        "print(\"\\n✓ Model k2-fsa/OmniVoice đã cache xong.\")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "f69ce212"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "PROFILE = speak.load_profile(ROOT / \"voices\" / DEFAULT_VOICE / \"profile.json\")\n",
        "MODEL = speak.load_model(PROFILE)\n",
        "PROMPT = speak.ensure_voice_prompt(MODEL, PROFILE)\n",
        "print(f\"Giọng: {PROFILE['name']} ({DEFAULT_VOICE}) | SR: {MODEL.sampling_rate}\")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "93c1dc54"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. Lồng tiếng SRT từ Google Drive\n",
        "\n",
        "Đặt file SRT vào **`MyDrive/Omivoice/`**. Giọng = **`DEFAULT_VOICE`** ở mục 0."
      ],
      "id": "1ea557c5"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from google.colab import drive\n",
        "\n",
        "drive.mount(\"/content/drive\")\n",
        "\n",
        "DRIVE_OMIVOICE = Path(\"/content/drive/MyDrive\") / DRIVE_FOLDER\n",
        "DRIVE_OMIVOICE.mkdir(parents=True, exist_ok=True)\n",
        "\n",
        "srt_name = SRT_FILE if SRT_FILE.lower().endswith(\".srt\") else f\"{SRT_FILE}.srt\"\n",
        "SRT_PATH = DRIVE_OMIVOICE / srt_name\n",
        "\n",
        "if not SRT_PATH.exists():\n",
        "    existing = sorted(DRIVE_OMIVOICE.glob(\"*.srt\"))\n",
        "    hint = \"\\n  \".join(str(p.name) for p in existing) if existing else \"(chưa có file .srt)\"\n",
        "    raise FileNotFoundError(\n",
        "        f\"Không thấy {SRT_PATH}\\n\"\n",
        "        f\"Đặt file vào MyDrive/{DRIVE_FOLDER}/ hoặc sửa SRT_FILE.\\n\"\n",
        "        f\"Các file .srt hiện có:\\n  {hint}\"\n",
        "    )\n",
        "\n",
        "MERGE_OUT = DRIVE_OMIVOICE / f\"{SRT_PATH.stem}_merged.wav\"\n",
        "OUTPUT_DIR = DRIVE_OMIVOICE / \"output\" / DEFAULT_VOICE / SRT_PATH.stem\n",
        "\n",
        "print(f\"Drive:  {DRIVE_OMIVOICE}\")\n",
        "print(f\"Giọng:  {DEFAULT_VOICE}\")\n",
        "print(f\"Input:  {SRT_PATH}\")\n",
        "print(f\"Output: {MERGE_OUT}\")\n",
        "print(f\"Cues:   {OUTPUT_DIR}\")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "ccb48064"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from IPython.display import Audio, display\n",
        "from tqdm.auto import tqdm\n",
        "import sys\n",
        "\n",
        "profile_path = ROOT / \"voices\" / DEFAULT_VOICE / \"profile.json\"\n",
        "\n",
        "pbar = tqdm(total=100, unit=\"%\", desc=\"Chuẩn bị\")\n",
        "\n",
        "\n",
        "def on_log(line: str) -> None:\n",
        "    tqdm.write(line)\n",
        "    sys.stdout.flush()\n",
        "\n",
        "def on_progress(pct: float, desc: str = \"\") -> None:\n",
        "    pbar.n = min(100, max(0, int(round(pct * 100))))\n",
        "    if desc:\n",
        "        pbar.set_description(desc)\n",
        "    pbar.refresh()\n",
        "\n",
        "print(f\"=== SRT: {SRT_PATH.name} | giọng {DEFAULT_VOICE} | mode {MERGE_MODE} ===\", flush=True)\n",
        "\n",
        "result = speak.run_srt_pipeline(\n",
        "    profile_path,\n",
        "    SRT_PATH,\n",
        "    output_dir=OUTPUT_DIR,\n",
        "    merge=True,\n",
        "    merge_output=MERGE_OUT,\n",
        "    merge_mode=MERGE_MODE,\n",
        "    num_step=NUM_STEP,\n",
        "    model=MODEL,\n",
        "    prompt=PROMPT,\n",
        "    on_log=on_log,\n",
        "    progress=on_progress,\n",
        ")\n",
        "\n",
        "pbar.close()\n",
        "\n",
        "merged = result.get(\"merged_wav\")\n",
        "if merged:\n",
        "    display(Audio(str(merged)))\n",
        "\n",
        "print(\"\\n--- Đã lưu trên Drive ---\")\n",
        "print(f\"WAV gộp:     {result.get('merged_wav')}\")\n",
        "print(f\"Từng cue:    {result.get('output_dir')}\")\n",
        "print(f\"SRT shifted: {result.get('shifted_srt')}\")\n",
        "stats = result.get(\"stats\", {})\n",
        "print(\n",
        "    f\"Thống kê: {stats.get('generated', 0)} cue mới, \"\n",
        "    f\"{stats.get('skipped', 0)} bỏ qua, \"\n",
        "    f\"{stats.get('overflow', 0)} tràn\"\n",
        ")"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "d924855a"
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. Giải phóng VRAM & tắt runtime\n",
        "\n",
        "Giải phóng bộ nhớ GPU rồi **ngắt session Colab** (không tính phí GPU nữa). Chạy cell này sau khi mục 4 xong."
      ],
      "id": "4ec794ec"
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import gc\n",
        "import torch\n",
        "from google.colab import runtime\n",
        "\n",
        "try:\n",
        "    del MODEL, PROMPT, result, pbar\n",
        "except NameError:\n",
        "    pass\n",
        "\n",
        "gc.collect()\n",
        "if torch.cuda.is_available():\n",
        "    torch.cuda.empty_cache()\n",
        "    torch.cuda.ipc_collect()\n",
        "\n",
        "print(\"Đã giải phóng VRAM\")\n",
        "print(\"Đang tắt runtime Colab...\")\n",
        "runtime.unassign()"
      ],
      "execution_count": null,
      "outputs": [],
      "id": "a3acbb68"
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "gpuType": "L4",
      "machine_shape": "hm",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.10.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}