chore: apply deployment fixes, timezone fixes, and cleanup unused dependencies
This commit is contained in:
+150
-45
@@ -18,10 +18,11 @@ 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
|
||||
# Models — configurable via .env, hardcoded values are defaults
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
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
|
||||
MODEL_TEXT = os.getenv("OCR_TEXT_MODEL", "meta-llama/llama-3.3-70b-instruct")
|
||||
MODEL_VISION = os.getenv("OCR_VISION_MODEL", "qwen/qwen2.5-vl-72b-instruct")
|
||||
MODEL_FALLBACK = os.getenv("OCR_FALLBACK_MODEL", "google/gemma-3-27b-it")
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Prompts
|
||||
@@ -42,23 +43,51 @@ BLANK_FORM_PROMPT = (
|
||||
"Return ONLY valid JSON, no markdown."
|
||||
)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Confidence tier definitions (Item 1)
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
_CONFIDENCE_TIERS = {
|
||||
1: {
|
||||
"stage": 1,
|
||||
"tier": "high",
|
||||
"label": "Native PDF text",
|
||||
"description": "Extracted directly from the PDF text layer — highly reliable.",
|
||||
"color": "green",
|
||||
},
|
||||
2: {
|
||||
"stage": 2,
|
||||
"tier": "medium",
|
||||
"label": "OCR (Tesseract)",
|
||||
"description": "Read from a scanned/image page via local OCR — review key numbers.",
|
||||
"color": "yellow",
|
||||
},
|
||||
3: {
|
||||
"stage": 3,
|
||||
"tier": "low",
|
||||
"label": "Vision model",
|
||||
"description": "Read from image by AI vision model — verify carefully.",
|
||||
"color": "orange",
|
||||
},
|
||||
}
|
||||
|
||||
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."
|
||||
)
|
||||
def _add_confidence(result: dict | None, stage: int, word_count: int = 0) -> dict | None:
|
||||
"""
|
||||
Attach a _meta block to an extraction result indicating which pipeline
|
||||
stage produced it and how reliable the output is likely to be.
|
||||
Returns None unchanged so callers can still check `if result is None`.
|
||||
"""
|
||||
if result is None:
|
||||
return None
|
||||
meta = dict(_CONFIDENCE_TIERS.get(stage, {"stage": stage, "tier": "unknown",
|
||||
"label": "Unknown", "color": "gray"}))
|
||||
if stage == 2 and word_count:
|
||||
meta["label"] = f"OCR ({word_count} words)"
|
||||
meta["description"] = (
|
||||
f"Tesseract OCR found {word_count} words. "
|
||||
+ ("Reasonable confidence." if word_count >= 60 else "Low word count — check key fields manually.")
|
||||
)
|
||||
result["_meta"] = meta
|
||||
return result
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -119,11 +148,14 @@ def _tesseract_text(pil_image: Image.Image) -> str:
|
||||
break
|
||||
|
||||
config = "--psm 6 --oem 3"
|
||||
# Tesseract language pack — configurable via TESSERACT_LANG env var
|
||||
# Default: eng+hin for bilingual Indian documents
|
||||
tess_lang = os.getenv("TESSERACT_LANG", "eng+hin")
|
||||
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")
|
||||
text = pytesseract.image_to_string(pil_image, lang=tess_lang, config=config).strip()
|
||||
logger.debug(f"[Tesseract] {tess_lang} produced {len(text.split())} words")
|
||||
except Exception:
|
||||
logger.debug("[Tesseract] eng+hin unavailable, using eng only")
|
||||
logger.debug(f"[Tesseract] {tess_lang} unavailable, using eng only")
|
||||
text = pytesseract.image_to_string(pil_image, lang="eng", config=config).strip()
|
||||
|
||||
return text
|
||||
@@ -144,10 +176,16 @@ def _call_openrouter(
|
||||
) -> 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.
|
||||
|
||||
Fallback chain (Item 4):
|
||||
1. Try requested model.
|
||||
2. If that fails AND it isn't already the fallback model, retry with MODEL_FALLBACK.
|
||||
|
||||
Blank template handling:
|
||||
If the model returns {} (unfilled form), retries with a metadata prompt
|
||||
so the admin always sees form_type / purpose / tax_year instead of nothing.
|
||||
"""
|
||||
def _post(content):
|
||||
def _post(m: str, content: list) -> dict | None:
|
||||
try:
|
||||
response = requests.post(
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
@@ -156,7 +194,7 @@ def _call_openrouter(
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
json={
|
||||
"model": model,
|
||||
"model": m,
|
||||
"messages": [
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{"role": "user", "content": content},
|
||||
@@ -174,19 +212,25 @@ def _call_openrouter(
|
||||
raw = raw[:-3]
|
||||
return json.loads(raw.strip())
|
||||
except Exception as e:
|
||||
logger.error(f"[OpenRouter] {model} call failed: {e}")
|
||||
logger.error(f"[OpenRouter] {m} call failed: {e}")
|
||||
return None
|
||||
|
||||
result = _post(user_content)
|
||||
# Primary attempt
|
||||
result = _post(model, user_content)
|
||||
|
||||
# If model returned {} (blank template), retry with metadata-only prompt
|
||||
# Fallback to secondary model if primary failed (Item 4)
|
||||
if result is None and model != MODEL_FALLBACK:
|
||||
logger.warning(f"[AI] {model} failed — retrying with fallback {MODEL_FALLBACK}")
|
||||
result = _post(MODEL_FALLBACK, user_content)
|
||||
|
||||
# Blank template fallback — retry with metadata prompt if result is {}
|
||||
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 {}
|
||||
result = _post(model, fallback_content) or {}
|
||||
|
||||
return result
|
||||
|
||||
@@ -195,21 +239,50 @@ def _call_openrouter(
|
||||
# Main extraction entry point
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
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."
|
||||
)
|
||||
|
||||
|
||||
def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
"""
|
||||
3-stage extraction pipeline:
|
||||
3-stage extraction pipeline with confidence scoring.
|
||||
|
||||
Stage 1 — Native text (FREE)
|
||||
pypdf + PyMuPDF pull embedded text from the PDF.
|
||||
>= MIN_TEXT_CHARS → llama-3.3-70b (free tier)
|
||||
pypdf + PyMuPDF pull embedded text from PDF.
|
||||
>= MIN_TEXT_CHARS → MODEL_TEXT.
|
||||
If MODEL_TEXT fails, falls through to Stage 2 (Item 2 fix — was silent None before).
|
||||
|
||||
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)
|
||||
>= MIN_TESS_WORDS → MODEL_TEXT.
|
||||
If MODEL_TEXT fails, falls through to Stage 3.
|
||||
|
||||
Stage 3 — Qwen2.5-VL-72B vision (paid, minimal cost)
|
||||
Sends rendered page image to Qwen via OpenRouter.
|
||||
Stage 3 — Vision model (paid, minimal cost)
|
||||
Sends rendered page image to MODEL_VISION via OpenRouter.
|
||||
|
||||
Confidence scoring (Item 1):
|
||||
Every successful result gets a _meta block:
|
||||
{"stage": 1|2|3, "tier": "high"|"medium"|"low",
|
||||
"label": "...", "description": "...", "color": "..."}
|
||||
|
||||
Model fallback (Item 4):
|
||||
Each _call_openrouter call tries MODEL_TEXT/MODEL_VISION first,
|
||||
then MODEL_FALLBACK if the primary fails.
|
||||
|
||||
Blank template fallback:
|
||||
If any stage returns {}, a second call extracts
|
||||
@@ -227,7 +300,12 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
logger.info(f"[AI] Unsupported file type, skipping: {file_path}")
|
||||
return None
|
||||
|
||||
user_prompt = _build_user_prompt(doc_type)
|
||||
# Item 5: For other_* uploads, detect actual doc type from text content
|
||||
# Required-slot uploads already carry the real template name — skip classifier for those
|
||||
effective_doc_type = doc_type
|
||||
# Classifier runs after text is available (done inline below per stage)
|
||||
|
||||
user_prompt = _build_user_prompt(effective_doc_type)
|
||||
|
||||
try:
|
||||
# ── PDF ───────────────────────────────────────────────────────────────
|
||||
@@ -256,9 +334,20 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
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}")
|
||||
# Item 5: classify other_* using actual extracted text
|
||||
if doc_type.startswith("other_"):
|
||||
from app.utils.doc_classifier import get_doc_type_for_prompt
|
||||
effective_doc_type = get_doc_type_for_prompt(
|
||||
doc_type, text.strip(), os.path.basename(file_path)
|
||||
)
|
||||
user_prompt = _build_user_prompt(effective_doc_type)
|
||||
logger.info(f"[Stage1] Text PDF ({len(text.strip())} chars) → {MODEL_TEXT} [{effective_doc_type}]")
|
||||
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())
|
||||
result = _call_openrouter(api_key, MODEL_TEXT, content, original_text=text.strip())
|
||||
if result is not None:
|
||||
return _add_confidence(result, stage=1) # ← Item 1: confidence
|
||||
# Item 2 fix: Stage 1 failure now falls through to Stage 2/3
|
||||
logger.warning("[Stage1] Text model failed — falling through to Stage 2")
|
||||
|
||||
# Stage 2 & 3 need rendered image
|
||||
rendered = _render_pdf_page(file_path)
|
||||
@@ -270,11 +359,18 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
word_count = len(tess_text.split())
|
||||
|
||||
if word_count >= MIN_TESS_WORDS:
|
||||
logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free)")
|
||||
# Item 5: classify other_* using Tesseract text if Stage 1 text was too short
|
||||
if doc_type.startswith("other_"):
|
||||
from app.utils.doc_classifier import get_doc_type_for_prompt
|
||||
effective_doc_type = get_doc_type_for_prompt(
|
||||
doc_type, tess_text, os.path.basename(file_path)
|
||||
)
|
||||
user_prompt = _build_user_prompt(effective_doc_type)
|
||||
logger.info(f"[Stage2] Tesseract {word_count} words → {MODEL_TEXT} (free) [{effective_doc_type}]")
|
||||
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
|
||||
return _add_confidence(result, stage=2, word_count=word_count) # ← Item 1
|
||||
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")
|
||||
@@ -285,7 +381,8 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
{"type": "text", "text": user_prompt},
|
||||
{"type": "image_url", "image_url": {"url": image_to_base64(rendered)}},
|
||||
]
|
||||
return _call_openrouter(api_key, MODEL_VISION, content)
|
||||
result = _call_openrouter(api_key, MODEL_VISION, content)
|
||||
return _add_confidence(result, stage=3) # ← Item 1 (None stays None)
|
||||
|
||||
# ── Image ─────────────────────────────────────────────────────────────
|
||||
elif is_image:
|
||||
@@ -295,11 +392,18 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
word_count = len(tess_text.split())
|
||||
|
||||
if word_count >= MIN_TESS_WORDS:
|
||||
logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free)")
|
||||
# Item 5: classify other_* from Tesseract text on image files
|
||||
if doc_type.startswith("other_"):
|
||||
from app.utils.doc_classifier import get_doc_type_for_prompt
|
||||
effective_doc_type = get_doc_type_for_prompt(
|
||||
doc_type, tess_text, os.path.basename(file_path)
|
||||
)
|
||||
user_prompt = _build_user_prompt(effective_doc_type)
|
||||
logger.info(f"[Stage2-img] Tesseract {word_count} words → {MODEL_TEXT} (free) [{effective_doc_type}]")
|
||||
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
|
||||
return _add_confidence(result, stage=2, word_count=word_count) # ← Item 1
|
||||
logger.warning("[Stage2-img] Text model failed — Stage 3")
|
||||
else:
|
||||
logger.info(f"[Stage2-img] Tesseract only {word_count} words → Stage 3")
|
||||
@@ -309,7 +413,8 @@ def extract_document_data(file_path: str, doc_type: str) -> dict | None:
|
||||
{"type": "text", "text": user_prompt},
|
||||
{"type": "image_url", "image_url": {"url": image_to_base64(img)}},
|
||||
]
|
||||
return _call_openrouter(api_key, MODEL_VISION, content)
|
||||
result = _call_openrouter(api_key, MODEL_VISION, content)
|
||||
return _add_confidence(result, stage=3) # ← Item 1
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[AI] Extraction pipeline failed for {file_path}: {e}")
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
Document type classifier for the "other_*" catch-all upload bucket.
|
||||
|
||||
When a user uploads via the "Additional Documents" slot, doc_type is set to
|
||||
`other_<timestamp>_<index>` — a meaningless slug. This module detects the
|
||||
actual document type from OCR text + filename so the extraction prompt
|
||||
becomes type-specific rather than generic.
|
||||
|
||||
Only used for `other_*` uploads. Required-slot uploads already carry the
|
||||
real template name (e.g. "Individual Tax Organizer 2025") from the DB.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import logging
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DocCategory(str, Enum):
|
||||
PAN_CARD = "PAN Card"
|
||||
AADHAAR = "Aadhaar Card"
|
||||
W2 = "W-2 Wage Statement"
|
||||
FORM_1099 = "1099 Income Form"
|
||||
ENGAGEMENT_LETTER = "Engagement Letter"
|
||||
TAX_ORGANIZER = "Tax Organizer"
|
||||
INVOICE = "Invoice / Bill"
|
||||
BANK_STATEMENT = "Bank Statement"
|
||||
PASSPORT = "Passport"
|
||||
DRIVING_LICENSE = "Driving License"
|
||||
GENERIC = "Other Document"
|
||||
|
||||
|
||||
# Priority-ordered keyword patterns — first match wins
|
||||
_PATTERNS: list[tuple[re.Pattern, DocCategory]] = [
|
||||
# Government IDs
|
||||
(re.compile(r'\bPERMANENT\s+ACCOUNT\s+NUMBER\b|\bINCOME\s+TAX\s+DEPT\b', re.I), DocCategory.PAN_CARD),
|
||||
(re.compile(r'\bAADHAAR\b|\bUIDPAI\b|\bUIDAI\b|\bENROLMENT\s+NO\b', re.I), DocCategory.AADHAAR),
|
||||
(re.compile(r'\bPASSPORT\b|\bREPUBLIC\s+OF\b.*\bPASSPORT\b', re.I), DocCategory.PASSPORT),
|
||||
(re.compile(r'\bDRIVING\s+(LICENCE|LICENSE)\b|\bDL\s+NO\b|\bMOTOR\s+VEHICLE\b', re.I), DocCategory.DRIVING_LICENSE),
|
||||
# US Tax forms
|
||||
(re.compile(r'\bW-?2\b.*\bWAGES\b|\bWAGES.*TIPS.*OTHER\b|\bFEDERAL\s+INCOME\s+TAX\s+WITHHELD\b', re.I), DocCategory.W2),
|
||||
(re.compile(r'\b1099-?[A-Z]{0,4}\b|\bNONEMPLOYEE\s+COMPENSATION\b|\bMISCELLANEOUS\s+INCOME\b', re.I), DocCategory.FORM_1099),
|
||||
# Accounting documents
|
||||
(re.compile(r'\bENGAGEMENT\s+LETTER\b|\bTAX\s+RETURN\s+PREPARATION\s+SERVICES\b', re.I), DocCategory.ENGAGEMENT_LETTER),
|
||||
(re.compile(r'\bTAX\s+ORGANIZER\b|\bLLC\s+TAX\b|\bS[-\s]?CORP\b|\bPARTNERSHIP\s+TAX\b', re.I), DocCategory.TAX_ORGANIZER),
|
||||
(re.compile(r'\bINVOICE\b|\bINV\s*(NO|#|:)\b|\bGST\s+INVOICE\b|\bTAX\s+INVOICE\b', re.I), DocCategory.INVOICE),
|
||||
(re.compile(r'\bACCOUNT\s+STATEMENT\b|\bSTATEMENT\s+OF\s+ACCOUNT\b|\bOPENING\s+BALANCE\b|\bCLOSING\s+BALANCE\b', re.I), DocCategory.BANK_STATEMENT),
|
||||
]
|
||||
|
||||
|
||||
def classify_other_doc(
|
||||
ocr_text: str,
|
||||
filename: str = "",
|
||||
) -> DocCategory:
|
||||
"""
|
||||
Detect the actual document type from OCR text and filename.
|
||||
Returns DocCategory.GENERIC if nothing matches.
|
||||
|
||||
Args:
|
||||
ocr_text: Raw text extracted from the document (any amount).
|
||||
filename: Original upload filename — used as a secondary hint.
|
||||
"""
|
||||
corpus = f"{filename} {ocr_text}"
|
||||
|
||||
for pattern, category in _PATTERNS:
|
||||
if pattern.search(corpus):
|
||||
logger.info(f"[DocClassifier] Detected '{category.value}' from other_* upload")
|
||||
return category
|
||||
|
||||
logger.info("[DocClassifier] No match — defaulting to GENERIC")
|
||||
return DocCategory.GENERIC
|
||||
|
||||
|
||||
def get_doc_type_for_prompt(original_doc_type: str, ocr_text: str, filename: str = "") -> str:
|
||||
"""
|
||||
Returns the best doc_type string to use in the extraction prompt.
|
||||
|
||||
For required-slot uploads (doc_type = real template name from DB),
|
||||
returns as-is. For other_* uploads, runs the classifier and returns
|
||||
the detected category's human-readable label.
|
||||
"""
|
||||
if not original_doc_type.startswith("other_"):
|
||||
return original_doc_type
|
||||
|
||||
category = classify_other_doc(ocr_text=ocr_text, filename=filename)
|
||||
return category.value
|
||||
@@ -0,0 +1,236 @@
|
||||
"""
|
||||
Document Intelligence Utilities.
|
||||
|
||||
Provides:
|
||||
1. field_validator — regex-based type validation for extracted fields
|
||||
2. reconcile_user_docs — cross-document field comparison (name/ID mismatches)
|
||||
3. build_daily_digest — AI-generated plain-English summary of today's activity
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import os
|
||||
import logging
|
||||
import requests
|
||||
from datetime import datetime, date
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 1. Field type validation
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Field name patterns → (regex that the VALUE must match, human label for error)
|
||||
_FIELD_VALIDATORS: list[tuple[re.Pattern, re.Pattern, str]] = [
|
||||
# key pattern value pattern error label
|
||||
(re.compile(r'pan[_\s]?(number|no)?', re.I), re.compile(r'^[A-Z]{5}\d{4}[A-Z]$'), "PAN (AAAAA9999A)"),
|
||||
(re.compile(r'aadhaar[_\s]?(no|number)?', re.I), re.compile(r'^\d{4}\s?\d{4}\s?\d{4}$'), "Aadhaar (12 digits)"),
|
||||
(re.compile(r'(ein|employer[_\s]?id)', re.I), re.compile(r'^\d{2}-\d{7}$'), "EIN (XX-XXXXXXX)"),
|
||||
(re.compile(r'ssn|social[_\s]?security', re.I), re.compile(r'^\d{3}-\d{2}-\d{4}$'), "SSN (XXX-XX-XXXX)"),
|
||||
(re.compile(r'date[_\s]?of[_\s]?birth|dob', re.I),
|
||||
re.compile(r'^\d{2}/\d{2}/\d{4}$'), "DOB (DD/MM/YYYY)"),
|
||||
(re.compile(r'(inv|invoice)[_\s]?(dt|date)', re.I),
|
||||
re.compile(r'^\d{2}/\d{2}/\d{4}$'), "Date (DD/MM/YYYY)"),
|
||||
(re.compile(r'tax[_\s]?year', re.I), re.compile(r'^\d{4}$'), "Tax Year (4 digits)"),
|
||||
(re.compile(r'gst[_\s]?(no|number)?', re.I),
|
||||
re.compile(r'^\d{2}[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$'), "GSTIN (15-char format)"),
|
||||
]
|
||||
|
||||
|
||||
def validate_extracted_fields(extracted_data: dict) -> list[dict]:
|
||||
"""
|
||||
Run format validation against extracted fields.
|
||||
Returns a list of validation warnings (empty list = all clear).
|
||||
|
||||
Each warning: {"field": str, "value": str, "expected": str, "severity": "warning"|"error"}
|
||||
"""
|
||||
if not extracted_data:
|
||||
return []
|
||||
|
||||
warnings = []
|
||||
for key, value in extracted_data.items():
|
||||
if key == "_meta" or value is None or not isinstance(value, str):
|
||||
continue
|
||||
val = value.strip()
|
||||
for key_pattern, val_pattern, label in _FIELD_VALIDATORS:
|
||||
if key_pattern.search(key):
|
||||
if not val_pattern.match(val):
|
||||
warnings.append({
|
||||
"field": key,
|
||||
"value": val,
|
||||
"expected": label,
|
||||
"severity": "warning",
|
||||
})
|
||||
break # only one pattern per field
|
||||
|
||||
if warnings:
|
||||
logger.info(f"[Validation] {len(warnings)} field format warnings on extracted data")
|
||||
return warnings
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 2. Cross-document reconciliation
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Fields to compare across documents — (canonical_name, list of key aliases)
|
||||
_RECONCILE_FIELDS = [
|
||||
("name", ["name", "full name", "taxpayer name", "account name"]),
|
||||
("pan", ["pan number", "pan", "pan_number", "permanent account number"]),
|
||||
("dob", ["date of birth", "dob", "date_of_birth", "birth date"]),
|
||||
("ein", ["ein", "employer id", "employer identification number"]),
|
||||
("tax_year",["tax year", "tax_year", "taxyear", "year"]),
|
||||
]
|
||||
|
||||
|
||||
def _find_field(data: dict, aliases: list[str]) -> str | None:
|
||||
"""Case-insensitive lookup of a field by any of its aliases."""
|
||||
for key, val in data.items():
|
||||
if any(alias in key.lower() for alias in aliases):
|
||||
if val and isinstance(val, str):
|
||||
return val.strip().lower()
|
||||
return None
|
||||
|
||||
|
||||
def reconcile_user_documents(docs: list[dict]) -> list[dict]:
|
||||
"""
|
||||
Compare key fields across a user's extracted documents.
|
||||
Returns mismatches as a list of flags.
|
||||
|
||||
`docs` is a list of {"doc_type": str, "extracted_data": dict} dicts.
|
||||
|
||||
Each flag: {"field": str, "doc_a": str, "value_a": str,
|
||||
"doc_b": str, "value_b": str, "severity": "warning"}
|
||||
"""
|
||||
if len(docs) < 2:
|
||||
return []
|
||||
|
||||
# Only include docs that have real extracted data (not blank templates)
|
||||
real_docs = [
|
||||
d for d in docs
|
||||
if d.get("extracted_data") and
|
||||
d["extracted_data"].get("status") != "blank_template" and
|
||||
isinstance(d["extracted_data"], dict)
|
||||
]
|
||||
|
||||
if len(real_docs) < 2:
|
||||
return []
|
||||
|
||||
flags = []
|
||||
for canonical, aliases in _RECONCILE_FIELDS:
|
||||
# Collect (doc_label, value) for all docs that have this field
|
||||
present = []
|
||||
for d in real_docs:
|
||||
val = _find_field(d["extracted_data"], aliases)
|
||||
if val:
|
||||
present.append((d.get("doc_type", "Unknown"), val))
|
||||
|
||||
if len(present) < 2:
|
||||
continue
|
||||
|
||||
# Compare all pairs
|
||||
for i in range(len(present)):
|
||||
for j in range(i + 1, len(present)):
|
||||
label_a, val_a = present[i]
|
||||
label_b, val_b = present[j]
|
||||
# Normalize: strip spaces/hyphens for ID-style fields
|
||||
norm_a = re.sub(r'[\s\-]', '', val_a)
|
||||
norm_b = re.sub(r'[\s\-]', '', val_b)
|
||||
if norm_a != norm_b:
|
||||
flags.append({
|
||||
"field": canonical,
|
||||
"doc_a": label_a,
|
||||
"value_a": val_a,
|
||||
"doc_b": label_b,
|
||||
"value_b": val_b,
|
||||
"severity": "warning",
|
||||
"message": f"'{canonical}' mismatch: '{val_a}' in {label_a} vs '{val_b}' in {label_b}",
|
||||
})
|
||||
|
||||
if flags:
|
||||
logger.info(f"[Reconciliation] {len(flags)} cross-document mismatches found")
|
||||
return flags
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# 3. Admin daily digest
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def build_daily_digest(db_stats: dict) -> str:
|
||||
"""
|
||||
Generate a plain-English daily digest using the LLM.
|
||||
`db_stats` should contain the same structure as get_admin_status() returns.
|
||||
Returns a formatted HTML string for display in the admin dashboard.
|
||||
"""
|
||||
api_key = os.getenv("OPENROUTER_API_KEY")
|
||||
if not api_key:
|
||||
return _fallback_digest(db_stats)
|
||||
|
||||
today = date.today().strftime("%B %d, %Y")
|
||||
stats_text = (
|
||||
f"Date: {today}\n"
|
||||
f"New users registered today: {db_stats.get('new_users_today', 0)}\n"
|
||||
f"Total users: {db_stats.get('total_users', 0)}\n"
|
||||
f"Pending personal docs: {db_stats.get('pending_personal', 0)}\n"
|
||||
f"Pending business docs: {db_stats.get('pending_business', 0)}\n"
|
||||
f"Total pending docs: {db_stats.get('total_pending', 0)}\n"
|
||||
)
|
||||
|
||||
recent = db_stats.get("recent_uploads", [])
|
||||
if recent:
|
||||
stats_text += "\nRecent uploads today:\n"
|
||||
for r in recent[:5]:
|
||||
stats_text += f"- {r['user_name']} uploaded {r['doc']} ({r['type']}) at {r['uploaded_at']}\n"
|
||||
|
||||
prompt = (
|
||||
"You are an accounting firm assistant. Write a brief, friendly, plain-English daily digest "
|
||||
"for the admin team based on today's activity data below. "
|
||||
"Keep it to 3-4 bullet points. Be specific about numbers. Use a professional but warm tone.\n\n"
|
||||
f"TODAY'S ACTIVITY DATA:\n{stats_text}\n\n"
|
||||
"Write the digest now. Use bullet points (•). No markdown headers."
|
||||
)
|
||||
|
||||
try:
|
||||
model = os.getenv("OCR_TEXT_MODEL", "meta-llama/llama-3.3-70b-instruct")
|
||||
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": "user", "content": prompt}],
|
||||
"max_tokens": 300,
|
||||
},
|
||||
timeout=20,
|
||||
)
|
||||
response.raise_for_status()
|
||||
content = response.json()["choices"][0]["message"]["content"].strip()
|
||||
# Wrap bullets in styled HTML
|
||||
lines = content.split("\n")
|
||||
html_lines = []
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line.startswith("•") or line.startswith("-"):
|
||||
html_lines.append(f"<li>{line.lstrip('•-').strip()}</li>")
|
||||
elif line:
|
||||
html_lines.append(f"<p>{line}</p>")
|
||||
return f"<ul style='margin:0;padding-left:18px'>{''.join(html_lines)}</ul>"
|
||||
except Exception as e:
|
||||
logger.error(f"[DailyDigest] LLM call failed: {e}")
|
||||
return _fallback_digest(db_stats)
|
||||
|
||||
|
||||
def _fallback_digest(stats: dict) -> str:
|
||||
today = date.today().strftime("%B %d, %Y")
|
||||
total = stats.get("total_pending", 0)
|
||||
new_u = stats.get("new_users_today", 0)
|
||||
lines = [
|
||||
f"<li>Today is {today}.</li>",
|
||||
f"<li>{new_u} new user(s) registered today.</li>",
|
||||
f"<li>{total} document(s) currently awaiting review.</li>",
|
||||
]
|
||||
pp = stats.get("pending_personal", 0)
|
||||
pb = stats.get("pending_business", 0)
|
||||
if pp or pb:
|
||||
lines.append(f"<li>{pp} personal and {pb} business documents are pending.</li>")
|
||||
return f"<ul style='margin:0;padding-left:18px'>{''.join(lines)}</ul>"
|
||||
Reference in New Issue
Block a user