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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""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",
]