clsa-code / src /clsa /envs /render.py
fahadhafeezofficial's picture
Upload folder using huggingface_hub
fd5366a verified
Raw History Blame Contribute Delete
7.07 kB
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Deterministic screenshot rendering and a small, honest image featuriser.
The benchmark needs a real image modality. We render invoice, product and
settings screenshots with Pillow and recover their fields with template
matching on a fixed bitmap font. The featuriser is real code operating on
pixels; it is not told the answer. It is deliberately small, and this
limitation is recorded in LIMITATIONS.md.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
FIG_W, FIG_H = 240, 160
DIGITS = "0123456789"
# 5x7 bitmap font for digits, drawn as rectangles so matching is exact.
_FONT = {
"0": ["01110", "10001", "10011", "10101", "11001", "10001", "01110"],
"1": ["00100", "01100", "00100", "00100", "00100", "00100", "01110"],
"2": ["01110", "10001", "00001", "00010", "00100", "01000", "11111"],
"3": ["11110", "00001", "00001", "01110", "00001", "00001", "11110"],
"4": ["00010", "00110", "01010", "10010", "11111", "00010", "00010"],
"5": ["11111", "10000", "11110", "00001", "00001", "10001", "01110"],
"6": ["00110", "01000", "10000", "11110", "10001", "10001", "01110"],
"7": ["11111", "00001", "00010", "00100", "01000", "01000", "01000"],
"8": ["01110", "10001", "10001", "01110", "10001", "10001", "01110"],
"9": ["01110", "10001", "10001", "01111", "00001", "00010", "01100"],
}
_CELL = 4
_DIGIT_W = 5 * _CELL
_DIGIT_H = 7 * _CELL
def _draw_text(draw: ImageDraw.ImageDraw, xy, text: str, colour=(20, 20, 20)) -> None:
x0, y0 = xy
for i, ch in enumerate(text):
glyph = _FONT.get(ch)
if not glyph:
continue
ox = x0 + i * (_DIGIT_W + _CELL)
for r, row in enumerate(glyph):
for c, bit in enumerate(row):
if bit == "1":
draw.rectangle(
[
ox + c * _CELL,
y0 + r * _CELL,
ox + c * _CELL + _CELL - 1,
y0 + r * _CELL + _CELL - 1,
],
fill=colour,
)
def render_screenshot(kind: str, fields: dict, out_path: str | Path) -> str:
"""Render a deterministic screenshot for an evidence item.
kind: invoice | product | settings. The rendering is a pure function of
(kind, fields), so a forked replay can regenerate a byte-identical image.
"""
img = Image.new("RGB", (FIG_W, FIG_H), (247, 247, 250))
d = ImageDraw.Draw(img)
if kind == "invoice":
d.rectangle([0, 0, FIG_W, 26], fill=(32, 48, 84))
d.rectangle([10, 40, FIG_W - 10, 120], outline=(32, 48, 84), width=2)
if fields.get("paid", False):
d.rectangle([150, 96, 228, 118], fill=(190, 40, 40))
d.rectangle([16, 48, 100, 60], fill=(120, 120, 140))
elif kind == "product":
d.rectangle([0, 0, FIG_W, 26], fill=(20, 90, 70))
d.rectangle([10, 36, 110, 116], fill=(200, 210, 220))
d.rectangle([120, 40, 230, 52], fill=(90, 90, 110))
d.rectangle([120, 60, 200, 70], fill=(140, 140, 160))
elif kind == "settings":
d.rectangle([0, 0, FIG_W, 26], fill=(60, 60, 70))
for i in range(3):
y = 44 + i * 28
d.rectangle([14, y, 150, y + 10], fill=(150, 150, 165))
on = bool(fields.get("toggles", [True, True, True])[i])
d.ellipse([186, y - 4, 214, y + 14], fill=(40, 160, 90) if on else (170, 60, 60))
else: # pragma: no cover - defensive
raise ValueError(f"unknown screenshot kind: {kind}")
# Field lines: amounts and identifiers rendered in the bitmap font.
value = fields.get("amount")
if value is not None:
_draw_text(d, (130, 44), f"{int(round(float(value)))}")
ident = str(fields.get("id", ""))
digits = "".join(ch for ch in ident if ch in DIGITS)
if digits:
_draw_text(d, (16, 130), digits[:8])
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
img.save(out_path, format="PNG")
return str(out_path)
# --------------------------------------------------------------------------- #
# Featuriser: template matching over the rendered region
# --------------------------------------------------------------------------- #
def _binarise(arr: np.ndarray) -> np.ndarray:
return (arr.mean(axis=2) < 100).astype(np.float32)
def _match_digit(patch: np.ndarray) -> tuple[str, float]:
"""Best matching digit glyph and its normalised score."""
best, best_score = "?", -1.0
for ch in DIGITS:
glyph = np.zeros((_DIGIT_H, _DIGIT_W), dtype=np.float32)
for r, row in enumerate(_FONT[ch]):
for c, bit in enumerate(row):
if bit == "1":
glyph[
r * _CELL : (r + 1) * _CELL, c * _CELL : (c + 1) * _CELL
] = 1.0
denom = float(glyph.sum() + patch.sum() + 1e-6)
score = 2.0 * float((glyph * patch).sum()) / denom
if score > best_score:
best, best_score = ch, score
return best, best_score
def extract_image_features(path: str | Path) -> dict:
"""Recover the amount and layout flags from a rendered screenshot.
Returns a dict with the parsed integer amount (or None), per-region colour
means and layout flags. This is a real pixel-level computation.
"""
img = Image.open(path).convert("RGB")
arr = np.asarray(img).astype(np.float32) / 255.0
binar = _binarise((arr * 255).astype(np.uint8))
# The amount is rendered at x=130,y=44 in up to 3 glyph cells.
region = binar[44 : 44 + _DIGIT_H, 130 : 130 + 3 * (_DIGIT_W + _CELL)]
digits, scores = [], []
for i in range(3):
x0 = i * (_DIGIT_W + _CELL)
patch = region[:, x0 : x0 + _DIGIT_W]
if patch.sum() < 8:
continue
ch, sc = _match_digit(patch)
digits.append(ch)
scores.append(sc)
amount = None
if digits and "?" not in digits and min(scores) > 0.55:
try:
amount = int("".join(digits))
except ValueError:
amount = None
def region_mean(y0, y1, x0, x1):
return arr[y0:y1, x0:x1].reshape(-1, 3).mean(axis=0)
h, w, _ = arr.shape
# Per-toggle state read from the pixel colours of the three switch regions.
toggles: list[bool] = []
for i in range(3):
y = 44 + i * 28
patch = arr[y - 4 : y + 14, 186:214].reshape(-1, 3).mean(axis=0)
toggles.append(bool(patch[1] > patch[0]))
return {
"amount": amount,
"digit_confidence": float(np.mean(scores)) if scores else 0.0,
"header_rgb": region_mean(0, 20, 0, w).tolist(),
"body_rgb": region_mean(h // 2, h // 2 + 20, 0, w).tolist(),
"stamp_present": bool(binar[96:118, 150:228].mean() > 0.15),
"toggle_mean": float(binar[40:110, 180:220].mean()),
"toggle_states": toggles,
}