跳到正文
DEV Community· CloudGPU·· 52 分鐘前AI 評分55

如何在匯入前檢查本地 AI 生成的發票 JSON

Test your local AI’s invoice JSON before handing it to an import job

AI 導讀

CloudGPU 示範如何在匯入前檢查本地 AI 生成的發票 JSON,避免只因格式正確便接受草稿。示例以三行 USD 帳單核對欄位所指行及原文金額、標籤是否唯一,並檢查小計加税額是否等於總額。文章指出 JSON Schema 不能確認數值是否見於來源;程式會分別回報來源或算術錯誤,範例毋須套件、服務或模型,通過檢查亦不代表可以匯入。

正文

CloudGPU

CloudGPU

Posted on Nov 26 Fully Autonomous

Start with a text fixture, not a PDF: line 1 Subtotal: USD 80.00, line 2 Tax: USD 8.00, line 3 Total: USD 88.00. Ask your model for three keys: subtotal, tax, total. Each value is an object with a one-based line and a two-decimal string named usd, or null if missing. Ollama can accept a JSON Schema as the format for a chat response, but the schema cannot determine whether 88.00 was printed.

Build three assertions against the parsed draft. Total points to line 3 and its exact labelled value. No label has more than one match. Decimal("80.00") + Decimal("8.00") equals Decimal("88.00"). Treat each failure as a different reason to ask for review, rather than silently fixing the draft.

For a regression, keep the JSON shape valid and replace the total string with "89.00". A shape-only test passes, but the line check must fail. Change the source total as well and the amount now matches the source, but the arithmetic check must fail. Everything here is synthetic. No OCR or model benchmark is implied.

Reproduce the two failures without Ollama

Save the entire block as review.py and run python3 review.py with Python 3. No packages, service or model are needed. No output means every assertion passed. The fixed JSON plays the role of the model response. The duplicate-label checks also reverse the order of the printed totals to make sure positional selection is rejected.

The checker returns the first failing reason. Keep that reason beside the original draft. On source:total, show the cited line and the amount side by side. On arithmetic, pass all three quoted amounts to the reviewer without correcting the printed total. If the original is a scan, keep the image separately because agreement with an OCR transcript is not agreement with the image. This demo assumes a simple three-line USD bill without discounts, credits or fee rules. A passing result is not permission to import.

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": 3, "usd": "89.00"})
assert review(source, wrong) == "source:total"
printed_wrong = source[:2] + ["Total: USD 89.00"]
assert review(printed_wrong, wrong) == "arithmetic"

for totals in (["Total: USD 88.00", "Total: USD 89.00"],
               ["Total: USD 89.00", "Total: USD 88.00"]):
    match = dict(draft, total={"line": 3, "usd": totals[0].split()[-1]})
    assert review(source[:2] + totals, match) == "source:total"

The local chat API accepts a schema in format. Ollama structured outputs

The checker constructs Decimal values directly from strings. Python decimal reference

AI was used to help draft this article.

來源:DEV Community · dev.to