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
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
"""PlotQA C1 source adapter (``docs/02`` §5).

PlotQA (``NiteshMethani/PlotQA`` @ ``e0f5c34``) ships scientific plots with
crowd-sourced QA instantiated from templates. The pinned GitHub revision carries
only docs/template definitions; the **data** (plot PNGs, ``annotations.json``,
``qa_pairs_v2.json``) is hosted on Google Drive, so the git revision is not a
data pin — SHA-256 of every downloaded archive is the integrity anchor and is
recorded in the ingest manifest.

Join key: ``image_index`` (qa pair ↔ plot annotation). Only rows whose template
is in the supported allowlist and whose referenced series/x label resolves
uniquely become candidates (§5.1); executor-tolerance answer reproduction is a
P3 gate. The template→PlotDSL mapping (§5.2) is dataset-level (per-template, not
per-example).

P1 scope: deterministic ingest + ``normalize`` to a schema-conforming
:class:`NormalizedItem`, a structural ``plot_world_v1`` builder, the released
``official_answer``, and the template allowlist + mapping table. The ≥50/template
reproduction unit gate is P3 (executor).

.. note:: The exact annotation/qa field shapes are confirmed against the real
   download at fetch time; the adapter is robust to the documented fields and
   unit-tested with fixtures that pin the schema it relies on.
"""

from __future__ import annotations

import json
from collections.abc import Iterator, Mapping
from pathlib import Path
from typing import Any

from ..dsl.ast import Program
from ..hashing import sha256_bytes
from ..ingest.base import (
    AnswerType,
    ImageStore,
    IngestError,
    NormalizedItem,
    Policy,
    infer_open_answer_type,
    make_item,
    mc_choices,
)
from .base import (
    AdapterError,
    CertificateTier,
    RawItem,
    World,
    extract_zip,
    gdrive_download,
    store_images,
)

SOURCE = "plotqa"
WORLD_SCHEMA = "plot_world_v1"
_VALID_SPLITS = frozenset({"train", "validation", "test"})
_MC_KEYS = ("A", "B", "C", "D", "E", "F", "G", "H")

# Supported template allowlist (§5.1). Templates not listed here are dropped
# wholesale — never patched per-row (§5.2). Extended as mappings are validated.
TEMPLATE_ALLOWLIST: frozenset[str] = frozenset(
    {"T_LOOKUP", "T_DIFFERENCE", "T_MAX_YEAR", "T_MIN_YEAR", "T_SUM"}
)

# Dataset-level template → PlotDSL mapping (§5.2). Per-template, not per-example.
# The ≥50-official-reproductions-per-template gate is a P3 executor test.
TEMPLATE_DSL_MAPPING: dict[str, str] = {
    "T_LOOKUP": "LOOKUP(SELECT_SERIES({series}), SELECT_X({x}))",
    "T_DIFFERENCE": "SUBTRACT(LOOKUP({series}, {x1}), LOOKUP({series}, {x2}))",
    "T_MAX_YEAR": "ARGMAX(POINTS(SELECT_SERIES({series})), value)",
    "T_MIN_YEAR": "ARGMIN(POINTS(SELECT_SERIES({series})), value)",
    "T_SUM": "SUM(POINTS(SELECT_SERIES({series})))",
}

# Google-Drive file ids per split (image archives). Annotation/qa-pair file ids
# are supplied via ``fetch``'s ``file_ids`` map; an unknown id is a hard error,
# never a silent skip. Image ids come from PlotQA_Dataset.md at the pinned rev.
_GDRIVE_IMAGE_IDS: dict[str, str] = {
    "train": "1AYuaPX-Lx7T0GZvnsPgN11Twq2FZbWXL",
    "validation": "1i74NRCEb-x44xqzAovuglex5d583qeiF",
    "test": "1D_WPUy91vOrFl6cJUkE55n3ZuB6Qrc4u",
}


class PlotQAAdapter:
    """C1 adapter for PlotQA."""

    def __init__(
        self,
        raw_dir: Path,
        store: ImageStore,
        *,
        revision: str,
        images_dir: Path | None = None,
    ) -> None:
        self.raw_dir = Path(raw_dir)
        self.store = store
        self.revision = revision
        # Plot images live under ``<raw_dir>/png/<index>.png`` by default; the
        # constructor lets a test pin an explicit images directory.
        self.images_dir = images_dir or (self.raw_dir / "png")

    # --- fetch -----------------------------------------------------------

    @classmethod
    def fetch(
        cls,
        raw_dir: Path,
        split: str,
        *,
        file_ids: Mapping[str, str],
        expected_sha256: Mapping[str, str] | None = None,
    ) -> Path:
        """Download one split's archives from Google Drive into ``raw_dir``.

        ``file_ids`` maps a local archive name (e.g. ``"train_images.zip"``,
        ``"train_annotations.json"``, ``"train_qa_pairs_v2.json"``) to a Drive
        file id. An id that is not supplied for a required artifact raises
        :class:`AdapterError` — never a silent skip. The image archive is
        extracted in place so ``_image_bytes`` can read ``png/<index>.png``.
        """
        if split not in _VALID_SPLITS:
            raise AdapterError(f"{SOURCE}: unsupported split {split!r}")
        raw_dir = Path(raw_dir)
        raw_dir.mkdir(parents=True, exist_ok=True)
        required = (f"{split}_images.zip", f"{split}_annotations.json", f"{split}_qa_pairs_v2.json")
        for archive in required:
            file_id = file_ids.get(archive)
            if not file_id:
                raise AdapterError(
                    f"{SOURCE}: missing Drive file id for {archive!r}; "
                    "supply it in resources/structured_sources.plotqa.file_ids"
                )
            dst = raw_dir / archive
            digest = (expected_sha256 or {}).get(archive)
            gdrive_download(file_id, dst, expected_sha256=digest)
            if archive.endswith(".zip"):
                extract_zip(dst, raw_dir)
        return raw_dir

    @classmethod
    def is_materialized(cls, raw_dir: Path, split: str) -> bool:
        """True when one split's annotation + qa files are already on disk."""
        raw_dir = Path(raw_dir)
        return (raw_dir / f"{split}_qa_pairs_v2.json").exists() and (
            raw_dir / f"{split}_annotations.json"
        ).exists()

    @classmethod
    def materialize(
        cls,
        raw_dir: Path,
        split: str,
        *,
        source_config: Mapping[str, Any],
        expected_sha256: Mapping[str, str] | None = None,
    ) -> Path:
        """Fetch a split from Drive using file ids from the resources config.

        The Drive file ids are not git-pinned, so they (and the per-archive
        sha256) must be supplied in ``source_config["file_ids"]``; their absence
        is a hard :class:`AdapterError`, never a silent skip.
        """
        file_ids = source_config.get("file_ids") or {}
        if not isinstance(file_ids, Mapping):
            raise AdapterError(f"{SOURCE}: file_ids must be a mapping in resources config")
        return cls.fetch(raw_dir, split, file_ids=file_ids, expected_sha256=expected_sha256)

    # --- iter ------------------------------------------------------------

    def _annotation_index(self) -> dict[int, dict[str, Any]]:
        path = self._first_split_file("annotations.json")
        records = json.loads(path.read_text(encoding="utf-8"))
        out: dict[int, dict[str, Any]] = {}
        for rec in records:
            idx = rec.get("image_index") if isinstance(rec, dict) else None
            if idx is None:
                continue
            out[int(idx)] = rec
        return out

    def _qa_pairs(self, split: str) -> list[dict[str, Any]]:
        path = self._first_split_file("qa_pairs_v2.json")
        data = json.loads(path.read_text(encoding="utf-8"))
        return [d for d in data if isinstance(d, dict)]

    def _first_split_file(self, suffix: str) -> Path:
        for prefix in ("train", "validation", "test"):
            candidate = self.raw_dir / f"{prefix}_{suffix}"
            if candidate.exists():
                return candidate
        raise AdapterError(f"{SOURCE}: missing {suffix} under {self.raw_dir}")

    def _image_bytes(self, image_index: int) -> bytes:
        for candidate in (
            self.images_dir / f"{image_index}.png",
            self.raw_dir / "png" / f"{image_index}.png",
        ):
            if candidate.exists():
                return candidate.read_bytes()
        raise AdapterError(f"{SOURCE}: plot image not found for image_index {image_index}")

    def iter_base_items(self, split: str) -> Iterator[RawItem]:
        if split not in _VALID_SPLITS:
            raise AdapterError(f"{SOURCE}: unsupported split {split!r}")
        annotations = self._annotation_index()
        qa_pairs = self._qa_pairs(split)
        # Deterministic order: (image_index, position in qa file).
        ordered = sorted(
            enumerate(qa_pairs),
            key=lambda pair: (
                int(pair[1].get("image_index", -1)) if isinstance(pair[1], dict) else -1,
                pair[0],
            ),
        )
        for qa_index, qa in ordered:
            if not isinstance(qa, dict):
                continue
            template = qa.get("template")
            if not isinstance(template, str) or template not in TEMPLATE_ALLOWLIST:
                continue  # out-of-allowlist template → whole-template skip (§5.2)
            image_index = qa.get("image_index")
            if image_index is None or int(image_index) not in annotations:
                continue  # referenced plot missing → not a candidate (§5.1)
            annotation = annotations[int(image_index)]
            if not _single_series_x_match(qa, annotation):
                continue  # referenced series/x not unique → not a candidate (§5.1)
            try:
                images = {"plot": self._image_bytes(int(image_index))}
            except AdapterError:
                continue  # image unavailable → drop, not a hard error at filter stage
            payload = {
                "image_index": int(image_index),
                "qa_index": qa_index,
                **qa,
                "annotation": annotation,
            }
            yield RawItem(
                source=SOURCE,
                split=split,
                source_revision=self.revision,
                native_id=f"{image_index}:{qa_index}",
                payload=payload,
                images=images,
            )

    # --- normalize -------------------------------------------------------

    def normalize(self, raw: RawItem) -> NormalizedItem:
        qa = raw.payload
        question = qa.get("question_string")
        if not isinstance(question, str) or not question.strip():
            raise IngestError(f"{SOURCE}/{raw.native_id}: question_string missing/empty")
        answer = qa.get("answer")
        if answer is None or (isinstance(answer, str) and not answer.strip()):
            raise IngestError(f"{SOURCE}/{raw.native_id}: answer missing/empty")
        if not raw.images:
            raise IngestError(f"{SOURCE}/{raw.native_id}: plot image missing")
        paths, shas = store_images(self.store, raw.images)

        choices_texts = qa.get("choices")
        answer_type: AnswerType
        if isinstance(choices_texts, list) and choices_texts:
            keys = list(_MC_KEYS[: len(choices_texts)])
            choices = mc_choices([str(c) for c in choices_texts], keys=keys)
            answer_type = "multiple_choice"
            answer_canonical = str(answer)
        else:
            choices = []
            answer_type = infer_open_answer_type(str(answer))
            answer_canonical = str(answer)

        annotation = qa.get("annotation") or {}
        policy: Policy = (
            "c1_train_candidate"
            if raw.split in ("train", "validation")
            else "c1_certified_eval_candidate"
        )
        extra = {
            "template": qa.get("template"),
            "type": qa.get("type"),
            "models": annotation.get("models"),
            "axes": {
                "x_axis": annotation.get("x_axis"),
                "y_axis": annotation.get("y_axis"),
                "legend": annotation.get("legend"),
                "title": annotation.get("title"),
            },
            # QA slot metadata consumed by the dataset-level program compiler
            # (§5.2). Carrying source-native slots is not per-example human
            # labeling; it is the template's structured input.
            "slots": {
                "series": qa.get("series") or qa.get("series_label"),
                "x": qa.get("x"),
                "x1": qa.get("x1"),
                "x2": qa.get("x2"),
            },
            "raw_payload_sha256": sha256_bytes(
                json.dumps(qa, sort_keys=True, separators=(",", ":")).encode("utf-8")
            ),
        }
        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=choices,
            answer_raw=str(answer),
            answer_canonical=answer_canonical,
            answer_type=answer_type,
            image_paths=paths,
            image_sha256=shas,
            policy=policy,
            native_row=qa,
            extra_provenance=extra,
        )

    # --- world / answer / tier ------------------------------------------

    def build_world(self, item: NormalizedItem) -> World:
        prov = item.provenance
        models = prov.get("models") or []
        axes = prov.get("axes") or {}
        series = _series_from_models(models, axes)
        return {
            "world_schema": WORLD_SCHEMA,
            "plot_type": _infer_plot_type(models, axes),
            "series": series,
            "x_axis": axes.get("x_axis"),
            "y_axis": axes.get("y_axis"),
            "legend": axes.get("legend"),
            "title": axes.get("title"),
            "style_seed": 0,
            "node_visibility": {},
            "provenance": {
                "source": item.source,
                "source_native_id": item.source_native_id,
                "template": prov.get("template"),
            },
        }

    def get_or_compile_program(self, item: NormalizedItem) -> Program:
        """Compile the typed ``plotqa_dsl_v1`` program for ``item`` (P2).

        Builds the world, hands it to the dataset-level compiler, and returns a
        :class:`Program` (``compiled`` or ``unsupported``). No execution, no
        model calls — those are P3/P4.
        """
        from ..dsl.plotdsl import compile_plotqa

        return compile_plotqa(item, self.build_world(item))

    def official_answer(self, item: NormalizedItem) -> str:
        return str(item.answer_canonical)

    def source_certificate_tier(self, item: NormalizedItem) -> CertificateTier:
        return "C1_SOURCE_NATIVE"


# --- candidate-filter + world helpers -------------------------------------


def _single_series_x_match(qa: Mapping[str, Any], annotation: Mapping[str, Any]) -> bool:
    """§5.1: the referenced series/x label must resolve to exactly one in the plot.

    A best-effort structural check that the QA's referenced series label (if
    extractable from the template slots) matches exactly one model in the
    annotation. The full slot/template-metadata consistency check is completed
    with the executor (P3); here we reject only the clearly-ambiguous case.
    """
    models = annotation.get("models") or []
    if not isinstance(models, list) or not models:
        return False
    series = qa.get("series") or qa.get("series_label")
    if series is None:
        return True  # no series slot to check (e.g. aggregate templates)
    matches = [m for m in models if isinstance(m, dict) and m.get("label") == series]
    return len(matches) == 1


def _series_from_models(models: Any, axes: Mapping[str, Any]) -> list[dict[str, Any]]:
    if not isinstance(models, list):
        return []
    series: list[dict[str, Any]] = []
    for i, model in enumerate(models):
        if not isinstance(model, dict):
            continue
        points = [
            {"id": f"point:{i}:{j}", "x": str(p.get("x", "")), "y": str(p.get("y", ""))}
            for j, p in enumerate(model.get("points") or [])
            if isinstance(p, dict)
        ]
        series.append(
            {
                "id": f"series:{i}",
                "label": model.get("label") or model.get("name") or f"series_{i}",
                "points": points,
            }
        )
    return series


def _infer_plot_type(models: Any, axes: Mapping[str, Any]) -> str:
    legend = axes.get("legend")
    if isinstance(models, list) and len(models) > 1:
        return "multi_line" if legend else "bar"
    return "line"


__all__ = [
    "PlotQAAdapter",
    "SOURCE",
    "TEMPLATE_ALLOWLIST",
    "TEMPLATE_DSL_MAPPING",
    "WORLD_SCHEMA",
]