File size: 10,833 Bytes
a1bdec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""
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()