File size: 9,885 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
"""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:
        # Avoid a second lossy generation for FULL and for replay input.
        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",
]