Download evaluate_hyperapi.py from hyperbots-inc/synthetic-invoice-extraction: direct link, hf CLI and curl.
- Browser
- Download file 4.87 kB
-
https://huggingface.co/datasets/hyperbots-inc/synthetic-invoice-extraction/resolve/main/evaluate_hyperapi.py
- Command line
-
hf download hf://datasets/hyperbots-inc/synthetic-invoice-extraction/evaluate_hyperapi.py
-
curl -L -o evaluate_hyperapi.py https://huggingface.co/datasets/hyperbots-inc/synthetic-invoice-extraction/resolve/main/evaluate_hyperapi.py
4.87 kB
| """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() | |