跳转到内容

收据和发票转为经过校验的 JSON

用 ppocr-v6 读取收据和发票,按规则抽取商户、日期、明细和合计,校验金额是否对得上,只把校验失败的项用 paddleocr-vl 重读。仍然失败的项写入复核文件,不进入数据库。

模型: ppocr-v6, paddleocr-vl · 无需密钥: 冒烟运行 · 语言: Python, TypeScript, Go · 在 Playground 中试用 (在新标签页打开) · GitHub 上的源码 (在新标签页打开)

收据是一张照片,而会计系统需要 JSON。OCR 给出带框的文字行,其后的一切都要自行处理:哪一行是合计,6.000 是六还是六千,以及最重要的一点:结果能否在无人复核的情况下采信。

决定代码形态的约束:

  • 错误的数字比缺失的数字更糟。 管线从不猜测。每个结果都要通过校验:明细之和等于小计,小计减折扣加税等于合计,日期存在且不在未来,取值所依据的文字行识别置信度足够。未通过的项重读,仍未通过的项写入 needs_review.jsonl。
  • 更好的模型贵 8 倍。 ppocr-v6 每张 0.25 credits,paddleocr-vl 每页 2 credits。对每份文档都用后者,会让昂贵路径变成默认路径,因此它只处理校验失败的项。
  • 速率限制。 免费层按模型的重量级别,对每个项目分别限制每分钟和每日的调用数,paddleocr-vl 属于最重的一级,额度最小。服务端返回 429 时,客户端按 Retry-After 等待(X-RateLimit-Remaining 为 0 时按 X-RateLimit-Reset 等待)后继续,自己不做限速。smoke 文档在免费层内可以跑完,完整集合需要密钥。
  • 重跑不能重复扣费。 崩溃或重复的运行不应为已经读过的文档再次付费。
  • 金额的写法多种多样:6.000、1,250.00、1.250,00,带 Rp、$ 或不带符号,负数写作 -23.56、(23.56) 或 23.56-。

管线:ppocr-v6、规则抽取、校验、回退到 paddleocr-vl、needs_review.jsonl

  1. 使用密钥时,上传图片一次(POST /v1/images,免费),保留 handle。免费层没有上传:每次调用都以 base64 内联发送图片。
  2. POST /v1/ocr,模型 ppocr-v6:返回带框和置信度的文字行。
  3. 按纵向位置把文字行归并为行,再从行中读出字段:商户、日期、币种、明细、小计、折扣、服务费、税、合计。每个取值都保留来源:模型、文字行序号和框。
  4. 校验,全部检查通过才算通过。
  5. 失败时,对同一个 handle 调用 POST /v1/documents/parse,模型 paddleocr-vl。其版面块(表格为 HTML)被转换成同样的行,因此适用同一套规则和同一套校验。
  6. 通过校验的收据写入 receipts.jsonl;其余写入 needs_review.jsonl,附原因和最佳尝试作为人工起点。

单项输出由 output.schema.json 描述。它保留每次尝试的收据,因此可以从同一次运行同时评估“只用 OCR”和“混合”两种策略。

各语言的安装与运行

以下命令针对冒烟数据集,在仓库根目录执行。冒烟数据集不需要 API 密钥,在免费层上运行;完整数据集需要密钥,设置上限后,客户端会拒绝可能超出上限的调用。

环境要求: 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
# 完整数据集: 完整数据集是仓库的发布附件,需要 API 密钥;解压后传入其 manifest。
export FOLDBUN_API_KEY="fbs_..."
export FOLDBUN_MAX_CREDITS=180
uv run --frozen python main.py --manifest ../assets/full.json --out out
# 无需密钥:smoke 运行使用免费层。设置 FOLDBUN_API_KEY 后调用按标价扣费;
# FOLDBUN_MAX_CREDITS=5(可选)让客户端拒绝可能超出该额度的调用
cd use-cases/03-receipts-to-json/python
uv run main.py --out out # 4 份 smoke 文档:标价约 3 credits,在免费层上免费
uv run main.py --out out --resume # 中断之后:已完成的项不再重读
uv run main.py --out out --no-fallback # 只用 OCR
# 或:cd ../typescript && pnpm install && node main.ts --out out # TypeScript 版本:同样的管线、参数和输出
# 或:cd ../go && go run . --out out # Go 版本:同样的管线、参数和输出

参数:--manifest、--out、--concurrency(默认 4)、--limit、--resume、--no-fallback。输出:result.json(格式见 contract/result.schema.json)、receipts.jsonl、needs_review.jsonl,以及 items/(每个完成的项一个文件,供 --resume 使用)。

paddleocr-vl 回退在免费层上也能运行,受重量级别的限额约束。如果服务端拒绝它(重试之后仍是 429,或返回 403),该项保留 ppocr-v6 的读取结果并进入复核,运行照常完成。

评估一次运行:python evaluate.py --result out/result.json --truth assets/smoke/truth.json。

完整集合(60 张 CORD 收据和 20 张合成发票,11 MB)是仓库的发布附件(见 datasets/README.md)。其清单已提交为 assets/full.json,图片和标准答案在压缩包里。把压缩包解压到 assets/,再在仓库根目录对参考实现运行完整集合。读完 80 份文档按标价最多 180 积分(每份都由 ppocr-v6 读取并再由 paddleocr-vl 重读),通常约 60 积分。完整运行需要 FOLDBUN_API_KEY(没有密钥时以退出码 2 结束):

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 # 只打印计划,不发送请求
uv run python -m harness refresh --size full --uc 03 --max-credits 180 # 运行、打分,写入 expected/full.json 与 expected/full-summary.json,之后执行 `uv run python -m harness snippets`

harness live 运行方式相同,只按 usecase.toml 的 [quality] 下限检查结果;指标即 evaluate.py --result out/result.json --truth assets/truth.json 的输出。

文档按编号分成两半:奇数编号的(cord-001、inv-003 等)是开发集,抽取规则就是在它们上面编写和调整的;偶数编号的是留出集,只运行、从不查看。evaluate.py 输出全部文档的指标,并以前缀 heldout_ 单独输出留出集的指标(如 heldout_validation_pass_rate);[quality] 门槛针对留出集指标,因为在调规则用的文档上测得的数字会高估效果。

幂等键由文件的 sha256 和模型推导,同一份文档和同一个模型总是发送相同的键。24 小时内,API 对重复的键直接回放已存的答案,不再运行也不再计费。键里还带有发送方程序的名称:API 按请求的字节比较,两个程序即使写出内容相同、空白不同的 JSON,也不能共用一个键(后发的一方会收到 409 idempotency_conflict)。

源码: python/main.py (在新标签页打开)

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}"

金额有两种数字格式。规则:两种符号同时出现时,最后一个是小数点;重复出现的符号是千分位;单个符号后恰好三位数字时视为千分位。因此 6.000 读作六千,这对数据集中的印尼盾收据是正确的,对三位小数的币种则不正确。金额不用浮点数相加:Python 使用 Decimal,TypeScript 使用基于 BigInt 的小型精确十进制类型(decimal.ts),Go 使用基于 math/big 的同类类型(decimal.go),因此校验中 0.10 + 0.20 等于 0.30。金额只在写入输出时才转为 JSON 数字。

源码: python/amounts.py (在新标签页打开)

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 返回的是文字行,而不是表格行。纵向中心相差不超过行高中位数 0.6 倍的文字行归入同一行。

源码: python/extract.py (在新标签页打开)

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]

第一条匹配某一行的规则决定该行是哪个字段,所以“小计”先于“合计”测试;支付行(现金、找零、刷卡)只用于识别并跳过。只有标签后面带金额的行才算汇总行,所以“Tax invoice”这样的标题不会结束明细行。印在明细之间、位于小计行之上的折扣是一条负数明细(小计已包含它)。

源码: python/extract.py (在新标签页打开)

# 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

明细来自第一个汇总行之上的各行。只有品名的行等待其下方的数字行。

源码: python/extract.py (在新标签页打开)

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

源码: python/validate.py (在新标签页打开)

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)

源码: python/main.py (在新标签页打开)

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))

使用密钥时,第二次调用读取同一个 handle:不再上传,图片也不再经网络传输第二次。免费层上两次调用都内联发送图片。

源码: python/main.py (在新标签页打开)

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})

源码: python/main.py (在新标签页打开)

# 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']})")

源码: python/main.py (在新标签页打开)

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)

源码: python/main.py (在新标签页打开)

# 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")

数字来自 evaluate.py。在记录实测之前,数字来自 expected/offline.json,它由离线的模拟 API 和手写响应(fixtures/synthetic.json)产生。这些数字说明管线的行为,不说明模型的表现,离线运行也不反映延迟。

Smoke 集合(4 份文档),离线夹具:

指标 数值
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

完整集合(80 份文档),实测;维护者记录一次运行后,由 expected/full-summary.json 自动填入:

指标 数值
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

指标名称:*_accuracy 是字段与标准答案一致的文档占比(合计精确匹配;真值有日期时日期精确匹配;明细条数精确匹配);无前缀的是管线最终交付的收据,accepted_ 只含通过校验的,ocr_only_ 是仅由 ppocr-v6 产生的结果。validation_pass_rate 是无需复核即被接受的占比;fallback_rate 是被重读的占比;needs_review_rate 是仍然失败的占比。成本为每 1,000 份文档的标价(charged 是该次记录的运行实际被扣的金额;规划时请按标价)。

ppocr-v6 每次调用标价 0.25 credits,paddleocr-vl 每次 2 credits。对 N 份文档、回退比例 f,标价为 0.25 N + 2 f N:只用 OCR 时每 1,000 份 250 credits,混合时为 250 + 2,000 f,f = 0.1 时为 450。smoke 运行在免费层上免费(运行时会打印标价并标注“免费层,不扣费”);带密钥的运行按这些标价扣费。幂等回放(需要密钥)不扣费。

运行 调用次数 标价(credits) 实扣(credits)
smoke 5 3 2
full 103 66 66
  • 金额之和无法发现品名与金额错配。 在拍摄的发票上,表格是倾斜的,同一表格行的单元格落入不同的行。“每个明细都有品名”这一检查能发现这种情形,但品名齐全的错配会通过校验。行的几何关系是规则中最脆弱的部分。
  • 规则面向收据和简单发票。 新版式需要新规则;字段多变的表单更适合直接用 paddleocr-vl 读取,再按版面块定位。
  • 并非每个字段都存在。 数据集中的 CORD 收据没有日期,商户也已被模糊处理,因此商户和日期为 null;检查只针对找到的内容。
  • 数字格式。 6.000 读作六千。三位小数的币种或混用格式的文档需要本代码不接受的提示。01/02/2026 按日在前读取。
  • OCR 混淆(例如把 0 读成 O)不做修复;它们会使校验失败并进入回退。
  • 同一张图的两次读取可能略有不同。 80 份文档的两次运行之间,有 2 份文档在一处返回了不同的文本(一个标题块、金额中的一位数字)。结果的稳定程度足以比较不同运行,但不应期待逐字相同;重复运行能返回已存的答案,靠的是幂等键。
  • 手写、褪色的热敏纸和有褶皱的照片会降低两个模型的质量;此时校验会把更多的项送去复核。
  • 不做税务或会计判断。 检查只是算术,不是合规。
  • 使用密钥时,已上传图片的 handle 最多保留 7 天;遇到 404 image_not_found 时客户端会自行重新上传。

参见文档中的文字识别 (在新标签页打开)、文档解析 (在新标签页打开)、速率限制 (在新标签页打开)和计费 (在新标签页打开)。

Smoke 集合为 3 张 CORD v2 收据(NAVER Clova,CC BY 4.0,重新编码为 JPEG)和 1 张合成发票(CC0,为本仓库生成,带拍摄式的透视)。署名见 assets/smoke/ATTRIBUTION.csv。CORD 的标准答案不含商户和日期。权利人如需移除某张图片或某个数据集,可通过联系页面 (在新标签页打开)提出。