""" Document Verification using LlamaParse OCR. Extracts structured text from PDFs/images of citizen documents (Aadhaar, Ration Card, Income Certificate, etc.) and verifies extracted data against the citizen profile. """ import os from typing import Dict, Any, Optional, List from src.utils.logger import setup_logger logger = setup_logger("DocumentVerifier") # ── LlamaParse Integration ── try: from llama_parse import LlamaParse LLAMAPARSE_AVAILABLE = True except ImportError: LLAMAPARSE_AVAILABLE = False logger.warning("llama_parse not installed. Run: pip install llama-parse") class DocumentVerifier: """ Parses citizen documents via LlamaParse and cross-references extracted fields against the CitizenProfile. """ def __init__(self): self.api_key = os.getenv("LLAMA_CLOUD_API_KEY") if not self.api_key: logger.warning("LLAMA_CLOUD_API_KEY not set. Document verification will be unavailable.") self.parser = None if LLAMAPARSE_AVAILABLE and self.api_key: self.parser = LlamaParse( api_key=self.api_key, result_type="markdown", verbose=False, language="en", ) @property def is_available(self) -> bool: return self.parser is not None def parse_document(self, file_path: str) -> Dict[str, Any]: """ Parse a document (PDF/image) and return structured text. Returns: { "success": bool, "raw_text": str, # Full extracted markdown "extracted_fields": dict, # Parsed key-value pairs "document_type": str, # Detected document type "confidence": float # Parse confidence } """ if not self.is_available: return { "success": False, "error": "LlamaParse not configured. Set LLAMA_CLOUD_API_KEY in .env", "raw_text": "", "extracted_fields": {}, "document_type": "unknown", "confidence": 0.0 } if not os.path.exists(file_path): return { "success": False, "error": f"File not found: {file_path}", "raw_text": "", "extracted_fields": {}, "document_type": "unknown", "confidence": 0.0 } try: logger.info(f"Parsing document: {file_path}") documents = self.parser.load_data(file_path) if not documents: return { "success": False, "error": "No text extracted from document", "raw_text": "", "extracted_fields": {}, "document_type": "unknown", "confidence": 0.0 } raw_text = "\n\n".join([doc.text for doc in documents]) doc_type = self._detect_document_type(raw_text) fields = self._extract_fields(raw_text, doc_type) return { "success": True, "raw_text": raw_text, "extracted_fields": fields, "document_type": doc_type, "confidence": 0.85 } except Exception as e: logger.error(f"Document parsing failed: {e}") return { "success": False, "error": str(e), "raw_text": "", "extracted_fields": {}, "document_type": "unknown", "confidence": 0.0 } def _detect_document_type(self, text: str) -> str: """Detect document type from extracted text.""" text_lower = text.lower() if "aadhaar" in text_lower or "uidai" in text_lower or "unique identification" in text_lower: return "aadhaar_card" elif "ration card" in text_lower or "public distribution" in text_lower: return "ration_card" elif "income certificate" in text_lower or "annual income" in text_lower: return "income_certificate" elif "caste certificate" in text_lower or "community certificate" in text_lower: return "caste_certificate" elif "voter" in text_lower or "election commission" in text_lower: return "voter_id" elif "pan" in text_lower and "income tax" in text_lower: return "pan_card" elif "land" in text_lower and ("patta" in text_lower or "khata" in text_lower or "ownership" in text_lower): return "land_document" elif "bank" in text_lower and ("passbook" in text_lower or "account" in text_lower or "statement" in text_lower): return "bank_document" else: return "other" def _extract_fields(self, text: str, doc_type: str) -> Dict[str, Any]: """Extract key fields based on document type.""" import re fields = {} # Common patterns name_match = re.search(r'(?:name|naam)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE) if name_match: fields["name"] = name_match.group(1).strip() dob_match = re.search(r'(?:date of birth|dob|d\.o\.b)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE) if dob_match: fields["date_of_birth"] = dob_match.group(1).strip() address_match = re.search(r'(?:address|pata)\s*[:\-]\s*(.+?)(?:\n\n|$)', text, re.IGNORECASE | re.DOTALL) if address_match: fields["address"] = address_match.group(1).strip()[:200] # Document-specific extraction if doc_type == "aadhaar_card": aadhaar_match = re.search(r'\b(\d{4}\s?\d{4}\s?\d{4})\b', text) if aadhaar_match: fields["aadhaar_number"] = aadhaar_match.group(1).replace(" ", "") gender_match = re.search(r'(?:gender|sex)\s*[:\-]\s*(male|female|other|transgender)', text, re.IGNORECASE) if gender_match: fields["gender"] = gender_match.group(1).strip() elif doc_type == "income_certificate": income_match = re.search(r'(?:annual income|yearly income|income)\s*[:\-]?\s*(?:Rs\.?|INR)?\s*([\d,]+)', text, re.IGNORECASE) if income_match: fields["annual_income"] = float(income_match.group(1).replace(",", "")) elif doc_type == "caste_certificate": caste_match = re.search(r'(?:caste|category|community)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE) if caste_match: fields["category"] = caste_match.group(1).strip() elif doc_type == "ration_card": card_type_match = re.search(r'(?:card type|category)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE) if card_type_match: fields["ration_card_type"] = card_type_match.group(1).strip() members_match = re.search(r'(?:members|family size|total members)\s*[:\-]\s*(\d+)', text, re.IGNORECASE) if members_match: fields["family_members"] = int(members_match.group(1)) elif doc_type == "land_document": area_match = re.search(r'(?:area|extent)\s*[:\-]\s*(.+?)(?:\n|$)', text, re.IGNORECASE) if area_match: fields["land_area"] = area_match.group(1).strip() return fields def verify_against_profile(self, extracted_fields: Dict[str, Any], profile_data: Dict[str, Any]) -> Dict[str, Any]: """ Cross-reference extracted document fields against the citizen profile. Returns: { "matches": [...], # Fields that match "mismatches": [...], # Fields that conflict "new_info": [...], # New info not in profile "verification_score": float } """ matches = [] mismatches = [] new_info = [] # Income verification if "annual_income" in extracted_fields and profile_data.get("income"): doc_income = extracted_fields["annual_income"] profile_income = profile_data.get("income") try: if isinstance(profile_income, (int, float)): diff = abs(float(doc_income) - float(profile_income)) if diff < 10000: matches.append(f"Income matches: Document says Rs.{doc_income:,.0f}, profile says Rs.{profile_income:,.0f}") else: mismatches.append(f"INCOME MISMATCH: Document says Rs.{doc_income:,.0f}, but profile says Rs.{profile_income:,.0f}") except (ValueError, TypeError): new_info.append(f"Document income: Rs.{doc_income}") # Category verification if "category" in extracted_fields and profile_data.get("category"): doc_cat = extracted_fields["category"].upper().strip() profile_cat = str(profile_data.get("category", "")).upper().strip() if doc_cat == profile_cat or doc_cat in profile_cat or profile_cat in doc_cat: matches.append(f"Category matches: {doc_cat}") else: mismatches.append(f"CATEGORY MISMATCH: Document says '{doc_cat}', profile says '{profile_cat}'") # Family size verification if "family_members" in extracted_fields and profile_data.get("family_size"): doc_size = extracted_fields["family_members"] profile_size = profile_data.get("family_size") try: if int(doc_size) == int(profile_size): matches.append(f"Family size matches: {doc_size} members") else: mismatches.append(f"FAMILY SIZE MISMATCH: Document says {doc_size}, profile says {profile_size}") except (ValueError, TypeError): pass # New info from document for key, value in extracted_fields.items(): if key not in ["annual_income", "category", "family_members"]: if key not in profile_data or not profile_data.get(key): new_info.append(f"New from document: {key} = {value}") total_checks = len(matches) + len(mismatches) verification_score = len(matches) / total_checks if total_checks > 0 else 0.5 return { "matches": matches, "mismatches": mismatches, "new_info": new_info, "verification_score": verification_score, "total_checks": total_checks } # Module-level singleton document_verifier = DocumentVerifier()