"""Sample scanned PDFs for OCR testing (Nov 21, 2026). The script is MIT. The PDFs and truth files it writes are CC0.

12 made-up documents with our own text (made-up people, shops and places; phone numbers 555-01xx; .example
mail domains). Each page is drawn clean with Pillow and macOS fonts at 300 dpi, then made into a scan of one kind.
The truth is every printed line in reading order (left column before right column), pages split by a form feed.
Pen marks, check marks, highlighter, the signature squiggle and the rule lines are not in the truth.

Run: python3 make_set.py <out dir>   (macOS fonts, Pillow, numpy) writes <out>/NN-name.pdf and <out>/NN-name.txt, and prints a summary.
"""

import io
import math
import sys
import time
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont

DPI, W, H, M = 300, 2550, 3300, 225
SUP = "/System/Library/Fonts/Supplemental/"
FONTS = {
    "times": SUP + "Times New Roman.ttf",
    "timesb": SUP + "Times New Roman Bold.ttf",
    "arial": SUP + "Arial.ttf",
    "arialb": SUP + "Arial Bold.ttf",
    "georgia": SUP + "Georgia.ttf",
    "georgiab": SUP + "Georgia Bold.ttf",
    "courier": SUP + "Courier New.ttf",
    "courierb": SUP + "Courier New Bold.ttf",
    "verdana": SUP + "Verdana.ttf",
    "verdanab": SUP + "Verdana Bold.ttf",
}
SEED = 20261121


class Sheet:
    """A white page. Each drawn line goes into self.lines (the truth) and self.boxes (its pixel box)."""

    def __init__(self, w=W, h=H):
        self.img = Image.new("L", (w, h), 255)
        self.d = ImageDraw.Draw(self.img)
        self.lines, self.boxes = [], []

    def font(self, name, pt):
        return ImageFont.truetype(FONTS[name], round(pt * DPI / 72))

    def text(self, x, y, s, name, pt, gap=1.4, right=False, truth=True):
        f = self.font(name, pt)
        if right:
            x -= f.getlength(s)
        self.d.text((x, y), s, font=f, fill=0)
        if truth:
            self.lines.append(s)
            self.boxes.append(self.d.textbbox((x, y), s, font=f))
        return y + round(pt * DPI / 72 * gap)

    def para(self, x, y, s, name, pt, width, gap=1.4):
        f, line = self.font(name, pt), ""
        for w in s.split():
            t = (line + " " + w).strip()
            if f.getlength(t) > width and line:
                y, line = self.text(x, y, line, name, pt, gap), w
            else:
                line = t
        return self.text(x, y, line, name, pt, gap) if line else y

    def row(self, y, cells, name, pt, gap=1.6):
        """cells: (x, text, right aligned). One truth line per row, cells joined by two spaces."""
        f = self.font(name, pt)
        for x, s, r in cells:
            self.d.text((x - (f.getlength(s) if r else 0), y), s, font=f, fill=0)
        self.lines.append("  ".join(s for _, s, _ in cells))
        return y + round(pt * DPI / 72 * gap)

    def rule(self, y, x0=M, x1=W - M, shade=120, width=3):
        self.d.line((x0, y, x1, y), fill=shade, width=width)

    def box(self, x, y, size=44, tick=False):
        self.d.rectangle((x, y, x + size, y + size), outline=0, width=4)
        if tick:
            self.d.line((x + 8, y + 8, x + size - 8, y + size - 8), fill=0, width=5)
            self.d.line((x + size - 8, y + 8, x + 8, y + size - 8), fill=0, width=5)


def scan(img, rng, paper=246, ink=25, noise=1.5, blur=0.7):
    """Clean drawing (255 paper, 0 ink) to a gray scan: paper and ink levels, a little blur and sensor noise."""
    if blur:
        img = img.filter(ImageFilter.GaussianBlur(blur))
    a = np.asarray(img, np.float32) / 255.0
    out = ink + (paper - ink) * a + rng.normal(0, noise, a.shape)
    return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))


def jpeg(img, q):
    b = io.BytesIO()
    img.save(b, "JPEG", quality=q)
    b.seek(0)
    return Image.open(b)


def persp_coeffs(src, dst):
    """Pillow PERSPECTIVE coefficients that map each output point in dst to the input point in src."""
    a, b = [], []
    for (x, y), (u, v) in zip(dst, src):
        a += [[x, y, 1, 0, 0, 0, -u * x, -u * y], [0, 0, 0, x, y, 1, -v * x, -v * y]]
        b += [u, v]
    return np.linalg.solve(np.array(a, float), np.array(b, float)).tolist()


# ---------------------------------------------------------------- the 12 documents


def letter():
    s = Sheet()
    y = s.text(M, 230, "Spokewell Cycle Repair", "timesb", 20)
    y = s.text(M, y, "418 Larkfield Road, Millbrook  |  555-0147  |  repairs@spokewell.example", "times", 10.5)
    s.rule(y + 10)
    y = s.text(M, y + 70, "November 12, 2026", "times", 12)
    for t in ("Ms. Rosa Delgado", "27 Quarry Street", "Millbrook"):
        y = s.text(M, y + (50 if t.startswith("Ms") else 0), t, "times", 12)
    y = s.text(M, y + 60, "Dear Ms. Delgado,", "times", 12)
    body = [
        ("Thank you for bringing your 1998 touring bike to us on November 9. We checked it from front to back, "
        "and this letter lists what we found and what we suggest."),
        ("The rear wheel has two broken spokes and a slight wobble. We can replace the spokes and true the wheel "
        "for $38.00. The chain is worn past 0.75 percent, so it will soon wear the cassette as well. A new chain "
        "costs $29.50 with fitting. Both brake pads are under 2 mm thick and must be replaced before you ride in "
        "wet weather ($24.00 for the pair)."),
        ("The frame, headset and bottom bracket are in good shape. We found no rust inside the seat tube, which is "
        "rare on a bike of this age."),
        ("The total for all three repairs is $91.50 before tax. If you approve, we can have the bike ready by "
        "Thursday, November 19. Call us at 555-0147 or reply to repairs@spokewell.example, and quote job number "
        "SW-20417."),
        "We kept the old spokes in a bag on the handlebar, in case you want to see them.",
    ]
    for p in body:
        y = s.para(M, y + 40, p, "times", 12, W - 2 * M)
    y = s.text(M, y + 50, "Kind regards,", "times", 12)
    y = s.text(M, y + 150, "Dana Whitlock", "times", 12)
    s.text(M, y, "Service Manager", "times", 12)
    return [s]


INVOICE = [
    ("Glazed planter, 30 cm, sage", 6, 42.00),
    ("Glazed planter, 45 cm, sage", 4, 68.50),
    ("Window box, 80 cm, charcoal", 3, 55.00),
    ("Drainage saucer, 30 cm", 6, 7.25),
    ("Drainage saucer, 45 cm", 4, 9.80),
    ("Potting mix, 40 L bag", 5, 12.40),
    ("Delivery and setup", 1, 45.00),
]


def invoice():
    s, R = Sheet(), W - M
    s.text(R, 230, "INVOICE", "arialb", 26, right=True)
    y = s.text(M, 240, "Fernlow Planters", "arialb", 16)
    for t in ("9 Kiln Yard, Eastbrook", "accounts@fernlow.example  |  555-0182"):
        y = s.text(M, y, t, "arial", 10)
    y += 60
    y2 = y
    for t in ("Bill to:", "Copperleaf Cafe", "140 Mill Street", "Westbrook"):
        y = s.text(M, y, t, "arialb" if t == "Bill to:" else "arial", 10.5)
    for t in ("Invoice no. FP-3318", "Date: October 30, 2026", "Due: November 29, 2026"):
        y2 = s.text(R, y2, t, "arial", 10.5, right=True)
    y = max(y, y2) + 80
    cols = [(M + 10, False), (1530, True), (1900, True), (R - 10, True)]
    s.d.rectangle((M, y - 20, R, y + 60), fill=225)
    y = s.row(y, [(x, t, r) for (x, r), t in zip(cols, ("Item", "Qty", "Unit price", "Amount"))], "arialb", 10.5)
    total = 0.0
    for item, qty, price in INVOICE:
        amount = round(qty * price, 2)
        total += amount
        y = s.row(y, [(x, t, r) for (x, r), t in zip(cols, (item, str(qty), f"{price:.2f}", f"{amount:.2f}"))], "arial", 10.5)
        s.rule(y - 22, shade=170, width=2)
    tax = round(total * 0.075 + 1e-9, 2)
    y += 30
    for label, v, f in (("Subtotal", total, "arial"), ("Tax 7.5%", tax, "arial"), ("Total due", total + tax, "arialb")):
        y = s.row(y, [(1900, label, True), (R - 10, f"{v:,.2f}", True)], f, 11)
    y += 90
    y = s.para(M, y, "Pay by bank transfer within 30 days and quote invoice number FP-3318. Thank you for your order.", "arial", 10, W - 2 * M)
    return [s]


def two_columns():
    s = Sheet()
    y = s.text(M, 220, "Millbrook Neighbors", "georgiab", 30)
    y = s.text(M, y, "Community newsletter  |  Issue 14  |  November 2026", "georgia", 11)
    s.rule(y + 5, shade=60, width=5)
    top, gap = y + 70, 90
    cw = (W - 2 * M - gap) // 2
    left = [
        ("Library opens a repair corner", [
            ("Starting December 5, the library will host a repair corner on the first Saturday of each month, from "
            "10 am to 1 pm. Volunteers fix lamps, toasters, zippers and bikes for free."),
            ("Bring one item per visit, and bring the parts if you already bought them. Sign up at the front desk "
            "or call 555-0111."),
        ]),
        ("Road work on Quarry Street", [
            ("Crews will resurface Quarry Street between Mill Street and the river bridge from November 23 to "
            "December 4. The road stays open to local traffic."),
            ("Parking on the east side is closed during work hours, 7 am to 5 pm. Bus stop 14 moves 50 meters "
            "north for these two weeks."),
        ]),
    ]
    right = [
        ("Winter coat drive", [
            ("The school gym takes clean winter coats, hats and gloves in all sizes until November 30. Drop boxes "
            "are at the front office and at the Copperleaf Cafe."),
        ]),
        ("Volunteer of the month", [
            ("Ana Kowalski has walked dogs for the animal shelter every Tuesday for six years. She says the secret "
            "is good shoes and a pocket full of treats. Thank you, Ana."),
        ]),
        ("Dates to remember", [
            "Nov 26: Town hall closed.", "Dec 1: Council meeting, 7 pm.", "Dec 5: Repair corner, 10 am.",
            "Dec 12: Tree lighting, 5 pm.",
        ]),
    ]
    for x, col in ((M, left), (M + cw + gap, right)):
        y = top
        for head, paras in col:
            y = s.para(x, y, head, "georgiab", 15, cw, gap=1.3) + 15
            for p in paras:
                y = s.para(x, y, p, "georgia", 10.5, cw) + (10 if head == "Dates to remember" else 30)
            y += 50
    s.d.line((M + cw + gap // 2, top, M + cw + gap // 2, y - 60), fill=150, width=2)
    s.text(M, H - 330, "Send news to editor@millbrook.example by the 20th of each month.", "georgia", 10)
    return [s]


def memo():
    s = Sheet()
    y = s.text(M, 260, "MEMO", "arialb", 24)
    for t in ("To: All kitchen staff", "From: Priya Raman, Copperleaf Cafe", "Date: November 16, 2026",
              "Subject: New closing checklist"):
        y = s.text(M, y + 5, t, "arial", 12)
    s.rule(y + 20, shade=60)
    y += 60
    for p in (
        ("From Monday, November 23, the last person on shift signs the closing checklist and leaves it in the blue "
        "folder by the office door. The list has twelve steps. Most of them you already do, but two are new."),
        ("First, the walk-in fridge now has a log sheet on its door. Write the temperature at close, and if it reads "
        "above 4 degrees C, call me before you leave, at any hour."),
        ("Second, the dish machine must run its cleaning cycle every Friday night. The cycle takes 25 minutes, so "
        "start it before you mop the floor."),
        ("Please read the full list on the board this week and ask me about anything that is not clear. Thank you "
        "all for a busy and smooth October."),
    ):
        y = s.para(M, y + 40, p, "arial", 12, W - 2 * M)
    s.text(M, y + 60, "Priya", "arial", 12)
    return [s]


def notice():
    s = Sheet()
    y = s.text(M, 260, "Notice to all residents", "verdanab", 22)
    y = s.text(M, y + 10, "Water shut-off on Wednesday, December 2", "verdanab", 14)
    for p in (
        ("The water supply to buildings A, B and C will be shut off on Wednesday, December 2, from 9:00 am to "
        "3:00 pm, while the plumbers replace the main valve in the basement of building B."),
        ("Please fill a few bottles or a kettle the night before. Toilets will flush once from the tank. Do not use "
        "the washing machines in the laundry room until 4:00 pm, as the water may run brown for a short time after "
        "it comes back."),
        ("If you have a medical need for water during these hours, tell the office by Monday, November 30, and we "
        "will bring you a 20 litre container."),
        ("We are sorry for the trouble. The new valve should stop the leaks that some of you reported in flats B4 "
        "and B7 this autumn."),
    ):
        y = s.para(M, y + 45, p, "verdana", 12, W - 2 * M)
    y += 80
    for t in ("Kiln Yard Housing Co-op", "Office hours: Monday to Friday, 9 am to 12 noon", "Phone: 555-0163"):
        y = s.text(M, y, t, "verdana", 11)
    return [s]


def agenda():
    s = Sheet()
    y = s.text(M, 240, "Millbrook Garden Club", "timesb", 22)
    y = s.text(M, y, "Meeting agenda", "timesb", 16)
    y = s.text(M, y + 10, "Thursday, November 19, 2026, 7:00 pm, Library meeting room", "times", 12)
    y += 50
    items = [
        "1. Welcome and apologies",
        "2. Minutes of the October meeting",
        "3. Treasurer's report: balance $1,482.16",
        "4. Spring plant sale: dates, tables, and who brings the tent",
        "5. Seed swap at the library in February",
        "6. New compost bins for the school garden (quote: $640)",
        "7. Speaker for January: pruning fruit trees",
        "8. Any other business",
    ]
    for t in items:
        y = s.text(M + 60, y + 18, t, "times", 13)
    y += 60
    y = s.text(M, y, "Next meeting: Thursday, December 17, at 7:00 pm.", "timesb", 13)
    for p in (
        ("Please bring a plate of food to share for the December meeting. Tea and coffee will be provided by the "
        "library. If you cannot come, send your apologies to the secretary, Joan Pike, at 555-0190."),
        ("Members who still have tools from the October work day, please return them to the shed behind the "
        "library before the end of the month."),
    ):
        y = s.para(M, y + 40, p, "times", 12, W - 2 * M)
    return [s]


def fax():
    s = Sheet()
    s.text(60, 40, "NOV-17-2026 14:32   FROM: EASTBROOK VET CLINIC   555-0128   P.01/01", "courier", 9)
    y = s.text(M, 260, "Eastbrook Vet Clinic", "courierb", 20)
    y = s.text(M, y, "FAX", "courierb", 28)
    for t in ("To: Millbrook Animal Shelter", "Attn: Intake desk", "Pages: 1",
              'Re: Lab results for "Biscuit", shelter ID MS-0912'):
        y = s.text(M, y + 5, t, "courier", 12)
    s.rule(y + 15, shade=0, width=4)
    y += 40
    for p in (
        ("Blood count and kidney values are within normal range. The thyroid level is slightly low (T4 1.1 ug/dL, "
        "reference 1.2 to 4.0). No treatment is needed now. Please recheck in 8 weeks, around January 12, 2027."),
        ("The dental cleaning is booked for Tuesday, December 8, at 8:30 am. No food after 10 pm the night before. "
        "Water is fine."),
        "Call us at 555-0128 with any questions.",
    ):
        y = s.para(M, y + 40, p, "courier", 12, W - 2 * M)
    y = s.text(M, y + 70, "Dr. Helen Osei", "courier", 12)
    s.text(M, y + 100, "CONFIDENTIAL: This fax is for the named recipient only.", "courier", 10)
    return [s]


def recipe():
    s = Sheet()
    y = s.text(M, 250, "Pumpkin Oat Muffins", "verdanab", 24)
    y = s.text(M, y, "Copperleaf Cafe  |  Makes 12", "verdana", 13)
    y = s.text(M, y + 50, "You need", "verdanab", 15)
    for t in ("2 cups rolled oats", "1 1/2 cups flour", "1 tsp baking soda", "1 tsp cinnamon", "1/2 tsp salt",
              "1 cup pumpkin puree", "2 eggs", "1/2 cup brown sugar", "1/3 cup melted butter", "3/4 cup milk"):
        y = s.text(M + 40, y, t, "verdana", 13, gap=1.45)
    y = s.text(M, y + 50, "Steps", "verdanab", 15)
    for t in (
        "1. Heat the oven to 375 F and line a 12-cup muffin tin.",
        "2. Mix the oats, flour, baking soda, cinnamon and salt in a large bowl.",
        "3. In a second bowl, whisk the pumpkin, eggs, sugar, butter and milk.",
        "4. Stir the wet mix into the dry mix until just combined. Lumps are fine.",
        "5. Fill each cup about three quarters full.",
        "6. Bake for 20 to 22 minutes, until a toothpick comes out clean.",
        "7. Cool for 10 minutes in the tin, then move to a rack.",
    ):
        y = s.para(M + 40, y + 8, t, "verdana", 13, W - 2 * M - 40)
    s.text(M, y + 50, "Keeps 3 days in a tin, or 2 months in the freezer.", "verdana", 12)
    return [s]


def small_print():
    s = Sheet()
    y = s.text(M, 230, "Terms of service", "arialb", 11)
    for p in (
        ("1. Estimates. Every estimate is free and valid for 30 days. We will not do work above the estimate without "
        "your approval by phone, text or email."),
        ("2. Parts. We fit new parts unless you ask for used ones. Old parts are kept for 14 days and then recycled, "
        "unless you ask to take them home."),
        ("3. Storage. Bikes not collected within 21 days of our ready notice are charged storage at $3.00 per day. "
        "After 90 days we may sell the bike to cover unpaid charges, as the law allows."),
        "4. Payment. We take cash, cards and bank transfer. Payment is due when you collect the bike.",
        ("5. Warranty. Labor is guaranteed for 90 days. Parts carry the maker's warranty. The warranty does not cover "
        "crash damage, wear, or work done by others after ours."),
        ("6. Electric bikes. We service the mechanical parts of electric bikes. We do not open batteries or motors, "
        "and we do not change speed limiters."),
        ("7. Liability. We are not liable for items left on the bike, such as lights, bags, locks and computers. "
        "Please remove them before you leave the bike with us."),
        ("8. Privacy. We keep your name, phone and email to contact you about your repair. We do not share them, and "
        "we delete them after two years without a visit."),
    ):
        y = s.para(M, y + 12, p, "arial", 7, W - 2 * M, gap=1.3)
    s.text(M, y + 30, "Spokewell Cycle Repair, 418 Larkfield Road, Millbrook. Version 3, updated September 1, 2026.", "arial", 6.5)
    return [s]


def form():
    s, R = Sheet(), W - M
    y = s.text(M, 230, "Membership form", "arialb", 22)
    y = s.text(M, y, "Millbrook Garden Club", "arial", 13)
    y += 60
    fields = [("Full name", "Thomas Brennan"), ("Address", "56 Orchard Close, Millbrook"), ("Phone", "555-0175"),
              ("Email", "t.brennan@mail.example"), ("Date of birth", "04/18/1961")]
    vf = s.font("courier", 13)
    for label, value in fields:
        s.d.rectangle((M, y, R, y + 110), outline=0, width=3)
        s.d.text((M + 20, y + 12), label, font=s.font("arial", 9), fill=0)
        s.d.text((M + 20, y + 50), value, font=vf, fill=0)
        s.lines.append(f"{label}  {value}")
        y += 130
    y += 30
    lf = s.font("arial", 11)
    for head, opts in (("Membership type", [("Single $25", True), ("Family $40", False), ("Student $10", False)]),
                       ("Interests", [("Vegetables", True), ("Fruit trees", True), ("Flowers", False), ("Bees", False)])):
        y = s.text(M, y, head, "arialb", 11, gap=1.6)
        x = M
        for label, on in opts:
            s.box(x, y + 2, tick=on)
            s.d.text((x + 70, y), label, font=lf, fill=0)
            x += 140 + lf.getlength(label)
        s.lines.append("  ".join(o for o, _ in opts))
        y += 110
    y = s.text(M, y, "How did you hear about us?", "arialb", 11, gap=1.5)
    s.d.text((M + 20, y), "Library notice board", font=vf, fill=0)
    s.lines.append("Library notice board")
    y += 130
    s.d.text((M, y), "Signature", font=lf, fill=0)
    s.d.text((1500, y), "Date", font=lf, fill=0)
    s.d.text((1650, y), "11/02/2026", font=vf, fill=0)
    s.lines.append("Signature  Date  11/02/2026")
    pts = [(M + 330 + i * 6, y + 30 - 28 * math.sin(i / 7.0) * math.cos(i / 23.0)) for i in range(150)]
    s.d.line(pts, fill=40, width=5)  # the signature squiggle, not in the truth
    s.d.line((M + 300, y + 70, 1400, y + 70), fill=0, width=2)
    y += 220
    s.d.rectangle((M, y, R, y + 150), fill=235, outline=0, width=2)
    s.d.text((M + 20, y + 15), "Office use only", font=s.font("arialb", 9), fill=0)
    s.d.text((M + 20, y + 70), "Paid: cash   Receipt no. 0447", font=lf, fill=0)
    s.lines += ["Office use only", "Paid: cash   Receipt no. 0447"]
    return [s]


RECEIPT = [("2 Latte large", 9.80), ("1 Pumpkin oat muffin", 3.75), ("1 Avocado toast", 11.50),
           ("1 Orange juice", 4.25), ("1 Extra shot", 0.90)]


def receipt():
    w = 945  # 3.15 in at 300 dpi
    s, L, R, y = Sheet(w, 2600), 50, w - 50, 60
    for t, f, pt in (("COPPERLEAF CAFE", "courierb", 11), ("140 Mill Street, Westbrook", "courier", 8),
                     ("Tel 555-0139", "courier", 8)):
        tw = s.font(f, pt).getlength(t)
        y = s.text((w - tw) / 2, y, t, f, pt)
    y += 30
    y = s.row(y, [(L, "11/20/2026", False), (R, "08:42", True)], "courier", 8, gap=1.5)
    y = s.text(L, y, "Order 1187  Table 6  Server: Mia", "courier", 8)
    s.d.line((L, y + 10, R, y + 10), fill=0, width=2)
    y += 40
    sub = 0.0
    for item, price in RECEIPT:
        sub += price
        y = s.row(y, [(L, item, False), (R, f"{price:.2f}", True)], "courier", 8, gap=1.5)
    tax = round(sub * 0.08 + 1e-9, 2)
    s.d.line((L, y + 10, R, y + 10), fill=0, width=2)
    y += 40
    for label, v, f in (("SUBTOTAL", sub, "courier"), ("TAX 8%", tax, "courier"), ("TOTAL", sub + tax, "courierb"),
                        ("VISA **** 4417", sub + tax, "courier")):
        y = s.row(y, [(L, label, False), (R, f"{v:.2f}", True)], f, 9 if f == "courierb" else 8, gap=1.5)
    y = s.text(L, y + 20, "AUTH 08812C", "courier", 8)
    for t in ("Thank you, see you soon!", "Free wifi: copperleaf-guest"):
        tw = s.font("courier", 8).getlength(t)
        y = s.text((w - tw) / 2, y + 20, t, "courier", 8)
    s.img = s.img.crop((0, 0, w, y + 120))
    return [s]


def report():
    pages = []
    texts = [
        ("1. Summary", [
            ("This year the co-op spent $48,210 on maintenance, against a budget of $52,000. The largest items were the "
            "new main valve in building B, roof repairs on building C, and the repainting of all stairwells."),
            ("We closed 131 repair requests from residents. The average time from request to repair was 6.4 days, down "
            "from 9.1 days in 2025."),
        ], "2. Buildings", [
            "Building A is in good condition. The windows on the north side will need new seals within two years.",
            ("Building B had three water leaks between August and October. All three came from the old main valve, "
            "which was replaced on December 2."),
            ("Building C had roof damage after the storm on March 8. A contractor replaced 40 square meters of roof "
            "felt and two gutters."),
        ]),
        ("4. Plans for 2027", [
            ("The committee proposes a budget of $55,000 for 2027. The main projects are new window seals in building "
            "A, a survey of the drains under the car park, and LED lights in all hallways."),
        ], None, None),
        ("5. Thank you", [
            ("Fourteen residents gave their time this year, from clearing gutters to painting the bike shed. Special "
            "thanks to the gardening group, who planted 60 bulbs along the front path."),
        ], "6. Questions", [
            ("Send questions about this report to maintenance@kilnyard.example before January 7, 2027, so that the "
            "committee can answer them at the meeting. Paper copies are at the office."),
            "Approved by the maintenance committee on December 10, 2026.",
        ]),
    ]
    spend = [("Plumbing", 12000, 14350), ("Roofs and gutters", 15000, 11980), ("Painting", 9000, 8640),
             ("Electrical", 6000, 4210), ("Grounds", 5000, 4930), ("Other", 5000, 4100)]
    for n, (h1, p1, h2, p2) in enumerate(texts, 1):
        s = Sheet()
        y = 230
        if n == 1:
            y = s.text(M, y, "Kiln Yard Housing Co-op", "georgiab", 22)
            y = s.text(M, y, "Annual maintenance report 2026", "georgia", 16)
            y = s.para(M, y + 20, "Prepared by the maintenance committee for the general meeting on January 14, 2027.",
                       "georgia", 11, W - 2 * M) + 40
        if n == 2:
            y = s.text(M, y, "3. Spending by category", "georgiab", 15, gap=1.8)
            cols = [(M + 10, False), (1500, True), (2000, True)]
            s.d.rectangle((M, y - 15, W - M, y + 60), fill=225)
            y = s.row(y, [(x, t, r) for (x, r), t in zip(cols, ("Category", "Budget", "Spent"))], "georgiab", 11)
            for cat, b, sp in spend + [("Total", sum(b for _, b, _ in spend), sum(x for _, _, x in spend))]:
                y = s.row(y, [(x, t, r) for (x, r), t in zip(cols, (cat, f"{b:,}", f"{sp:,}"))],
                          "georgiab" if cat == "Total" else "georgia", 11)
                s.rule(y - 20, shade=170, width=2)
            y = s.para(M, y + 40, "Plumbing went over budget because of the emergency valve repair. Roof spending was "
                       "lower than planned because insurance paid for part of the storm repair.", "georgia", 11,
                       W - 2 * M) + 40
        for h, ps in ((h1, p1), (h2, p2)):
            if not h:
                continue
            y = s.text(M, y + 20, h, "georgiab", 15, gap=1.6)
            for p in ps:
                y = s.para(M, y + 20, p, "georgia", 11, W - 2 * M)
            y += 40
        s.text(W // 2 - 120, H - 230, f"Page {n} of 3", "georgia", 10)
        pages.append(s)
    return pages


# ---------------------------------------------------------------- the scan kinds


def save(path, imgs, dpi, q=None):
    when = time.strptime("20261121", "%Y%m%d")  # fixed dates: the same bytes on every run
    kw = {"creationDate": when, "modDate": when, "title": Path(path).stem, "author": "Brasspage (made-up document, CC0)"}
    if len(imgs) > 1:
        kw |= {"save_all": True, "append_images": imgs[1:]}
    if q:
        kw["quality"] = q
    imgs[0].save(path, "PDF", dpi=dpi if isinstance(dpi, tuple) else (dpi, dpi), **kw)


def make(out):
    rng = np.random.default_rng(SEED)
    docs = {}

    def plain(sheets, dpi=300, q=75, **kw):
        imgs = []
        for s in sheets:
            img = scan(s.img, rng, **kw)
            if dpi != 300:
                img = img.resize((round(img.width * dpi / 300), round(img.height * dpi / 300)), Image.LANCZOS)
            imgs.append(img)
        return imgs, dpi, q

    # 01 a clean office scan: the control
    docs["01-letter"] = (letter(), "clean letter, 300 dpi gray", lambda sh: plain(sh, paper=248, ink=22))
    # 02 a table with rule lines and shaded header
    docs["02-invoice"] = (invoice(), "invoice table, 300 dpi gray", lambda sh: plain(sh))
    # 03 two columns: reading order matters
    docs["03-two-columns"] = (two_columns(), "two columns, 300 dpi gray", lambda sh: plain(sh))

    # 04 tilted 3.5 degrees counterclockwise
    def tilted(sh):
        s = sh[0]
        s.img = s.img.rotate(3.5, resample=Image.BICUBIC, fillcolor=255)
        return plain([s])

    docs["04-tilted"] = (memo(), "page tilted 3.5 degrees, 300 dpi gray", tilted)

    # 05 faded toner with a lighter vertical streak
    def faded(sh):
        s = sh[0]
        a = np.asarray(s.img.filter(ImageFilter.GaussianBlur(0.7)), np.float32) / 255.0
        x = np.arange(W, dtype=np.float32)
        ink = 168 + 35 * np.exp(-(((x - 1450) / 260) ** 2))  # streak: ink as light as 203 near x = 1450
        out = ink + (247 - ink) * a + rng.normal(0, 1.5, a.shape)
        return [Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))], 300, 75

    docs["05-faded"] = (notice(), "faded toner and a light streak, 300 dpi gray", faded)

    # 06 pen marks and highlighter, color scan
    def pen(sh):
        s = sh[0]
        img = scan(s.img, rng, paper=244, ink=28).convert("RGB")
        a = np.asarray(img, np.float32)
        bx = {t: b for t, b in zip(s.lines, s.boxes)}
        x0, y0, x1, y1 = bx["Next meeting: Thursday, December 17, at 7:00 pm."]
        a[y0 - 10 : y1 + 12, x0 - 10 : x1 + 10] *= np.array([1.0, 0.96, 0.45], np.float32)  # yellow highlighter
        img = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
        d, blue = ImageDraw.Draw(img), (35, 55, 160)
        x0, y0, x1, y1 = bx["6. New compost bins for the school garden (quote: $640)"]
        d.ellipse((x1 - 330, y0 - 25, x1 + 30, y1 + 30), outline=blue, width=7)  # circle round "(quote: $640)"
        x0, y0, x1, y1 = bx["4. Spring plant sale: dates, tables, and who brings the tent"]
        d.line([(x0 + 60 + i * 12, y1 + 12 + 4 * math.sin(i / 3)) for i in range(int((x1 - x0) / 12) - 4)], fill=blue, width=6)
        for t in ("1. Welcome and apologies", "2. Minutes of the October meeting", "3. Treasurer's report: balance $1,482.16"):
            x0, y0, x1, y1 = bx[t]
            d.line([(x0 - 140, (y0 + y1) / 2), (x0 - 110, y1), (x0 - 60, y0 - 10)], fill=blue, width=7)  # check marks
        x0, y0, x1, y1 = bx["5. Seed swap at the library in February"]
        cx, cy, r = x1 + 120, (y0 + y1) / 2, 45
        d.line([(cx + r * math.sin(k * 4 * math.pi / 5), cy - r * math.cos(k * 4 * math.pi / 5)) for k in range(6)], fill=blue, width=6)
        d.line([(W - 170 + 18 * math.sin(i / 2), 1100 + i * 8) for i in range(90)], fill=blue, width=5)  # margin scribble
        return [jpeg(img, 80)], 300, 80

    docs["06-pen-marks"] = (agenda(), "blue pen marks and highlighter, 300 dpi color", pen)

    # 07 a standard fax: 204 x 98 dpi, 1 bit, specks
    def faxed(sh):
        s = sh[0]
        img = scan(s.img, rng, paper=255, ink=0, noise=18, blur=1.0)
        img = img.resize((1728, 1078), Image.BILINEAR)
        a = np.asarray(img) < 140
        a ^= rng.random(a.shape) < 0.002  # specks and dropouts
        a[600:603, :] |= rng.random((3, 1728)) < 0.5  # a streak across the page
        return [Image.fromarray(~a).convert("1")], (204, 98), None

    docs["07-fax"] = (fax(), "fax, 204 x 98 dpi, black and white", faxed)

    # 08 a phone photo of the page on a table: perspective, warm light, shadow, JPEG
    def photo(sh):
        s = sh[0]
        page = scan(s.img, rng, paper=240, ink=35, noise=2, blur=0.9).convert("RGB")
        pw, ph = 1512, 2016
        dst = [(150, 170), (1390, 120), (1440, 1900), (95, 1950)]
        c = persp_coeffs([(0, 0), (W, 0), (W, H), (0, H)], dst)
        warped = page.transform((pw, ph), Image.PERSPECTIVE, c, Image.BICUBIC, fillcolor=(0, 0, 0))
        mask = Image.new("L", (W, H), 255).transform((pw, ph), Image.PERSPECTIVE, c, Image.BILINEAR, fillcolor=0)
        yy, xx = np.mgrid[0:ph, 0:pw].astype(np.float32)
        table = np.stack([118 + 20 * np.sin(xx / 37 + yy / 400), 88 + 14 * np.sin(xx / 37 + yy / 400), 62 + 8 * np.sin(xx / 37)], -1)
        light = 0.62 + 0.38 * np.clip(1 - ((xx - 1100) ** 2 + (yy - 300) ** 2) / 2.6e6, 0, 1)  # brighter top right
        light *= 1 - 0.28 * (1 / (1 + np.exp(-(xx + yy - 2700) / 90)))  # a soft shadow over the bottom left
        tint = np.array([1.0, 0.97, 0.9], np.float32)
        m = np.asarray(mask, np.float32)[..., None] / 255
        a = (np.asarray(warped, np.float32) * tint * m + table * (1 - m)) * light[..., None]
        img = Image.fromarray(np.clip(a + rng.normal(0, 4, a.shape), 0, 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.6))
        return [jpeg(img, 80)], 180, 80

    docs["08-phone-photo"] = (recipe(), "phone photo: angle, shadow, table", photo)
    # 09 7 pt print scanned at 200 dpi
    docs["09-small-print"] = (small_print(), "7 pt print at 200 dpi gray", lambda sh: plain(sh, dpi=200, q=80))
    # 10 a filled form with boxes, check boxes and a signature
    docs["10-form"] = (form(), "form with boxes and check boxes, 300 dpi gray", lambda sh: plain(sh))

    # 11 a thermal receipt that fades toward the bottom
    def thermal(sh):
        s = sh[0]
        a = np.asarray(s.img.filter(ImageFilter.GaussianBlur(0.9)), np.float32) / 255.0
        ink = np.linspace(60, 140, a.shape[0], dtype=np.float32)[:, None]
        out = ink + (236 - ink) * a + rng.normal(0, 4, a.shape)
        return [jpeg(Image.fromarray(np.clip(out, 0, 255).astype(np.uint8)), 80)], 300, 80

    docs["11-receipt"] = (receipt(), "thermal receipt, fading, 300 dpi gray", thermal)

    # 12 three pages at 200 dpi, page 3 upside down
    def three(sh):
        imgs, dpi, q = plain(sh, dpi=200, q=70)
        imgs[2] = imgs[2].rotate(180)
        return imgs, dpi, q

    docs["12-report-3-pages"] = (report(), "3 pages at 200 dpi, page 3 upside down", three)

    out.mkdir(parents=True, exist_ok=True)
    rows = []
    for name, (sheets, what, kind) in docs.items():
        imgs, dpi, q = kind(sheets)
        save(out / f"{name}.pdf", imgs, dpi, q)
        truth = "\f".join("\n".join(s.lines) for s in sheets) + "\n"
        (out / f"{name}.txt").write_text(truth)
        rows.append((name, what, len(sheets), len(truth.split()), (out / f"{name}.pdf").stat().st_size))
    for r in rows:
        print(f"{r[0]:20} {r[2]} page(s) {r[3]:4} words {r[4] // 1024:5} KB  {r[1]}")
    return rows


if __name__ == "__main__":
    make(Path(sys.argv[1]))
