Datasets:
Commit ·
c292bfa
0
Parent(s):
Duplicate from STBack23/omnivoice-vi
Browse filesCo-authored-by: STBack23 <STBack23@users.noreply.huggingface.co>
- .gitattributes +60 -0
- README.md +62 -0
- colab/Omivoice_VI_Colab.ipynb +401 -0
- tools/speak.py +1209 -0
- voices/ban_mai/profile.json +11 -0
- voices/ban_mai/ref.mp3 +3 -0
- voices/ban_mai/ref_text.txt +1 -0
- voices/ban_mai/ref_text_asr.txt +1 -0
- voices/ban_mai/voice.pt +3 -0
- voices/lan_trinh/profile.json +11 -0
- voices/lan_trinh/ref.wav +3 -0
- voices/lan_trinh/ref_text.txt +1 -0
- voices/lan_trinh/voice.pt +3 -0
- voices/ngan_ha/profile.json +11 -0
- voices/ngan_ha/ref.wav +3 -0
- voices/ngan_ha/ref_text.txt +1 -0
- voices/ngan_ha/voice.pt +3 -0
- voices/ngoc_huyen/profile.json +9 -0
- voices/ngoc_huyen/ref.mp3 +3 -0
- voices/ngoc_huyen/ref_text.txt +1 -0
- voices/ngoc_huyen/voice.pt +3 -0
- voices/thao_trinh/profile.json +11 -0
- voices/thao_trinh/ref.wav +3 -0
- voices/thao_trinh/ref_text.txt +1 -0
- voices/thao_trinh/voice.pt +3 -0
- voices/tuong_vy/profile.json +11 -0
- voices/tuong_vy/ref.wav +3 -0
- voices/tuong_vy/ref_text.txt +1 -0
- voices/tuong_vy/voice.pt +3 -0
.gitattributes
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
# Audio files - uncompressed
|
| 40 |
+
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
# Audio files - compressed
|
| 44 |
+
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
# Image files - uncompressed
|
| 50 |
+
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
# Image files - compressed
|
| 55 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
# Video files - compressed
|
| 59 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
*.webm filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- vi
|
| 5 |
+
tags:
|
| 6 |
+
- text-to-speech
|
| 7 |
+
- tts
|
| 8 |
+
- voice-cloning
|
| 9 |
+
- vietnamese
|
| 10 |
+
- srt
|
| 11 |
+
- dubbing
|
| 12 |
+
- omnivoice
|
| 13 |
+
pretty_name: OmniVoice Vietnamese Voices
|
| 14 |
+
size_categories:
|
| 15 |
+
- n<1K
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
# OmniVoice VI — Giọng Việt + SRT lồng tiếng
|
| 19 |
+
|
| 20 |
+
Dataset chứa **6 giọng tiếng Việt** và công cụ `speak.py` để chạy trên **Google Colab** với [OmniVoice](https://huggingface.co/k2-fsa/OmniVoice).
|
| 21 |
+
|
| 22 |
+
## Giọng có sẵn
|
| 23 |
+
|
| 24 |
+
| Slug | Tên |
|
| 25 |
+
|------|-----|
|
| 26 |
+
| `ban_mai` | Ban Mai |
|
| 27 |
+
| `lan_trinh` | Lan Trinh |
|
| 28 |
+
| `ngan_ha` | Ngan Ha |
|
| 29 |
+
| `ngoc_huyen` | Ngoc Huyen |
|
| 30 |
+
| `thao_trinh` | Thao Trinh |
|
| 31 |
+
| `tuong_vy` | Tuong Vy |
|
| 32 |
+
|
| 33 |
+
Mỗi giọng gồm `profile.json`, `voice.pt` (prompt cache), audio mẫu và `ref_text.txt`.
|
| 34 |
+
|
| 35 |
+
## Chạy trên Colab
|
| 36 |
+
|
| 37 |
+
1. Mở notebook `colab/Omivoice_VI_Colab.ipynb`
|
| 38 |
+
2. Đặt `HF_REPO = "<repo-này>"`
|
| 39 |
+
3. Runtime → GPU → chạy từng cell
|
| 40 |
+
|
| 41 |
+
## Cấu trúc
|
| 42 |
+
|
| 43 |
+
```
|
| 44 |
+
├── voices/<slug>/ # profile + voice.pt + ref audio
|
| 45 |
+
├── tools/speak.py # TTS + SRT pipeline
|
| 46 |
+
└── colab/ # Notebook Colab
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
## SRT merge modes
|
| 50 |
+
|
| 51 |
+
- **`native`** (mặc định): model nói nhanh native, tràn vào khoảng trống sau cue, không cắt ngắt
|
| 52 |
+
- **`cascade`**: giữ tốc độ tự nhiên, cue dài đẩy cue sau
|
| 53 |
+
- **`fit`**: kéo nén tín hiệu vừa khung SRT
|
| 54 |
+
- **`strict`**: ghép theo timestamp (có thể cắt audio)
|
| 55 |
+
|
| 56 |
+
## Model gốc
|
| 57 |
+
|
| 58 |
+
- [k2-fsa/OmniVoice](https://huggingface.co/k2-fsa/OmniVoice) — tự tải khi chạy lần đầu (~GB VRAM T4)
|
| 59 |
+
|
| 60 |
+
## License
|
| 61 |
+
|
| 62 |
+
Apache-2.0 (theo OmniVoice upstream).
|
colab/Omivoice_VI_Colab.ipynb
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# OmniVoice — Lồng tiếng tiếng Việt trên Colab\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"Notebook chạy [OmniVoice](https://huggingface.co/k2-fsa/OmniVoice) với pipeline **SRT lồng tiếng** (`native`).\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"**Luồng Drive:**\n",
|
| 12 |
+
"1. Cấu hình giọng + tên file SRT ở **mục 0**\n",
|
| 13 |
+
"2. Đặt file `.srt` vào **`MyDrive/Omivoice/`** (tên = `SRT_FILE` + `.srt`, vd. `input` → `input.srt`)\n",
|
| 14 |
+
"3. Chạy notebook → kết quả ghi lại **`MyDrive/Omivoice/`**\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"**Yêu cầu:** Runtime **GPU L4** (Runtime → Change runtime type → L4)."
|
| 17 |
+
],
|
| 18 |
+
"id": "4027962a"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"cell_type": "markdown",
|
| 22 |
+
"metadata": {},
|
| 23 |
+
"source": [
|
| 24 |
+
"## 0. Cấu hình"
|
| 25 |
+
],
|
| 26 |
+
"id": "02fceea2"
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"source": [
|
| 32 |
+
"# Hugging Face (giọng + speak.py)\n",
|
| 33 |
+
"HF_REPO = \"STBack23/omnivoice-vi\"\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"# Google Drive — MyDrive/Omivoice/\n",
|
| 36 |
+
"DRIVE_FOLDER = \"Omivoice\"\n",
|
| 37 |
+
"SRT_FILE = \"input\" # tên file (không cần .srt) -> input.srt\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"# Giọng: ban_mai | lan_trinh | ngan_ha | ngoc_huyen | thao_trinh | tuong_vy\n",
|
| 40 |
+
"DEFAULT_VOICE = \"tuong_vy\"\n",
|
| 41 |
+
"MERGE_MODE = \"native\" # native | cascade | fit | strict\n",
|
| 42 |
+
"NUM_STEP = 32"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": [],
|
| 46 |
+
"id": "1d36167e"
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "markdown",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"## 1. Kiểm tra GPU & cài đặt"
|
| 53 |
+
],
|
| 54 |
+
"id": "342cf199"
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"cell_type": "code",
|
| 58 |
+
"metadata": {},
|
| 59 |
+
"source": [
|
| 60 |
+
"import torch\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"assert torch.cuda.is_available(), (\n",
|
| 63 |
+
" \"Bật GPU L4: Runtime → Change runtime type → Hardware accelerator → L4\"\n",
|
| 64 |
+
")\n",
|
| 65 |
+
"gpu = torch.cuda.get_device_name(0)\n",
|
| 66 |
+
"print(f\"GPU: {gpu}\")\n",
|
| 67 |
+
"if \"L4\" not in gpu.upper():\n",
|
| 68 |
+
" print(\n",
|
| 69 |
+
" f\"⚠ Đang dùng {gpu}, không phải L4 — đổi runtime sang L4 để nhanh hơn.\"\n",
|
| 70 |
+
" )"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": [],
|
| 74 |
+
"id": "9372766b"
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Tắt XET — thường gây treo download ~89% trên Colab.\n",
|
| 81 |
+
"# PHẢI chạy cell này TRƯỚC mọi `from huggingface_hub import ...`\n",
|
| 82 |
+
"import os\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"os.environ[\"HF_HUB_DISABLE_XET\"] = \"1\"\n",
|
| 85 |
+
"os.environ[\"HF_HUB_DOWNLOAD_TIMEOUT\"] = \"300\"\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"print(\"HF: HF_HUB_DISABLE_XET=1, timeout 300s\")"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": [],
|
| 91 |
+
"id": "109256f6"
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"!pip install -q omnivoice audiotsm huggingface_hub soundfile librosa"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": [],
|
| 101 |
+
"id": "f320297d"
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "markdown",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"### Repo private — đăng nhập Hugging Face (một lần)\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"1. Tạo token **Read** tại [hf.co/settings/tokens](https://huggingface.co/settings/tokens)\n",
|
| 110 |
+
"2. Colab → **🔑 Khóa bí mật** (Manage secrets) → thêm tên `HF_TOKEN`, dán token → **Lưu**\n",
|
| 111 |
+
"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"
|
| 112 |
+
],
|
| 113 |
+
"id": "dd112ce5"
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"from huggingface_hub import login\n",
|
| 120 |
+
"from google.colab import userdata\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"try:\n",
|
| 123 |
+
" token = userdata.get(\"HF_TOKEN\")\n",
|
| 124 |
+
"except userdata.SecretNotFoundError as e:\n",
|
| 125 |
+
" raise RuntimeError(\n",
|
| 126 |
+
" \"Chưa có khóa bí mật HF_TOKEN.\\n\"\n",
|
| 127 |
+
" \"Colab → 🔑 Khóa bí mật → Thêm secret tên HF_TOKEN \"\n",
|
| 128 |
+
" \"(token Read từ hf.co/settings/tokens).\\n\"\n",
|
| 129 |
+
" \"Lưu một lần, lần sau không cần nhập lại.\"\n",
|
| 130 |
+
" ) from e\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"if not token or not str(token).strip():\n",
|
| 133 |
+
" raise RuntimeError(\"HF_TOKEN trong Khóa bí mật đang trống — hãy cập nhật lại.\")\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"login(token.strip())\n",
|
| 136 |
+
"print(\"Đã login Hugging Face (HF_TOKEN từ Khóa bí mật)\")"
|
| 137 |
+
],
|
| 138 |
+
"execution_count": null,
|
| 139 |
+
"outputs": [],
|
| 140 |
+
"id": "7093f8b8"
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "markdown",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"## 2. Tải giọng & công cụ t�� Hugging Face"
|
| 147 |
+
],
|
| 148 |
+
"id": "cf360488"
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"from pathlib import Path\n",
|
| 155 |
+
"from huggingface_hub import snapshot_download\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"ROOT = Path(snapshot_download(HF_REPO, repo_type=\"dataset\", local_dir=\"/content/omnivoice-vi\"))\n",
|
| 158 |
+
"print(f\"Đã tải: {ROOT}\")\n",
|
| 159 |
+
"print(\"Giọng:\", [p.parent.name for p in sorted((ROOT / \"voices\").glob(\"*/profile.json\"))])"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": [],
|
| 163 |
+
"id": "db3a8b3d"
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"import importlib.util\n",
|
| 170 |
+
"import sys\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"speak_path = ROOT / \"tools\" / \"speak.py\"\n",
|
| 173 |
+
"spec = importlib.util.spec_from_file_location(\"speak\", speak_path)\n",
|
| 174 |
+
"speak = importlib.util.module_from_spec(spec)\n",
|
| 175 |
+
"sys.modules[\"speak\"] = speak\n",
|
| 176 |
+
"spec.loader.exec_module(speak)\n",
|
| 177 |
+
"print(\"Đã load speak.py\")"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": [],
|
| 181 |
+
"id": "15179395"
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "markdown",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"## 3. Tải & nạp model (~3–8 phút lần đầu)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"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)."
|
| 190 |
+
],
|
| 191 |
+
"id": "1098d631"
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"from huggingface_hub import hf_hub_download\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"OMNI_MODEL = \"k2-fsa/OmniVoice\"\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"# Tải từng file lớn (tránh treo snapshot_download trên Colab)\n",
|
| 202 |
+
"for relpath, label in [\n",
|
| 203 |
+
" (\"model.safetensors\", \"LLM ~2.4 GB\"),\n",
|
| 204 |
+
" (\"audio_tokenizer/model.safetensors\", \"Audio tokenizer ~770 MB\"),\n",
|
| 205 |
+
"]:\n",
|
| 206 |
+
" print(f\"\\n>>> {label}\")\n",
|
| 207 |
+
" path = hf_hub_download(OMNI_MODEL, relpath)\n",
|
| 208 |
+
" print(f\" OK: {path}\")\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"for relpath in (\n",
|
| 211 |
+
" \"config.json\",\n",
|
| 212 |
+
" \"tokenizer.json\",\n",
|
| 213 |
+
" \"tokenizer_config.json\",\n",
|
| 214 |
+
" \"chat_template.jinja\",\n",
|
| 215 |
+
" \"audio_tokenizer/config.json\",\n",
|
| 216 |
+
" \"audio_tokenizer/preprocessor_config.json\",\n",
|
| 217 |
+
"):\n",
|
| 218 |
+
" hf_hub_download(OMNI_MODEL, relpath)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"print(\"\\n✓ Model k2-fsa/OmniVoice đã cache xong.\")"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": [],
|
| 224 |
+
"id": "f69ce212"
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"cell_type": "code",
|
| 228 |
+
"metadata": {},
|
| 229 |
+
"source": [
|
| 230 |
+
"PROFILE = speak.load_profile(ROOT / \"voices\" / DEFAULT_VOICE / \"profile.json\")\n",
|
| 231 |
+
"MODEL = speak.load_model(PROFILE)\n",
|
| 232 |
+
"PROMPT = speak.ensure_voice_prompt(MODEL, PROFILE)\n",
|
| 233 |
+
"print(f\"Giọng: {PROFILE['name']} ({DEFAULT_VOICE}) | SR: {MODEL.sampling_rate}\")"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": [],
|
| 237 |
+
"id": "93c1dc54"
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"cell_type": "markdown",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"source": [
|
| 243 |
+
"## 4. Lồng tiếng SRT từ Google Drive\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"Đặt file SRT vào **`MyDrive/Omivoice/`**. Giọng = **`DEFAULT_VOICE`** ở mục 0."
|
| 246 |
+
],
|
| 247 |
+
"id": "1ea557c5"
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "code",
|
| 251 |
+
"metadata": {},
|
| 252 |
+
"source": [
|
| 253 |
+
"from google.colab import drive\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"drive.mount(\"/content/drive\")\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"DRIVE_OMIVOICE = Path(\"/content/drive/MyDrive\") / DRIVE_FOLDER\n",
|
| 258 |
+
"DRIVE_OMIVOICE.mkdir(parents=True, exist_ok=True)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"srt_name = SRT_FILE if SRT_FILE.lower().endswith(\".srt\") else f\"{SRT_FILE}.srt\"\n",
|
| 261 |
+
"SRT_PATH = DRIVE_OMIVOICE / srt_name\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"if not SRT_PATH.exists():\n",
|
| 264 |
+
" existing = sorted(DRIVE_OMIVOICE.glob(\"*.srt\"))\n",
|
| 265 |
+
" hint = \"\\n \".join(str(p.name) for p in existing) if existing else \"(chưa có file .srt)\"\n",
|
| 266 |
+
" raise FileNotFoundError(\n",
|
| 267 |
+
" f\"Không thấy {SRT_PATH}\\n\"\n",
|
| 268 |
+
" f\"Đặt file vào MyDrive/{DRIVE_FOLDER}/ hoặc sửa SRT_FILE.\\n\"\n",
|
| 269 |
+
" f\"Các file .srt hiện có:\\n {hint}\"\n",
|
| 270 |
+
" )\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"MERGE_OUT = DRIVE_OMIVOICE / f\"{SRT_PATH.stem}_merged.wav\"\n",
|
| 273 |
+
"OUTPUT_DIR = DRIVE_OMIVOICE / \"output\" / DEFAULT_VOICE / SRT_PATH.stem\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"print(f\"Drive: {DRIVE_OMIVOICE}\")\n",
|
| 276 |
+
"print(f\"Giọng: {DEFAULT_VOICE}\")\n",
|
| 277 |
+
"print(f\"Input: {SRT_PATH}\")\n",
|
| 278 |
+
"print(f\"Output: {MERGE_OUT}\")\n",
|
| 279 |
+
"print(f\"Cues: {OUTPUT_DIR}\")"
|
| 280 |
+
],
|
| 281 |
+
"execution_count": null,
|
| 282 |
+
"outputs": [],
|
| 283 |
+
"id": "ccb48064"
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"cell_type": "code",
|
| 287 |
+
"metadata": {},
|
| 288 |
+
"source": [
|
| 289 |
+
"from IPython.display import Audio, display\n",
|
| 290 |
+
"from tqdm.auto import tqdm\n",
|
| 291 |
+
"import sys\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"profile_path = ROOT / \"voices\" / DEFAULT_VOICE / \"profile.json\"\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"pbar = tqdm(total=100, unit=\"%\", desc=\"Chuẩn bị\")\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"def on_log(line: str) -> None:\n",
|
| 299 |
+
" tqdm.write(line)\n",
|
| 300 |
+
" sys.stdout.flush()\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"def on_progress(pct: float, desc: str = \"\") -> None:\n",
|
| 303 |
+
" pbar.n = min(100, max(0, int(round(pct * 100))))\n",
|
| 304 |
+
" if desc:\n",
|
| 305 |
+
" pbar.set_description(desc)\n",
|
| 306 |
+
" pbar.refresh()\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"print(f\"=== SRT: {SRT_PATH.name} | giọng {DEFAULT_VOICE} | mode {MERGE_MODE} ===\", flush=True)\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"result = speak.run_srt_pipeline(\n",
|
| 311 |
+
" profile_path,\n",
|
| 312 |
+
" SRT_PATH,\n",
|
| 313 |
+
" output_dir=OUTPUT_DIR,\n",
|
| 314 |
+
" merge=True,\n",
|
| 315 |
+
" merge_output=MERGE_OUT,\n",
|
| 316 |
+
" merge_mode=MERGE_MODE,\n",
|
| 317 |
+
" num_step=NUM_STEP,\n",
|
| 318 |
+
" model=MODEL,\n",
|
| 319 |
+
" prompt=PROMPT,\n",
|
| 320 |
+
" on_log=on_log,\n",
|
| 321 |
+
" progress=on_progress,\n",
|
| 322 |
+
")\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"pbar.close()\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"merged = result.get(\"merged_wav\")\n",
|
| 327 |
+
"if merged:\n",
|
| 328 |
+
" display(Audio(str(merged)))\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"print(\"\\n--- Đã lưu trên Drive ---\")\n",
|
| 331 |
+
"print(f\"WAV gộp: {result.get('merged_wav')}\")\n",
|
| 332 |
+
"print(f\"Từng cue: {result.get('output_dir')}\")\n",
|
| 333 |
+
"print(f\"SRT shifted: {result.get('shifted_srt')}\")\n",
|
| 334 |
+
"stats = result.get(\"stats\", {})\n",
|
| 335 |
+
"print(\n",
|
| 336 |
+
" f\"Thống kê: {stats.get('generated', 0)} cue mới, \"\n",
|
| 337 |
+
" f\"{stats.get('skipped', 0)} bỏ qua, \"\n",
|
| 338 |
+
" f\"{stats.get('overflow', 0)} tràn\"\n",
|
| 339 |
+
")"
|
| 340 |
+
],
|
| 341 |
+
"execution_count": null,
|
| 342 |
+
"outputs": [],
|
| 343 |
+
"id": "d924855a"
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"cell_type": "markdown",
|
| 347 |
+
"metadata": {},
|
| 348 |
+
"source": [
|
| 349 |
+
"## 5. Giải phóng VRAM & tắt runtime\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"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."
|
| 352 |
+
],
|
| 353 |
+
"id": "4ec794ec"
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"cell_type": "code",
|
| 357 |
+
"metadata": {},
|
| 358 |
+
"source": [
|
| 359 |
+
"import gc\n",
|
| 360 |
+
"import torch\n",
|
| 361 |
+
"from google.colab import runtime\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"try:\n",
|
| 364 |
+
" del MODEL, PROMPT, result, pbar\n",
|
| 365 |
+
"except NameError:\n",
|
| 366 |
+
" pass\n",
|
| 367 |
+
"\n",
|
| 368 |
+
"gc.collect()\n",
|
| 369 |
+
"if torch.cuda.is_available():\n",
|
| 370 |
+
" torch.cuda.empty_cache()\n",
|
| 371 |
+
" torch.cuda.ipc_collect()\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"print(\"Đã giải phóng VRAM\")\n",
|
| 374 |
+
"print(\"Đang tắt runtime Colab...\")\n",
|
| 375 |
+
"runtime.unassign()"
|
| 376 |
+
],
|
| 377 |
+
"execution_count": null,
|
| 378 |
+
"outputs": [],
|
| 379 |
+
"id": "a3acbb68"
|
| 380 |
+
}
|
| 381 |
+
],
|
| 382 |
+
"metadata": {
|
| 383 |
+
"accelerator": "GPU",
|
| 384 |
+
"colab": {
|
| 385 |
+
"gpuType": "L4",
|
| 386 |
+
"machine_shape": "hm",
|
| 387 |
+
"provenance": []
|
| 388 |
+
},
|
| 389 |
+
"kernelspec": {
|
| 390 |
+
"display_name": "Python 3",
|
| 391 |
+
"language": "python",
|
| 392 |
+
"name": "python3"
|
| 393 |
+
},
|
| 394 |
+
"language_info": {
|
| 395 |
+
"name": "python",
|
| 396 |
+
"version": "3.10.0"
|
| 397 |
+
}
|
| 398 |
+
},
|
| 399 |
+
"nbformat": 4,
|
| 400 |
+
"nbformat_minor": 5
|
| 401 |
+
}
|
tools/speak.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Đọc văn bản / file / SRT bằng voice profile (.pt).
|
| 2 |
+
|
| 3 |
+
Ví dụ:
|
| 4 |
+
python tools/speak.py voices
|
| 5 |
+
python tools/speak.py --profile voices/ban_mai/profile.json build
|
| 6 |
+
python tools/speak.py --profile voices/ban_mai/profile.json text --text "..." -o out.wav
|
| 7 |
+
python tools/speak.py --profile voices/ban_mai/profile.json srt --input video.srt
|
| 8 |
+
python tools/speak.py --profile voices/ban_mai/profile.json srt --input video.srt --merge -o dub.wav --fit-duration
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import re
|
| 17 |
+
import sys
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Callable, List, Optional
|
| 21 |
+
|
| 22 |
+
import librosa
|
| 23 |
+
import numpy as np
|
| 24 |
+
import soundfile as sf
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
from omnivoice.models.omnivoice import OmniVoice, VoiceClonePrompt
|
| 28 |
+
|
| 29 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 30 |
+
VOICES_DIR = ROOT / "voices"
|
| 31 |
+
DEFAULT_VOICE_SLUG = "tuong_vy"
|
| 32 |
+
DEFAULT_PROFILE = VOICES_DIR / DEFAULT_VOICE_SLUG / "profile.json"
|
| 33 |
+
|
| 34 |
+
# Mặc định biểu cảm: bật lấy mẫu token có nhiệt độ thay vì greedy (0.0).
|
| 35 |
+
# Greedy khiến ngữ điệu phẳng, "máy móc"; 0.4 cho nhấn nhá vừa phải, ổn định.
|
| 36 |
+
DEFAULT_CLASS_TEMPERATURE = 0.4
|
| 37 |
+
DEFAULT_GUIDANCE_SCALE = 2.0
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class SrtCue:
|
| 42 |
+
index: int
|
| 43 |
+
start_sec: float
|
| 44 |
+
end_sec: float
|
| 45 |
+
text: str
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def discover_profiles() -> List[Path]:
|
| 49 |
+
if not VOICES_DIR.exists():
|
| 50 |
+
return []
|
| 51 |
+
return sorted(
|
| 52 |
+
p for p in VOICES_DIR.glob("*/profile.json") if p.is_file()
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def profile_slug(profile_path: Path) -> str:
|
| 57 |
+
return profile_path.parent.name
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def load_profile(profile_path: Path) -> dict:
|
| 61 |
+
with profile_path.open(encoding="utf-8") as f:
|
| 62 |
+
profile = json.load(f)
|
| 63 |
+
base = profile_path.parent
|
| 64 |
+
profile["_base"] = base
|
| 65 |
+
profile["_profile_path"] = str(profile_path)
|
| 66 |
+
profile["slug"] = profile.get("slug", profile_slug(profile_path))
|
| 67 |
+
profile["ref_audio_path"] = str(base / profile["ref_audio"])
|
| 68 |
+
profile["ref_text_path"] = str(base / profile["ref_text_file"])
|
| 69 |
+
profile["voice_prompt_path"] = str(base / profile["voice_prompt"])
|
| 70 |
+
return profile
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def default_output_dir(profile: dict, stem: str) -> Path:
|
| 74 |
+
return ROOT / "output" / profile["slug"] / stem
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def read_ref_text(profile: dict) -> str:
|
| 78 |
+
return Path(profile["ref_text_path"]).read_text(encoding="utf-8").strip()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def load_model(profile: dict) -> OmniVoice:
|
| 82 |
+
return OmniVoice.from_pretrained(
|
| 83 |
+
profile.get("model", "k2-fsa/OmniVoice"),
|
| 84 |
+
device_map=profile.get("device", "cuda:0"),
|
| 85 |
+
dtype=torch.float16,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def build_voice_prompt(model: OmniVoice, profile: dict) -> VoiceClonePrompt:
|
| 90 |
+
preprocess = profile.get("preprocess_prompt", True)
|
| 91 |
+
auto_transcribe = profile.get("auto_transcribe", False)
|
| 92 |
+
|
| 93 |
+
if auto_transcribe:
|
| 94 |
+
ref_text = None
|
| 95 |
+
logging.info(
|
| 96 |
+
"Tạo voice profile từ %s (Whisper tự nhận diện ref_text)",
|
| 97 |
+
profile["ref_audio_path"],
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
ref_text = read_ref_text(profile)
|
| 101 |
+
logging.info("Tạo voice profile từ %s", profile["ref_audio_path"])
|
| 102 |
+
|
| 103 |
+
prompt = model.create_voice_clone_prompt(
|
| 104 |
+
ref_audio=profile["ref_audio_path"],
|
| 105 |
+
ref_text=ref_text,
|
| 106 |
+
preprocess_prompt=preprocess,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
if auto_transcribe:
|
| 110 |
+
ref_text_path = Path(profile["ref_text_path"])
|
| 111 |
+
ref_text_path.write_text(prompt.ref_text, encoding="utf-8")
|
| 112 |
+
logging.info("Đã cập nhật ref_text từ Whisper: %s", ref_text_path)
|
| 113 |
+
|
| 114 |
+
return prompt
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def save_voice_prompt(prompt: VoiceClonePrompt, path: Path) -> None:
|
| 118 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
torch.save(
|
| 120 |
+
{
|
| 121 |
+
"ref_audio_tokens": prompt.ref_audio_tokens.cpu(),
|
| 122 |
+
"ref_text": prompt.ref_text,
|
| 123 |
+
"ref_rms": prompt.ref_rms,
|
| 124 |
+
},
|
| 125 |
+
path,
|
| 126 |
+
)
|
| 127 |
+
logging.info("Đã lưu voice profile: %s", path)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def load_voice_prompt(path: Path) -> VoiceClonePrompt:
|
| 131 |
+
data = torch.load(path, map_location="cpu", weights_only=True)
|
| 132 |
+
return VoiceClonePrompt(
|
| 133 |
+
ref_audio_tokens=data["ref_audio_tokens"],
|
| 134 |
+
ref_text=data["ref_text"],
|
| 135 |
+
ref_rms=data["ref_rms"],
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def ensure_voice_prompt(model: OmniVoice, profile: dict) -> VoiceClonePrompt:
|
| 140 |
+
prompt_path = Path(profile["voice_prompt_path"])
|
| 141 |
+
if prompt_path.exists():
|
| 142 |
+
logging.info("Dùng voice profile có sẵn: %s", prompt_path)
|
| 143 |
+
return load_voice_prompt(prompt_path)
|
| 144 |
+
prompt = build_voice_prompt(model, profile)
|
| 145 |
+
save_voice_prompt(prompt, prompt_path)
|
| 146 |
+
return prompt
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def time_stretch_speech(audio: np.ndarray, rate: float) -> np.ndarray:
|
| 150 |
+
"""Tăng/giảm tốc audio giữ cao độ, ưu tiên WSOLA cho giọng nói.
|
| 151 |
+
|
| 152 |
+
WSOLA (audiotsm) giữ chất giọng tự nhiên hơn nhiều so với phase vocoder
|
| 153 |
+
của librosa khi tăng tốc. Nếu WSOLA lỗi, fallback về librosa.
|
| 154 |
+
"""
|
| 155 |
+
rate = float(rate)
|
| 156 |
+
audio = np.ascontiguousarray(audio.astype(np.float32))
|
| 157 |
+
if abs(rate - 1.0) < 1e-3 or audio.size == 0:
|
| 158 |
+
return audio
|
| 159 |
+
try:
|
| 160 |
+
from audiotsm import wsola
|
| 161 |
+
from audiotsm.io.array import ArrayReader, ArrayWriter
|
| 162 |
+
|
| 163 |
+
reader = ArrayReader(audio.reshape(1, -1))
|
| 164 |
+
writer = ArrayWriter(channels=1)
|
| 165 |
+
wsola(channels=1, speed=rate).run(reader, writer)
|
| 166 |
+
out = np.asarray(writer.data, dtype=np.float32).flatten()
|
| 167 |
+
if out.size > 0:
|
| 168 |
+
return out
|
| 169 |
+
raise ValueError("WSOLA trả về rỗng")
|
| 170 |
+
except Exception as exc: # noqa: BLE001
|
| 171 |
+
logging.warning("WSOLA lỗi (%s), dùng librosa phase vocoder", exc)
|
| 172 |
+
return librosa.effects.time_stretch(audio, rate=rate)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def apply_speed_policy(
|
| 176 |
+
audio: np.ndarray,
|
| 177 |
+
sample_rate: int,
|
| 178 |
+
slot_sec: float,
|
| 179 |
+
*,
|
| 180 |
+
speed_mode: str,
|
| 181 |
+
gentle_threshold: float,
|
| 182 |
+
) -> tuple[np.ndarray, dict]:
|
| 183 |
+
"""Xử lý tốc độ theo chế độ — ưu tiên giữ chất giọng đoạn dài.
|
| 184 |
+
|
| 185 |
+
- off: không đổi tốc độ, cascade tràn sang cue sau.
|
| 186 |
+
- gentle: chỉ tăng tốc nhẹ nếu cần <= gentle_threshold (mặc định 1.08).
|
| 187 |
+
- force: ép vừa slot bằng time-stretch (có thể méo giọng).
|
| 188 |
+
"""
|
| 189 |
+
generated_sec = len(audio) / sample_rate
|
| 190 |
+
meta = {
|
| 191 |
+
"generated_sec": round(generated_sec, 3),
|
| 192 |
+
"slot_sec": round(slot_sec, 3),
|
| 193 |
+
"required_speed_factor": 1.0,
|
| 194 |
+
"speed_factor": 1.0,
|
| 195 |
+
"speed_mode": speed_mode,
|
| 196 |
+
"gentle_threshold": round(gentle_threshold, 3),
|
| 197 |
+
"speed_fitted": False,
|
| 198 |
+
"speed_skipped": False,
|
| 199 |
+
"speed_skip_reason": None,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
if slot_sec <= 0 or generated_sec <= slot_sec:
|
| 203 |
+
meta["audio_sec"] = round(generated_sec, 3)
|
| 204 |
+
return audio, meta
|
| 205 |
+
|
| 206 |
+
required_rate = generated_sec / slot_sec
|
| 207 |
+
meta["required_speed_factor"] = round(required_rate, 3)
|
| 208 |
+
|
| 209 |
+
if speed_mode == "off":
|
| 210 |
+
meta["audio_sec"] = round(generated_sec, 3)
|
| 211 |
+
meta["speed_skipped"] = True
|
| 212 |
+
meta["speed_skip_reason"] = "cascade_overflow"
|
| 213 |
+
logging.info(
|
| 214 |
+
"Cue %.2fs > slot %.2fs: giữ nguyên giọng, tràn cascade (cần x%.2f)",
|
| 215 |
+
generated_sec,
|
| 216 |
+
slot_sec,
|
| 217 |
+
required_rate,
|
| 218 |
+
)
|
| 219 |
+
return audio, meta
|
| 220 |
+
|
| 221 |
+
if speed_mode == "gentle" and required_rate > gentle_threshold:
|
| 222 |
+
meta["audio_sec"] = round(generated_sec, 3)
|
| 223 |
+
meta["speed_skipped"] = True
|
| 224 |
+
meta["speed_skip_reason"] = "exceeds_gentle_threshold"
|
| 225 |
+
logging.info(
|
| 226 |
+
"Cue dài %.2fs / slot %.2fs (x%.2f > %.2f): giữ nguyên giọng, tràn cascade",
|
| 227 |
+
generated_sec,
|
| 228 |
+
slot_sec,
|
| 229 |
+
required_rate,
|
| 230 |
+
gentle_threshold,
|
| 231 |
+
)
|
| 232 |
+
return audio, meta
|
| 233 |
+
|
| 234 |
+
rate = required_rate if speed_mode == "force" else min(required_rate, gentle_threshold)
|
| 235 |
+
stretched = time_stretch_speech(audio, rate)
|
| 236 |
+
|
| 237 |
+
if speed_mode == "gentle" or speed_mode == "force":
|
| 238 |
+
target_samples = int(round(slot_sec * sample_rate))
|
| 239 |
+
if len(stretched) > target_samples:
|
| 240 |
+
stretched = stretched[:target_samples]
|
| 241 |
+
elif len(stretched) < target_samples:
|
| 242 |
+
stretched = np.pad(stretched, (0, target_samples - len(stretched)))
|
| 243 |
+
|
| 244 |
+
meta["speed_factor"] = round(rate, 3)
|
| 245 |
+
meta["speed_fitted"] = True
|
| 246 |
+
meta["audio_sec"] = round(len(stretched) / sample_rate, 3)
|
| 247 |
+
logging.info(
|
| 248 |
+
"Tăng tốc nhẹ cue: %.2fs -> %.2fs (x%.2f, mode=%s)",
|
| 249 |
+
generated_sec,
|
| 250 |
+
meta["audio_sec"],
|
| 251 |
+
rate,
|
| 252 |
+
speed_mode,
|
| 253 |
+
)
|
| 254 |
+
return stretched, meta
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def synthesize(
|
| 258 |
+
model: OmniVoice,
|
| 259 |
+
prompt: VoiceClonePrompt,
|
| 260 |
+
text: str,
|
| 261 |
+
language: str,
|
| 262 |
+
**kwargs,
|
| 263 |
+
) -> np.ndarray:
|
| 264 |
+
text = text.strip()
|
| 265 |
+
if not text:
|
| 266 |
+
raise ValueError("Văn bản trống.")
|
| 267 |
+
audios = model.generate(
|
| 268 |
+
text=text,
|
| 269 |
+
language=language,
|
| 270 |
+
voice_clone_prompt=prompt,
|
| 271 |
+
**kwargs,
|
| 272 |
+
)
|
| 273 |
+
return audios[0]
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def estimate_natural_duration_sec(
|
| 277 |
+
model: OmniVoice, prompt: VoiceClonePrompt, text: str
|
| 278 |
+
) -> float:
|
| 279 |
+
"""Ước lượng thời lượng đọc tự nhiên (giây) của text với giọng mẫu.
|
| 280 |
+
|
| 281 |
+
Dùng chính bộ ước lượng của model (không cần sinh audio), nhờ đó biết
|
| 282 |
+
trước câu nào sẽ dài hơn khung SRT để quyết định tốc độ native.
|
| 283 |
+
"""
|
| 284 |
+
text = text.strip()
|
| 285 |
+
if not text:
|
| 286 |
+
return 0.0
|
| 287 |
+
est_tokens = model.duration_estimator.estimate_duration(
|
| 288 |
+
text,
|
| 289 |
+
prompt.ref_text,
|
| 290 |
+
prompt.ref_audio_tokens.size(-1),
|
| 291 |
+
)
|
| 292 |
+
frame_rate = model.audio_tokenizer.config.frame_rate
|
| 293 |
+
return float(est_tokens) / frame_rate if frame_rate else 0.0
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def parse_srt_time(value: str) -> float:
|
| 297 |
+
hh, mm, rest = value.strip().split(":")
|
| 298 |
+
ss, ms = rest.split(",")
|
| 299 |
+
return int(hh) * 3600 + int(mm) * 60 + int(ss) + int(ms) / 1000.0
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def parse_srt(content: str) -> List[SrtCue]:
|
| 303 |
+
content = content.replace("\r\n", "\n").replace("\r", "\n").strip()
|
| 304 |
+
blocks = re.split(r"\n\s*\n", content)
|
| 305 |
+
cues: List[SrtCue] = []
|
| 306 |
+
|
| 307 |
+
for block in blocks:
|
| 308 |
+
lines = [line.strip() for line in block.split("\n") if line.strip()]
|
| 309 |
+
if len(lines) < 2:
|
| 310 |
+
continue
|
| 311 |
+
if not lines[0].isdigit():
|
| 312 |
+
continue
|
| 313 |
+
index = int(lines[0])
|
| 314 |
+
if "-->" not in lines[1]:
|
| 315 |
+
continue
|
| 316 |
+
start_raw, end_raw = [part.strip() for part in lines[1].split("-->")]
|
| 317 |
+
text = " ".join(lines[2:])
|
| 318 |
+
text = re.sub(r"<[^>]+>", "", text).strip()
|
| 319 |
+
if not text:
|
| 320 |
+
continue
|
| 321 |
+
cues.append(
|
| 322 |
+
SrtCue(
|
| 323 |
+
index=index,
|
| 324 |
+
start_sec=parse_srt_time(start_raw),
|
| 325 |
+
end_sec=parse_srt_time(end_raw),
|
| 326 |
+
text=text,
|
| 327 |
+
)
|
| 328 |
+
)
|
| 329 |
+
return cues
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def format_srt_time(sec: float) -> str:
|
| 333 |
+
if sec < 0:
|
| 334 |
+
sec = 0.0
|
| 335 |
+
total_ms = int(round(sec * 1000))
|
| 336 |
+
ms = total_ms % 1000
|
| 337 |
+
total_sec = total_ms // 1000
|
| 338 |
+
hours = total_sec // 3600
|
| 339 |
+
minutes = (total_sec % 3600) // 60
|
| 340 |
+
seconds = total_sec % 60
|
| 341 |
+
return f"{hours:02d}:{minutes:02d}:{seconds:02d},{ms:03d}"
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def plan_cascade_placements(
|
| 345 |
+
cues: List[SrtCue],
|
| 346 |
+
segments: List[np.ndarray],
|
| 347 |
+
sample_rate: int,
|
| 348 |
+
) -> List[dict]:
|
| 349 |
+
"""Tính vị trí thực tế: cue dài hơn slot sẽ đẩy các cue sau."""
|
| 350 |
+
placements: List[dict] = []
|
| 351 |
+
cursor = 0.0
|
| 352 |
+
|
| 353 |
+
for cue, audio in zip(cues, segments):
|
| 354 |
+
audio_sec = len(audio) / sample_rate
|
| 355 |
+
slot_sec = max(0.0, cue.end_sec - cue.start_sec)
|
| 356 |
+
actual_start = max(cue.start_sec, cursor)
|
| 357 |
+
actual_end = actual_start + audio_sec
|
| 358 |
+
pushed = actual_start > cue.start_sec + 0.01
|
| 359 |
+
if pushed:
|
| 360 |
+
overflow_sec = 0.0
|
| 361 |
+
else:
|
| 362 |
+
overflow_sec = max(0.0, actual_end - cue.end_sec)
|
| 363 |
+
|
| 364 |
+
placements.append(
|
| 365 |
+
{
|
| 366 |
+
"actual_start_sec": round(actual_start, 3),
|
| 367 |
+
"actual_end_sec": round(actual_end, 3),
|
| 368 |
+
"overflow_sec": round(overflow_sec, 3),
|
| 369 |
+
"pushed_by_previous": pushed,
|
| 370 |
+
}
|
| 371 |
+
)
|
| 372 |
+
if overflow_sec > 0:
|
| 373 |
+
logging.info(
|
| 374 |
+
"Cue %s dài %.2fs / slot %.2fs -> tràn %.2fs, kết thúc %.2fs",
|
| 375 |
+
cue.index,
|
| 376 |
+
audio_sec,
|
| 377 |
+
slot_sec,
|
| 378 |
+
overflow_sec,
|
| 379 |
+
actual_end,
|
| 380 |
+
)
|
| 381 |
+
cursor = actual_end
|
| 382 |
+
|
| 383 |
+
return placements
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def plan_native_placements(
|
| 387 |
+
cues: List[SrtCue],
|
| 388 |
+
segments: List[np.ndarray],
|
| 389 |
+
sample_rate: int,
|
| 390 |
+
) -> List[dict]:
|
| 391 |
+
"""Neo cứng mỗi cue đúng mốc SRT gốc — lỗi lệch KHÔNG bao giờ cộng dồn.
|
| 392 |
+
|
| 393 |
+
Kiểu lồng tiếng chuyên nghiệp: câu dài hơn khung đã được nói nhanh native
|
| 394 |
+
vừa đủ chứa hết chữ (xử lý lúc sinh audio), nên ở đây chỉ cần đặt từng câu
|
| 395 |
+
đúng vị trí thời gian của nó. Mỗi câu độc lập theo mốc SRT, câu này không
|
| 396 |
+
đẩy câu kia → đồng bộ tiếng/hình ổn định suốt video.
|
| 397 |
+
"""
|
| 398 |
+
placements: List[dict] = []
|
| 399 |
+
n = len(cues)
|
| 400 |
+
|
| 401 |
+
for i, (cue, audio) in enumerate(zip(cues, segments)):
|
| 402 |
+
audio_sec = len(audio) / sample_rate
|
| 403 |
+
actual_start = cue.start_sec
|
| 404 |
+
actual_end = actual_start + audio_sec
|
| 405 |
+
next_start = cues[i + 1].start_sec if i + 1 < n else actual_end
|
| 406 |
+
overflow = max(0.0, actual_end - next_start)
|
| 407 |
+
|
| 408 |
+
placements.append(
|
| 409 |
+
{
|
| 410 |
+
"actual_start_sec": round(actual_start, 3),
|
| 411 |
+
"actual_end_sec": round(actual_end, 3),
|
| 412 |
+
"overflow_sec": round(overflow, 3),
|
| 413 |
+
"pushed_by_previous": False,
|
| 414 |
+
}
|
| 415 |
+
)
|
| 416 |
+
if overflow > 0.05:
|
| 417 |
+
logging.info(
|
| 418 |
+
"Cue %s: vẫn vượt khung %.2fs sau khi tăng tốc (cân nhắc tăng "
|
| 419 |
+
"--native-speed-cap để chứa hết chữ)",
|
| 420 |
+
cue.index,
|
| 421 |
+
overflow,
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
return placements
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def write_shifted_srt(
|
| 428 |
+
path: Path,
|
| 429 |
+
cues: List[SrtCue],
|
| 430 |
+
placements: List[dict],
|
| 431 |
+
) -> None:
|
| 432 |
+
blocks = []
|
| 433 |
+
for cue, placement in zip(cues, placements):
|
| 434 |
+
start = format_srt_time(placement["actual_start_sec"])
|
| 435 |
+
end = format_srt_time(placement["actual_end_sec"])
|
| 436 |
+
blocks.append(f"{cue.index}\n{start} --> {end}\n{cue.text}\n")
|
| 437 |
+
path.write_text("\n".join(blocks), encoding="utf-8")
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def write_manifest(
|
| 441 |
+
path: Path,
|
| 442 |
+
cues: List[SrtCue],
|
| 443 |
+
wav_paths: List[Path],
|
| 444 |
+
fit_metas: List[dict],
|
| 445 |
+
sample_rate: int,
|
| 446 |
+
profile: dict,
|
| 447 |
+
srt_input: Path,
|
| 448 |
+
merge_mode: str,
|
| 449 |
+
) -> None:
|
| 450 |
+
rows = []
|
| 451 |
+
for cue, wav, fit_meta in zip(cues, wav_paths, fit_metas):
|
| 452 |
+
slot_sec = max(0.0, cue.end_sec - cue.start_sec)
|
| 453 |
+
rows.append(
|
| 454 |
+
{
|
| 455 |
+
"index": cue.index,
|
| 456 |
+
"start_sec": cue.start_sec,
|
| 457 |
+
"end_sec": cue.end_sec,
|
| 458 |
+
"slot_sec": round(slot_sec, 3),
|
| 459 |
+
"actual_start_sec": fit_meta.get("actual_start_sec"),
|
| 460 |
+
"actual_end_sec": fit_meta.get("actual_end_sec"),
|
| 461 |
+
"overflow_sec": fit_meta.get("overflow_sec", 0.0),
|
| 462 |
+
"pushed_by_previous": fit_meta.get("pushed_by_previous", False),
|
| 463 |
+
"fit_applied": fit_meta.get("fit_applied", False),
|
| 464 |
+
"fit_speed_factor": fit_meta.get("fit_speed_factor", 1.0),
|
| 465 |
+
"generated_sec": fit_meta.get("generated_sec"),
|
| 466 |
+
"audio_sec": fit_meta.get("audio_sec"),
|
| 467 |
+
"required_speed_factor": fit_meta.get("required_speed_factor", 1.0),
|
| 468 |
+
"speed_factor": fit_meta.get("speed_factor", 1.0),
|
| 469 |
+
"speed_mode": fit_meta.get("speed_mode"),
|
| 470 |
+
"gentle_threshold": fit_meta.get("gentle_threshold"),
|
| 471 |
+
"speed_fitted": fit_meta.get("speed_fitted", False),
|
| 472 |
+
"speed_skipped": fit_meta.get("speed_skipped", False),
|
| 473 |
+
"speed_skip_reason": fit_meta.get("speed_skip_reason"),
|
| 474 |
+
"text": cue.text,
|
| 475 |
+
"wav": str(wav),
|
| 476 |
+
"wav_relative": wav.name,
|
| 477 |
+
}
|
| 478 |
+
)
|
| 479 |
+
payload = {
|
| 480 |
+
"voice": profile.get("name", profile["slug"]),
|
| 481 |
+
"voice_slug": profile["slug"],
|
| 482 |
+
"language": profile.get("language"),
|
| 483 |
+
"srt_input": str(srt_input),
|
| 484 |
+
"sample_rate": sample_rate,
|
| 485 |
+
"merge_mode": merge_mode,
|
| 486 |
+
"cues": rows,
|
| 487 |
+
}
|
| 488 |
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def merge_timeline_strict(
|
| 492 |
+
cues: List[SrtCue],
|
| 493 |
+
audio_segments: List[np.ndarray],
|
| 494 |
+
sample_rate: int,
|
| 495 |
+
tail_sec: float = 0.5,
|
| 496 |
+
) -> np.ndarray:
|
| 497 |
+
if not cues:
|
| 498 |
+
raise ValueError("Không có cue SRT để gộp.")
|
| 499 |
+
total_sec = max(cue.end_sec for cue in cues) + tail_sec
|
| 500 |
+
merged = np.zeros(int(total_sec * sample_rate), dtype=np.float32)
|
| 501 |
+
for cue, audio in zip(cues, audio_segments):
|
| 502 |
+
start = int(cue.start_sec * sample_rate)
|
| 503 |
+
end = min(start + len(audio), len(merged))
|
| 504 |
+
merged[start:end] = audio[: end - start]
|
| 505 |
+
return _normalize_audio(merged)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def merge_timeline_cascade(
|
| 509 |
+
placements: List[dict],
|
| 510 |
+
audio_segments: List[np.ndarray],
|
| 511 |
+
sample_rate: int,
|
| 512 |
+
tail_sec: float = 0.5,
|
| 513 |
+
) -> np.ndarray:
|
| 514 |
+
if not placements:
|
| 515 |
+
raise ValueError("Không có cue SRT để gộp.")
|
| 516 |
+
total_sec = placements[-1]["actual_end_sec"] + tail_sec
|
| 517 |
+
merged = np.zeros(int(total_sec * sample_rate), dtype=np.float32)
|
| 518 |
+
for placement, audio in zip(placements, audio_segments):
|
| 519 |
+
start = int(placement["actual_start_sec"] * sample_rate)
|
| 520 |
+
end = start + len(audio)
|
| 521 |
+
if end > len(merged):
|
| 522 |
+
merged = np.pad(merged, (0, end - len(merged)))
|
| 523 |
+
merged[start:end] = audio
|
| 524 |
+
return _normalize_audio(merged)
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def plan_fit_placements(
|
| 528 |
+
cues: List[SrtCue],
|
| 529 |
+
segments: List[np.ndarray],
|
| 530 |
+
sample_rate: int,
|
| 531 |
+
max_speed_factor: float = 1.6,
|
| 532 |
+
min_gap_sec: float = 0.05,
|
| 533 |
+
) -> tuple[List[dict], List[np.ndarray]]:
|
| 534 |
+
"""Neo mỗi cue đúng mốc SRT gốc, tăng tốc cả câu (giữ pitch) cho vừa khung.
|
| 535 |
+
|
| 536 |
+
- Cue vừa khung: giữ nguyên, không đổi tốc độ.
|
| 537 |
+
- Cue tràn, cần tăng tốc <= max_speed_factor: time-stretch vừa đủ -> khớp SRT
|
| 538 |
+
tuyệt đối, giọng tự nhiên (phase vocoder giữ cao độ).
|
| 539 |
+
- Cue tràn nặng, cần > max_speed_factor: chỉ tăng tới trần (giữ giọng),
|
| 540 |
+
phần dư cho tràn nhẹ và tự khớp lại ở các cue ngắn kế tiếp (cascade mềm).
|
| 541 |
+
"""
|
| 542 |
+
placements: List[dict] = []
|
| 543 |
+
fitted_segments: List[np.ndarray] = []
|
| 544 |
+
n = len(cues)
|
| 545 |
+
cursor = 0.0
|
| 546 |
+
|
| 547 |
+
for i, (cue, audio) in enumerate(zip(cues, segments)):
|
| 548 |
+
audio_sec = len(audio) / sample_rate
|
| 549 |
+
start = max(cue.start_sec, cursor)
|
| 550 |
+
|
| 551 |
+
if i + 1 < n:
|
| 552 |
+
room_sec = max(min_gap_sec, cues[i + 1].start_sec - start)
|
| 553 |
+
else:
|
| 554 |
+
room_sec = audio_sec # cue cuối: không giới hạn
|
| 555 |
+
|
| 556 |
+
capped = False
|
| 557 |
+
if audio_sec > room_sec + 1e-3:
|
| 558 |
+
required = audio_sec / room_sec
|
| 559 |
+
rate = min(required, max_speed_factor)
|
| 560 |
+
stretched = time_stretch_speech(audio, rate)
|
| 561 |
+
if rate >= required - 1e-3:
|
| 562 |
+
target = int(round(room_sec * sample_rate))
|
| 563 |
+
if len(stretched) > target:
|
| 564 |
+
stretched = stretched[:target]
|
| 565 |
+
elif len(stretched) < target:
|
| 566 |
+
stretched = np.pad(stretched, (0, target - len(stretched)))
|
| 567 |
+
else:
|
| 568 |
+
capped = True
|
| 569 |
+
fitted = True
|
| 570 |
+
speed_factor = rate
|
| 571 |
+
else:
|
| 572 |
+
stretched = audio
|
| 573 |
+
fitted = False
|
| 574 |
+
speed_factor = 1.0
|
| 575 |
+
|
| 576 |
+
seg_sec = len(stretched) / sample_rate
|
| 577 |
+
actual_end = start + seg_sec
|
| 578 |
+
next_start = cues[i + 1].start_sec if i + 1 < n else actual_end
|
| 579 |
+
overflow = max(0.0, actual_end - next_start)
|
| 580 |
+
placements.append(
|
| 581 |
+
{
|
| 582 |
+
"actual_start_sec": round(start, 3),
|
| 583 |
+
"actual_end_sec": round(actual_end, 3),
|
| 584 |
+
"overflow_sec": round(overflow, 3),
|
| 585 |
+
"pushed_by_previous": start > cue.start_sec + 0.01,
|
| 586 |
+
"fit_applied": fitted,
|
| 587 |
+
"fit_speed_factor": round(speed_factor, 3),
|
| 588 |
+
"fit_capped": capped,
|
| 589 |
+
}
|
| 590 |
+
)
|
| 591 |
+
fitted_segments.append(stretched)
|
| 592 |
+
cursor = actual_end
|
| 593 |
+
if fitted:
|
| 594 |
+
logging.info(
|
| 595 |
+
"Cue %s: %.2fs -> %.2fs (x%.2f%s)",
|
| 596 |
+
cue.index,
|
| 597 |
+
audio_sec,
|
| 598 |
+
seg_sec,
|
| 599 |
+
speed_factor,
|
| 600 |
+
", chạm trần - tràn nhẹ" if capped else "",
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
return placements, fitted_segments
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def merge_timeline_fit(
|
| 607 |
+
placements: List[dict],
|
| 608 |
+
fitted_segments: List[np.ndarray],
|
| 609 |
+
sample_rate: int,
|
| 610 |
+
tail_sec: float = 0.5,
|
| 611 |
+
) -> np.ndarray:
|
| 612 |
+
if not placements:
|
| 613 |
+
raise ValueError("Không có cue SRT để gộp.")
|
| 614 |
+
total_sec = placements[-1]["actual_end_sec"] + tail_sec
|
| 615 |
+
merged = np.zeros(int(total_sec * sample_rate), dtype=np.float32)
|
| 616 |
+
for placement, audio in zip(placements, fitted_segments):
|
| 617 |
+
start = int(placement["actual_start_sec"] * sample_rate)
|
| 618 |
+
end = start + len(audio)
|
| 619 |
+
if end > len(merged):
|
| 620 |
+
merged = np.pad(merged, (0, end - len(merged)))
|
| 621 |
+
merged[start:end] = audio
|
| 622 |
+
return _normalize_audio(merged)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def _normalize_audio(audio: np.ndarray) -> np.ndarray:
|
| 626 |
+
peak = np.max(np.abs(audio))
|
| 627 |
+
if peak > 1.0:
|
| 628 |
+
return audio / peak * 0.98
|
| 629 |
+
return audio
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def cmd_build(args: argparse.Namespace) -> None:
|
| 633 |
+
profile = load_profile(Path(args.profile))
|
| 634 |
+
model = load_model(profile)
|
| 635 |
+
prompt = build_voice_prompt(model, profile)
|
| 636 |
+
save_voice_prompt(prompt, Path(profile["voice_prompt_path"]))
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def cmd_text(args: argparse.Namespace) -> None:
|
| 640 |
+
profile = load_profile(Path(args.profile))
|
| 641 |
+
model = load_model(profile)
|
| 642 |
+
prompt = ensure_voice_prompt(model, profile)
|
| 643 |
+
audio = synthesize(
|
| 644 |
+
model,
|
| 645 |
+
prompt,
|
| 646 |
+
args.text,
|
| 647 |
+
profile["language"],
|
| 648 |
+
num_step=args.num_step,
|
| 649 |
+
class_temperature=args.class_temperature,
|
| 650 |
+
guidance_scale=args.guidance_scale,
|
| 651 |
+
)
|
| 652 |
+
out = Path(args.output)
|
| 653 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 654 |
+
sf.write(out, audio, model.sampling_rate)
|
| 655 |
+
logging.info("Đã lưu: %s", out)
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def cmd_file(args: argparse.Namespace) -> None:
|
| 659 |
+
text = Path(args.input).read_text(encoding="utf-8").strip()
|
| 660 |
+
ns = argparse.Namespace(**vars(args))
|
| 661 |
+
ns.text = text
|
| 662 |
+
cmd_text(ns)
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def cmd_voices(_: argparse.Namespace) -> None:
|
| 666 |
+
profiles = discover_profiles()
|
| 667 |
+
if not profiles:
|
| 668 |
+
print("Chưa có giọng nào trong voices/*/profile.json")
|
| 669 |
+
return
|
| 670 |
+
for path in profiles:
|
| 671 |
+
profile = load_profile(path)
|
| 672 |
+
ready = Path(profile["voice_prompt_path"]).exists()
|
| 673 |
+
status = "ready" if ready else "missing voice.pt"
|
| 674 |
+
print(f"- {profile['slug']}: {profile.get('name', profile['slug'])} [{status}]")
|
| 675 |
+
print(f" profile: {path}")
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def list_voice_choices() -> List[tuple[str, str, str]]:
|
| 679 |
+
rows = []
|
| 680 |
+
for path in discover_profiles():
|
| 681 |
+
profile = load_profile(path)
|
| 682 |
+
ready = Path(profile["voice_prompt_path"]).exists()
|
| 683 |
+
label = f"{profile.get('name', profile['slug'])} ({'ready' if ready else 'no .pt'})"
|
| 684 |
+
rows.append((profile["slug"], label, str(path)))
|
| 685 |
+
return rows
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
def _pipe_log(log_lines: List[str], line: str, on_log: Optional[Callable[[str], None]] = None) -> None:
|
| 689 |
+
log_lines.append(line)
|
| 690 |
+
if on_log is not None:
|
| 691 |
+
on_log(line)
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def run_srt_pipeline(
|
| 695 |
+
profile_path: Path,
|
| 696 |
+
srt_path: Path,
|
| 697 |
+
*,
|
| 698 |
+
output_dir: Optional[Path] = None,
|
| 699 |
+
merge: bool = False,
|
| 700 |
+
merge_output: Optional[Path] = None,
|
| 701 |
+
merge_mode: str = "cascade",
|
| 702 |
+
speed_mode: str = "off",
|
| 703 |
+
gentle_threshold: float = 1.08,
|
| 704 |
+
max_speed_factor: float = 1.6,
|
| 705 |
+
native_speed_cap: float = 2.0,
|
| 706 |
+
num_step: int = 32,
|
| 707 |
+
class_temperature: float = DEFAULT_CLASS_TEMPERATURE,
|
| 708 |
+
guidance_scale: float = DEFAULT_GUIDANCE_SCALE,
|
| 709 |
+
skip_existing: bool = False,
|
| 710 |
+
from_cue: Optional[int] = None,
|
| 711 |
+
to_cue: Optional[int] = None,
|
| 712 |
+
model: Optional[OmniVoice] = None,
|
| 713 |
+
prompt: Optional[VoiceClonePrompt] = None,
|
| 714 |
+
progress=None,
|
| 715 |
+
on_log: Optional[Callable[[str], None]] = None,
|
| 716 |
+
) -> dict:
|
| 717 |
+
if speed_mode == "gentle" and gentle_threshold <= 1.0:
|
| 718 |
+
raise ValueError("--gentle-threshold phải lớn hơn 1.0")
|
| 719 |
+
|
| 720 |
+
profile = load_profile(profile_path)
|
| 721 |
+
if model is None:
|
| 722 |
+
model = load_model(profile)
|
| 723 |
+
if prompt is None:
|
| 724 |
+
prompt = ensure_voice_prompt(model, profile)
|
| 725 |
+
|
| 726 |
+
srt_path = Path(srt_path)
|
| 727 |
+
content = srt_path.read_text(encoding="utf-8")
|
| 728 |
+
cues = parse_srt(content)
|
| 729 |
+
if not cues:
|
| 730 |
+
raise ValueError("Không đọc được cue nào từ file SRT.")
|
| 731 |
+
|
| 732 |
+
if from_cue is not None:
|
| 733 |
+
cues = [c for c in cues if c.index >= from_cue]
|
| 734 |
+
if to_cue is not None:
|
| 735 |
+
cues = [c for c in cues if c.index <= to_cue]
|
| 736 |
+
if not cues:
|
| 737 |
+
raise ValueError("Không còn cue nào sau khi lọc from/to.")
|
| 738 |
+
|
| 739 |
+
if output_dir:
|
| 740 |
+
output_dir = Path(output_dir)
|
| 741 |
+
else:
|
| 742 |
+
output_dir = default_output_dir(profile, srt_path.stem)
|
| 743 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 744 |
+
|
| 745 |
+
wav_paths: List[Path] = []
|
| 746 |
+
segments: List[np.ndarray] = []
|
| 747 |
+
fit_metas: List[dict] = []
|
| 748 |
+
log_lines: List[str] = []
|
| 749 |
+
generated = 0
|
| 750 |
+
skipped = 0
|
| 751 |
+
speed_fitted_count = 0
|
| 752 |
+
speed_skipped_count = 0
|
| 753 |
+
merged_path: Optional[Path] = None
|
| 754 |
+
total = len(cues)
|
| 755 |
+
_pipe_log(log_lines, f"Bắt đầu: {total} cue | chế độ ghép: {merge_mode}", on_log)
|
| 756 |
+
|
| 757 |
+
for idx, cue in enumerate(cues):
|
| 758 |
+
if progress is not None:
|
| 759 |
+
progress(idx / max(total, 1), desc=f"Cue {cue.index}/{total}")
|
| 760 |
+
|
| 761 |
+
wav_path = output_dir / f"{cue.index:04d}.wav"
|
| 762 |
+
slot_sec = max(0.0, cue.end_sec - cue.start_sec)
|
| 763 |
+
|
| 764 |
+
if skip_existing and wav_path.exists():
|
| 765 |
+
audio, sr = sf.read(wav_path, dtype="float32")
|
| 766 |
+
if audio.ndim > 1:
|
| 767 |
+
audio = audio.mean(axis=1)
|
| 768 |
+
audio_sec = len(audio) / sr
|
| 769 |
+
segments.append(audio)
|
| 770 |
+
wav_paths.append(wav_path)
|
| 771 |
+
fit_metas.append(
|
| 772 |
+
{
|
| 773 |
+
"generated_sec": round(audio_sec, 3),
|
| 774 |
+
"audio_sec": round(audio_sec, 3),
|
| 775 |
+
"slot_sec": round(slot_sec, 3),
|
| 776 |
+
"required_speed_factor": 1.0,
|
| 777 |
+
"speed_factor": 1.0,
|
| 778 |
+
"speed_mode": speed_mode,
|
| 779 |
+
"gentle_threshold": round(gentle_threshold, 3),
|
| 780 |
+
"speed_fitted": False,
|
| 781 |
+
"speed_skipped": False,
|
| 782 |
+
"speed_skip_reason": None,
|
| 783 |
+
}
|
| 784 |
+
)
|
| 785 |
+
skipped += 1
|
| 786 |
+
_pipe_log(log_lines, f"[skip] Cue {cue.index}: {wav_path.name}", on_log)
|
| 787 |
+
if progress is not None:
|
| 788 |
+
progress((idx + 1) / max(total, 1), desc=f"Xong cue {cue.index}/{total}")
|
| 789 |
+
continue
|
| 790 |
+
|
| 791 |
+
_pipe_log(log_lines, f"[gen] Cue {cue.index} ({slot_sec:.1f}s): {cue.text[:50]}...", on_log)
|
| 792 |
+
|
| 793 |
+
native_meta: Optional[dict] = None
|
| 794 |
+
gen_duration: Optional[float] = None
|
| 795 |
+
if merge_mode == "native":
|
| 796 |
+
# Ngân sách = thời gian tới khi cue kế bắt đầu (slot + khoảng lặng sau).
|
| 797 |
+
if idx + 1 < total:
|
| 798 |
+
budget = max(0.05, cues[idx + 1].start_sec - cue.start_sec)
|
| 799 |
+
else:
|
| 800 |
+
budget = None
|
| 801 |
+
if budget is not None and budget > 0:
|
| 802 |
+
# Chừa biên an toàn nhỏ để phần đệm fade/pad ở đuôi không đè
|
| 803 |
+
# sang cue sau (tránh cảm giác mất chữ/đè đuôi).
|
| 804 |
+
fit_target = max(0.1, budget - 0.12)
|
| 805 |
+
natural_sec = estimate_natural_duration_sec(model, prompt, cue.text)
|
| 806 |
+
if natural_sec > fit_target + 1e-3:
|
| 807 |
+
# Ép native vừa khít, không vượt trần tốc độ.
|
| 808 |
+
gen_duration = round(
|
| 809 |
+
max(fit_target, natural_sec / native_speed_cap), 3
|
| 810 |
+
)
|
| 811 |
+
native_meta = {
|
| 812 |
+
"natural_sec": round(natural_sec, 3),
|
| 813 |
+
"budget_sec": round(budget, 3),
|
| 814 |
+
"native_duration_sec": gen_duration,
|
| 815 |
+
"native_speed_factor": round(
|
| 816 |
+
natural_sec / gen_duration, 3
|
| 817 |
+
)
|
| 818 |
+
if gen_duration
|
| 819 |
+
else 1.0,
|
| 820 |
+
"native_capped": natural_sec / native_speed_cap
|
| 821 |
+
> fit_target + 1e-3,
|
| 822 |
+
}
|
| 823 |
+
|
| 824 |
+
synth_kwargs = dict(
|
| 825 |
+
num_step=num_step,
|
| 826 |
+
class_temperature=class_temperature,
|
| 827 |
+
guidance_scale=guidance_scale,
|
| 828 |
+
)
|
| 829 |
+
if gen_duration is not None:
|
| 830 |
+
synth_kwargs["duration"] = gen_duration
|
| 831 |
+
|
| 832 |
+
audio = synthesize(
|
| 833 |
+
model,
|
| 834 |
+
prompt,
|
| 835 |
+
cue.text,
|
| 836 |
+
profile["language"],
|
| 837 |
+
**synth_kwargs,
|
| 838 |
+
)
|
| 839 |
+
|
| 840 |
+
if merge_mode == "native":
|
| 841 |
+
audio_sec = len(audio) / model.sampling_rate
|
| 842 |
+
fit_meta = {
|
| 843 |
+
"generated_sec": round(audio_sec, 3),
|
| 844 |
+
"audio_sec": round(audio_sec, 3),
|
| 845 |
+
"slot_sec": round(slot_sec, 3),
|
| 846 |
+
"required_speed_factor": 1.0,
|
| 847 |
+
"speed_factor": 1.0,
|
| 848 |
+
"speed_mode": "native",
|
| 849 |
+
"gentle_threshold": round(gentle_threshold, 3),
|
| 850 |
+
"speed_fitted": gen_duration is not None,
|
| 851 |
+
"speed_skipped": False,
|
| 852 |
+
"speed_skip_reason": None,
|
| 853 |
+
}
|
| 854 |
+
if native_meta is not None:
|
| 855 |
+
fit_meta.update(native_meta)
|
| 856 |
+
speed_fitted_count += 1
|
| 857 |
+
if native_meta.get("native_capped"):
|
| 858 |
+
_pipe_log(
|
| 859 |
+
log_lines,
|
| 860 |
+
f" Cue {cue.index}: native {native_meta['natural_sec']}s "
|
| 861 |
+
f"-> {native_meta['native_duration_sec']}s "
|
| 862 |
+
f"(x{native_meta['native_speed_factor']}, chạm trần - tràn nhẹ)",
|
| 863 |
+
on_log,
|
| 864 |
+
)
|
| 865 |
+
elif slot_sec > 0 and merge_mode != "fit":
|
| 866 |
+
audio, fit_meta = apply_speed_policy(
|
| 867 |
+
audio,
|
| 868 |
+
model.sampling_rate,
|
| 869 |
+
slot_sec,
|
| 870 |
+
speed_mode=speed_mode,
|
| 871 |
+
gentle_threshold=gentle_threshold,
|
| 872 |
+
)
|
| 873 |
+
if fit_meta["speed_fitted"]:
|
| 874 |
+
speed_fitted_count += 1
|
| 875 |
+
if fit_meta.get("speed_skipped"):
|
| 876 |
+
speed_skipped_count += 1
|
| 877 |
+
else:
|
| 878 |
+
audio_sec = len(audio) / model.sampling_rate
|
| 879 |
+
fit_meta = {
|
| 880 |
+
"generated_sec": round(audio_sec, 3),
|
| 881 |
+
"audio_sec": round(audio_sec, 3),
|
| 882 |
+
"slot_sec": round(slot_sec, 3),
|
| 883 |
+
"required_speed_factor": 1.0,
|
| 884 |
+
"speed_factor": 1.0,
|
| 885 |
+
"speed_mode": speed_mode,
|
| 886 |
+
"gentle_threshold": round(gentle_threshold, 3),
|
| 887 |
+
"speed_fitted": False,
|
| 888 |
+
"speed_skipped": False,
|
| 889 |
+
"speed_skip_reason": None,
|
| 890 |
+
}
|
| 891 |
+
|
| 892 |
+
sf.write(wav_path, audio, model.sampling_rate)
|
| 893 |
+
wav_paths.append(wav_path)
|
| 894 |
+
segments.append(audio)
|
| 895 |
+
fit_metas.append(fit_meta)
|
| 896 |
+
generated += 1
|
| 897 |
+
if progress is not None:
|
| 898 |
+
progress((idx + 1) / max(total, 1), desc=f"Xong cue {cue.index}/{total}")
|
| 899 |
+
|
| 900 |
+
if progress is not None:
|
| 901 |
+
progress(0.9, desc="Đang canh giờ & ghi manifest")
|
| 902 |
+
fitted_segments: Optional[List[np.ndarray]] = None
|
| 903 |
+
if merge_mode == "native":
|
| 904 |
+
placements = plan_native_placements(cues, segments, model.sampling_rate)
|
| 905 |
+
elif merge_mode == "cascade":
|
| 906 |
+
placements = plan_cascade_placements(cues, segments, model.sampling_rate)
|
| 907 |
+
elif merge_mode == "fit":
|
| 908 |
+
placements, fitted_segments = plan_fit_placements(
|
| 909 |
+
cues, segments, model.sampling_rate, max_speed_factor=max_speed_factor
|
| 910 |
+
)
|
| 911 |
+
else:
|
| 912 |
+
placements = [
|
| 913 |
+
{
|
| 914 |
+
"actual_start_sec": round(cue.start_sec, 3),
|
| 915 |
+
"actual_end_sec": round(
|
| 916 |
+
cue.start_sec + len(audio) / model.sampling_rate, 3
|
| 917 |
+
),
|
| 918 |
+
"overflow_sec": 0.0,
|
| 919 |
+
"pushed_by_previous": False,
|
| 920 |
+
}
|
| 921 |
+
for cue, audio in zip(cues, segments)
|
| 922 |
+
]
|
| 923 |
+
|
| 924 |
+
overflow_count = sum(1 for p in placements if p["overflow_sec"] > 0)
|
| 925 |
+
pushed_count = sum(1 for p in placements if p["pushed_by_previous"])
|
| 926 |
+
fit_count = sum(1 for p in placements if p.get("fit_applied"))
|
| 927 |
+
capped_count = sum(1 for p in placements if p.get("fit_capped"))
|
| 928 |
+
|
| 929 |
+
for fit_meta, placement in zip(fit_metas, placements):
|
| 930 |
+
fit_meta.update(placement)
|
| 931 |
+
|
| 932 |
+
manifest = output_dir / "manifest.json"
|
| 933 |
+
write_manifest(
|
| 934 |
+
manifest,
|
| 935 |
+
cues,
|
| 936 |
+
wav_paths,
|
| 937 |
+
fit_metas,
|
| 938 |
+
model.sampling_rate,
|
| 939 |
+
profile,
|
| 940 |
+
srt_path,
|
| 941 |
+
merge_mode,
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
shifted_srt = output_dir / f"{srt_path.stem}_shifted.srt"
|
| 945 |
+
write_shifted_srt(shifted_srt, cues, placements)
|
| 946 |
+
|
| 947 |
+
if merge_mode == "fit":
|
| 948 |
+
summary = (
|
| 949 |
+
f"Hoàn tất [{profile['slug']}] (fit): {generated} cue mới, "
|
| 950 |
+
f"{fit_count} cue tăng tốc khớp giờ ({capped_count} chạm trần, tràn nhẹ), "
|
| 951 |
+
f"{skipped} bỏ qua"
|
| 952 |
+
)
|
| 953 |
+
elif merge_mode == "native":
|
| 954 |
+
native_capped = sum(1 for m in fit_metas if m.get("native_capped"))
|
| 955 |
+
summary = (
|
| 956 |
+
f"Hoàn tất [{profile['slug']}] (native): {generated} cue mới, "
|
| 957 |
+
f"{speed_fitted_count} cue nói nhanh native cho vừa khung "
|
| 958 |
+
f"({native_capped} câu chạm trần x{native_speed_cap}, còn vượt khung; "
|
| 959 |
+
f"neo cứng SRT - không cộng dồn lệch), {skipped} bỏ qua"
|
| 960 |
+
)
|
| 961 |
+
else:
|
| 962 |
+
summary = (
|
| 963 |
+
f"Hoàn tất [{profile['slug']}] ({merge_mode}): {generated} cue mới, "
|
| 964 |
+
f"{overflow_count} tràn, {pushed_count} đẩy, {speed_fitted_count} tăng tốc nhẹ, "
|
| 965 |
+
f"{speed_skipped_count} giữ giọng, {skipped} bỏ qua"
|
| 966 |
+
)
|
| 967 |
+
for line in (
|
| 968 |
+
summary,
|
| 969 |
+
f"Output: {output_dir}",
|
| 970 |
+
f"Manifest: {manifest}",
|
| 971 |
+
f"Shifted SRT: {shifted_srt}",
|
| 972 |
+
):
|
| 973 |
+
_pipe_log(log_lines, line, on_log)
|
| 974 |
+
|
| 975 |
+
if merge:
|
| 976 |
+
if progress is not None:
|
| 977 |
+
progress(0.95, desc="Đang ghép file WAV")
|
| 978 |
+
_pipe_log(log_lines, "Đang ghép file WAV...", on_log)
|
| 979 |
+
if merge_mode in ("cascade", "native"):
|
| 980 |
+
merged = merge_timeline_cascade(
|
| 981 |
+
placements, segments, model.sampling_rate
|
| 982 |
+
)
|
| 983 |
+
elif merge_mode == "fit":
|
| 984 |
+
merged = merge_timeline_fit(
|
| 985 |
+
placements, fitted_segments or segments, model.sampling_rate
|
| 986 |
+
)
|
| 987 |
+
else:
|
| 988 |
+
merged = merge_timeline_strict(cues, segments, model.sampling_rate)
|
| 989 |
+
merge_out = (
|
| 990 |
+
Path(merge_output)
|
| 991 |
+
if merge_output
|
| 992 |
+
else output_dir / f"{srt_path.stem}_merged.wav"
|
| 993 |
+
)
|
| 994 |
+
merge_out.parent.mkdir(parents=True, exist_ok=True)
|
| 995 |
+
sf.write(merge_out, merged, model.sampling_rate)
|
| 996 |
+
merged_path = merge_out
|
| 997 |
+
_pipe_log(log_lines, f"Merged WAV: {merge_out}", on_log)
|
| 998 |
+
|
| 999 |
+
if progress is not None:
|
| 1000 |
+
progress(1.0, desc="Hoàn tất")
|
| 1001 |
+
|
| 1002 |
+
return {
|
| 1003 |
+
"output_dir": str(output_dir),
|
| 1004 |
+
"manifest": str(manifest),
|
| 1005 |
+
"shifted_srt": str(shifted_srt),
|
| 1006 |
+
"merged_wav": str(merged_path) if merged_path else None,
|
| 1007 |
+
"sample_rate": model.sampling_rate,
|
| 1008 |
+
"stats": {
|
| 1009 |
+
"generated": generated,
|
| 1010 |
+
"overflow": overflow_count,
|
| 1011 |
+
"pushed": pushed_count,
|
| 1012 |
+
"speed_fitted": speed_fitted_count,
|
| 1013 |
+
"speed_skipped": speed_skipped_count,
|
| 1014 |
+
"skipped": skipped,
|
| 1015 |
+
},
|
| 1016 |
+
"log": "\n".join(log_lines),
|
| 1017 |
+
}
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
def cmd_srt(args: argparse.Namespace) -> None:
|
| 1021 |
+
result = run_srt_pipeline(
|
| 1022 |
+
Path(args.profile),
|
| 1023 |
+
Path(args.input),
|
| 1024 |
+
output_dir=Path(args.output_dir) if args.output_dir else None,
|
| 1025 |
+
merge=args.merge,
|
| 1026 |
+
merge_output=Path(args.output) if args.output else None,
|
| 1027 |
+
merge_mode=args.merge_mode,
|
| 1028 |
+
speed_mode=args.speed_mode,
|
| 1029 |
+
gentle_threshold=args.gentle_threshold,
|
| 1030 |
+
max_speed_factor=args.max_speed_factor,
|
| 1031 |
+
native_speed_cap=args.native_speed_cap,
|
| 1032 |
+
num_step=args.num_step,
|
| 1033 |
+
class_temperature=args.class_temperature,
|
| 1034 |
+
guidance_scale=args.guidance_scale,
|
| 1035 |
+
skip_existing=args.skip_existing,
|
| 1036 |
+
from_cue=args.from_cue,
|
| 1037 |
+
to_cue=args.to_cue,
|
| 1038 |
+
)
|
| 1039 |
+
print(result["log"])
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
def get_parser() -> argparse.ArgumentParser:
|
| 1043 |
+
parser = argparse.ArgumentParser(
|
| 1044 |
+
description="Đọc văn bản/SRT bằng voice profile trong voices/",
|
| 1045 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 1046 |
+
)
|
| 1047 |
+
parser.add_argument(
|
| 1048 |
+
"--profile",
|
| 1049 |
+
type=str,
|
| 1050 |
+
default=str(DEFAULT_PROFILE),
|
| 1051 |
+
help="Đường dẫn profile.json",
|
| 1052 |
+
)
|
| 1053 |
+
parser.add_argument(
|
| 1054 |
+
"--num-step",
|
| 1055 |
+
type=int,
|
| 1056 |
+
default=32,
|
| 1057 |
+
help="Số bước diffusion (16 = nhanh hơn, 32 = chất lượng cao hơn)",
|
| 1058 |
+
)
|
| 1059 |
+
parser.add_argument(
|
| 1060 |
+
"--class-temperature",
|
| 1061 |
+
type=float,
|
| 1062 |
+
default=DEFAULT_CLASS_TEMPERATURE,
|
| 1063 |
+
help="Độ biểu cảm: nhiệt độ lấy mẫu token. 0 = đều/máy móc (greedy), "
|
| 1064 |
+
"0.7-0.9 = nhấn nhá tự nhiên, >1.0 = ngẫu hứng mạnh hơn",
|
| 1065 |
+
)
|
| 1066 |
+
parser.add_argument(
|
| 1067 |
+
"--guidance-scale",
|
| 1068 |
+
type=float,
|
| 1069 |
+
default=DEFAULT_GUIDANCE_SCALE,
|
| 1070 |
+
help="Mức bám giọng mẫu (CFG). Cao hơn = rõ/chắc giọng, thấp hơn = mềm hơn",
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 1074 |
+
|
| 1075 |
+
p_voices = sub.add_parser("voices", help="Liệt kê các giọng có sẵn")
|
| 1076 |
+
p_voices.set_defaults(func=cmd_voices)
|
| 1077 |
+
|
| 1078 |
+
p_build = sub.add_parser("build", help="Tạo file voice.pt từ audio mẫu")
|
| 1079 |
+
p_build.set_defaults(func=cmd_build)
|
| 1080 |
+
|
| 1081 |
+
p_text = sub.add_parser("text", help="Đọc một đoạn văn bản")
|
| 1082 |
+
p_text.add_argument("--text", required=True)
|
| 1083 |
+
p_text.add_argument("-o", "--output", required=True)
|
| 1084 |
+
p_text.set_defaults(func=cmd_text)
|
| 1085 |
+
|
| 1086 |
+
p_file = sub.add_parser("file", help="Đọc cả file .txt")
|
| 1087 |
+
p_file.add_argument("--input", required=True)
|
| 1088 |
+
p_file.add_argument("-o", "--output", required=True)
|
| 1089 |
+
p_file.set_defaults(func=cmd_file)
|
| 1090 |
+
|
| 1091 |
+
p_srt = sub.add_parser("srt", help="Đọc file phụ đề .srt")
|
| 1092 |
+
p_srt.add_argument("--input", required=True)
|
| 1093 |
+
p_srt.add_argument(
|
| 1094 |
+
"--output-dir",
|
| 1095 |
+
type=str,
|
| 1096 |
+
default=None,
|
| 1097 |
+
help="Thư mục lưu từng cue. Mặc định: output/<voice>/<ten_srt>/",
|
| 1098 |
+
)
|
| 1099 |
+
p_srt.add_argument(
|
| 1100 |
+
"-o",
|
| 1101 |
+
"--output",
|
| 1102 |
+
type=str,
|
| 1103 |
+
default=None,
|
| 1104 |
+
help="File WAV gộp khi dùng --merge",
|
| 1105 |
+
)
|
| 1106 |
+
p_srt.add_argument(
|
| 1107 |
+
"--merge",
|
| 1108 |
+
action="store_true",
|
| 1109 |
+
help="Gộp các cue thành 1 file WAV",
|
| 1110 |
+
)
|
| 1111 |
+
p_srt.add_argument(
|
| 1112 |
+
"--merge-mode",
|
| 1113 |
+
choices=["native", "fit", "cascade", "strict"],
|
| 1114 |
+
default="native",
|
| 1115 |
+
help="native: model nói nhanh native (giữ nhấn nhá) có trần tốc độ, "
|
| 1116 |
+
"phần dư tràn nhẹ/cascade - khuyến nghị cho lồng tiếng; "
|
| 1117 |
+
"fit: sinh dài rồi kéo nén tín hiệu vừa khung SRT (khít giờ, dễ mất nhấn nhá); "
|
| 1118 |
+
"cascade: cue dài tràn/đẩy cue sau (giữ chất giọng, lệch SRT); "
|
| 1119 |
+
"strict: ghép theo timestamp gốc (có thể cắt audio)",
|
| 1120 |
+
)
|
| 1121 |
+
p_srt.add_argument(
|
| 1122 |
+
"--speed-mode",
|
| 1123 |
+
choices=["off", "gentle", "force"],
|
| 1124 |
+
default="off",
|
| 1125 |
+
help="off: giữ giọng, tràn cascade (mặc định); "
|
| 1126 |
+
"gentle: chỉ tăng tốc nhẹ khi hơn slot <= gentle-threshold; "
|
| 1127 |
+
"force: ép vừa slot (có thể méo giọng)",
|
| 1128 |
+
)
|
| 1129 |
+
p_srt.add_argument(
|
| 1130 |
+
"--gentle-threshold",
|
| 1131 |
+
type=float,
|
| 1132 |
+
default=1.08,
|
| 1133 |
+
help="Với gentle: chỉ tăng tốc nếu cần <= hệ số này (vd. 1.08 = 8%%)",
|
| 1134 |
+
)
|
| 1135 |
+
p_srt.add_argument(
|
| 1136 |
+
"--max-speed-factor",
|
| 1137 |
+
type=float,
|
| 1138 |
+
default=1.6,
|
| 1139 |
+
help="Với fit: trần tăng tốc 1 câu để giữ giọng tự nhiên (vd. 1.6 = 60%%). "
|
| 1140 |
+
"Câu cần hơn trần sẽ tràn nhẹ và tự khớp lại sau",
|
| 1141 |
+
)
|
| 1142 |
+
p_srt.add_argument(
|
| 1143 |
+
"--native-speed-cap",
|
| 1144 |
+
type=float,
|
| 1145 |
+
default=2.0,
|
| 1146 |
+
help="Với native: trần tốc độ nói native để chứa hết chữ trong khung "
|
| 1147 |
+
"(vd. 2.0 = nói nhanh tối đa gấp đôi). Cao hơn = chắc chắn đủ chữ nhưng "
|
| 1148 |
+
"câu dài nói nhanh hơn; thấp hơn = giữ nhấn nhá nhưng câu rất dài có thể "
|
| 1149 |
+
"vẫn vượt khung",
|
| 1150 |
+
)
|
| 1151 |
+
p_srt.add_argument(
|
| 1152 |
+
"--skip-existing",
|
| 1153 |
+
action="store_true",
|
| 1154 |
+
help="Bỏ qua cue đã có file WAV (tiếp tục job dở)",
|
| 1155 |
+
)
|
| 1156 |
+
p_srt.add_argument("--from-cue", type=int, default=None, help="Cue bắt đầu")
|
| 1157 |
+
p_srt.add_argument("--to-cue", type=int, default=None, help="Cue kết thúc")
|
| 1158 |
+
p_srt.set_defaults(func=cmd_srt)
|
| 1159 |
+
|
| 1160 |
+
return parser
|
| 1161 |
+
|
| 1162 |
+
|
| 1163 |
+
def _force_utf8_stdio() -> None:
|
| 1164 |
+
"""Tránh UnicodeEncodeError khi in tiếng Việt trên console Windows (cp1252)."""
|
| 1165 |
+
for stream in (sys.stdout, sys.stderr):
|
| 1166 |
+
if stream is None:
|
| 1167 |
+
continue
|
| 1168 |
+
reconfigure = getattr(stream, "reconfigure", None)
|
| 1169 |
+
if reconfigure is not None:
|
| 1170 |
+
try:
|
| 1171 |
+
reconfigure(encoding="utf-8", errors="replace")
|
| 1172 |
+
except (ValueError, OSError, AttributeError):
|
| 1173 |
+
pass
|
| 1174 |
+
|
| 1175 |
+
|
| 1176 |
+
class _SafeLogHandler(logging.StreamHandler):
|
| 1177 |
+
"""Handler log không crash khi console Windows không hỗ trợ Unicode."""
|
| 1178 |
+
|
| 1179 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 1180 |
+
try:
|
| 1181 |
+
super().emit(record)
|
| 1182 |
+
except UnicodeEncodeError:
|
| 1183 |
+
record.msg = str(record.getMessage()).encode("ascii", errors="replace").decode("ascii")
|
| 1184 |
+
record.args = ()
|
| 1185 |
+
super().emit(record)
|
| 1186 |
+
|
| 1187 |
+
|
| 1188 |
+
def _setup_logging() -> None:
|
| 1189 |
+
_force_utf8_stdio()
|
| 1190 |
+
root = logging.getLogger()
|
| 1191 |
+
if root.handlers:
|
| 1192 |
+
return
|
| 1193 |
+
handler = _SafeLogHandler()
|
| 1194 |
+
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
|
| 1195 |
+
root.addHandler(handler)
|
| 1196 |
+
root.setLevel(logging.INFO)
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
def main() -> None:
|
| 1200 |
+
_setup_logging()
|
| 1201 |
+
parser = get_parser()
|
| 1202 |
+
args = parser.parse_args()
|
| 1203 |
+
args.func(args)
|
| 1204 |
+
|
| 1205 |
+
|
| 1206 |
+
if __name__ == "__main__":
|
| 1207 |
+
main()
|
| 1208 |
+
else:
|
| 1209 |
+
_setup_logging()
|
voices/ban_mai/profile.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Ban Mai",
|
| 3 |
+
"language": "Vietnamese",
|
| 4 |
+
"ref_audio": "ref.mp3",
|
| 5 |
+
"ref_text_file": "ref_text.txt",
|
| 6 |
+
"voice_prompt": "voice.pt",
|
| 7 |
+
"model": "k2-fsa/OmniVoice",
|
| 8 |
+
"device": "cuda:0",
|
| 9 |
+
"preprocess_prompt": false,
|
| 10 |
+
"auto_transcribe": true
|
| 11 |
+
}
|
voices/ban_mai/ref.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c3774c27143f771951697874889027695ae05ad8d6a88a8e5500ba589d3392e6
|
| 3 |
+
size 123830
|
voices/ban_mai/ref_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Capybara, còn được gọi là chuột lang nước, được mệnh danh là Bộ trưởng Bộ Ngoại giao trong thế giới động vật vì tính cách hiền lành, thân thiện và khả năng hòa đồng. Chúng thường sống hòa bình với các loài động vật khác, kể cả những loài săn mồi, và được yêu thích bởi sự gần gũi, thân thiện với con người.
|
voices/ban_mai/ref_text_asr.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Capybara, còn được gọi là chuột lang nước, được mệnh danh là Bộ trưởng Bộ Ngoại giao trong thế giới động vật vì tính cách hiền lành, thân thiện và khả năng hòa đồng. Chúng thường sống hòa bình với các loài động vật khác, kể cả những loài săn mồi, và được yêu thích bởi sự gần gũi, thân thiện với con người.
|
voices/ban_mai/voice.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:35009a3ebca2fa59e7082177f4b8ab9ff8fa0cbcd44c952b03cfd2dfd9e2d139
|
| 3 |
+
size 27547
|
voices/lan_trinh/profile.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Lan Trinh",
|
| 3 |
+
"language": "Vietnamese",
|
| 4 |
+
"ref_audio": "ref.wav",
|
| 5 |
+
"ref_text_file": "ref_text.txt",
|
| 6 |
+
"voice_prompt": "voice.pt",
|
| 7 |
+
"model": "k2-fsa/OmniVoice",
|
| 8 |
+
"device": "cuda:0",
|
| 9 |
+
"preprocess_prompt": false,
|
| 10 |
+
"auto_transcribe": false
|
| 11 |
+
}
|
voices/lan_trinh/ref.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5369ba15dc222cd390d4d9f6db1253cd17ae3d9c60d3e5068484c1d4aba6af4b
|
| 3 |
+
size 2719822
|
voices/lan_trinh/ref_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Tức chết được, tức chết được. Vì tên và chuyên ngành y hệt nên mình mới đọc cuốn tiểu thuyết này. Nhân vật này đúng là làm mất mặt sinh viên ngành y. Yêu đương mù quáng, tỉnh lại đi. Bạch Khê à, Cố Thanh Diên là bạn học của con, vậy mối hôn sự này mẹ cả quyết định cho con
|
voices/lan_trinh/voice.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1979379e5b32997011db6078f9f6cc22195db7c81bba92d5d777896086de481c
|
| 3 |
+
size 26587
|
voices/ngan_ha/profile.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Ngân Hà",
|
| 3 |
+
"language": "Vietnamese",
|
| 4 |
+
"ref_audio": "ref.wav",
|
| 5 |
+
"ref_text_file": "ref_text.txt",
|
| 6 |
+
"voice_prompt": "voice.pt",
|
| 7 |
+
"model": "k2-fsa/OmniVoice",
|
| 8 |
+
"device": "cuda:0",
|
| 9 |
+
"preprocess_prompt": false,
|
| 10 |
+
"auto_transcribe": false
|
| 11 |
+
}
|
voices/ngan_ha/ref.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1b11d5aacdc4797fd90162f1283c4721e8caca814b4ee285db20bf8f72ef45da
|
| 3 |
+
size 370987
|
voices/ngan_ha/ref_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Tên hôn quân vô sĩ kia, sao dám nhìn lén bổn hậu tắm rữa! Chẳng phải ta đang ở biên cảnh làm nhiệm vụ bí mật sao? Chỉ chợp mắt một lát sao lại biến thành nông nổi này? Ta vậy mà lại xuyên không thành hoàng đế Đại Chu! Tên Hoàng Đế này chỉ là bù nhìn
|
voices/ngan_ha/voice.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:311b4f4c42c19e466eb0592c5cd40ac6edee5e710caef699763accd85bd52f87
|
| 3 |
+
size 24347
|
voices/ngoc_huyen/profile.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Ngoc Huyen",
|
| 3 |
+
"language": "Vietnamese",
|
| 4 |
+
"ref_audio": "ref.mp3",
|
| 5 |
+
"ref_text_file": "ref_text.txt",
|
| 6 |
+
"voice_prompt": "voice.pt",
|
| 7 |
+
"model": "k2-fsa/OmniVoice",
|
| 8 |
+
"device": "cuda:0"
|
| 9 |
+
}
|
voices/ngoc_huyen/ref.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8a4628b205482f448499847bae3c2697a3f3c97be97b27e470cf670db3ff4e57
|
| 3 |
+
size 254162
|
voices/ngoc_huyen/ref_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Capybara, còn được gọi là chuột lang nước, được mệnh danh là "bộ trưởng bộ ngoại giao" trong thế giới động vật vì tính cách hiền lành, thân thiện và khả năng hòa đồng. Chúng thường sống hòa bình với các loài động vật khác, kể cả những loài săn mồi, và được yêu thích bởi sự gần gũi, thân thiện với con người.
|
voices/ngoc_huyen/voice.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d851dd9360791bc49e903dd88139d7866264baa9f9be754645c9d6e85298abc5
|
| 3 |
+
size 26651
|
voices/thao_trinh/profile.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Thảo Trinh",
|
| 3 |
+
"language": "Vietnamese",
|
| 4 |
+
"ref_audio": "ref.wav",
|
| 5 |
+
"ref_text_file": "ref_text.txt",
|
| 6 |
+
"voice_prompt": "voice.pt",
|
| 7 |
+
"model": "k2-fsa/OmniVoice",
|
| 8 |
+
"device": "cuda:0",
|
| 9 |
+
"preprocess_prompt": false,
|
| 10 |
+
"auto_transcribe": false
|
| 11 |
+
}
|
voices/thao_trinh/ref.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53c73596dbcf9edea22bee79485cc14bcc8c22764ee4a35be17436f8b3dc5b0f
|
| 3 |
+
size 2670670
|
voices/thao_trinh/ref_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Liên quan gì đến ngươi và Viện Thanh Sơn của ngươi, Gia Cát Nguyệt! Từ nay, chúng ta không còn tình nghĩa, chỉ như người lạ. Yến Trung cho rằng mọi việc đều do Viện Thanh Sơn làm, hoàn toàn trở mặt với ta. Tinh Nhi gây dựng lại quân Tú Lệ, trợ giúp Yến Trung chạy về Yến Bắc.
|
voices/thao_trinh/voice.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e563eea443a5ac86ea9d9d7a8d2f9b283a1828974e2ff48559426677cac0399a
|
| 3 |
+
size 26139
|
voices/tuong_vy/profile.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "Tường Vy",
|
| 3 |
+
"language": "Vietnamese",
|
| 4 |
+
"ref_audio": "ref.wav",
|
| 5 |
+
"ref_text_file": "ref_text.txt",
|
| 6 |
+
"voice_prompt": "voice.pt",
|
| 7 |
+
"model": "k2-fsa/OmniVoice",
|
| 8 |
+
"device": "cuda:0",
|
| 9 |
+
"preprocess_prompt": false,
|
| 10 |
+
"auto_transcribe": false
|
| 11 |
+
}
|
voices/tuong_vy/ref.wav
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4f4c2d8e0fadb33d3dce0e46bbaa58303676cb56b83b1c3761b8d41fd053ad7f
|
| 3 |
+
size 372164
|
voices/tuong_vy/ref_text.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Mau mau xem mau. Nghe nói Thất công chúa đến đây để hủy hôn với thế tử, Trấn Bắc Vương. Không phải chứ? Cha hắn, Trấn Bắc Vương chẳng phải mới tử trận nơi biên cương sao? Nghe nói tên đó ngoài việc lêu lổng thanh lâu thì chẳng biết làm gì. Nếu là ta thì ta cũng hủy hôn
|
voices/tuong_vy/voice.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6e3bec906d12cf9d1012e8e8bd749f36056989ef868bb50f8b292f4520dba1bf
|
| 3 |
+
size 22747
|