#!/usr/bin/env python3 """Check this local release. Optional loader checks use the local HF dataset card. The default checks use only the standard library and make no network requests. This verifies packaging and data access, not scientific correctness. """ from __future__ import annotations import argparse import csv import hashlib import json import math from pathlib import Path, PurePosixPath import re import sys import tempfile ROOT = Path(__file__).resolve().parents[1] def verify_manifest(base: Path) -> int: entries = set() for number, line in enumerate((base / "SHA256SUMS.txt").read_text(encoding="utf-8").splitlines(), 1): if not line.strip(): continue match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) if not match: raise ValueError(f"Malformed manifest entry {number}.") expected, name = match.groups() relative = PurePosixPath(name) if (relative.is_absolute() or "\\" in name or ":" in name or any(part in {"", ".", ".."} for part in name.split("/")) or name in entries or name == "SHA256SUMS.txt"): raise ValueError(f"Unsafe or duplicate manifest path: {name}") path = base / name if not path.resolve().is_relative_to(base.resolve()): raise ValueError(f"Path escapes release: {name}") cursor = path while cursor != base: if cursor.is_symlink(): raise ValueError(f"Unexpected symlink: {name}") cursor = cursor.parent if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != expected: raise ValueError(f"Missing file or checksum mismatch: {name}") entries.add(name) if not entries: raise ValueError("Empty integrity manifest.") return len(entries) def validate_tables() -> tuple[dict, list]: index = json.loads((ROOT / "dataset_index.json").read_text(encoding="utf-8")) configs = index["configurations"] names = [entry["config_name"] for entry in configs] paths = [entry["path"] for entry in configs] if len(configs) != 11 or len(set(names)) != 11 or len(set(paths)) != 11: raise ValueError("Expected 11 distinct CSV configurations.") found = {p.relative_to(ROOT).as_posix() for p in (ROOT / "research/data").glob("*.csv")} if set(paths) != found: raise ValueError("Dataset index does not cover exactly the research CSV tables.") total = 0 for entry in configs: if entry["split"] != "train": raise ValueError("Unexpected split mapping.") path = ROOT / entry["path"] with path.open(newline="", encoding="utf-8") as handle: reader = csv.DictReader(handle) if reader.fieldnames != entry["columns"]: raise ValueError(f"Column mismatch: {entry['config_name']}") rows = list(reader) if len(rows) != entry["rows"]: raise ValueError(f"Row count mismatch: {entry['config_name']}") for row in rows: if set(row) != set(entry["columns"]) or any(v is None for v in row.values()): raise ValueError(f"Malformed CSV row: {entry['config_name']}") if not all(math.isfinite(float(value)) for value in row.values()): raise ValueError(f"Non-finite numeric cell: {entry['config_name']}") total += len(rows) if total != index["total_rows"] or total != 532: raise ValueError("Unexpected total row count.") text = (ROOT / "README.md").read_text(encoding="utf-8") if not text.startswith("---\n") or "\n---\n" not in text[4:]: raise ValueError("Missing dataset-card front matter.") front = text.split("---", 2)[1] # This accepts the simple generated list shape; the optional HF check below # also parses the full YAML through DatasetCard and exercises its mappings. blocks = re.findall(r"^ - config_name: ([a-z_]+)\n(.*?)(?=^ - config_name:|\Z)", front, re.M | re.S) mappings = {} for name, block in blocks: files = re.findall(r"^ path: (\S+)\s*$", block, re.M) splits = re.findall(r"^ - split: (\S+)\s*$", block, re.M) if len(files) != 1 or splits != ["train"] or name in mappings: raise ValueError("Unexpected card configuration structure.") mappings[name] = files[0] if mappings != {entry["config_name"]: entry["path"] for entry in configs}: raise ValueError("Card mappings and dataset index differ.") if front.count("default: true") != 1 or not re.search(r"config_name: rank_law\n default: true", front): raise ValueError("Expected rank_law as the unique default configuration.") if re.search(r"^license:", front, re.M): raise ValueError("Unexpected license grant in dataset card.") return {"configurations": len(configs), "total_rows": total, "numeric_csv_cells": "finite"}, configs def validate_links_and_syntax() -> dict: checked = 0 documents = [ROOT / "README.md", *(ROOT / "docs").glob("*.md")] for document in documents: for target in re.findall(r"!?\[[^\]]*\]\(([^)]+)\)", document.read_text(encoding="utf-8")): target = target.split("#", 1)[0] if not target or re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*:", target): continue path = document.parent / target if not path.resolve().is_relative_to(ROOT) or not path.exists(): raise ValueError(f"Broken local link in {document.name}: {target}") checked += 1 python_files = [ROOT / "upload_to_hf.py", ROOT / "tools/validate_release.py"] for path in python_files: compile(path.read_text(encoding="utf-8"), path.name, "exec") return {"local_links_checked": checked, "python_helpers_compiled": len(python_files)} def check_datasets(configs: list) -> dict: import datasets import huggingface_hub from datasets import load_dataset from huggingface_hub import DatasetCard card = DatasetCard((ROOT / "README.md").read_text(encoding="utf-8")) declared = card.data.to_dict()["configs"] expected = {entry["config_name"]: entry["path"] for entry in configs} actual = {entry["config_name"]: entry["data_files"][0]["path"] for entry in declared} if expected != actual: raise ValueError("HF card parser found unexpected mappings.") checks = [] with tempfile.TemporaryDirectory(prefix="eiroq-local-datasets-") as cache: for entry in configs: data = load_dataset(str(ROOT), name=entry["config_name"], split="train", cache_dir=cache) if len(data) != entry["rows"] or data.column_names != entry["columns"]: raise ValueError(f"Local HF loader mismatch: {entry['config_name']}") checks.append({"configuration": entry["config_name"], "rows": len(data)}) return {"status": "passed", "datasets_version": datasets.__version__, "huggingface_hub_version": huggingface_hub.__version__, "checks": checks, "scope": "local card parsing and CSV loading; live Hub viewer not tested"} def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check-datasets", action="store_true", help="Load all 11 local configs using datasets.") args = parser.parse_args() try: result = {"release": "EIROQ-PHI Hugging Face preparation 1.0.0-hf.1", "outer_manifest_entries_verified": verify_manifest(ROOT), "original_manifest_entries_verified": verify_manifest(ROOT / "research")} result["tables"], configs = validate_tables() result["links_and_syntax"] = validate_links_and_syntax() result["hf_loader"] = check_datasets(configs) if args.check_datasets else {"status": "not requested"} result["passed"] = True result["limitations"] = ["No upload performed", "No new laboratory measurements", "Original scientific test totals are preserved recorded evidence, not newly rerun here"] print(json.dumps(result, indent=2)) return 0 except Exception as exc: print(f"Validation failed ({type(exc).__name__}): {exc}", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())