"""Parquet build for the PyAra (Russian audio deepfake) HF dataset repo. PyAra (https://www.kaggle.com/datasets/alep079/pyara) — a Russian-language anti-spoofing set. Source layout: Real/.wav (fake=0) -> bonafide (73,583) Fake/.wav (fake=1) -> spoof (128,195, 5 TTS/VC algorithms alg_1..alg_5) final_dataset.tsv : path, sentence, age, gender, fake, algorithm, length A full decode probe of all clips runs first; 0 failures -> CLEAN raw-byte embed (no decode/re-encode). All source audio is already 16 kHz mono PCM_16 WAV, every clip >= 3.0 s. Records are processed sorted by utterance_id for stable sharding and near-sequential HDD reads. Sample mode (--limit N): first N rows into a single shard, skipping full-count asserts -- used for the fast offline validate-dataset pass. """ import argparse import csv import io import json import os import tempfile from concurrent.futures import ProcessPoolExecutor from pathlib import Path import datasets # noqa: E402 import pyarrow.parquet as pq # noqa: E402 import soundfile as sf # noqa: E402 from datasets import Audio, ClassLabel, Dataset, Features, Value # noqa: E402 from tqdm.auto import tqdm # noqa: E402 try: datasets.disable_progress_bars() except AttributeError: from datasets.utils.logging import disable_progress_bar disable_progress_bar() REPO_ROOT = Path(__file__).resolve().parent SRC_ROOT = Path("/home/kirill/mnt/users_4tb/datasets/final_dataset") META_PATH = SRC_ROOT / "final_dataset.tsv" PARQUET_DIR = REPO_ROOT / "data" NUM_SHARDS = 100 EXPECTED_ROWS = 201778 EXPECTED_BONAFIDE = 73583 EXPECTED_SPOOF = 128195 TARGET_SR = 16000 WORKERS = int(os.environ.get("PYARA_BUILD_WORKERS", "64")) FEATURES = Features( { "path": Value("string"), "audio": Audio(sampling_rate=16000), "label": ClassLabel(names=["bonafide", "spoof"]), "notes": Value("string"), } ) def parse_metadata(): """Parse final_dataset.tsv -> records. Columns: path, sentence, age, gender, fake, algorithm, length.""" records = [] seen = set() with open(META_PATH, encoding="utf-8") as fh: reader = csv.DictReader(fh, delimiter="\t") for row in reader: rel = row["path"].strip() if not rel: continue stem = Path(rel).stem if stem in seen: raise ValueError(f"Duplicate utterance_id stem: {stem}") seen.add(stem) is_spoof = row["fake"].strip() == "1" records.append( { "uid": stem, "relpath": rel, "abspath": str(SRC_ROOT / rel), "label": "spoof" if is_spoof else "bonafide", "algorithm": (row.get("algorithm") or "").strip() or ("bonafide" if not is_spoof else ""), "gender": (row.get("gender") or "").strip(), "age": (row.get("age") or "").strip(), "length": (row.get("length") or "").strip(), } ) return records def build_notes(rec): return json.dumps( { "utterance_id": rec["uid"], "algorithm": rec["algorithm"], "gender": rec["gender"], "age": rec["age"], "length": rec["length"], } ) def _probe_one(abspath): try: data, _ = sf.read(abspath) if data.shape[0] == 0: return f"{abspath}: empty" return None except Exception as e: # noqa: BLE001 return f"{abspath}: {str(e).splitlines()[0][:100]}" def probe_decodability(records): paths = [r["abspath"] for r in records] failures = [] with ProcessPoolExecutor(max_workers=WORKERS) as ex: for err in ex.map(_probe_one, paths, chunksize=32): if err: failures.append(err) print(f"Probe: {len(failures)}/{len(paths)} clips failed soundfile decode") if failures: for f in failures[:10]: print(f" {f}") raise RuntimeError( "Source audio no longer cleanly decodable; the CLEAN raw-embed path " "is unsafe. Re-introduce a re-encode stage (see ASVspoof2021_LA)." ) def _clip_duration(abspath): info = sf.info(abspath) return info.frames / info.samplerate def _ensure_long_first_row(records): for i in range(len(records)): if _clip_duration(records[i]["abspath"]) >= 1.0: if i != 0: records[0], records[i] = records[i], records[0] return raise RuntimeError("No clip with duration >= 1.0s found") def _build_shard(task): shard_index, rows, num_shards = task shard_name = f"test-{shard_index:05d}-of-{num_shards:05d}.parquet" final = PARQUET_DIR / shard_name if final.exists() and final.stat().st_size > 0: return (shard_index, len(rows), "skipped") def row_gen(): for rec in rows: yield { "path": rec["relpath"], "audio": { "bytes": Path(rec["abspath"]).read_bytes(), "path": rec["relpath"], }, "label": rec["label"], "notes": build_notes(rec), } with tempfile.TemporaryDirectory() as cache: ds = Dataset.from_generator(row_gen, features=FEATURES, cache_dir=cache) tmp = PARQUET_DIR / f".{shard_name}.tmp" ds.to_parquet(str(tmp)) os.replace(tmp, final) return (shard_index, len(rows), "built") def _partition(records, num_shards): n = len(records) per = (n + num_shards - 1) // num_shards out = [] for i in range(num_shards): chunk = records[i * per : (i + 1) * per] if chunk: out.append(chunk) return out def build(): parser = argparse.ArgumentParser() parser.add_argument("--limit", type=int, default=None) args = parser.parse_args() limit = args.limit sample_mode = limit is not None print(f"Reading metadata from {META_PATH}") records = parse_metadata() print(f"Parsed {len(records)} rows") if not sample_mode: assert len(records) == EXPECTED_ROWS, f"Expected {EXPECTED_ROWS}, got {len(records)}" check = records if not sample_mode else records[: max(limit * 4, limit)] missing = [r["uid"] for r in check if not Path(r["abspath"]).exists()] assert not missing, f"{len(missing)} wav files missing, e.g. {missing[:5]}" records.sort(key=lambda r: r["uid"]) _ensure_long_first_row(records) probe_decodability(records) if sample_mode: records = records[:limit] num_shards = 1 print(f"SAMPLE MODE: {len(records)} rows -> 1 shard") else: num_shards = NUM_SHARDS bona = sum(1 for r in records if r["label"] == "bonafide") spoof = sum(1 for r in records if r["label"] == "spoof") print(f" bonafide={bona} spoof={spoof} total={len(records)}") PARQUET_DIR.mkdir(parents=True, exist_ok=True) keep_suffix = f"-of-{num_shards:05d}.parquet" for stale in PARQUET_DIR.glob("test-*.parquet"): if not stale.name.endswith(keep_suffix): print(f"Removing stale shard {stale.name}") stale.unlink() shards = _partition(records, num_shards) tasks = [(i, rows, num_shards) for i, rows in enumerate(shards)] stage_workers = min(WORKERS, len(tasks)) print(f"Building {len(tasks)} shard(s) with {stage_workers} workers...") built = skipped = 0 with ProcessPoolExecutor(max_workers=stage_workers) as ex: for idx, n, status in tqdm( ex.map(_build_shard, tasks), total=len(tasks), desc="shards", unit="shard" ): if status == "built": built += 1 elif status == "skipped": skipped += 1 print(f"Done: {built} built, {skipped} skipped") _verify(num_shards, sample_mode) print("All verifications passed!") if not sample_mode: from speech_spoof_bench import labels out = labels.emit_labels(REPO_ROOT) print(f"Wrote {out}") def _verify(num_shards, sample_mode): shards = sorted(PARQUET_DIR.glob("test-*.parquet")) total = sum(pq.read_metadata(str(f)).num_rows for f in shards) uid_set, path_set, bona, spoof = set(), set(), 0, 0 for f in shards: t = pq.read_table(str(f), columns=["path", "label", "notes"]) for p, lab, n in zip( t.column("path").to_pylist(), t.column("label").to_pylist(), t.column("notes").to_pylist(), ): path_set.add(p) uid_set.add(json.loads(n)["utterance_id"]) if lab == 0: bona += 1 elif lab == 1: spoof += 1 assert len(uid_set) == total, "Duplicate utterance_ids" assert len(path_set) == total, "Duplicate paths" if not sample_mode: assert total == EXPECTED_ROWS, f"{total} != {EXPECTED_ROWS}" assert bona == EXPECTED_BONAFIDE, f"bonafide {bona} != {EXPECTED_BONAFIDE}" assert spoof == EXPECTED_SPOOF, f"spoof {spoof} != {EXPECTED_SPOOF}" t0 = pq.read_table(str(shards[0])) assert set(t0.column_names) == {"path", "audio", "label", "notes"}, t0.column_names audio0 = t0.column("audio")[0].as_py() data, sr = sf.read(io.BytesIO(audio0["bytes"])) dur = len(data) / sr assert sr == 16000, f"row0 sr {sr} != 16000" assert dur >= 1.0, f"row0 dur {dur:.2f}s < 1.0s" print(f" verify: {total} rows, row0 {sr}Hz {dur:.2f}s decodable OK") if __name__ == "__main__": build()