Python 检查 AI 抄录金额时,先排除「数值没错,行错了」
·
假设第 1 行是 Subtotal: USD 80.00,第 2 行是 Tax: USD 8.00,第 3 行是 Total: USD 88.00。助手返回 total 的 usd 是 “88.00”,但 line 填成 1。把金额转成 Decimal 再求和也发现不了错行。
先对 line 做严格类型和边界检查,再取 source.splitlines()[line-1],期望整行等于 “Total: USD 88.00”。注意 Python 里 True 能参与整数运算,验证行号可用 type(line) is int。原文若有两个 Total 标签,也送复核,不让行号替它擅自选一个。
最小测试准备三份候选:同值同源、正确金额错行、布尔行号。只有第一份通过此关。再单独测试 Decimal 加法。本例只管统一格式的测试文本,不替 OCR 或真实发票校验。
保存为 review.py 后运行 python3 review.py。不打印内容代表断言都通过。错误行号有两种:能定位到错误原文的是 source:total,布尔值、越界或字符串则是 line:total。即使指向其中一行,两个 Total 同名也会拦截。
import json
import re
from decimal import Decimal
labels = {"subtotal": "Subtotal", "tax": "Tax", "total": "Total"}
source = ["Subtotal: USD 80.00", "Tax: USD 8.00", "Total: USD 88.00"]
raw = """{"subtotal":{"line":1,"usd":"80.00"},
"tax":{"line":2,"usd":"8.00"},
"total":{"line":3,"usd":"88.00"}}"""
draft = json.loads(raw)
def review(lines, candidate):
if not isinstance(candidate, dict) or set(candidate) != set(labels):
return "shape"
amounts = {}
for key, label in labels.items():
cell = candidate[key]
if cell is None:
return "unknown:" + key
if not isinstance(cell, dict) or set(cell) != {"line", "usd"}:
return "shape:" + key
line, usd = cell["line"], cell["usd"]
if type(line) is not int or not 1 <= line <= len(lines):
return "line:" + key
matches = [i for i, text in enumerate(lines, 1)
if text.startswith(label + ":")]
if (matches != [line] or not isinstance(usd, str)
or not re.fullmatch(r"(0|[1-9][0-9]{0,8})[.][0-9]{2}", usd)
or lines[line - 1] != f"{label}: USD {usd}"):
return "source:" + key
amounts[key] = Decimal(usd)
if amounts["subtotal"] + amounts["tax"] != amounts["total"]:
return "arithmetic"
return "checks_passed"
assert review(source, draft) == "checks_passed"
wrong = dict(draft, total={"line": 1, "usd": "88.00"})
assert review(source, wrong) == "source:total"
for bad in (True, 0, 4, "3"):
wrong = dict(draft, total={"line": bad, "usd": "88.00"})
assert review(source, wrong) == "line:total"
assert review(source + ["Total: USD 89.00"], draft) == "source:total"
文档说明 bool 是 int 的子类,这就是行号不应只用 isinstance 检查的原因。 Python 布尔类型文档
本文使用 AI 辅助起草。
更多推荐

所有评论(0)