"""split-half.py: split each page of a PDF into a left page and a right page.
MIT License, Brasspage 2026. Needs Python 3.11+ and: pip install pymupdf numpy
Usage: python3 split-half.py in.pdf out.pdf
On a scanned book spread it cuts at the gutter (the blank band between the two pages), not at the middle.
If it finds no gutter near the middle, it cuts at the middle. A text layer (OCR) is split too: each new
page keeps only the text of its own half. The pictures stay as they are, so the file stays the same size.
"""

import sys

import numpy as np
import pymupdf


def gutter(page):
    """The cut, as a share of the page width: the darkest column of the widest band with no text, 30% to 70%."""
    pix = page.get_pixmap(dpi=40, colorspace=pymupdf.csGRAY)
    g = np.frombuffer(pix.samples, np.uint8).reshape(pix.height, pix.stride)[:, : pix.width].astype(float)
    box = np.ones(max(3, pix.width // 50)) / max(3, pix.width // 50)
    near = np.apply_along_axis(lambda row: np.convolve(row, box, "same"), 1, g)
    ink = ((near - g) > 40).sum(axis=0)  # dark strokes; a smooth spine shadow is not darker than its neighbors
    lo, hi = int(pix.width * 0.3), int(pix.width * 0.7)
    quiet = ink[lo:hi] <= 0.1 * np.median(ink[lo:hi])
    best, start = (0, 0), None
    for i, q in enumerate([*quiet, False]):
        if q and start is None:
            start = i
        elif not q and start is not None:
            best, start = max(best, (i - start, start)), None
    if best[0] == 0:
        return 0.5
    a, b = lo + best[1], lo + best[1] + best[0]
    shade = np.convolve(g.mean(axis=0), box, "same")
    return (a + int(np.argmin(shade[a:b])) + 0.5) / pix.width


src, out = pymupdf.open(sys.argv[1]), pymupdf.open()
for number in range(src.page_count):
    out.insert_pdf(src, from_page=number, to_page=number)
    out.insert_pdf(src, from_page=number, to_page=number)
    left, right = out[-2], out[-1]
    for p in (left, right):
        p.remove_rotation()
    r = left.rect
    x = r.x0 + r.width * gutter(left)
    halves = pymupdf.Rect(r.x0, r.y0, x, r.y1), pymupdf.Rect(x, r.y0, r.x1, r.y1)
    for p, keep, drop in ((left, *halves), (right, *halves[::-1])):
        p.add_redact_annot(drop, fill=False)  # removes the other half's text only
        p.apply_redactions(images=pymupdf.PDF_REDACT_IMAGE_NONE, graphics=pymupdf.PDF_REDACT_LINE_ART_NONE)
        p.set_mediabox(keep)
    print(f"page {number + 1}: cut at {100 * (x - r.x0) / r.width:.1f}% of the width")
out.save(sys.argv[2], garbage=4, deflate=True)
