crazylemonade commited on
Commit
7252771
·
verified ·
1 Parent(s): 60afcec

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -2068
main.py DELETED
@@ -1,2068 +0,0 @@
1
- """
2
- MinerU OCR & Document Extraction Service — v3.0
3
- FastAPI application for Hugging Face Docker Space (CPU / pipeline backend)
4
-
5
- ═══════════════════════════════════════════════════════════════════════════════
6
- ARCHITECTURE (v3.0 — dual-path OCR + document-aware extraction)
7
- ═══════════════════════════════════════════════════════════════════════════════
8
-
9
- PATH A — Fast OCR (images: jpg / png / webp / bmp / heic / heif / avif)
10
- Engine : rapidocr-onnxruntime ≥ 1.3.22
11
- Models : Bundled in pip wheel — zero first-use download, ~50 MB
12
- Target : 1–5 s (acceptable < 10 s)
13
- Multi-pass : if confidence < FAST_CONFIDENCE_THRESHOLD → MinerU fallback
14
-
15
- PATH B — Full pipeline (PDFs, multi-page, layout-sensitive docs)
16
- Engine : MinerU magic-pdf pipeline backend
17
- Models : opendatalab/PDF-Extract-Kit-1.0 (downloaded at build time)
18
- Target : 5–20 s (acceptable < 30 s)
19
-
20
- ═══════════════════════════════════════════════════════════════════════════════
21
- EXTRACTION ARCHITECTURE (v3.0 changes)
22
- ═══════════════════════════════════════════════════════════════════════════════
23
-
24
- OCR → Document Classification → Template Selection → Structured Extraction
25
- → Independent Calculation → Validation → Confidence Scoring → Response
26
-
27
- Key change: CBSE marksheet now uses a dedicated table parser that reads the
28
- 3-digit subject code column, not keyword matching on subject names.
29
- Format handled: "184 ENGLISH LNG & LIT. 073 020 093" → code=184, total=093
30
-
31
- ═══════════════════════════════════════════════════════════════════════════════
32
- API ENDPOINTS
33
- ═══════════════════════════════════════════════════════════════════════════════
34
-
35
- GET /health Liveness (always fast)
36
- GET /status Node status: memory, uptime, cache, active requests
37
- GET /warmup Pre-load both OCR engines into RAM
38
- GET /diagnostics Full environment + model inventory dump
39
- GET /extraction-debug Last extraction debug trace: template, fields, validation
40
- POST /benchmark RapidOCR timing on synthetic test image
41
- POST /extract Single file — PDF or image — with SHA256 cache
42
- POST /batch Up to 8 files, sequential, per-file error isolation
43
-
44
- ═══════════════════════════════════════════════════════════════════════════════
45
- RESPONSE FORMAT (v3.0)
46
- ═══════════════════════════════════════════════════════════════════════════════
47
-
48
- {
49
- "success": true,
50
- "filename": "marksheet.jpg",
51
- "docType": "marksheet",
52
- "pageCount": 1,
53
- "confidence": 0.94,
54
- "ocrEngine": "rapidocr",
55
- "markdown": "...",
56
- "plainText": "...",
57
- "documentSummary": "CBSE marksheet for ARYAN (Roll: 28169763). 5 subjects extracted. Total 433/500 (86.6%). Result: PASS.",
58
- "entities": {
59
- "studentName": "ARYAN",
60
- "rollNumber": "28169763",
61
- "dob": "17-10-2009",
62
- "fatherName": "VIJENDER SINGH",
63
- "motherName": "RENU",
64
- "subjects": [
65
- {"code": "184", "name": "English", "theory": 73, "practical": 20, "marks": 93, "grade": "A1"},
66
- ...
67
- ],
68
- "totalMarks": 433,
69
- "maxMarks": 500,
70
- "percentage": 86.6,
71
- "result": "PASS"
72
- },
73
- "validationReport": {
74
- "passed": true,
75
- "score": 0.9,
76
- "fieldsFound": ["studentName", "rollNumber", "dob", "subjects", "totalMarks"],
77
- "fieldsMissing": [],
78
- "warnings": [],
79
- "subjectCount": 5
80
- },
81
- "timings": { "uploadMs": 12, "ocrTotalMs": 820, "totalMs": 898 },
82
- "metadata": {
83
- "parseMethod": "fast_ocr", "backend": "rapidocr",
84
- "cached": false, "processingTimeMs": 898,
85
- "passesUsed": 1, "textBlocks": 24
86
- }
87
- }
88
- """
89
-
90
- import hashlib
91
- import io
92
- import os
93
- import re
94
- import shutil
95
- import sys
96
- import tempfile
97
- import threading
98
- import time
99
- import traceback
100
- import logging
101
- from importlib.metadata import version as pkg_version
102
- from typing import Any, Optional
103
-
104
- import fitz # PyMuPDF — bundled with magic-pdf[full]
105
- import numpy as np
106
- from PIL import Image
107
-
108
- from fastapi import FastAPI, File, UploadFile
109
- from fastapi.middleware.cors import CORSMiddleware
110
- from fastapi.responses import JSONResponse
111
-
112
- # ── Logging ───────────────────────────────────────────────────────────────────
113
- logging.basicConfig(
114
- level=logging.INFO,
115
- format="%(asctime)s %(levelname)-8s %(name)s %(message)s",
116
- )
117
- logger = logging.getLogger("mineru-service")
118
-
119
- # ── Start time ────────────────────────────────────────────────────────────────
120
- _START_TIME: float = time.time()
121
-
122
- # ── Upload / batch constants ──────────────────────────────────────────────────
123
- MAX_UPLOAD_BYTES = 30 * 1024 * 1024 # 30 MB
124
- BATCH_MAX_FILES = 8
125
-
126
- # ── File type sets ────────────────────────────────────────────────────────────
127
- PDF_EXTENSIONS = {"pdf"}
128
- NATIVE_IMAGE_EXTENSIONS = {"jpg", "jpeg", "png"}
129
- PILLOW_IMAGE_EXTENSIONS = {"webp", "bmp", "tiff", "tif", "gif", "heic", "heif", "avif"}
130
- IMAGE_EXTENSIONS = NATIVE_IMAGE_EXTENSIONS | PILLOW_IMAGE_EXTENSIONS
131
- ALLOWED_EXTENSIONS = PDF_EXTENSIONS | IMAGE_EXTENSIONS
132
-
133
- # ── Fast-OCR confidence threshold for MinerU fallback ─────────────────────────
134
- FAST_CONFIDENCE_THRESHOLD = 0.65
135
-
136
- # ── Memory safety ─────────────────────────────────────────────────────────────
137
- BYTES_PER_OCR_PAGE = 100 * 1024 * 1024
138
- IMAGE_MEMORY_FACTOR = 4
139
- MEM_SAFETY_FLOOR_MB = 1024
140
-
141
- # ── SHA256 extraction cache ───────────────────────────────────────────────────
142
- _cache: dict[str, dict[str, Any]] = {}
143
- _cache_lock = threading.Lock()
144
-
145
- # ── Active-request counter ────────────────────────────────────────────────────
146
- _active_requests: int = 0
147
- _active_lock = threading.Lock()
148
-
149
- # ── Model load state ──────────────────────────────────────────────────────────
150
- _model_load_ms: int = 0
151
- _pipeline_ready: bool = False
152
- _pipeline_lock = threading.Lock()
153
-
154
- _rapidocr_engine: Any = None
155
- _rapidocr_lock = threading.Lock()
156
- _rapidocr_load_ms: int = 0
157
- _rapidocr_ready: bool = False
158
-
159
- # ── Startup issues ────────────────────────────────────────────────────────────
160
- _startup_issues: list[str] = []
161
- _startup_done: bool = False
162
-
163
- # ── Last extraction debug trace (for /extraction-debug) ──────────────────────
164
- _last_debug: dict[str, Any] = {}
165
- _last_debug_lock = threading.Lock()
166
-
167
-
168
- # ═════════════════════════════════════════════════════════════════════════════
169
- # CBSE lookup tables
170
- # ═════════════════════════════════════════════════════════════════════════════
171
-
172
- # Official CBSE subject code → canonical name mapping
173
- CBSE_CODE_MAP: dict[str, str] = {
174
- "101": "English",
175
- "184": "English",
176
- "085": "Hindi",
177
- "002": "Hindi",
178
- "086": "Hindi",
179
- "041": "Mathematics",
180
- "241": "Mathematics",
181
- "086": "Science",
182
- "087": "Social Science",
183
- "165": "Information Technology",
184
- "064": "Computer Science",
185
- "065": "Informatics Practices",
186
- "044": "Biology",
187
- "042": "Physics",
188
- "043": "Chemistry",
189
- "030": "Economics",
190
- "028": "History",
191
- "029": "Geography",
192
- "027": "Political Science",
193
- "048": "Physical Education",
194
- "049": "Painting",
195
- "054": "Business Studies",
196
- "055": "Accountancy",
197
- "096": "Mathematics",
198
- "301": "English Elective",
199
- "302": "Hindi Elective",
200
- "083": "Science & Technology",
201
- "149": "National Cadet Corps",
202
- "606": "Yoga",
203
- }
204
- # Overrides for common codes that map to the same key above (Python dict overwrites)
205
- CBSE_CODE_MAP.update({
206
- "086": "Science",
207
- "085": "Hindi",
208
- })
209
-
210
- # Fuzzy subject name normalization
211
- # Maps OCR noise → canonical subject name (all keys lower-case, stripped)
212
- SUBJECT_NORM_MAP: dict[str, str] = {
213
- # English variants
214
- "english lng & lit": "English",
215
- "english lng&lit": "English",
216
- "englishlng&lit": "English",
217
- "english language & literature": "English",
218
- "english language and literature": "English",
219
- "english communicative": "English",
220
- "english core": "English",
221
- "eng": "English",
222
- "english course a": "English",
223
- "english course b": "English",
224
- "english course-a": "English",
225
- "english course-b": "English",
226
- # Hindi variants
227
- "hindi course a": "Hindi",
228
- "hindi course b": "Hindi",
229
- "hindi course-a": "Hindi",
230
- "hindi course-b": "Hindi",
231
- "hindi core": "Hindi",
232
- "hindi (course b)": "Hindi",
233
- # Mathematics variants
234
- "mathematics standard": "Mathematics",
235
- "mathematics basic": "Mathematics",
236
- "maths standard": "Mathematics",
237
- "maths basic": "Mathematics",
238
- "mathematics (basic)": "Mathematics",
239
- "mathematics (standard)": "Mathematics",
240
- "maths": "Mathematics",
241
- "math": "Mathematics",
242
- # Science variants
243
- "natural science": "Science",
244
- "general science": "Science",
245
- "sci": "Science",
246
- # Social Science variants
247
- "social science": "Social Science",
248
- "socialscience": "Social Science",
249
- "social studies": "Social Science",
250
- "sst": "Social Science",
251
- # Computer variants
252
- "computer science": "Computer Science",
253
- "computer application": "Computer Applications",
254
- "it": "Information Technology",
255
- "informatics practices": "Informatics Practices",
256
- }
257
-
258
- # CBSE grade bands (marks out of 100 → grade)
259
- def _cbse_grade(marks: int) -> str:
260
- if marks >= 91: return "A1"
261
- if marks >= 81: return "A2"
262
- if marks >= 71: return "B1"
263
- if marks >= 61: return "B2"
264
- if marks >= 51: return "C1"
265
- if marks >= 41: return "C2"
266
- if marks >= 33: return "D"
267
- return "E"
268
-
269
-
270
- # ═════════════════════════════════════════════════════════════════════════════
271
- # Document templates (required/optional field definitions)
272
- # ═════════════════════════════════════════════════════════════════════════════
273
-
274
- DOC_TEMPLATES: dict[str, dict[str, Any]] = {
275
- "marksheet": {
276
- "required": ["studentName", "rollNumber", "subjects"],
277
- "optional": ["dob", "fatherName", "motherName", "school", "year",
278
- "totalMarks", "maxMarks", "percentage", "result"],
279
- "min_subjects": 1,
280
- "expected_subjects": 5,
281
- },
282
- "invoice": {
283
- "required": ["invoiceNumber", "totalAmount"],
284
- "optional": ["invoiceDate", "dueDate", "billTo", "gstin", "lineItems"],
285
- },
286
- "form": {
287
- "required": ["name"],
288
- "optional": ["dob", "gender", "phone", "email", "address"],
289
- },
290
- "certificate": {
291
- "required": ["recipientName"],
292
- "optional": ["certificateId", "issueDate", "courseOrEvent", "issuingAuthority"],
293
- },
294
- "id_card": {
295
- "required": ["name"],
296
- "optional": ["idNumber", "dob", "validTill", "designation"],
297
- },
298
- }
299
-
300
-
301
- # ═════════════════════════════════════════════════════════════════════════════
302
- # Structured error
303
- # ═════════════════════════════════════════════════════════════════════════════
304
- class ExtractionError(Exception):
305
- def __init__(
306
- self,
307
- stage: str,
308
- code: str,
309
- message: str,
310
- http_status: int = 422,
311
- root_cause: str = "",
312
- recommendation: str = "",
313
- ) -> None:
314
- self.stage = stage
315
- self.code = code
316
- self.message = message
317
- self.http_status = http_status
318
- self.root_cause = root_cause or message
319
- self.recommendation = recommendation
320
- super().__init__(message)
321
-
322
- def to_dict(self) -> dict[str, Any]:
323
- return {
324
- "success": False,
325
- "stage": self.stage,
326
- "errorCode": self.code,
327
- "rootCause": self.root_cause,
328
- "recommendation": self.recommendation,
329
- "message": self.message,
330
- }
331
-
332
-
333
- def _err(
334
- stage: str,
335
- code: str,
336
- msg: str,
337
- status: int = 422,
338
- root_cause: str = "",
339
- recommendation: str = "",
340
- ) -> ExtractionError:
341
- return ExtractionError(stage, code, msg, status, root_cause, recommendation)
342
-
343
-
344
- # ═════════════════════════════════════════════════════════════════════════════
345
- # Active request helpers
346
- # ═════════════════════════════════════════════════════════════════════════════
347
- def _inc_active() -> None:
348
- global _active_requests
349
- with _active_lock:
350
- _active_requests += 1
351
-
352
-
353
- def _dec_active() -> None:
354
- global _active_requests
355
- with _active_lock:
356
- _active_requests = max(0, _active_requests - 1)
357
-
358
-
359
- # ═════════════════════════════════════════════════════════════════════════════
360
- # Engine loaders
361
- # ═════════════════════════════════════════════════════════════════════════════
362
- def _ensure_rapidocr() -> Any:
363
- global _rapidocr_engine, _rapidocr_ready, _rapidocr_load_ms
364
- if _rapidocr_ready:
365
- return _rapidocr_engine
366
- with _rapidocr_lock:
367
- if _rapidocr_ready:
368
- return _rapidocr_engine
369
- t0 = time.perf_counter()
370
- try:
371
- from rapidocr_onnxruntime import RapidOCR
372
- _rapidocr_engine = RapidOCR()
373
- _rapidocr_load_ms = int((time.perf_counter() - t0) * 1000)
374
- _rapidocr_ready = True
375
- logger.info("RapidOCR engine loaded (%d ms).", _rapidocr_load_ms)
376
- except Exception as exc:
377
- raise _err(
378
- "model_load", "RAPIDOCR_LOAD_FAILED", f"RapidOCR failed to load: {exc}", 503,
379
- root_cause=str(exc),
380
- recommendation="Check that rapidocr-onnxruntime is installed in Dockerfile Layer 1.",
381
- ) from exc
382
- return _rapidocr_engine
383
-
384
-
385
- def _ensure_pipeline() -> None:
386
- global _pipeline_ready, _model_load_ms
387
- if _pipeline_ready:
388
- return
389
- with _pipeline_lock:
390
- if _pipeline_ready:
391
- return
392
- config_path = os.path.expanduser("~/magic-pdf.json")
393
- if not os.path.exists(config_path):
394
- raise _err(
395
- "model_load", "CONFIG_MISSING",
396
- f"magic-pdf.json not found at {config_path}.", 503,
397
- root_cause="download_models.py did not run or /root was wiped.",
398
- recommendation="Check Docker build log for download_models.py output.",
399
- )
400
- t0 = time.perf_counter()
401
- try:
402
- from magic_pdf.data.dataset import PymuDocDataset, ImageDataset # noqa
403
- from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter # noqa
404
- except ImportError as exc:
405
- raise _err(
406
- "model_load", "IMPORT_FAILED", f"magic_pdf not importable: {exc}", 503,
407
- root_cause=str(exc),
408
- recommendation="Check that magic-pdf[full]==1.3.12 is installed in Dockerfile Layer 3.",
409
- ) from exc
410
- _model_load_ms = int((time.perf_counter() - t0) * 1000)
411
- _pipeline_ready = True
412
- logger.info("MinerU pipeline ready (%d ms).", _model_load_ms)
413
-
414
-
415
- # ═════════════════════════════════════════════════════════════════════════════
416
- # FastAPI app
417
- # ═════════════════════════════════════════════════════════════════════════════
418
- app = FastAPI(
419
- title="MinerU OCR Service",
420
- description="Dual-path OCR with document-aware entity extraction.",
421
- version="3.0.0",
422
- )
423
-
424
- app.add_middleware(
425
- CORSMiddleware,
426
- allow_origins=["*"],
427
- allow_methods=["GET", "POST"],
428
- allow_headers=["*"],
429
- )
430
-
431
-
432
- # ─────────────────────────────────────────────────────────────────────────────
433
- # Startup self-test
434
- # ─────────────────────────────────────────────────────────────────────────────
435
- @app.on_event("startup")
436
- async def startup_self_test() -> None:
437
- global _startup_done
438
- issues: list[str] = []
439
- checks = [
440
- ("cv2", lambda: __import__("cv2").__version__),
441
- ("torch", lambda: __import__("torch").__version__),
442
- ("rapidocr", lambda: pkg_version("rapidocr-onnxruntime")),
443
- ("magic_pdf", lambda: __import__("magic_pdf").__version__),
444
- ]
445
- for name, fn in checks:
446
- try:
447
- ver = fn()
448
- logger.info("startup ✓ %s %s", name, ver)
449
- except Exception as exc:
450
- msg = f"{name} unavailable: {exc}"
451
- issues.append(msg)
452
- logger.critical("startup FAIL %s", msg)
453
-
454
- config_path = os.path.expanduser("~/magic-pdf.json")
455
- if not os.path.exists(config_path):
456
- issues.append(f"magic-pdf.json missing at {config_path}")
457
-
458
- if not os.path.isdir("/app/models/PDF-Extract-Kit-1.0/models"):
459
- issues.append("Models directory missing: /app/models/PDF-Extract-Kit-1.0/models")
460
-
461
- try:
462
- td = tempfile.mkdtemp(prefix="mineru_selftest_")
463
- shutil.rmtree(td)
464
- except Exception as exc:
465
- issues.append(f"Temp storage not writable: {exc}")
466
-
467
- _startup_issues.extend(issues)
468
- _startup_done = True
469
- level = logger.info if not issues else logger.error
470
- level("Startup self-test %s — %d issue(s).", "PASSED" if not issues else "FAILED", len(issues))
471
-
472
-
473
- # ═════════════════════════════════════════════════════════════════════════════
474
- # GET /health
475
- # ═════════════════════════════════════════════════════════════════════════════
476
- @app.get("/health")
477
- def health() -> dict[str, Any]:
478
- return {"status": "healthy"}
479
-
480
-
481
- # ═════════════════════════════════════════════════════════════════════════════
482
- # GET /status
483
- # ═════════════════════════════════════════════════════════════════════════════
484
- @app.get("/status")
485
- def status() -> dict[str, Any]:
486
- used_mb, total_mb = _mem_mb()
487
- return {
488
- "status": "healthy" if not _startup_issues else "degraded",
489
- "provider": "mineru",
490
- "version": _mineru_version(),
491
- "ocrEngines": {
492
- "rapidocr": {"ready": _rapidocr_ready, "loadMs": _rapidocr_load_ms, "purpose": "images (1–5 s)"},
493
- "mineru": {"ready": _pipeline_ready, "loadMs": _model_load_ms, "purpose": "PDFs + fallback"},
494
- },
495
- "startupIssues": _startup_issues,
496
- "uptimeSeconds": int(time.time() - _START_TIME),
497
- "memoryUsedMB": used_mb,
498
- "memoryTotalMB": total_mb,
499
- "activeRequests": _active_requests,
500
- "cacheEntries": len(_cache),
501
- "confidenceThreshold": FAST_CONFIDENCE_THRESHOLD,
502
- }
503
-
504
-
505
- # ═════════════════════════════════════════════════════════════════════════════
506
- # GET /warmup
507
- # ═════════════════════════════════════════════════════════════════════════════
508
- @app.get("/warmup")
509
- def warmup() -> dict[str, Any]:
510
- results: dict[str, Any] = {}
511
- t0 = time.perf_counter()
512
- try:
513
- _ensure_rapidocr()
514
- results["rapidocr"] = {"status": "ready", "loadMs": _rapidocr_load_ms}
515
- except Exception as exc:
516
- results["rapidocr"] = {"status": "failed", "error": str(exc)}
517
- t1 = time.perf_counter()
518
- try:
519
- _ensure_pipeline()
520
- results["mineru"] = {"status": "ready", "loadMs": _model_load_ms}
521
- except Exception as exc:
522
- results["mineru"] = {"status": "failed", "error": str(exc)}
523
- results["totalElapsedMs"] = int((time.perf_counter() - t0) * 1000)
524
- results["allReady"] = _rapidocr_ready and _pipeline_ready
525
- return results
526
-
527
-
528
- # ═════════════════════════════════════════════════════════════════════════════
529
- # GET /diagnostics
530
- # ═════════════════════════════════════════════════════════════════════════════
531
- @app.get("/diagnostics")
532
- def diagnostics() -> dict[str, Any]:
533
- import platform
534
- pkgs = {}
535
- for name in ("magic-pdf", "rapidocr-onnxruntime", "torch", "torchvision",
536
- "ultralytics", "doclayout-yolo", "rapid-table", "onnxruntime",
537
- "opencv-python-headless", "Pillow", "fastapi", "uvicorn"):
538
- try:
539
- pkgs[name] = pkg_version(name)
540
- except Exception:
541
- pkgs[name] = "not found"
542
-
543
- models_root = "/app/models/PDF-Extract-Kit-1.0/models"
544
- model_files: dict[str, Any] = {}
545
- for rel in [
546
- "OCR/paddleocr_torch/ch_PP-OCRv5_det_infer.pth",
547
- "OCR/paddleocr_torch/ch_PP-OCRv5_rec_infer.pth",
548
- "Layout/YOLO/doclayout_yolo_docstructbench_imgsz1280_2501.pt",
549
- ]:
550
- full = os.path.join(models_root, rel)
551
- model_files[rel] = f"{os.path.getsize(full) / (1024*1024):.1f} MB" if os.path.isfile(full) else "MISSING"
552
-
553
- used_mb, total_mb = _mem_mb()
554
- return {
555
- "python": platform.python_version(),
556
- "packages": pkgs,
557
- "modelFiles": model_files,
558
- "memory": {"usedMB": used_mb, "totalMB": total_mb},
559
- "engines": {
560
- "rapidocr": {"ready": _rapidocr_ready, "loadMs": _rapidocr_load_ms},
561
- "mineru": {"ready": _pipeline_ready, "loadMs": _model_load_ms},
562
- },
563
- "uptime": int(time.time() - _START_TIME),
564
- "cacheEntries": len(_cache),
565
- "config": _load_config_safe(),
566
- }
567
-
568
-
569
- # ═════════════════════════════════════════════════════════════════════════════
570
- # GET /extraction-debug
571
- # Shows the detailed trace of the most recent extraction.
572
- # ═════════════════════════════════════════════════════════════════════════════
573
- @app.get("/extraction-debug")
574
- def extraction_debug() -> dict[str, Any]:
575
- """
576
- Returns a detailed trace of the last /extract call:
577
- - raw OCR text
578
- - document type detected
579
- - template used
580
- - every field found / missing
581
- - validation report
582
- - confidence breakdown
583
- - subject rows parsed (for marksheets)
584
-
585
- Use this to diagnose extraction failures without SSH access.
586
- """
587
- with _last_debug_lock:
588
- if not _last_debug:
589
- return {"message": "No extraction has been run yet. Call POST /extract first."}
590
- return dict(_last_debug)
591
-
592
-
593
- # ═════════════════════════════════════════════════════════════════════════════
594
- # POST /benchmark
595
- # ═════════════════════════════════════════════════════════════════════════════
596
- @app.post("/benchmark")
597
- async def benchmark() -> JSONResponse:
598
- import cv2
599
-
600
- img = np.ones((400, 900, 3), dtype=np.uint8) * 255
601
- rows = [
602
- ("184 ENGLISH LNG & LIT. 073 020 093", 60),
603
- ("085 HINDI COURSE-B 075 020 095", 110),
604
- ("041 MATHEMATICS STANDARD 063 020 083", 160),
605
- ("086 SCIENCE 065 020 085", 210),
606
- ("087 SOCIAL SCIENCE 057 020 077", 260),
607
- ("Total Marks: 433 / 500 Percentage: 86.6%", 330),
608
- ]
609
- for text, y in rows:
610
- cv2.putText(img, text, (20, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2)
611
-
612
- results: dict[str, Any] = {}
613
-
614
- t0 = time.perf_counter()
615
- try:
616
- engine = _ensure_rapidocr()
617
- t_load = time.perf_counter()
618
- ocr_result, elapse = engine(img)
619
- t_done = time.perf_counter()
620
-
621
- texts = [item[1] for item in (ocr_result or []) if len(item) > 1]
622
- scores = [item[2] for item in (ocr_result or []) if len(item) > 2 and item[2] is not None]
623
- plain_text, _, _ = _parse_rapidocr_output(ocr_result)
624
- entities = _entities_marksheet(plain_text, ocr_result)
625
- validation = _validate_entities(entities, "marksheet")
626
-
627
- results["rapidocr"] = {
628
- "status": "ok",
629
- "inferenceMs": int((t_done - t_load) * 1000),
630
- "totalMs": int((t_done - t0) * 1000),
631
- "textBlocks": len(texts),
632
- "rawLines": texts,
633
- "plainText": plain_text,
634
- "confidence": round(sum(scores) / len(scores), 4) if scores else 0.0,
635
- "parsedEntities": entities,
636
- "validation": validation,
637
- }
638
- except Exception as exc:
639
- results["rapidocr"] = {"status": "failed", "error": str(exc), "traceback": traceback.format_exc()[-2000:]}
640
-
641
- used_mb, total_mb = _mem_mb()
642
- results["memory"] = {"usedMB": used_mb, "totalMB": total_mb}
643
- results["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
644
- return JSONResponse(content=results)
645
-
646
-
647
- # ═════════════════════��═══════════════════════════════════════════════════════
648
- # POST /extract
649
- # ═════════════════════════════════════════════════════════════════════════════
650
- @app.post("/extract")
651
- async def extract(file: UploadFile = File(...)) -> JSONResponse:
652
- t_upload_start = time.perf_counter()
653
- try:
654
- raw, filename, ext = await _read_upload(file)
655
- upload_ms = int((time.perf_counter() - t_upload_start) * 1000)
656
- result = _run_extraction(raw, filename, ext, upload_ms=upload_ms)
657
- return JSONResponse(content=result)
658
- except ExtractionError as exc:
659
- logger.warning("/extract [%s/%s]: %s", exc.stage, exc.code, exc.message)
660
- return JSONResponse(status_code=exc.http_status, content=exc.to_dict())
661
- except Exception as exc:
662
- logger.exception("/extract unhandled error")
663
- return JSONResponse(
664
- status_code=500,
665
- content={
666
- "success": False,
667
- "stage": "unknown",
668
- "errorCode": "INTERNAL_ERROR",
669
- "rootCause": str(exc),
670
- "recommendation": "Check HF Space logs for full traceback.",
671
- "message": str(exc),
672
- "traceback": traceback.format_exc()[-3000:],
673
- },
674
- )
675
-
676
-
677
- # ═════════════════════════════════════════════════════════════════════════════
678
- # POST /batch
679
- # ═════════════════════════════════════════════════════════════════════════════
680
- @app.post("/batch")
681
- async def batch(files: list[UploadFile] = File(...)) -> JSONResponse:
682
- candidates = files[:BATCH_MAX_FILES]
683
- results: list[dict[str, Any]] = []
684
- for upload in candidates:
685
- t0 = time.perf_counter()
686
- try:
687
- raw, filename, ext = await _read_upload(upload)
688
- result = _run_extraction(raw, filename, ext,
689
- upload_ms=int((time.perf_counter() - t0) * 1000))
690
- except ExtractionError as exc:
691
- result = exc.to_dict()
692
- result["filename"] = _sanitize_filename(upload.filename or "upload")
693
- except Exception as exc:
694
- fname = _sanitize_filename(upload.filename or "upload")
695
- logger.exception("Batch item failed: %s", fname)
696
- result = {
697
- "success": False, "filename": fname,
698
- "stage": "unknown", "errorCode": "INTERNAL_ERROR",
699
- "rootCause": str(exc), "recommendation": "Check HF Space logs.",
700
- "message": str(exc),
701
- }
702
- results.append(result)
703
- return JSONResponse(content={"success": True, "processed": len(results), "results": results})
704
-
705
-
706
- # ═════════════════════════════════════════════════════════════════════════════
707
- # Upload reader
708
- # ═════════════════════════════════════════════════════════════════════════════
709
- async def _read_upload(upload: UploadFile) -> tuple[bytes, str, str]:
710
- filename = _sanitize_filename(upload.filename or "upload")
711
- ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
712
-
713
- if ext not in ALLOWED_EXTENSIONS:
714
- raise _err(
715
- "validation", "UNSUPPORTED_TYPE",
716
- f"Unsupported file type '.{ext}'. Supported: {sorted(ALLOWED_EXTENSIONS)}",
717
- 415,
718
- root_cause=f"Extension '{ext}' is not in the allowed set.",
719
- recommendation="Convert to PDF, JPG, PNG, or WEBP before uploading.",
720
- )
721
- raw = await upload.read(MAX_UPLOAD_BYTES + 1)
722
- if len(raw) > MAX_UPLOAD_BYTES:
723
- raise _err(
724
- "upload", "FILE_TOO_LARGE",
725
- f"'{filename}' exceeds {MAX_UPLOAD_BYTES // 1024 // 1024} MB.", 413,
726
- root_cause=f"File is {len(raw) // 1024 // 1024} MB.",
727
- recommendation="Compress or split the file.",
728
- )
729
- if len(raw) == 0:
730
- raise _err("upload", "EMPTY_FILE", f"'{filename}' is empty.", 400,
731
- root_cause="Zero bytes received.",
732
- recommendation="Check the file before uploading.")
733
- return raw, filename, ext
734
-
735
-
736
- # ════════════════════════════════════════════════���════════════════════════════
737
- # Extraction dispatcher
738
- # ═════════════════════════════════════════════════════════════════════════════
739
- def _run_extraction(raw: bytes, filename: str, ext: str, upload_ms: int = 0) -> dict[str, Any]:
740
- file_hash = hashlib.sha256(raw).hexdigest()
741
- with _cache_lock:
742
- cached = _cache.get(file_hash)
743
- if cached is not None:
744
- logger.info("Cache hit %s sha256=%.12s…", filename, file_hash)
745
- out = {**cached}
746
- out["metadata"] = {**cached["metadata"], "cached": True, "processingTimeMs": 0}
747
- out["timings"] = {**cached.get("timings", {}), "totalMs": 0}
748
- return out
749
-
750
- _assert_memory_safe(raw, ext)
751
- _inc_active()
752
- work_dir = tempfile.mkdtemp(prefix="mineru_")
753
- t0 = time.perf_counter()
754
- try:
755
- if ext in PDF_EXTENSIONS:
756
- _ensure_pipeline()
757
- result = _process_pdf(raw, filename, work_dir, upload_ms=upload_ms)
758
- else:
759
- result = _process_image_routed(raw, filename, ext, work_dir, upload_ms=upload_ms)
760
-
761
- total_ms = int((time.perf_counter() - t0) * 1000)
762
- result["timings"]["totalMs"] = total_ms
763
- result["timings"]["uploadMs"] = upload_ms
764
- result["metadata"]["processingTimeMs"] = total_ms
765
- result["metadata"]["cached"] = False
766
-
767
- entry = {k: v for k, v in result.items() if k != "timings"}
768
- entry["metadata"] = {k: v for k, v in result["metadata"].items()
769
- if k not in ("processingTimeMs", "cached")}
770
- with _cache_lock:
771
- _cache[file_hash] = entry
772
-
773
- logger.info("Extracted %s engine=%s conf=%.2f %d ms",
774
- filename, result.get("ocrEngine", "?"),
775
- result.get("confidence", 0), total_ms)
776
- return result
777
-
778
- except ExtractionError:
779
- raise
780
- except Exception as exc:
781
- logger.exception("Extraction failed for %s", filename)
782
- raise _err("unknown", "INTERNAL_ERROR", f"Unexpected error: {exc}", 500,
783
- root_cause=str(exc),
784
- recommendation="Check HF Space logs for full traceback.") from exc
785
- finally:
786
- _dec_active()
787
- shutil.rmtree(work_dir, ignore_errors=True)
788
-
789
-
790
- # ═════════════════════════════════════════════════════════════════════════════
791
- # Image routing: RapidOCR fast path + optional MinerU fallback
792
- # ═════════════════════════════════════════════════════════════════════════════
793
- def _process_image_routed(
794
- raw: bytes, filename: str, ext: str, work_dir: str, upload_ms: int = 0
795
- ) -> dict[str, Any]:
796
- t_decode = time.perf_counter()
797
- img_bgr = _decode_image_to_bgr(raw, ext)
798
- decode_ms = int((time.perf_counter() - t_decode) * 1000)
799
-
800
- t_ocr = time.perf_counter()
801
- try:
802
- engine = _ensure_rapidocr()
803
- ocr_result, elapse = engine(img_bgr)
804
- except ExtractionError:
805
- raise
806
- except Exception as exc:
807
- raise _err("ocr", "OCR_ENGINE_FAILED", f"RapidOCR failed: {exc}", 500,
808
- root_cause=str(exc),
809
- recommendation="Check rapidocr-onnxruntime in Dockerfile Layer 1.") from exc
810
- ocr_ms = int((time.perf_counter() - t_ocr) * 1000)
811
-
812
- t_parse = time.perf_counter()
813
- plain_text, markdown, raw_conf = _parse_rapidocr_output(ocr_result)
814
- parse_ms = int((time.perf_counter() - t_parse) * 1000)
815
-
816
- logger.info("RapidOCR conf=%.3f text_len=%d ocr_ms=%d", raw_conf, len(plain_text), ocr_ms)
817
-
818
- # ── Pass 2: MinerU fallback ────────────────────────────────────────────────
819
- passes_used = 1
820
- ocr_engine = "rapidocr"
821
- if raw_conf < FAST_CONFIDENCE_THRESHOLD and plain_text.strip():
822
- logger.info("conf %.3f < %.2f — MinerU fallback", raw_conf, FAST_CONFIDENCE_THRESHOLD)
823
- try:
824
- _ensure_pipeline()
825
- mr = _process_image_mineru(raw, filename, ext, work_dir)
826
- if len(mr.get("plainText", "")) > len(plain_text) * 0.8:
827
- mr["ocrEngine"] = "mineru_fallback"
828
- mr["metadata"]["passesUsed"] = 2
829
- mr["timings"]["pass1RapidOCRMs"] = ocr_ms
830
- return mr
831
- except Exception as exc:
832
- logger.warning("MinerU fallback failed (%s) — using RapidOCR result", exc)
833
- passes_used = 2
834
-
835
- # ── Extract entities with FULL ocr_result (for table reconstruction) ──────
836
- t_ent = time.perf_counter()
837
- doc_type = _classify_document(plain_text + " " + filename)
838
- entities = _extract_entities(plain_text, doc_type, ocr_result=ocr_result)
839
- validation = _validate_entities(entities, doc_type)
840
- summary = _build_document_summary(entities, doc_type, validation)
841
- confidence = _score_confidence_v3(raw_conf, plain_text, entities, validation)
842
- ent_ms = int((time.perf_counter() - t_ent) * 1000)
843
-
844
- det_ms = rec_ms = 0
845
- if isinstance(elapse, dict):
846
- det_ms = int(elapse.get("det", 0) * 1000)
847
- rec_ms = int(elapse.get("rec", 0) * 1000)
848
- elif isinstance(elapse, (int, float)):
849
- det_ms = int(elapse * 500)
850
- rec_ms = int(elapse * 500)
851
-
852
- debug = {
853
- "filename": filename,
854
- "docType": doc_type,
855
- "templateUsed": doc_type if doc_type in DOC_TEMPLATES else "generic",
856
- "ocrEngine": ocr_engine,
857
- "rawPlainText": plain_text,
858
- "fieldsFound": validation.get("fieldsFound", []),
859
- "fieldsMissing": validation.get("fieldsMissing", []),
860
- "validationReport": validation,
861
- "confidenceBreakdown": _confidence_breakdown(raw_conf, plain_text, entities, validation),
862
- "entitiesExtracted": entities,
863
- "ocr_block_count": len(ocr_result) if ocr_result else 0,
864
- }
865
- with _last_debug_lock:
866
- _last_debug.clear()
867
- _last_debug.update(debug)
868
-
869
- return {
870
- "success": True,
871
- "filename": filename,
872
- "docType": doc_type,
873
- "pageCount": 1,
874
- "confidence": confidence,
875
- "ocrEngine": ocr_engine,
876
- "markdown": markdown,
877
- "plainText": plain_text,
878
- "documentSummary": summary,
879
- "entities": entities,
880
- "validationReport": validation,
881
- "timings": {
882
- "uploadMs": upload_ms,
883
- "decodeMs": decode_ms,
884
- "classifyMs": ent_ms,
885
- "ocrDetMs": det_ms,
886
- "ocrRecMs": rec_ms,
887
- "ocrTotalMs": ocr_ms,
888
- "markdownMs": parse_ms,
889
- "totalMs": 0,
890
- },
891
- "metadata": {
892
- "parseMethod": "fast_ocr",
893
- "backend": "rapidocr",
894
- "passesUsed": passes_used,
895
- "docTypeClassification": doc_type,
896
- "textBlocks": len(ocr_result) if ocr_result else 0,
897
- "imageCount": 0,
898
- "tableCount": _count_tables_in_text(plain_text),
899
- "formulaCount": 0,
900
- "processingTimeMs": 0,
901
- "cached": False,
902
- },
903
- }
904
-
905
-
906
- def _process_image_mineru(raw: bytes, filename: str, ext: str, work_dir: str) -> dict[str, Any]:
907
- from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter
908
- from magic_pdf.data.dataset import ImageDataset
909
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
910
-
911
- images_dir = os.path.join(work_dir, "images_mineru")
912
- os.makedirs(images_dir, exist_ok=True)
913
-
914
- t0 = time.perf_counter()
915
- if ext in PILLOW_IMAGE_EXTENSIONS:
916
- raw = _convert_to_png(raw, ext)
917
- save_ext = "png"
918
- else:
919
- save_ext = ext
920
- decode_ms = int((time.perf_counter() - t0) * 1000)
921
-
922
- img_path = os.path.join(work_dir, f"input_mineru.{save_ext}")
923
- with open(img_path, "wb") as fh:
924
- fh.write(raw)
925
-
926
- t_ocr = time.perf_counter()
927
- try:
928
- reader = FileBasedDataReader(work_dir)
929
- image_bytes = reader.read(f"input_mineru.{save_ext}")
930
- ds = ImageDataset(image_bytes)
931
- infer_result = ds.apply(doc_analyze, ocr=True)
932
- pipe_result = infer_result.pipe_ocr_mode(FileBasedDataWriter(images_dir))
933
- except Exception as exc:
934
- raise _err("ocr", "OCR_PIPELINE_FAILED", f"MinerU image pipeline failed: {exc}", 500,
935
- root_cause=str(exc),
936
- recommendation="Check magic-pdf installation and model files.") from exc
937
- ocr_ms = int((time.perf_counter() - t_ocr) * 1000)
938
-
939
- t_md = time.perf_counter()
940
- try:
941
- markdown = pipe_result.get_markdown(images_dir)
942
- except Exception as exc:
943
- raise _err("markdown", "MARKDOWN_FAILED", f"get_markdown failed: {exc}") from exc
944
- md_ms = int((time.perf_counter() - t_md) * 1000)
945
-
946
- plain_text = _markdown_to_plain(markdown)
947
- doc_type = _classify_document(plain_text + " " + filename)
948
- entities = _extract_entities(plain_text, doc_type)
949
- validation = _validate_entities(entities, doc_type)
950
- summary = _build_document_summary(entities, doc_type, validation)
951
- content_list = _safe_content_list(pipe_result, images_dir)
952
- confidence = _score_confidence_mineru(markdown, entities, validation)
953
-
954
- return {
955
- "success": True,
956
- "filename": filename,
957
- "docType": doc_type,
958
- "pageCount": 1,
959
- "confidence": confidence,
960
- "ocrEngine": "mineru",
961
- "markdown": markdown,
962
- "plainText": plain_text,
963
- "documentSummary": summary,
964
- "entities": entities,
965
- "validationReport": validation,
966
- "timings": {
967
- "uploadMs": 0, "decodeMs": decode_ms,
968
- "classifyMs": 0, "ocrDetMs": 0, "ocrRecMs": 0,
969
- "ocrTotalMs": ocr_ms, "markdownMs": md_ms, "totalMs": 0,
970
- },
971
- "metadata": {
972
- "parseMethod": "ocr", "backend": "pipeline", "passesUsed": 1,
973
- "docTypeClassification": doc_type,
974
- "imageCount": _count_images(content_list),
975
- "tableCount": _count_tables(content_list),
976
- "formulaCount": _count_formulas(content_list),
977
- "processingTimeMs": 0, "cached": False,
978
- },
979
- }
980
-
981
-
982
- # ═════════════════════════════════════════════════════════════════════════════
983
- # PDF processor (MinerU)
984
- # ═════════════════════════════════════════════════════════════════════════════
985
- def _process_pdf(raw: bytes, filename: str, work_dir: str, upload_ms: int = 0) -> dict[str, Any]:
986
- from magic_pdf.data.data_reader_writer import FileBasedDataWriter
987
- from magic_pdf.data.dataset import PymuDocDataset
988
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
989
- from magic_pdf.config.enums import SupportedPdfParseMethod
990
-
991
- images_dir = os.path.join(work_dir, "images")
992
- os.makedirs(images_dir, exist_ok=True)
993
- page_count = _pdf_page_count(raw)
994
-
995
- t_classify = time.perf_counter()
996
- try:
997
- ds = PymuDocDataset(raw)
998
- method = ds.classify()
999
- except Exception as exc:
1000
- raise _err("decode", "PDF_PARSE_FAILED", f"Could not parse PDF: {exc}", 422,
1001
- root_cause=str(exc),
1002
- recommendation="Ensure the file is a valid, non-encrypted PDF.") from exc
1003
- classify_ms = int((time.perf_counter() - t_classify) * 1000)
1004
-
1005
- t_ocr = time.perf_counter()
1006
- try:
1007
- image_writer = FileBasedDataWriter(images_dir)
1008
- if method == SupportedPdfParseMethod.TXT:
1009
- infer_result = ds.apply(doc_analyze, ocr=False)
1010
- pipe_result = infer_result.pipe_txt_mode(image_writer)
1011
- parse_method = "txt"
1012
- base_conf = 0.95
1013
- else:
1014
- infer_result = ds.apply(doc_analyze, ocr=True)
1015
- pipe_result = infer_result.pipe_ocr_mode(image_writer)
1016
- parse_method = "ocr"
1017
- base_conf = 0.85
1018
- except Exception as exc:
1019
- raise _err("ocr", "OCR_PIPELINE_FAILED", f"doc_analyze/pipe failed: {exc}", 500,
1020
- root_cause=str(exc),
1021
- recommendation="Check model files in /app/models and validate.py output.") from exc
1022
- ocr_ms = int((time.perf_counter() - t_ocr) * 1000)
1023
-
1024
- t_md = time.perf_counter()
1025
- try:
1026
- markdown = pipe_result.get_markdown(images_dir)
1027
- except Exception as exc:
1028
- raise _err("markdown", "MARKDOWN_FAILED", f"get_markdown failed: {exc}") from exc
1029
- md_ms = int((time.perf_counter() - t_md) * 1000)
1030
-
1031
- plain_text = _markdown_to_plain(markdown)
1032
- content_list = _safe_content_list(pipe_result, images_dir)
1033
- doc_type = _classify_document(plain_text + " " + filename)
1034
- entities = _extract_entities(plain_text, doc_type)
1035
- validation = _validate_entities(entities, doc_type)
1036
- summary = _build_document_summary(entities, doc_type, validation)
1037
- confidence = _score_confidence_mineru(markdown, entities, validation, base=base_conf)
1038
-
1039
- debug = {
1040
- "filename": filename, "docType": doc_type, "ocrEngine": "mineru",
1041
- "templateUsed": doc_type if doc_type in DOC_TEMPLATES else "generic",
1042
- "rawPlainText": plain_text[:3000],
1043
- "fieldsFound": validation.get("fieldsFound", []),
1044
- "fieldsMissing": validation.get("fieldsMissing", []),
1045
- "validationReport": validation,
1046
- "entitiesExtracted": entities,
1047
- }
1048
- with _last_debug_lock:
1049
- _last_debug.clear()
1050
- _last_debug.update(debug)
1051
-
1052
- return {
1053
- "success": True,
1054
- "filename": filename,
1055
- "docType": doc_type,
1056
- "pageCount": page_count,
1057
- "confidence": confidence,
1058
- "ocrEngine": "mineru",
1059
- "markdown": markdown,
1060
- "plainText": plain_text,
1061
- "documentSummary": summary,
1062
- "entities": entities,
1063
- "validationReport": validation,
1064
- "timings": {
1065
- "uploadMs": upload_ms, "classifyMs": classify_ms,
1066
- "ocrDetMs": 0, "ocrRecMs": 0,
1067
- "ocrTotalMs": ocr_ms, "markdownMs": md_ms, "totalMs": 0,
1068
- },
1069
- "metadata": {
1070
- "parseMethod": parse_method, "backend": "pipeline", "passesUsed": 1,
1071
- "docTypeClassification": doc_type,
1072
- "imageCount": _count_images(content_list),
1073
- "tableCount": _count_tables(content_list),
1074
- "formulaCount": _count_formulas(content_list),
1075
- "processingTimeMs": 0, "cached": False,
1076
- },
1077
- }
1078
-
1079
-
1080
- # ═════════════════════════════════════════════════════════════════════════════
1081
- # RapidOCR output parser
1082
- # Returns (plain_text, markdown, mean_confidence)
1083
- # Also preserves per-block positional data for table reconstruction.
1084
- # ═════════════════════════════════════════════════════════════════════════════
1085
- def _parse_rapidocr_output(result: Any) -> tuple[str, str, float]:
1086
- if not result:
1087
- return "", "", 0.0
1088
-
1089
- def _avg_y(item: Any) -> float:
1090
- box = item[0]
1091
- try:
1092
- return sum(pt[1] for pt in box) / 4
1093
- except Exception:
1094
- return 0.0
1095
-
1096
- def _avg_x(item: Any) -> float:
1097
- box = item[0]
1098
- try:
1099
- return sum(pt[0] for pt in box) / 4
1100
- except Exception:
1101
- return 0.0
1102
-
1103
- sorted_items = sorted(result, key=_avg_y)
1104
-
1105
- LINE_GAP = 20
1106
- lines: list[list[Any]] = []
1107
- if sorted_items:
1108
- current: list[Any] = [sorted_items[0]]
1109
- for item in sorted_items[1:]:
1110
- if abs(_avg_y(item) - _avg_y(current[-1])) < LINE_GAP:
1111
- current.append(item)
1112
- else:
1113
- lines.append(current)
1114
- current = [item]
1115
- lines.append(current)
1116
-
1117
- text_lines: list[str] = []
1118
- for line in lines:
1119
- words = sorted(line, key=_avg_x)
1120
- text_lines.append(" ".join(str(item[1]) for item in words if len(item) > 1))
1121
-
1122
- plain_text = "\n".join(text_lines)
1123
-
1124
- scores = [item[2] for item in result if len(item) > 2 and item[2] is not None]
1125
- mean_conf = float(sum(scores) / len(scores)) if scores else 0.5
1126
- return plain_text, plain_text, mean_conf
1127
-
1128
-
1129
- # ═════════════════════════════════════════════════════════════════════════════
1130
- # Confidence scoring (v3 — 4-signal with validation)
1131
- # ═════════════════════════════════════════════════════════════════════════════
1132
- def _confidence_breakdown(
1133
- raw_ocr_conf: float,
1134
- plain_text: str,
1135
- entities: dict[str, Any],
1136
- validation: dict[str, Any],
1137
- ) -> dict[str, float]:
1138
- """Compute the 4-signal confidence components."""
1139
- nonws = len(plain_text.replace(" ", "").replace("\n", ""))
1140
- total = len(plain_text)
1141
- alpha = sum(1 for c in plain_text if c.isalpha())
1142
-
1143
- ocr_quality = round(raw_ocr_conf, 4)
1144
- text_coverage = round(min(1.0, nonws / max(1, total)), 4)
1145
- entity_complete = round(validation.get("entityCompleteness", 0.5), 4)
1146
- validation_score = round(validation.get("score", 0.5), 4)
1147
- return {
1148
- "ocrQuality": ocr_quality,
1149
- "textCoverage": text_coverage,
1150
- "entityComplete": entity_complete,
1151
- "validationScore": validation_score,
1152
- }
1153
-
1154
-
1155
- def _score_confidence_v3(
1156
- raw_ocr_conf: float,
1157
- plain_text: str,
1158
- entities: dict[str, Any],
1159
- validation: dict[str, Any],
1160
- ) -> float:
1161
- """
1162
- 4-signal composite confidence (v3):
1163
- 40% — OCR quality (mean block confidence)
1164
- 30% — Document completeness (entity completeness from validation)
1165
- 20% — Text coverage (non-whitespace density)
1166
- 10% — Validation pass rate
1167
- """
1168
- bd = _confidence_breakdown(raw_ocr_conf, plain_text, entities, validation)
1169
- score = (
1170
- 0.40 * bd["ocrQuality"] +
1171
- 0.30 * bd["entityComplete"] +
1172
- 0.20 * bd["textCoverage"] +
1173
- 0.10 * bd["validationScore"]
1174
- )
1175
- return round(min(1.0, max(0.0, score)), 4)
1176
-
1177
-
1178
- def _score_confidence_mineru(
1179
- markdown: str,
1180
- entities: dict[str, Any],
1181
- validation: dict[str, Any],
1182
- base: float = 0.85,
1183
- ) -> float:
1184
- if not markdown or len(markdown.strip()) < 20:
1185
- return 0.2
1186
- score = base
1187
- length = len(markdown.strip())
1188
- if length < 100:
1189
- score -= 0.15
1190
- elif length < 300:
1191
- score -= 0.05
1192
- if "| " in markdown and " |" in markdown:
1193
- score = min(1.0, score + 0.03)
1194
- # Apply entity completeness bonus/penalty
1195
- ec = validation.get("entityCompleteness", 0.5)
1196
- if ec < 0.3:
1197
- score -= 0.10
1198
- elif ec > 0.8:
1199
- score = min(1.0, score + 0.05)
1200
- return round(min(1.0, max(0.0, score)), 4)
1201
-
1202
-
1203
- # ═════════════════════════════════════════════════════════════════════════════
1204
- # Document classification
1205
- # ═════════════════════════════════════════════════════════════════════════════
1206
- def _classify_document(text: str) -> str:
1207
- text_l = text.lower()
1208
- rules: list[tuple[str, list[str]]] = [
1209
- ("marksheet", ["marksheet", "mark sheet", "grade sheet", "scorecard",
1210
- "score card", "cgpa", "sgpa", "semester result",
1211
- "result sheet", "marks obtained", "roll no", "roll number",
1212
- "board of education", "cbse", "icse", "ssc", "hsc",
1213
- "subject", "marks", "grade", "aggregate", "percentage"]),
1214
- ("invoice", ["invoice", "bill to", "invoice number", "invoice #",
1215
- "due date", "amount due", "subtotal", "tax invoice",
1216
- "gst", "gstin", "vat", "total amount", "payable"]),
1217
- ("receipt", ["receipt", "thank you for your purchase", "order total",
1218
- "payment received", "transaction id", "cash receipt"]),
1219
- ("certificate", ["certificate", "this is to certify", "awarded to",
1220
- "in recognition", "completed", "participation", "achievement"]),
1221
- ("resume", ["curriculum vitae", "work experience", "education",
1222
- "skills", "references", "objective", "professional summary"]),
1223
- ("form", ["please fill", "signature", "applicant", "application form",
1224
- "form no", "checkbox", "declaration", "hereby declare"]),
1225
- ("research paper", ["abstract", "introduction", "methodology", "conclusion",
1226
- "references", "keywords", "doi:", "arxiv"]),
1227
- ("contract", ["agreement", "hereby", "whereas", "terms and conditions",
1228
- "party of the first", "signed by", "indemnify"]),
1229
- ("id_card", ["id card", "identification", "employee id", "student id",
1230
- "valid till", "date of issue"]),
1231
- ]
1232
- scores: dict[str, int] = {}
1233
- for doc_type, keywords in rules:
1234
- score = sum(1 for kw in keywords if kw in text_l)
1235
- if score:
1236
- scores[doc_type] = score
1237
- return max(scores, key=lambda k: scores[k]) if scores else "document"
1238
-
1239
-
1240
- # ═════════════════════════════════════════════════════════════════════════════
1241
- # Entity extraction dispatcher
1242
- # ═════════════════════════════════════════════════════════════════════════════
1243
- def _extract_entities(
1244
- text: str,
1245
- doc_type: str,
1246
- ocr_result: Any = None,
1247
- ) -> dict[str, Any]:
1248
- """
1249
- Route to document-specific parser.
1250
- ocr_result is passed to the marksheet parser so it can use positional
1251
- data for table reconstruction (not just plain text).
1252
- """
1253
- if doc_type == "marksheet":
1254
- return _entities_marksheet(text, ocr_result)
1255
- if doc_type == "invoice":
1256
- return _entities_invoice(text)
1257
- if doc_type == "form":
1258
- return _entities_form(text)
1259
- if doc_type == "certificate":
1260
- return _entities_certificate(text)
1261
- if doc_type == "id_card":
1262
- return _entities_id_card(text)
1263
- return _entities_generic(text)
1264
-
1265
-
1266
- # ═════════════════════════════════════════════════════════════════════════════
1267
- # CBSE / Board Marksheet Parser
1268
- #
1269
- # Root cause of the previous failure:
1270
- # The old parser searched for subject-name keywords ("english", "science")
1271
- # followed by whitespace and a number. In the OCR text:
1272
- # "184 ENGLISH LNG & LIT. 073 020 093"
1273
- # it found "ENGLISH" then grabbed "073" (the THEORY column, not the TOTAL).
1274
- # When "SCIENCE" appeared as "086 SCIENCE 065 020 085", it found 065 for the
1275
- # single occurrence of "SCIENCE" (only worked once because the second regex
1276
- # hit landed on the first subject row, Science was the 4th row).
1277
- # Result: only "Science: 65" extracted out of 5 subjects.
1278
- #
1279
- # Fix: parse the CBSE subject table structure directly.
1280
- # Format: CODE SUBJECT_NAME THEORY PRACTICAL TOTAL [GRADE]
1281
- # All three numeric columns are 2-3 digits; TOTAL = THEORY + PRACTICAL.
1282
- # Use CBSE subject code lookup first; fall back to subject name normalization.
1283
- # ════════════════════════════════��════════════════════════════════════════════
1284
-
1285
- def _normalize_subject_name(raw: str) -> str:
1286
- """Normalize OCR noise in a subject name to a canonical name."""
1287
- s = raw.strip().rstrip(".")
1288
- # Remove common OCR artefacts
1289
- s = re.sub(r"\s+", " ", s)
1290
- key = s.lower().strip()
1291
-
1292
- # Direct lookup (most reliable)
1293
- if key in SUBJECT_NORM_MAP:
1294
- return SUBJECT_NORM_MAP[key]
1295
-
1296
- # Partial match — try removing trailing qualifiers like "(STANDARD)", "CORE"
1297
- for pat in (r"\s*\(.*?\)$", r"\s*(core|elective|standard|basic|advanced)$"):
1298
- stripped = re.sub(pat, "", key, flags=re.I).strip()
1299
- if stripped in SUBJECT_NORM_MAP:
1300
- return SUBJECT_NORM_MAP[stripped]
1301
-
1302
- # First significant word capitalised (fallback)
1303
- return s.title()
1304
-
1305
-
1306
- def _parse_cbse_subject_rows(text: str) -> list[dict[str, Any]]:
1307
- """
1308
- Parse CBSE subject table rows from OCR plain text.
1309
-
1310
- Recognises these formats (all from real CBSE marksheets):
1311
- "184 ENGLISH LNG & LIT. 073 020 093 A1"
1312
- "085 HINDI COURSE-B 075 020 095"
1313
- "041 MATHS 063 020 083"
1314
- "086 SCIENCE 65 20 85" (leading zero dropped by OCR)
1315
- "Social Science 077" (code missing, name + total only)
1316
-
1317
- Strategy:
1318
- 1. Try full pattern: 3-digit-code SUBJECT_NAME N1 N2 N3 [GRADE]
1319
- where total = N3 (or the largest of N1..N3)
1320
- 2. Try code-only: 3-digit-code SUBJECT_NAME TOTAL
1321
- 3. Try name-only: SUBJECT_NAME TOTAL
1322
- """
1323
- rows: list[dict[str, Any]] = []
1324
- seen_codes: set[str] = set()
1325
- seen_names: set[str] = set()
1326
-
1327
- lines = text.split("\n")
1328
-
1329
- # ── Pattern 1: CODE SUBJECT N N N [GRADE] ───────────────────────────────
1330
- # Matches: 3-digit code, subject words (may include & . -), 2-3 numbers, optional grade
1331
- # Subject name: letters, spaces, &, ., (, ), hyphen — NO digits.
1332
- # Must use greedy +? (not {1,N?}) — the min-bound lazy form fails backtracking
1333
- # when \s is in both the char class and the separator.
1334
- # Marks use \d{2,3} (zero-padded CBSE format: 073, 020, 093).
1335
- PAT_FULL = re.compile(
1336
- r"(\d{3})" # subject code (3 digits)
1337
- r"\s+"
1338
- r"([A-Z][A-Z\s&.()\-]+?)" # subject name — greedy-lazy +?
1339
- r"\s+"
1340
- r"(\d{2,3})" # theory marks
1341
- r"\s+"
1342
- r"(\d{2,3})" # practical marks
1343
- r"\s+"
1344
- r"(\d{2,3})" # total marks
1345
- r"(?:\s+([A-E][1-2]?))?", # optional CBSE grade
1346
- re.I,
1347
- )
1348
- # ── Pattern 2: CODE SUBJECT TOTAL [GRADE] (no theory/practical split) ───
1349
- PAT_CODE_SHORT = re.compile(
1350
- r"(\d{3})"
1351
- r"\s+"
1352
- r"([A-Z][A-Z\s&.()\-]+?)"
1353
- r"\s+"
1354
- r"(\d{2,3})"
1355
- r"(?:\s+([A-E][1-2]?))?",
1356
- re.I,
1357
- )
1358
-
1359
- for line in lines:
1360
- line = line.strip()
1361
- if len(line) < 8:
1362
- continue
1363
-
1364
- m = PAT_FULL.search(line)
1365
- if m:
1366
- code = m.group(1).strip()
1367
- raw_name = m.group(2).strip()
1368
- n1, n2, n3 = int(m.group(3)), int(m.group(4)), int(m.group(5))
1369
- grade_raw = (m.group(6) or "").strip().upper()
1370
-
1371
- # N3 is total; N1+N2 should equal N3 (validate)
1372
- # Handle OCR transpositions: pick the column that equals n1+n2
1373
- theory = practical = total = 0
1374
- if 0 <= n1 <= 100 and 0 <= n2 <= 100:
1375
- expected_total = n1 + n2
1376
- if abs(n3 - expected_total) <= 2:
1377
- theory, practical, total = n1, n2, n3
1378
- else:
1379
- # Try other orderings
1380
- if abs(n1 - (n2 + n3)) <= 2 and n2 <= 30:
1381
- theory, practical, total = n2, n3, n1
1382
- elif abs(n2 - (n1 + n3)) <= 2 and n3 <= 30:
1383
- theory, practical, total = n1, n3, n2
1384
- else:
1385
- # Cannot verify; use n3 as total (last column)
1386
- theory, practical, total = n1, n2, n3
1387
- else:
1388
- theory, practical, total = n1, n2, n3
1389
-
1390
- if not (0 <= total <= 100):
1391
- continue
1392
-
1393
- if code in seen_codes:
1394
- continue
1395
-
1396
- # Resolve subject name: code lookup first, then normalization
1397
- name = CBSE_CODE_MAP.get(code) or _normalize_subject_name(raw_name)
1398
- if name.lower() in seen_names:
1399
- continue
1400
-
1401
- grade = grade_raw if grade_raw else _cbse_grade(total)
1402
- rows.append({
1403
- "code": code,
1404
- "name": name,
1405
- "theory": theory,
1406
- "practical": practical,
1407
- "marks": total,
1408
- "grade": grade,
1409
- })
1410
- seen_codes.add(code)
1411
- seen_names.add(name.lower())
1412
- continue
1413
-
1414
- m = PAT_CODE_SHORT.search(line)
1415
- if m:
1416
- code = m.group(1).strip()
1417
- raw_name = m.group(2).strip()
1418
- total = int(m.group(3))
1419
- grade_raw = (m.group(4) or "").strip().upper()
1420
-
1421
- if not (0 <= total <= 100):
1422
- continue
1423
- if code in seen_codes:
1424
- continue
1425
-
1426
- name = CBSE_CODE_MAP.get(code) or _normalize_subject_name(raw_name)
1427
- if name.lower() in seen_names:
1428
- continue
1429
-
1430
- grade = grade_raw if grade_raw else _cbse_grade(total)
1431
- rows.append({
1432
- "code": code,
1433
- "name": name,
1434
- "theory": None,
1435
- "practical": None,
1436
- "marks": total,
1437
- "grade": grade,
1438
- })
1439
- seen_codes.add(code)
1440
- seen_names.add(name.lower())
1441
-
1442
- return rows
1443
-
1444
-
1445
- def _parse_cbse_name_only_rows(text: str, existing_names: set[str]) -> list[dict[str, Any]]:
1446
- """
1447
- Fallback: extract subject rows when the CBSE code column is absent.
1448
- Format: SUBJECT_NAME TOTAL [GRADE]
1449
- Used when OCR drops the leading code or when marks appear without codes.
1450
- """
1451
- rows: list[dict[str, Any]] = []
1452
- KNOWN_SUBJECTS = list(SUBJECT_NORM_MAP.keys()) + [
1453
- "english", "hindi", "mathematics", "maths", "science",
1454
- "social science", "physics", "chemistry", "biology",
1455
- "computer science", "economics", "history", "geography",
1456
- "political science", "accountancy", "business studies",
1457
- "physical education", "informatics practices",
1458
- ]
1459
-
1460
- for sub in KNOWN_SUBJECTS:
1461
- if sub.lower() in existing_names:
1462
- continue
1463
- # Match: subject_name marks [grade]
1464
- pat = (
1465
- r"(?i)(?<!\w)" + re.escape(sub) + r"(?!\w)"
1466
- r"[\s:–\-]+"
1467
- r"(\d{2,3})"
1468
- r"(?:\s+([A-E][1-2]?))?"
1469
- )
1470
- m = re.search(pat, text, re.I)
1471
- if m:
1472
- total = int(m.group(1))
1473
- if not (20 <= total <= 100): # sanity: marks < 20 likely a code artefact
1474
- continue
1475
- grade_raw = (m.group(2) or "").strip().upper()
1476
- name = _normalize_subject_name(sub)
1477
- if name.lower() in existing_names:
1478
- continue
1479
- grade = grade_raw if grade_raw else _cbse_grade(total)
1480
- rows.append({
1481
- "code": None,
1482
- "name": name,
1483
- "theory": None,
1484
- "practical": None,
1485
- "marks": total,
1486
- "grade": grade,
1487
- })
1488
- existing_names.add(name.lower())
1489
- return rows
1490
-
1491
-
1492
- def _entities_marksheet(
1493
- text: str, ocr_result: Any = None
1494
- ) -> dict[str, Any]:
1495
- """
1496
- Dedicated CBSE / board marksheet extractor.
1497
-
1498
- Pass 1: Parse the CBSE subject table (3-digit code rows).
1499
- Pass 2: Fallback name-only scan for any missed subjects.
1500
- Then: extract header fields, calculate totals independently.
1501
- """
1502
- entities: dict[str, Any] = {}
1503
-
1504
- # ── Student name ──────────────────────────────────────────────────────────
1505
- for pat in [
1506
- r"(?:student['\s]*s?\s*name|candidate\s*name|name\s*of\s*(?:the\s*)?(?:student|candidate))[\s:]*([A-Z][A-Z\s.]{2,40})",
1507
- r"(?:name)[\s:]+([A-Z][A-Z\s.]{2,35})\b",
1508
- ]:
1509
- m = re.search(pat, text, re.I)
1510
- if m:
1511
- name = m.group(1).strip()
1512
- # Reject obvious non-names
1513
- if not any(kw in name.lower() for kw in ("school", "board", "cbse", "icse", "result")):
1514
- entities["studentName"] = name
1515
- break
1516
-
1517
- # ── Roll number ───────────────────────────────────────────────────────────
1518
- for pat in [
1519
- r"(?:roll\s*(?:no\.?|number|num\.?)|enrollment\s*(?:no\.?|number))[\s:.#]*([A-Z0-9\-]{5,15})",
1520
- r"roll[\s:]*(\d{6,12})",
1521
- ]:
1522
- m = re.search(pat, text, re.I)
1523
- if m:
1524
- entities["rollNumber"] = m.group(1).strip()
1525
- break
1526
-
1527
- # ── Date of birth ─────────────────────────────────────────────────────────
1528
- m = re.search(
1529
- r"(?:d\.?o\.?b\.?|date\s+of\s+birth)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
1530
- text, re.I,
1531
- )
1532
- if m:
1533
- entities["dob"] = m.group(1).strip()
1534
-
1535
- # ── Parent names ──────────────────────────────────────────────────────────
1536
- m = re.search(r"(?:father['\s]*s?\s*name|father)[\s:]+([A-Z][A-Z\s.]{2,40})", text, re.I)
1537
- if m:
1538
- val = m.group(1).strip()
1539
- if not any(kw in val.lower() for kw in ("school", "board", "roll", "date")):
1540
- entities["fatherName"] = val
1541
-
1542
- m = re.search(r"(?:mother['\s]*s?\s*name|mother)[\s:]+([A-Z][A-Z\s.]{2,40})", text, re.I)
1543
- if m:
1544
- val = m.group(1).strip()
1545
- if not any(kw in val.lower() for kw in ("school", "board", "roll", "date")):
1546
- entities["motherName"] = val
1547
-
1548
- # ── School / board ────────────────────────────────────────────────────────
1549
- m = re.search(r"(?:school|institution)[\s:]+([A-Z][A-Za-z0-9\s,.-]{3,60})", text, re.I)
1550
- if m:
1551
- entities["school"] = m.group(1).strip()
1552
-
1553
- m = re.search(r"(CBSE|ICSE|ISC|IGCSE|NIOS|state\s+board)", text, re.I)
1554
- if m:
1555
- entities["board"] = m.group(1).upper().strip()
1556
-
1557
- # ── Exam year ─────────────────────────────────────────────────────────────
1558
- m = re.search(r"(?:year|session|batch|exam\s*year)[\s:]*(\d{4}(?:[/-]\d{2,4})?)", text, re.I)
1559
- if m:
1560
- entities["year"] = m.group(1).strip()
1561
-
1562
- # ── Class / grade level ───────────────────────────────────────────────────
1563
- m = re.search(r"(?:class|grade|std)[\s:.]*(\d{1,2}|[Xx]{1,3}|XII|XI|X|IX|VIII)", text, re.I)
1564
- if m:
1565
- entities["class"] = m.group(1).strip().upper()
1566
-
1567
- # ── Subject table — CBSE code rows ───────────────────────────────────────
1568
- subject_rows = _parse_cbse_subject_rows(text)
1569
-
1570
- # ── Subject table — name-only fallback ────────────────────────────────────
1571
- existing_names = {row["name"].lower() for row in subject_rows}
1572
- fallback_rows = _parse_cbse_name_only_rows(text, existing_names)
1573
- subject_rows.extend(fallback_rows)
1574
-
1575
- if subject_rows:
1576
- entities["subjects"] = subject_rows
1577
-
1578
- # ── Independent calculation (never trust OCR totals) ─────────────────
1579
- marks_list = [r["marks"] for r in subject_rows]
1580
- total = sum(marks_list)
1581
- max_marks = len(subject_rows) * 100
1582
- percentage = round(total / max_marks * 100, 2) if max_marks else 0.0
1583
-
1584
- entities["totalMarks"] = total
1585
- entities["maxMarks"] = max_marks
1586
- entities["percentage"] = percentage
1587
- entities["subjectCount"] = len(subject_rows)
1588
- entities["highestMark"] = max(marks_list)
1589
- entities["lowestMark"] = min(marks_list)
1590
-
1591
- # Grade distribution
1592
- grade_dist: dict[str, int] = {}
1593
- for row in subject_rows:
1594
- g = row.get("grade", "?")
1595
- grade_dist[g] = grade_dist.get(g, 0) + 1
1596
- entities["gradeDistribution"] = grade_dist
1597
-
1598
- # Result: PASS if no subject has marks < 33 (CBSE passing threshold)
1599
- all_pass = all(r["marks"] >= 33 for r in subject_rows)
1600
- entities["result"] = "PASS" if all_pass else "FAIL"
1601
-
1602
- # ── Overall result from OCR text ─────────────────────────────────────────
1603
- m = re.search(r"\b(PASS|FAIL|PASSED|FAILED|COMPARTMENT)\b", text, re.I)
1604
- if m:
1605
- result_txt = m.group(1).upper().strip()
1606
- if result_txt in ("PASSED",):
1607
- result_txt = "PASS"
1608
- elif result_txt in ("FAILED",):
1609
- result_txt = "FAIL"
1610
- entities["result"] = result_txt
1611
-
1612
- # ── Explicitly printed percentage (cross-check) ───────────────────────────
1613
- m = re.search(
1614
- r"(?:percentage|aggregate|overall|total\s+%)[\s:]*(\d{1,3}(?:\.\d{1,2})?)\s*%?",
1615
- text, re.I,
1616
- )
1617
- if m:
1618
- printed_pct = float(m.group(1))
1619
- # Only override if calculated percentage is absent or very different
1620
- if "percentage" not in entities or abs(printed_pct - entities.get("percentage", 0)) < 5:
1621
- entities["percentage"] = printed_pct
1622
-
1623
- return entities
1624
-
1625
-
1626
- # ═════════════════════════════════════════════════════════════════════════════
1627
- # Invoice extractor
1628
- # ═════════════════════════════════════════════════════════════════════════════
1629
- def _entities_invoice(text: str) -> dict[str, Any]:
1630
- entities: dict[str, Any] = {}
1631
-
1632
- m = re.search(r"invoice\s*(?:no\.?|number|#)[\s:]*([A-Z0-9\-/]{3,30})", text, re.I)
1633
- if m: entities["invoiceNumber"] = m.group(1).strip()
1634
-
1635
- m = re.search(r"(?:invoice\s*date|date)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1636
- if m: entities["invoiceDate"] = m.group(1).strip()
1637
-
1638
- m = re.search(r"due\s*date[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1639
- if m: entities["dueDate"] = m.group(1).strip()
1640
-
1641
- m = re.search(r"(?:bill\s*to|sold\s*to|customer)[\s:]+([A-Z][A-Za-z0-9\s,.-]{2,50})", text, re.I)
1642
- if m: entities["billTo"] = m.group(1).strip()[:80]
1643
-
1644
- m = re.search(
1645
- r"(?:total|grand\s*total|amount\s*due|net\s*payable)[\s:]*"
1646
- r"(?:rs\.?|inr|usd|\$|€|£)?[\s]*(\d[\d,]*(?:\.\d{1,2})?)",
1647
- text, re.I,
1648
- )
1649
- if m: entities["totalAmount"] = m.group(1).replace(",", "")
1650
-
1651
- m = re.search(r"(?:gstin|gst\s*no)[\s:]*([A-Z0-9]{15})", text, re.I)
1652
- if m: entities["gstin"] = m.group(1).strip()
1653
-
1654
- return entities
1655
-
1656
-
1657
- # ═════════════════════════════════════════════════════════════════════════════
1658
- # Form extractor
1659
- # ═════════════════════════════════════════════════════════════════════════════
1660
- def _entities_form(text: str) -> dict[str, Any]:
1661
- entities: dict[str, Any] = {}
1662
- for field, patterns in [
1663
- ("name", [r"(?:name|applicant)[\s:]+([A-Z][A-Za-z\s.]{2,40})"]),
1664
- ("dob", [r"(?:d\.?o\.?b\.?|date\s+of\s+birth)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})"]),
1665
- ("gender", [r"(?:gender|sex)[\s:]*(\bMale\b|\bFemale\b|\bOther\b)"]),
1666
- ("phone", [r"(?:phone|mobile|contact)[\s:]*(\+?\d[\d\s\-]{8,15})"]),
1667
- ("email", [r"([\w.+-]+@[\w-]+\.[\w.]{2,})"]),
1668
- ]:
1669
- for pat in patterns:
1670
- m = re.search(pat, text, re.I)
1671
- if m:
1672
- entities[field] = m.group(1).strip()
1673
- break
1674
- return entities
1675
-
1676
-
1677
- # ═════════════════════════════════════════════════════════════════════════════
1678
- # Certificate extractor
1679
- # ═════════════════════════════════════════════════════════════════════════════
1680
- def _entities_certificate(text: str) -> dict[str, Any]:
1681
- entities: dict[str, Any] = {}
1682
- m = re.search(
1683
- r"(?:awarded\s*to|presented\s*to|certify\s*that)[\s:]+([A-Z][A-Za-z\s.]{2,40})", text, re.I,
1684
- )
1685
- if m: entities["recipientName"] = m.group(1).strip()
1686
-
1687
- m = re.search(r"(?:certificate\s*(?:no|number|id))[\s:]*([A-Z0-9\-]{3,20})", text, re.I)
1688
- if m: entities["certificateId"] = m.group(1).strip()
1689
-
1690
- m = re.search(r"(?:date|issued\s*on)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1691
- if m: entities["issueDate"] = m.group(1).strip()
1692
-
1693
- m = re.search(r"(?:course|program|event|competition)[\s:]+([A-Z][A-Za-z0-9\s&,-]{2,60})", text, re.I)
1694
- if m: entities["courseOrEvent"] = m.group(1).strip()[:60]
1695
-
1696
- return entities
1697
-
1698
-
1699
- # ═════════════════════════════════════════════════════════════════════════════
1700
- # ID card extractor
1701
- # ═════════════════════════════════════════════════════════════════════════════
1702
- def _entities_id_card(text: str) -> dict[str, Any]:
1703
- entities: dict[str, Any] = {}
1704
- m = re.search(r"(?:name)[\s:]+([A-Z][A-Za-z\s.]{2,40})", text, re.I)
1705
- if m: entities["name"] = m.group(1).strip()
1706
-
1707
- m = re.search(r"(?:employee|student|id|membership)\s*(?:no\.?|number|#|id)[\s:]*([A-Z0-9\-]{3,20})", text, re.I)
1708
- if m: entities["idNumber"] = m.group(1).strip()
1709
-
1710
- m = re.search(r"(?:d\.?o\.?b\.?|date\s+of\s+birth)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1711
- if m: entities["dob"] = m.group(1).strip()
1712
-
1713
- m = re.search(r"(?:valid\s*(?:till|until|upto)|expiry)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1714
- if m: entities["validTill"] = m.group(1).strip()
1715
-
1716
- return entities
1717
-
1718
-
1719
- # ═════════════════════════════════════════════════════════════════════════════
1720
- # Generic extractor (unknown document types)
1721
- # ════════════════════════════════════════════════════════════════��════════════
1722
- def _entities_generic(text: str) -> dict[str, Any]:
1723
- entities: dict[str, Any] = {}
1724
- for m in re.finditer(r"^([A-Za-z][A-Za-z\s]{1,30})[\s:–]+([^\n]{1,80})$", text, re.M):
1725
- key = m.group(1).strip().lower().replace(" ", "_")
1726
- val = m.group(2).strip()
1727
- if 3 <= len(val) <= 80 and not val.endswith(":") and key not in entities:
1728
- entities[key] = val
1729
- if len(entities) >= 20:
1730
- break
1731
- return entities
1732
-
1733
-
1734
- # ═════════════════════════════════════════════════════════════════════════════
1735
- # Validation engine
1736
- # ═════════════════════════════════════════════════════════════════════════════
1737
- def _validate_entities(entities: dict[str, Any], doc_type: str) -> dict[str, Any]:
1738
- """
1739
- Validate extracted entities against the document template.
1740
- Returns a validation report with pass/fail, found/missing fields,
1741
- warnings, and a 0-1 completeness score.
1742
- """
1743
- template = DOC_TEMPLATES.get(doc_type, {})
1744
- required = template.get("required", [])
1745
- optional = template.get("optional", [])
1746
- all_fields = required + optional
1747
-
1748
- fields_found: list[str] = []
1749
- fields_missing: list[str] = []
1750
- warnings: list[str] = []
1751
-
1752
- for field in required:
1753
- if field in entities and entities[field]:
1754
- fields_found.append(field)
1755
- else:
1756
- fields_missing.append(field)
1757
-
1758
- for field in optional:
1759
- if field in entities and entities[field]:
1760
- fields_found.append(field)
1761
-
1762
- # Doc-type specific validation
1763
- if doc_type == "marksheet":
1764
- subjects = entities.get("subjects", [])
1765
- sub_count = len(subjects)
1766
- entities["subjectCount"] = sub_count
1767
-
1768
- min_subs = template.get("min_subjects", 1)
1769
- expected_subs = template.get("expected_subjects", 5)
1770
-
1771
- if sub_count == 0:
1772
- fields_missing.append("subjects")
1773
- warnings.append("No subjects extracted. OCR text may not contain CBSE subject table rows.")
1774
- elif sub_count < min_subs:
1775
- warnings.append(f"Only {sub_count} subject(s) found; expected ≥ {expected_subs}.")
1776
- elif sub_count < expected_subs:
1777
- warnings.append(f"Only {sub_count}/{expected_subs} subjects found. Remaining rows may have OCR noise.")
1778
-
1779
- # Validate totals if present
1780
- if sub_count > 0 and "totalMarks" in entities:
1781
- computed_total = sum(r["marks"] for r in subjects)
1782
- if abs(computed_total - entities["totalMarks"]) > 1:
1783
- warnings.append(
1784
- f"Computed total {computed_total} ≠ extracted total {entities['totalMarks']}. "
1785
- f"OCR printed-total ignored; using computed value."
1786
- )
1787
- entities["totalMarks"] = computed_total
1788
-
1789
- elif doc_type == "invoice":
1790
- if "totalAmount" in entities:
1791
- try:
1792
- float(str(entities["totalAmount"]).replace(",", ""))
1793
- except ValueError:
1794
- warnings.append(f"totalAmount '{entities['totalAmount']}' is not numeric.")
1795
-
1796
- # Compute entity completeness score (0-1)
1797
- if not all_fields:
1798
- completeness = 1.0
1799
- else:
1800
- req_w = 0.7 * len(required)
1801
- opt_w = 0.3 * len(optional)
1802
- req_ok = 0.7 * sum(1 for f in required if f in fields_found)
1803
- opt_ok = 0.3 * sum(1 for f in optional if f in fields_found and f in entities)
1804
- completeness = (req_ok + opt_ok) / max(1, req_w + opt_w)
1805
-
1806
- # Validation passes if all required fields found
1807
- passed = len(fields_missing) == 0
1808
-
1809
- # Score: 1.0 if all required found + warnings weighted down
1810
- val_score = completeness * (1.0 - 0.05 * min(len(warnings), 4))
1811
-
1812
- return {
1813
- "passed": passed,
1814
- "score": round(max(0.0, val_score), 4),
1815
- "entityCompleteness": round(completeness, 4),
1816
- "fieldsFound": fields_found,
1817
- "fieldsMissing": fields_missing,
1818
- "warnings": warnings,
1819
- "subjectCount": entities.get("subjectCount", 0) if doc_type == "marksheet" else None,
1820
- }
1821
-
1822
-
1823
- # ═════════════════════════════════════════════════════════════════════════════
1824
- # Document summary generator
1825
- # ═════════════════════════════════════════════════════════════════════════════
1826
- def _build_document_summary(
1827
- entities: dict[str, Any],
1828
- doc_type: str,
1829
- validation: dict[str, Any],
1830
- ) -> str:
1831
- """
1832
- One-line human-readable summary of the extracted document.
1833
- Sent to AI before raw text — reduces hallucinations dramatically.
1834
- """
1835
- if doc_type == "marksheet":
1836
- name = entities.get("studentName", "Unknown")
1837
- roll = entities.get("rollNumber", "?")
1838
- subs = entities.get("subjects", [])
1839
- total = entities.get("totalMarks", "?")
1840
- max_m = entities.get("maxMarks", "?")
1841
- pct = entities.get("percentage", "?")
1842
- result = entities.get("result", "?")
1843
- board = entities.get("board", "")
1844
- board_str = f" ({board})" if board else ""
1845
- return (
1846
- f"{board_str.strip() or 'Board'} marksheet for {name} (Roll: {roll}). "
1847
- f"{len(subs)} subject(s) extracted. "
1848
- f"Total {total}/{max_m} ({pct}%). Result: {result}."
1849
- )
1850
-
1851
- if doc_type == "invoice":
1852
- inv_no = entities.get("invoiceNumber", "?")
1853
- amount = entities.get("totalAmount", "?")
1854
- bill_to = entities.get("billTo", "?")
1855
- return f"Invoice #{inv_no} for {bill_to}. Total: {amount}."
1856
-
1857
- if doc_type == "certificate":
1858
- name = entities.get("recipientName", "Unknown")
1859
- course = entities.get("courseOrEvent", "")
1860
- issued = entities.get("issueDate", "")
1861
- course_str = f" for {course}" if course else ""
1862
- issued_str = f" (issued {issued})" if issued else ""
1863
- return f"Certificate awarded to {name}{course_str}{issued_str}."
1864
-
1865
- if doc_type == "form":
1866
- name = entities.get("name", "Unknown")
1867
- return f"Form submitted by {name}."
1868
-
1869
- missing = validation.get("fieldsMissing", [])
1870
- found = validation.get("fieldsFound", [])
1871
- return (
1872
- f"{doc_type.title()} document. "
1873
- f"{len(found)} field(s) extracted. "
1874
- + (f"Missing: {', '.join(missing)}." if missing else "")
1875
- )
1876
-
1877
-
1878
- # ═════════════════════════════════════════════════════════════════════════════
1879
- # Utility helpers
1880
- # ═════════════════════════════════════════════════════════════════════════════
1881
- def _sanitize_filename(name: str) -> str:
1882
- name = os.path.basename(name)
1883
- name = re.sub(r"[^\w.\-]", "_", name)
1884
- return name[:200] or "upload"
1885
-
1886
-
1887
- def _decode_image_to_bgr(raw: bytes, ext: str) -> "np.ndarray":
1888
- import cv2
1889
- if ext in {"heic", "heif"}:
1890
- try:
1891
- from pillow_heif import register_heif_opener
1892
- register_heif_opener()
1893
- except ImportError:
1894
- raise _err("decode", "HEIF_NOT_SUPPORTED", "HEIC/HEIF requires pillow-heif.", 415,
1895
- recommendation="Add pillow-heif to Dockerfile Layer 1.")
1896
- try:
1897
- pil_img = Image.open(io.BytesIO(raw)).convert("RGB")
1898
- buf = io.BytesIO()
1899
- pil_img.save(buf, format="PNG")
1900
- raw = buf.getvalue()
1901
- except Exception as exc:
1902
- raise _err("decode", "HEIF_DECODE_FAILED", f"HEIF decode error: {exc}") from exc
1903
-
1904
- arr = np.frombuffer(raw, np.uint8)
1905
- img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
1906
- if img is None:
1907
- try:
1908
- pil_img = Image.open(io.BytesIO(raw)).convert("RGB")
1909
- img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
1910
- except Exception as exc:
1911
- raise _err("decode", "IMAGE_DECODE_FAILED",
1912
- f"Could not decode image: {exc}", 422,
1913
- root_cause=str(exc),
1914
- recommendation="Ensure the file is a valid, non-corrupted image.") from exc
1915
- return img
1916
-
1917
-
1918
- def _convert_to_png(raw: bytes, ext: str) -> bytes:
1919
- if ext in {"heic", "heif"}:
1920
- try:
1921
- from pillow_heif import register_heif_opener
1922
- register_heif_opener()
1923
- except ImportError:
1924
- raise _err("decode", "HEIF_NOT_SUPPORTED", "HEIC/HEIF requires pillow-heif.", 415)
1925
- try:
1926
- img = Image.open(io.BytesIO(raw)).convert("RGB")
1927
- buf = io.BytesIO()
1928
- img.save(buf, format="PNG")
1929
- return buf.getvalue()
1930
- except Exception as exc:
1931
- raise _err("decode", "IMAGE_DECODE_FAILED",
1932
- f"Pillow could not open image: {exc}", 422) from exc
1933
-
1934
-
1935
- def _markdown_to_plain(markdown: str) -> str:
1936
- text = re.sub(r"!\[.*?\]\(.*?\)", "", markdown)
1937
- text = re.sub(r"\[([^\]]+)\]\([^\)]+\)", r"\1", text)
1938
- text = re.sub(r"#{1,6}\s*", "", text)
1939
- text = re.sub(r"\*{1,2}([^*]+)\*{1,2}", r"\1", text)
1940
- text = re.sub(r"`{1,3}[^`]*`{1,3}", "", text)
1941
- text = re.sub(r"\|", " ", text)
1942
- text = re.sub(r"-{3,}", "", text)
1943
- text = re.sub(r"\n{3,}", "\n\n", text)
1944
- return text.strip()
1945
-
1946
-
1947
- def _pdf_page_count(raw: bytes) -> int:
1948
- try:
1949
- doc = fitz.open(stream=raw, filetype="pdf")
1950
- count = doc.page_count
1951
- doc.close()
1952
- return count
1953
- except Exception:
1954
- return 0
1955
-
1956
-
1957
- def _safe_content_list(pipe_result: Any, images_dir: str) -> list[dict]:
1958
- try:
1959
- return pipe_result.get_content_list(images_dir) or []
1960
- except Exception:
1961
- return []
1962
-
1963
-
1964
- def _count_images(content_list: list[dict]) -> int:
1965
- return sum(1 for item in content_list if item.get("type") == "image")
1966
-
1967
-
1968
- def _count_tables(content_list: list[dict]) -> int:
1969
- return sum(1 for item in content_list if item.get("type") == "table")
1970
-
1971
-
1972
- def _count_formulas(content_list: list[dict]) -> int:
1973
- return sum(1 for item in content_list
1974
- if item.get("type") in {"equation", "formula", "interline_equation"})
1975
-
1976
-
1977
- def _count_tables_in_text(text: str) -> int:
1978
- return len(re.findall(r"^\s*\|[-\s|]+\|\s*$", text, re.M))
1979
-
1980
-
1981
- def _mem_mb() -> tuple[int, int]:
1982
- try:
1983
- with open("/sys/fs/cgroup/memory.max") as f:
1984
- raw_max = f.read().strip()
1985
- if raw_max != "max":
1986
- limit_bytes = int(raw_max)
1987
- with open("/sys/fs/cgroup/memory.current") as f:
1988
- used_bytes = int(f.read().strip())
1989
- if limit_bytes > 0:
1990
- return used_bytes // (1024 * 1024), limit_bytes // (1024 * 1024)
1991
- except (FileNotFoundError, ValueError, OSError):
1992
- pass
1993
- try:
1994
- with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
1995
- limit_bytes = int(f.read().strip())
1996
- with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
1997
- used_bytes = int(f.read().strip())
1998
- if limit_bytes < 128 * 1024 * 1024 * 1024:
1999
- return used_bytes // (1024 * 1024), limit_bytes // (1024 * 1024)
2000
- except (FileNotFoundError, ValueError, OSError):
2001
- pass
2002
- try:
2003
- info: dict[str, int] = {}
2004
- with open("/proc/meminfo") as f:
2005
- for line in f:
2006
- parts = line.split()
2007
- if len(parts) >= 2:
2008
- info[parts[0].rstrip(":")] = int(parts[1])
2009
- total_kb = info.get("MemTotal", 0)
2010
- avail_kb = info.get("MemAvailable", 0)
2011
- return (total_kb - avail_kb) // 1024, total_kb // 1024
2012
- except Exception:
2013
- return 0, 0
2014
-
2015
-
2016
- def _assert_memory_safe(raw: bytes, ext: str) -> None:
2017
- used_mb, total_mb = _mem_mb()
2018
- if total_mb == 0:
2019
- return
2020
- available_mb = total_mb - used_mb
2021
- if ext in PDF_EXTENSIONS:
2022
- page_count = max(1, _pdf_page_count(raw))
2023
- estimated_mb = (page_count * BYTES_PER_OCR_PAGE) // (1024 * 1024)
2024
- else:
2025
- try:
2026
- if ext in {"heic", "heif"}:
2027
- try:
2028
- from pillow_heif import register_heif_opener
2029
- register_heif_opener()
2030
- except ImportError:
2031
- pass
2032
- img = Image.open(io.BytesIO(raw))
2033
- w, h = img.size
2034
- channels = len(img.getbands()) or 3
2035
- img.close()
2036
- estimated_mb = w * h * channels * IMAGE_MEMORY_FACTOR // (1024 * 1024)
2037
- except Exception:
2038
- estimated_mb = len(raw) * 20 // (1024 * 1024)
2039
-
2040
- free_after = available_mb - estimated_mb
2041
- logger.info("Memory check: avail=%d MB est=%d MB free_after=%d MB",
2042
- available_mb, estimated_mb, free_after)
2043
- if free_after < MEM_SAFETY_FLOOR_MB:
2044
- raise _err(
2045
- "validation", "LOW_MEMORY",
2046
- f"Insufficient memory. Available: {available_mb} MB, "
2047
- f"Estimated needed: {estimated_mb} MB.", 507,
2048
- root_cause=f"Container has {available_mb} MB; pipeline needs ~{estimated_mb} MB.",
2049
- recommendation="Wait for active requests to complete, or use a smaller file.",
2050
- )
2051
-
2052
-
2053
- def _mineru_version() -> str:
2054
- for pkg in ("magic-pdf", "mineru"):
2055
- try:
2056
- return pkg_version(pkg)
2057
- except Exception:
2058
- continue
2059
- return "unknown"
2060
-
2061
-
2062
- def _load_config_safe() -> dict[str, Any]:
2063
- try:
2064
- import json
2065
- with open(os.path.expanduser("~/magic-pdf.json")) as f:
2066
- return json.load(f)
2067
- except Exception:
2068
- return {}