DocsAPI LogoDocsAPI

How to Test Invoice OCR for Accounts Payable (2026)

Nupura UghadeNupura Ughade
/November 30, 2026/15 min read
In short

A Python harness generated 304 invoices with known ground truth (4 templates, 4 quality tiers, 48 seeded defects: wrong total, tax error, missing PO, duplicate) and scored a baseline built for this test, regex and word positions on Tesseract 5.5.2 and PyMuPDF text layers, on seven metrics plus time. Plain Tesseract read 97.2% of header fields, 73.3% of line item rows and 52.0% of whole invoices correctly, and 103 of 256 clean invoices (40.2%) went through with no flag and correct data. After enlarging, straightening and removing ruled lines, those figures were 98.4%, 87.4%, 64.8% and 118 of 256 (46.1%). A bordered template read 95.2% of header fields but 24.1% of rows until ruled lines were removed. The independence model predicted 8.6% document accuracy against 52.0% measured, because errors cluster by layout. Exception rules flagged 47 of 48 seeded defects, but also stopped 58.2% (plain) and 49.2% (cleaned) of clean invoices, and 46 of 48 were caught for the right reason. A Tesseract confidence rule at 75 removed 6 of 18 leaks at the price of 44 needless stops. A hypothetical cost model (4 minutes of review per flagged invoice, 15 minutes of rework per leak, $30 per hour, $0.02 per page placeholder) gave $1.31 and $1.36 per clean invoice. These are generated invoices and a baseline extractor, not a vendor benchmark and not DocsAPI results.

To test invoice OCR for accounts payable, build 200 to 500 invoices with known correct answers, run the engine on them, and score seven numbers. They are header accuracy, line item accuracy, document accuracy, totals that reconcile, straight through rate, exception catch rate and cost per clean invoice. Time per invoice comes on top. The one that decides your cost is the straight through rate, because every invoice that stops costs a person's minutes.

The script at the end of this guide did exactly that on 304 generated invoices. Tesseract 5.5.2 and a plain regex parser read 97.2% of header fields correctly, yet only 52.0% of invoices were right in every field and row. Only 40.2% of the invoices without a seeded defect went through untouched. After ruled lines were removed, pages straightened and 100 dpi scans enlarged, the same three figures were 98.4%, 64.8% and 46.1%.

These are generated invoices read by a baseline we wrote for this test. They are not a vendor benchmark and not a DocsAPI result. What they show is how the metrics behave and how far 98% field accuracy sits from a number that pays the bills. They also show what to put in a scorecard before you run the same test on a real engine.

This guide builds on our posts about parallel run sample size, line item OCR and invoice data to Excel. If you still need a shortlist, read best OCR software for accounts payable first, then come back and test the finalists.

How many invoices do you need to test AP OCR, and which ones?

Use 200 to 500 of your own invoices, and choose them to cover what you receive, not what is easy. Spread them over vendors, page counts, layouts and image quality. Include the worst 10% on purpose. A test made of clean digital files from three friendly vendors will pass any engine.

The reason for 200 or more is the width of the error bar. A proportion measured on 20 invoices can be 20 points off. The table uses the Wilson interval, the same method as our sample size guide, which has the derivation and a worked rollout. We do not repeat it here.

Invoices tested95% interval if about 90% are right95% interval if about 50% are right
1968.6% to 97.1%31.7% to 72.7%
7680.6% to 94.6%39.0% to 61.0%
20085.1% to 93.4%43.1% to 56.9%
30086.1% to 92.9%44.4% to 55.6%
50087.1% to 92.3%45.6% to 54.4%

The test set here has 304 invoices: 4 templates by 4 quality tiers, 19 invoices in each of the 16 cells. Each tier holds 76 invoices, which is enough to see large gaps and not enough to rank two engines that differ by 3 points. A single cell of 19 can tell 0 of 19 from 17 of 19 and little else. Treat cell counts as signs of where to look, not as measurements.

Stratify before you draw. If 30% of your real volume is photos or phone scans, they should be roughly 30% of the test, and you should report them separately. An overall number hides the tier that hurts.

Which seven metrics should you score, and how is each one calculated?

Score header accuracy, line item accuracy, document accuracy, totals reconcile, straight through rate, exception catch rate and cost per clean invoice, plus time. Write the definitions down before the first run, because a definition chosen after you see results tends to favor the engine you already like.

MetricDefinitionFormula
Header accuracyShare of header fields exactly right after normalization: vendor, invoice number, date, currency, subtotal, tax, total, POcorrect header fields / header fields (8 per invoice)
Line item accuracyShare of true rows matched on description, quantity, unit price and amount; row precision is reported next to itmatched rows / true rows
Document accuracyShare of invoices with zero errors in header and rows, and no extra rowserror free invoices / invoices
Totals reconcileExtracted line amounts sum to the extracted subtotal, and subtotal plus tax equals total, within 0.01passing invoices / invoices
Straight through rateInvoices with no exception flag and every field right, with no human touch. The rules are listed belowstraight through invoices / clean invoices
Exception catch rateOf invoices seeded with a defect, the share the rules flagged. Reported with the false stop rate on clean invoicesflagged seeded / seeded
Cost per clean invoiceSoftware, review and rework cost divided by invoices that end up correcttotal cost / clean invoices
TimeSeconds per page and per invoice, measuredelapsed time / pages

Denominators matter, so the script fixes them. Header, line item and document accuracy use all 304 invoices, since a defect that is printed on the page still has to be read correctly. Totals reconcile, straight through rate, false stops and cost use the 256 invoices with no seeded defect. Exception catch uses the 48 that carry one.

Header accuracy and line item accuracy are ratios over many small units, so their intervals come from resampling invoices 2,000 times. The others are counts of whole invoices, so they use Wilson intervals. Error bars on field counts that treated each field as independent would be too narrow, because fields from one bad scan fail together.

How do you build a test set when you cannot share real invoices?

Generate invoices whose correct answers you know. The script draws vendors, numbers, dates, purchase order numbers, currencies, tax rates and 3 to 14 line items from a seeded random generator. It writes one ground truth JSON file per invoice and renders the PDF with reportlab. Anyone running it with the same seed and Python version gets the same files.

The four templates differ in the ways real invoices differ:

  • Template A: a bordered line item table, labels on the right, a due date next to the invoice date, ISO dates.
  • Template B: no borders, a serif font, "Tax Invoice #" glued to the number, left aligned columns in a different order, dates like 27 Jan 2026.
  • Template C: a two column header with the vendor on the left and details on the right, a shaded table header, dates like 06.06.2026, tax labeled "Sales tax".
  • Template D: label above value in a strip across the top, quantity as the first column, and the subtotal, tax and total on a second page.

Currencies are USD, EUR and GBP, and EUR amounts use the decimal comma. The four quality tiers are:

  • Digital: the PDF with its text layer, read with PyMuPDF and no OCR.
  • Clean scan: the page rendered at 200 dpi as an image, no noise.
  • Mild: 200 dpi, a 1 to 3 degree skew, light blur, sensor noise and JPEG compression at quality 70.
  • Low: 100 dpi, noise, light blur and JPEG quality 55. A person can still read every field.

Each scan is a separate image per page, which Tesseract 5.5.2 reads with page segmentation mode 6. Defects are seeded into 48 invoices, 12 of each kind. One kind has a printed total that does not equal subtotal plus tax. One has a tax amount that does not match the printed rate. One has no purchase order number. The last is a second copy of an earlier invoice with the same vendor and number.

Two choices are worth copying. The generator keeps ground truth separate from the rendered file, and the extractor never sees it. And the thresholds were set on a separate 64 invoice development set drawn with a different seed, so the 304 were not used to tune them.

How do you score an OCR result field by field?

Normalize both sides, then compare exactly. Vendor and invoice number are lowercased with punctuation removed. Dates are compared as ISO dates. Amounts are compared as decimals. A missing purchase order is correct only when the invoice has none. A field that comes back empty is wrong.

Line items are matched row by row. For each true row, the scorer looks for an unused extracted row with the same description (normalized), quantity, unit price and amount. Row recall is matched rows over true rows. Row precision is matched rows over extracted rows, which exposes invented rows. The tables also show a looser match that ignores the description, to separate misread words from misread numbers.

An invoice is document correct only when all eight header fields are right, every true row matched, and no extra rows came back. That is the strictest version, and it is the one that matches what an auditor sees.

The exception rules decide what a person looks at. An invoice is flagged when any of these hold:

  • vendor, invoice number, date or total is missing, or the purchase order number is missing;
  • the extracted line amounts do not add up to the subtotal, within 0.01;
  • subtotal plus tax does not equal the total, within 0.01;
  • a line's quantity times unit price does not equal its amount, within 0.01;
  • the printed tax rate times the subtotal does not match the tax, within 0.01;
  • the same vendor and invoice number were already seen earlier in the batch;
  • the lowest Tesseract word confidence among the header numbers is below 75 (digital files score 100).

The 0.01 tolerance follows the tolerance idea in our 3-way match guide. The line sum check is the one from the line item OCR post. An unflagged invoice is released with no human touch. If its data were right, it counts as straight through. If its data were wrong, it counts as a leak, the outcome AP most wants to avoid.

The extractor is a baseline we wrote for this test: regular expressions for the fields, word positions for the table, nothing more. It finds the table header, reads column positions from it, and puts each word of a row in the nearest column. It is not any vendor's product and it is deliberately plain. Errors in the results come from both Tesseract and this parser, which is true of any pipeline you test.

What did a baseline run look like on 304 generated invoices?

Plain Tesseract, with no preprocessing, read headers well and everything else badly. The table gives each metric by tier, with 95% intervals in brackets. Straight through rate and totals reconcile use the clean invoices in each tier, and exception catch uses the seeded ones.

NHeader accuracyLine item accuracyDocument accuracyTotals reconcileStraight throughExceptions caughtSeconds per page
Digital (text layer)76100.0% (100.0 to 100.0)100.0% (100.0 to 100.0)100.0% (95.2 to 100.0)100.0% (93.9 to 100.0)100.0% (93.9 to 100.0)16 of 170.005
Clean scan, 200 dpi7698.4% (97.2 to 99.3)75.7% (64.5 to 85.7)67.1% (55.9 to 76.6)71.2% (59.4 to 80.7)42.4% (31.2 to 54.4)10 of 100.399
Mild noise and skew7698.7% (97.5 to 99.7)65.1% (53.7 to 76.7)38.2% (28.1 to 49.4)66.2% (54.3 to 76.3)23.5% (15.0 to 34.9)8 of 80.368
Low, 100 dpi with noise7691.8% (89.6 to 93.9)50.2% (41.5 to 59.3)2.6% (0.7 to 9.1)34.9% (24.3 to 47.2)0.0% (0.0 to 5.7)13 of 130.284
All invoices30497.2% (96.4 to 97.9)73.3% (68.3 to 78.2)52.0% (46.4 to 57.5)67.6% (61.6 to 73.0)40.2% (34.4 to 46.3)47 of 480.264

Three things stand out. Header accuracy is 97.2% overall, yet document accuracy is 52.0%. The gap is the table: line item accuracy is 73.3%. And the low quality tier reads headers at 91.8% while only 2.6% of its invoices are right throughout, with none passing straight through.

The split by template explains most of the line item gap.

NHeader accuracyLine item accuracyDocument accuracyTotals reconcileStraight throughExceptions caughtSeconds per page
Template A7695.2% (93.3 to 97.2)24.1% (14.2 to 34.5)25.0% (16.6 to 35.8)22.6% (14.0 to 34.4)22.6% (14.0 to 34.4)14 of 140.308
Template B7697.7% (96.4 to 99.0)89.8% (85.6 to 93.6)59.2% (48.0 to 69.6)74.6% (63.1 to 83.5)59.7% (47.7 to 70.6)9 of 90.276
Template C7697.0% (95.6 to 98.4)91.3% (86.1 to 95.7)64.5% (53.3 to 74.3)83.1% (72.2 to 90.3)27.7% (18.3 to 39.6)11 of 110.307
Template D7698.8% (97.9 to 99.7)89.6% (84.3 to 94.1)59.2% (48.0 to 69.6)88.7% (78.5 to 94.4)50.0% (37.9 to 62.1)13 of 140.214

Template A reads its headers fine (95.2%) and its line items badly (24.1%). A surprise, so we tested why. Row precision on A is 100.0%, so the parser never invented rows; the rows were missing. The cause is the grid. Tesseract treats the cell borders as text, drops the table header and the quantity column, and the parser then finds no table. Templates B, C and D have no vertical rules and read at about 90%.

To check that explanation, a second run added a preprocessing step to the same extractor. It enlarges pages under 200 dpi to 200 dpi, straightens them by trying angles from minus 4 to 4 degrees, and blanks out long thin dark lines. Nothing else changed.

Line items, plainLine items, cleanedDocuments, plainDocuments, cleanedStraight through, plainStraight through, cleanedSec per page, plainSec per page, cleaned
Digital (text layer)100.0%100.0%100.0%100.0%100.0%100.0%0.0050.005
Clean scan, 200 dpi75.7%99.8%67.1%82.9%42.4%40.9%0.3990.530
Mild noise and skew65.1%79.3%38.2%47.4%23.5%29.4%0.3680.728
Low, 100 dpi with noise50.2%68.4%2.6%28.9%0.0%19.0%0.2840.679
All invoices73.3%87.4%52.0%64.8%40.2%46.1%0.2640.486

Document accuracy rose from 52.0% to 64.8% and line item accuracy from 73.3% to 87.4%. On clean scans of template A, fully correct invoices went from 0 of 19 to 17 of 19, so the borders were the problem. The fix has limits. Template A in the mild and low tiers stayed at 0 of 19 fully correct. Skew and noise leave fragments of the rules behind, which turn up as extra words in descriptions, and at 100 dpi the table header is often not recognized at all.

Plain, cleanPlain, mildPlain, lowCleaned, cleanCleaned, mildCleaned, low
Template A0 of 190 of 190 of 1917 of 190 of 190 of 19
Template B18 of 198 of 190 of 1913 of 198 of 198 of 19
Template C17 of 1911 of 192 of 1917 of 1913 of 198 of 19
Template D16 of 1910 of 190 of 1916 of 1915 of 196 of 19

Each cell shows invoices fully correct out of 19. Cells like these are too small to rank, but the pattern is clear. Every engine in the test is helped by a clean file and hurt by a low one, and the same layout can be easy in one tier and fail in another.

Time was measured on an Apple M5 with Tesseract limited to one thread, one invoice at a time. Digital files took 0.005 seconds per page. Scans took 0.28 to 0.40 seconds per page without preprocessing and 0.53 to 0.73 with it, because the enlargement and straightening cost more than they look. Total run time for the 304 invoices was about 100 seconds plain and 185 seconds with preprocessing. Those are timings of this baseline on this machine, not a speed claim for any product.

Why does 98% field accuracy give a much lower straight through rate?

Because every field on an invoice has to be right, and some errors hide from every check. Suppose each of 15 fields is right 97% of the time and the errors are independent. The chance all 15 are right is 0.97 to the 15th power, which is 63.3%. A 3% miss per field becomes a 37% miss per invoice.

The independence model can be checked on our data. Treat each header field and each line row as one unit that is right or wrong. The table predicts document accuracy from the unit accuracy and the number of units, and sets it beside what happened. Our OCR accuracy metrics guide covers the character level version of this arithmetic.

Run and tierUnit accuracyUnits per invoicePredicted document accuracyMeasured document accuracy
Plain, digital100.0%16.5100.0%100.0%
Plain, clean86.6%16.610.4%67.1%
Plain, mild82.1%15.85.9%38.2%
Plain, low71.0%15.90.7%2.6%
Plain, all85.1%16.28.6%52.0%
Cleaned, digital100.0%16.5100.0%100.0%
Cleaned, clean98.8%16.682.1%82.9%
Cleaned, mild89.1%15.817.8%47.4%
Cleaned, low83.0%15.96.1%28.9%
Cleaned, all92.9%16.231.1%64.8%

The model is wrong in both directions, which is the useful finding. For plain Tesseract it predicted 8.6% and 52.0% happened, because the errors are not independent: template A failed on almost every invoice and the other templates mostly did not. Errors that come from one cause, such as a bordered table or a tilted page, pile up on certain invoices and leave others perfect. After preprocessing, the clean scan tier shows the other case. Unit accuracy was 98.8%, the model predicted 82.1%, and 82.9% were fully correct, because there the remaining errors are scattered. So use the formula for a rough sense of scale and never as a forecast.

Now the step from correct to straight through. An invoice goes straight through only if its data are right and no rule flags it. The clean invoices end in one of four places.

Run and tierClean invoicesStraight throughRight but stopped (needless)Wrong and stopped (justified)Wrong and released (leak)
Plain, digital5959000
Plain, clean662817192
Plain, mild68169421
Plain, low6302601
Plain, all256103281214
Cleaned, digital5959000
Cleaned, clean66272757
Cleaned, mild682011352
Cleaned, low63126423
Cleaned, all256118448212

The two hard numbers are the leaks and the needless stops. A leak is a wrong invoice that no rule caught. A needless stop is a right invoice that a rule flagged, which costs a reviewer a few minutes for nothing. The confidence rule is a good illustration, because it is the one rule that depends on a setting. This table reruns the scoring of the preprocessed read on the 256 clean invoices with different confidence thresholds. Nothing was re-read.

Confidence thresholdStraight throughRateNeedless stopsJustified stopsLeaksSeeded caught
No confidence rule16263.3%0761847 of 48
5014757.4%15811347 of 48
7511846.1%44821247 of 48
908332.4%7989547 of 48

With no confidence rule, 162 invoices went straight through and 18 were leaks. At 75, only 117 went through, and the leaks fell from 18 to 12. The rule bought 6 fewer leaks at the price of 44 needless stops. Tesseract's confidence is a weak signal here. To remove the last leaks the threshold would have to stop most correct invoices too: at 90 there are 5 leaks and 79 needless stops. A threshold has to be set on your own data for your own engine, and the cost model below says what each kind of error is worth.

What leaks now? In the preprocessed run, 9 of the 12 leaks were a misread vendor name, such as a capital I read as a lowercase l, and nothing in the rule set compares the vendor against a vendor master. That is a rule you would have in a real AP system, and the first lesson of the leak count is to ask which rule would have caught each leak.

Does the pipeline catch the invoices that should be stopped?

Mostly, and the catch rate alone is misleading. Of the 48 seeded invoices, both runs flagged 47. But they also flagged 58.2% and 49.2% of the clean invoices. A pipeline that stops everything catches everything. Report the exception catch rate together with the false stop rate, and add the share caught for the right reason.

RunWrong totalTax errorMissing PODuplicateCaught, any reasonCaught, right reasonClean invoices stopped
Plain12 of 1212 of 1212 of 1211 of 1247 of 4846 of 48149 of 256 (58.2%)
Cleaned12 of 1212 of 1212 of 1211 of 1247 of 4846 of 48126 of 256 (49.2%)

The right reason matters because a defect caught by accident is not a defect caught. A wrong total should trip the totals rule, a tax error the rate rule, a missing purchase order the missing field rule and a duplicate the duplicate rule. By that standard 46 of the 48 were caught for the right reason in both runs. The other one was a duplicate flagged only because its own read was damaged and the sums did not add up.

One duplicate got through in each run. Its original had been read as "lronbridge" with a lowercase L, so an exact match on vendor plus invoice number found nothing. A fuzzy comparison of number and total would catch it. Our posts on duplicate invoice detection and duplicate detection after OCR test those rules in detail.

Digital files show the clean case. They produced no false stops in 59 clean invoices and caught 16 of 17 seeded ones. The miss was that same duplicate, whose scanned original had been misread. It is an argument for reading the original well, not only the copy.

What does one clean invoice cost, counting the exceptions?

Add the software cost per page, the review time on every flagged invoice, and the rework time for every leaked error. Divide by the invoices that end up correct. The cost model below is hypothetical, and every input is an assumption you should replace with your own.

The formula is:

cost per clean invoice = (page price x pages
                          + review minutes x flagged x rate / 60
                          + rework minutes x leaked x rate / 60) / clean invoices

Our assumptions, which are ours and not data: 4 minutes of review for each flagged invoice, 15 minutes of rework for each leak found later, and a loaded rate of $30 per hour. The page price is $0.02, DocsAPI's lowest listed price, used as a placeholder. Tesseract itself is free, and this run is not a DocsAPI result. For comparison, 4 minutes of manual work on every invoice would cost $2.00.

Run and tierClean invoicesCost per clean invoice (hypothetical)Leaks
Plain, digital59$0.030
Plain, clean66$1.342
Plain, mild68$1.641
Plain, low63$2.111
Plain, all256$1.314
Cleaned, digital59$0.030
Cleaned, clean66$1.797
Cleaned, mild68$1.602
Cleaned, low63$1.913
Cleaned, all256$1.3612

Two things follow from the table. First, the page price barely moves the result. At $0.02 a page it is about 1% of the $2.00 cost of one manual review. What moves the result is how many invoices stop, and how many wrong ones slip by.

Second, a leak is expensive. At our assumptions one leak costs as much as 3.75 reviews. In the clean scan tier the preprocessed run read more invoices correctly, yet it let 7 wrong ones through against 2 for the plain run. Its cost per clean invoice was higher, $1.79 against $1.34. Read the cost per clean invoice with the leaks beside it.

The cost at other straight through rates, with no leaks and one page, is $0.02 plus $2.00 times the share that stops. At 40% straight through that is $1.22. At 60% it is $0.82, at 80% it is $0.42 and at 95% it is $0.12. Our pricing models post covers the other cost inputs, such as per page, per invoice and per seat plans.

How do you run the same test on a vendor or your own API?

Keep the ground truth, the scorer and the rules as they are, and replace the extractor. The script has a function named vendor_adapter that receives the invoice folder and the invoice record. It must return the same dictionary the baseline returns, which holds the eight header fields, the tax rate, the line items and a confidence value. Run it with the engine option set to vendor. Scoring then gives the same tables.

Five rules make the comparison fair:

  • Write the acceptance thresholds before the first run, for example 99% on header fields and 85% straight through on your clean tier.
  • Give every engine the same files in the same order, with the same rule set.
  • Have someone who did not pick the vendor review every disagreement between engine and ground truth, and decide whether a mismatch is a misread or a bad label.
  • Report each tier separately and show the leaks.
  • Run your own real invoices too. Anonymize them, label a few hundred by hand, and score them with the same script.

The test does not cover ERP posting, approval routing or supplier portals. Those need their own check against your ledger, and our guides to QuickBooks, NetSuite, SAP and Xero list the field mappings to check. If you plan to build your own pipeline, read build vs buy and rules vs AI extraction first. The which OCR tool picks a shortlist.

DocsAPI has no public API documentation, and we had no access to run it for this test. Nothing here is a DocsAPI result, and no vendor was run.

What did the earlier runs get wrong?

Three runs happened before the one reported here, and each exposed a flaw in our own test code. That is the best argument for running a test before trusting it. The first run on a set of 304 invoices scored 53.3% document accuracy plain and 59.2% preprocessed, with 44.5% and 46.1% straight through.

  • The parser looked for the word "Total" followed by a word boundary, and Tesseract often fused it into "Totaldue". Total accuracy on scanned template A invoices fell to 51% after preprocessing until the pattern allowed fused words.
  • The invoice number pattern assumed the prefix SI was capital letters, and Tesseract often read the I as a lowercase l. That run flagged 34 plain reads for a missing invoice number.
  • The rule set did not multiply quantity by unit price. Rows with a lost quantity but a correct unit price and amount passed the sum check. In that run 9 of the 10 plain leaks and 12 of the 16 preprocessed leaks were such rows, and the line math rule closed the gap.
  • The generator had a bug. Two of the 12 seeded duplicates had lost their originals, because a later step overwrote the invoice they copied. They showed up as misses until we checked each miss against the ground truth. A locked list now stops an original from being overwritten.

After the parser and rule fixes we drew a new set and then fixed the generator and drew the set reported here. The seed in the commands is the last one. Check every miss against the ground truth before blaming the engine, because the test code can be wrong too.

The script

The whole test is one Python file. It needs Python 3.9 or later, reportlab, pymupdf, pillow and numpy, plus Tesseract 5 on the path. It writes a results CSV with one row per invoice and a results JSON with the figures behind every table, and it takes a tag so that several configurations can sit side by side.

python3 ap_ocr_test.py generate data --seed 2027 --per-cell 19
python3 ap_ocr_test.py run data --prep none --tag _plain
python3 ap_ocr_test.py run data --prep cleanup --tag _cleanup
python3 ap_ocr_test.py score data --tag _plain
python3 ap_ocr_test.py score data --tag _cleanup --conf 75

Download the script, or the per-invoice results of the plain run and the cleaned run. Each CSV has one row per invoice with the fields right, flags raised and seconds taken. Here is the whole script:

#!/usr/bin/env python3
"""Invoice OCR test harness for accounts payable: generate, extract, score.

  python3 ap_ocr_test.py generate DIR --seed 2027 --per-cell 19
  python3 ap_ocr_test.py run DIR [--engine baseline|vendor] [--prep none|cleanup] [--tag _plain]
  python3 ap_ocr_test.py score DIR [--tag _plain] [--conf 75]
Writes DIR/extractions<tag>.json, DIR/results<tag>.csv (one row per invoice) and DIR/results<tag>.json.

Needs Python 3.9+, reportlab, pymupdf, pillow, numpy and tesseract 5 on PATH.
The extractor is a plain baseline written for this test (regex plus word
positions). It is not any vendor's product. To test a vendor, fill in
vendor_adapter() below; scoring does not change.
"""
import argparse, csv, datetime, difflib, json, math, os, random, re, subprocess, sys, time
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path

TEMPLATES = ["A", "B", "C", "D"]
TIERS = ["digital", "clean", "mild", "low"]
DPI = {"clean": 200, "mild": 200, "low": 100}
DEFECTS = ["wrong_total", "tax_mismatch", "missing_po", "duplicate"]
HEADER = ["vendor", "invoice_number", "date", "currency", "subtotal", "tax", "total", "po"]
RATES = {"USD": [5, 7, 8, 10], "EUR": [19, 21], "GBP": [20]}
MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
CONF_MIN = 75          # low-confidence rule, fixed on the development set
TOL = Decimal("0.01")  # reconcile tolerance
REVIEW_MIN, REWORK_MIN, RATE_PER_HOUR, PAGE_PRICE = 4, 15, 30, Decimal("0.02")  # hypothetical cost inputs


def q2(x):
    return Decimal(x).quantize(Decimal("0.01"), ROUND_HALF_UP)


# ------------------------------------------------------------------ generate
ADJ = ["Thermal", "Copper", "Steel", "Laminated", "Recycled", "Rapid", "Heavy duty", "Standard", "Compact", "Industrial"]
NOUN = ["paper rolls", "pipe fittings", "label ribbon", "safety gloves", "pallet wrap", "bearing set", "cable ties",
        "filter cartridges", "hex bolts", "storage bins", "work lamps", "drill bits"]
FIRST = ["Northwind", "Alder", "Birch", "Cobalt", "Dunmore", "Everly", "Fairhaven", "Granite", "Harlow", "Ironbridge",
         "Juniper", "Kestrel", "Larkspur", "Mercer", "Norfolk", "Oakridge", "Pinecrest", "Quillon", "Ridgeway", "Stonebrook"]
LAST = ["Supply Co.", "Logistics Ltd", "Industrial GmbH", "Office Goods", "Packaging Inc.", "Tools & Parts", "Freight Services"]
STREET = ["Mill Road", "Station Lane", "Harbour Street", "Foundry Way", "Elm Avenue", "Canal Row"]
CUSTOMER = ["Marlowe Distribution Ltd", "Tern Hospitality Group", "Calder Clinics LLC", "Pike and Sons Builders"]


def fm(v, cur):
    s = f"{Decimal(v):,.2f}"
    return s.translate(str.maketrans(",.", ".,")) if cur == "EUR" else s


def fd(iso, style):
    y, m, d = map(int, iso.split("-"))
    return {"iso": iso, "dmy": f"{d} {MON[m - 1]} {y}", "dot": f"{d:02d}.{m:02d}.{y}", "mdy": f"{MON[m - 1]} {d}, {y}"}[style]


def new_invoice(rng, used):
    cur = rng.choice(["USD", "USD", "EUR", "GBP"])
    rate = rng.choice(RATES[cur])
    descs = rng.sample([f"{a} {b}" for a in ADJ for b in NOUN], rng.randint(3, 14))
    lines = []
    for d in descs:
        qty, unit = rng.randint(1, 40), q2(Decimal(rng.randint(150, 45000)) / 100)
        lines.append({"desc": d, "qty": qty, "unit": str(unit), "amount": str(q2(qty * unit))})
    sub = sum(Decimal(l["amount"]) for l in lines)
    tax = q2(sub * rate / 100)
    while True:
        no = f"{rng.choice(['INV', 'BC', 'SI', 'AP'])}-{rng.randint(10000, 99999)}"
        if no not in used:
            used.add(no)
            break
    return {"vendor": f"{rng.choice(FIRST)} {rng.choice(LAST)}", "invoice_number": no,
            "date": str(datetime.date(2026, rng.randint(1, 10), rng.randint(1, 28))),
            "po": f"PO-{rng.randint(10000, 99999)}", "currency": cur, "tax_rate": rate, "lines": lines,
            "subtotal": str(q2(sub)), "tax": str(tax), "total": str(q2(sub + tax)),
            "addr": f"{rng.randint(2, 480)} {rng.choice(STREET)}", "customer": rng.choice(CUSTOMER)}


def T(c, x, y, s, font="Helvetica", size=10, right=False):
    c.setFont(font, size)
    (c.drawRightString if right else c.drawString)(x, y, s)


def draw(c, t):
    from reportlab.lib.colors import Color
    cur, tp = t["currency"], t["template"]
    f = lambda v: fm(v, cur)
    due = str(datetime.date.fromisoformat(t["date"]) + datetime.timedelta(30))
    lines, rate = t["lines"], t["tax_rate"]
    if tp == "A":  # bordered line item table, labels on the right
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 16); T(c, 562, 750, "INVOICE", "Helvetica-Bold", 22, True)
        T(c, 50, 736, t["addr"], size=9)
        meta = [("Invoice No:", t["invoice_number"]), ("Date:", fd(t["date"], "iso")), ("Due:", fd(due, "iso"))]
        if t["po"]: meta.append(("PO Number:", t["po"]))
        meta.append(("Currency:", cur))
        for i, (k, v) in enumerate(meta): T(c, 380, 715 - 14 * i, k); T(c, 465, 715 - 14 * i, v)
        T(c, 50, 700, "Bill to:"); T(c, 50, 686, t["customer"])
        edges, top = [50, 300, 350, 450, 562], 630
        for j, h in enumerate(["Description", "Qty", "Unit price", "Amount"]):
            c.rect(edges[j], top - 20, edges[j + 1] - edges[j], 20); T(c, edges[j + 1] - 5 if j else 55, top - 14, h, "Helvetica-Bold", 10, bool(j))
        for r, l in enumerate(lines):
            y0 = top - 20 * (r + 2)
            for j, v in enumerate([l["desc"], str(l["qty"]), f(l["unit"]), f(l["amount"])]):
                c.rect(edges[j], y0, edges[j + 1] - edges[j], 20); T(c, edges[j + 1] - 5 if j else 55, y0 + 6, v, right=bool(j))
        y = top - 20 * (len(lines) + 2) - 22
        for lab, v, bold in [("Subtotal", t["subtotal"], 0), (f"Tax {rate}%", t["tax"], 0), ("Total due", t["total"], 1)]:
            fn = "Helvetica-Bold" if bold else "Helvetica"
            T(c, 500, y, lab, fn, 10, True); T(c, 557, y, f(v), fn, 10, True); y -= 16
        T(c, 50, 60, "Payment terms: Net 30", size=9)
    elif tp == "B":  # no borders, Times, labels glued to values, left aligned columns
        T(c, 50, 750, t["vendor"], "Times-Bold", 18); T(c, 50, 736, t["addr"], "Times-Roman", 10)
        T(c, 50, 706, f"Tax Invoice #{t['invoice_number']}", "Times-Roman", 12)
        T(c, 50, 690, f"Issued: {fd(t['date'], 'dmy')}", "Times-Roman", 12)
        yy = 674
        if t["po"]: T(c, 50, yy, f"Customer order ref: {t['po']}", "Times-Roman", 12); yy -= 16
        T(c, 50, yy, f"Currency: {cur}", "Times-Roman", 12)
        xs, top = [50, 330, 400, 470], 610
        for x, h in zip(xs, ["Item", "Price", "Quantity", "Line total"]): T(c, x, top, h, "Times-Bold", 11)
        for r, l in enumerate(lines):
            for x, v in zip(xs, [l["desc"], f(l["unit"]), str(l["qty"]), f(l["amount"])]): T(c, x, top - 18 * (r + 1), v, "Times-Roman", 11)
        y = top - 18 * (len(lines) + 1) - 24
        for lab, v in [("Net", t["subtotal"]), (f"VAT {rate}%", t["tax"]), ("Amount payable", t["total"])]:
            T(c, 380, y, lab, "Times-Roman", 11); T(c, 540, y, f(v), "Times-Roman", 11, True); y -= 16
        T(c, 50, 60, "Payment terms: net 30", "Times-Roman", 10)
    elif tp == "C":  # two column header, ruled rows only
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 14); T(c, 50, 736, t["addr"], size=9); T(c, 50, 724, "Customer accounts", size=9)
        T(c, 562, 752, "INVOICE", "Helvetica-Bold", 24, True)
        meta = [("Invoice number:", t["invoice_number"]), ("Invoice date:", fd(t["date"], "dot")), ("Payment due:", fd(due, "dot"))]
        if t["po"]: meta.append(("Purchase order:", t["po"]))
        meta.append(("Currency:", cur))
        for i, (k, v) in enumerate(meta): T(c, 350, 724 - 14 * i, k); T(c, 450, 724 - 14 * i, v)
        T(c, 50, 660, "Bill to", "Helvetica-Bold", 10); T(c, 50, 646, t["customer"])
        c.setFillColor(Color(0.88, 0.88, 0.88)); c.rect(50, 584, 512, 20, fill=1, stroke=0); c.setFillColor(Color(0, 0, 0))
        for x, h, rt in [(55, "Description", 0), (340, "Qty", 1), (430, "Rate", 1), (557, "Amount", 1)]: T(c, x, 590, h, "Helvetica-Bold", 10, bool(rt))
        for r, l in enumerate(lines):
            y0 = 584 - 20 * (r + 1)
            c.line(50, y0, 562, y0)
            T(c, 55, y0 + 6, l["desc"]); T(c, 340, y0 + 6, str(l["qty"]), right=True); T(c, 430, y0 + 6, f(l["unit"]), right=True); T(c, 557, y0 + 6, f(l["amount"]), right=True)
        y = 584 - 20 * (len(lines) + 1) - 22
        for lab, v, bold in [("Subtotal", t["subtotal"], 0), (f"Sales tax ({rate}%)", t["tax"], 0), ("Balance due", t["total"], 1)]:
            fn = "Helvetica-Bold" if bold else "Helvetica"
            T(c, 500, y, lab, fn, 10, True); T(c, 557, y, f(v), fn, 10, True); y -= 16
    else:  # D: label above value strip, quantity first, summary on page 2
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 16); T(c, 562, 750, "Invoice", "Helvetica-Bold", 20, True); T(c, 50, 736, t["addr"], size=9)
        cells = [("Invoice no.", t["invoice_number"]), ("Date", fd(t["date"], "mdy")), ("PO no.", t["po"] or "n/a"), ("Due", fd(due, "mdy")), ("Currency", cur)]
        for i, (k, v) in enumerate(cells): T(c, 50 + 105 * i, 690, k, size=8); T(c, 50 + 105 * i, 676, v)
        T(c, 50, 650, "Bill to: " + t["customer"])
        c.setFillColor(Color(0.88, 0.88, 0.88)); c.rect(50, 604, 512, 20, fill=1, stroke=0); c.setFillColor(Color(0, 0, 0))
        T(c, 55, 610, "Qty", "Helvetica-Bold", 10); T(c, 100, 610, "Description", "Helvetica-Bold", 10)
        T(c, 440, 610, "Unit price", "Helvetica-Bold", 10, True); T(c, 557, 610, "Total", "Helvetica-Bold", 10, True)
        for r, l in enumerate(lines):
            y0 = 610 - 18 * (r + 1)
            T(c, 55, y0, str(l["qty"])); T(c, 100, y0, l["desc"]); T(c, 440, y0, f(l["unit"]), right=True); T(c, 557, y0, f(l["amount"]), right=True)
        T(c, 50, 60, "Totals are on page 2", size=9)
        c.showPage()
        T(c, 50, 750, t["vendor"], "Helvetica-Bold", 12); T(c, 562, 750, f"Page 2 of 2", size=9, right=True)
        T(c, 50, 700, "Summary", "Helvetica-Bold", 16)
        y = 670
        for lab, v, bold in [("Subtotal", t["subtotal"], 0), (f"Tax ({rate}%)", t["tax"], 0), ("Total", t["total"], 1)]:
            fn = "Helvetica-Bold" if bold else "Helvetica"
            T(c, 400, y, lab, fn, 11, True); T(c, 520, y, f(v), fn, 11, True); y -= 18
        T(c, 50, 600, "Please pay within 30 days. Bank reference 2026" + t["invoice_number"][-5:], size=9)
    c.showPage()


def degrade(img, tier, nrng, rng):
    import numpy as np
    from PIL import Image, ImageFilter
    if tier == "clean":
        return img, "png", {}
    if tier == "mild":
        ang = rng.choice([-1, 1]) * rng.uniform(1, 3)
        img = img.rotate(ang, resample=Image.BICUBIC, fillcolor=255).filter(ImageFilter.GaussianBlur(0.6))
        sigma, qual = 10, 70
    else:
        ang, img = 0, img.filter(ImageFilter.GaussianBlur(0.5))
        sigma, qual = 12, 55
    a = np.asarray(img, dtype=np.float32) + nrng.normal(0, sigma, (img.height, img.width))
    return Image.fromarray(np.clip(a, 0, 255).astype("uint8")), "jpg", {"quality": qual, "angle": round(ang, 2)}


def generate(a):
    import numpy as np, pymupdf
    from PIL import Image
    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    out = Path(a.dir); out.mkdir(parents=True, exist_ok=True)
    rng, nrng, used = random.Random(a.seed), np.random.default_rng(a.seed), set()
    cells = [(tp, ti) for tp in TEMPLATES for ti in TIERS for _ in range(a.per_cell)]
    rng.shuffle(cells)
    n = len(cells)
    k = max(1, round(n * 0.04))  # 4 defect types, about 16 percent seeded in all
    idx = list(range(n)); rng.shuffle(idx)
    defect = {}
    for d, chunk in zip(DEFECTS[:3], [idx[:k], idx[k:2 * k], idx[2 * k:3 * k]]):
        for i in chunk: defect[i] = d
    inv = [dict(new_invoice(rng, used), template=tp, tier=ti, defect="none", dup_of=None) for tp, ti in cells]
    for i, d in defect.items():
        t = inv[i]; t["defect"] = d
        if d == "missing_po": t["po"] = None
        if d == "wrong_total": t["total"] = str(q2(Decimal(t["total"]) + rng.choice([-1, 1]) * Decimal(rng.randint(500, 50000)) / 100))
        if d == "tax_mismatch":
            t["tax"] = str(max(Decimal("0"), q2(Decimal(t["tax"]) + rng.choice([1, 1, -1]) * Decimal(rng.randint(100, 2500)) / 100)))
            t["total"] = str(q2(Decimal(t["subtotal"]) + Decimal(t["tax"])))
    free = [i for i in idx[3 * k:]]
    dups, locked = 0, set()  # locked: invoices already used as the original of a duplicate
    for i in sorted(free, key=lambda _: rng.random()):
        if dups == k: break
        if i < 20 or i in locked or inv[i]["defect"] != "none": continue
        pool = [j for j in range(i) if inv[j]["template"] == inv[i]["template"] and inv[j]["defect"] == "none"]
        if not pool: continue
        j = rng.choice(pool); locked.add(j)
        keep = {x: inv[i][x] for x in ("template", "tier")}
        inv[i] = dict(inv[j], **keep, defect="duplicate", dup_of=f"inv{j:03d}")
        dups += 1
    order = []
    for i, t in enumerate(inv):
        t["id"] = f"inv{i:03d}"
        t["pages"] = 2 if t["template"] == "D" else 1
        pdf = out / f"{t['id']}.pdf"
        c = canvas.Canvas(str(pdf), pagesize=letter); draw(c, t); c.save()
        if t["tier"] != "digital":
            for p, pg in enumerate(pymupdf.open(str(pdf))):
                pix = pg.get_pixmap(dpi=DPI[t["tier"]], colorspace=pymupdf.csGRAY)
                img, ext, info = degrade(Image.frombytes("L", (pix.width, pix.height), pix.samples), t["tier"], nrng, rng)
                img.save(out / f"{t['id']}_p{p + 1}.{ext}", dpi=(DPI[t["tier"]],) * 2, **({"quality": info["quality"]} if ext == "jpg" else {}))
        (out / f"{t['id']}.json").write_text(json.dumps(t, indent=1))
        order.append(t["id"])
    (out / "manifest.json").write_text(json.dumps(order))
    print(f"{n} invoices in {out}; defects:", {d: sum(1 for t in inv if t['defect'] == d) for d in DEFECTS})


# ------------------------------------------------------------------- extract
def long_runs(m, L):
    """Mark pixels that sit inside a horizontal run of at least L dark pixels."""
    import numpy as np
    c = np.zeros((m.shape[0], m.shape[1] + 1), np.int32); c[:, 1:] = np.cumsum(m, axis=1)
    full = (c[:, L:] - c[:, :-L]) == L
    c2 = np.zeros((m.shape[0], full.shape[1] + 1), np.int32); c2[:, 1:] = np.cumsum(full, axis=1)
    x = np.arange(m.shape[1])
    return (c2[:, np.minimum(x + 1, full.shape[1])] - c2[:, np.maximum(x - L + 1, 0)]) > 0


def cleanup(path, dpi, out):
    """Optional pre-processing: upscale to 200 dpi, straighten (projection profile, -4 to 4 degrees), blank ruled lines."""
    import numpy as np
    from PIL import Image
    img = Image.open(path).convert("L")
    if dpi < 200:
        img = img.resize((round(img.width * 200 / dpi), round(img.height * 200 / dpi)), Image.LANCZOS)
    ink = Image.fromarray(255 - np.asarray(img.resize((img.width // 4, img.height // 4))))
    best = max(np.arange(-4, 4.01, 0.5), key=lambda g: np.var(np.asarray(ink.rotate(g, fillcolor=0)).sum(axis=1)))
    img = img.rotate(best, resample=Image.BICUBIC, fillcolor=255)
    g = np.asarray(img)
    dark, L = g < 200, 25
    thin_h = ~np.roll(dark, 3, axis=0) & ~np.roll(dark, -3, axis=0)  # a ruled line is thin
    thin_v = ~np.roll(dark, 3, axis=1) & ~np.roll(dark, -3, axis=1)
    h = g.copy(); h[(long_runs(dark, L) & thin_h) | (long_runs(dark.T, L).T & thin_v)] = 255
    Image.fromarray(h).save(out, dpi=(200, 200))
    return out, 200


def read_words(truth, folder, prep="none"):
    """Words with page, box in points, text and confidence. Digital PDFs use the text layer, scans use Tesseract."""
    import pymupdf
    from PIL import Image
    words = []
    if truth["tier"] == "digital":
        for p, pg in enumerate(pymupdf.open(str(folder / f"{truth['id']}.pdf"))):
            for x0, y0, x1, y1, t, *_ in pg.get_text("words"):
                words.append({"p": p, "x0": x0, "y0": y0, "x1": x1, "y1": y1, "t": t, "c": 100, "ln": None})
        return words
    for p in range(truth["pages"]):
        path = next(folder.glob(f"{truth['id']}_p{p + 1}.*"))
        dpi = Image.open(path).info.get("dpi", (200, 200))[0]
        s = 72 / dpi
        if prep == "cleanup":
            path, dpi = cleanup(path, dpi, folder / "_tmp_clean.png")
            s = 72 / dpi
        env = dict(os.environ, OMP_THREAD_LIMIT="1")
        tsv = subprocess.run(["tesseract", str(path), "stdout", "--psm", "6", "tsv"], capture_output=True, text=True, env=env).stdout
        for row in tsv.split("\n")[1:]:
            f = row.split("\t")
            if len(f) == 12 and f[0] == "5" and f[11].strip():
                l, tp, w, h = int(f[6]), int(f[7]), int(f[8]), int(f[9])
                words.append({"p": p, "x0": l * s, "y0": tp * s, "x1": (l + w) * s, "y1": (tp + h) * s, "t": f[11].strip(),
                              "c": float(f[10]), "ln": (p, f[2], f[3], f[4])})
    return words


def make_lines(words):
    by, free = {}, []
    for w in words:
        (by.setdefault(w["ln"], []) if w["ln"] else free).append(w)
    groups = list(by.values())
    for p in sorted({w["p"] for w in free}):
        cur = []
        for w in sorted([w for w in free if w["p"] == p], key=lambda w: (w["y0"] + w["y1"]) / 2):
            yc = (w["y0"] + w["y1"]) / 2
            if cur and abs(yc - sum((x["y0"] + x["y1"]) / 2 for x in cur) / len(cur)) > 0.5 * (w["y1"] - w["y0"]):
                groups.append(cur); cur = []
            cur.append(w)
        if cur: groups.append(cur)
    out = []
    for g in groups:
        g = sorted(g, key=lambda w: w["x0"])
        out.append({"p": g[0]["p"], "y": sum((w["y0"] + w["y1"]) / 2 for w in g) / len(g), "words": g, "text": " ".join(w["t"] for w in g)})
    return sorted(out, key=lambda L: (L["p"], L["y"]))


DIG = str.maketrans("OolIS|", "001115")
MONEY = re.compile(r"(?<![\d.,])\d{1,3}(?:[.,]\d{3})*[.,]\d{2}(?!\d)|(?<![\d.,])\d+[.,]\d{2}(?!\d)")
SUB = re.compile(r"(?i)^\W*(?:sub\s*-?\s*total|net(?:\s+amount)?)\b")
TAX = re.compile(r"(?i)^\W*(?:sales\s+)?(?:tax|vat|gst)(?![a-z])")
TOT = re.compile(r"(?i)^\W*(?:grand\s+)?(?:total(?:\s*(?:due|amount))?|amount\s*(?:payable|due)|balance\s*due)(?![a-z])")
VOC = {"desc": ["description", "item", "details"], "qty": ["qty", "quantity"], "unit": ["unit", "price", "rate"], "amt": ["amount", "total", "line"]}
DATES = [(re.compile(r"\b(\d{4})-(\d{2})-(\d{2})\b"), "ymd"), (re.compile(r"\b(\d{1,2})\s+([A-Z][a-z]{2})\s+(\d{4})\b"), "dmy"),
         (re.compile(r"\b(\d{2})\.(\d{2})\.(\d{4})\b"), "dot"), (re.compile(r"\b([A-Z][a-z]{2})\s+(\d{1,2}),\s*(\d{4})\b"), "mdy")]


def to_money(tok):
    t = tok.translate(DIG) if sum(ch.isdigit() for ch in tok) >= len(tok) // 2 else tok
    m = re.fullmatch(r"([\d.,]*\d)[.,](\d{2})", t)
    return Decimal(re.sub(r"[.,]", "", m.group(1)) + "." + m.group(2)) if m else None


def to_date(s):
    for rx, kind in DATES:
        m = rx.search(s)
        if not m: continue
        g = m.groups()
        try:
            if kind == "ymd": return str(datetime.date(int(g[0]), int(g[1]), int(g[2])))
            if kind == "dmy": return str(datetime.date(int(g[2]), MON.index(g[1]) + 1, int(g[0])))
            if kind == "dot": return str(datetime.date(int(g[2]), int(g[1]), int(g[0])))
            return str(datetime.date(int(g[2]), MON.index(g[0]) + 1, int(g[1])))
        except ValueError:
            continue
    return None


def conf_of(L, s):
    return min([w["c"] for w in L["words"] if w["t"] in s] or [100])


def header_cells(L):
    cells = []
    for w in L["words"]:
        m = {k: difflib.get_close_matches(w["t"].lower().strip(":"), v, 1, 0.75) for k, v in VOC.items()}
        k = next((k for k, v in m.items() if v), None)
        if k and cells and cells[-1]["k"] == k and w["x0"] - cells[-1]["x1"] < 15: cells[-1]["x1"] = w["x1"]
        elif k: cells.append({"k": k, "x0": w["x0"], "x1": w["x1"]})
    return cells if {c["k"] for c in cells} == set(VOC) else None


def extract(words):
    words = [dict(w, t=w["t"].strip("|;_[]")) for w in words]  # stray rule fragments become empty tokens
    lines = make_lines([w for w in words if re.search(r"\w", w["t"])])
    e = {k: None for k in HEADER}; e.update(rate=None, lines=[]); conf = []
    for L in lines:
        m = re.search(r"\b(USD|EUR|GBP)\b", L["text"])
        if m: e["currency"] = m.group(1); break
    for L in lines:  # vendor: leading words of the first top line, cut at the first wide gap
        if L["p"]: break
        ws, cut = L["words"], len(L["words"])
        for i in range(1, len(ws)):
            if ws[i]["x0"] - ws[i - 1]["x1"] > 25: cut = i; break
        name = " ".join(w["t"] for w in ws[:cut])
        if re.search(r"[A-Za-z]{3}", name) and not re.match(r"(?i)\W*(tax\s+)?invoice\b", name): e["vendor"] = name; break
    for strict in (True, False):  # invoice number: prefer a line that says invoice
        for L in lines:
            if L["p"]: break
            m = re.search(r"\b((?!PO)[A-Z][A-Zl1I!|]{1,2})\s?-\s?([0-9OolIS]{5})\b", L["text"])
            if m and (not strict or re.search(r"(?i)\binv", L["text"])):
                e["invoice_number"] = f"{m.group(1).translate(str.maketrans('l1!|', 'IIII'))}-{m.group(2).translate(DIG)}"; conf.append(conf_of(L, m.group(0))); break
        if e["invoice_number"]: break
    for L in lines:
        m = re.search(r"\bP[O0]\s?[-\u2013]?\s?([0-9OolIS]{5})\b", L["text"])
        if m: e["po"] = "PO-" + m.group(1).translate(DIG); conf.append(conf_of(L, m.group(0))); break
    for L in lines:
        if L["p"] == 0 and "due" not in L["text"].lower() and to_date(L["text"]):
            e["date"] = to_date(L["text"]); conf.append(conf_of(L, L["text"])); break
    hi = next((i for i, L in enumerate(lines) if header_cells(L)), None)
    stop = len(lines)
    for i, L in enumerate(lines):  # totals: anchored labels below the table header
        if hi is not None and i <= hi: continue
        nums = [(w, to_money(w["t"])) for w in L["words"] if to_money(w["t"]) is not None]
        if not nums: continue
        key = "subtotal" if SUB.match(L["text"]) else "tax" if TAX.match(L["text"]) else "total" if TOT.match(L["text"]) else None
        if key:
            stop = min(stop, i)
            if key == "total" or e[key] is None:
                e[key] = str(nums[-1][1]); conf.append(nums[-1][0]["c"])
            r = re.search(r"(\d{1,2})\s*%", L["text"])
            if key == "tax" and r: e["rate"] = int(r.group(1))
    if hi is not None:
        cells = header_cells(lines[hi])
        d = next(c for c in cells if c["k"] == "desc")
        right = [c["x0"] for c in cells if c["k"] != "desc" and c["x0"] > d["x0"]]
        lo, hi_x = d["x0"] - 14, (min(right) - 14 if right else 9999)
        num = [c for c in cells if c["k"] != "desc"]
        for L in lines[hi + 1:stop]:
            row = {"desc": [], "qty": [], "unit": [], "amt": []}
            for w in L["words"]:
                if lo <= w["x0"] < hi_x: row["desc"].append(w["t"])
                else:
                    xc = (w["x0"] + w["x1"]) / 2
                    row[min(num, key=lambda c: abs((c["x0"] + c["x1"]) / 2 - xc))["k"]].append(w["t"])
            qty = "".join(row["qty"]).translate(DIG)
            r = {"desc": " ".join(row["desc"]), "qty": int(qty) if qty.isdigit() else None,
                 "unit": to_money("".join(row["unit"])), "amount": to_money("".join(row["amt"]))}
            if any(r[k] is not None for k in ("qty", "unit", "amount")):
                e["lines"].append({k: (str(v) if isinstance(v, Decimal) else v) for k, v in r.items()})
    e["conf"] = min(conf) if conf else 0
    return e


def vendor_adapter(folder, truth):
    """Return the same dict as extract(): header fields, rate, lines and conf. Call your vendor here."""
    raise NotImplementedError("plug a vendor in; scoring is unchanged")


def run(a):
    folder = Path(a.dir); res = {}
    for iid in json.loads((folder / "manifest.json").read_text()):
        t = json.loads((folder / f"{iid}.json").read_text())
        t0 = time.perf_counter()
        e = vendor_adapter(folder, t) if a.engine == "vendor" else extract(read_words(t, folder, a.prep))
        e["seconds"], e["pages"] = time.perf_counter() - t0, t["pages"]
        res[iid] = e
    (folder / f"extractions{a.tag}.json").write_text(json.dumps(res, indent=1))
    print("extracted", len(res), "invoices,", round(sum(e["seconds"] for e in res.values()), 1), "s")


# --------------------------------------------------------------------- score
def norm(s): return re.sub(r"[^a-z0-9]", "", (s or "").lower())
def D(x): return None if x is None else Decimal(str(x))


def field_ok(k, truth, e):
    a, b = truth.get(k), e.get(k)
    if k in ("subtotal", "tax", "total"): return b is not None and D(a) == D(b)
    if k == "po": return norm(a) == norm(b)
    if k in ("vendor", "invoice_number"): return bool(b) and norm(a) == norm(b)
    return a == b


def match_rows(truth, e, desc=True):
    used, hit = set(), 0
    for g in truth["lines"]:
        for j, r in enumerate(e["lines"]):
            if j in used: continue
            if (r["qty"] == g["qty"] and D(r["unit"]) == D(g["unit"]) and D(r["amount"]) == D(g["amount"])
                    and (not desc or norm(r["desc"]) == norm(g["desc"]))):
                used.add(j); hit += 1; break
    return hit


def rules(ordered):
    """The exception rules. A flagged invoice goes to a person; an unflagged one is released untouched."""
    seen, out = {}, {}
    for iid, e in ordered:
        fl = []
        miss = [k for k in ("vendor", "invoice_number", "date", "total") if not e.get(k)]
        if miss: fl.append("missing:" + "+".join(miss))
        if not e.get("po"): fl.append("missing:po")
        sub, tax, tot = D(e.get("subtotal")), D(e.get("tax")), D(e.get("total"))
        amts = [D(l["amount"]) for l in e["lines"]]
        if sub is None or None in amts or abs(sum(amts, Decimal(0)) - sub) > TOL: fl.append("reconcile:lines")
        if None in (sub, tax, tot) or abs(sub + tax - tot) > TOL: fl.append("reconcile:total")
        if any(l["qty"] is None or l["unit"] is None or l["amount"] is None or abs(l["qty"] * D(l["unit"]) - D(l["amount"])) > TOL for l in e["lines"]):
            fl.append("reconcile:line_math")
        if e.get("rate") is not None and None not in (sub, tax) and abs(q2(sub * e["rate"] / 100) - tax) > TOL: fl.append("tax_rate")
        key = (norm(e.get("vendor")), norm(e.get("invoice_number")))
        if all(key):
            if key in seen: fl.append("duplicate")
            else: seen[key] = iid
        if e.get("conf", 0) < CONF_MIN: fl.append("low_conf")
        out[iid] = fl
    return out


REASON = {"wrong_total": "reconcile:total", "tax_mismatch": "tax_rate", "missing_po": "missing:po", "duplicate": "duplicate"}


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 (max(0.0, c - h), min(1.0, c + h))


def boot(rows, num, den, reps=2000, seed=7):
    """95 percent interval for sum(num)/sum(den), resampling invoices."""
    r = random.Random(seed); n = len(rows); vals = []
    for _ in range(reps):
        s = [rows[r.randrange(n)] for _ in range(n)]
        d = sum(x[den] for x in s)
        if d: vals.append(sum(x[num] for x in s) / d)
    vals.sort()
    return (vals[int(0.025 * len(vals))], vals[int(0.975 * len(vals)) - 1]) if vals else (0, 0)


def cost(pages, flagged, leaked, clean):
    """Hypothetical cost per clean invoice. Inputs are assumptions, not prices; change them."""
    people = (flagged * REVIEW_MIN + leaked * REWORK_MIN) / 60 * RATE_PER_HOUR
    return float((PAGE_PRICE * pages + Decimal(str(people))) / clean) if clean else None


def score(a):
    folder = Path(a.dir)
    order = json.loads((folder / "manifest.json").read_text())
    global CONF_MIN
    CONF_MIN = a.conf
    ext = json.loads((folder / f"extractions{a.tag}.json").read_text())
    flags = rules([(i, ext[i]) for i in order])
    rows = []
    for iid in order:
        t, e = json.loads((folder / f"{iid}.json").read_text()), ext[iid]
        ok = {k: field_ok(k, t, e) for k in HEADER}
        full, nod, n_gt, n_ex = match_rows(t, e), match_rows(t, e, False), len(t["lines"]), len(e["lines"])
        doc = all(ok.values()) and full == n_gt == n_ex
        amts = [D(l["amount"]) for l in e["lines"]]
        sub, tax, tot = D(e.get("subtotal")), D(e.get("tax")), D(e.get("total"))
        rec = (sub is not None and None not in amts and abs(sum(amts, Decimal(0)) - sub) <= TOL and None not in (tax, tot) and abs(sub + tax - tot) <= TOL)
        fl, clean = flags[iid], t["defect"] == "none"
        rows.append({"id": iid, "template": t["template"], "tier": t["tier"], "defect": t["defect"], "pages": t["pages"],
                     "hdr_ok": sum(ok.values()), "hdr_n": len(HEADER), "rows_gt": n_gt, "rows_ext": n_ex, "rows_ok": full, "rows_ok_nodesc": nod,
                     "doc_ok": int(doc), "reconcile": int(rec), "flags": "|".join(fl), "flagged": int(bool(fl)), "clean": int(clean),
                     "stp": int(clean and not fl and doc), "leaked": int(not fl and not doc), "justified": int(bool(fl) and not doc),
                     "needless": int(bool(fl) and doc), "caught": int(not clean and bool(fl)),
                     "right_reason": int(not clean and REASON[t["defect"]] in fl), "seconds": round(e["seconds"], 3),
                     **{f"ok_{k}": int(v) for k, v in ok.items()}})
    with open(folder / f"results{a.tag}.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)

    def block(rs):
        cl = [r for r in rs if r["clean"]]; sd = [r for r in rs if not r["clean"]]
        pr = lambda k, n: {"k": k, "n": n, "p": k / n if n else None, "ci": wilson(k, n)}
        o = {"n": len(rs), "n_clean": len(cl), "n_seeded": len(sd)}
        o["header"] = {"p": sum(r["hdr_ok"] for r in rs) / sum(r["hdr_n"] for r in rs), "ci": boot(rs, "hdr_ok", "hdr_n")}
        o["lines"] = {"p": sum(r["rows_ok"] for r in rs) / sum(r["rows_gt"] for r in rs), "ci": boot(rs, "rows_ok", "rows_gt"),
                      "precision": sum(r["rows_ok"] for r in rs) / max(1, sum(r["rows_ext"] for r in rs)),
                      "nodesc": sum(r["rows_ok_nodesc"] for r in rs) / sum(r["rows_gt"] for r in rs)}
        o["doc"] = pr(sum(r["doc_ok"] for r in rs), len(rs))
        o["reconcile"] = pr(sum(r["reconcile"] for r in cl), len(cl))
        o["stp"] = pr(sum(r["stp"] for r in cl), len(cl))
        o["clean_flow"] = {k: sum(r[k] for r in cl) for k in ("stp", "needless", "justified", "leaked")}
        o["false_stop"] = pr(sum(r["flagged"] for r in cl), len(cl))
        o["catch"] = pr(sum(r["caught"] for r in sd), len(sd))
        o["right_reason"] = pr(sum(r["right_reason"] for r in sd), len(sd))
        o["catch_by_type"] = {d: pr(sum(r["caught"] for r in sd if r["defect"] == d), sum(1 for r in sd if r["defect"] == d)) for d in DEFECTS}
        o["sec_per_page"] = sum(r["seconds"] for r in rs) / sum(r["pages"] for r in rs)
        o["sec_per_invoice"] = sum(r["seconds"] for r in rs) / len(rs)
        o["cost_per_clean"] = cost(sum(r["pages"] for r in cl), sum(r["flagged"] for r in cl), sum(r["leaked"] for r in cl), len(cl))
        # independence model: each header field and each row is one unit that is right with probability p
        units = sum(r["hdr_n"] + r["rows_gt"] for r in rs); right = sum(r["hdr_ok"] + r["rows_ok"] for r in rs); p = right / units
        o["indep"] = {"unit_acc": p, "mean_units": units / len(rs), "predicted_doc": sum(p ** (r["hdr_n"] + r["rows_gt"]) for r in rs) / len(rs)}
        return o
    res = {"overall": block(rows), "by_tier": {t: block([r for r in rows if r["tier"] == t]) for t in TIERS},
           "by_template": {t: block([r for r in rows if r["template"] == t]) for t in TEMPLATES},
           "doc_grid": {f"{tp}/{ti}": [sum(r["doc_ok"] for r in rows if r["template"] == tp and r["tier"] == ti), sum(1 for r in rows if r["template"] == tp and r["tier"] == ti)]
                        for tp in TEMPLATES for ti in TIERS},
           "field_acc": {k: sum(r[f"ok_{k}"] for r in rows) / len(rows) for k in HEADER},
           "field_acc_by_tier": {t: {k: sum(r[f"ok_{k}"] for r in rows if r["tier"] == t) / sum(1 for r in rows if r["tier"] == t) for k in HEADER} for t in TIERS},
           "flag_counts": {}, "assumptions": {"review_min": REVIEW_MIN, "rework_min": REWORK_MIN, "rate_per_hour": RATE_PER_HOUR, "page_price": str(PAGE_PRICE), "conf_min": CONF_MIN}}
    for r in rows:
        for f in filter(None, r["flags"].split("|")):
            f = "missing:" + f[8:].split("+")[0] if f.startswith("missing:") and f != "missing:po" else f
            res["flag_counts"][f] = res["flag_counts"].get(f, 0) + 1
    (folder / f"results{a.tag}.json").write_text(json.dumps(res, indent=1))
    o = res["overall"]
    print(f"invoices {o['n']} (clean {o['n_clean']}, seeded {o['n_seeded']}); header {o['header']['p']:.3f}; lines {o['lines']['p']:.3f}; doc {o['doc']['p']:.3f}; "
          f"reconcile {o['reconcile']['p']:.3f}; STP {o['stp']['p']:.3f}; catch {o['catch']['p']:.3f}; false stop {o['false_stop']['p']:.3f}")


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
    g = sp.add_parser("generate"); g.add_argument("dir"); g.add_argument("--seed", type=int, default=2026); g.add_argument("--per-cell", type=int, default=19)
    r = sp.add_parser("run"); r.add_argument("dir"); r.add_argument("--engine", choices=["baseline", "vendor"], default="baseline"); r.add_argument("--prep", choices=["none", "cleanup"], default="none"); r.add_argument("--tag", default="")
    s = sp.add_parser("score"); s.add_argument("dir"); s.add_argument("--tag", default=""); s.add_argument("--conf", type=float, default=CONF_MIN)
    a = ap.parse_args()
    {"generate": generate, "run": run, "score": score}[a.cmd](a)

What can this test not tell you?

  • How a real engine performs. The baseline is regex and Tesseract. A trained extraction model, a different OCR engine or a vendor service will behave differently, and these numbers do not predict them.
  • How real invoices look. Four generated templates are far fewer than the layouts in a real mailbox. Real invoices have logos, stamps, handwriting, folded pages and credit notes, none of which are here.
  • How your vendors behave. The mix of templates and tiers is our choice. A different mix gives different overall numbers, and the overall numbers are the least meaningful ones.
  • How a person would score a disputed field. The scorer is exact after normalization. Some mismatches, such as a trailing period in a vendor name, a person might accept.
  • Anything about ERP posting, approvals, payment or security.

Treat the numbers as a demonstration of the method. Three lessons should travel. One is the arithmetic from field accuracy to straight through. Another is reporting leaks and false stops with the catch rate. The third is a cost model whose assumptions are written out.

What do published benchmarks say, and how do you use them?

Use them to build the shortlist, not to replace the test. A vendor figure comes from the vendor's own documents, scoring rules and file mix, none of which match yours. Our OCR accuracy benchmark post describes how to run a benchmark on your own documents, and this guide is the longer version for invoices.

One benchmark is ours to report. This box is separate from the Tesseract test above, and its numbers are not comparable to it.

DocsAPI and its 2026 benchmark

DocsAPI is a document intelligence API built by HyperVerge for SMB lending and fintech, and it processes about 4 million pages a month. Its own 2026 benchmark on 1,700 real documents reported 97 to 99% on clean typed English, 93% on invoice line items and 91% on multi-page bank statement tables. It reported 81% on multilingual documents, 78% on handwritten documents and 76% on phone receipts, at about 1.1 seconds per page.

Pricing starts from $0.02 per page, with volume discounts above 100,000 pages a month. Classification and tables are included. Access starts with a demo, then a free 30 day trial for qualified lenders. DocsAPI is built mainly for lending and fintech document flows, so check that it fits an accounts payable workload before you test it. Our accounts payable OCR guide covers what AP teams usually need.

Common questions

Frequently asked questions

Use 200 to 500 of your own invoices, spread over vendors, layouts, page counts and image quality. At 200, a result near 90% has a 95% interval of about 85.1% to 93.4%. At 20 it spans 70 to 97. Report each quality tier separately, since a tier of 76 invoices can show large gaps but not rank two close engines.

It is the share of invoices that pass every exception rule and have correct data, with no human touch. Define the rules first. In our baseline run, 103 of 256 clean invoices (40.2%) went straight through with plain Tesseract and 118 (46.1%) after preprocessing, while header field accuracy was above 97%.

Every field and row must be right for an invoice to count, and errors cluster on particular layouts and scans. If 15 fields are each 97% right and independent, only 63.3% of invoices are fully right. In our run the independence model predicted 8.6% for plain Tesseract and 52.0% happened, because one bordered template failed almost entirely.

A catch rate means little without the false stop rate and the right-reason share. Our rules flagged 47 of 48 seeded defects, but also stopped 58.2% of clean invoices in the plain run and 49.2% after preprocessing. A pipeline that stops everything catches everything. 46 of the 48 were flagged for the right reason.

Generate invoices with known ground truth, render them in several layouts and quality tiers, and seed a known share of defects. The script in this guide does that with reportlab and a seeded random generator. For a vendor, replace the extractor with an adapter that returns the same fields, and keep the scorer and rules unchanged.

Count software, review and rework. Under our hypothetical inputs of 4 minutes per flagged invoice, 15 minutes per leaked error, $30 an hour and $0.02 a page, the baseline cost $1.31 (plain) and $1.36 (preprocessed) per clean invoice. The page price was about 1% of one manual review. Stops and leaks drove the cost.

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.