import os import json import logging import requests import base64 from io import BytesIO from pypdf import PdfReader from PIL import Image import fitz # PyMuPDF — PDF rendering for scanned docs logger = logging.getLogger(__name__) # ───────────────────────────────────────────────────────────────────────────── # Pipeline thresholds # ───────────────────────────────────────────────────────────────────────────── MIN_TEXT_CHARS = 50 # Stage 1: native text must have at least this many chars MIN_TESS_WORDS = 30 # Stage 2: Tesseract must return at least this many words RENDER_DPI = 2.5 # PyMuPDF render scale (2.5x ≈ 212 DPI) # ───────────────────────────────────────────────────────────────────────────── # Models # ───────────────────────────────────────────────────────────────────────────── MODEL_TEXT = "meta-llama/llama-3.3-70b-instruct" # Stage 1 & 2 — FREE tier MODEL_VISION = "qwen/qwen2.5-vl-72b-instruct" # Stage 3 — best document OCR # ───────────────────────────────────────────────────────────────────────────── # Prompts # ───────────────────────────────────────────────────────────────────────────── SYSTEM_PROMPT = ( "You are a highly accurate document data extraction AI. " "Extract only what is explicitly present in the document — never invent, guess, or add placeholder fields. " "Respond with a raw JSON object only. No markdown, no explanation, no extra keys." ) BLANK_FORM_PROMPT = ( "This appears to be an unfilled form or template. " "Return a JSON object with these keys only: " "form_type (name of the form), " "tax_year (year if visible, else null), " "purpose (one sentence describing what this form is for), " "status (always set to 'blank_template'). " "Return ONLY valid JSON, no markdown." ) def _build_user_prompt(doc_type: str) -> str: return ( f"Document type hint: {doc_type}\n\n" "You are a precise data extraction AI. Read this document and extract its key information.\n\n" "STRICT RULES:\n" "1. Use field names exactly as they appear in the document " "(e.g. 'PAN Number', 'Date of Birth', 'Employer Name', 'Tax Year').\n" "2. For LEGAL DOCUMENTS, LETTERS, or CONTRACTS: extract key terms — " "services included, responsibilities, fees, tax forms mentioned, deadlines, party names.\n" "3. Extract ONLY fields that have actual content — do NOT add null or empty fields.\n" "4. Dates: format as DD/MM/YYYY. A run-together date like '27082022' → '27/08/2022'.\n" "5. For list fields (services, items, fees) use JSON arrays.\n" "6. Ignore bilingual label noise (Hindi/Devanagari text) — extract English values only.\n" "7. If the document is truly a blank unfilled form with zero data, return {}.\n" "8. Return ONLY a valid JSON object — no markdown, no explanation." ) # ───────────────────────────────────────────────────────────────────────────── # Helpers # ───────────────────────────────────────────────────────────────────────────── def image_to_base64(pil_image: Image.Image, max_size: int = 2048) -> str: """Encode a PIL image to a base64 data URI, downscaling if needed.""" w, h = pil_image.size if w > max_size or h > max_size: scale = max_size / max(w, h) pil_image = pil_image.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS) logger.debug(f"[Vision] Resized {w}x{h} → {pil_image.size}") if pil_image.mode != "RGB": pil_image = pil_image.convert("RGB") buf = BytesIO() pil_image.save(buf, format="JPEG", quality=92) return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode() def _render_pdf_page(file_path: str, scale: float = RENDER_DPI) -> Image.Image | None: """Render the first page of a PDF to a PIL Image using PyMuPDF.""" try: pdf_doc = fitz.open(file_path) pix = pdf_doc[0].get_pixmap( matrix=fitz.Matrix(scale, scale), colorspace=fitz.csRGB ) img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) pdf_doc.close() return img except Exception as e: logger.error(f"[PyMuPDF] Render failed for {file_path}: {e}") return None def _tesseract_text(pil_image: Image.Image) -> str: """ Run Tesseract OCR on a PIL image. Uses eng+hin for bilingual Indian documents (Aadhaar, PAN, tax forms). Falls back to eng-only if Hindi data not installed. Auto-detects binary on Windows vs Linux/Docker. """ try: import pytesseract import platform if platform.system() == "Windows": win_paths = [ r"C:\Program Files\Tesseract-OCR\tesseract.exe", r"C:\Users\abhil\AppData\Local\Programs\Tesseract-OCR\tesseract.exe", ] for p in win_paths: if os.path.isfile(p): pytesseract.pytesseract.tesseract_cmd = p break config = "--psm 6 --oem 3" try: text = pytesseract.image_to_string(pil_image, lang="eng+hin", config=config).strip() logger.debug(f"[Tesseract] eng+hin produced {len(text.split())} words") except Exception: logger.debug("[Tesseract] eng+hin unavailable, using eng only") text = pytesseract.image_to_string(pil_image, lang="eng", config=config).strip() return text except ImportError: logger.warning("[Tesseract] pytesseract not installed — skipping Stage 2") return "" except Exception as e: logger.warning(f"[Tesseract] OCR failed: {e}") return "" def _call_openrouter( api_key: str, model: str, user_content: list, original_text: str = "", ) -> dict | None: """ POST to OpenRouter and return parsed JSON dict, or None on failure. If the model returns {} (blank/unfilled doc), retries with a metadata prompt so the admin always sees form_type / purpose / tax_year. """ def _post(content): try: response = requests.post( url="https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }, json={ "model": model, "messages": [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": content}, ], "response_format": {"type": "json_object"}, }, timeout=60, ) response.raise_for_status() raw = response.json()["choices"][0]["message"]["content"].strip() for fence in ("```json", "```"): if raw.startswith(fence): raw = raw[len(fence):] if raw.endswith("```"): raw = raw[:-3] return json.loads(raw.strip()) except Exception as e: logger.error(f"[OpenRouter] {model} call failed: {e}") return None result = _post(user_content) # If model returned {} (blank template), retry with metadata-only prompt if result == {} and original_text: logger.info("[AI] Empty result — retrying with blank-form metadata prompt") fallback_content = [{ "type": "text", "text": f"{BLANK_FORM_PROMPT}\n\nDocument text:\n{original_text[:3000]}" }] result = _post(fallback_content) or {} return result # ───────────────────────────────────────────────────────────────────────────── # Main extraction entry point # ───────────────────────────────────────────────────────────────────────────── def extract_document_data(file_path: str, doc_type: str) -> dict | None: """ 3-stage extraction pipeline: Stage 1 — Native text (FREE) pypdf + PyMuPDF pull embedded text from the PDF. >= MIN_TEXT_CHARS → llama-3.3-70b (free tier) Stage 2 — Tesseract OCR (FREE, local CPU) PyMuPDF renders page at 2.5x DPI. Tesseract reads with eng+hin for bilingual docs. >= MIN_TESS_WORDS → llama-3.3-70b (free tier) Stage 3 — Qwen2.5-VL-72B vision (paid, minimal cost) Sends rendered page image to Qwen via OpenRouter. Blank template fallback: If any stage returns {}, a second call extracts form_type / purpose / tax_year / status metadata. """ api_key = os.getenv("OPENROUTER_API_KEY") if not api_key: logger.warning("[AI] OPENROUTER_API_KEY not set — skipping extraction") return None is_pdf = file_path.lower().endswith(".pdf") is_image = file_path.lower().endswith((".jpg", ".jpeg", ".png", ".webp")) if not (is_pdf or is_image): logger.info(f"[AI] Unsupported file type, skipping: {file_path}") return None user_prompt = _build_user_prompt(doc_type) try: # ── PDF ─────────────────────────────────────────────────────────────── if is_pdf: # Stage 1: native text text = "" try: reader = PdfReader(file_path) for page in reader.pages[:3]: t = page.extract_text() if t: text += t + "\n" except Exception as e: logger.warning(f"[Stage1] pypdf failed: {e}") # PyMuPDF sometimes recovers text pypdf misses if len(text.strip()) < MIN_TEXT_CHARS: try: doc = fitz.open(file_path) mu = "".join(doc[i].get_text() for i in range(min(3, len(doc)))) doc.close() if len(mu.strip()) > len(text.strip()): text = mu except Exception as e: logger.warning(f"[Stage1] PyMuPDF text failed: {e}") if len(text.strip()) >= MIN_TEXT_CHARS: logger.info(f"[Stage1] Text PDF ({len(text.strip())} chars) → {MODEL_TEXT}") content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text:\n{text.strip()}"}] return _call_openrouter(api_key, MODEL_TEXT, content, original_text=text.strip()) # Stage 2 & 3 need rendered image rendered = _render_pdf_page(file_path) if rendered is None: return None # Stage 2: Tesseract tess_text = _tesseract_text(rendered) word_count = len(tess_text.split()) if word_count >= MIN_TESS_WORDS: logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free)") content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}] result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text) if result is not None: return result logger.warning("[Stage2] Text model failed — falling through to Stage 3") else: logger.info(f"[Stage2] Tesseract only {word_count} words (threshold {MIN_TESS_WORDS}) → Stage 3") # Stage 3: vision model logger.info(f"[Stage3] Vision model: {MODEL_VISION}") content = [ {"type": "text", "text": user_prompt}, {"type": "image_url", "image_url": {"url": image_to_base64(rendered)}}, ] return _call_openrouter(api_key, MODEL_VISION, content) # ── Image ───────────────────────────────────────────────────────────── elif is_image: img = Image.open(file_path) tess_text = _tesseract_text(img) word_count = len(tess_text.split()) if word_count >= MIN_TESS_WORDS: logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free)") content = [{"type": "text", "text": f"{user_prompt}\n\nDocument text (OCR):\n{tess_text}"}] result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=tess_text) if result is not None: return result logger.warning("[Stage2-img] Text model failed — Stage 3") else: logger.info(f"[Stage2-img] Tesseract only {word_count} words → Stage 3") logger.info(f"[Stage3-img] Vision model: {MODEL_VISION}") content = [ {"type": "text", "text": user_prompt}, {"type": "image_url", "image_url": {"url": image_to_base64(img)}}, ] return _call_openrouter(api_key, MODEL_VISION, content) except Exception as e: logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}") return None