-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_schema.py
More file actions
55 lines (43 loc) · 2.29 KB
/
Copy pathcustom_schema.py
File metadata and controls
55 lines (43 loc) · 2.29 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
47
48
49
50
51
52
53
54
55
"""Custom fields on top of a preset, fields injected into every line-item row, and saving
the combination so later calls are one argument.
python examples/custom_schema.py invoice.pdf
"""
import sys
from visionapi import ConflictError, VisionAPI, rows, unwrap, value
path = sys.argv[1] if len(sys.argv) > 1 else "invoice.pdf"
vision = VisionAPI()
schema = {
# Plain form: the string is the description. Descriptions are the prompt — the more
# precisely you say what you want, the better the extraction.
"machine_serial": 'Serial number of the machine being invoiced, without the "SN:" prefix',
# Typed form. Numbers come back as JSON numbers, dates as ISO YYYY-MM-DD.
"total_net": {"type": "number", "description": "Total before tax"},
"is_paid": {"type": "boolean", "description": "Whether the invoice is stamped or marked PAID"},
"reference_numbers": {"type": "array", "description": "All reference numbers", "items": "string"},
# "line_item" is reserved: these become extra columns on every row of the preset's
# line-item array. Only meaningful with a preset that has line items; with a bare
# custom schema there is nothing to inject into.
"line_item": {"lot_number": "The lot number printed on this line, if present"},
}
res = vision.analyze(file=path, preset="invoice", schema=schema)
result = res["result"]
print("serial:", value(result, "machine_serial"))
print("net total:", value(result, "total_net"))
print("paid:", value(result, "is_paid"))
for row in rows(result, "line_item"):
line = unwrap(row)
print(
f" {line.get('quantity') or '?'} × {line.get('description') or '(no description)'}"
f" = {line.get('amount') or '?'} [lot {line.get('lot_number') or '—'}]"
)
# Save it, and the next call is schema_name="our-invoices". The definition is compiled
# before it is stored, so an invalid schema fails here rather than on the first extraction
# that uses it.
try:
vision.create_schema("our-invoices", preset="invoice", schema=schema)
print('\nsaved as "our-invoices"')
except ConflictError:
vision.update_schema("our-invoices", preset="invoice", schema=schema)
print('\nupdated "our-invoices"')
again = vision.analyze(file=path, schema_name="our-invoices")
print("same fields via the saved schema:", len(again["result"]))