"""Zonal OCR, free: read named boxes (zones) of a blank form from a filled scan or phone photo.

    python zonal.py blank.pdf PAGE scan.jpg [zones.json] [--align sift|orb|none] [--read drop|crop|page]

Zones are the PDF's own text fields, or zones.json: {"name": [x0, y0, x1, y1], ...} in PDF points from the
top left of the page. The script lines the scan up with the blank page (SIFT features and a homography),
erases the blank form's own print (drop-out), skips zones with no ink, and reads each other zone with
Tesseract. Prints JSON: {zone name: text}.
Needs: pip install opencv-python-headless numpy pypdf; tesseract and pdftoppm (brew install tesseract poppler).
Brasspage, Nov 2026: https://brasspage.com/zonal-ocr/
"""

import argparse
import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path

import cv2
import numpy as np
from pypdf import PdfReader

DPI = 200  # the blank page is drawn at this size; zones are cut from the scan lined up to it
PAD = 0  # pixels added around each zone before it is read
MININK = 20  # a box with fewer dark pixels than this is empty
GROW = 1  # pixels the blank form's ink is grown by before it is erased (slack for the line-up)
ENV = {**os.environ, "OMP_THREAD_LIMIT": "1"}


def inherited(chain, key):
    """A field value from the widget or its nearest parent that has it."""
    return next((c[key] for c in chain if key in c), None)


def zones(pdf, pno):
    """Text fields of the page: name, rect in points from the top left, MaxLen, comb and multiline flags."""
    page = PdfReader(pdf).pages[pno - 1]
    H = float(page.mediabox[3])
    out = []
    for ref in page.get("/Annots") or []:
        a = ref.get_object()
        if a.get("/Subtype") != "/Widget":
            continue
        chain, o = [], a
        while o is not None:
            chain.append(o)
            o = o["/Parent"].get_object() if "/Parent" in o else None
        if inherited(chain, "/FT") != "/Tx":
            continue
        name = ".".join(str(c["/T"]) for c in reversed(chain) if "/T" in c)
        x0, y0, x1, y1 = [float(v) for v in a["/Rect"]]
        ff = int(inherited(chain, "/Ff") or 0)
        out.append(
            {
                "name": name,
                "rect": [x0, H - y1, x1, H - y0],
                "maxlen": int(inherited(chain, "/MaxLen") or 0),
                "comb": bool(ff & 1 << 24),
                "multi": bool(ff & 1 << 12),
            }
        )
    return out


def render(pdf, pno):
    """The blank page in gray at DPI."""
    with tempfile.TemporaryDirectory() as td:
        subprocess.run(
            ["pdftoppm", "-r", str(DPI), "-f", str(pno), "-l", str(pno), "-gray"]
            + ["-png", "-singlefile", str(pdf), f"{td}/o"],
            check=True,
        )
        return cv2.imread(f"{td}/o.png", cv2.IMREAD_GRAYSCALE)


def align(img, tpl, how="sift"):
    """Warp the scan onto the blank page. Returns (aligned image, inlier count or None)."""
    h, w = tpl.shape
    if how == "none":
        return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA), None
    s = max(tpl.shape) / max(img.shape)  # find features at the blank page's size
    small = (
        cv2.resize(img, None, fx=s, fy=s, interpolation=cv2.INTER_AREA)
        if s < 1
        else img
    )
    s = min(s, 1.0)
    if how == "orb":  # the common tutorial: ORB, best 20% of matches
        det = cv2.ORB_create(5000)
        ka, da = det.detectAndCompute(small, None)
        kb, db = det.detectAndCompute(tpl, None)
        m = sorted(
            cv2.BFMatcher(cv2.NORM_HAMMING).match(da, db), key=lambda x: x.distance
        )
        m = m[: max(4, len(m) // 5)]
    else:  # SIFT with Lowe's ratio test
        det = cv2.SIFT_create(5000)
        ka, da = det.detectAndCompute(small, None)
        kb, db = det.detectAndCompute(tpl, None)
        pairs = cv2.BFMatcher(cv2.NORM_L2).knnMatch(da, db, k=2)
        m = [
            p[0] for p in pairs if len(p) == 2 and p[0].distance < 0.75 * p[1].distance
        ]
    if len(m) < 4:
        return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA), 0
    pa = np.float32([ka[x.queryIdx].pt for x in m])
    pb = np.float32([kb[x.trainIdx].pt for x in m])
    Hm, mask = cv2.findHomography(pa, pb, cv2.RANSAC, 5.0)
    if Hm is None:
        return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA), 0
    Hm = Hm @ np.diag([s, s, 1.0])  # from full-size scan pixels
    out = cv2.warpPerspective(img, Hm, (w, h), flags=cv2.INTER_LINEAR, borderValue=255)
    return out, int(mask.sum())


def dropout(page, tpl, grow=GROW):
    """Erase the blank form's own ink (lines, labels, dots) from the lined-up scan; the typed fill stays.
    Returns (page, ink): ink marks pixels darker than their surroundings that are not the form's."""
    k = np.ones((2 * grow + 1, 2 * grow + 1), np.uint8)
    form = cv2.dilate((tpl < 160).astype(np.uint8), k) > 0
    out = page.copy()
    out[form] = 255
    ink = (
        cv2.adaptiveThreshold(
            page, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 15
        )
        == 0
    )
    return out, ink & ~form


def px(rect):
    """Zone rect in points to pixel box on the aligned page."""
    k = DPI / 72
    x0, y0, x1, y1 = rect
    return (
        int(x0 * k) - PAD,
        int(y0 * k) - PAD,
        int(np.ceil(x1 * k)) + PAD,
        int(np.ceil(y1 * k)) + PAD,
    )


def clean(t):
    return " ".join(t.split()).strip("|_[]{} ")


def read_crops(page, rects, psm=7, ink=None):
    """Cut out each zone and read them all in one Tesseract run (a list file). One string per zone.
    A zone with under MININK ink pixels (from dropout, else pixels under 128) is empty and is not read."""
    out = [""] * len(rects)
    with tempfile.TemporaryDirectory() as td:
        paths, idx = [], []
        for i, r in enumerate(rects):
            x0, y0, x1, y1 = px(r)
            x0, y0 = max(x0, 0), max(y0, 0)
            crop = page[y0:y1, x0:x1]
            dark = ink[y0:y1, x0:x1] if ink is not None else crop < 128
            if dark.sum() < MININK:  # Tesseract reads a blank box as junk, so skip it
                continue
            p = f"{td}/{i:04d}.png"
            cv2.imwrite(p, crop)
            paths.append(p)
            idx.append(i)
        if not paths:
            return out
        Path(f"{td}/list.txt").write_text("\n".join(paths) + "\n")
        res = subprocess.run(
            ["tesseract", f"{td}/list.txt", "stdout", "--psm", str(psm), "-l", "eng"],
            capture_output=True,
            text=True,
            check=True,
            env=ENV,
        )
    parts = res.stdout.split("\f")
    if len(parts) != len(paths):
        raise RuntimeError(f"tesseract gave {len(parts)} parts for {len(paths)} zones")
    for i, p in zip(idx, parts):
        out[i] = clean(p)
    return out


def read_page(page, rects):
    """Read the whole aligned page once, then give each word to the zone that holds its centre."""
    with tempfile.TemporaryDirectory() as td:
        cv2.imwrite(f"{td}/p.png", page)
        tsv = subprocess.run(
            ["tesseract", f"{td}/p.png", "stdout", "-l", "eng", "tsv"],
            capture_output=True,
            text=True,
            check=True,
            env=ENV,
        ).stdout
    words = [[] for _ in rects]
    boxes = [px(r) for r in rects]
    for row in tsv.splitlines()[1:]:
        c = row.split("\t")
        if len(c) < 12 or c[0] != "5" or not c[11].strip():
            continue
        x, y, w, h = map(int, c[6:10])
        cx, cy = x + w / 2, y + h / 2
        for i, (x0, y0, x1, y1) in enumerate(boxes):
            if x0 <= cx < x1 and y0 <= cy < y1:
                words[i].append(c[11])
                break
    return [clean(" ".join(w)) for w in words]


def main():
    ap = argparse.ArgumentParser(
        description="Zonal OCR: read named boxes of a form from a scan or photo."
    )
    ap.add_argument("pdf", help="the blank form PDF")
    ap.add_argument("page", type=int, help="page number, from 1")
    ap.add_argument("scan", help="the filled scan or photo (JPEG, PNG or TIFF)")
    ap.add_argument(
        "zones",
        nargs="?",
        help="zones.json; leave out to use the PDF's own text fields",
    )
    ap.add_argument("--align", choices=["sift", "orb", "none"], default="sift")
    ap.add_argument("--read", choices=["drop", "crop", "page"], default="drop")
    ap.add_argument(
        "--save", help="also save the lined-up page here (PNG), to check the line-up"
    )
    a = ap.parse_args()
    if a.zones:
        zs = [
            {"name": k, "rect": v, "multi": False}
            for k, v in json.loads(Path(a.zones).read_text()).items()
        ]
    else:
        zs = zones(a.pdf, a.page)
    tpl = render(a.pdf, a.page)
    img = cv2.imread(a.scan, cv2.IMREAD_GRAYSCALE)
    if img is None:
        sys.exit(f"can not read {a.scan}")
    page, inliers = align(img, tpl, a.align)
    if inliers is not None and inliers < 20:
        print(
            f"warning: only {inliers} matching points; check that the scan is this form page",
            file=sys.stderr,
        )
    if a.save:
        cv2.imwrite(a.save, page)
    if a.read == "page":
        out = dict(
            zip([z["name"] for z in zs], read_page(page, [z["rect"] for z in zs]))
        )
    else:
        ink = None
        if a.read == "drop":
            page, ink = dropout(page, tpl)
        out = {}
        for multi, psm in (
            (False, 7),
            (True, 6),
        ):  # one line, or a multiline field as a block
            part = [z for z in zs if z["multi"] == multi]
            out.update(
                zip(
                    [z["name"] for z in part],
                    read_crops(page, [z["rect"] for z in part], psm, ink),
                )
            )
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
