Spaces:
Sleeping
Sleeping
Delete README.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308---title: MinerU OCR Serviceemoji: πcolorFrom: bluecolorTo: greensdk: dockerapp_port: 7860pinned: false---
# MinerU OCR & Document Extraction Service
Production-quality OCR and document extraction API powered by **MinerU** (`magic-pdf` package), running on Hugging Face Docker Spaces β free CPU tier.
---
## Complete Forensic Audit β All Root Causes Found and Fixed
### Root Cause 1 β `[full-cpu]` is NOT a valid extra (primary failure)
```OCR_PIPELINE_FAILED: No module named 'ultralytics'```
`magic-pdf[full-cpu]` does not exist. When pip receives an unknown extra name it **silently installs only the base package**, omitting:- `ultralytics` (YOLO framework for layout detection)- `doclayout-yolo==0.0.2b1` (layout detection model)- `rapid-table>=1.0.5` (table extraction)- `shapely`, `pyclipper`, `omegaconf`, `albumentations`, `ftfy`, and other deps
The container booted without error because `torch` **is** in the base deps, but `doc_analyze` crashed at the first layout detection call.
**Fix:** `magic-pdf[full]==1.3.12` (not `[full-cpu]`).
### Root Cause 2 β OpenCV non-headless conflict
`doclayout-yolo==0.0.2b1`, `ultralytics>=8.3.48`, and `rapid-table>=1.0.5` all declare `opencv-python` (non-headless) as a runtime dep. After Layer 3, pip has installed the full X11-linked `opencv-python` build, overwriting the headless cv2 module installed in Layer 1.
**Fix:** Layer 4 force-reinstalls `opencv-python-headless>=4.8.0` after all other packages. This overwrites the cv2 shared object with the headless build, which works on this slim container without X11 libs. pip-check shows "ultralytics requires opencv-python" warnings but they are harmless β both packages expose an identical cv2 API.
### Root Cause 3 β OCR model path mismatch (new, 2025-06)
```No such file or directory: /app/models/PDF-Extract-Kit-1.0/models/OCR/paddleocr_torch/ch_PP-OCRv3_det_infer.pth```
**Forensic proof:**
`magic-pdf 1.3.12` ships `models_config.yml` that references OCR det weight files which **do not exist** in the `opendatalab/PDF-Extract-Kit-1.0` HF repo. The repo was updated to v5 det models; the package config still references v3.
Cross-reference of **all** languages vs HF repo (read directly from wheel and HF API):
| Language | Det needed by config | In HF repo? | Rec needed by config | In HF repo? ||---|---|---|---|---|| `ch_lite` (CPU default) | `ch_PP-OCRv3_det_infer.pth` | β MISSING | `ch_PP-OCRv5_rec_infer.pth` | β
|| `ch` | `ch_PP-OCRv3_det_infer.pth` | β MISSING | `ch_PP-OCRv4_rec_server_doc_infer.pth` | β
|| `ch_server` | `ch_PP-OCRv3_det_infer.pth` | β MISSING | `ch_PP-OCRv5_rec_server_infer.pth` | β
|| `en` | `en_PP-OCRv3_det_infer.pth` | β MISSING | `en_PP-OCRv4_rec_infer.pth` | β MISSING || `latin` | `en_PP-OCRv3_det_infer.pth` | β MISSING | `latin_PP-OCRv3_rec_infer.pth` | β MISSING || `korean` | `Multilingual_PP-OCRv3_det_infer.pth` | β
| `korean_PP-OCRv3_rec_infer.pth` | β (v5 available) || `ka` | `Multilingual_PP-OCRv3_det_infer.pth` | β
| `ka_PP-OCRv3_rec_infer.pth` | β
|
**Why only det files are missing for ch\*:** The HF repo has all `ch` rec files (v4/v5) but replaced the v3 det with v5 det. Only the det cross-version rename is the problem.
**Path resolution** (read from `pytorch_paddle.py`):```pythonocr_models_dir = os.path.join(get_local_models_dir(), 'OCR', 'paddleocr_torch')det_model_path = os.path.join(ocr_models_dir, det_filename)# β /app/models/PDF-Extract-Kit-1.0/models/OCR/paddleocr_torch/<filename>```
**CPU default flow** (read from `pytorch_paddle.py`):```pythonself.lang = kwargs.get('lang', 'ch') # default when no lang= kwargif device == 'cpu' and self.lang in ['ch', 'ch_server']: self.lang = 'ch_lite' # CPU always switches to ch_lite# β ch_lite.det = ch_PP-OCRv3_det_infer.pth β MISSING```
**Arch safety proof** (read from `pytorchocr_utility.py`):```pythondef get_arch_config(model_path): file_name = Path(model_path).stem # filename without .pth = arch config key arch_config = OmegaConf.load(arch_config_yaml)[file_name]```Both replacement file stems (`ch_PP-OCRv5_det_infer`, `Multilingual_PP-OCRv3_det_infer`) have entries in `arch_config.yaml` β confirmed by reading the bundled file from the wheel.
**Fix:** Dockerfile **Layer 3.5** patches `models_config.yml` in the installed magic_pdf package at build time:
| Config entry | Was | Now | File in HF repo? ||---|---|---|---|| All `ch*` langs `.det` | `ch_PP-OCRv3_det_infer.pth` | `ch_PP-OCRv5_det_infer.pth` | β
|| `en`, `latin` `.det` | `en_PP-OCRv3_det_infer.pth` | `Multilingual_PP-OCRv3_det_infer.pth` | β
|
**Additional finding β `slanet-plus.onnx`:** The table model is **bundled inside the magic-pdf wheel** at `magic_pdf/resources/slanet_plus/slanet-plus.onnx`. No separate HF download is needed.
---
## Why `[lite]` / paddlepaddle / paddleocr Are NOT Installed
| Package | Status | Reason ||---|---|---|| `paddlepaddle==3.0.0b1` | β Not on PyPI | The `[lite]` extra pins this exact beta version. Available on PyPI: 2.6.2, 3.0.0, 3.1.x+ β NOT 3.0.0b1. || `paddleocr==2.7.3` | β Incompatible | Requires `opencv-python <=4.6.0.66`. Conflicts with `ultralytics>=4.6.0` and `doclayout-yolo>=4.6.0`. || PaddleOCR (any) | β Not needed | The pipeline (full) backend never uses PaddleOCR. See below. |
### The Actual OCR Engine: `paddleocr2pytorch`
The pipeline backend uses **`paddleocr2pytorch`** β a self-contained PyTorch reimplementation of the PaddleOCR architecture, **bundled directly inside the `magic-pdf` wheel** at:
```magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/```
It is initialized via `PytorchPaddleOCR` in `model_init.py`. It requires only:- `torch` (CPU, already installed in Layer 2)- `cv2`, `numpy`, `pyclipper`, `shapely`, `yaml` (all in `magic-pdf[full]`)
`pp_structure_v2.py` (which imports `paddleocr`) is only loaded when `model_config.__model_mode__ == 'lite'`. The pipeline backend always uses `full` mode (`CustomPEKModel`). That file is **never imported at runtime**.
---
## Valid `magic-pdf` 1.3.12 Extras
| Extra | Provides ||---|---|| `[full]` | `ultralytics>=8.3.48`, `doclayout-yolo==0.0.2b1`, `rapid-table`, `shapely`, `pyclipper`, `omegaconf`, `matplotlib`, `ftfy`, `dill`, `PyYAML`, `openai`, `albumentations` || `[full_old_linux]` | Same as `[full]` but with tighter version pins for older Linux || `[lite]` | `paddleocr==2.7.3`, `paddlepaddle==3.0.0b1` (Linux) β **unusable**: `paddlepaddle==3.0.0b1` not on PyPI || ~~`[full-cpu]`~~ | **Does not exist** β pip silently ignores and installs base package only |
---
## Dockerfile Layer Strategy
```Layer 1: fastapi, uvicorn, pillow, pillow-heif, huggingface_hub opencv-python-headless (placeholder β overridden in Layer 4) βLayer 2: torch + torchvision from download.pytorch.org/whl/cpu (CPU-only) CPU wheel locked in β pip skips ~2.5 GB CUDA wheel from PyPI βLayer 3: magic-pdf[full]==1.3.12 --extra-index-url myhloli [full] β ultralytics, doclayout-yolo 0.0.2b1, rapid-table, shapely, pyclipper, omegaconf, matplotlib, ftfy, dill onnxruntime pulled automatically as transitive dep of rapid-table opencv-python (non-headless) also pulled as transitive dep (overridden in Layer 4) βLayer 3.5: python3 - <<'PYEOF' β patch models_config.yml in magic_pdf package ch_PP-OCRv3_det_infer.pth β ch_PP-OCRv5_det_infer.pth (all ch* langs) en_PP-OCRv3_det_infer.pth β Multilingual_PP-OCRv3_det_infer.pth (en, latin) Both replacement arch keys verified in arch_config.yaml before writing. βLayer 4: pip install --force-reinstall opencv-python-headless>=4.8.0 Headless cv2 wins β container works without X11 libs βApp code: download_models.py, validate.py, main.py, entrypoint.sh βModel download: opendatalab/PDF-Extract-Kit-1.0 (MFR excluded) hantian/layoutreader (optional)```
Note: `--extra-index-url https://myhloli.github.io/wheels/` is required because `doclayout-yolo==0.0.2b1` only exists on the myhloli wheel server, not on PyPI.
---
## validate.py β What Is Checked
`validate.py` runs at every container start (before uvicorn). It exits 1 on any CRITICAL failure, making the problem visible in HF logs immediately.
| Section | Checks | Critical? ||---|---|---|| 1 | Python >= 3.10 | β
|| 2 | cv2 import + headless build | β
|| 3 | torch + torchvision | β
|| 4 | ultralytics | β
|| 5 | doclayout_yolo | β
|| 6 | rapid_table | β
|| 7 | onnxruntime | β
|| 8 | magic_pdf core imports | β
|| 8b | PytorchPaddleOCR (bundled OCR engine) | β
|| 9 | End-to-end import chain smoke test | β
|| 10 | magic-pdf.json config file + keys | β
|| 11 | Model directory structure | β
|| **11b** | **Exact weight files: ch_PP-OCRv5_det_infer.pth, ch_PP-OCRv5_rec_infer.pth, doclayout_yolo YOLO weight, LayoutLMv3 weight, Multilingual det** | **β
CRITICAL** || **11c** | **models_config.yml consistency: referenced det/rec files exist on disk** | **β
CRITICAL** || **11d** | **Bundled wheel resources: slanet-plus.onnx, langdetect models, model_configs.yaml** | **β
** || 12 | Temp storage write test | β
|| 13β14 | Memory (cgroups + /proc/meminfo) | β warning only |
---
## Previous Bug History
| Cause | Detail | Fix ||---|---|---|| `No module named magic_pdf` | Wrong install command | Fixed || `stat: path should be string ... not list` | Old `read_local_images([path])` API (removed in 1.x) | Fixed β use `FileBasedDataReader` || `No module named cv2` | `opencv-python-headless` missing | Fixed β Layer 1 || `No module named 'ultralytics'` | `[full-cpu]` is not a valid extra | Fixed β Layer 3 uses `[full]` || Memory showing `105 GB / 123 GB` | `/proc/meminfo` showing host RAM inside container | Fixed β cgroup-aware memory logic || `libreoffice` in apt-get | 1.5 GB; caused OOM / build timeout | Removed || X11 libs (`libsm6`, `libxrender-dev`) | Added 80 MB, not needed for headless cv2 | Removed || `python-magic` / `libmagic1` | Listed but never imported | Removed || `ch_PP-OCRv3_det_infer.pth not found` | models_config.yml v3 ref vs HF repo v5 | Fixed β Layer 3.5 patches config |
---
## Supported File Types
| Category | Extensions ||---|---|| PDF | `.pdf` (searchable, scanned, mixed) || Images | `.jpg` `.jpeg` `.png` `.webp` `.bmp` `.tiff` `.tif` `.gif` `.heic` `.heif` `.avif` |
---
## API Endpoints
### `GET /health````json{ "status": "healthy" }```
### `GET /status````json{ "status": "healthy", "provider": "mineru", "version": "1.3.12", "modelsLoaded": true, "uptimeSeconds": 3742, "memoryUsedMB": 5200, "memoryTotalMB": 16384, "activeRequests": 0, "cacheEntries": 3}```
### `POST /extract````json{ "success": true, "filename": "invoice.jpg", "docType": "invoice", "pageCount": 1, "confidence": 0.85, "markdown": "# Invoice\n\n...", "metadata": { "parseMethod": "ocr", "backend": "pipeline", "cached": false, "processingTimeMs": 4200, "docTypeClassification": "invoice", "imageCount": 0, "tableCount": 1, "formulaCount": 0 }}```
### `POST /batch````json{ "success": true, "processed": 3, "results": [...]}```
---
## Deployment
1. Create a new Hugging Face Space β **Docker** SDK2. Upload all files from this directory to the Space repo root3. Space builds automatically (~25β35 min for first build; code-only rebuilds are faster due to Docker layer cache)4. Test with curl:
```bashcurl https://<your-space>.hf.space/healthcurl -X POST https://<your-space>.hf.space/extract -F "file=@photo.jpg"curl -X POST https://<your-space>.hf.space/batch \ -F "files=@a.pdf" -F "files=@b.jpg" -F "files=@c.png"```
---
## Resource Budget (free CPU Basic)
| Resource | Budget | Usage ||---|---|---|| Disk | 50 GB | ~10β13 GB (packages ~5 GB + models ~5 GB) || RAM | 16 GB | ~6β8 GB at load; peaks ~10β12 GB during extraction || vCPU | 2 | Single uvicorn worker; sequential batch processing |
---
## Known Limitations
1. **No DOCX/PPTX/XLSX** β dropped to make the build reliable. Re-add with LibreOffice on paid hardware.2. **Formula OCR disabled** β MFR models excluded to save ~1-2 GB. Set `"enable": true` in `~/magic-pdf.json` and re-download MFR models to enable.3. **First-request latency** β models lazy-load into RAM on the first request (~30β60 s).4. **30 MB file size limit** β enforced on both `/extract` and `/batch`.5. **In-process cache** β SHA256 cache lives in RAM, cleared on container restart.6. **HEIC/HEIF** β requires `pillow-heif` (included); may fail on unusual encoder variants.7. **`en` language OCR** β `en_PP-OCRv4_rec_infer.pth` is absent from the HF repo and has no v5 replacement with a matching arch entry in `arch_config.yaml`. The det fix (β Multilingual) is applied but rec will still fail if `lang='en'` is explicitly passed. Default (no lang) uses `ch_lite` which handles English text adequately.README.mdDeleted-308