"""Find colored rubber stamps and round seals on a scanned page, and read their text. Free, from brasspage.com.

Usage: python stamp.py page.jpg [more.jpg ...]
Needs: pip install opencv-python-headless numpy, and Tesseract (brew install tesseract or apt install tesseract-ocr).
Prints one line per stamp: file, box (x0 y0 x1 y1), the text read. Finds colored ink only (red, blue, purple):
a black stamp or a gray scan needs a trained model. Blue signatures and colored form fields also show up.
"""

import subprocess
import sys

import cv2
import numpy as np


def ocr(img, psm):
    """Tesseract words and confidences for a black-on-white image."""
    png = cv2.imencode(".png", img)[1].tobytes()
    tsv = subprocess.run(["tesseract", "stdin", "stdout", "--psm", str(psm), "tsv"], input=png, capture_output=True, check=False)  # fmt: skip
    rows = [r.split("\t") for r in tsv.stdout.decode().splitlines()[1:]]
    words = [
        (r[11], float(r[10]))
        for r in rows
        if len(r) == 12 and r[11].strip() and float(r[10]) > 0
    ]
    good = [
        (w, c)
        for w, c in words
        if c >= 60 and len([ch for ch in w if ch.isalnum()]) >= 3
    ]
    return " ".join(w for w, _ in words), sum(c * len(w) for w, c in good)


def turn(img, angle):
    h, w = img.shape
    m = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)
    return cv2.warpAffine(img, m, (w, h), borderValue=0)


def read(ink):
    """ink: white stamp ink on black. Straight text at 13 angles, then the top arc of a seal unrolled."""
    # fill the speckle in worn ink
    ink = cv2.morphologyEx(ink, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
    pad = cv2.copyMakeBorder(ink, 40, 40, 40, 40, cv2.BORDER_CONSTANT, value=0)
    best = max(
        (ocr(255 - turn(pad, a), 6) for a in range(-24, 25, 4)), key=lambda t: t[1]
    )
    h, w = ink.shape
    rad = max(h, w) / 2
    polar = cv2.warpPolar(
        ink, (int(rad), 720), (w / 2, h / 2), rad, cv2.WARP_POLAR_LINEAR
    )
    # between the two rings, where the name runs
    band = polar[:, int(rad * 0.68) : int(rad * 0.94)]
    # angle runs left to right; 150 to 390 degrees is the top arc, read left to right
    ring = cv2.rotate(band, cv2.ROTATE_90_COUNTERCLOCKWISE)
    ring = np.hstack([ring, ring])[:, 300:780]
    arc = ocr(255 - cv2.resize(ring, None, fx=1.5, fy=1.5), 7)
    return arc if arc[1] > best[1] else best


def stamps(path):
    im = cv2.imread(path)
    h, w = im.shape[:2]
    ink = cv2.inRange(cv2.cvtColor(im, cv2.COLOR_BGR2HSV), (0, 70, 40), (180, 255, 235))
    k = max(3, w // 70)
    blobs = cv2.morphologyEx(
        ink, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (k, k))
    )
    n, _, st, _ = cv2.connectedComponentsWithStats(blobs)
    boxes = [[x, y, x + bw, y + bh] for x, y, bw, bh, _ in st[1:n] if min(bw, bh) > w / 40 and bw * bh < 0.15 * w * h]  # fmt: skip
    merged = True
    while merged:  # join pieces of one stamp: boxes that touch become one
        merged = False
        for a in boxes:
            for b in boxes:
                if (
                    a is not b
                    and a[0] <= b[2]
                    and b[0] <= a[2]
                    and a[1] <= b[3]
                    and b[1] <= a[3]
                ):
                    a[:] = [
                        min(a[0], b[0]),
                        min(a[1], b[1]),
                        max(a[2], b[2]),
                        max(a[3], b[3]),
                    ]
                    boxes.remove(b)
                    merged = True
                    break
            if merged:
                break
    for b in boxes:
        yield b, read(ink[b[1] : b[3], b[0] : b[2]])[0]


for f in sys.argv[1:]:
    for box, text in stamps(f):
        print(f, *box, text, sep="\t")
