Spaces:
Sleeping
Sleeping
Update logiccode.py
Browse files- logiccode.py +574 -548
logiccode.py
CHANGED
|
@@ -1,549 +1,575 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
import
|
| 16 |
-
import
|
| 17 |
-
import
|
| 18 |
-
import
|
| 19 |
-
from
|
| 20 |
-
|
| 21 |
-
import
|
| 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 |
-
"passport
|
| 51 |
-
"
|
| 52 |
-
"
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"
|
| 57 |
-
"
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
"
|
| 62 |
-
"
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
"age nationality domicile", "
|
| 67 |
-
"
|
| 68 |
-
"residence
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
"ration card
|
| 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 |
-
for
|
| 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 |
-
if
|
| 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 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
print(f"
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
print("="*60
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
'
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
print(f"
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 549 |
main()
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
OCR Document Verification with Batch Processing & Required Document Checklist
|
| 4 |
+
Usage:
|
| 5 |
+
# Single file (backward compatible)
|
| 6 |
+
python ocrupdated2.py --file image.jpg --inputkeywords "keyword1 keyword2" --fuzzy --debug
|
| 7 |
+
# Multiple files with required document checklist
|
| 8 |
+
python ocrupdated2.py --file doc1.pdf doc2.jpg doc3.png --inputkeywords "Shaikh Anisa Rahat" --required PAN HSC AgeNationalityDomicile --fuzzy --debug
|
| 9 |
+
NOTE: Use spaces to separate required document types, NOT commas:
|
| 10 |
+
✅ --required PAN Aadhaar HSC
|
| 11 |
+
❌ --required PAN, Aadhaar, HSC
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import re
|
| 16 |
+
import os
|
| 17 |
+
import tempfile
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
from paddleocr import PaddleOCR
|
| 20 |
+
import difflib
|
| 21 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 22 |
+
import multiprocessing
|
| 23 |
+
|
| 24 |
+
# Optional PDF support
|
| 25 |
+
try:
|
| 26 |
+
import fitz # PyMuPDF
|
| 27 |
+
PDF_SUPPORT = True
|
| 28 |
+
except ImportError:
|
| 29 |
+
PDF_SUPPORT = False
|
| 30 |
+
print("Warning: PyMuPDF not installed. PDF support disabled. Install with: pip install PyMuPDF")
|
| 31 |
+
|
| 32 |
+
# Document keywords (unchanged)
|
| 33 |
+
DOC_KEYWORDS = {
|
| 34 |
+
"Aadhaar": [
|
| 35 |
+
"uidai", "aadhaar", "aadhar", "government of india", "भारत सरकार",
|
| 36 |
+
"आधार", "यूआईडीएआई", "प्रधानमंत्री", "जन्म तिथि", "पता", "लिंग",
|
| 37 |
+
"unique identification authority", "aadhaar number", "enrollment number"
|
| 38 |
+
],
|
| 39 |
+
"PAN": [
|
| 40 |
+
"permanent account number", "income tax", "incometaxindia", "pan",
|
| 41 |
+
"income tax department", "आयकर विभाग", "स्थायी खाता संख्या",
|
| 42 |
+
"taxpayer", "father's name", "पिता का नाम", "signature", "inc"
|
| 43 |
+
],
|
| 44 |
+
"Driving_License": [
|
| 45 |
+
"driving licence", "motor vehicles act", "rto", "mcwg", "lmv",
|
| 46 |
+
"transport department", "licence no", "valid till", "date of issue",
|
| 47 |
+
"ड्राइविंग लाइसेंस", "परिवहन विभाग", "challan", "regional transport office"
|
| 48 |
+
],
|
| 49 |
+
"Passport": [
|
| 50 |
+
"passport", "republic of india", "ministry of external affairs",
|
| 51 |
+
"passport number", "date of issue", "date of expiry", "surname",
|
| 52 |
+
"given names", "nationality indian", "पासपोर्ट", "गणराज्य", "विदेश मंत्रालय",
|
| 53 |
+
"consular", "visa"
|
| 54 |
+
],
|
| 55 |
+
"SSC": [
|
| 56 |
+
"secondary school certificate", "statement of marks", "ssc", "10th", "class x",
|
| 57 |
+
"board of secondary education", "maharashtra state board", "matriculation",
|
| 58 |
+
"roll number", "seat number", "subject code", "marks obtained", "grade", "pass"
|
| 59 |
+
],
|
| 60 |
+
"HSC": [
|
| 61 |
+
"higher secondary certificate", "statement of marks", "hsc", "12th", "class xii",
|
| 62 |
+
"board of higher secondary education", "maharashtra state board", "intermediate",
|
| 63 |
+
"stream", "science", "commerce", "arts", "marks obtained", "grade", "percentage"
|
| 64 |
+
],
|
| 65 |
+
"AgeNationalityDomicile": [
|
| 66 |
+
"certificate of age nationality and domicile", "domicile certificate",
|
| 67 |
+
"age nationality domicile", "tehsildar", "executive magistrate", "collector",
|
| 68 |
+
"certificate of residence", "domiciled in the state of", "citizen of india",
|
| 69 |
+
"residence proof", "maharashtra domicile", "satara", "karad", "taluka", "district"
|
| 70 |
+
],
|
| 71 |
+
"Ration_Card": [
|
| 72 |
+
"ration card", "food and civil supplies", "apl", "bpl", "aay", "antyodaya",
|
| 73 |
+
"ration card number", "family members", "head of family",
|
| 74 |
+
"राशन कार्ड", "खाद्य पुरवठा", "नागरी पुरवठा विभाग", "fps", "fair price shop"
|
| 75 |
+
],
|
| 76 |
+
"Cast_Certificate": [
|
| 77 |
+
"CASTE CERTIFICATE",
|
| 78 |
+
"FORM - 8",
|
| 79 |
+
"Rule No. 5(6)",
|
| 80 |
+
"De-Notified Tribe (Vimukt Jati)",
|
| 81 |
+
"Nomadic Tribe/Other Backward Class",
|
| 82 |
+
"Special Backward Category",
|
| 83 |
+
"recognised as",
|
| 84 |
+
"Government Resolution",
|
| 85 |
+
"Sub Divisional Officer",
|
| 86 |
+
"belonging to the State of Maharashtra"
|
| 87 |
+
],
|
| 88 |
+
"Income_Certificate": [
|
| 89 |
+
"१ वर्षासाठी उत्पन्नाचे प्रमाणपत्र",
|
| 90 |
+
"ऑफिस ऑफ नायब तहसीलदार",
|
| 91 |
+
"वार्षिक उत्पन्न",
|
| 92 |
+
"मिळालेले १ वर्षाचे उत्पन्न",
|
| 93 |
+
"कुटुंबातील सर्व सदस्यांचे",
|
| 94 |
+
"प्रमाणित करण्यात येते की",
|
| 95 |
+
"वैध राहील",
|
| 96 |
+
"Signature valid",
|
| 97 |
+
"Digitally Signed by"
|
| 98 |
+
],
|
| 99 |
+
"PCM_Score_Card": [
|
| 100 |
+
"MAH-MHT CET (PCM Group)",
|
| 101 |
+
"State Common Entrance Test Cell",
|
| 102 |
+
"Score Card",
|
| 103 |
+
"Physics",
|
| 104 |
+
"Chemistry",
|
| 105 |
+
"Mathematics",
|
| 106 |
+
"Total Percentile",
|
| 107 |
+
"Normalization document",
|
| 108 |
+
"Centralized Admission Process (CAP)",
|
| 109 |
+
"IP address of the Computer"
|
| 110 |
+
]
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
# Validate keyword uniqueness (unchanged)
|
| 114 |
+
_keyword_sets = {k: set(v) for k, v in DOC_KEYWORDS.items()}
|
| 115 |
+
for doc1 in DOC_KEYWORDS:
|
| 116 |
+
for doc2 in DOC_KEYWORDS:
|
| 117 |
+
if doc1 < doc2:
|
| 118 |
+
overlap = _keyword_sets[doc1].intersection(_keyword_sets[doc2])
|
| 119 |
+
if overlap:
|
| 120 |
+
print(f"⚠️ Warning: Overlap between {doc1} and {doc2}: {overlap}")
|
| 121 |
+
|
| 122 |
+
# NEW: Pre-compile regex patterns for performance
|
| 123 |
+
NOISE_PATTERN = re.compile(r'^[b-df-hj-np-tv-xz]{4,}$')
|
| 124 |
+
TOKEN_PATTERN = re.compile(r'[\u0900-\u097F]{2,}|\w{3,}')
|
| 125 |
+
STOPWORDS = {'the', 'and', 'of', 'in', 'to', 'for', 'is', 'on', 'by', 'with', 'at', 'from', 'a', 'an', 'this'}
|
| 126 |
+
|
| 127 |
+
def normalize_text(text):
|
| 128 |
+
"""Robust multilingual tokenization with noise filtering"""
|
| 129 |
+
text = text.lower()
|
| 130 |
+
# Extract Hindi Devanagari (2+ chars) OR English alphanumeric (3+ chars)
|
| 131 |
+
tokens = TOKEN_PATTERN.findall(text)
|
| 132 |
+
|
| 133 |
+
# Remove common English stopwords
|
| 134 |
+
tokens = [t for t in tokens if t not in STOPWORDS]
|
| 135 |
+
|
| 136 |
+
# Remove OCR noise (4+ consecutive consonants = garbage)
|
| 137 |
+
tokens = [t for t in tokens if not NOISE_PATTERN.match(t)]
|
| 138 |
+
|
| 139 |
+
return tokens
|
| 140 |
+
|
| 141 |
+
def pdf_to_images(pdf_path, max_pages=3):
|
| 142 |
+
"""Convert PDF pages to high-resolution temporary images"""
|
| 143 |
+
if not PDF_SUPPORT:
|
| 144 |
+
raise ValueError("PDF support not available. Install PyMuPDF")
|
| 145 |
+
|
| 146 |
+
doc = fitz.open(pdf_path)
|
| 147 |
+
total_pages = len(doc)
|
| 148 |
+
pages_to_process = min(total_pages, max_pages)
|
| 149 |
+
|
| 150 |
+
image_paths = []
|
| 151 |
+
temp_dir = tempfile.mkdtemp(prefix="ocr_pdf_")
|
| 152 |
+
|
| 153 |
+
for page_num in range(pages_to_process):
|
| 154 |
+
page = doc.load_page(page_num)
|
| 155 |
+
zoom = 2 # 2x resolution for better OCR
|
| 156 |
+
mat = fitz.Matrix(zoom, zoom)
|
| 157 |
+
pix = page.get_pixmap(matrix=mat)
|
| 158 |
+
|
| 159 |
+
img_path = os.path.join(temp_dir, f"page_{page_num + 1}.png")
|
| 160 |
+
pix.save(img_path)
|
| 161 |
+
image_paths.append(img_path)
|
| 162 |
+
|
| 163 |
+
doc.close()
|
| 164 |
+
return image_paths, total_pages, temp_dir
|
| 165 |
+
|
| 166 |
+
def process_page_ocr(img_path, page_num, ocr, debug):
|
| 167 |
+
"""Process a single page with OCR (for parallel execution)"""
|
| 168 |
+
if debug:
|
| 169 |
+
print(f"\n--- Processing PDF Page {page_num} ---")
|
| 170 |
+
result = ocr.predict(input=img_path)
|
| 171 |
+
texts = []
|
| 172 |
+
for res in result:
|
| 173 |
+
texts.extend(res['rec_texts'])
|
| 174 |
+
return texts
|
| 175 |
+
|
| 176 |
+
def get_ocr_text(file_path, ocr, max_pages=3, debug=False):
|
| 177 |
+
"""Process image or PDF with OCR, returning all extracted text lines"""
|
| 178 |
+
all_texts = []
|
| 179 |
+
temp_dir = None
|
| 180 |
+
|
| 181 |
+
try:
|
| 182 |
+
if file_path.lower().endswith('.pdf'):
|
| 183 |
+
if not PDF_SUPPORT:
|
| 184 |
+
print("Error: PDF file provided but PyMuPDF not installed")
|
| 185 |
+
return []
|
| 186 |
+
|
| 187 |
+
image_paths, total_pages, temp_dir = pdf_to_images(file_path, max_pages)
|
| 188 |
+
print(f"Processing PDF: {total_pages} pages total, processing first {len(image_paths)} pages...")
|
| 189 |
+
|
| 190 |
+
# NEW: Process pages in parallel with ThreadPoolExecutor
|
| 191 |
+
max_workers = min(len(image_paths), 4) # Max 4 parallel pages
|
| 192 |
+
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
| 193 |
+
# Submit all pages
|
| 194 |
+
future_to_page = {
|
| 195 |
+
executor.submit(process_page_ocr, img_path, i+1, ocr, debug): i
|
| 196 |
+
for i, img_path in enumerate(image_paths)
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
# Collect results in order
|
| 200 |
+
page_results = [None] * len(image_paths)
|
| 201 |
+
for future in future_to_page:
|
| 202 |
+
page_idx = future_to_page[future]
|
| 203 |
+
try:
|
| 204 |
+
page_results[page_idx] = future.result()
|
| 205 |
+
except Exception as e:
|
| 206 |
+
print(f"Error processing page {page_idx+1}: {e}")
|
| 207 |
+
page_results[page_idx] = []
|
| 208 |
+
|
| 209 |
+
# Combine results in correct order
|
| 210 |
+
for texts in page_results:
|
| 211 |
+
all_texts.extend(texts)
|
| 212 |
+
else:
|
| 213 |
+
result = ocr.predict(input=file_path)
|
| 214 |
+
for res in result:
|
| 215 |
+
all_texts.extend(res['rec_texts'])
|
| 216 |
+
|
| 217 |
+
finally:
|
| 218 |
+
if temp_dir and os.path.exists(temp_dir):
|
| 219 |
+
import shutil
|
| 220 |
+
shutil.rmtree(temp_dir)
|
| 221 |
+
|
| 222 |
+
return all_texts
|
| 223 |
+
|
| 224 |
+
def fuzzy_match(token, target_set, threshold=0.75):
|
| 225 |
+
"""
|
| 226 |
+
Multi-level matching for OCR errors:
|
| 227 |
+
1. Exact match
|
| 228 |
+
2. Levenshtein distance
|
| 229 |
+
3. Substring containment
|
| 230 |
+
4. Hindi character-level similarity
|
| 231 |
+
"""
|
| 232 |
+
if token in target_set:
|
| 233 |
+
return token
|
| 234 |
+
|
| 235 |
+
# Levenshtein distance match
|
| 236 |
+
matches = difflib.get_close_matches(token, target_set, n=1, cutoff=threshold)
|
| 237 |
+
if matches:
|
| 238 |
+
return matches[0]
|
| 239 |
+
|
| 240 |
+
# Substring match (handles concatenated words)
|
| 241 |
+
for ocr_token in target_set:
|
| 242 |
+
if token in ocr_token or ocr_token in token:
|
| 243 |
+
return ocr_token
|
| 244 |
+
|
| 245 |
+
# Hindi-specific fuzzy matching
|
| 246 |
+
if any('\u0900' <= c <= '\u097F' for c in token):
|
| 247 |
+
for ocr_token in target_set:
|
| 248 |
+
if len(ocr_token) > 3:
|
| 249 |
+
similarity = difflib.SequenceMatcher(None, token, ocr_token).ratio()
|
| 250 |
+
if similarity > threshold:
|
| 251 |
+
return ocr_token
|
| 252 |
+
|
| 253 |
+
return None
|
| 254 |
+
|
| 255 |
+
def calculate_doc_type(ocr_tokens, debug=False):
|
| 256 |
+
"""
|
| 257 |
+
Enhanced document classification with CORRECTED tie-breaking logic.
|
| 258 |
+
Only compares documents that are ACTUALLY TIED (within 5% score).
|
| 259 |
+
"""
|
| 260 |
+
ocr_set = set(ocr_tokens)
|
| 261 |
+
ocr_combined = " ".join(ocr_tokens)
|
| 262 |
+
scores = {}
|
| 263 |
+
|
| 264 |
+
# NEW: Pre-calculate keyword sets once
|
| 265 |
+
doc_keyword_sets = {}
|
| 266 |
+
for doc_type, keywords in DOC_KEYWORDS.items():
|
| 267 |
+
doc_keyword_sets[doc_type] = set(k.lower() for k in keywords)
|
| 268 |
+
|
| 269 |
+
for doc_type, kw_set in doc_keyword_sets.items():
|
| 270 |
+
# Primary: exact/fuzzy token matches (weighted 2 for exact, 1.5 for fuzzy)
|
| 271 |
+
primary_matches = 0
|
| 272 |
+
for kw in kw_set:
|
| 273 |
+
if kw in ocr_set:
|
| 274 |
+
primary_matches += 2
|
| 275 |
+
elif fuzzy_match(kw, ocr_set):
|
| 276 |
+
primary_matches += 1.5
|
| 277 |
+
|
| 278 |
+
# Secondary: multi-word phrase matches in combined text
|
| 279 |
+
phrase_matches = sum(1 for kw in kw_set if " " in kw and kw in ocr_combined)
|
| 280 |
+
|
| 281 |
+
# Tertiary: title keyword bonus
|
| 282 |
+
title_keywords = [kw for kw in kw_set if any(word in kw for word in ["certificate", "card", "licence", "passport"])]
|
| 283 |
+
title_match = sum(1 for kw in title_keywords if kw in ocr_combined)
|
| 284 |
+
|
| 285 |
+
# Calculate weighted score
|
| 286 |
+
max_possible = len(kw_set) * 2
|
| 287 |
+
weighted_score = ((primary_matches + phrase_matches + title_match) / max_possible) * 100
|
| 288 |
+
|
| 289 |
+
scores[doc_type] = weighted_score
|
| 290 |
+
|
| 291 |
+
if debug:
|
| 292 |
+
print(f" {doc_type:<25}: {weighted_score:>6.1f}% ({primary_matches:.1f} + {phrase_matches} + {title_match})")
|
| 293 |
+
|
| 294 |
+
# Sort by score descending
|
| 295 |
+
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
|
| 296 |
+
best_type, best_score = sorted_scores[0]
|
| 297 |
+
|
| 298 |
+
# Tie-breaking logic (unchanged)
|
| 299 |
+
if len(sorted_scores) > 1 and (sorted_scores[0][1] - sorted_scores[1][1]) < 5:
|
| 300 |
+
if debug:
|
| 301 |
+
print(f"\n⚠️ Tie detected between '{sorted_scores[0][0]}' and '{sorted_scores[1][0]}'!")
|
| 302 |
+
|
| 303 |
+
tied_docs = [(doc_type, score) for doc_type, score in sorted_scores
|
| 304 |
+
if (best_score - score) < 5]
|
| 305 |
+
|
| 306 |
+
if debug:
|
| 307 |
+
print(f"Tied documents: {[f'{doc}({score:.1f}%)' for doc, score in tied_docs]}")
|
| 308 |
+
|
| 309 |
+
unique_counts = {}
|
| 310 |
+
for doc_type, _ in tied_docs:
|
| 311 |
+
kw_set = doc_keyword_sets[doc_type]
|
| 312 |
+
|
| 313 |
+
other_tied_keywords = set()
|
| 314 |
+
for other_doc, _ in tied_docs:
|
| 315 |
+
if other_doc != doc_type:
|
| 316 |
+
other_tied_keywords.update(doc_keyword_sets[other_doc])
|
| 317 |
+
|
| 318 |
+
unique_keywords = kw_set - other_tied_keywords
|
| 319 |
+
unique_matches = sum(1 for kw in unique_keywords if fuzzy_match(kw, ocr_set))
|
| 320 |
+
unique_counts[doc_type] = unique_matches
|
| 321 |
+
|
| 322 |
+
if debug:
|
| 323 |
+
print(f" {doc_type:<25}: {unique_matches} unique matches ({len(unique_keywords)} available)")
|
| 324 |
+
|
| 325 |
+
if unique_counts and max(unique_counts.values()) > 0:
|
| 326 |
+
sorted_unique = sorted(unique_counts.items(), key=lambda x: x[1], reverse=True)
|
| 327 |
+
if len(sorted_unique) > 1 and sorted_unique[0][1] > sorted_unique[1][1]:
|
| 328 |
+
best_type = sorted_unique[0][0]
|
| 329 |
+
best_score = scores[best_type]
|
| 330 |
+
|
| 331 |
+
if debug:
|
| 332 |
+
print(f"✓ Tie broken: {best_type} wins with {unique_counts[best_type]} unique matches")
|
| 333 |
+
|
| 334 |
+
return best_type, best_score
|
| 335 |
+
|
| 336 |
+
def verify_keywords(ocr_tokens, user_keywords, use_fuzzy=False):
|
| 337 |
+
"""
|
| 338 |
+
FIXED: Sequence-aware matching for multi-keyword inputs.
|
| 339 |
+
Checks if keywords appear consecutively in OCR text first.
|
| 340 |
+
"""
|
| 341 |
+
ocr_set = set(ocr_tokens)
|
| 342 |
+
ocr_combined = " ".join(ocr_tokens)
|
| 343 |
+
results = []
|
| 344 |
+
|
| 345 |
+
if len(user_keywords) > 1:
|
| 346 |
+
user_phrase = " ".join([kw.lower() if all(ord(c) < 128 for c in kw) else kw for kw in user_keywords])
|
| 347 |
+
|
| 348 |
+
if user_phrase in ocr_combined:
|
| 349 |
+
for kw in user_keywords:
|
| 350 |
+
results.append({
|
| 351 |
+
'keyword': kw,
|
| 352 |
+
'matched': True,
|
| 353 |
+
'matched_text': kw
|
| 354 |
+
})
|
| 355 |
+
return results
|
| 356 |
+
|
| 357 |
+
if use_fuzzy:
|
| 358 |
+
n = len(user_keywords)
|
| 359 |
+
ocr_phrases = [" ".join(ocr_tokens[i:i+n]) for i in range(len(ocr_tokens) - n + 1)]
|
| 360 |
+
|
| 361 |
+
phrase_match = fuzzy_match(user_phrase, set(ocr_phrases))
|
| 362 |
+
if phrase_match:
|
| 363 |
+
for kw in user_keywords:
|
| 364 |
+
results.append({
|
| 365 |
+
'keyword': kw,
|
| 366 |
+
'matched': True,
|
| 367 |
+
'matched_text': kw
|
| 368 |
+
})
|
| 369 |
+
return results
|
| 370 |
+
|
| 371 |
+
# Fallback to individual keyword matching
|
| 372 |
+
for kw in user_keywords:
|
| 373 |
+
kw_processed = kw.lower() if all(ord(c) < 128 for c in kw) else kw
|
| 374 |
+
matched = False
|
| 375 |
+
matched_text = None
|
| 376 |
+
|
| 377 |
+
if kw_processed in ocr_set:
|
| 378 |
+
matched = True
|
| 379 |
+
matched_text = kw_processed
|
| 380 |
+
elif " " in kw_processed and kw_processed in ocr_combined:
|
| 381 |
+
matched = True
|
| 382 |
+
matched_text = kw_processed
|
| 383 |
+
elif use_fuzzy:
|
| 384 |
+
matched_text = fuzzy_match(kw_processed, ocr_set)
|
| 385 |
+
if matched_text:
|
| 386 |
+
matched = True
|
| 387 |
+
|
| 388 |
+
results.append({
|
| 389 |
+
'keyword': kw,
|
| 390 |
+
'matched': matched,
|
| 391 |
+
'matched_text': matched_text or kw_processed if matched else None
|
| 392 |
+
})
|
| 393 |
+
|
| 394 |
+
return results
|
| 395 |
+
|
| 396 |
+
def main():
|
| 397 |
+
parser = argparse.ArgumentParser(description='OCR Document Verification with PDF Support')
|
| 398 |
+
parser.add_argument('--file', nargs='+', required=True, help='Paths to image or PDF files')
|
| 399 |
+
parser.add_argument('--inputkeywords', required=True, help='Space-separated keywords to verify')
|
| 400 |
+
parser.add_argument('--required', nargs='+', help='List of required document types')
|
| 401 |
+
parser.add_argument('--fuzzy', action='store_true', help='Enable fuzzy matching')
|
| 402 |
+
parser.add_argument('--debug', action='store_true', help='Show detailed OCR and scoring output')
|
| 403 |
+
parser.add_argument('--pages', type=int, default=3, help='Max pages to process for PDFs')
|
| 404 |
+
global args
|
| 405 |
+
args = parser.parse_args()
|
| 406 |
+
|
| 407 |
+
# Clean required list
|
| 408 |
+
required_list = []
|
| 409 |
+
if args.required:
|
| 410 |
+
for item in args.required:
|
| 411 |
+
parts = [part.strip() for part in item.split(',') if part.strip()]
|
| 412 |
+
required_list.extend(parts)
|
| 413 |
+
|
| 414 |
+
required_set = set(required_list)
|
| 415 |
+
|
| 416 |
+
# NEW: Initialize OCR once, reuse for all files
|
| 417 |
+
print("Initializing OCR engine (first run may take a few seconds)...")
|
| 418 |
+
ocr_engine = PaddleOCR(
|
| 419 |
+
lang="mr",
|
| 420 |
+
use_doc_orientation_classify=False,
|
| 421 |
+
use_doc_unwarping=False,
|
| 422 |
+
use_textline_orientation=False,
|
| 423 |
+
max_batch_size=16, # Process multiple images in parallel
|
| 424 |
+
num_workers=min(4, multiprocessing.cpu_count()), # CPU workers for preprocessing
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
# Process each file and collect results
|
| 428 |
+
file_results = []
|
| 429 |
+
found_documents = set()
|
| 430 |
+
all_matched_keywords_per_file = []
|
| 431 |
+
|
| 432 |
+
print(f"\n{'='*60}")
|
| 433 |
+
print(f"PROCESSING {len(args.file)} FILES")
|
| 434 |
+
print(f"{'='*60}\n")
|
| 435 |
+
|
| 436 |
+
for idx, file_path in enumerate(args.file, 1):
|
| 437 |
+
print(f"--- FILE {idx}/{len(args.file)}: {os.path.basename(file_path)} ---")
|
| 438 |
+
|
| 439 |
+
# Extract text from file
|
| 440 |
+
ocr_texts = get_ocr_text(file_path, ocr_engine, args.pages, args.debug)
|
| 441 |
+
|
| 442 |
+
if not ocr_texts:
|
| 443 |
+
print(f"⚠️ No text extracted from {file_path}\n")
|
| 444 |
+
file_results.append({
|
| 445 |
+
'file': file_path,
|
| 446 |
+
'doc_type': 'Unknown',
|
| 447 |
+
'doc_score': 0,
|
| 448 |
+
'keywords_matched': [],
|
| 449 |
+
'status': 'ERROR'
|
| 450 |
+
})
|
| 451 |
+
continue
|
| 452 |
+
|
| 453 |
+
# Debug: Show raw OCR
|
| 454 |
+
if args.debug:
|
| 455 |
+
print("\n" + "="*60)
|
| 456 |
+
print("RAW OCR EXTRACTED TEXT:")
|
| 457 |
+
print("="*60)
|
| 458 |
+
for i, text in enumerate(ocr_texts, 1):
|
| 459 |
+
print(f"{i:3d}. {text}")
|
| 460 |
+
print("="*60 + "\n")
|
| 461 |
+
|
| 462 |
+
# Normalize tokens
|
| 463 |
+
ocr_tokens = normalize_text(" ".join(ocr_texts))
|
| 464 |
+
|
| 465 |
+
# Debug: Show normalized tokens
|
| 466 |
+
if args.debug:
|
| 467 |
+
print("="*60)
|
| 468 |
+
print("NORMALIZED TOKENS:")
|
| 469 |
+
print("="*60)
|
| 470 |
+
print(f"Total tokens: {len(ocr_tokens)}")
|
| 471 |
+
print(f"First 50 tokens: {', '.join(ocr_tokens[:50])}{'...' if len(ocr_tokens) > 50 else ''}")
|
| 472 |
+
print("="*60 + "\n")
|
| 473 |
+
|
| 474 |
+
# Document classification
|
| 475 |
+
if args.debug:
|
| 476 |
+
print("="*60)
|
| 477 |
+
print("DOCUMENT TYPE SCORING:")
|
| 478 |
+
print("="*60)
|
| 479 |
+
|
| 480 |
+
doc_type, doc_score = calculate_doc_type(ocr_tokens, debug=args.debug)
|
| 481 |
+
found_documents.add(doc_type)
|
| 482 |
+
|
| 483 |
+
if args.debug:
|
| 484 |
+
print("="*60 + "\n")
|
| 485 |
+
|
| 486 |
+
# Keyword verification
|
| 487 |
+
user_keywords = [kw.strip() for kw in args.inputkeywords.split()]
|
| 488 |
+
verification_results = verify_keywords(ocr_tokens, user_keywords, args.fuzzy)
|
| 489 |
+
|
| 490 |
+
# Status: ALL keywords must match in this file
|
| 491 |
+
all_matched = all(r['matched'] for r in verification_results)
|
| 492 |
+
status = "VERIFIED" if all_matched else "NOT VERIFIED"
|
| 493 |
+
|
| 494 |
+
# Store results for this file
|
| 495 |
+
file_results.append({
|
| 496 |
+
'file': file_path,
|
| 497 |
+
'doc_type': doc_type,
|
| 498 |
+
'doc_score': doc_score,
|
| 499 |
+
'keywords_matched': verification_results,
|
| 500 |
+
'status': status,
|
| 501 |
+
'all_keywords_matched': all_matched
|
| 502 |
+
})
|
| 503 |
+
|
| 504 |
+
# Track which keywords were matched in this file
|
| 505 |
+
matched_keywords_in_file = {r['keyword'] for r in verification_results if r['matched']}
|
| 506 |
+
all_matched_keywords_per_file.append(matched_keywords_in_file)
|
| 507 |
+
|
| 508 |
+
# Per-file output
|
| 509 |
+
print(f"\n{'='*60}")
|
| 510 |
+
print(f"Document Type: {doc_type} ({doc_score:.1f}% confidence)")
|
| 511 |
+
print(f"{'='*60}")
|
| 512 |
+
print(f"{'Keyword':<25} | {'Status':<10} | {'Matched Text'}")
|
| 513 |
+
print(f"{'-'*60}")
|
| 514 |
+
|
| 515 |
+
for r in verification_results:
|
| 516 |
+
status_icon = "✓" if r['matched'] else "✗"
|
| 517 |
+
matched_text = r['matched_text'] if r['matched_text'] else "Not found"
|
| 518 |
+
print(f"{r['keyword']:<25} | {status_icon:<10} | {matched_text}")
|
| 519 |
+
|
| 520 |
+
print(f"{'='*60}")
|
| 521 |
+
print(f"File Status: {status}")
|
| 522 |
+
print(f"{'='*60}\n")
|
| 523 |
+
|
| 524 |
+
# FINAL SUMMARY (unchanged)
|
| 525 |
+
print(f"\n{'='*60}")
|
| 526 |
+
print(f"FINAL SUMMARY")
|
| 527 |
+
print(f"{'='*60}")
|
| 528 |
+
|
| 529 |
+
# Required documents check
|
| 530 |
+
if required_set:
|
| 531 |
+
missing_docs = required_set - found_documents
|
| 532 |
+
|
| 533 |
+
print(f"\nRequired Documents: {', '.join(sorted(required_set))}")
|
| 534 |
+
print(f"Found Documents: {', '.join(sorted(found_documents)) if found_documents else 'None'}")
|
| 535 |
+
|
| 536 |
+
if missing_docs:
|
| 537 |
+
print(f"❌ Missing Documents: {', '.join(sorted(missing_docs))}")
|
| 538 |
+
docs_status = "NOT VERIFIED"
|
| 539 |
+
else:
|
| 540 |
+
print(f"✅ All required documents found!")
|
| 541 |
+
docs_status = "VERIFIED"
|
| 542 |
+
else:
|
| 543 |
+
docs_status = "N/A (no required list specified)"
|
| 544 |
+
missing_docs = set()
|
| 545 |
+
|
| 546 |
+
# Overall keyword verification across ALL files
|
| 547 |
+
all_user_keywords = set(args.inputkeywords.split())
|
| 548 |
+
keywords_found_across_files = set()
|
| 549 |
+
|
| 550 |
+
for file_keyword_set in all_matched_keywords_per_file:
|
| 551 |
+
keywords_found_across_files.update(file_keyword_set)
|
| 552 |
+
|
| 553 |
+
missing_keywords = all_user_keywords - keywords_found_across_files
|
| 554 |
+
|
| 555 |
+
print(f"\nKeywords to Find: {', '.join(sorted(all_user_keywords))}")
|
| 556 |
+
print(f"Keywords Found (across all files): {', '.join(sorted(keywords_found_across_files)) if keywords_found_across_files else 'None'}")
|
| 557 |
+
|
| 558 |
+
if missing_keywords:
|
| 559 |
+
print(f"❌ Missing Keywords: {', '.join(sorted(missing_keywords))}")
|
| 560 |
+
keywords_status = "NOT VERIFIED"
|
| 561 |
+
else:
|
| 562 |
+
print(f"✅ All keywords found across uploaded documents!")
|
| 563 |
+
keywords_status = "VERIFIED"
|
| 564 |
+
|
| 565 |
+
# Overall status: BOTH documents and keywords must be verified
|
| 566 |
+
overall_status = "VERIFIED" if (docs_status == "VERIFIED" and keywords_status == "VERIFIED") else "NOT VERIFIED"
|
| 567 |
+
|
| 568 |
+
print(f"\n{'='*60}")
|
| 569 |
+
print(f"Documents Status: {docs_status}")
|
| 570 |
+
print(f"Keywords Status: {keywords_status}")
|
| 571 |
+
print(f"OVERALL STATUS: {overall_status}")
|
| 572 |
+
print(f"{'='*60}")
|
| 573 |
+
|
| 574 |
+
if __name__ == "__main__":
|
| 575 |
main()
|