"""Find handwritten signatures on page images. Free to use, no warranty. Brasspage, Nov 2026.

Usage: python signature.py page.jpg [more.jpg ...] > signatures.csv
Needs: pip install torch transformers timm pillow
Output rows: file, x0, y0, x1, y1 (pixels of the input image), score (0 to 1).
For a PDF, make page images first, for example: pdftoppm -r 200 -png form.pdf page

How it works: the model (tech4humans/conditional-detr-50-signature-detector, Apache-2.0) squashes any
image to 640 x 640, so a signature on a full page gets very small. This script cuts the page into 6
overlapping tiles, runs the model on each tile, puts the boxes back on the page and drops the copies
found twice where tiles overlap. A handwritten date or name can come back as a signature too.
"""

import csv
import sys

from PIL import Image
from transformers import pipeline

MODEL = "tech4humans/conditional-detr-50-signature-detector"
REVISION = "9582471a229a9cbbe721e56dcd4e95e1fef7cb8b"
MIN_SCORE = 0.5  # the pipeline's default


def tiles(w, h):
    """2 across and 3 down, each 0.6 of the page width."""
    s = int(0.6 * w)
    ys = [0, (h - s) // 2, h - s] if h > s else [0]
    return [(x, y, s) for y in ys for x in (0, w - s)]


def merge(boxes):
    """Best score first. Drop a box that covers 70% of a kept box, or 70% of it is covered."""
    kept = []
    for b in sorted(boxes, key=lambda b: -b[4]):
        for k in kept:
            w = min(b[2], k[2]) - max(b[0], k[0])
            h = min(b[3], k[3]) - max(b[1], k[1])
            small = min((b[2] - b[0]) * (b[3] - b[1]), (k[2] - k[0]) * (k[3] - k[1]))
            if w > 0 and h > 0 and w * h >= 0.7 * small:
                break
        else:
            kept.append(b)
    return kept


def find(detect, im):
    boxes = []
    for x, y, s in tiles(*im.size):
        for d in detect(im.crop((x, y, x + s, y + s)), threshold=MIN_SCORE):
            b = d["box"]
            boxes.append(
                [
                    b["xmin"] + x,
                    b["ymin"] + y,
                    b["xmax"] + x,
                    b["ymax"] + y,
                    round(d["score"], 4),
                ]
            )
    return merge(boxes)


def main():
    detect = pipeline("object-detection", model=MODEL, revision=REVISION, device="cpu")
    out = csv.writer(sys.stdout)
    out.writerow(["file", "x0", "y0", "x1", "y1", "score"])
    for path in sys.argv[1:]:
        for b in find(detect, Image.open(path).convert("RGB")):
            out.writerow([path, *b])


if __name__ == "__main__":
    main()
