DFADD / build_parquet.py
korallll's picture
Add DFADD test split (canonical parquet)
c578c83 verified
raw
history blame
9.46 kB
"""Parquet build for the DFADD (eval / test split) HF dataset repo.
DFADD ("The Diffusion and Flow-Matching Based Audio Deepfake Dataset", arXiv
2409.08731) packaged for the Arena. Only the **test** split is used (eval-only).
Label is the top-level source directory:
DATASET_VCTK_BONAFIDE/test/*.wav -> bonafide (755, VCTK)
DATASET_<GEN>/test/*.{flac,wav} -> spoof (600 each, 5 generators)
GradTTS, MatchaTTS, NaturalSpeech2, PflowTTS, StyleTTS2
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. Records are
processed sorted by utterance_id for stable sharding.
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 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/dfadd")
PARQUET_DIR = REPO_ROOT / "data"
NUM_SHARDS = 2
EXPECTED_ROWS = 3755
EXPECTED_BONAFIDE = 755
EXPECTED_SPOOF = 3000
TARGET_SR = 16000
WORKERS = int(os.environ.get("DFADD_BUILD_WORKERS", "32"))
# source dir -> (label, generator)
GENERATORS = {
"DATASET_VCTK_BONAFIDE": ("bonafide", "vctk"),
"DATASET_GradTTS": ("spoof", "gradtts"),
"DATASET_MatchaTTS": ("spoof", "matchatts"),
"DATASET_NaturalSpeech2": ("spoof", "naturalspeech2"),
"DATASET_PflowTTS": ("spoof", "pflowtts"),
"DATASET_StyleTTS2": ("spoof", "styletts2"),
}
FEATURES = Features(
{
"path": Value("string"),
"audio": Audio(sampling_rate=16000),
"label": ClassLabel(names=["bonafide", "spoof"]),
"notes": Value("string"),
}
)
def build_catalogue():
"""Enumerate test-split audio across all generator dirs -> records."""
records = []
for src_dir, (label, gen) in GENERATORS.items():
test_dir = SRC_ROOT / src_dir / "test"
if not test_dir.is_dir():
raise FileNotFoundError(test_dir)
for f in test_dir.iterdir():
if not f.is_file() or f.suffix.lower() not in (".wav", ".flac"):
continue
stem = f.stem
uid = f"{gen}__{stem}"
speaker = stem.split("_")[0]
records.append(
{
"uid": uid,
"abspath": str(f),
"relpath": f"{src_dir}/test/{f.name}",
"label": label,
"generator": gen,
"speaker": speaker,
"attack": "bonafide" if label == "bonafide" else gen,
}
)
return records
def build_notes(rec):
return json.dumps(
{
"utterance_id": rec["uid"],
"generator": rec["generator"],
"speaker": rec["speaker"],
"attack": rec["attack"],
}
)
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=16):
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"Building catalogue from {SRC_ROOT}")
records = build_catalogue()
print(f"Catalogued {len(records)} clips")
if not sample_mode:
assert len(records) == EXPECTED_ROWS, f"Expected {EXPECTED_ROWS}, got {len(records)}"
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()