Datasets:
v2.1.0: Full-archive Layer 3 topological trajectories, tlaw physical-anchor homography, and work-grouped train/val/test benchmark splits
c14da2e Download tools/validate_derived_v2.py from maxwellinked/time-lapse-artifacts-derived: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts-derived/resolve/main/tools/validate_derived_v2.py
- Command line
-
hf download hf://datasets/maxwellinked/time-lapse-artifacts-derived/tools/validate_derived_v2.py
-
curl -L -o validate_derived_v2.py https://huggingface.co/datasets/maxwellinked/time-lapse-artifacts-derived/resolve/main/tools/validate_derived_v2.py
10.8 kB
| #!/usr/bin/env python3 | |
| """Validate Time-Lapse Artifacts Derived v2.1.0 tables, native benchmark splits, | |
| JSON Schemas, split disjointness, epistemic/path-leak guardrails, and Dataset Card metadata. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import re | |
| import warnings | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import jsonschema | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import DatasetCard | |
| EXPECTED_CANONICAL_REPO = "maxwellinked/time-lapse-artifacts" | |
| EXPECTED_CANONICAL_REVISION = "1af2da013370104ca579485f5a28c51ee4c5c8cf" | |
| EXPECTED_CANONICAL_TAG = "v2.0.0" | |
| _FORBIDDEN_TOKEN = "hf" + "-" + "work" | |
| LEAK_RE = re.compile(rf"(?i)([c-e]:[\\/]|{_FORBIDDEN_TOKEN})") | |
| EXPECTED_TABLES = { | |
| "records_telemetry_v2": 1388, | |
| "works_trajectories_v2": 442, | |
| "transitions_v2": 946, | |
| "splits_v2": 1388, | |
| "deferred_cv_v2": 1388, | |
| "progress_21pt_index_v2": 29148, | |
| "records_manifests_v2": 1388, | |
| "topological_trajectories_v21": 1388, | |
| "topological_frames_v21": 29148, | |
| } | |
| EXPECTED_BENCHMARKS = { | |
| "stratified_v2": {"train": (1092, 354), "validation": (135, 44), "test": (161, 44)}, | |
| "temporal_v2": {"train": (438, 354), "validation": (478, 44), "test": (472, 44)}, | |
| } | |
| def validate_derived_root(root: Path) -> dict: | |
| # 1. Dataset Card YAML & zero-warning DatasetCardData check | |
| readme_path = root / "README.md" | |
| with warnings.catch_warnings(record=True) as w: | |
| warnings.simplefilter("always") | |
| card = DatasetCard.load(readme_path) | |
| if w: | |
| raise ValueError(f"DatasetCard emitted Hub warnings: {[str(x.message) for x in w]}") | |
| if card.data.get("license") != "cc-by-nc-4.0": | |
| raise ValueError(f"Expected YAML frontmatter license 'cc-by-nc-4.0', got {card.data.get('license')!r}") | |
| if card.data.get("size_categories") != ["10K<n<100K"]: | |
| raise ValueError(f"Expected size_categories ['10K<n<100K'], got {card.data.get('size_categories')!r}") | |
| if card.data.get("dataset_info") is not None: | |
| raise ValueError("Manual dataset_info block must be omitted so datasets-server computes coherent sizes") | |
| configs = card.data.get("configs") or [] | |
| cfg_names = [c["config_name"] for c in configs] | |
| seen_paths: set[str] = set() | |
| for c in configs: | |
| for df in c.get("data_files", []): | |
| p_val = df["path"] | |
| paths = [p_val] if isinstance(p_val, str) else list(p_val) | |
| for p_str in paths: | |
| if p_str in seen_paths: | |
| raise ValueError(f"Overlapping data_files path across configs: {p_str}") | |
| seen_paths.add(p_str) | |
| if not (root / p_str).is_file(): | |
| raise FileNotFoundError(f"Config data_file missing on disk: {p_str}") | |
| for req_cfg in ( | |
| "records_telemetry_v2", | |
| "benchmark_stratified_v2", | |
| "benchmark_temporal_v2", | |
| "topological_trajectories_v21", | |
| "topological_frames_v21", | |
| "works_trajectories_v2", | |
| "transitions_v2", | |
| "splits_v2", | |
| "deferred_cv_v2", | |
| "progress_21pt_index_v2", | |
| "records_manifests_v2", | |
| ): | |
| if req_cfg not in cfg_names: | |
| raise ValueError(f"Missing Dataset Viewer config in README.md: {req_cfg}") | |
| for req_doc in ( | |
| "CURATORIAL_EVOLUTION.md", | |
| "DERIVATION_CONTRACT.md", | |
| "LICENSE", | |
| "docs/V210_TOPOLOGY_REPORT.md", | |
| "tools/extract_shard_topology.py", | |
| ): | |
| if not (root / req_doc).is_file(): | |
| raise FileNotFoundError(f"Missing required document/tool: {req_doc}") | |
| # 2. Parquet & CSV integrity + 0 NaN/Inf + 0 local paths | |
| tables_dir = root / "tables" | |
| for name, exp_rows in EXPECTED_TABLES.items(): | |
| pq_path = tables_dir / f"{name}.parquet" | |
| if not pq_path.is_file(): | |
| raise FileNotFoundError(f"Missing table: {pq_path}") | |
| tbl = pq.read_table(pq_path) | |
| if tbl.num_rows != exp_rows: | |
| raise ValueError(f"{name}: expected {exp_rows} rows, got {tbl.num_rows}") | |
| for col in tbl.column_names: | |
| if LEAK_RE.search(col): | |
| raise ValueError(f"{name}: forbidden column name {col!r}") | |
| for idx, row in enumerate(tbl.to_pylist()): | |
| if "source_canonical_revision" in row: | |
| if row["source_canonical_revision"] != EXPECTED_CANONICAL_REVISION: | |
| raise ValueError(f"{name}[{idx}]: bad source_canonical_revision") | |
| if row["source_canonical_tag"] != EXPECTED_CANONICAL_TAG: | |
| raise ValueError(f"{name}[{idx}]: bad source_canonical_tag") | |
| for k, v in row.items(): | |
| if isinstance(v, float) and (math.isnan(v) or math.isinf(v)): | |
| raise ValueError(f"{name}[{idx}].{k} contains NaN/Inf: {v}") | |
| if isinstance(v, str) and LEAK_RE.search(v): | |
| raise ValueError(f"{name}[{idx}].{k} contains local path leak: {v!r}") | |
| # 3. Cross-split work_id disjointness across all split-bearing tables and pre-sliced benchmark subsets | |
| for tname in ( | |
| "splits_v2", | |
| "records_telemetry_v2", | |
| "works_trajectories_v2", | |
| "transitions_v2", | |
| "topological_trajectories_v21", | |
| ): | |
| rows = pq.read_table(tables_dir / f"{tname}.parquet").to_pylist() | |
| for sp_col in ("split_stratified_v2", "split_temporal_v2"): | |
| by_sp: dict[str, set[str]] = defaultdict(set) | |
| for r in rows: | |
| by_sp[r[sp_col]].add(r["work_id"]) | |
| if ( | |
| (by_sp["train"] & by_sp["val"]) | |
| or (by_sp["train"] & by_sp["test"]) | |
| or (by_sp["val"] & by_sp["test"]) | |
| ): | |
| raise ValueError(f"{tname}.{sp_col} has cross-split work_id leakage") | |
| for regime, sp_spec in EXPECTED_BENCHMARKS.items(): | |
| works_by_sp: dict[str, set[str]] = {} | |
| total_rows = 0 | |
| for sp_name, (exp_r, exp_w) in sp_spec.items(): | |
| bp = tables_dir / "benchmarks" / regime / f"{sp_name}.parquet" | |
| if not bp.is_file(): | |
| raise FileNotFoundError(f"Missing benchmark split Parquet: {bp}") | |
| btbl = pq.read_table(bp) | |
| if btbl.num_rows != exp_r: | |
| raise ValueError(f"benchmarks/{regime}/{sp_name}: expected {exp_r} rows, got {btbl.num_rows}") | |
| brows = btbl.to_pylist() | |
| total_rows += len(brows) | |
| wset = {str(r["work_id"]) for r in brows} | |
| if len(wset) != exp_w: | |
| raise ValueError(f"benchmarks/{regime}/{sp_name}: expected {exp_w} works, got {len(wset)}") | |
| works_by_sp[sp_name] = wset | |
| for idx, row in enumerate(brows): | |
| for k, v in row.items(): | |
| if isinstance(v, float) and (math.isnan(v) or math.isinf(v)): | |
| raise ValueError(f"benchmarks/{regime}/{sp_name}[{idx}].{k} NaN/Inf: {v}") | |
| if isinstance(v, str) and LEAK_RE.search(v): | |
| raise ValueError(f"benchmarks/{regime}/{sp_name}[{idx}].{k} leak: {v!r}") | |
| if total_rows != 1388: | |
| raise ValueError(f"benchmarks/{regime}: expected 1388 total rows, got {total_rows}") | |
| if ( | |
| (works_by_sp["train"] & works_by_sp["validation"]) | |
| or (works_by_sp["train"] & works_by_sp["test"]) | |
| or (works_by_sp["validation"] & works_by_sp["test"]) | |
| ): | |
| raise ValueError(f"benchmarks/{regime}: cross-split work_id overlap detected") | |
| # 4. JSON Schema validation across records_manifests_v2.jsonl (1,388) and topology_manifests_v21.jsonl (1,388) | |
| schema_path = root / "schemas" / "derivation-manifest.schema.json" | |
| schema = json.loads(schema_path.read_text(encoding="utf-8")) | |
| val_cls = jsonschema.validators.validator_for(schema) | |
| val_cls.check_schema(schema) | |
| validator = val_cls(schema) | |
| cur_schema = json.loads((root / "schemas" / "curatorial_process.v1.schema.json").read_text(encoding="utf-8")) | |
| top_schema = json.loads((root / "schemas" / "topology_trajectory.v1.schema.json").read_text(encoding="utf-8")) | |
| jsonschema.Draft202012Validator.check_schema(cur_schema) | |
| jsonschema.Draft202012Validator.check_schema(top_schema) | |
| top_validator = jsonschema.Draft202012Validator(top_schema) | |
| jsonl_path = tables_dir / "records_manifests_v2.jsonl" | |
| lines = [ln for ln in jsonl_path.read_text(encoding="utf-8").splitlines() if ln.strip()] | |
| if len(lines) != 1388: | |
| raise ValueError(f"Expected 1,388 JSONL manifests, got {len(lines)}") | |
| for line in lines: | |
| if LEAK_RE.search(line): | |
| raise ValueError("Local path leak in records_manifests_v2.jsonl") | |
| validator.validate(json.loads(line)) | |
| expected_script_sha = hashlib.sha256((root / "tools" / "extract_shard_topology.py").read_bytes()).hexdigest() | |
| topo_jsonl_path = tables_dir / "topology_manifests_v21.jsonl" | |
| topo_lines = [ln for ln in topo_jsonl_path.read_text(encoding="utf-8").splitlines() if ln.strip()] | |
| if len(topo_lines) != 1388: | |
| raise ValueError(f"Expected 1,388 topology JSONL manifests, got {len(topo_lines)}") | |
| for line in topo_lines: | |
| if LEAK_RE.search(line): | |
| raise ValueError("Local path leak in topology_manifests_v21.jsonl") | |
| tdoc = json.loads(line) | |
| top_validator.validate(tdoc) | |
| if tdoc["extractor_provenance"]["script_sha256"] != expected_script_sha: | |
| raise ValueError("topology_manifests_v21.jsonl script_sha256 mismatch with tools/extract_shard_topology.py") | |
| # 5. Scan all Markdown, CSV, JSON, LICENSE, and Python files under root for local path leaks | |
| for p in root.rglob("*"): | |
| if not p.is_file() or ".git" in p.parts or "__pycache__" in p.parts or ".pytest_cache" in p.parts: | |
| continue | |
| if p.name in {"LICENSE", ".gitattributes"} or p.suffix.lower() in {".md", ".csv", ".json", ".py"}: | |
| txt = p.read_text(encoding="utf-8", errors="replace") | |
| if LEAK_RE.search(txt): | |
| raise ValueError(f"Forbidden local workstation path in {p.relative_to(root)}") | |
| return { | |
| "status": "passed", | |
| "source_canonical_revision": EXPECTED_CANONICAL_REVISION, | |
| "configs": cfg_names, | |
| "verified_tables": EXPECTED_TABLES, | |
| "verified_jsonl_manifests": len(lines), | |
| "verified_topology_manifests_v21": len(topo_lines), | |
| "verified_script_sha256": expected_script_sha, | |
| } | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) | |
| args = ap.parse_args() | |
| res = validate_derived_root(args.root.resolve()) | |
| print(json.dumps(res, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |