Spaces:
Sleeping
Sleeping
Delete validate.py
Browse files- validate.py +0 -324
validate.py
DELETED
|
@@ -1,324 +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 critical checks pass.
|
| 7 |
-
Exits 1 if any CRITICAL check fails — kills container startup with a clear
|
| 8 |
-
log message instead of allowing a broken service to appear healthy.
|
| 9 |
-
|
| 10 |
-
Usage:
|
| 11 |
-
python validate.py # exits 0/1
|
| 12 |
-
python validate.py --soft # always exits 0 (log only, no abort)
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
-
import importlib
|
| 16 |
-
import json
|
| 17 |
-
import os
|
| 18 |
-
import shutil
|
| 19 |
-
import sys
|
| 20 |
-
import tempfile
|
| 21 |
-
|
| 22 |
-
SOFT_MODE = "--soft" in sys.argv
|
| 23 |
-
|
| 24 |
-
MODELS_DIR = "/app/models"
|
| 25 |
-
EXTRACT_KIT_DIR = os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0")
|
| 26 |
-
EXTRACT_KIT_MODELS= os.path.join(EXTRACT_KIT_DIR, "models")
|
| 27 |
-
LAYOUT_MARKER = os.path.join(EXTRACT_KIT_MODELS, "Layout")
|
| 28 |
-
CONFIG_PATH = os.path.expanduser("~/magic-pdf.json")
|
| 29 |
-
|
| 30 |
-
failures: list[tuple[str, str]] = []
|
| 31 |
-
warnings: list[tuple[str, str]] = []
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def _ok(label: str, detail: str = "") -> None:
|
| 35 |
-
suffix = f" ({detail})" if detail else ""
|
| 36 |
-
print(f" ✓ {label}{suffix}", flush=True)
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def _fail(label: str, detail: str, critical: bool = True) -> None:
|
| 40 |
-
tag = "CRITICAL" if critical else "WARNING "
|
| 41 |
-
print(f" ✗ [{tag}] {label}: {detail}", flush=True)
|
| 42 |
-
if critical:
|
| 43 |
-
failures.append((label, detail))
|
| 44 |
-
else:
|
| 45 |
-
warnings.append((label, detail))
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
def _section(title: str) -> None:
|
| 49 |
-
print(f"\n{'─' * 60}", flush=True)
|
| 50 |
-
print(f" {title}", flush=True)
|
| 51 |
-
print(f"{'─' * 60}", flush=True)
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
def _check_import(
|
| 55 |
-
module: str,
|
| 56 |
-
symbols: list[str] | None = None,
|
| 57 |
-
label: str | None = None,
|
| 58 |
-
critical: bool = True,
|
| 59 |
-
) -> bool:
|
| 60 |
-
display = label or module
|
| 61 |
-
try:
|
| 62 |
-
mod = importlib.import_module(module)
|
| 63 |
-
if symbols:
|
| 64 |
-
missing = [s for s in symbols if not hasattr(mod, s)]
|
| 65 |
-
if missing:
|
| 66 |
-
_fail(display, f"missing symbols: {missing}", critical)
|
| 67 |
-
return False
|
| 68 |
-
version = getattr(mod, "__version__", None) or getattr(mod, "VERSION", None)
|
| 69 |
-
_ok(display, str(version) if version else "imported")
|
| 70 |
-
return True
|
| 71 |
-
except ImportError as exc:
|
| 72 |
-
_fail(display, str(exc), critical)
|
| 73 |
-
return False
|
| 74 |
-
except Exception as exc:
|
| 75 |
-
_fail(display, f"unexpected: {exc}", critical)
|
| 76 |
-
return False
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
# ═══════════════════════════════════════════════════════════════════════════════
|
| 80 |
-
print("\n" + "═" * 60, flush=True)
|
| 81 |
-
print(" MinerU OCR Service — Pre-flight Validation", flush=True)
|
| 82 |
-
print("═" * 60, flush=True)
|
| 83 |
-
|
| 84 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 85 |
-
_section("1. Python runtime")
|
| 86 |
-
pv = sys.version_info
|
| 87 |
-
if pv >= (3, 10):
|
| 88 |
-
_ok("Python", f"{pv.major}.{pv.minor}.{pv.micro}")
|
| 89 |
-
else:
|
| 90 |
-
_fail("Python", f"{pv.major}.{pv.minor} — magic-pdf requires >= 3.10")
|
| 91 |
-
|
| 92 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 93 |
-
_section("2. Core image + API libraries")
|
| 94 |
-
_check_import("cv2", label="cv2 (opencv-python-headless)")
|
| 95 |
-
_check_import("PIL", label="Pillow", symbols=["Image"])
|
| 96 |
-
_check_import("fastapi", label="fastapi")
|
| 97 |
-
_check_import("uvicorn", label="uvicorn")
|
| 98 |
-
_check_import("fitz", label="PyMuPDF (fitz)")
|
| 99 |
-
|
| 100 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 101 |
-
_section("3. PyTorch (CPU)")
|
| 102 |
-
torch_ok = _check_import("torch", label="torch")
|
| 103 |
-
if torch_ok:
|
| 104 |
-
try:
|
| 105 |
-
import torch
|
| 106 |
-
device = "cpu"
|
| 107 |
-
_ok("torch.cuda.is_available()", str(torch.cuda.is_available()))
|
| 108 |
-
t = torch.tensor([1.0, 2.0])
|
| 109 |
-
_ok("torch CPU tensor", f"shape={list(t.shape)} device={t.device}")
|
| 110 |
-
except Exception as exc:
|
| 111 |
-
_fail("torch CPU tensor test", str(exc))
|
| 112 |
-
|
| 113 |
-
_check_import("torchvision", label="torchvision")
|
| 114 |
-
|
| 115 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 116 |
-
_section("4. Layout detection (ultralytics / doclayout_yolo)")
|
| 117 |
-
_check_import("ultralytics", label="ultralytics")
|
| 118 |
-
_check_import("doclayout_yolo", label="doclayout_yolo", critical=False)
|
| 119 |
-
|
| 120 |
-
# ──────────────────────────────────────────────────��──────────────────────────
|
| 121 |
-
_section("5. ONNX Runtime")
|
| 122 |
-
_check_import("onnxruntime", label="onnxruntime")
|
| 123 |
-
|
| 124 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 125 |
-
_section("6. PaddleOCR stack")
|
| 126 |
-
_check_import("paddle", label="paddlepaddle (paddle)")
|
| 127 |
-
_check_import("paddleocr", label="paddleocr")
|
| 128 |
-
|
| 129 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 130 |
-
_section("7. Support libraries")
|
| 131 |
-
_check_import("shapely", label="shapely")
|
| 132 |
-
_check_import("pyclipper", label="pyclipper")
|
| 133 |
-
_check_import("scipy", label="scipy")
|
| 134 |
-
_check_import("rapid_table", label="rapid-table", critical=False)
|
| 135 |
-
|
| 136 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 137 |
-
_section("8. magic_pdf core")
|
| 138 |
-
_check_import("magic_pdf", label="magic_pdf (package root)")
|
| 139 |
-
_check_import(
|
| 140 |
-
"magic_pdf.data.dataset",
|
| 141 |
-
symbols=["PymuDocDataset", "ImageDataset"],
|
| 142 |
-
label="magic_pdf.data.dataset",
|
| 143 |
-
)
|
| 144 |
-
_check_import(
|
| 145 |
-
"magic_pdf.data.data_reader_writer",
|
| 146 |
-
symbols=["FileBasedDataReader", "FileBasedDataWriter"],
|
| 147 |
-
label="magic_pdf.data.data_reader_writer",
|
| 148 |
-
)
|
| 149 |
-
_check_import(
|
| 150 |
-
"magic_pdf.model.doc_analyze_by_custom_model",
|
| 151 |
-
symbols=["doc_analyze"],
|
| 152 |
-
label="magic_pdf.model.doc_analyze_by_custom_model [doc_analyze]",
|
| 153 |
-
)
|
| 154 |
-
_check_import(
|
| 155 |
-
"magic_pdf.config.enums",
|
| 156 |
-
symbols=["SupportedPdfParseMethod"],
|
| 157 |
-
label="magic_pdf.config.enums [SupportedPdfParseMethod]",
|
| 158 |
-
)
|
| 159 |
-
|
| 160 |
-
# Confirm removed deprecated API is gone
|
| 161 |
-
for dead in ["magic_pdf.pipe.UNIPipe", "magic_pdf.rw.DiskReaderWriter"]:
|
| 162 |
-
try:
|
| 163 |
-
importlib.import_module(dead)
|
| 164 |
-
_fail(dead, "still importable — code may use deprecated API", critical=False)
|
| 165 |
-
except ImportError:
|
| 166 |
-
_ok(f"{dead} (correctly absent)")
|
| 167 |
-
|
| 168 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 169 |
-
_section("9. MinerU config (magic-pdf.json)")
|
| 170 |
-
if os.path.exists(CONFIG_PATH):
|
| 171 |
-
try:
|
| 172 |
-
with open(CONFIG_PATH) as f:
|
| 173 |
-
cfg = json.load(f)
|
| 174 |
-
required_keys = ["models-dir", "device-mode"]
|
| 175 |
-
missing_keys = [k for k in required_keys if k not in cfg]
|
| 176 |
-
if missing_keys:
|
| 177 |
-
_fail("Config keys", f"missing: {missing_keys}")
|
| 178 |
-
else:
|
| 179 |
-
_ok("Config file", CONFIG_PATH)
|
| 180 |
-
_ok("device-mode", cfg.get("device-mode", "?"))
|
| 181 |
-
_ok("models-dir", cfg.get("models-dir", "?"))
|
| 182 |
-
_ok("formula.enable", str(cfg.get("formula-config", {}).get("enable", "?")))
|
| 183 |
-
_ok("table.enable", str(cfg.get("table-config", {}).get("enable", "?")))
|
| 184 |
-
_ok("layoutreader-dir", cfg.get("layoutreader-model-dir", "(empty)") or "(empty — fallback)")
|
| 185 |
-
except json.JSONDecodeError as exc:
|
| 186 |
-
_fail("Config JSON", f"parse error: {exc}")
|
| 187 |
-
except Exception as exc:
|
| 188 |
-
_fail("Config file", str(exc))
|
| 189 |
-
else:
|
| 190 |
-
_fail(
|
| 191 |
-
"Config file",
|
| 192 |
-
f"not found at {CONFIG_PATH}. "
|
| 193 |
-
"Run download_models.py or check the Docker build log for errors.",
|
| 194 |
-
)
|
| 195 |
-
|
| 196 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 197 |
-
_section("10. Model files")
|
| 198 |
-
model_checks = [
|
| 199 |
-
("PDF-Extract-Kit-1.0 root", EXTRACT_KIT_DIR, True),
|
| 200 |
-
("Layout models (canary dir)", LAYOUT_MARKER, True),
|
| 201 |
-
("MFD models", os.path.join(EXTRACT_KIT_MODELS, "MFD"), True),
|
| 202 |
-
("Table models", os.path.join(EXTRACT_KIT_MODELS, "TabRec"), True),
|
| 203 |
-
("layoutreader (optional)", os.path.join(MODELS_DIR, "layoutreader"), False),
|
| 204 |
-
]
|
| 205 |
-
for label, check_path, critical in model_checks:
|
| 206 |
-
if os.path.isdir(check_path):
|
| 207 |
-
try:
|
| 208 |
-
n = sum(1 for _ in os.scandir(check_path))
|
| 209 |
-
except OSError:
|
| 210 |
-
n = "?"
|
| 211 |
-
_ok(label, f"{n} entries")
|
| 212 |
-
else:
|
| 213 |
-
_fail(label, f"directory not found: {check_path}", critical)
|
| 214 |
-
|
| 215 |
-
# Validate config models-dir points to an existing path
|
| 216 |
-
try:
|
| 217 |
-
with open(CONFIG_PATH) as f:
|
| 218 |
-
cfg = json.load(f)
|
| 219 |
-
cfg_models = cfg.get("models-dir", "")
|
| 220 |
-
if cfg_models and os.path.isdir(cfg_models):
|
| 221 |
-
_ok("Config models-dir exists", cfg_models)
|
| 222 |
-
elif cfg_models:
|
| 223 |
-
_fail("Config models-dir", f"points to missing path: {cfg_models}")
|
| 224 |
-
except Exception:
|
| 225 |
-
pass # already reported above
|
| 226 |
-
|
| 227 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 228 |
-
_section("11. Temp storage")
|
| 229 |
-
try:
|
| 230 |
-
td = tempfile.mkdtemp(prefix="mineru_validate_")
|
| 231 |
-
test_file = os.path.join(td, "write_test.bin")
|
| 232 |
-
with open(test_file, "wb") as f:
|
| 233 |
-
f.write(b"\x00" * 4096)
|
| 234 |
-
assert os.path.getsize(test_file) == 4096
|
| 235 |
-
shutil.rmtree(td)
|
| 236 |
-
_ok("Temp write + delete", tempfile.gettempdir())
|
| 237 |
-
except Exception as exc:
|
| 238 |
-
_fail("Temp storage", str(exc))
|
| 239 |
-
|
| 240 |
-
# ─────────────────────────────────────────────────────────────────────────────
|
| 241 |
-
_section("12. Memory (cgroups preferred over /proc/meminfo)")
|
| 242 |
-
total_mb = used_mb = 0
|
| 243 |
-
mem_source = "unavailable"
|
| 244 |
-
|
| 245 |
-
try:
|
| 246 |
-
with open("/sys/fs/cgroup/memory.max") as f:
|
| 247 |
-
raw = f.read().strip()
|
| 248 |
-
if raw != "max":
|
| 249 |
-
total_mb = int(raw) // (1024 * 1024)
|
| 250 |
-
with open("/sys/fs/cgroup/memory.current") as f:
|
| 251 |
-
used_mb = int(f.read().strip()) // (1024 * 1024)
|
| 252 |
-
mem_source = "cgroups v2"
|
| 253 |
-
except (FileNotFoundError, ValueError, OSError):
|
| 254 |
-
pass
|
| 255 |
-
|
| 256 |
-
if total_mb == 0:
|
| 257 |
-
try:
|
| 258 |
-
with open("/sys/fs/cgroup/memory/memory.limit_in_bytes") as f:
|
| 259 |
-
lim = int(f.read().strip())
|
| 260 |
-
with open("/sys/fs/cgroup/memory/memory.usage_in_bytes") as f:
|
| 261 |
-
usg = int(f.read().strip())
|
| 262 |
-
if lim < 128 * 1024 * 1024 * 1024:
|
| 263 |
-
total_mb = lim // (1024 * 1024)
|
| 264 |
-
used_mb = usg // (1024 * 1024)
|
| 265 |
-
mem_source = "cgroups v1"
|
| 266 |
-
except (FileNotFoundError, ValueError, OSError):
|
| 267 |
-
pass
|
| 268 |
-
|
| 269 |
-
if total_mb == 0:
|
| 270 |
-
try:
|
| 271 |
-
info: dict[str, int] = {}
|
| 272 |
-
with open("/proc/meminfo") as f:
|
| 273 |
-
for line in f:
|
| 274 |
-
parts = line.split()
|
| 275 |
-
if len(parts) >= 2:
|
| 276 |
-
info[parts[0].rstrip(":")] = int(parts[1])
|
| 277 |
-
total_mb = info.get("MemTotal", 0) // 1024
|
| 278 |
-
used_mb = (info.get("MemTotal", 0) - info.get("MemAvailable", 0)) // 1024
|
| 279 |
-
mem_source = "/proc/meminfo (may show host RAM, not container limit)"
|
| 280 |
-
except Exception:
|
| 281 |
-
pass
|
| 282 |
-
|
| 283 |
-
_ok("Memory source", mem_source)
|
| 284 |
-
_ok("Total memory", f"{total_mb} MB")
|
| 285 |
-
_ok("Used memory", f"{used_mb} MB")
|
| 286 |
-
_ok("Free memory", f"{total_mb - used_mb} MB")
|
| 287 |
-
if total_mb > 32 * 1024:
|
| 288 |
-
_fail(
|
| 289 |
-
"Memory plausibility",
|
| 290 |
-
f"{total_mb} MB is suspiciously large for a container "
|
| 291 |
-
"(cgroups may be missing; /proc/meminfo shows host RAM). "
|
| 292 |
-
"Memory guard in main.py will be conservative.",
|
| 293 |
-
critical=False,
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
-
# ═══════════════════════════════════════════════════════════════════════════════
|
| 297 |
-
# Summary
|
| 298 |
-
# ═══════════════════════════════════════════════════════════════════════════════
|
| 299 |
-
print("\n" + "═" * 60, flush=True)
|
| 300 |
-
print(" Validation Summary", flush=True)
|
| 301 |
-
print("═" * 60, flush=True)
|
| 302 |
-
|
| 303 |
-
if warnings:
|
| 304 |
-
print(f"\n ⚠ {len(warnings)} non-critical warning(s):", flush=True)
|
| 305 |
-
for lbl, det in warnings:
|
| 306 |
-
print(f" • {lbl}: {det}", flush=True)
|
| 307 |
-
|
| 308 |
-
if failures:
|
| 309 |
-
print(f"\n ✗ {len(failures)} CRITICAL failure(s) — service WILL NOT start:", flush=True)
|
| 310 |
-
for lbl, det in failures:
|
| 311 |
-
print(f" • {lbl}: {det}", flush=True)
|
| 312 |
-
print("\n Remediation:", flush=True)
|
| 313 |
-
print(" 1. Check Dockerfile pip layers for missing packages.", flush=True)
|
| 314 |
-
print(" 2. Ensure torch CPU layer uses --index-url https://download.pytorch.org/whl/cpu", flush=True)
|
| 315 |
-
print(" 3. Ensure magic-pdf layer uses --extra-index-url https://myhloli.github.io/wheels/", flush=True)
|
| 316 |
-
print(" 4. Ensure doclayout-yolo, ultralytics, onnxruntime, paddleocr are explicit.", flush=True)
|
| 317 |
-
print("═" * 60 + "\n", flush=True)
|
| 318 |
-
if not SOFT_MODE:
|
| 319 |
-
sys.exit(1)
|
| 320 |
-
else:
|
| 321 |
-
print(f"\n ✓ All critical checks passed ({len(warnings)} warning(s) non-critical).", flush=True)
|
| 322 |
-
print("\n Service is ready to start.", flush=True)
|
| 323 |
-
print("═" * 60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