{ "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 }