File size: 15,103 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
"""Geometry3K C1 source adapter (``docs/02`` §6).

Geometry3K (``lupantech/InterGPS`` @ ``99e6b52``) ships 3,002 high-school
geometry problems across ``train`` / ``validation`` / ``test``. Each problem has
a released ``data.json`` (problem text, four choices, answer letter, diagram
image) and an **annotated** logic form; the global ``logic_forms.zip`` holds the
authoritative annotated text/diagram logic forms keyed by integer ``id``. C1 uses
the annotated forms only — predicted diagram-parser output is excluded
(``docs/02`` §6.1).

P1 scope: deterministic ingest + ``normalize`` to a schema-conforming
:class:`NormalizedItem`, a structural ``geometry_world_v1`` builder with channel
provenance, and the released ``official_answer``. The typed DSL AST (P2) and the
6-check solver acceptance (P3) are deferred.
"""

from __future__ import annotations

import json
import re
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 (
    ImageStore,
    IngestError,
    NormalizedItem,
    Policy,
    make_item,
    mc_choices,
)
from .base import (
    AdapterError,
    CertificateTier,
    Channel,
    RawItem,
    World,
    extract_zip,
    github_raw_url,
    http_download,
    store_images,
)

SOURCE = "geometry3k"
WORLD_SCHEMA = "geometry_world_v1"

# The release names its split archive/directory ``val``; the resources manifest
# records the conventional ``validation``. Accept either.
_SPLIT_ALIAS: dict[str, str] = {"validation": "val"}
_VALID_SPLITS = frozenset({"train", "validation", "test"})
_MC_KEYS = ("A", "B", "C", "D")

# Archives fetched from the pinned revision. ``symbols.zip`` (predicted diagram
# symbols) is intentionally excluded — C1 uses annotated forms only (§6.1).
_ARCHIVES = ("train.zip", "val.zip", "test.zip", "logic_forms.zip")

# Annotated logic-form files inside ``logic_forms.zip``, keyed by integer id.
_TEXT_LOGIC_FORMS = "text_logic_forms_annot.json"
_TEXT_LOGIC_FORMS_DISSOLVED = "text_logic_forms_annot_dissolved.json"
_DIAGRAM_LOGIC_FORMS = "diagram_logic_forms_annot.json"


class Geometry3KAdapter:
    """C1 adapter for Geometry3K."""

    def __init__(self, raw_dir: Path, store: ImageStore, *, revision: str) -> None:
        self.raw_dir = Path(raw_dir)
        self.store = store
        self.revision = revision
        self._logic_forms: dict[str, dict[int, Any]] | None = None

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

    @classmethod
    def fetch(
        cls,
        raw_dir: Path,
        *,
        repo_id: str,
        revision: str,
        data_path: str,
        expected_sha256: Mapping[str, str] | None = None,
    ) -> Path:
        """Download + extract the Geometry3K archives into ``raw_dir``.

        Idempotent: existing verified archives are kept. ``expected_sha256`` maps
        archive name to a known-good digest when available; absent entries
        download without verification (the git revision is the pin) but the
        computed digest is still recorded by the caller's manifest.
        """
        raw_dir = Path(raw_dir)
        raw_dir.mkdir(parents=True, exist_ok=True)
        for archive in _ARCHIVES:
            url = github_raw_url(repo_id, revision, f"{data_path}/{archive}")
            dst = raw_dir / archive
            digest = (expected_sha256 or {}).get(archive)
            http_download(url, dst, expected_sha256=digest)
            extract_zip(dst, raw_dir)
        return raw_dir

    @classmethod
    def is_materialized(cls, raw_dir: Path, split: str) -> bool:
        """True when the split dir and annotated logic forms are on disk."""
        if split not in _VALID_SPLITS:
            return False
        raw_dir = Path(raw_dir)
        dir_name = _SPLIT_ALIAS.get(split, split)
        split_present = (raw_dir / dir_name).is_dir()
        logic_forms_present = (raw_dir / "logic_forms").is_dir() or (
            raw_dir / _TEXT_LOGIC_FORMS
        ).exists()
        return split_present and logic_forms_present

    @classmethod
    def materialize(
        cls,
        raw_dir: Path,
        split: str,
        *,
        source_config: Mapping[str, Any],
        expected_sha256: Mapping[str, str] | None = None,
    ) -> Path:
        """Fetch all Geometry3K archives git-pinned via the resources config.

        ``source_config`` carries ``repo_id``, ``revision``, and ``data_path``
        from ``resources.structured_sources.geometry3k``. Fetch grabs every split
        archive (idempotent), so ``split`` only gates ``is_materialized``.
        """
        repo_id = source_config.get("repo_id")
        revision = source_config.get("revision")
        data_path = source_config.get("data_path")
        if not (
            isinstance(repo_id, str) and isinstance(revision, str) and isinstance(data_path, str)
        ):
            raise AdapterError(
                f"{SOURCE}: materialize requires repo_id, revision, data_path in resources config"
            )
        return cls.fetch(
            raw_dir,
            repo_id=repo_id,
            revision=revision,
            data_path=data_path,
            expected_sha256=expected_sha256,
        )

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

    def _load_logic_forms(self) -> dict[str, dict[int, Any]]:
        if self._logic_forms is not None:
            return self._logic_forms
        root = self.raw_dir / "logic_forms"
        if not root.is_dir():
            # Some extractions place the three json files directly under raw_dir.
            root = self.raw_dir
        loaded: dict[str, dict[int, Any]] = {}
        for fname in (_TEXT_LOGIC_FORMS, _TEXT_LOGIC_FORMS_DISSOLVED, _DIAGRAM_LOGIC_FORMS):
            path = root / fname
            if not path.exists():
                raise AdapterError(f"missing annotated logic-form file: {path}")
            data = json.loads(path.read_text(encoding="utf-8"))
            # The release keys these by integer id (stringified in JSON).
            keyed = {int(k): v for k, v in data.items()}
            loaded[fname] = keyed
        self._logic_forms = loaded
        return loaded

    def iter_base_items(self, split: str) -> Iterator[RawItem]:
        if split not in _VALID_SPLITS:
            raise AdapterError(f"{SOURCE}: unsupported split {split!r}")
        dir_name = _SPLIT_ALIAS.get(split, split)
        split_dir = self.raw_dir / dir_name
        if not split_dir.is_dir():
            raise AdapterError(f"{SOURCE}: split directory not found: {split_dir}")
        logic = self._load_logic_forms()
        text_forms = logic[_TEXT_LOGIC_FORMS_DISSOLVED] or logic[_TEXT_LOGIC_FORMS]
        diagram_forms = logic[_DIAGRAM_LOGIC_FORMS]

        ids = sorted(int(p.name) for p in split_dir.iterdir() if p.is_dir() and p.name.isdigit())
        for pid in ids:
            problem_dir = split_dir / str(pid)
            data_path = problem_dir / "data.json"
            if not data_path.exists():
                raise AdapterError(f"{SOURCE}/{pid}: missing data.json")
            data = json.loads(data_path.read_text(encoding="utf-8"))
            img_path = problem_dir / "img_diagram.png"
            if not img_path.exists():
                raise AdapterError(f"{SOURCE}/{pid}: missing img_diagram.png")
            images = {"diagram": img_path.read_bytes()}
            text_lf = text_forms.get(pid)
            diagram_lf = diagram_forms.get(pid)
            if text_lf is None or diagram_lf is None:
                # A problem without annotated forms cannot be a C1 candidate.
                raise AdapterError(f"{SOURCE}/{pid}: missing annotated logic forms")
            payload = {
                "id": pid,
                **data,
                "text_logic_form": text_lf,
                "diagram_logic_form": diagram_lf,
            }
            yield RawItem(
                source=SOURCE,
                split=split,
                source_revision=self.revision,
                native_id=str(pid),
                payload=payload,
                images=images,
            )

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

    def normalize(self, raw: RawItem) -> NormalizedItem:
        data = raw.payload
        problem_text = data.get("problem_text")
        if not isinstance(problem_text, str) or not problem_text.strip():
            raise IngestError(f"{SOURCE}/{raw.native_id}: problem_text missing/empty")
        choice_texts = data.get("choices")
        if not isinstance(choice_texts, list) or len(choice_texts) != len(_MC_KEYS):
            raise IngestError(f"{SOURCE}/{raw.native_id}: choices must be {len(_MC_KEYS)} strings")
        choices = mc_choices([str(c) for c in choice_texts], keys=list(_MC_KEYS))
        answer = data.get("answer")
        if not isinstance(answer, str) or answer not in _MC_KEYS:
            raise IngestError(
                f"{SOURCE}/{raw.native_id}: answer must be a letter A-D, got {answer!r}"
            )
        if not raw.images:
            raise IngestError(f"{SOURCE}/{raw.native_id}: diagram image missing")
        paths, shas = store_images(self.store, raw.images)

        graph_types = data.get("problem_type_graph") or []
        subject = (
            str(graph_types[0]) if isinstance(graph_types, list) and graph_types else "geometry"
        )
        policy: Policy = (
            "c1_train_candidate"
            if raw.split in ("train", "validation")
            else "c1_certified_eval_candidate"
        )
        goal = data.get("problem_type_goal")
        channel_map = _channel_map(data.get("text_logic_form"), data.get("diagram_logic_form"))
        extra = {
            "annotated_text_logic_form": data.get("text_logic_form"),
            "annotated_diagram_logic_form": data.get("diagram_logic_form"),
            "channel_map": channel_map,
            "goal": goal,
            "problem_type_goal": goal,
            "raw_payload_sha256": sha256_bytes(
                json.dumps(data, 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=problem_text,
            choices=choices,
            answer_raw=answer,
            answer_canonical=answer,
            answer_type="multiple_choice",
            image_paths=paths,
            image_sha256=shas,
            policy=policy,
            native_row=data,
            subject=subject,
            extra_provenance=extra,
        )

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

    def build_world(self, item: NormalizedItem) -> World:
        prov = item.provenance
        text_lf = _as_logic_lines(prov.get("annotated_text_logic_form"))
        diagram_lf = _as_logic_lines(prov.get("annotated_diagram_logic_form"))
        channel_map = prov.get("channel_map") or {}
        entities: dict[str, dict[str, Any]] = {}
        constraints: list[dict[str, Any]] = []
        for line in text_lf:
            pred = _parse_predicate(line)
            if pred is not None:
                constraints.append({**pred, "channel": channel_map.get(line, "text")})
                _collect_entities(pred, entities)
        for line in diagram_lf:
            pred = _parse_predicate(line)
            if pred is not None:
                constraints.append({**pred, "channel": channel_map.get(line, "visual")})
                _collect_entities(pred, entities)
        return {
            "world_schema": WORLD_SCHEMA,
            "entities": [{"id": eid, **body} for eid, body in sorted(entities.items())],
            "constraints": constraints,
            "goal": prov.get("goal"),
            "provenance": {
                "source": item.source,
                "source_native_id": item.source_native_id,
                "channels": sorted(set(channel_map.values()) or {"text", "visual"}),
            },
        }

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

        Builds the world, hands it to the compiler, and returns a
        :class:`Program` (``compiled`` or ``unsupported``) with constraint
        channel provenance on the envelope. No execution, no model calls — P3/P4.
        """
        from ..dsl.geometrydsl import compile_geometry3k

        return compile_geometry3k(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"


# --- logic-form parsing helpers -------------------------------------------

_PRED_RE = re.compile(r"^([A-Za-z_]+)\((.*)\)$")


def _as_logic_lines(value: Any) -> list[str]:
    """Normalize an annotated logic-form value to a list of predicate strings."""
    if value is None:
        return []
    if isinstance(value, str):
        return [ln.strip() for ln in value.splitlines() if ln.strip()]
    if isinstance(value, list):
        return [str(ln).strip() for ln in value if str(ln).strip()]
    return []


def _parse_predicate(line: str) -> dict[str, Any] | None:
    match = _PRED_RE.match(line.strip())
    if match is None:
        return None
    predicate, raw_args = match.groups()
    args = [a.strip() for a in raw_args.split(",")] if raw_args else []
    return {"predicate": predicate, "args": args}


def _collect_entities(pred: Mapping[str, Any], entities: dict[str, dict[str, Any]]) -> None:
    """Record referenced entity ids (``point:A``, ``segment:A:B``, ...) from args."""
    for arg in pred["args"]:
        if isinstance(arg, str) and ":" in arg:
            eid, _, body = arg.partition(":")
            full = arg
            etype = eid.capitalize() if eid else "Entity"
            if full not in entities:
                entities[full] = {"type": etype, "args": []}
            if body and body not in entities[full]["args"]:
                entities[full]["args"].append(body)


def _channel_map(text_lf: Any, diagram_lf: Any) -> dict[str, Channel]:
    """Tag each predicate string with its provenance channel (§6.2).

    A fact present in both text and diagram is ``redundant``; text-only is
    ``text``; diagram-only is ``visual``. Interventions alter only ``visual``.
    """
    text_set = set(_as_logic_lines(text_lf))
    diagram_set = set(_as_logic_lines(diagram_lf))
    channel_map: dict[str, Channel] = {}
    for line in text_set & diagram_set:
        channel_map[line] = "redundant"
    for line in text_set - diagram_set:
        channel_map[line] = "text"
    for line in diagram_set - text_set:
        channel_map[line] = "visual"
    return channel_map


__all__ = ["Geometry3KAdapter", "SOURCE", "WORLD_SCHEMA"]