STBack23 commited on
Commit
93a90eb
·
verified ·
1 Parent(s): e2ad17e

Update OmniVoice VI voices + Colab tools

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