"""Measures each drawn visor: the largest dark region in the top half of the figure that cream surrounds, as fractions of the
figure's height; for the colleague, the dark field inside her two lenses together."""
from collections import deque
from PIL import Image
out = {}
for voice in ("butler", "coach", "colleague", "homie", "squire"):
    im = Image.open(f"toon-preview/rest/{voice}.png").convert("RGBA")
    W, H = im.size
    px = im.load()
    rows = [y for y in range(H) if any(px[x, y][3] > 40 for x in range(0, W, 2))]
    top, bottom = rows[0], rows[-1]
    fig = bottom - top
    dark = lambda x, y: px[x, y][3] > 200 and sum(px[x, y][:3]) < 110
    seen = set()
    blobs = []
    for y in range(top, top + fig // 2, 2):
        for x in range(0, W, 2):
            if (x, y) in seen or not dark(x, y): continue
            q, pts = deque([(x, y)]), []
            seen.add((x, y))
            while q:
                a, b = q.popleft()
                pts.append((a, b))
                for c, d in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
                    if 0 <= c < W and 0 <= d < H and (c, d) not in seen and dark(c, d):
                        seen.add((c, d)); q.append((c, d))
            xs, ys = [p[0] for p in pts], [p[1] for p in pts]
            box = (min(xs), min(ys), max(xs), max(ys))
            # Cream on both sides of the region's middle row marks it as set into the head.
            mid = (box[1] + box[3]) // 2
            def cream(xx): return 0 <= xx < W and px[xx, mid][3] > 200 and sum(px[xx, mid][:3]) > 600
            if voice == "colleague" and max(ys) > top + fig * 0.35: continue
            if len(pts) > 400 and (voice == "colleague" or (any(cream(box[0] - k) for k in range(2, 30)) and any(cream(box[2] + k) for k in range(2, 30)))):
                blobs.append((len(pts), box))
    blobs.sort(reverse=True)
    if voice == "colleague":
        pair = [b for _, b in blobs[:2]]
        box = (min(b[0] for b in pair), min(b[1] for b in pair), max(b[2] for b in pair), max(b[3] for b in pair))
    else:
        box = blobs[0][1]
    w, h = box[2] - box[0], box[3] - box[1]
    out[voice] = (round(w / fig, 3), round(h / fig, 3), round(w / h, 2), box, fig)
    print(f"{voice:9} visor {w}x{h} px, figure {fig} px: width {w / fig:.3f}, height {h / fig:.3f} of the figure, {w / h:.2f} wide to tall, at {box}")
