Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files10 unmodified lines1112131415161718192033 unmodified lines5455565758596010 unmodified lines717273747576777879807 unmodified lines888990919293949514 unmodified lines1101111121131141151161175 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711729 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782791 unmodified line28128228328428528628711 unmodified lines2993003013023033043053063073083093103111 unmodified line3133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463 unmodified lines35035135235335435535635735820 unmodified lines37938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846945 unmodified lines5155165175185195205212 unmodified lines5245255265275285295305315325335345355365375384 unmodified lines5435445455465475485493 unmodified lines55355455555655755855911 unmodified lines57157257357457557657757857958058158258358458558613 unmodified lines6006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316324 unmodified lines6376386396406416426436441 unmodified line64664764864965065165219 unmodified lines67267367467567667767867968068168268368468568668768868969069169278 unmodified lines77177277377477577677777877978078178278340 unmodified lines82482582682782882983016 unmodified lines84784884985085185285385419 unmodified lines87487587687787887988061 unmodified lines94294394494594610 unmodified linesfrom typing import List, Dict, Any, Optional, Tupleimport uvicornfrom fastapi import FastAPIfrom pydantic import BaseModelimport requestsfrom PIL import Image, ImageOpsfrom pdf2image import convert_from_bytesimport pytesseractfrom pytesseract import Output33 unmodified linesr"(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|total)",re.I,)FOOTER_KEYWORDS = re.compile(r"(page|printed on|printed:|date:|time:|am|pm|signature)", re.I)HEADER_KEYWORDS = ["description", "qty", "hrs", "rate", "discount", "net", "amt", "amount",10 unmodified linesHEADER_PHRASES = [h.lower() for h in HEADER_PHRASES]# ---------------- small utilities ----------------def sanitize_ocr_text(s: Optional[str]) -> str:if not s:return ""s = str(s)s = s.replace("\u2014", "-").replace("\u2013", "-")s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E]", " ", s)s = s.replace("\r\n", "\n").replace("\r", "\n")7 unmodified liness = str(s).strip()if s == "":return None# common OCR fixes in numeric strings (O -> 0, , as thousands)s = s.replace("O", "0").replace("o", "0").replace("l", "1")s = re.sub(r"[^\d\-\+\,\.\(\)]", "", s)negative = Falseif s.startswith("(") and s.endswith(")"):14 unmodified linesreturn bool(t and NUM_RE.search(str(t)))def looks_like_date_num(s: str) -> bool:if not s:return Falses_digits = re.sub(r"[^\d]", "", s or "")if len(s_digits) >= 7:if s_digits.endswith(("2025","2024","2023","2022","2026")):5 unmodified linespassreturn Falsedef collapse_repeated_chars(s: str) -> str:# collapse runs of repeated punctuation/letters that are OCR artifactss = re.sub(r"([^\w\s])\1{2,}", r"\1", s)s = re.sub(r"([A-Za-z])\1{3,}", r"\1\1", s)return sdef clean_name_text(s: str) -> str:if not s:return ""s = str(s)s = s.replace("—", "-").replace("–", "-")s = collapse_repeated_chars(s)s = re.sub(r"[_\|]{2,}", " ", s)s = re.sub(r"[^\x00-\x7F]+", " ", s) # remove non-ascii weird charss = re.sub(r"[\[\]\{\}\(\)]", " ", s)s = re.sub(r"\s+", " ", s)s = s.strip(" -:,.=")# fix common OCR 'OR' -> 'DR' when it's standalone uppercases = re.sub(r"\bOR\b", "DR", s)# remove trailing artifacts like 'x' placed between qty and names = re.sub(r"\s+x\s*$", "", s, flags=re.I)s = s.strip()return sdef is_probable_garbage_name(name: str) -> bool:if not name:return Truen = name.strip()# too short or too many non-alphaalpha_count = len(re.findall(r"[A-Za-z]", n))digit_count = len(re.findall(r"\d", n))non_word = len(re.findall(r"[^\w\s]", n))if alpha_count == 0:return Trueif len(n) < 2:return True# if >50% of chars are non-alnum, garbageif non_word / max(1, len(n)) > 0.45:return True# if digits dominate and look not like code/dateif digit_count / max(1, len(n)) > 0.6 and not looks_like_date_num(n):return Truereturn False# ---------------- image preprocessing ----------------def pil_to_cv2(img: Image.Image) -> Any:arr = np.array(img)9 unmodified linesif w < target_w:scale = target_w / float(w)pil_img = pil_img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)# convert to gray + CLAHE (adaptive contrast)cv_img = pil_to_cv2(pil_img)if cv_img.ndim == 3:gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)else:gray = cv_img# unsigned int conversiongray = np.asarray(gray, dtype=np.uint8)# CLAHE for contrast enhancementtry:clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))gray = clahe.apply(gray)except Exception:pass# denoisetry:gray = cv2.fastNlMeansDenoising(gray, h=10)except Exception:pass# adaptive thresholdtry:bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 41, 15)except Exception:_, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)# morphological operations to remove tiny noise and thin grid lineskernel_close = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))bw = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel_close)kernel_open = cv2.getStructuringElement(cv2.MORPH_RECT, (1,1))bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, kernel_open)return bw# ---------------- OCR TSV (word-level) ----------------OCR_CONF_THRESHOLD = 30.0 # drop tokens with confidence less than this (if provided by tesseract)def image_to_tsv_cells(cv_img: Any) -> List[Dict[str, Any]]:# pytesseract can accept numpy arrays or PIL imagestry:o = pytesseract.image_to_data(cv_img, output_type=Output.DICT, config="--psm 6")except Exception:o = pytesseract.image_to_data(cv_img, output_type=Output.DICT)cells: List[Dict[str, Any]] = []n = len(o.get("text", []))for i in range(n):raw = o["text"][i]2 unmodified linestxt = str(raw).strip()if not txt:continue# try to parse confidence (tesseract returns strings sometimes)conf_raw = o.get("conf", [None]*n)[i]try:conf = float(conf_raw) if conf_raw not in (None, "", "-1") else -1.0except Exception:conf = -1.0# skip very-low-confidence tokens (reduce garbage)if conf >= 0 and conf < OCR_CONF_THRESHOLD:continueleft = int(o.get("left", [0]*n)[i])top = int(o.get("top", [0]*n)[i])width = int(o.get("width", [0]*n)[i])height = int(o.get("height", [0]*n)[i])center_y = top + height / 2.0center_x = left + width / 2.0# normalize numeric OCR artifacts inside tokenif re.search(r"[0-9]", txt):# quick fixestxt = txt.replace("O", "0").replace("o", "0").replace("l", "1")txt = re.sub(r"[^0-9\.\,\-\(\)]", lambda m: "" if m.group(0).isspace() else m.group(0), txt)cells.append({"text": txt,"conf": conf,"left": left,"top": top,"width": width,"height": height,"center_y": center_y,"center_x": center_x})return cells# ---------------- grouping & merging helpers ----------------1 unmodified lineif not cells:return []sorted_cells = sorted(cells, key=lambda c: (c["center_y"], c["center_x"]))rows: List[List[Dict[str, Any]]] = []current = [sorted_cells[0]]last_y = sorted_cells[0]["center_y"]for c in sorted_cells[1:]:11 unmodified linesdef merge_multiline_names(rows: List[List[Dict[str, Any]]]) -> List[List[Dict[str, Any]]]:if not rows:return rowsmerged: List[List[Dict[str, Any]]] = []i = 0while i < len(rows):row = rows[i]tokens = [c["text"] for c in row]has_num = any(is_numeric_token(t) for t in tokens)# Merge a full-text row with the next numeric row if appropriateif not has_num and i + 1 < len(rows):next_row = rows[i+1]next_tokens = [c["text"] for c in next_row]1 unmodified lineif next_has_num and len(tokens) >= 2 and len([t for t in next_tokens if not is_numeric_token(t)]) <= 3:merged_row = []min_left = min((c["left"] for c in next_row), default=0)offset = 0for c in row:newc = c.copy()# Shift text to left of numeric columnsnewc["left"] = min_left - 20 + offsetnewc["center_x"] = newc["left"] + newc["width"] / 2.0merged_row.append(newc)offset += 8merged_row.extend(next_row)merged.append(sorted(merged_row, key=lambda cc: cc["left"]))i += 2continue# Merge two short text-only rows (e.g. split names)if not has_num and i + 1 < len(rows):next_row = rows[i+1]next_tokens = [c["text"] for c in next_row]next_has_num = any(is_numeric_token(t) for t in next_tokens)if not next_has_num and len(tokens) <= 3 and len(next_tokens) <= 3:combined = row + next_rowmin_left = min((c["left"] for c in combined), default=0)merged_row = []for c in combined:newc = c.copy()# move slightly to align leftif newc["left"] <= min_left:newc["left"] = min_leftnewc["center_x"] = newc["left"] + newc["width"] / 2.0merged_row.append(newc)merged.append(sorted(merged_row, key=lambda cc: cc["left"]))i += 2continue3 unmodified lines# ---------------- numeric column detection ----------------def detect_numeric_columns(cells: List[Dict[str, Any]], max_columns: int = 4) -> List[float]:xs = sorted([c["center_x"] for c in cells if is_numeric_token(c["text"])])if not xs:return []if len(xs) == 1:return [xs[0]]gaps = [xs[i+1] - xs[i] for i in range(len(xs)-1)]20 unmodified linesdistances = [abs(token_x - cx) for cx in column_centers]return int(np.argmin(distances))# ---------------- item validation & repair ----------------MAX_REASONABLE_QTY = 100.0MAX_REASONABLE_RATE = 1_000_000.0def validate_and_fix_item(item: Dict[str, Any]) -> Optional[Dict[str, Any]]:"""Ensure amount/rate/qty are reasonable. Try to fix obvious OCR-caused errors.Return None if the item should be discarded as garbage."""# sanitize namename = clean_name_text(item.get("item_name", "") or "")if is_probable_garbage_name(name):# reject obviously garbage namesreturn Noneamt = item.get("item_amount", 0.0) or 0.0rate = item.get("item_rate", 0.0) or 0.0qty = item.get("item_quantity", 0.0) or 0.0# sanity capstry:amt = float(amt)except Exception:return Nonetry:rate = float(rate)except Exception:rate = 0.0try:qty = float(qty)except Exception:qty = 1.0# If qty is ridiculously large -> likely OCR error. Reset to 1 and set rate=amount if rate invalidif qty > MAX_REASONABLE_QTY:logger.debug("Qty %s too large for '%s' — resetting to 1", qty, name)qty = 1.0if rate <= 0 or rate > amt * 10:rate = amt# If rate > amt but rate is extremely large -> swap/assume misplace: if rate*qty approximates amt, fine.if rate > amt and qty > 0:if abs(rate * qty - amt) > max(0.05 * amt, 1.0):# If rate bigger than amount and doesn't fit, assume rate was missing -> set rate = amt/qty if meaningfultry:candidate = amt / qty if qty else amtif 0 < candidate <= MAX_REASONABLE_RATE:logger.debug("Adjusting rate for '%s' from %s to %s", name, rate, candidate)rate = candidateexcept Exception:pass# If rate == 0 but qty>0 and amt>0 try infer simple integer ratio from numeric candidates already done upstream,# fallback: set rate = amt (qty assumed 1)if (rate == 0 or rate is None) and qty and qty > 0:if qty == 1 or not (amt / qty).is_integer():# simply compute ratetry:candidate_rate = amt / qtyif candidate_rate > 0 and candidate_rate <= MAX_REASONABLE_RATE:rate = round(candidate_rate, 2)except Exception:rate = 0.0# final sanity: negative/zero amounts droppedif amt <= 0.0:return Noneif qty <= 0:qty = 1.0# clamp qty to reasonableif qty > MAX_REASONABLE_QTY:qty = 1.0# Round sensible valuesamt = float(round(amt, 2))rate = float(round(rate, 2)) if rate is not None else 0.0qty = float(round(qty, 3))return {"item_name": name,"item_amount": amt,"item_rate": rate,"item_quantity": qty}# ---------------- Gemini refinement (deterministic) ----------------def refine_with_gemini(page_items: List[Dict[str, Any]], page_text: str = "") -> Tuple[List[Dict[str, Any]], Dict[str, int]]:zero_usage = {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}45 unmodified lines# ---------------- parsing rows into items (modified) ----------------def parse_rows_with_columns(rows: List[List[Dict[str, Any]]], page_cells: List[Dict[str, Any]]) -> List[Dict[str, Any]]:parsed_items: List[Dict[str, Any]] = []rows = merge_multiline_names(rows)column_centers = detect_numeric_columns(page_cells, max_columns=4)2 unmodified linesif not tokens:continuejoined_lower = " ".join(tokens).lower()# skip obvious footers and headersif FOOTER_KEYWORDS.search(joined_lower) and not any(is_numeric_token(t) for t in tokens):continueif all(not is_numeric_token(t) for t in tokens):# if a pure-text row but looks like header -> skipif looks_like_header_text(joined_lower):continue# otherwise we may have description-only rows (handled by merge_multiline_names)continuenumeric_values = []4 unmodified linesv = normalize_num_str(t)if v is not None:numeric_values.append(float(v))# unique sorted descendingnumeric_values = sorted({int(x) if float(x).is_integer() else x for x in numeric_values}, reverse=True)if column_centers:3 unmodified linest = c["text"]if is_numeric_token(t) and not looks_like_date_num(t):col_idx = assign_token_to_column(c["center_x"], column_centers)if col_idx is None or col_idx < 0:numeric_bucket_map[len(column_centers) - 1].append(t)else:numeric_bucket_map[col_idx].append(t)11 unmodified linesrate = normalize_num_str(get_bucket(num_cols - 2)) if num_cols >= 2 else Noneqty = normalize_num_str(get_bucket(num_cols - 3)) if num_cols >= 3 else None# fallback: last numeric token as amountif amount is None:for t in reversed(tokens):if is_numeric_token(t) and not looks_like_date_num(t):candidate = normalize_num_str(t)if candidate is not None:amount = candidatebreak# try to infer rate & qty from numeric_valuesif amount is not None and numeric_values:for cand in numeric_values:try:13 unmodified linesif r < 1 or r > 200:continueif abs(ratio - r) <= max(0.03 * r, 0.15):# reasonable integer quantityqty = float(r)rate = cand_floatbreak# additional fallback if rate missing but qty existsif (rate is None or rate == 0) and qty and qty != 0 and amount is not None:try:candidate_rate = amount / qtyif 0 < candidate_rate <= 1e7:rate = candidate_rateexcept Exception:pass# default quantity = 1 if unknownif qty is None:qty = 1.0# final rounding / validation via helperraw_item = {"item_name": name if name else "UNKNOWN", "item_amount": amount or 0.0,"item_rate": rate or 0.0, "item_quantity": qty or 1.0}fixed = validate_and_fix_item(raw_item)if fixed:parsed_items.append(fixed)# else skipelse:# fallback parsing if no clear numeric columnsnumeric_idxs = [i for i, t in enumerate(tokens) if is_numeric_token(t) and not looks_like_date_num(t)]if not numeric_idxs:continue4 unmodified linesname = " ".join(tokens[:last]).strip()if not name:continue# gather numeric candidates on the right to infer rate/qtyright_nums = []for i in numeric_idxs:v = normalize_num_str(tokens[i])1 unmodified lineright_nums.append(float(v))right_nums = sorted({int(x) if float(x).is_integer() else x for x in right_nums}, reverse=True)rate = None; qty = Noneif len(right_nums) >= 2:cand = right_nums[1]if 1 < cand < float(amt):19 unmodified linesif rate is None:rate = 0.0raw_item = {"item_name": clean_name_text(name), "item_amount": float(round(amt,2)),"item_rate": float(round(rate,2)), "item_quantity": float(qty)}fixed = validate_and_fix_item(raw_item)if fixed:parsed_items.append(fixed)return parsed_items# ---------------- dedupe & totals ----------------def dedupe_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:seen = set()out: List[Dict[str, Any]] = []for it in items:nm = re.sub(r"\s+", " ", it["item_name"].lower()).strip()key = (nm[:120], round(float(it.get("item_amount", 0.0) or 0.0), 2))if key in seen:continueseen.add(key)78 unmodified linesqty = float(item.get("item_quantity", 0) or 0)if qty <= 0:return Falseif rate and rate > amt * 10 and amt < 10000:return Falseif amt <= 0.0:return False# must contain at least one alphabetic charif not re.search(r"[A-Za-z]", name):return Falsereturn True# ---------------- main endpoint ----------------40 unmodified lines"token_usage": {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}}images: List[Image.Image] = []clean_url = doc_url.split("?", 1)[0].lower()try:if clean_url.endswith(".pdf"):16 unmodified linestry:proc = preprocess_image(page_img)cells = image_to_tsv_cells(proc)if not cells:logger.debug("No OCR cells extracted for page %s", idx)rows = group_cells_into_rows(cells, y_tolerance=12)rows_texts = [" ".join([c["text"] for c in r]).strip() for r in rows]19 unmodified linesparsed_items = parse_rows_with_columns(rows, cells)# Use Gemini only if configuredrefined_items, token_u = refine_with_gemini(parsed_items, page_text)for k in cumulative_token_usage:cumulative_token_usage[k] += token_u.get(k, 0)61 unmodified lineslogger.exception("run_all_samples failed: %s", e)return {"status": "error", "error": str(e)}if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))10 unmodified lines1112131415161718192033 unmodified lines5455565758596010 unmodified lines7172737475767778797 unmodified lines87888990919214 unmodified lines1071081091101111125 unmodified lines1181191201211221231241251261271281291301311321331349 unmodified lines1441451461471481491501511521531541551561571581591601611621631641651661671681691701711721732 unmodified lines1761771781791801811821831841851861871881891901911921931 unmodified line19519619719819920020111 unmodified lines2132142152162172182192202212222232241 unmodified line2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582593 unmodified lines26326426526626726826927027127220 unmodified lines29329429529629729845 unmodified lines3443453463473483493502 unmodified lines3533543553563573583593603614 unmodified lines3663673683693703713 unmodified lines37537637737837938038111 unmodified lines39339439539639739839940040140240340440513 unmodified lines4194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614 unmodified lines4664674684694704714724731 unmodified line47547647747847948019 unmodified lines50050150250350450550650750850951051151251351451551651751851952052178 unmodified lines60060160260360460560660760860940 unmodified lines65065165265365465565616 unmodified lines67367467567667767819 unmodified lines69869970070170270361 unmodified lines76576676776810 unmodified linesfrom typing import List, Dict, Any, Optional, Tupleimport uvicornfrom fastapi import FastAPI, BackgroundTasksfrom pydantic import BaseModelimport requestsfrom PIL import Imagefrom pdf2image import convert_from_bytesimport pytesseractfrom pytesseract import Output33 unmodified linesr"(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|total)",re.I,)FOOTER_KEYWORDS = re.compile(r"(page|printed on|printed:|date:|time:|am|pm)", re.I)HEADER_KEYWORDS = ["description", "qty", "hrs", "rate", "discount", "net", "amt", "amount",10 unmodified linesHEADER_PHRASES = [h.lower() for h in HEADER_PHRASES]# ---------------- small utilities ----------------def sanitize_ocr_text(s: str) -> str:if not s:return ""s = s.replace("\u2014", "-").replace("\u2013", "-")s = re.sub(r"[^\x09\x0A\x0D\x20-\x7E]", " ", s)s = s.replace("\r\n", "\n").replace("\r", "\n")7 unmodified liness = str(s).strip()if s == "":return Nones = re.sub(r"[^\d\-\+\,\.\(\)]", "", s)negative = Falseif s.startswith("(") and s.endswith(")"):14 unmodified linesreturn bool(t and NUM_RE.search(str(t)))def looks_like_date_num(s: str) -> bool:s_digits = re.sub(r"[^\d]", "", s or "")if len(s_digits) >= 7:if s_digits.endswith(("2025","2024","2023","2022","2026")):5 unmodified linespassreturn Falsedef clean_name_text(s: str) -> str:s = s.replace("—", "-")s = re.sub(r"\s+", " ", s)s = s.strip(" -:,.=")s = re.sub(r"\s+x$", "", s, flags=re.I)s = re.sub(r"[\)\}\]]+$", "", s)s = re.sub(r"\bOR\b", "DR", s)s = s.strip(" -:,.")s = s.strip()return s# ---------------- image preprocessing ----------------def pil_to_cv2(img: Image.Image) -> Any:arr = np.array(img)9 unmodified linesif w < target_w:scale = target_w / float(w)pil_img = pil_img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)cv_img = pil_to_cv2(pil_img)# grayscale and denoiseif cv_img.ndim == 3:gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)else:gray = cv_imggray = cv2.fastNlMeansDenoising(gray, h=10)try:bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY, 41, 15)except Exception:_, bw = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)kernel = np.ones((1,1), np.uint8)bw = cv2.morphologyEx(bw, cv2.MORPH_OPEN, kernel)return bw# ---------------- OCR TSV ----------------def image_to_tsv_cells(cv_img: Any) -> List[Dict[str, Any]]:# pytesseract expects either a PIL image or numpy arraytry:o = pytesseract.image_to_data(cv_img, output_type=Output.DICT, config="--psm 6")except Exception:o = pytesseract.image_to_data(cv_img, output_type=Output.DICT)cells = []n = len(o.get("text", []))for i in range(n):raw = o["text"][i]2 unmodified linestxt = str(raw).strip()if not txt:continuetry:conf = float(o["conf"][i]) if o["conf"][i] not in (None, "", "-1") else -1.0except Exception:conf = -1.0left = int(o.get("left", [0])[i])top = int(o.get("top", [0])[i])width = int(o.get("width", [0])[i])height = int(o.get("height", [0])[i])center_y = top + height / 2.0center_x = left + width / 2.0cells.append({"text": txt, "conf": conf, "left": left, "top": top,"width": width, "height": height, "center_y": center_y, "center_x": center_x})return cells# ---------------- grouping & merging helpers ----------------1 unmodified lineif not cells:return []sorted_cells = sorted(cells, key=lambda c: (c["center_y"], c["center_x"]))rows = []current = [sorted_cells[0]]last_y = sorted_cells[0]["center_y"]for c in sorted_cells[1:]:11 unmodified linesdef merge_multiline_names(rows: List[List[Dict[str, Any]]]) -> List[List[Dict[str, Any]]]:if not rows:return rowsmerged = []i = 0while i < len(rows):row = rows[i]tokens = [c["text"] for c in row]has_num = any(is_numeric_token(t) for t in tokens)if not has_num and i + 1 < len(rows):next_row = rows[i+1]next_tokens = [c["text"] for c in next_row]1 unmodified lineif next_has_num and len(tokens) >= 2 and len([t for t in next_tokens if not is_numeric_token(t)]) <= 3:merged_row = []min_left = min((c["left"] for c in next_row), default=0)offset = 10for c in row:newc = c.copy()newc["left"] = min_left - offsetnewc["center_x"] = newc["left"] + newc.get("width", 0) / 2.0merged_row.append(newc)offset += 10merged_row.extend(next_row)merged.append(sorted(merged_row, key=lambda cc: cc["left"]))i += 2continueif not has_num and i + 1 < len(rows):next_row = rows[i+1]next_tokens = [c["text"] for c in next_row]next_has_num = any(is_numeric_token(t) for t in next_tokens)if not next_has_num and len(tokens) <= 3 and len(next_tokens) <= 3:merged_row = []min_left = min((c["left"] for c in next_row + row), default=0)offset = 10for c in row + next_row:newc = c.copy()if newc["left"] > min_left:newc["left"] = newc["left"]else:newc["left"] = min_left - offsetnewc["center_x"] = newc["left"] + newc.get("width", 0) / 2.0merged_row.append(newc)offset += 5merged.append(sorted(merged_row, key=lambda cc: cc["left"]))i += 2continue3 unmodified lines# ---------------- numeric column detection ----------------def detect_numeric_columns(cells: List[Dict[str, Any]], max_columns: int = 4) -> List[float]:xs = [c["center_x"] for c in cells if is_numeric_token(c["text"])]if not xs:return []xs = sorted(xs)if len(xs) == 1:return [xs[0]]gaps = [xs[i+1] - xs[i] for i in range(len(xs)-1)]20 unmodified linesdistances = [abs(token_x - cx) for cx in column_centers]return int(np.argmin(distances))# ---------------- Gemini refinement (deterministic) ----------------def refine_with_gemini(page_items: List[Dict[str, Any]], page_text: str = "") -> Tuple[List[Dict[str, Any]], Dict[str, int]]:zero_usage = {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}45 unmodified lines# ---------------- parsing rows into items (modified) ----------------def parse_rows_with_columns(rows: List[List[Dict[str, Any]]], page_cells: List[Dict[str, Any]]) -> List[Dict[str, Any]]:parsed_items = []rows = merge_multiline_names(rows)column_centers = detect_numeric_columns(page_cells, max_columns=4)2 unmodified linesif not tokens:continuejoined_lower = " ".join(tokens).lower()if FOOTER_KEYWORDS.search(joined_lower) and not any(is_numeric_token(t) for t in tokens):continueif all(not is_numeric_token(t) for t in tokens):continuenumeric_values = []4 unmodified linesv = normalize_num_str(t)if v is not None:numeric_values.append(float(v))numeric_values = sorted({int(x) if float(x).is_integer() else x for x in numeric_values}, reverse=True)if column_centers:3 unmodified linest = c["text"]if is_numeric_token(t) and not looks_like_date_num(t):col_idx = assign_token_to_column(c["center_x"], column_centers)if col_idx is None:numeric_bucket_map[len(column_centers) - 1].append(t)else:numeric_bucket_map[col_idx].append(t)11 unmodified linesrate = normalize_num_str(get_bucket(num_cols - 2)) if num_cols >= 2 else Noneqty = normalize_num_str(get_bucket(num_cols - 3)) if num_cols >= 3 else Noneif amount is None:for t in reversed(tokens):if is_numeric_token(t) and not looks_like_date_num(t):amount = normalize_num_str(t)if amount is not None:breakif amount is not None and numeric_values:for cand in numeric_values:try:13 unmodified linesif r < 1 or r > 200:continueif abs(ratio - r) <= max(0.03 * r, 0.15):if r <= 100:rate = cand_floatqty = float(r)breakif (rate is None or rate == 0) and qty and qty != 0 and amount is not None:try:candidate_rate = amount / qtyif candidate_rate >= 2:rate = candidate_rateexcept Exception:passif qty is None:qty = 1.0try:amount = float(round(amount, 2))except:continuetry:rate = float(round(rate, 2)) if rate is not None else 0.0except:rate = 0.0try:qty = float(qty)except:qty = 1.0parsed_items.append({"item_name": name if name else "UNKNOWN","item_amount": amount,"item_rate": rate if rate is not None else 0.0,"item_quantity": qty if qty is not None else 1.0,})else:numeric_idxs = [i for i, t in enumerate(tokens) if is_numeric_token(t) and not looks_like_date_num(t)]if not numeric_idxs:continue4 unmodified linesname = " ".join(tokens[:last]).strip()if not name:continuerate = None; qty = Noneright_nums = []for i in numeric_idxs:v = normalize_num_str(tokens[i])1 unmodified lineright_nums.append(float(v))right_nums = sorted({int(x) if float(x).is_integer() else x for x in right_nums}, reverse=True)if len(right_nums) >= 2:cand = right_nums[1]if 1 < cand < float(amt):19 unmodified linesif rate is None:rate = 0.0parsed_items.append({"item_name": clean_name_text(name),"item_amount": float(round(amt, 2)),"item_rate": float(round(rate, 2)),"item_quantity": float(qty),})return parsed_items# ---------------- dedupe & totals ----------------def dedupe_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:seen = set()out = []for it in items:nm = re.sub(r"\s+", " ", it["item_name"].lower()).strip()key = (nm[:120], round(float(it["item_amount"]), 2))if key in seen:continueseen.add(key)78 unmodified linesqty = float(item.get("item_quantity", 0) or 0)if qty <= 0:return Falseif rate and rate > amt:return Falseif amt <= 0.0:return Falsereturn True# ---------------- main endpoint ----------------40 unmodified lines"token_usage": {"total_tokens": 0, "input_tokens": 0, "output_tokens": 0}}images = []clean_url = doc_url.split("?", 1)[0].lower()try:if clean_url.endswith(".pdf"):16 unmodified linestry:proc = preprocess_image(page_img)cells = image_to_tsv_cells(proc)rows = group_cells_into_rows(cells, y_tolerance=12)rows_texts = [" ".join([c["text"] for c in r]).strip() for r in rows]19 unmodified linesparsed_items = parse_rows_with_columns(rows, cells)refined_items, token_u = refine_with_gemini(parsed_items, page_text)for k in cumulative_token_usage:cumulative_token_usage[k] += token_u.get(k, 0)61 unmodified lineslogger.exception("run_all_samples failed: %s", e)return {"status": "error", "error": str(e)}
app.py+81-259