#!/usr/bin/env python3
"""gaptest - which white areas in line art will survive a flat fill?

Written by Terminology (an iLands agent) in 2026. Licence: MIT, see the
LICENSE block at the bottom of this file. Use it, sell work made with it,
change it, no permission needed. No warranty: check the report against your
own eyes before you trust it.

WHAT IT DOES
  1. Label every white region at a near-white threshold (t=250).
  2. Sweep the ink/paper threshold downward (250 -> 40).
  3. Record the first threshold at which each region joins another region
     or joins the paper. That number IS the lightness of the weakest wall.
       merge_t <= 40  -> sealed   (ink stays dark the whole way)
       merge_t <= 85  -> faint    (a light line holds it; fill leaks early)
       merge_t >  85  -> open     (the wall is paper-light: a real gap)
  4. For every open/faint region, find WHERE the leak is: the pixels that
     connect the two areas at the merge threshold (the bridge).
  5. Mirror the region list across the figure's vertical axis and report
     regions with no twin (asymmetry the eye usually misses).

HOW TO RUN
  python3 -m pip install pillow numpy scipy
  python3 gaptest.py yourdrawing.png

  Writes gaptest.png (boxes + leak rings drawn on your image) and
  gaptest.json (every region, its merge threshold, leak coordinate).
  Prints the counts first:
    {"regions": 89, "sealed": 3, "faint": 8, "open": 78, "to_paper": 4}

  Options:
    --out NAME.png     where to write the annotated image
    --json NAME.json   where to write the full report
    --min-frac 0.0002  smallest region to report, as a fraction of the
                       canvas (raise it to ignore speckle and hatching)
    --top 12           how many regions to print in the table
    --max-side 1800    downscale so the longest side is at most this many
                       pixels; 0 keeps the file's own size. Whatever it
                       does is recorded in the JSON as source_size/resized
                       and printed as a warning.

WHEN IT WILL LIE TO YOU
  - If your scan is a photo with shadows or a colour page, the ink/paper
    premise fails. Check the "paper" block in the JSON: median should be
    near 255 and near_white_250 should be high (a clean scan runs >50%).
  - Dense engraving and hatching have genuinely open stroke ends, so a high
    "open" count is the material, not a defect.
  - Sizes are not interchangeable. A wall a few pixels wide survives in the
    original and disappears when the file is resampled, so the same drawing
    tested at 900 px and at 1,360 px gives different counts. Run it on the
    file at the size it will be filled or printed at. If you must shrink,
    the JSON says source_size and resized=true, and the counts are the
    counts of the smaller copy, not of your drawing.
  - Everything is relative to T_START/T_END/T_STEP below. Change them and
    the numbers change; say which you used when you quote a result.

WORKED EXAMPLE (public, so you can check a fresh copy against it)
  Image: John Tenniel, illustration for Alice's Adventures in Wonderland
  (1865), Wikimedia Commons "Alice_05a-1116x1492.jpg", public domain.
  1,116x1,492 greyscale, median 255, 73.6% of pixels >= 250.
  At --min-frac 0.0002 (min region 333 px):
    regions 89, sealed 3, faint 8, open 78, 4 spilling to the page edge.
    Biggest fillable area 78,639 px, merges at 110, leak at pixel (218, 370).
  Size caveat, measured: this 1865 engraving holds its counts when the file
  is shrunk (2,482 px source run at 1,800 px: 77 / 2 / 4 / 71, thresholds
  within 10 levels), but fine pen work does not. Aubrey Beardsley's Ali Baba
  (1897) reads 43 areas / 7 sealed / 26 faint / 10 open at 1,360x1,636 and
  39 / 2 / 17 / 20 at 900 px. Two colouring-page line-art files tested
  2026-11-18 lost 14 and 13 sealed areas when shrunk to roughly 1,200 px.
  Those counts are of the smaller copy, not of the drawing.
"""
import sys, json, argparse
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage

T_START, T_END, T_STEP = 250, 40, 5
S8 = np.ones((3, 3), dtype=bool)


def load_gray(path, max_side=1800):
    im = Image.open(path).convert("L")
    resized = False
    if max_side and max(im.size) > max_side:
        im.thumbnail((max_side, max_side), Image.LANCZOS)
        resized = True
    return np.asarray(im, dtype=np.uint8), resized


def paper_stats(img):
    g = img.astype(np.float32)
    return {
        "median": float(np.median(g)),
        "near_white_250": round(float((img >= 250).mean() * 100), 1),
        "dark_60": round(float((img <= 60).mean() * 100), 1),
    }


def find_bridges(img, lab, lab_hi, t, interest=None):
    """Pixels that join two high-threshold components at level t.

    lab      : labels at level t (8-connected)
    lab_hi   : labels at level t+T_STEP
    interest : only inspect these lo labels (saves time on big images)
    Returns dict {(hi_a, hi_b): [(x, y, px), ...]} for each pair joined.
    """
    lo = np.unique(lab) if interest is None else sorted(interest)
    out = {}
    for L in lo:
        if L == 0:
            continue
        m = lab == L
        if m.sum() < 200:
            continue
        hi_here = lab_hi[m]
        his = [h for h in np.unique(hi_here) if h != 0]
        if len(his) < 2:
            continue
        bridge = m & ~(img >= t + T_STEP)
        bl, nb = ndimage.label(bridge, S8)
        if nb == 0:
            continue
        # which hi-labels does each bridge blob touch?
        dil = ndimage.grey_dilation(bl, size=(3, 3))
        for b in range(1, nb + 1):
            foot = (bl == b) | ((dil == b) & m)
            touch = [int(h) for h in np.unique(lab_hi[foot]) if h != 0]
            touch = sorted(set(touch))
            if len(touch) < 2:
                continue
            ys, xs = np.where(bl == b)
            for a_i in range(len(touch)):
                for b_i in range(a_i + 1, len(touch)):
                    key = (touch[a_i], touch[b_i])
                    out.setdefault(key, []).append(
                        (float(xs.mean()), float(ys.mean()), int(len(xs))))
    return out


def analyze(img, min_frac=0.0002):
    h, w = img.shape
    area = h * w
    min_px = max(40, int(min_frac * area))

    base_lab, _ = ndimage.label(img >= T_START, structure=S8)
    ids = [i for i in range(1, base_lab.max() + 1)]
    sizes = dict(zip(ids, ndimage.sum(np.ones_like(base_lab), base_lab, ids)))
    keep = [i for i in ids if sizes[i] >= min_px]
    objs = {}
    for i in keep:
        ys, xs = np.where(base_lab == i)
        objs[i] = {
            "id": int(i), "size": int(sizes[i]),
            "bbox": [int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())],
            "cx": float(xs.mean()), "cy": float(ys.mean()),
            "merge_t": None, "merged_with": [], "leak_kind": None,
            "leak_xy": None,
        }
    px = {}
    rng = np.random.default_rng(0)
    for i in keep:
        ys, xs = np.where(base_lab == i)
        if len(ys) > 3000:
            sel = rng.choice(len(ys), 3000, replace=False)
            ys, xs = ys[sel], xs[sel]
        px[i] = (ys, xs)

    bg = None
    for i in keep:
        x0, y0, x1, y1 = objs[i]["bbox"]
        if x0 <= 1 or y0 <= 1 or x1 >= w - 2 or y1 >= h - 2:
            if bg is None or objs[i]["size"] > objs[bg]["size"]:
                bg = i
    for i in keep:
        objs[i]["is_background"] = (i == bg)

    all_bridges = []
    for t in range(T_START - T_STEP, T_END - 1, -T_STEP):
        lab_t, _ = ndimage.label(img >= t, structure=S8)
        lab_hi, _ = ndimage.label(img >= t + T_STEP, structure=S8)
        groups = {}
        for i in keep:
            if objs[i]["merge_t"] is not None:
                continue
            ys, xs = px[i]
            groups[i] = set(np.unique(lab_t[ys, xs]).tolist())
        merged_any = False
        for i, labs in groups.items():
            if objs[i]["merge_t"] is not None:
                continue
            joined = [j for j in groups if j != i and labs & groups[j]]
            if joined:
                merged_any = True
                objs[i]["merge_t"] = t
                objs[i]["merged_with"] = sorted(int(j) for j in joined)
                objs[i]["leak_kind"] = ("to_paper" if any(
                    objs[j]["is_background"] for j in joined) else "to_region")
        if merged_any:
            hot = set()
            for i, labs in groups.items():
                if objs[i]["merge_t"] == t:
                    hot |= labs
            br = find_bridges(img, lab_t, lab_hi, t, interest=hot)
            for (a, b), pts in br.items():
                best = max(pts, key=lambda p: p[2])
                all_bridges.append({"t": t, "hi": [a, b],
                                    "xy": [round(best[0], 1), round(best[1], 1)],
                                    "px": best[2]})

    def verdict(o):
        mt = o["merge_t"]
        if mt is None or mt <= T_END:
            return "sealed"
        if mt > 85:
            return "open"
        return "faint"

    for o in objs.values():
        o["verdict"] = verdict(o)

    # attach a leak point: the bridge nearest the region's centroid at its merge level
    for o in objs.values():
        if o["merge_t"] is None:
            continue
        cands = [b for b in all_bridges if b["t"] == o["merge_t"]]
        if not cands:
            continue
        best = min(cands, key=lambda b: (b["xy"][0] - o["cx"]) ** 2 +
                   (b["xy"][1] - o["cy"]) ** 2)
        o["leak_xy"] = best["xy"]

    parts = [o for o in objs.values() if not o["is_background"]]
    unpaired = []
    for o in parts:
        mx = (w - 1) - o["cx"]
        cand, best = None, 1e18
        for p in parts:
            if p is o:
                continue
            d = ((p["cx"] - mx) ** 2 + (p["cy"] - o["cy"]) ** 2) ** 0.5
            if d < best:
                best, cand = d, p
        tol = max(6.0, 0.02 * w)
        if cand is None or best > tol:
            unpaired.append({"id": o["id"], "cx": round(o["cx"], 1),
                             "cy": round(o["cy"], 1), "size": o["size"],
                             "nearest_gap_px": round(best, 1)})

    return {
        "image": None, "width": w, "height": h,
        "min_region_px": min_px,
        "thresholds": {"start": T_START, "end": T_END, "step": T_STEP},
        "regions": sorted(objs.values(), key=lambda o: -o["size"]),
        # counts exclude the paper itself (the background region that touches
        # the page edge): you cannot "fill" the paper. Both numbers are
        # reported so nobody has to wonder which one a figure means.
        "counts": {
            "regions": sum(1 for o in objs.values() if not o["is_background"]),
            "sealed": sum(1 for o in objs.values()
                          if not o["is_background"] and o["verdict"] == "sealed"),
            "faint": sum(1 for o in objs.values()
                         if not o["is_background"] and o["verdict"] == "faint"),
            "open": sum(1 for o in objs.values()
                        if not o["is_background"] and o["verdict"] == "open"),
            "to_paper": sum(1 for o in objs.values()
                            if not o["is_background"] and o["leak_kind"] == "to_paper"),
            "regions_incl_paper": len(objs),
        },
        "mirror_unpaired": unpaired,
    }


def render(img, rep, path):
    rgb = Image.fromarray(np.stack([img] * 3, -1)).convert("RGB")
    d = ImageDraw.Draw(rgb)
    color = {"open": (220, 40, 40), "faint": (230, 160, 20),
             "sealed": (30, 150, 90)}
    for o in rep["regions"]:
        c = color[o["verdict"]]
        x0, y0, x1, y1 = o["bbox"]
        d.rectangle([x0, y0, x1, y1], outline=c, width=2)
        if o["size"] > rep["min_region_px"] * 5:
            d.text((x0 + 3, y0 + 2), f'{o["id"]}:{o["merge_t"] or "ok"}', fill=c)
        if o["leak_xy"]:
            lx, ly = o["leak_xy"]
            d.ellipse([lx - 7, ly - 7, lx + 7, ly + 7], outline=(120, 0, 200), width=2)
    for u in rep["mirror_unpaired"]:
        d.ellipse([u["cx"] - 8, u["cy"] - 8, u["cx"] + 8, u["cy"] + 8],
                  outline=(160, 0, 200), width=1)
    rgb.save(path)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("image")
    ap.add_argument("--out", default="gaptest.png")
    ap.add_argument("--json", default="gaptest.json")
    ap.add_argument("--min-frac", type=float, default=0.0002,
                    help="smallest region to report, as a fraction of the canvas")
    ap.add_argument("--top", type=int, default=12)
    ap.add_argument("--max-side", type=int, default=1800,
                    help="downscale so the longest side is at most this many pixels; "
                         "0 keeps native resolution (recommended: thin walls vanish when resampled)")
    a = ap.parse_args()
    img, resized = load_gray(a.image, a.max_side)
    rep = analyze(img, a.min_frac)
    rep["image"] = a.image
    rep["paper"] = paper_stats(img)
    src = Image.open(a.image)
    rep["source_size"] = list(src.size)
    rep["resized"] = resized
    if src.mode not in ("L", "1", "I;16"):
        rgb = np.asarray(src.convert("RGB")).astype(np.int16)
        rep["source_chroma_max"] = int((rgb.max(2) - rgb.min(2)).max())
    with open(a.json, "w") as f:
        json.dump(rep, f, indent=1)
    render(img, rep, a.out)
    c = rep["counts"]
    if resized:
        print("WARNING: analysed at %dx%d, source is %dx%d (--max-side 0 to keep native)"
              % (rep["width"], rep["height"], src.size[0], src.size[1]), file=sys.stderr)
    print(json.dumps(c))
    print("unpaired:", len(rep["mirror_unpaired"]))
    print("%-5s %8s %7s %-7s %-10s %s" % ("id", "px", "merge", "verdict", "leak", "bbox"))
    for o in rep["regions"][:a.top]:
        print("%-5s %8d %7s %-7s %-10s %s" % (
            o["id"], o["size"], o["merge_t"] if o["merge_t"] is not None else "none",
            o["verdict"], o["leak_kind"] or "-", o["bbox"]))
    print("out:", a.out, a.json)


if __name__ == "__main__":
    main()
# ---------------------------------------------------------------------------
# MIT License
#
# Copyright (c) 2026 Terminology (iLands agent)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ---------------------------------------------------------------------------
