aave-bns-data / scripts /clean_load.py
zlysunshine's picture
Publish Aave BNS dataset release candidate
e5277d2 verified
Raw
History Blame Contribute Delete
4.14 kB
#!/usr/bin/env python3
"""Validate every Dataset Card configuration with Hugging Face Datasets.
This script performs a real local load_dataset call. It deliberately does
not contact the Hub and therefore does not validate publication, visibility,
the Dataset Viewer, or the platform-generated Croissant endpoint.
"""
from __future__ import annotations
import argparse
import csv
import json
import sys
from pathlib import Path
import yaml
def read_card(root: Path) -> dict:
text = (root / "README.md").read_text(encoding="utf-8")
if not text.startswith("---\n"):
raise ValueError("README.md must begin with YAML frontmatter")
return yaml.safe_load(text.split("---", 2)[1]) or {}
def csv_fallback(root: Path, configs: list[dict]) -> list[dict]:
"""Dependency-light structural load; not a substitute for datasets."""
results = []
for config in configs:
name = config["config_name"]
specs = config.get("data_files") or []
if len(specs) != 1:
raise ValueError(f"{name}: expected exactly one data_files entry")
spec = specs[0]
path = root / spec["path"]
with path.open(newline="", encoding="utf-8-sig") as handle:
reader = csv.DictReader(handle)
rows = sum(1 for _ in reader)
columns = list(reader.fieldnames or [])
results.append(
{
"configuration": name,
"split": spec["split"],
"path": spec["path"],
"rows": rows,
"columns": columns,
"loader": "python.csv",
"status": "PASS",
}
)
return results
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("root", nargs="?", default=".")
parser.add_argument(
"--require-hf-datasets",
action="store_true",
help="fail instead of using the CSV structural fallback",
)
parser.add_argument("--json-out")
args = parser.parse_args()
root = Path(args.root).resolve()
configs = read_card(root).get("configs") or []
try:
from datasets import get_dataset_config_names, load_dataset
except ImportError as exc:
if args.require_hf_datasets:
print(
"Hugging Face Datasets is not installed. Install "
"requirements-validation.txt before using "
"--require-hf-datasets.",
file=sys.stderr,
)
return 2
results = csv_fallback(root, configs)
report = {
"status": "PASS_STRUCTURAL_CSV_ONLY",
"hf_datasets_clean_load": "NOT_RUN_DEPENDENCY_UNAVAILABLE",
"detail": str(exc),
"configurations": results,
}
else:
expected = [item["config_name"] for item in configs]
discovered = get_dataset_config_names(str(root))
if discovered != expected:
raise RuntimeError(
f"configuration mismatch: expected {expected}, got {discovered}"
)
results = []
for config in configs:
name = config["config_name"]
spec = config["data_files"][0]
dataset = load_dataset(
str(root),
name=name,
split=spec["split"],
)
results.append(
{
"configuration": name,
"split": spec["split"],
"rows": dataset.num_rows,
"columns": dataset.column_names,
"loader": "datasets.load_dataset",
"status": "PASS",
}
)
report = {
"status": "PASS_LOCAL_HF_DATASETS_CLEAN_LOAD",
"hf_datasets_clean_load": "PASS",
"configurations": results,
}
rendered = json.dumps(report, indent=2, sort_keys=True) + "\n"
if args.json_out:
Path(args.json_out).write_text(rendered, encoding="utf-8")
print(rendered, end="")
return 0
if __name__ == "__main__":
raise SystemExit(main())