#!/usr/bin/env python3
"""Document classification test harness for a lending packet: generate, OCR, classify, score.

  python3 doc_class_test.py generate DIR --seed 2026 --per-cell 15
  python3 doc_class_test.py ocr DIR
  python3 doc_class_test.py score DIR [--external predictions.csv]

Own documents: put images in DIR, write DIR/manifest.csv with columns
id,file,label (template, tier and hard may be left blank), then run ocr and score.
Writes DIR/ocr.json, DIR/pages.csv (one row per page, out-of-fold predictions)
and DIR/results.json (every figure used in the post).

Needs Python 3.9+, numpy, pillow and tesseract 5 on PATH. No scikit-learn: the
TF-IDF + logistic regression and naive Bayes baselines are written here.
All three classifiers are baselines written for this test. They are not any
vendor's product. To test a vendor, write its answers to a CSV with columns
id,label,confidence and pass it as --external; the scoring does not change.
"""
import argparse, csv, io, json, math, os, random, re, subprocess, sys, time
from collections import Counter, defaultdict
from multiprocessing import Pool
from pathlib import Path

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

CLASSES = ["invoice", "receipt", "bank_statement", "pay_stub", "tax_form", "id_card", "utility_bill", "other"]
TIERS = ["clean", "noise", "skew", "low"]
TEMPLATES = [0, 1, 2]
HARD_P = 0.30          # share of pages that use the confusable header variant of their class
CONT_P = 0.20          # share that are continuation pages: the header block is missing
CUT = {"invoice": 880, "receipt": 480, "bank_statement": 600, "pay_stub": 640, "tax_form": 330, "utility_bill": 600, "other": 400, "id_card": 0}
FOLDS = 5
DPI = 200
W, H = int(8.5 * DPI), int(11 * DPI)

# ------------------------------------------------------------------ fonts and canvas
FONT_DIRS = ["/System/Library/Fonts/Supplemental/", "/Library/Fonts/", "/usr/share/fonts/truetype/msttcorefonts/",
             "/usr/share/fonts/truetype/dejavu/", "C:/Windows/Fonts/"]
FONT_FILES = {"sans": ["Arial.ttf", "arial.ttf", "DejaVuSans.ttf"], "sansb": ["Arial Bold.ttf", "arialbd.ttf", "DejaVuSans-Bold.ttf"],
              "serif": ["Times New Roman.ttf", "times.ttf", "DejaVuSerif.ttf"], "serifb": ["Times New Roman Bold.ttf", "timesbd.ttf", "DejaVuSerif-Bold.ttf"],
              "mono": ["Courier New.ttf", "cour.ttf", "DejaVuSansMono.ttf"], "monob": ["Courier New Bold.ttf", "courbd.ttf", "DejaVuSansMono-Bold.ttf"],
              "geo": ["Georgia.ttf", "georgia.ttf", "DejaVuSerif.ttf"], "geob": ["Georgia Bold.ttf", "georgiab.ttf", "DejaVuSerif-Bold.ttf"],
              "verd": ["Verdana.ttf", "verdana.ttf", "DejaVuSans.ttf"], "verdb": ["Verdana Bold.ttf", "verdanab.ttf", "DejaVuSans-Bold.ttf"]}
_FC = {}


def font(name, pt):
    px = max(8, int(round(pt * DPI / 72)))
    key = (name, px)
    if key not in _FC:
        f = None
        for fn in FONT_FILES[name]:
            for d in FONT_DIRS:
                if os.path.exists(d + fn):
                    f = ImageFont.truetype(d + fn, px)
                    break
            if f:
                break
        _FC[key] = f or ImageFont.load_default(px)
    return _FC[key]


class Page:
    """A page that remembers every string drawn on it (the oracle text)."""

    def __init__(self):
        self.im = Image.new("L", (W, H), 255)
        self.d = ImageDraw.Draw(self.im)
        self.words = []
        self.ys = []

    def blank_above(self, y):
        """Continuation page: white out everything above y and forget those words."""
        if y > 0:
            self.d.rectangle((0, 0, W, y), fill=255)
            self.words = [w for w, yy in zip(self.words, self.ys) if yy >= y]
            self.ys = [yy for yy in self.ys if yy >= y]

    def t(self, x, y, s, f="sans", pt=10, right=False, center=False):
        s = str(s)
        self.ys.append(y)
        fo = font(f, pt)
        w = self.d.textlength(s, font=fo)
        xx = x - w if right else (x - w / 2 if center else x)
        self.d.text((xx, y), s, font=fo, fill=0)
        self.words.append(s)

    def line(self, x1, y1, x2, y2, w=2):
        self.d.line((x1, y1, x2, y2), fill=0, width=w)

    def box(self, x1, y1, x2, y2, w=2):
        self.d.rectangle((x1, y1, x2, y2), outline=0, width=w)

    def fill(self, x1, y1, x2, y2, v=0):
        self.d.rectangle((x1, y1, x2, y2), fill=v)


def I(pt):
    return int(pt * DPI / 72)


# ------------------------------------------------------------------ content pools
CO1 = ["Northwind", "Alder", "Birch", "Cobalt", "Dunmore", "Everly", "Fairhaven", "Granite", "Harlow", "Ironbridge", "Juniper", "Kestrel", "Larkspur", "Mercer", "Norfolk", "Oakridge", "Pinecrest", "Quillon", "Ridgeway", "Stonebrook"]
CO2 = ["Supply Co.", "Logistics Ltd", "Industrial Inc.", "Office Goods", "Packaging LLC", "Tools and Parts", "Freight Services", "Foods Market", "Hardware"]
FIRST = ["Maria", "James", "Priya", "Daniel", "Aisha", "Tomas", "Grace", "Omar", "Elena", "Kevin", "Linh", "Robert", "Sofia", "Marcus", "Hannah", "Victor"]
LAST = ["Alvarez", "Brooks", "Chen", "Dawson", "Edwards", "Fischer", "Gupta", "Hughes", "Ibrahim", "Jensen", "Kowalski", "Lopez", "Morgan", "Nguyen", "Okafor", "Patel"]
STREET = ["Mill Road", "Station Lane", "Harbor Street", "Foundry Way", "Elm Avenue", "Canal Row", "Maple Drive", "Cedar Court"]
CITY = ["Springfield", "Riverton", "Lakeview", "Fairmont", "Ashland", "Brookline", "Glenwood", "Westbury"]
ST = ["CA", "TX", "NY", "OH", "WA", "IL", "FL", "GA"]
ITEMS = ["Thermal paper rolls", "Pipe fittings", "Label ribbon", "Safety gloves", "Pallet wrap", "Bearing set", "Cable ties", "Filter cartridges", "Hex bolts", "Storage bins", "Work lamps", "Drill bits", "Printer toner", "Copy paper", "Cleaning supplies"]
GROC = ["Whole milk", "Brown bread", "Eggs dozen", "Bananas", "Chicken breast", "Coffee beans", "Orange juice", "Pasta", "Tomatoes", "Cheddar", "Dish soap", "Batteries AA"]
MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
MERCH = ["POS DEBIT GROCERY", "ATM WITHDRAWAL", "ONLINE TRANSFER", "CHECK DEPOSIT", "UTILITY AUTOPAY", "FUEL STATION", "RESTAURANT", "PHARMACY", "INSURANCE PREMIUM", "RENT PAYMENT"]
PROSE = ("we would like to thank you for taking the time to meet with us last week and for the clear overview you gave of the project timeline "
         "the team has reviewed the points raised and agrees with most of them there are a few open questions about scope and about who will own the next "
         "steps please let us know a convenient time to talk again this month so that we can confirm the plan and share it with everyone involved "
         "in the meantime we will continue to gather the background material and prepare a short summary for the group").split()


def nm(r): return f"{r.choice(FIRST)} {r.choice(LAST)}"
def co(r): return f"{r.choice(CO1)} {r.choice(CO2)}"
def addr(r): return f"{r.randint(2, 980)} {r.choice(STREET)}, {r.choice(CITY)} {r.choice(ST)} {r.randint(10000, 99999)}"
def money(r, a, b): return f"{r.randint(a, b)}.{r.randint(0, 99):02d}"
def mdy(r): return f"{r.randint(1, 12):02d}/{r.randint(1, 28):02d}/2026"
def dmy(r): return f"{r.randint(1, 28)} {r.choice(MON)} 2026"
def acct(r): return "".join(str(r.randint(0, 9)) for _ in range(r.choice([8, 10])))
def fm(x): return f"{x:,.2f}"


def prose(r, n):
    out = []
    for _ in range(n):
        out.append(r.choice(PROSE))
    s = " ".join(out)
    return s[0].upper() + s[1:] + "."


def wrap(s, n):
    words, lines, cur = s.split(), [], ""
    for w in words:
        if len(cur) + len(w) + 1 > n:
            lines.append(cur)
            cur = w
        else:
            cur = (cur + " " + w).strip()
    return lines + [cur]


# ------------------------------------------------------------------ page templates: each returns a Page
def draw_invoice(r, tpl, hard):
    p = Page()
    f, fb = [("sans", "sansb"), ("serif", "serifb"), ("verd", "verdb")][tpl]
    vendor, no = co(r), f"{r.choice(['INV', 'BC', 'SI'])}-{r.randint(10000, 99999)}"
    x0 = 150
    p.t(x0, 150, vendor, fb, 20)
    p.t(x0, 150 + I(26), addr(r), f, 10)
    if hard:   # no big title word; looks like a shop slip
        p.t(W - 150, 160, f"Inv # {no}", f, 11, right=True)
    else:
        p.t(W - 150, 150, "INVOICE" if tpl != 1 else "Tax Invoice", fb, 26, right=True)
        p.t(W - 150, 150 + I(34), f"Invoice No: {no}", f, 11, right=True)
    p.t(W - 150, 150 + I(52), f"Date: {mdy(r) if tpl != 1 else dmy(r)}", f, 11, right=True)
    y = 520
    p.t(x0, y, "Bill To", fb, 11)
    p.t(x0, y + I(16), nm(r), f, 11)
    p.t(x0, y + I(30), addr(r), f, 10)
    if not hard or r.random() < 0.5:
        p.t(W - 150, y, f"PO Number: PO-{r.randint(10000, 99999)}", f, 11, right=True)
    if not hard:
        p.t(W - 150, y + I(16), f"Due Date: {mdy(r)}", f, 11, right=True)
        p.t(W - 150, y + I(32), "Terms: Net 30", f, 11, right=True)
    y = 900
    cols = [x0, 1000, 1250, W - 150]
    p.fill(x0, y, W - 150, y + 56, 215)
    for cx, lab, rt in [(cols[0] + 10, "Description", False), (cols[1], "Qty", True), (cols[2] + 100, "Unit price", True), (cols[3] - 10, "Amount", True)]:
        p.t(cx, y + 10, lab, fb, 11, right=rt)
    y += 70
    sub = 0.0
    for it in r.sample(ITEMS, r.randint(3, 9)):
        q, u = r.randint(1, 30), r.randint(300, 40000) / 100
        a = q * u
        sub += a
        p.t(cols[0] + 10, y, it, f, 11)
        p.t(cols[1], y, str(q), f, 11, right=True)
        p.t(cols[2] + 100, y, fm(u), f, 11, right=True)
        p.t(cols[3] - 10, y, fm(a), f, 11, right=True)
        y += 56
        if tpl == 0:
            p.line(x0, y - 8, W - 150, y - 8, 1)
    y += 30
    tax = sub * 0.08
    for lab, v in [("Subtotal", sub), ("Tax 8%", tax), ("Total Due" if not hard else "Total", sub + tax)]:
        p.t(1250 + 100 - 250, y, lab, fb if lab.startswith("Total") else f, 12)
        p.t(cols[3] - 10, y, fm(v), fb if lab.startswith("Total") else f, 12, right=True)
        y += 50
    if hard:
        p.t(x0, y + 60, "Thank you for your business.", f, 11)
    else:
        p.t(x0, y + 60, "Please remit payment within 30 days. Bank transfer details on request.", f, 10)
    return p


def draw_receipt(r, tpl, hard):
    p = Page()
    f, fb = [("mono", "monob"), ("sans", "sansb"), ("mono", "monob")][tpl]
    x0 = 330 if tpl != 1 else 200
    wd = 760
    cx = x0 + wd // 2
    store = co(r)
    y = 200
    if hard:
        p.t(cx, y, "TAX INVOICE / RECEIPT", fb, 13, center=True)
        y += 60
    p.t(cx, y, store.upper(), fb, 15, center=True)
    p.t(cx, y + 50, addr(r), f, 9, center=True)
    p.t(cx, y + 90, f"Tel {r.randint(200, 999)}-{r.randint(200, 999)}-{r.randint(1000, 9999)}", f, 9, center=True)
    y += 160
    p.t(x0, y, f"{mdy(r)}  {r.randint(8, 21):02d}:{r.randint(10, 59)}", f, 10)
    p.t(x0 + wd, y, f"Reg {r.randint(1, 9)}", f, 10, right=True)
    if hard:
        p.t(x0, y + 40, f"Invoice no {r.randint(100000, 999999)}", f, 10)
        y += 40
    y += 70
    tot = 0.0
    for it in r.sample(GROC + ITEMS, r.randint(3, 10)):
        v = r.randint(99, 3999) / 100
        qty = r.choice([1, 1, 1, 2, 3])
        tot += v * qty
        p.t(x0, y, (it if qty == 1 else f"{qty} x {it}")[:26], f, 10)
        p.t(x0 + wd, y, fm(v * qty), f, 10, right=True)
        y += 44
    y += 20
    p.line(x0, y, x0 + wd, y, 2)
    y += 20
    tax = tot * 0.07
    for lab, v in [("SUBTOTAL", tot), ("TAX", tax), ("TOTAL", tot + tax)]:
        p.t(x0, y, lab, fb, 11)
        p.t(x0 + wd, y, fm(v), fb, 11, right=True)
        y += 48
    y += 20
    p.t(x0, y, f"PAID BY {r.choice(['VISA', 'MASTERCARD', 'CASH', 'DEBIT'])} **** {r.randint(1000, 9999)}", f, 10)
    p.t(x0, y + 46, f"Trans # {r.randint(100000, 999999)}", f, 10)
    p.t(cx, y + 130, "THANK YOU FOR SHOPPING WITH US", fb, 10, center=True)
    p.t(cx, y + 176, "Keep this receipt for returns", f, 9, center=True)
    return p


def draw_bank(r, tpl, hard):
    p = Page()
    f, fb = [("sans", "sansb"), ("serif", "serifb"), ("verd", "verdb")][tpl]
    bank = f"{r.choice(CO1)} {r.choice(['Bank', 'Credit Union', 'Savings Bank', 'Trust'])}"
    x0 = 150
    p.fill(0, 0, W, 230, 40 if tpl == 0 else 230)
    p.d.text((x0, 80), bank, font=font(fb, 22), fill=255 if tpl == 0 else 0)
    p.words.append(bank)
    p.ys.append(80)
    p.t(W - 150, 120, "Account Summary" if hard else ("Account Statement" if tpl != 1 else "Statement of Account"), fb, 15, right=True)
    y = 300
    p.t(x0, y, nm(r), fb, 11)
    p.t(x0, y + I(15), addr(r), f, 10)
    start = f"{r.randint(1, 12):02d}/01/2026"
    p.t(W - 150, y, f"Account number: ****{r.randint(1000, 9999)}", f, 10, right=True)
    p.t(W - 150, y + I(15), f"Statement period: {start} to {start[:3]}30/2026" if False else f"Statement period {start} - {start[:3]}28/2026", f, 10, right=True)
    y += 160
    opening = r.randint(50000, 900000) / 100
    bal = opening
    p.t(x0, y, "Opening balance", f, 11)
    p.t(x0 + 520, y, fm(opening), fb, 11, right=True)
    y += 70
    cols = [x0, 400, 1000, 1250, W - 150]
    p.line(x0, y, W - 150, y, 2)
    for cx, lab, rt in [(cols[0], "Date", False), (cols[1], "Description", False), (cols[2] + 100, "Debit", True), (cols[3] + 100, "Credit", True), (cols[4], "Balance", True)]:
        p.t(cx, y + 10, lab, fb, 10, right=rt)
    y += 60
    p.line(x0, y, W - 150, y, 1)
    y += 14
    for i in range(r.randint(10, 20)):
        a = r.randint(500, 150000) / 100
        if r.random() < 0.2 or (hard and i == 2):
            desc, cred = ("PAYROLL DIRECT DEPOSIT " + r.choice(CO1).upper()), True
            a = r.randint(150000, 420000) / 100
        elif r.random() < 0.1:
            desc, cred = "TRANSFER FROM SAVINGS", True
        else:
            desc, cred = r.choice(MERCH), False
        bal += a if cred else -a
        p.t(cols[0], y, f"{r.randint(1, 12):02d}/{r.randint(1, 28):02d}", f, 10)
        p.t(cols[1], y, desc, f, 10)
        p.t(cols[3] + 100 if cred else cols[2] + 100, y, fm(a), f, 10, right=True)
        p.t(cols[4], y, fm(bal), f, 10, right=True)
        y += 48
        if y > H - 300:
            break
    y += 40
    p.t(x0, y, "Closing balance", fb, 11)
    p.t(x0 + 520, y, fm(bal), fb, 11, right=True)
    p.t(x0, H - 160, "Member FDIC. Questions about this statement? Call the number on your card.", f, 8)
    return p


def draw_stub(r, tpl, hard):
    p = Page()
    f, fb = [("sans", "sansb"), ("mono", "monob"), ("geo", "geob")][tpl]
    emp = co(r)
    x0 = 150
    p.t(x0, 150, emp, fb, 18)
    p.t(x0, 150 + I(24), addr(r), f, 10)
    title = "Statement" if hard else r.choice(["Earnings Statement", "Pay Stub", "Payslip"]) if tpl == 0 else ("Earnings Statement" if tpl == 1 else "Payslip")
    p.t(W - 150, 150, title, fb, 20, right=True)
    y = 420
    p.t(x0, y, f"Employee: {nm(r)}", f, 11)
    p.t(x0, y + I(15), f"Employee ID: {r.randint(1000, 99999)}", f, 10)
    d = r.randint(1, 12)
    p.t(W - 150, y, f"{'Period' if hard else 'Pay period'}: {d:02d}/01/2026 - {d:02d}/15/2026", f, 10, right=True)
    p.t(W - 150, y + I(15), f"{'Date' if hard else 'Pay date'}: {d:02d}/20/2026", f, 10, right=True)
    if hard:
        p.t(W - 150, y + I(30), f"Account ending {r.randint(1000, 9999)}", f, 10, right=True)
    y += 180
    p.fill(x0, y, W - 150, y + 56, 215)
    for cx, lab, rt in [(x0 + 10, "Earnings", False), (900, "Rate", True), (1100, "Hours", True), (1350, "Current", True), (W - 160, "YTD", True)]:
        p.t(cx, y + 10, lab, fb, 11, right=rt)
    y += 76
    rate = r.randint(1800, 6500) / 100
    hrs = r.choice([80, 80, 72, 86.5])
    gross = rate * hrs
    for lab, a in [("Regular", gross), ("Overtime", rate * 1.5 * r.randint(0, 6))]:
        p.t(x0 + 10, y, lab, f, 11)
        p.t(900, y, fm(rate), f, 11, right=True)
        p.t(1100, y, str(hrs), f, 11, right=True)
        p.t(1350, y, fm(a), f, 11, right=True)
        p.t(W - 160, y, fm(a * r.randint(3, 20)), f, 11, right=True)
        y += 52
    y += 40
    p.t(x0 + 10, y, "Deductions", fb, 11)
    y += 56
    ded = 0
    for lab, pc in [("Federal income tax", 0.12), ("Social Security", 0.062), ("Medicare", 0.0145), ("State tax", 0.04), ("401k", 0.05)]:
        a = gross * pc
        ded += a
        p.t(x0 + 10, y, lab, f, 11)
        p.t(1350, y, fm(a), f, 11, right=True)
        p.t(W - 160, y, fm(a * r.randint(3, 20)), f, 11, right=True)
        y += 52
    y += 40
    p.t(x0 + 10, y, "Gross pay", fb, 12)
    p.t(1350, y, fm(gross), fb, 12, right=True)
    p.t(x0 + 10, y + 56, "Net pay", fb, 12)
    p.t(1350, y + 56, fm(gross - ded), fb, 12, right=True)
    p.t(x0 + 10, y + 150, f"Direct deposit to account ****{r.randint(1000, 9999)}", f, 10)
    return p


def draw_tax(r, tpl, hard):
    p = Page()
    x0 = 150
    yr = 2025
    if tpl == 0:    # W-2 style grid
        if not hard:
            p.t(x0, 150, "Form W-2  Wage and Tax Statement", "sansb", 18)
            p.t(x0, 150 + I(24), f"Department of the Treasury  Internal Revenue Service    {yr}", "sans", 10)
        else:
            p.t(x0, 150, f"Copy B  To be filed with employee's federal tax return    {yr}", "sans", 11)
        labs = ["a Employee's social security number", "b Employer identification number (EIN)", "c Employer's name, address, and ZIP code",
                "1 Wages, tips, other compensation", "2 Federal income tax withheld", "3 Social security wages", "4 Social security tax withheld",
                "5 Medicare wages and tips", "6 Medicare tax withheld", "e Employee's first name and initial   Last name", "15 State   Employer's state ID number",
                "16 State wages, tips, etc.", "17 State income tax"]
        y = 330
        for i, lab in enumerate(labs):
            cx = x0 + (i % 2) * 760
            yy = y + (i // 2) * 190
            p.box(cx, yy, cx + 740, yy + 170, 2)
            p.t(cx + 12, yy + 10, lab, "sans", 8)
            val = f"{r.randint(100, 999)}-{r.randint(10, 99)}-{r.randint(1000, 9999)}" if i == 0 else (f"{r.randint(10, 99)}-{r.randint(1000000, 9999999)}" if i == 1 else (co(r) if i == 2 else (nm(r) if i == 9 else money(r, 1000, 95000))))
            p.t(cx + 30, yy + 90, val, "mono", 12)
    elif tpl == 1:  # 1099-NEC style
        if not hard:
            p.t(x0, 150, f"Form 1099-NEC  Nonemployee Compensation   {yr}", "sansb", 18)
            p.t(x0, 150 + I(24), "Department of the Treasury  Internal Revenue Service", "sans", 10)
        else:
            p.t(x0, 150, f"Copy 1  For state tax department    {yr}", "sans", 11)
        y = 330
        for i, (lab, v) in enumerate([("PAYER'S name, street address, city, state, ZIP code", co(r)), ("PAYER'S TIN", f"{r.randint(10, 99)}-{r.randint(1000000, 9999999)}"),
                                      ("RECIPIENT'S TIN", f"{r.randint(100, 999)}-{r.randint(10, 99)}-{r.randint(1000, 9999)}"), ("RECIPIENT'S name", nm(r)),
                                      ("1 Nonemployee compensation", "$ " + money(r, 2000, 90000)), ("4 Federal income tax withheld", "$ " + money(r, 0, 5000)),
                                      ("5 State tax withheld", "$ " + money(r, 0, 3000)), ("Account number (see instructions)", acct(r))]):
            yy = y + i * 190
            p.box(x0, yy, W - 150, yy + 170, 2)
            p.t(x0 + 12, yy + 10, lab, "sans", 8)
            p.t(x0 + 30, yy + 90, v, "mono", 12)
    else:           # 1040 summary lines
        if not hard:
            p.t(x0, 150, f"Form 1040  U.S. Individual Income Tax Return   {yr}", "sansb", 17)
        else:
            p.t(x0, 150, f"Page 2   {yr}", "sans", 12)
        p.t(x0, 150 + I(26), f"Filing status: {r.choice(['Single', 'Married filing jointly', 'Head of household'])}", "sans", 11)
        p.t(x0, 150 + I(42), f"Your social security number {r.randint(100, 999)}-{r.randint(10, 99)}-{r.randint(1000, 9999)}", "sans", 11)
        y = 420
        for lab in ["1a Total amount from Form(s) W-2, box 1", "2b Taxable interest", "3b Ordinary dividends", "9 Total income", "11 Adjusted gross income",
                    "12 Standard deduction or itemized deductions", "15 Taxable income", "16 Tax", "24 Total tax", "25a Federal income tax withheld from Form(s) W-2",
                    "33 Total payments", "34 Amount you overpaid"]:
            p.t(x0, y, lab, "sans", 11)
            p.t(W - 150, y, money(r, 0, 120000), "mono", 11, right=True)
            p.line(x0, y + 44, W - 150, y + 44, 1)
            y += 100
        p.t(x0, y + 30, "Sign here. Under penalties of perjury, I declare that I have examined this return.", "sans", 9)
    return p


def draw_id(r, tpl, hard):
    p = Page()
    cw, ch = 1020, 640
    x0, y0 = 340 + r.randint(-60, 60), 500 + r.randint(-80, 120)
    p.box(x0, y0, x0 + cw, y0 + ch, 4)
    state = r.choice(["California", "Texas", "New York", "Ohio", "Washington", "Illinois"])
    if tpl == 0:
        p.fill(x0 + 4, y0 + 4, x0 + cw - 4, y0 + 90, 200)
        if hard:   # back side: barcode and restrictions
            p.t(x0 + 30, y0 + 20, f"{state.upper()}", "sansb", 14)
            for i in range(60):
                xx = x0 + 40 + i * 15
                p.fill(xx, y0 + 130, xx + r.choice([3, 6, 9]), y0 + 330, 0)
            p.t(x0 + 40, y0 + 370, f"RESTRICTIONS NONE   ENDORSEMENTS NONE", "sans", 8)
            p.t(x0 + 40, y0 + 420, f"ORGAN DONOR   {r.randint(1000, 9999)}-{r.randint(1000, 9999)}", "sans", 8)
        else:
            p.t(x0 + 30, y0 + 20, f"{state.upper()}  DRIVER LICENSE", "sansb", 14)
            p.box(x0 + 30, y0 + 130, x0 + 300, y0 + 470, 2)
            p.t(x0 + 165, y0 + 280, "PHOTO", "sans", 10, center=True)
            n = nm(r).split()
            for i, (lab, v) in enumerate([("DL", f"{r.choice('ABCD')}{r.randint(1000000, 9999999)}"), ("LN", n[1].upper()), ("FN", n[0].upper()),
                                          ("DOB", mdy(r).replace("/2026", f"/{r.randint(1950, 2002)}")), ("EXP", mdy(r).replace("/2026", "/2030")), ("CLASS", "C"), ("SEX", r.choice("MF")),
                                          ("HGT", f"{r.randint(5, 6)}-{r.randint(0, 11):02d}"), ("EYES", r.choice(["BRN", "BLU", "GRN"]))]):
                p.t(x0 + 340, y0 + 110 + i * 46, f"{lab} {v}", "sansb" if i < 3 else "sans", 9)
            p.t(x0 + 30, y0 + 520, addr(r)[:40], "sans", 8)
    elif tpl == 1:
        p.t(x0 + 30, y0 + 20, f"{state.upper()} IDENTIFICATION CARD", "serifb", 13)
        p.t(x0 + cw - 30, y0 + 20, "NOT A DRIVER LICENSE" if not hard else "", "serif", 8, right=True)
        p.box(x0 + cw - 330, y0 + 110, x0 + cw - 30, y0 + 450, 2)
        n = nm(r).split()
        for i, (lab, v) in enumerate([("ID NO", f"{r.randint(10000000, 99999999)}"), ("NAME", f"{n[1].upper()}, {n[0].upper()}"), ("DOB", mdy(r).replace("/2026", "/1988")), ("ISSUED", mdy(r)), ("EXPIRES", mdy(r).replace("/2026", "/2031")), ("ADDRESS", addr(r)[:34])]):
            p.t(x0 + 30, y0 + 120 + i * 70, f"{lab}: {v}", "serif", 10)
        p.t(x0 + 30, y0 + 560, "Signature: ______________", "serif", 9)
    else:
        p.t(x0 + 30, y0 + 20, "PASSPORT   P   USA   United States of America", "sansb", 11)
        n = nm(r).split()
        for i, (lab, v) in enumerate([("Surname", n[1].upper()), ("Given names", n[0].upper()), ("Nationality", "UNITED STATES OF AMERICA"), ("Date of birth", dmy(r).replace("2026", "1985")), ("Place of birth", r.choice(CITY).upper()), ("Date of issue", dmy(r)), ("Date of expiry", dmy(r).replace("2026", "2034"))]):
            p.t(x0 + 330, y0 + 90 + i * 62, lab, "sans", 7)
            p.t(x0 + 330, y0 + 90 + i * 62 + 22, v, "sansb", 9)
        p.box(x0 + 30, y0 + 100, x0 + 300, y0 + 450, 2)
        if not hard:
            p.t(x0 + 30, y0 + 540, f"P<USA{n[1].upper()}<<{n[0].upper()}<<<<<<<<<<<<<<<", "mono", 8)
            p.t(x0 + 30, y0 + 580, f"{r.randint(100000000, 999999999)}<0USA{r.randint(100000, 999999)}<<<<<<<<<<<<<<04", "mono", 8)
    return p


def draw_utility(r, tpl, hard):
    p = Page()
    f, fb = [("sans", "sansb"), ("verd", "verdb"), ("serif", "serifb")][tpl]
    kind = r.choice(["Power and Light", "Water Services", "Gas Company", "Electric Cooperative"])
    util = f"{r.choice(CITY)} {kind}"
    x0 = 150
    p.t(x0, 150, util, fb, 19)
    if hard:   # titled like an invoice
        p.t(W - 150, 150, "Customer Invoice", fb, 18, right=True)
        p.t(W - 150, 150 + I(24), f"Invoice number {r.randint(100000, 999999)}", f, 10, right=True)
    else:
        p.t(W - 150, 150, "Your Monthly Bill" if tpl != 2 else "Billing Statement", fb, 18, right=True)
    y = 380
    p.t(x0, y, nm(r), fb, 11)
    p.t(x0, y + I(15), f"Service address: {addr(r)}", f, 10)
    p.t(W - 150, y, f"Account number: {acct(r)}", f, 10, right=True)
    p.t(W - 150, y + I(32), f"Billing period: {mdy(r)} to {mdy(r)}", f, 10, right=True)
    y += 190
    unit = "kWh" if "Power" in kind or "Electric" in kind else ("CCF" if "Gas" in kind else "gallons")
    p.t(x0, y, f"Meter number {r.randint(10000, 99999)}   Previous read {r.randint(1000, 50000)}   Current read {r.randint(50001, 90000)}", f, 10)
    p.t(x0, y + I(16), f"Usage this period: {r.randint(200, 2400)} {unit}", fb, 11)
    y += 130
    tot = 0.0
    for lab in ["Usage charge", "Delivery charge", "Service fee", "Taxes and surcharges"]:
        v = r.randint(400, 9000) / 100
        tot += v
        p.t(x0, y, lab, f, 11)
        p.t(W - 150, y, fm(v), f, 11, right=True)
        y += 56
    y += 30
    p.line(x0, y, W - 150, y, 2)
    p.t(x0, y + 24, "Total amount due" if not hard else "Total", fb, 13)
    p.t(W - 150, y + 24, "$" + fm(tot), fb, 13, right=True)
    p.t(x0, y + 100, f"Due date: {mdy(r)}", f, 11)
    p.t(x0, y + 150, "Pay online or by phone. Late payments may incur a fee. Call us about payment plans.", f, 9)
    if hard:
        p.t(x0, y + 200, "Past due balance 0.00", f, 9)
    return p


def draw_other(r, tpl, hard):
    p = Page()
    x0 = 170
    if tpl == 0:    # cover letter
        p.t(x0, 160, co(r), "serifb", 16)
        p.t(x0, 160 + I(22), addr(r), "serif", 10)
        p.t(x0, 420, dmy(r), "serif", 11)
        p.t(x0, 500, f"Dear {nm(r)},", "serif", 12)
        y = 600
        txt = prose(r, 150)
        if hard:
            txt += " The invoice and the latest bank statement are attached for your records. Payment is due on receipt."
        for ln in wrap(txt, 78):
            p.t(x0, y, ln, "serif", 12)
            y += 56
        p.t(x0, y + 60, "Sincerely,", "serif", 12)
        p.t(x0, y + 140, nm(r), "serif", 12)
    elif tpl == 1:  # meeting agenda
        p.t(x0, 160, "Team meeting agenda", "sansb", 20)
        p.t(x0, 160 + I(30), f"Date {mdy(r)}   Room {r.randint(1, 40)}", "sans", 11)
        y = 420
        for i, it in enumerate(["Welcome and notes from last time", "Project status and blockers", "Budget and payment schedule" if hard else "Hiring plan", "Open questions", "Next steps and owners"]):
            p.t(x0, y, f"{i + 1}. {it}", "sans", 13)
            p.t(W - 170, y, f"{r.randint(5, 20)} min", "sans", 11, right=True)
            y += 100
        for ln in wrap(prose(r, 60), 80):
            p.t(x0, y + 40, ln, "sans", 11)
            y += 52
    elif tpl == 2:  # marketing flyer
        p.fill(0, 0, W, 520, 60)
        p.d.text((200, 160), "GRAND SALE", font=font("sansb", 56), fill=255)
        p.words.append("GRAND SALE")
        p.ys.append(160)
        p.t(200, 650, f"Up to {r.choice([30, 40, 50, 60])}% off everything" + (" including invoices and statements software" if hard else ""), "sansb", 22)
        y = 800
        for ln in wrap(prose(r, 50), 60):
            p.t(200, y, ln, "sans", 15)
            y += 70
        p.t(200, y + 80, f"Visit us at {addr(r)}", "sansb", 14)
        p.t(200, y + 150, "Offer ends soon. Terms apply.", "sans", 10)
    else:           # lease-style contract page or near-blank fax sheet
        if r.random() < 0.5:
            p.t(x0, 160, "Fax cover sheet", "sansb", 20)
            p.t(x0, 420, f"To: {nm(r)}", "sans", 13)
            p.t(x0, 500, f"From: {nm(r)}", "sans", 13)
            p.t(x0, 580, f"Pages: {r.randint(1, 12)}", "sans", 13)
            p.t(x0, 660, "Comments: " + ("see payment attached" if hard else "please call me back"), "sans", 13)
        else:
            p.t(x0, 160, f"{r.randint(1, 20)}. General terms", "serifb", 14)
            y = 300
            for _ in range(3):
                for ln in wrap(prose(r, 70), 80):
                    p.t(x0, y, ln, "serif", 11)
                    y += 50
                y += 40
    return p


DRAW = {"invoice": draw_invoice, "receipt": draw_receipt, "bank_statement": draw_bank, "pay_stub": draw_stub,
        "tax_form": draw_tax, "id_card": draw_id, "utility_bill": draw_utility, "other": draw_other}


# ------------------------------------------------------------------ degradation
def degrade(im, tier, nr):
    a = np.asarray(im, dtype=np.float32)
    if tier == "clean":
        return im, DPI
    if tier == "noise":
        img = im.filter(ImageFilter.GaussianBlur(1.0))
        a = np.asarray(img, dtype=np.float32) * 0.92 + 12
        a += nr.normal(0, 28, a.shape)
        m = nr.random(a.shape)
        a[m < 0.004] = 0
        a[m > 0.996] = 255
        return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)), DPI
    if tier == "skew":
        ang = nr.uniform(1.5, 3.5) * nr.choice([-1, 1])
        img = im.rotate(ang, resample=Image.BICUBIC, expand=False, fillcolor=255).filter(ImageFilter.GaussianBlur(0.6))
        a = np.asarray(img, dtype=np.float32) + nr.normal(0, 9, (H, W))
        return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)), DPI
    img = im.filter(ImageFilter.GaussianBlur(1.2)).resize((W * 3 // 8, H * 3 // 8), Image.BILINEAR)
    a = np.asarray(img, dtype=np.float32) * 0.93 + 10 + nr.normal(0, 18, (H * 3 // 8, W * 3 // 8))
    img = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
    buf = io.BytesIO()
    img.save(buf, "JPEG", quality=35)
    return Image.open(io.BytesIO(buf.getvalue())).convert("L"), DPI * 3 // 8


def generate(a):
    out = Path(a.dir)
    (out / "img").mkdir(parents=True, exist_ok=True)
    rows = []
    n = 0
    for ci, cl in enumerate(CLASSES):
        for ti, tier in enumerate(TIERS):
            for k in range(a.per_cell):
                seed = a.seed * 100000 + ci * 10000 + ti * 1000 + k
                r = random.Random(seed)
                nr = np.random.RandomState(seed % (2 ** 31))
                tpl = k % 3
                u = r.random()
                hard = 1 if u < HARD_P else (2 if u < HARD_P + CONT_P and CUT[cl] else 0)
                page = DRAW[cl](r, tpl, 1 if hard == 1 else 0)
                if hard == 2:
                    page.blank_above(CUT[cl])
                img, dpi = degrade(page.im, tier, nr)
                ext = "jpg" if tier == "low" else "png"
                fn = f"img/p{n:04d}.{ext}"
                if ext == "jpg":
                    img.save(out / fn, "JPEG", quality=85, dpi=(dpi, dpi))
                else:
                    img.save(out / fn, dpi=(dpi, dpi))
                rows.append({"id": f"p{n:04d}", "file": fn, "label": cl, "template": tpl, "tier": tier, "hard": hard, "dpi": dpi, "oracle": " ".join(page.words)})
                n += 1
    with open(out / "manifest.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)
    print("generated", n, "pages in", out)


# ------------------------------------------------------------------ OCR
def tess(args):
    path, dpi = args
    env = dict(os.environ, OMP_THREAD_LIMIT="1")
    t0 = time.time()
    p = subprocess.run(["tesseract", str(path), "stdout", "--psm", "3", "--dpi", str(dpi), "tsv"], capture_output=True, text=True, env=env)
    words, confs = [], []
    for ln in p.stdout.splitlines()[1:]:
        c = ln.split("\t")
        if len(c) >= 12 and c[0] == "5" and c[11].strip():
            words.append(c[11])
            try:
                confs.append(float(c[10]))
            except ValueError:
                pass
    return {"text": " ".join(words), "n_words": len(words), "mean_conf": round(float(np.mean(confs)), 1) if confs else 0.0, "seconds": round(time.time() - t0, 3)}


def read_manifest(d):
    with open(Path(d) / "manifest.csv", newline="") as fh:
        rows = list(csv.DictReader(fh))
    for r in rows:
        r.setdefault("template", "")
        r.setdefault("tier", "")
        r.setdefault("hard", "")
        r.setdefault("oracle", "")
        r["tier"] = r["tier"] or "na"
        r["hard"] = r["hard"] or "na"
    return rows


def run_ocr(a):
    d = Path(a.dir)
    rows = read_manifest(d)
    jobs = [(d / r["file"], int(r.get("dpi") or DPI)) for r in rows]
    with Pool(a.procs) as pool:
        res = pool.map(tess, jobs, chunksize=4)
    ver = subprocess.run(["tesseract", "--version"], capture_output=True, text=True).stdout.splitlines()[0]
    json.dump({"tesseract": ver, "pages": {r["id"]: x for r, x in zip(rows, res)}}, open(d / "ocr.json", "w"))
    print("ocr done", len(res), ver)


# ------------------------------------------------------------------ text features
def toks(text):
    t = re.sub(r"\d+", "0", text.lower())
    return re.findall(r"[a-z0]{2,}", t)


def grams(text):
    w = toks(text)
    return w + [w[i] + "_" + w[i + 1] for i in range(len(w) - 1)]


class Tfidf:
    def __init__(self, min_df=2):
        self.min_df = min_df

    def fit(self, docs):
        df = Counter()
        for d in docs:
            df.update(set(grams(d)))
        self.vocab = {t: i for i, t in enumerate(sorted(t for t, c in df.items() if c >= self.min_df))}
        n = len(docs)
        self.idf = np.zeros(len(self.vocab))
        for t, i in self.vocab.items():
            self.idf[i] = math.log((1 + n) / (1 + df[t])) + 1
        return self

    def counts(self, docs):
        X = np.zeros((len(docs), len(self.vocab)))
        for i, d in enumerate(docs):
            for t, c in Counter(grams(d)).items():
                j = self.vocab.get(t)
                if j is not None:
                    X[i, j] = c
        return X

    def transform(self, docs):
        X = self.counts(docs)
        X = np.where(X > 0, 1 + np.log(np.maximum(X, 1)), 0) * self.idf
        nrm = np.linalg.norm(X, axis=1, keepdims=True)
        return X / np.maximum(nrm, 1e-9)


def softmax(z):
    z = z - z.max(1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(1, keepdims=True)


class LogReg:
    """Multinomial logistic regression on TF-IDF, L2, full-batch Adam, fixed 300 steps."""

    def __init__(self, lam=1e-4, steps=300, lr=0.1):
        self.lam, self.steps, self.lr = lam, steps, lr

    def fit(self, docs, y):
        self.tf = Tfidf().fit(docs)
        X = self.tf.transform(docs)
        Y = np.eye(len(CLASSES))[y]
        n, d = X.shape
        Wt = np.zeros((d, len(CLASSES)))
        b = np.zeros(len(CLASSES))
        m = np.zeros_like(Wt); v = np.zeros_like(Wt); mb = np.zeros_like(b); vb = np.zeros_like(b)
        for s in range(1, self.steps + 1):
            P = softmax(X @ Wt + b)
            G = X.T @ (P - Y) / n + self.lam * Wt
            gb = (P - Y).mean(0)
            for (p_, g_, m_, v_) in ((Wt, G, m, v), (b, gb, mb, vb)):
                m_ *= 0.9; m_ += 0.1 * g_
                v_ *= 0.999; v_ += 0.001 * g_ * g_
                p_ -= self.lr * (m_ / (1 - 0.9 ** s)) / (np.sqrt(v_ / (1 - 0.999 ** s)) + 1e-8)
        self.W, self.b = Wt, b
        return self

    def proba(self, docs):
        return softmax(self.tf.transform(docs) @ self.W + self.b)


class NB:
    """Multinomial naive Bayes on word counts, add 0.5 smoothing."""

    def fit(self, docs, y, alpha=0.5):
        self.tf = Tfidf(min_df=2).fit(docs)
        X = self.tf.counts(docs)
        y = np.asarray(y)
        self.logp = np.zeros((len(CLASSES), X.shape[1]))
        self.prior = np.zeros(len(CLASSES))
        for c in range(len(CLASSES)):
            xc = X[y == c]
            self.prior[c] = math.log((len(xc) + 1) / (len(y) + len(CLASSES)))
            s = xc.sum(0) + alpha
            self.logp[c] = np.log(s / s.sum())
        return self

    def proba(self, docs):
        return softmax(self.tf.counts(docs) @ self.logp.T + self.prior)


# keyword rules, written by hand and frozen on a development set (seed 1) before the test set was generated
RULES = {
    "invoice": [(r"\binvoice\b", 2), (r"bill to", 2), (r"due date", 2), (r"net 30", 2), (r"po number", 2), (r"unit price", 1.5), (r"\bqty\b", 1), (r"amount", .5), (r"total due", 1), (r"remit", 1.5), (r"terms", 1), (r"thank you for your business", .5)],
    "receipt": [(r"receipt", 3), (r"paid by", 2.5), (r"visa|mastercard|debit|cash", 1), (r"trans\b", 1.5), (r"thank you for shopping", 3), (r"returns", 1.5), (r"\breg\b", 1.5), (r"subtotal", .5), (r"\btel\b", 1)],
    "bank_statement": [(r"opening balance", 3), (r"closing balance", 3), (r"statement period", 2), (r"account statement|statement of account", 2), (r"\bdebit\b", 1), (r"\bcredit\b", .5), (r"\bbalance\b", 1), (r"\bfdic\b", 2), (r"account summary", 2), (r"bank|credit union|trust", 1), (r"atm|pos debit|transfer", 1)],
    "pay_stub": [(r"earnings", 2.5), (r"pay stub|payslip", 3), (r"pay period", 2.5), (r"pay date", 2), (r"gross pay", 2.5), (r"net pay", 2.5), (r"\bytd\b", 2), (r"deductions", 2), (r"federal income tax", 1), (r"medicare", 1.5), (r"social security", 1), (r"employee", 1.5), (r"401k", 1.5)],
    "tax_form": [(r"internal revenue", 3), (r"\bform w", 3), (r"1099", 3), (r"1040", 3), (r"employer identification", 2.5), (r"withheld", 1.5), (r"wages, tips", 3), (r"filing status", 2.5), (r"taxable income", 2), (r"\btin\b", 2), (r"nonemployee", 3), (r"copy [b1]", 2), (r"treasury", 2), (r"adjusted gross", 2.5)],
    "id_card": [(r"driver", 2.5), (r"license", 2.5), (r"identification card", 3), (r"passport", 3), (r"\bdob\b|date of birth", 2), (r"\bexp\b|expires|date of expiry", 1.5), (r"\bsex\b", 1.5), (r"\bhgt\b", 2), (r"eyes", 2), (r"nationality", 2), (r"organ donor|restrictions|endorsements", 2.5), (r"surname|given names", 2), (r"signature", .5), (r"p<usa", 3)],
    "utility_bill": [(r"kwh|ccf|gallons", 3), (r"meter", 3), (r"service address", 3), (r"billing period", 3), (r"usage", 2), (r"power and light|water services|gas company|electric cooperative", 3), (r"delivery charge", 2.5), (r"amount due", 1), (r"account number", 1), (r"late payments", 2), (r"monthly bill|billing statement", 2), (r"past due", 1)],
}


def rule_scores(text):
    t = text.lower()
    return np.array([sum(w for pat, w in RULES.get(c, []) if re.search(pat, t)) for c in CLASSES])


def rules_proba(docs, min_top=2.0):
    """Hand rules. Confidence is top / (top + second + 1); below min_top points the answer is 'other'."""
    P = np.zeros((len(docs), len(CLASSES)))
    for i, d in enumerate(docs):
        s = rule_scores(d)
        o = np.argsort(-s)
        top, sec = s[o[0]], s[o[1]]
        if top < min_top:
            P[i, CLASSES.index("other")] = 0.5 if top == 0 else 0.5 + 0.1 * top
            P[i] += 0.01
            continue
        conf = top / (top + sec + 1)
        P[i] = (1 - conf) / (len(CLASSES) - 1)
        P[i, o[0]] = conf
    return P / P.sum(1, keepdims=True)


# ------------------------------------------------------------------ metrics
def wilson(k, n, z=1.96):
    if n == 0:
        return (0.0, 0.0)
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return (round(max(0.0, 100 * (c - h)), 1), round(min(100.0, 100 * (c + h)), 1))


def pct(k, n):
    return round(100 * k / n, 1) if n else None


def confusion(y, p):
    M = np.zeros((len(CLASSES), len(CLASSES)), dtype=int)
    for a_, b_ in zip(y, p):
        M[a_, b_] += 1
    return M


def per_class(M):
    out = {}
    for i, c in enumerate(CLASSES):
        tp = M[i, i]
        pr = tp / M[:, i].sum() if M[:, i].sum() else 0
        rc = tp / M[i].sum() if M[i].sum() else 0
        out[c] = {"n": int(M[i].sum()), "precision": round(100 * pr, 1), "recall": round(100 * rc, 1), "f1": round(100 * (2 * pr * rc / (pr + rc) if pr + rc else 0), 1)}
    return out


def folds_for(rows, seed):
    """Stratified by class x tier so every fold has the same mix."""
    rnd = random.Random(seed)
    g = defaultdict(list)
    for i, r in enumerate(rows):
        g[(r["label"], r["tier"])].append(i)
    f = [0] * len(rows)
    for k in sorted(g):
        idx = g[k][:]
        rnd.shuffle(idx)
        for j, i in enumerate(idx):
            f[i] = j % FOLDS
    return np.array(f)


def fit_predict(kind, tr_docs, tr_y, te_docs):
    if kind == "rules":
        return rules_proba(te_docs)
    m = LogReg().fit(tr_docs, tr_y) if kind == "tfidf_lr" else NB().fit(tr_docs, tr_y)
    return m.proba(te_docs)


def crossval(kind, docs, y, fold):
    P = np.zeros((len(docs), len(CLASSES)))
    for f in range(FOLDS):
        tr = np.where(fold != f)[0]
        te = np.where(fold == f)[0]
        P[te] = fit_predict(kind, [docs[i] for i in tr], y[tr], [docs[i] for i in te])
    return P


def sweep(P, y, thr):
    pred, conf = P.argmax(1), P.max(1)
    out = []
    for t in thr:
        acc = conf >= t
        n = int(acc.sum())
        err = int(((pred != y) & acc).sum())
        junk = int(((y == CLASSES.index("other")) & acc & (pred != y)).sum())
        out.append({"threshold": t, "auto": n, "auto_pct": pct(n, len(y)), "review_pct": pct(len(y) - n, len(y)), "errors_in_auto": err,
                    "auto_error_pct": pct(err, n), "auto_error_ci": wilson(err, n), "errors_caught_pct": pct(int((pred != y).sum()) - err, int((pred != y).sum())), "junk_accepted_as_class": junk})
    return out


def score(a):
    d = Path(a.dir)
    rows = read_manifest(d)
    ocr = json.load(open(d / "ocr.json"))
    ids = [r["id"] for r in rows]
    docs = [ocr["pages"][i]["text"] for i in ids]
    y = np.array([CLASSES.index(r["label"]) for r in rows])
    tier = np.array([r["tier"] for r in rows])
    tpl = np.array([r["template"] for r in rows])
    hard = np.array([r["hard"] for r in rows])
    fold = folds_for(rows, a.seed)
    res = {"n_pages": len(rows), "tesseract": ocr["tesseract"], "numpy": np.__version__, "python": sys.version.split()[0], "folds": FOLDS,
           "class_counts": {c: int((y == i).sum()) for i, c in enumerate(CLASSES)}}
    kinds = ["rules", "tfidf_lr", "naive_bayes"]
    kmap = {"rules": "rules", "tfidf_lr": "tfidf_lr", "naive_bayes": "nb"}
    P = {k: crossval(kmap[k], docs, y, fold) for k in kinds}
    if a.external:
        ext = {r["id"]: r for r in csv.DictReader(open(a.external))}
        Pe = np.full((len(rows), len(CLASSES)), 0.0)
        for i, rid in enumerate(ids):
            c = float(ext[rid]["confidence"])
            Pe[i] = (1 - c) / (len(CLASSES) - 1)
            Pe[i, CLASSES.index(ext[rid]["label"])] = c
        P["external"] = Pe
    res["overall"], res["per_class"], res["confusion"], res["by_tier"], res["by_hard"] = {}, {}, {}, {}, {}
    for k, Pk in P.items():
        pred = Pk.argmax(1)
        ok = int((pred == y).sum())
        res["overall"][k] = {"correct": ok, "n": len(y), "acc": pct(ok, len(y)), "ci": wilson(ok, len(y))}
        M = confusion(y, pred)
        res["confusion"][k] = M.tolist()
        res["per_class"][k] = per_class(M)
        res["by_tier"][k] = {t: {"n": int((tier == t).sum()), "acc": pct(int(((pred == y) & (tier == t)).sum()), int((tier == t).sum()))} for t in sorted(set(tier))}
        res["by_hard"][k] = {h: {"n": int((hard == h).sum()), "acc": pct(int(((pred == y) & (hard == h)).sum()), int((hard == h).sum()))} for h in sorted(set(hard))}
        res["by_hard"][k]["_by_tier_hard"] = {f"{t}|{h}": pct(int(((pred == y) & (tier == t) & (hard == h)).sum()), int(((tier == t) & (hard == h)).sum())) for t in sorted(set(tier)) for h in sorted(set(hard)) if ((tier == t) & (hard == h)).sum()}
    # confusable pairs
    pairs = [("invoice", "receipt"), ("invoice", "utility_bill"), ("pay_stub", "bank_statement"), ("other", "invoice"), ("other", "bank_statement")]
    res["pairs"] = {}
    for k in kinds:
        pred = P[k].argmax(1)
        res["pairs"][k] = {f"{a_}->{b_}": int(((y == CLASSES.index(a_)) & (pred == CLASSES.index(b_))).sum()) + 0 for a_, b_ in pairs}
        res["pairs"][k].update({f"{b_}->{a_}": int(((y == CLASSES.index(b_)) & (pred == CLASSES.index(a_))).sum()) for a_, b_ in pairs})
    # OCR quality: share of oracle word tokens that OCR found
    if rows[0]["oracle"]:
        rec = []
        for r, dd in zip(rows, docs):
            o = set(toks(r["oracle"]))
            rec.append(len(o & set(toks(dd))) / max(1, len(o)))
        rec = np.array(rec)
        res["ocr_token_recall"] = {t: round(100 * float(rec[tier == t].mean()), 1) for t in sorted(set(tier))}
        res["ocr_token_recall"]["all"] = round(100 * float(rec.mean()), 1)
        # same classifiers on the generator's own text: isolates template difficulty from OCR damage
        oracle_docs = [r["oracle"] for r in rows]
        res["oracle"] = {}
        for k in kinds:
            Po = crossval(kmap[k], oracle_docs, y, fold)
            pred = Po.argmax(1)
            res["oracle"][k] = {"acc": pct(int((pred == y).sum()), len(y)), "n": len(y),
                                "easy": pct(int(((pred == y) & (hard == "0")).sum()), int((hard == "0").sum())),
                                "hard": pct(int(((pred == y) & (hard != "0")).sum()), int((hard != "0").sum())),
                                "n_easy": int((hard == "0").sum()), "n_hard": int((hard != "0").sum()),
                                "ocr_easy": pct(int(((P[k].argmax(1) == y) & (hard == "0")).sum()), int((hard == "0").sum())),
                                "ocr_hard": pct(int(((P[k].argmax(1) == y) & (hard != "0")).sum()), int((hard != "0").sum()))}
    # threshold sweep
    thr = [0.0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95]
    res["sweep"] = {k: sweep(P[k], y, thr) for k in P}
    # calibration bins
    bins = [0, 0.3, 0.5, 0.7, 0.9, 1.01]
    res["calibration"] = {}
    for k in P:
        conf, pred = P[k].max(1), P[k].argmax(1)
        res["calibration"][k] = [{"bin": f"{bins[i]:.1f}-{min(bins[i + 1], 1):.1f}", "n": int(((conf >= bins[i]) & (conf < bins[i + 1])).sum()),
                                  "acc": pct(int(((conf >= bins[i]) & (conf < bins[i + 1]) & (pred == y)).sum()), int(((conf >= bins[i]) & (conf < bins[i + 1])).sum()))} for i in range(len(bins) - 1)]
    # review decision by tier at 0.7 for the LR model
    res["lr_tier_at"] = {}
    for t in [0.7, 0.9]:
        conf, pred = P["tfidf_lr"].max(1), P["tfidf_lr"].argmax(1)
        res["lr_tier_at"][str(t)] = {tt: {"auto_pct": pct(int(((conf >= t) & (tier == tt)).sum()), int((tier == tt).sum())),
                                          "auto_errors": int(((conf >= t) & (tier == tt) & (pred != y)).sum()), "auto": int(((conf >= t) & (tier == tt)).sum())} for tt in sorted(set(tier))}
    # learning curve: k labeled pages per class, evaluated on the held-out fold
    rs = random.Random(a.seed + 7)
    ks = [2, 5, 10, 20, 40]
    res["learning_curve"] = {"ks": ks, "reps": 3, "tfidf_lr": {}, "naive_bayes": {}}
    for kind, nm_ in [("tfidf_lr", "tfidf_lr"), ("nb", "naive_bayes")]:
        for k in ks:
            accs, worst = [], []
            for f in range(FOLDS):
                tr_all = np.where(fold != f)[0]
                te = np.where(fold == f)[0]
                for _ in range(3):
                    tr = []
                    for c in range(len(CLASSES)):
                        pool_ = [i for i in tr_all if y[i] == c]
                        tr += rs.sample(pool_, min(k, len(pool_)))
                    Pk = fit_predict(kind, [docs[i] for i in tr], y[tr], [docs[i] for i in te])
                    pr = Pk.argmax(1)
                    accs.append(float((pr == y[te]).mean()))
                    worst.append(min(float((pr[y[te] == c] == c).mean()) for c in range(len(CLASSES)) if (y[te] == c).sum()))
            res["learning_curve"][nm_][str(k)] = {"acc": round(100 * float(np.mean(accs)), 1), "worst_class_recall": round(100 * float(np.mean(worst)), 1), "sd": round(100 * float(np.std(accs)), 1)}
    # unseen template: train on two templates of each class, test on the third
    tpl_i = np.array([int(t) if t not in ("", "na") else -1 for t in tpl])
    if (tpl_i >= 0).all():
        res["unseen_template"] = {"tfidf_lr": {}, "naive_bayes": {}, "seen_same_size": {}}
        for kind, nm_ in [("tfidf_lr", "tfidf_lr"), ("nb", "naive_bayes")]:
            for t in TEMPLATES:
                tr, te = np.where(tpl_i != t)[0], np.where(tpl_i == t)[0]
                pr = fit_predict(kind, [docs[i] for i in tr], y[tr], [docs[i] for i in te]).argmax(1)
                res["unseen_template"][nm_][str(t)] = {"acc": pct(int((pr == y[te]).sum()), len(te)), "n": int(len(te))}
        rnd = random.Random(a.seed + 11)
        te_all = np.where(tpl_i == 2)[0]
        tr_pool = np.where(tpl_i != 2)[0].tolist()
        tr = rnd.sample(tr_pool, len(tr_pool))[:len(tr_pool)]
        # same training size, but test pages come from templates that were in training (random held-out pages)
        idx = list(range(len(rows)))
        rnd.shuffle(idx)
        te2, tr2 = idx[:len(te_all)], idx[len(te_all):][:len(tr_pool)]
        pr2 = fit_predict("tfidf_lr", [docs[i] for i in tr2], y[tr2], [docs[i] for i in te2]).argmax(1)
        res["unseen_template"]["seen_same_size"] = {"tfidf_lr_acc": pct(int((pr2 == y[te2]).sum()), len(te2)), "n_test": len(te2), "n_train": len(tr2)}
    # packet check: 10-page packets, independence assumption vs what the predictions do
    res["packet"] = {}
    pr = P["tfidf_lr"].argmax(1)
    okp = (pr == y)
    p_all = float(okp.mean())
    rr = random.Random(a.seed + 13)
    N, L = 20000, 10
    mixed = sum(all(okp[rr.randrange(len(okp))] for _ in range(L)) for _ in range(N)) / N
    by_t = {t: np.where(tier == t)[0].tolist() for t in sorted(set(tier))}
    same = 0
    for _ in range(N):
        pool_ = by_t[rr.choice(sorted(by_t))]
        same += all(okp[rr.choice(pool_)] for _ in range(L))
    res["packet"] = {"page_acc": round(100 * p_all, 1), "len": L, "independent_formula": round(100 * p_all ** L, 1), "mixed_tier_packets": round(100 * mixed, 1), "same_tier_packets": round(100 * same / N, 1), "draws": N}
    per_tier_p = {t: float(okp[tier == t].mean()) for t in by_t}
    res["packet"]["same_tier_independent_formula"] = round(100 * sum(v ** L for v in per_tier_p.values()) / len(per_tier_p), 1)
    # pages where OCR found almost nothing: a cheap review trigger that needs no classifier at all
    nw = np.array([ocr["pages"][i]["n_words"] for i in ids])
    res["few_words"] = {"min_words": 10, "n_pages": int((nw < 10).sum())}
    for k in kinds:
        pr_ = P[k].argmax(1)
        err_all = int((pr_ != y).sum())
        err_few = int(((pr_ != y) & (nw < 10)).sum())
        res["few_words"][k] = {"errors_total": err_all, "errors_on_few_word_pages": err_few, "acc_on_few_word_pages": pct(int(((pr_ == y) & (nw < 10)).sum()), int((nw < 10).sum())),
                               "errors_left_after_review_of_them": err_all - err_few}
    # timing
    secs = np.array([ocr["pages"][i]["seconds"] for i in ids])
    res["ocr_seconds_per_page"] = {"mean": round(float(secs.mean()), 2), "by_tier": {t: round(float(secs[tier == t].mean()), 2) for t in sorted(set(tier))}}
    res["ocr_mean_conf"] = {t: round(float(np.mean([ocr["pages"][i]["mean_conf"] for i, tt in zip(ids, tier) if tt == t])), 1) for t in sorted(set(tier))}
    json.dump(res, open(d / "results.json", "w"), indent=1)
    with open(d / "pages.csv", "w", newline="") as fh:
        w = csv.writer(fh)
        head = ["id", "label", "template", "tier", "hard", "ocr_words", "ocr_mean_conf", "ocr_seconds"]
        for k in P:
            head += [f"{k}_pred", f"{k}_conf", f"{k}_ok"]
        w.writerow(head)
        for i, r in enumerate(rows):
            o = ocr["pages"][r["id"]]
            line = [r["id"], r["label"], r["template"], r["tier"], r["hard"], o["n_words"], o["mean_conf"], o["seconds"]]
            for k in P:
                pi = int(P[k][i].argmax())
                line += [CLASSES[pi], round(float(P[k][i].max()), 3), int(pi == y[i])]
            w.writerow(line)
    for k in P:
        print(k, res["overall"][k])


def main():
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    g = sub.add_parser("generate"); g.add_argument("dir"); g.add_argument("--seed", type=int, default=2026); g.add_argument("--per-cell", type=int, default=15)
    o = sub.add_parser("ocr"); o.add_argument("dir"); o.add_argument("--procs", type=int, default=6)
    s = sub.add_parser("score"); s.add_argument("dir"); s.add_argument("--seed", type=int, default=2026); s.add_argument("--external")
    a = ap.parse_args()
    {"generate": generate, "ocr": run_ocr, "score": score}[a.cmd](a)


if __name__ == "__main__":
    main()
