"""GQA-v1.2 source adapter backed only by native questions and scene graphs. The released question files are mappings keyed by question id. Each question contains a native dependency-indexed ``semantic`` program and points to an image whose released scene graph supplies object names, attributes, relations, and bounding boxes. This adapter joins those records deterministically and never uses a VLM or the source answer to infer a program operand. """ from __future__ import annotations import json from collections.abc import Iterator, Mapping from pathlib import Path from typing import TYPE_CHECKING, Any from ..hashing import canonical_json_hash from ..ingest.base import ( AnswerType, ImageStore, IngestError, NormalizedItem, Policy, infer_open_answer_type, make_item, ) from .base import AdapterError, CertificateTier, RawItem, World, store_images if TYPE_CHECKING: from ..executors.gqa import GQASemanticProgram SOURCE = "gqa" WORLD_SCHEMA = "gqa_scene_graph_v1" _HIDDEN_OBJECTS_KEY = "_gqa_hidden_object_ids" _VALID_SPLITS = frozenset({"train", "val", "validation", "test", "testdev", "challenge"}) class GQAAdapter: """Deterministic adapter for GQA-v1.2 native JSON files.""" def __init__( self, raw_dir: Path, store: ImageStore, *, revision: str, images_dir: Path | None = None, questions_path: Path | None = None, scene_graphs_path: Path | None = None, ) -> None: self.raw_dir = Path(raw_dir) self.store = store self.revision = revision self.images_dir = Path(images_dir) if images_dir is not None else self.raw_dir / "images" self.questions_path = Path(questions_path) if questions_path is not None else None self.scene_graphs_path = Path(scene_graphs_path) if scene_graphs_path is not None else None @classmethod def is_materialized(cls, raw_dir: Path, split: str) -> bool: if split not in _VALID_SPLITS: return False root = Path(raw_dir) return ( _first_existing(root, _question_names(split)) is not None and _first_existing(root, _scene_graph_names(split)) is not None and (root / "images").is_dir() ) @classmethod def materialize( cls, raw_dir: Path, split: str, *, source_config: Mapping[str, Any], expected_sha256: Mapping[str, str] | None = None, ) -> Path: """Validate an already materialized native GQA tree. GQA's multi-gigabyte image/question archives are intentionally not downloaded implicitly. Callers materialize the pinned source snapshot out of band, then this method performs the same fail-closed check used by the ingest CLI. ``source_config`` and ``expected_sha256`` are accepted for protocol parity; hashes belong in the surrounding resource manifest. """ del source_config, expected_sha256 root = Path(raw_dir) if not cls.is_materialized(root, split): raise AdapterError( f"{SOURCE}: native {split!r} questions, scene graphs, and images " f"are not materialized under {root}" ) return root def iter_base_items(self, split: str) -> Iterator[RawItem]: from ..executors.gqa import compile_gqa_program if split not in _VALID_SPLITS: raise AdapterError(f"{SOURCE}: unsupported split {split!r}") questions = _load_mapping(self._questions_file(split), label="questions") scene_graphs = _load_mapping(self._scene_graphs_file(split), label="scene graphs") for question_id in sorted(str(key) for key in questions): row = questions.get(question_id) if not isinstance(row, Mapping): raise AdapterError(f"{SOURCE}/{question_id}: question row must be an object") image_id = str(row.get("imageId", "")).strip() if not image_id: raise AdapterError(f"{SOURCE}/{question_id}: imageId missing/empty") scene_graph = scene_graphs.get(image_id) if not isinstance(scene_graph, Mapping): raise AdapterError(f"{SOURCE}/{question_id}: scene graph {image_id!r} missing") # Compile during iteration so an unsupported native operation is a # typed hard rejection, never a silently dropped candidate. compile_gqa_program(question_id, row) image = self._image_bytes(image_id) payload = { "question_id": question_id, **dict(row), "scene_graph": dict(scene_graph), } yield RawItem( source=SOURCE, split=split, source_revision=self.revision, native_id=question_id, payload=payload, images={image_id: image}, ) def normalize(self, raw: RawItem) -> NormalizedItem: from ..executors.gqa import compile_gqa_program if raw.source != SOURCE: raise IngestError(f"{SOURCE}: cannot normalize raw source {raw.source!r}") row = raw.payload question = row.get("question") if not isinstance(question, str) or not question.strip(): raise IngestError(f"{SOURCE}/{raw.native_id}: question missing/empty") answer = row.get("answer") if answer is None or not str(answer).strip(): raise IngestError(f"{SOURCE}/{raw.native_id}: answer missing/empty") image_id = str(row.get("imageId", "")).strip() scene_graph = row.get("scene_graph") if not image_id or not isinstance(scene_graph, Mapping): raise IngestError(f"{SOURCE}/{raw.native_id}: joined scene graph missing") if not raw.images: raise IngestError(f"{SOURCE}/{raw.native_id}: image missing") program = compile_gqa_program(raw.native_id, row) paths, image_hashes = store_images(self.store, raw.images) answer_text = str(answer).strip() answer_type: AnswerType if answer_text.casefold() in {"yes", "no"}: answer_type = "boolean" answer_canonical = answer_text.casefold() else: answer_type = infer_open_answer_type(answer_text) answer_canonical = answer_text policy: Policy = ( "c1_train_candidate" if raw.split in {"train", "val", "validation"} else "c1_certified_eval_candidate" ) types = row.get("types") subject = None if isinstance(types, Mapping) and types.get("semantic"): subject = f"gqa_{str(types['semantic']).strip()}" extra = { "image_id": image_id, "semantic": [step.to_dict() for step in program.steps], "semanticStr": program.semantic_str, "semantic_program_sha256": program.canonical_program_sha256, "annotations": row.get("annotations") if isinstance(row.get("annotations"), Mapping) else {}, "types": dict(types) if isinstance(types, Mapping) else {}, "scene_graph": dict(scene_graph), "source_record_sha256": canonical_json_hash( { "question_id": raw.native_id, "question": {key: value for key, value in row.items() if key != "scene_graph"}, "scene_graph": scene_graph, } ), } return make_item( source=SOURCE, source_revision=raw.source_revision, source_config="default", source_split=raw.split, source_native_id=raw.native_id, question=question, choices=[], answer_raw=answer_text, answer_canonical=answer_canonical, answer_type=answer_type, image_paths=paths, image_sha256=image_hashes, policy=policy, native_row={key: value for key, value in row.items() if key != "scene_graph"}, subject=subject, extra_provenance=extra, ) def build_world(self, item: NormalizedItem) -> World: scene_graph = item.provenance.get("scene_graph") image_id = str(item.provenance.get("image_id", "")).strip() if not isinstance(scene_graph, Mapping) or not image_id: raise IngestError(f"{SOURCE}/{item.source_native_id}: scene graph provenance missing") return build_gqa_world(scene_graph, image_id=image_id, question_id=item.source_native_id) def get_or_compile_program(self, item: NormalizedItem) -> GQASemanticProgram: from ..executors.gqa import compile_gqa_program semantic = item.provenance.get("semantic") if not isinstance(semantic, list): raise IngestError(f"{SOURCE}/{item.source_native_id}: semantic provenance missing") return compile_gqa_program( item.source_native_id, { "imageId": item.provenance.get("image_id"), "semantic": semantic, "semanticStr": item.provenance.get("semanticStr", ""), }, ) def official_answer(self, item: NormalizedItem) -> str | int | bool: return item.answer_canonical def source_certificate_tier(self, item: NormalizedItem) -> CertificateTier: return "C1_SOURCE_NATIVE" def _questions_file(self, split: str) -> Path: if self.questions_path is not None: if not self.questions_path.is_file(): raise AdapterError(f"{SOURCE}: questions file not found: {self.questions_path}") return self.questions_path path = _first_existing(self.raw_dir, _question_names(split)) if path is None: raise AdapterError(f"{SOURCE}: no native questions file for split {split!r}") return path def _scene_graphs_file(self, split: str) -> Path: if self.scene_graphs_path is not None: if not self.scene_graphs_path.is_file(): raise AdapterError( f"{SOURCE}: scene-graphs file not found: {self.scene_graphs_path}" ) return self.scene_graphs_path path = _first_existing(self.raw_dir, _scene_graph_names(split)) if path is None: raise AdapterError(f"{SOURCE}: no native scene-graphs file for split {split!r}") return path def _image_bytes(self, image_id: str) -> bytes: roots = (self.images_dir, self.raw_dir / "images", self.raw_dir) for root in roots: for suffix in (".jpg", ".jpeg", ".png"): candidate = root / f"{image_id}{suffix}" if candidate.is_file(): return candidate.read_bytes() raise AdapterError(f"{SOURCE}: image {image_id!r} not found") def build_gqa_world( scene_graph: Mapping[str, Any], *, image_id: str, question_id: str | None = None, ) -> World: """Validate and canonicalize one native GQA scene graph. Object ids remain the released ids. Relations are sorted only after their source order has been validated, making hashes stable even when the native relation container is a mapping. Dangling relation targets are rejected. """ width = _positive_int(scene_graph.get("width"), "width") height = _positive_int(scene_graph.get("height"), "height") raw_objects = scene_graph.get("objects") if not isinstance(raw_objects, Mapping) or not raw_objects: raise IngestError(f"{SOURCE}/{image_id}: objects must be a non-empty mapping") objects: dict[str, dict[str, Any]] = {} for raw_id in sorted(raw_objects, key=str): object_id = str(raw_id) raw = raw_objects[raw_id] if not isinstance(raw, Mapping): raise IngestError(f"{SOURCE}/{image_id}: object {object_id!r} must be an object") name = str(raw.get("name", "")).strip() if not name: raise IngestError(f"{SOURCE}/{image_id}: object {object_id!r} name missing") x = _nonnegative_int(raw.get("x"), f"object {object_id} x") y = _nonnegative_int(raw.get("y"), f"object {object_id} y") w = _positive_int(raw.get("w"), f"object {object_id} w") h = _positive_int(raw.get("h"), f"object {object_id} h") if x + w > width or y + h > height: raise IngestError( f"{SOURCE}/{image_id}: object {object_id!r} bbox exceeds image bounds" ) raw_attributes = raw.get("attributes", []) if not isinstance(raw_attributes, list) or any( not isinstance(attribute, str) for attribute in raw_attributes ): raise IngestError( f"{SOURCE}/{image_id}: object {object_id!r} attributes must be strings" ) relations = _normalize_relations(raw.get("relations", []), image_id, object_id) objects[object_id] = { "id": object_id, "name": name, "x": x, "y": y, "w": w, "h": h, "attributes": list(raw_attributes), "relations": relations, } known = frozenset(objects) for source_id, obj in objects.items(): for relation in obj["relations"]: target = str(relation["object"]) if target not in known: raise IngestError( f"{SOURCE}/{image_id}: relation {source_id!r}->{target!r} is dangling" ) world: World = { "world_schema": WORLD_SCHEMA, "image_id": str(image_id), "width": width, "height": height, "objects": objects, _HIDDEN_OBJECTS_KEY: [], "provenance": { "source": SOURCE, "image_id": str(image_id), "question_id": question_id, }, } for field in ("location", "weather"): value = scene_graph.get(field) if isinstance(value, str) and value.strip(): world[field] = value.strip() return world def _normalize_relations( raw: Any, image_id: str, object_id: str, ) -> list[dict[str, str]]: values = list(raw.values()) if isinstance(raw, Mapping) else raw if not isinstance(values, list): raise IngestError( f"{SOURCE}/{image_id}: object {object_id!r} relations must be a list or mapping" ) out: list[dict[str, str]] = [] for index, relation in enumerate(values): if not isinstance(relation, Mapping): raise IngestError( f"{SOURCE}/{image_id}: object {object_id!r} relation {index} must be an object" ) name = str(relation.get("name", "")).strip() target = str(relation.get("object", "")).strip() if not name or not target: raise IngestError( f"{SOURCE}/{image_id}: object {object_id!r} relation {index} is incomplete" ) out.append({"name": name, "object": target}) return sorted(out, key=lambda relation: (relation["name"], relation["object"])) def _question_names(split: str) -> tuple[str, ...]: aliases = _split_aliases(split) names: list[str] = [] for alias in aliases: names.extend( ( f"{alias}_balanced_questions.json", f"{alias}_all_questions.json", f"{alias}_questions.json", ) ) names.extend(("questions.json", "Questions.json")) return tuple(names) def _scene_graph_names(split: str) -> tuple[str, ...]: aliases = _split_aliases(split) names: list[str] = [] for alias in aliases: names.extend( ( f"{alias}_sceneGraphs.json", f"{alias}_scene_graphs.json", ) ) names.extend(("sceneGraphs.json", "scene_graphs.json", "Scene_graphs.json")) return tuple(names) def _split_aliases(split: str) -> tuple[str, ...]: if split == "validation": return ("validation", "val") if split == "val": return ("val", "validation") return (split,) def _first_existing(root: Path, names: tuple[str, ...]) -> Path | None: for name in names: path = root / name if path.is_file(): return path return None def _load_mapping(path: Path, *, label: str) -> dict[str, Any]: try: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise AdapterError(f"{SOURCE}: cannot read {label} at {path}: {exc}") from exc if not isinstance(value, Mapping): raise AdapterError(f"{SOURCE}: {label} at {path} must be a JSON object") return {str(key): row for key, row in value.items()} def _positive_int(value: Any, label: str) -> int: number = _integer(value, label) if number <= 0: raise IngestError(f"{SOURCE}: {label} must be positive") return number def _nonnegative_int(value: Any, label: str) -> int: number = _integer(value, label) if number < 0: raise IngestError(f"{SOURCE}: {label} must be non-negative") return number def _integer(value: Any, label: str) -> int: if isinstance(value, bool) or not isinstance(value, int): raise IngestError(f"{SOURCE}: {label} must be an integer") return int(value) __all__ = [ "GQAAdapter", "SOURCE", "WORLD_SCHEMA", "build_gqa_world", ]