"""clean_scan.py: make a gray or color scanned PDF easier to read. White paper, dark text.

Each page: render at --dpi (poppler's pdftoppm), divide it by a heavily blurred copy of itself (this flattens
yellow paper, gray backgrounds and shadows to white), then stretch the levels so the darkest text is black and
light marks (most show-through) go white. Gray by default; --color keeps colored ink and stamps.
Output pages are JPEG (quality 75) in a new PDF with the same page size. It has no text layer, and any text layer
the input had is dropped: run OCRmyPDF on it after, if you want search. Our color JPEG test scans came out smaller. A black and white (1-bit) scan already has
white paper and would get bigger, so do not use it on those.

It does not remove specks or straighten tilted pages (OCRmyPDF --deskew does that). It can erase light shading and
faint pencil: on one of our test pages it erased a light pencil note. Check the first pages before you run a whole
book. It renders every page first: about 4 MB of temporary disk a page at 300 dpi.

Needs Python 3 (tested on 3.14), numpy, Pillow, and pdftoppm (poppler).
  python3 clean_scan.py in.pdf out.pdf [--color] [--dpi 300]

MIT License. Brasspage, Nov 20, 2026. https://brasspage.com/enhance-scanned-pdf/
"""

import argparse
import io
import subprocess
import tempfile
from pathlib import Path

import numpy as np
from PIL import Image, ImageFilter

WHITE = 217  # after the divide, anything lighter than this becomes white (85%)
BLACK_MAX = 160  # the black point never goes above this, so a blank page stays white


def clean(img, dpi=300, color=False):
    """One page (a PIL image) in, the cleaned page out (L, or RGB with color=True)."""
    img = img.convert("RGB" if color else "L")
    a = np.asarray(img, np.float32)
    back = np.asarray(img.filter(ImageFilter.GaussianBlur(25 * dpi / 300)), np.float32)
    flat = np.clip(a / np.maximum(back, 1) * 255, 0, 255)
    black = min(np.percentile(flat, 0.5), BLACK_MAX)
    out = np.clip((flat - black) / (WHITE - black) * 255, 0, 255)
    return Image.fromarray(out.astype(np.uint8), img.mode)


def write_pdf(path, pages, dpi):
    """pages: JPEG bytes, one per page. Each JPEG goes in as is (DCTDecode); page size from dpi."""
    objs, kids = [], []
    for data in pages:
        im = Image.open(io.BytesIO(data))
        (w, h), cs = im.size, b"/DeviceRGB" if im.mode == "RGB" else b"/DeviceGray"
        pw, ph = w * 72 / dpi, h * 72 / dpi
        n = len(objs) + 3
        objs.append(
            b"<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace %s /BitsPerComponent 8 "
            b"/Filter /DCTDecode /Length %d >>\nstream\n" % (w, h, cs, len(data)) + data + b"\nendstream"
        )
        c = b"q %.3f 0 0 %.3f 0 0 cm /Im0 Do Q" % (pw, ph)
        objs.append(b"<< /Length %d >>\nstream\n" % len(c) + c + b"\nendstream")
        objs.append(
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.3f %.3f] "
            b"/Resources << /XObject << /Im0 %d 0 R >> >> /Contents %d 0 R >>" % (pw, ph, n, n + 1)
        )
        kids.append(n + 2)
    allobj = [
        b"<< /Type /Catalog /Pages 2 0 R >>",
        b"<< /Type /Pages /Kids [%s] /Count %d >>" % (b" ".join(b"%d 0 R" % k for k in kids), len(kids)),
    ] + objs
    buf, offs = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n"), []
    for i, o in enumerate(allobj, 1):
        offs.append(len(buf))
        buf += b"%d 0 obj\n" % i + o + b"\nendobj\n"
    x = len(buf)
    buf += b"xref\n0 %d\n0000000000 65535 f \n" % (len(offs) + 1)
    buf += b"".join(b"%010d 00000 n \n" % o for o in offs)
    buf += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (len(offs) + 1, x)
    Path(path).write_bytes(bytes(buf))


def main():
    ap = argparse.ArgumentParser(description="Clean up a scanned PDF: white paper, dark text.")
    ap.add_argument("src", help="scanned PDF in")
    ap.add_argument("dst", help="cleaned PDF out")
    ap.add_argument("--color", action="store_true", help="keep color (default: gray)")
    ap.add_argument("--dpi", type=int, default=300, help="render dpi (default 300)")
    a = ap.parse_args()
    with tempfile.TemporaryDirectory() as tmp:
        subprocess.run(["pdftoppm", "-r", str(a.dpi), "-png", a.src, f"{tmp}/p"], check=True)
        pages = []
        for f in sorted(Path(tmp).glob("p-*.png"), key=lambda p: int(p.stem.rsplit("-", 1)[1])):
            buf = io.BytesIO()
            clean(Image.open(f), a.dpi, a.color).save(buf, "JPEG", quality=75)
            pages.append(buf.getvalue())
            f.unlink()
    write_pdf(a.dst, pages, a.dpi)
    print(f"{len(pages)} pages -> {a.dst}")


if __name__ == "__main__":
    main()
