crazylemonade commited on
Commit
b1d24dd
·
verified ·
1 Parent(s): 159b696

Delete download_models.py

Browse files
Files changed (1) hide show
  1. download_models.py +0 -185
download_models.py DELETED
@@ -1,185 +0,0 @@
1
- """
2
- Download MinerU pipeline models from Hugging Face Hub.
3
-
4
- Called once during Docker build: python download_models.py
5
-
6
- Optimizations vs original:
7
- - Skip-if-exists: if models are already present (Docker layer cache reuse),
8
- the entire download is skipped without re-downloading anything.
9
- - MFR excluded: formula recognition models (unimernet, ~1-2 GB) are not
10
- downloaded because formula recognition is disabled in the config. Excluding
11
- them cuts download time and image size significantly.
12
- - layoutreader optional: if download fails (network issue, repo unavailable),
13
- the script logs a warning and continues. MinerU falls back to its built-in
14
- layout ordering without layoutreader.
15
-
16
- ── FORENSIC: OCR MODEL AVAILABILITY IN opendatalab/PDF-Extract-Kit-1.0 ───────
17
-
18
- models_config.yml in magic-pdf 1.3.12 was patched in Dockerfile Layer 3.5 to
19
- use the weight files that ARE present in the HF repo. After the patch:
20
-
21
- DEFAULT CPU path (ch_lite):
22
- det: ch_PP-OCRv5_det_infer.pth ← present in HF repo ✓
23
- rec: ch_PP-OCRv5_rec_infer.pth ← present in HF repo ✓
24
-
25
- en / latin det (patched):
26
- det: Multilingual_PP-OCRv3_det_infer.pth ← present in HF repo ✓
27
-
28
- NOT IN REPO (these files do NOT exist and are not needed for default usage):
29
- ch_PP-OCRv3_det_infer.pth ← absent; patched to v5
30
- en_PP-OCRv3_det_infer.pth ← absent; patched to multilingual
31
- en_PP-OCRv4_rec_infer.pth ← absent; en rec unavailable
32
- korean/japan/chinese_cht/etc v3 rec ← absent; those langs need explicit
33
- lang= arg which is not default
34
-
35
- BUNDLED IN WHEEL (not downloaded here):
36
- magic_pdf/resources/slanet_plus/slanet-plus.onnx ← table model, in wheel
37
- magic_pdf/resources/fasttext-langdetect/lid.176.ftz
38
- magic_pdf/resources/yolov11-langdetect/yolo_v11_ft.pt
39
-
40
- Models saved to /app/models/
41
- Config written to /root/magic-pdf.json
42
- """
43
-
44
- import json
45
- import os
46
- import sys
47
-
48
- MODELS_DIR = "/app/models"
49
- EXTRACT_KIT_DIR = os.path.join(MODELS_DIR, "PDF-Extract-Kit-1.0")
50
- LAYOUTREADER_DIR = os.path.join(MODELS_DIR, "layoutreader")
51
-
52
- # Canary files: both must exist for the skip-if-exists check to pass.
53
- # Using the OCR det weight (not just the Layout dir) ensures a stale cache
54
- # that predates the v3→v5 model rename cannot produce a false positive.
55
- _CANARY_DIR = os.path.join(EXTRACT_KIT_DIR, "models", "Layout")
56
- _CANARY_FILE = os.path.join(
57
- EXTRACT_KIT_DIR, "models", "OCR", "paddleocr_torch",
58
- "ch_PP-OCRv5_det_infer.pth" # patched det; absent in v3-era cache
59
- )
60
-
61
-
62
- def _models_present() -> bool:
63
- """Return True only when BOTH the Layout directory AND the OCR v5 det weight
64
- exist. This prevents stale Docker layer caches (built before the v3→v5 patch)
65
- from reporting models as present when the required file is missing."""
66
- return os.path.isdir(_CANARY_DIR) and os.path.isfile(_CANARY_FILE)
67
-
68
-
69
- def _write_config(layoutreader_dir: str) -> None:
70
- config = {
71
- "bucket_info": {},
72
- "models-dir": os.path.join(EXTRACT_KIT_DIR, "models"),
73
- "layoutreader-model-dir": layoutreader_dir,
74
- "device-mode": "cpu",
75
- "layout-config": {
76
- "model": "doclayout_yolo"
77
- },
78
- "formula-config": {
79
- "mfd_model": "yolo_v8_mfd",
80
- "mfr_model": "unimernet_small",
81
- "enable": False
82
- },
83
- "table-config": {
84
- "model": "rapid_table",
85
- "enable": True,
86
- "max_time": 400
87
- },
88
- "backend": "pipeline"
89
- }
90
- config_path = os.path.expanduser("~/magic-pdf.json")
91
- with open(config_path, "w") as f:
92
- json.dump(config, f, indent=2)
93
- print(f"Config written → {config_path}")
94
- return config_path
95
-
96
-
97
- def download() -> None:
98
- try:
99
- from huggingface_hub import snapshot_download
100
- except ImportError:
101
- print("ERROR: huggingface_hub not installed", file=sys.stderr)
102
- sys.exit(1)
103
-
104
- # ── Skip-if-exists ────────────────────────────────────────────────────────
105
- if _models_present():
106
- print("Models already present — skipping download (Docker layer cache).")
107
- # Config may still need writing if this is a fresh container from cached layer
108
- lr_dir = LAYOUTREADER_DIR if os.path.isdir(LAYOUTREADER_DIR) else ""
109
- _write_config(lr_dir)
110
- return
111
-
112
- os.makedirs(MODELS_DIR, exist_ok=True)
113
-
114
- # ── PDF-Extract-Kit-1.0 ───────────────────────────────────────────────────
115
- # Excluded via ignore_patterns:
116
- # models/MFR — formula recognition (unimernet). Disabled in config.
117
- # Saves ~1-2 GB of download and disk.
118
- #
119
- # OCR models (models/OCR/paddleocr_torch/) ARE included (not ignored).
120
- # After the Layer 3.5 patch, the files models_config.yml references match
121
- # what is actually present in the repo:
122
- # ch_PP-OCRv5_det_infer.pth ← present ✓
123
- # ch_PP-OCRv5_rec_infer.pth ← present ✓
124
- # Multilingual_PP-OCRv3_det_infer.pth ← present ✓
125
- print("=" * 60)
126
- print("Downloading PDF-Extract-Kit-1.0 ...")
127
- print(" (MFR/formula-recognition excluded — disabled in config)")
128
- print("=" * 60)
129
- snapshot_download(
130
- repo_id="opendatalab/PDF-Extract-Kit-1.0",
131
- local_dir=EXTRACT_KIT_DIR,
132
- ignore_patterns=[
133
- "*.git*",
134
- ".gitattributes",
135
- "models/MFR*",
136
- "models/MFR/*",
137
- ],
138
- )
139
- print(f" → {EXTRACT_KIT_DIR}")
140
-
141
- # Verify canary file landed correctly
142
- if not os.path.isfile(_CANARY_FILE):
143
- print(
144
- f"\nERROR: Expected OCR model not found after download:\n"
145
- f" {_CANARY_FILE}\n"
146
- f"The HF repo may have changed its file structure.\n"
147
- f"Run: python3 -c \"from huggingface_hub import list_repo_files; "
148
- f"[print(f) for f in list_repo_files('opendatalab/PDF-Extract-Kit-1.0')]\"\n"
149
- f"to inspect the current repo contents.",
150
- file=sys.stderr,
151
- )
152
- sys.exit(1)
153
- print(f" Canary verified: {os.path.basename(_CANARY_FILE)} ✓")
154
-
155
- # ── layoutreader (optional) ───────────────────────────────────────────────
156
- # Improves reading-order accuracy. If unavailable, MinerU uses fallback.
157
- layoutreader_dir = ""
158
- print("=" * 60)
159
- print("Downloading layoutreader (optional, improves reading order) ...")
160
- print("=" * 60)
161
- try:
162
- snapshot_download(
163
- repo_id="hantian/layoutreader",
164
- local_dir=LAYOUTREADER_DIR,
165
- ignore_patterns=["*.git*", ".gitattributes"],
166
- )
167
- layoutreader_dir = LAYOUTREADER_DIR
168
- print(f" → {LAYOUTREADER_DIR}")
169
- except Exception as exc:
170
- print(f" WARNING: layoutreader download failed ({exc})")
171
- print(" Continuing without layoutreader — MinerU will use fallback ordering.")
172
-
173
- # ── Write config ──────────────────────────────────────────────────────────
174
- _write_config(layoutreader_dir)
175
-
176
- print("\n✓ Model setup complete.")
177
- print(f" models-dir : {os.path.join(EXTRACT_KIT_DIR, 'models')}")
178
- print(f" layoutreader-dir : {layoutreader_dir or '(not available)'}")
179
- print(f" device-mode : cpu")
180
- print(f" formula recognition : disabled (MFR models excluded)")
181
- print(f" table recognition : enabled (slanet-plus.onnx bundled in wheel)")
182
-
183
-
184
- if __name__ == "__main__":
185
- download()