Spaces:
Sleeping
Sleeping
Expand schema for multi-tax/discount edge cases, add totals validation, fix truncation/parsing robustness
Browse files- README.md +51 -6
- app.py +141 -19
- requirements.txt +1 -0
README.md
CHANGED
|
@@ -50,7 +50,7 @@ result = client.predict(
|
|
| 50 |
high_accuracy=False, # set True only for long/narrow thermal-paper receipts
|
| 51 |
api_name="/extract",
|
| 52 |
)
|
| 53 |
-
print(result) # JSON string
|
| 54 |
```
|
| 55 |
|
| 56 |
## Image size handling
|
|
@@ -80,14 +80,59 @@ you — that's the easier route for most use cases).
|
|
| 80 |
|
| 81 |
If the Space is private, pass `hf_token="hf_..."` to `Client(...)`.
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
## Notes / tuning
|
| 84 |
|
| 85 |
-
- `@spaces.GPU(duration=
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
- `do_sample=False` (greedy decoding) is used for repeatability; extraction
|
| 88 |
tasks don't benefit from sampling.
|
|
|
|
|
|
|
|
|
|
| 89 |
- The prompt in `app.py` defines the JSON schema. Edit it directly if you
|
| 90 |
need extra fields (e.g. `po_number`, `tax_id`).
|
| 91 |
-
- For production
|
| 92 |
-
output against a `pydantic` schema and retrying once on failure
|
| 93 |
-
|
|
|
|
| 50 |
high_accuracy=False, # set True only for long/narrow thermal-paper receipts
|
| 51 |
api_name="/extract",
|
| 52 |
)
|
| 53 |
+
print(result) # JSON string — see "Output schema & tax/item edge cases" below
|
| 54 |
```
|
| 55 |
|
| 56 |
## Image size handling
|
|
|
|
| 80 |
|
| 81 |
If the Space is private, pass `hf_token="hf_..."` to `Client(...)`.
|
| 82 |
|
| 83 |
+
## Output schema & tax/item edge cases
|
| 84 |
+
|
| 85 |
+
`app.py`'s prompt asks for a schema built to handle the messy realities of
|
| 86 |
+
real receipts, not just the happy path:
|
| 87 |
+
|
| 88 |
+
- **Multiple tax lines** (GST+PST, state+county, a VAT rate table) go in a
|
| 89 |
+
`taxes: [{label, rate_percent, amount}]` array; `tax` stays as a
|
| 90 |
+
convenience sum. A receipt with one combined tax figure just uses `tax`
|
| 91 |
+
and leaves `taxes` empty.
|
| 92 |
+
- **`tax_inclusive`** flags whether listed prices already include tax
|
| 93 |
+
(common outside the US) — matters if you're recomputing anything downstream.
|
| 94 |
+
- **Discounts and refunds** are captured as a positive `discount` amount
|
| 95 |
+
(meant to be subtracted) at the document level, and as a *negative*
|
| 96 |
+
`amount` on the specific line item if it's an itemized discount/return.
|
| 97 |
+
- **`service_charge` vs `tip`** are kept separate — a mandatory service fee
|
| 98 |
+
isn't the same as a voluntary gratuity, and conflating them breaks
|
| 99 |
+
downstream accounting.
|
| 100 |
+
- **Non-receipt images** (or unreadable ones) get `document_type: "unknown"`,
|
| 101 |
+
everything else `null`, and a reason in `notes` — instead of the model
|
| 102 |
+
forcing garbage into the schema.
|
| 103 |
+
- **`validation`** is appended after parsing, not part of what the model
|
| 104 |
+
generates: it recomputes `subtotal` from `line_items`, sums `taxes`, adds
|
| 105 |
+
`service_charge`/`tip`, subtracts `discount`, and compares against the
|
| 106 |
+
stated `total` (±$0.02 tolerance). Use `matches_stated_total: false` as a
|
| 107 |
+
signal to flag a document for manual review — it usually means either the
|
| 108 |
+
model misread a digit or the receipt itself doesn't add up.
|
| 109 |
+
- If generation hits the token limit before finishing, `validation.warning`
|
| 110 |
+
says so — treat line items near the end of the list as unverified rather
|
| 111 |
+
than silently trusting a cut-off list.
|
| 112 |
+
|
| 113 |
+
This is inherently a **known-limitations tool, not a guarantee**: a 4B model
|
| 114 |
+
can still misread a smudged digit that happens to produce internally
|
| 115 |
+
consistent (but wrong) totals — `validation` only catches *inconsistency*,
|
| 116 |
+
not every possible misread. It also currently assumes **one document per
|
| 117 |
+
image** (a photo containing two separate receipts side by side isn't
|
| 118 |
+
handled) and doesn't support multi-page PDFs in a single call.
|
| 119 |
+
|
| 120 |
## Notes / tuning
|
| 121 |
|
| 122 |
+
- `@spaces.GPU(duration=90)` caps each call at 90s of GPU time — bumped up
|
| 123 |
+
from 60s since `MAX_NEW_TOKENS` was raised to 1536 to fit long itemized
|
| 124 |
+
receipts. Raise further if you still see timeouts on dense invoices.
|
| 125 |
+
- `MAX_NEW_TOKENS = 1536` in `app.py` — the ceiling on how long a generated
|
| 126 |
+
JSON response can be. Grocery-length receipts (40+ line items) can get
|
| 127 |
+
close to this; the truncation check (`validation.warning`) tells you when
|
| 128 |
+
a response likely got cut off so you know to raise it further.
|
| 129 |
- `do_sample=False` (greedy decoding) is used for repeatability; extraction
|
| 130 |
tasks don't benefit from sampling.
|
| 131 |
+
- JSON parsing has two fallback layers before giving up: stripping stray
|
| 132 |
+
prose/fences around the `{...}`, then repairing trailing commas — the two
|
| 133 |
+
most common small-model output quirks.
|
| 134 |
- The prompt in `app.py` defines the JSON schema. Edit it directly if you
|
| 135 |
need extra fields (e.g. `po_number`, `tax_id`).
|
| 136 |
+
- For stricter production reliability, consider validating the model's JSON
|
| 137 |
+
output against a `pydantic` schema and retrying once on failure/mismatch
|
| 138 |
+
before falling back to returning the raw output for manual handling.
|
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import json
|
|
|
|
| 2 |
|
| 3 |
import gradio as gr
|
| 4 |
import spaces
|
|
@@ -16,6 +17,11 @@ MODEL_ID = "unsloth/gemma-3-4b-it-qat"
|
|
| 16 |
# latency. We downscale before it ever reaches the processor.
|
| 17 |
MAX_EDGE = 1568
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 20 |
model = Gemma3ForConditionalGeneration.from_pretrained(
|
| 21 |
MODEL_ID,
|
|
@@ -50,32 +56,138 @@ matching exactly this schema:
|
|
| 50 |
{
|
| 51 |
"document_type": "invoice" | "receipt" | "unknown",
|
| 52 |
"vendor_name": string | null,
|
|
|
|
| 53 |
"date": string | null,
|
|
|
|
| 54 |
"currency": string | null,
|
|
|
|
| 55 |
"subtotal": number | null,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
"tax": number | null,
|
|
|
|
| 57 |
"tip": number | null,
|
| 58 |
"total": number | null,
|
|
|
|
|
|
|
| 59 |
"payment_method": string | null,
|
| 60 |
"line_items": [
|
| 61 |
{
|
| 62 |
"description": string,
|
| 63 |
"quantity": number | null,
|
|
|
|
| 64 |
"unit_price": number | null,
|
|
|
|
|
|
|
| 65 |
"amount": number | null
|
| 66 |
}
|
| 67 |
-
]
|
|
|
|
| 68 |
}
|
| 69 |
|
| 70 |
Rules:
|
| 71 |
-
- Use null for any field you cannot read
|
| 72 |
-
- Numbers must be plain numbers (no currency symbols, no commas).
|
| 73 |
-
- "date" should be ISO 8601 (YYYY-MM-DD) if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
- Output valid JSON and nothing else.
|
| 75 |
"""
|
| 76 |
|
| 77 |
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def extract(image: Image.Image, high_accuracy: bool = False):
|
| 80 |
if image is None:
|
| 81 |
return json.dumps({"error": "no image provided"}, indent=2)
|
|
@@ -109,28 +221,38 @@ def extract(image: Image.Image, high_accuracy: bool = False):
|
|
| 109 |
with torch.inference_mode():
|
| 110 |
generated = model.generate(
|
| 111 |
**inputs,
|
| 112 |
-
max_new_tokens=
|
| 113 |
do_sample=False,
|
| 114 |
)
|
| 115 |
|
| 116 |
output_ids = generated[0][input_len:]
|
| 117 |
-
|
| 118 |
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
text = text.strip("`")
|
| 122 |
-
if text.lower().startswith("json"):
|
| 123 |
-
text = text[4:]
|
| 124 |
-
text = text.strip()
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
except json.JSONDecodeError:
|
| 130 |
return json.dumps(
|
| 131 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
)
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
demo = gr.Interface(
|
| 136 |
fn=extract,
|
|
@@ -142,7 +264,7 @@ demo = gr.Interface(
|
|
| 142 |
info="Costs more tokens/time — only needed for thermal-paper strips or tiny print.",
|
| 143 |
),
|
| 144 |
],
|
| 145 |
-
outputs=gr.Textbox(label="Structured JSON", lines=
|
| 146 |
title="Invoice & Receipt Extractor (Gemma 3 4B)",
|
| 147 |
description=(
|
| 148 |
"Upload a photo or scan of an invoice or receipt. Runs on ZeroGPU. "
|
|
|
|
| 1 |
import json
|
| 2 |
+
import re
|
| 3 |
|
| 4 |
import gradio as gr
|
| 5 |
import spaces
|
|
|
|
| 17 |
# latency. We downscale before it ever reaches the processor.
|
| 18 |
MAX_EDGE = 1568
|
| 19 |
|
| 20 |
+
# Itemized receipts (groceries, long invoices) can easily need more than a
|
| 21 |
+
# few hundred output tokens. Truncation mid-JSON is the #1 cause of "invalid
|
| 22 |
+
# JSON" failures on small models, so we give this generous headroom.
|
| 23 |
+
MAX_NEW_TOKENS = 1536
|
| 24 |
+
|
| 25 |
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 26 |
model = Gemma3ForConditionalGeneration.from_pretrained(
|
| 27 |
MODEL_ID,
|
|
|
|
| 56 |
{
|
| 57 |
"document_type": "invoice" | "receipt" | "unknown",
|
| 58 |
"vendor_name": string | null,
|
| 59 |
+
"vendor_address": string | null,
|
| 60 |
"date": string | null,
|
| 61 |
+
"time": string | null,
|
| 62 |
"currency": string | null,
|
| 63 |
+
"tax_inclusive": boolean | null,
|
| 64 |
"subtotal": number | null,
|
| 65 |
+
"discount": number | null,
|
| 66 |
+
"taxes": [
|
| 67 |
+
{"label": string, "rate_percent": number | null, "amount": number | null}
|
| 68 |
+
],
|
| 69 |
"tax": number | null,
|
| 70 |
+
"service_charge": number | null,
|
| 71 |
"tip": number | null,
|
| 72 |
"total": number | null,
|
| 73 |
+
"amount_paid": number | null,
|
| 74 |
+
"change_due": number | null,
|
| 75 |
"payment_method": string | null,
|
| 76 |
"line_items": [
|
| 77 |
{
|
| 78 |
"description": string,
|
| 79 |
"quantity": number | null,
|
| 80 |
+
"unit": string | null,
|
| 81 |
"unit_price": number | null,
|
| 82 |
+
"discount": number | null,
|
| 83 |
+
"tax_rate_percent": number | null,
|
| 84 |
"amount": number | null
|
| 85 |
}
|
| 86 |
+
],
|
| 87 |
+
"notes": string | null
|
| 88 |
}
|
| 89 |
|
| 90 |
Rules:
|
| 91 |
+
- Use null for any field you cannot read. Never guess or invent values.
|
| 92 |
+
- Numbers must be plain numbers (no currency symbols, no thousands commas).
|
| 93 |
+
- "date" should be ISO 8601 (YYYY-MM-DD) if determinable; "time" as 24h HH:MM.
|
| 94 |
+
- "currency" should be an ISO 4217 code (e.g. "USD", "EUR") if determinable.
|
| 95 |
+
- If the receipt shows a SINGLE combined tax figure, put it in "tax" and leave
|
| 96 |
+
"taxes" as an empty array. If it breaks tax out by type or rate (e.g. GST +
|
| 97 |
+
PST, or a VAT rate table), list each one in "taxes" AND put their sum in
|
| 98 |
+
"tax" for convenience.
|
| 99 |
+
- "tax_inclusive": true if listed prices already include tax (common outside
|
| 100 |
+
the US), false if tax is added on top, null if you can't tell.
|
| 101 |
+
- Discounts, coupons, and refunds are negative in effect: put the discount
|
| 102 |
+
amount as a positive number in the "discount" field (it will be subtracted),
|
| 103 |
+
and for a line item that IS a discount/refund, use a negative "amount".
|
| 104 |
+
- "service_charge" is a mandatory/automatic charge (e.g. restaurant service
|
| 105 |
+
fee); "tip" is a voluntary gratuity. Don't conflate them.
|
| 106 |
+
- If the image is not an invoice or receipt (or is unreadable), set
|
| 107 |
+
"document_type" to "unknown", leave other fields null, "line_items" as an
|
| 108 |
+
empty array, and briefly say why in "notes".
|
| 109 |
+
- If you notice the totals don't add up, don't silently correct them — record
|
| 110 |
+
what the document actually states and mention the discrepancy in "notes".
|
| 111 |
- Output valid JSON and nothing else.
|
| 112 |
"""
|
| 113 |
|
| 114 |
|
| 115 |
+
def isolate_json(text: str) -> str:
|
| 116 |
+
"""Best-effort isolation of the JSON object from the model's raw output."""
|
| 117 |
+
text = text.strip()
|
| 118 |
+
if text.startswith("```"):
|
| 119 |
+
text = text.strip("`")
|
| 120 |
+
if text.lower().startswith("json"):
|
| 121 |
+
text = text[4:]
|
| 122 |
+
text = text.strip()
|
| 123 |
+
|
| 124 |
+
start = text.find("{")
|
| 125 |
+
end = text.rfind("}")
|
| 126 |
+
if start != -1 and end != -1 and end > start:
|
| 127 |
+
text = text[start : end + 1]
|
| 128 |
+
return text
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def parse_json_loose(text: str):
|
| 132 |
+
"""Try strict parsing, then one repair pass for the most common small-model
|
| 133 |
+
glitch (a trailing comma before a closing brace/bracket)."""
|
| 134 |
+
try:
|
| 135 |
+
return json.loads(text), None
|
| 136 |
+
except json.JSONDecodeError as e:
|
| 137 |
+
repaired = re.sub(r",\s*([}\]])", r"\1", text)
|
| 138 |
+
try:
|
| 139 |
+
return json.loads(repaired), None
|
| 140 |
+
except json.JSONDecodeError:
|
| 141 |
+
return None, str(e)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def validate_totals(data: dict) -> dict:
|
| 145 |
+
"""Lightweight arithmetic cross-check. Never raises — this is a hint for
|
| 146 |
+
downstream review, not a hard guarantee, since it can only catch
|
| 147 |
+
internal inconsistency, not a value that was misread but still adds up."""
|
| 148 |
+
try:
|
| 149 |
+
line_items = data.get("line_items") or []
|
| 150 |
+
item_amounts = [
|
| 151 |
+
i["amount"] for i in line_items if isinstance(i.get("amount"), (int, float))
|
| 152 |
+
]
|
| 153 |
+
computed_subtotal = round(sum(item_amounts), 2) if item_amounts else None
|
| 154 |
+
|
| 155 |
+
taxes = data.get("taxes") or []
|
| 156 |
+
tax_amounts = [
|
| 157 |
+
t["amount"] for t in taxes if isinstance(t.get("amount"), (int, float))
|
| 158 |
+
]
|
| 159 |
+
computed_tax = round(sum(tax_amounts), 2) if tax_amounts else data.get("tax")
|
| 160 |
+
|
| 161 |
+
subtotal = data.get("subtotal") if data.get("subtotal") is not None else computed_subtotal
|
| 162 |
+
discount = data.get("discount")
|
| 163 |
+
service_charge = data.get("service_charge")
|
| 164 |
+
tip = data.get("tip")
|
| 165 |
+
|
| 166 |
+
parts = [subtotal, computed_tax, service_charge, tip]
|
| 167 |
+
numeric_parts = [p for p in parts if isinstance(p, (int, float))]
|
| 168 |
+
computed_total = None
|
| 169 |
+
if numeric_parts:
|
| 170 |
+
computed_total = sum(numeric_parts)
|
| 171 |
+
if isinstance(discount, (int, float)):
|
| 172 |
+
computed_total -= discount
|
| 173 |
+
computed_total = round(computed_total, 2)
|
| 174 |
+
|
| 175 |
+
stated_total = data.get("total")
|
| 176 |
+
matches = None
|
| 177 |
+
if isinstance(stated_total, (int, float)) and computed_total is not None:
|
| 178 |
+
matches = abs(computed_total - stated_total) <= 0.02
|
| 179 |
+
|
| 180 |
+
return {
|
| 181 |
+
"computed_subtotal_from_line_items": computed_subtotal,
|
| 182 |
+
"computed_total": computed_total,
|
| 183 |
+
"stated_total": stated_total,
|
| 184 |
+
"matches_stated_total": matches,
|
| 185 |
+
}
|
| 186 |
+
except Exception:
|
| 187 |
+
return {"error": "validation check failed"}
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@spaces.GPU(duration=90)
|
| 191 |
def extract(image: Image.Image, high_accuracy: bool = False):
|
| 192 |
if image is None:
|
| 193 |
return json.dumps({"error": "no image provided"}, indent=2)
|
|
|
|
| 221 |
with torch.inference_mode():
|
| 222 |
generated = model.generate(
|
| 223 |
**inputs,
|
| 224 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 225 |
do_sample=False,
|
| 226 |
)
|
| 227 |
|
| 228 |
output_ids = generated[0][input_len:]
|
| 229 |
+
likely_truncated = output_ids.shape[-1] >= MAX_NEW_TOKENS
|
| 230 |
|
| 231 |
+
text = processor.decode(output_ids, skip_special_tokens=True)
|
| 232 |
+
cleaned = isolate_json(text)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
+
parsed, err = parse_json_loose(cleaned)
|
| 235 |
+
|
| 236 |
+
if parsed is None:
|
|
|
|
| 237 |
return json.dumps(
|
| 238 |
+
{
|
| 239 |
+
"error": "model did not return valid JSON",
|
| 240 |
+
"likely_truncated": likely_truncated,
|
| 241 |
+
"parse_error": err,
|
| 242 |
+
"raw_output": text.strip(),
|
| 243 |
+
},
|
| 244 |
+
indent=2,
|
| 245 |
)
|
| 246 |
|
| 247 |
+
parsed["validation"] = validate_totals(parsed)
|
| 248 |
+
if likely_truncated:
|
| 249 |
+
parsed["validation"]["warning"] = (
|
| 250 |
+
"Output may have been truncated before completion — treat with caution, "
|
| 251 |
+
"especially for line_items near the end of the list."
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
return json.dumps(parsed, indent=2)
|
| 255 |
+
|
| 256 |
|
| 257 |
demo = gr.Interface(
|
| 258 |
fn=extract,
|
|
|
|
| 264 |
info="Costs more tokens/time — only needed for thermal-paper strips or tiny print.",
|
| 265 |
),
|
| 266 |
],
|
| 267 |
+
outputs=gr.Textbox(label="Structured JSON", lines=32),
|
| 268 |
title="Invoice & Receipt Extractor (Gemma 3 4B)",
|
| 269 |
description=(
|
| 270 |
"Upload a photo or scan of an invoice or receipt. Runs on ZeroGPU. "
|
requirements.txt
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
gradio>=5.0.0
|
| 2 |
huggingface_hub>=0.26.0
|
|
|
|
| 3 |
spaces
|
| 4 |
transformers>=4.50.0
|
| 5 |
accelerate
|
|
|
|
| 1 |
gradio>=5.0.0
|
| 2 |
huggingface_hub>=0.26.0
|
| 3 |
+
pydantic<2.11
|
| 4 |
spaces
|
| 5 |
transformers>=4.50.0
|
| 6 |
accelerate
|