"""Find check boxes on a form image and say if each one is ticked. OpenCV only. Free to use, no warranty.
Brasspage, Nov 2026.

Usage: python checkbox.py form.jpg [more.jpg ...] > boxes.csv
Needs: pip install opencv-python-headless numpy
Output rows: file, x0, y0, x1, y1 (pixels of the input image), checked (1 or 0), ink (0 to 1).

How it works: a phone photo is first flattened to the page (the largest 4-corner shape). Long straight
lines are kept, so pen strokes that cross a box do not hide it. Small closed squares about the size of a
form box are boxes. A box counts as checked when enough ink sits inside it.
"""

import csv
import sys

import cv2
import numpy as np

PAGE_W = 1700  # work at about 200 dpi for a letter page
BOX = (14, 40)  # box side in pixels at PAGE_W: 8 pt boxes are about 22
INK = 0.11  # share of dark pixels inside the box that means checked
FULL = 0.4  # a closed square with no hole needs this much ink inside to count as a box


def flatten(gray):
    """Warp a photo to the page. Returns page image and the 3x3 matrix back to the input pixels."""
    h, w = gray.shape
    b = max(h, w) // 50
    edge = np.concatenate(
        [gray[:b].ravel(), gray[-b:].ravel(), gray[:, :b].ravel(), gray[:, -b:].ravel()]
    )
    quad = None
    s = 1000 / max(h, w)
    small = cv2.GaussianBlur(cv2.resize(gray, None, fx=s, fy=s), (5, 5), 0)
    edges = cv2.dilate(cv2.Canny(small, 30, 90), np.ones((3, 3), np.uint8))
    cs, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # Paper to the edge means a scan: then a big frame printed on the form is not the page.
    for c in (
        sorted(cs, key=cv2.contourArea, reverse=True)[:5]
        if np.median(edge) < 0.8 * np.median(gray)
        else []
    ):
        a = cv2.approxPolyDP(cv2.convexHull(c), 0.02 * cv2.arcLength(c, True), True)
        _, _, bw, _ = cv2.boundingRect(a)
        if (
            len(a) == 4
            and cv2.contourArea(a) > 0.3 * small.size
            and bw < 0.98 * small.shape[1]
        ):
            quad = a.reshape(4, 2).astype(np.float32) / s
            break
    if quad is None:  # the page is the image
        k = PAGE_W / w
        return cv2.resize(
            gray, (PAGE_W, int(h * k)), interpolation=cv2.INTER_AREA
        ), np.diag([1 / k, 1 / k, 1.0])
    sm, df = quad.sum(1), quad[:, 1] - quad[:, 0]
    src = np.float32(
        [quad[sm.argmin()], quad[df.argmin()], quad[sm.argmax()], quad[df.argmax()]]
    )
    ph = int(PAGE_W * np.linalg.norm(src[3] - src[0]) / np.linalg.norm(src[1] - src[0]))
    dst = np.float32([[0, 0], [PAGE_W, 0], [PAGE_W, ph], [0, ph]])
    M = cv2.getPerspectiveTransform(src, dst)
    return cv2.warpPerspective(
        gray, M, (PAGE_W, ph), flags=cv2.INTER_AREA
    ), np.linalg.inv(M)


def boxes(page):
    """Boxes on the flat page: [(x0, y0, x1, y1, ink)]."""
    ink = cv2.adaptiveThreshold(
        page, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 31, 12
    )
    k = 17  # a line must run this far; most pen strokes and letter parts do not
    lines = cv2.morphologyEx(
        ink, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (k, 1))
    )
    lines |= cv2.morphologyEx(
        ink, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (1, k))
    )
    cs, tree = cv2.findContours(lines, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    found = []
    for c, (_, _, _, parent) in zip(cs, tree[0] if cs else []):
        x, y, w, h = cv2.boundingRect(c)
        if not (BOX[0] <= w <= BOX[1] and BOX[0] <= h <= BOX[1] and 0.8 < w / h < 1.25):
            continue
        # A hole (the white inside of a drawn square) must be square: a round hole (O, D, 0) is a letter.
        # An outline with no hole counts only if it is square and full of ink: a box scribbled over.
        if cv2.contourArea(c) < 0.85 * w * h:
            continue
        if parent != -1:
            x, y, w, h = (
                max(0, x - 2),
                max(0, y - 2),
                w + 4,
                h + 4,
            )  # the hole plus the printed border
        # A box has all 4 sides drawn: check each edge strip of the line mask.
        t = max(2, w // 8)
        sides = [
            lines[y : y + t, x : x + w],
            lines[y + h - t : y + h, x : x + w],
            lines[y : y + h, x : x + t],
            lines[y : y + h, x + w - t : x + w],
        ]
        if (
            min((s.max(axis=0 if i < 2 else 1) > 0).mean() for i, s in enumerate(sides))
            < 0.8
        ):
            continue
        m = max(3, w // 5)  # stay off the printed border
        share = float((ink[y + m : y + h - m, x + m : x + w - m] > 0).mean())
        if parent == -1 and share < FULL:
            continue
        found.append([x, y, x + w, y + h, share])
    found.sort(key=lambda b: -(b[2] - b[0]))
    keep = []  # the inner and outer edge of one box are one box
    for b in found:
        if all(
            min(b[2], k[2]) - max(b[0], k[0]) < 0.5 * (b[2] - b[0])
            or min(b[3], k[3]) - max(b[1], k[1]) < 0.5 * (b[3] - b[1])
            for k in keep
        ):
            keep.append(b)
    return keep


def read(path):
    gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    if gray is None:
        raise ValueError(f"{path}: not an image I can read")
    page, back = flatten(gray)
    out = []
    for x0, y0, x1, y1, ink in boxes(page):
        p = cv2.perspectiveTransform(np.float32([[[x0, y0]], [[x1, y1]]]), back)[:, 0]
        out.append(
            [
                *np.round(p.min(0)).astype(int),
                *np.round(p.max(0)).astype(int),
                int(ink >= INK),
                round(ink, 3),
            ]
        )
    return out


if __name__ == "__main__":
    w = csv.writer(sys.stdout)
    w.writerow(["file", "x0", "y0", "x1", "y1", "checked", "ink"])
    for f in sys.argv[1:]:
        for row in read(f):
            w.writerow([f, *row])
