crazylemonade commited on
Commit
b435f7c
·
verified ·
1 Parent(s): 28fa555

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -885
main.py DELETED
@@ -1,885 +0,0 @@
1
- """
2
- MinerU OCR & Document Extraction Service
3
- FastAPI application for Hugging Face Docker Space (CPU / pipeline backend)
4
-
5
- Correct imports for magic-pdf >= 1.0.x (magic_pdf module):
6
-
7
- from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter
8
- from magic_pdf.data.dataset import PymuDocDataset, ImageDataset
9
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
10
- from magic_pdf.config.enums import SupportedPdfParseMethod
11
-
12
- OBSOLETE imports (removed in magic-pdf >= 1.0, do not use):
13
- from magic_pdf.pipe.UNIPipe import UNIPipe ← removed
14
- from magic_pdf.rw.DiskReaderWriter import ... ← removed
15
- from magic_pdf.data.read_api import read_local_images ← NOT used here;
16
- function expects a single string path in 1.x but crashes with
17
- "stat: ... not list" if given a list. Use FileBasedDataReader instead.
18
-
19
- Removed features vs original:
20
- - DOCX / PPTX / XLSX (required LibreOffice; caused build OOM/timeout)
21
- - subprocess (was only used for LibreOffice conversion)
22
- - python-magic / libmagic (listed in requirements but never imported)
23
-
24
- Endpoints:
25
- GET /health — liveness (always fast, no dependency check)
26
- GET /status — full node status including memory (via cgroups), uptime,
27
- cache, active requests, lastModelLoadMs
28
- POST /extract — single file (PDF or image) with SHA256 cache + memory guard
29
- POST /batch — up to BATCH_MAX_FILES files; extras silently ignored
30
-
31
- Structured error format (all non-2xx responses from /extract and /batch):
32
- {
33
- "success": false,
34
- "stage": "upload" | "validation" | "decode" | "ocr" | "markdown" | "unknown",
35
- "errorCode": "UNSUPPORTED_TYPE" | "FILE_TOO_LARGE" | "EMPTY_FILE" |
36
- "LOW_MEMORY" | "IMAGE_DECODE_FAILED" | "OCR_PIPELINE_FAILED" |
37
- "MARKDOWN_FAILED" | "INTERNAL_ERROR",
38
- "message": "<human-readable detail>"
39
- }
40
- """
41
-
42
- import hashlib
43
- import io
44
- import os
45
- import re
46
- import shutil
47
- import sys
48
- import tempfile
49
- import threading
50
- import time
51
- import traceback
52
- import logging
53
- from importlib.metadata import version as pkg_version
54
- from typing import Any
55
-
56
- import fitz # PyMuPDF — bundled with magic-pdf[full]
57
- from PIL import Image
58
-
59
- from fastapi import FastAPI, File, UploadFile, HTTPException
60
- from fastapi.middleware.cors import CORSMiddleware
61
- from fastapi.responses import JSONResponse
62
-
63
- # ── Logging ───────────────────────────────────────────────────────────────────
64
- logging.basicConfig(
65
- level=logging.INFO,
66
- format="%(asctime)s %(levelname)-8s %(name)s %(message)s",
67
- )
68
- logger = logging.getLogger("mineru-service")
69
-
70
- # ── Start time ────────────────────────────────────────────────────────────────
71
- _START_TIME: float = time.time()
72
-
73
- # ── Upload / batch constants ──────────────────────────────────────────────────
74
- MAX_UPLOAD_BYTES = 30 * 1024 * 1024 # 30 MB
75
- BATCH_MAX_FILES = 8
76
-
77
- # ── Supported file types ──────────────────────────────────────────────────────
78
- PDF_EXTENSIONS = {"pdf"}
79
-
80
- # Natively supported by ImageDataset via FileBasedDataReader
81
- NATIVE_IMAGE_EXTENSIONS = {"jpg", "jpeg", "png"}
82
-
83
- # Need Pillow conversion to PNG before feeding to MinerU
84
- PILLOW_IMAGE_EXTENSIONS = {"webp", "bmp", "tiff", "tif", "gif", "heic", "heif", "avif"}
85
-
86
- IMAGE_EXTENSIONS = NATIVE_IMAGE_EXTENSIONS | PILLOW_IMAGE_EXTENSIONS
87
- ALLOWED_EXTENSIONS = PDF_EXTENSIONS | IMAGE_EXTENSIONS
88
-
89
- # ── Memory safety thresholds ──────────────────────────────────────────────────
90
- BYTES_PER_OCR_PAGE = 100 * 1024 * 1024 # ~100 MB / page (conservative)
91
- IMAGE_MEMORY_FACTOR = 4 # decoded pixels × 4 for pipeline buffers
92
- MEM_SAFETY_FLOOR_MB = 1024 # always keep 1 GB free
93
-
94
- # ── SHA256 extraction cache (in-process, bounded by available RAM) ────────────
95
- _cache: dict[str, dict[str, Any]] = {}
96
- _cache_lock = threading.Lock()
97
-
98
- # ── Active-request counter ────────────────────────────────────────────────────
99
- _active_requests: int = 0
100
- _active_lock = threading.Lock()
101
-
102
- # ── Model load timing ─────────────────────────────────────────────────────────
103
- _model_load_ms: int = 0
104
-
105
- # ── Startup self-test results (populated by startup handler) ──────────────────
106
- _startup_issues: list[str] = []
107
- _startup_done: bool = False
108
-
109
-
110
- # ─────────────────────────────────────────────────────────────────────────────
111
- # Structured error exception
112
- # ─────────────────────────────────────────────────────────────────────────────
113
- class ExtractionError(Exception):
114
- """
115
- Raised anywhere in the extraction pipeline to produce a structured
116
- JSON error response with stage + errorCode instead of a generic 500.
117
- """
118
- def __init__(
119
- self,
120
- stage: str,
121
- code: str,
122
- message: str,
123
- http_status: int = 422,
124
- ) -> None:
125
- self.stage = stage
126
- self.code = code
127
- self.message = message
128
- self.http_status = http_status
129
- super().__init__(message)
130
-
131
- def to_dict(self) -> dict[str, Any]:
132
- return {
133
- "success": False,
134
- "stage": self.stage,
135
- "errorCode": self.code,
136
- "message": self.message,
137
- }
138
-
139
-
140
- def _err(stage: str, code: str, msg: str, status: int = 422) -> ExtractionError:
141
- """Shorthand constructor."""
142
- return ExtractionError(stage, code, msg, status)
143
-
144
-
145
- # ─────────────────────────────────────────────────────────────────────────────
146
- # Active request helpers
147
- # ─────────────────────────────────────────────────────────────────────────────
148
- def _inc_active() -> None:
149
- global _active_requests
150
- with _active_lock:
151
- _active_requests += 1
152
-
153
-
154
- def _dec_active() -> None:
155
- global _active_requests
156
- with _active_lock:
157
- _active_requests = max(0, _active_requests - 1)
158
-
159
-
160
- # ─────────────────────────────────────────────────────────────────────────────
161
- # Pipeline readiness (lazy, first-request check)
162
- # ─────────────────────────────────────────────────────────────────────────────
163
- _pipeline_ready: bool = False
164
- _pipeline_lock = threading.Lock()
165
-
166
-
167
- def _ensure_pipeline() -> None:
168
- """
169
- Verify MinerU is importable and its config is present.
170
- Sets _pipeline_ready on first success; raises ExtractionError on failure.
171
- Checks are done under a lock so concurrent first-requests don't race.
172
- """
173
- global _pipeline_ready, _model_load_ms
174
- if _pipeline_ready:
175
- return
176
-
177
- with _pipeline_lock:
178
- if _pipeline_ready: # double-checked locking
179
- return
180
-
181
- config_path = os.path.expanduser("~/magic-pdf.json")
182
- if not os.path.exists(config_path):
183
- raise _err(
184
- "model_load", "CONFIG_MISSING",
185
- f"magic-pdf.json not found at {config_path}. "
186
- "Check Docker build log for download_models.py output.",
187
- 503,
188
- )
189
-
190
- # Trigger a lightweight import to confirm the package is usable.
191
- t0 = time.perf_counter()
192
- try:
193
- from magic_pdf.data.dataset import PymuDocDataset, ImageDataset # noqa: F401
194
- from magic_pdf.data.data_reader_writer import ( # noqa: F401
195
- FileBasedDataReader, FileBasedDataWriter,
196
- )
197
- except ImportError as exc:
198
- raise _err(
199
- "model_load", "IMPORT_FAILED",
200
- f"magic_pdf not importable: {exc}. Check Dockerfile pip layers.",
201
- 503,
202
- ) from exc
203
-
204
- _model_load_ms = int((time.perf_counter() - t0) * 1000)
205
- _pipeline_ready = True
206
- logger.info("Pipeline ready (import check: %d ms).", _model_load_ms)
207
-
208
-
209
- # ─────────────────────────────────────────────────────────────────────────────
210
- # FastAPI app
211
- # ─────────────────────────────────────────────────────────────────────────────
212
- app = FastAPI(
213
- title="MinerU OCR Service",
214
- description=(
215
- "OCR and document extraction via MinerU pipeline backend (CPU). "
216
- "Supports PDF and image files up to 30 MB."
217
- ),
218
- version="1.1.0",
219
- )
220
-
221
- app.add_middleware(
222
- CORSMiddleware,
223
- allow_origins=["*"],
224
- allow_methods=["GET", "POST"],
225
- allow_headers=["*"],
226
- )
227
-
228
-
229
- # ─────────────────────────────────────────────────────────────────────────────
230
- # Startup self-test
231
- # ─────────────────────────────────────────────────────────────────────────────
232
- @app.on_event("startup")
233
- async def startup_self_test() -> None:
234
- """
235
- Run at container startup. Verifies all critical dependencies are present.
236
- Never crashes the server — issues are stored in _startup_issues and
237
- surfaced via GET /status so operators can diagnose without SSH access.
238
- """
239
- global _startup_done
240
- issues: list[str] = []
241
-
242
- # 1. cv2 — most common missing dependency
243
- try:
244
- import cv2 # noqa: F401
245
- logger.info("startup ✓ cv2 available (version %s)", cv2.__version__)
246
- except ImportError as exc:
247
- msg = (
248
- f"cv2 not importable: {exc}. "
249
- "Add 'opencv-python-headless>=4.8.0' to pip layer 1 in Dockerfile."
250
- )
251
- issues.append(msg)
252
- logger.critical("startup FAIL %s", msg)
253
-
254
- # 2. magic_pdf core imports
255
- try:
256
- from magic_pdf.data.dataset import PymuDocDataset, ImageDataset # noqa: F401
257
- from magic_pdf.data.data_reader_writer import ( # noqa: F401
258
- FileBasedDataReader, FileBasedDataWriter,
259
- )
260
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze # noqa: F401
261
- from magic_pdf.config.enums import SupportedPdfParseMethod # noqa: F401
262
- logger.info("startup ✓ magic_pdf imports OK")
263
- except ImportError as exc:
264
- msg = f"magic_pdf not importable: {exc}"
265
- issues.append(msg)
266
- logger.critical("startup FAIL %s", msg)
267
-
268
- # 3. MinerU config
269
- config_path = os.path.expanduser("~/magic-pdf.json")
270
- if os.path.exists(config_path):
271
- logger.info("startup ✓ magic-pdf.json found at %s", config_path)
272
- else:
273
- msg = f"magic-pdf.json missing at {config_path} — run download_models.py"
274
- issues.append(msg)
275
- logger.critical("startup FAIL %s", msg)
276
-
277
- # 4. Model files
278
- models_dir = "/app/models/PDF-Extract-Kit-1.0/models"
279
- if os.path.isdir(models_dir):
280
- logger.info("startup ✓ models directory found at %s", models_dir)
281
- else:
282
- msg = f"Models directory missing at {models_dir} — run download_models.py"
283
- issues.append(msg)
284
- logger.critical("startup FAIL %s", msg)
285
-
286
- # 5. Temp storage writable
287
- try:
288
- td = tempfile.mkdtemp(prefix="mineru_selftest_")
289
- shutil.rmtree(td)
290
- logger.info("startup ✓ temp storage writable")
291
- except Exception as exc:
292
- msg = f"Temp storage not writable: {exc}"
293
- issues.append(msg)
294
- logger.critical("startup FAIL %s", msg)
295
-
296
- _startup_issues.extend(issues)
297
- _startup_done = True
298
-
299
- if not issues:
300
- logger.info("=" * 60)
301
- logger.info("Startup self-test PASSED — service ready.")
302
- logger.info("=" * 60)
303
- else:
304
- logger.error("=" * 60)
305
- logger.error("Startup self-test FAILED — %d issue(s). See above.", len(issues))
306
- logger.error("Service will start but /extract will fail until fixed.")
307
- logger.error("=" * 60)
308
-
309
-
310
- # ─────────────────────────────────────────────────────────────────────────────
311
- # GET /health
312
- # ─────────────────────────────────────────────────────────────────────────────
313
- @app.get("/health")
314
- def health() -> dict[str, Any]:
315
- """
316
- Liveness probe. Always returns 200 so HF Space marks the container as
317
- running. Use GET /status to check whether the OCR pipeline is ready.
318
- """
319
- return {"status": "healthy"}
320
-
321
-
322
- # ─────────────────────────────────────────────────────────────────────────────
323
- # GET /status
324
- # ─────────────────────────────────────────────────────────────────────────────
325
- @app.get("/status")
326
- def status() -> dict[str, Any]:
327
- """
328
- Full readiness report. Memory is read from cgroups (not /proc/meminfo)
329
- so the container's actual allocation is reported — not the host's RAM.
330
- /proc/meminfo inside a Docker container on HF shows the host machine's
331
- RAM (e.g. 123 GB) which is misleading. Cgroups v2 → v1 → /proc fallback.
332
- """
333
- used_mb, total_mb = _mem_mb()
334
- return {
335
- "status": "healthy" if not _startup_issues else "degraded",
336
- "provider": "mineru",
337
- "version": _mineru_version(),
338
- "modelsLoaded": _pipeline_ready,
339
- "startupIssues": _startup_issues,
340
- "uptimeSeconds": int(time.time() - _START_TIME),
341
- "memoryUsedMB": used_mb,
342
- "memoryTotalMB": total_mb,
343
- "activeRequests": _active_requests,
344
- "cacheEntries": len(_cache),
345
- "lastModelLoadMs": _model_load_ms,
346
- }
347
-
348
-
349
- # ─────────────────────────────────────────────────────────────────────────────
350
- # POST /extract — single file
351
- # ─────────────────────────────────────────────────────────────────────────────
352
- @app.post("/extract")
353
- async def extract(file: UploadFile = File(...)) -> JSONResponse:
354
- try:
355
- _ensure_pipeline()
356
- raw, filename, ext = await _read_upload(file)
357
- result = _run_extraction(raw, filename, ext)
358
- return JSONResponse(content=result)
359
- except ExtractionError as exc:
360
- logger.warning(
361
- "/extract structured error [%s/%s]: %s",
362
- exc.stage, exc.code, exc.message,
363
- )
364
- return JSONResponse(status_code=exc.http_status, content=exc.to_dict())
365
- except HTTPException:
366
- raise
367
- except Exception as exc:
368
- logger.exception("/extract unhandled error")
369
- return JSONResponse(
370
- status_code=500,
371
- content={
372
- "success": False,
373
- "stage": "unknown",
374
- "errorCode": "INTERNAL_ERROR",
375
- "message": str(exc),
376
- "traceback": traceback.format_exc()[-2000:],
377
- },
378
- )
379
-
380
-
381
- # ─────────────────────────────────────────────────────────────────────────────
382
- # POST /batch — up to 8 files; extras silently ignored
383
- # ─────────────────────────────────────────────────────────────────────────────
384
- @app.post("/batch")
385
- async def batch(files: list[UploadFile] = File(...)) -> JSONResponse:
386
- """
387
- Policy:
388
- - 1–8 files → process all.
389
- - > 8 files → silently process only files[0:8].
390
- Sequential processing to stay within CPU Basic memory limits.
391
- Per-file failures use the structured error format; one failure never
392
- aborts the rest of the batch.
393
- """
394
- try:
395
- _ensure_pipeline()
396
- except ExtractionError as exc:
397
- return JSONResponse(status_code=exc.http_status, content=exc.to_dict())
398
-
399
- candidates = files[:BATCH_MAX_FILES]
400
- results: list[dict[str, Any]] = []
401
-
402
- for upload in candidates:
403
- try:
404
- raw, filename, ext = await _read_upload(upload)
405
- result = _run_extraction(raw, filename, ext)
406
- except ExtractionError as exc:
407
- result = exc.to_dict()
408
- result["filename"] = _sanitize_filename(upload.filename or "upload")
409
- except Exception as exc:
410
- fname = _sanitize_filename(upload.filename or "upload")
411
- logger.exception("Batch item failed: %s", fname)
412
- result = {
413
- "success": False,
414
- "filename": fname,
415
- "stage": "unknown",
416
- "errorCode": "INTERNAL_ERROR",
417
- "message": str(exc),
418
- }
419
- results.append(result)
420
-
421
- return JSONResponse(content={
422
- "success": True,
423
- "processed": len(results),
424
- "results": results,
425
- })
426
-
427
-
428
- # ─────────────────────────────────────────────────────────────────────────────
429
- # Upload reader (shared by /extract and /batch)
430
- # ─────────────────────────────────────────────────────────────────────────────
431
- async def _read_upload(upload: UploadFile) -> tuple[bytes, str, str]:
432
- """Validate and read one upload. Returns (raw_bytes, filename, ext)."""
433
- filename = _sanitize_filename(upload.filename or "upload")
434
- ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
435
-
436
- if ext not in ALLOWED_EXTENSIONS:
437
- raise _err(
438
- "validation", "UNSUPPORTED_TYPE",
439
- f"Unsupported file type '.{ext}'. "
440
- f"Supported: {sorted(ALLOWED_EXTENSIONS)}",
441
- 415,
442
- )
443
-
444
- raw = await upload.read(MAX_UPLOAD_BYTES + 1)
445
-
446
- if len(raw) > MAX_UPLOAD_BYTES:
447
- raise _err(
448
- "upload", "FILE_TOO_LARGE",
449
- f"'{filename}' exceeds the {MAX_UPLOAD_BYTES // 1024 // 1024} MB limit.",
450
- 413,
451
- )
452
- if len(raw) == 0:
453
- raise _err("upload", "EMPTY_FILE", f"'{filename}' is empty.", 400)
454
-
455
- return raw, filename, ext
456
-
457
-
458
- # ─────────────────────────────────────────────────────────────────────────────
459
- # Extraction dispatcher (shared by /extract and /batch)
460
- # ─────────────────────────────────────────────────────────────────────────────
461
- def _run_extraction(raw: bytes, filename: str, ext: str) -> dict[str, Any]:
462
- """
463
- 1. SHA256 cache lookup → return immediately on hit (cached: true)
464
- 2. Memory safety guard → raise ExtractionError(LOW_MEMORY) if OOM likely
465
- 3. Dispatch to PDF or image processor
466
- 4. Cache successful result
467
- 5. Return with timing metadata
468
- """
469
- # ── SHA256 cache ──────────────────────────────────────────────────────────
470
- file_hash = hashlib.sha256(raw).hexdigest()
471
- with _cache_lock:
472
- cached = _cache.get(file_hash)
473
- if cached is not None:
474
- logger.info("Cache hit %s sha256=%.12s…", filename, file_hash)
475
- result = {**cached}
476
- result["metadata"] = {**cached["metadata"], "cached": True, "processingTimeMs": 0}
477
- return result
478
-
479
- # ── Memory safety guard ───────────────────────────────────────────────────
480
- _assert_memory_safe(raw, ext)
481
-
482
- # ── Process ───────────────────────────────────────────────────────────────
483
- _inc_active()
484
- work_dir = tempfile.mkdtemp(prefix="mineru_")
485
- try:
486
- t0 = time.perf_counter()
487
-
488
- if ext in PDF_EXTENSIONS:
489
- result = _process_pdf(raw, filename, work_dir)
490
- else:
491
- result = _process_image(raw, filename, ext, work_dir)
492
-
493
- elapsed_ms = int((time.perf_counter() - t0) * 1000)
494
- result["metadata"] = {
495
- **result["metadata"],
496
- "processingTimeMs": elapsed_ms,
497
- "cached": False,
498
- }
499
-
500
- # Store without timing so cache entries stay lean
501
- entry = {**result, "metadata": {k: v for k, v in result["metadata"].items()
502
- if k not in ("processingTimeMs", "cached")}}
503
- with _cache_lock:
504
- _cache[file_hash] = entry
505
-
506
- return result
507
-
508
- except ExtractionError:
509
- raise
510
- except Exception as exc:
511
- logger.exception("Extraction failed for %s", filename)
512
- raise _err(
513
- "unknown", "INTERNAL_ERROR",
514
- f"Unexpected error during extraction: {exc}",
515
- 500,
516
- ) from exc
517
- finally:
518
- _dec_active()
519
- shutil.rmtree(work_dir, ignore_errors=True)
520
-
521
-
522
- # ─────────────────────────────────────────────────────────────────────────────
523
- # Memory safety guard
524
- # ─────────────────────────────────────────────────────────────────────────────
525
- def _assert_memory_safe(raw: bytes, ext: str) -> None:
526
- """
527
- Estimate peak memory the pipeline needs and reject with LOW_MEMORY if
528
- available would drop below MEM_SAFETY_FLOOR_MB.
529
- """
530
- used_mb, total_mb = _mem_mb()
531
- if total_mb == 0:
532
- return # cgroups and /proc both unavailable — skip guard
533
-
534
- available_mb = total_mb - used_mb
535
-
536
- if ext in PDF_EXTENSIONS:
537
- page_count = max(1, _pdf_page_count(raw))
538
- estimated_mb = (page_count * BYTES_PER_OCR_PAGE) // (1024 * 1024)
539
- else:
540
- estimated_mb = _image_memory_estimate(raw, ext) // (1024 * 1024)
541
-
542
- free_after = available_mb - estimated_mb
543
- logger.info(
544
- "Memory check: avail=%d MB est=%d MB free_after=%d MB",
545
- available_mb, estimated_mb, free_after,
546
- )
547
-
548
- if free_after < MEM_SAFETY_FLOOR_MB:
549
- raise _err(
550
- "validation", "LOW_MEMORY",
551
- f"Insufficient memory. "
552
- f"Available: {available_mb} MB, "
553
- f"Estimated needed: {estimated_mb} MB, "
554
- f"Safety floor: {MEM_SAFETY_FLOOR_MB} MB. "
555
- "Try a smaller file or wait for active requests to complete.",
556
- 507,
557
- )
558
-
559
-
560
- def _image_memory_estimate(raw: bytes, ext: str) -> int:
561
- try:
562
- if ext in {"heic", "heif"}:
563
- try:
564
- from pillow_heif import register_heif_opener
565
- register_heif_opener()
566
- except ImportError:
567
- pass
568
- img = Image.open(io.BytesIO(raw))
569
- w, h = img.size
570
- channels = len(img.getbands()) or 3
571
- img.close()
572
- return w * h * channels * IMAGE_MEMORY_FACTOR
573
- except Exception:
574
- return len(raw) * 20 # conservative fallback
575
-
576
-
577
- # ─────────────────────────────────────────────────────────────────────────────
578
- # PDF processor
579
- # ─────────────────────────────────────────────────────────────────────────────
580
- def _process_pdf(raw: bytes, filename: str, work_dir: str) -> dict[str, Any]:
581
- from magic_pdf.data.data_reader_writer import FileBasedDataWriter
582
- from magic_pdf.data.dataset import PymuDocDataset
583
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
584
- from magic_pdf.config.enums import SupportedPdfParseMethod
585
-
586
- images_dir = os.path.join(work_dir, "images")
587
- os.makedirs(images_dir, exist_ok=True)
588
-
589
- try:
590
- image_writer = FileBasedDataWriter(images_dir)
591
- except Exception as exc:
592
- raise _err("decode", "PDF_WRITER_FAILED", f"Could not create image writer: {exc}") from exc
593
-
594
- page_count = _pdf_page_count(raw)
595
-
596
- try:
597
- ds = PymuDocDataset(raw)
598
- method = ds.classify()
599
- except Exception as exc:
600
- raise _err("decode", "PDF_PARSE_FAILED", f"Could not parse PDF: {exc}") from exc
601
-
602
- try:
603
- if method == SupportedPdfParseMethod.TXT:
604
- infer_result = ds.apply(doc_analyze, ocr=False)
605
- pipe_result = infer_result.pipe_txt_mode(image_writer)
606
- parse_method = "txt"
607
- confidence = 0.95
608
- else:
609
- infer_result = ds.apply(doc_analyze, ocr=True)
610
- pipe_result = infer_result.pipe_ocr_mode(image_writer)
611
- parse_method = "ocr"
612
- confidence = 0.85
613
- except Exception as exc:
614
- raise _err("ocr", "OCR_PIPELINE_FAILED", f"doc_analyze/pipe failed: {exc}") from exc
615
-
616
- try:
617
- markdown = pipe_result.get_markdown(images_dir)
618
- except Exception as exc:
619
- raise _err("markdown", "MARKDOWN_FAILED", f"get_markdown failed: {exc}") from exc
620
-
621
- content_list = _safe_content_list(pipe_result, images_dir)
622
- doc_type = _classify_document(markdown, filename)
623
-
624
- return {
625
- "success": True,
626
- "filename": filename,
627
- "docType": doc_type,
628
- "pageCount": page_count,
629
- "confidence": confidence,
630
- "markdown": markdown,
631
- "metadata": {
632
- "parseMethod": parse_method,
633
- "backend": "pipeline",
634
- "docTypeClassification": doc_type,
635
- "imageCount": _count_images(content_list),
636
- "tableCount": _count_tables(content_list),
637
- "formulaCount": _count_formulas(content_list),
638
- },
639
- }
640
-
641
-
642
- # ─────────────────────────────────────────────────────────────────────────────
643
- # Image processor
644
- # ─────────────────────────────────────────────────────────────────────────────
645
- def _process_image(raw: bytes, filename: str, ext: str, work_dir: str) -> dict[str, Any]:
646
- """
647
- NOTE: read_local_images() is intentionally NOT used here.
648
- In magic-pdf 1.x it expects a single path string; passing a list causes:
649
- "stat: path should be string, bytes, os.PathLike or integer, not list"
650
- We use FileBasedDataReader + ImageDataset directly — explicit and safe.
651
- """
652
- from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter
653
- from magic_pdf.data.dataset import ImageDataset
654
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze
655
-
656
- images_dir = os.path.join(work_dir, "images")
657
- os.makedirs(images_dir, exist_ok=True)
658
-
659
- try:
660
- image_writer = FileBasedDataWriter(images_dir)
661
- except Exception as exc:
662
- raise _err("decode", "IMAGE_WRITER_FAILED", f"Could not create image writer: {exc}") from exc
663
-
664
- # Convert non-native formats to PNG before feeding to MinerU
665
- try:
666
- if ext in PILLOW_IMAGE_EXTENSIONS:
667
- raw = _convert_image_to_png(raw, ext)
668
- save_ext = "png"
669
- else:
670
- save_ext = ext
671
- except ExtractionError:
672
- raise
673
- except Exception as exc:
674
- raise _err("decode", "IMAGE_DECODE_FAILED", f"Could not decode image: {exc}") from exc
675
-
676
- img_filename = f"input.{save_ext}"
677
- img_path = os.path.join(work_dir, img_filename)
678
- try:
679
- with open(img_path, "wb") as fh:
680
- fh.write(raw)
681
- except OSError as exc:
682
- raise _err("decode", "WRITE_FAILED", f"Could not write temp image: {exc}") from exc
683
-
684
- try:
685
- # FileBasedDataReader(base_dir).read(relative_name) → bytes
686
- reader = FileBasedDataReader(work_dir)
687
- image_bytes = reader.read(img_filename)
688
- ds = ImageDataset(image_bytes)
689
- except Exception as exc:
690
- raise _err("decode", "IMAGE_DATASET_FAILED",
691
- f"Could not build ImageDataset: {exc}") from exc
692
-
693
- try:
694
- infer_result = ds.apply(doc_analyze, ocr=True)
695
- pipe_result = infer_result.pipe_ocr_mode(image_writer)
696
- except Exception as exc:
697
- raise _err("ocr", "OCR_PIPELINE_FAILED", f"doc_analyze/pipe failed: {exc}") from exc
698
-
699
- try:
700
- markdown = pipe_result.get_markdown(images_dir)
701
- except Exception as exc:
702
- raise _err("markdown", "MARKDOWN_FAILED", f"get_markdown failed: {exc}") from exc
703
-
704
- content_list = _safe_content_list(pipe_result, images_dir)
705
- doc_type = _classify_document(markdown, filename)
706
-
707
- return {
708
- "success": True,
709
- "filename": filename,
710
- "docType": doc_type,
711
- "pageCount": 1,
712
- "confidence": 0.85,
713
- "markdown": markdown,
714
- "metadata": {
715
- "parseMethod": "ocr",
716
- "backend": "pipeline",
717
- "docTypeClassification": doc_type,
718
- "imageCount": _count_images(content_list),
719
- "tableCount": _count_tables(content_list),
720
- "formulaCount": _count_formulas(content_list),
721
- },
722
- }
723
-
724
-
725
- # ─────────────────────────────────────────────────────────────────────────────
726
- # Utility helpers
727
- # ─────────────────────────────────────────────────────────────────────────────
728
- def _sanitize_filename(name: str) -> str:
729
- name = os.path.basename(name)
730
- name = re.sub(r"[^\w.\-]", "_", name)
731
- return name[:200] or "upload"
732
-
733
-
734
- def _pdf_page_count(raw: bytes) -> int:
735
- try:
736
- doc = fitz.open(stream=raw, filetype="pdf")
737
- count = doc.page_count
738
- doc.close()
739
- return count
740
- except Exception:
741
- return 0
742
-
743
-
744
- def _convert_image_to_png(raw: bytes, ext: str) -> bytes:
745
- if ext in {"heic", "heif"}:
746
- try:
747
- from pillow_heif import register_heif_opener
748
- register_heif_opener()
749
- except ImportError:
750
- raise _err(
751
- "decode", "HEIF_NOT_SUPPORTED",
752
- "HEIC/HEIF support requires pillow-heif (not installed).",
753
- 415,
754
- )
755
- try:
756
- img = Image.open(io.BytesIO(raw)).convert("RGB")
757
- buf = io.BytesIO()
758
- img.save(buf, format="PNG")
759
- return buf.getvalue()
760
- except Exception as exc:
761
- raise _err("decode", "IMAGE_DECODE_FAILED", f"Pillow could not open image: {exc}") from exc
762
-
763
-
764
- def _safe_content_list(pipe_result: Any, images_dir: str) -> list[dict]:
765
- try:
766
- return pipe_result.get_content_list(images_dir) or []
767
- except Exception:
768
- return []
769
-
770
-
771
- def _count_images(content_list: list[dict]) -> int:
772
- return sum(1 for item in content_list if item.get("type") == "image")
773
-
774
-
775
- def _count_tables(content_list: list[dict]) -> int:
776
- return sum(1 for item in content_list if item.get("type") == "table")
777
-
778
-
779
- def _count_formulas(content_list: list[dict]) -> int:
780
- return sum(
781
- 1 for item in content_list
782
- if item.get("type") in {"equation", "formula", "interline_equation"}
783
- )
784
-
785
-
786
- def _classify_document(markdown: str, filename: str) -> str:
787
- """Keyword-based document type heuristic over extracted Markdown + filename."""
788
- text = (markdown + " " + filename).lower()
789
-
790
- rules: list[tuple[str, list[str]]] = [
791
- ("invoice", ["invoice", "bill to", "invoice number", "invoice #",
792
- "due date", "amount due", "subtotal", "tax invoice"]),
793
- ("receipt", ["receipt", "thank you for your purchase", "order total",
794
- "payment received", "transaction id", "cash receipt"]),
795
- ("marksheet", ["marksheet", "mark sheet", "grade sheet", "scorecard",
796
- "score card", "cgpa", "sgpa", "semester result",
797
- "result sheet", "marks obtained"]),
798
- ("resume", ["curriculum vitae", "cv", "resume", "work experience",
799
- "education", "skills", "references", "objective",
800
- "professional summary"]),
801
- ("research paper", ["abstract", "introduction", "methodology", "conclusion",
802
- "references", "keywords", "doi:", "arxiv", "journal",
803
- "proceedings"]),
804
- ("form", ["please fill", "signature", "date of birth", "applicant",
805
- "application form", "form no", "checkbox", "tick", "field"]),
806
- ("contract", ["agreement", "hereby", "whereas", "terms and conditions",
807
- "party of the first", "signed by", "witnesseth",
808
- "indemnify", "governing law"]),
809
- ("screenshot", ["screenshot", "screen capture", "url:", "http://",
810
- "https://", "browser", "toolbar", "desktop"]),
811
- ]
812
-
813
- scores: dict[str, int] = {}
814
- for doc_type, keywords in rules:
815
- score = sum(1 for kw in keywords if kw in text)
816
- if score:
817
- scores[doc_type] = score
818
-
819
- return max(scores, key=lambda k: scores[k]) if scores else "generic document"
820
-
821
-
822
- # ─────────────────────────────────────────────────────────────────────────────
823
- # Memory — cgroup-aware (fixes "105 GB / 123 GB" /proc/meminfo host bleed)
824
- # ─────────────────────────────────────────────────────────────────────────────
825
- def _mem_mb() -> tuple[int, int]:
826
- """
827
- Return (used_mb, total_mb) for the CONTAINER, not the host.
828
-
829
- Priority:
830
- 1. cgroups v2 /sys/fs/cgroup/memory.max + memory.current
831
- 2. cgroups v1 /sys/fs/cgroup/memory/memory.limit_in_bytes + usage_in_bytes
832
- 3. /proc/meminfo fallback (may show host memory in Docker — known inaccuracy)
833
-
834
- /proc/meminfo is last resort because HF Docker containers typically do NOT
835
- have cgroup memory limits mapped into /proc, so it shows the physical host
836
- RAM (e.g. 123 GB on a 128 GB bare-metal host), misleading the memory guard.
837
- """
838
- # ── cgroups v2 (preferred — modern Docker / HF Spaces) ───────────────────
839
- try:
840
- with open("/sys/fs/cgroup/memory.max") as f:
841
- raw_max = f.read().strip()
842
- if raw_max != "max":
843
- limit_bytes = int(raw_max)
844
- with open("/sys/fs/cgroup/memory.current") as f:
845
- used_bytes = int(f.read().strip())
846
- if limit_bytes > 0:
847
- return used_bytes // (1024 * 1024), limit_bytes // (1024 * 1024)
848
- except (FileNotFoundError, ValueError, OSError):
849
- pass
850
-
851
- # ── cgroups v1 ────────────────────────────────────────────────────────────
852
- try:
853
- with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
854
- limit_bytes = int(f.read().strip())
855
- with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
856
- used_bytes = int(f.read().strip())
857
- # Unconstrained cgroup reports a sentinel > 1 PB; skip it
858
- if limit_bytes < 128 * 1024 * 1024 * 1024:
859
- return used_bytes // (1024 * 1024), limit_bytes // (1024 * 1024)
860
- except (FileNotFoundError, ValueError, OSError):
861
- pass
862
-
863
- # ── /proc/meminfo fallback ────────────────────────────────────────────────
864
- try:
865
- info: dict[str, int] = {}
866
- with open("/proc/meminfo") as f:
867
- for line in f:
868
- parts = line.split()
869
- if len(parts) >= 2:
870
- info[parts[0].rstrip(":")] = int(parts[1]) # values are in kB
871
- total_kb = info.get("MemTotal", 0)
872
- avail_kb = info.get("MemAvailable", 0)
873
- used_kb = total_kb - avail_kb
874
- return used_kb // 1024, total_kb // 1024
875
- except Exception:
876
- return 0, 0
877
-
878
-
879
- def _mineru_version() -> str:
880
- for pkg in ("magic-pdf", "mineru"):
881
- try:
882
- return pkg_version(pkg)
883
- except Exception:
884
- continue
885
- return "unknown"