"""Read bubble sheets with OpenCV. Free to use, no warranty. Brasspage, Nov 2026.

Usage: python omr.py layout.json sheet1.jpg [sheet2.jpg ...] > answers.csv
Needs: pip install opencv-python-headless numpy

The sheet needs 4 bullseye marks near its corners (rings around a dot).
layout.json gives the page size and the 4 mark centres (top-left, top-right, bottom-left, bottom-right) in
pixels of your blank sheet, the bubble radius, and the centre of every bubble:
{"page": [2480, 3508], "markers": [[160, 160], [2320, 160], [160, 3348], [2320, 3348]], "radius": 28,
 "fields": {"q1": {"A": [380, 1440], "B": [470, 1440], "C": [560, 1440], "D": [650, 1440]}, ...}}
Each answer cell is the marked value, "" for no mark, or several values (like "AC") for a double mark.
"""

import csv
import json
import sys

import cv2
import numpy as np

# A bubble counts if it is this dark, or if it is the darkest in its field by this much.
MARK, GAP = 0.30, 0.09


def find_marks(gray):
    """Centres of the 4 bullseyes: shapes with 4 or more nested outlines (ring, ring, dot)."""
    b = cv2.adaptiveThreshold(
        cv2.GaussianBlur(gray, (5, 5), 0),
        255,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY_INV,
        51,
        10,
    )
    cs, hier = cv2.findContours(b, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    found = []
    for i, c in enumerate(cs):
        depth, k = 0, hier[0][i][2]
        while k != -1:
            depth, k = depth + 1, hier[0][k][2]
        x, y, w, h = cv2.boundingRect(c)
        if depth >= 4 and 0.6 < w / h < 1.6 and w < gray.shape[1] / 8:  # not the page
            found.append((x + w / 2, y + h / 2, w * h))
    if len(found) < 4:
        raise ValueError(f"found {len(found)} corner marks, need 4")
    big = max(a for _, _, a in found)
    p = np.array([(x, y) for x, y, a in found if a > 0.3 * big], np.float32)
    s, d = p.sum(1), p[:, 1] - p[:, 0]
    return np.float32(
        [p[s.argmin()], p[d.argmin()], p[d.argmax()], p[s.argmax()]]
    )  # TL, TR, BL, BR


def fills(path, lay):
    """How dark each bubble is next to the paper just around it: 0 = clean paper, 1 = black."""
    gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    if gray is None:
        raise ValueError("not an image I can read")
    M = cv2.getPerspectiveTransform(find_marks(gray), np.float32(lay["markers"]))
    page = cv2.warpPerspective(gray, M, tuple(lay["page"]), borderValue=255).astype(
        np.float32
    )
    r = lay["radius"]
    yy, xx = np.mgrid[-2 * r : 2 * r + 1, -2 * r : 2 * r + 1]
    dist = np.hypot(xx, yy)
    inner, ring = dist < 0.75 * r, (dist > r + 6) & (dist < r + 16)
    out = {}
    for field, opts in lay["fields"].items():
        out[field] = {}
        for value, (cx, cy) in opts.items():
            cell = page[cy - 2 * r : cy + 2 * r + 1, cx - 2 * r : cx + 2 * r + 1]
            paper = np.percentile(cell[ring], 75)
            out[field][value] = float(max(0.0, 1 - cell[inner].mean() / max(paper, 1)))
    return out


def answer(f, mark=MARK, gap=GAP):
    vals = sorted(f, key=f.get, reverse=True)
    rest = np.median(list(f.values()))
    picked = [v for v in vals if f[v] >= mark]
    if not picked and f[vals[0]] - rest >= gap:
        picked = [vals[0]]
    return "".join(sorted(picked))


def main():
    with open(sys.argv[1]) as f:
        lay = json.load(f)
    w = csv.writer(sys.stdout)
    w.writerow(["file"] + list(lay["fields"]))
    for path in sys.argv[2:]:
        try:
            f = fills(path, lay)
            w.writerow([path] + [answer(f[k]) for k in lay["fields"]])
        except ValueError as e:
            print(f"{path}: {e}", file=sys.stderr)


if __name__ == "__main__":
    main()
