ccvoice / split.py
bonelag's picture
Upload folder using huggingface_hub
7ec34e0 verified
Raw History Blame Contribute Delete
20.5 kB
#!/usr/bin/env python3
"""
Dataset Split & Sub-dataset Generator for TTS
=============================================
Cắt trích xuất tập dữ liệu con (sub-dataset) từ dataset gốc:
1. Theo khoảng số câu cụ thể:
split.py [folder] [start-end]
Ví dụ:
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
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
2. Theo thời lượng nói thực tế:
split.py [folder] [time]
Ví dụ:
python split.py Mai 5h6m30s -> Cắt 5h6m30s, tạo thư mục Mai5h6m30s
python split.py HoatNgon 1h -> Cắt 1h, tạo thư mục HoatNgon1h
python split.py ReviewNew 300m -> Cắt 300m, tạo thư mục ReviewNew300m
python split.py NuPhoThong 2000s-> Cắt 2000s, tạo thư mục NuPhoThong2000s
Đặc điểm:
1. Hỗ trợ 2 chế độ:
- 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.
- 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).
2. Tên thư mục mới tự động tạo theo chuẩn: [folder] + [target] (ví dụ: Test1-300, Mai5h6m30s).
3. Đổi tên liên tục từ audio_0001.wav đến hết và tạo file metadata.csv chuẩn LJSpeech,
tuyệt đối không nhảy cóc số thứ tự (1, 2, 3, 4...).
4. Sao chép đa luồng tốc độ cao với ThreadPoolExecutor.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
import os
from pathlib import Path
import re
import shutil
import struct
import sys
import time
from typing import Dict, List, Optional, Tuple
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
def parse_time_to_seconds(time_str: str) -> float:
"""
Chuyển đổi chuỗi thời gian thành số giây:
Hỗ trợ đơn vị đơn: 5h, 300m, 2000s, 1.5h
Hỗ trợ kết hợp: 5h6m30s, 1h30m, 45m20s, 2h15m
"""
s = time_str.strip().lower()
pattern = r"^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m)?(?:(\d+(?:\.\d+)?)s)?$"
match = re.match(pattern, s)
if match and any(match.groups()):
h = float(match.group(1) or 0)
m = float(match.group(2) or 0)
sec = float(match.group(3) or 0)
total = h * 3600 + m * 60 + sec
if total > 0:
return total
# Kiểm tra số nguyên giây thuần túy
try:
val = float(s)
if val > 0:
return val
except ValueError:
pass
raise ValueError(
f"Định dạng thời gian không hợp lệ: '{time_str}'.\n"
f"Ví dụ hợp lệ: 1h, 30m, 2000s, 1h30m, 5h6m30s, 45m20s"
)
def format_duration(seconds: float) -> str:
"""Đổi số giây thành chuỗi HH:MM:SS."""
h = int(seconds // 3600)
m = int((seconds % 3600) // 60)
s = int(seconds % 60)
return f"{h:02d}h {m:02d}m {s:02d}s"
def find_metadata_file(folder_path: Path) -> Optional[Path]:
"""Tìm metadata.csv trong thư mục dataset hoặc các thư mục chuẩn lân cận."""
candidates = [
folder_path / "metadata.csv",
folder_path.parent / "metadata.csv",
folder_path.parent / "capi" / "metadata.csv",
Path("E:/VieTTS/capi/metadata.csv"),
]
for c in candidates:
if c.is_file() and c.stat().st_size > 0:
return c.resolve()
return None
def get_wav_duration_fast(file_path: Path) -> float:
"""
Lấy thời lượng file WAV cực nhanh bằng cách đọc header fmt và data (không load full PCM).
"""
try:
size = file_path.stat().st_size
if size < 44:
return 0.0
with open(file_path, "rb") as fp:
head = fp.read(256)
if head[:4] != b"RIFF" or head[8:12] != b"WAVE":
return 0.0
# Đọc sample_rate và channels từ chunk fmt
fmt_idx = head.find(b"fmt ")
if fmt_idx == -1 or fmt_idx + 24 > len(head):
return 0.0
_, channels, sample_rate, _, block_align, _ = struct.unpack(
"<HHIIHH", head[fmt_idx + 8 : fmt_idx + 24]
)
data_idx = head.find(b"data")
if data_idx == -1:
# Tìm xa hơn nếu data chunk nằm sau các chunk mở rộng
with open(file_path, "rb") as fp:
full_head = fp.read(4096)
data_idx = full_head.find(b"data")
if data_idx == -1:
return 0.0
bytes_per_second = sample_rate * block_align
pcm_bytes = size - (data_idx + 8)
if bytes_per_second <= 0 or pcm_bytes <= 0:
return 0.0
return pcm_bytes / bytes_per_second
except Exception:
return 0.0
def copy_worker(task: Tuple[Path, Path]) -> None:
"""Sao chép 1 file audio."""
src, dst = task
shutil.copy2(src, dst)
def main():
parser = argparse.ArgumentParser(
description="Dataset Splitter: Trích xuất sub-dataset theo khoảng câu (start-end) hoặc thời gian (time)",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"folder",
help="Thư mục dataset đầu vào (ví dụ: Test, Mai, HoatNgon, E:/VieTTS/dataset/ReviewNew)",
)
parser.add_argument(
"target",
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)",
)
parser.add_argument(
"--out",
"-o",
default=None,
help="Đường dẫn thư mục xuất (Mặc định: [folder_parent]/[folder][target], ví dụ: Test1-300, Mai5h6m30s)",
)
parser.add_argument(
"--workers",
"-w",
type=int,
default=16,
help="Số luồng sao chép file song song (Mặc định: 16)",
)
parser.add_argument(
"--force",
"-f",
action="store_true",
help="Ghi đè nếu thư mục đích đã tồn tại",
)
args = parser.parse_args()
# 1. Kiểm tra thư mục đầu vào
src_folder = Path(args.folder).resolve()
if not src_folder.is_dir():
print(f"[LỖI] Thư mục '{src_folder}' không tồn tại!")
sys.exit(1)
target_str = args.target.strip()
# 2. Xác định chế độ: Khoảng câu (Range) hay Thời gian (Time)
range_match = re.match(r"^(\d+)\s*[-]\s*(\d+)$", target_str)
is_range_mode = False
start_sentence = 0
end_sentence = 0
target_seconds = 0.0
if range_match:
is_range_mode = True
start_sentence = int(range_match.group(1))
end_sentence = int(range_match.group(2))
if start_sentence > end_sentence:
start_sentence, end_sentence = end_sentence, start_sentence
if start_sentence < 1:
start_sentence = 1
else:
# Chế độ thời gian
try:
target_seconds = parse_time_to_seconds(target_str)
except ValueError as e:
print(f"[LỖI] {e}")
print("\nHướng dẫn tham số:")
print(" • Theo khoảng câu : split.py Test 1-300")
print(" • Theo thời gian : split.py Mai 5h6m30s (hoặc 1h, 300m, 2000s)")
sys.exit(1)
# 3. Tìm metadata.csv
meta_path = find_metadata_file(src_folder)
if not meta_path:
print(f"[LỖI] Không tìm thấy metadata.csv trong '{src_folder}' hoặc các thư mục chuẩn!")
sys.exit(1)
# Đọc danh sách câu từ metadata theo đúng thứ tự ban đầu
# entries: list các tuple (line_idx_1_based, stem, filename, text)
meta_entries: List[Tuple[int, str, str, str]] = []
meta_map: Dict[str, Tuple[str, int]] = {}
with open(meta_path, "r", encoding="utf-8") as f:
line_idx = 1
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("|")
if len(parts) >= 2:
fn = parts[0].strip()
stem = Path(fn).stem
text = parts[1].strip()
meta_entries.append((line_idx, stem, fn, text))
meta_map[stem] = (text, line_idx - 1)
line_idx += 1
total_meta_sentences = len(meta_entries)
if total_meta_sentences == 0:
print(f"[LỖI] File metadata '{meta_path}' rỗng hoặc không có dữ liệu hợp lệ!")
sys.exit(1)
# 4. Quét các file WAV gốc
all_wav_dict: Dict[str, Path] = {w.stem: w for w in src_folder.glob("*.wav")}
if not all_wav_dict:
print(f"[LỖI] Không tìm thấy file WAV nào trong '{src_folder}'!")
sys.exit(1)
print("=" * 80)
print("CÔNG CỤ TRÍCH XUẤT SUB-DATASET CHO HUẤN LUYỆN TTS")
print("=" * 80)
print(f"• Thư mục gốc : {src_folder.name} ({src_folder})")
print(f"• Metadata nguồn : {meta_path.name} ({total_meta_sentences:,} câu)")
print(f"• Số file audio gốc: {len(all_wav_dict):,} file")
selected: List[Dict] = []
actual_dur = 0.0
# =========================================================================
# CHẾ ĐỘ 1: LẤY THEO KHOẢNG SỐ CÂU CỤ THỂ (ví dụ: 1-300)
# =========================================================================
if is_range_mode:
if end_sentence > total_meta_sentences:
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}).")
print(f"Tự động giới hạn đến câu {total_meta_sentences}.")
end_sentence = total_meta_sentences
req_count = end_sentence - start_sentence + 1
print(f"• Chế độ xử lý : Theo số câu cụ thể (Range)")
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)")
print("-" * 80)
missing_files = []
target_slice = meta_entries[start_sentence - 1 : end_sentence]
print("Đang quét và đối chiếu các file WAV theo khoảng câu...", end=" ", flush=True)
t_scan0 = time.time()
for line_no, stem, fn, text in target_slice:
wav_path = all_wav_dict.get(stem)
if not wav_path or not wav_path.is_file():
missing_files.append((line_no, fn))
continue
dur = get_wav_duration_fast(wav_path)
actual_dur += dur
words = text.split()
selected.append({
"path": wav_path,
"filename": wav_path.name,
"stem": stem,
"dur": dur,
"text": text,
"word_count": len(words),
"order": line_no,
})
scan_elapsed = time.time() - t_scan0
print(f"Xong ({scan_elapsed:.2f}s)!")
if missing_files:
print(f"\n[CẢNH BÁO] Có {len(missing_files)} file không tìm thấy trong thư mục:")
for l_no, f_name in missing_files[:5]:
print(f" - Câu {l_no}: {f_name}")
if len(missing_files) > 5:
print(f" - ... và {len(missing_files) - 5} file khác.")
if not selected:
print("[LỖI] Không trích xuất được file audio nào hợp lệ trong dải câu đã chọn!")
sys.exit(1)
# =========================================================================
# CHẾ ĐỘ 2: LẤY THEO THỜI LƯỢNG NÓI THỰC TẾ (~ [time])
# =========================================================================
else:
print(f"• Chế độ xử lý : Theo thời lượng nói thực tế (Time)")
print(f"• Thời gian yêu cầu: {target_str} (~{target_seconds:.1f}s | {format_duration(target_seconds)})")
print("-" * 80)
# Phân loại theo 3 nhóm số tiếng
# Bucket 1: 1 tiếng (á, à, vâng, ấp, vực...) -> 20%
# Bucket 2: 2 - 5 tiếng -> 30%
# Bucket 3: > 5 tiếng -> 50%
b1: List[Dict] = []
b2: List[Dict] = []
b3: List[Dict] = []
total_src_duration = 0.0
print("Đang quét thời lượng toàn bộ file WAV...", end=" ", flush=True)
t_scan0 = time.time()
for stem, wav_path in all_wav_dict.items():
dur = get_wav_duration_fast(wav_path)
if dur <= 0.0:
continue
total_src_duration += dur
meta_info = meta_map.get(stem)
text = meta_info[0] if meta_info else ""
order = meta_info[1] if meta_info else 999999
words = text.split()
word_count = len(words)
item = {
"path": wav_path,
"filename": wav_path.name,
"stem": stem,
"dur": dur,
"text": text,
"word_count": word_count,
"order": order,
}
if word_count == 1:
b1.append(item)
elif 2 <= word_count <= 5:
b2.append(item)
else:
b3.append(item)
scan_elapsed = time.time() - t_scan0
print(f"Xong ({scan_elapsed:.2f}s)!")
print(f"• Tổng thời lượng gốc: {format_duration(total_src_duration)} ({total_src_duration/3600:.2f} giờ)")
print(f" - Nhóm 1 tiếng : {len(b1):,} file ({sum(x['dur'] for x in b1)/3600:.2f}h)")
print(f" - Nhóm 2-5 tiếng: {len(b2):,} file ({sum(x['dur'] for x in b2)/3600:.2f}h)")
print(f" - Nhóm >5 tiếng : {len(b3):,} file ({sum(x['dur'] for x in b3)/3600:.2f}h)")
if target_seconds > total_src_duration:
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)})!")
print("Tập kết quả sẽ bao gồm toàn bộ dataset.")
target_seconds = total_src_duration
# Thuật toán chọn mẫu tối ưu (Tỉ lệ ưu tiên 20% : 30% : 50%)
d1 = sum(x["dur"] for x in b1) / len(b1) if b1 else 0.5
d2 = sum(x["dur"] for x in b2) / len(b2) if b2 else 0.8
d3 = sum(x["dur"] for x in b3) / len(b3) if b3 else 3.5
cycle_dur = 5 * d3 + 3 * d2 + 2 * d1
num_cycles = target_seconds / cycle_dur if cycle_dur > 0 else 0
req3 = int(round(num_cycles * 5))
req2 = int(round(num_cycles * 3))
req1 = int(round(num_cycles * 2))
cnt3 = min(len(b3), req3)
cnt2 = min(len(b2), req2)
cnt1 = min(len(b1), req1)
cur_est = cnt3 * d3 + cnt2 * d2 + cnt1 * d1
rem_dur = target_seconds - cur_est
if rem_dur > 0 and cnt3 == len(b3) and (len(b2) > cnt2 or len(b1) > cnt1):
sub_cycle_dur = 3 * d2 + 2 * d1
sub_cycles = rem_dur / sub_cycle_dur if sub_cycle_dur > 0 else 0
add2 = min(len(b2) - cnt2, int(round(sub_cycles * 3)))
add1 = min(len(b1) - cnt1, int(round(sub_cycles * 2)))
cnt2 += add2
cnt1 += add1
s3 = [b3[int(i * len(b3) / cnt3)] for i in range(cnt3)] if cnt3 > 0 else []
s2 = [b2[int(i * len(b2) / cnt2)] for i in range(cnt2)] if cnt2 > 0 else []
s1 = [b1[int(i * len(b1) / cnt1)] for i in range(cnt1)] if cnt1 > 0 else []
selected = s1 + s2 + s3
actual_dur = sum(x["dur"] for x in selected)
# Tinh chỉnh độ lệch thời lượng < 0.5s
used_paths = {x["path"] for x in selected}
diff = target_seconds - actual_dur
if diff > 0.3:
candidates = [x for x in (b3 + b2 + b1) if x["path"] not in used_paths]
for c in sorted(candidates, key=lambda x: x["dur"], reverse=True):
if actual_dur + c["dur"] <= target_seconds + 0.4:
selected.append(c)
actual_dur += c["dur"]
if abs(target_seconds - actual_dur) < 0.3:
break
elif diff < -0.3:
while actual_dur > target_seconds + 0.3 and len(selected) > 0:
best_idx = None
best_gap = abs(target_seconds - actual_dur)
for idx in range(len(selected) - 1, max(-1, len(selected) - 30), -1):
gap = abs(target_seconds - (actual_dur - selected[idx]["dur"]))
if gap < best_gap:
best_gap = gap
best_idx = idx
if best_idx is not None and best_gap < abs(target_seconds - actual_dur):
actual_dur -= selected[best_idx]["dur"]
selected.pop(best_idx)
else:
break
selected.sort(key=lambda x: x["order"])
total_selected = len(selected)
# Thống kê phân bổ
actual_b1 = sum(1 for x in selected if x["word_count"] == 1)
actual_b2 = sum(1 for x in selected if 2 <= x["word_count"] <= 5)
actual_b3 = sum(1 for x in selected if x["word_count"] > 5)
# 5. Xác định thư mục đầu ra [folder] + [target]
# Ví dụ: Test1-300, Mai5h6m30s
target_folder_name = f"{src_folder.name}{target_str}"
if args.out:
out_dir = Path(args.out).resolve()
else:
out_dir = src_folder.parent / target_folder_name
if out_dir.exists():
if not args.force:
print(f"\n[LỖI] Thư mục đích '{out_dir}' đã tồn tại!")
print("Dùng cờ '--force' hoặc '-f' nếu muốn ghi đè lên thư mục này.")
sys.exit(1)
else:
shutil.rmtree(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
print("\nKẾT QUẢ PHÂN BỔ TRÍCH XUẤT:")
print("-" * 80)
print(f"• Số lượng trích xuất : {total_selected:,} file")
if is_range_mode:
print(f"• Phạm vi trích xuất : Câu {start_sentence:,} -> Câu {end_sentence:,} (Tuần tự 100%)")
print(f"• Tổng thời lượng nói : {format_duration(actual_dur)} ({actual_dur:.1f}s)")
else:
print(f"• Thời lượng đạt được : {format_duration(actual_dur)} ({actual_dur:.1f}s | Lệch: {actual_dur - target_seconds:+.2f}s)")
print(f"• Nhóm 1 tiếng (1w) : {actual_b1:,} câu ({actual_b1/total_selected*100:.1f}%)")
print(f"• Nhóm 2-5 tiếng (2-5): {actual_b2:,} câu ({actual_b2/total_selected*100:.1f}%)")
print(f"• Nhóm >5 tiếng (>5w) : {actual_b3:,} câu ({actual_b3/total_selected*100:.1f}%)")
print(f"• Thư mục đích : {out_dir}")
print("-" * 80)
# 6. Đổi tên liên tục 1..N và sao chép audio + tạo metadata.csv mới
print(f"Đang sao chép và đổi tên liên tục {total_selected:,} file audio...", end=" ", flush=True)
t_cp0 = time.time()
copy_tasks: List[Tuple[Path, Path]] = []
new_metadata_lines: List[str] = []
for i, item in enumerate(selected, 1):
new_filename = f"audio_{i:04d}.wav"
new_wav_path = out_dir / new_filename
copy_tasks.append((item["path"], new_wav_path))
new_metadata_lines.append(f"{new_filename}|{item['text']}")
with ThreadPoolExecutor(max_workers=args.workers) as executor:
list(executor.map(copy_worker, copy_tasks))
# Ghi file metadata.csv mới
new_meta_path = out_dir / "metadata.csv"
with open(new_meta_path, "w", encoding="utf-8") as mf:
for line in new_metadata_lines:
mf.write(f"{line}\n")
cp_elapsed = time.time() - t_cp0
print(f"Hoàn tất ({cp_elapsed:.2f}s, {total_selected/cp_elapsed:,.0f} files/s)!")
print("=" * 80)
print(f"[THÀNH CÔNG] Đã tạo sub-dataset hoàn chỉnh tại: {out_dir}")
print(f"• File đầu tiên : audio_0001.wav")
print(f"• File cuối cùng: audio_{total_selected:04d}.wav (Không có bước nhảy số)")
print(f"• File nhãn : {new_meta_path} ({total_selected:,} dòng)")
print("=" * 80)
if __name__ == "__main__":
main()