-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect_then_analyze.py
More file actions
46 lines (34 loc) · 1.94 KB
/
Copy pathdetect_then_analyze.py
File metadata and controls
46 lines (34 loc) · 1.94 KB
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
"""Routing a mixed inbox.
The pattern is detect (1 credit per 10 calls, amortised) → analyze with the chosen preset
(normal price). Worth it when the *type* is the decision: you can refuse to spend 40
credits on a 40-page PDF that turns out to be a scanned fax cover sheet.
If you just want the data and don't care which preset produced it, skip this and pass
preset="auto" — classification bundled into an extraction is free.
python examples/detect_then_analyze.py ./inbox
"""
import json
import sys
from pathlib import Path
from visionapi import VisionAPI, unwrap
inbox = Path(sys.argv[1] if len(sys.argv) > 1 else "./inbox")
vision = VisionAPI()
# What we are willing to spend extraction credits on, and what to do otherwise.
HANDLED = {"invoice", "receipt", "purchase_order", "packing_slip"}
SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff"}
for path in sorted(p for p in inbox.iterdir() if p.suffix.lower() in SUFFIXES):
guess = vision.detect(file=path)
# fallback=True means nothing matched confidently and the generic preset was
# substituted. That is "shape unknown", not a match — check what was rejected.
if guess["fallback"]:
closest = guess["detections"][0] if guess["detections"] else None
extra = f" (closest: {closest['preset']} — {closest['reason']})" if closest else ""
print(f"{path.name}: unrecognised{extra}")
continue
if guess["recommended"] not in HANDLED:
print(f"{path.name}: {guess['recommended']} — not a type we process, skipping")
continue
# `recommended` is exactly what preset="auto" would have run, so it is safe to commit.
res = vision.analyze(file=path, preset=guess["recommended"])
summary = json.dumps(unwrap(res["result"], drop_null=True), ensure_ascii=False)[:160]
print(f"{path.name}: {guess['recommended']} → {res['credits_used']} credit(s) {summary}")
print(f"\n{vision.credits()['balance']} credits remaining")