Datasets:
Upload folder using huggingface_hub
Browse files
README.md
CHANGED
|
@@ -176,40 +176,35 @@ Dataset đi kèm 2 công cụ Python chuyên dụng cho kỹ sư TTS, hỗ trợ
|
|
| 176 |
|
| 177 |
---
|
| 178 |
|
| 179 |
-
### B. `split.py` — Công cụ trích xuất Sub-dataset theo thời lượng thực tế
|
| 180 |
|
| 181 |
- **Tác dụng**:
|
| 182 |
-
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
-
|
| 186 |
-
|
| 187 |
-
- **30%** câu 2 đến 5 tiếng
|
| 188 |
-
- **50%** câu dài hơn 5 tiếng (> 5 tiếng)
|
| 189 |
-
- **Đổi tên file liên tục tuyệt đối**: Đánh số tuần tự từ `audio_0001.wav` đến hết, đồng bộ vào `metadata.csv` mới, không bị nhảy cóc số (1, 2, 3, 4...).
|
| 190 |
- Tốc độ sao chép cực nhanh nhờ xử lý đa luồng (`ThreadPoolExecutor`).
|
| 191 |
|
| 192 |
- **Cú pháp**:
|
| 193 |
```bash
|
| 194 |
-
python split.py [folder] [time]
|
| 195 |
```
|
| 196 |
|
| 197 |
- **Cách sử dụng**:
|
| 198 |
```bash
|
| 199 |
-
# 1.
|
| 200 |
-
python split.py
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
python split.py ReviewNew 300m
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
# 5. Chỉ định thư mục đầu ra tùy ý với cờ --out (-o)
|
| 212 |
-
python split.py Mai 1h30m -o ./subsets/Mai_1h30m
|
| 213 |
```
|
| 214 |
|
| 215 |
---
|
|
|
|
| 176 |
|
| 177 |
---
|
| 178 |
|
| 179 |
+
### B. `split.py` — Công cụ trích xuất Sub-dataset theo dải câu hoặc thời lượng thực tế
|
| 180 |
|
| 181 |
- **Tác dụng**:
|
| 182 |
+
- Hỗ trợ 2 chế độ trích xuất linh hoạt:
|
| 183 |
+
1. **Theo dải số câu cụ thể (`start-end`)**: Ví dụ `1-300`, `101-500` — trích xuất chính xác dải câu tuần tự từ câu bắt đầu đến câu kết thúc, không quan tâm thời gian.
|
| 184 |
+
2. **Theo thời lượng nói thực tế (`time`)**: Ví dụ `5h6m30s`, `1h`, `300m` — tự đo sóng âm WAV (sai số < 0.5s) và phân bổ tỉ lệ câu vàng cho TTS (20% 1 tiếng, 30% 2-5 tiếng, 50% > 5 tiếng).
|
| 185 |
+
- Tự động tạo thư mục đầu ra theo cấu trúc `[folder] + [target]` (ví dụ: `Test1-300`, `Mai5h6m30s`, `HoatNgon1h`).
|
| 186 |
+
- **Đổi tên file liên tục tuyệt đối**: Đánh số tuần tự từ `audio_0001.wav` đến hết, đồng bộ vào `metadata.csv` mới, tuyệt đối không nhảy cóc số (1, 2, 3, 4...).
|
|
|
|
|
|
|
|
|
|
| 187 |
- Tốc độ sao chép cực nhanh nhờ xử lý đa luồng (`ThreadPoolExecutor`).
|
| 188 |
|
| 189 |
- **Cú pháp**:
|
| 190 |
```bash
|
| 191 |
+
python split.py [folder] [start-end | time]
|
| 192 |
```
|
| 193 |
|
| 194 |
- **Cách sử dụng**:
|
| 195 |
```bash
|
| 196 |
+
# 1. Trích xuất theo dải số câu cụ thể (không quan tâm thời gian)
|
| 197 |
+
python split.py Test 1-300 # Lấy từ câu 1 đến câu 300 -> tạo thư mục Test1-300
|
| 198 |
+
python split.py Mai 101-500 # Lấy từ câu 101 đến câu 500 -> tạo thư mục Mai101-500
|
| 199 |
+
|
| 200 |
+
# 2. Trích xuất theo thời lượng nói thực tế
|
| 201 |
+
python split.py Mai 5h6m30s # Cắt 5 giờ 6 phút 30 giây -> tạo thư mục Mai5h6m30s
|
| 202 |
+
python split.py HoatNgon 1h # Cắt 1 giờ -> tạo thư mục HoatNgon1h
|
| 203 |
+
python split.py ReviewNew 300m # Cắt 300 phút -> tạo thư mục ReviewNew300m
|
| 204 |
+
python split.py NuPhoThong 2000s # Cắt 2000 giây -> tạo thư mục NuPhoThong2000s
|
| 205 |
+
|
| 206 |
+
# 3. Chỉ định thư mục đầu ra tùy ý với cờ --out (-o)
|
| 207 |
+
python split.py Test 1-300 -o ./subsets/Test_300
|
|
|
|
|
|
|
| 208 |
```
|
| 209 |
|
| 210 |
---
|
split.py
CHANGED
|
@@ -2,26 +2,29 @@
|
|
| 2 |
"""
|
| 3 |
Dataset Split & Sub-dataset Generator for TTS
|
| 4 |
=============================================
|
| 5 |
-
Cắt trích xuất tập dữ liệu con (sub-dataset) từ dataset gốc
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
Ví dụ:
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
Đặc điểm:
|
| 15 |
-
1.
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
- 30% câu ngắn 2-5 tiếng
|
| 21 |
-
- 50% câu dài > 5 tiếng
|
| 22 |
-
(Được lấy mẫu đều toàn dải để tối đa hóa đa dạng ngữ âm và từ vựng).
|
| 23 |
-
5. Đổi tên liên tục từ audio_0001.wav đến hết và tạo file metadata.csv chuẩn LJSpeech,
|
| 24 |
tuyệt đối không nhảy cóc số thứ tự (1, 2, 3, 4...).
|
|
|
|
| 25 |
"""
|
| 26 |
|
| 27 |
import argparse
|
|
@@ -145,22 +148,22 @@ def copy_worker(task: Tuple[Path, Path]) -> None:
|
|
| 145 |
|
| 146 |
def main():
|
| 147 |
parser = argparse.ArgumentParser(
|
| 148 |
-
description="Dataset Splitter:
|
| 149 |
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 150 |
)
|
| 151 |
parser.add_argument(
|
| 152 |
"folder",
|
| 153 |
-
help="Thư mục dataset đầu vào (ví dụ: Mai, HoatNgon, E:/VieTTS/dataset/ReviewNew)",
|
| 154 |
)
|
| 155 |
parser.add_argument(
|
| 156 |
-
"
|
| 157 |
-
help="
|
| 158 |
)
|
| 159 |
parser.add_argument(
|
| 160 |
"--out",
|
| 161 |
"-o",
|
| 162 |
default=None,
|
| 163 |
-
help="Đường dẫn thư mục xuất (Mặc định: [folder_parent]/[folder][
|
| 164 |
)
|
| 165 |
parser.add_argument(
|
| 166 |
"--workers",
|
|
@@ -184,12 +187,33 @@ def main():
|
|
| 184 |
print(f"[LỖI] Thư mục '{src_folder}' không tồn tại!")
|
| 185 |
sys.exit(1)
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
# 3. Tìm metadata.csv
|
| 195 |
meta_path = find_metadata_file(src_folder)
|
|
@@ -197,22 +221,34 @@ def main():
|
|
| 197 |
print(f"[LỖI] Không tìm thấy metadata.csv trong '{src_folder}' hoặc các thư mục chuẩn!")
|
| 198 |
sys.exit(1)
|
| 199 |
|
| 200 |
-
# Đọc metadata
|
|
|
|
|
|
|
| 201 |
meta_map: Dict[str, Tuple[str, int]] = {}
|
|
|
|
| 202 |
with open(meta_path, "r", encoding="utf-8") as f:
|
| 203 |
-
|
|
|
|
| 204 |
line = line.strip()
|
| 205 |
if not line or line.startswith("#"):
|
| 206 |
continue
|
| 207 |
parts = line.split("|")
|
| 208 |
if len(parts) >= 2:
|
| 209 |
-
|
|
|
|
| 210 |
text = parts[1].strip()
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
# 4. Quét các file WAV gốc
|
| 214 |
-
|
| 215 |
-
if not
|
| 216 |
print(f"[LỖI] Không tìm thấy file WAV nào trong '{src_folder}'!")
|
| 217 |
sys.exit(1)
|
| 218 |
|
|
@@ -220,141 +256,201 @@ def main():
|
|
| 220 |
print("CÔNG CỤ TRÍCH XUẤT SUB-DATASET CHO HUẤN LUYỆN TTS")
|
| 221 |
print("=" * 80)
|
| 222 |
print(f"• Thư mục gốc : {src_folder.name} ({src_folder})")
|
| 223 |
-
print(f"• Metadata nguồn : {meta_path.name}")
|
| 224 |
-
print(f"• Số file audio gốc: {len(
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
"
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
sub_cycle_dur = 3 * d2 + 2 * d1
|
| 304 |
-
sub_cycles = rem_dur / sub_cycle_dur if sub_cycle_dur > 0 else 0
|
| 305 |
-
add2 = min(len(b2) - cnt2, int(round(sub_cycles * 3)))
|
| 306 |
-
add1 = min(len(b1) - cnt1, int(round(sub_cycles * 2)))
|
| 307 |
-
cnt2 += add2
|
| 308 |
-
cnt1 += add1
|
| 309 |
-
|
| 310 |
-
# Lấy mẫu đều dải (uniform stride) để đảm bảo độ bao phủ từ vựng tối đa
|
| 311 |
-
s3 = [b3[int(i * len(b3) / cnt3)] for i in range(cnt3)] if cnt3 > 0 else []
|
| 312 |
-
s2 = [b2[int(i * len(b2) / cnt2)] for i in range(cnt2)] if cnt2 > 0 else []
|
| 313 |
-
s1 = [b1[int(i * len(b1) / cnt1)] for i in range(cnt1)] if cnt1 > 0 else []
|
| 314 |
-
|
| 315 |
-
selected = s1 + s2 + s3
|
| 316 |
-
actual_dur = sum(x["dur"] for x in selected)
|
| 317 |
-
|
| 318 |
-
# Tinh chỉnh độ lệch thời lượng < 0.5s
|
| 319 |
-
used_paths = {x["path"] for x in selected}
|
| 320 |
-
diff = target_seconds - actual_dur
|
| 321 |
-
|
| 322 |
-
if diff > 0.3:
|
| 323 |
-
candidates = [x for x in (b3 + b2 + b1) if x["path"] not in used_paths]
|
| 324 |
-
for c in sorted(candidates, key=lambda x: x["dur"], reverse=True):
|
| 325 |
-
if actual_dur + c["dur"] <= target_seconds + 0.4:
|
| 326 |
-
selected.append(c)
|
| 327 |
-
actual_dur += c["dur"]
|
| 328 |
-
if abs(target_seconds - actual_dur) < 0.3:
|
| 329 |
-
break
|
| 330 |
-
elif diff < -0.3:
|
| 331 |
-
while actual_dur > target_seconds + 0.3 and len(selected) > 0:
|
| 332 |
-
best_idx = None
|
| 333 |
-
best_gap = abs(target_seconds - actual_dur)
|
| 334 |
-
for idx in range(len(selected) - 1, max(-1, len(selected) - 30), -1):
|
| 335 |
-
gap = abs(target_seconds - (actual_dur - selected[idx]["dur"]))
|
| 336 |
-
if gap < best_gap:
|
| 337 |
-
best_gap = gap
|
| 338 |
-
best_idx = idx
|
| 339 |
-
if best_idx is not None and best_gap < abs(target_seconds - actual_dur):
|
| 340 |
-
actual_dur -= selected[best_idx]["dur"]
|
| 341 |
-
selected.pop(best_idx)
|
| 342 |
else:
|
| 343 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
-
# Sắp xếp lại theo thứ tự ngữ nghĩa tự nhiên ban đầu của dataset gốc
|
| 346 |
-
selected.sort(key=lambda x: x["order"])
|
| 347 |
total_selected = len(selected)
|
| 348 |
|
| 349 |
-
# Thống kê phân bổ
|
| 350 |
actual_b1 = sum(1 for x in selected if x["word_count"] == 1)
|
| 351 |
actual_b2 = sum(1 for x in selected if 2 <= x["word_count"] <= 5)
|
| 352 |
actual_b3 = sum(1 for x in selected if x["word_count"] > 5)
|
| 353 |
|
| 354 |
-
#
|
| 355 |
-
# Ví dụ: Mai5h6m30s
|
| 356 |
-
|
| 357 |
-
target_folder_name = f"{src_folder.name}{time_clean}"
|
| 358 |
if args.out:
|
| 359 |
out_dir = Path(args.out).resolve()
|
| 360 |
else:
|
|
@@ -366,7 +462,6 @@ def main():
|
|
| 366 |
print("Dùng cờ '--force' hoặc '-f' nếu muốn ghi đè lên thư mục này.")
|
| 367 |
sys.exit(1)
|
| 368 |
else:
|
| 369 |
-
# Xóa các file cũ trong out_dir
|
| 370 |
shutil.rmtree(out_dir)
|
| 371 |
|
| 372 |
out_dir.mkdir(parents=True, exist_ok=True)
|
|
@@ -374,14 +469,18 @@ def main():
|
|
| 374 |
print("\nKẾT QUẢ PHÂN BỔ TRÍCH XUẤT:")
|
| 375 |
print("-" * 80)
|
| 376 |
print(f"• Số lượng trích xuất : {total_selected:,} file")
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
print(f"• Thư mục đích : {out_dir}")
|
| 382 |
print("-" * 80)
|
| 383 |
|
| 384 |
-
#
|
| 385 |
print(f"Đang sao chép và đổi tên liên tục {total_selected:,} file audio...", end=" ", flush=True)
|
| 386 |
t_cp0 = time.time()
|
| 387 |
|
|
|
|
| 2 |
"""
|
| 3 |
Dataset Split & Sub-dataset Generator for TTS
|
| 4 |
=============================================
|
| 5 |
+
Cắt trích xuất tập dữ liệu con (sub-dataset) từ dataset gốc:
|
| 6 |
+
1. Theo khoảng số câu cụ thể:
|
| 7 |
+
split.py [folder] [start-end]
|
| 8 |
+
Ví dụ:
|
| 9 |
+
python split.py Test 1-300 -> Trích xuất từ câu 1 đến câu 300, tạo thư mục Test1-300
|
| 10 |
+
python split.py Mai 101-500 -> Trích xuất từ câu 101 đến câu 500, tạo thư mục Mai101-500
|
| 11 |
+
|
| 12 |
+
2. Theo thời lượng nói thực tế:
|
| 13 |
+
split.py [folder] [time]
|
| 14 |
+
Ví dụ:
|
| 15 |
+
python split.py Mai 5h6m30s -> Cắt 5h6m30s, tạo thư mục Mai5h6m30s
|
| 16 |
+
python split.py HoatNgon 1h -> Cắt 1h, tạo thư mục HoatNgon1h
|
| 17 |
+
python split.py ReviewNew 300m -> Cắt 300m, tạo thư mục ReviewNew300m
|
| 18 |
+
python split.py NuPhoThong 2000s-> Cắt 2000s, tạo thư mục NuPhoThong2000s
|
| 19 |
|
| 20 |
Đặc điểm:
|
| 21 |
+
1. Hỗ trợ 2 chế độ:
|
| 22 |
+
- Chế độ số câu (start-end): Lấy chính xác dải câu chỉ định, không phụ thuộc thời gian.
|
| 23 |
+
- Chế độ thời gian: Phân bổ ưu tiên 20% từ ngắn (1 tiếng), 30% (2-5 tiếng), 50% (>5 tiếng).
|
| 24 |
+
2. Tên thư mục mới tự động tạo theo chuẩn: [folder] + [target] (ví dụ: Test1-300, Mai5h6m30s).
|
| 25 |
+
3. Đổi tên liên tục từ audio_0001.wav đến hết và tạo file metadata.csv chuẩn LJSpeech,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
tuyệt đối không nhảy cóc số thứ tự (1, 2, 3, 4...).
|
| 27 |
+
4. Sao chép đa luồng tốc độ cao với ThreadPoolExecutor.
|
| 28 |
"""
|
| 29 |
|
| 30 |
import argparse
|
|
|
|
| 148 |
|
| 149 |
def main():
|
| 150 |
parser = argparse.ArgumentParser(
|
| 151 |
+
description="Dataset Splitter: Trích xuất sub-dataset theo khoảng câu (start-end) hoặc thời gian (time)",
|
| 152 |
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 153 |
)
|
| 154 |
parser.add_argument(
|
| 155 |
"folder",
|
| 156 |
+
help="Thư mục dataset đầu vào (ví dụ: Test, Mai, HoatNgon, E:/VieTTS/dataset/ReviewNew)",
|
| 157 |
)
|
| 158 |
parser.add_argument(
|
| 159 |
+
"target",
|
| 160 |
+
help="Khoảng câu cụ thể (ví dụ: 1-300, 101-500) HOẶC thời gian (ví dụ: 5h, 300m, 2000s, 5h6m30s, 1h30m)",
|
| 161 |
)
|
| 162 |
parser.add_argument(
|
| 163 |
"--out",
|
| 164 |
"-o",
|
| 165 |
default=None,
|
| 166 |
+
help="Đường dẫn thư mục xuất (Mặc định: [folder_parent]/[folder][target], ví dụ: Test1-300, Mai5h6m30s)",
|
| 167 |
)
|
| 168 |
parser.add_argument(
|
| 169 |
"--workers",
|
|
|
|
| 187 |
print(f"[LỖI] Thư mục '{src_folder}' không tồn tại!")
|
| 188 |
sys.exit(1)
|
| 189 |
|
| 190 |
+
target_str = args.target.strip()
|
| 191 |
+
|
| 192 |
+
# 2. Xác định chế độ: Khoảng câu (Range) hay Thời gian (Time)
|
| 193 |
+
range_match = re.match(r"^(\d+)\s*[-]\s*(\d+)$", target_str)
|
| 194 |
+
is_range_mode = False
|
| 195 |
+
start_sentence = 0
|
| 196 |
+
end_sentence = 0
|
| 197 |
+
target_seconds = 0.0
|
| 198 |
+
|
| 199 |
+
if range_match:
|
| 200 |
+
is_range_mode = True
|
| 201 |
+
start_sentence = int(range_match.group(1))
|
| 202 |
+
end_sentence = int(range_match.group(2))
|
| 203 |
+
if start_sentence > end_sentence:
|
| 204 |
+
start_sentence, end_sentence = end_sentence, start_sentence
|
| 205 |
+
if start_sentence < 1:
|
| 206 |
+
start_sentence = 1
|
| 207 |
+
else:
|
| 208 |
+
# Chế độ thời gian
|
| 209 |
+
try:
|
| 210 |
+
target_seconds = parse_time_to_seconds(target_str)
|
| 211 |
+
except ValueError as e:
|
| 212 |
+
print(f"[LỖI] {e}")
|
| 213 |
+
print("\nHướng dẫn tham số:")
|
| 214 |
+
print(" • Theo khoảng câu : split.py Test 1-300")
|
| 215 |
+
print(" • Theo thời gian : split.py Mai 5h6m30s (hoặc 1h, 300m, 2000s)")
|
| 216 |
+
sys.exit(1)
|
| 217 |
|
| 218 |
# 3. Tìm metadata.csv
|
| 219 |
meta_path = find_metadata_file(src_folder)
|
|
|
|
| 221 |
print(f"[LỖI] Không tìm thấy metadata.csv trong '{src_folder}' hoặc các thư mục chuẩn!")
|
| 222 |
sys.exit(1)
|
| 223 |
|
| 224 |
+
# Đọc danh sách câu từ metadata theo đúng thứ tự ban đầu
|
| 225 |
+
# entries: list các tuple (line_idx_1_based, stem, filename, text)
|
| 226 |
+
meta_entries: List[Tuple[int, str, str, str]] = []
|
| 227 |
meta_map: Dict[str, Tuple[str, int]] = {}
|
| 228 |
+
|
| 229 |
with open(meta_path, "r", encoding="utf-8") as f:
|
| 230 |
+
line_idx = 1
|
| 231 |
+
for line in f:
|
| 232 |
line = line.strip()
|
| 233 |
if not line or line.startswith("#"):
|
| 234 |
continue
|
| 235 |
parts = line.split("|")
|
| 236 |
if len(parts) >= 2:
|
| 237 |
+
fn = parts[0].strip()
|
| 238 |
+
stem = Path(fn).stem
|
| 239 |
text = parts[1].strip()
|
| 240 |
+
meta_entries.append((line_idx, stem, fn, text))
|
| 241 |
+
meta_map[stem] = (text, line_idx - 1)
|
| 242 |
+
line_idx += 1
|
| 243 |
+
|
| 244 |
+
total_meta_sentences = len(meta_entries)
|
| 245 |
+
if total_meta_sentences == 0:
|
| 246 |
+
print(f"[LỖI] File metadata '{meta_path}' rỗng hoặc không có dữ liệu hợp lệ!")
|
| 247 |
+
sys.exit(1)
|
| 248 |
|
| 249 |
# 4. Quét các file WAV gốc
|
| 250 |
+
all_wav_dict: Dict[str, Path] = {w.stem: w for w in src_folder.glob("*.wav")}
|
| 251 |
+
if not all_wav_dict:
|
| 252 |
print(f"[LỖI] Không tìm thấy file WAV nào trong '{src_folder}'!")
|
| 253 |
sys.exit(1)
|
| 254 |
|
|
|
|
| 256 |
print("CÔNG CỤ TRÍCH XUẤT SUB-DATASET CHO HUẤN LUYỆN TTS")
|
| 257 |
print("=" * 80)
|
| 258 |
print(f"• Thư mục gốc : {src_folder.name} ({src_folder})")
|
| 259 |
+
print(f"• Metadata nguồn : {meta_path.name} ({total_meta_sentences:,} câu)")
|
| 260 |
+
print(f"• Số file audio gốc: {len(all_wav_dict):,} file")
|
| 261 |
+
|
| 262 |
+
selected: List[Dict] = []
|
| 263 |
+
actual_dur = 0.0
|
| 264 |
+
|
| 265 |
+
# =========================================================================
|
| 266 |
+
# CHẾ ĐỘ 1: LẤY THEO KHOẢNG SỐ CÂU CỤ THỂ (ví dụ: 1-300)
|
| 267 |
+
# =========================================================================
|
| 268 |
+
if is_range_mode:
|
| 269 |
+
if end_sentence > total_meta_sentences:
|
| 270 |
+
print(f"[CẢNH BÁO] Câu kết thúc ({end_sentence}) lớn hơn tổng số câu ({total_meta_sentences}).")
|
| 271 |
+
print(f"Tự động giới hạn đến câu {total_meta_sentences}.")
|
| 272 |
+
end_sentence = total_meta_sentences
|
| 273 |
+
|
| 274 |
+
req_count = end_sentence - start_sentence + 1
|
| 275 |
+
print(f"• Chế độ xử lý : Theo số câu cụ thể (Range)")
|
| 276 |
+
print(f"• Dải câu yêu cầu : Từ câu {start_sentence:,} đến câu {end_sentence:,} (Tổng {req_count:,} câu)")
|
| 277 |
+
print("-" * 80)
|
| 278 |
+
|
| 279 |
+
missing_files = []
|
| 280 |
+
target_slice = meta_entries[start_sentence - 1 : end_sentence]
|
| 281 |
+
|
| 282 |
+
print("Đang quét và đối chiếu các file WAV theo khoảng câu...", end=" ", flush=True)
|
| 283 |
+
t_scan0 = time.time()
|
| 284 |
+
|
| 285 |
+
for line_no, stem, fn, text in target_slice:
|
| 286 |
+
wav_path = all_wav_dict.get(stem)
|
| 287 |
+
if not wav_path or not wav_path.is_file():
|
| 288 |
+
missing_files.append((line_no, fn))
|
| 289 |
+
continue
|
| 290 |
|
| 291 |
+
dur = get_wav_duration_fast(wav_path)
|
| 292 |
+
actual_dur += dur
|
| 293 |
+
words = text.split()
|
| 294 |
+
|
| 295 |
+
selected.append({
|
| 296 |
+
"path": wav_path,
|
| 297 |
+
"filename": wav_path.name,
|
| 298 |
+
"stem": stem,
|
| 299 |
+
"dur": dur,
|
| 300 |
+
"text": text,
|
| 301 |
+
"word_count": len(words),
|
| 302 |
+
"order": line_no,
|
| 303 |
+
})
|
| 304 |
+
|
| 305 |
+
scan_elapsed = time.time() - t_scan0
|
| 306 |
+
print(f"Xong ({scan_elapsed:.2f}s)!")
|
| 307 |
+
|
| 308 |
+
if missing_files:
|
| 309 |
+
print(f"\n[CẢNH BÁO] Có {len(missing_files)} file không tìm thấy trong thư mục:")
|
| 310 |
+
for l_no, f_name in missing_files[:5]:
|
| 311 |
+
print(f" - Câu {l_no}: {f_name}")
|
| 312 |
+
if len(missing_files) > 5:
|
| 313 |
+
print(f" - ... và {len(missing_files) - 5} file khác.")
|
| 314 |
+
|
| 315 |
+
if not selected:
|
| 316 |
+
print("[LỖI] Không trích xuất được file audio nào hợp lệ trong dải câu đã chọn!")
|
| 317 |
+
sys.exit(1)
|
| 318 |
+
|
| 319 |
+
# =========================================================================
|
| 320 |
+
# CHẾ ĐỘ 2: LẤY THEO THỜI LƯỢNG NÓI THỰC TẾ (~ [time])
|
| 321 |
+
# =========================================================================
|
| 322 |
+
else:
|
| 323 |
+
print(f"• Chế độ xử lý : Theo thời lượng nói thực tế (Time)")
|
| 324 |
+
print(f"• Thời gian yêu cầu: {target_str} (~{target_seconds:.1f}s | {format_duration(target_seconds)})")
|
| 325 |
+
print("-" * 80)
|
| 326 |
+
|
| 327 |
+
# Phân loại theo 3 nhóm số tiếng
|
| 328 |
+
# Bucket 1: 1 tiếng (á, à, vâng, ấp, vực...) -> 20%
|
| 329 |
+
# Bucket 2: 2 - 5 tiếng -> 30%
|
| 330 |
+
# Bucket 3: > 5 tiếng -> 50%
|
| 331 |
+
b1: List[Dict] = []
|
| 332 |
+
b2: List[Dict] = []
|
| 333 |
+
b3: List[Dict] = []
|
| 334 |
+
total_src_duration = 0.0
|
| 335 |
+
|
| 336 |
+
print("Đang quét thời lượng toàn bộ file WAV...", end=" ", flush=True)
|
| 337 |
+
t_scan0 = time.time()
|
| 338 |
+
|
| 339 |
+
for stem, wav_path in all_wav_dict.items():
|
| 340 |
+
dur = get_wav_duration_fast(wav_path)
|
| 341 |
+
if dur <= 0.0:
|
| 342 |
+
continue
|
| 343 |
+
total_src_duration += dur
|
| 344 |
+
|
| 345 |
+
meta_info = meta_map.get(stem)
|
| 346 |
+
text = meta_info[0] if meta_info else ""
|
| 347 |
+
order = meta_info[1] if meta_info else 999999
|
| 348 |
+
|
| 349 |
+
words = text.split()
|
| 350 |
+
word_count = len(words)
|
| 351 |
+
|
| 352 |
+
item = {
|
| 353 |
+
"path": wav_path,
|
| 354 |
+
"filename": wav_path.name,
|
| 355 |
+
"stem": stem,
|
| 356 |
+
"dur": dur,
|
| 357 |
+
"text": text,
|
| 358 |
+
"word_count": word_count,
|
| 359 |
+
"order": order,
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
if word_count == 1:
|
| 363 |
+
b1.append(item)
|
| 364 |
+
elif 2 <= word_count <= 5:
|
| 365 |
+
b2.append(item)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
else:
|
| 367 |
+
b3.append(item)
|
| 368 |
+
|
| 369 |
+
scan_elapsed = time.time() - t_scan0
|
| 370 |
+
print(f"Xong ({scan_elapsed:.2f}s)!")
|
| 371 |
+
print(f"• Tổng thời lượng gốc: {format_duration(total_src_duration)} ({total_src_duration/3600:.2f} giờ)")
|
| 372 |
+
print(f" - Nhóm 1 tiếng : {len(b1):,} file ({sum(x['dur'] for x in b1)/3600:.2f}h)")
|
| 373 |
+
print(f" - Nhóm 2-5 tiếng: {len(b2):,} file ({sum(x['dur'] for x in b2)/3600:.2f}h)")
|
| 374 |
+
print(f" - Nhóm >5 tiếng : {len(b3):,} file ({sum(x['dur'] for x in b3)/3600:.2f}h)")
|
| 375 |
+
|
| 376 |
+
if target_seconds > total_src_duration:
|
| 377 |
+
print(f"\n[CẢNH BÁO] Thời gian yêu cầu ({format_duration(target_seconds)}) lớn hơn tổng thời lượng gốc ({format_duration(total_src_duration)})!")
|
| 378 |
+
print("Tập kết quả sẽ bao gồm toàn bộ dataset.")
|
| 379 |
+
target_seconds = total_src_duration
|
| 380 |
+
|
| 381 |
+
# Thuật toán chọn mẫu tối ưu (Tỉ lệ ưu tiên 20% : 30% : 50%)
|
| 382 |
+
d1 = sum(x["dur"] for x in b1) / len(b1) if b1 else 0.5
|
| 383 |
+
d2 = sum(x["dur"] for x in b2) / len(b2) if b2 else 0.8
|
| 384 |
+
d3 = sum(x["dur"] for x in b3) / len(b3) if b3 else 3.5
|
| 385 |
+
|
| 386 |
+
cycle_dur = 5 * d3 + 3 * d2 + 2 * d1
|
| 387 |
+
num_cycles = target_seconds / cycle_dur if cycle_dur > 0 else 0
|
| 388 |
+
|
| 389 |
+
req3 = int(round(num_cycles * 5))
|
| 390 |
+
req2 = int(round(num_cycles * 3))
|
| 391 |
+
req1 = int(round(num_cycles * 2))
|
| 392 |
+
|
| 393 |
+
cnt3 = min(len(b3), req3)
|
| 394 |
+
cnt2 = min(len(b2), req2)
|
| 395 |
+
cnt1 = min(len(b1), req1)
|
| 396 |
+
|
| 397 |
+
cur_est = cnt3 * d3 + cnt2 * d2 + cnt1 * d1
|
| 398 |
+
rem_dur = target_seconds - cur_est
|
| 399 |
+
|
| 400 |
+
if rem_dur > 0 and cnt3 == len(b3) and (len(b2) > cnt2 or len(b1) > cnt1):
|
| 401 |
+
sub_cycle_dur = 3 * d2 + 2 * d1
|
| 402 |
+
sub_cycles = rem_dur / sub_cycle_dur if sub_cycle_dur > 0 else 0
|
| 403 |
+
add2 = min(len(b2) - cnt2, int(round(sub_cycles * 3)))
|
| 404 |
+
add1 = min(len(b1) - cnt1, int(round(sub_cycles * 2)))
|
| 405 |
+
cnt2 += add2
|
| 406 |
+
cnt1 += add1
|
| 407 |
+
|
| 408 |
+
s3 = [b3[int(i * len(b3) / cnt3)] for i in range(cnt3)] if cnt3 > 0 else []
|
| 409 |
+
s2 = [b2[int(i * len(b2) / cnt2)] for i in range(cnt2)] if cnt2 > 0 else []
|
| 410 |
+
s1 = [b1[int(i * len(b1) / cnt1)] for i in range(cnt1)] if cnt1 > 0 else []
|
| 411 |
+
|
| 412 |
+
selected = s1 + s2 + s3
|
| 413 |
+
actual_dur = sum(x["dur"] for x in selected)
|
| 414 |
+
|
| 415 |
+
# Tinh chỉnh độ lệch thời lượng < 0.5s
|
| 416 |
+
used_paths = {x["path"] for x in selected}
|
| 417 |
+
diff = target_seconds - actual_dur
|
| 418 |
+
|
| 419 |
+
if diff > 0.3:
|
| 420 |
+
candidates = [x for x in (b3 + b2 + b1) if x["path"] not in used_paths]
|
| 421 |
+
for c in sorted(candidates, key=lambda x: x["dur"], reverse=True):
|
| 422 |
+
if actual_dur + c["dur"] <= target_seconds + 0.4:
|
| 423 |
+
selected.append(c)
|
| 424 |
+
actual_dur += c["dur"]
|
| 425 |
+
if abs(target_seconds - actual_dur) < 0.3:
|
| 426 |
+
break
|
| 427 |
+
elif diff < -0.3:
|
| 428 |
+
while actual_dur > target_seconds + 0.3 and len(selected) > 0:
|
| 429 |
+
best_idx = None
|
| 430 |
+
best_gap = abs(target_seconds - actual_dur)
|
| 431 |
+
for idx in range(len(selected) - 1, max(-1, len(selected) - 30), -1):
|
| 432 |
+
gap = abs(target_seconds - (actual_dur - selected[idx]["dur"]))
|
| 433 |
+
if gap < best_gap:
|
| 434 |
+
best_gap = gap
|
| 435 |
+
best_idx = idx
|
| 436 |
+
if best_idx is not None and best_gap < abs(target_seconds - actual_dur):
|
| 437 |
+
actual_dur -= selected[best_idx]["dur"]
|
| 438 |
+
selected.pop(best_idx)
|
| 439 |
+
else:
|
| 440 |
+
break
|
| 441 |
+
|
| 442 |
+
selected.sort(key=lambda x: x["order"])
|
| 443 |
|
|
|
|
|
|
|
| 444 |
total_selected = len(selected)
|
| 445 |
|
| 446 |
+
# Thống kê phân bổ
|
| 447 |
actual_b1 = sum(1 for x in selected if x["word_count"] == 1)
|
| 448 |
actual_b2 = sum(1 for x in selected if 2 <= x["word_count"] <= 5)
|
| 449 |
actual_b3 = sum(1 for x in selected if x["word_count"] > 5)
|
| 450 |
|
| 451 |
+
# 5. Xác định thư mục đầu ra [folder] + [target]
|
| 452 |
+
# Ví dụ: Test1-300, Mai5h6m30s
|
| 453 |
+
target_folder_name = f"{src_folder.name}{target_str}"
|
|
|
|
| 454 |
if args.out:
|
| 455 |
out_dir = Path(args.out).resolve()
|
| 456 |
else:
|
|
|
|
| 462 |
print("Dùng cờ '--force' hoặc '-f' nếu muốn ghi đè lên thư mục này.")
|
| 463 |
sys.exit(1)
|
| 464 |
else:
|
|
|
|
| 465 |
shutil.rmtree(out_dir)
|
| 466 |
|
| 467 |
out_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 469 |
print("\nKẾT QUẢ PHÂN BỔ TRÍCH XUẤT:")
|
| 470 |
print("-" * 80)
|
| 471 |
print(f"• Số lượng trích xuất : {total_selected:,} file")
|
| 472 |
+
if is_range_mode:
|
| 473 |
+
print(f"• Phạm vi trích xuất : Câu {start_sentence:,} -> Câu {end_sentence:,} (Tuần tự 100%)")
|
| 474 |
+
print(f"• Tổng thời lượng nói : {format_duration(actual_dur)} ({actual_dur:.1f}s)")
|
| 475 |
+
else:
|
| 476 |
+
print(f"• Thời lượng đạt được : {format_duration(actual_dur)} ({actual_dur:.1f}s | Lệch: {actual_dur - target_seconds:+.2f}s)")
|
| 477 |
+
print(f"• Nhóm 1 tiếng (1w) : {actual_b1:,} câu ({actual_b1/total_selected*100:.1f}%)")
|
| 478 |
+
print(f"• Nhóm 2-5 tiếng (2-5): {actual_b2:,} câu ({actual_b2/total_selected*100:.1f}%)")
|
| 479 |
+
print(f"• Nhóm >5 tiếng (>5w) : {actual_b3:,} câu ({actual_b3/total_selected*100:.1f}%)")
|
| 480 |
print(f"• Thư mục đích : {out_dir}")
|
| 481 |
print("-" * 80)
|
| 482 |
|
| 483 |
+
# 6. Đổi tên liên tục 1..N và sao chép audio + tạo metadata.csv mới
|
| 484 |
print(f"Đang sao chép và đổi tên liên tục {total_selected:,} file audio...", end=" ", flush=True)
|
| 485 |
t_cp0 = time.time()
|
| 486 |
|