crazylemonade commited on
Commit
183d18b
·
verified ·
1 Parent(s): de1b8b6

Delete validate.py

Browse files
Files changed (1) hide show
  1. validate.py +0 -461
validate.py DELETED
@@ -1,461 +0,0 @@
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
- OpenCV conflict handling:
28
- doclayout-yolo, ultralytics, and rapid-table all declare opencv-python
29
- (non-headless) as a required dep. pip installs the full build in Layer 3.
30
- Layer 4 force-reinstalls opencv-python-headless to overwrite cv2. Both
31
- packages expose an identical cv2 API so all callers work correctly at
32
- runtime. pip-check shows warnings but they are harmless.
33
-
34
- onnxruntime:
35
- rapid-table declares onnxruntime>1.17.0 as a required (non-optional) dep.
36
- pip resolves it automatically when magic-pdf[full] is installed in Layer 3.
37
- """
38
-
39
- import importlib
40
- import json
41
- import os
42
- import shutil
43
- import sys
44
- import tempfile
45
- import traceback
46
-
47
- SOFT_MODE = "--soft" in sys.argv # never exit 1, just print
48
-
49
- MODELS_DIR = "/app/models"
50
- EXTRACT_KIT_MODELS = os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0", "models")
51
- LAYOUT_MARKER = os.path.join(EXTRACT_KIT_MODELS, "Layout") # canary directory
52
- CONFIG_PATH = os.path.expanduser("~/magic-pdf.json")
53
-
54
-
55
- # ── helpers ────────────────────────────────────────────────────────────────────
56
- def ok(label: str, detail: str = "") -> None:
57
- suffix = f" ({detail})" if detail else ""
58
- print(f" ✓ {label}{suffix}", flush=True)
59
-
60
-
61
- def fail(label: str, detail: str, critical: bool = True) -> None:
62
- tag = "CRITICAL" if critical else "WARNING"
63
- print(f" ✗ [{tag}] {label}: {detail}", flush=True)
64
-
65
-
66
- def section(title: str) -> None:
67
- print(f"\n{'─' * 60}", flush=True)
68
- print(f" {title}", flush=True)
69
- print(f"{'─' * 60}", flush=True)
70
-
71
-
72
- # ── check registry ─────────────────────────────────────────────────────────────
73
- failures: list[tuple[str, str]] = []
74
- warnings: list[tuple[str, str]] = []
75
-
76
-
77
- def record_fail(label: str, detail: str, critical: bool = True) -> None:
78
- fail(label, detail, critical)
79
- if critical:
80
- failures.append((label, detail))
81
- else:
82
- warnings.append((label, detail))
83
-
84
-
85
- # ═══════════════════════════════════════════════════════════════════════════════
86
- print("\n" + "═" * 60, flush=True)
87
- print(" MinerU OCR Service — Pre-flight Validation", flush=True)
88
- print("═" * 60, flush=True)
89
-
90
- # ── 1. Python version ──────────────────────────────────────────────────────────
91
- section("1. Python runtime")
92
- pv = sys.version_info
93
- if pv >= (3, 10):
94
- ok("Python version", f"{pv.major}.{pv.minor}.{pv.micro}")
95
- else:
96
- record_fail("Python version",
97
- f"{pv.major}.{pv.minor} detected — magic-pdf requires >= 3.10")
98
-
99
- # ── 2. cv2 ─────────────────────────────────────────────────────────────────────
100
- section("2. OpenCV (cv2)")
101
- try:
102
- import cv2
103
- ok("cv2 import", f"version {cv2.__version__}")
104
- build = cv2.getBuildInformation()
105
- if "GTK" in build or "Qt" in build:
106
- record_fail("cv2 build", "GUI backend detected — use opencv-python-headless",
107
- critical=False)
108
- else:
109
- ok("cv2 headless", "no GUI backend detected")
110
- except ImportError as exc:
111
- record_fail(
112
- "cv2 import",
113
- f"{exc}. "
114
- "Layer 4 force-reinstall of opencv-python-headless may have failed. "
115
- "Check Docker build log for the 'pip install --force-reinstall opencv-python-headless' step.",
116
- )
117
- except Exception as exc:
118
- record_fail("cv2 import", f"unexpected error: {exc}")
119
-
120
- # ── 3. PyTorch ─────────────────────────────────────────────────────────────────
121
- section("3. PyTorch + TorchVision")
122
- try:
123
- import torch
124
- ok("torch import", f"version {torch.__version__}")
125
- if torch.cuda.is_available():
126
- record_fail("torch CUDA", "CUDA detected on CPU-only space — unexpected",
127
- critical=False)
128
- else:
129
- ok("torch device", "CPU-only (expected for free tier)")
130
- except ImportError as exc:
131
- record_fail(
132
- "torch import",
133
- f"{exc}. "
134
- "Install from PyTorch CPU index BEFORE magic-pdf in Dockerfile Layer 2: "
135
- "pip install --index-url https://download.pytorch.org/whl/cpu torch torchvision",
136
- )
137
- except Exception as exc:
138
- record_fail("torch import", f"unexpected: {exc}")
139
-
140
- try:
141
- import torchvision
142
- ok("torchvision import", f"version {torchvision.__version__}")
143
- except ImportError as exc:
144
- record_fail("torchvision import", str(exc))
145
- except Exception as exc:
146
- record_fail("torchvision import", f"unexpected: {exc}")
147
-
148
- # ── 4. ultralytics ─────────────────────────────────────────────────────────────
149
- section("4. ultralytics (YOLO — required by doclayout_yolo)")
150
- try:
151
- import ultralytics
152
- ok("ultralytics import", f"version {ultralytics.__version__}")
153
- except ImportError as exc:
154
- record_fail(
155
- "ultralytics import",
156
- f"{exc}. "
157
- "Provided by magic-pdf[full]. "
158
- "ROOT CAUSE: [full-cpu] is NOT a valid extra in magic-pdf 1.3.12 — "
159
- "pip silently installed only the base package when given an unknown extra. "
160
- "Dockerfile Layer 3 must use magic-pdf[full]==1.3.12 (not [full-cpu]).",
161
- )
162
- except Exception as exc:
163
- record_fail("ultralytics import", f"unexpected: {exc}")
164
-
165
- # ── 5. doclayout_yolo ──────────────────────────────────────────────────────────
166
- section("5. doclayout_yolo (layout detection model)")
167
- try:
168
- import doclayout_yolo
169
- ok("doclayout_yolo import", f"version {getattr(doclayout_yolo, '__version__', 'unknown')}")
170
- except ImportError as exc:
171
- record_fail(
172
- "doclayout_yolo import",
173
- f"{exc}. "
174
- "Provided by magic-pdf[full] (version 0.0.2b1). "
175
- "doclayout-yolo==0.0.2b1 is only on the myhloli custom wheel index — "
176
- "Dockerfile Layer 3 must include: "
177
- "--extra-index-url https://myhloli.github.io/wheels/",
178
- )
179
- except Exception as exc:
180
- record_fail("doclayout_yolo import", f"unexpected: {exc}")
181
-
182
- # ── 6. rapid_table ─────────────────────────────────────────────────────────────
183
- section("6. rapid_table (table extraction)")
184
- try:
185
- import rapid_table
186
- ok("rapid_table import", f"version {getattr(rapid_table, '__version__', 'unknown')}")
187
- except ImportError as exc:
188
- record_fail(
189
- "rapid_table import",
190
- f"{exc}. Provided by magic-pdf[full]. Check Layer 3 install.",
191
- )
192
- except Exception as exc:
193
- record_fail("rapid_table import", f"unexpected: {exc}")
194
-
195
- # ── 7. onnxruntime ─────────────────────────────────────────────────────────────
196
- section("7. onnxruntime (required by rapid-table for table model inference)")
197
- # onnxruntime is a required (non-optional) dep of rapid-table>=1.0.5.
198
- # pip resolves it automatically when magic-pdf[full] is installed in Layer 3.
199
- # If it is missing it means rapid-table itself failed to install.
200
- try:
201
- import onnxruntime
202
- ok("onnxruntime import", f"version {onnxruntime.__version__}")
203
- except ImportError as exc:
204
- record_fail(
205
- "onnxruntime import",
206
- f"{exc}. "
207
- "onnxruntime is a required dep of rapid-table>=1.0.5. "
208
- "Its absence means rapid-table failed to install in Layer 3. "
209
- "Check Docker build log for rapid-table install errors.",
210
- )
211
- except Exception as exc:
212
- record_fail("onnxruntime import", f"unexpected: {exc}")
213
-
214
- # ── 8. magic_pdf core imports ──────────────────────────────────────────────────
215
- section("8. magic_pdf core imports")
216
-
217
- REQUIRED_IMPORTS = [
218
- ("magic_pdf.data.dataset", ["PymuDocDataset", "ImageDataset"]),
219
- ("magic_pdf.data.data_reader_writer", ["FileBasedDataReader", "FileBasedDataWriter"]),
220
- ("magic_pdf.model.doc_analyze_by_custom_model", ["doc_analyze"]),
221
- ("magic_pdf.config.enums", ["SupportedPdfParseMethod"]),
222
- ]
223
-
224
- for module_path, symbols in REQUIRED_IMPORTS:
225
- try:
226
- mod = importlib.import_module(module_path)
227
- missing = [s for s in symbols if not hasattr(mod, s)]
228
- if missing:
229
- record_fail(f"{module_path}", f"missing symbols: {missing}")
230
- else:
231
- ok(module_path, ", ".join(symbols))
232
- except ImportError as exc:
233
- record_fail(module_path, str(exc))
234
- except Exception as exc:
235
- record_fail(module_path, f"unexpected: {exc}")
236
-
237
- # ── 8b. paddleocr2pytorch (OCR engine bundled inside magic-pdf wheel) ──────────
238
- section("8b. paddleocr2pytorch (PyTorch OCR — bundled in magic-pdf wheel)")
239
- # This is the actual OCR engine for the pipeline backend.
240
- # It is NOT a separate pip package — it lives inside the magic-pdf wheel at
241
- # magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/
242
- # If it is missing, the entire magic-pdf package did not install correctly.
243
- try:
244
- from magic_pdf.model.sub_modules.ocr.paddleocr2pytorch.pytorch_paddle import PytorchPaddleOCR
245
- ok("PytorchPaddleOCR (paddleocr2pytorch)", "bundled inside magic-pdf wheel — no paddlepaddle pkg needed")
246
- except ImportError as exc:
247
- record_fail(
248
- "PytorchPaddleOCR import",
249
- f"{exc}. "
250
- "This module is bundled inside magic_pdf/model/sub_modules/ocr/paddleocr2pytorch/. "
251
- "If missing, magic-pdf itself did not install correctly.",
252
- )
253
- except Exception as exc:
254
- record_fail("PytorchPaddleOCR import", f"unexpected: {exc}")
255
-
256
- # ── 8c. Deprecated API check ───────────────────────────────────────────────────
257
- section("8c. Deprecated API check (should NOT exist)")
258
- OBSOLETE = [
259
- "magic_pdf.pipe.UNIPipe",
260
- "magic_pdf.rw.DiskReaderWriter",
261
- ]
262
- for mod_path in OBSOLETE:
263
- try:
264
- importlib.import_module(mod_path)
265
- record_fail(mod_path, "still importable — code may use old API", critical=False)
266
- except ImportError:
267
- ok(f"{mod_path} (correctly absent)")
268
-
269
- # ── 9. End-to-end pipeline smoke test ─────────────────────────────────────────
270
- section("9. End-to-end pipeline smoke test")
271
- try:
272
- from magic_pdf.model.doc_analyze_by_custom_model import doc_analyze # noqa: F401
273
- import ultralytics # noqa: F401
274
- from magic_pdf.data.dataset import ImageDataset # noqa: F401
275
- from magic_pdf.data.data_reader_writer import FileBasedDataReader, FileBasedDataWriter # noqa: F401
276
- ok("Pipeline imports (doc_analyze + ultralytics + ImageDataset + readers)", "all OK")
277
- except ImportError as exc:
278
- record_fail(
279
- "Pipeline smoke test",
280
- f"Full pipeline import chain failed: {exc}. "
281
- "This means POST /extract will fail on every request.",
282
- )
283
- except Exception as exc:
284
- record_fail("Pipeline smoke test", f"unexpected: {exc}")
285
-
286
- # ── 10. Config file ────────────────────────────────────────────────────────────
287
- section("10. MinerU config (magic-pdf.json)")
288
- if os.path.exists(CONFIG_PATH):
289
- try:
290
- with open(CONFIG_PATH) as f:
291
- cfg = json.load(f)
292
- required_keys = ["models-dir", "device-mode"]
293
- missing_keys = [k for k in required_keys if k not in cfg]
294
- if missing_keys:
295
- record_fail("Config keys", f"missing: {missing_keys}")
296
- else:
297
- ok("Config file", CONFIG_PATH)
298
- ok("device-mode", cfg.get("device-mode", "?"))
299
- ok("models-dir", cfg.get("models-dir", "?"))
300
- ok("formula-enable", str(cfg.get("formula-config", {}).get("enable", "?")))
301
- ok("table-enable", str(cfg.get("table-config", {}).get("enable", "?")))
302
- except json.JSONDecodeError as exc:
303
- record_fail("Config file", f"invalid JSON: {exc}")
304
- except Exception as exc:
305
- record_fail("Config file", str(exc))
306
- else:
307
- record_fail(
308
- "Config file",
309
- f"not found at {CONFIG_PATH}. "
310
- "Run download_models.py or check Docker build log.",
311
- )
312
-
313
- # ── 11. Model files ────────────────────────────────────────────────────────────
314
- section("11. Model files")
315
-
316
- model_checks = [
317
- ("PDF-Extract-Kit-1.0 root", os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0")),
318
- ("Layout models (canary)", LAYOUT_MARKER),
319
- ("MFD models", os.path.join(EXTRACT_KIT_MODELS, "MFD")),
320
- ("Table models", os.path.join(EXTRACT_KIT_MODELS, "TabRec")),
321
- ]
322
-
323
- for label, path in model_checks:
324
- if os.path.isdir(path):
325
- try:
326
- n = sum(1 for _ in os.scandir(path))
327
- ok(label, f"{path} ({n} entries)")
328
- except OSError:
329
- ok(label, path)
330
- else:
331
- record_fail(label, f"directory not found: {path}")
332
-
333
- lr_dir = os.path.join(MODELS_DIR, "layoutreader")
334
- if os.path.isdir(lr_dir):
335
- ok("layoutreader (optional)", lr_dir)
336
- else:
337
- record_fail("layoutreader (optional)",
338
- "not found — MinerU will use fallback ordering (non-critical)",
339
- critical=False)
340
-
341
- try:
342
- with open(CONFIG_PATH) as f:
343
- cfg = json.load(f)
344
- cfg_models = cfg.get("models-dir", "")
345
- if cfg_models and os.path.isdir(cfg_models):
346
- ok("Config models-dir exists", cfg_models)
347
- elif cfg_models:
348
- record_fail("Config models-dir", f"points to missing path: {cfg_models}")
349
- except Exception:
350
- pass
351
-
352
- # ── 12. Temp storage ───────────────────────────────────────────────────────────
353
- section("12. Temp storage")
354
- try:
355
- td = tempfile.mkdtemp(prefix="mineru_validate_")
356
- test_file = os.path.join(td, "write_test.bin")
357
- with open(test_file, "wb") as f:
358
- f.write(b"x" * 4096)
359
- assert os.path.getsize(test_file) == 4096
360
- shutil.rmtree(td)
361
- ok("Temp write + delete", tempfile.gettempdir())
362
- except Exception as exc:
363
- record_fail("Temp storage", str(exc))
364
-
365
- # ── 13. System memory (cgroups) ────────────────────────────────────────────────
366
- section("13. System memory (cgroups)")
367
- mem_source = "unknown"
368
- total_mb = used_mb = 0
369
-
370
- try:
371
- with open("/sys/fs/cgroup/memory.max") as f:
372
- raw = f.read().strip()
373
- if raw != "max":
374
- total_mb = int(raw) // (1024 * 1024)
375
- with open("/sys/fs/cgroup/memory.current") as f:
376
- used_mb = int(f.read().strip()) // (1024 * 1024)
377
- mem_source = "cgroups v2"
378
- except (FileNotFoundError, ValueError):
379
- pass
380
-
381
- if total_mb == 0:
382
- try:
383
- with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
384
- limit = int(f.read().strip())
385
- with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
386
- used_bytes = int(f.read().strip())
387
- if limit < 128 * 1024 * 1024 * 1024:
388
- total_mb = limit // (1024 * 1024)
389
- used_mb = used_bytes // (1024 * 1024)
390
- mem_source = "cgroups v1"
391
- except (FileNotFoundError, ValueError):
392
- pass
393
-
394
- if total_mb == 0:
395
- try:
396
- info: dict[str, int] = {}
397
- with open("/proc/meminfo") as f:
398
- for line in f:
399
- parts = line.split()
400
- if len(parts) >= 2:
401
- info[parts[0].rstrip(":")] = int(parts[1])
402
- total_mb = info.get("MemTotal", 0) // 1024
403
- used_mb = (info.get("MemTotal", 0) - info.get("MemAvailable", 0)) // 1024
404
- mem_source = "/proc/meminfo (may show host RAM)"
405
- except Exception:
406
- pass
407
-
408
- ok("Memory source", mem_source)
409
- ok("Total memory", f"{total_mb} MB")
410
- ok("Used memory", f"{used_mb} MB")
411
- ok("Free memory", f"{total_mb - used_mb} MB")
412
-
413
- if total_mb > 32 * 1024:
414
- record_fail(
415
- "Memory total",
416
- f"{total_mb} MB seems too large — cgroups may not be available; "
417
- "/proc/meminfo showing host RAM. Memory guard in main.py will be conservative.",
418
- critical=False,
419
- )
420
-
421
- # ── 14. /proc/meminfo sanity ───────────────────────────────────────────────────
422
- section("14. /proc/meminfo (reference)")
423
- try:
424
- with open("/proc/meminfo") as f:
425
- lines = f.readlines()[:5]
426
- for line in lines:
427
- parts = line.split()
428
- if len(parts) >= 2:
429
- kb = int(parts[1])
430
- ok(parts[0].rstrip(":"), f"{kb // 1024} MB")
431
- except Exception as exc:
432
- record_fail("/proc/meminfo", str(exc), critical=False)
433
-
434
- # ═══════════════════════════════════════════════════════════════════════════════
435
- # Summary
436
- # ═══════════════════════════════════════════════════════════════════════════════
437
- print("\n" + "═" * 60, flush=True)
438
- print(" Validation Summary", flush=True)
439
- print("═" * 60, flush=True)
440
-
441
- if warnings:
442
- print(f"\n ⚠ {len(warnings)} warning(s):", flush=True)
443
- for label, detail in warnings:
444
- print(f" • {label}: {detail}", flush=True)
445
-
446
- if failures:
447
- print(f"\n ✗ {len(failures)} CRITICAL failure(s):", flush=True)
448
- for label, detail in failures:
449
- print(f" • {label}: {detail}", flush=True)
450
- print("\n Service will NOT start until these are resolved.", flush=True)
451
- print(" Check Dockerfile pip layers and Docker build log.", flush=True)
452
- print("═" * 60 + "\n", flush=True)
453
- if not SOFT_MODE:
454
- sys.exit(1)
455
- else:
456
- print(f"\n ✓ All critical checks passed", flush=True)
457
- if warnings:
458
- print(f" ⚠ {len(warnings)} non-critical warning(s) — see above", flush=True)
459
- print("\n Service is ready to start.", flush=True)
460
- print("═" * 60 + "\n", flush=True)
461
- sys.exit(0)