crazylemonade commited on
Commit
fd0dcec
Β·
verified Β·
1 Parent(s): 6038966

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +125 -0
  2. requirements.txt +32 -0
  3. validate.py +324 -0
Dockerfile ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ─────────────────────────────────────────────────────────────────────────────
2
+ # MinerU OCR Service β€” Hugging Face Docker Space (CPU / pipeline backend)
3
+ # Optimized for FREE tier: 2 vCPU Β· 16 GB RAM Β· 50 GB Disk Β· No GPU
4
+ #
5
+ # ── Root cause of previous failures ──────────────────────────────────────────
6
+ #
7
+ # Failure 1: No module named 'cv2'
8
+ # Cause: magic-pdf[full-cpu] may pull in opencv-python (X11 build) instead
9
+ # of headless; removed X11 libs caused dlopen failure.
10
+ # Fix: Explicitly install opencv-python-headless in Layer 1 BEFORE
11
+ # magic-pdf, so pip considers cv2 already satisfied.
12
+ #
13
+ # Failure 2: stat: path should be string ... not list
14
+ # Cause: read_local_images([path]) β€” list passed where string expected.
15
+ # Fix: FileBasedDataReader + ImageDataset in main.py (code fix, not here).
16
+ #
17
+ # Failure 3: No module named 'ultralytics'
18
+ # Cause: ultralytics β†’ torch β†’ no CPU torch wheel on PyPI. pip's resolver
19
+ # saw no satisfiable torch, skipped ultralytics entirely. Since
20
+ # doclayout_yolo requires ultralytics, layout detection crashed.
21
+ # Fix: Install torch/torchvision CPU from the official PyTorch CPU index
22
+ # in a dedicated layer BEFORE magic-pdf, then list all OCR runtime
23
+ # deps explicitly so pip cannot skip them.
24
+ #
25
+ # ── Pip layer strategy ────────────────────────────────────────────────────────
26
+ # Layer 1 β€” small/fast packages + opencv-headless
27
+ # Layer 2 β€” torch CPU + torchvision CPU (PyTorch official CPU wheel index)
28
+ # Own layer: large (~500 MB), slow, cached on rebuild.
29
+ # Must be BEFORE magic-pdf so torch is pre-satisfied.
30
+ # Layer 3 β€” magic-pdf[full-cpu] + ALL explicit OCR runtime deps
31
+ # Explicit listing prevents silent skip of transitive deps.
32
+ #
33
+ # ── System packages ───────────────────────────────────────────────────────────
34
+ # Removed: libreoffice (1.5 GB, DOCX/PPTX/XLSX support dropped for MVP)
35
+ # libsm6 libxext6 libxrender-dev (X11 display stubs, not needed headless)
36
+ # libmagic1 (python-magic not used)
37
+ # wget curl (runtime tools, not needed in container)
38
+ # Kept: libgl1 β€” OpenCV requires libGL.so.1
39
+ # libglib2.0-0 β€” GLib, required by OpenCV and C extensions
40
+ # libgomp1 β€” OpenMP, required by ONNX Runtime and YOLO
41
+ # poppler-utils β€” pdfinfo / pdftoppm for MinerU PDF pre-processing
42
+ # ─────────────────────────────────────────────────────────────────────────────
43
+
44
+ FROM python:3.10-slim
45
+
46
+ ENV PYTHONUNBUFFERED=1
47
+ ENV PYTHONDONTWRITEBYTECODE=1
48
+ ENV PORT=7860
49
+ ENV MINERU_DEVICE_MODE=cpu
50
+ ENV MINERU_BACKEND=pipeline
51
+
52
+ # ── System dependencies ───────────────────────────────────────────────────────
53
+ RUN apt-get update \
54
+ && apt-get install -y --no-install-recommends \
55
+ libgl1 \
56
+ libglib2.0-0 \
57
+ libgomp1 \
58
+ poppler-utils \
59
+ && rm -rf /var/lib/apt/lists/*
60
+
61
+ WORKDIR /app
62
+
63
+ # ── Layer 1: small packages + opencv-headless ─────────────────────────────────
64
+ RUN pip install --no-cache-dir --timeout 300 \
65
+ "fastapi>=0.115.0" \
66
+ "uvicorn[standard]>=0.32.0" \
67
+ "python-multipart>=0.0.12" \
68
+ "Pillow>=10.0.0" \
69
+ "pillow-heif>=0.18.0" \
70
+ "huggingface_hub>=0.25.0" \
71
+ "opencv-python-headless>=4.8.0"
72
+
73
+ # ── Layer 2: torch CPU + torchvision CPU ──────────────────────────────────────
74
+ # MUST use --index-url (not --extra-index-url) to prefer the CPU-only wheel.
75
+ # Without this layer, pip finds no CPU-compatible torch on PyPI and silently
76
+ # skips ultralytics, doclayout_yolo, and anything else that depends on torch.
77
+ RUN pip install --no-cache-dir --timeout 600 \
78
+ --index-url https://download.pytorch.org/whl/cpu \
79
+ "torch>=2.0.0" \
80
+ "torchvision>=0.15.0"
81
+
82
+ # ── Layer 3: magic-pdf + ALL explicit OCR runtime dependencies ────────────────
83
+ # Every package listed here is a confirmed runtime requirement of doc_analyze:
84
+ #
85
+ # magic-pdf[full-cpu] β€” MinerU core + extras
86
+ # doclayout-yolo β€” layout detection model wrapper (uses ultralytics)
87
+ # ultralytics β€” YOLO inference (doclayout_yolo runtime)
88
+ # onnxruntime β€” ONNX inference for MFD / table models
89
+ # paddlepaddle β€” PaddleOCR backend (CPU; from myhloli index)
90
+ # paddleocr β€” OCR engine (text extraction)
91
+ # rapid-table β€” table structure reconstruction
92
+ # shapely β€” geometry ops used by paddleocr
93
+ # pyclipper β€” polygon clipping used by paddleocr
94
+ # scipy β€” scientific computing used by layout/OCR models
95
+ RUN pip install --no-cache-dir --timeout 600 \
96
+ --extra-index-url https://myhloli.github.io/wheels/ \
97
+ "magic-pdf[full-cpu]==1.3.12" \
98
+ "doclayout-yolo>=0.0.2" \
99
+ "ultralytics>=8.0.0" \
100
+ "onnxruntime>=1.17.0" \
101
+ "paddleocr>=2.7.0" \
102
+ "rapid-table>=0.2.0" \
103
+ "shapely>=2.0.0" \
104
+ "pyclipper>=1.3.0" \
105
+ "scipy>=1.11.0"
106
+
107
+ # ── Application code ──────────────────────────────────────────────────────────
108
+ COPY download_models.py .
109
+ COPY validate.py .
110
+ COPY main.py .
111
+ COPY entrypoint.sh .
112
+ RUN chmod +x entrypoint.sh
113
+
114
+ # ── Download models at build time ─────────────────────────────────────────────
115
+ # Baked into image = zero cold-start download delay.
116
+ # Skip-if-exists in download_models.py = Docker layer-cache reuse on
117
+ # code-only rebuilds (models already present, download skipped).
118
+ RUN python download_models.py
119
+
120
+ # Persist config; entrypoint.sh restores it if /root is wiped on restart.
121
+ RUN mkdir -p /app/config && cp /root/magic-pdf.json /app/config/magic-pdf.json
122
+
123
+ # ── Runtime ───────────────────────────────────────────────────────────────────
124
+ EXPOSE 7860
125
+ ENTRYPOINT ["/app/entrypoint.sh"]
requirements.txt ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reference only β€” dependencies are installed directly in the Dockerfile
2
+ # as three separate pip layers for granular Docker layer caching.
3
+ #
4
+ # ── Layer 1: small packages ───────────────────────────────────────────────────
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 ← headless; must be Layer 1 before magic-pdf
12
+ #
13
+ # ── Layer 2: torch CPU (from https://download.pytorch.org/whl/cpu) ────────────
14
+ # torch>=2.0.0 ← CPU-only wheel (not on PyPI as CPU)
15
+ # torchvision>=0.15.0 ← CPU-only wheel
16
+ #
17
+ # ── Layer 3: magic-pdf + ALL explicit OCR runtime deps ───────────────────────
18
+ # (--extra-index-url https://myhloli.github.io/wheels/ for paddlepaddle CPU)
19
+ # magic-pdf[full-cpu]==1.3.12
20
+ # doclayout-yolo>=0.0.2 ← layout detection (uses ultralytics)
21
+ # ultralytics>=8.0.0 ← YOLO inference engine
22
+ # onnxruntime>=1.17.0 ← ONNX for MFD + table models
23
+ # paddleocr>=2.7.0 ← OCR text extraction engine
24
+ # rapid-table>=0.2.0 ← table structure reconstruction
25
+ # shapely>=2.0.0 ← geometry ops (paddleocr dep)
26
+ # pyclipper>=1.3.0 ← polygon clipping (paddleocr dep)
27
+ # scipy>=1.11.0 ← scientific computing (layout/OCR dep)
28
+ #
29
+ # ── Why explicit listing matters ──────────────────────────────────────────────
30
+ # Without explicit listing, pip's resolver can skip transitive deps when
31
+ # it cannot satisfy their sub-deps (e.g. torch on PyPI has no CPU wheel,
32
+ # so pip silently skips ultralytics β†’ doclayout_yolo β†’ layout fails at runtime).
validate.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 + "\n", flush=True)
324
+ sys.exit(0)