| """Deterministic source-raster renderer for GQA scene-graph interventions. |
| |
| GQA is the real-image slice of EVI-PO. Its source photographs cannot be |
| faithfully regenerated from the released scene graph, so the certified |
| operation is deliberately narrow: normalize the released image once, then |
| replace exactly one source-annotated object box with an opaque constant patch. |
| The paired node map is generated only from released object boxes; it is an |
| annotation projection, not an inferred segmentation. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import io |
| from collections.abc import Iterable, Mapping |
| from dataclasses import dataclass |
| from typing import Any |
|
|
| from PIL import Image, ImageDraw |
|
|
| from ..hashing import canonical_json_hash, sha256_bytes |
| from ..sources.base import World |
| from ..sources.world_ops import world_sha256 |
| from .base import RenderError, _encode_uint32_png |
|
|
| GQA_RENDERER_NAME = "gqa_source_bbox_renderer" |
| GQA_RENDERER_VERSION = "1" |
| GQA_RENDERER_ID = "gqa_source_bbox_v1" |
| GQA_JPEG_QUALITY = 88 |
| _MASK_RGB = (127, 127, 127) |
|
|
|
|
| @dataclass(frozen=True) |
| class GQARenderedObservation: |
| """One content-addressed GQA observation and its annotation projection.""" |
|
|
| image_jpeg: bytes |
| node_map_png: bytes |
| render_manifest: dict[str, Any] |
| text_manifest: dict[str, Any] |
|
|
| @property |
| def image_sha256(self) -> str: |
| return sha256_bytes(self.image_jpeg) |
|
|
| @property |
| def node_map_sha256(self) -> str: |
| return sha256_bytes(self.node_map_png) |
|
|
|
|
| def normalize_gqa_source_image(source_image: bytes, *, width: int, height: int) -> bytes: |
| """Decode a released source image and freeze deterministic JPEG bytes.""" |
|
|
| try: |
| with Image.open(io.BytesIO(source_image)) as opened: |
| image = opened.convert("RGB") |
| except (OSError, ValueError) as exc: |
| raise RenderError(f"cannot decode GQA source image: {exc}") from exc |
| if image.size != (width, height): |
| raise RenderError( |
| f"GQA source image dimensions {image.size!r} != scene graph {(width, height)!r}" |
| ) |
| return _jpeg_bytes(image) |
|
|
|
|
| def render_gqa_observation( |
| normalized_source_jpeg: bytes, |
| world: World, |
| *, |
| masked_node_id: str | None, |
| seed: int, |
| ) -> GQARenderedObservation: |
| """Render FULL or one opaque source-bbox mask with a deterministic node map.""" |
|
|
| if world.get("world_schema") != "gqa_scene_graph_v1": |
| raise RenderError("GQA renderer requires gqa_scene_graph_v1") |
| width, height = _dimensions(world) |
| objects = _objects(world) |
| try: |
| with Image.open(io.BytesIO(normalized_source_jpeg)) as opened: |
| image = opened.convert("RGB") |
| except (OSError, ValueError) as exc: |
| raise RenderError(f"cannot decode normalized GQA image: {exc}") from exc |
| if image.size != (width, height): |
| raise RenderError("normalized GQA image dimensions drifted") |
| if masked_node_id is not None: |
| try: |
| bbox = _bbox(objects[masked_node_id]) |
| except KeyError as exc: |
| raise RenderError(f"GQA mask target {masked_node_id!r} is absent") from exc |
| ImageDraw.Draw(image).rectangle( |
| (bbox[0], bbox[1], bbox[2] - 1, bbox[3] - 1), |
| fill=_MASK_RGB, |
| ) |
| image_jpeg = _jpeg_bytes(image) |
| else: |
| |
| image_jpeg = bytes(normalized_source_jpeg) |
|
|
| node_ids = sorted(objects) |
| node_table = ["__background__", *node_ids] |
| import numpy as np |
|
|
| owners = np.zeros((height, width), dtype="<u4") |
| coverage: dict[str, int] = {} |
| for index, node_id in enumerate(node_ids, 1): |
| if node_id == masked_node_id: |
| coverage[node_id] = 0 |
| continue |
| x0, y0, x1, y1 = _bbox(objects[node_id]) |
| owners[y0:y1, x0:x1] = index |
| for index, node_id in enumerate(node_ids, 1): |
| coverage[node_id] = int(np.count_nonzero(owners == index)) |
| node_map = _encode_uint32_png(owners) |
| visible = [node_id for node_id in node_ids if node_id != masked_node_id] |
| hidden = [masked_node_id] if masked_node_id is not None else [] |
| manifest = { |
| "renderer_id": GQA_RENDERER_ID, |
| "renderer_name": GQA_RENDERER_NAME, |
| "renderer_version": GQA_RENDERER_VERSION, |
| "backend": "pillow_source_bbox", |
| "backend_version": _pillow_version(), |
| "format": "JPEG", |
| "jpeg_quality": GQA_JPEG_QUALITY, |
| "locale": "C", |
| "seed": seed, |
| "width": width, |
| "height": height, |
| "world_sha256": world_sha256(world), |
| "normalized_source_sha256": sha256_bytes(normalized_source_jpeg), |
| "rgba_sha256": sha256_bytes(image_jpeg), |
| "node_map_sha256": sha256_bytes(node_map), |
| "node_table": node_table, |
| "visible_node_ids": visible, |
| "hidden_node_ids": hidden, |
| "node_map_coverage": coverage, |
| "masked_node_id": masked_node_id, |
| "mask_rgb": list(_MASK_RGB), |
| "fresh_structured_render": False, |
| "source_annotation_projection": "gqa_v1_2_object_bbox", |
| } |
| return GQARenderedObservation( |
| image_jpeg=image_jpeg, |
| node_map_png=node_map, |
| render_manifest=manifest, |
| text_manifest={ |
| "world_sha256": world_sha256(world), |
| "glyphs": [], |
| "source": "source_raster_no_synthetic_text", |
| }, |
| ) |
|
|
|
|
| def gqa_evidence_mask_png(world: World, dependency_node_ids: Iterable[str]) -> bytes: |
| """Project executor dependency object IDs to their released bounding boxes.""" |
|
|
| width, height = _dimensions(world) |
| objects = _objects(world) |
| image = Image.new("L", (width, height), 0) |
| draw = ImageDraw.Draw(image) |
| used = 0 |
| for node_id in sorted({str(value) for value in dependency_node_ids}): |
| obj = objects.get(node_id) |
| if obj is None: |
| continue |
| x0, y0, x1, y1 = _bbox(obj) |
| draw.rectangle((x0, y0, x1 - 1, y1 - 1), fill=255) |
| used += 1 |
| if used == 0: |
| raise RenderError("GQA evidence mask has no source object boxes") |
| output = io.BytesIO() |
| image.save(output, format="PNG", optimize=False, compress_level=9) |
| return output.getvalue() |
|
|
|
|
| def raster_diff_mask_png(full_image: bytes, changed_image: bytes) -> bytes: |
| """Return a lossless binary mask of actual decoded-pixel differences.""" |
|
|
| import numpy as np |
|
|
| try: |
| with Image.open(io.BytesIO(full_image)) as before: |
| left = np.asarray(before.convert("RGB")) |
| with Image.open(io.BytesIO(changed_image)) as after: |
| right = np.asarray(after.convert("RGB")) |
| except (OSError, ValueError) as exc: |
| raise RenderError(f"cannot decode images for diff mask: {exc}") from exc |
| if left.shape != right.shape: |
| raise RenderError("GQA diff images have different shapes") |
| mask = np.any(left != right, axis=2).astype("uint8") * 255 |
| output = io.BytesIO() |
| Image.fromarray(mask, mode="L").save( |
| output, |
| format="PNG", |
| optimize=False, |
| compress_level=9, |
| ) |
| return output.getvalue() |
|
|
|
|
| def gqa_region_bbox(world: World, node_id: str) -> tuple[int, int, int, int]: |
| """Expose one validated source-annotation box for group metadata.""" |
|
|
| objects = _objects(world) |
| try: |
| return _bbox(objects[node_id]) |
| except KeyError as exc: |
| raise RenderError(f"GQA region target {node_id!r} is absent") from exc |
|
|
|
|
| def gqa_render_contract_sha256() -> str: |
| """Stable implementation-level identity recorded in release manifests.""" |
|
|
| return canonical_json_hash( |
| { |
| "renderer": GQA_RENDERER_NAME, |
| "version": GQA_RENDERER_VERSION, |
| "format": "JPEG", |
| "jpeg_quality": GQA_JPEG_QUALITY, |
| "mask_rgb": list(_MASK_RGB), |
| "node_map": "source_bbox_owner_projection_v1", |
| } |
| ) |
|
|
|
|
| def _dimensions(world: Mapping[str, Any]) -> tuple[int, int]: |
| width, height = world.get("width"), world.get("height") |
| if ( |
| isinstance(width, bool) |
| or isinstance(height, bool) |
| or not isinstance(width, int) |
| or not isinstance(height, int) |
| or width <= 0 |
| or height <= 0 |
| ): |
| raise RenderError("GQA world dimensions are invalid") |
| return width, height |
|
|
|
|
| def _objects(world: Mapping[str, Any]) -> dict[str, Mapping[str, Any]]: |
| raw = world.get("objects") |
| if not isinstance(raw, Mapping) or not raw: |
| raise RenderError("GQA world objects must be a non-empty mapping") |
| objects: dict[str, Mapping[str, Any]] = {} |
| for raw_id, value in raw.items(): |
| if not isinstance(value, Mapping): |
| raise RenderError(f"GQA object {raw_id!r} is malformed") |
| objects[str(raw_id)] = value |
| return objects |
|
|
|
|
| def _bbox(obj: Mapping[str, Any]) -> tuple[int, int, int, int]: |
| try: |
| x, y, width, height = (int(obj[key]) for key in ("x", "y", "w", "h")) |
| except (KeyError, TypeError, ValueError) as exc: |
| raise RenderError("GQA object bbox is malformed") from exc |
| if x < 0 or y < 0 or width <= 0 or height <= 0: |
| raise RenderError("GQA object bbox has invalid extent") |
| return x, y, x + width, y + height |
|
|
|
|
| def _jpeg_bytes(image: Image.Image) -> bytes: |
| output = io.BytesIO() |
| image.save( |
| output, |
| format="JPEG", |
| quality=GQA_JPEG_QUALITY, |
| subsampling=2, |
| optimize=False, |
| progressive=False, |
| ) |
| return output.getvalue() |
|
|
|
|
| def _pillow_version() -> str: |
| import PIL |
|
|
| return PIL.__version__ |
|
|
|
|
| __all__ = [ |
| "GQA_JPEG_QUALITY", |
| "GQA_RENDERER_ID", |
| "GQA_RENDERER_NAME", |
| "GQA_RENDERER_VERSION", |
| "GQARenderedObservation", |
| "gqa_evidence_mask_png", |
| "gqa_region_bbox", |
| "gqa_render_contract_sha256", |
| "normalize_gqa_source_image", |
| "raster_diff_mask_png", |
| "render_gqa_observation", |
| ] |
|
|