Bhuvi13 commited on
Commit
c755a11
·
verified ·
1 Parent(s): de7097d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. 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 datetime import datetime
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
- t = s.strip()
252
- t = t.replace("\\'", "'").replace('\"{', '{').replace('}\"', '}')
253
- return json.loads(t)
254
- except Exception:
255
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- def parse_date(s):
276
- if not s:
277
- return ""
278
- s = str(s).strip()
279
- for fmt in ("%Y-%m-%d", "%d-%m-%Y", "%d/%m/%Y", "%m/%d/%Y", "%d.%m.%Y"):
280
- try:
281
- return datetime.strptime(s, fmt).strftime("%Y-%m-%d")
282
- except Exception:
283
- pass
284
- m = re.match(r"^(\d{1,2})/(\d{1,2})/(\d{4})$", s)
285
- if m:
286
- a, b, y = int(m.group(1)), int(m.group(2)), int(m.group(3))
287
- if a > 12:
288
- d, mo = a, b
289
- else:
290
- mo, d = a, b
291
- try:
292
- return datetime(year=y, month=mo, day=d).strftime("%Y-%m-%d")
293
- except Exception:
294
- return s
295
- return s
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- if pred is None:
317
- return ui
318
-
319
- if isinstance(pred, str):
320
- parsed = safe_json_load(pred)
321
- if parsed is not None:
322
- pred = parsed
323
-
324
- gt = None
325
- if isinstance(pred, dict):
326
- if "gt_parse" in pred:
327
- gp = pred["gt_parse"]
328
- gp_parsed = safe_json_load(gp)
329
- gt = gp_parsed if gp_parsed is not None else (gp if isinstance(gp, dict) else {})
330
- else:
331
- gt = pred
332
- else:
333
- return ui
334
-
335
- header = gt.get("header") or {}
336
- items = gt.get("items") or []
337
- summary = gt.get("summary") or {}
338
-
339
- ui["Invoice Number"] = header.get("invoice_no") or header.get("invoice_number") or ui["Invoice Number"]
340
- ui["Invoice Date"] = str(header.get("invoice_date") or header.get("inv_date") or "")
341
- ui["Due Date"] = str(header.get("due_date") or header.get("due") or "")
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
- ui["Sender"] = {"Name": ui["Sender Name"], "Address": ui["Sender Address"]}
349
- ui["Recipient"] = {"Name": ui["Recipient Name"], "Address": ui["Recipient Address"]}
 
 
 
 
 
 
350
 
 
351
  bank = {}
352
- if header.get("bank_name"):
353
- bank["bank_name"] = str(header.get("bank_name")).strip()
354
- if header.get("bank_acc_no"):
355
- bank["bank_account_number"] = str(header.get("bank_acc_no")).strip()
356
- if header.get("bank_account_number"):
357
- bank["bank_account_number"] = bank.get("bank_account_number") or str(header.get("bank_account_number")).strip()
358
- if header.get("bank_iban"):
359
- bank["bank_iban"] = str(header.get("bank_iban")).strip()
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
- ui["Subtotal"] = clean_number(summary.get("subtotal") or summary.get("sub_total") or summary.get("subTotal"))
390
- ui["Tax Percentage"] = clean_number(summary.get("tax_rate") or summary.get("taxRate") or summary.get("tax_percentage"))
391
- ui["Total Tax"] = clean_number(summary.get("tax_amount") or summary.get("tax") or summary.get("taxAmount"))
392
- ui["Total Amount"] = clean_number(summary.get("total_amount") or summary.get("grand_total") or summary.get("total") or summary.get("amount_total"))
393
- ui["Currency"] = summary.get("currency") or header.get("currency") or ui["Currency"] or ""
394
-
395
- normalized_items = []
396
-
397
- if isinstance(items, str):
398
- parsed_items = safe_json_load(items)
399
- if parsed_items is not None:
400
- items = parsed_items
401
-
402
- if isinstance(items, dict):
403
- if any(isinstance(v, list) for v in items.values()):
404
- list_cols = {k: v for k, v in items.items() if isinstance(v, list)}
405
- max_len = max((len(v) for v in list_cols.values()), default=0)
406
- for i in range(max_len):
407
- row = {}
408
- for k, v in items.items():
409
- if isinstance(v, list):
410
- row[k] = v[i] if i < len(v) else ""
411
- else:
412
- row[k] = v
413
- normalized_items.append(row)
414
- else:
415
- normalized_items.append(items)
416
- elif isinstance(items, list):
417
- normalized_items = items
418
- else:
419
- normalized_items = []
420
-
421
- item_rows = []
422
- for it in normalized_items:
423
- if not isinstance(it, dict):
424
- item_rows.append({"Description": str(it), "Quantity": 1, "Unit Price": 0.0, "Amount": 0.0, "Tax": 0.0, "Line Total": 0.0})
425
- continue
426
- desc = it.get("descriptions") or it.get("description") or it.get("desc") or it.get("item") or it.get("name") or ""
427
- qty = it.get("quantity") or it.get("qty") or it.get("Quantity") or ""
428
- unit = it.get("unit_price") or it.get("unitPrice") or it.get("price") or ""
429
- amt = it.get("amount") or it.get("Line_total") or it.get("line_total") or it.get("total") or ""
430
-
431
- # Extract item-level tax if available under common keys
432
- tax_val = it.get("tax") or it.get("tax_amount") or it.get("line_tax") or it.get("item_tax") or it.get("taxAmount") or ""
433
-
434
- # Extract explicit line total if present; otherwise fall back to amount
435
- line_total_val = it.get("Line_total") or it.get("line_total") or it.get("lineTotal") or amt
436
-
437
- item_rows.append({
438
- "Description": str(desc).strip(),
439
- "Quantity": float(clean_number(qty)),
440
- "Unit Price": float(clean_number(unit)),
441
- "Amount": float(clean_number(amt)),
442
- "Tax": float(clean_number(tax_val)),
443
- "Line Total": float(clean_number(line_total_val))
444
- })
445
-
446
- ui["Itemized Data"] = item_rows
 
 
 
 
 
 
 
 
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