Update src/streamlit_app.py
Browse files- src/streamlit_app.py +199 -154
src/streamlit_app.py
CHANGED
|
@@ -236,25 +236,44 @@ def run_inference_on_image(image: Image.Image, processor, model, device, decoder
|
|
| 236 |
# ---------------------------
|
| 237 |
def map_prediction_to_ui(pred):
|
| 238 |
import json, re
|
| 239 |
-
from
|
| 240 |
|
|
|
|
| 241 |
def safe_json_load(s):
|
| 242 |
if s is None:
|
| 243 |
return None
|
| 244 |
if isinstance(s, (dict, list)):
|
| 245 |
return s
|
| 246 |
if isinstance(s, str):
|
|
|
|
|
|
|
|
|
|
| 247 |
try:
|
| 248 |
return json.loads(s)
|
| 249 |
except Exception:
|
| 250 |
-
try
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
return None
|
| 257 |
|
|
|
|
| 258 |
def clean_number(x):
|
| 259 |
if x is None:
|
| 260 |
return 0.0
|
|
@@ -263,6 +282,7 @@ def map_prediction_to_ui(pred):
|
|
| 263 |
s = str(x).strip()
|
| 264 |
if s == "":
|
| 265 |
return 0.0
|
|
|
|
| 266 |
s = re.sub(r"[,\s]", "", s)
|
| 267 |
s = re.sub(r"[^\d\.\-]", "", s)
|
| 268 |
if s in ("", ".", "-", "-."):
|
|
@@ -272,28 +292,69 @@ def map_prediction_to_ui(pred):
|
|
| 272 |
except Exception:
|
| 273 |
return 0.0
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
ui = {
|
| 298 |
"Invoice Number": "",
|
| 299 |
"Invoice Date": "",
|
|
@@ -313,137 +374,121 @@ def map_prediction_to_ui(pred):
|
|
| 313 |
"Itemized Data": []
|
| 314 |
}
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
if isinstance(
|
| 320 |
-
parsed
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
ui["Sender Name"] = header.get("sender_name") or header.get("seller_name") or header.get("from_name") or ui["Sender Name"]
|
| 344 |
-
ui["Sender Address"] = header.get("sender_addr") or header.get("sender_address") or header.get("seller_addr") or ui["Sender Address"]
|
| 345 |
-
ui["Recipient Name"] = header.get("rcpt_name") or header.get("recipient_name") or header.get("to_name") or ui["Recipient Name"]
|
| 346 |
-
ui["Recipient Address"] = header.get("rcpt_addr") or header.get("rcpt_address") or header.get("recipient_address") or ui["Recipient Address"]
|
| 347 |
|
| 348 |
-
|
| 349 |
-
ui["
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
|
|
|
|
| 351 |
bank = {}
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
if header.get("bank_routing"):
|
| 361 |
-
bank["bank_routing"] = str(header.get("bank_routing")).strip()
|
| 362 |
-
if header.get("bank_swift"):
|
| 363 |
-
bank["bank_swift"] = str(header.get("bank_swift")).strip()
|
| 364 |
-
if header.get("bank_branch"):
|
| 365 |
-
bank["bank_branch"] = str(header.get("bank_branch")).strip()
|
| 366 |
-
if header.get("bank_acc_name"):
|
| 367 |
-
bank["bank_acc_name"] = str(header.get("bank_acc_name")).strip()
|
| 368 |
-
hb = header.get("bank")
|
| 369 |
-
if isinstance(hb, dict):
|
| 370 |
-
for k, v in hb.items():
|
| 371 |
-
if not v:
|
| 372 |
-
continue
|
| 373 |
-
lk = k.lower()
|
| 374 |
-
if "iban" in lk:
|
| 375 |
-
bank["bank_iban"] = bank.get("bank_iban") or str(v).strip()
|
| 376 |
-
elif "swift" in lk:
|
| 377 |
-
bank["bank_swift"] = bank.get("bank_swift") or str(v).strip()
|
| 378 |
-
elif "acc" in lk or "account" in lk:
|
| 379 |
-
bank["bank_account_number"] = bank.get("bank_account_number") or str(v).strip()
|
| 380 |
-
elif "name" in lk and "bank" in lk:
|
| 381 |
-
bank["bank_name"] = bank.get("bank_name") or str(v).strip()
|
| 382 |
-
elif "branch" in lk:
|
| 383 |
-
bank["bank_branch"] = bank.get("bank_branch") or str(v).strip()
|
| 384 |
-
elif "acc_name" in lk or "account_name" in lk:
|
| 385 |
-
bank["bank_acc_name"] = bank.get("bank_acc_name") or str(v).strip()
|
| 386 |
-
|
| 387 |
ui["Bank Details"] = bank
|
| 388 |
|
| 389 |
-
|
| 390 |
-
ui["
|
| 391 |
-
ui["
|
| 392 |
-
ui["Total
|
| 393 |
-
ui["
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
if
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
|
| 448 |
return ui
|
| 449 |
|
|
|
|
| 236 |
# ---------------------------
|
| 237 |
def map_prediction_to_ui(pred):
|
| 238 |
import json, re
|
| 239 |
+
from collections import defaultdict
|
| 240 |
|
| 241 |
+
# --- parse raw string payloads that embed JSON ---
|
| 242 |
def safe_json_load(s):
|
| 243 |
if s is None:
|
| 244 |
return None
|
| 245 |
if isinstance(s, (dict, list)):
|
| 246 |
return s
|
| 247 |
if isinstance(s, str):
|
| 248 |
+
s = s.strip()
|
| 249 |
+
if s == "":
|
| 250 |
+
return None
|
| 251 |
try:
|
| 252 |
return json.loads(s)
|
| 253 |
except Exception:
|
| 254 |
+
# try to extract balanced-brace substrings (simple approach)
|
| 255 |
+
subs = []
|
| 256 |
+
stack = []
|
| 257 |
+
start = None
|
| 258 |
+
for i, ch in enumerate(s):
|
| 259 |
+
if ch == "{":
|
| 260 |
+
if not stack:
|
| 261 |
+
start = i
|
| 262 |
+
stack.append("{")
|
| 263 |
+
elif ch == "}":
|
| 264 |
+
if stack:
|
| 265 |
+
stack.pop()
|
| 266 |
+
if not stack and start is not None:
|
| 267 |
+
subs.append(s[start:i+1])
|
| 268 |
+
start = None
|
| 269 |
+
for sub in subs:
|
| 270 |
+
try:
|
| 271 |
+
return json.loads(sub)
|
| 272 |
+
except Exception:
|
| 273 |
+
continue
|
| 274 |
return None
|
| 275 |
|
| 276 |
+
# --- normalize numeric strings like "1,800.00" -> float ---
|
| 277 |
def clean_number(x):
|
| 278 |
if x is None:
|
| 279 |
return 0.0
|
|
|
|
| 282 |
s = str(x).strip()
|
| 283 |
if s == "":
|
| 284 |
return 0.0
|
| 285 |
+
# remove commas and non-number chars except dot and minus
|
| 286 |
s = re.sub(r"[,\s]", "", s)
|
| 287 |
s = re.sub(r"[^\d\.\-]", "", s)
|
| 288 |
if s in ("", ".", "-", "-."):
|
|
|
|
| 292 |
except Exception:
|
| 293 |
return 0.0
|
| 294 |
|
| 295 |
+
# --- collect all keys -> list of values from pred, recursively ---
|
| 296 |
+
def collect_keys(obj, out):
|
| 297 |
+
if isinstance(obj, dict):
|
| 298 |
+
for k, v in obj.items():
|
| 299 |
+
lk = str(k).strip().lower()
|
| 300 |
+
out[lk].append(v)
|
| 301 |
+
collect_keys(v, out)
|
| 302 |
+
elif isinstance(obj, list):
|
| 303 |
+
for it in obj:
|
| 304 |
+
collect_keys(it, out)
|
| 305 |
+
else:
|
| 306 |
+
# primitive: handled via parent key
|
| 307 |
+
pass
|
| 308 |
+
|
| 309 |
+
# --- find list-of-dicts candidates for items (recursively) ---
|
| 310 |
+
def collect_lists_of_dicts(obj, out_lists):
|
| 311 |
+
if isinstance(obj, dict):
|
| 312 |
+
for v in obj.values():
|
| 313 |
+
if isinstance(v, list) and v and isinstance(v[0], dict):
|
| 314 |
+
out_lists.append(v)
|
| 315 |
+
else:
|
| 316 |
+
collect_lists_of_dicts(v, out_lists)
|
| 317 |
+
elif isinstance(obj, list):
|
| 318 |
+
for it in obj:
|
| 319 |
+
if isinstance(it, list) and it and isinstance(it[0], dict):
|
| 320 |
+
out_lists.append(it)
|
| 321 |
+
else:
|
| 322 |
+
collect_lists_of_dicts(it, out_lists)
|
| 323 |
+
|
| 324 |
+
# --- map item dict -> UI item row using the keys you specified in example ---
|
| 325 |
+
def map_item_dict(it):
|
| 326 |
+
if not isinstance(it, dict):
|
| 327 |
+
return None
|
| 328 |
+
# lowered keys mapping
|
| 329 |
+
lower = {str(k).strip().lower(): v for k, v in it.items()}
|
| 330 |
+
desc = (lower.get("descriptions") or lower.get("description") or lower.get("desc") or lower.get("item") or "")
|
| 331 |
+
qty = lower.get("quantity") or lower.get("qty") or lower.get("count") or ""
|
| 332 |
+
unit_price = lower.get("unit_price") or lower.get("price") or ""
|
| 333 |
+
amount = lower.get("amount") or lower.get("line_total") or lower.get("line total") or lower.get("total") or ""
|
| 334 |
+
tax = lower.get("tax") or lower.get("tax_amount") or ""
|
| 335 |
+
line_total = lower.get("line_total") or lower.get("line_total".lower()) or lower.get("line total") or amount
|
| 336 |
+
|
| 337 |
+
return {
|
| 338 |
+
"Description": str(desc).strip(),
|
| 339 |
+
"Quantity": float(clean_number(qty)),
|
| 340 |
+
"Unit Price": float(clean_number(unit_price)),
|
| 341 |
+
"Amount": float(clean_number(amount)),
|
| 342 |
+
"Tax": float(clean_number(tax)),
|
| 343 |
+
"Line Total": float(clean_number(line_total))
|
| 344 |
+
}
|
| 345 |
|
| 346 |
+
# ----------------- Start mapping -----------------
|
| 347 |
+
# Try parse if pred is a JSON-like string
|
| 348 |
+
parsed = safe_json_load(pred) if isinstance(pred, str) else pred
|
| 349 |
+
if parsed is None and isinstance(pred, str):
|
| 350 |
+
# not parseable -> fallback to empty UI
|
| 351 |
+
parsed = None
|
| 352 |
+
|
| 353 |
+
if parsed is None and not isinstance(pred, dict):
|
| 354 |
+
# nothing we can map
|
| 355 |
+
parsed = pred # will still allow collect_keys if it's dict; else produce empty ui
|
| 356 |
+
|
| 357 |
+
# create empty UI template
|
| 358 |
ui = {
|
| 359 |
"Invoice Number": "",
|
| 360 |
"Invoice Date": "",
|
|
|
|
| 374 |
"Itemized Data": []
|
| 375 |
}
|
| 376 |
|
| 377 |
+
# If parsed is a dict, collect all keys and list-of-dict candidates
|
| 378 |
+
key_map = defaultdict(list) # lowercase-key -> list of values
|
| 379 |
+
list_candidates = [] # list of list-of-dicts found
|
| 380 |
+
if isinstance(parsed, dict):
|
| 381 |
+
collect_keys(parsed, key_map)
|
| 382 |
+
collect_lists_of_dicts(parsed, list_candidates)
|
| 383 |
+
elif isinstance(pred, dict):
|
| 384 |
+
# if parsing failed but original pred is dict, use that
|
| 385 |
+
collect_keys(pred, key_map)
|
| 386 |
+
collect_lists_of_dicts(pred, list_candidates)
|
| 387 |
+
|
| 388 |
+
# Helper to pick first non-empty value from candidate keys
|
| 389 |
+
def pick_first(*candidate_keys):
|
| 390 |
+
for k in candidate_keys:
|
| 391 |
+
lk = k.strip().lower()
|
| 392 |
+
if lk in key_map:
|
| 393 |
+
# pick first non-empty
|
| 394 |
+
for v in key_map[lk]:
|
| 395 |
+
if v is None:
|
| 396 |
+
continue
|
| 397 |
+
# return primitive or string immediately; if dict/list, return as-is
|
| 398 |
+
if isinstance(v, (dict, list)):
|
| 399 |
+
return v
|
| 400 |
+
s = str(v).strip()
|
| 401 |
+
if s != "":
|
| 402 |
+
return s
|
| 403 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
+
# Map simple scalar fields using the exact keys you provided (plus common close variants)
|
| 406 |
+
ui["Invoice Number"] = pick_first("invoice_no", "invoice_number", "invoiceid", "invoice id") or ""
|
| 407 |
+
ui["Invoice Date"] = pick_first("invoice_date", "date", "invoice date") or ""
|
| 408 |
+
ui["Due Date"] = pick_first("due_date", "due_date", "due") or ""
|
| 409 |
+
ui["Sender Name"] = pick_first("sender_name", "sender") or ""
|
| 410 |
+
ui["Sender Address"] = pick_first("sender_addr", "sender_address", "sender addr") or ""
|
| 411 |
+
ui["Recipient Name"] = pick_first("rcpt_name", "recipient_name", "recipient", "rcpt") or ""
|
| 412 |
+
ui["Recipient Address"] = pick_first("rcpt_addr", "recipient_address", "recipient addr") or ""
|
| 413 |
|
| 414 |
+
# bank details: gather keys that start with 'bank_' or exact matches
|
| 415 |
bank = {}
|
| 416 |
+
for bk in ("bank_name", "bank_acc_no", "bank_account_number", "bank_acc_name", "bank_iban", "bank_swift", "bank_routing", "bank_branch", "iban"):
|
| 417 |
+
val = pick_first(bk, bk.replace("bank_", "")) # allow both 'iban' and 'bank_iban'
|
| 418 |
+
if val:
|
| 419 |
+
# normalize key name to bank_* form
|
| 420 |
+
if bk == "iban":
|
| 421 |
+
bank["bank_iban"] = str(val)
|
| 422 |
+
else:
|
| 423 |
+
bank[bk] = str(val)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
ui["Bank Details"] = bank
|
| 425 |
|
| 426 |
+
# summary / totals
|
| 427 |
+
ui["Subtotal"] = clean_number(pick_first("subtotal", "sub_total", "sub total") or 0.0)
|
| 428 |
+
ui["Tax Percentage"] = clean_number(pick_first("tax_rate", "tax_percentage", "tax pct", "tax percentage") or 0.0)
|
| 429 |
+
ui["Total Tax"] = clean_number(pick_first("tax_amount", "tax", "total_tax") or 0.0)
|
| 430 |
+
ui["Total Amount"] = clean_number(pick_first("total_amount", "grand_total", "total", "amount") or 0.0)
|
| 431 |
+
ui["Currency"] = (pick_first("currency") or "").strip()
|
| 432 |
+
|
| 433 |
+
# Item extraction:
|
| 434 |
+
items_rows = []
|
| 435 |
+
|
| 436 |
+
# 1) If we found an explicit list-of-dicts candidate, use the first one that looks like invoice items
|
| 437 |
+
def list_looks_like_items(lst):
|
| 438 |
+
if not isinstance(lst, list) or not lst:
|
| 439 |
+
return False
|
| 440 |
+
if not isinstance(lst[0], dict):
|
| 441 |
+
return False
|
| 442 |
+
# check if any expected item key present in first element
|
| 443 |
+
expected = {"descriptions", "description", "desc", "item", "quantity", "qty", "amount", "unit_price", "line_total", "line_total".lower(), "line_total"}
|
| 444 |
+
keys0 = {str(k).strip().lower() for k in lst[0].keys()}
|
| 445 |
+
return bool(expected.intersection(keys0))
|
| 446 |
+
|
| 447 |
+
for cand in list_candidates:
|
| 448 |
+
if list_looks_like_items(cand):
|
| 449 |
+
for it in cand:
|
| 450 |
+
row = map_item_dict(it)
|
| 451 |
+
if row is not None:
|
| 452 |
+
items_rows.append(row)
|
| 453 |
+
# prefer first plausible list
|
| 454 |
+
if items_rows:
|
| 455 |
+
break
|
| 456 |
+
|
| 457 |
+
# 2) If no list-of-dicts found, try to find a single dict anywhere that looks like an item (e.g., 'items': {...} as dict)
|
| 458 |
+
if not items_rows:
|
| 459 |
+
# search key_map values for dicts that have item-like keys
|
| 460 |
+
for k, vals in key_map.items():
|
| 461 |
+
for v in vals:
|
| 462 |
+
if isinstance(v, dict):
|
| 463 |
+
# does this dict have an item-like key?
|
| 464 |
+
lower_keys = {str(x).strip().lower() for x in v.keys()}
|
| 465 |
+
if lower_keys.intersection({"descriptions", "description", "desc", "amount", "line_total", "quantity", "qty", "unit_price"}):
|
| 466 |
+
row = map_item_dict(v)
|
| 467 |
+
if row is not None:
|
| 468 |
+
items_rows.append(row)
|
| 469 |
+
# we don't break because there might be multiple item-like dicts at different keys,
|
| 470 |
+
# but continue scanning to collect all.
|
| 471 |
+
# 3) Last resort: if key_map contains 'descriptions' or 'amount' as scalar but no dict, build a single-item row
|
| 472 |
+
if not items_rows:
|
| 473 |
+
desc = pick_first("descriptions", "description")
|
| 474 |
+
amt = pick_first("amount", "line_total")
|
| 475 |
+
qty = pick_first("quantity", "qty")
|
| 476 |
+
unit_price = pick_first("unit_price", "price")
|
| 477 |
+
if desc or amt or qty or unit_price:
|
| 478 |
+
items_rows.append({
|
| 479 |
+
"Description": str(desc or ""),
|
| 480 |
+
"Quantity": float(clean_number(qty)),
|
| 481 |
+
"Unit Price": float(clean_number(unit_price)),
|
| 482 |
+
"Amount": float(clean_number(amt)),
|
| 483 |
+
"Tax": float(clean_number(pick_first("tax", "tax_amount") or 0.0)),
|
| 484 |
+
"Line Total": float(clean_number(amt or 0.0))
|
| 485 |
+
})
|
| 486 |
+
|
| 487 |
+
ui["Itemized Data"] = items_rows
|
| 488 |
+
|
| 489 |
+
# Also set Sender/Recipient convenience fields
|
| 490 |
+
ui["Sender"] = {"Name": ui["Sender Name"], "Address": ui["Sender Address"]}
|
| 491 |
+
ui["Recipient"] = {"Name": ui["Recipient Name"], "Address": ui["Recipient Address"]}
|
| 492 |
|
| 493 |
return ui
|
| 494 |
|