0

Kiểm tra JSON trích từ hóa đơn bằng hai mẫu lỗi khác nhau

Dùng hóa đơn giả gồm ba dòng theo thứ tự: Subtotal: USD 80.00, Tax: USD 8.00, Total: USD 88.00. Yêu cầu AI trả giá trị dưới dạng chuỗi, kèm số dòng bắt đầu từ 1. Nếu không tìm được một dòng duy nhất, trả null thay vì suy ra từ các số còn lại.

Ở phía ứng dụng, đối chiếu nhãn, số dòng, đơn vị tiền và số tiền trước. Sau đó mới dùng kiểu thập phân để kiểm tra phép cộng. Đổi tổng trong JSON thành 89.00 nhưng giữ nguyên nguồn: lỗi phải là sai với dòng gốc. Đổi cả nguồn thành 89.00: lúc này lỗi phải là phép cộng, không phải trích sai.

Hai ca kiểm thử không cần hóa đơn thật. Kết quả qua kiểm tra cũng chỉ là dữ liệu nháp, chưa phải bản ghi đã duyệt để nhập sổ.

Lưu cả đoạn dưới đây thành review.py rồi chạy python3 review.py. Không có đầu ra nghĩa là các phép kiểm tra đều đạt. source:total báo bản nháp lệch dòng gốc; arithmetic báo dòng gốc khớp nhưng phép cộng không khớp. Không sửa giá trị in trên hóa đơn để làm cho bài thử qua.

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"

Có thể gửi lược đồ qua format cho API cục bộ. Tài liệu đầu ra có cấu trúc của Ollama

Ví dụ tạo số thập phân trực tiếp từ chuỗi tiền. Tài liệu decimal của Python

Bài viết có sử dụng AI để hỗ trợ soạn thảo.


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.