Skip to content

Receipts and invoices to validated JSON

Read receipts and invoices with ppocr-v6, extract merchant, date, line items and totals by rules, check that the numbers add up, and read only the items that fail again with paddleocr-vl. Items that still fail go to a review file instead of into your database.

Models: ppocr-v6, paddleocr-vl · Without a key: Smoke run · Languages: Python, TypeScript, Go · Try in Playground (opens in a new tab) · Source on GitHub (opens in a new tab)

A receipt is a photo, and the accounting system wants JSON. OCR gives lines of text with boxes, and everything after that is yours: which line is the total, whether 6.000 is six or six thousand, and above all whether the result can be trusted without a person looking at it.

The constraints that shape the code:

  • A wrong number is worse than a missing one. The pipeline never guesses. Every result passes checks (items add up to the subtotal, subtotal minus discount plus tax is the total, the date exists and is not in the future, the lines it was read from were read with confidence). What fails is read again, and what still fails is written to needs_review.jsonl.
  • The better model is 8 times the price. ppocr-v6 costs 0.25 credits per image and paddleocr-vl 2 credits per page. Using the second one for every document would make the expensive path the default, so it runs only for the items that fail.
  • Rate limits. The free tier limits each project per minute and per day by the weight of the model, and paddleocr-vl is the heaviest class, with the smallest limits. When the server answers 429, the client waits for Retry-After (or for X-RateLimit-Reset when X-RateLimit-Remaining is 0) and carries on; it does not pace itself. The smoke documents fit the free tier, the full set needs a key.
  • Reruns must not cost twice. A crashed or repeated run should not pay for documents it already read.
  • Amounts are printed in several ways: 6.000 and 1,250.00 and 1.250,00, with Rp, $ or no mark, and negatives as -23.56, (23.56) or 23.56-.

Pipeline: ppocr-v6, rules, validation, fallback to paddleocr-vl, needs_review.jsonl

  1. With a key, upload the image once (POST /v1/images, free) and keep the handle. On the free tier there is no upload: the image goes inline as base64 on each call.
  2. POST /v1/ocr with ppocr-v6: lines with boxes and confidence.
  3. Group the lines into rows by vertical position, then read the fields from the rows: merchant, date, currency, line items, subtotal, discount, service, tax, total. Each value keeps its provenance: the model, the line indices and the box it was read from.
  4. Validate. All checks must pass.
  5. On failure, POST /v1/documents/parse with paddleocr-vl on the same handle. Its layout blocks (tables as HTML) are turned into the same kind of rows, so the same rules and the same validation apply.
  6. Validated receipts go to receipts.jsonl; the rest go to needs_review.jsonl with the reasons and the best attempt as a starting point.

The output of one item is described by output.schema.json. It keeps the receipt of every attempt, so the strategies “OCR only” and “hybrid” can be scored from one run.

Setup and run in each language

Commands for the smoke set, run from the repository root. The smoke set needs no API key: it runs on the free tier. The full set needs a key; the cap makes the client refuse calls that could exceed it.

Requires: Python 3.12, uv 0.5

cd use-cases/03-receipts-to-json/python
uv sync --frozen
uv run --frozen python main.py --manifest ../assets/smoke/manifest.json --out out
# Full set: the full dataset is a release asset of the repository and needs an API key; unpack it and pass its manifest.
export FOLDBUN_API_KEY="fbs_..."
export FOLDBUN_MAX_CREDITS=180
uv run --frozen python main.py --manifest ../assets/full.json --out out
# no key needed: the smoke run uses the free tier. With FOLDBUN_API_KEY set the calls are charged at list price;
# FOLDBUN_MAX_CREDITS=5 (optional) makes the client refuse calls that could pass it
cd use-cases/03-receipts-to-json/python
uv run main.py --out out # the 4 smoke documents: about 3 credits at list price, free on the free tier
uv run main.py --out out --resume # after an interruption: finished items are not read again
uv run main.py --out out --no-fallback # OCR only
# or: cd ../typescript && pnpm install && node main.ts --out out # the same pipeline in TypeScript
# or: cd ../go && go run . --out out # the same pipeline in Go

Arguments: --manifest, --out, --concurrency (default 4), --limit, --resume, --no-fallback. Outputs: result.json (format of contract/result.schema.json), receipts.jsonl, needs_review.jsonl, and items/ with one file per finished item (used by --resume).

The paddleocr-vl fallback runs on the free tier too, within its heavy-class limits. If the server refuses it (a 429 that outlasts the retries, or a 403), the item stays with what ppocr-v6 read and goes to review, and the run still completes.

To score a run: python evaluate.py --result out/result.json --truth assets/smoke/truth.json.

The full set (60 CORD receipts and 20 synthetic invoices, 11 MB) is a release asset of the repository (see datasets/README.md). Its manifest is committed as assets/full.json; the images and the ground truth are in the archive. Extract it into assets/, then run the reference implementation on it from the repository root. Reading all 80 documents is at most 180 credits at list price (every document read by ppocr-v6 and again by paddleocr-vl), usually about 60. The full run needs FOLDBUN_API_KEY (it exits with code 2 without one):

tar xzf 03-receipts-to-json-full.tar.gz -C use-cases/03-receipts-to-json/assets
export FOLDBUN_API_KEY="fbs_..."
uv run python -m harness live --size full --uc 03 --max-credits 180 --dry-run # the plan, nothing is sent
uv run python -m harness refresh --size full --uc 03 --max-credits 180 # runs, scores, writes expected/full.json and expected/full-summary.json, then `uv run python -m harness snippets`

harness live runs the same and only checks the result against the floors in usecase.toml [quality]; the metrics are those of evaluate.py --result out/result.json --truth assets/truth.json.

The documents are split by number: the odd-numbered ones (cord-001, inv-003, …) are the development half, on which the extraction rules were written and tuned, and the even-numbered ones are the held-out half, which was only ever run, never read. evaluate.py prints the metrics for all documents and, with the prefix heldout_, for the held-out half alone (heldout_validation_pass_rate, …); the [quality] floors apply to the held-out metrics, because numbers measured on the documents the rules were tuned on would overstate the result.

The key is derived from the sha256 of the file and the model, so the same document and model always send the same key. For 24 hours the API replays the stored answer for a repeated key without running or charging the call. The key also names the program that sends it: the API compares the bytes of the request, so two programs that write the same JSON with different spacing must not share a key (the second one gets 409 idempotency_conflict).

Source: python/main.py (opens in a new tab)

def idempotency_key(image_sha256: str, model: str) -> str:
"""Same file and model give the same key (at most 128 printable ASCII characters). Within 24 hours the API
replays the stored answer for a repeated key without running or charging the call, so a restarted run is free.
The key names this program ("py"): the API compares the bytes of the request, and another program that writes
the same JSON with different spacing would get `409 idempotency_conflict` under a shared key."""
return f"r03-py-{image_sha256}-{model}"

Amounts come in both number formats. The rule: when both marks occur the last one is the decimal mark, a repeated mark is a thousands mark, and a single mark followed by exactly three digits is a thousands mark. That makes 6.000 six thousand, which is right for the rupiah receipts in the set and wrong for a three-decimal currency. Money is never added as a float: Python uses Decimal, TypeScript a small exact decimal type over BigInt (decimal.ts), Go the same over math/big (decimal.go), so that 0.10 + 0.20 is 0.30 in the checks. Amounts become JSON numbers only when they are written to the output.

Source: python/amounts.py (opens in a new tab)

def parse_number(num: str) -> Decimal | None:
"""Digits with "." and "," in either convention: "1,234.50", "1.234,50", "6.000", "4,500", "12,5", "1 234,50".
The rule: when both marks occur, the last one is the decimal mark. A mark that occurs several times is a thousands
mark. A single mark followed by exactly three digits is a thousands mark ("6.000" is six thousand, as on the
Indonesian receipts of the CORD set); followed by one or two digits it is a decimal mark. "0.500" is a decimal.
"""
num = num.replace("\u00a0", "").replace("\u202f", "")
marks = [c for c in num if c in ".,"]
if not marks:
return Decimal(num)
last = max(num.rfind("."), num.rfind(","))
if len(set(marks)) == 2: # "1.234,50" or "1,234.50": the last mark is the decimal mark
return Decimal(num[:last].replace(".", "").replace(",", "") + "." + num[last + 1 :])
mark = marks[0]
if len(marks) > 1: # "1.250.000": thousands marks only
groups = num.split(mark)
return Decimal("".join(groups)) if all(len(g) == 3 for g in groups[1:]) else None
head, tail = num.split(mark)
if len(tail) == 3 and head != "0" and 1 <= len(head) <= 3:
return Decimal(head + tail)
return Decimal(f"{head}.{tail}") if head else None
def parse_amount(text: str) -> Decimal | None:
"""The amount in a cell such as "$1,234.50", "-$23.56", "(12.00)", "12.00-" or "Rp 45.000"; None when there is none."""
found = amounts_in(text)
return found[-1][0] if found else None
def amounts_in(text: str) -> list[tuple[Decimal, str | None]]:
"""Every money-looking token of the text as (signed value, currency mark), left to right."""
out = []
for m in AMOUNT_RE.finditer(text):
value = parse_number(m["num"])
if value is None:
continue
post = (m["post"] or "").strip().upper()
# A minus (ASCII or U+2212) before the number or the mark, "(12.00)", "12.00-" and "12.00 CR" all mean negative.
if m["pre"] in ("-", "−") or m["sign"] or (m["pre"] == "(" and post == ")") or post in ("-", "CR"):
value = -value
out.append((value, m["cur"]))
return out

OCR returns lines, not rows. Lines whose vertical centres are within 0.6 of a median line height share a row.

Source: python/extract.py (opens in a new tab)

def rows_from_ocr(lines: list) -> list[Row]:
"""Group OCR lines into rows. Lines whose vertical centres are within 0.6 of a median line height share a row."""
cells = [Cell(ln["text"], ln["bbox"], i, ln["confidence"], ln["bbox"][3] - ln["bbox"][1]) for i, ln in enumerate(lines) if ln["text"].strip()]
if not cells:
return []
tolerance = 0.6 * statistics.median(c.bbox[3] - c.bbox[1] for c in cells)
centre = lambda c: (c.bbox[1] + c.bbox[3]) / 2 # noqa: E731
rows, anchor = [], None
for cell in sorted(cells, key=centre):
if rows and abs(centre(cell) - anchor) <= tolerance:
rows[-1].append(cell)
else:
rows.append([cell])
anchor = centre(cell)
return [Row(sorted(r, key=lambda c: c.bbox[0])) for r in rows]

The first rule that matches a row decides which field it is, so “subtotal” is tested before “total”, and payment rows (cash, change, card) are recognised only to be skipped. A row is a summary row only when an amount follows its label, so a heading such as “Tax invoice” does not end the item rows. A discount printed among the items, above the subtotal row, is a negative item (the subtotal already includes it).

Source: python/extract.py (opens in a new tab)

# Which printed label is which field. The first rule that matches a row wins, so "subtotal" is tested before "total".
# Payment rows (cash, change, card) are recognised only to be skipped: they carry amounts that are not fields.
SUMMARY_RULES = [
("skip", re.compile(r"cash|change|kemba|uang|tender|paid|payment|visa|mastercard|debit|credit|go-?pay|ovo|qris|\bqr\b|card|tunai|round", re.I)),
# "Net total" / "net sales" print the sum of the items; "ITEMS: 13 561,800" is a count of items followed by that sum.
("subtotal", re.compile(r"sub\s?-?\s?total|zwischensumme|sous-total|\bnet\s?(total|sales)|\bitems?\s?[:.]?\s?\d+\b", re.I)),
("discount", re.compile(r"discount|\bdisc\b|diskon|rabatt|remise|potongan|savings", re.I)),
("service", re.compile(r"service|servis|\bsvc\b|\bsrv\b", re.I)),
# "P.Rest" / "PResto" / "Pb 1" are the Indonesian restaurant tax (pajak restoran, PB1) as receipts abbreviate it.
("tax", re.compile(r"\btax|\bvat\b|\bgst\b|pajak|\bppn\b|\bpb\s?1\b|\bp\.?\s?rest(o|aurant)?\b|mwst|\btva\b|\biva\b", re.I)),
# "T O T A L" (letters spaced out, as some thermal printers and their OCR give it) is a total too.
("total", re.compile(r"total|\bt\s?o\s?t\s?a\s?l\b|amount due|balance due|grand|jumlah|gesamt|summe|to pay", re.I)),
]
STRONG_TOTAL = re.compile(r"grand|amount due|balance due|total bayar|to pay", re.I)
HEADER_WORDS = re.compile(r"description|item|qty|quantity|unit price|price|amount|harga|jumlah", re.I)
META_ROW = re.compile(r"\b(date|time|due|invoice|no|tel|phone|cashier|kasir|table|order|bill to|terms)\b", re.I)
NOT_A_NAME = re.compile(r"invoice|receipt|\bbill\b|\btax\b|faktur|struk|nota|\bdate\b|total|\btel\b|phone", re.I)
CURRENCY_TOKEN = re.compile(r"[$€£¥]|Rp\.?|IDR|USD|EUR|GBP|AUD|CAD", re.I)
def summary_kind(row: Row) -> str | None:
"""Which summary field the row is, or None. A summary row is a label followed by an amount: a row whose only amount comes
before the label ("9 Rue des Tilleuls Tax invoice", a street number next to a heading) or that has no amount at all
("Tax invoice") is not one, so it neither ends the item rows nor gives a value."""
text = row.text
for kind, rx in SUMMARY_RULES:
m = rx.search(text)
if m and (kind == "skip" or amounts_in(text[m.end() :])):
return kind
return None

Line items come from the rows above the first summary row. A description-only row waits for the numeric row under it.

Source: python/extract.py (opens in a new tab)

def parse_item_row(row: Row):
"""(quantity, description, unit price, amount) of one row; any part may be None. "1 Nasi (MLY) 6.000" and the numeric row
"1 4,500 4,500" of a two-line item are both read here."""
# A currency mark printed apart from its number ("82,37 €", "$ 12.00") is dropped, so the number ends the row.
tokens = [t for t in row.text.split() if not CURRENCY_TOKEN.fullmatch(t)]
qty = None
if len(tokens) > 1 and re.fullmatch(r"\d{1,3}", tokens[0]):
qty, tokens = Decimal(tokens[0]), tokens[1:]
elif tokens and (m := re.fullmatch(r"(\d{1,3})\s?x|x\s?(\d{1,3})", tokens[0], re.I)):
qty, tokens = Decimal(m[1] or m[2]), tokens[1:]
numeric = [bool(re.search(r"\d", t)) and len(amounts_in(t)) == 1 and not re.search(r"[A-Za-z]{2}", re.sub(r"Rp|IDR", "", t)) for t in tokens]
trailing = len(numeric)
while trailing and numeric[trailing - 1]:
trailing -= 1
description = " ".join(tokens[:trailing]).strip(" -:")
prices = [amounts_in(t)[0][0] for t in tokens[trailing:]]
if qty is None and len(prices) >= 3 and prices[-3] == prices[-3].to_integral_value(): # table row: quantity, unit price, amount
qty = prices[-3]
return qty, description or None, (prices[-2] if len(prices) > 1 else None), (prices[-1] if prices else None)
def _quantity_row(parsed) -> bool:
"""A description followed by one lone small whole number (the quantity of a table row whose prices wrapped to the next line)."""
qty, description, unit, amount = parsed
return bool(description) and qty is None and unit is None and amount is not None and amount < 1000 and amount == amount.to_integral_value()
def extract_items(rows: list[Row], model: str, width: int | None, header_at: int | None, stop_at: int) -> list:
"""Line items from the rows between the table header (when there is one) and the first summary row.
A row with a description and an amount is an item. A row with a description only is held back for the next row
when that row has an amount and no description (the two-line layout of many receipts). Without a table header, an
amount must sit in the right 40 percent of the image: that keeps addresses and phone numbers out.
"""
items, pending = [], None
body = rows[(header_at + 1 if header_at is not None else 0) : stop_at]
for n, row in enumerate(body):
# Wrapped table row: "Equipment rental, per day 1" and then "71,96 € 71,96 €" (a photographed table whose numbers
# sit a little lower than the text). A description ending in a lone small integer, followed by a row that is only
# two or more numbers, is one item: the integer is the quantity, not the amount.
if header_at is not None and n + 1 < len(body):
head, tail = parse_item_row(row), parse_item_row(body[n + 1])
if _quantity_row(head) and not tail[1] and tail[2] is not None:
row = Row(row.cells + body[n + 1].cells)
body[n + 1] = Row([])
if not row.cells:
continue
qty, description, unit, amount = parse_item_row(row)
if header_at is None and META_ROW.search(row.text):
continue
if amount is None:
pending = (description, row) if description and len(description) > 2 and not HEADER_WORDS.fullmatch(description) else None
continue
if header_at is None and width and description and max(c.bbox[2] for c in row.cells if c.bbox) < 0.6 * width:
continue
cells = list(row.cells)
if not description and pending:
description, cells = pending[0], pending[1].cells + cells
pending = None
items.append({"description": description or "", "quantity": qty, "unitPrice": unit, "amount": amount, "_cells": cells})
return items

Source: python/validate.py (opens in a new tab)

def items_tolerance(amounts: list, subtotal) -> Decimal:
"""How far the item amounts may be from the subtotal. Normally one cent. A receipt that prints whole numbers of a large
currency (45,500 rupiah) rounds every item to the unit, so n items can add up to n/2 units away from the subtotal; that
is the receipt's rounding, not an error. Receipts with decimals, and small amounts, keep the cent."""
whole = all(a == a.to_integral_value() for a in amounts) and _d(subtotal) == _d(subtotal).to_integral_value()
return max(TOLERANCE, Decimal(len(amounts)) / 2) if whole and _d(subtotal) >= 1000 else TOLERANCE
def validate(receipt: dict, today: date) -> list[dict]:
"""Run every check. Returns [{name, passed, detail}]; a receipt is accepted when all of them passed."""
items = receipt["lineItems"]
total, subtotal = receipt["total"], receipt["subtotal"]
amounts = [_d(i["amount"]) for i in items]
items_sum = sum(amounts, Decimal(0))
checks = []
def check(name, passed, detail):
checks.append({"name": name, "passed": bool(passed), "detail": detail})
check("total_present", total is not None, "a total was found" if total is not None else "no total row was found")
check("line_items_present", items, f"{len(items)} line items")
incomplete = [n for n, i in enumerate(items) if not i["description"] or i["amount"] is None]
check("line_items_complete", not incomplete, "every item has a description and an amount" if not incomplete else f"items {incomplete} lack a description")
bad = [
n
for n, i in enumerate(items)
if i["quantity"] is not None and i["unitPrice"] is not None and abs(_d(i["quantity"]) * _d(i["unitPrice"]) - _d(i["amount"])) > TOLERANCE
]
check("line_item_arithmetic", not bad, "quantity x unit price = amount" if not bad else f"quantity x unit price differs from the amount in items {bad}")
if subtotal is not None:
check(
"items_sum_to_subtotal", abs(items_sum - _d(subtotal)) <= items_tolerance(amounts, subtotal), f"items add up to {items_sum}, subtotal is {subtotal}"
)
if total is not None:
base = _d(subtotal) if subtotal is not None else items_sum
expected = base - _d(receipt["discount"] or 0) + _d(receipt["service"] or 0) + _d(receipt["tax"] or 0)
check("total_matches_parts", abs(expected - _d(total)) <= TOLERANCE, f"subtotal - discount + service + tax is {expected}, total is {total}")
if receipt["date"]:
check("date_not_in_future", date.fromisoformat(receipt["date"]) <= today, f"date {receipt['date']}")
sources = list(receipt["sources"].items()) + [(f"lineItems[{n}]", i["source"]) for n, i in enumerate(items)]
low = [(n, c) for n, s in sources if (c := s["confidence"]) is not None and c < CONFIDENCE_FLOOR]
check(
"confidence_floor",
not low,
f"every field line has confidence of at least {CONFIDENCE_FLOOR}" if not low else f"low confidence for {[n for n, _ in low]}",
)
return checks
def passed(checks: list[dict]) -> bool:
return all(c["passed"] for c in checks)

Source: python/main.py (opens in a new tab)

ocr = client.post(
"/v1/ocr",
{"model": OCR_MODEL, "image": image, "options": {"words": False}},
idempotency_key=idempotency_key(sha, OCR_MODEL),
tag=item["id"],
)
attempts.append(attempt(OCR_MODEL, extract_receipt(rows_from_ocr(ocr["lines"]), OCR_MODEL, ocr["image"]["width"]), today))

With a key the second call reads the same handle: no second upload and no second image on the wire. On the free tier the image is sent inline in both calls.

Source: python/main.py (opens in a new tab)

if use_fallback and not attempts[0]["passed"]:
try:
page = client.post(
"/v1/documents/parse",
{"model": FALLBACK_MODEL, "image": image, "options": {"blocks": True}},
idempotency_key=idempotency_key(sha, FALLBACK_MODEL),
tag=item["id"],
)
attempts.append(attempt(FALLBACK_MODEL, extract_receipt(rows_from_blocks(page["blocks"]), FALLBACK_MODEL, page["image"]["width"]), today))
except sc.StackError as err:
if err.code == "budget_exceeded":
raise
# A key without access to the model (model_locked) or a failed call: the item stays with what ppocr-v6 read.
attempts.append({"model": FALLBACK_MODEL, "receipt": None, "passed": False, "checks": [], "note": err.code})

Source: python/main.py (opens in a new tab)

# The client allows `--concurrency` requests in flight and waits out a 429 by itself, so the worker threads here only
# keep it busy. One item is one thread: its calls are sequential (OCR, then maybe parse).
code, lock = 0, threading.Lock()
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = {pool.submit(process_item, client, item, base, use_fallback, today): item for item in todo}
for future in as_completed(futures):
item = futures[future]
try:
entry = future.result()
except sc.StackError as err:
print(f"{item['id']}: {err.status} {err.code}: {err.message}" + (f" (request {err.request_id})" if err.request_id else ""), file=sys.stderr)
if err.code in ("model_locked", "budget_exceeded"):
code = EXIT_TIER if err.code == "model_locked" else EXIT_BUDGET
for f in futures:
f.cancel()
continue
entry = {
"id": item["id"],
"status": "error",
"calls": client.calls(item["id"]),
"output": None,
"error": {"status": err.status, "code": err.code, "message": err.message},
}
entries[item["id"]] = entry
if entry["status"] == "ok":
save_done(args.out, entry, use_fallback)
with lock:
print(f"{item['id']}: {entry['output']['outcome']} ({entry['output']['model']})")

Source: python/main.py (opens in a new tab)

def item_file(out: Path, item_id: str) -> Path:
return out / "items" / f"{item_id}.json"
def load_done(out: Path, item: dict, base: Path, use_fallback: bool) -> dict | None:
"""The saved entry of an item finished by an earlier run of this directory, when the file, the rules and the options are unchanged."""
path = item_file(out, item["id"])
if not path.exists():
return None
saved = json.loads(path.read_text())
key = [hashlib.sha256((base / item["image"]).read_bytes()).hexdigest(), PIPELINE, use_fallback]
return saved["entry"] if saved["key"] == key and saved["entry"]["status"] == "ok" else None
def save_done(out: Path, entry: dict, use_fallback: bool):
"""One small file per finished item, written atomically, so a killed run loses at most the items in flight."""
path = item_file(out, entry["id"])
path.parent.mkdir(parents=True, exist_ok=True)
clean = {k: v for k, v in entry.items() if k != "_sha256"}
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps({"key": [entry["_sha256"], PIPELINE, use_fallback], "entry": clean}))
os.replace(tmp, path)

Source: python/main.py (opens in a new tab)

# What no model could make pass goes to a person, with the best receipt as a starting point and the reasons.
with (args.out / "needs_review.jsonl").open("w") as review, (args.out / "receipts.jsonl").open("w") as good:
for entry in done:
out = entry["output"]
if out is None:
continue
if out["outcome"] == "validated":
good.write(json.dumps({"id": entry["id"], "model": out["model"], "receipt": out["receipt"]}, ensure_ascii=False) + "\n")
else:
reasons = [c["detail"] for c in out["checks"] if not c["passed"]]
review.write(json.dumps({"id": entry["id"], "reasons": reasons, "model": out["model"], "receipt": out["receipt"]}, ensure_ascii=False) + "\n")

The numbers come from evaluate.py. Until a live run is recorded they come from expected/offline.json, which was produced against the offline fake API with hand-written responses (fixtures/synthetic.json). They show how the pipeline behaves, not how the models perform, and the offline run says nothing about latency.

Smoke set (4 documents), offline fixtures:

Metric Value
items 4
items_scored 4
total_accuracy 1
date_accuracy 1
line_item_count_accuracy 1
merchant_accuracy 1
accepted_total_accuracy 1
accepted_date_accuracy 1
accepted_line_item_count_accuracy 1
accepted_merchant_accuracy 1
ocr_only_total_accuracy 1
ocr_only_date_accuracy 1
ocr_only_line_item_count_accuracy 1
ocr_only_merchant_accuracy 1
validation_pass_rate 1
ocr_only_validation_pass_rate 0.75
fallback_rate 0.25
needs_review_rate 0
ocr_only_needs_review_rate 0.25
ocr_only_cost_per_1000_list 250
hybrid_cost_per_1000_list 750
hybrid_cost_per_1000_charged 750

Full set (80 documents), live run; filled in from expected/full-summary.json once a maintainer has recorded one:

Metric Value
items 80
items_scored 80
total_accuracy 0.9625
date_accuracy 1
line_item_count_accuracy 0.8375
merchant_accuracy 0.9
accepted_total_accuracy 0.9851
accepted_date_accuracy 1
accepted_line_item_count_accuracy 0.9104
accepted_merchant_accuracy 0.9444
ocr_only_total_accuracy 0.9
ocr_only_date_accuracy 0.95
ocr_only_line_item_count_accuracy 0.7625
ocr_only_merchant_accuracy 0.75
validation_pass_rate 0.8375
ocr_only_validation_pass_rate 0.7125
fallback_rate 0.2875
needs_review_rate 0.1625
ocr_only_needs_review_rate 0.2875
ocr_only_cost_per_1000_list 250
hybrid_cost_per_1000_list 825
hybrid_cost_per_1000_charged 825
heldout_total_accuracy 0.95
heldout_date_accuracy 1
heldout_line_item_count_accuracy 0.825
heldout_merchant_accuracy 0.8
heldout_accepted_total_accuracy 1
heldout_accepted_date_accuracy 1
heldout_accepted_line_item_count_accuracy 0.9032
heldout_accepted_merchant_accuracy 0.875
heldout_ocr_only_total_accuracy 0.875
heldout_ocr_only_date_accuracy 0.9
heldout_ocr_only_line_item_count_accuracy 0.775
heldout_ocr_only_merchant_accuracy 0.7
heldout_validation_pass_rate 0.775
heldout_ocr_only_validation_pass_rate 0.7
heldout_fallback_rate 0.3
heldout_needs_review_rate 0.225
heldout_ocr_only_needs_review_rate 0.3
heldout_ocr_only_cost_per_1000_list 250
heldout_hybrid_cost_per_1000_list 850
heldout_hybrid_cost_per_1000_charged 850

Metric names: *_accuracy are the share of documents whose field matches the ground truth (total exact; date exact where the truth has one; line-item count exact); with no prefix, the receipts the pipeline delivered, with accepted_ only those that passed validation, with ocr_only_ what ppocr-v6 alone produced. validation_pass_rate is the share accepted without review; fallback_rate the share read again; needs_review_rate the share that still failed. Costs are per 1,000 documents at list price (charged is what the recorded run was debited; plan with the list price).

One ppocr-v6 call is 0.25 credits and one paddleocr-vl call is 2 credits at list price. For N documents with a fallback rate f the list price is 0.25 N + 2 f N: 250 credits per 1,000 documents for OCR only, and 250 + 2,000 f for the hybrid, so f = 0.1 gives 450. A smoke run is free on the free tier (the run prints its list price labelled “free tier, not charged”); a keyed run is charged these list prices. Idempotent replays, which need a key, are not charged.

Run Calls List price (credits) Charged (credits)
smoke 5 3 2
full 103 66 66
  • Sums cannot see a description attached to the wrong amount. On the photographed invoice the table is tilted, so the cells of one table row fall into different rows. The check that every item has a description catches that case, but a pairing error with complete descriptions would pass. Row geometry is the fragile part of the rules.
  • The rules are for receipts and simple invoices. A new layout needs new rules; forms with many variable fields are better read with paddleocr-vl directly and located by layout block.
  • Not every field exists. The CORD receipts in the set have no date, and their merchant is blurred, so the merchant and date are null there; the checks only apply to what is found.
  • Number formats. 6.000 is read as six thousand. Currencies with three decimals, or a document that mixes formats, need a hint that this code does not take. 01/02/2026 is read day first.
  • OCR confusions such as O for 0 are not repaired; they fail validation and go to the fallback.
  • Two readings of the same image can differ slightly. Between two runs of the 80-document set, 2 documents came back with a different text in one place (a title block, one digit of an amount). Results are stable enough to compare runs, not to expect them identical; the idempotency key is what makes a repeated run return the stored answer.
  • Handwriting, faded thermal paper and creased photos reduce the quality of both models; the validation then sends more items to review.
  • No tax or accounting judgement. The checks are arithmetic, not compliance.
  • With a key, the handle of an uploaded image is kept for 7 days at most; on 404 image_not_found the client uploads again by itself.

See Text recognition (opens in a new tab), Document parsing (opens in a new tab), Rate limits (opens in a new tab) and Billing (opens in a new tab) in the documentation.

The smoke set is 3 receipts from CORD v2 (NAVER Clova, CC BY 4.0, re-encoded as JPEG) and one synthetic invoice (CC0), generated for this repository, rendered with the perspective of a photograph. Attribution: assets/smoke/ATTRIBUTION.csv. The CORD ground truth has no merchant and no date. Rights holders can request removal of an image or dataset through the contact page (opens in a new tab).