DocsAPI LogoDocsAPI

How to Test Document Classification Accuracy (2026)

Nupura UghadeNupura Ughade
/December 2, 2026/17 min read
In short

A Python harness generated 480 pages (8 classes including out of scope junk, 3 layouts each, 4 quality tiers, lookalike headers and continuation pages), read them with Tesseract 5.5.2 and scored three baselines written for the test, not any vendor or DocsAPI: keyword rules, TF-IDF logistic regression and naive Bayes, with five fold cross validation. Logistic regression was right on 95.0% of pages (100.0% clean, 87.5% noisy), naive Bayes 93.5% and the rules 88.3%. At a confidence of 0.50 the logistic regression accepted 441 pages with none wrong and sent 8.1% to review, while the rule confidence was not usable below 0.90. 21 of its 24 errors were pages where OCR found fewer than 10 words. About 10 labeled pages per class reached 92.4%, an unseen layout cost 5 to 10 points, and a 10 page packet at 95% per page is fully right about 60% of the time if pages are independent. Script, results CSVs and a method for scoring your own pages or a vendor are included.

To test document classification accuracy on a lending packet, label 200 to 500 pages, hold each page out of training once, and report four numbers: accuracy by scan quality, the confusion matrix, the error rate among pages the system accepts without a human, and how that error rate moves as you add labeled examples. Overall accuracy is the least useful of the four. On 480 generated pages in eight classes, a TF-IDF logistic regression baseline we wrote was right on 95.0% of them (456 of 480, 95% interval 92.7% to 96.6%), 100.0% on clean scans and 87.5% on noisy ones.

The number that mattered was different. With auto accept set at a confidence of 0.50, 441 pages (91.9%) were accepted and none of them was wrong, while 8.1% went to review. Twenty one of the baseline's 24 errors were pages where Tesseract found fewer than 10 words, so a lookalike layout was almost never the cause. Everything here was measured on generated pages, with classifiers we wrote for the test. These are not vendor results and not DocsAPI results, and we did not run DocsAPI through this harness.

This guide is about how to measure, with a script you can run on your own pages. For what classification software does and how to choose it, read our document classification software guide. For cutting a combined PDF into documents before you classify, see how to split a loan packet PDF. The same method applied to extraction is in our invoice OCR test for accounts payable.

How many pages do you need to test document classification?

Use 200 to 500 pages, with at least 30 in every class and about one page in eight from outside your scope. At 20 pages a result of 95% right could really be anywhere from 76% to 99%. The table gives the 95% Wilson interval for a measured accuracy at several sizes.

Pages tested95% interval if 95% are right95% interval if 85% are right
2076.4 to 99.164.0 to 94.8
6086.3 to 98.373.9 to 91.9
12089.5 to 97.777.5 to 90.3
24091.5 to 97.179.9 to 89.0
48092.7 to 96.681.5 to 87.9

Per class the numbers are smaller. Our 60 pages per class gave a recall of 55 of 60 for one class, which is 91.7% with an interval of 81.9% to 96.4%. Even 60 pages cannot separate a class at 92% from one at 97%, so read per class figures as a place to look and not as a ranking. If you need a decision on one class, such as IDs, test that class with more pages.

Make the set look like your inbox. If a quarter of what you receive is a phone photo, a quarter of the test should be phone photos, reported on their own line. Include the pages you are afraid of: page two of a bank statement with no logo, a receipt that says invoice, a fax cover sheet. An overall figure from a friendly sample is the easiest way to buy the wrong system.

What was in the test set?

The generator draws eight classes, 60 pages each: seven document types a lender sees and one class of pages that belong in none of them. Each class has three layouts. Thirty percent of pages use a lookalike header meant to confuse the class with a neighbour, and 72 pages are continuation pages with the top of the page blanked, the way page two of a statement arrives. That leaves 255 standard pages, 153 lookalikes and 72 continuations.

ClassWhat the generator drawsLookalike variant (30% of pages)Pages
Invoice3 layouts: bordered, serif, sans; bill to, PO, terms, line itemsNo title word, just a vendor name and an Inv # line, ends with a thank you line60
Receipt3 narrow store receipts; items, subtotal, tax, paid by, thank youHeaded TAX INVOICE / RECEIPT and carries an invoice number60
Bank statement3 layouts; opening and closing balance, debit and credit columns, payroll depositsTitled Account Summary60
Pay stub3 layouts; earnings, deductions, gross, net, YTD, direct depositTitled just Statement, with Period, Date and Account ending lines60
Tax formW-2 box grid, 1099-NEC boxes, 1040 summary linesForm title cropped; only Copy B or Page 2 remains60
ID cardDriver license, state ID card, passport data page, placed mid pageBack of a license (barcode and restrictions), passport without the machine readable lines60
Utility bill3 layouts; meter reads, usage, delivery charge, total amount dueTitled Customer Invoice with an invoice number60
Other (out of scope)Cover letter, meeting agenda, sale flyer, fax cover sheet or contract terms pageMentions an invoice, a statement or a payment in passing60

Every class is rendered at four quality tiers, 15 pages per class per tier, so each tier holds 120 pages. Clean is a 200 dpi render. Skewed rotates the page 1.5 to 3.5 degrees with light noise. Noisy adds blur, Gaussian noise and salt and pepper specks. Low resolution drops to 75 dpi and saves as a heavily compressed JPEG. The pages come from a seeded generator, so anyone with the same seed, fonts and Python version builds the same files. Names, numbers and addresses are random. Nothing is a real person's data.

Which classifiers did we compare, and how did we keep the test fair?

We wrote three baselines. None is a vendor product.

  • Keyword rules: 85 hand written phrase patterns with weights, for example opening balance for a bank statement and paid by for a receipt. The score is the weight of matched phrases, the confidence is top score over top plus second plus one, and a page scoring under 2 points is called other. The rules were written before the first run and not edited afterwards.
  • TF-IDF logistic regression: word and word pair features with a minimum document frequency of 2, sublinear term counts, L2 regularization and 300 steps of Adam, in plain numpy. The confidence is the highest class probability.
  • Multinomial naive Bayes on the same word and word pair counts, with 0.5 smoothing. Its confidence is the posterior of the top class.

Pages were read by Tesseract 5.5.2 in its default page segmentation mode. The two trained models were scored with five fold cross validation, stratified by class and tier, so every page was predicted by a model that never saw it, and the numbers below are pooled over all 480 pages. A separate 160 page set from a different seed was used only to debug the harness before the test set was generated. Environment: Python 3.9.6, numpy 2.0.2, Pillow 11.3.0. Scikit-learn was not used, which is why the classifiers are short enough to print at the end.

How accurate were the baselines overall, and class by class?

BaselinePages rightAccuracy95% interval
TF-IDF logistic regression456 of 48095.0%92.7 to 96.6
Naive Bayes449 of 48093.5%91.0 to 95.4
Keyword rules424 of 48088.3%85.2 to 90.9

The ordering is no surprise, and the gaps are wider than the intervals. A model learned from examples beat hand rules by about 7 points, mostly because pages that OCR damaged still leave a few words a model can use. The per class table shows where each one lost points.

ClassPagesLR precisionLR recallNB precisionNB recallRules precisionRules recall
Invoice60100.091.769.096.7100.085.0
Receipt6072.3100.0100.080.084.070.0
Bank statement60100.0100.0100.0100.0100.0100.0
Pay stub6098.291.7100.091.798.291.7
Tax form60100.093.395.196.798.290.0
ID card60100.088.398.188.3100.090.0
Utility bill60100.095.0100.095.0100.095.0
Other (out of scope)60100.0100.098.4100.052.685.0

The logistic regression's weakest number is receipt precision, 72.3%. It is not a receipt problem. Its confusion matrix shows where the other 24 errors went.

True class (rows), predicted (columns)InvoiceReceiptBank st.Pay stubTax formID cardUtilityOther
Invoice554010000
Receipt060000000
Bank statement006000000
Pay stub050550000
Tax form040056000
ID card070005300
Utility bill030000570
Other (out of scope)000000060

Every one of its 24 errors but one was labeled a receipt. Most of those pages came back from OCR with almost no text, and a model with nothing to read falls back on whichever class its intercept favours. Here that class was receipts. So a weak precision figure for one class can come from other classes' failures. The keyword rules failed another way: when OCR returned nothing they answered other, which is why their other precision is 52.6%.

For comparison, here is the keyword rules matrix.

True class (rows), predicted (columns)InvoiceReceiptBank st.Pay stubTax formID cardUtilityOther
Invoice510000009
Receipt0420000018
Bank statement006000000
Pay stub000550005
Tax form000154005
ID card000005406
Utility bill000000573
Other (out of scope)080010051

Do lookalike layouts or OCR errors cause the mistakes?

In this test, OCR errors. We ran the same classifiers, with the same folds, on the text the generator printed instead of the text Tesseract read. That isolates template difficulty from OCR damage.

BaselineOn the true text (no OCR)On OCR textCost of OCRStandard pages, true text to OCRLookalike and continuation pages, true text to OCR
TF-IDF logistic regression100.0%95.0%5.0 points100.0% to 96.9%100.0% to 92.9%
Naive Bayes100.0%93.5%6.5 points100.0% to 93.7%100.0% to 93.3%
Keyword rules98.3%88.3%10.0 points100.0% to 91.0%96.4% to 85.3%

On true text, both trained models scored 100.0% on all 480 pages, including the lookalikes. The rules lost 1.7 points to the confusable layouts. Reading the pages with Tesseract cost the models 5.0 and 6.5 points and the rules 10.0. The pairs we built to confuse the classifiers did little: pay stubs and bank statements were never mixed up by any of the three, and the only invoice and receipt confusions were 4 invoices read as receipts by the logistic regression and 11 receipts read as invoices by naive Bayes.

That is a limit of this data, and we say so plainly. Our lookalike pages still carry some class vocabulary, such as earnings on the pay stub and opening balance on the statement. Real lookalikes are probably harder than ours, but that is a guess. The nearest thing to evidence we have is the section on unseen layouts below, which shows what happens when the model meets a layout it has not trained on. For a first test, the finding is practical: before you buy a better classifier, find out how many of your pages OCR cannot read.

How much does scan quality change classification accuracy?

A lot, and it tracks how many words the OCR recovered. The word recovery column is the share of distinct words printed on the page that Tesseract found.

Quality tierPagesWords OCR recoveredTesseract mean confidenceLRNBRules
Clean, 200 dpi12099.8%95.4100.0%100.0%99.2%
Skewed 1.5 to 3.5 degrees12096.1%93.599.2%99.2%97.5%
Low resolution, 75 dpi, JPEG12051.7%54.493.3%93.3%80.0%
Scanner noise and blur12075.5%65.787.5%81.7%76.7%

Clean and skewed pages are nearly solved by every baseline. Noise and low resolution are where the models separate. Tesseract's own mean word confidence was 95.4 on clean pages and 54.4 on low resolution ones, so the OCR engine already knew those pages were bad. Time per page was 0.69 seconds on average inside six parallel workers on a 10 core Mac, and 1.59 seconds on noisy pages, since Tesseract spends longer on garbage.

The same set by page type shows what a missing header costs.

Page typePagesLRNBRules
Standard page25596.9%93.7%91.0%
Lookalike header15394.8%95.4%86.9%
Continuation page, header missing7288.9%88.9%81.9%

Continuation pages are the weak spot for the logistic regression, 88.9% against 96.9% for standard pages. Most of that gap is noise: the 16 noisy continuation pages were right 68.8% of the time, since blanking the top leaves the OCR less to work with. If your packets contain statements, continuation pages deserve their own line in your scorecard, and splitting is a separate step covered in the packet splitting guide.

What confidence threshold should you set, and what does it cost?

Pick the threshold from the error rate among the pages you accept, not from overall accuracy. A system with 95% accuracy that can tell which 5% it is unsure of is worth more than one at 97% that cannot. For each threshold the script reports the share accepted, the share sent to review, the wrong pages among the accepted ones with a Wilson interval, and the share of all errors that review caught.

Accept at confidence of at leastAuto acceptedSent to reviewWrong among acceptedError rate among accepted95% intervalWrong pages caught by review
0.00100.0%0.0%24 of 4805.0%3.4 to 7.30.0%
0.30100.0%0.0%24 of 4805.0%3.4 to 7.30.0%
0.4094.0%6.0%6 of 4511.3%0.6 to 2.975.0%
0.5091.9%8.1%0 of 4410.0%0.0 to 0.9100.0%
0.6091.2%8.8%0 of 4380.0%0.0 to 0.9100.0%
0.7090.0%10.0%0 of 4320.0%0.0 to 0.9100.0%
0.8088.8%11.2%0 of 4260.0%0.0 to 0.9100.0%
0.9085.2%14.8%0 of 4090.0%0.0 to 0.9100.0%
0.9578.8%21.2%0 of 3780.0%0.0 to 1.0100.0%

Between 0.50 and 0.95 no accepted page was wrong. That is 0 of 441 at 0.50, and the interval means the true rate could be as high as 0.9%. At 0.40, six wrong pages slipped through. At 0.30 the threshold did nothing at all, because nothing scored below it. The price of safety rose slowly, from 8.1% of pages in review at 0.50 to 21.2% at 0.95. In this data a threshold of 0.50 to 0.60 was the sensible range. On real documents, with real lookalikes, the right value will be elsewhere, and the only way to find it is to run this sweep.

Naive Bayes and the keyword rules behave differently with the same pages.

Accept at confidence of at leastAuto acceptedSent to reviewWrong among acceptedError rate among accepted95% intervalWrong pages caught by review
0.00100.0%0.0%31 of 4806.5%4.6 to 9.00.0%
0.3094.0%6.0%5 of 4511.1%0.5 to 2.683.9%
0.4093.3%6.7%2 of 4480.4%0.1 to 1.693.5%
0.5093.3%6.7%2 of 4480.4%0.1 to 1.693.5%
0.6093.1%6.9%1 of 4470.2%0.0 to 1.396.8%
0.7092.9%7.1%1 of 4460.2%0.0 to 1.396.8%
0.8092.7%7.3%0 of 4450.0%0.0 to 0.9100.0%
0.9092.7%7.3%0 of 4450.0%0.0 to 0.9100.0%
0.9592.5%7.5%0 of 4440.0%0.0 to 0.9100.0%

Naive Bayes had 31 errors with no threshold and needed 0.80 to reach none among accepted pages, at a cost of 7.3% in review. The keyword rules are the cautionary table.

Accept at confidence of at leastAuto acceptedSent to reviewWrong among acceptedError rate among accepted95% intervalWrong pages caught by review
0.00100.0%0.0%56 of 48011.7%9.1 to 14.80.0%
0.30100.0%0.0%56 of 48011.7%9.1 to 14.80.0%
0.40100.0%0.0%56 of 48011.7%9.1 to 14.80.0%
0.5099.6%0.4%56 of 47811.7%9.1 to 14.90.0%
0.6095.8%4.2%48 of 46010.4%8.0 to 13.614.3%
0.7089.6%10.4%46 of 43010.7%8.1 to 14.017.9%
0.8078.3%21.7%46 of 37612.2%9.3 to 15.917.9%
0.9019.8%80.2%1 of 951.1%0.2 to 5.798.2%
0.953.8%96.2%0 of 180.0%0.0 to 17.6100.0%

The rule confidence is not a probability. At 0.80 the error rate among accepted pages was 12.2%, higher than with no threshold at all, because pages with no OCR text were answered other at a confidence of about 0.88, which passes every threshold up to that value. Only at 0.90 did they drop out, and by then 80.2% of pages were in review. If your vendor or your own rules return a score, check what it means against labeled pages before routing on it.

The calibration view makes the same point by band.

Confidence bandLRNBRules
0.0-0.3no pages29 pages, 10.3% rightno pages
0.3-0.539 pages, 38.5% right3 pages, 0.0% right2 pages, 100.0% right
0.5-0.79 pages, 100.0% right2 pages, 50.0% right48 pages, 79.2% right
0.7-0.923 pages, 100.0% right1 pages, 0.0% right335 pages, 86.6% right
0.9-1.0409 pages, 100.0% right445 pages, 100.0% right95 pages, 98.9% right

Confidence from the logistic regression was well ordered: its 409 pages above 0.9 were all right, and the 39 pages between 0.3 and 0.5 were right 38.5% of the time. Naive Bayes put 445 pages at 0.9 or above, all right, and its 29 pages below 0.3 were right 10.3% of the time. Only 6 pages fell in between. Its posterior is bunched at the two ends, so it works more as a flag for pages with nothing to read than as a graded score. Check that on your own pages and do not assume it from a table that happens to work.

Is a word count rule just as good as a confidence threshold?

Here it was. We counted pages where OCR found fewer than 10 words: 34 of 480, 25 of them in the noisy tier. A rule that sends those to review needs no classifier at all.

BaselineErrors in all 480 pagesErrors on the 34 pages with fewer than 10 wordsAccuracy on those 34 pagesErrors left if those 34 go to review
TF-IDF logistic regression242138.2%3
Naive Bayes312914.7%2
Keyword rules563011.8%26

Sending those 34 pages to review would have left the logistic regression with 3 errors out of 24, and naive Bayes with 2 out of 31. It cost 7.1% of pages in review, against 8.1% for the 0.50 threshold. The rules are a different story, with 26 errors left, which shows the word count catches blanks but not the rules' real weakness, which is losing key phrases to OCR. Use both signals if you can: the classifier's confidence and a plain check that the page had text.

How many labeled examples does each class need?

About 10 per class gets you most of the way, and 20 to 40 to make sure no class is left behind. We trained on k pages per class, sampled from each training fold, three draws per fold, and scored on the held out fold. Each figure is the mean of 15 runs.

Labeled pages per classTraining pagesLR accuracyLR worst class recallNB accuracyNB worst class recall
21681.6%43.9%83.3%37.8%
54089.7%63.3%90.6%66.1%
108092.4%74.4%92.6%74.4%
2016094.2%80.6%93.4%78.3%
4032095.0%82.2%93.5%77.8%

Accuracy rose from 81.6% at 2 pages per class to 92.4% at 10 and 95.0% at 40, which is the full cross validation level. The standard deviation across runs shrank from 4.6 points to 1.8. The worst class is the better guide to how many examples you need: its recall was 74.4% at 10 pages and 82.2% at 40, so one class was still lagging after 320 training pages. Naive Bayes stopped improving at about 20 per class. On a second generated set (seed 2027) the logistic regression went 83.1%, 87.4%, 91.3%, 93.6% and 94.9% across the same five sizes, so the shape holds, with a different wobble.

The ceiling here is set by OCR, not by examples. More labeled pages would not bring back the text from the pages Tesseract could not read. The practical advice: label 10 to 20 pages per class, run the test, read the confusion matrix and the pages in the worst class, and add labeled examples where it fails and not evenly.

What happens when the layout is one the model has never seen?

Accuracy falls. We trained on two of the three layouts of every class and tested on the third. A real intake sees new layouts every week, so this is closer to how classification fails in production than cross validation is.

Test pagesLR, seed 2026NB, seed 2026LR, seed 2027NB, seed 2027
Template 090.6%91.9%85.0%88.8%
Template 188.1%88.8%88.1%87.5%
Template 282.5%80.0%78.1%78.8%
Random held out pages, templates seen in training92.5%not run96.2%not run

On the main set the logistic regression scored 90.6%, 88.1% and 82.5% on a layout it had never seen, against 92.5% on random pages from layouts it had seen, with the same number of training pages. The second set showed a wider gap (85.0%, 88.1%, 78.1% against 96.2%). With 160 pages per cell, each result has an interval of roughly 5 to 6 points either side, so the gap is real in direction and rough in size. Keep out a layout or an issuer at test time, and test on it. If the drop is big, your classifier is reading layout, not meaning.

Why does 95% per page become 60% per packet?

Because a packet needs every page to be right, and errors do not spread evenly. Take a 10 page packet. If page results were independent, the chance of every page being right is the page accuracy to the tenth power.

Pages in the packet come fromPages rightPage accuracyChance all 10 pages are right (independence)
Clean, 200 dpi120 of 120100.0%100.0%
Skewed 1.5 to 3.5 degrees119 of 12099.2%92.0%
Low resolution, 75 dpi, JPEG112 of 12093.3%50.2%
Scanner noise and blur105 of 12087.5%26.3%
All pages pooled456 of 48095.0%59.9%

At 95.0% per page that is 59.9%. The pooled figure hides the packets that matter: a packet scanned entirely at clean quality passes at 100.0%, one scanned entirely with scanner noise passes at 26.3%. This is an independence calculation on measured page results, not a measurement of real packets, and we also simulated 20,000 packets from the page results to confirm the arithmetic: 60.0% for random mixes, 67.2% when all ten pages share a quality tier. What it supports is a reporting rule. Report accuracy by tier and keep a review path for the pages from bad scans, because an average accuracy figure will not tell you how many packets arrive complete.

Do the results hold on a second, independent set?

We generated a second 480 page set from a different seed and ran the identical pipeline.

MeasureSeed 2026 (main run)Seed 2027 (second set)
TF-IDF logistic regression95.0%95.2%
Naive Bayes93.5%93.8%
Keyword rules88.3%86.9%
LR, wrong among pages accepted at 0.500 of 4410 of 441
NB, wrong among pages accepted at 0.502 of 4483 of 449
Rules, wrong among pages accepted at 0.901 of 954 of 101
Pages with fewer than 10 OCR words3438

The logistic regression moved 0.2 points, naive Bayes 0.3 and the rules 1.4. The threshold result repeated: no wrong pages among 441 accepted at 0.50 for the logistic regression. It is two sets of one generator, not two sources of data, so it checks random variation and not that the result carries over to real pages.

How do you run this on your own documents?

Put page images or PDF pages exported as images in a folder and write a manifest with three columns: id, file and label. The labels must come from your own staff, one label per page, using the classes you actually route on. Then run two commands.

python3 doc_class_test.py ocr my_pages
python3 doc_class_test.py score my_pages

The script reads each page with Tesseract, cross validates the two trained baselines and the rules, and writes a pages CSV with every page's predicted class and confidence, and a results JSON with the tables in this guide. Template, tier and hard columns are optional. Fill in the tier by hand, such as phone photo, flatbed scan or digital PDF, if you want accuracy by quality. The rules in the script are written for the eight classes above, so edit the RULES table for yours, or ignore the rules baseline.

To score a vendor or your own classifier on the same pages, write its answers to a CSV with the columns id, label and confidence, and pass it on:

python3 doc_class_test.py score my_pages --external vendor_answers.csv

It prints the same overall, per class and threshold tables for the external answers. The score and the threshold sweep do not change, which is the point. Ask any vendor for a confidence per page, and test that it means something using the sweep above.

DocsAPI includes classification in its per-page price, which starts at $0.02 a page, see pricing. We have not published a classification accuracy figure for it from this harness. If you want to test it, run it on your own labeled pages and score its answers with --external.

If you are also weighing OCR engines, our OCR accuracy benchmark compares them on real documents, and classification accuracy will follow whichever one reads your worst scans.

What this test cannot tell you

The pages are generated, in one language, in a few fonts, with no handwriting, stamps, staples, folds or photographs. The layouts and the lookalike variants were written by the same person who wrote the classifiers, and class vocabulary survives in them. One OCR engine was used. There are 480 pages per set and 60 per class, so per class numbers are rough. The baselines are small. A layout aware model may treat lookalikes and blank pages differently, and this test does not say how. None of this says how any commercial product performs. It says how to measure one, and how large the traps are when you do.

The script and the results

The whole test is one Python file. It needs Python 3.9 or later, numpy, Pillow and Tesseract 5 on the path. A different set of installed fonts or a different Tesseract version will move the numbers a little.

python3 doc_class_test.py generate data --seed 2026 --per-cell 15
python3 doc_class_test.py ocr data
python3 doc_class_test.py score data

Download the script, the per page results for the main run and the second set, and the figures behind every table as JSON for seed 2026 and seed 2027. Each CSV has one row per page with the label, template, tier, OCR word count, and the predicted class, confidence and correctness for each baseline. Here is the whole script:

#!/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()
Common questions

Frequently asked questions

Use 200 to 500 labeled pages with at least 30 per class and about one page in eight from outside your scope. At 20 pages a measured 95% could really be anywhere from 76% to 99%. At 480 pages the same result has a 95% interval of 92.7% to 96.6%. Per class results from 60 pages are rough, so test any class you care about most with more.

The error rate among pages accepted without review at your chosen confidence threshold. In our test a logistic regression baseline was right on 95.0% of 480 pages overall, but at a confidence of 0.50 it accepted 441 pages with none wrong (95% upper bound 0.9%) and sent 8.1% to review. Overall accuracy cannot tell you that.

In our test, OCR. On the text the generator printed, both trained baselines were right on all 480 pages. On Tesseract's text they were right on 95.0% and 93.5%. 21 of the logistic regression's 24 errors were pages where OCR found fewer than 10 words. These are generated pages and baselines we wrote, so check the split on your own scans.

In our test, 10 per class reached 92.4% accuracy and 40 reached 95.0%, but the worst class was at 74.4% recall with 10 and 82.2% with 40. Label 10 to 20 per class to start, read the confusion matrix, and add examples where a class fails. Results are for a simple TF-IDF logistic regression on generated pages.

Only after you measure it. In our test the logistic regression confidence ordered pages well, with no errors among accepted pages from 0.50 up. The keyword rule score did not: at 0.80 the error rate among accepted pages was 12.2%, higher than with no threshold. Run a threshold sweep on labeled pages before routing on any vendor or in house score.

Label your pages, ask the vendor for a class and a confidence for every page, and score the answers with the same tables: overall accuracy, per class precision and recall, confusion matrix, accuracy by scan quality and the error rate among accepted pages at each threshold. The script in this guide takes a CSV of id, label and confidence through its external option.

Nupura Ughade

Content Marketing Lead, DocsAPI

Nupura Ughade creates clear, insightful content on OCR, document AI, and fintech. She combines technical depth with real-world finance use cases to help engineers and operations leaders navigate digital transformation with confidence.

Want to see it on your own documents?

Try our free OCR tool in your browser, or book a demo to see how DocsAPI reads the document types covered in this guide.