Datasets:
Download src/explicit_learning/dsl/ast.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/dsl/ast.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/dsl/ast.py
-
curl -L -o ast.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/dsl/ast.py
12.1 kB
| """Immutable typed AST for the canonical question programs (``docs/02`` §7). | |
| A question *program* is a tree of :class:`AstNode` values. The serialized form | |
| conforms to ``schemas/compiled_program.schema.json`` ``$defs/astNode``:: | |
| {"op": <str>, "args": [<astNode | str | number | bool>, ...], "return_type": <str>?} | |
| Design choices pinned by the spec: | |
| * **Exact numerics.** Numeric literals are ``fractions.Fraction`` internally and | |
| serialize to a *canonical rational string* (``5`` → ``"5"``, ``3/2`` → | |
| ``"3/2"``, ``"1.50"`` → ``"3/2"``), never a JSON float — so ``1.5`` and | |
| ``3/2`` collapse to one canonical form (``docs/02`` §3.2/§3.3 "exact rational | |
| 우선", "decimal string canonicalizer trailing-zero 제거"). A literal that would | |
| lose precision as a float is therefore exact. | |
| * **Uniform nodes.** Every meaningful operand is an :class:`AstNode`: compound | |
| ops (``LOOKUP``, ``MEASURE``, …) and two leaf kinds — ``REF`` (an entity | |
| reference with a stable id) and ``LITERAL`` (an atomic value). Bare atomic | |
| ``args`` are reserved for *field/key* strings (e.g. ``"value"``) that are not | |
| themselves typed operands. This keeps the type checker uniform: it dispatches | |
| on ``op`` and reads ``return_type``. | |
| * **Immutability.`` :class:`AstNode` and :class:`Program` are frozen; ``args`` is | |
| a tuple. Canonicalization returns new nodes rather than mutating. | |
| The :class:`Program` envelope is the P2 structural record — it carries the AST, | |
| the referent selector, the *declared* referent cardinality, the resolved | |
| referenced node ids, and the canonical program hash. The full | |
| ``compiled_program`` record (``compile_id`` / ``compiler_role`` / ``model`` / | |
| ``request_sha256``) is the **P4 C2 model-compiler** record and is not produced | |
| here. | |
| """ | |
| from __future__ import annotations | |
| from collections.abc import Mapping | |
| from dataclasses import dataclass | |
| from fractions import Fraction | |
| from functools import lru_cache | |
| from typing import Any, Literal, Union | |
| from ..ingest.base import IngestError | |
| from ..paths import repo_root | |
| from ..schema_io import load_schema, validate | |
| Dsl = Literal["plotqa_dsl_v1", "geometry_dsl_v1", "table_dsl_v1", "clevr_dsl_v1"] | |
| CompileStatus = Literal["compiled", "unsupported"] | |
| # Leaf op markers. A leaf node carries exactly one atomic arg. | |
| REF = "REF" # entity reference: args=(id_str,), return_type = entity kind | |
| LITERAL = "LITERAL" # atomic value: args=(serialized_value,), return_type = value kind | |
| # One positional operand of a node: a sub-node, or a bare atomic field/key. | |
| Arg = Union["AstNode", str, int, Fraction, bool] | |
| class ProgramError(IngestError): | |
| """Raised when an AST node or :class:`Program` is malformed or schema-invalid.""" | |
| # --- numeric canonicalization (§3.2/§3.3) ---------------------------------- | |
| def parse_number(value: str | int | Fraction) -> Fraction: | |
| """Parse a decimal/rational/integer into an exact reduced :class:`Fraction`. | |
| Accepts ``"1.5"``, ``"3/2"``, ``"5"``, ``"5.0"`` and integers. ``Fraction`` | |
| reduces and exact-represents each so numerically-equal inputs compare equal. | |
| """ | |
| if isinstance(value, Fraction): | |
| return value | |
| if isinstance(value, int) and not isinstance(value, bool): | |
| return Fraction(value) | |
| return Fraction(str(value)) | |
| def canonical_number_str(value: str | int | Fraction) -> str: | |
| """Canonical exact-rational string of a numeric value (``docs/02`` §3.2). | |
| Integers render as their decimal string (``5`` → ``"5"``); non-integer | |
| rationals as ``"num/den"`` in lowest terms (``3/2`` → ``"3/2"``). Trailing | |
| zeros are gone because the form is exact, not decimal. Two numerically-equal | |
| inputs always produce the same string. | |
| """ | |
| frac = parse_number(value) | |
| if frac.denominator == 1: | |
| return str(frac.numerator) | |
| return f"{frac.numerator}/{frac.denominator}" | |
| # --- AST node --------------------------------------------------------------- | |
| class AstNode: | |
| """One immutable node of a question program (``compiled_program.schema.json`` astNode). | |
| ``op`` is the operator/predicate name (``LOOKUP``, ``MeasureOf``, ``REF``, | |
| ``LITERAL``, …). ``args`` is an order-significant tuple of sub-nodes and bare | |
| atomic field keys. ``return_type`` is the typed result kind | |
| (``value``/``series``/``point``/``angle``/``number``/…); it is the type the | |
| checker and canonicalizer propagate. | |
| """ | |
| op: str | |
| args: tuple[Arg, ...] = () | |
| return_type: str = "" | |
| def to_ast_node_dict(self) -> dict[str, Any]: | |
| """Serialize to a dict conforming to ``$defs/astNode``.""" | |
| out: dict[str, Any] = {"op": self.op, "args": [_arg_to_dict(a) for a in self.args]} | |
| if self.return_type: | |
| out["return_type"] = self.return_type | |
| return out | |
| def is_ref(self) -> bool: | |
| return self.op == REF | |
| def is_literal(self) -> bool: | |
| return self.op == LITERAL | |
| def ref_id(self) -> str: | |
| """The stable entity id of a ``REF`` leaf (raises otherwise).""" | |
| if not self.is_ref(): | |
| raise ProgramError(f"{self.op!r} node is not an entity reference") | |
| if len(self.args) != 1 or not isinstance(self.args[0], str): | |
| raise ProgramError(f"REF node must carry one string id, got {self.args!r}") | |
| return self.args[0] | |
| def _arg_to_dict(arg: Arg) -> Any: | |
| if isinstance(arg, AstNode): | |
| return arg.to_ast_node_dict() | |
| if isinstance(arg, bool): # before int: bool is an int subclass | |
| return arg | |
| if isinstance(arg, int): | |
| return arg | |
| if isinstance(arg, Fraction): | |
| # A bare numeric arg is serialized as its canonical exact string so it | |
| # never degrades to a lossy float; builders normally wrap numerics in a | |
| # LITERAL node, but this keeps a bare Fraction exact if it appears. | |
| return canonical_number_str(arg) | |
| if isinstance(arg, str): | |
| return arg | |
| raise ProgramError(f"unsupported AST arg type {type(arg)!r}") | |
| def _arg_from_dict(arg: Any) -> Arg: | |
| """Inverse of :func:`_arg_to_dict`: rebuild one AST arg from model JSON.""" | |
| if isinstance(arg, Mapping): # nested astNode | |
| return ast_node_from_dict(arg) | |
| if isinstance(arg, bool): # before int: bool is an int subclass | |
| return arg | |
| if isinstance(arg, int): | |
| return arg | |
| if isinstance(arg, float): | |
| return parse_number(str(arg)) # exact rational, never a lossy float | |
| if isinstance(arg, str): | |
| return arg | |
| raise ProgramError(f"unsupported astNode arg {arg!r}") | |
| def ast_node_from_dict(data: Mapping[str, Any]) -> AstNode: | |
| """Rebuild an :class:`AstNode` from a ``$defs/astNode``-shaped dict. | |
| The inverse of :meth:`AstNode.to_ast_node_dict`, used by the C2 compiler | |
| (P4) to parse a model's JSON program response into the typed AST. Numeric | |
| args are kept exact (a JSON float becomes a :class:`~fractions.Fraction`). | |
| Raises :class:`ProgramError` on a malformed node; call | |
| :func:`validate_ast_node` first for schema-level errors. | |
| """ | |
| if not isinstance(data, Mapping): | |
| raise ProgramError(f"astNode must be an object, got {type(data).__name__}") | |
| op = data.get("op") | |
| if not isinstance(op, str) or not op: | |
| raise ProgramError("astNode requires a non-empty string 'op'") | |
| raw_args = data.get("args", []) | |
| if not isinstance(raw_args, list): | |
| raise ProgramError("astNode 'args' must be an array") | |
| args = tuple(_arg_from_dict(a) for a in raw_args) | |
| return_type = str(data.get("return_type", "") or "") | |
| return AstNode(op=op, args=args, return_type=return_type) | |
| # --- leaf constructors ------------------------------------------------------ | |
| def ref(entity_id: str, *, return_type: str = "entity") -> AstNode: | |
| """Build an entity-reference leaf (``op=REF``, one string id arg).""" | |
| if not entity_id: | |
| raise ProgramError("entity reference id must be non-empty") | |
| return AstNode(op=REF, args=(entity_id,), return_type=return_type) | |
| def lit(value: str | int | Fraction | bool, *, return_type: str) -> AstNode: | |
| """Build an atomic-literal leaf. | |
| Numerics (``return_type`` ``number``/``integer``) serialize via | |
| :func:`canonical_number_str`; booleans as JSON booleans; expressions/strings | |
| as their (pre-canonicalization) string form. | |
| """ | |
| if return_type in ("number", "integer"): | |
| return AstNode(op=LITERAL, args=(canonical_number_str(value),), return_type=return_type) | |
| if return_type == "boolean": | |
| return AstNode(op=LITERAL, args=(bool(value),), return_type=return_type) | |
| if return_type in ("expression", "string", "field"): | |
| return AstNode(op=LITERAL, args=(str(value),), return_type=return_type) | |
| raise ProgramError(f"unsupported literal return_type {return_type!r}") | |
| # --- program envelope ------------------------------------------------------- | |
| class Program: | |
| """The P2 structural program record for one normalized item. | |
| ``canonical_program_sha256`` is filled by | |
| :func:`~explicit_learning.dsl.canonicalize.canonical_program_sha256`. | |
| ``constraint_channels`` carries geometry channel provenance (constraint | |
| node key → ``text``/``visual``/``redundant``) for the P3 intervention layer; | |
| it is **not** part of the schema-conforming envelope. | |
| """ | |
| dsl: Dsl | |
| program: AstNode | |
| base_id: str | |
| question_sha256: str | |
| choices_sha256: str | |
| compile_status: CompileStatus | |
| referent_selector: AstNode | None = None | |
| required_referent_cardinality: int | None = None | |
| referenced_node_ids: tuple[str, ...] = () | |
| canonical_program_sha256: str = "" | |
| reason_code: str | None = None | |
| constraint_channels: tuple[tuple[str, str], ...] = () | |
| def to_dict(self) -> dict[str, Any]: | |
| """The P2 program envelope (a subset of ``compiled_program``). | |
| The ``program`` sub-dict conforms to ``$defs/astNode``; the envelope is | |
| not itself a full ``compiled_program`` record (that needs P4's | |
| ``compile_id``/``compiler_role``/``model``). | |
| """ | |
| envelope: dict[str, Any] = { | |
| "dsl": self.dsl, | |
| "program": self.program.to_ast_node_dict(), | |
| "base_id": self.base_id, | |
| "question_sha256": self.question_sha256, | |
| "choices_sha256": self.choices_sha256, | |
| "compile_status": self.compile_status, | |
| "referent_selector": ( | |
| self.referent_selector.to_ast_node_dict() if self.referent_selector else None | |
| ), | |
| "required_referent_cardinality": self.required_referent_cardinality, | |
| "referenced_node_ids": list(self.referenced_node_ids), | |
| "canonical_program_sha256": self.canonical_program_sha256 or None, | |
| } | |
| if self.reason_code is not None: | |
| envelope["reason_code"] = self.reason_code | |
| return envelope | |
| # --- schema validation ------------------------------------------------------ | |
| def _compiled_program_schema() -> dict[str, Any]: | |
| return load_schema(repo_root() / "schemas" / "compiled_program.schema.json") | |
| def _ast_node_schema() -> dict[str, Any]: | |
| """A standalone schema validating one ``astNode`` (with ``$defs`` in scope).""" | |
| full = _compiled_program_schema() | |
| return {"$schema": full.get("$schema", ""), "$defs": full["$defs"], "$ref": "#/$defs/astNode"} | |
| def validate_ast_node(node: Mapping[str, Any] | AstNode) -> None: | |
| """Raise :class:`ProgramError` if ``node`` violates ``$defs/astNode``.""" | |
| instance = node.to_ast_node_dict() if isinstance(node, AstNode) else dict(node) | |
| errors = validate(instance, _ast_node_schema()) | |
| if errors: | |
| raise ProgramError("astNode failed schema validation: " + "; ".join(errors)) | |
| __all__ = [ | |
| "Arg", | |
| "AstNode", | |
| "CompileStatus", | |
| "Dsl", | |
| "LITERAL", | |
| "Program", | |
| "ProgramError", | |
| "REF", | |
| "ast_node_from_dict", | |
| "canonical_number_str", | |
| "lit", | |
| "parse_number", | |
| "ref", | |
| "validate_ast_node", | |
| ] | |