Datasets:
Download src/explicit_learning/ingest/base.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/ingest/base.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/ingest/base.py
-
curl -L -o base.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/ingest/base.py
17.3 kB
| """Common normalized item schema, content-addressed images, and the eval registry. | |
| Stage 1 of the data pipeline (``docs/02_DATA_PIPELINE.md`` §4) maps every source | |
| row to one immutable :class:`NormalizedItem` matching | |
| ``schemas/normalized_item.schema.json``. The canonical ``base_id`` is the | |
| content-addressed hash of ``docs/02`` §3.1 (source identity + question + | |
| choices + image family); ``question_sha256`` / ``choices_sha256`` are over the | |
| exact UTF-8 source bytes (the model input string is never normalized). Images | |
| are content-addressed by their SHA-256 so the same bytes are stored once and | |
| referenced by hash from any mount. | |
| Stage 0 (``docs/02`` §3) freezes the evaluation registry | |
| (``evaluation_items.v1.jsonl``) *before* any training source is touched. The | |
| registry is write-once: a second freeze that would change its bytes is a hard | |
| failure, never a silent overwrite. | |
| """ | |
| from __future__ import annotations | |
| from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import Any, Literal | |
| from ..atomic_io import JsonlAppender, atomic_write_bytes, atomic_write_jsonl, read_jsonl | |
| from ..hashing import ( | |
| base_id as compute_base_id, | |
| ) | |
| from ..hashing import ( | |
| canonical_json, | |
| choices_sha256, | |
| sha256_bytes, | |
| ) | |
| from ..hashing import ( | |
| image_family_sha256 as compute_image_family_sha256, | |
| ) | |
| from ..hashing import question_sha256 as compute_question_sha256 | |
| from ..paths import repo_root | |
| from ..schema_io import load_schema, validate | |
| SCHEMA_VERSION = 2 | |
| AnswerType = Literal["multiple_choice", "integer", "number", "expression", "short_text", "boolean"] | |
| # ADR-0002 normalized-item policies (schemas/normalized_item.schema.json v2). | |
| # C1 rows come from source-native structured worlds (PlotQA, Geometry3K); C2 rows | |
| # are dual-compiled train candidates; untouched rows are retention-eval only; | |
| # blocked rows are held back and never substituted. | |
| Policy = Literal[ | |
| "c1_train_candidate", | |
| "c1_certified_eval_candidate", | |
| "c2_train_candidate", | |
| "untouched_evaluation_only", | |
| "blocked", | |
| ] | |
| # A resolver turns one native image reference (a path/relative name in the raw | |
| # row) into its raw bytes. The importer never opens files itself, so importers | |
| # are unit-testable with an in-memory resolver. | |
| ImageResolver = Callable[[str], bytes] | |
| _NORMALIZED_ITEM_SCHEMA: dict[str, Any] | None = None | |
| class IngestError(ValueError): | |
| """Raised when a source row violates an ingest invariant. | |
| Invariants are hard failures (never silently dropped): a non-math MMK12 row | |
| is source revision drift, not a row to skip. | |
| """ | |
| class RegistryFrozenError(IngestError): | |
| """Raised when a write-once registry would be changed by a re-freeze.""" | |
| def normalized_item_schema() -> dict[str, Any]: | |
| """Load and cache the compiled ``normalized_item`` JSON Schema.""" | |
| global _NORMALIZED_ITEM_SCHEMA | |
| if _NORMALIZED_ITEM_SCHEMA is None: | |
| _NORMALIZED_ITEM_SCHEMA = load_schema( | |
| repo_root() / "schemas" / "normalized_item.schema.json" | |
| ) | |
| return _NORMALIZED_ITEM_SCHEMA | |
| def validate_normalized_item(row: Mapping[str, Any]) -> None: | |
| """Raise :class:`IngestError` if ``row`` violates the normalized item schema.""" | |
| errors = validate(dict(row), normalized_item_schema()) | |
| if errors: | |
| raise IngestError("normalized item failed schema validation: " + "; ".join(errors)) | |
| # --- content-addressed image store ----------------------------------------- | |
| def _ext_for(data: bytes) -> str: | |
| """Infer a file extension from image bytes (PNG/JPEG), else ``bin``.""" | |
| if data.startswith(b"\x89PNG\r\n\x1a\n"): | |
| return "png" | |
| if data.startswith(b"\xff\xd8\xff"): | |
| return "jpg" | |
| return "bin" | |
| class ImageStore: | |
| """Store image bytes content-addressed under ``<output>/images/<sha>.<ext>``. | |
| The same bytes are written once; repeat stores are a no-op. Paths are | |
| returned relative to ``base_dir`` so artifacts reproduce across mounts. | |
| """ | |
| base_dir: Path | |
| def __post_init__(self) -> None: | |
| (self.base_dir / "images").mkdir(parents=True, exist_ok=True) | |
| def store(self, data: bytes) -> tuple[str, str]: | |
| """Store ``data``; return ``(relative_path, sha256)``.""" | |
| digest = sha256_bytes(data) | |
| ext = _ext_for(data) | |
| relative = f"images/{digest}.{ext}" | |
| target = self.base_dir / relative | |
| if not target.exists(): | |
| atomic_write_bytes(target, data) | |
| return relative, digest | |
| class DirectoryImageResolver: | |
| """Resolve native image refs to bytes by reading from a root directory.""" | |
| def __init__(self, root: str | Path) -> None: | |
| self.root = Path(root) | |
| def __call__(self, ref: str) -> bytes: | |
| return (self.root / ref).read_bytes() | |
| # --- normalized item ------------------------------------------------------- | |
| class Choice: | |
| """One multiple-choice option in source order.""" | |
| key: str | |
| text: str | |
| def to_dict(self) -> dict[str, str]: | |
| return {"key": self.key, "text": self.text} | |
| class NormalizedItem: | |
| """One immutable normalized source row (``docs/02`` §4 schema).""" | |
| base_id: str | |
| source: str | |
| source_revision: str | |
| source_config: str | |
| source_split: str | |
| source_native_id: str | |
| question: str | |
| question_sha256: str | |
| choices: tuple[Choice, ...] | |
| choices_sha256: str | |
| answer_raw: str | int | bool | |
| answer_canonical: str | int | bool | |
| answer_type: AnswerType | |
| image_paths: tuple[str, ...] | |
| image_sha256: tuple[str, ...] | |
| policy: Policy | |
| provenance: dict[str, Any] | |
| subject: str | None = None | |
| license_gate: str | None = None | |
| def to_row(self) -> dict[str, Any]: | |
| """Serialize to the schema-conforming dict written to ``items.jsonl``.""" | |
| row: dict[str, Any] = { | |
| "schema_version": SCHEMA_VERSION, | |
| "base_id": self.base_id, | |
| "source": self.source, | |
| "source_revision": self.source_revision, | |
| "source_config": self.source_config, | |
| "source_split": self.source_split, | |
| "source_native_id": self.source_native_id, | |
| "question": self.question, | |
| "question_sha256": self.question_sha256, | |
| "choices": [c.to_dict() for c in self.choices], | |
| "choices_sha256": self.choices_sha256, | |
| "answer_raw": self.answer_raw, | |
| "answer_canonical": self.answer_canonical, | |
| "answer_type": self.answer_type, | |
| "image_paths": list(self.image_paths), | |
| "image_sha256": list(self.image_sha256), | |
| "provenance": dict(self.provenance), | |
| "policy": self.policy, | |
| } | |
| if self.subject is not None: | |
| row["subject"] = self.subject | |
| if self.license_gate is not None: | |
| row["license_gate"] = self.license_gate | |
| return row | |
| def _native_row_sha256(row: Mapping[str, Any]) -> str: | |
| """SHA-256 of the native row's canonical JSON (the source-record fingerprint).""" | |
| return sha256_bytes(canonical_json(dict(row)).encode("utf-8")) | |
| def canonicalize_mc_answer(answer: str, choices: Sequence[Choice]) -> str | int | bool: | |
| """Map a multiple-choice answer to its choice key when it matches a text. | |
| Sources disagree on whether the answer is a key (``"B"``) or the option | |
| text (``"42"``). The canonical form is the choice key when the raw answer | |
| equals one option's text; otherwise the raw string is preserved. | |
| """ | |
| text_answer = str(answer).strip() | |
| for choice in choices: | |
| if text_answer == str(choice.text).strip(): | |
| return choice.key | |
| return text_answer | |
| def make_item( | |
| *, | |
| source: str, | |
| source_revision: str, | |
| source_config: str, | |
| source_split: str, | |
| source_native_id: str, | |
| question: str, | |
| choices: Sequence[Choice] | Sequence[Mapping[str, str]], | |
| answer_raw: str | int | bool, | |
| answer_canonical: str | int | bool, | |
| answer_type: AnswerType, | |
| image_paths: Sequence[str], | |
| image_sha256: Sequence[str], | |
| policy: Policy, | |
| native_row: Mapping[str, Any], | |
| subject: str | None = None, | |
| license_gate: str | None = None, | |
| extra_provenance: Mapping[str, Any] | None = None, | |
| ) -> NormalizedItem: | |
| """Build a :class:`NormalizedItem`, computing ``base_id`` and byte hashes. | |
| ``base_id`` is the content-addressed hash of ``docs/02`` §3.1 — | |
| sha256(canonical_json({source, source_revision, source_native_id, | |
| image_family_sha256, question_sha256, choices_sha256})). ``source_config`` | |
| and ``source_split`` are stored on the item but excluded from the ID. The | |
| native row's canonical-JSON SHA-256 is recorded in provenance so a row can | |
| be traced back to its source record. | |
| """ | |
| if not question: | |
| raise IngestError(f"{source}: question must be non-empty") | |
| if not image_paths or len(image_paths) != len(image_sha256): | |
| raise IngestError( | |
| f"{source}/{source_native_id}: image_paths and image_sha256 must be " | |
| "parallel non-empty sequences" | |
| ) | |
| norm_choices = tuple( | |
| c if isinstance(c, Choice) else Choice(key=str(c["key"]), text=str(c["text"])) | |
| for c in choices | |
| ) | |
| q_sha = compute_question_sha256(question) | |
| c_sha = choices_sha256([{"key": c.key, "text": c.text} for c in norm_choices]) | |
| fam_sha = compute_image_family_sha256(image_sha256) | |
| bid = compute_base_id( | |
| source=source, | |
| source_revision=source_revision, | |
| source_native_id=source_native_id, | |
| image_family_sha256=fam_sha, | |
| question_sha256=q_sha, | |
| choices_sha256=c_sha, | |
| ) | |
| provenance: dict[str, Any] = { | |
| "native_row_json_sha256": _native_row_sha256(native_row), | |
| } | |
| if extra_provenance: | |
| provenance.update(extra_provenance) | |
| item = NormalizedItem( | |
| base_id=bid, | |
| source=source, | |
| source_revision=source_revision, | |
| source_config=source_config, | |
| source_split=source_split, | |
| source_native_id=str(source_native_id), | |
| question=question, | |
| question_sha256=q_sha, | |
| choices=norm_choices, | |
| choices_sha256=c_sha, | |
| answer_raw=answer_raw, | |
| answer_canonical=answer_canonical, | |
| answer_type=answer_type, | |
| image_paths=tuple(image_paths), | |
| image_sha256=tuple(image_sha256), | |
| policy=policy, | |
| provenance=provenance, | |
| subject=subject, | |
| license_gate=license_gate, | |
| ) | |
| validate_normalized_item(item.to_row()) | |
| return item | |
| # --- ingest driver --------------------------------------------------------- | |
| class IngestResult: | |
| """Summary of one ingest run.""" | |
| source: str | |
| split: str | |
| written: int | |
| dropped: int | |
| output_path: Path | |
| def ok(self) -> bool: | |
| return self.written > 0 or self.dropped > 0 | |
| def write_items( | |
| output_path: str | Path, | |
| items: Iterable[NormalizedItem], | |
| *, | |
| fsync: bool = True, | |
| ) -> int: | |
| """Atomically write ``items`` as canonical JSONL; return the row count.""" | |
| rows = [item.to_row() for item in items] | |
| atomic_write_jsonl(output_path, rows, fsync_dir=fsync) | |
| return len(rows) | |
| def append_items(output_path: str | Path, items: Iterable[NormalizedItem]) -> int: | |
| """Append items to an existing JSONL with per-record fsync (resume-friendly).""" | |
| count = 0 | |
| with JsonlAppender(output_path) as appender: | |
| for item in items: | |
| appender.append(item.to_row()) | |
| count += 1 | |
| return count | |
| def read_items(path: str | Path) -> Iterator[dict[str, Any]]: | |
| """Yield parsed normalized-item rows from ``path``.""" | |
| yield from read_jsonl(path) | |
| # --- evaluation registry --------------------------------------------------- | |
| def registry_row(item: NormalizedItem) -> dict[str, Any]: | |
| """Build one ``evaluation_items.v1.jsonl`` row from a normalized item. | |
| Fingerprint fields (``image_phash``, ``ocr_minhash_ref``, | |
| ``question_minhash_ref``) are left ``None`` here and populated by the P3 | |
| ``fingerprint`` stage; the identity + content fields are frozen now. | |
| """ | |
| return { | |
| "base_id": item.base_id, | |
| "source": item.source, | |
| "source_revision": item.source_revision, | |
| "config": item.source_config, | |
| "split": item.source_split, | |
| "native_id": item.source_native_id, | |
| "question_sha256": item.question_sha256, | |
| "choices_sha256": item.choices_sha256, | |
| "image_sha256": list(item.image_sha256), | |
| "image_phash": None, | |
| "ocr_minhash_ref": None, | |
| "question_minhash_ref": None, | |
| "policy": item.policy, | |
| } | |
| def text_registry_row( | |
| *, | |
| source: str, | |
| source_revision: str, | |
| config: str, | |
| split: str, | |
| native_id: str, | |
| question: str, | |
| choices: Sequence[Choice] | Sequence[Mapping[str, str]], | |
| answer_canonical: str | int | bool, | |
| policy: Policy = "untouched_evaluation_only", | |
| ) -> dict[str, Any]: | |
| """Build a registry row for a text-only eval item (no image, e.g. MMLU-Pro). | |
| Text-only ``untouched`` probes are retention checks, not intervention | |
| candidates, so they carry no image fingerprints. They are recorded directly | |
| in the registry rather than as visual :class:`NormalizedItem` rows. | |
| """ | |
| norm_choices = tuple( | |
| c if isinstance(c, Choice) else Choice(key=str(c["key"]), text=str(c["text"])) | |
| for c in choices | |
| ) | |
| q_sha = compute_question_sha256(question) | |
| c_sha = choices_sha256([{"key": c.key, "text": c.text} for c in norm_choices]) | |
| # Text-only probes carry no images: their image family is the empty set. | |
| fam_sha = compute_image_family_sha256([]) | |
| return { | |
| "base_id": compute_base_id( | |
| source=source, | |
| source_revision=source_revision, | |
| source_native_id=native_id, | |
| image_family_sha256=fam_sha, | |
| question_sha256=q_sha, | |
| choices_sha256=c_sha, | |
| ), | |
| "source": source, | |
| "source_revision": source_revision, | |
| "config": config, | |
| "split": split, | |
| "native_id": str(native_id), | |
| "question_sha256": q_sha, | |
| "choices_sha256": c_sha, | |
| "image_sha256": [], | |
| "image_phash": None, | |
| "ocr_minhash_ref": None, | |
| "question_minhash_ref": None, | |
| "policy": policy, | |
| "answer_canonical": answer_canonical, | |
| } | |
| class FrozenRegistry: | |
| """A write-once evaluation registry on disk.""" | |
| path: Path | |
| sha256: str | |
| row_count: int | |
| def _registry_rows_keyed(rows: Iterable[Mapping[str, Any]]) -> dict[str, dict[str, Any]]: | |
| return {str(r["base_id"]): dict(r) for r in rows} | |
| def freeze_registry( | |
| output_path: str | Path, | |
| rows: Sequence[Mapping[str, Any]], | |
| *, | |
| force: bool = False, | |
| resume: bool = False, | |
| ) -> FrozenRegistry: | |
| """Write the evaluation registry write-once; return its hash and row count. | |
| If the registry already exists: | |
| - ``force`` overwrites it atomically. | |
| - ``resume`` succeeds only if the existing rows are byte-identical to the | |
| computed rows (idempotent re-freeze); a mismatch raises | |
| :class:`RegistryFrozenError`. | |
| - otherwise the existing file is left untouched and a | |
| :class:`RegistryFrozenError` is raised. | |
| """ | |
| path = Path(output_path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| if path.exists(): | |
| if not force and not resume: | |
| raise RegistryFrozenError( | |
| f"evaluation registry already frozen at {path}; " | |
| "use --force to overwrite or --resume to verify" | |
| ) | |
| if resume: | |
| existing = _registry_rows_keyed(read_jsonl(path)) | |
| computed = _registry_rows_keyed(rows) | |
| if existing != computed: | |
| raise RegistryFrozenError( | |
| f"evaluation registry at {path} differs from the computed " | |
| "freeze; refusing to overwrite a frozen registry" | |
| ) | |
| return _hash_registry(path) | |
| atomic_write_jsonl(path, rows) | |
| return _hash_registry(path) | |
| def _hash_registry(path: str | Path) -> FrozenRegistry: | |
| from ..hashing import sha256_file | |
| rows = list(read_jsonl(path)) | |
| return FrozenRegistry(path=Path(path), sha256=sha256_file(path), row_count=len(rows)) | |
| # --- helpers shared by importers ------------------------------------------- | |
| def infer_open_answer_type(answer: str) -> AnswerType: | |
| """Classify an open-ended answer string as integer/number/short_text.""" | |
| text = str(answer).strip() | |
| if text.lstrip("-+").isdigit(): | |
| return "integer" | |
| try: | |
| float(text) | |
| except ValueError: | |
| return "short_text" | |
| return "number" | |
| def mc_choices(texts: Sequence[str], *, keys: Sequence[str] | None = None) -> list[Choice]: | |
| """Build lettered choices (A, B, C, ...) from option texts in source order.""" | |
| if keys is None: | |
| keys = [chr(ord("A") + i) for i in range(len(texts))] | |
| if len(keys) != len(texts): | |
| raise IngestError(f"choices/keys length mismatch: {len(keys)} keys vs {len(texts)} texts") | |
| return [Choice(key=k, text=str(t)) for k, t in zip(keys, texts, strict=True)] | |