"""Find the layout of a page: titles, headings, text, lists, tables, pictures, page headers and footers.
Free, from brasspage.com.
Usage: python layout.py page.png [more.pdf ...] [--crops DIR]
Needs: pip install torch transformers pillow pypdfium2
Runs heron, Docling's layout model (docling-project/docling-layout-heron, Apache-2.0), on each image or PDF page.
Prints one line per box, top to bottom: file, page, label, score, x0 y0 x1 y1 (pixels; PDFs at 144 dpi).
With --crops DIR it also saves each table and picture as a PNG.
"""

import sys
from pathlib import Path

import pypdfium2 as pdfium
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForObjectDetection

MODEL = "docling-project/docling-layout-heron"  # or "Aryn/deformable-detr-DocLayNet": fewer false boxes, slower
THRESHOLD = 0.6  # the model card's
OVERLAP = 0.5  # drop a box that overlaps a box with a higher score this much (IoU)


def pages(path):
    if path.suffix.lower() == ".pdf":
        for n, page in enumerate(pdfium.PdfDocument(path), 1):
            yield n, page.render(scale=2).to_pil().convert("RGB")
    else:
        yield 1, Image.open(path).convert("RGB")


def iou(a, b):
    w = min(a[2], b[2]) - max(a[0], b[0])
    h = min(a[3], b[3]) - max(a[1], b[1])
    if w <= 0 or h <= 0:
        return 0.0
    inter = w * h
    return inter / (
        (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    )


args = sys.argv[1:]
crops = None
if "--crops" in args:
    i = args.index("--crops")
    crops = Path(args[i + 1])
    del args[i : i + 2]
    crops.mkdir(parents=True, exist_ok=True)
dev = "cpu"
if torch.cuda.is_available():
    dev = "cuda"
elif torch.backends.mps.is_available():
    dev = "mps"
proc = AutoImageProcessor.from_pretrained(MODEL)
model = AutoModelForObjectDetection.from_pretrained(MODEL).eval().to(dev)
for f in map(Path, args):
    for n, im in pages(f):
        with torch.inference_mode():
            out = model(**proc(images=im, return_tensors="pt").to(dev))
        r = proc.post_process_object_detection(
            out, threshold=THRESHOLD, target_sizes=[im.size[::-1]]
        )[0]
        found = sorted(
            zip(r["scores"].tolist(), r["labels"].tolist(), r["boxes"].tolist()),
            reverse=True,
        )
        keep = []
        for score, label, box in found:
            if all(iou(box, k[2]) < OVERLAP for k in keep):
                keep.append((score, model.config.id2label[label], box))
        keep.sort(key=lambda k: (k[2][1], k[2][0]))
        for i, (score, label, box) in enumerate(keep):
            print(f, n, label, f"{score:.2f}", *(round(v) for v in box), sep="\t")
            if crops and label in ("table", "picture"):
                im.crop(box).save(crops / f"{f.stem}-p{n}-{i}-{label}.png")
