aave-bns-data / scripts /validate_hf_handoff.py
zlysunshine's picture
Publish Aave BNS dataset release candidate
e5277d2 verified
Raw
History Blame Contribute Delete
6.04 kB
#!/usr/bin/env python3
"""Validate the deterministic pre-upload Hugging Face handoff contract."""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
import yaml
LICENSE_ID = "cc-by-4.0"
LICENSE_SPDX = "CC-BY-4.0"
LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
CORE_VERSION = "http://mlcommons.org/croissant/1.1"
RAI_FIELDS = {
"rai:dataLimitations",
"rai:dataBiases",
"rai:personalSensitiveInformation",
"rai:dataUseCases",
"rai:dataSocialImpact",
"rai:hasSyntheticData",
"prov:wasDerivedFrom",
"prov:wasGeneratedBy",
}
NONPUBLIC_REPOSITORY_URL = re.compile(
r"https://github\.com/[^\s\"']+/[^/\s\"']*(?:paper|manuscript)[^/\s\"']*",
re.IGNORECASE,
)
def read_card(path: Path) -> dict:
text = path.read_text(encoding="utf-8")
if not text.startswith("---\n"):
raise ValueError("README.md does not start with YAML frontmatter")
return yaml.safe_load(text.split("---", 2)[1]) or {}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", nargs="?", default=".", type=Path)
args = parser.parse_args()
root = args.root.resolve()
errors: list[str] = []
card = read_card(root / "README.md")
configs = card.get("configs") or []
if card.get("license") != LICENSE_ID:
errors.append(f"Dataset Card license must be {LICENSE_ID}")
if len(configs) != 14:
errors.append(f"Dataset Card must declare 14 configurations, found {len(configs)}")
defaults = [item for item in configs if item.get("default") is True]
if [item.get("config_name") for item in defaults] != [
"observed_protocol_action_counts"
]:
errors.append("Dataset Card must declare exactly the governed default configuration")
for item in configs:
specs = item.get("data_files") or []
if len(specs) != 1 or not (root / str(specs[0].get("path"))).is_file():
errors.append(f"unresolvable data_files entry for {item.get('config_name')}")
croissant = json.loads((root / "metadata/croissant.json").read_text(encoding="utf-8"))
if croissant.get("conformsTo") != CORE_VERSION:
errors.append("Croissant candidate must conform to Croissant 1.1")
if croissant.get("license") != LICENSE_URL:
errors.append("Croissant candidate must use the recognized CC BY 4.0 URL")
missing_rai = sorted(
field
for field in RAI_FIELDS
if field not in croissant or croissant[field] in (None, "", [], {})
)
if missing_rai:
errors.append(f"missing or empty RAI/PROV fields: {missing_rai}")
if not isinstance(croissant.get("rai:hasSyntheticData"), bool):
errors.append("rai:hasSyntheticData must be a JSON boolean")
for field in RAI_FIELDS - {
"rai:hasSyntheticData",
"prov:wasDerivedFrom",
"prov:wasGeneratedBy",
}:
if len(str(croissant.get(field, "")).strip()) < 80:
errors.append(f"{field} is not substantive")
if len(croissant.get("distribution") or []) != 14:
errors.append("Croissant must describe 14 distributions")
if len(croissant.get("recordSet") or []) != 14:
errors.append("Croissant must describe 14 RecordSets")
cff = yaml.safe_load((root / "CITATION.cff").read_text(encoding="utf-8")) or {}
if cff.get("license") != LICENSE_SPDX:
errors.append(f"CITATION.cff license must be {LICENSE_SPDX}")
handoff = json.loads(
(root / "metadata/huggingface_handoff.json").read_text(encoding="utf-8")
)
if handoff.get("status") != "READY_FOR_HF_STAGING":
errors.append("handoff status must be READY_FOR_HF_STAGING")
if handoff.get("target", {}).get("publication_status") != "NOT_YET_UPLOADED":
errors.append("handoff must not claim publication before the Hub upload")
if len(handoff.get("post_upload_gates") or []) < 7:
errors.append("post-upload validation gates are incomplete")
if handoff.get("local_clean_load", {}).get("status") != "PASS":
errors.append("local Hugging Face clean-load receipt is not a pass")
clean_load = json.loads(
(root / "metadata/clean_load_audit.json").read_text(encoding="utf-8")
)
if clean_load.get("hf_datasets_clean_load") != "PASS":
errors.append("all configurations must pass datasets.load_dataset")
if len(clean_load.get("configurations") or []) != 14:
errors.append("clean-load receipt must cover 14 configurations")
croissant_receipt = json.loads(
(root / "metadata/croissant_validation.json").read_text(encoding="utf-8")
)
if croissant_receipt.get("status") != "PASS_LOCAL_CANDIDATE":
errors.append("local Croissant candidate validation is not a pass")
text_suffixes = {".md", ".json", ".csv", ".yml", ".yaml", ".txt", ".cff"}
for path in root.rglob("*"):
if not path.is_file() or path.suffix.lower() not in text_suffixes:
continue
if "__pycache__" in path.parts or path.name == "checksums.sha256":
continue
content = path.read_text(encoding="utf-8", errors="ignore")
match = NONPUBLIC_REPOSITORY_URL.search(content)
if match:
errors.append(
f"forbidden non-public repository URL in "
f"{path.relative_to(root)}: {match.group(0)}"
)
status = "PASS" if not errors else "FAIL"
print(
json.dumps(
{
"status": status,
"handoff": "READY_FOR_HF_STAGING" if not errors else "BLOCKED",
"configuration_count": len(configs),
"rai_field_count": len(RAI_FIELDS) - len(missing_rai),
"license": LICENSE_SPDX,
"errors": errors,
"post_upload_validation_required": True,
},
indent=2,
sort_keys=True,
)
)
return 1 if errors else 0
if __name__ == "__main__":
raise SystemExit(main())