Sathvik-kota commited on
Commit
3cd83b8
·
verified ·
1 Parent(s): 97eaa23

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +273 -256
app.py CHANGED
@@ -1,14 +1,14 @@
1
- # app.py (HIGH ACCURACY TSV + preprocessing + optional Gemini refinement)
2
  import os
3
  import re
4
  import json
5
  from io import BytesIO
6
- from typing import List, Dict, Any, Optional
7
 
8
  from fastapi import FastAPI
9
  from pydantic import BaseModel
10
  import requests
11
- from PIL import Image, ImageOps
12
  from pdf2image import convert_from_bytes
13
  import pytesseract
14
  from pytesseract import Output
@@ -29,23 +29,28 @@ app = FastAPI(title="Bajaj Datathon - Bill Extractor (High Accuracy)")
29
  class BillRequest(BaseModel):
30
  document: str
31
 
32
- # ---------------- Helpers: number normalization & detection ----------------
33
- NUM_RE = re.compile(r"[-+]?\d{1,3}(?:[,0-9]*)(?:\.\d+)?") # matches numbers with commas, decimals
34
- TOTAL_KEYWORDS = re.compile(r"(grand\s*total|net\s*payable|total\s*amount|amount\s*payable|bill\s*amount|final\s*amount|balance\s*due|sub\s*total|subtotal)", re.I)
 
 
 
35
 
36
- def normalize_num_str(s: str) -> Optional[float]:
 
37
  if s is None:
38
  return None
39
- s = s.strip()
40
- # remove currency symbols, whitespace
41
- s = re.sub(r"[^\d\-\+\,\.()]", "", s)
42
- # remove parentheses meaning negative
 
43
  negative = False
44
  if s.startswith("(") and s.endswith(")"):
45
  negative = True
46
  s = s[1:-1]
47
  s = s.replace(",", "")
48
- if s == "":
49
  return None
50
  try:
51
  val = float(s)
@@ -53,47 +58,32 @@ def normalize_num_str(s: str) -> Optional[float]:
53
  except Exception:
54
  return None
55
 
56
- def looks_like_amount_token(token: str) -> bool:
57
- if not token or token.strip() == "":
58
  return False
59
- return NUM_RE.search(token) is not None
60
 
61
  # ---------------- Image preprocessing ----------------
62
  def pil_to_cv2(img: Image.Image) -> np.ndarray:
63
  arr = np.array(img)
64
  if arr.ndim == 2:
65
  return arr
66
- # PIL gives RGB; cv2 uses BGR — but for preprocessing grayscale is fine
67
  return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
68
 
69
  def preprocess_image(pil_img: Image.Image) -> np.ndarray:
70
- """
71
- Preprocess image for better OCR:
72
- - convert to grayscale
73
- - increase DPI / upscale if small
74
- - denoise
75
- - adaptive thresholding
76
- - morphological opening to remove small noise
77
- Returns cv2 image (grayscale).
78
- """
79
- # ensure RGB -> convert if necessary
80
  pil_img = pil_img.convert("RGB")
81
  w, h = pil_img.size
82
- # upscale small images to minimum 1500 width for better OCR (but avoid huge upscales)
83
  target_w = 1500
84
  if w < target_w:
85
  scale = target_w / float(w)
86
  new_size = (int(w * scale), int(h * scale))
87
  pil_img = pil_img.resize(new_size, Image.LANCZOS)
88
 
89
- # convert to grayscale
90
  cv_img = pil_to_cv2(pil_img)
91
  gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
92
-
93
- # denoise
94
  gray = cv2.fastNlMeansDenoising(gray, h=10)
95
 
96
- # adaptive threshold (helps with varied contrast)
97
  try:
98
  bw = cv2.adaptiveThreshold(
99
  gray, 255,
@@ -102,44 +92,41 @@ def preprocess_image(pil_img: Image.Image) -> np.ndarray:
102
  41, 15
103
  )
104
  except Exception:
105
- # fallback
106
  _, bw = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
107
 
108
- # morphological opening to remove small speckles
109
  kernel = np.ones((1, 1), np.uint8)
110
  bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, kernel)
111
-
112
  return bw
113
 
114
- # ---------------- OCR with TSV ----------------
115
  def image_to_tsv_cells(cv_img: np.ndarray) -> List[Dict[str, Any]]:
116
- """
117
- Runs pytesseract.image_to_data and returns a list of word-level cells with bbox + text + conf
118
- Each cell: {left, top, width, height, text, conf, center_y, center_x}
119
- """
120
  try:
121
  o = pytesseract.image_to_data(cv_img, output_type=Output.DICT, config="--psm 6")
122
  except Exception:
123
- # fallback try without specifying psm
124
  o = pytesseract.image_to_data(cv_img, output_type=Output.DICT)
125
 
126
- cells = []
127
  n = len(o.get("text", []))
128
  for i in range(n):
129
- txt = o["text"][i].strip() if o["text"][i] is not None else ""
130
- conf = float(o["conf"][i]) if o["conf"][i] not in (None, "", "-1") else -1.0
 
 
131
  if txt == "":
132
- # skip empty words
133
  continue
134
- left = int(o["left"][i])
135
- top = int(o["top"][i])
136
- width = int(o["width"][i])
137
- height = int(o["height"][i])
 
 
 
 
138
  center_y = top + height / 2.0
139
  center_x = left + width / 2.0
140
  cells.append({
141
  "text": txt,
142
- "conf": conf,
143
  "left": left,
144
  "top": top,
145
  "width": width,
@@ -149,207 +136,265 @@ def image_to_tsv_cells(cv_img: np.ndarray) -> List[Dict[str, Any]]:
149
  })
150
  return cells
151
 
152
- # ---------------- Row reconstruction ----------------
153
  def group_cells_into_rows(cells: List[Dict[str, Any]], y_tolerance: int = 12) -> List[List[Dict[str, Any]]]:
154
- """
155
- Group word-cells into rows using center_y clustering.
156
- Returns list of rows, each row is a list of cells sorted by x (left).
157
- """
158
  if not cells:
159
  return []
160
-
161
- # sort by center_y then center_x
162
  cells_sorted = sorted(cells, key=lambda c: (c["center_y"], c["center_x"]))
163
- rows = []
164
  current_row = [cells_sorted[0]]
165
  last_y = cells_sorted[0]["center_y"]
166
-
167
  for c in cells_sorted[1:]:
168
  if abs(c["center_y"] - last_y) <= y_tolerance:
169
  current_row.append(c)
170
- # update running average of row y
171
  last_y = (last_y * (len(current_row) - 1) + c["center_y"]) / len(current_row)
172
  else:
173
- # finalize previous row
174
  rows.append(sorted(current_row, key=lambda cc: cc["left"]))
175
  current_row = [c]
176
  last_y = c["center_y"]
177
-
178
  if current_row:
179
  rows.append(sorted(current_row, key=lambda cc: cc["left"]))
180
-
181
  return rows
182
 
183
- # ---------------- Parse row into columns (name, qty, rate, amount) ----------------
184
- def parse_row_to_item(cells_row: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
185
- """
186
- Given a row (list of cells sorted by x), attempt to parse:
187
- - right-most numeric token -> item_amount
188
- - preceding numeric tokens -> rate, quantity (in that order)
189
- - remaining left text -> item_name
190
- Returns dict or None if not parsable.
191
- """
192
- tokens = [c["text"] for c in cells_row]
193
- token_positions = [c["left"] for c in cells_row]
194
- # find numeric tokens indices
195
- numeric_indices = []
196
- for i, t in enumerate(tokens):
197
- if looks_like_amount_token(t):
198
- numeric_indices.append(i)
199
- if not numeric_indices:
200
- return None
201
-
202
- # Right-most numeric token is candidate amount
203
- amt_idx = numeric_indices[-1]
204
- amt_token = tokens[amt_idx]
205
- amt_val = normalize_num_str(amt_token)
206
- if amt_val is None:
207
- return None
208
-
209
- # Name = everything before amt_idx, but exclude obvious label columns like "qty"
210
- name_tokens = tokens[:amt_idx]
211
- name = " ".join(name_tokens).strip()
212
- if name == "":
213
- # sometimes shape is reversed: maybe item name after left numeric; discard
214
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
- # try parse rate and quantity from preceding numeric tokens
217
- rate_val = 0.0
218
- qty_val = 0.0
219
-
220
- if len(numeric_indices) >= 2:
221
- rate_token = tokens[numeric_indices[-2]]
222
- r = normalize_num_str(rate_token)
223
- rate_val = r if r is not None else 0.0
224
-
225
- if len(numeric_indices) >= 3:
226
- qty_token = tokens[numeric_indices[-3]]
227
- q = normalize_num_str(qty_token)
228
- qty_val = q if q is not None else 0.0
229
-
230
- # Basic plausibility fixes: if quantity seems zero or not present, default to 1.0
231
- if qty_val == 0.0:
232
- # attempt to infer qty from tokens like '2x' or '2'
233
- # search in entire row
234
- for t in tokens:
235
- m = re.match(r"^(\d+)\s*[xX]?$", t)
236
- if m:
237
- qty_val = float(m.group(1))
238
- break
239
- if qty_val == 0.0:
240
- qty_val = 1.0
241
-
242
- return {
243
- "item_name": name,
244
- "item_amount": float(round(amt_val, 2)),
245
- "item_rate": float(round(rate_val, 2)) if rate_val else 0.0,
246
- "item_quantity": float(qty_val)
247
- }
248
-
249
- # ---------------- Duplicate suppression & subtotal detection ----------------
250
  def dedupe_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
251
- """
252
- Remove obvious duplicates:
253
- - same item_name normalized + same amount -> keep first
254
- """
255
  seen = set()
256
- out = []
257
  for it in items:
258
- n = it["item_name"].lower()
259
- n = re.sub(r"\s+", " ", n).strip()
260
- key = (n[:80], round(float(it["item_amount"]), 2)) # use first 80 chars to be safe
261
  if key in seen:
262
  continue
263
  seen.add(key)
264
  out.append(it)
265
  return out
266
 
267
- def detect_subtotals_and_totals(rows_texts: List[str]) -> Dict[str, Any]:
268
- """
269
- Look through page-level row texts for subtotal/final total cues and values.
270
- Returns dict with keys: subtotal (float or None), final_total (float or None)
271
- """
272
- subtotal = None
273
- final_total = None
274
- for rt in rows_texts[::-1]: # scan bottom-up
275
  if not rt or rt.strip() == "":
276
  continue
277
  if TOTAL_KEYWORDS.search(rt):
278
- # find first number in the line
279
  m = NUM_RE.search(rt)
280
  if m:
281
- val = normalize_num_str(m.group(0))
282
- if val is None:
283
  continue
284
- # decide if subtotal or final_total based on keyword
285
  if re.search(r"sub", rt, re.I):
286
  if subtotal is None:
287
- subtotal = float(round(val, 2))
288
  else:
289
- # treat as final total likely
290
  if final_total is None:
291
- final_total = float(round(val, 2))
292
  return {"subtotal": subtotal, "final_total": final_total}
293
 
294
- # ---------------- Optional: Gemini refinement ----------------
295
- def refine_with_gemini(page_items: List[Dict[str, Any]]) -> (List[Dict[str, Any]], Dict[str,int]):
296
- """
297
- Send structured extracted items to Gemini to ask it to:
298
- - validate amounts and quantities
299
- - remove summary rows (if any slipped)
300
- - dedupe and correct obvious OCR mis-splits
301
- Returns (refined_items, token_usage)
302
- If GEMINI_API_KEY not set or any error occurs, returns original items and zero token_usage.
303
- """
304
  zero_usage = {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}
305
  if not GEMINI_API_KEY:
306
  return page_items, zero_usage
307
-
308
  try:
309
- # Build compact JSON payload for the LLM
310
  prompt = (
311
- "You are a precise bill extraction assistant. You are given a list of extracted line items "
312
- "parsed from OCR with fields item_name, item_quantity, item_rate, item_amount. "
313
- "Your job: remove any rows that are totals or duplicate summaries, fix numeric mistakes if obvious, "
314
- "and return cleaned JSON array of items only. Do NOT add new items. "
315
- "Return ONLY valid JSON (an array of objects with same fields).\n\n"
316
  f"items = {json.dumps(page_items, ensure_ascii=False)}"
317
  )
318
-
319
  model = genai.GenerativeModel(GEMINI_MODEL_NAME)
320
  response = model.generate_content(
321
  [
322
- {"role": "system", "parts": ["You are concise and precise. Return only valid JSON."]},
323
- {"role": "user", "parts": [prompt]},
324
  ]
325
  )
326
-
327
  raw_text = response.text.strip()
328
- # remove fenced codeblock markers
329
  if raw_text.startswith("```"):
330
  raw_text = re.sub(r"^```[a-zA-Z]*", "", raw_text)
331
  raw_text = re.sub(r"```$", "", raw_text).strip()
332
-
333
  parsed = json.loads(raw_text)
334
  if isinstance(parsed, list):
335
- # normalize returned items
336
  cleaned = []
337
  for obj in parsed:
338
  try:
339
  cleaned.append({
340
- "item_name": str(obj.get("item_name", "")).strip(),
341
- "item_amount": float(obj.get("item_amount", 0.0)),
342
- "item_rate": float(obj.get("item_rate", 0.0) or 0.0),
343
- "item_quantity": float(obj.get("item_quantity", 1.0) or 1.0)
344
  })
345
  except Exception:
346
  continue
347
- # Token usage: we cannot reliably extract tokens without genai usage details; keep zero schema
348
- token_usage = zero_usage
349
- return cleaned, token_usage
350
- else:
351
- return page_items, zero_usage
352
-
353
  except Exception:
354
  return page_items, zero_usage
355
 
@@ -357,119 +402,92 @@ def refine_with_gemini(page_items: List[Dict[str, Any]]) -> (List[Dict[str, Any]
357
  @app.post("/extract-bill-data")
358
  async def extract_bill_data(payload: BillRequest):
359
  doc_url = payload.document
360
- # Step 1: download
361
  try:
362
  headers = {"User-Agent": "Mozilla/5.0"}
363
  resp = requests.get(doc_url, headers=headers, timeout=30)
364
  if resp.status_code != 200:
365
  raise RuntimeError(f"download failed status={resp.status_code}")
366
  file_bytes = resp.content
367
- except Exception as e:
368
  return {
369
  "is_success": False,
370
- "token_usage": {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0},
371
  "data": {"pagewise_line_items": [], "total_item_count": 0}
372
  }
373
 
374
- # Step 2: convert PDF->images or handle single image
375
- images = []
376
- clean_url = doc_url.split("?", 1)[0].lower()
377
  try:
378
  if clean_url.endswith(".pdf"):
379
- pages = convert_from_bytes(file_bytes)
380
- images = pages
381
- elif any(clean_url.endswith(ext) for ext in [".png", ".jpg", ".jpeg", ".tiff", ".bmp"]):
382
- img = Image.open(BytesIO(file_bytes))
383
- images = [img]
384
  else:
385
- # try PDF conversion as fallback
386
  try:
387
- pages = convert_from_bytes(file_bytes)
388
- images = pages
389
  except Exception:
390
  images = []
391
  except Exception:
392
  images = []
393
 
394
- pagewise_line_items = []
395
- cumulative_token_usage = {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}
396
 
397
- # Process each page
398
  for idx, page_img in enumerate(images, start=1):
399
  try:
400
- # preprocess
401
  processed_cv = preprocess_image(page_img)
402
-
403
- # get TSV / word cells
404
  cells = image_to_tsv_cells(processed_cv)
405
-
406
- # reconstruct rows
407
  rows = group_cells_into_rows(cells, y_tolerance=12)
408
  rows_texts = [" ".join([c["text"] for c in r]) for r in rows]
 
409
 
410
- # detect subtotal/final totals in page text
411
- subtotals = detect_subtotals_and_totals(rows_texts)
412
-
413
- # parse each row to items
414
- parsed_items = []
415
- for r in rows:
416
- parsed = parse_row_to_item(r)
417
- if parsed is None:
418
- continue
419
- # filter out obvious total-like names
420
- if TOTAL_KEYWORDS.search(parsed["item_name"]):
421
- continue
422
- parsed_items.append(parsed)
423
-
424
- # dedupe
425
  parsed_items = dedupe_items(parsed_items)
426
 
427
- # if no items found via TSV (e.g., OCR failed), fallback to plain OCR text + simple extractor
428
  if not parsed_items:
429
- try:
430
- raw_text = pytesseract.image_to_string(processed_cv)
431
- parsed_items = []
432
- # reuse your simpler extractor logic (very small and safe)
433
- for line in [ln.strip() for ln in raw_text.splitlines() if ln.strip()]:
434
- if TOTAL_KEYWORDS.search(line):
435
- continue
436
- toks = line.split()
437
- numeric_idxs = [i for i,t in enumerate(toks) if NUM_RE.search(t)]
438
- if numeric_idxs:
439
- last = numeric_idxs[-1]
440
- amt = normalize_num_str(toks[last])
441
- if amt is None:
442
- continue
443
- name = " ".join(toks[:last]).strip()
444
- if name == "":
445
- continue
446
- parsed_items.append({
447
- "item_name": name,
448
- "item_amount": float(round(amt, 2)),
449
- "item_rate": 0.0,
450
- "item_quantity": 1.0
451
- })
452
- parsed_items = dedupe_items(parsed_items)
453
- except Exception:
454
- parsed_items = []
455
 
456
- # optional Gemini refinement (page-level)
457
  if GEMINI_API_KEY and parsed_items:
458
  refined, token_u = refine_with_gemini(parsed_items)
459
  parsed_items = refined
460
- # accumulate token usage (placeholder zeros kept)
461
  for k in cumulative_token_usage:
462
- cumulative_token_usage[k] += token_u.get(k, 0)
463
 
464
- # Page type heuristics
465
  page_type = "Bill Detail"
466
  page_text_join = " ".join(rows_texts).lower()
467
- if "pharmacy" in page_text_join or "medicine" in page_text_join or "tablet" in page_text_join:
468
  page_type = "Pharmacy"
469
  if "final bill" in page_text_join or "grand total" in page_text_join:
470
  page_type = "Final Bill"
471
 
472
- # attach to pagewise output
473
  pagewise_line_items.append({
474
  "page_no": str(idx),
475
  "page_type": page_type,
@@ -477,7 +495,6 @@ async def extract_bill_data(payload: BillRequest):
477
  })
478
 
479
  except Exception:
480
- # on per-page failure continue with empty list
481
  pagewise_line_items.append({
482
  "page_no": str(idx),
483
  "page_type": "Bill Detail",
@@ -485,7 +502,7 @@ async def extract_bill_data(payload: BillRequest):
485
  })
486
  continue
487
 
488
- total_item_count = sum(len(p.get("bill_items", [])) for p in pagewise_line_items)
489
 
490
  return {
491
  "is_success": True,
 
1
+ # app.py (HIGH ACCURACY — Column detection + TSV parsing + optional Gemini refinement)
2
  import os
3
  import re
4
  import json
5
  from io import BytesIO
6
+ from typing import List, Dict, Any, Optional, Tuple
7
 
8
  from fastapi import FastAPI
9
  from pydantic import BaseModel
10
  import requests
11
+ from PIL import Image
12
  from pdf2image import convert_from_bytes
13
  import pytesseract
14
  from pytesseract import Output
 
29
  class BillRequest(BaseModel):
30
  document: str
31
 
32
+ # ---------------- Globals & regex ----------------
33
+ NUM_RE = re.compile(r"[-+]?\d{1,3}(?:[,0-9]*)(?:\.\d+)?") # numbers with commas/decimals
34
+ TOTAL_KEYWORDS = re.compile(
35
+ r"(grand\s*total|net\s*payable|total\s*amount|amount\s*payable|bill\s*amount|final\s*amount|balance\s*due|sub\s*total|subtotal)",
36
+ re.I
37
+ )
38
 
39
+ # ---------------- Utility funcs ----------------
40
+ def normalize_num_str(s: Optional[str]) -> Optional[float]:
41
  if s is None:
42
  return None
43
+ s = str(s).strip()
44
+ if s == "":
45
+ return None
46
+ # remove currency and letters; keep digits, minus, dot, commas, parentheses
47
+ s = re.sub(r"[^\d\-\+\,\.\(\)]", "", s)
48
  negative = False
49
  if s.startswith("(") and s.endswith(")"):
50
  negative = True
51
  s = s[1:-1]
52
  s = s.replace(",", "")
53
+ if s == "" or s in ("-", "+"):
54
  return None
55
  try:
56
  val = float(s)
 
58
  except Exception:
59
  return None
60
 
61
+ def is_numeric_token(t: Optional[str]) -> bool:
62
+ if not t:
63
  return False
64
+ return bool(NUM_RE.search(str(t)))
65
 
66
  # ---------------- Image preprocessing ----------------
67
  def pil_to_cv2(img: Image.Image) -> np.ndarray:
68
  arr = np.array(img)
69
  if arr.ndim == 2:
70
  return arr
 
71
  return cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
72
 
73
  def preprocess_image(pil_img: Image.Image) -> np.ndarray:
74
+ # ensure RGB
 
 
 
 
 
 
 
 
 
75
  pil_img = pil_img.convert("RGB")
76
  w, h = pil_img.size
 
77
  target_w = 1500
78
  if w < target_w:
79
  scale = target_w / float(w)
80
  new_size = (int(w * scale), int(h * scale))
81
  pil_img = pil_img.resize(new_size, Image.LANCZOS)
82
 
 
83
  cv_img = pil_to_cv2(pil_img)
84
  gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
 
 
85
  gray = cv2.fastNlMeansDenoising(gray, h=10)
86
 
 
87
  try:
88
  bw = cv2.adaptiveThreshold(
89
  gray, 255,
 
92
  41, 15
93
  )
94
  except Exception:
 
95
  _, bw = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
96
 
 
97
  kernel = np.ones((1, 1), np.uint8)
98
  bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, kernel)
 
99
  return bw
100
 
101
+ # ---------------- OCR: TSV -> cells ----------------
102
  def image_to_tsv_cells(cv_img: np.ndarray) -> List[Dict[str, Any]]:
 
 
 
 
103
  try:
104
  o = pytesseract.image_to_data(cv_img, output_type=Output.DICT, config="--psm 6")
105
  except Exception:
 
106
  o = pytesseract.image_to_data(cv_img, output_type=Output.DICT)
107
 
108
+ cells: List[Dict[str, Any]] = []
109
  n = len(o.get("text", []))
110
  for i in range(n):
111
+ raw_text = o["text"][i]
112
+ if raw_text is None:
113
+ continue
114
+ txt = str(raw_text).strip()
115
  if txt == "":
 
116
  continue
117
+ try:
118
+ conf_val = float(o["conf"][i]) if o["conf"][i] not in (None, "", "-1") else -1.0
119
+ except Exception:
120
+ conf_val = -1.0
121
+ left = int(o.get("left", [0])[i])
122
+ top = int(o.get("top", [0])[i])
123
+ width = int(o.get("width", [0])[i])
124
+ height = int(o.get("height", [0])[i])
125
  center_y = top + height / 2.0
126
  center_x = left + width / 2.0
127
  cells.append({
128
  "text": txt,
129
+ "conf": conf_val,
130
  "left": left,
131
  "top": top,
132
  "width": width,
 
136
  })
137
  return cells
138
 
139
+ # ---------------- Group into rows ----------------
140
  def group_cells_into_rows(cells: List[Dict[str, Any]], y_tolerance: int = 12) -> List[List[Dict[str, Any]]]:
 
 
 
 
141
  if not cells:
142
  return []
 
 
143
  cells_sorted = sorted(cells, key=lambda c: (c["center_y"], c["center_x"]))
144
+ rows: List[List[Dict[str, Any]]] = []
145
  current_row = [cells_sorted[0]]
146
  last_y = cells_sorted[0]["center_y"]
 
147
  for c in cells_sorted[1:]:
148
  if abs(c["center_y"] - last_y) <= y_tolerance:
149
  current_row.append(c)
 
150
  last_y = (last_y * (len(current_row) - 1) + c["center_y"]) / len(current_row)
151
  else:
 
152
  rows.append(sorted(current_row, key=lambda cc: cc["left"]))
153
  current_row = [c]
154
  last_y = c["center_y"]
 
155
  if current_row:
156
  rows.append(sorted(current_row, key=lambda cc: cc["left"]))
 
157
  return rows
158
 
159
+ # ---------------- Numeric column detection & parsing ----------------
160
+ def detect_numeric_columns(cells: List[Dict[str, Any]], max_columns: int = 4) -> List[float]:
161
+ xs = [c["center_x"] for c in cells if is_numeric_token(c["text"])]
162
+ if not xs:
163
+ return []
164
+ xs = sorted(xs)
165
+ if len(xs) == 1:
166
+ return [xs[0]]
167
+ gaps = [xs[i+1] - xs[i] for i in range(len(xs)-1)]
168
+ mean_gap = float(np.mean(gaps))
169
+ std_gap = float(np.std(gaps)) if len(gaps) > 1 else 0.0
170
+ gap_thresh = max(30.0, mean_gap + 0.6 * std_gap)
171
+ clusters: List[List[float]] = []
172
+ current = [xs[0]]
173
+ for i, g in enumerate(gaps):
174
+ if g > gap_thresh and len(clusters) < (max_columns - 1):
175
+ clusters.append(current)
176
+ current = [xs[i+1]]
177
+ else:
178
+ current.append(xs[i+1])
179
+ clusters.append(current)
180
+ centers = [float(np.median(c)) for c in clusters]
181
+ if len(centers) > max_columns:
182
+ centers = centers[-max_columns:]
183
+ return sorted(centers)
184
+
185
+ def assign_token_to_column(token_x: float, column_centers: List[float]) -> Optional[int]:
186
+ if not column_centers:
 
 
 
187
  return None
188
+ distances = [abs(token_x - cx) for cx in column_centers]
189
+ return int(int(np.argmin(distances)))
190
+
191
+ def parse_rows_with_columns(rows: List[List[Dict[str, Any]]], page_cells: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
192
+ parsed_items: List[Dict[str, Any]] = []
193
+ column_centers = detect_numeric_columns(page_cells, max_columns=4)
194
+ for row in rows:
195
+ tokens = [c["text"] for c in row]
196
+ xs = [c["center_x"] for c in row]
197
+ if not tokens:
198
+ continue
199
+ if all(not is_numeric_token(t) for t in tokens):
200
+ # likely header/section -> skip
201
+ continue
202
+ if column_centers:
203
+ left_text_parts: List[str] = []
204
+ numeric_bucket_map: Dict[int, List[str]] = {i: [] for i in range(len(column_centers))}
205
+ for c in row:
206
+ t = c["text"]
207
+ cx = c["center_x"]
208
+ if is_numeric_token(t):
209
+ col_idx = assign_token_to_column(cx, column_centers)
210
+ if col_idx is None:
211
+ numeric_bucket_map[len(column_centers)-1].append(t)
212
+ else:
213
+ numeric_bucket_map[col_idx].append(t)
214
+ else:
215
+ # decide if textual token belongs to left name region
216
+ if cx < (column_centers[0] - 10):
217
+ left_text_parts.append(t)
218
+ else:
219
+ left_text_parts.append(t)
220
+ item_name = " ".join(left_text_parts).strip()
221
+ num_cols = len(column_centers)
222
+ def get_clean_value(bucket_idx: int) -> Optional[float]:
223
+ vals = numeric_bucket_map.get(bucket_idx, [])
224
+ if not vals:
225
+ return None
226
+ chosen = vals[-1]
227
+ return normalize_num_str(chosen)
228
+ amount = None
229
+ rate = None
230
+ qty = None
231
+ discount = None
232
+ if num_cols >= 1:
233
+ amount = get_clean_value(num_cols - 1)
234
+ if num_cols >= 2:
235
+ # treat second last as rate or discount candidate
236
+ rate = get_clean_value(num_cols - 2)
237
+ if num_cols >= 3:
238
+ qty = get_clean_value(num_cols - 3)
239
+ # reasonable defaults
240
+ if qty is None:
241
+ # attempt to infer from any simple integer tokens in left part
242
+ for pt in left_text_parts[::-1]:
243
+ m = re.match(r"^(\d+)(?:[xX])?$", pt)
244
+ if m:
245
+ qty = float(m.group(1)); break
246
+ if qty is None:
247
+ qty = 1.0
248
+ if amount is None:
249
+ # fallback to rightmost numeric token in the row
250
+ for t in reversed(tokens):
251
+ if is_numeric_token(t):
252
+ amount = normalize_num_str(t)
253
+ break
254
+ if rate is None:
255
+ # fallback attempt: nearest numeric left of amount
256
+ numeric_tokens_in_row = [(i, t) for i, t in enumerate(tokens) if is_numeric_token(t)]
257
+ if len(numeric_tokens_in_row) >= 2:
258
+ # choose second-rightmost as rate
259
+ idx_rate = numeric_tokens_in_row[-2][1] if False else None
260
+ # safer: pick nearest numeric whose center_x is left of amount column
261
+ # but keep rate=0 if not found
262
+ rate = rate or 0.0
263
+ # normalize final numeric types
264
+ try:
265
+ amount = float(round(amount, 2)) if amount is not None else None
266
+ except Exception:
267
+ amount = None
268
+ try:
269
+ rate = float(round(rate, 2)) if rate else 0.0
270
+ except Exception:
271
+ rate = 0.0
272
+ try:
273
+ qty = float(qty) if qty is not None else 1.0
274
+ except Exception:
275
+ qty = 1.0
276
+ # skip header-like names
277
+ if item_name and re.match(r"^(consultation|room|nursing|surgery|radiology|laborat|laboratory|charges|services|page)$", item_name.strip(), re.I):
278
+ continue
279
+ # validate using qty * rate ≈ amount
280
+ validated = False
281
+ if amount is not None:
282
+ prod = qty * rate
283
+ if rate and abs(prod - amount) <= max(2.0, 0.03 * (amount if amount != 0 else 1.0)):
284
+ validated = True
285
+ else:
286
+ # if rate is 0, maybe amount equals rate and qty missing; set rate = amount, qty =1
287
+ if rate == 0:
288
+ rate = amount
289
+ qty = 1.0
290
+ validated = True
291
+ # finalize only if amount present
292
+ if amount is None:
293
+ continue
294
+ parsed_items.append({
295
+ "item_name": item_name if item_name else "UNKNOWN",
296
+ "item_amount": float(round(amount, 2)),
297
+ "item_rate": float(round(rate, 2)) if rate else 0.0,
298
+ "item_quantity": float(qty) if qty else 1.0
299
+ })
300
+ else:
301
+ # fallback simple parse
302
+ numeric_idxs = [i for i,t in enumerate(tokens) if is_numeric_token(t)]
303
+ if not numeric_idxs:
304
+ continue
305
+ last_idx = numeric_idxs[-1]
306
+ amt = normalize_num_str(tokens[last_idx])
307
+ if amt is None:
308
+ continue
309
+ name = " ".join(tokens[:last_idx]).strip()
310
+ if name == "":
311
+ continue
312
+ rate = 0.0; qty = 1.0
313
+ if len(numeric_idxs) >= 2:
314
+ r = normalize_num_str(tokens[numeric_idxs[-2]])
315
+ rate = r if r else 0.0
316
+ if len(numeric_idxs) >= 3:
317
+ q = normalize_num_str(tokens[numeric_idxs[-3]])
318
+ qty = q if q else 1.0
319
+ parsed_items.append({
320
+ "item_name": name,
321
+ "item_amount": float(round(amt, 2)),
322
+ "item_rate": float(round(rate, 2)),
323
+ "item_quantity": float(qty)
324
+ })
325
+ return parsed_items
326
 
327
+ # ---------------- dedupe & totals detection ----------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  def dedupe_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
 
 
 
 
329
  seen = set()
330
+ out: List[Dict[str, Any]] = []
331
  for it in items:
332
+ name_norm = re.sub(r"\s+", " ", it["item_name"].lower()).strip()
333
+ key = (name_norm[:100], round(float(it["item_amount"]), 2))
 
334
  if key in seen:
335
  continue
336
  seen.add(key)
337
  out.append(it)
338
  return out
339
 
340
+ def detect_subtotals_and_totals(rows_texts: List[str]) -> Dict[str, Optional[float]]:
341
+ subtotal = None; final_total = None
342
+ for rt in rows_texts[::-1]:
 
 
 
 
 
343
  if not rt or rt.strip() == "":
344
  continue
345
  if TOTAL_KEYWORDS.search(rt):
 
346
  m = NUM_RE.search(rt)
347
  if m:
348
+ v = normalize_num_str(m.group(0))
349
+ if v is None:
350
  continue
 
351
  if re.search(r"sub", rt, re.I):
352
  if subtotal is None:
353
+ subtotal = float(round(v, 2))
354
  else:
 
355
  if final_total is None:
356
+ final_total = float(round(v, 2))
357
  return {"subtotal": subtotal, "final_total": final_total}
358
 
359
+ # ---------------- optional Gemini refinement ----------------
360
+ def refine_with_gemini(page_items: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], Dict[str,int]]:
 
 
 
 
 
 
 
 
361
  zero_usage = {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}
362
  if not GEMINI_API_KEY:
363
  return page_items, zero_usage
 
364
  try:
 
365
  prompt = (
366
+ "You are a precise bill extraction assistant. Given an array of line items with fields "
367
+ "item_name, item_quantity, item_rate, item_amount, return a cleaned array where "
368
+ "summary/total rows removed, numeric mistakes corrected, and duplicates removed. "
369
+ "Return ONLY valid JSON array.\n\n"
 
370
  f"items = {json.dumps(page_items, ensure_ascii=False)}"
371
  )
 
372
  model = genai.GenerativeModel(GEMINI_MODEL_NAME)
373
  response = model.generate_content(
374
  [
375
+ {"role":"system","parts":["Be concise. Return ONLY valid JSON array."]},
376
+ {"role":"user","parts":[prompt]},
377
  ]
378
  )
 
379
  raw_text = response.text.strip()
 
380
  if raw_text.startswith("```"):
381
  raw_text = re.sub(r"^```[a-zA-Z]*", "", raw_text)
382
  raw_text = re.sub(r"```$", "", raw_text).strip()
 
383
  parsed = json.loads(raw_text)
384
  if isinstance(parsed, list):
 
385
  cleaned = []
386
  for obj in parsed:
387
  try:
388
  cleaned.append({
389
+ "item_name": str(obj.get("item_name","")).strip(),
390
+ "item_amount": float(obj.get("item_amount",0.0)),
391
+ "item_rate": float(obj.get("item_rate",0.0) or 0.0),
392
+ "item_quantity": float(obj.get("item_quantity",1.0) or 1.0)
393
  })
394
  except Exception:
395
  continue
396
+ return cleaned, zero_usage
397
+ return page_items, zero_usage
 
 
 
 
398
  except Exception:
399
  return page_items, zero_usage
400
 
 
402
  @app.post("/extract-bill-data")
403
  async def extract_bill_data(payload: BillRequest):
404
  doc_url = payload.document
405
+ # download
406
  try:
407
  headers = {"User-Agent": "Mozilla/5.0"}
408
  resp = requests.get(doc_url, headers=headers, timeout=30)
409
  if resp.status_code != 200:
410
  raise RuntimeError(f"download failed status={resp.status_code}")
411
  file_bytes = resp.content
412
+ except Exception:
413
  return {
414
  "is_success": False,
415
+ "token_usage": {"total_tokens":0,"input_tokens":0,"output_tokens":0},
416
  "data": {"pagewise_line_items": [], "total_item_count": 0}
417
  }
418
 
419
+ # convert pages
420
+ images: List[Image.Image] = []
421
+ clean_url = doc_url.split("?",1)[0].lower()
422
  try:
423
  if clean_url.endswith(".pdf"):
424
+ images = convert_from_bytes(file_bytes)
425
+ elif any(clean_url.endswith(ext) for ext in [".png",".jpg",".jpeg",".tiff",".bmp"]):
426
+ images = [Image.open(BytesIO(file_bytes))]
 
 
427
  else:
 
428
  try:
429
+ images = convert_from_bytes(file_bytes)
 
430
  except Exception:
431
  images = []
432
  except Exception:
433
  images = []
434
 
435
+ pagewise_line_items: List[Dict[str,Any]] = []
436
+ cumulative_token_usage = {"total_tokens":0,"input_tokens":0,"output_tokens":0}
437
 
 
438
  for idx, page_img in enumerate(images, start=1):
439
  try:
 
440
  processed_cv = preprocess_image(page_img)
 
 
441
  cells = image_to_tsv_cells(processed_cv)
 
 
442
  rows = group_cells_into_rows(cells, y_tolerance=12)
443
  rows_texts = [" ".join([c["text"] for c in r]) for r in rows]
444
+ totals = detect_subtotals_and_totals(rows_texts)
445
 
446
+ parsed_items = parse_rows_with_columns(rows, cells)
447
+ parsed_items = [p for p in parsed_items if not TOTAL_KEYWORDS.search(p["item_name"] or "")]
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  parsed_items = dedupe_items(parsed_items)
449
 
 
450
  if not parsed_items:
451
+ # fallback: raw OCR lines
452
+ raw_text = pytesseract.image_to_string(processed_cv)
453
+ fallback_items: List[Dict[str,Any]] = []
454
+ for line in [ln.strip() for ln in raw_text.splitlines() if ln.strip()]:
455
+ if TOTAL_KEYWORDS.search(line):
456
+ continue
457
+ toks = line.split()
458
+ numeric_idxs = [i for i,t in enumerate(toks) if NUM_RE.search(t)]
459
+ if not numeric_idxs:
460
+ continue
461
+ last = numeric_idxs[-1]
462
+ amt = normalize_num_str(toks[last])
463
+ if amt is None:
464
+ continue
465
+ name = " ".join(toks[:last]).strip()
466
+ if not name:
467
+ continue
468
+ fallback_items.append({
469
+ "item_name": name,
470
+ "item_amount": float(round(amt,2)),
471
+ "item_rate": 0.0,
472
+ "item_quantity": 1.0
473
+ })
474
+ parsed_items = dedupe_items(fallback_items)
 
 
475
 
476
+ # optional LLM refinement
477
  if GEMINI_API_KEY and parsed_items:
478
  refined, token_u = refine_with_gemini(parsed_items)
479
  parsed_items = refined
480
+ # token usage placeholder
481
  for k in cumulative_token_usage:
482
+ cumulative_token_usage[k] += token_u.get(k,0)
483
 
 
484
  page_type = "Bill Detail"
485
  page_text_join = " ".join(rows_texts).lower()
486
+ if any(x in page_text_join for x in ["pharmacy","medicine","tablet"]):
487
  page_type = "Pharmacy"
488
  if "final bill" in page_text_join or "grand total" in page_text_join:
489
  page_type = "Final Bill"
490
 
 
491
  pagewise_line_items.append({
492
  "page_no": str(idx),
493
  "page_type": page_type,
 
495
  })
496
 
497
  except Exception:
 
498
  pagewise_line_items.append({
499
  "page_no": str(idx),
500
  "page_type": "Bill Detail",
 
502
  })
503
  continue
504
 
505
+ total_item_count = sum(len(p.get("bill_items",[])) for p in pagewise_line_items)
506
 
507
  return {
508
  "is_success": True,