#!/usr/bin/env python3 # Robust build_parquet.py # Usage examples: # python build_parquet.py # python build_parquet.py --root . --splits train test # python build_parquet.py --root /abs/path/to/repo # Requirements: datasets==3.*, pyarrow==17.*, soundfile==0.12.* import argparse, csv, re, sys, zipfile from pathlib import Path from datasets import Dataset, Audio AUDIO_EXTS = {".wav", ".flac", ".mp3", ".ogg", ".m4a"} ALLOW_MISSING_TEXT_SPLITS = {"test"} PATTERNS = [ re.compile(r"nombre_(qu|es)_(\d+)$", re.IGNORECASE), re.compile(r"(?:.*_)?(qu|es)_(\d+)$", re.IGNORECASE), re.compile(r"(\d+)_(qu|es)$", re.IGNORECASE), ] def parse_args(): ap = argparse.ArgumentParser() ap.add_argument("--root", type=Path, default=Path.cwd(), help="Repo root where transcripts.txt lives") ap.add_argument("--splits", nargs="*", default=["train","test"], help="Split directories to scan") return ap.parse_args() def read_transcripts(path: Path): id2pair = {} if not path.exists(): print(f"[ERR] transcripts.txt not found: {path}", file=sys.stderr) sys.exit(1) with path.open(encoding="utf-8") as f: reader = csv.reader(f, delimiter='|', quotechar='"') for row in reader: if not row or len(row) < 3: continue rid, quz, es = row[0].strip(), row[1].strip(), row[2].strip() id2pair[rid] = {"quz": quz, "es": es} id2pair[rid.lstrip("0") or "0"] = {"quz": quz, "es": es} print(f"[OK] transcripts loaded: {len(id2pair)//2} unique ids") return id2pair def parse_lang_id(stem: str): for rgx in PATTERNS: m = rgx.search(stem) if m: g1, g2 = m.groups() if g1.lower() in {"qu","es"}: return g1.lower(), g2 if g2.lower() in {"qu","es"}: return g2.lower(), g1 return None, None def _flatten_if_nested(sp_dir: Path, split_name: str): """ If sp_dir contains a single subdir with the same name (train/test) or just one folder, move its contents up to sp_dir and remove the nested dir. """ if not sp_dir.exists(): return # If there are files already at top-level, do nothing top_files = [p for p in sp_dir.iterdir() if p.is_file()] if top_files: return # Find immediate subdirs subdirs = [p for p in sp_dir.iterdir() if p.is_dir()] if len(subdirs) != 1: return nested = subdirs[0] # Flatten only if nested is the same name or if sp_dir has exactly one subdir and no files if nested.name == split_name or True: for item in nested.iterdir(): item.rename(sp_dir / item.name) nested.rmdir() def ensure_splits_exist_or_extract(root: Path, splits): found_any = False for sp in splits: sp_dir = root / sp sp_zip = root / f"{sp}.zip" if sp_dir.exists(): found_any = True continue if sp_zip.exists() and zipfile.is_zipfile(sp_zip): print(f"[INFO] Extracting {sp_zip} -> {sp_dir}") sp_dir.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(sp_zip, 'r') as zf: zf.extractall(sp_dir) _flatten_if_nested(sp_dir, sp) # <-- add this line found_any = True else: if sp_zip.exists(): print(f"[WARN] {sp_zip} exists but is not a valid zip (maybe an LFS pointer?). Skipping.") return found_any def collect_rows(root: Path, splits, id2pair): rows, counted = [], 0 missing_details, kept_missing, skipped_missing = [], 0, 0 have_split_dirs = any((root/sp).exists() for sp in splits) if not have_split_dirs: # try to auto-extract if zips exist if ensure_splits_exist_or_extract(root, splits): have_split_dirs = True if have_split_dirs: # standard split traversal for sp in splits: sp_dir = root / sp if not sp_dir.exists(): print(f"[WARN] split folder not found: {sp_dir} (skipping)") continue for wav in sp_dir.rglob("*"): if wav.suffix.lower() not in AUDIO_EXTS: continue lang, idx = parse_lang_id(wav.stem) if not idx or not lang: continue pair = id2pair.get(idx) or id2pair.get(idx.lstrip("0") or "0") tq = pair["quz"] if pair else None te = pair["es"] if pair else None text = tq if lang == "qu" else te rel = wav.relative_to(root).as_posix() has_transcription = text is not None and text.strip() != "" if not has_transcription: missing_details.append({ "path": rel, "lang": lang, "id": idx, "split": sp }) if sp in ALLOW_MISSING_TEXT_SPLITS: kept_missing += 1 else: skipped_missing += 1 continue rows.append({ "id": idx, "language": lang, "path": rel, "text": text, "has_transcription": has_transcription, "split": sp }) counted += 1 else: # no split dirs at all: index every wav under root as train print("[INFO] No split folders found; indexing all audio under root as split='train'") for wav in root.rglob("*"): if wav.suffix.lower() not in AUDIO_EXTS: continue lang, idx = parse_lang_id(wav.stem) if not idx or not lang: continue pair = id2pair.get(idx) or id2pair.get(idx.lstrip("0") or "0") tq = pair["quz"] if pair else None te = pair["es"] if pair else None text = tq if lang == "qu" else te rel = wav.relative_to(root).as_posix() has_transcription = text is not None and text.strip() != "" if not has_transcription: missing_details.append({ "path": rel, "lang": lang, "id": idx, "split": "train" }) if "train" in ALLOW_MISSING_TEXT_SPLITS: kept_missing += 1 else: skipped_missing += 1 continue rows.append({ "id": idx, "language": lang, "path": rel, "text": text, "has_transcription": has_transcription, "split": "train" }) counted += 1 print(f"[OK] audio files indexed: {counted}") if kept_missing: print(f"[INFO] samples kept without text: {kept_missing} (allowed splits: {', '.join(sorted(ALLOW_MISSING_TEXT_SPLITS))})") if skipped_missing: print(f"[WARN] samples skipped due to missing text: {skipped_missing}") if missing_details: for miss in missing_details[:10]: flag = "kept" if miss["split"] in ALLOW_MISSING_TEXT_SPLITS else "skipped" print(f" - {miss['path']} (id={miss['id']}, lang={miss['lang']}, split={miss['split']}, {flag})") if len(missing_details) > 10: print(f" ... {len(missing_details) - 10} more") return rows def main(): args = parse_args() root = args.root.resolve() print(f"[INFO] repo root: {root}") id2pair = read_transcripts(root / "transcripts.txt") rows = collect_rows(root, args.splits, id2pair) if not rows: print("[ERR] no audio rows collected. Check paths, zips, or patterns.", file=sys.stderr) sys.exit(2) ds_all = Dataset.from_list(rows).cast_column("path", Audio(sampling_rate=None)) out_dir = root out_dir.mkdir(parents=True, exist_ok=True) splits_present = sorted({r["split"] for r in rows}) for sp in splits_present: ds = ds_all.filter(lambda x: x["split"] == sp).remove_columns(["split"]) out = out_dir / f"{sp}.parquet" ds.to_parquet(out) print(f"[OK] wrote {out} ({len(ds)} rows)") print("[DONE] Parquet build complete.") if __name__ == "__main__": main()