#!/usr/bin/env python3
"""ZIRULAB article demo: common PDF tasks without Acrobat, on self-made sample PDFs.
Needs: qpdf, ocrmypdf (with Tesseract and Ghostscript), tabula-py (with Java), pdftotext, reportlab, pillow.
Run: python3 pdf_tools_demo.py OUTPUT_DIR"""
import hashlib, subprocess, sys, time
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
import tabula

out = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
run = lambda *a: subprocess.run(a, check=True, capture_output=True, text=True).stdout
pages = lambda p: int(run("qpdf", "--show-npages", str(p)).strip())

def sample(path, label, n):
    c = canvas.Canvas(str(path), pagesize=A4)
    for i in range(1, n + 1):
        c.setFont("Helvetica", 14); c.drawString(72, 760, f"{label} page {i}")
        c.showPage()
    c.save()
a, b = out / "a.pdf", out / "b.pdf"
sample(a, "Paper A", 3); sample(b, "Paper B", 2)

print("merge:", end=" ")
m = out / "merged.pdf"; run("qpdf", "--empty", "--pages", str(a), str(b), "--", str(m)); print(pages(m), "pages")
print("split pages 2-3 of merged:", end=" ")
s = out / "split.pdf"; run("qpdf", str(m), "--pages", ".", "2-3", "--", str(s)); print(pages(s), "pages")
print("reorder (5,1):", end=" ")
r = out / "reordered.pdf"; run("qpdf", str(m), "--pages", ".", "5,1", "--", str(r)); print(run("pdftotext", str(r), "-").split())
print("rotate page 1 by 90:", end=" ")
ro = out / "rotated.pdf"; run("qpdf", str(m), "--rotate=+90:1", str(ro))
print([l for l in run("pdfinfo", "-f", "1", "-l", "1", str(ro)).splitlines() if "rot" in l])

# table in a text-based PDF
t = out / "table.pdf"
rows = [["sample", "area_um2", "note"], ["S1", "12.5", "ok"], ["S2", "8.75", "edge"], ["S3", "20.1", "ok"], ["S4", "16.4", "ok"]]
c = canvas.Canvas(str(t), pagesize=A4); c.setFont("Helvetica", 11)
x = [80, 200, 320]; y0 = 700; h = 22
for j in range(len(rows) + 1): c.line(x[0] - 8, y0 + 16 - j * h, x[2] + 110, y0 + 16 - j * h)
for v in (x[0] - 8, x[1] - 8, x[2] - 8, x[2] + 110): c.line(v, y0 + 16, v, y0 + 16 - len(rows) * h)
for j, row in enumerate(rows):
    for i, v in enumerate(row): c.drawString(x[i], y0 - j * h, v)
c.showPage(); c.save()
df = tabula.read_pdf(str(t), pages=1, lattice=True)[0]
print("tabula, text PDF:", df.shape, df.values.tolist() == [[r[0], float(r[1]), r[2]] for r in rows[1:]]); print(df.to_string())

# scanned page: the text is only pixels
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 42)
img = Image.new("L", (1654, 2339), 255); d = ImageDraw.Draw(img)
lines = ["Calibration of the image scale", "Sample 17 was measured three times.", "The mean diameter was 24.6 micrometres."]
for k, l in enumerate(lines): d.text((150, 300 + k * 90), l, font=font, fill=0)
for j, row in enumerate(rows):
    for i, v in enumerate(row): d.text((150 + i * 380, 800 + j * 70), v, font=font, fill=0)
scan = out / "scan.pdf"; img.save(scan, resolution=200)
print("text before OCR:", repr(run("pdftotext", str(scan), "-").strip()))
print("tabula on scan: tables found =", len([x for x in tabula.read_pdf(str(scan), pages=1) if not x.empty]))
o = out / "scan_ocr.pdf"
t0 = time.time(); subprocess.run(["ocrmypdf", "-l", "eng", "--output-type", "pdf", str(scan), str(o)], check=True, capture_output=True)
print("OCR text:", run("pdftotext", "-layout", str(o), "-").strip())
words = run("pdftotext", str(o), "-")
print("target lines found:", [l in " ".join(words.split()) for l in lines])

# batch
batch = out / "batch"; batch.mkdir(exist_ok=True)
for i in range(1, 4): img.save(batch / f"s{i}.pdf", resolution=200)
for f in sorted(batch.glob("s?.pdf")):
    subprocess.run(["ocrmypdf", "-l", "eng", "--output-type", "pdf", "-q", str(f), str(batch / f"{f.stem}_ocr.pdf")], check=True)
print("batch OCR outputs:", len(list(batch.glob("*_ocr.pdf"))))
