#!/usr/bin/env python3
"""edit-scan.py: change words in a scanned PDF, in the scan itself, and keep it searchable.

  python3 edit-scan.py in.pdf out.pdf "old text" "new text" ["old 2" "new 2" ...]

Needs Python 3 with Pillow (pip install pillow), Poppler (pdftoppm) and Tesseract.
How: render each page (pdftoppm), find the old words with Tesseract, paint the paper color over them,
draw the new words at the same height and letter width, in the system font that fits the old ink best,
then rebuild the PDF with a fresh Tesseract text layer. The old words are gone from the pixels and
from the text, not hidden under a box. Every page is rendered again at --dpi (default 300).
Options: --font FILE (repeat it; default: Arial, Times New Roman, Courier New or the Liberation fonts),
--dpi N, --lang eng. Brasspage, Nov 2026. MIT license.
"""

import argparse
import csv
import difflib
import functools
import io
import os
import subprocess
import sys
import tempfile
from pathlib import Path

from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont

FONT_NAMES = [  # one regular sans, serif and mono font, the first file found of each row
    ["Arial.ttf", "arial.ttf", "LiberationSans-Regular.ttf", "DejaVuSans.ttf"],
    ["Times New Roman.ttf", "times.ttf", "LiberationSerif-Regular.ttf", "DejaVuSerif.ttf"],
    ["Courier New.ttf", "cour.ttf", "LiberationMono-Regular.ttf", "DejaVuSansMono.ttf"],
]
FONT_DIRS = ["/System/Library/Fonts/Supplemental", "/Library/Fonts", "/usr/share/fonts", "C:/Windows/Fonts"]
TAIL = ",.;:!?)"
DARK = 1  # percent: the mean of the darkest 1% of the old ink pixels is the ink color
BLUR = 0.6  # px at 300 dpi; DARK and BLUR were set on one word of one test page


def default_fonts():
    found = {}
    for d in FONT_DIRS + [str(Path.home() / ".fonts")]:
        if os.path.isdir(d):
            for p in Path(d).rglob("*.tt[fc]"):
                found.setdefault(p.name, str(p))
    return [next(found[n] for n in row if n in found) for row in FONT_NAMES if any(n in found for n in row)]


def words(img, lang):
    """Tesseract word boxes, grouped by line: {line key: [(text, left, top, right, bottom)]}."""
    buf = io.BytesIO()
    img.save(buf, "PNG")
    tsv = subprocess.run(
        ["tesseract", "stdin", "stdout", "-l", lang, "--psm", "3", "tsv"],
        input=buf.getvalue(),
        capture_output=True,
        check=True,
    ).stdout.decode("utf-8", "replace")
    lines = {}
    for r in csv.DictReader(io.StringIO(tsv), delimiter="\t", quoting=csv.QUOTE_NONE):
        if r["level"] == "5" and r["text"].strip():
            x, y, w, h = (int(r[k]) for k in ("left", "top", "width", "height"))
            key = (r["block_num"], r["par_num"], r["line_num"])
            lines.setdefault(key, []).append((r["text"], x, y, x + w, y + h))
    return lines


def find(lines, old):
    """Each place where the words of `old` follow each other on one line.
    Returns (line key, box, text as read, trailing punctuation, words after it, all words of the line)."""
    toks = old.split()
    hits = []
    for key, ws in lines.items():
        for i in range(len(ws) - len(toks) + 1):
            run = ws[i : i + len(toks)]
            last = run[-1][0]
            tail = last[len(toks[-1]) :] if last.startswith(toks[-1]) else None
            if [w[0] for w in run[:-1]] == toks[:-1] and tail is not None and all(c in TAIL for c in tail):
                box = (min(w[1] for w in run), min(w[2] for w in run), max(w[3] for w in run), max(w[4] for w in run))
                hits.append((key, box, " ".join(w[0] for w in run), tail, ws[i + len(toks) :], ws))
    return hits


def phrase(box, after):
    """The words that follow the old text closely (no column gap), as (top, bottom, right) or None."""
    line_h = max([box[3] - box[1]] + [w[4] - w[2] for w in after])
    right, run = box[2], []
    for w in after:
        if w[1] - right > 2 * line_h:  # a gap this wide starts another column of a table or form
            break
        run.append(w)
        right = w[3]
    if not run:
        return None
    return min(w[2] for w in run), max(w[4] for w in run), right


def pixels(im):
    b = im.tobytes()
    return list(b) if im.mode == "L" else [tuple(b[i : i + 3]) for i in range(0, len(b), 3)]


load = functools.lru_cache(maxsize=None)(ImageFont.truetype)


def fit(text, font_file, h):
    """The font size at which `text` has ink exactly h px tall, and its ink box from the baseline origin."""
    x0, y0, x1, y1 = load(font_file, 100).getbbox(text, anchor="ls")
    font = load(font_file, max(4, round(100 * h / (y1 - y0))))
    return font, font.getbbox(text, anchor="ls")


def mask(text, font, sx=1.0, size=None):
    """White-on-black ink of `text`, x scaled by sx (or resized to size)."""
    x0, y0, x1, y1 = font.getbbox(text, anchor="ls")
    m = Image.new("L", (max(1, x1 - x0), max(1, y1 - y0)), 0)
    ImageDraw.Draw(m).text((-x0, -y0), text, font=font, fill=255, anchor="ls")
    return m.resize(size or (max(1, round(m.width * sx)), m.height), Image.LANCZOS)


def ink_mask(crop):
    """Ink pixels of a gray crop: darker than halfway between the paper and the darkest ink."""
    lo, hi = crop.getextrema()
    hist = crop.histogram()
    paper = max(range(lo, hi + 1), key=lambda v: hist[v] if v > (lo + hi) // 2 else -1)
    cut = (lo + paper) // 2
    return crop.point(lambda v: 255 if v < cut else 0), paper


def tight(gray, box):
    """The ink box inside a word box (a Tesseract box can run a few px past the ink)."""
    bb = ink_mask(gray.crop(box))[0].getbbox()
    return (box[0] + bb[0], box[1] + bb[1], box[0] + bb[2], box[1] + bb[3]) if bb else box


def iou(a, b):
    both = ImageChops.multiply(a, b).histogram()[255]
    either = ImageChops.lighter(a, b).histogram()[255]
    return both / either if either else 0


def pick_font(gray, lines, fonts):
    """The font whose letters cover the ink of these lines best (each word fitted to its box, 3 px slack)."""

    def score(f):
        total = 0
        for line in lines:
            for text, *wb in line[:12]:
                font, _ = fit(text, f, wb[3] - wb[1])
                m = mask(text, font, size=(wb[2] - wb[0], wb[3] - wb[1])).point(lambda v: 255 if v > 127 else 0)
                total += iou(ink_mask(gray.crop(wb))[0].filter(ImageFilter.MaxFilter(3)), m.filter(ImageFilter.MaxFilter(3)))
        return total

    return max(fonts, key=score) if len(fonts) > 1 else fonts[0]


def patch(img, box, old_text, new_text, line, after, extra, font_file, dpi):
    """Paint over old_text at box, draw new_text on its baseline, and slide the rest of the phrase
    so the spacing stays right. `extra`: how far edits further right on this line pushed it.
    Returns the change in width."""
    gray = img.convert("L")
    _, paper = ink_mask(gray.crop(box))
    l, t, r, b = box = tight(gray, box)
    w, h = r - l, b - t
    # Size and letter width: the median of every word on the line, so one misread word cannot skew them.
    sizes, widths = [], []
    for text, *wb in line:
        wb = tight(gray, wb)
        f, (x0, _, x1, _) = fit(text, font_file, wb[3] - wb[1])
        sizes.append(f.size)
        widths.append((wb[2] - wb[0]) / max(1, x1 - x0))
    font = load(font_file, sorted(sizes)[len(sizes) // 2])
    sx = min(1.4, max(0.7, sorted(widths)[len(widths) // 2]))  # keep the old letter width, within reason
    ox0, oy0, _, oy1 = font.getbbox(old_text, anchor="ls")
    bx, by = l - ox0 * sx, (t - oy0 + b - oy1) / 2  # the old baseline, from its top and its bottom
    nx0, ny0, _, _ = font.getbbox(new_text, anchor="ls")
    new = mask(new_text, font, sx).filter(ImageFilter.GaussianBlur(BLUR * dpi / 300))  # scans are soft
    nl, nt = round(bx + nx0 * sx), round(by + ny0)
    delta = nl + new.width - r
    pad = max(2, round(0.15 * h))
    run = phrase(box, after)
    top, bottom, right = (min(t, nt, run[0]), max(b, nt + new.height, run[1]), run[2] + extra) if run else (t, b, r)
    area = (min(l, nl) - pad, min(top, nt) - pad, max(right, right + delta, nl + new.width) + pad, bottom + pad)
    # Paper: median color and grain of the light pixels around the words. Ink: the darkest DARK % of the old ink.
    lights = sorted((g, px) for g, px in zip(pixels(gray.crop(area)), pixels(img.crop(area))) if g >= paper - 20)
    bg = lights[len(lights) // 2][1] if lights else (255 if img.mode == "L" else (255, 255, 255))
    gs = [g for g, _ in lights] or [255]
    grain = (sum((g - sum(gs) / len(gs)) ** 2 for g in gs) / len(gs)) ** 0.5
    darkest = sorted(zip(pixels(gray.crop(box)), pixels(img.crop(box))))[: max(1, w * h * DARK // 100)]
    if img.mode == "L":
        fg = round(sum(p for _, p in darkest) / len(darkest))
    else:
        fg = tuple(round(sum(p[c] for _, p in darkest) / len(darkest)) for c in range(3))
    strip = img.crop((r, top - pad, right + pad, bottom + pad)) if run else None
    size = (area[2] - area[0], area[3] - area[1])
    noise = Image.effect_noise(size, grain).convert(img.mode)  # gray noise around 128
    img.paste(ImageChops.add(Image.new(img.mode, size, bg), noise, 1, -128), area[:2])
    if strip:
        img.paste(strip, (r + delta, top - pad))
    img.paste(Image.new(img.mode, new.size, fg), (nl, nt), new)
    return delta


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("inp")
    ap.add_argument("out")
    ap.add_argument("pairs", nargs="+", help='"old text" "new text", one or more pairs')
    ap.add_argument("--font", action="append", help="a .ttf or .ttc file to use; repeat for more")
    ap.add_argument("--dpi", type=int, default=300)
    ap.add_argument("--lang", default="eng")
    a = ap.parse_args()
    if len(a.pairs) % 2:
        sys.exit("give old and new text in pairs")
    pairs = list(zip(a.pairs[::2], a.pairs[1::2]))
    fonts = a.font or default_fonts()
    if not fonts:
        sys.exit("no font found; pass one with --font /path/to/font.ttf")
    count = {old: 0 for old, _ in pairs}
    seen = {old: [] for old, _ in pairs}
    with tempfile.TemporaryDirectory() as tmp:
        subprocess.run(["pdftoppm", "-r", str(a.dpi), "-tiff", a.inp, f"{tmp}/p"], check=True)
        pages = sorted(Path(tmp).glob("p-*.tif"), key=lambda p: int(p.stem.split("-")[-1]))
        jpgs = []
        for n, f in enumerate(pages, 1):
            img = Image.open(f).convert("RGB")
            if all(ImageChops.difference(c1, c2).getextrema()[1] < 24 for c1, c2 in [img.split()[:2], img.split()[1:]]):
                img = img.convert("L")  # a gray scan stays gray, and small
            lines = words(img, a.lang)
            for old, _ in pairs:  # what the OCR read, to suggest a spelling when old text is not found
                for k in {max(1, len(old.split()) - 1), len(old.split()), len(old.split()) + 1}:
                    seen[old] += [(" ".join(w[0] for w in ws[i : i + k]), n) for ws in lines.values() for i in range(len(ws) - k + 1)]
            hits = [(h, old, new) for old, new in pairs for h in find(lines, old)]
            grown = {}  # line key: how far edits further right on that line pushed its words
            used = pick_font(img.convert("L"), list({h[0]: h[5] for h, _, _ in hits}.values()), fonts) if hits else None
            for (key, box, text, tail, after, line), old, new in sorted(hits, key=lambda x: -x[0][1][0]):
                delta = patch(img, box, text, new + tail, line, after, grown.get(key, 0), used, a.dpi)
                grown[key] = grown.get(key, 0) + max(0, delta)
                count[old] += 1
                print(f"page {n}: {text!r} -> {new + tail!r} ({Path(used).stem})")
            jpg = Path(tmp) / f"e-{n:04d}.jpg"
            img.save(jpg, "JPEG", quality=90, dpi=(a.dpi, a.dpi))
            jpgs.append(str(jpg))
        missing = [old for old, c in count.items() if c == 0]
        for old in missing:
            texts = [t for t, _ in seen[old]]
            near = [(t, n) for t in difflib.get_close_matches(old, texts, n=3, cutoff=0.5) for tt, n in seen[old] if tt == t]
            hint = "; the OCR read " + ", ".join(f"{t!r} (page {n})" for t, n in dict.fromkeys(near)) if near else ""
            print(f"not found: {old!r}{hint}. To edit one of those, pass it as the old text.", file=sys.stderr)
        if len(missing) == len(pairs):
            sys.exit(1)
        (Path(tmp) / "list.txt").write_text("\n".join(jpgs) + "\n")
        base = Path(tmp) / "out"
        subprocess.run(
            ["tesseract", f"{tmp}/list.txt", str(base), "-l", a.lang, "--psm", "3", "pdf"],
            check=True,
            capture_output=True,
        )
        Path(a.out).write_bytes(base.with_suffix(".pdf").read_bytes())
    print(f"wrote {a.out}: {sum(count.values())} edits, {len(pages)} pages")


if __name__ == "__main__":
    main()
