"""CLEVR structured-source adapter. The adapter joins official ``CLEVR__questions.json`` rows to ``CLEVR__scenes.json`` by ``image_index``. Scene objects keep the released attributes and coordinates while receiving stable ``object:`` semantic IDs; relationship adjacency is rewritten to those IDs so deleting an object never silently renumbers another. The public no-images CLEVR archive is supported directly. When the source PNG is absent, the adapter creates a deterministic fresh scene render from the structured world. That fallback is fully machine generated and records its origin in provenance; it never asks a vision-language model to reconstruct the scene. """ from __future__ import annotations import json from collections.abc import Iterator, Mapping, Sequence from pathlib import Path from typing import Any from ..dsl.ast import Program from ..ingest.base import ( AnswerType, ImageStore, IngestError, NormalizedItem, Policy, make_item, ) from .base import ( AdapterError, CertificateTier, RawItem, World, extract_zip, http_download, store_images, ) SOURCE = "clevr" WORLD_SCHEMA = "clevr_world_v1" _VALID_SPLITS = frozenset({"train", "val", "test"}) _COLORS = frozenset({"gray", "red", "blue", "green", "brown", "purple", "cyan", "yellow"}) _MATERIALS = frozenset({"rubber", "metal"}) _SHAPES = frozenset({"cube", "sphere", "cylinder"}) _SIZES = frozenset({"small", "large"}) _RELATIONS = frozenset({"left", "right", "front", "behind"}) class ClevrAdapter: """C1 adapter for official CLEVR scenes and native functional programs.""" def __init__( self, raw_dir: Path, store: ImageStore, *, revision: str, render_missing_images: bool = True, ) -> None: self.raw_dir = Path(raw_dir) self.store = store self.revision = revision self.render_missing_images = render_missing_images @classmethod def is_materialized(cls, raw_dir: Path, split: str) -> bool: if split not in _VALID_SPLITS: return False return ( _find_split_file(Path(raw_dir), split, "questions", required=False) is not None and _find_split_file(Path(raw_dir), split, "scenes", required=False) is not None ) @classmethod def materialize( cls, raw_dir: Path, split: str, *, source_config: Mapping[str, Any], expected_sha256: Mapping[str, str] | None = None, ) -> Path: """Materialize the official no-images archive when it is not present.""" raw_dir = Path(raw_dir) if cls.is_materialized(raw_dir, split): return raw_dir archive_url = source_config.get("archive_url") if not isinstance(archive_url, str) or not archive_url: raise AdapterError( f"{SOURCE}: missing {split} scenes/questions and no archive_url configured" ) archive = raw_dir / "clevr-no-images.zip" http_download( archive_url, archive, expected_sha256=(expected_sha256 or {}).get("archive"), ) extract_zip(archive, raw_dir) if not cls.is_materialized(raw_dir, split): raise AdapterError(f"{SOURCE}: archive does not contain the {split!r} split") return raw_dir def iter_base_items(self, split: str) -> Iterator[RawItem]: if split not in _VALID_SPLITS: raise AdapterError(f"{SOURCE}: unsupported split {split!r}") question_path = _find_split_file(self.raw_dir, split, "questions") scene_path = _find_split_file(self.raw_dir, split, "scenes") if question_path is None or scene_path is None: # required=True above raise AdapterError(f"{SOURCE}: split {split!r} is not materialized") questions = _record_array(question_path, "questions") scenes = _record_array(scene_path, "scenes") scene_index: dict[int, Mapping[str, Any]] = {} for scene in scenes: image_index = _integer_field(scene, "image_index", context="scene") if image_index in scene_index: raise AdapterError(f"{SOURCE}: duplicate scene image_index {image_index}") scene_index[image_index] = scene indexed_questions = list(enumerate(questions)) indexed_questions.sort( key=lambda pair: ( _sort_integer(pair[1].get("question_index"), pair[0]), pair[0], ) ) for source_position, question in indexed_questions: image_index = _integer_field( question, "image_index", context=f"question[{source_position}]", ) matched_scene = scene_index.get(image_index) if matched_scene is None: raise AdapterError( f"{SOURCE}: question[{source_position}] references missing scene {image_index}" ) filename = question.get("image_filename") or matched_scene.get("image_filename") if not isinstance(filename, str) or not filename: raise AdapterError(f"{SOURCE}: question[{source_position}] has no image_filename") image = _find_image(self.raw_dir, split, filename) image_origin = "official_png" if image is None: if not self.render_missing_images: raise AdapterError(f"{SOURCE}: image {filename!r} is absent") from ..renderers.clevr import ClevrRenderer assets = ClevrRenderer().render( world_from_scene(matched_scene), renderer_id="clevr_train_v1", seed=image_index, width=480, height=320, ) image_bytes = assets.rgba_png image_origin = "fresh_scene_render" else: image_bytes = image.read_bytes() question_index = _sort_integer(question.get("question_index"), source_position) payload = { "question": dict(question), "scene": dict(matched_scene), "image_origin": image_origin, } yield RawItem( source=SOURCE, split=split, source_revision=self.revision, native_id=str(question_index), payload=payload, images={"scene": image_bytes}, ) def normalize(self, raw: RawItem) -> NormalizedItem: question_row = raw.payload.get("question") scene = raw.payload.get("scene") if not isinstance(question_row, Mapping) or not isinstance(scene, Mapping): raise IngestError(f"{SOURCE}/{raw.native_id}: joined question/scene missing") question = question_row.get("question") answer = question_row.get("answer") program = question_row.get("program") if not isinstance(question, str) or not question.strip(): raise IngestError(f"{SOURCE}/{raw.native_id}: question missing/empty") if not isinstance(answer, (str, int, bool)) or str(answer).strip() == "": raise IngestError(f"{SOURCE}/{raw.native_id}: answer missing/empty") if not isinstance(program, list) or not program: raise IngestError(f"{SOURCE}/{raw.native_id}: native program missing/empty") if not raw.images: raise IngestError(f"{SOURCE}/{raw.native_id}: scene image missing") paths, shas = store_images(self.store, raw.images) answer_type, answer_canonical = _answer(answer) policy: Policy = ( "c1_train_candidate" if raw.split == "train" else "c1_certified_eval_candidate" ) return make_item( source=SOURCE, source_revision=raw.source_revision, source_config="official", source_split=raw.split, source_native_id=raw.native_id, question=question, choices=(), answer_raw=answer, answer_canonical=answer_canonical, answer_type=answer_type, image_paths=paths, image_sha256=shas, policy=policy, native_row=dict(question_row), extra_provenance={ "program": program, "scene": dict(scene), "image_index": question_row.get("image_index"), "image_filename": question_row.get("image_filename"), "question_family_index": question_row.get("question_family_index"), "image_origin": raw.payload.get("image_origin"), }, ) def build_world(self, item: NormalizedItem) -> World: scene = item.provenance.get("scene") if not isinstance(scene, Mapping): raise AdapterError(f"{SOURCE}/{item.source_native_id}: scene provenance missing") return world_from_scene(scene) def get_or_compile_program(self, item: NormalizedItem) -> Program: from ..dsl.clevrdsl import compile_clevr return compile_clevr(item, self.build_world(item)) 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 world_from_scene(scene: Mapping[str, Any]) -> World: """Normalize one official scene into a renderer/executor-ready world.""" raw_objects = scene.get("objects") if not isinstance(raw_objects, list): raise AdapterError(f"{SOURCE}: scene objects must be an array") objects: list[dict[str, Any]] = [] for index, raw in enumerate(raw_objects): if not isinstance(raw, Mapping): raise AdapterError(f"{SOURCE}: scene object {index} is not an object") color = _enum(raw, "color", _COLORS, index) material = _enum(raw, "material", _MATERIALS, index) shape = _enum(raw, "shape", _SHAPES, index) size = _enum(raw, "size", _SIZES, index) pixel_coords = _coords(raw.get("pixel_coords"), "pixel_coords", index, minimum=2) coords_3d = _coords(raw.get("3d_coords"), "3d_coords", index, minimum=2) rotation = raw.get("rotation", 0) if isinstance(rotation, bool) or not isinstance(rotation, (int, float)): raise AdapterError(f"{SOURCE}: object {index} rotation is not numeric") objects.append( { "id": f"object:{index}", "index": index, "color": color, "material": material, "shape": shape, "size": size, "rotation": rotation, "3d_coords": coords_3d, "pixel_coords": pixel_coords, } ) relationships = _relationships(scene.get("relationships"), len(objects)) world: World = { "world_schema": WORLD_SCHEMA, "image_index": scene.get("image_index"), "image_filename": scene.get("image_filename"), "split": scene.get("split"), "objects": objects, "relationships": relationships, "_node_visibility": {}, } directions = scene.get("directions") if isinstance(directions, Mapping): world["directions"] = dict(directions) return world def _relationships(raw: Any, object_count: int) -> dict[str, dict[str, list[str]]]: if raw is None: raw = {} if not isinstance(raw, Mapping): raise AdapterError(f"{SOURCE}: scene relationships must be an object") output: dict[str, dict[str, list[str]]] = {} for relation in sorted(_RELATIONS): adjacency = raw.get(relation, [[] for _ in range(object_count)]) relation_map: dict[str, list[str]] = {} if isinstance(adjacency, list): if len(adjacency) != object_count: raise AdapterError( f"{SOURCE}: {relation} adjacency has {len(adjacency)} rows, " f"expected {object_count}" ) for index, targets in enumerate(adjacency): relation_map[f"object:{index}"] = _target_ids( targets, object_count, relation, index, ) elif isinstance(adjacency, Mapping): for index in range(object_count): oid = f"object:{index}" targets = adjacency.get(oid, adjacency.get(str(index), [])) relation_map[oid] = _target_ids(targets, object_count, relation, index) else: raise AdapterError(f"{SOURCE}: {relation} adjacency is malformed") output[relation] = relation_map return output def _target_ids(raw: Any, count: int, relation: str, source: int) -> list[str]: if not isinstance(raw, list): raise AdapterError(f"{SOURCE}: {relation}[{source}] is not an array") output: list[str] = [] for value in raw: if isinstance(value, str) and value.startswith("object:"): try: index = int(value.split(":", 1)[1]) except ValueError as exc: raise AdapterError(f"{SOURCE}: malformed object id {value!r}") from exc elif isinstance(value, int) and not isinstance(value, bool): index = value else: raise AdapterError(f"{SOURCE}: invalid {relation} target {value!r}") if index < 0 or index >= count: raise AdapterError(f"{SOURCE}: {relation} target {index} is out of range") output.append(f"object:{index}") return sorted(set(output), key=_object_index) def _record_array(path: Path, key: str) -> list[Mapping[str, Any]]: try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise AdapterError(f"{SOURCE}: cannot read {path}: {exc}") from exc records = payload.get(key) if isinstance(payload, Mapping) else None if not isinstance(records, list) or any(not isinstance(row, Mapping) for row in records): raise AdapterError(f"{SOURCE}: {path} has no valid {key!r} array") return records def _find_split_file( raw_dir: Path, split: str, kind: str, *, required: bool = True, ) -> Path | None: name = f"CLEVR_{split}_{kind}.json" matches = sorted(path for path in raw_dir.rglob(name) if path.is_file()) if not matches: if required: raise AdapterError(f"{SOURCE}: cannot find {name} under {raw_dir}") return None if len(matches) > 1: raise AdapterError(f"{SOURCE}: multiple files named {name}: {matches}") return matches[0] def _find_image(raw_dir: Path, split: str, filename: str) -> Path | None: direct = ( raw_dir / "images" / split / filename, raw_dir / "images" / filename, raw_dir / filename, ) for path in direct: if path.is_file(): return path matches = sorted(path for path in raw_dir.rglob(filename) if path.is_file()) if len(matches) > 1: raise AdapterError(f"{SOURCE}: multiple images named {filename}: {matches}") return matches[0] if matches else None def _answer(answer: str | int | bool) -> tuple[AnswerType, str | int | bool]: if isinstance(answer, bool): return "boolean", "yes" if answer else "no" text = str(answer).strip() if text.lower() in {"yes", "no"}: return "boolean", text.lower() try: return "integer", int(text) except ValueError: return "short_text", text def _integer_field(row: Mapping[str, Any], key: str, *, context: str) -> int: value = row.get(key) if isinstance(value, bool) or not isinstance(value, int): raise AdapterError(f"{SOURCE}: {context} {key} is not an integer") return value def _sort_integer(value: Any, fallback: int) -> int: return value if isinstance(value, int) and not isinstance(value, bool) else fallback def _enum( row: Mapping[str, Any], key: str, allowed: frozenset[str], index: int, ) -> str: value = row.get(key) if not isinstance(value, str) or value not in allowed: raise AdapterError(f"{SOURCE}: object {index} has invalid {key} {value!r}") return value def _coords(raw: Any, name: str, index: int, *, minimum: int) -> list[int | float]: if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes)) or len(raw) < minimum: raise AdapterError(f"{SOURCE}: object {index} {name} is malformed") if any(isinstance(value, bool) or not isinstance(value, (int, float)) for value in raw): raise AdapterError(f"{SOURCE}: object {index} {name} is not numeric") return list(raw) def _object_index(node_id: str) -> int: return int(node_id.split(":", 1)[1]) __all__ = ["ClevrAdapter", "SOURCE", "WORLD_SCHEMA", "world_from_scene"]