"""Structured deterministic renderers (``docs/02`` §9, ``docs/07`` §8 P6). A renderer turns a structured :class:`World` into four byte-addressed assets — ``rgba.png``, ``node_map.uint32.png``, ``render_manifest.json``, ``text_manifest.json`` — by **drawing fresh from the world**, never by editing an input raster. Two hard P6 gates shape this module: * **Byte-identical replay** — the same ``(world, renderer_id, seed, size)`` in the same clean process must reproduce the PNG bytes and the node-map hash exactly. So nothing time-dependent ever enters a manifest or a canvas: the backend is the fixed matplotlib ``Agg`` backend, the font is a pinned TTF (its SHA-256 recorded), and iteration order is sorted. * **No pixel-edit / inpainting code path** — REDACT_SOLID_V1 (§10.1) hides a node by *drawing a fixed, content-independent patch* over its would-be pixels. The hidden node is excluded from the canvas and the node map; the patch carries no node id. There is no code path that inpaints or otherwise edits the pixels of an existing raster. The node map encodes, per pixel, the index of the semantic node that owns it (``0`` = background / no node) as a little-endian ``uint32`` packed into the RGBA channels — a standard, lossless PNG. Anti-alias boundaries are resolved by an alpha-aware ownership mask (the node with the highest drawn alpha wins; ties break to the lower node index), produced in the same draw pass as the RGBA. """ from __future__ import annotations import hashlib from collections.abc import Callable, Sequence from dataclasses import dataclass, field from typing import Any, Literal, Protocol import matplotlib matplotlib.use("Agg") # fixed, headless, deterministic backend from ..hashing import sha256_bytes from ..ingest.base import IngestError from ..sources.base import World from ..sources.world_ops import hidden_nodes # A draw command: ``node_id`` owns every pixel the callable paints onto ``ax`` # (``None`` for a content-independent patch — e.g. a REDACT_SOLID cover — which # owns no node). The callable must be deterministic and depend only on the world # layout, never on wall-clock state. DrawCommand = tuple[str | None, Callable[[Any], None]] RendererKind = Literal["plot", "geometry", "table", "clevr"] #: Node-map pixel value for background / unowned pixels (also a real index is #: offset by 1, so node 0 in the table is never ambiguous with background). _BACKGROUND = 0 class RenderError(IngestError): """A world cannot be rendered (unsupported kind/predicate, infeasible layout). Raised rather than emitting a partial or faked render — P6 never silently coerces an unrenderable world into assets. """ @dataclass(frozen=True) class RendererFamily: """One train/held-out rendering family (``docs/02`` §9.3). Train and held-out families are **disjoint**: different font file, different palette, different layout parameters, so an asset rendered under one family cannot leak into a pipeline bound to the other (gate: "train/held-out assets disjoint"). The font SHA-256 is recorded in every manifest for replay. """ name: str kind: RendererKind font_name: str # matplotlib font family name (resolved to a pinned TTF) palette: dict[str, str] # named colors, disjoint across families layout: dict[str, Any] = field(default_factory=dict) @dataclass(frozen=True) class GlyphRecord: """One text glyph cluster linked to the semantic node it labels (§9 gate).""" node_id: str text: str x0: float y0: float x1: float y1: float font_sha256: str @dataclass(frozen=True) class RenderedAssets: """The four byte-addressed assets one ``render`` call produces.""" rgba_png: bytes node_map_png: bytes render_manifest: dict[str, Any] text_manifest: dict[str, Any] @property def rgba_sha256(self) -> str: return sha256_bytes(self.rgba_png) @property def node_map_sha256(self) -> str: return sha256_bytes(self.node_map_png) class Renderer(Protocol): """One deterministic renderer for one world kind (``docs/02`` §9.1).""" name: str version: str kind: RendererKind def render( self, world: World, *, renderer_id: str, seed: int, width: int, height: int, family: RendererFamily | None = ..., ) -> RenderedAssets: """Render ``world`` to four byte-addressed assets; never edits a raster. ``family`` overrides the renderer's default train family (used to render under a held-out family — §9.3); ``None``/default keeps the train family. """ ... # --- common pipeline: commands + glyphs → RGBA + node map ------------------- @dataclass(frozen=True) class _Layout: """The deterministic draw plan a kind-specific renderer produces. ``owner_ids`` is every non-background owner the canvas may paint — semantic world nodes **plus** synthetic display nodes (axes/ticks) — so the node map fully segments the image. ``visible_node_ids`` is the semantic subset (world nodes that are not hidden) the manifest reports and the coverage gate checks. """ commands: tuple[DrawCommand, ...] glyphs: tuple[GlyphRecord, ...] owner_ids: tuple[str, ...] visible_node_ids: tuple[str, ...] family: RendererFamily def rasterize( layout: _Layout, *, width: int, height: int, seed: int, ) -> tuple[bytes, bytes, dict[str, int]]: """Turn a layout into ``(rgba_png, node_map_png, node_pixel_counts)``. The RGBA canvas runs every command; the node map runs each owner's commands alone into an alpha mask, then takes the alpha-aware argmax (highest alpha wins; ties to the lower node index) so anti-alias boundaries have one owner. Returns the per-owner pixel count; the manifest filters coverage to the semantic ``visible_node_ids`` subset. """ import io import matplotlib.pyplot as plt import numpy as np from PIL import Image dpi = 100 fig_w, fig_h = width / dpi, height / dpi def _new_fig() -> tuple[Any, Any]: fig = plt.figure(figsize=(fig_w, fig_h), dpi=dpi) ax = fig.add_axes((0.0, 0.0, 1.0, 1.0)) ax.set_xlim(0.0, 1.0) ax.set_ylim(0.0, 1.0) ax.set_axis_off() return fig, ax # --- RGBA canvas: every command, in order --- fig, ax = _new_fig() _paint_background(ax, layout.family) for _nid, draw in layout.commands: draw(ax) rgba_buf = io.BytesIO() fig.savefig(rgba_buf, format="png", dpi=dpi) plt.close(fig) rgba_png = rgba_buf.getvalue() # --- node map: per-owner alpha masks → alpha-aware ownership --- # Ownership is measured by *paint coverage* (the alpha channel), not # luminance: a black text label on a black ground is still opaque paint and # must own its pixels. So each mask is rendered on a *transparent* canvas # (no background rect) and we read the alpha channel; only the node's own # drawn artists produce non-zero alpha. This keeps black-label nodes (a plot # series, a geometry entity label) covered, not just colored markers. owner_ids = layout.owner_ids masks: list[np.ndarray] = [] for nid in owner_ids: fig, ax = _new_fig() fig.patch.set_alpha(0.0) # transparent figure; nothing else is painted for cmd_nid, draw in layout.commands: if cmd_nid == nid: draw(ax) buf = io.BytesIO() fig.savefig(buf, format="png", dpi=dpi, transparent=True) plt.close(fig) rgba = np.asarray(Image.open(buf).convert("RGBA"), dtype=np.float32) masks.append(rgba[..., 3]) # alpha channel = this node's painted coverage counts: dict[str, int] = {} if masks: stack = np.stack(masks, axis=0) # (N, H, W) top_alpha = stack.max(axis=0) owners = np.argmax(stack, axis=0) # ties → lowest index (np.argmax rule) owned = top_alpha > _MASK_ALPHA # any non-zero alpha on an owner mask claims it idx = np.where(owned, owners.astype(" None: # The RGBA canvas gets the family background. (Per-node masks render on a # transparent figure instead — see :func:`rasterize` — so nothing is painted # here for the mask pass.) color = family.palette.get("background", "#FFFFFF") ax.add_patch(_mpl_patch_rect(0.0, 0.0, 1.0, 1.0, facecolor=color, edgecolor="none", zorder=-10)) def _mpl_patch_rect(x: float, y: float, w: float, h: float, **kw: Any) -> Any: from matplotlib.patches import Rectangle return Rectangle((x, y), w, h, **kw) def paint_text(text: str, x: float, y: float, font_name: str, *, size: int = 11) -> Any: """A draw callable painting ``text`` at ``(x, y)`` in the pinned ``font_name``. Used so a label-bearing semantic node (a plot series, a geometry entity) owns the pixels of its label text — giving it node-map coverage (§9.4 step 5: "glyph를 그리며 각 draw call에 semantic node ID를 붙인다") in addition to its :class:`GlyphRecord` entry in the text manifest. """ def draw(ax: Any) -> None: ax.text( x, y, text, fontfamily=font_name, fontsize=size, color="#000000", va="bottom", ha="left", clip_on=False, ) return draw def glyph_command(glyph: GlyphRecord, font_name: str) -> DrawCommand: """The owned draw command that paints a glyph's label text (for node coverage).""" return (glyph.node_id, paint_text(glyph.text, glyph.x0, glyph.y0, font_name)) def _encode_uint32_png(idx: Any) -> bytes: """Pack a ``uint32`` index array into an RGBA PNG (little-endian per pixel).""" import io import numpy as np from PIL import Image idx = np.asarray(idx, dtype="> 8) & 0xFF).astype("uint8") rgba[..., 2] = ((idx >> 16) & 0xFF).astype("uint8") rgba[..., 3] = ((idx >> 24) & 0xFF).astype("uint8") buf = io.BytesIO() Image.fromarray(rgba, mode="RGBA").save(buf, format="png") return buf.getvalue() def decode_uint32_png(png: bytes) -> Any: """Inverse of :func:`_encode_uint32_png` — read the node-index array back.""" import io import numpy as np from PIL import Image rgba = np.asarray(Image.open(io.BytesIO(png)).convert("RGBA"), dtype="uint8") return ( rgba[..., 0].astype(" str: """SHA-256 of the pinned TTF matplotlib resolves ``font_name`` to.""" from matplotlib.font_manager import findfont path = findfont(font_name, fallback_to_default=False) with open(path, "rb") as fh: return hashlib.sha256(fh.read()).hexdigest() def build_render_manifest( *, renderer_id: str, renderer_name: str, renderer_version: str, family: RendererFamily, world: World, seed: int, width: int, height: int, rgba_png: bytes, node_map_png: bytes, visible_node_ids: Sequence[str], owner_ids: Sequence[str], node_pixel_counts: dict[str, int], glyph_count: int, backend: str = "matplotlib_agg", backend_version: str | None = None, ) -> dict[str, Any]: """The deterministic ``render_manifest.json`` content (no time fields).""" hidden = sorted(hidden_nodes(world)) import matplotlib if backend_version is None: backend_version = matplotlib.__version__ coverage = {nid: node_pixel_counts.get(nid, 0) for nid in sorted(visible_node_ids)} return { "renderer_id": renderer_id, "renderer_name": renderer_name, "renderer_version": renderer_version, "backend": backend, "backend_version": backend_version, "font_name": family.font_name, "font_sha256": font_sha256(family.font_name), "locale": "C", "seed": seed, "width": width, "height": height, "world_sha256": _world_sha(world), "rgba_sha256": sha256_bytes(rgba_png), "node_map_sha256": sha256_bytes(node_map_png), "node_table": ["__background__", *owner_ids], "visible_node_ids": sorted(visible_node_ids), "hidden_node_ids": hidden, "node_map_coverage": coverage, "text_glyph_count": glyph_count, } def build_text_manifest(glyphs: Sequence[GlyphRecord], *, world: World) -> dict[str, Any]: """The ``text_manifest.json`` content — every glyph linked to a node.""" return { "world_sha256": _world_sha(world), "glyphs": [ { "node_id": g.node_id, "text": g.text, "bbox": [g.x0, g.y0, g.x1, g.y1], "font_sha256": g.font_sha256, } for g in sorted(glyphs, key=lambda x: (x.node_id, x.text, x.x0, x.y0)) ], } def assert_replay_identical(renderer: Renderer, world: World, **kwargs: Any) -> None: """Gate helper: render twice in-process and assert byte-identical assets.""" a = renderer.render(world, **kwargs) b = renderer.render(world, **kwargs) assert a.rgba_png == b.rgba_png, "rgba.png not byte-identical on replay" assert a.node_map_png == b.node_map_png, "node_map not byte-identical on replay" assert a.render_manifest == b.render_manifest, "render_manifest differs on replay" assert a.text_manifest == b.text_manifest, "text_manifest differs on replay" def assert_node_coverage(assets: RenderedAssets) -> None: """Gate helper: every visible semantic node has verified node-map pixels.""" import numpy as np manifest = assets.render_manifest node_table = manifest["node_table"] visible = manifest["visible_node_ids"] hidden = set(manifest["hidden_node_ids"]) coverage = manifest["node_map_coverage"] if len(node_table) != len(set(node_table)): raise RenderError("node table contains duplicate ids") leaked = hidden.intersection(node_table) if leaked: raise RenderError(f"hidden nodes appear in the node table: {sorted(leaked)}") owners = decode_uint32_png(assets.node_map_png) expected_shape = (manifest["height"], manifest["width"]) if owners.shape != expected_shape: raise RenderError( f"node-map dimensions differ from manifest: {owners.shape!r} != {expected_shape!r}" ) if owners.size and int(owners.max()) >= len(node_table): raise RenderError("node map references an index absent from the node table") missing: list[str] = [] for node_id in visible: if node_id not in node_table: missing.append(node_id) continue actual = int(np.count_nonzero(owners == node_table.index(node_id))) if coverage.get(node_id) != actual: raise RenderError( f"node-map coverage for {node_id!r} differs from pixels: " f"{coverage.get(node_id)!r} != {actual}" ) if actual <= 0: missing.append(node_id) if missing: raise RenderError(f"visible nodes without node-map coverage: {missing}") def assert_glyphs_linked(assets: RenderedAssets) -> None: """Gate helper: every glyph is linked, family-font-matched, and in-canvas.""" node_table = set(assets.render_manifest["node_table"][1:]) expected_font = assets.render_manifest["font_sha256"] glyphs = assets.text_manifest["glyphs"] if len(glyphs) != assets.render_manifest["text_glyph_count"]: raise RenderError( "text glyph count differs from render manifest: " f"{len(glyphs)} != {assets.render_manifest['text_glyph_count']}" ) for g in glyphs: node_id = g.get("node_id") if not node_id: raise RenderError(f"glyph without a node link: {g!r}") if node_id not in node_table: raise RenderError(f"glyph links to a node absent from the node table: {g!r}") if g.get("font_sha256") != expected_font: raise RenderError( f"glyph font hash differs from render family font: " f"{g.get('font_sha256')!r} != {expected_font!r}" ) bbox = g.get("bbox") if ( not isinstance(bbox, list) or len(bbox) != 4 or not all(isinstance(value, (int, float)) for value in bbox) ): raise RenderError(f"glyph has an invalid bbox: {g!r}") x0, y0, x1, y1 = bbox if not (0.0 <= x0 <= x1 <= 1.0 and 0.0 <= y0 <= y1 <= 1.0): raise RenderError(f"glyph is outside the canvas: {g!r}") def validate_rendered_assets(assets: RenderedAssets) -> None: """Apply the mandatory structural gates before any renderer returns assets.""" manifest = assets.render_manifest if manifest["rgba_sha256"] != assets.rgba_sha256: raise RenderError("rgba hash differs from render manifest") if manifest["node_map_sha256"] != assets.node_map_sha256: raise RenderError("node-map hash differs from render manifest") assert_node_coverage(assets) assert_glyphs_linked(assets) def _world_sha(world: World) -> str: from ..sources.world_ops import world_sha256 return world_sha256(world)