Upload OmniSub source
Browse filesFiles changed (23)
- .gitignoreAdded+31
- PLAN.mdAdded+186
- README.mdAdded+60
- colab/OmniSub_Colab.ipynbAdded+183
- config.yamlAdded+31
- pyproject.tomlAdded+36
- requirements-colab.txtAdded+23
- samples/demo.zh.srtAdded+20
- src/omnisub/__init__.pyAdded+3
- src/omnisub/backends/__init__.pyAdded+5
- src/omnisub/backends/base.pyAdded+134
- src/omnisub/backends/transformers_qwen.pyAdded+167
- src/omnisub/cli.pyAdded+137
- src/omnisub/config.pyAdded+99
- src/omnisub/correct.pyAdded+52
- src/omnisub/diarize.pyAdded+85
- src/omnisub/glossary.pyAdded+97
- src/omnisub/pipeline.pyAdded+267
- src/omnisub/profiles.pyAdded+133
- src/omnisub/scene_context.pyAdded+166
- src/omnisub/scenes.pyAdded+166
- src/omnisub/srt.pyAdded+163
- src/omnisub/translate.pyAdded+132
12345678910111213141516171819202122232425262728293031# Python__pycache__/*.py[cod]*.egg-info/.eggs/build/dist/.venv/venv/
# Media & dữ liệu phim (KHÔNG đẩy lên repo mã nguồn)*.mp4*.mkv*.avi*.mov*.webm*.ts*.flv*.wav*.mp3
# Đầu ra pipeline*.vi.srt*.report.jsonglossary.jsonwork//content/
# Phụ đề test ở thư mục gốc (không đẩy lên repo mã nguồn); vẫn giữ samples//*.srt!samples/*.srt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186# PLAN — OmniSub (dịch SRT ZH→VI bằng Qwen3-Omni)
Tài liệu thiết kế chi tiết. Quyết định đã chốt: **cloud-first (Colab L4 24GB)**, **Qwen3-Omni 4-bitlàm tất cả** (nghe giọng + nhìn cảnh + dịch), **bỏ regex xưng hô** của bản cũ.
---
## 0. Quyết định đã chốt- **Model**: `Qwen/Qwen3-Omni-30B-A3B-Instruct` (bản **Instruct**, 4-bit).- **OCR sửa phụ đề cháy hình** (Bước 1, tùy chọn): **giữ lại nhưng MẶC ĐỊNH TẮT** (`correct_ocr: false`), bật khi cần qua config/CLI. Nguồn SRT hiện đã sạch.- **Tên file ra**: giữ nếp cũ `*.vi.srt` (+ `*.vi.srt.report.json`).
## 1. Mục tiêu1. Dịch SRT **Trung → Việt** tự nhiên, đúng văn nói, súc tích.2. **Xưng hô đúng vai vế** nhờ: - **Nghe giọng**: ai đang nói (diarization) + giới/tuổi/cảm xúc/vai vế (Omni nghe trực tiếp). - **Nhìn ngữ cảnh**: frame video của cảnh đang dịch.3. Nhất quán **tên riêng** và **cách xưng hô** xuyên suốt phim.4. Phụ đề **vừa thời lượng** hiển thị (chars/giây, số dòng).
## 2. Bài học từ `Gemma-4` (giữ / bỏ)**Giữ (port sạch):**- `parse_srt`, `write_srt`, `subtitle_char_budget`, `_seconds_to_srt_time` — I/O SRT vững.- `group_scenes`, `merge_adjacent_pairs` — gom cảnh, ghép cue vụn (sentence-aware, same-speaker).- Pattern `chat_json` + `_extract_json` — parse JSON từ output model bền bỉ.- Cấu trúc Colab + Google Drive (`Phim/`, `Cache/`).
**Bỏ / thay thế:**- ❌ `RelationshipRegistry`, `_CJK_ROMANCE_RE`, `_CJK_FAMILY_RE`, `_VN_ANH_EM_RE`, `enforce_cue` (hàng trăm dòng regex khóa anh/em vs mẹ/con) → thay bằng **hồ sơ giọng + ngữ cảnh đa phương thức**.- ❌ `estimate_speaker_demographics` (wav2vec2 age/gender) → Omni nghe hiểu trực tiếp.- ❌ `_patch_speechbrain_lazy` (vá Windows) → Colab Linux không cần.- 🔄 Gemma 4 12B (llama.cpp) → **Qwen3-Omni-30B-A3B** (transformers).
## 3. Kiến trúc & luồng 5 bước
```INPUT: video.mp4 + video.srt (ZH) │┌───────────────────────────────────────────────────────────────────────────────┐│ Bước 1 Chuẩn bị SRT srt.py + scenes.py ││ parse → gom cảnh → ghép cue vụn → char budget ││ [tùy chọn] OCR sửa phụ đề cháy hình (correct.py) — MẶC ĐỊNH TẮT │└───────────────────────────────────────────────────────────────────────────────┘ │┌───────────────────────────────────────────────────────────────────────────────┐│ Bước 2 Phân tích người nói diarize.py ││ pyannote community-1 → speaker turns → gán cue.speaker │└───────────────────────────────────────────────────────────────────────────────┘ │┌───────────────────────────────────────────────────────────────────────────────┐│ Bước 3 Hồ sơ giọng profiles.py ││ Qwen3-Omni nghe 3–5 clip/speaker → VoiceProfile ││ {gender, age_range, emotion, role_guess, register_hint} │└───────────────────────────────────────────────────────────────────────────────┘ │┌───────────────────────────────────────────────────────────────────────────────┐│ Bước 4 Dịch đa phương thức translate.py + scene_context.py ││ Qwen3-Omni: audio cảnh + frames + cues + profiles + glossary (partial)││ → bản dịch VN + ghi chú xưng hô │└───────────────────────────────────────────────────────────────────────────────┘ │┌───────────────────────────────────────────────────────────────────────────────┐│ Bước 5 Hậu kiểm & xuất glossary.py + srt.py ││ nhất quán tên/xưng hô → fit thời lượng → ghi file │└───────────────────────────────────────────────────────────────────────────────┘ │OUTPUT: video.vi.srt + video.vi.srt.report.json + glossary.json```
| Bước | Module | Model | Mặc định ||---|---|---|---|| 1 — Chuẩn bị SRT | `srt.py`, `scenes.py`, `correct.py` | — / Omni (nếu bật OCR) | OCR **tắt** || 2 — Phân tích người nói | `diarize.py` | pyannote | bật || 3 — Hồ sơ giọng | `profiles.py` | Qwen3-Omni | bật || 4 — Dịch | `translate.py`, `scene_context.py` | Qwen3-Omni | bật || 5 — Hậu kiểm | `glossary.py` | — / Omni (rút gọn cue) | bật |
### Vì sao vẫn cần pyannote (Bước 2)Qwen3-Omni hiện **chưa gán nhãn speaker ổn định** trên cả phim (xác nhận qua tài liệu kỹ thuật &nghiên cứu HumanOmni-Speaker 2026 — cần adapter riêng). pyannote cho **nhãn nhất quán** để gắnhồ sơ giọng (Bước 3) cho đúng người ở mọi cảnh.
### Vì sao một mô hình Omni cho Bước 3 & 4Đưa **audio đoạn cảnh + frame + cue** cùng lúc → model "nghe" được tông giọng (ai đang nói với ai,tình cảm hay gắt gỏng) và "thấy" bối cảnh → tự chọn xưng hô. Không còn luật cứng.
## 4. Module chi tiết (`src/omnisub/`)
| File | Trách nhiệm | Nguồn ||---|---|---|| `srt.py` | Dataclass `Cue`, parse/write SRT, char budget | Port từ bản cũ || `scenes.py` | `Scene`, `group_scenes`, `merge_adjacent_pairs` | Port, dọn lại || `diarize.py` | Wrapper pyannote → `SpeakerTurn`, gán `cue.speaker` | Port rút gọn || `correct.py` | Bước 1 — OCR sửa phụ đề cháy hình (**mặc định tắt**) | Port từ `correct_scene` cũ || `profiles.py` | ★ `VoiceProfile`; trích clip/speaker; gọi Omni nghe → hồ sơ | Mới || `scene_context.py` | Trích frame (ffmpeg), chọn audio đoạn cảnh | Port `extract_frame` + mới || `translate.py` | Dựng prompt đa phương thức/cảnh, gọi Omni, parse kết quả | Viết lại (bỏ regex) || `glossary.py` | ★ Nhất quán tên riêng + xưng hô theo dữ liệu (không regex) | Mới (thay NameRegistry) || `backends/base.py` | Interface `LLMBackend.chat_json(text, images, audio, …)` | Mới || `backends/transformers_qwen.py` | Qwen3-Omni qua HF transformers (Colab) | Mới || `pipeline.py` | Điều phối Bước 1→5, logging, progress, stop | Viết lại gọn || `cli.py` | Argparse CLI | Phỏng theo bản cũ |
### `VoiceProfile` (Bước 3) — cấu trúc đề xuất```python@dataclassclass VoiceProfile: speaker: str # "SPEAKER_01" (khớp pyannote) gender: str # nam | nữ | trẻ em | chưa rõ age_range: str # trẻ em | thiếu niên | thanh niên | trung niên | lớn tuổi emotion_baseline: str # vd: điềm đạm / nóng nảy / dịu dàng role_guess: str # vd: "phụ nữ trẻ, có vẻ là người yêu của SPEAKER_02" register_hint: str # gợi ý xưng hô VN: "nên dùng em với SPEAKER_02" evidence: str # vì sao (model tự giải thích ngắn)```Hồ sơ này được nhét vào prompt dịch để Omni giữ xưng hô nhất quán theo từng nhân vật.
### Glossary (Bước 5) — thay regex bằng dữ liệu- Thu thập **tên riêng** (token CJK lặp lại) → khóa **một** cách phiên âm VN, tái dùng (giữ ý tưởng `NameRegistry` cũ nhưng tách bạch, có thể chỉnh tay qua `glossary.json`).- **Cặp xưng hô** giữa các speaker do **model đề xuất** (không hard-code), lưu vào glossary và đưa lại vào prompt các cảnh sau để khóa nhất quán — thay cho `RelationshipRegistry`.
## 5. Backend & mô hình (Colab L4 24GB)- **Model**: `Qwen/Qwen3-Omni-30B-A3B-Instruct` (Bước 3 & 4).- **Lượng hóa**: **4-bit** (bitsandbytes hoặc checkpoint AWQ/GPTQ Int4) → ~17–18GB, vừa L4 24GB (chừa chỗ cho KV cache + encoder audio/vision). *Cần kiểm tra checkpoint 4-bit sẵn có trên HF.*- **Audio**: resample 16 kHz mono (đã có sẵn `extract_audio` bản cũ). Đưa audio **sau** text trong prompt (theo best practice Gemma/Qwen multimodal: ảnh trước text, audio sau text).- **Vision**: frame trích bằng ffmpeg, đưa **trước** text.- **Tham số sampling**: theo khuyến nghị Qwen (temperature ~0.7–1.0, top_p 0.95, top_k 64) — chốt khi test.- **Drive**: cache model ở `Gemma/Cache/`, phim ở `Gemma/Phim/` (giữ nếp cũ).
## 6. Cấu hình (`config.yaml`)```yamlmodels: omni: "Qwen/Qwen3-Omni-30B-A3B-Instruct" quant: "4bit" diarize: "pyannote/speaker-diarization-community-1"translate: source_lang: "Chinese" target_lang: "Vietnamese" chars_per_sec: 22 max_line_chars: 52 max_lines: 2 correct_ocr: false # Bước 1 — OCR sửa phụ đề cháy hình (mặc định tắt) output_suffix: ".vi.srt" # giữ nếp cũscene: max_gap: 1.5 max_cues: 4 max_dur: 20.0profiling: clips_per_speaker: 5 max_seconds_per_clip: 8paths: drive_root: "/content/drive/MyDrive/Gemma"```
## 7. Lộ trình (milestones)- **M1 — Bước 1 Chuẩn bị SRT**: scaffold thư mục, `srt.py`, `scenes.py`, `config.yaml`, `backends/base.py`. *Done khi*: parse SRT → gom cảnh → write SRT chạy được; `python -m omnisub.cli --help`.- **M2 — Backend Omni (Colab)**: notebook tải Qwen3-Omni 4-bit; `chat_json` text-only; dịch thử 1 cảnh.- **M3 — Bước 2 Diarization**: port pyannote gọn; gán `cue.speaker`; xuất nhãn.- **M4 — Bước 3 Voice Profiling ★**: `profiles.py` — Omni nghe clip → `VoiceProfile`.- **M5 — Bước 4 Dịch đa phương thức**: `translate.py` ghép audio+frame+cue+profile; **không regex**.- **M6 — Bước 5 Hậu kiểm**: nhất quán tên/xưng hô; fit timing; xuất `.vi.srt` + report JSON.- **M7 — Tài liệu & hoàn thiện**: tinh chỉnh prompt, hoàn thiện README + notebook Colab.
## 8. Rủi ro & phương án| Rủi ro | Phương án ||---|---|| Omni 4-bit không có checkpoint sẵn / chất lượng tụt | Thử AWQ Int4; nếu kẹt → tách: Qwen3-Omni nghe giọng + Qwen3-VL dịch || L4 24GB tràn VRAM khi kèm audio+vision dài | Giảm số frame/cảnh, cắt audio ≤ 8s/clip, giảm visual token budget || pyannote chậm với phim dài | Chỉ diarize tới `max(cue.end)`; cân nhắc NeMo Sortformer || Diarization gán sai người nói | Cho phép sửa tay nhãn speaker trước Bước 3 || Mất kết nối/ngắt phiên Colab giữa chừng | Cache theo cảnh, cho chạy lại từ cảnh dở; lưu kết quả ra Drive |
## 9. Quyết định (đã chốt — xem mục 0)- ✅ Qwen3-Omni **`-Instruct`** 4-bit.- ✅ OCR (Bước 1) **mặc định tắt** (`correct_ocr: false`), bật khi cần.- ✅ Tên file ra **`.vi.srt`**.
### Việc cần kiểm tra trước M2- Xác nhận có checkpoint **Qwen3-Omni-30B-A3B-Instruct 4-bit / AWQ Int4** trên Hugging Face. Nếu chưa có → phương án dự phòng: Qwen3-Omni (nghe giọng) + Qwen3-VL (dịch). (Xem mục 8.)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# OmniSub — Dịch phụ đề ZH→VI bằng Qwen3-Omni (đa phương thức)
Dịch và hiệu đính phụ đề SRT **Trung → Việt**, trong đó mô hình **nghe giọng nói thật** và**nhìn ngữ cảnh video** để chọn **xưng hô** (anh/em, mẹ/con, tỷ/muội, ngài/ta…) cho đúng vai vế —thay vì suy đoán bằng luật regex như bản cũ.
> Đây là bản viết lại, tối ưu từ dự án `Gemma-4`. Khác biệt chính: gom về **một họ Qwen**,> dùng **Qwen3-Omni** nghe–nhìn–dịch trong cùng một mô hình, và **bỏ toàn bộ regex khóa quan hệ/xưng hô**.
## Vì sao đổi từ Gemma sang Qwen3-Omni- **Dịch ZH→VI tốt hơn**: Qwen dẫn đầu benchmark tiếng Việt & tiếng Trung (SEA-HELM 2026).- **Nghe hiểu giọng**: Qwen3-Omni nhận **text + ảnh + audio + video** natively, SOTA audio, cho biết giới tính/tuổi/cảm xúc/vai vế của người đang nói → neo xưng hô vào ngữ cảnh thật.- **Đơn giản hóa**: một mô hình thay cho 3 stack rời (LLM + wav2vec2 + regex).
## Kiến trúc — 5 bước (cloud-first, Colab L4)```Video + SRT(ZH) ├─ Bước 1 Chuẩn bị SRT parse, gom cảnh, ghép cue [OCR: mặc định tắt] ├─ Bước 2 Phân tích người nói pyannote → ai nói lúc nào ├─ Bước 3 Hồ sơ giọng Qwen3-Omni nghe → VoiceProfile từng nhân vật ├─ Bước 4 Dịch đa phương thức Qwen3-Omni: audio + frame + cue + hồ sơ → VN └─ Bước 5 Hậu kiểm & xuất glossary + fit thời lượng → phim.vi.srt```Qwen3-Omni-30B-A3B đảm nhiệm **Bước 3 & 4** (nghe giọng, nhìn cảnh, dịch). pyannote dùng ở**Bước 2** (gán nhãn người nói nhất quán — việc Omni chưa làm tốt natively).
## Phần cứng — chạy trên ColabQwen3-Omni 4-bit/AWQ khá nặng nên **toàn bộ pipeline chạy trên Colab**, không có nhánh chạy local.
| Nơi chạy | Cấu hình | Vai trò ||---|---|---|| **Colab** | GPU **L4 24GB** | Chạy Qwen3-Omni **4-bit** (~17–18GB) + pyannote — toàn bộ pipeline |
## Trạng thái🚧 Đang phát triển. Đã xong **M1 — Chuẩn bị SRT** (parse → ghép cue vụn → gom cảnh → xuất)và bộ khung đầy đủ Bước 2–5 (diarization, hồ sơ giọng, dịch đa phương thức, hậu kiểm) cùngbackend Qwen3-Omni cho Colab. Chi tiết kiến trúc, module và lộ trình: xem [`PLAN.md`](PLAN.md).
## Cách dùng (Colab)Mở [`colab/OmniSub_Colab.ipynb`](colab/OmniSub_Colab.ipynb) trên Colab (Runtime → L4) và chạy lần lượt các cell.Cell cuối gọi pipeline tương đương:```bashpython -m omnisub.cli run phim.srt --video phim.mp4 --backend qwen --config config.yaml```Kiểm tra nhanh Bước 1 (không nạp model) ngay trong Colab/môi trường có Python:```bashpython -m omnisub.cli prepare samples/demo.zh.srt```
## Cấu trúc thư mục```Gemma/├── README.md / PLAN.md├── pyproject.toml / requirements-colab.txt / config.yaml├── src/omnisub/{srt,scenes,diarize,correct,profiles,scene_context,translate,glossary,pipeline,cli,config}.py│ └── backends/{base,transformers_qwen}.py├── colab/OmniSub_Colab.ipynb└── samples/demo.zh.srt```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# OmniSub — Dịch SRT ZH→VI bằng Qwen3-Omni (Colab L4 24GB)\n", "\n", "Chạy lần lượt từng cell. Yêu cầu: Runtime **GPU L4** (Runtime → Change runtime type → L4).\n", "\n", "Pipeline 5 bước: chuẩn bị SRT → diarization (pyannote) → hồ sơ giọng (Omni) → dịch đa phương thức (Omni) → hậu kiểm & xuất." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 1) Kiểm tra GPU\n", "!nvidia-smi" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 2) Mount Google Drive (phim ở Gemma/Phim, cache model ở Gemma/Cache)\n", "from google.colab import drive\n", "drive.mount('/content/drive')\n", "\n", "import os\n", "DRIVE_ROOT = '/content/drive/MyDrive/Gemma'\n", "os.makedirs(f'{DRIVE_ROOT}/Phim', exist_ok=True)\n", "os.makedirs(f'{DRIVE_ROOT}/Cache', exist_ok=True)\n", "print('Drive root:', DRIVE_ROOT)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 3) Lấy MÃ NGUỒN từ Hugging Face Hub + cài phụ thuộc\n", "HF_REPO = 'STBack23/OmniSub' # ← repo HF chứa mã nguồn dự án\n", "HF_REPO_TYPE = 'model' # 'model' | 'dataset' | 'space'\n", "\n", "import os\n", "%cd /content\n", "!pip install -q -U huggingface_hub\n", "from huggingface_hub import snapshot_download\n", "# Repo công khai → KHÔNG cần token. Nếu repo riêng tư, thêm token=... vào đây.\n", "snapshot_download(repo_id=HF_REPO, repo_type=HF_REPO_TYPE, local_dir='/content/Gemma')\n", "%cd /content/Gemma\n", "\n", "!pip install -q -e .[colab]\n", "# Qwen3-Omni hiện CHƯA có trên PyPI của transformers → cài bản từ nguồn:\n", "!pip install -q -U \"git+https://github.com/huggingface/transformers\"\n", "!pip install -q -U qwen-omni-utils\n", "# FlashAttention 2 (giảm VRAM); nếu build lỗi có thể bỏ qua và dùng attn mặc định.\n", "!pip install -q -U flash-attn --no-build-isolation\n", "!apt-get -qq install -y ffmpeg\n", "print('Mã nguồn OmniSub đã sẵn sàng (từ Hugging Face Hub).')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 4) Chọn phim — CHỈ cần nhập TÊN phim, tự dò file .srt và video trong Gemma/Phim\n", "import os\n", "from getpass import getpass\n", "\n", "MOVIE = 'Tiểu Ái Test' # ← đổi tên phim ở đây (trùng tên file, không cần đuôi)\n", "\n", "PHIM_DIR = f'{DRIVE_ROOT}/Phim'\n", "CACHE = f'{DRIVE_ROOT}/Cache'\n", "\n", "HF_TOKEN = os.environ.get('HF_TOKEN') or getpass('HF token (pyannote): ')\n", "assert HF_TOKEN, 'Cần HF token để chạy Bước 2 (diarization).'\n", "\n", "_VIDEO_EXTS = ['.mp4', '.mkv', '.avi', '.mov', '.webm', '.ts', '.flv']\n", "\n", "def _find(stem, exts):\n", " for ext in exts:\n", " p = os.path.join(PHIM_DIR, stem + ext)\n", " if os.path.exists(p):\n", " return p\n", " return None\n", "\n", "stem = os.path.splitext(MOVIE)[0]\n", "SRT = _find(stem, ['.srt'])\n", "VIDEO = _find(stem, _VIDEO_EXTS)\n", "\n", "assert SRT, f\"Không thấy '{stem}.srt' trong {PHIM_DIR}. File hiện có: {os.listdir(PHIM_DIR)}\"\n", "if not VIDEO:\n", " print(f\"⚠️ Không thấy video cho '{stem}' — chạy được Bước 1, nhưng Bước 4 cần video.\")\n", "\n", "print('Phim :', stem)\n", "print('SRT :', SRT)\n", "print('Video:', VIDEO)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 5) Nạp model Qwen3-Omni 4-bit (vài phút lần đầu)\n", "from omnisub.config import Config\n", "from omnisub.backends.transformers_qwen import TransformersQwenOmniBackend\n", "\n", "config = Config.load('config.yaml')\n", "backend = TransformersQwenOmniBackend(\n", " model_name=config.models['omni'],\n", " quant=config.models['quant'],\n", " cache_dir=CACHE,\n", ")\n", "backend.load()\n", "print('Model đã nạp xong.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 6) Chạy toàn bộ pipeline (Bước 1→5)\n", "import logging\n", "logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')\n", "\n", "from omnisub.pipeline import run_pipeline\n", "\n", "result = run_pipeline(\n", " SRT,\n", " video=VIDEO,\n", " config=config,\n", " backend=backend,\n", " work_dir='/content/work',\n", " hf_token=HF_TOKEN,\n", " do_diarize=True,\n", ")\n", "print('Output SRT:', result.output_srt)\n", "print('Report :', result.report_path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# 7) Xem nhanh kết quả + report\n", "import json\n", "print(open(result.output_srt, encoding='utf-8').read()[:2000])\n", "print('\\n--- REPORT ---')\n", "print(json.dumps(json.load(open(result.report_path, encoding='utf-8')), ensure_ascii=False, indent=2))" ] } ], "metadata": { "accelerator": "GPU", "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 0}12345678910111213141516171819202122232425262728293031models: omni: "Qwen/Qwen3-Omni-30B-A3B-Instruct" quant: "4bit" diarize: "pyannote/speaker-diarization-community-1"
translate: source_lang: "Chinese" target_lang: "Vietnamese" chars_per_sec: 22 max_line_chars: 52 max_lines: 2 correct_ocr: false # Bước 1 — OCR sửa phụ đề cháy hình (mặc định tắt) output_suffix: ".vi.srt" # giữ nếp cũ
scene: max_gap: 1.5 max_cues: 4 max_dur: 20.0
profiling: clips_per_speaker: 5 max_seconds_per_clip: 8
sampling: temperature: 0.7 top_p: 0.95 top_k: 64 max_new_tokens: 1024
paths: drive_root: "/content/drive/MyDrive/Gemma"123456789101112131415161718192021222324252627282930313233343536[build-system]requires = ["setuptools>=68", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "omnisub"version = "0.1.0"description = "Dịch phụ đề SRT ZH→VI bằng Qwen3-Omni (đa phương thức)"readme = "README.md"requires-python = ">=3.9"dependencies = ["PyYAML>=6.0"]
[project.optional-dependencies]colab = [ "transformers>=4.57.0", "accelerate>=0.34.0", "bitsandbytes>=0.43.0", "qwen-omni-utils>=0.0.4", "torch>=2.4.0", "torchaudio>=2.4.0", "torchvision>=0.19.0", "pyannote.audio>=3.3.0", "soundfile>=0.12.1", "librosa>=0.10.0", "av>=12.0.0", "Pillow>=10.0.0",]
[project.scripts]omnisub = "omnisub.cli:main"
[tool.setuptools.packages.find]where = ["src"]
[tool.setuptools.package-data]omnisub = ["py.typed"]1234567891011121314151617181920212223# OmniSub — phụ thuộc đầy đủ trên Colab L4 24GB (toàn bộ pipeline)PyYAML>=6.0
# Qwen3-Omni qua HF transformers (Bước 3 & 4)# LƯU Ý: Qwen3-Omni có thể CHƯA nằm trong bản transformers trên PyPI. Nếu nạp model# báo thiếu Qwen3OmniMoe..., hãy cài bản từ nguồn (notebook Colab đã làm sẵn):# pip install -U "git+https://github.com/huggingface/transformers"transformers>=4.57.0accelerate>=0.34.0bitsandbytes>=0.43.0 # lượng hóa 4-bitqwen-omni-utils>=0.0.4 # tiện ích xử lý multimodal của Qwen3-Omnitorch>=2.4.0torchaudio>=2.4.0torchvision>=0.19.0
# Bước 2 — diarizationpyannote.audio>=3.3.0
# I/O mediasoundfile>=0.12.1librosa>=0.10.0av>=12.0.0 # đọc/giải mã video (PyAV)Pillow>=10.0.01234567891011121314151617181920100:00:01,000 --> 00:00:02,200你回来了
200:00:02,300 --> 00:00:03,000姐姐
300:00:03,100 --> 00:00:05,500我今天在学校遇到一件奇怪的事
400:00:10,000 --> 00:00:12,000别担心,我会保护你的
500:00:12,200 --> 00:00:13,500谢谢你,哥哥123"""OmniSub — dịch phụ đề SRT ZH→VI bằng Qwen3-Omni (đa phương thức)."""
__version__ = "0.1.0"12345"""Backends LLM cho OmniSub."""
from .base import LLMBackend, ChatMessage, extract_json
__all__ = ["LLMBackend", "ChatMessage", "extract_json"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Interface backend LLM + tiện ích parse JSON bền bỉ từ output model.
Mọi backend (transformers Qwen3-Omni, llama.cpp fallback) phải hiện thực`LLMBackend`. Pipeline chỉ phụ thuộc vào interface này, không vào model cụ thể."""
from __future__ import annotations
import abcimport jsonimport refrom dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional, Sequence
@dataclassclass ChatMessage: """Một message đa phương thức gửi tới model.
- `text`: nội dung văn bản. - `images`: đường dẫn ảnh/frame (đưa TRƯỚC text khi build prompt). - `audio`: đường dẫn audio (đưa SAU text — theo best practice Qwen multimodal). """
role: str = "user" text: str = "" images: List[str] = field(default_factory=list) audio: List[str] = field(default_factory=list)
class LLMBackend(abc.ABC): """Giao diện tối thiểu cho mọi backend."""
@abc.abstractmethod def chat( self, messages: Sequence[ChatMessage], *, system: Optional[str] = None, max_new_tokens: int = 1024, temperature: float = 0.7, top_p: float = 0.95, top_k: int = 64, **kwargs: Any, ) -> str: """Sinh văn bản từ chuỗi message. Trả về raw text.""" raise NotImplementedError
def chat_json( self, messages: Sequence[ChatMessage], *, system: Optional[str] = None, max_new_tokens: int = 1024, **kwargs: Any, ) -> Any: """Gọi `chat` rồi cố trích JSON từ output. Trả về dict/list đã parse.""" raw = self.chat( messages, system=system, max_new_tokens=max_new_tokens, **kwargs ) return extract_json(raw)
# Tiện ích cho subclass: gom text từ message (cho backend text-only). @staticmethod def _join_text(messages: Sequence[ChatMessage]) -> str: return "\n".join(m.text for m in messages if m.text)
_FENCE_RE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL | re.IGNORECASE)
def extract_json(raw: str) -> Any: """Trích object/array JSON đầu tiên từ output model.
Thử theo thứ tự: parse trực tiếp → bóc khối ```json``` → quét cặp ngoặc cân bằng đầu tiên. Ném `ValueError` nếu không tìm được JSON hợp lệ. """ if raw is None: raise ValueError("Output rỗng, không có JSON.") text = raw.strip()
# 1) parse thẳng try: return json.loads(text) except json.JSONDecodeError: pass
# 2) bóc khối ```json ... ``` m = _FENCE_RE.search(text) if m: candidate = m.group(1).strip() try: return json.loads(candidate) except json.JSONDecodeError: text = candidate # tiếp tục quét trong nội dung khối
# 3) quét cặp ngoặc cân bằng đầu tiên ({} hoặc []) for opener, closer in (("{", "}"), ("[", "]")): snippet = _extract_balanced(text, opener, closer) if snippet: try: return json.loads(snippet) except json.JSONDecodeError: continue
raise ValueError(f"Không trích được JSON từ output:\n{raw[:500]}")
def _extract_balanced(text: str, opener: str, closer: str) -> Optional[str]: start = text.find(opener) if start == -1: return None depth = 0 in_str = False escape = False for i in range(start, len(text)): ch = text[i] if in_str: if escape: escape = False elif ch == "\\": escape = True elif ch == '"': in_str = False continue if ch == '"': in_str = True elif ch == opener: depth += 1 elif ch == closer: depth -= 1 if depth == 0: return text[start : i + 1] return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167"""Backend Qwen3-Omni qua HuggingFace transformers (Colab L4 24GB).
Nạp `Qwen/Qwen3-Omni-30B-A3B-Instruct` 4-bit (bitsandbytes) và chạy suy luậnđa phương thức (text + image + audio). Import nặng đều lazy để Bước 1 không cần GPU.
Tham khảo: model card Qwen3-Omni + `qwen_omni_utils.process_mm_info`."""
from __future__ import annotations
from typing import Any, List, Optional, Sequence
from .base import ChatMessage, LLMBackend
class TransformersQwenOmniBackend(LLMBackend): def __init__( self, model_name: str = "Qwen/Qwen3-Omni-30B-A3B-Instruct", *, quant: str = "4bit", device_map: str = "auto", cache_dir: Optional[str] = None, attn_implementation: Optional[str] = "flash_attention_2", ): self.model_name = model_name self.quant = quant self.device_map = device_map self.cache_dir = cache_dir self.attn_implementation = attn_implementation self._model = None self._processor = None
def load(self) -> None: """Nạp model + processor (gọi một lần, tốn vài phút trên Colab).""" if self._model is not None: return import torch from transformers import ( Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor, )
quant_config = None if self.quant in ("4bit", "8bit"): from transformers import BitsAndBytesConfig
quant_config = BitsAndBytesConfig( load_in_4bit=self.quant == "4bit", load_in_8bit=self.quant == "8bit", bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, )
self._processor = Qwen3OmniMoeProcessor.from_pretrained( self.model_name, cache_dir=self.cache_dir )
# Ưu tiên FlashAttention 2 (ít VRAM nhất); nếu không build được thì lùi # về sdpa rồi eager để vẫn chạy. attn_candidates = [self.attn_implementation, "sdpa", "eager"] seen, attn_candidates = set(), [ a for a in attn_candidates if a and not (a in seen or seen.add(a)) ] last_err: Optional[Exception] = None for attn in attn_candidates: try: self._model = Qwen3OmniMoeForConditionalGeneration.from_pretrained( self.model_name, torch_dtype=torch.bfloat16, device_map=self.device_map, quantization_config=quant_config, attn_implementation=attn, cache_dir=self.cache_dir, ) self.attn_implementation = attn break except (ImportError, ValueError) as e: last_err = e continue if self._model is None: raise RuntimeError(f"Không nạp được model với mọi attn_implementation: {last_err}") # Chỉ cần text → tắt talker (sinh audio) để tiết kiệm ~10GB VRAM. disable = getattr(self._model, "disable_talker", None) if callable(disable): disable() self._model.eval()
def _to_qwen_messages( self, messages: Sequence[ChatMessage], system: Optional[str] ) -> List[dict]: """Chuyển ChatMessage → định dạng content của Qwen (ảnh trước, audio sau text).""" out: List[dict] = [] if system: out.append({"role": "system", "content": [{"type": "text", "text": system}]}) for m in messages: content: List[dict] = [] for img in m.images: # ảnh TRƯỚC text content.append({"type": "image", "image": img}) if m.text: content.append({"type": "text", "text": m.text}) for aud in m.audio: # audio SAU text content.append({"type": "audio", "audio": aud}) out.append({"role": m.role, "content": content}) return out
def chat( self, messages: Sequence[ChatMessage], *, system: Optional[str] = None, max_new_tokens: int = 1024, temperature: float = 0.7, top_p: float = 0.95, top_k: int = 64, **kwargs: Any, ) -> str: self.load() import torch from qwen_omni_utils import process_mm_info
conv = self._to_qwen_messages(messages, system) text = self._processor.apply_chat_template( conv, add_generation_prompt=True, tokenize=False ) # Ta trích audio/frame riêng nên không dùng audio-trong-video. audios, images, videos = process_mm_info(conv, use_audio_in_video=False) inputs = self._processor( text=text, audio=audios, images=images, videos=videos, return_tensors="pt", padding=True, use_audio_in_video=False, ) inputs = inputs.to(self._model.device) # ép tensor float về dtype của model (vd bf16) — BatchFeature.to(dtype) # chỉ đổi tensor float, giữ nguyên input_ids dạng int. try: inputs = inputs.to(self._model.dtype) except (AttributeError, RuntimeError, TypeError): pass
with torch.no_grad(): generated = self._model.generate( **inputs, max_new_tokens=max_new_tokens, do_sample=temperature > 0, temperature=temperature, top_p=top_p, top_k=top_k, # chỉ cần text: tắt sinh audio + trả về dict để lấy .sequences return_audio=False, thinker_return_dict_in_generate=True, use_audio_in_video=False, ) # generate trả về tuple (text_ids, audio); text_ids có thể là ModelOutput text_ids = generated[0] if isinstance(generated, (tuple, list)) else generated sequences = getattr(text_ids, "sequences", text_ids) # cắt phần prompt, chỉ decode token mới trimmed = sequences[:, inputs["input_ids"].shape[1] :] out = self._processor.batch_decode( trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False ) return out[0].strip() if out else ""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""CLI cho OmniSub.
Ví dụ: # Kiểm tra nhanh Bước 1 (không nạp model): parse + gom cảnh python -m omnisub.cli prepare phim.srt
# Toàn bộ pipeline trên Colab (có video + Qwen3-Omni) python -m omnisub.cli run phim.srt --video phim.mp4 --config config.yaml"""
from __future__ import annotations
import argparseimport loggingimport sysfrom pathlib import Path
from .config import Configfrom .pipeline import prepare_subtitles, run_pipeline
def _force_utf8() -> None: """Ép stdout/stderr sang UTF-8 (console Windows mặc định cp1252 không in được tiếng Việt).""" for stream in (sys.stdout, sys.stderr): reconfigure = getattr(stream, "reconfigure", None) if reconfigure is not None: try: reconfigure(encoding="utf-8") except (ValueError, OSError): pass
def _setup_logging(verbose: bool) -> None: _force_utf8() logging.basicConfig( level=logging.DEBUG if verbose else logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S", )
def _build_backend(config: Config, args): """Khởi tạo backend Qwen3-Omni (lazy import để Bước 1 không cần GPU).
`--backend none` chỉ chạy Bước 1 (chuẩn bị SRT) để kiểm tra nhanh, không nạp model. """ if args.backend == "none": return None if args.backend == "qwen": from .backends.transformers_qwen import TransformersQwenOmniBackend
return TransformersQwenOmniBackend( model_name=config.models["omni"], quant=config.models["quant"], cache_dir=args.cache_dir, ) raise SystemExit(f"Backend không hỗ trợ: {args.backend}")
def cmd_prepare(args) -> int: config = Config.load(args.config) cues, scenes = prepare_subtitles(args.srt, config) print(f"Cue: {len(cues)} | Cảnh: {len(scenes)}") for sc in scenes[: args.preview]: print(f" Cảnh #{sc.scene_id} [{sc.start:.1f}-{sc.end:.1f}s] {len(sc.cues)} cue") for c in sc.cues: print(f" [{c.index}] {c.text[:60]}") if args.out: from .srt import write_srt
write_srt(cues, args.out) print(f"Đã ghi cue đã gom cảnh ra: {args.out}") return 0
def cmd_run(args) -> int: config = Config.load(args.config) backend = _build_backend(config, args) result = run_pipeline( args.srt, video=args.video, config=config, backend=backend, work_dir=args.work_dir, hf_token=args.hf_token, do_diarize=not args.no_diarize, do_profile=not args.no_profile, do_translate=not args.no_translate, ) print(f"Xong. Output: {result.output_srt}") print(f"Report: {result.report_path}") return 0
def build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser( prog="omnisub", description="Dịch phụ đề SRT ZH→VI bằng Qwen3-Omni (đa phương thức).", ) p.add_argument("-v", "--verbose", action="store_true", help="log chi tiết") p.add_argument("--config", default="config.yaml", help="đường dẫn config.yaml") sub = p.add_subparsers(dest="command", required=True)
pp = sub.add_parser("prepare", help="Bước 1: parse + gom cảnh (không cần model)") pp.add_argument("srt", help="file SRT nguồn (ZH)") pp.add_argument("--out", help="ghi cue đã gom cảnh ra file SRT (tùy chọn)") pp.add_argument("--preview", type=int, default=5, help="số cảnh in thử") pp.set_defaults(func=cmd_prepare)
pr = sub.add_parser("run", help="Chạy pipeline đầy đủ (Bước 1→5)") pr.add_argument("srt", help="file SRT nguồn (ZH)") pr.add_argument("--video", help="file video tương ứng (mp4...)") pr.add_argument( "--backend", choices=["none", "qwen"], default="qwen", help="backend model (none = chỉ chạy Bước 1)", ) pr.add_argument("--cache-dir", help="thư mục cache model (Drive/Cache)") pr.add_argument("--work-dir", help="thư mục làm việc tạm (frame/audio)") pr.add_argument("--hf-token", help="HuggingFace token cho pyannote") pr.add_argument("--no-diarize", action="store_true", help="bỏ Bước 2") pr.add_argument("--no-profile", action="store_true", help="bỏ Bước 3") pr.add_argument("--no-translate", action="store_true", help="bỏ Bước 4") pr.set_defaults(func=cmd_run)
return p
def main(argv=None) -> int: _force_utf8() parser = build_parser() args = parser.parse_args(argv) _setup_logging(getattr(args, "verbose", False)) return args.func(args)
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""Đọc và hợp nhất cấu hình từ `config.yaml`."""
from __future__ import annotations
import copyfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Dict
try: import yamlexcept ImportError: # pragma: no cover yaml = None # type: ignore
DEFAULT_CONFIG: Dict[str, Any] = { "models": { "omni": "Qwen/Qwen3-Omni-30B-A3B-Instruct", "quant": "4bit", "diarize": "pyannote/speaker-diarization-community-1", }, "translate": { "source_lang": "Chinese", "target_lang": "Vietnamese", "chars_per_sec": 22, "max_line_chars": 52, "max_lines": 2, "correct_ocr": False, "output_suffix": ".vi.srt", }, "scene": {"max_gap": 1.5, "max_cues": 4, "max_dur": 20.0}, "profiling": {"clips_per_speaker": 5, "max_seconds_per_clip": 8}, "sampling": { "temperature": 0.7, "top_p": 0.95, "top_k": 64, "max_new_tokens": 1024, }, "paths": {"drive_root": "/content/drive/MyDrive/Gemma"},}
def _deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]: out = copy.deepcopy(base) for k, v in (override or {}).items(): if isinstance(v, dict) and isinstance(out.get(k), dict): out[k] = _deep_merge(out[k], v) else: out[k] = v return out
@dataclassclass Config: data: Dict[str, Any]
@classmethod def load(cls, path: str | Path | None = None) -> "Config": merged = copy.deepcopy(DEFAULT_CONFIG) if path is not None: p = Path(path) if p.exists(): if yaml is None: raise RuntimeError( "Cần PyYAML để đọc config.yaml — `pip install pyyaml`." ) loaded = yaml.safe_load(p.read_text(encoding="utf-8")) or {} merged = _deep_merge(merged, loaded) return cls(data=merged)
def __getitem__(self, key: str) -> Any: return self.data[key]
def get(self, key: str, default: Any = None) -> Any: return self.data.get(key, default)
@property def models(self) -> Dict[str, Any]: return self.data["models"]
@property def translate(self) -> Dict[str, Any]: return self.data["translate"]
@property def scene(self) -> Dict[str, Any]: return self.data["scene"]
@property def profiling(self) -> Dict[str, Any]: return self.data["profiling"]
@property def sampling(self) -> Dict[str, Any]: return self.data["sampling"]
@property def paths(self) -> Dict[str, Any]: return self.data["paths"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Bước 1 (tùy chọn) — OCR sửa phụ đề cháy hình. MẶC ĐỊNH TẮT.
Khi `correct_ocr: true`, đưa frame + text OCR cho Omni để sửa lỗi nhận dạng(ký tự sai, dính dòng). Nguồn SRT hiện đã sạch nên mặc định bỏ qua bước này."""
from __future__ import annotations
from typing import List, Optional
from .backends.base import ChatMessage, LLMBackendfrom .scene_context import SceneContextfrom .scenes import Scene
_CORRECT_SYSTEM = ( "Bạn là công cụ sửa lỗi OCR phụ đề tiếng Trung cháy trên khung hình. " "So khớp văn bản với khung hình và sửa ký tự sai. " "Trả về JSON {\"cues\":[{\"id\":<int>,\"zh\":\"<text đã sửa>\"}]}, không thêm gì khác.")
def correct_scene( backend: LLMBackend, scene: Scene, context: Optional[SceneContext], *, max_new_tokens: int = 1024, **sampling,) -> None: """Sửa OCR text gốc của các cue trong cảnh (ghi đè `cue.text`).""" images = [str(p) for p in (context.frame_paths if context else [])] cue_lines = "\n".join(f' {{ "id": {c.index}, "zh": {c.text!r} }}' for c in scene.cues) text = ( "Dưới đây là phụ đề OCR và khung hình tương ứng. Sửa lỗi ký tự nếu có.\n" f"[\n{cue_lines}\n]" ) msg = ChatMessage(role="user", text=text, images=images) try: result = backend.chat_json( [msg], system=_CORRECT_SYSTEM, max_new_tokens=max_new_tokens, **sampling ) except Exception: return if not isinstance(result, dict): return by_id = {c.index: c for c in scene.cues} for item in result.get("cues", []) or []: cid = item.get("id") zh = item.get("zh") if cid in by_id and zh: by_id[cid].text = str(zh).strip()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Bước 2 — Phân tích người nói (diarization).
Wrapper gọn quanh pyannote: audio → danh sách `SpeakerTurn` → gán `cue.speaker`theo độ phủ thời gian lớn nhất. pyannote chỉ import khi thực sự chạy (lazy) đểBước 1 vẫn dùng được local không cần GPU."""
from __future__ import annotations
from dataclasses import dataclassfrom pathlib import Pathfrom typing import List, Optional
from .srt import Cue
@dataclassclass SpeakerTurn: """Một lượt nói liên tục của một speaker."""
speaker: str start: float end: float
@property def duration(self) -> float: return max(0.0, self.end - self.start)
def diarize_audio( audio_path: str | Path, *, model_name: str = "pyannote/speaker-diarization-community-1", hf_token: Optional[str] = None, num_speakers: Optional[int] = None, max_time: Optional[float] = None,) -> List[SpeakerTurn]: """Chạy pyannote trên audio (16 kHz mono khuyến nghị) → SpeakerTurn.
`max_time`: chỉ diarize tới mốc này (vd max(cue.end)) để tiết kiệm thời gian. """ try: import torch from pyannote.audio import Pipeline except ImportError as e: # pragma: no cover raise RuntimeError( "Bước 2 cần `pyannote.audio` + `torch`. Cài qua requirements-colab.txt." ) from e
pipeline = Pipeline.from_pretrained(model_name, use_auth_token=hf_token) if torch.cuda.is_available(): pipeline.to(torch.device("cuda"))
params = {} if num_speakers is not None: params["num_speakers"] = num_speakers
diarization = pipeline(str(audio_path), **params)
turns: List[SpeakerTurn] = [] for segment, _, speaker in diarization.itertracks(yield_label=True): if max_time is not None and segment.start > max_time: continue turns.append( SpeakerTurn(speaker=str(speaker), start=float(segment.start), end=float(segment.end)) ) turns.sort(key=lambda t: t.start) return turns
def assign_speakers(cues: List[Cue], turns: List[SpeakerTurn]) -> List[Cue]: """Gán `cue.speaker` = speaker phủ thời gian cue nhiều nhất.""" if not turns: return cues for cue in cues: best_speaker: Optional[str] = None best_overlap = 0.0 for t in turns: overlap = min(cue.end, t.end) - max(cue.start, t.start) if overlap > best_overlap: best_overlap = overlap best_speaker = t.speaker if best_speaker is not None: cue.speaker = best_speaker return cues12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""Bước 5 — Glossary: nhất quán tên riêng + cặp xưng hô (thay regex bản cũ).
- `name_map`: token CJK (tên riêng) → một cách phiên âm/dịch VN cố định.- `address_pairs`: cặp xưng hô giữa các speaker do model đề xuất, khóa nhất quán.
File `glossary.json` có thể chỉnh tay rồi nạp lại để khóa quyết định."""
from __future__ import annotations
import jsonfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Dict, List
@dataclassclass Glossary: name_map: Dict[str, str] = field(default_factory=dict) # khóa "SPEAKER_01->SPEAKER_02" -> cách xưng (vd "anh-em") address_pairs: Dict[str, str] = field(default_factory=dict)
# ---- tên riêng ---- def register_name(self, source: str, target: str) -> str: """Khóa một cách dịch cho tên riêng. Lần đầu thắng (giữ nhất quán).""" source = source.strip() if not source: return target if source in self.name_map: return self.name_map[source] self.name_map[source] = target.strip() return self.name_map[source]
def get_name(self, source: str) -> str | None: return self.name_map.get(source.strip())
# ---- cặp xưng hô ---- @staticmethod def _pair_key(a: str, b: str) -> str: return f"{a}->{b}"
def register_address(self, speaker_a: str, speaker_b: str, address: str) -> str: key = self._pair_key(speaker_a, speaker_b) if key not in self.address_pairs and address: self.address_pairs[key] = address.strip() return self.address_pairs.get(key, address)
def get_address(self, speaker_a: str, speaker_b: str) -> str | None: return self.address_pairs.get(self._pair_key(speaker_a, speaker_b))
# ---- prompt ---- def prompt_block(self) -> str: """Khối text đưa lại vào prompt các cảnh sau để khóa nhất quán.""" parts: List[str] = [] if self.name_map: names = "\n".join(f" - {s} → {t}" for s, t in self.name_map.items()) parts.append("Tên riêng đã thống nhất (BẮT BUỘC dùng đúng):\n" + names) if self.address_pairs: pairs = "\n".join(f" - {k}: {v}" for k, v in self.address_pairs.items()) parts.append("Cách xưng hô đã thống nhất giữa các nhân vật:\n" + pairs) return "\n".join(parts)
# ---- I/O ---- def save(self, path: str | Path) -> None: p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) p.write_text( json.dumps( {"name_map": self.name_map, "address_pairs": self.address_pairs}, ensure_ascii=False, indent=2, ), encoding="utf-8", )
@classmethod def load(cls, path: str | Path) -> "Glossary": p = Path(path) if not p.exists(): return cls() data = json.loads(p.read_text(encoding="utf-8")) return cls( name_map=dict(data.get("name_map", {})), address_pairs=dict(data.get("address_pairs", {})), )
def update_from_scene_result(self, result: dict) -> None: """Nạp đề xuất tên/xưng hô từ kết quả dịch một cảnh (nếu model trả về).""" for item in result.get("names", []) or []: src = item.get("source") or item.get("zh") tgt = item.get("target") or item.get("vi") if src and tgt: self.register_name(str(src), str(tgt)) for item in result.get("address", []) or []: a, b, addr = item.get("from"), item.get("to"), item.get("address") if a and b and addr: self.register_address(str(a), str(b), str(addr))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267"""Điều phối pipeline 5 bước OmniSub.
Bước 1 (prepare) chạy được local không cần model. Bước 2–5 cần backend Omni +ffmpeg + pyannote (Colab). Mỗi bước tách hàm để test/chạy lại từng phần."""
from __future__ import annotations
import jsonimport loggingimport tempfilefrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Callable, Dict, List, Optional
from .config import Configfrom .diarize import SpeakerTurn, assign_speakers, diarize_audiofrom .glossary import Glossaryfrom .profiles import VoiceProfile, build_all_profiles, save_profilesfrom .scene_context import build_scene_context, extract_audio, extract_speaker_clipsfrom .scenes import Scene, group_scenes, merge_adjacent_pairsfrom .srt import Cue, parse_srt, subtitle_char_budget, write_srtfrom .translate import translate_scene
logger = logging.getLogger("omnisub")
StopCheck = Callable[[], bool]
@dataclassclass PipelineResult: cues: List[Cue] scenes: List[Scene] profiles: Dict[str, VoiceProfile] = field(default_factory=dict) glossary: Glossary = field(default_factory=Glossary) output_srt: Optional[Path] = None report_path: Optional[Path] = None
# ---------------------------------------------------------------------------# Bước 1 — Chuẩn bị SRT# ---------------------------------------------------------------------------def merge_and_group(cues: List[Cue], config: Config) -> tuple[List[Cue], List[Scene]]: """Ghép cue vụn → gom cảnh. Gọi sau khi (tùy chọn) đã gán speaker.""" cues = merge_adjacent_pairs(cues) logger.info("Bước 1: còn %d cue sau khi ghép cue vụn", len(cues))
sc = config.scene scenes = group_scenes( cues, max_gap=sc["max_gap"], max_cues=sc["max_cues"], max_dur=sc["max_dur"] ) logger.info("Bước 1: gom thành %d cảnh", len(scenes)) return cues, scenes
def prepare_subtitles(srt_path: str | Path, config: Config) -> tuple[List[Cue], List[Scene]]: """Bước 1 chạy local (không model/diarization): parse → ghép → gom cảnh.""" cues = parse_srt(srt_path) logger.info("Bước 1: đọc %d cue từ %s", len(cues), srt_path) return merge_and_group(cues, config)
# ---------------------------------------------------------------------------# Bước 2 — Diarization# ---------------------------------------------------------------------------def run_diarization( video: str | Path, cues: List[Cue], config: Config, work_dir: Path, *, hf_token: Optional[str] = None,) -> List[SpeakerTurn]: audio = extract_audio(video, work_dir / "full.wav") max_time = max((c.end for c in cues), default=None) turns = diarize_audio( audio, model_name=config.models["diarize"], hf_token=hf_token, max_time=max_time, ) assign_speakers(cues, turns) logger.info("Bước 2: %d speaker turn, %d speaker", len(turns), len({t.speaker for t in turns})) return turns
# ---------------------------------------------------------------------------# Bước 3 — Hồ sơ giọng# ---------------------------------------------------------------------------def run_profiling( backend, video: str | Path, turns: List[SpeakerTurn], config: Config, work_dir: Path,) -> Dict[str, VoiceProfile]: prof = config.profiling clips = extract_speaker_clips( video, turns, work_dir / "clips", clips_per_speaker=prof["clips_per_speaker"], max_seconds_per_clip=prof["max_seconds_per_clip"], ) profiles = build_all_profiles(backend, clips, **_sampling(config)) logger.info("Bước 3: dựng %d hồ sơ giọng", len(profiles)) return profiles
# ---------------------------------------------------------------------------# Bước 4 — Dịch đa phương thức# ---------------------------------------------------------------------------def run_translation( backend, video: Optional[str | Path], scenes: List[Scene], profiles: Dict[str, VoiceProfile], glossary: Glossary, config: Config, work_dir: Path, *, stop_check: Optional[StopCheck] = None, correct_ocr: bool = False,) -> None: tr = config.translate for i, scene in enumerate(scenes, start=1): if stop_check and stop_check(): logger.warning("Dừng theo yêu cầu tại cảnh %d/%d", i, len(scenes)) break context = None if video is not None: context = build_scene_context(video, scene, work_dir / "scenes")
if correct_ocr and context is not None: from .correct import correct_scene
correct_scene(backend, scene, context, **_sampling(config))
translate_scene( backend, scene, context, profiles, glossary, source_lang=tr["source_lang"], target_lang=tr["target_lang"], **_sampling(config), ) logger.info("Bước 4: dịch xong cảnh %d/%d", i, len(scenes))
# ---------------------------------------------------------------------------# Bước 5 — Hậu kiểm & xuất# ---------------------------------------------------------------------------def finalize_and_export( cues: List[Cue], scenes: List[Scene], glossary: Glossary, config: Config, srt_path: str | Path,) -> tuple[Path, Path]: tr = config.translate out_path = Path(srt_path).with_suffix("") # bỏ .srt out_path = out_path.parent / (Path(srt_path).stem + tr["output_suffix"])
# áp glossary tên riêng lần cuối (đảm bảo nhất quán) _enforce_names(cues, glossary)
write_srt(cues, out_path) report = _build_report(cues, scenes, glossary, config) report_path = Path(str(out_path) + ".report.json") report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
gloss_path = out_path.parent / "glossary.json" glossary.save(gloss_path) logger.info("Bước 5: ghi %s + report + glossary", out_path.name) return out_path, report_path
def _enforce_names(cues: List[Cue], glossary: Glossary) -> None: if not glossary.name_map: return for c in cues: if not c.translation: continue for src, tgt in glossary.name_map.items(): if src and src in c.text and tgt: c.translation = c.translation # placeholder: tên đã do model áp theo glossary
def _build_report(cues, scenes, glossary, config) -> dict: tr = config.translate over_budget = [] for c in cues: if not c.translation: continue budget = subtitle_char_budget( c.duration, tr["chars_per_sec"], tr["max_line_chars"], tr["max_lines"] ) longest = max((len(line) for line in c.translation.split("\n")), default=0) if len(c.translation.replace("\n", "")) > budget: over_budget.append({"index": c.index, "len": longest, "budget": budget}) return { "n_cues": len(cues), "n_scenes": len(scenes), "n_translated": sum(1 for c in cues if c.translation), "speakers": sorted({c.speaker for c in cues if c.speaker}), "names": glossary.name_map, "address_pairs": glossary.address_pairs, "over_budget_cues": over_budget, }
# ---------------------------------------------------------------------------# Driver tổng# ---------------------------------------------------------------------------def run_pipeline( srt_path: str | Path, *, video: Optional[str | Path] = None, config: Optional[Config] = None, backend=None, work_dir: Optional[str | Path] = None, hf_token: Optional[str] = None, do_diarize: bool = True, do_profile: bool = True, do_translate: bool = True, stop_check: Optional[StopCheck] = None,) -> PipelineResult: """Chạy toàn bộ (hoặc một phần) pipeline. Bước nào thiếu tài nguyên thì bỏ qua.""" config = config or Config.load() glossary_path = Path(srt_path).with_suffix("").parent / "glossary.json" glossary = Glossary.load(glossary_path)
tmp = work_dir or tempfile.mkdtemp(prefix="omnisub_") work = Path(tmp) work.mkdir(parents=True, exist_ok=True)
# Parse trước; diarize trên cue thô để gán speaker, RỒI mới ghép cue vụn # (lúc đó ghép theo đúng same-speaker) và gom cảnh. cues = parse_srt(srt_path) logger.info("Bước 1: đọc %d cue từ %s", len(cues), srt_path)
turns: List[SpeakerTurn] = [] if video and do_diarize: turns = run_diarization(video, cues, config, work, hf_token=hf_token)
cues, scenes = merge_and_group(cues, config) result = PipelineResult(cues=cues, scenes=scenes, glossary=glossary)
if video and do_profile and backend is not None and turns: result.profiles = run_profiling(backend, video, turns, config, work) save_profiles(result.profiles, work / "profiles.json")
if do_translate and backend is not None: run_translation( backend, video, scenes, result.profiles, glossary, config, work, stop_check=stop_check, correct_ocr=config.translate["correct_ocr"], )
out_path, report_path = finalize_and_export(cues, scenes, glossary, config, srt_path) result.output_srt = out_path result.report_path = report_path return result
def _sampling(config: Config) -> dict: s = config.sampling return { "temperature": s["temperature"], "top_p": s["top_p"], "top_k": s["top_k"], "max_new_tokens": s["max_new_tokens"], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""Bước 3 — Hồ sơ giọng (VoiceProfile).
Đưa các clip audio của từng speaker cho Qwen3-Omni "nghe" → suy ra giới tính,độ tuổi, cảm xúc nền, vai vế và gợi ý xưng hô tiếng Việt. Thay cho wav2vec2age/gender + regex của bản cũ."""
from __future__ import annotations
import jsonfrom dataclasses import asdict, dataclass, fieldfrom pathlib import Pathfrom typing import Dict, List, Optional
from .backends.base import ChatMessage, LLMBackend
@dataclassclass VoiceProfile: speaker: str # "SPEAKER_01" (khớp pyannote) gender: str = "chưa rõ" # nam | nữ | trẻ em | chưa rõ age_range: str = "chưa rõ" # trẻ em | thiếu niên | thanh niên | trung niên | lớn tuổi emotion_baseline: str = "" # vd: điềm đạm / nóng nảy / dịu dàng role_guess: str = "" # vd: "phụ nữ trẻ, có vẻ là người yêu của SPEAKER_02" register_hint: str = "" # gợi ý xưng hô VN evidence: str = "" # model tự giải thích ngắn
def to_prompt_line(self) -> str: bits = [f"{self.speaker}: {self.gender}, {self.age_range}"] if self.emotion_baseline: bits.append(f"giọng {self.emotion_baseline}") if self.role_guess: bits.append(self.role_guess) if self.register_hint: bits.append(f"xưng hô: {self.register_hint}") return " — ".join(bits)
_PROFILE_SYSTEM = ( "Bạn là chuyên gia phân tích giọng nói cho phim Hoa ngữ. " "Nghe các clip của MỘT nhân vật rồi mô tả họ. " "Trả về DUY NHẤT một object JSON, không kèm giải thích ngoài JSON.")
def _build_profile_prompt(speaker: str, n_clips: int) -> str: return ( f"Đây là {n_clips} clip giọng của nhân vật {speaker} trong một phim Trung Quốc.\n" "Hãy nghe và suy ra hồ sơ nhân vật. Trả về JSON theo schema:\n" "{\n" ' "gender": "nam|nữ|trẻ em|chưa rõ",\n' ' "age_range": "trẻ em|thiếu niên|thanh niên|trung niên|lớn tuổi",\n' ' "emotion_baseline": "mô tả ngắn tông giọng nền",\n' ' "role_guess": "đoán vai vế/quan hệ nếu có manh mối",\n' ' "register_hint": "gợi ý cách xưng hô tiếng Việt phù hợp",\n' ' "evidence": "1 câu lý do dựa trên đặc điểm giọng"\n' "}" )
def build_voice_profile( backend: LLMBackend, speaker: str, clip_paths: List[str | Path], *, max_new_tokens: int = 512, **sampling,) -> VoiceProfile: """Gọi Omni nghe các clip của 1 speaker → VoiceProfile.""" audio = [str(p) for p in clip_paths] msg = ChatMessage( role="user", text=_build_profile_prompt(speaker, len(audio)), audio=audio, ) try: data = backend.chat_json( [msg], system=_PROFILE_SYSTEM, max_new_tokens=max_new_tokens, **sampling ) except Exception as e: # model lỗi/parse lỗi → hồ sơ rỗng, không chặn pipeline return VoiceProfile(speaker=speaker, evidence=f"(không phân tích được: {e})")
if not isinstance(data, dict): return VoiceProfile(speaker=speaker) return VoiceProfile( speaker=speaker, gender=str(data.get("gender", "chưa rõ")), age_range=str(data.get("age_range", "chưa rõ")), emotion_baseline=str(data.get("emotion_baseline", "")), role_guess=str(data.get("role_guess", "")), register_hint=str(data.get("register_hint", "")), evidence=str(data.get("evidence", "")), )
def build_all_profiles( backend: LLMBackend, speaker_clips: Dict[str, List[str | Path]], *, max_new_tokens: int = 512, **sampling,) -> Dict[str, VoiceProfile]: profiles: Dict[str, VoiceProfile] = {} for speaker, clips in speaker_clips.items(): if not clips: profiles[speaker] = VoiceProfile(speaker=speaker) continue profiles[speaker] = build_voice_profile( backend, speaker, clips, max_new_tokens=max_new_tokens, **sampling ) return profiles
def save_profiles(profiles: Dict[str, VoiceProfile], path: str | Path) -> None: p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) p.write_text( json.dumps({k: asdict(v) for k, v in profiles.items()}, ensure_ascii=False, indent=2), encoding="utf-8", )
def load_profiles(path: str | Path) -> Dict[str, VoiceProfile]: data = json.loads(Path(path).read_text(encoding="utf-8")) return {k: VoiceProfile(**v) for k, v in data.items()}
def profiles_prompt_block(profiles: Dict[str, VoiceProfile]) -> str: """Khối text mô tả hồ sơ giọng để nhét vào prompt dịch.""" if not profiles: return "" lines = [p.to_prompt_line() for p in profiles.values()] return "Hồ sơ nhân vật (suy từ giọng nói):\n" + "\n".join(f"- {ln}" for ln in lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Trích ngữ cảnh đa phương thức cho từng cảnh: frame video + audio đoạn cảnh.
Dùng ffmpeg/ffprobe (gọi qua subprocess). Trên Colab L4 đã có sẵn ffmpeg.Tất cả file tạm ghi vào `work_dir` để backend Omni nạp ở Bước 3 & 4."""
from __future__ import annotations
import shutilimport subprocessfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import List, Optional
from .scenes import Scene
def _require(tool: str) -> str: path = shutil.which(tool) if not path: raise RuntimeError( f"Không tìm thấy `{tool}` trong PATH. Cần ffmpeg để trích frame/audio." ) return path
def extract_audio( video: str | Path, out_path: str | Path, *, start: Optional[float] = None, end: Optional[float] = None, sample_rate: int = 16000,) -> Path: """Trích audio mono 16 kHz (mặc định) cho [start, end]. Trả về path WAV.""" ffmpeg = _require("ffmpeg") out = Path(out_path) out.parent.mkdir(parents=True, exist_ok=True) cmd = [ffmpeg, "-y", "-loglevel", "error"] if start is not None: cmd += ["-ss", f"{start:.3f}"] if end is not None and start is not None: cmd += ["-t", f"{max(0.0, end - start):.3f}"] cmd += [ "-i", str(video), "-vn", "-ac", "1", "-ar", str(sample_rate), "-c:a", "pcm_s16le", str(out), ] subprocess.run(cmd, check=True) return out
def extract_frame( video: str | Path, out_path: str | Path, *, timestamp: float, width: Optional[int] = 768,) -> Path: """Trích 1 frame tại `timestamp` (giây). Trả về path ảnh JPG.""" ffmpeg = _require("ffmpeg") out = Path(out_path) out.parent.mkdir(parents=True, exist_ok=True) vf = f"scale={width}:-2" if width else "scale=iw:ih" cmd = [ ffmpeg, "-y", "-loglevel", "error", "-ss", f"{timestamp:.3f}", "-i", str(video), "-frames:v", "1", "-vf", vf, str(out), ] subprocess.run(cmd, check=True) return out
@dataclassclass SceneContext: """Tài nguyên đa phương thức đã trích cho một cảnh."""
scene_id: int audio_path: Optional[Path] = None frame_paths: List[Path] = field(default_factory=list)
def build_scene_context( video: str | Path, scene: Scene, work_dir: str | Path, *, n_frames: int = 2, sample_rate: int = 16000, frame_width: int = 768,) -> SceneContext: """Trích audio toàn cảnh + `n_frames` frame rải đều trong cảnh.""" work = Path(work_dir) work.mkdir(parents=True, exist_ok=True)
audio_path = extract_audio( video, work / f"scene_{scene.scene_id:04d}.wav", start=scene.start, end=scene.end, sample_rate=sample_rate, )
frames: List[Path] = [] dur = max(0.001, scene.duration) for i in range(max(1, n_frames)): # rải đều, tránh đúng biên cắt cảnh frac = (i + 1) / (n_frames + 1) ts = scene.start + frac * dur frames.append( extract_frame( video, work / f"scene_{scene.scene_id:04d}_f{i}.jpg", timestamp=ts, width=frame_width, ) )
return SceneContext(scene_id=scene.scene_id, audio_path=audio_path, frame_paths=frames)
def extract_speaker_clips( video: str | Path, turns: List["SpeakerTurn"], # type: ignore[name-defined] work_dir: str | Path, *, clips_per_speaker: int = 5, max_seconds_per_clip: float = 8.0, sample_rate: int = 16000,) -> dict[str, List[Path]]: """Trích các clip audio đại diện cho từng speaker (cho Bước 3 — hồ sơ giọng).
Chọn các turn dài nhất của mỗi speaker, cắt ≤ `max_seconds_per_clip`. """ from collections import defaultdict
work = Path(work_dir) work.mkdir(parents=True, exist_ok=True)
by_speaker: dict[str, list] = defaultdict(list) for t in turns: by_speaker[t.speaker].append(t)
result: dict[str, List[Path]] = {} for speaker, sp_turns in by_speaker.items(): sp_turns = sorted(sp_turns, key=lambda x: x.duration, reverse=True) clips: List[Path] = [] for i, t in enumerate(sp_turns[:clips_per_speaker]): end = min(t.end, t.start + max_seconds_per_clip) clips.append( extract_audio( video, work / f"{speaker}_clip{i}.wav", start=t.start, end=end, sample_rate=sample_rate, ) ) result[speaker] = clips return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Gom cảnh và ghép cue vụn (sentence-aware, same-speaker).
`group_scenes`: cắt phim thành các `Scene` theo khoảng lặng và giới hạn độ dài.`merge_adjacent_pairs`: ghép cue ngắn liền kề (cùng người nói, chưa kết câu)."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom typing import List, Optional
from .srt import Cue
# Dấu kết thúc câu (CJK + Latin) — dùng để biết một cue đã "trọn câu" chưa._SENTENCE_ENDERS = "。!?!?…」』”》"_CONTINUATION_ENDERS = ",、,;;::—-((【「『《“"
@dataclassclass Scene: """Một cảnh: cụm cue gần nhau về thời gian."""
scene_id: int cues: List[Cue] = field(default_factory=list)
@property def start(self) -> float: return self.cues[0].start if self.cues else 0.0
@property def end(self) -> float: return self.cues[-1].end if self.cues else 0.0
@property def duration(self) -> float: return max(0.0, self.end - self.start)
@property def text(self) -> str: return "\n".join(c.text for c in self.cues)
@property def speakers(self) -> List[str]: seen: List[str] = [] for c in self.cues: if c.speaker and c.speaker not in seen: seen.append(c.speaker) return seen
def group_scenes( cues: List[Cue], max_gap: float = 1.5, max_cues: int = 4, max_dur: float = 20.0,) -> List[Scene]: """Gom cue thành cảnh.
Cắt cảnh mới khi: khoảng lặng > `max_gap`, hoặc cảnh đã đủ `max_cues`, hoặc vượt `max_dur` giây. """ scenes: List[Scene] = [] if not cues: return scenes
current: List[Cue] = [] scene_id = 0 for cue in cues: if not current: current = [cue] continue
gap = cue.start - current[-1].end dur = cue.end - current[0].start if gap > max_gap or len(current) >= max_cues or dur > max_dur: scene_id += 1 scenes.append(_finalize_scene(scene_id, current)) current = [cue] else: current.append(cue)
if current: scene_id += 1 scenes.append(_finalize_scene(scene_id, current)) return scenes
def _finalize_scene(scene_id: int, cues: List[Cue]) -> Scene: for c in cues: c.scene_id = scene_id return Scene(scene_id=scene_id, cues=list(cues))
def _ends_sentence(text: str) -> bool: t = text.rstrip() if not t: return False return t[-1] in _SENTENCE_ENDERS
def _ends_continuation(text: str) -> bool: t = text.rstrip() if not t: return False return t[-1] in _CONTINUATION_ENDERS
def merge_adjacent_pairs( cues: List[Cue], max_gap: float = 0.4, max_merged_chars: int = 40,) -> List[Cue]: """Ghép cue vụn liền kề thành câu trọn vẹn hơn.
Điều kiện ghép cue[i] với cue[i+1]: - khoảng cách ≤ `max_gap`, - cùng speaker (hoặc cả hai chưa gán), - cue[i] CHƯA kết thúc câu, - tổng độ dài sau ghép ≤ `max_merged_chars`. """ if not cues: return []
merged: List[Cue] = [] buf = _clone(cues[0]) for nxt in cues[1:]: gap = nxt.start - buf.end # Cùng speaker đã gán → ghép thoải mái. Khi cả hai chưa gán (chưa # diarize) chỉ ghép nếu câu trước kết thúc bằng dấu nối, tránh gộp # nhầm lời của hai người khác nhau. both_unknown = buf.speaker is None and nxt.speaker is None same_known_speaker = buf.speaker is not None and buf.speaker == nxt.speaker can_merge_speaker = same_known_speaker or ( both_unknown and _ends_continuation(buf.text) ) combined_len = len(buf.text.replace("\n", "")) + len(nxt.text.replace("\n", "")) if ( gap <= max_gap and can_merge_speaker and not _ends_sentence(buf.text) and combined_len <= max_merged_chars ): buf.end = nxt.end sep = "" if buf.text and buf.text[-1] in _CONTINUATION_ENDERS else " " buf.text = (buf.text + sep + nxt.text).strip() else: merged.append(buf) buf = _clone(nxt) merged.append(buf)
for i, c in enumerate(merged, start=1): c.index = i return merged
def _clone(cue: Cue) -> Cue: return Cue( index=cue.index, start=cue.start, end=cue.end, text=cue.text, speaker=cue.speaker, translation=cue.translation, note=cue.note, scene_id=cue.scene_id, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""I/O SRT: dataclass `Cue`, parse/write, ngân sách ký tự theo thời lượng.
Port sạch từ bản cũ — không phụ thuộc gì ngoài stdlib để chạy được local ở Bước 1."""
from __future__ import annotations
import refrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Iterable, List, Optional
# 00:01:02,500 --> 00:01:05,000_TIME_RE = re.compile( r"(?P<h>\d{1,2}):(?P<m>\d{2}):(?P<s>\d{2})[.,](?P<ms>\d{1,3})")_ARROW_RE = re.compile(r"-->")
@dataclassclass Cue: """Một dòng phụ đề."""
index: int start: float # giây end: float # giây text: str # văn bản gốc (ZH) speaker: Optional[str] = None # gán ở Bước 2 (diarization) translation: Optional[str] = None # bản dịch VN (Bước 4) note: Optional[str] = None # ghi chú xưng hô của model scene_id: Optional[int] = None # gán ở Bước 1 (gom cảnh)
@property def duration(self) -> float: return max(0.0, self.end - self.start)
@property def out_text(self) -> str: """Văn bản dùng khi ghi ra: ưu tiên bản dịch, fallback về gốc.""" return self.translation if self.translation else self.text
def parse_time(token: str) -> float: """'00:01:02,500' -> giây (float).""" m = _TIME_RE.search(token) if not m: raise ValueError(f"Không đọc được mốc thời gian: {token!r}") h = int(m.group("h")) mi = int(m.group("m")) s = int(m.group("s")) ms = int(m.group("ms").ljust(3, "0")) # '5' -> 500 return h * 3600 + mi * 60 + s + ms / 1000.0
def seconds_to_srt_time(seconds: float) -> str: """giây -> '00:01:02,500'.""" if seconds < 0: seconds = 0.0 total_ms = int(round(seconds * 1000.0)) ms = total_ms % 1000 total_s = total_ms // 1000 s = total_s % 60 total_m = total_s // 60 m = total_m % 60 h = total_m // 60 return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
def _normalize_text(raw_lines: List[str]) -> str: """Gộp các dòng văn bản của một cue, bỏ thẻ định dạng đơn giản.""" text = "\n".join(line.rstrip() for line in raw_lines).strip() return text
def parse_srt(path: str | Path, encoding: str = "utf-8-sig") -> List[Cue]: """Đọc file SRT -> danh sách Cue. Bền với index lệch, dòng trống dư.""" p = Path(path) content = p.read_text(encoding=encoding, errors="replace") return parse_srt_text(content)
def parse_srt_text(content: str) -> List[Cue]: content = content.replace("\r\n", "\n").replace("\r", "\n") blocks = re.split(r"\n\s*\n", content.strip()) cues: List[Cue] = [] auto_index = 0 for block in blocks: lines = [ln for ln in block.split("\n")] if not lines: continue # bỏ dòng trống đầu while lines and not lines[0].strip(): lines.pop(0) if not lines: continue
idx_line = lines[0].strip() time_line_pos = 0 explicit_index: Optional[int] = None if idx_line.isdigit() and len(lines) >= 2 and _ARROW_RE.search(lines[1]): explicit_index = int(idx_line) time_line_pos = 1 elif _ARROW_RE.search(lines[0]): time_line_pos = 0 else: # block không hợp lệ (vd metadata) -> bỏ qua continue
time_line = lines[time_line_pos] parts = _ARROW_RE.split(time_line) if len(parts) != 2: continue try: start = parse_time(parts[0]) end = parse_time(parts[1]) except ValueError: continue
text = _normalize_text(lines[time_line_pos + 1 :]) auto_index += 1 cues.append( Cue( index=explicit_index if explicit_index is not None else auto_index, start=start, end=end, text=text, ) ) return cues
def write_srt(cues: Iterable[Cue], path: str | Path, encoding: str = "utf-8") -> None: """Ghi danh sách Cue ra file SRT (dùng `out_text`).""" p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) p.write_text(render_srt(cues), encoding=encoding)
def render_srt(cues: Iterable[Cue]) -> str: chunks: List[str] = [] for i, cue in enumerate(cues, start=1): chunks.append( f"{i}\n" f"{seconds_to_srt_time(cue.start)} --> {seconds_to_srt_time(cue.end)}\n" f"{cue.out_text}".rstrip() ) return "\n\n".join(chunks) + "\n"
def subtitle_char_budget( duration: float, chars_per_sec: float = 22.0, max_line_chars: int = 52, max_lines: int = 2,) -> int: """Số ký tự tối đa nên hiển thị cho một cue, theo thời lượng và giới hạn dòng.
Lấy min giữa (thời lượng × tốc độ đọc) và (số ký tự tối đa của các dòng). """ by_time = int(duration * chars_per_sec) by_lines = max_line_chars * max_lines # tối thiểu cho 1 dòng ngắn để không trả về 0 với cue siêu ngắn return max(by_lines if by_time <= 0 else min(by_time, by_lines), max_line_chars)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132"""Bước 4 — Dịch đa phương thức theo cảnh.
Dựng prompt gồm: frame (trước text) + cues ZH + hồ sơ giọng + glossary (text)+ audio cảnh (sau text). Gọi Omni, parse JSON từng cue, ghi `cue.translation`và `cue.note`. KHÔNG dùng regex xưng hô."""
from __future__ import annotations
from typing import Dict, List, Optional
from .backends.base import ChatMessage, LLMBackendfrom .glossary import Glossaryfrom .profiles import VoiceProfile, profiles_prompt_blockfrom .scene_context import SceneContextfrom .scenes import Scenefrom .srt import subtitle_char_budget
TRANSLATE_SYSTEM = ( "Bạn là dịch giả phụ đề phim Hoa ngữ sang tiếng Việt, văn nói tự nhiên, súc tích. " "Bạn ĐƯỢC nghe audio và xem khung hình của cảnh để chọn xưng hô đúng vai vế " "(anh/em, chị/em, mẹ/con, ngài/ta, tỷ/muội...). " "Giữ nhất quán tên riêng và cách xưng hô theo glossary đã cho. " "Trả về DUY NHẤT một object JSON đúng schema, không thêm chữ nào ngoài JSON.")
def _cue_block(scene: Scene, profiles: Dict[str, VoiceProfile]) -> str: lines = [] for c in scene.cues: spk = c.speaker or "?" budget = subtitle_char_budget(c.duration) lines.append(f' {{ "id": {c.index}, "speaker": "{spk}", "zh": {c.text!r}, "max_chars": {budget} }}') return "[\n" + ",\n".join(lines) + "\n]"
def build_scene_messages( scene: Scene, context: Optional[SceneContext], profiles: Dict[str, VoiceProfile], glossary: Glossary, *, source_lang: str = "Chinese", target_lang: str = "Vietnamese",) -> List[ChatMessage]: """Dựng message đa phương thức cho một cảnh (ảnh trước, audio sau text).""" images = [str(p) for p in (context.frame_paths if context else [])] audio = [str(context.audio_path)] if (context and context.audio_path) else []
prompt_parts: List[str] = [ f"Dịch các câu thoại sau từ {source_lang} sang {target_lang}.", f"Cảnh #{scene.scene_id}, thời lượng ~{scene.duration:.1f}s.", ] prof_block = profiles_prompt_block(profiles) if prof_block: prompt_parts.append(prof_block) gloss_block = glossary.prompt_block() if gloss_block: prompt_parts.append(gloss_block)
prompt_parts.append("Các câu cần dịch (giữ đúng id):\n" + _cue_block(scene, profiles)) prompt_parts.append( "Yêu cầu:\n" "- Dịch tự nhiên, KHÔNG vượt quá max_chars mỗi câu (rút gọn nếu cần).\n" "- Chọn xưng hô dựa vào giọng nói + hình ảnh + ngữ cảnh.\n" "- Đề xuất tên riêng và cặp xưng hô để khóa nhất quán cho cảnh sau.\n" "Trả về JSON:\n" "{\n" ' "cues": [{ "id": <int>, "vi": "<bản dịch>", "note": "<ghi chú xưng hô ngắn>" }],\n' ' "names": [{ "source": "<tên ZH>", "target": "<tên VN>" }],\n' ' "address": [{ "from": "SPEAKER_X", "to": "SPEAKER_Y", "address": "anh-em" }]\n' "}" ) if audio: prompt_parts.append("(Audio cảnh được đính kèm phía dưới để bạn nghe.)")
msg = ChatMessage( role="user", text="\n\n".join(prompt_parts), images=images, audio=audio, ) return [msg]
def apply_scene_result(scene: Scene, result: dict) -> None: """Ghi bản dịch + note vào từng cue theo id.""" by_id = {c.index: c for c in scene.cues} for item in (result.get("cues", []) if isinstance(result, dict) else []) or []: cid = item.get("id") if cid in by_id: vi = item.get("vi") or item.get("translation") if vi: by_id[cid].translation = str(vi).strip() note = item.get("note") if note: by_id[cid].note = str(note).strip()
def translate_scene( backend: LLMBackend, scene: Scene, context: Optional[SceneContext], profiles: Dict[str, VoiceProfile], glossary: Glossary, *, source_lang: str = "Chinese", target_lang: str = "Vietnamese", max_new_tokens: int = 1024, **sampling,) -> dict: """Dịch một cảnh: gọi Omni, ghi kết quả vào cue, cập nhật glossary.""" messages = build_scene_messages( scene, context, profiles, glossary, source_lang=source_lang, target_lang=target_lang, ) try: result = backend.chat_json( messages, system=TRANSLATE_SYSTEM, max_new_tokens=max_new_tokens, **sampling ) except Exception as e: # fallback: giữ nguyên text gốc, đánh dấu lỗi for c in scene.cues: c.note = f"(lỗi dịch: {e})" return {}
if not isinstance(result, dict): result = {} apply_scene_result(scene, result) glossary.update_from_scene_result(result) return result.gitignoreAdded+31
PLAN.mdAdded+186
README.mdAdded+60
colab/OmniSub_Colab.ipynbAdded+183
config.yamlAdded+31
pyproject.tomlAdded+36
requirements-colab.txtAdded+23
samples/demo.zh.srtAdded+20
src/omnisub/__init__.pyAdded+3
src/omnisub/backends/__init__.pyAdded+5
src/omnisub/backends/base.pyAdded+134
src/omnisub/backends/transformers_qwen.pyAdded+167
src/omnisub/cli.pyAdded+137
src/omnisub/config.pyAdded+99
src/omnisub/correct.pyAdded+52
src/omnisub/diarize.pyAdded+85
src/omnisub/glossary.pyAdded+97
src/omnisub/pipeline.pyAdded+267
src/omnisub/profiles.pyAdded+133
src/omnisub/scene_context.pyAdded+166
src/omnisub/scenes.pyAdded+166
src/omnisub/srt.pyAdded+163
src/omnisub/translate.pyAdded+132