sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw
History Blame Contribute Delete
13.6 kB
"""Fresh deterministic symbolic renderer for ``clevr_world_v1`` scenes.
This is deliberately a structured renderer, not an image editor. It projects
the official scene coordinates onto a clean canvas and draws simple
attribute-complete object glyphs: fill encodes color, geometry encodes shape,
extent encodes size, and outline/highlight encodes material. A hidden object
is replaced by a fixed position-only patch, so completion worlds that differ in
that object's hidden attributes render byte-identically.
"""
from __future__ import annotations
import io
from collections.abc import Mapping, Sequence
from typing import Any
from ..sources.base import World
from ..sources.world_ops import hidden_nodes
from .base import (
RenderedAssets,
RendererFamily,
RendererKind,
RenderError,
_encode_uint32_png,
build_render_manifest,
build_text_manifest,
validate_rendered_assets,
)
_NAME = "clevr_renderer"
_VERSION = "1"
_KIND: RendererKind = "clevr"
_MIN_WIDTH = 240
_MIN_HEIGHT = 160
_TRAIN_FAMILY = RendererFamily(
name="clevr_train_v1",
kind=_KIND,
font_name="DejaVu Sans",
palette={
"background": "#E9EEF5",
"ground": "#CCD5E1",
"outline": "#202733",
"metal": "#F8FAFC",
"redact": "#111827",
"gray": "#777F8C",
"red": "#D64545",
"blue": "#3F6FD8",
"green": "#39A66A",
"brown": "#93643D",
"purple": "#8654B5",
"cyan": "#32AFC4",
"yellow": "#D9B62E",
},
layout={"source_width": 480, "source_height": 320, "horizon": 0.78},
)
_HELDOUT_FAMILY = RendererFamily(
name="clevr_heldout_v1",
kind=_KIND,
font_name="DejaVu Serif",
palette={
"background": "#FFF8EA",
"ground": "#E8D8BC",
"outline": "#3B2F2F",
"metal": "#FFFDF7",
"redact": "#291F1A",
"gray": "#626B73",
"red": "#B52F57",
"blue": "#225E9F",
"green": "#1F8860",
"brown": "#7B4E35",
"purple": "#714099",
"cyan": "#18899A",
"yellow": "#C69516",
},
layout={"source_width": 480, "source_height": 320, "horizon": 0.74},
)
CLEVR_FAMILIES: dict[str, RendererFamily] = {
_TRAIN_FAMILY.name: _TRAIN_FAMILY,
_HELDOUT_FAMILY.name: _HELDOUT_FAMILY,
}
class _Canvas:
def __init__(self, width: int, height: int, family: RendererFamily) -> None:
import numpy as np
from PIL import Image, ImageDraw
self.width = width
self.height = height
self.family = family
self.image = Image.new("RGBA", (width, height), family.palette["background"])
self.owners = Image.new("I", (width, height), 0)
self.draw = ImageDraw.Draw(self.image)
self.owner_draw = ImageDraw.Draw(self.owners)
self.owner_ids: list[str] = []
self.owner_index: dict[str, int] = {}
self._np = np
def reserve(self, node_id: str) -> None:
self._owner(node_id)
def _owner(self, node_id: str) -> int:
value = self.owner_index.get(node_id)
if value is None:
self.owner_ids.append(node_id)
value = len(self.owner_ids)
self.owner_index[node_id] = value
return value
def polygon(
self,
node_id: str,
points: Sequence[tuple[float, float]],
*,
fill: str,
outline: str,
width: int,
) -> None:
owner = self._owner(node_id)
self.draw.polygon(points, fill=fill, outline=outline)
if width > 1:
self.draw.line([*points, points[0]], fill=outline, width=width, joint="curve")
self.owner_draw.polygon(points, fill=owner)
def ellipse(
self,
node_id: str,
box: tuple[float, float, float, float],
*,
fill: str,
outline: str,
width: int,
) -> None:
owner = self._owner(node_id)
self.draw.ellipse(box, fill=fill, outline=outline, width=width)
self.owner_draw.ellipse(box, fill=owner)
def rectangle(
self,
node_id: str,
box: tuple[float, float, float, float],
*,
fill: str,
outline: str,
width: int,
) -> None:
owner = self._owner(node_id)
self.draw.rounded_rectangle(
box,
radius=max(2, int((box[2] - box[0]) * 0.12)),
fill=fill,
outline=outline,
width=width,
)
self.owner_draw.rounded_rectangle(
box,
radius=max(2, int((box[2] - box[0]) * 0.12)),
fill=owner,
)
def highlight(
self,
node_id: str,
points: Sequence[tuple[float, float]],
*,
fill: str,
width: int,
) -> None:
owner = self._owner(node_id)
self.draw.line(points, fill=fill, width=width)
self.owner_draw.line(points, fill=owner, width=max(1, width))
def redact(self, x: float, y: float) -> None:
radius = max(11, int(min(self.width, self.height) * 0.055))
box = (x - radius, y - radius, x + radius, y + radius)
self.draw.rounded_rectangle(
box,
radius=max(3, radius // 4),
fill=self.family.palette["redact"],
)
self.draw.line(
(x - radius * 0.6, y, x + radius * 0.6, y),
fill="#FFFFFF",
width=max(2, radius // 7),
)
# Redaction pixels intentionally belong to background, never the hidden node.
self.owner_draw.rounded_rectangle(box, radius=max(3, radius // 4), fill=0)
def finish(self) -> tuple[bytes, bytes, dict[str, int]]:
owner_array = self._np.asarray(self.owners, dtype="<u4")
rgba = io.BytesIO()
self.image.save(rgba, format="PNG", compress_level=9, optimize=False)
counts = {
node_id: int(self._np.count_nonzero(owner_array == index))
for node_id, index in self.owner_index.items()
}
return rgba.getvalue(), _encode_uint32_png(owner_array), counts
class ClevrRenderer:
"""Render normalized CLEVR scene objects with semantic ownership."""
name = _NAME
version = _VERSION
kind = _KIND
def render(
self,
world: World,
*,
renderer_id: str,
seed: int,
width: int,
height: int,
family: RendererFamily | None = None,
) -> RenderedAssets:
if world.get("world_schema") != "clevr_world_v1":
raise RenderError(
f"CLEVR renderer expects clevr_world_v1, got {world.get('world_schema')!r}"
)
family = family or _TRAIN_FAMILY
if family.kind != self.kind:
raise RenderError(
f"renderer family {family.name!r} has kind {family.kind!r}, expected {self.kind!r}"
)
if renderer_id != family.name:
raise RenderError(f"renderer_id {renderer_id!r} does not match family {family.name!r}")
if width < _MIN_WIDTH or height < _MIN_HEIGHT:
raise RenderError(
f"CLEVR canvas must be at least {_MIN_WIDTH}x{_MIN_HEIGHT}, got {width}x{height}"
)
objects = _objects(world)
hidden = hidden_nodes(world)
canvas = _Canvas(width, height, family)
horizon = int(height * float(family.layout.get("horizon", 0.78)))
canvas.draw.rectangle(
(0, horizon, width, height),
fill=family.palette["ground"],
)
visible = tuple(sorted(str(obj["id"]) for obj in objects if obj["id"] not in hidden))
for node_id in visible:
canvas.reserve(node_id)
for obj in sorted(objects, key=_draw_order, reverse=True):
x, y = _position(obj, width, height, family)
node_id = str(obj["id"])
if node_id in hidden:
canvas.redact(x, y)
else:
_draw_object(canvas, obj, x=x, y=y, family=family)
rgba_png, node_map_png, counts = canvas.finish()
manifest = build_render_manifest(
renderer_id=renderer_id,
renderer_name=self.name,
renderer_version=self.version,
family=family,
world=world,
seed=seed,
width=width,
height=height,
rgba_png=rgba_png,
node_map_png=node_map_png,
visible_node_ids=visible,
owner_ids=canvas.owner_ids,
node_pixel_counts=counts,
glyph_count=0,
backend="pillow",
backend_version=_pillow_version(),
)
manifest["scene_object_count"] = len(objects)
assets = RenderedAssets(
rgba_png=rgba_png,
node_map_png=node_map_png,
render_manifest=manifest,
text_manifest=build_text_manifest((), world=world),
)
validate_rendered_assets(assets)
return assets
def _objects(world: World) -> tuple[Mapping[str, Any], ...]:
raw = world.get("objects")
if not isinstance(raw, list):
raise RenderError("CLEVR world objects is not an array")
output: list[Mapping[str, Any]] = []
seen: set[str] = set()
for obj in raw:
if not isinstance(obj, Mapping) or not obj.get("id"):
raise RenderError("CLEVR object is missing an id")
node_id = str(obj["id"])
if node_id in seen:
raise RenderError(f"duplicate CLEVR object id {node_id!r}")
seen.add(node_id)
output.append(obj)
return tuple(output)
def _draw_order(obj: Mapping[str, Any]) -> tuple[float, str]:
coords = obj.get("pixel_coords")
depth = (
float(coords[2])
if isinstance(coords, list) and len(coords) >= 3 and isinstance(coords[2], (int, float))
else 0.0
)
return depth, str(obj.get("id", ""))
def _position(
obj: Mapping[str, Any],
width: int,
height: int,
family: RendererFamily,
) -> tuple[float, float]:
coords = obj.get("pixel_coords")
if (
isinstance(coords, list)
and len(coords) >= 2
and all(isinstance(value, (int, float)) for value in coords[:2])
):
source_width = float(family.layout.get("source_width", 480))
source_height = float(family.layout.get("source_height", 320))
x = float(coords[0]) / source_width * width
y = float(coords[1]) / source_height * height
else:
coords = obj.get("3d_coords")
if (
not isinstance(coords, list)
or len(coords) < 2
or not all(isinstance(value, (int, float)) for value in coords[:2])
):
raise RenderError(f"CLEVR object {obj.get('id')!r} has no usable coordinates")
x = (float(coords[0]) + 3.0) / 6.0 * width
y = (3.0 - float(coords[1])) / 6.0 * height
margin = max(14, int(min(width, height) * 0.06))
return (
min(width - margin, max(margin, x)),
min(height - margin, max(margin, y)),
)
def _draw_object(
canvas: _Canvas,
obj: Mapping[str, Any],
*,
x: float,
y: float,
family: RendererFamily,
) -> None:
node_id = str(obj["id"])
color = obj.get("color")
shape = obj.get("shape")
size = obj.get("size")
material = obj.get("material")
if not isinstance(color, str) or color not in family.palette:
raise RenderError(f"CLEVR object {node_id!r} has invalid color {color!r}")
if shape not in {"cube", "sphere", "cylinder"}:
raise RenderError(f"CLEVR object {node_id!r} has invalid shape {shape!r}")
if size not in {"small", "large"}:
raise RenderError(f"CLEVR object {node_id!r} has invalid size {size!r}")
if material not in {"rubber", "metal"}:
raise RenderError(f"CLEVR object {node_id!r} has invalid material {material!r}")
radius = max(10, int(min(canvas.width, canvas.height) * (0.052 if size == "small" else 0.078)))
fill = family.palette[color]
outline = family.palette["metal"] if material == "metal" else family.palette["outline"]
width = max(2, radius // 7) if material == "metal" else max(1, radius // 11)
if shape == "sphere":
canvas.ellipse(
node_id,
(x - radius, y - radius, x + radius, y + radius),
fill=fill,
outline=outline,
width=width,
)
elif shape == "cube":
skew = radius * 0.38
points = (
(x - radius, y - radius + skew),
(x - skew, y - radius),
(x + radius, y - radius + skew),
(x + radius - skew, y + radius),
(x - radius, y + radius - skew),
)
canvas.polygon(node_id, points, fill=fill, outline=outline, width=width)
else:
canvas.rectangle(
node_id,
(x - radius * 0.82, y - radius, x + radius * 0.82, y + radius),
fill=fill,
outline=outline,
width=width,
)
canvas.ellipse(
node_id,
(x - radius * 0.82, y - radius, x + radius * 0.82, y - radius * 0.45),
fill=fill,
outline=outline,
width=width,
)
if material == "metal":
canvas.highlight(
node_id,
((x - radius * 0.45, y - radius * 0.45), (x + radius * 0.15, y - radius * 0.12)),
fill=family.palette["metal"],
width=max(2, radius // 6),
)
def _pillow_version() -> str:
import PIL
return PIL.__version__
__all__ = ["CLEVR_FAMILIES", "ClevrRenderer"]