Datasets:
Download scripts/validate.py from christian-bick/edugraph-bench: direct link, hf CLI and curl.
- Browser
- Download file 23.4 kB
-
https://huggingface.co/datasets/christian-bick/edugraph-bench/resolve/main/scripts/validate.py
- Command line
-
hf download hf://datasets/christian-bick/edugraph-bench/scripts/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/christian-bick/edugraph-bench/resolve/main/scripts/validate.py
23.4 kB
| #!/usr/bin/env python3 | |
| """Validate the external evaluation dataset without third-party dependencies. | |
| The JSON Schema documents individual rows. This validator additionally checks | |
| assets, provenance joins, ontology vocabulary, review state, and split isolation. | |
| A declared human review receipt is required for gold, but reviewer identity is not | |
| authenticated by this offline check. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| from datetime import datetime | |
| from pathlib import Path, PurePosixPath, PureWindowsPath | |
| import re | |
| import sys | |
| from urllib.parse import urlparse | |
| CORE_LICENSES = frozenset({"CC0-1.0", "PDM-1.0", "CC-BY-3.0", "CC-BY-4.0"}) | |
| SPLITS = frozenset({"development", "test"}) | |
| IMAGE_EXTENSIONS = frozenset({ | |
| ".png", ".apng", ".jpg", ".jpeg", ".jfif", ".webp", ".bmp", ".dib", | |
| ".gif", ".tif", ".tiff", ".ico", ".avif", ".heic", ".heif", ".jp2", | |
| ".jxl", ".pnm", ".ppm", ".pgm", ".pbm", | |
| }) | |
| HASH_PATTERN = re.compile(r"^[0-9a-f]{64}$") | |
| LABEL_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$") | |
| VERSION_PATTERN = re.compile(r"^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?$") | |
| TIMESTAMP_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})$") | |
| REQUIRED_FIELDS = frozenset({ | |
| "file_name", "sample_id", "task_id", "document_id", "family_id", "source_id", | |
| "split", "labels", "proposed_labels", "solution", "annotation_status", | |
| "annotation_method", "ontology_version", "annotation_policy_version", | |
| "source_url", "license", "license_url", "attribution", "page", "crop_bbox", | |
| "context_bbox", "image_sha256", "original_sha256", "exposure_status", | |
| "original_path", | |
| }) | |
| def _object(pairs: list[tuple[str, object]]) -> dict: | |
| result = {} | |
| for key, value in pairs: | |
| if key in result: | |
| raise ValueError(f"duplicate JSON key: {key}") | |
| result[key] = value | |
| return result | |
| def _read_json(path: Path, errors: list[str]) -> dict: | |
| try: | |
| value = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_object) | |
| if not isinstance(value, dict): | |
| raise ValueError("expected a JSON object") | |
| return value | |
| except (OSError, UnicodeError, ValueError) as exc: | |
| errors.append(f"{path.name}: {exc}") | |
| return {} | |
| def _text(value: object) -> bool: | |
| return isinstance(value, str) and bool(value.strip()) | |
| def _url(value: object) -> bool: | |
| if not isinstance(value, str): | |
| return False | |
| try: | |
| parsed = urlparse(value) | |
| return parsed.scheme in {"http", "https"} and bool(parsed.netloc) | |
| except ValueError: | |
| return False | |
| def _hash(value: object) -> bool: | |
| return isinstance(value, str) and HASH_PATTERN.fullmatch(value) is not None | |
| def _positive_integer(value: object) -> bool: | |
| return type(value) is int and value > 0 | |
| def _number(value: object) -> bool: | |
| return type(value) is int or (type(value) is float and math.isfinite(value)) | |
| def _choice(value: object, choices: set | frozenset) -> bool: | |
| return isinstance(value, str) and value in choices | |
| def _bbox(value: object) -> bool: | |
| return (isinstance(value, list) and len(value) == 4 | |
| and all(_number(v) for v in value) | |
| and 0 <= value[0] < value[2] and 0 <= value[1] < value[3]) | |
| def _labels(value: object) -> bool: | |
| return (isinstance(value, list) | |
| and all(isinstance(v, str) and LABEL_PATTERN.fullmatch(v) for v in value) | |
| and len(value) == len(set(value))) | |
| def _resolve_file(base: Path, relative: object, label: str, errors: list[str]) -> Path | None: | |
| if not _text(relative): | |
| errors.append(f"{label}: expected a nonempty relative file path") | |
| return None | |
| posix = PurePosixPath(relative) | |
| windows = PureWindowsPath(relative) | |
| if ("\\" in relative or posix.is_absolute() or windows.drive or windows.is_absolute() | |
| or ".." in posix.parts or relative != posix.as_posix() or ":" in relative): | |
| errors.append(f"{label}: path must be normalized, relative, and cannot escape its root") | |
| return None | |
| try: | |
| path = (base / relative).resolve() | |
| path.relative_to(base.resolve()) | |
| except (ValueError, OSError): | |
| errors.append(f"{label}: path escapes its root") | |
| return None | |
| if not path.is_file(): | |
| errors.append(f"{label}: file does not exist: {relative}") | |
| return None | |
| return path | |
| def _file_hash(path: Path, cache: dict[Path, str], errors: list[str]) -> str | None: | |
| if path not in cache: | |
| try: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as stream: | |
| for block in iter(lambda: stream.read(1024 * 1024), b""): | |
| digest.update(block) | |
| cache[path] = digest.hexdigest() | |
| except OSError as exc: | |
| errors.append(f"{path.name}: cannot hash file: {exc}") | |
| return None | |
| return cache[path] | |
| def _index(payload: dict, collection: str, id_field: str, errors: list[str]) -> dict[str, dict]: | |
| entries = payload.get(collection) | |
| if not isinstance(entries, list): | |
| errors.append(f"{collection}: expected a list") | |
| return {} | |
| index = {} | |
| for number, entry in enumerate(entries, 1): | |
| if not isinstance(entry, dict) or not _text(entry.get(id_field)): | |
| errors.append(f"{collection}[{number}]: missing {id_field}") | |
| continue | |
| key = entry[id_field] | |
| if key in index: | |
| errors.append(f"{collection}: duplicate {id_field}: {key}") | |
| else: | |
| index[key] = entry | |
| return index | |
| def _timestamp(value: object) -> datetime | None: | |
| if not isinstance(value, str) or not TIMESTAMP_PATTERN.fullmatch(value): | |
| return None | |
| try: | |
| result = datetime.fromisoformat(value.upper().replace("Z", "+00:00")) | |
| return result if result.tzinfo is not None else None | |
| except ValueError: | |
| return None | |
| def _review_receipt(value: object, row: dict) -> bool: | |
| """Check the declared two-human process, retaining independent judgments.""" | |
| if (not isinstance(value, dict) or not _text(value.get("adjudicator_id")) | |
| or not _text(value.get("rationale")) or value.get("decision") != "approved" | |
| or value.get("method") != "human"): | |
| return False | |
| reviewer_ids = value.get("reviewer_ids") | |
| reviews = value.get("reviews") | |
| if (not isinstance(reviewer_ids, list) or len(reviewer_ids) < 2 | |
| or not all(_text(v) for v in reviewer_ids) | |
| or len(set(reviewer_ids)) != len(reviewer_ids) | |
| or not isinstance(reviews, list) or len(reviews) != len(reviewer_ids)): | |
| return False | |
| adjudicated_at = _timestamp(value.get("adjudicated_at")) | |
| if adjudicated_at is None: | |
| return False | |
| if any(value.get(field) != row.get(field) | |
| for field in ("ontology_version", "annotation_policy_version")): | |
| return False | |
| seen = set() | |
| for review in reviews: | |
| if not isinstance(review, dict) or not _text(review.get("reviewer_id")): | |
| return False | |
| reviewer_id = review["reviewer_id"] | |
| reviewed_at = _timestamp(review.get("reviewed_at")) | |
| if (reviewer_id not in reviewer_ids or reviewer_id in seen | |
| or reviewed_at is None or reviewed_at > adjudicated_at | |
| or not _labels(review.get("labels"))): | |
| return False | |
| seen.add(reviewer_id) | |
| return seen == set(reviewer_ids) | |
| def _check_row_shape(row: dict, label: str, errors: list[str], require_gold: bool) -> None: | |
| missing = sorted(REQUIRED_FIELDS - row.keys()) | |
| if missing: | |
| errors.append(f"{label}: missing fields: {', '.join(missing)}") | |
| for field in ("sample_id", "task_id", "document_id", "family_id", "source_id", "attribution"): | |
| if not _text(row.get(field)): | |
| errors.append(f"{label}: {field} must be a nonempty string") | |
| for field in ("source_url", "license_url"): | |
| if not _url(row.get(field)): | |
| errors.append(f"{label}: {field} must be an HTTP(S) URL") | |
| for field in ("image_sha256", "original_sha256"): | |
| if not _hash(row.get(field)): | |
| errors.append(f"{label}: {field} must be a lowercase SHA-256") | |
| for field in ("ontology_version", "annotation_policy_version"): | |
| if not isinstance(row.get(field), str) or not VERSION_PATTERN.fullmatch(row[field]): | |
| errors.append(f"{label}: {field} must be a semantic version") | |
| if not _choice(row.get("license"), CORE_LICENSES): | |
| errors.append(f"{label}: license is outside the core allowlist") | |
| if type(row.get("solution")) is not bool: | |
| errors.append(f"{label}: solution must be a boolean") | |
| if not _positive_integer(row.get("page")): | |
| errors.append(f"{label}: page must be a positive 1-based integer") | |
| for field in ("crop_bbox", "context_bbox", "footer_bbox"): | |
| if field != "crop_bbox" and row.get(field) is None: | |
| continue | |
| if not _bbox(row.get(field)): | |
| errors.append(f"{label}: {field} must be an ordered nonnegative PDF-point box") | |
| if not _labels(row.get("proposed_labels")): | |
| errors.append(f"{label}: proposed_labels must contain unique ontology local names") | |
| status = row.get("annotation_status") | |
| if status == "proposed": | |
| if row.get("labels") is not None: | |
| errors.append(f"{label}: proposed annotations must keep labels null; proposals are not gold") | |
| if row.get("annotation_method") != "assistant_proposed": | |
| errors.append(f"{label}: proposed annotations require annotation_method assistant_proposed") | |
| if row.get("split") != "development" or row.get("exposure_status") != "development": | |
| errors.append(f"{label}: proposed annotations are development-only") | |
| elif status == "human_adjudicated": | |
| if not _labels(row.get("labels")) or not row.get("labels"): | |
| errors.append(f"{label}: human_adjudicated requires nonempty unique gold labels") | |
| if row.get("annotation_method") != "human_reviewed": | |
| errors.append(f"{label}: human_adjudicated requires annotation_method human_reviewed") | |
| if not _review_receipt(row.get("review_receipt"), row): | |
| errors.append(f"{label}: human_adjudicated requires a dated two-human review receipt with matching versions") | |
| else: | |
| errors.append(f"{label}: unknown annotation_status") | |
| if (require_gold or row.get("split") == "test") and status != "human_adjudicated": | |
| errors.append(f"{label}: scoring requires human_adjudicated gold") | |
| if not _choice(row.get("exposure_status"), {"development", "confirmation", "regression"}): | |
| errors.append(f"{label}: unknown exposure_status") | |
| if row.get("split") == "test" and row.get("exposure_status") == "development": | |
| errors.append(f"{label}: development-exposed samples cannot enter the test split") | |
| def validate_dataset(root: Path, *, require_gold: bool = False) -> list[str]: | |
| """Return deterministic validation errors; an empty list means valid packaging. | |
| By default proposed annotations are accepted in development only. Use | |
| ``require_gold`` before scoring to reject any remaining proposals. | |
| """ | |
| root = Path(root).resolve() | |
| errors: list[str] = [] | |
| hashes: dict[Path, str] = {} | |
| registry = _read_json(root / "sources/registry.json", errors) | |
| if registry.get("schema_version") != "0.1.0": | |
| errors.append("registry: unsupported schema_version (expected 0.1.0)") | |
| sources = _index(registry, "sources", "source_id", errors) | |
| documents = _index(_read_json(root / "sources/documents.json", errors), "documents", "document_id", errors) | |
| ontology = _read_json(root / "sources/ontology.json", errors) | |
| vocabulary = ontology.get("eligible_labels") | |
| if not _labels(vocabulary) or not vocabulary: | |
| errors.append("ontology: eligible_labels must be a nonempty list of unique local names") | |
| vocabulary = [] | |
| vocabulary = set(vocabulary) | |
| for field in ("version", "repository", "revision"): | |
| if not _text(ontology.get(field)): | |
| errors.append(f"ontology: missing {field}") | |
| if not _hash(ontology.get("snapshot_sha256")): | |
| errors.append("ontology: missing or invalid snapshot_sha256") | |
| dimensions = ontology.get("dimensions") | |
| if (not isinstance(dimensions, dict) or set(dimensions) != vocabulary | |
| or not all(_choice(v, {"areas", "scopes", "abilities"}) for v in dimensions.values())): | |
| errors.append("ontology: dimensions must map every eligible label exactly once to a valid dimension") | |
| else: | |
| canonical = json.dumps(dimensions, sort_keys=True, separators=(",", ":"), ensure_ascii=False) | |
| if hashlib.sha256(canonical.encode("utf-8")).hexdigest() != ontology.get("snapshot_sha256"): | |
| errors.append("ontology: snapshot SHA-256 does not match canonical dimensions map") | |
| for source_id, source in sources.items(): | |
| if not _choice(source.get("status"), {"approved", "candidate", "excluded"}): | |
| errors.append(f"source {source_id}: unknown status") | |
| if source.get("status") == "approved": | |
| if not _choice(source.get("license"), CORE_LICENSES): | |
| errors.append(f"source {source_id}: license is outside the core allowlist") | |
| for field in ("license_url", "evidence_url"): | |
| if not _url(source.get(field)): | |
| errors.append(f"source {source_id}: missing or invalid {field}") | |
| page_sizes: dict[str, dict[int, tuple[float, float]]] = {} | |
| for document_id, document in documents.items(): | |
| label = f"document {document_id}" | |
| source = sources.get(document.get("source_id")) if isinstance(document.get("source_id"), str) else None | |
| if source is None or source.get("status") != "approved": | |
| errors.append(f"{label}: source must exist and be approved") | |
| for field in ("license", "license_url"): | |
| if source is not None and document.get(field) != source.get(field): | |
| errors.append(f"{label}: {field} does not match source registry") | |
| if not _text(document.get("family_id")): | |
| errors.append(f"{label}: missing family_id") | |
| if not _url(document.get("source_url")): | |
| errors.append(f"{label}: missing or invalid source_url") | |
| path = _resolve_file(root, document.get("path"), f"{label} path", errors) | |
| if not _hash(document.get("sha256")): | |
| errors.append(f"{label}: invalid sha256") | |
| elif path is not None and _file_hash(path, hashes, errors) != document["sha256"]: | |
| errors.append(f"{label}: original file SHA-256 mismatch") | |
| if "page_count" in document and not _positive_integer(document["page_count"]): | |
| errors.append(f"{label}: invalid page_count") | |
| sizes = {} | |
| pages = document.get("pages", []) | |
| if not isinstance(pages, list): | |
| errors.append(f"{label}: pages must be a list") | |
| pages = [] | |
| for page in pages: | |
| if (not isinstance(page, dict) or not _positive_integer(page.get("page")) | |
| or not _number(page.get("width_pt")) or page["width_pt"] <= 0 | |
| or not _number(page.get("height_pt")) or page["height_pt"] <= 0): | |
| errors.append(f"{label}: invalid page dimensions") | |
| continue | |
| if page["page"] in sizes: | |
| errors.append(f"{label}: duplicate page dimensions") | |
| if _positive_integer(document.get("page_count")) and page["page"] > document["page_count"]: | |
| errors.append(f"{label}: dimensions exceed page_count") | |
| sizes[page["page"]] = (page["width_pt"], page["height_pt"]) | |
| page_sizes[document_id] = sizes | |
| sample_ids: set[str] = set() | |
| image_paths: set[Path] = set() | |
| registered_image_paths: set[Path] = set() | |
| groups: dict[tuple[str, str], str] = {} | |
| seen_images: dict[str, tuple[str, str]] = {} | |
| row_count = 0 | |
| metadata_files = sorted((root / "data").glob("*/metadata.jsonl")) | |
| if not metadata_files: | |
| errors.append("data: no split metadata.jsonl files found") | |
| for metadata_path in metadata_files: | |
| split = metadata_path.parent.name | |
| try: | |
| metadata_path.resolve().relative_to(root) | |
| except ValueError: | |
| errors.append(f"data/{split}: metadata path escapes dataset root") | |
| continue | |
| if split not in SPLITS: | |
| errors.append(f"data/{split}: unsupported split") | |
| try: | |
| lines = metadata_path.read_text(encoding="utf-8").splitlines() | |
| except (OSError, UnicodeError) as exc: | |
| errors.append(f"{metadata_path}: cannot read metadata: {exc}") | |
| continue | |
| for line_number, line in enumerate(lines, 1): | |
| if not line.strip(): | |
| continue | |
| label = f"data/{split}/metadata.jsonl:{line_number}" | |
| try: | |
| row = json.loads(line, object_pairs_hook=_object) | |
| if not isinstance(row, dict): | |
| raise ValueError("expected an object") | |
| except ValueError as exc: | |
| errors.append(f"{label}: malformed row: {exc}") | |
| continue | |
| row_count += 1 | |
| _check_row_shape(row, label, errors, require_gold) | |
| if row.get("split") != split: | |
| errors.append(f"{label}: split must match containing directory") | |
| sample_id = row.get("sample_id") | |
| if isinstance(sample_id, str): | |
| if sample_id in sample_ids: | |
| errors.append(f"{label}: duplicate sample_id: {sample_id}") | |
| sample_ids.add(sample_id) | |
| for field in ("task_id", "document_id", "family_id", "original_sha256"): | |
| if isinstance(row.get(field), str): | |
| key = (field, row[field]) | |
| if key in groups and groups[key] != split: | |
| errors.append(f"{label}: {field} appears across splits: {row[field]}") | |
| groups[key] = split | |
| if row.get("ontology_version") != ontology.get("version"): | |
| errors.append(f"{label}: ontology_version does not match pinned ontology") | |
| for field in ("labels", "proposed_labels"): | |
| if _labels(row.get(field)): | |
| unknown = sorted(set(row[field]) - vocabulary) | |
| if unknown: | |
| errors.append(f"{label}: {field} contains unknown or ineligible labels: {', '.join(unknown)}") | |
| receipt = row.get("review_receipt") | |
| if isinstance(receipt, dict) and isinstance(receipt.get("reviews"), list): | |
| for review in receipt["reviews"]: | |
| if isinstance(review, dict) and _labels(review.get("labels")): | |
| unknown = sorted(set(review["labels"]) - vocabulary) | |
| if unknown: | |
| errors.append(f"{label}: human review contains unknown or ineligible labels: {', '.join(unknown)}") | |
| source = sources.get(row.get("source_id")) if isinstance(row.get("source_id"), str) else None | |
| if source is None or source.get("status") != "approved": | |
| errors.append(f"{label}: source must exist and be approved") | |
| document = documents.get(row.get("document_id")) if isinstance(row.get("document_id"), str) else None | |
| if document is None: | |
| errors.append(f"{label}: document_id does not exist") | |
| else: | |
| for field, document_field in (("source_id", "source_id"), ("family_id", "family_id"), | |
| ("source_url", "source_url"), ("license", "license"), ("license_url", "license_url"), | |
| ("original_path", "path"), ("original_sha256", "sha256")): | |
| if row.get(field) != document.get(document_field): | |
| errors.append(f"{label}: {field} does not match document provenance") | |
| page_number = row.get("page") | |
| if _positive_integer(page_number): | |
| if _positive_integer(document.get("page_count")) and page_number > document["page_count"]: | |
| errors.append(f"{label}: page exceeds document page_count") | |
| sizes = page_sizes.get(row["document_id"], {}) | |
| if sizes and page_number not in sizes: | |
| errors.append(f"{label}: page has no recorded dimensions") | |
| if page_number in sizes: | |
| width, height = sizes[page_number] | |
| for field in ("crop_bbox", "context_bbox", "footer_bbox"): | |
| box = row.get(field) | |
| if _bbox(box) and (box[2] > width or box[3] > height): | |
| errors.append(f"{label}: {field} extends outside PDF page bounds") | |
| _resolve_file(root, row.get("original_path"), f"{label} original_path", errors) | |
| image_path = _resolve_file(metadata_path.parent, row.get("file_name"), f"{label} file_name", errors) | |
| if image_path is not None: | |
| registered_image_paths.add(metadata_path.parent / row["file_name"]) | |
| if image_path.suffix.lower() not in IMAGE_EXTENSIONS: | |
| errors.append(f"{label}: unsupported image extension") | |
| if image_path in image_paths: | |
| errors.append(f"{label}: duplicate image path") | |
| image_paths.add(image_path) | |
| image_hash = _file_hash(image_path, hashes, errors) | |
| if image_hash != row.get("image_sha256"): | |
| errors.append(f"{label}: image SHA-256 mismatch") | |
| if image_hash is not None: | |
| if image_hash in seen_images and seen_images[image_hash][0] != split: | |
| errors.append(f"{label}: identical image bytes appear across splits") | |
| seen_images[image_hash] = (split, label) | |
| for image_path in sorted((root / "data").rglob("*")): | |
| if (image_path.is_file() and image_path.suffix.lower() in IMAGE_EXTENSIONS | |
| and image_path not in registered_image_paths): | |
| errors.append(f"{image_path.relative_to(root).as_posix()}: orphan image is not registered in split metadata") | |
| if not row_count: | |
| errors.append("data: no sample rows found") | |
| return errors | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument("--require-gold", action="store_true", help="Reject proposals before scoring.") | |
| args = parser.parse_args(argv) | |
| errors = validate_dataset(args.root, require_gold=args.require_gold) | |
| if errors: | |
| for error in errors: | |
| print(f"ERROR: {error}", file=sys.stderr) | |
| print(f"Validation failed: {len(errors)} error(s).", file=sys.stderr) | |
| return 1 | |
| print("Validation passed: provenance, assets, labels, annotation state, and splits.") | |
| if not args.require_gold: | |
| print("Development proposals may be present. Use --require-gold before scoring.") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |