Datasets:
Download kaggle_fix_dataset.py from ViuAI/ViuAI_TTS_Dataset: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/datasets/ViuAI/ViuAI_TTS_Dataset/resolve/main/kaggle_fix_dataset.py
- Command line
-
hf download hf://datasets/ViuAI/ViuAI_TTS_Dataset/kaggle_fix_dataset.py
-
curl -L -o kaggle_fix_dataset.py https://huggingface.co/datasets/ViuAI/ViuAI_TTS_Dataset/resolve/main/kaggle_fix_dataset.py
10 kB
| """ | |
| ViuAI_TTS_Dataset Fix Script — Kaggle par chalao (local kuch nahi). | |
| Problem: HF repo me audio/ me orphan WAVs hain jinka metadata.csv me | |
| koi transcript/row nahi (purane collector bug se). Training unko ignore | |
| karta hai, repo ganda rehta hai. | |
| Usage (Kaggle single cell): | |
| !pip install -q datasets huggingface_hub soundfile | |
| !wget -q https://huggingface.co/datasets/ViuAI/ViuAI_TTS_Dataset/resolve/main/kaggle_fix_dataset.py | |
| !python kaggle_fix_dataset.py --mode all | |
| Ya step-by-step: --mode audit | fix | push | |
| Token: Kaggle Secrets me HF_TOKEN (Write access) add karo, ya --token do. | |
| """ | |
| import os | |
| import sys | |
| import csv | |
| import glob | |
| import shutil | |
| import argparse | |
| from collections import Counter | |
| if hasattr(sys.stdout, "reconfigure"): | |
| try: | |
| sys.stdout.reconfigure(encoding="utf-8") | |
| except Exception: | |
| pass | |
| def get_token(args_token=None): | |
| token = args_token or os.environ.get("HF_TOKEN") | |
| if not token: | |
| try: | |
| from kaggle_secrets import UserSecretsClient | |
| token = UserSecretsClient().get_secret("HF_TOKEN") | |
| except Exception: | |
| pass | |
| if not token: | |
| from huggingface_hub import get_token as hf_get_token | |
| token = hf_get_token() | |
| if not token: | |
| raise SystemExit("[!] HF token nahi mila. Kaggle Secrets me HF_TOKEN add karo ya --token do.") | |
| return token | |
| def download_repo(repo, workdir, token): | |
| from huggingface_hub import snapshot_download, login | |
| login(token=token) | |
| snapshot_download(repo_id=repo, repo_type="dataset", local_dir=workdir) | |
| print(f"[+] Downloaded {repo} -> {workdir}") | |
| def load_state(workdir): | |
| wavs = {os.path.basename(p) for p in glob.glob(os.path.join(workdir, "audio", "*.wav"))} | |
| rows = [] | |
| with open(os.path.join(workdir, "metadata.csv"), encoding="utf-8") as f: | |
| for row in csv.reader(f, delimiter="|"): | |
| if len(row) >= 4 and row[0] != "audio_file": | |
| rows.append(row) | |
| return wavs, rows | |
| def do_audit(workdir): | |
| wavs, rows = load_state(workdir) | |
| meta_files = {os.path.basename(r[0]) for r in rows} | |
| orphans = sorted(wavs - meta_files) | |
| missing = sorted(meta_files - wavs) | |
| print("=" * 60) | |
| print(f"Disk WAVs : {len(wavs)}") | |
| print(f"Metadata rows : {len(rows)}") | |
| print(f"Orphan WAVs : {len(orphans)} (transcript nahi, training me bekaar)") | |
| print(f"Missing files : {len(missing)} (row hai, audio nahi)") | |
| print(f"By language : {dict(Counter(r[3].strip() for r in rows))}") | |
| print(f"Speakers : {sorted({r[2].strip() for r in rows})}") | |
| print("Sample orphans :", orphans[:5]) | |
| print("Sample missing :", missing[:5]) | |
| print("=" * 60) | |
| def do_fix(workdir): | |
| wavs, rows = load_state(workdir) | |
| meta_files = {os.path.basename(r[0]) for r in rows} | |
| orphans = sorted(wavs - meta_files) | |
| qdir = "./quarantine" | |
| os.makedirs(qdir, exist_ok=True) | |
| for fn in orphans: | |
| shutil.move(os.path.join(workdir, "audio", fn), os.path.join(qdir, fn)) | |
| disk_now = {os.path.basename(p) for p in glob.glob(os.path.join(workdir, "audio", "*.wav"))} | |
| final = [r for r in rows if os.path.basename(r[0]) in disk_now] | |
| with open(os.path.join(workdir, "metadata.csv"), "w", encoding="utf-8", newline="") as f: | |
| w = csv.writer(f, delimiter="|") | |
| w.writerow(["audio_file", "transcript", "speaker", "language"]) | |
| w.writerows(final) | |
| print(f"[+] Quarantined orphans : {len(orphans)} (./quarantine, session ke sath discard)") | |
| print(f"[+] Dropped stale rows : {len(rows) - len(final)}") | |
| print(f"[+] FINAL clips : {len(final)} (WAVs == rows, 1:1)") | |
| print(f" By language: {dict(Counter(r[3].strip() for r in final))}") | |
| def do_push(repo, workdir, token): | |
| from huggingface_hub import HfApi | |
| api = HfApi(token=token) | |
| remote_files = api.list_repo_files(repo_id=repo, repo_type="dataset") | |
| remote_wavs = [f for f in remote_files if f.startswith("audio/") and f.endswith(".wav")] | |
| _, rows = load_state(workdir) | |
| keep = {r[0].strip() for r in rows} | |
| to_delete = [f for f in remote_wavs if f not in keep] | |
| print(f"Remote WAVs: {len(remote_wavs)}, keep: {len(keep)}, delete: {len(to_delete)}") | |
| if not rows: | |
| raise SystemExit("[!] metadata.csv khaali hai — push roka (pehle --mode fix chalao).") | |
| for i in range(0, len(to_delete), 200): | |
| batch = to_delete[i:i + 200] | |
| api.delete_files(repo_id=repo, repo_type="dataset", delete_patterns=batch, | |
| commit_message=f"Remove {len(batch)} orphan WAVs (no transcript)") | |
| print(f" deleted batch {i // 200 + 1}: {len(batch)} files") | |
| api.upload_file(path_or_fileobj=os.path.join(workdir, "metadata.csv"), | |
| path_in_repo="metadata.csv", repo_id=repo, repo_type="dataset", | |
| commit_message=f"Clean metadata: {len(keep)} clips, WAVs == rows 1:1") | |
| print(f"[DONE] Verify: https://huggingface.co/datasets/{repo}") | |
| def fresh_download(repo, workdir, token): | |
| """Stale-session guard: purana workdir mitao, HF se taaza snapshot lao.""" | |
| if os.path.exists(workdir): | |
| import shutil | |
| shutil.rmtree(workdir) | |
| print(f"[*] Stale local copy hatayi: {workdir}") | |
| download_repo(repo, workdir, token) | |
| def do_all(repo, workdir, token): | |
| """Single-cell full run: download -> audit -> fix -> verify 1:1 -> push.""" | |
| fresh_download(repo, workdir, token) | |
| print("\n### STEP 1: AUDIT (before)\n") | |
| do_audit(workdir) | |
| print("\n### STEP 2: FIX\n") | |
| do_fix(workdir) | |
| # Safety gate: push sirf tabhi jab WAVs == rows 1:1 ho | |
| wavs, rows = load_state(workdir) | |
| disk = {os.path.basename(p) for p in glob.glob(os.path.join(workdir, "audio", "*.wav"))} | |
| meta = {os.path.basename(r[0]) for r in rows} | |
| print("\n### STEP 3: VERIFY GATE\n") | |
| print(f"Disk WAVs: {len(disk)}, Metadata rows: {len(rows)}") | |
| if disk != meta: | |
| raise SystemExit(f"[!] 1:1 match nahi hua (diff {len(disk ^ meta)}). Push ROKA. Audit dekho.") | |
| print("[OK] 1:1 match — push kar rahe hain...\n") | |
| print("### STEP 4: PUSH\n") | |
| do_push(repo, workdir, token) | |
| def qc_file(path): | |
| """ | |
| Real-human audio QC. Returns (ok: bool, reason: str). | |
| Rejects: unreadable, <1s, >20s, silent (RMS<0.01), clipped (>5% samples), | |
| wrong channels handled (mixed to mono at train time). | |
| NOTE: sources (IndicTTS studio + LibriSpeech audiobook) are all real human | |
| recordings — koi TTS/robot data upstream me nahi hai. Yeh QC garbage | |
| (silence/corrupt/clipped) hatata hai, robot-tone detect karna iska kaam nahi. | |
| """ | |
| import numpy as np | |
| try: | |
| import soundfile as sf | |
| data, sr = sf.read(path, dtype="float32", always_2d=True) | |
| except Exception as e: | |
| return False, f"unreadable ({e})" | |
| dur = len(data) / float(sr) | |
| if dur < 1.0: | |
| return False, f"too_short ({dur:.2f}s)" | |
| if dur > 20.0: | |
| return False, f"too_long ({dur:.2f}s)" | |
| mono = data.mean(axis=1) | |
| rms = float((mono ** 2).mean() ** 0.5) | |
| if rms < 0.01: | |
| return False, f"silent (rms={rms:.4f})" | |
| clip_frac = float((abs(mono) > 0.99).mean()) | |
| if clip_frac > 0.05: | |
| return False, f"clipped ({clip_frac * 100:.1f}%)" | |
| return True, "ok" | |
| def do_clean(repo, workdir, token): | |
| """Full garbage-removal pipeline: download -> orphan fix -> audio QC -> verify -> push.""" | |
| fresh_download(repo, workdir, token) | |
| print("\n### STEP 1: ORPHAN FIX\n") | |
| do_fix(workdir) | |
| print("\n### STEP 2: AUDIO QC (har clip sunke nahi, naap ke — 5k files, kuch min)\n") | |
| _, rows = load_state(workdir) | |
| qdir = "./quarantine" | |
| os.makedirs(qdir, exist_ok=True) | |
| q_reasons = Counter() | |
| kept = [] | |
| for i, r in enumerate(rows): | |
| rel = r[0].strip() | |
| p = os.path.join(workdir, rel) | |
| if not os.path.exists(p): | |
| q_reasons["missing_file"] += 1 | |
| continue | |
| ok, reason = qc_file(p) | |
| if ok: | |
| kept.append(r) | |
| else: | |
| q_reasons[reason.split("(")[0].strip()] += 1 | |
| shutil.move(p, os.path.join(qdir, os.path.basename(p))) | |
| if (i + 1) % 1000 == 0: | |
| print(f" checked {i + 1}/{len(rows)}...") | |
| print(f"[+] QC pass: {len(kept)}/{len(rows)} | quarantined: {dict(q_reasons)}") | |
| with open(os.path.join(workdir, "metadata.csv"), "w", encoding="utf-8", newline="") as f: | |
| w = csv.writer(f, delimiter="|") | |
| w.writerow(["audio_file", "transcript", "speaker", "language"]) | |
| w.writerows(kept) | |
| print("\n### STEP 3: VERIFY GATE\n") | |
| disk = {os.path.basename(p) for p in glob.glob(os.path.join(workdir, "audio", "*.wav"))} | |
| meta = {os.path.basename(r[0]) for r in kept} | |
| print(f"Disk WAVs: {len(disk)}, Metadata rows: {len(kept)}") | |
| if disk != meta: | |
| raise SystemExit("[!] 1:1 match nahi hua. Push ROKA.") | |
| print("[OK] 1:1 match — push kar rahe hain...\n") | |
| print("### STEP 4: PUSH\n") | |
| do_push(repo, workdir, token) | |
| if __name__ == "__main__": | |
| p = argparse.ArgumentParser(description="ViuAI_TTS_Dataset fix (Kaggle)") | |
| p.add_argument("--mode", choices=["audit", "fix", "push", "all", "clean"], default="audit", | |
| help="all = orphan fix+push | clean = orphan fix + audio QC + push (single cell)") | |
| p.add_argument("--repo", default="ViuAI/ViuAI_TTS_Dataset") | |
| p.add_argument("--workdir", default="./hf_dataset") | |
| p.add_argument("--token", default=None) | |
| a = p.parse_args() | |
| tok = get_token(a.token) | |
| if a.mode == "all": | |
| do_all(a.repo, a.workdir, tok) | |
| raise SystemExit(0) | |
| if a.mode == "clean": | |
| do_clean(a.repo, a.workdir, tok) | |
| raise SystemExit(0) | |
| if a.mode in ("audit", "fix") and not os.path.exists(os.path.join(a.workdir, "metadata.csv")): | |
| download_repo(a.repo, a.workdir, tok) | |
| if a.mode == "audit": | |
| do_audit(a.workdir) | |
| elif a.mode == "fix": | |
| do_fix(a.workdir) | |
| elif a.mode == "push": | |
| do_push(a.repo, a.workdir, tok) | |