crazylemonade commited on
Commit
26833f2
Β·
verified Β·
1 Parent(s): 44aba5e

Upload 7 files

Browse files
Files changed (7) hide show
  1. Dockerfile +163 -0
  2. README.md +267 -0
  3. download_models.py +185 -0
  4. entrypoint.sh +40 -0
  5. main.py +1608 -0
  6. requirements.txt +54 -0
  7. validate.py +633 -0
Dockerfile ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─────────────────────────────────────────────────────────────────────────────
2
+ # MinerU OCR Service β€” Hugging Face Docker Space (CPU / pipeline backend)
3
+ #
4
+ # Optimized for FREE tier: 2 vCPU Β· 16 GB RAM Β· 50 GB Disk Β· No GPU
5
+ #
6
+ # ── OCR ROUTING ARCHITECTURE ──────────────────────────────────────────────────
7
+ #
8
+ # FAST PATH (images: jpg/png/webp/bmp/heic/etc)
9
+ # rapidocr-onnxruntime β‰₯ 1.3.22
10
+ # - Pure ONNX inference β€” no PaddleOCR / paddlepaddle needed
11
+ # - Models bundled in the pip wheel (~50 MB); no first-use download
12
+ # - Target latency: 1–5 s on CPU
13
+ # Multi-pass: if RapidOCR confidence < 0.65 β†’ MinerU fallback automatically
14
+ #
15
+ # HEAVY PATH (PDFs, multi-page, forms with layout)
16
+ # MinerU (magic-pdf pipeline backend)
17
+ # - Layout detection (doclayout_yolo)
18
+ # - OCR (paddleocr2pytorch β€” PyTorch reimplementation bundled in wheel)
19
+ # - Markdown reconstruction
20
+ # - Target latency: 5–30 s on CPU
21
+ #
22
+ # ── ROOT CAUSE HISTORY ────────────────────────────────────────────────────────
23
+ #
24
+ # FAILURE 1: [full-cpu] is NOT a valid extra β†’ pip silently installs base only
25
+ # Fix: magic-pdf[full]==1.3.12
26
+ #
27
+ # FAILURE 2: opencv non-headless conflict
28
+ # Fix: Layer 4 force-reinstall of opencv-python-headless
29
+ #
30
+ # FAILURE 3: ch_PP-OCRv3_det_infer.pth not in HF repo (repo updated to v5)
31
+ # Fix: Layer 3.5 patches models_config.yml inside installed wheel:
32
+ # ch_PP-OCRv3_det β†’ ch_PP-OCRv5_det (all ch* langs)
33
+ # en_PP-OCRv3_det β†’ Multilingual_PP-OCRv3_det (en, latin)
34
+ # Arch safety: both replacement stems verified in arch_config.yaml
35
+ #
36
+ # ── System packages ────────────────────────────────────────────────────────────
37
+ # libgl1 β€” OpenCV needs libGL.so.1 for ALL image operations (not just GUI)
38
+ # libglib2.0-0 β€” GLib; required by OpenCV and many C extensions
39
+ # libgomp1 β€” OpenMP; required by ONNX Runtime and YOLO inference
40
+ # poppler-utils β€” pdfinfo/pdftoppm; used by MinerU PDF pre-processing
41
+ # ─────────────────────────────────────────────────────────────────────────────
42
+
43
+ FROM python:3.10-slim
44
+
45
+ ENV PYTHONUNBUFFERED=1
46
+ ENV PYTHONDONTWRITEBYTECODE=1
47
+ ENV PORT=7860
48
+ ENV MINERU_DEVICE_MODE=cpu
49
+ ENV MINERU_BACKEND=pipeline
50
+
51
+ # ── System dependencies ────────────────────────────────────────────────────────
52
+ RUN apt-get update \
53
+ && apt-get install -y --no-install-recommends \
54
+ libgl1 \
55
+ libglib2.0-0 \
56
+ libgomp1 \
57
+ poppler-utils \
58
+ && rm -rf /var/lib/apt/lists/*
59
+
60
+ WORKDIR /app
61
+
62
+ # ── Layer 1: FastAPI + lightweight runtime deps ───────────────────────────────
63
+ # rapidocr-onnxruntime: ONNX-based fast OCR engine; models bundled in wheel.
64
+ # - requires onnxruntime (will be auto-resolved or overridden by magic-pdf deps)
65
+ # - requires numpy, pyclipper, shapely β€” all covered by magic-pdf[full]
66
+ # - ~50 MB wheel; zero first-use model download needed
67
+ # opencv-python-headless: placeholder; will be force-reinstalled in Layer 4
68
+ RUN pip install --no-cache-dir --timeout 300 \
69
+ "fastapi>=0.115.0" \
70
+ "uvicorn[standard]>=0.32.0" \
71
+ "python-multipart>=0.0.12" \
72
+ "Pillow>=10.0.0" \
73
+ "pillow-heif>=0.18.0" \
74
+ "huggingface_hub>=0.25.0" \
75
+ "opencv-python-headless>=4.8.0" \
76
+ "rapidocr-onnxruntime>=1.3.22"
77
+
78
+ # ── Layer 2: CPU-only PyTorch β€” MUST precede magic-pdf ───────────────────────
79
+ # PyPI serves the CUDA-enabled torch wheel by default (~2.5 GB).
80
+ # Installing from the official CPU wheel index first causes pip to treat the
81
+ # already-installed CPU build as satisfying magic-pdf's torch requirement.
82
+ RUN pip install --no-cache-dir --timeout 600 \
83
+ --index-url https://download.pytorch.org/whl/cpu \
84
+ "torch>=2.2.2,!=2.5.0,!=2.5.1,<3" \
85
+ "torchvision>=0.15.2"
86
+
87
+ # ── Layer 3: magic-pdf with the CORRECT extras ────────────────────────────────
88
+ # [full] provides ultralytics, doclayout-yolo==0.0.2b1, rapid-table, shapely,
89
+ # pyclipper, omegaconf, matplotlib, ftfy, dill, PyYAML, openai, albumentations.
90
+ # doclayout-yolo==0.0.2b1 is ONLY on the myhloli index β€” not on PyPI.
91
+ # onnxruntime resolved automatically as transitive dep of rapid-table.
92
+ RUN pip install --no-cache-dir --timeout 600 \
93
+ --extra-index-url https://myhloli.github.io/wheels/ \
94
+ "magic-pdf[full]==1.3.12"
95
+
96
+ # ── Layer 3.5: Patch OCR model config ────────────────────────────────────────
97
+ # HF repo opendatalab/PDF-Extract-Kit-1.0 was updated to v5 det models.
98
+ # magic-pdf 1.3.12 models_config.yml still references v3 det files (absent).
99
+ # This patch runs at build time so download_models.py fetches correct files.
100
+ RUN python3 - <<'PYEOF'
101
+ import sys, yaml
102
+ from pathlib import Path
103
+ import magic_pdf
104
+
105
+ pkg = Path(magic_pdf.__file__).parent
106
+ cfg_path = pkg / 'model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/models_config.yml'
107
+ arch_path = pkg / 'model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/arch_config.yaml'
108
+
109
+ print(f"Patching: {cfg_path}")
110
+
111
+ with open(cfg_path) as f:
112
+ config = yaml.safe_load(f)
113
+ with open(arch_path) as f:
114
+ arch_text = f.read()
115
+
116
+ DET_MAP = {
117
+ 'ch_PP-OCRv3_det_infer.pth': 'ch_PP-OCRv5_det_infer.pth',
118
+ 'en_PP-OCRv3_det_infer.pth': 'Multilingual_PP-OCRv3_det_infer.pth',
119
+ }
120
+
121
+ patched = 0
122
+ for lang, files in config['lang'].items():
123
+ old = files.get('det', '')
124
+ if old in DET_MAP:
125
+ new = DET_MAP[old]
126
+ arch_key = new[:-4]
127
+ if (arch_key + ':') not in arch_text:
128
+ print(f"ERROR: arch key '{arch_key}' not found in arch_config.yaml", file=sys.stderr)
129
+ sys.exit(1)
130
+ files['det'] = new
131
+ print(f" [{lang}] det: {old} -> {new}")
132
+ patched += 1
133
+
134
+ with open(cfg_path, 'w') as f:
135
+ yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
136
+
137
+ print(f"Patched {patched} language entries. models_config.yml updated.")
138
+ PYEOF
139
+
140
+ # ── Layer 4: Restore headless OpenCV ─────────────────────────────────────────
141
+ # Layer 3 pulled opencv-python (non-headless) via doclayout-yolo/ultralytics/
142
+ # rapid-table. Force-reinstall headless build so cv2 works on this slim image.
143
+ RUN pip install --no-cache-dir --timeout 300 \
144
+ --force-reinstall \
145
+ "opencv-python-headless>=4.8.0"
146
+
147
+ # ── Application code ──────────────────────────────────────────────────────────
148
+ COPY download_models.py .
149
+ COPY validate.py .
150
+ COPY main.py .
151
+ COPY entrypoint.sh .
152
+ RUN chmod +x entrypoint.sh
153
+
154
+ # ── Download models at build time ─────────────────────────────────────────────
155
+ # MFR (formula recognition, ~1-2 GB) excluded β€” disabled in config.
156
+ # rapidocr-onnxruntime models are BUNDLED in the pip wheel; no download needed.
157
+ RUN python download_models.py
158
+
159
+ RUN mkdir -p /app/config && cp /root/magic-pdf.json /app/config/magic-pdf.json
160
+
161
+ # ── Runtime ───────────────────────────────────────────────────────────────────
162
+ EXPOSE 7860
163
+ ENTRYPOINT ["/app/entrypoint.sh"]
README.md ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: MinerU OCR Service
3
+ emoji: πŸ“„
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # MinerU OCR & Document Extraction Service β€” v2.0
12
+
13
+ Production OCR API with dual-path routing. Powered by **RapidOCR** (fast path) and **MinerU** (full pipeline), running on Hugging Face Docker Spaces β€” free CPU tier.
14
+
15
+ ---
16
+
17
+ ## Architecture
18
+
19
+ ```
20
+ Image file (jpg/png/webp/bmp/heic/heif/avif)
21
+ β”‚
22
+ β–Ό
23
+ Path A β€” RapidOCR (target: 1–5 s)
24
+ ONNX inference, CPU-optimised
25
+ Models bundled in pip wheel (~50 MB), no separate download
26
+ β”‚
27
+ β”œβ”€β”€ confidence β‰₯ 0.65 β†’ return result
28
+ β”‚
29
+ └── confidence < 0.65 β†’ MinerU fallback (Pass 2)
30
+
31
+ PDF file (or explicit escalation)
32
+ β”‚
33
+ β–Ό
34
+ Path B β€” MinerU pipeline (target: 5–20 s)
35
+ Layout detection (doclayout_yolo)
36
+ OCR (paddleocr2pytorch β€” PyTorch, bundled in magic-pdf wheel)
37
+ Markdown reconstruction
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Response Format (v2.0)
43
+
44
+ All successful responses include:
45
+
46
+ ```json
47
+ {
48
+ "success": true,
49
+ "filename": "marksheet.jpg",
50
+ "docType": "marksheet",
51
+ "pageCount": 1,
52
+ "confidence": 0.92,
53
+ "ocrEngine": "rapidocr",
54
+ "markdown": "...",
55
+ "plainText": "...",
56
+ "entities": {
57
+ "studentName": "Rahul Sharma",
58
+ "rollNumber": "23456789",
59
+ "dob": "15/03/2008",
60
+ "subjects": {
61
+ "English": 93,
62
+ "Hindi": 95,
63
+ "Mathematics": 83,
64
+ "Science": 85,
65
+ "Sst": 77
66
+ },
67
+ "totalMarks": 433,
68
+ "maxMarks": 500,
69
+ "percentage": 86.6,
70
+ "overallGrade": "A"
71
+ },
72
+ "timings": {
73
+ "uploadMs": 12,
74
+ "decodeMs": 18,
75
+ "classifyMs": 3,
76
+ "ocrDetMs": 180,
77
+ "ocrRecMs": 620,
78
+ "ocrTotalMs": 820,
79
+ "markdownMs": 45,
80
+ "totalMs": 898
81
+ },
82
+ "metadata": {
83
+ "parseMethod": "fast_ocr",
84
+ "backend": "rapidocr",
85
+ "cached": false,
86
+ "processingTimeMs": 898,
87
+ "passesUsed": 1,
88
+ "docTypeClassification": "marksheet",
89
+ "textBlocks": 24,
90
+ "tableCount": 1
91
+ }
92
+ }
93
+ ```
94
+
95
+ Error responses always include `errorCode`, `rootCause`, and `recommendation`:
96
+
97
+ ```json
98
+ {
99
+ "success": false,
100
+ "stage": "ocr",
101
+ "errorCode": "OCR_ENGINE_FAILED",
102
+ "rootCause": "...",
103
+ "recommendation": "...",
104
+ "message": "..."
105
+ }
106
+ ```
107
+
108
+ ---
109
+
110
+ ## Entity Extraction by Document Type
111
+
112
+ | Doc Type | Extracted Fields |
113
+ |---|---|
114
+ | `marksheet` | studentName, rollNumber, dob, school, year, subjects{}, totalMarks, maxMarks, percentage, overallGrade |
115
+ | `invoice` | invoiceNumber, invoiceDate, dueDate, billTo, totalAmount, gstin |
116
+ | `form` | name, dob, gender, phone, email |
117
+ | `certificate` | recipientName, certificateId, issueDate, courseOrEvent |
118
+ | `document` | key-value pairs (up to 20 fields, generic extraction) |
119
+
120
+ ---
121
+
122
+ ## Confidence Scoring
123
+
124
+ RapidOCR path β€” composite of three signals:
125
+
126
+ | Signal | Weight | Source |
127
+ |---|---|---|
128
+ | OCR engine block confidence | 40% | Mean of per-text-block scores from RapidOCR |
129
+ | Text density | 40% | Non-whitespace chars / total chars |
130
+ | Text coherence | 20% | Alpha chars / non-whitespace chars |
131
+
132
+ MinerU path β€” based on parse method + markdown quality:
133
+ - Base: `txt` mode = 0.95, `ocr` mode = 0.85
134
+ - Penalty: markdown < 100 chars β†’ βˆ’0.15
135
+ - Bonus: markdown contains tables β†’ +0.03
136
+
137
+ ---
138
+
139
+ ## Endpoints
140
+
141
+ | Method | Path | Purpose |
142
+ |---|---|---|
143
+ | `GET` | `/health` | Liveness β€” always 200 |
144
+ | `GET` | `/status` | Engine readiness, memory, cache, uptime |
145
+ | `GET` | `/warmup` | Pre-load both engines into RAM (call after deploy) |
146
+ | `GET` | `/diagnostics` | Model inventory, package versions, OCR config |
147
+ | `POST` | `/benchmark` | Benchmark RapidOCR on synthetic test image |
148
+ | `POST` | `/extract` | Single file extraction |
149
+ | `POST` | `/batch` | Up to 8 files, sequential |
150
+
151
+ ---
152
+
153
+ ## Performance Targets
154
+
155
+ | File type | Target | Acceptable | Unacceptable |
156
+ |---|---|---|---|
157
+ | Image (RapidOCR) | 1–5 s | < 10 s | > 15 s |
158
+ | PDF (MinerU, TXT) | 5–15 s | < 25 s | > 35 s |
159
+ | PDF (MinerU, scanned OCR) | 10–25 s | < 35 s | > 45 s |
160
+
161
+ ---
162
+
163
+ ## Dockerfile Layer Strategy
164
+
165
+ ```
166
+ Layer 1: fastapi, uvicorn, pillow, pillow-heif, huggingface_hub,
167
+ opencv-python-headless (placeholder),
168
+ rapidocr-onnxruntime ← NEW: bundled ONNX models, no extra download
169
+ ↓
170
+ Layer 2: torch + torchvision (CPU wheel β€” skips 2.5 GB CUDA default)
171
+ ↓
172
+ Layer 3: magic-pdf[full]==1.3.12 (doclayout-yolo from myhloli index)
173
+ ↓
174
+ Layer 3.5: patch models_config.yml in magic_pdf package
175
+ ch_PP-OCRv3_det β†’ ch_PP-OCRv5_det (all ch* langs)
176
+ en_PP-OCRv3_det β†’ Multilingual_PP-OCRv3_det (en, latin)
177
+ ↓
178
+ Layer 4: pip install --force-reinstall opencv-python-headless
179
+ ↓
180
+ App code + MinerU model download (MFR excluded, ~5 GB total)
181
+ ```
182
+
183
+ ---
184
+
185
+ ## OCR Root Cause History
186
+
187
+ | # | Error | Root Cause | Fix |
188
+ |---|---|---|---|
189
+ | 1 | `No module named 'ultralytics'` | `[full-cpu]` is not a valid extra; pip installs base only | Changed to `magic-pdf[full]==1.3.12` |
190
+ | 2 | `ImportError: cv2` at runtime | `doclayout-yolo` pulls non-headless `opencv-python`, breaks slim container | Layer 4 `--force-reinstall opencv-python-headless` |
191
+ | 3 | `ch_PP-OCRv3_det_infer.pth not found` | HF repo updated to v5 det; `models_config.yml` in wheel still says v3 | Layer 3.5 patches config; arch safety verified in `arch_config.yaml` |
192
+ | 4 | Quality unacceptable for images | MinerU full pipeline used for all files; 40+ s for a simple marksheet JPG | RapidOCR fast path for images (1–5 s), MinerU only for PDFs |
193
+
194
+ ---
195
+
196
+ ## Deployment
197
+
198
+ 1. Create a new Hugging Face Space β†’ **Docker** SDK
199
+ 2. Upload all files in this directory to the Space repo root
200
+ 3. First build: ~25–35 min (model download included)
201
+ 4. Call `/warmup` once after deploy to pre-load both engines
202
+
203
+ ```bash
204
+ # Health check
205
+ curl https://<your-space>.hf.space/health
206
+
207
+ # Warmup (do this once after deploy)
208
+ curl https://<your-space>.hf.space/warmup
209
+
210
+ # Benchmark (verify RapidOCR timing)
211
+ curl -X POST https://<your-space>.hf.space/benchmark
212
+
213
+ # Extract a marksheet
214
+ curl -X POST https://<your-space>.hf.space/extract -F "file=@marksheet.jpg"
215
+
216
+ # Diagnostics (model inventory + config)
217
+ curl https://<your-space>.hf.space/diagnostics
218
+ ```
219
+
220
+ ---
221
+
222
+ ## Validation Steps (post-deploy)
223
+
224
+ ```bash
225
+ # 1. Confirm RapidOCR is ready
226
+ curl https://<your-space>.hf.space/status | python3 -m json.tool
227
+
228
+ # 2. Run benchmark and check timing
229
+ curl -X POST https://<your-space>.hf.space/benchmark | python3 -m json.tool
230
+ # Expected: rapidocr.inferenceMs < 5000, status: "ok"
231
+
232
+ # 3. Extract a marksheet β€” verify entities and timing
233
+ curl -X POST https://<your-space>.hf.space/extract \
234
+ -F "file=@marksheet.jpg" | python3 -m json.tool
235
+ # Expected: ocrEngine="rapidocr", timings.totalMs < 10000
236
+ # Expected: entities.subjects populated, entities.percentage present
237
+
238
+ # 4. Extract a PDF
239
+ curl -X POST https://<your-space>.hf.space/extract \
240
+ -F "file=@document.pdf" | python3 -m json.tool
241
+ # Expected: ocrEngine="mineru", metadata.parseMethod in ["txt","ocr"]
242
+
243
+ # 5. Repeat upload (cache hit)
244
+ curl -X POST https://<your-space>.hf.space/extract \
245
+ -F "file=@marksheet.jpg" | python3 -m json.tool
246
+ # Expected: metadata.cached=true, timings.totalMs=0
247
+ ```
248
+
249
+ ---
250
+
251
+ ## Resource Budget (free CPU Basic)
252
+
253
+ | Resource | Budget | Usage |
254
+ |---|---|---|
255
+ | Disk | 50 GB | ~10–13 GB (packages ~5 GB + models ~5 GB) |
256
+ | RAM | 16 GB | RapidOCR: ~200 MB; MinerU models: ~4–6 GB at load |
257
+ | vCPU | 2 | Single uvicorn worker; sequential batch processing |
258
+
259
+ ---
260
+
261
+ ## Known Limitations
262
+
263
+ 1. **`en` language OCR** β€” `en_PP-OCRv4_rec_infer.pth` absent from HF repo. MinerU falls back to ch_lite which handles printed English adequately. RapidOCR handles English natively.
264
+ 2. **Formula OCR** β€” disabled. MFR models excluded (~1-2 GB saved). Set `"enable": true` in `~/magic-pdf.json` and re-download MFR models to enable.
265
+ 3. **First-request latency** β€” MinerU models lazy-load on first PDF request (~30–60 s). Call `/warmup` to pre-load.
266
+ 4. **In-process cache** β€” SHA256 cache lives in RAM, cleared on container restart.
267
+ 5. **Batch is sequential** β€” 8-file max; parallel processing would OOM on 16 GB.
download_models.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Download MinerU pipeline models from Hugging Face Hub.
3
+
4
+ Called once during Docker build: python download_models.py
5
+
6
+ Optimizations vs original:
7
+ - Skip-if-exists: if models are already present (Docker layer cache reuse),
8
+ the entire download is skipped without re-downloading anything.
9
+ - MFR excluded: formula recognition models (unimernet, ~1-2 GB) are not
10
+ downloaded because formula recognition is disabled in the config. Excluding
11
+ them cuts download time and image size significantly.
12
+ - layoutreader optional: if download fails (network issue, repo unavailable),
13
+ the script logs a warning and continues. MinerU falls back to its built-in
14
+ layout ordering without layoutreader.
15
+
16
+ ── FORENSIC: OCR MODEL AVAILABILITY IN opendatalab/PDF-Extract-Kit-1.0 ───────
17
+
18
+ models_config.yml in magic-pdf 1.3.12 was patched in Dockerfile Layer 3.5 to
19
+ use the weight files that ARE present in the HF repo. After the patch:
20
+
21
+ DEFAULT CPU path (ch_lite):
22
+ det: ch_PP-OCRv5_det_infer.pth ← present in HF repo βœ“
23
+ rec: ch_PP-OCRv5_rec_infer.pth ← present in HF repo βœ“
24
+
25
+ en / latin det (patched):
26
+ det: Multilingual_PP-OCRv3_det_infer.pth ← present in HF repo βœ“
27
+
28
+ NOT IN REPO (these files do NOT exist and are not needed for default usage):
29
+ ch_PP-OCRv3_det_infer.pth ← absent; patched to v5
30
+ en_PP-OCRv3_det_infer.pth ← absent; patched to multilingual
31
+ en_PP-OCRv4_rec_infer.pth ← absent; en rec unavailable
32
+ korean/japan/chinese_cht/etc v3 rec ← absent; those langs need explicit
33
+ lang= arg which is not default
34
+
35
+ BUNDLED IN WHEEL (not downloaded here):
36
+ magic_pdf/resources/slanet_plus/slanet-plus.onnx ← table model, in wheel
37
+ magic_pdf/resources/fasttext-langdetect/lid.176.ftz
38
+ magic_pdf/resources/yolov11-langdetect/yolo_v11_ft.pt
39
+
40
+ Models saved to /app/models/
41
+ Config written to /root/magic-pdf.json
42
+ """
43
+
44
+ import json
45
+ import os
46
+ import sys
47
+
48
+ MODELS_DIR = "/app/models"
49
+ EXTRACT_KIT_DIR = os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0")
50
+ LAYOUTREADER_DIR = os.path.join(MODELS_DIR, "layoutreader")
51
+
52
+ # Canary files: both must exist for the skip-if-exists check to pass.
53
+ # Using the OCR det weight (not just the Layout dir) ensures a stale cache
54
+ # that predates the v3β†’v5 model rename cannot produce a false positive.
55
+ _CANARY_DIR = os.path.join(EXTRACT_KIT_DIR, "models", "Layout")
56
+ _CANARY_FILE = os.path.join(
57
+ EXTRACT_KIT_DIR, "models", "OCR", "paddleocr_torch",
58
+ "ch_PP-OCRv5_det_infer.pth" # patched det; absent in v3-era cache
59
+ )
60
+
61
+
62
+ def _models_present() -> bool:
63
+ """Return True only when BOTH the Layout directory AND the OCR v5 det weight
64
+ exist. This prevents stale Docker layer caches (built before the v3β†’v5 patch)
65
+ from reporting models as present when the required file is missing."""
66
+ return os.path.isdir(_CANARY_DIR) and os.path.isfile(_CANARY_FILE)
67
+
68
+
69
+ def _write_config(layoutreader_dir: str) -> None:
70
+ config = {
71
+ "bucket_info": {},
72
+ "models-dir": os.path.join(EXTRACT_KIT_DIR, "models"),
73
+ "layoutreader-model-dir": layoutreader_dir,
74
+ "device-mode": "cpu",
75
+ "layout-config": {
76
+ "model": "doclayout_yolo"
77
+ },
78
+ "formula-config": {
79
+ "mfd_model": "yolo_v8_mfd",
80
+ "mfr_model": "unimernet_small",
81
+ "enable": False
82
+ },
83
+ "table-config": {
84
+ "model": "rapid_table",
85
+ "enable": True,
86
+ "max_time": 400
87
+ },
88
+ "backend": "pipeline"
89
+ }
90
+ config_path = os.path.expanduser("~/magic-pdf.json")
91
+ with open(config_path, "w") as f:
92
+ json.dump(config, f, indent=2)
93
+ print(f"Config written β†’ {config_path}")
94
+ return config_path
95
+
96
+
97
+ def download() -> None:
98
+ try:
99
+ from huggingface_hub import snapshot_download
100
+ except ImportError:
101
+ print("ERROR: huggingface_hub not installed", file=sys.stderr)
102
+ sys.exit(1)
103
+
104
+ # ── Skip-if-exists ────────────────────────────────────────────────────────
105
+ if _models_present():
106
+ print("Models already present β€” skipping download (Docker layer cache).")
107
+ # Config may still need writing if this is a fresh container from cached layer
108
+ lr_dir = LAYOUTREADER_DIR if os.path.isdir(LAYOUTREADER_DIR) else ""
109
+ _write_config(lr_dir)
110
+ return
111
+
112
+ os.makedirs(MODELS_DIR, exist_ok=True)
113
+
114
+ # ── PDF-Extract-Kit-1.0 ───────────────────────────────────────────────────
115
+ # Excluded via ignore_patterns:
116
+ # models/MFR β€” formula recognition (unimernet). Disabled in config.
117
+ # Saves ~1-2 GB of download and disk.
118
+ #
119
+ # OCR models (models/OCR/paddleocr_torch/) ARE included (not ignored).
120
+ # After the Layer 3.5 patch, the files models_config.yml references match
121
+ # what is actually present in the repo:
122
+ # ch_PP-OCRv5_det_infer.pth ← present βœ“
123
+ # ch_PP-OCRv5_rec_infer.pth ← present βœ“
124
+ # Multilingual_PP-OCRv3_det_infer.pth ← present βœ“
125
+ print("=" * 60)
126
+ print("Downloading PDF-Extract-Kit-1.0 ...")
127
+ print(" (MFR/formula-recognition excluded β€” disabled in config)")
128
+ print("=" * 60)
129
+ snapshot_download(
130
+ repo_id="opendatalab/PDF-Extract-Kit-1.0",
131
+ local_dir=EXTRACT_KIT_DIR,
132
+ ignore_patterns=[
133
+ "*.git*",
134
+ ".gitattributes",
135
+ "models/MFR*",
136
+ "models/MFR/*",
137
+ ],
138
+ )
139
+ print(f" β†’ {EXTRACT_KIT_DIR}")
140
+
141
+ # Verify canary file landed correctly
142
+ if not os.path.isfile(_CANARY_FILE):
143
+ print(
144
+ f"\nERROR: Expected OCR model not found after download:\n"
145
+ f" {_CANARY_FILE}\n"
146
+ f"The HF repo may have changed its file structure.\n"
147
+ f"Run: python3 -c \"from huggingface_hub import list_repo_files; "
148
+ f"[print(f) for f in list_repo_files('opendatalab/PDF-Extract-Kit-1.0')]\"\n"
149
+ f"to inspect the current repo contents.",
150
+ file=sys.stderr,
151
+ )
152
+ sys.exit(1)
153
+ print(f" Canary verified: {os.path.basename(_CANARY_FILE)} βœ“")
154
+
155
+ # ── layoutreader (optional) ───────────────────────────────────────────────
156
+ # Improves reading-order accuracy. If unavailable, MinerU uses fallback.
157
+ layoutreader_dir = ""
158
+ print("=" * 60)
159
+ print("Downloading layoutreader (optional, improves reading order) ...")
160
+ print("=" * 60)
161
+ try:
162
+ snapshot_download(
163
+ repo_id="hantian/layoutreader",
164
+ local_dir=LAYOUTREADER_DIR,
165
+ ignore_patterns=["*.git*", ".gitattributes"],
166
+ )
167
+ layoutreader_dir = LAYOUTREADER_DIR
168
+ print(f" β†’ {LAYOUTREADER_DIR}")
169
+ except Exception as exc:
170
+ print(f" WARNING: layoutreader download failed ({exc})")
171
+ print(" Continuing without layoutreader β€” MinerU will use fallback ordering.")
172
+
173
+ # ── Write config ──────────────────────────────────────────────────────────
174
+ _write_config(layoutreader_dir)
175
+
176
+ print("\nβœ“ Model setup complete.")
177
+ print(f" models-dir : {os.path.join(EXTRACT_KIT_DIR, 'models')}")
178
+ print(f" layoutreader-dir : {layoutreader_dir or '(not available)'}")
179
+ print(f" device-mode : cpu")
180
+ print(f" formula recognition : disabled (MFR models excluded)")
181
+ print(f" table recognition : enabled (slanet-plus.onnx bundled in wheel)")
182
+
183
+
184
+ if __name__ == "__main__":
185
+ download()
entrypoint.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # ─────────────────────────────────────────────────────────────────────────────
3
+ # MinerU OCR Service β€” container entrypoint
4
+ #
5
+ # Sequence:
6
+ # 1. Restore magic-pdf.json if wiped (HF container restart)
7
+ # 2. Run validate.py (pre-flight dependency check)
8
+ # β†’ exits 1 and kills container if any critical dep is missing
9
+ # β†’ this surfaces a clear error in HF logs instead of a silent bad start
10
+ # 3. Start uvicorn (single worker β€” CPU Basic, no RAM contention)
11
+ # ─────────────────────────────────────────────────────────────────────────────
12
+ set -e
13
+
14
+ CONFIG_FILE="${HOME}/magic-pdf.json"
15
+
16
+ # ── 1. Restore config if /root was wiped (HF container restart) ───────────────
17
+ if [ ! -f "$CONFIG_FILE" ]; then
18
+ echo "[entrypoint] magic-pdf.json missing β€” restoring from baked copy..."
19
+ cp /app/config/magic-pdf.json "$CONFIG_FILE"
20
+ fi
21
+
22
+ echo "[entrypoint] Config : $CONFIG_FILE"
23
+ echo "[entrypoint] Port : ${PORT:-7860}"
24
+
25
+ # ── 2. Pre-flight validation ──────────────────────────────────────────────────
26
+ # validate.py exits 0 on pass, exits 1 on any CRITICAL failure.
27
+ # 'set -e' above ensures a non-zero exit from validate.py aborts this script,
28
+ # preventing a broken uvicorn from starting and appearing healthy.
29
+ echo "[entrypoint] Running pre-flight validation..."
30
+ python /app/validate.py
31
+ echo "[entrypoint] Validation passed."
32
+
33
+ # ── 3. Start API server ───────────────────────────────────────────────────────
34
+ echo "[entrypoint] Starting uvicorn on 0.0.0.0:${PORT:-7860}..."
35
+ exec uvicorn main:app \
36
+ --host 0.0.0.0 \
37
+ --port "${PORT:-7860}" \
38
+ --workers 1 \
39
+ --timeout-keep-alive 120 \
40
+ --log-level info
main.py ADDED
@@ -0,0 +1,1608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MinerU OCR & Document Extraction Service β€” v2.0
3
+ FastAPI application for Hugging Face Docker Space (CPU / pipeline backend)
4
+
5
+ ═══════════════════════════════════════════════════════════════════════════════
6
+ ARCHITECTURE (v2.0 β€” dual-path OCR routing)
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
+ API ENDPOINTS
22
+ ═══════════════════════════════════════════════════════════════════════════════
23
+
24
+ GET /health Liveness (always fast)
25
+ GET /status Node status: memory, uptime, cache, active requests
26
+ GET /warmup Pre-load both OCR engines into RAM (call after deploy)
27
+ GET /diagnostics Full environment + model inventory dump
28
+ POST /benchmark Run OCR on a built-in synthetic image, return timings
29
+ POST /extract Single file β€” PDF or image β€” with SHA256 cache
30
+ POST /batch Up to 8 files, sequential, per-file error isolation
31
+
32
+ ═══════════════════════════════════════════════════════════════════════════════
33
+ RESPONSE FORMAT
34
+ ═══════════════════════════════════════════════════════════════════════════════
35
+
36
+ {
37
+ "success": true,
38
+ "filename": "...",
39
+ "docType": "marksheet" | "invoice" | "form" | "certificate" | ...,
40
+ "pageCount": 1,
41
+ "confidence": 0.94,
42
+ "ocrEngine": "rapidocr" | "mineru" | "mineru_fallback",
43
+ "markdown": "...",
44
+ "plainText": "...",
45
+ "entities": { ... document-type-specific fields ... },
46
+ "timings": {
47
+ "uploadMs": 10,
48
+ "classifyMs": 2,
49
+ "ocrDetMs": 180,
50
+ "ocrRecMs": 620,
51
+ "markdownMs": 90,
52
+ "serializeMs": 15,
53
+ "totalMs": 917
54
+ },
55
+ "metadata": {
56
+ "parseMethod": "fast_ocr" | "ocr" | "txt",
57
+ "backend": "rapidocr" | "pipeline",
58
+ "cached": false,
59
+ "processingTimeMs": 917,
60
+ "passesUsed": 1,
61
+ "docTypeClassification": "...",
62
+ "imageCount": 0,
63
+ "tableCount": 1,
64
+ "formulaCount": 0
65
+ }
66
+ }
67
+
68
+ Errors (all non-2xx):
69
+ {
70
+ "success": false,
71
+ "stage": "upload" | "validation" | "decode" | "ocr" | "markdown" | "unknown",
72
+ "errorCode": "...",
73
+ "rootCause": "...",
74
+ "recommendation": "...",
75
+ "message": "..."
76
+ }
77
+ """
78
+
79
+ import hashlib
80
+ import io
81
+ import os
82
+ import re
83
+ import shutil
84
+ import sys
85
+ import tempfile
86
+ import threading
87
+ import time
88
+ import traceback
89
+ import logging
90
+ from importlib.metadata import version as pkg_version
91
+ from typing import Any
92
+
93
+ import fitz # PyMuPDF β€” bundled with magic-pdf[full]
94
+ import numpy as np
95
+ from PIL import Image
96
+
97
+ from fastapi import FastAPI, File, UploadFile
98
+ from fastapi.middleware.cors import CORSMiddleware
99
+ from fastapi.responses import JSONResponse
100
+
101
+ # ── Logging ───────────────────────────────────────────────────────────────────
102
+ logging.basicConfig(
103
+ level=logging.INFO,
104
+ format="%(asctime)s %(levelname)-8s %(name)s %(message)s",
105
+ )
106
+ logger = logging.getLogger("mineru-service")
107
+
108
+ # ── Start time ────────────────────────────────────────────────────────────────
109
+ _START_TIME: float = time.time()
110
+
111
+ # ── Upload / batch constants ──────────────────────────────────────────────────
112
+ MAX_UPLOAD_BYTES = 30 * 1024 * 1024 # 30 MB
113
+ BATCH_MAX_FILES = 8
114
+
115
+ # ── File type sets ────────────────────────────────────────────────────────────
116
+ PDF_EXTENSIONS = {"pdf"}
117
+ NATIVE_IMAGE_EXTENSIONS = {"jpg", "jpeg", "png"}
118
+ PILLOW_IMAGE_EXTENSIONS = {"webp", "bmp", "tiff", "tif", "gif", "heic", "heif", "avif"}
119
+ IMAGE_EXTENSIONS = NATIVE_IMAGE_EXTENSIONS | PILLOW_IMAGE_EXTENSIONS
120
+ ALLOWED_EXTENSIONS = PDF_EXTENSIONS | IMAGE_EXTENSIONS
121
+
122
+ # ── Fast-OCR confidence threshold for MinerU fallback ─────────────────────────
123
+ # If RapidOCR returns < this confidence, the request escalates to the full
124
+ # MinerU pipeline for a second pass.
125
+ FAST_CONFIDENCE_THRESHOLD = 0.65
126
+
127
+ # ── Memory safety ─────────────────────────────────────────────────────────────
128
+ BYTES_PER_OCR_PAGE = 100 * 1024 * 1024 # ~100 MB / page (conservative)
129
+ IMAGE_MEMORY_FACTOR = 4 # decoded pixels Γ— 4 for pipeline buffers
130
+ MEM_SAFETY_FLOOR_MB = 1024 # always keep 1 GB free
131
+
132
+ # ── SHA256 extraction cache ───────────────────────────────────────────────────
133
+ _cache: dict[str, dict[str, Any]] = {}
134
+ _cache_lock = threading.Lock()
135
+
136
+ # ── Active-request counter ────────────────────────────────────────────────────
137
+ _active_requests: int = 0
138
+ _active_lock = threading.Lock()
139
+
140
+ # ── Model load state ──────────────────────────────────────────────────────────
141
+ _model_load_ms: int = 0
142
+ _pipeline_ready: bool = False
143
+ _pipeline_lock = threading.Lock()
144
+
145
+ _rapidocr_engine: Any = None
146
+ _rapidocr_lock = threading.Lock()
147
+ _rapidocr_load_ms: int = 0
148
+ _rapidocr_ready: bool = False
149
+
150
+ # ── Startup issues ────────────────────────────────────────────────────────────
151
+ _startup_issues: list[str] = []
152
+ _startup_done: bool = False
153
+
154
+
155
+ # ═════════════════════════════════════════════════════════════════════════════
156
+ # Structured error
157
+ # ═════════════════════════════════════════════════════════════════════════════
158
+ class ExtractionError(Exception):
159
+ def __init__(
160
+ self,
161
+ stage: str,
162
+ code: str,
163
+ message: str,
164
+ http_status: int = 422,
165
+ root_cause: str = "",
166
+ recommendation: str = "",
167
+ ) -> None:
168
+ self.stage = stage
169
+ self.code = code
170
+ self.message = message
171
+ self.http_status = http_status
172
+ self.root_cause = root_cause or message
173
+ self.recommendation = recommendation
174
+ super().__init__(message)
175
+
176
+ def to_dict(self) -> dict[str, Any]:
177
+ return {
178
+ "success": False,
179
+ "stage": self.stage,
180
+ "errorCode": self.code,
181
+ "rootCause": self.root_cause,
182
+ "recommendation": self.recommendation,
183
+ "message": self.message,
184
+ }
185
+
186
+
187
+ def _err(
188
+ stage: str,
189
+ code: str,
190
+ msg: str,
191
+ status: int = 422,
192
+ root_cause: str = "",
193
+ recommendation: str = "",
194
+ ) -> ExtractionError:
195
+ return ExtractionError(stage, code, msg, status, root_cause, recommendation)
196
+
197
+
198
+ # ═════════════════════════════════════════════════════════════════════════════
199
+ # Active request helpers
200
+ # ═════════════════════════════════════════════════════════════════════════════
201
+ def _inc_active() -> None:
202
+ global _active_requests
203
+ with _active_lock:
204
+ _active_requests += 1
205
+
206
+
207
+ def _dec_active() -> None:
208
+ global _active_requests
209
+ with _active_lock:
210
+ _active_requests = max(0, _active_requests - 1)
211
+
212
+
213
+ # ══════════════════════════════════════════════���══════════════════════════════
214
+ # Engine loaders
215
+ # ═════════════════════════════════════════════════════════════════════════════
216
+ def _ensure_rapidocr() -> Any:
217
+ """Load and return the RapidOCR engine (singleton, thread-safe)."""
218
+ global _rapidocr_engine, _rapidocr_ready, _rapidocr_load_ms
219
+ if _rapidocr_ready:
220
+ return _rapidocr_engine
221
+
222
+ with _rapidocr_lock:
223
+ if _rapidocr_ready:
224
+ return _rapidocr_engine
225
+ t0 = time.perf_counter()
226
+ try:
227
+ from rapidocr_onnxruntime import RapidOCR
228
+ _rapidocr_engine = RapidOCR()
229
+ _rapidocr_load_ms = int((time.perf_counter() - t0) * 1000)
230
+ _rapidocr_ready = True
231
+ logger.info("RapidOCR engine loaded (%d ms).", _rapidocr_load_ms)
232
+ except Exception as exc:
233
+ raise _err(
234
+ "model_load", "RAPIDOCR_LOAD_FAILED",
235
+ f"RapidOCR failed to load: {exc}",
236
+ 503,
237
+ root_cause=str(exc),
238
+ recommendation="Check that rapidocr-onnxruntime is installed in Dockerfile Layer 1.",
239
+ ) from exc
240
+ return _rapidocr_engine
241
+
242
+
243
+ def _ensure_pipeline() -> None:
244
+ """Verify MinerU imports and config are present (singleton, thread-safe)."""
245
+ global _pipeline_ready, _model_load_ms
246
+ if _pipeline_ready:
247
+ return
248
+
249
+ with _pipeline_lock:
250
+ if _pipeline_ready:
251
+ return
252
+ config_path = os.path.expanduser("~/magic-pdf.json")
253
+ if not os.path.exists(config_path):
254
+ raise _err(
255
+ "model_load", "CONFIG_MISSING",
256
+ f"magic-pdf.json not found at {config_path}.",
257
+ 503,
258
+ root_cause="download_models.py did not run or /root was wiped.",
259
+ recommendation="Check Docker build log for download_models.py output.",
260
+ )
261
+ t0 = time.perf_counter()
262
+ try:
263
+ from magic_pdf.data.dataset import PymuDocDataset, ImageDataset # noqa
264
+ from magic_pdf.data.data_reader_writer import ( # noqa
265
+ FileBasedDataReader, FileBasedDataWriter,
266
+ )
267
+ except ImportError as exc:
268
+ raise _err(
269
+ "model_load", "IMPORT_FAILED",
270
+ f"magic_pdf not importable: {exc}",
271
+ 503,
272
+ root_cause=str(exc),
273
+ recommendation="Check that magic-pdf[full]==1.3.12 is installed in Dockerfile Layer 3.",
274
+ ) from exc
275
+ _model_load_ms = int((time.perf_counter() - t0) * 1000)
276
+ _pipeline_ready = True
277
+ logger.info("MinerU pipeline ready (%d ms).", _model_load_ms)
278
+
279
+
280
+ # ═════════════════════════════════════════════════════════════════════════════
281
+ # FastAPI app
282
+ # ═════════════════════════════════════════════════════════════════════════════
283
+ app = FastAPI(
284
+ title="MinerU OCR Service",
285
+ description="Dual-path OCR: RapidOCR (1–5 s) for images, MinerU for PDFs.",
286
+ version="2.0.0",
287
+ )
288
+
289
+ app.add_middleware(
290
+ CORSMiddleware,
291
+ allow_origins=["*"],
292
+ allow_methods=["GET", "POST"],
293
+ allow_headers=["*"],
294
+ )
295
+
296
+
297
+ # ─────────────────────────────────────────────────────────────────────────────
298
+ # Startup self-test
299
+ # ─────────────────────────────────────────────────────────────────────────────
300
+ @app.on_event("startup")
301
+ async def startup_self_test() -> None:
302
+ global _startup_done
303
+ issues: list[str] = []
304
+
305
+ checks = [
306
+ ("cv2", lambda: __import__("cv2").__version__),
307
+ ("torch", lambda: __import__("torch").__version__),
308
+ ("rapidocr", lambda: pkg_version("rapidocr-onnxruntime")),
309
+ ("magic_pdf", lambda: __import__("magic_pdf").__version__),
310
+ ]
311
+ for name, fn in checks:
312
+ try:
313
+ ver = fn()
314
+ logger.info("startup βœ“ %s %s", name, ver)
315
+ except Exception as exc:
316
+ msg = f"{name} unavailable: {exc}"
317
+ issues.append(msg)
318
+ logger.critical("startup FAIL %s", msg)
319
+
320
+ config_path = os.path.expanduser("~/magic-pdf.json")
321
+ if not os.path.exists(config_path):
322
+ issues.append(f"magic-pdf.json missing at {config_path}")
323
+
324
+ models_dir = "/app/models/PDF-Extract-Kit-1.0/models"
325
+ if not os.path.isdir(models_dir):
326
+ issues.append(f"Models directory missing: {models_dir}")
327
+
328
+ try:
329
+ td = tempfile.mkdtemp(prefix="mineru_selftest_")
330
+ shutil.rmtree(td)
331
+ logger.info("startup βœ“ temp storage writable")
332
+ except Exception as exc:
333
+ issues.append(f"Temp storage not writable: {exc}")
334
+
335
+ _startup_issues.extend(issues)
336
+ _startup_done = True
337
+ level = logger.info if not issues else logger.error
338
+ level("Startup self-test %s β€” %d issue(s).", "PASSED" if not issues else "FAILED", len(issues))
339
+
340
+
341
+ # ═════════════════════════════════════════════════════════════════════════════
342
+ # GET /health
343
+ # ═════════════════════════════════════════════════════════════════════════════
344
+ @app.get("/health")
345
+ def health() -> dict[str, Any]:
346
+ return {"status": "healthy"}
347
+
348
+
349
+ # ═════════════════════════════════════════════════════════════════════════════
350
+ # GET /status
351
+ # ═════════════════════════════════════════════════════════════════════════════
352
+ @app.get("/status")
353
+ def status() -> dict[str, Any]:
354
+ used_mb, total_mb = _mem_mb()
355
+ return {
356
+ "status": "healthy" if not _startup_issues else "degraded",
357
+ "provider": "mineru",
358
+ "version": _mineru_version(),
359
+ "ocrEngines": {
360
+ "rapidocr": {
361
+ "ready": _rapidocr_ready,
362
+ "loadMs": _rapidocr_load_ms,
363
+ "purpose": "images (fast path, 1-5 s target)",
364
+ },
365
+ "mineru": {
366
+ "ready": _pipeline_ready,
367
+ "loadMs": _model_load_ms,
368
+ "purpose": "PDFs + fallback for low-confidence images",
369
+ },
370
+ },
371
+ "startupIssues": _startup_issues,
372
+ "uptimeSeconds": int(time.time() - _START_TIME),
373
+ "memoryUsedMB": used_mb,
374
+ "memoryTotalMB": total_mb,
375
+ "activeRequests": _active_requests,
376
+ "cacheEntries": len(_cache),
377
+ "confidenceThreshold": FAST_CONFIDENCE_THRESHOLD,
378
+ }
379
+
380
+
381
+ # ═════════════════════════════════════════════════════════════════════════════
382
+ # GET /warmup
383
+ # Pre-loads both OCR engines into RAM. Call once after deploy.
384
+ # ═════════════════════════════════════════════════════════════════════════════
385
+ @app.get("/warmup")
386
+ def warmup() -> dict[str, Any]:
387
+ results: dict[str, Any] = {}
388
+
389
+ t0 = time.perf_counter()
390
+ try:
391
+ _ensure_rapidocr()
392
+ results["rapidocr"] = {"status": "ready", "loadMs": _rapidocr_load_ms}
393
+ except Exception as exc:
394
+ results["rapidocr"] = {"status": "failed", "error": str(exc)}
395
+ results["rapidocrElapsedMs"] = int((time.perf_counter() - t0) * 1000)
396
+
397
+ t1 = time.perf_counter()
398
+ try:
399
+ _ensure_pipeline()
400
+ results["mineru"] = {"status": "ready", "loadMs": _model_load_ms}
401
+ except Exception as exc:
402
+ results["mineru"] = {"status": "failed", "error": str(exc)}
403
+ results["mineruElapsedMs"] = int((time.perf_counter() - t1) * 1000)
404
+
405
+ results["totalElapsedMs"] = int((time.perf_counter() - t0) * 1000)
406
+ results["allReady"] = _rapidocr_ready and _pipeline_ready
407
+ return results
408
+
409
+
410
+ # ═════════════════════════════════════════════════════════════════════════════
411
+ # GET /diagnostics
412
+ # Full environment dump β€” model files, package versions, memory, config
413
+ # ═════════════════════════════════════════════════════════════════════════════
414
+ @app.get("/diagnostics")
415
+ def diagnostics() -> dict[str, Any]:
416
+ import platform
417
+
418
+ # Package versions
419
+ pkgs = {}
420
+ for name in ("magic-pdf", "rapidocr-onnxruntime", "torch", "torchvision",
421
+ "ultralytics", "doclayout-yolo", "rapid-table", "onnxruntime",
422
+ "opencv-python-headless", "Pillow", "fastapi", "uvicorn"):
423
+ try:
424
+ pkgs[name] = pkg_version(name)
425
+ except Exception:
426
+ pkgs[name] = "not found"
427
+
428
+ # Model file inventory
429
+ models_root = "/app/models/PDF-Extract-Kit-1.0/models"
430
+ model_files: dict[str, Any] = {}
431
+ critical = [
432
+ "OCR/paddleocr_torch/ch_PP-OCRv5_det_infer.pth",
433
+ "OCR/paddleocr_torch/ch_PP-OCRv5_rec_infer.pth",
434
+ "OCR/paddleocr_torch/Multilingual_PP-OCRv3_det_infer.pth",
435
+ "Layout/YOLO/doclayout_yolo_docstructbench_imgsz1280_2501.pt",
436
+ "Layout/LayoutLMv3/model_final.pth",
437
+ ]
438
+ for rel in critical:
439
+ full = os.path.join(models_root, rel)
440
+ if os.path.isfile(full):
441
+ model_files[rel] = f"{os.path.getsize(full) / (1024*1024):.1f} MB"
442
+ else:
443
+ model_files[rel] = "MISSING"
444
+
445
+ # Bundled wheel resources
446
+ try:
447
+ import magic_pdf as _mp
448
+ from pathlib import Path as _P
449
+ pkg_root = _P(_mp.__file__).parent
450
+ bundled = {}
451
+ for name, rel in [
452
+ ("slanet-plus.onnx", "resources/slanet_plus/slanet-plus.onnx"),
453
+ ("lid.176.ftz", "resources/fasttext-langdetect/lid.176.ftz"),
454
+ ]:
455
+ p = pkg_root / rel
456
+ bundled[name] = f"{p.stat().st_size / (1024*1024):.1f} MB" if p.exists() else "MISSING"
457
+ except Exception as exc:
458
+ bundled = {"error": str(exc)}
459
+
460
+ # models_config.yml β€” show patched det values
461
+ try:
462
+ import yaml as _yaml
463
+ from pathlib import Path as _Pp
464
+ _pkg = _Pp(__import__("magic_pdf").__file__).parent
465
+ _mc_path = _pkg / 'model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/models_config.yml'
466
+ with open(_mc_path) as _f:
467
+ _mc = _yaml.safe_load(_f)
468
+ ocr_config = {
469
+ lang: {"det": files.get("det"), "rec": files.get("rec")}
470
+ for lang, files in _mc.get("lang", {}).items()
471
+ if lang in ("ch_lite", "ch", "ch_server", "en", "latin")
472
+ }
473
+ except Exception as exc:
474
+ ocr_config = {"error": str(exc)}
475
+
476
+ used_mb, total_mb = _mem_mb()
477
+
478
+ return {
479
+ "python": platform.python_version(),
480
+ "platform": platform.platform(),
481
+ "packages": pkgs,
482
+ "modelFiles": model_files,
483
+ "bundledResources": bundled,
484
+ "ocrConfig": ocr_config,
485
+ "memory": {
486
+ "usedMB": used_mb,
487
+ "totalMB": total_mb,
488
+ "freeMB": total_mb - used_mb,
489
+ },
490
+ "engines": {
491
+ "rapidocr": {"ready": _rapidocr_ready, "loadMs": _rapidocr_load_ms},
492
+ "mineru": {"ready": _pipeline_ready, "loadMs": _model_load_ms},
493
+ },
494
+ "uptime": int(time.time() - _START_TIME),
495
+ "cacheEntries": len(_cache),
496
+ "config": _load_config_safe(),
497
+ }
498
+
499
+
500
+ # ═════════════════════════════════════════════════════════════════════════════
501
+ # POST /benchmark
502
+ # Runs OCR on a synthetic test image; returns per-stage timings.
503
+ # ═════════════════════════════════════════════════════════════════════════════
504
+ @app.post("/benchmark")
505
+ async def benchmark() -> JSONResponse:
506
+ """
507
+ Generates a 800Γ—300 white PNG with black text, runs both OCR engines,
508
+ and returns exact per-stage timing measurements.
509
+ No file upload needed β€” uses a built-in test pattern.
510
+ """
511
+ import cv2
512
+
513
+ results: dict[str, Any] = {}
514
+
515
+ # Generate test image: white background, black text lines
516
+ img = np.ones((300, 800, 3), dtype=np.uint8) * 255
517
+ test_lines = [
518
+ ("English: 93", 50),
519
+ ("Hindi: 95", 100),
520
+ ("Mathematics: 83", 150),
521
+ ("Science: 85", 200),
522
+ ("Total: 356 / 400 89.0%", 250),
523
+ ]
524
+ for text, y in test_lines:
525
+ cv2.putText(img, text, (30, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 2)
526
+
527
+ # ── RapidOCR benchmark ────────────────────────────────────────────────────
528
+ t0 = time.perf_counter()
529
+ try:
530
+ engine = _ensure_rapidocr()
531
+ t_load = time.perf_counter()
532
+ result, elapse = engine(img)
533
+ t_done = time.perf_counter()
534
+
535
+ texts = [item[1] for item in (result or []) if len(item) > 1]
536
+ scores = [item[2] for item in (result or []) if len(item) > 2 and item[2] is not None]
537
+ mean_conf = round(sum(scores) / len(scores), 4) if scores else 0.0
538
+
539
+ results["rapidocr"] = {
540
+ "status": "ok",
541
+ "engineLoadMs": int((t_load - t0) * 1000),
542
+ "inferenceMs": int((t_done - t_load) * 1000),
543
+ "totalMs": int((t_done - t0) * 1000),
544
+ "textBlocks": len(texts),
545
+ "confidence": mean_conf,
546
+ "sample": texts[:5],
547
+ "elapseDetail": elapse if isinstance(elapse, dict) else str(elapse),
548
+ }
549
+ except Exception as exc:
550
+ results["rapidocr"] = {"status": "failed", "error": str(exc)}
551
+
552
+ # ── MinerU import benchmark ───────────────────────────────────────────────
553
+ t1 = time.perf_counter()
554
+ try:
555
+ _ensure_pipeline()
556
+ results["mineru"] = {
557
+ "status": "ready",
558
+ "importLoadMs": _model_load_ms,
559
+ "checkMs": int((time.perf_counter() - t1) * 1000),
560
+ "note": "Full pipeline benchmark skipped to avoid 40+ s runtime. Use /extract with a real PDF.",
561
+ }
562
+ except Exception as exc:
563
+ results["mineru"] = {"status": "failed", "error": str(exc)}
564
+
565
+ used_mb, total_mb = _mem_mb()
566
+ results["memory"] = {"usedMB": used_mb, "totalMB": total_mb}
567
+ results["benchmarkTimestampUtc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
568
+
569
+ return JSONResponse(content=results)
570
+
571
+
572
+ # ═════════════════════════════════════════════════════════════════════════════
573
+ # POST /extract
574
+ # ═════════════════════════════════════════════════════════════════════════════
575
+ @app.post("/extract")
576
+ async def extract(file: UploadFile = File(...)) -> JSONResponse:
577
+ t_upload_start = time.perf_counter()
578
+ try:
579
+ raw, filename, ext = await _read_upload(file)
580
+ t_upload_end = time.perf_counter()
581
+ result = _run_extraction(raw, filename, ext,
582
+ upload_ms=int((t_upload_end - t_upload_start) * 1000))
583
+ return JSONResponse(content=result)
584
+ except ExtractionError as exc:
585
+ logger.warning("/extract [%s/%s]: %s", exc.stage, exc.code, exc.message)
586
+ return JSONResponse(status_code=exc.http_status, content=exc.to_dict())
587
+ except Exception as exc:
588
+ logger.exception("/extract unhandled error")
589
+ return JSONResponse(
590
+ status_code=500,
591
+ content={
592
+ "success": False,
593
+ "stage": "unknown",
594
+ "errorCode": "INTERNAL_ERROR",
595
+ "rootCause": str(exc),
596
+ "recommendation": "Check HF Space logs for full traceback.",
597
+ "message": str(exc),
598
+ "traceback": traceback.format_exc()[-3000:],
599
+ },
600
+ )
601
+
602
+
603
+ # ═════════════════════════════════════════════════════════════════════════════
604
+ # POST /batch
605
+ # ═════════════════════════════════════════════════════════════════════════════
606
+ @app.post("/batch")
607
+ async def batch(files: list[UploadFile] = File(...)) -> JSONResponse:
608
+ candidates = files[:BATCH_MAX_FILES]
609
+ results: list[dict[str, Any]] = []
610
+
611
+ for upload in candidates:
612
+ t0 = time.perf_counter()
613
+ try:
614
+ raw, filename, ext = await _read_upload(upload)
615
+ upload_ms = int((time.perf_counter() - t0) * 1000)
616
+ result = _run_extraction(raw, filename, ext, upload_ms=upload_ms)
617
+ except ExtractionError as exc:
618
+ result = exc.to_dict()
619
+ result["filename"] = _sanitize_filename(upload.filename or "upload")
620
+ except Exception as exc:
621
+ fname = _sanitize_filename(upload.filename or "upload")
622
+ logger.exception("Batch item failed: %s", fname)
623
+ result = {
624
+ "success": False,
625
+ "filename": fname,
626
+ "stage": "unknown",
627
+ "errorCode": "INTERNAL_ERROR",
628
+ "rootCause": str(exc),
629
+ "recommendation": "Check HF Space logs.",
630
+ "message": str(exc),
631
+ }
632
+ results.append(result)
633
+
634
+ return JSONResponse(content={
635
+ "success": True,
636
+ "processed": len(results),
637
+ "results": results,
638
+ })
639
+
640
+
641
+ # ═════════════════════════════════════════════════════════════════════════════
642
+ # Upload reader
643
+ # ═════════════════════════════════════════════════════════════════════════════
644
+ async def _read_upload(upload: UploadFile) -> tuple[bytes, str, str]:
645
+ filename = _sanitize_filename(upload.filename or "upload")
646
+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
647
+
648
+ if ext not in ALLOWED_EXTENSIONS:
649
+ raise _err(
650
+ "validation", "UNSUPPORTED_TYPE",
651
+ f"Unsupported file type '.{ext}'. Supported: {sorted(ALLOWED_EXTENSIONS)}",
652
+ 415,
653
+ root_cause=f"Extension '{ext}' is not in the allowed set.",
654
+ recommendation="Convert the file to PDF, JPG, PNG, or WEBP before uploading.",
655
+ )
656
+
657
+ raw = await upload.read(MAX_UPLOAD_BYTES + 1)
658
+
659
+ if len(raw) > MAX_UPLOAD_BYTES:
660
+ raise _err(
661
+ "upload", "FILE_TOO_LARGE",
662
+ f"'{filename}' exceeds the {MAX_UPLOAD_BYTES // 1024 // 1024} MB limit.",
663
+ 413,
664
+ root_cause=f"File is {len(raw) // 1024 // 1024} MB; limit is 30 MB.",
665
+ recommendation="Compress the image or split a multi-page PDF into smaller parts.",
666
+ )
667
+ if len(raw) == 0:
668
+ raise _err("upload", "EMPTY_FILE", f"'{filename}' is empty.", 400,
669
+ root_cause="Zero bytes received.", recommendation="Check the file before uploading.")
670
+
671
+ return raw, filename, ext
672
+
673
+
674
+ # ═════════════════════════════════════════════════════════════════════════════
675
+ # Extraction dispatcher
676
+ # ═════════════════════════════════════════════════════════════════════════════
677
+ def _run_extraction(
678
+ raw: bytes, filename: str, ext: str, upload_ms: int = 0
679
+ ) -> dict[str, Any]:
680
+ """
681
+ 1. SHA256 cache lookup β€” return immediately on hit
682
+ 2. Memory safety guard
683
+ 3. Route: image β†’ fast OCR (RapidOCR) / PDF β†’ MinerU
684
+ 4. Multi-pass: low confidence image β†’ MinerU fallback
685
+ 5. Cache and return
686
+ """
687
+ file_hash = hashlib.sha256(raw).hexdigest()
688
+ with _cache_lock:
689
+ cached = _cache.get(file_hash)
690
+ if cached is not None:
691
+ logger.info("Cache hit %s sha256=%.12s…", filename, file_hash)
692
+ out = {**cached}
693
+ out["metadata"] = {**cached["metadata"], "cached": True, "processingTimeMs": 0}
694
+ out["timings"] = {**cached.get("timings", {}), "totalMs": 0}
695
+ return out
696
+
697
+ _assert_memory_safe(raw, ext)
698
+
699
+ _inc_active()
700
+ work_dir = tempfile.mkdtemp(prefix="mineru_")
701
+ t_total_start = time.perf_counter()
702
+ try:
703
+ if ext in PDF_EXTENSIONS:
704
+ _ensure_pipeline()
705
+ result = _process_pdf(raw, filename, work_dir, upload_ms=upload_ms)
706
+ else:
707
+ result = _process_image_routed(raw, filename, ext, work_dir, upload_ms=upload_ms)
708
+
709
+ total_ms = int((time.perf_counter() - t_total_start) * 1000)
710
+ result["timings"]["totalMs"] = total_ms
711
+ result["timings"]["uploadMs"] = upload_ms
712
+ result["metadata"]["processingTimeMs"] = total_ms
713
+ result["metadata"]["cached"] = False
714
+
715
+ # Cache without timing (timings are per-run)
716
+ entry = {k: v for k, v in result.items() if k != "timings"}
717
+ entry["metadata"] = {k: v for k, v in result["metadata"].items()
718
+ if k not in ("processingTimeMs", "cached")}
719
+ with _cache_lock:
720
+ _cache[file_hash] = entry
721
+
722
+ logger.info("Extracted %s engine=%s conf=%.2f %d ms",
723
+ filename, result.get("ocrEngine", "?"),
724
+ result.get("confidence", 0), total_ms)
725
+ return result
726
+
727
+ except ExtractionError:
728
+ raise
729
+ except Exception as exc:
730
+ logger.exception("Extraction failed for %s", filename)
731
+ raise _err(
732
+ "unknown", "INTERNAL_ERROR",
733
+ f"Unexpected error: {exc}", 500,
734
+ root_cause=str(exc),
735
+ recommendation="Check HF Space logs for full traceback.",
736
+ ) from exc
737
+ finally:
738
+ _dec_active()
739
+ shutil.rmtree(work_dir, ignore_errors=True)
740
+
741
+
742
+ # ═════════════════════════════════════════════════════════════════════════════
743
+ # Image routing: RapidOCR fast path + optional MinerU fallback
744
+ # ═════════════════════════════════════════════════════════════════════════════
745
+ def _process_image_routed(
746
+ raw: bytes, filename: str, ext: str, work_dir: str, upload_ms: int = 0
747
+ ) -> dict[str, Any]:
748
+ """
749
+ Pass 1: RapidOCR (target 1–5 s)
750
+ Pass 2: MinerU fallback if confidence < FAST_CONFIDENCE_THRESHOLD
751
+ """
752
+ # ── Normalise to numpy BGR for RapidOCR + cv2 ─────────────────────────────
753
+ t_decode_start = time.perf_counter()
754
+ img_bgr = _decode_image_to_bgr(raw, ext)
755
+ decode_ms = int((time.perf_counter() - t_decode_start) * 1000)
756
+
757
+ # ── Pass 1: RapidOCR ──────────────────────────────────────────────────────
758
+ t_ocr_start = time.perf_counter()
759
+ try:
760
+ engine = _ensure_rapidocr()
761
+ ocr_result, elapse = engine(img_bgr)
762
+ except ExtractionError:
763
+ raise
764
+ except Exception as exc:
765
+ raise _err(
766
+ "ocr", "OCR_ENGINE_FAILED",
767
+ f"RapidOCR inference failed: {exc}", 500,
768
+ root_cause=str(exc),
769
+ recommendation="Check rapidocr-onnxruntime install in Dockerfile Layer 1.",
770
+ ) from exc
771
+
772
+ ocr_ms = int((time.perf_counter() - t_ocr_start) * 1000)
773
+
774
+ # ── Parse RapidOCR output ─────────────────────────────────────────────────
775
+ t_md_start = time.perf_counter()
776
+ plain_text, markdown, raw_confidence = _parse_rapidocr_output(ocr_result)
777
+ confidence = _score_confidence_image(
778
+ ocr_result, plain_text, raw_confidence
779
+ )
780
+ md_ms = int((time.perf_counter() - t_md_start) * 1000)
781
+
782
+ logger.info("RapidOCR pass1 conf=%.3f text_len=%d ocr_ms=%d",
783
+ confidence, len(plain_text), ocr_ms)
784
+
785
+ # ── Pass 2: MinerU fallback if confidence too low ─────────────────────────
786
+ passes_used = 1
787
+ ocr_engine = "rapidocr"
788
+
789
+ if confidence < FAST_CONFIDENCE_THRESHOLD and plain_text.strip():
790
+ logger.info(
791
+ "Confidence %.3f < %.2f β€” escalating to MinerU fallback",
792
+ confidence, FAST_CONFIDENCE_THRESHOLD,
793
+ )
794
+ try:
795
+ _ensure_pipeline()
796
+ mineru_result = _process_image_mineru(raw, filename, ext, work_dir)
797
+ # Use MinerU result if it has more text
798
+ if len(mineru_result.get("plainText", "")) > len(plain_text) * 0.8:
799
+ mineru_result["ocrEngine"] = "mineru_fallback"
800
+ mineru_result["metadata"]["passesUsed"] = 2
801
+ mineru_result["timings"]["pass1RapidOCRMs"] = ocr_ms
802
+ return mineru_result
803
+ except Exception as exc:
804
+ logger.warning("MinerU fallback failed (%s) β€” using RapidOCR result", exc)
805
+ passes_used = 2
806
+
807
+ # ── Classify and extract entities ─────────────────────────────────────────
808
+ t_classify_start = time.perf_counter()
809
+ doc_type = _classify_document(plain_text + " " + filename)
810
+ entities = _extract_entities(plain_text, doc_type)
811
+ classify_ms = int((time.perf_counter() - t_classify_start) * 1000)
812
+
813
+ # ── Parse elapse detail from RapidOCR ─────────────────────────────────────
814
+ det_ms = rec_ms = 0
815
+ if isinstance(elapse, dict):
816
+ det_ms = int(elapse.get("det", 0) * 1000)
817
+ rec_ms = int(elapse.get("rec", 0) * 1000)
818
+ elif isinstance(elapse, (int, float)):
819
+ det_ms = int(elapse * 500)
820
+ rec_ms = int(elapse * 500)
821
+
822
+ return {
823
+ "success": True,
824
+ "filename": filename,
825
+ "docType": doc_type,
826
+ "pageCount": 1,
827
+ "confidence": confidence,
828
+ "ocrEngine": ocr_engine,
829
+ "markdown": markdown,
830
+ "plainText": plain_text,
831
+ "entities": entities,
832
+ "timings": {
833
+ "uploadMs": upload_ms,
834
+ "decodeMs": decode_ms,
835
+ "classifyMs": classify_ms,
836
+ "ocrDetMs": det_ms,
837
+ "ocrRecMs": rec_ms,
838
+ "ocrTotalMs": ocr_ms,
839
+ "markdownMs": md_ms,
840
+ "totalMs": 0, # filled by caller
841
+ },
842
+ "metadata": {
843
+ "parseMethod": "fast_ocr",
844
+ "backend": "rapidocr",
845
+ "passesUsed": passes_used,
846
+ "docTypeClassification": doc_type,
847
+ "textBlocks": len(ocr_result) if ocr_result else 0,
848
+ "imageCount": 0,
849
+ "tableCount": _count_tables_in_text(plain_text),
850
+ "formulaCount": 0,
851
+ "processingTimeMs": 0,
852
+ "cached": False,
853
+ },
854
+ }
855
+
856
+
857
+ def _process_image_mineru(
858
+ raw: bytes, filename: str, ext: str, work_dir: str
859
+ ) -> dict[str, Any]:
860
+ """MinerU full pipeline for a single image (fallback or forced)."""
861
+ from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter
862
+ from magic_pdf.data.dataset import ImageDataset
863
+ from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
864
+
865
+ images_dir = os.path.join(work_dir, "images_mineru")
866
+ os.makedirs(images_dir, exist_ok=True)
867
+
868
+ # Convert non-native formats to PNG
869
+ t0 = time.perf_counter()
870
+ if ext in PILLOW_IMAGE_EXTENSIONS:
871
+ raw = _convert_to_png(raw, ext)
872
+ save_ext = "png"
873
+ else:
874
+ save_ext = ext
875
+ decode_ms = int((time.perf_counter() - t0) * 1000)
876
+
877
+ img_path = os.path.join(work_dir, f"input_mineru.{save_ext}")
878
+ with open(img_path, "wb") as fh:
879
+ fh.write(raw)
880
+
881
+ t_ocr = time.perf_counter()
882
+ try:
883
+ reader = FileBasedDataReader(work_dir)
884
+ image_bytes = reader.read(f"input_mineru.{save_ext}")
885
+ ds = ImageDataset(image_bytes)
886
+ infer_result = ds.apply(doc_analyze, ocr=True)
887
+ pipe_result = infer_result.pipe_ocr_mode(FileBasedDataWriter(images_dir))
888
+ except Exception as exc:
889
+ raise _err(
890
+ "ocr", "OCR_PIPELINE_FAILED",
891
+ f"MinerU image pipeline failed: {exc}", 500,
892
+ root_cause=str(exc),
893
+ recommendation="Check magic-pdf installation and model files.",
894
+ ) from exc
895
+ ocr_ms = int((time.perf_counter() - t_ocr) * 1000)
896
+
897
+ t_md = time.perf_counter()
898
+ try:
899
+ markdown = pipe_result.get_markdown(images_dir)
900
+ except Exception as exc:
901
+ raise _err("markdown", "MARKDOWN_FAILED", f"get_markdown failed: {exc}") from exc
902
+ md_ms = int((time.perf_counter() - t_md) * 1000)
903
+
904
+ plain_text = _markdown_to_plain(markdown)
905
+ doc_type = _classify_document(plain_text + " " + filename)
906
+ entities = _extract_entities(plain_text, doc_type)
907
+ content_list = _safe_content_list(pipe_result, images_dir)
908
+ confidence = _score_confidence_mineru(markdown, doc_type)
909
+
910
+ return {
911
+ "success": True,
912
+ "filename": filename,
913
+ "docType": doc_type,
914
+ "pageCount": 1,
915
+ "confidence": confidence,
916
+ "ocrEngine": "mineru",
917
+ "markdown": markdown,
918
+ "plainText": plain_text,
919
+ "entities": entities,
920
+ "timings": {
921
+ "uploadMs": 0,
922
+ "decodeMs": decode_ms,
923
+ "classifyMs": 0,
924
+ "ocrDetMs": 0,
925
+ "ocrRecMs": 0,
926
+ "ocrTotalMs": ocr_ms,
927
+ "markdownMs": md_ms,
928
+ "totalMs": 0,
929
+ },
930
+ "metadata": {
931
+ "parseMethod": "ocr",
932
+ "backend": "pipeline",
933
+ "passesUsed": 1,
934
+ "docTypeClassification": doc_type,
935
+ "imageCount": _count_images(content_list),
936
+ "tableCount": _count_tables(content_list),
937
+ "formulaCount": _count_formulas(content_list),
938
+ "processingTimeMs": 0,
939
+ "cached": False,
940
+ },
941
+ }
942
+
943
+
944
+ # ═════════════════════════════════════════════════════════════════════════════
945
+ # PDF processor (MinerU)
946
+ # ═════════════════════════════════════════════════════════════════════════════
947
+ def _process_pdf(
948
+ raw: bytes, filename: str, work_dir: str, upload_ms: int = 0
949
+ ) -> dict[str, Any]:
950
+ from magic_pdf.data.data_reader_writer import FileBasedDataWriter
951
+ from magic_pdf.data.dataset import PymuDocDataset
952
+ from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
953
+ from magic_pdf.config.enums import SupportedPdfParseMethod
954
+
955
+ images_dir = os.path.join(work_dir, "images")
956
+ os.makedirs(images_dir, exist_ok=True)
957
+
958
+ page_count = _pdf_page_count(raw)
959
+
960
+ t_classify = time.perf_counter()
961
+ try:
962
+ ds = PymuDocDataset(raw)
963
+ method = ds.classify()
964
+ except Exception as exc:
965
+ raise _err(
966
+ "decode", "PDF_PARSE_FAILED",
967
+ f"Could not parse PDF: {exc}", 422,
968
+ root_cause=str(exc),
969
+ recommendation="Ensure the file is a valid, non-encrypted PDF.",
970
+ ) from exc
971
+ classify_ms = int((time.perf_counter() - t_classify) * 1000)
972
+
973
+ t_ocr = time.perf_counter()
974
+ try:
975
+ image_writer = FileBasedDataWriter(images_dir)
976
+ if method == SupportedPdfParseMethod.TXT:
977
+ infer_result = ds.apply(doc_analyze, ocr=False)
978
+ pipe_result = infer_result.pipe_txt_mode(image_writer)
979
+ parse_method = "txt"
980
+ base_confidence = 0.95
981
+ else:
982
+ infer_result = ds.apply(doc_analyze, ocr=True)
983
+ pipe_result = infer_result.pipe_ocr_mode(image_writer)
984
+ parse_method = "ocr"
985
+ base_confidence = 0.85
986
+ except Exception as exc:
987
+ raise _err(
988
+ "ocr", "OCR_PIPELINE_FAILED",
989
+ f"doc_analyze/pipe failed: {exc}", 500,
990
+ root_cause=str(exc),
991
+ recommendation="Check model files in /app/models and validate.py output.",
992
+ ) from exc
993
+ ocr_ms = int((time.perf_counter() - t_ocr) * 1000)
994
+
995
+ t_md = time.perf_counter()
996
+ try:
997
+ markdown = pipe_result.get_markdown(images_dir)
998
+ except Exception as exc:
999
+ raise _err("markdown", "MARKDOWN_FAILED", f"get_markdown failed: {exc}") from exc
1000
+ md_ms = int((time.perf_counter() - t_md) * 1000)
1001
+
1002
+ plain_text = _markdown_to_plain(markdown)
1003
+ content_list = _safe_content_list(pipe_result, images_dir)
1004
+ doc_type = _classify_document(plain_text + " " + filename)
1005
+ entities = _extract_entities(plain_text, doc_type)
1006
+ confidence = _score_confidence_mineru(markdown, doc_type, base=base_confidence)
1007
+
1008
+ return {
1009
+ "success": True,
1010
+ "filename": filename,
1011
+ "docType": doc_type,
1012
+ "pageCount": page_count,
1013
+ "confidence": confidence,
1014
+ "ocrEngine": "mineru",
1015
+ "markdown": markdown,
1016
+ "plainText": plain_text,
1017
+ "entities": entities,
1018
+ "timings": {
1019
+ "uploadMs": upload_ms,
1020
+ "classifyMs": classify_ms,
1021
+ "ocrDetMs": 0,
1022
+ "ocrRecMs": 0,
1023
+ "ocrTotalMs": ocr_ms,
1024
+ "markdownMs": md_ms,
1025
+ "totalMs": 0,
1026
+ },
1027
+ "metadata": {
1028
+ "parseMethod": parse_method,
1029
+ "backend": "pipeline",
1030
+ "passesUsed": 1,
1031
+ "docTypeClassification": doc_type,
1032
+ "imageCount": _count_images(content_list),
1033
+ "tableCount": _count_tables(content_list),
1034
+ "formulaCount": _count_formulas(content_list),
1035
+ "processingTimeMs": 0,
1036
+ "cached": False,
1037
+ },
1038
+ }
1039
+
1040
+
1041
+ # ═════════════════════════════════════════════════════════════════════════════
1042
+ # RapidOCR output parser
1043
+ # ═════════════════════════════════════════════════════════════════════════════
1044
+ def _parse_rapidocr_output(
1045
+ result: Any,
1046
+ ) -> tuple[str, str, float]:
1047
+ """
1048
+ Parse RapidOCR output into (plain_text, markdown, mean_confidence).
1049
+
1050
+ RapidOCR returns: list of [box_pts, text, confidence]
1051
+ box_pts = [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
1052
+ Items are approximately top-to-bottom, left-to-right.
1053
+
1054
+ Markdown strategy: sort by average Y, group nearby items into lines,
1055
+ sort each line by average X, join with spaces.
1056
+ """
1057
+ if not result:
1058
+ return "", "", 0.0
1059
+
1060
+ def _avg_y(item: Any) -> float:
1061
+ box = item[0]
1062
+ try:
1063
+ return sum(pt[1] for pt in box) / 4
1064
+ except Exception:
1065
+ return 0.0
1066
+
1067
+ def _avg_x(item: Any) -> float:
1068
+ box = item[0]
1069
+ try:
1070
+ return sum(pt[0] for pt in box) / 4
1071
+ except Exception:
1072
+ return 0.0
1073
+
1074
+ # Sort top-to-bottom
1075
+ sorted_items = sorted(result, key=_avg_y)
1076
+
1077
+ # Group into visual lines (items within 20 px of last item in group)
1078
+ LINE_GAP = 20
1079
+ lines: list[list[Any]] = []
1080
+ if sorted_items:
1081
+ current: list[Any] = [sorted_items[0]]
1082
+ for item in sorted_items[1:]:
1083
+ if abs(_avg_y(item) - _avg_y(current[-1])) < LINE_GAP:
1084
+ current.append(item)
1085
+ else:
1086
+ lines.append(current)
1087
+ current = [item]
1088
+ lines.append(current)
1089
+
1090
+ # Build text lines (sort each line left-to-right)
1091
+ text_lines: list[str] = []
1092
+ for line in lines:
1093
+ words = sorted(line, key=_avg_x)
1094
+ text_lines.append(" ".join(str(item[1]) for item in words if len(item) > 1))
1095
+
1096
+ plain_text = "\n".join(text_lines)
1097
+ markdown = plain_text # simple markdown for images (no headers/tables from RapidOCR)
1098
+
1099
+ # Mean confidence
1100
+ scores = [item[2] for item in result if len(item) > 2 and item[2] is not None]
1101
+ mean_conf = float(sum(scores) / len(scores)) if scores else 0.5
1102
+
1103
+ return plain_text, markdown, mean_conf
1104
+
1105
+
1106
+ # ═════════════════════════════════════════════════════════════════════════════
1107
+ # Confidence scoring
1108
+ # ═════════════════════════════════════════════════════════════════════════════
1109
+ def _score_confidence_image(
1110
+ ocr_result: Any, plain_text: str, raw_ocr_confidence: float
1111
+ ) -> float:
1112
+ """
1113
+ Composite confidence for RapidOCR image result.
1114
+ 40% β€” raw OCR engine confidence (mean of block scores)
1115
+ 40% β€” text density (non-whitespace characters / expected coverage)
1116
+ 20% β€” text coherence (ratio of alpha chars to all chars)
1117
+ Range: [0.0, 1.0]
1118
+ """
1119
+ if not plain_text or not plain_text.strip():
1120
+ return 0.0
1121
+
1122
+ total_chars = len(plain_text)
1123
+ nonws_chars = len(plain_text.replace(" ", "").replace("\n", ""))
1124
+ alpha_chars = sum(1 for c in plain_text if c.isalpha())
1125
+
1126
+ density = min(1.0, nonws_chars / max(1, total_chars)) if total_chars else 0.0
1127
+ coherence = min(1.0, alpha_chars / max(1, nonws_chars)) if nonws_chars else 0.0
1128
+
1129
+ score = (
1130
+ 0.40 * raw_ocr_confidence +
1131
+ 0.40 * density +
1132
+ 0.20 * coherence
1133
+ )
1134
+ return round(min(1.0, max(0.0, score)), 4)
1135
+
1136
+
1137
+ def _score_confidence_mineru(
1138
+ markdown: str, doc_type: str, base: float = 0.85
1139
+ ) -> float:
1140
+ """
1141
+ Composite confidence for MinerU result.
1142
+ Base from parse method (txt=0.95, ocr=0.85)
1143
+ Penalty if markdown is very short (< 100 chars)
1144
+ Bonus if doc_type-specific keywords detected
1145
+ """
1146
+ if not markdown or len(markdown.strip()) < 20:
1147
+ return 0.2
1148
+
1149
+ score = base
1150
+ length = len(markdown.strip())
1151
+
1152
+ if length < 100:
1153
+ score -= 0.15
1154
+ elif length < 300:
1155
+ score -= 0.05
1156
+
1157
+ # Structural quality bonus
1158
+ if "| " in markdown and " |" in markdown:
1159
+ score = min(1.0, score + 0.03)
1160
+ if markdown.count("\n") > 10:
1161
+ score = min(1.0, score + 0.02)
1162
+
1163
+ return round(min(1.0, max(0.0, score)), 4)
1164
+
1165
+
1166
+ # ═════════════════════════════════════════════════════════════════════════════
1167
+ # Document classification
1168
+ # ═════════════════════════════════════════════════════════════════════════════
1169
+ def _classify_document(text: str) -> str:
1170
+ text_l = text.lower()
1171
+
1172
+ rules: list[tuple[str, list[str]]] = [
1173
+ ("marksheet", ["marksheet", "mark sheet", "grade sheet", "scorecard",
1174
+ "score card", "cgpa", "sgpa", "semester result",
1175
+ "result sheet", "marks obtained", "roll no", "roll number",
1176
+ "board of education", "cbse", "icse", "ssc", "hsc",
1177
+ "subject", "marks", "grade", "aggregate", "percentage"]),
1178
+ ("invoice", ["invoice", "bill to", "invoice number", "invoice #",
1179
+ "due date", "amount due", "subtotal", "tax invoice",
1180
+ "gst", "gstin", "vat", "total amount", "payable"]),
1181
+ ("receipt", ["receipt", "thank you for your purchase", "order total",
1182
+ "payment received", "transaction id", "cash receipt",
1183
+ "order id", "payment method"]),
1184
+ ("certificate", ["certificate", "this is to certify", "awarded to",
1185
+ "in recognition", "completed", "participation",
1186
+ "achievement", "principal", "director"]),
1187
+ ("resume", ["curriculum vitae", "work experience",
1188
+ "education", "skills", "references", "objective",
1189
+ "professional summary", "linkedin", "github"]),
1190
+ ("form", ["please fill", "signature", "applicant",
1191
+ "application form", "form no", "tick", "checkbox",
1192
+ "declaration", "hereby declare"]),
1193
+ ("research paper", ["abstract", "introduction", "methodology", "conclusion",
1194
+ "references", "keywords", "doi:", "arxiv", "journal"]),
1195
+ ("contract", ["agreement", "hereby", "whereas", "terms and conditions",
1196
+ "party of the first", "signed by", "indemnify"]),
1197
+ ("id card", ["id card", "identification", "employee id", "student id",
1198
+ "valid till", "date of issue", "authority"]),
1199
+ ]
1200
+
1201
+ scores: dict[str, int] = {}
1202
+ for doc_type, keywords in rules:
1203
+ score = sum(1 for kw in keywords if kw in text_l)
1204
+ if score:
1205
+ scores[doc_type] = score
1206
+
1207
+ return max(scores, key=lambda k: scores[k]) if scores else "document"
1208
+
1209
+
1210
+ # ═════════════════════════════════════════════════════════════════════════════
1211
+ # Entity extraction
1212
+ # ═════════════════════════════════════════════════════════════════════════════
1213
+ def _extract_entities(text: str, doc_type: str) -> dict[str, Any]:
1214
+ if doc_type == "marksheet":
1215
+ return _entities_marksheet(text)
1216
+ if doc_type == "invoice":
1217
+ return _entities_invoice(text)
1218
+ if doc_type == "form":
1219
+ return _entities_form(text)
1220
+ if doc_type == "certificate":
1221
+ return _entities_certificate(text)
1222
+ # For all others: extract key-value pairs generically
1223
+ return _entities_generic(text)
1224
+
1225
+
1226
+ def _entities_marksheet(text: str) -> dict[str, Any]:
1227
+ """
1228
+ Extract structured fields from CBSE / ICSE / state-board marksheets.
1229
+ Handles formats like:
1230
+ "English 93" "Hindi : 95" "Maths - 83"
1231
+ """
1232
+ entities: dict[str, Any] = {}
1233
+
1234
+ # Student name
1235
+ m = re.search(
1236
+ r"(?:student['\s]*s?\s*name|candidate\s*name|name\s*of\s*(?:the\s*)?(?:student|candidate))[\s:]*([A-Z][A-Za-z\s.]{2,40})",
1237
+ text, re.I,
1238
+ )
1239
+ if m:
1240
+ entities["studentName"] = m.group(1).strip()
1241
+
1242
+ # Roll number
1243
+ m = re.search(
1244
+ r"(?:roll\s*(?:no\.?|number|num\.?)|enrollment\s*(?:no\.?|number))[\s:.#]*([A-Z0-9\-]{3,20})",
1245
+ text, re.I,
1246
+ )
1247
+ if m:
1248
+ entities["rollNumber"] = m.group(1).strip()
1249
+
1250
+ # Date of birth
1251
+ m = re.search(
1252
+ r"(?:d\.?o\.?b\.?|date\s+of\s+birth)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})",
1253
+ text, re.I,
1254
+ )
1255
+ if m:
1256
+ entities["dob"] = m.group(1).strip()
1257
+
1258
+ # School / institution
1259
+ m = re.search(
1260
+ r"(?:school|institution|college)[\s:]*([A-Z][A-Za-z0-9\s,.-]{3,60})",
1261
+ text, re.I,
1262
+ )
1263
+ if m:
1264
+ entities["school"] = m.group(1).strip()
1265
+
1266
+ # Academic year / exam year
1267
+ m = re.search(r"(?:year|session|batch|exam)[\s:]*(\d{4}(?:[/-]\d{2,4})?)", text, re.I)
1268
+ if m:
1269
+ entities["year"] = m.group(1).strip()
1270
+
1271
+ # Subjects and marks
1272
+ # Covers: "English 93", "English: 93", "English - 93", "English 93"
1273
+ SUBJECT_NAMES = [
1274
+ "english", "hindi", "mathematics", "maths", "math", "science",
1275
+ "social science", "sst", "sanskrit", "computer science", "computers",
1276
+ "physics", "chemistry", "biology", "history", "geography",
1277
+ "economics", "political science", "accountancy", "business studies",
1278
+ "physical education", "drawing", "music", "kannada", "tamil",
1279
+ "telugu", "marathi", "bengali", "gujarati", "urdu", "punjabi",
1280
+ "environmental science", "evs", "general science",
1281
+ ]
1282
+ subjects: dict[str, int] = {}
1283
+ for sub in SUBJECT_NAMES:
1284
+ pattern = (
1285
+ r"(?<!\w)" + re.escape(sub) + r"(?!\w)"
1286
+ r"[\s:–\-]+"
1287
+ r"(\d{1,3})"
1288
+ r"(?:/\d{1,3})?"
1289
+ )
1290
+ m = re.search(pattern, text, re.I)
1291
+ if m:
1292
+ mark = int(m.group(1))
1293
+ if 0 <= mark <= 100:
1294
+ subjects[sub.title()] = mark
1295
+
1296
+ if subjects:
1297
+ entities["subjects"] = subjects
1298
+ total = sum(subjects.values())
1299
+ entities["totalMarks"] = total
1300
+ entities["maxMarks"] = len(subjects) * 100
1301
+ entities["percentage"] = round(total / (len(subjects) * 100) * 100, 2)
1302
+
1303
+ # Grade / result
1304
+ m = re.search(r"(?:grade|result|status)[\s:]*([A-F][+\-]?|pass|fail|distinction|first\s+class)", text, re.I)
1305
+ if m:
1306
+ entities["overallGrade"] = m.group(1).upper().strip()
1307
+
1308
+ # Overall percentage (explicit)
1309
+ m = re.search(r"(?:percentage|aggregate|total\s+%|overall)[\s:]*(\d{1,3}(?:\.\d{1,2})?)\s*%?", text, re.I)
1310
+ if m:
1311
+ entities["percentage"] = float(m.group(1))
1312
+
1313
+ return entities
1314
+
1315
+
1316
+ def _entities_invoice(text: str) -> dict[str, Any]:
1317
+ entities: dict[str, Any] = {}
1318
+
1319
+ m = re.search(r"invoice\s*(?:no\.?|number|#)[\s:]*([A-Z0-9\-/]{3,30})", text, re.I)
1320
+ if m:
1321
+ entities["invoiceNumber"] = m.group(1).strip()
1322
+
1323
+ m = re.search(r"(?:invoice\s*date|date)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1324
+ if m:
1325
+ entities["invoiceDate"] = m.group(1).strip()
1326
+
1327
+ m = re.search(r"due\s*date[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1328
+ if m:
1329
+ entities["dueDate"] = m.group(1).strip()
1330
+
1331
+ m = re.search(r"(?:bill\s*to|sold\s*to|customer)[\s:]+([A-Z][A-Za-z0-9\s,.-]{2,50})", text, re.I)
1332
+ if m:
1333
+ entities["billTo"] = m.group(1).strip()[:80]
1334
+
1335
+ m = re.search(
1336
+ r"(?:total|grand\s*total|amount\s*due|net\s*payable|invoice\s*total)[\s:]*"
1337
+ r"(?:rs\.?|inr|usd|\$|€|Β£)?[\s]*(\d[\d,]*(?:\.\d{1,2})?)",
1338
+ text, re.I,
1339
+ )
1340
+ if m:
1341
+ entities["totalAmount"] = m.group(1).replace(",", "")
1342
+
1343
+ m = re.search(r"(?:gstin|gst\s*no)[\s:]*([A-Z0-9]{15})", text, re.I)
1344
+ if m:
1345
+ entities["gstin"] = m.group(1).strip()
1346
+
1347
+ return entities
1348
+
1349
+
1350
+ def _entities_form(text: str) -> dict[str, Any]:
1351
+ entities: dict[str, Any] = {}
1352
+ for field, patterns in [
1353
+ ("name", [r"(?:name|applicant)[\s:]+([A-Z][A-Za-z\s.]{2,40})"]),
1354
+ ("dob", [r"(?:d\.?o\.?b\.?|date\s+of\s+birth)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})"]),
1355
+ ("gender", [r"(?:gender|sex)[\s:]*(\bMale\b|\bFemale\b|\bOther\b)", ]),
1356
+ ("phone", [r"(?:phone|mobile|contact)[\s:]*(\+?\d[\d\s\-]{8,15})"]),
1357
+ ("email", [r"([\w.+-]+@[\w-]+\.[\w.]{2,})"]),
1358
+ ]:
1359
+ for pat in patterns:
1360
+ m = re.search(pat, text, re.I)
1361
+ if m:
1362
+ entities[field] = m.group(1).strip()
1363
+ break
1364
+ return entities
1365
+
1366
+
1367
+ def _entities_certificate(text: str) -> dict[str, Any]:
1368
+ entities: dict[str, Any] = {}
1369
+
1370
+ m = re.search(r"(?:awarded\s*to|presented\s*to|this\s*is\s*to\s*certify\s*that)[\s:]+([A-Z][A-Za-z\s.]{2,40})", text, re.I)
1371
+ if m:
1372
+ entities["recipientName"] = m.group(1).strip()
1373
+
1374
+ m = re.search(r"(?:certificate\s*(?:no|number|id))[\s:]*([A-Z0-9\-]{3,20})", text, re.I)
1375
+ if m:
1376
+ entities["certificateId"] = m.group(1).strip()
1377
+
1378
+ m = re.search(r"(?:date|issued\s*on|valid\s*from)[\s:]*(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})", text, re.I)
1379
+ if m:
1380
+ entities["issueDate"] = m.group(1).strip()
1381
+
1382
+ m = re.search(r"(?:course|program|event|competition|subject)[\s:]+([A-Z][A-Za-z0-9\s&,-]{2,60})", text, re.I)
1383
+ if m:
1384
+ entities["courseOrEvent"] = m.group(1).strip()[:60]
1385
+
1386
+ return entities
1387
+
1388
+
1389
+ def _entities_generic(text: str) -> dict[str, Any]:
1390
+ """Extract key:value pairs from unrecognised document types."""
1391
+ entities: dict[str, Any] = {}
1392
+ for m in re.finditer(r"^([A-Za-z][A-Za-z\s]{1,30})[\s:–]+([^\n]{1,80})$", text, re.M):
1393
+ key = m.group(1).strip().lower().replace(" ", "_")
1394
+ val = m.group(2).strip()
1395
+ if 3 <= len(val) <= 80 and not val.endswith(":"):
1396
+ entities[key] = val
1397
+ if len(entities) >= 20:
1398
+ break
1399
+ return entities
1400
+
1401
+
1402
+ # ═════════════════════════════════════════════════════════════════════════════
1403
+ # Utility helpers
1404
+ # ═════════════════════════════════════════════════════════════════════════════
1405
+ def _sanitize_filename(name: str) -> str:
1406
+ name = os.path.basename(name)
1407
+ name = re.sub(r"[^\w.\-]", "_", name)
1408
+ return name[:200] or "upload"
1409
+
1410
+
1411
+ def _decode_image_to_bgr(raw: bytes, ext: str) -> "np.ndarray":
1412
+ """Decode raw bytes to a BGR numpy array for RapidOCR and cv2."""
1413
+ import cv2
1414
+ if ext in {"heic", "heif"}:
1415
+ try:
1416
+ from pillow_heif import register_heif_opener
1417
+ register_heif_opener()
1418
+ except ImportError:
1419
+ raise _err("decode", "HEIF_NOT_SUPPORTED",
1420
+ "HEIC/HEIF requires pillow-heif.", 415,
1421
+ recommendation="Add pillow-heif to Dockerfile Layer 1.")
1422
+ try:
1423
+ pil_img = Image.open(io.BytesIO(raw)).convert("RGB")
1424
+ raw = io.BytesIO()
1425
+ pil_img.save(raw, format="PNG")
1426
+ raw = raw.getvalue()
1427
+ except Exception as exc:
1428
+ raise _err("decode", "HEIF_DECODE_FAILED", f"HEIF decode error: {exc}") from exc
1429
+
1430
+ arr = np.frombuffer(raw, np.uint8)
1431
+ img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
1432
+ if img is None:
1433
+ # Fallback: use Pillow then convert
1434
+ try:
1435
+ pil_img = Image.open(io.BytesIO(raw)).convert("RGB")
1436
+ img = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
1437
+ except Exception as exc:
1438
+ raise _err("decode", "IMAGE_DECODE_FAILED",
1439
+ f"Could not decode image as BGR: {exc}", 422,
1440
+ root_cause=str(exc),
1441
+ recommendation="Ensure file is a valid image (not corrupted).") from exc
1442
+ return img
1443
+
1444
+
1445
+ def _convert_to_png(raw: bytes, ext: str) -> bytes:
1446
+ """Convert Pillow-supported format to PNG bytes."""
1447
+ if ext in {"heic", "heif"}:
1448
+ try:
1449
+ from pillow_heif import register_heif_opener
1450
+ register_heif_opener()
1451
+ except ImportError:
1452
+ raise _err("decode", "HEIF_NOT_SUPPORTED",
1453
+ "HEIC/HEIF requires pillow-heif.", 415,
1454
+ recommendation="Add pillow-heif to Dockerfile Layer 1.")
1455
+ try:
1456
+ img = Image.open(io.BytesIO(raw)).convert("RGB")
1457
+ buf = io.BytesIO()
1458
+ img.save(buf, format="PNG")
1459
+ return buf.getvalue()
1460
+ except Exception as exc:
1461
+ raise _err("decode", "IMAGE_DECODE_FAILED",
1462
+ f"Pillow could not open image: {exc}", 422) from exc
1463
+
1464
+
1465
+ def _markdown_to_plain(markdown: str) -> str:
1466
+ """Strip Markdown syntax to produce plain text."""
1467
+ text = re.sub(r"!\[.*?\]\(.*?\)", "", markdown) # images
1468
+ text = re.sub(r"\[([^\]]+)\]\([^\)]+\)", r"\1", text) # links
1469
+ text = re.sub(r"#{1,6}\s*", "", text) # headings
1470
+ text = re.sub(r"\*{1,2}([^*]+)\*{1,2}", r"\1", text) # bold/italic
1471
+ text = re.sub(r"`{1,3}[^`]*`{1,3}", "", text) # code
1472
+ text = re.sub(r"\|", " ", text) # table pipes
1473
+ text = re.sub(r"-{3,}", "", text) # hr
1474
+ text = re.sub(r"\n{3,}", "\n\n", text) # excess newlines
1475
+ return text.strip()
1476
+
1477
+
1478
+ def _pdf_page_count(raw: bytes) -> int:
1479
+ try:
1480
+ doc = fitz.open(stream=raw, filetype="pdf")
1481
+ count = doc.page_count
1482
+ doc.close()
1483
+ return count
1484
+ except Exception:
1485
+ return 0
1486
+
1487
+
1488
+ def _safe_content_list(pipe_result: Any, images_dir: str) -> list[dict]:
1489
+ try:
1490
+ return pipe_result.get_content_list(images_dir) or []
1491
+ except Exception:
1492
+ return []
1493
+
1494
+
1495
+ def _count_images(content_list: list[dict]) -> int:
1496
+ return sum(1 for item in content_list if item.get("type") == "image")
1497
+
1498
+
1499
+ def _count_tables(content_list: list[dict]) -> int:
1500
+ return sum(1 for item in content_list if item.get("type") == "table")
1501
+
1502
+
1503
+ def _count_formulas(content_list: list[dict]) -> int:
1504
+ return sum(
1505
+ 1 for item in content_list
1506
+ if item.get("type") in {"equation", "formula", "interline_equation"}
1507
+ )
1508
+
1509
+
1510
+ def _count_tables_in_text(text: str) -> int:
1511
+ """Rough table count for plain-text output (count delimiter rows)."""
1512
+ return len(re.findall(r"^\s*\|[-\s|]+\|\s*$", text, re.M))
1513
+
1514
+
1515
+ # ─────────────────────────────────────────────────────────────────────────────
1516
+ # Memory β€” cgroup-aware (fixes "105 GB / 123 GB" /proc/meminfo host bleed)
1517
+ # ─────────────────────────────────────────────────────────────────────────────
1518
+ def _mem_mb() -> tuple[int, int]:
1519
+ try:
1520
+ with open("/sys/fs/cgroup/memory.max") as f:
1521
+ raw_max = f.read().strip()
1522
+ if raw_max != "max":
1523
+ limit_bytes = int(raw_max)
1524
+ with open("/sys/fs/cgroup/memory.current") as f:
1525
+ used_bytes = int(f.read().strip())
1526
+ if limit_bytes > 0:
1527
+ return used_bytes // (1024 * 1024), limit_bytes // (1024 * 1024)
1528
+ except (FileNotFoundError, ValueError, OSError):
1529
+ pass
1530
+
1531
+ try:
1532
+ with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
1533
+ limit_bytes = int(f.read().strip())
1534
+ with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
1535
+ used_bytes = int(f.read().strip())
1536
+ if limit_bytes < 128 * 1024 * 1024 * 1024:
1537
+ return used_bytes // (1024 * 1024), limit_bytes // (1024 * 1024)
1538
+ except (FileNotFoundError, ValueError, OSError):
1539
+ pass
1540
+
1541
+ try:
1542
+ info: dict[str, int] = {}
1543
+ with open("/proc/meminfo") as f:
1544
+ for line in f:
1545
+ parts = line.split()
1546
+ if len(parts) >= 2:
1547
+ info[parts[0].rstrip(":")] = int(parts[1])
1548
+ total_kb = info.get("MemTotal", 0)
1549
+ avail_kb = info.get("MemAvailable", 0)
1550
+ return (total_kb - avail_kb) // 1024, total_kb // 1024
1551
+ except Exception:
1552
+ return 0, 0
1553
+
1554
+
1555
+ def _assert_memory_safe(raw: bytes, ext: str) -> None:
1556
+ used_mb, total_mb = _mem_mb()
1557
+ if total_mb == 0:
1558
+ return
1559
+ available_mb = total_mb - used_mb
1560
+ if ext in PDF_EXTENSIONS:
1561
+ page_count = max(1, _pdf_page_count(raw))
1562
+ estimated_mb = (page_count * BYTES_PER_OCR_PAGE) // (1024 * 1024)
1563
+ else:
1564
+ try:
1565
+ if ext in {"heic", "heif"}:
1566
+ try:
1567
+ from pillow_heif import register_heif_opener
1568
+ register_heif_opener()
1569
+ except ImportError:
1570
+ pass
1571
+ img = Image.open(io.BytesIO(raw))
1572
+ w, h = img.size
1573
+ channels = len(img.getbands()) or 3
1574
+ img.close()
1575
+ estimated_mb = w * h * channels * IMAGE_MEMORY_FACTOR // (1024 * 1024)
1576
+ except Exception:
1577
+ estimated_mb = len(raw) * 20 // (1024 * 1024)
1578
+
1579
+ free_after = available_mb - estimated_mb
1580
+ logger.info("Memory check: avail=%d MB est=%d MB free_after=%d MB",
1581
+ available_mb, estimated_mb, free_after)
1582
+ if free_after < MEM_SAFETY_FLOOR_MB:
1583
+ raise _err(
1584
+ "validation", "LOW_MEMORY",
1585
+ f"Insufficient memory. Available: {available_mb} MB, "
1586
+ f"Estimated needed: {estimated_mb} MB.",
1587
+ 507,
1588
+ root_cause=f"Container has {available_mb} MB available; pipeline needs ~{estimated_mb} MB.",
1589
+ recommendation="Wait for active requests to complete, or use a smaller file.",
1590
+ )
1591
+
1592
+
1593
+ def _mineru_version() -> str:
1594
+ for pkg in ("magic-pdf", "mineru"):
1595
+ try:
1596
+ return pkg_version(pkg)
1597
+ except Exception:
1598
+ continue
1599
+ return "unknown"
1600
+
1601
+
1602
+ def _load_config_safe() -> dict[str, Any]:
1603
+ try:
1604
+ import json
1605
+ with open(os.path.expanduser("~/magic-pdf.json")) as f:
1606
+ return json.load(f)
1607
+ except Exception:
1608
+ return {}
requirements.txt ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reference only β€” dependencies are installed directly in the Dockerfile
2
+ # to allow layered pip caching. See Dockerfile for the authoritative install order.
3
+ #
4
+ # ── Layer 1 β€” FastAPI + lightweight runtime deps ──────────────────────────────
5
+ fastapi>=0.115.0
6
+ uvicorn[standard]>=0.32.0
7
+ python-multipart>=0.0.12
8
+ Pillow>=10.0.0
9
+ pillow-heif>=0.18.0
10
+ huggingface_hub>=0.25.0
11
+ opencv-python-headless>=4.8.0 # placeholder; force-reinstalled in Layer 4
12
+ #
13
+ # ── Layer 2 β€” CPU-only PyTorch ────────────────────────────────────────────────
14
+ # pip install --index-url https://download.pytorch.org/whl/cpu torch torchvision
15
+ # MUST come before magic-pdf. PyPI serves the CUDA wheel by default (~2.5 GB).
16
+ # Pre-installing the CPU build causes pip to skip the CUDA wheel when resolving
17
+ # magic-pdf's `torch` requirement.
18
+ torch>=2.2.2,!=2.5.0,!=2.5.1,<3
19
+ torchvision>=0.15.2
20
+ #
21
+ # ── Layer 3 β€” magic-pdf with CORRECT extras ───────────────────────────────────
22
+ # pip install --extra-index-url https://myhloli.github.io/wheels/ magic-pdf[full]==1.3.12
23
+ #
24
+ # FORENSIC SUMMARY:
25
+ #
26
+ # [full-cpu] is NOT a valid extra in magic-pdf 1.3.12.
27
+ # Valid extras: [full], [full_old_linux], [lite]
28
+ # Using an invalid extra causes pip to install base-only β€” omitting
29
+ # ultralytics, doclayout-yolo, rapid-table, and OCR support entirely.
30
+ #
31
+ # [full] provides:
32
+ # ultralytics >=8.3.48 YOLO framework, required by doclayout-yolo
33
+ # doclayout-yolo ==0.0.2b1 layout detection (myhloli index only)
34
+ # rapid-table >=1.0.5 table detection (onnxruntime pulled as transitive dep)
35
+ # shapely, pyclipper used by paddleocr2pytorch (baked into magic-pdf wheel)
36
+ # omegaconf, matplotlib, ftfy, dill, PyYAML, openai, albumentations
37
+ #
38
+ # [lite] is NOT used because:
39
+ # - paddlepaddle==3.0.0b1 pinned by [lite] does not exist on PyPI (removed beta)
40
+ # - paddleocr==2.7.3 requires opencv-python <=4.6.0.66, incompatible with
41
+ # ultralytics (>=4.6.0) and doclayout-yolo (>=4.6.0)
42
+ # - paddlepaddle/paddleocr are NOT needed: pipeline backend uses paddleocr2pytorch,
43
+ # a self-contained PyTorch reimplementation bundled inside the magic-pdf wheel
44
+ #
45
+ # --extra-index-url https://myhloli.github.io/wheels/ is required because
46
+ # doclayout-yolo==0.0.2b1 is only on the myhloli wheel server, not on PyPI.
47
+ magic-pdf[full]==1.3.12
48
+ #
49
+ # ── Layer 4 β€” Restore headless OpenCV (MUST be last) ─────────────────────────
50
+ # pip install --force-reinstall opencv-python-headless>=4.8.0
51
+ # Layer 3 installs opencv-python (non-headless) via doclayout-yolo + ultralytics
52
+ # + rapid-table transitive deps. Force-reinstalling headless overwrites cv2 with
53
+ # the build that works on this container without X11 libs.
54
+ opencv-python-headless>=4.8.0 # force-reinstalled in Layer 4
validate.py ADDED
@@ -0,0 +1,633 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Pre-flight validation script for MinerU OCR Service.
4
+
5
+ Run by entrypoint.sh BEFORE uvicorn starts.
6
+ Exits 0 if all checks pass.
7
+ Exits 1 if any CRITICAL check fails β€” this crashes the container loudly
8
+ so Hugging Face logs show an actionable error instead of a silent crash
9
+ or a healthy-looking service that fails on every request.
10
+
11
+ Usage:
12
+ python validate.py # run all checks, exit 0/1
13
+ python validate.py --soft # run all checks, always exit 0 (log only)
14
+
15
+ ── FORENSIC NOTES (2025-06) ──────────────────────────────────────────────────
16
+
17
+ OCR engine:
18
+ The pipeline (full) backend uses paddleocr2pytorch β€” a self-contained
19
+ PyTorch reimplementation of PaddleOCR bundled inside the magic-pdf wheel.
20
+ It uses: torch, cv2, numpy, pyclipper, shapely, yaml.
21
+ paddlepaddle and paddleocr packages are NOT installed and NOT needed.
22
+
23
+ pp_structure_v2.py (which imports paddleocr) is only loaded in 'lite' model
24
+ mode. Pipeline backend always uses 'full' mode (CustomPEKModel). That file is
25
+ never imported at runtime.
26
+
27
+ OCR model path resolution (from pytorch_paddle.py):
28
+ ocr_models_dir = os.path.join(get_local_models_dir(), 'OCR', 'paddleocr_torch')
29
+ det_model_path = os.path.join(ocr_models_dir, det_filename)
30
+ where det_filename comes from models_config.yml keyed by language.
31
+
32
+ Default CPU path: lang='ch' β†’ forced to 'ch_lite' on CPU device.
33
+ After Dockerfile Layer 3.5 patch:
34
+ ch_lite.det = ch_PP-OCRv5_det_infer.pth (was ch_PP-OCRv3 β€” not in HF repo)
35
+ ch_lite.rec = ch_PP-OCRv5_rec_infer.pth (unchanged β€” already in HF repo)
36
+
37
+ Arch config lookup (from pytorchocr_utility.py):
38
+ get_arch_config(model_path) uses Path(model_path).stem as the key into
39
+ arch_config.yaml (bundled in magic-pdf wheel). Both replacement filenames
40
+ have entries in arch_config.yaml β€” verified before patch was written.
41
+
42
+ OpenCV conflict handling:
43
+ doclayout-yolo, ultralytics, and rapid-table all declare opencv-python
44
+ (non-headless) as a required dep. pip installs the full build in Layer 3.
45
+ Layer 4 force-reinstalls opencv-python-headless to overwrite cv2. Both
46
+ packages expose an identical cv2 API so all callers work correctly at
47
+ runtime. pip-check shows warnings but they are harmless.
48
+
49
+ onnxruntime:
50
+ rapid-table declares onnxruntime>1.17.0 as a required (non-optional) dep.
51
+ pip resolves it automatically when magic-pdf[full] is installed in Layer 3.
52
+
53
+ slanet-plus.onnx (table model):
54
+ Bundled inside the magic-pdf wheel at:
55
+ magic_pdf/resources/slanet_plus/slanet-plus.onnx
56
+ NOT downloaded from HF Hub β€” no separate download needed.
57
+ """
58
+
59
+ import importlib
60
+ import json
61
+ import os
62
+ import shutil
63
+ import sys
64
+ import tempfile
65
+ import traceback
66
+
67
+ SOFT_MODE = "--soft" in sys.argv # never exit 1, just print
68
+
69
+ MODELS_DIR = "/app/models"
70
+ EXTRACT_KIT_MODELS = os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0", "models")
71
+ LAYOUT_MARKER = os.path.join(EXTRACT_KIT_MODELS, "Layout") # canary directory
72
+ CONFIG_PATH = os.path.expanduser("~/magic-pdf.json")
73
+
74
+
75
+ # ── helpers ────────────────────────────────────────────────────────────────────
76
+ def ok(label: str, detail: str = "") -> None:
77
+ suffix = f" ({detail})" if detail else ""
78
+ print(f" βœ“ {label}{suffix}", flush=True)
79
+
80
+
81
+ def fail(label: str, detail: str, critical: bool = True) -> None:
82
+ tag = "CRITICAL" if critical else "WARNING"
83
+ print(f" βœ— [{tag}] {label}: {detail}", flush=True)
84
+
85
+
86
+ def section(title: str) -> None:
87
+ print(f"\n{'─' * 60}", flush=True)
88
+ print(f" {title}", flush=True)
89
+ print(f"{'─' * 60}", flush=True)
90
+
91
+
92
+ # ── check registry ─────────────────────────────────────────────────────────────
93
+ failures: list[tuple[str, str]] = []
94
+ warnings: list[tuple[str, str]] = []
95
+
96
+
97
+ def record_fail(label: str, detail: str, critical: bool = True) -> None:
98
+ fail(label, detail, critical)
99
+ if critical:
100
+ failures.append((label, detail))
101
+ else:
102
+ warnings.append((label, detail))
103
+
104
+
105
+ # ═══════════════════════════════════════════════════════════════════════════════
106
+ print("\n" + "═" * 60, flush=True)
107
+ print(" MinerU OCR Service β€” Pre-flight Validation", flush=True)
108
+ print("═" * 60, flush=True)
109
+
110
+ # ── 1. Python version ──────────────────────────────────────────────────────────
111
+ section("1. Python runtime")
112
+ pv = sys.version_info
113
+ if pv >= (3, 10):
114
+ ok("Python version", f"{pv.major}.{pv.minor}.{pv.micro}")
115
+ else:
116
+ record_fail("Python version",
117
+ f"{pv.major}.{pv.minor} detected β€” magic-pdf requires >= 3.10")
118
+
119
+ # ── 2. cv2 ─────────────────────────────────────────────────────────────────────
120
+ section("2. OpenCV (cv2)")
121
+ try:
122
+ import cv2
123
+ ok("cv2 import", f"version {cv2.__version__}")
124
+ build = cv2.getBuildInformation()
125
+ if "GTK" in build or "Qt" in build:
126
+ record_fail("cv2 build", "GUI backend detected β€” use opencv-python-headless",
127
+ critical=False)
128
+ else:
129
+ ok("cv2 headless", "no GUI backend detected")
130
+ except ImportError as exc:
131
+ record_fail(
132
+ "cv2 import",
133
+ f"{exc}. "
134
+ "Layer 4 force-reinstall of opencv-python-headless may have failed. "
135
+ "Check Docker build log for the 'pip install --force-reinstall opencv-python-headless' step.",
136
+ )
137
+ except Exception as exc:
138
+ record_fail("cv2 import", f"unexpected error: {exc}")
139
+
140
+ # ── 3. PyTorch ─────────────────────────────────────────────────────────────────
141
+ section("3. PyTorch + TorchVision")
142
+ try:
143
+ import torch
144
+ ok("torch import", f"version {torch.__version__}")
145
+ if torch.cuda.is_available():
146
+ record_fail("torch CUDA", "CUDA detected on CPU-only space β€” unexpected",
147
+ critical=False)
148
+ else:
149
+ ok("torch device", "CPU-only (expected for free tier)")
150
+ except ImportError as exc:
151
+ record_fail(
152
+ "torch import",
153
+ f"{exc}. "
154
+ "Install from PyTorch CPU index BEFORE magic-pdf in Dockerfile Layer 2: "
155
+ "pip install --index-url https://download.pytorch.org/whl/cpu torch torchvision",
156
+ )
157
+ except Exception as exc:
158
+ record_fail("torch import", f"unexpected: {exc}")
159
+
160
+ try:
161
+ import torchvision
162
+ ok("torchvision import", f"version {torchvision.__version__}")
163
+ except ImportError as exc:
164
+ record_fail("torchvision import", str(exc))
165
+ except Exception as exc:
166
+ record_fail("torchvision import", f"unexpected: {exc}")
167
+
168
+ # ── 4. ultralytics ─────────────────────────────────────────────────────────────
169
+ section("4. ultralytics (YOLO β€” required by doclayout_yolo)")
170
+ try:
171
+ import ultralytics
172
+ ok("ultralytics import", f"version {ultralytics.__version__}")
173
+ except ImportError as exc:
174
+ record_fail(
175
+ "ultralytics import",
176
+ f"{exc}. "
177
+ "Provided by magic-pdf[full]. "
178
+ "ROOT CAUSE: [full-cpu] is NOT a valid extra in magic-pdf 1.3.12 β€” "
179
+ "pip silently installed only the base package when given an unknown extra. "
180
+ "Dockerfile Layer 3 must use magic-pdf[full]==1.3.12 (not [full-cpu]).",
181
+ )
182
+ except Exception as exc:
183
+ record_fail("ultralytics import", f"unexpected: {exc}")
184
+
185
+ # ── 5. doclayout_yolo ──────────────────────────────────────────────────────────
186
+ section("5. doclayout_yolo (layout detection model)")
187
+ try:
188
+ import doclayout_yolo
189
+ ok("doclayout_yolo import", f"version {getattr(doclayout_yolo, '__version__', 'unknown')}")
190
+ except ImportError as exc:
191
+ record_fail(
192
+ "doclayout_yolo import",
193
+ f"{exc}. "
194
+ "Provided by magic-pdf[full] (version 0.0.2b1). "
195
+ "doclayout-yolo==0.0.2b1 is only on the myhloli custom wheel index β€” "
196
+ "Dockerfile Layer 3 must include: "
197
+ "--extra-index-url https://myhloli.github.io/wheels/",
198
+ )
199
+ except Exception as exc:
200
+ record_fail("doclayout_yolo import", f"unexpected: {exc}")
201
+
202
+ # ── 6. rapid_table ─────────────────────────────────────────────────────────────
203
+ section("6. rapid_table (table extraction)")
204
+ try:
205
+ import rapid_table
206
+ ok("rapid_table import", f"version {getattr(rapid_table, '__version__', 'unknown')}")
207
+ except ImportError as exc:
208
+ record_fail(
209
+ "rapid_table import",
210
+ f"{exc}. Provided by magic-pdf[full]. Check Layer 3 install.",
211
+ )
212
+ except Exception as exc:
213
+ record_fail("rapid_table import", f"unexpected: {exc}")
214
+
215
+ # ── 7. onnxruntime ─────────────────────────────────────────────────────────────
216
+ section("7. onnxruntime (required by rapid-table for table model inference)")
217
+ # onnxruntime is a required (non-optional) dep of rapid-table>=1.0.5.
218
+ # pip resolves it automatically when magic-pdf[full] is installed in Layer 3.
219
+ # If it is missing it means rapid-table itself failed to install.
220
+ try:
221
+ import onnxruntime
222
+ ok("onnxruntime import", f"version {onnxruntime.__version__}")
223
+ except ImportError as exc:
224
+ record_fail(
225
+ "onnxruntime import",
226
+ f"{exc}. "
227
+ "onnxruntime is a required dep of rapid-table>=1.0.5. "
228
+ "Its absence means rapid-table failed to install in Layer 3. "
229
+ "Check Docker build log for rapid-table install errors.",
230
+ )
231
+ except Exception as exc:
232
+ record_fail("onnxruntime import", f"unexpected: {exc}")
233
+
234
+ # ── 8. magic_pdf core imports ──────────────────────────────────────────────────
235
+ section("8. magic_pdf core imports")
236
+
237
+ REQUIRED_IMPORTS = [
238
+ ("magic_pdf.data.dataset", ["PymuDocDataset", "ImageDataset"]),
239
+ ("magic_pdf.data.data_reader_writer", ["FileBasedDataReader", "FileBasedDataWriter"]),
240
+ ("magic_pdf.model.doc_analyze_by_custom_model", ["doc_analyze"]),
241
+ ("magic_pdf.config.enums", ["SupportedPdfParseMethod"]),
242
+ ]
243
+
244
+ for module_path, symbols in REQUIRED_IMPORTS:
245
+ try:
246
+ mod = importlib.import_module(module_path)
247
+ missing = [s for s in symbols if not hasattr(mod, s)]
248
+ if missing:
249
+ record_fail(f"{module_path}", f"missing symbols: {missing}")
250
+ else:
251
+ ok(module_path, ", ".join(symbols))
252
+ except ImportError as exc:
253
+ record_fail(module_path, str(exc))
254
+ except Exception as exc:
255
+ record_fail(module_path, f"unexpected: {exc}")
256
+
257
+ # ── 8b. paddleocr2pytorch (OCR engine bundled inside magic-pdf wheel) ──────────
258
+ section("8b. paddleocr2pytorch (PyTorch OCR β€” bundled in magic-pdf wheel)")
259
+ # This is the actual OCR engine for the pipeline backend.
260
+ # It is NOT a separate pip package β€” it lives inside the magic-pdf wheel at
261
+ # magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/
262
+ # If it is missing, the entire magic-pdf package did not install correctly.
263
+ try:
264
+ from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.pytorch_paddle import PytorchPaddleOCR
265
+ ok("PytorchPaddleOCR (paddleocr2pytorch)", "bundled inside magic-pdf wheel β€” no paddlepaddle pkg needed")
266
+ except ImportError as exc:
267
+ record_fail(
268
+ "PytorchPaddleOCR import",
269
+ f"{exc}. "
270
+ "This module is bundled inside magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/. "
271
+ "If missing, magic-pdf itself did not install correctly.",
272
+ )
273
+ except Exception as exc:
274
+ record_fail("PytorchPaddleOCR import", f"unexpected: {exc}")
275
+
276
+ # ── 8c. Deprecated API check ───────────────────────────────────────────────────
277
+ section("8c. Deprecated API check (should NOT exist)")
278
+ OBSOLETE = [
279
+ "magic_pdf.pipe.UNIPipe",
280
+ "magic_pdf.rw.DiskReaderWriter",
281
+ ]
282
+ for mod_path in OBSOLETE:
283
+ try:
284
+ importlib.import_module(mod_path)
285
+ record_fail(mod_path, "still importable β€” code may use old API", critical=False)
286
+ except ImportError:
287
+ ok(f"{mod_path} (correctly absent)")
288
+
289
+ # ── 9. End-to-end pipeline smoke test ─────────────────────────────────────────
290
+ section("9. End-to-end pipeline smoke test")
291
+ try:
292
+ from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze # noqa: F401
293
+ import ultralytics # noqa: F401
294
+ from magic_pdf.data.dataset import ImageDataset # noqa: F401
295
+ from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter # noqa: F401
296
+ ok("Pipeline imports (doc_analyze + ultralytics + ImageDataset + readers)", "all OK")
297
+ except ImportError as exc:
298
+ record_fail(
299
+ "Pipeline smoke test",
300
+ f"Full pipeline import chain failed: {exc}. "
301
+ "This means POST /extract will fail on every request.",
302
+ )
303
+ except Exception as exc:
304
+ record_fail("Pipeline smoke test", f"unexpected: {exc}")
305
+
306
+ # ── 10. Config file ────────────────────────────────────────────────────────────
307
+ section("10. MinerU config (magic-pdf.json)")
308
+ _cfg: dict = {}
309
+ if os.path.exists(CONFIG_PATH):
310
+ try:
311
+ with open(CONFIG_PATH) as f:
312
+ _cfg = json.load(f)
313
+ required_keys = ["models-dir", "device-mode"]
314
+ missing_keys = [k for k in required_keys if k not in _cfg]
315
+ if missing_keys:
316
+ record_fail("Config keys", f"missing: {missing_keys}")
317
+ else:
318
+ ok("Config file", CONFIG_PATH)
319
+ ok("device-mode", _cfg.get("device-mode", "?"))
320
+ ok("models-dir", _cfg.get("models-dir", "?"))
321
+ ok("formula-enable", str(_cfg.get("formula-config", {}).get("enable", "?")))
322
+ ok("table-enable", str(_cfg.get("table-config", {}).get("enable", "?")))
323
+ except json.JSONDecodeError as exc:
324
+ record_fail("Config file", f"invalid JSON: {exc}")
325
+ except Exception as exc:
326
+ record_fail("Config file", str(exc))
327
+ else:
328
+ record_fail(
329
+ "Config file",
330
+ f"not found at {CONFIG_PATH}. "
331
+ "Run download_models.py or check Docker build log.",
332
+ )
333
+
334
+ # ── 11. Model directory structure ─────────────────────────────────────────────
335
+ section("11. Model directory structure")
336
+
337
+ model_dir_checks = [
338
+ ("PDF-Extract-Kit-1.0 root", os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0")),
339
+ ("Layout models", os.path.join(EXTRACT_KIT_MODELS, "Layout")),
340
+ ("Layout/YOLO", os.path.join(EXTRACT_KIT_MODELS, "Layout", "YOLO")),
341
+ ("OCR models", os.path.join(EXTRACT_KIT_MODELS, "OCR")),
342
+ ("OCR/paddleocr_torch", os.path.join(EXTRACT_KIT_MODELS, "OCR", "paddleocr_torch")),
343
+ ("Table models (TabRec)", os.path.join(EXTRACT_KIT_MODELS, "TabRec")),
344
+ ]
345
+
346
+ for label, path in model_dir_checks:
347
+ if os.path.isdir(path):
348
+ try:
349
+ n = sum(1 for _ in os.scandir(path))
350
+ ok(label, f"{n} entries [{path}]")
351
+ except OSError:
352
+ ok(label, path)
353
+ else:
354
+ record_fail(label, f"directory not found: {path}")
355
+
356
+ lr_dir = os.path.join(MODELS_DIR, "layoutreader")
357
+ if os.path.isdir(lr_dir):
358
+ ok("layoutreader (optional)", lr_dir)
359
+ else:
360
+ record_fail("layoutreader (optional)",
361
+ "not found β€” MinerU will use fallback ordering (non-critical)",
362
+ critical=False)
363
+
364
+ # ── 11b. Critical model weight files ──────────────────────────────────────────
365
+ section("11b. Critical model weight files")
366
+ #
367
+ # These are the EXACT files MinerU will try to open when processing a document
368
+ # on a CPU deployment (default language = ch β†’ forced to ch_lite on CPU).
369
+ #
370
+ # After Dockerfile Layer 3.5 patch, models_config.yml now references:
371
+ # ch_lite.det = ch_PP-OCRv5_det_infer.pth (patched from v3 β€” v3 NOT in repo)
372
+ # ch_lite.rec = ch_PP-OCRv5_rec_infer.pth (unchanged β€” always in repo)
373
+ #
374
+ # Layout uses doclayout_yolo (from magic-pdf.json layout-config).
375
+ # Table (rapid_table) uses slanet-plus.onnx BUNDLED IN THE WHEEL β€” not here.
376
+ # Formula is DISABLED β€” MFD/MFR files not required.
377
+ #
378
+ # Any CRITICAL failure here = service boots but crashes on first document.
379
+
380
+ _ocr_dir = os.path.join(EXTRACT_KIT_MODELS, "OCR", "paddleocr_torch")
381
+
382
+ CRITICAL_WEIGHT_FILES: list[tuple[str, str, str]] = [
383
+ # (label, relative-to-EXTRACT_KIT_MODELS, reason)
384
+ (
385
+ "OCR det weight (ch_lite, default CPU lang)",
386
+ os.path.join("OCR", "paddleocr_torch", "ch_PP-OCRv5_det_infer.pth"),
387
+ "Patched from ch_PP-OCRv3_det_infer.pth (absent in HF repo). "
388
+ "Missing = all OCR will crash at model load time."
389
+ ),
390
+ (
391
+ "OCR rec weight (ch_lite)",
392
+ os.path.join("OCR", "paddleocr_torch", "ch_PP-OCRv5_rec_infer.pth"),
393
+ "Recognition model for ch_lite. "
394
+ "Missing = OCR loads det but crashes at recognition."
395
+ ),
396
+ (
397
+ "OCR cls weight (angle classifier)",
398
+ os.path.join("OCR", "paddleocr_torch", "ch_ptocr_mobile_v2.0_cls_infer.pth"),
399
+ "Used when use_angle_cls=True. Default is False so non-critical, "
400
+ "but its absence causes crash if angle classification is enabled."
401
+ ),
402
+ (
403
+ "Layout YOLO weight (doclayout_yolo)",
404
+ os.path.join("Layout", "YOLO", "doclayout_yolo_docstructbench_imgsz1280_2501.pt"),
405
+ "Layout detection model. Missing = layout detection crashes on every document."
406
+ ),
407
+ (
408
+ "Layout LayoutLMv3 weight",
409
+ os.path.join("Layout", "LayoutLMv3", "model_final.pth"),
410
+ "Alternative layout model. Required even when doclayout_yolo is primary "
411
+ "because model_configs.yaml always lists it."
412
+ ),
413
+ (
414
+ "Multilingual OCR det (en/latin fallback)",
415
+ os.path.join("OCR", "paddleocr_torch", "Multilingual_PP-OCRv3_det_infer.pth"),
416
+ "Patched det for en and latin languages. Missing = crash if lang=en/latin."
417
+ ),
418
+ ]
419
+
420
+ # cls weight is only critical if use_angle_cls=True (default False)
421
+ NON_CRITICAL_LABELS = {"OCR cls weight (angle classifier)"}
422
+
423
+ for label, rel_path, reason in CRITICAL_WEIGHT_FILES:
424
+ full_path = os.path.join(EXTRACT_KIT_MODELS, rel_path)
425
+ is_critical = label not in NON_CRITICAL_LABELS
426
+ if os.path.isfile(full_path):
427
+ size_mb = os.path.getsize(full_path) / (1024 * 1024)
428
+ ok(label, f"{size_mb:.1f} MB [{full_path}]")
429
+ else:
430
+ record_fail(
431
+ label,
432
+ f"FILE NOT FOUND: {full_path}\n"
433
+ f" Reason: {reason}",
434
+ critical=is_critical,
435
+ )
436
+
437
+ # ── 11c. models_config.yml consistency check ──────────────────────────────────
438
+ section("11c. models_config.yml consistency check")
439
+ #
440
+ # Reads the installed models_config.yml (inside magic_pdf package) and verifies
441
+ # that every det/rec file it references for the default CPU language (ch_lite)
442
+ # actually exists on disk in the expected location.
443
+ #
444
+ # This catches future version drift between the magic-pdf package and the HF repo
445
+ # BEFORE the service starts, rather than mid-request.
446
+
447
+ try:
448
+ import magic_pdf
449
+ import yaml as _yaml
450
+ from pathlib import Path as _Path
451
+
452
+ _pkg = _Path(magic_pdf.__file__).parent
453
+ _mcfg = _pkg / 'model/sub_modules/ocr/paddleocr2pytorch/pytorchocr/utils/resources/models_config.yml'
454
+
455
+ if not _mcfg.exists():
456
+ record_fail("models_config.yml", f"not found at expected path: {_mcfg}")
457
+ else:
458
+ with open(_mcfg) as _f:
459
+ _mc = _yaml.safe_load(_f)
460
+
461
+ _ocr_torch = os.path.join(EXTRACT_KIT_MODELS, "OCR", "paddleocr_torch")
462
+
463
+ # Check the two languages actually used on this CPU deployment
464
+ _check_langs = ["ch_lite", "ch"]
465
+ _mc_ok = True
466
+ for _lang in _check_langs:
467
+ _entry = _mc.get("lang", {}).get(_lang, {})
468
+ for _field in ("det", "rec"):
469
+ _fname = _entry.get(_field)
470
+ if not _fname:
471
+ continue
472
+ _fpath = os.path.join(_ocr_torch, _fname)
473
+ if os.path.isfile(_fpath):
474
+ ok(f"models_config[{_lang}].{_field}", _fname)
475
+ else:
476
+ record_fail(
477
+ f"models_config[{_lang}].{_field}",
478
+ f"Config references '{_fname}' but file not found at:\n"
479
+ f" {_fpath}\n"
480
+ f" Dockerfile Layer 3.5 patch may not have run, "
481
+ f"or HF repo changed its file structure again.",
482
+ critical=True,
483
+ )
484
+ _mc_ok = False
485
+
486
+ if _mc_ok:
487
+ ok("models_config.yml consistency", "all referenced det/rec files exist on disk")
488
+
489
+ except Exception as _exc:
490
+ record_fail("models_config.yml consistency check", f"unexpected error: {_exc}", critical=False)
491
+
492
+ # ── 11d. Bundled wheel resources ──────────────────────────────────────────────
493
+ section("11d. Bundled wheel resources (inside magic_pdf package)")
494
+ #
495
+ # These files are shipped inside the magic-pdf wheel itself.
496
+ # They do NOT come from the HF download. Their absence means the wheel
497
+ # installed incorrectly or was corrupted.
498
+
499
+ try:
500
+ import magic_pdf as _mp
501
+ from pathlib import Path as _P
502
+
503
+ _pkg_root = _P(_mp.__file__).parent
504
+ _bundled = [
505
+ ("slanet-plus.onnx (table model)",
506
+ _pkg_root / "resources" / "slanet_plus" / "slanet-plus.onnx"),
507
+ ("fasttext langdetect model",
508
+ _pkg_root / "resources" / "fasttext-langdetect" / "lid.176.ftz"),
509
+ ("YOLO langdetect model",
510
+ _pkg_root / "resources" / "yolov11-langdetect" / "yolo_v11_ft.pt"),
511
+ ("model_configs.yaml (weight path map)",
512
+ _pkg_root / "resources" / "model_config" / "model_configs.yaml"),
513
+ ]
514
+ for _lbl, _p in _bundled:
515
+ if _p.exists():
516
+ _sz = _p.stat().st_size / (1024 * 1024)
517
+ ok(_lbl, f"{_sz:.2f} MB")
518
+ else:
519
+ record_fail(_lbl, f"expected inside wheel at {_p} β€” magic-pdf install may be corrupted")
520
+
521
+ except Exception as _exc:
522
+ record_fail("Bundled wheel resources check", f"unexpected: {_exc}", critical=False)
523
+
524
+ # ── 12. Temp storage ───────────────────────────────────────────────────────────
525
+ section("12. Temp storage")
526
+ try:
527
+ td = tempfile.mkdtemp(prefix="mineru_validate_")
528
+ test_file = os.path.join(td, "write_test.bin")
529
+ with open(test_file, "wb") as f:
530
+ f.write(b"x" * 4096)
531
+ assert os.path.getsize(test_file) == 4096
532
+ shutil.rmtree(td)
533
+ ok("Temp write + delete", tempfile.gettempdir())
534
+ except Exception as exc:
535
+ record_fail("Temp storage", str(exc))
536
+
537
+ # ── 13. System memory (cgroups) ────────────────────────────────────────────────
538
+ section("13. System memory (cgroups)")
539
+ mem_source = "unknown"
540
+ total_mb = used_mb = 0
541
+
542
+ try:
543
+ with open("/sys/fs/cgroup/memory.max") as f:
544
+ raw = f.read().strip()
545
+ if raw != "max":
546
+ total_mb = int(raw) // (1024 * 1024)
547
+ with open("/sys/fs/cgroup/memory.current") as f:
548
+ used_mb = int(f.read().strip()) // (1024 * 1024)
549
+ mem_source = "cgroups v2"
550
+ except (FileNotFoundError, ValueError):
551
+ pass
552
+
553
+ if total_mb == 0:
554
+ try:
555
+ with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
556
+ limit = int(f.read().strip())
557
+ with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
558
+ used_bytes = int(f.read().strip())
559
+ if limit < 128 * 1024 * 1024 * 1024:
560
+ total_mb = limit // (1024 * 1024)
561
+ used_mb = used_bytes // (1024 * 1024)
562
+ mem_source = "cgroups v1"
563
+ except (FileNotFoundError, ValueError):
564
+ pass
565
+
566
+ if total_mb == 0:
567
+ try:
568
+ info: dict[str, int] = {}
569
+ with open("/proc/meminfo") as f:
570
+ for line in f:
571
+ parts = line.split()
572
+ if len(parts) >= 2:
573
+ info[parts[0].rstrip(":")] = int(parts[1])
574
+ total_mb = info.get("MemTotal", 0) // 1024
575
+ used_mb = (info.get("MemTotal", 0) - info.get("MemAvailable", 0)) // 1024
576
+ mem_source = "/proc/meminfo (may show host RAM)"
577
+ except Exception:
578
+ pass
579
+
580
+ ok("Memory source", mem_source)
581
+ ok("Total memory", f"{total_mb} MB")
582
+ ok("Used memory", f"{used_mb} MB")
583
+ ok("Free memory", f"{total_mb - used_mb} MB")
584
+
585
+ if total_mb > 32 * 1024:
586
+ record_fail(
587
+ "Memory total",
588
+ f"{total_mb} MB seems too large β€” cgroups may not be available; "
589
+ "/proc/meminfo showing host RAM. Memory guard in main.py will be conservative.",
590
+ critical=False,
591
+ )
592
+
593
+ # ── 14. /proc/meminfo sanity ───────────────────────────────────────────────────
594
+ section("14. /proc/meminfo (reference)")
595
+ try:
596
+ with open("/proc/meminfo") as f:
597
+ lines = f.readlines()[:5]
598
+ for line in lines:
599
+ parts = line.split()
600
+ if len(parts) >= 2:
601
+ kb = int(parts[1])
602
+ ok(parts[0].rstrip(":"), f"{kb // 1024} MB")
603
+ except Exception as exc:
604
+ record_fail("/proc/meminfo", str(exc), critical=False)
605
+
606
+ # ═══════════════════════════════════════════════════════════════════════════════
607
+ # Summary
608
+ # ═══════════════════════════════════════════════════════════════════════════════
609
+ print("\n" + "═" * 60, flush=True)
610
+ print(" Validation Summary", flush=True)
611
+ print("═" * 60, flush=True)
612
+
613
+ if warnings:
614
+ print(f"\n ⚠ {len(warnings)} warning(s):", flush=True)
615
+ for label, detail in warnings:
616
+ print(f" β€’ {label}: {detail}", flush=True)
617
+
618
+ if failures:
619
+ print(f"\n βœ— {len(failures)} CRITICAL failure(s):", flush=True)
620
+ for label, detail in failures:
621
+ print(f" β€’ {label}: {detail}", flush=True)
622
+ print("\n Service will NOT start until these are resolved.", flush=True)
623
+ print(" Check Dockerfile pip layers and Docker build log.", flush=True)
624
+ print("═" * 60 + "\n", flush=True)
625
+ if not SOFT_MODE:
626
+ sys.exit(1)
627
+ else:
628
+ print(f"\n βœ“ All critical checks passed", flush=True)
629
+ if warnings:
630
+ print(f" ⚠ {len(warnings)} non-critical warning(s) β€” see above", flush=True)
631
+ print("\n Service is ready to start.", flush=True)
632
+ print("═" * 60 + "\n", flush=True)
633
+ sys.exit(0)