File size: 4,865 Bytes
ccd1a6d
 
 
9f3cbd9
ccd1a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""Score HyperAPI's Extract endpoint on hyperbots-inc/synthetic-invoice-extraction.

Setup:
    # install the HyperAPI SDK: https://apis.hyperbots.com/docs/quickstart
    export HYPERAPI_KEY=hk_test_...           # free key: https://apis.hyperbots.com/dashboard/api-keys

Run:
    python evaluate_hyperapi.py --limit 25            # score 25 invoices (uses the OCR text as a .txt upload)
    python evaluate_hyperapi.py --limit 25 --pdf      # render the HTML to PDF first (needs: pip install weasyprint)
    python evaluate_hyperapi.py --dry-run             # check the scoring pipeline with gold labels, no API calls

The free tier covers 30 pages per month, so keep --limit at or below 30 on a free key.
"""
import argparse
import json
import os
import re
import tempfile
from datetime import datetime

CORE_FIELDS = ["invoice_number", "date", "due_date", "vendor_name", "total_amount", "currency"]
DATE_FORMATS = ["%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%b %d, %Y", "%d %B %Y", "%B %d, %Y", "%d-%m-%Y", "%Y/%m/%d"]


def load_rows(path=None):
    if path is None:
        from huggingface_hub import hf_hub_download
        path = hf_hub_download("hyperbots-inc/synthetic-invoice-extraction", "data/test.jsonl", repo_type="dataset")
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def norm_text(x):
    return re.sub(r"\s+", " ", str(x or "")).strip().lower().rstrip(".")


def norm_amount(x):
    if x is None:
        return None
    s = re.sub(r"[^0-9.\-]", "", str(x).replace(",", ""))
    try:
        return round(float(s), 2)
    except ValueError:
        return None


def norm_date(x, hint=None):
    s = str(x or "").strip()
    fmts = DATE_FORMATS
    if hint == "eu":  # dd/mm/yyyy is ambiguous with mm/dd/yyyy; prefer the document's convention
        fmts = ["%d/%m/%Y"] + [f for f in DATE_FORMATS if f != "%d/%m/%Y"]
    for f in fmts:
        try:
            return datetime.strptime(s, f).strftime("%Y-%m-%d")
        except ValueError:
            continue
    return s


def field_match(name, pred, gold, row):
    if name in ("total_amount",):
        return norm_amount(pred) is not None and norm_amount(pred) == norm_amount(gold)
    if name in ("date", "due_date"):
        return norm_date(pred, row.get("date_format")) == gold
    return norm_text(pred) == norm_text(gold)


def line_items_match(pred_items, gold_items):
    """Fraction of gold line items whose total appears among predicted line totals."""
    pred_totals = [norm_amount(i.get("total") or i.get("amount")) for i in (pred_items or [])]
    hits = 0
    for g in gold_items:
        t = norm_amount(g["total"])
        if t in pred_totals:
            pred_totals.remove(t)
            hits += 1
    return hits / max(len(gold_items), 1)


def to_file(row, tmpdir, as_pdf):
    if as_pdf:
        from weasyprint import HTML
        path = os.path.join(tmpdir, row["id"] + ".pdf")
        HTML(string=row["html"]).write_pdf(path)
    else:
        path = os.path.join(tmpdir, row["id"] + ".txt")
        with open(path, "w", encoding="utf-8") as f:
            f.write(row["ocr_text"])
    return path


def predict(client, path):
    res = client.extract(path)
    result = res.get("result", res) if isinstance(res, dict) else {}
    return result.get("entities", {}), result.get("line_items", [])


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--limit", type=int, default=25)
    ap.add_argument("--pdf", action="store_true", help="render HTML to PDF before upload (needs weasyprint)")
    ap.add_argument("--data", default=None, help="local path to test.jsonl (default: download from the Hub)")
    ap.add_argument("--dry-run", action="store_true", help="score gold labels against themselves; no API calls")
    args = ap.parse_args()

    rows = load_rows(args.data)[: args.limit]
    client = None
    if not args.dry_run:
        from hyperapi import HyperAPIClient
        client = HyperAPIClient()  # reads HYPERAPI_KEY

    hits = {f: 0 for f in CORE_FIELDS}
    li_scores = []
    with tempfile.TemporaryDirectory() as tmp:
        for row in rows:
            gold = row["labels"]
            if args.dry_run:
                ents, items = gold["entities"], gold["line_items"]
            else:
                ents, items = predict(client, to_file(row, tmp, args.pdf))
            for f in CORE_FIELDS:
                hits[f] += field_match(f, ents.get(f), gold["entities"][f], row)
            li_scores.append(line_items_match(items, gold["line_items"]))
    if client is not None:
        client.close()

    n = len(rows)
    print(f"Scored {n} invoices")
    for f in CORE_FIELDS:
        print(f"  {f:<16} {hits[f] / n:6.1%}")
    print(f"  {'line_items':<16} {sum(li_scores) / n:6.1%}  (share of gold line totals recovered)")


if __name__ == "__main__":
    main()