File size: 7,066 Bytes
fd5366a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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,
    }