File size: 4,444 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import numpy as np
from PIL import Image, ImageDraw, ImageFont

PALETTE = [(230, 25, 75), (60, 180, 75), (255, 225, 25), (0, 130, 200), (245, 130, 48), (145, 30, 180),
           (70, 240, 240), (240, 50, 230), (210, 245, 60), (250, 190, 212), (0, 128, 128), (220, 190, 255),
           (170, 110, 40), (255, 250, 200), (128, 0, 0), (170, 255, 195), (128, 128, 0), (255, 215, 180),
           (0, 0, 128), (128, 128, 128), (255, 105, 180), (0, 200, 120), (255, 140, 0), (120, 160, 255)]
LOCATOR_W, CTX_W, CTX_H, TILE_HEADER, TILE_GAP = 360, 620, 300, 56, 12
TILE_W = LOCATOR_W + TILE_GAP + CTX_W
CANDIDATES_PER_SHEET = 6


def page_candidates(kept: list[dict], per_page: int) -> list[list[dict]]:
    ordered = sorted(kept, key=lambda d: d["candidate_id"])
    return [ordered[i:i + per_page] for i in range(0, len(ordered), per_page)]


def _font(size: int):
    return ImageFont.load_default(size=size)


def outline(mask: np.ndarray) -> np.ndarray:
    padded = np.pad(mask, 1)
    inner = padded[1:-1, 1:-1] & padded[:-2, 1:-1] & padded[2:, 1:-1] & padded[1:-1, :-2] & padded[1:-1, 2:]
    return mask & ~inner


def _context_window(box, size):
    width, height = size
    x0, y0, x1, y1 = box
    bw, bh = max(1.0, x1 - x0), max(1.0, y1 - y0)
    cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
    w = max(bw * 1.6, width * 0.25, bw + 2 * width * 0.04)
    h = max(bh * 1.6, height * 0.15, bh + 2 * height * 0.04)
    ratio = CTX_W / CTX_H
    if w / h < ratio:
        w = h * ratio
    else:
        h = w / ratio
    w, h = min(w, width), min(h, height)
    cx0 = int(round(min(max(0, cx - w / 2), width - w)))
    cy0 = int(round(min(max(0, cy - h / 2), height - h)))
    return cx0, cy0, int(round(cx0 + w)), int(round(cy0 + h))


def render_candidate_tile(rgb: np.ndarray, mask: np.ndarray, decision: dict, colour) -> Image.Image:
    height, width = rgb.shape[:2]
    mask = mask.astype(bool)
    tile = Image.new("RGB", (TILE_W, TILE_HEADER + CTX_H), (18, 18, 18))
    draw = ImageDraw.Draw(tile)
    x0, y0, x1, y1 = [int(round(v)) for v in decision["box_xyxy_pixels"]]
    rows = np.flatnonzero(mask.any(axis=1))
    cx, cy = (x0 + x1) / 2 / width, (y0 + y1) / 2 / height
    touches_bottom = len(rows) > 0 and rows.max() >= height * 0.85
    draw.text((8, 4), f"#{decision['candidate_id']}", fill=colour, font=_font(24))
    draw.text((8, 32), f"proposed as: {decision['phrase']}  (score {decision['score']:.2f})   centre {cx*100:.0f}% from left, {cy*100:.0f}% from top   "
              f"reaches bottom edge: {'yes' if touches_bottom else 'no'}", fill=(200, 200, 200), font=_font(18))
    loc = rgb.astype(np.float32).copy()
    loc[mask] = loc[mask] * 0.4 + np.array(colour, np.float32) * 0.6
    loc_img = Image.fromarray(np.clip(loc, 0, 255).astype(np.uint8))
    scale = LOCATOR_W / width
    loc_img = loc_img.resize((LOCATOR_W, max(1, int(round(height * scale)))), Image.LANCZOS)
    ImageDraw.Draw(loc_img).rectangle((x0 * scale - 3, y0 * scale - 3, x1 * scale + 3, y1 * scale + 3), outline=colour, width=3)
    tile.paste(loc_img, (0, TILE_HEADER + (CTX_H - loc_img.height) // 2))
    cx0, cy0, cx1, cy1 = _context_window((x0, y0, x1, y1), (width, height))
    crop = rgb[cy0:cy1, cx0:cx1].astype(np.float32).copy()
    sub = mask[cy0:cy1, cx0:cx1]
    crop[sub] = crop[sub] * 0.75 + np.array(colour, np.float32) * 0.25
    crop[outline(sub)] = np.array(colour, np.float32)
    crop_img = Image.fromarray(np.clip(crop, 0, 255).astype(np.uint8))
    f = min(CTX_W / crop_img.width, CTX_H / crop_img.height)
    crop_img = crop_img.resize((max(1, int(crop_img.width * f)), max(1, int(crop_img.height * f))), Image.LANCZOS)
    tile.paste(crop_img, (LOCATOR_W + TILE_GAP + (CTX_W - crop_img.width) // 2, TILE_HEADER + (CTX_H - crop_img.height) // 2))
    return tile


def render_candidate_sheets(rgb: np.ndarray, masks: np.ndarray, page: list[dict], per_sheet: int = CANDIDATES_PER_SHEET) -> list[Image.Image]:
    sheets = []
    for start in range(0, len(page), per_sheet):
        chunk = page[start:start + per_sheet]
        sheet = Image.new("RGB", (TILE_W, len(chunk) * (TILE_HEADER + CTX_H)), (18, 18, 18))
        for k, decision in enumerate(chunk):
            colour = PALETTE[(start + k) % len(PALETTE)]
            sheet.paste(render_candidate_tile(rgb, masks[decision["index"]], decision, colour), (0, k * (TILE_HEADER + CTX_H)))
        sheets.append(sheet)
    return sheets