Datasets:
Download scripts/verify_hf_dataset.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 8.81 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/scripts/verify_hf_dataset.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/scripts/verify_hf_dataset.py
-
curl -L -o verify_hf_dataset.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/scripts/verify_hf_dataset.py
8.81 kB
| #!/usr/bin/env python3 | |
| """Offline integrity, HF loading, cohort, image, and source-label validation.""" | |
| from __future__ import annotations | |
| import argparse | |
| import io | |
| import json | |
| import os | |
| import sys | |
| from collections import Counter, defaultdict | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| from hf_release_common import ( | |
| STATES, | |
| digest, | |
| file_digest, | |
| read_json, | |
| read_rows, | |
| safe_path, | |
| write_json, | |
| ) | |
| def verify_proof(row): | |
| from explicit_learning.certificates.bounded_plot import verify_bounded_plot | |
| result = verify_bounded_plot(row) | |
| if not result["ok"]: | |
| raise ValueError("Invalid chart proof " + str(result)) | |
| return row["group_id"] | |
| def verify(dataset, workers, pre_seal=False): | |
| sys.path.insert(0, str(dataset / "src")) | |
| os.environ["HF_HUB_OFFLINE"] = "1" | |
| os.environ["HF_DATASETS_OFFLINE"] = "1" | |
| from datasets import Image as HFImage | |
| from datasets import load_dataset | |
| from PIL import Image | |
| from explicit_learning.certificates.build import program_from_dict | |
| from explicit_learning.executors.clevr import ClevrExecutor | |
| from explicit_learning.executors.plot import PlotExecutor | |
| if not pre_seal: | |
| manifest = read_json(dataset / "MANIFEST.json") | |
| actual = { | |
| str(path.relative_to(dataset)) | |
| for path in dataset.rglob("*") | |
| if path.is_file() and "__pycache__" not in path.parts and path.name != "MANIFEST.json" | |
| } | |
| if actual != set(manifest["files"]): | |
| raise ValueError("Frozen file set changed") | |
| for relative, item in manifest["files"].items(): | |
| path = safe_path(dataset, relative) | |
| if path.stat().st_size != item["bytes"] or file_digest(path) != item["sha256"]: | |
| raise ValueError("Frozen file changed: " + relative) | |
| labels = read_rows(dataset / "metadata/views.jsonl.gz") | |
| by_id = {row["item_id"]: row for row in labels} | |
| if len(labels) != len(by_id) or Counter(row["source"] for row in labels) != { | |
| "plotqa": 5000, | |
| "clevr": 4000, | |
| "gqa": 3000, | |
| }: | |
| raise ValueError("Wrong cohort") | |
| groups = defaultdict(list) | |
| image_ids = defaultdict(set) | |
| for row in labels: | |
| groups[row["group_id"]].append(row) | |
| image_ids[row["source"]].add(row["source_image_id"]) | |
| if len(groups) != 3000 or any(len(ids) != 1000 for ids in image_ids.values()): | |
| raise ValueError("Group/source-image uniqueness differs") | |
| for rows in groups.values(): | |
| if len(rows) != len(STATES[rows[0]["source"]]) or {row["state"] for row in rows} != set( | |
| STATES[rows[0]["source"]] | |
| ): | |
| raise ValueError("Incomplete state group") | |
| if len({row["question_sha256"] for row in rows}) != 1: | |
| raise ValueError("Sibling questions differ") | |
| seen, image_checks = set(), 0 | |
| for source in STATES: | |
| # Exercise the README's actual config discovery, not just a Parquet reader. | |
| data = load_dataset(str(dataset), name=source, split="test").cast_column( | |
| "image", HFImage(decode=False) | |
| ) | |
| if len(data) != {"plotqa": 5000, "clevr": 4000, "gqa": 3000}[source]: | |
| raise ValueError("HF configuration row count differs") | |
| for row in data: | |
| if row["item_id"] in seen: | |
| raise ValueError("Repeated HF item") | |
| seen.add(row["item_id"]) | |
| if {key: value for key, value in row.items() if key != "image"} != by_id[ | |
| row["item_id"] | |
| ]: | |
| raise ValueError("HF metadata differs from scoring metadata") | |
| if source == "gqa": | |
| if row["image"] is not None or row["question"] is not None: | |
| raise ValueError("GQA upstream media/text present in the upload candidate") | |
| continue | |
| blob = row["image"]["bytes"] | |
| if digest(blob) != row["image_sha256"]: | |
| raise ValueError("Image bytes changed in Parquet") | |
| with Image.open(io.BytesIO(blob)) as image: | |
| image.load() | |
| if image.size != (row["width"], row["height"]): | |
| raise ValueError("Image dimensions changed") | |
| image_checks += 1 | |
| if seen != set(by_id): | |
| raise ValueError("HF and scoring IDs differ") | |
| proofs = read_rows(dataset / "evidence/plotqa/bounded-witness-proofs.jsonl.gz") | |
| plot_groups = {gid: rows for gid, rows in groups.items() if rows[0]["source"] == "plotqa"} | |
| if len(proofs) != len({proof["group_id"] for proof in proofs}) or { | |
| proof["group_id"] for proof in proofs | |
| } != set(plot_groups): | |
| raise ValueError("Proof cohort differs") | |
| import base64 | |
| for proof in proofs: | |
| rows = plot_groups[proof["group_id"]] | |
| if any( | |
| proof["source_native_id"] != row["source_question_id"] | |
| or proof["question"] != row["question"] | |
| for row in rows | |
| ): | |
| raise ValueError("Proof question/source join failed") | |
| missing = next(row for row in rows if row["state"] == "U_MISSING") | |
| if ( | |
| digest(base64.b64decode(proof["observed_png_base64"], validate=True)) | |
| != missing["image_sha256"] | |
| ): | |
| raise ValueError("Proof observation is not the evaluated image") | |
| with ProcessPoolExecutor(max_workers=workers) as pool: | |
| checked = list(pool.map(verify_proof, proofs, chunksize=5)) | |
| semantic_checks = Counter() | |
| for source, executor in (("plotqa", PlotExecutor()), ("clevr", ClevrExecutor())): | |
| for row in read_rows(dataset / f"evidence/{source}/views.jsonl.gz"): | |
| label = by_id[row["item_id"]] | |
| program = program_from_dict(row["program"]) | |
| result = executor.execute(program, world=row["world_after"]) | |
| if label["answerable"]: | |
| if result.status != "UNIQUE" or str(result.answer_canonical) != label["target"]: | |
| raise ValueError("Supported source-program target differs: " + row["item_id"]) | |
| elif ( | |
| result.status | |
| != {"U_MISSING": "MISSING_INFORMATION", "U_INVALID": "INVALID_REFERENT"}[ | |
| row["state"] | |
| ] | |
| ): | |
| raise ValueError("Unanswerable source-program failure category differs") | |
| if source == "clevr" and row["state"] == "U_MISSING": | |
| a, b = [ | |
| executor.execute(program, world=row[key]) | |
| for key in ("completion_a", "completion_b") | |
| ] | |
| if ( | |
| a.status != "UNIQUE" | |
| or b.status != "UNIQUE" | |
| or a.answer_canonical == b.answer_canonical | |
| ): | |
| raise ValueError("CLEVR symbolic alternatives fail") | |
| semantic_checks[source] += 1 | |
| recipes = read_rows(dataset / "evidence/gqa/reconstruction.jsonl.gz") | |
| if len(recipes) != 3000 or {row["item_id"] for row in recipes} != { | |
| row["item_id"] for row in labels if row["source"] == "gqa" | |
| }: | |
| raise ValueError("GQA reconstruction coverage differs") | |
| if sum(row["gqa_location_stratum"] for row in recipes) != 376 * 3: | |
| raise ValueError("GQA sensitivity stratum changed") | |
| return { | |
| "status": "passed", | |
| "hf_configs": list(STATES), | |
| "unique_views": len(seen), | |
| "source_groups": len(groups), | |
| "embedded_images_decoded_and_hashed": image_checks, | |
| "proofs_verified": len(checked), | |
| "proof_observations_match_evaluated_images": len(proofs), | |
| "source_program_checks": dict(semantic_checks), | |
| "gqa_recipes": len(recipes), | |
| "gqa_location_groups": 376, | |
| "gqa_hydration": "separate reconstruction-validation.json", | |
| "file_manifest_verified": not pre_seal, | |
| "network_calls": 0, | |
| "publication_performed": False, | |
| } | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--dataset", type=Path, default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument("--workers", type=int, default=8) | |
| parser.add_argument( | |
| "--pre-seal", | |
| action="store_true", | |
| help="Maintainer validation before creating MANIFEST.json", | |
| ) | |
| parser.add_argument("--output", type=Path, required=True) | |
| args = parser.parse_args() | |
| if args.workers < 1: | |
| parser.error("workers must be positive") | |
| if args.output.resolve().is_relative_to(args.dataset.resolve()): | |
| parser.error("Write validation outside the frozen dataset directory") | |
| report = verify(args.dataset.resolve(), args.workers, args.pre_seal) | |
| write_json(args.output, report) | |
| print(json.dumps(report)) | |