davanstrien HF Staff commited on
Commit
0a2d343
·
verified ·
1 Parent(s): 37431e4

Upload glm-ocr-bucket.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. glm-ocr-bucket.py +364 -0
glm-ocr-bucket.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "pillow",
5
+ # "pymupdf",
6
+ # "vllm",
7
+ # "torch",
8
+ # ]
9
+ #
10
+ # [[tool.uv.index]]
11
+ # url = "https://wheels.vllm.ai/nightly/cu129"
12
+ #
13
+ # [tool.uv]
14
+ # prerelease = "allow"
15
+ # override-dependencies = ["transformers>=5.1.0"]
16
+ # ///
17
+
18
+ """
19
+ OCR images and PDFs from a directory using GLM-OCR, writing markdown files.
20
+
21
+ Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`
22
+ (requires huggingface_hub with PR #3936 volume mounting support).
23
+
24
+ The script reads images/PDFs from INPUT_DIR, runs GLM-OCR via vLLM, and writes
25
+ one .md file per image (or per PDF page) to OUTPUT_DIR, preserving directory structure.
26
+
27
+ Input: Output:
28
+ /input/page1.png → /output/page1.md
29
+ /input/report.pdf → /output/report/page_001.md
30
+ (3 pages) /output/report/page_002.md
31
+ /output/report/page_003.md
32
+ /input/sub/photo.jpg → /output/sub/photo.md
33
+
34
+ Examples:
35
+
36
+ # Local test
37
+ uv run glm-ocr-bucket.py ./test-images ./test-output
38
+
39
+ # HF Jobs with bucket volumes (PR #3936)
40
+ hf jobs uv run --flavor l4x1 \\
41
+ -s HF_TOKEN \\
42
+ -v bucket/user/ocr-input:/input:ro \\
43
+ -v bucket/user/ocr-output:/output \\
44
+ glm-ocr-bucket.py /input /output
45
+
46
+ Model: zai-org/GLM-OCR (0.9B, 94.62% OmniDocBench V1.5, MIT licensed)
47
+ """
48
+
49
+ import argparse
50
+ import base64
51
+ import io
52
+ import logging
53
+ import sys
54
+ import time
55
+ from pathlib import Path
56
+
57
+ import torch
58
+ from PIL import Image
59
+ from vllm import LLM, SamplingParams
60
+
61
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
62
+ logger = logging.getLogger(__name__)
63
+
64
+ MODEL = "zai-org/GLM-OCR"
65
+
66
+ TASK_PROMPTS = {
67
+ "ocr": "Text Recognition:",
68
+ "formula": "Formula Recognition:",
69
+ "table": "Table Recognition:",
70
+ }
71
+
72
+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}
73
+
74
+
75
+ def check_cuda_availability():
76
+ if not torch.cuda.is_available():
77
+ logger.error("CUDA is not available. This script requires a GPU.")
78
+ sys.exit(1)
79
+ logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
80
+
81
+
82
+ def make_ocr_message(image: Image.Image, task: str = "ocr") -> list[dict]:
83
+ """Create chat message for GLM-OCR from a PIL Image."""
84
+ image = image.convert("RGB")
85
+ buf = io.BytesIO()
86
+ image.save(buf, format="PNG")
87
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
88
+
89
+ return [
90
+ {
91
+ "role": "user",
92
+ "content": [
93
+ {"type": "image_url", "image_url": {"url": data_uri}},
94
+ {"type": "text", "text": TASK_PROMPTS.get(task, TASK_PROMPTS["ocr"])},
95
+ ],
96
+ }
97
+ ]
98
+
99
+
100
+ def discover_files(input_dir: Path) -> list[Path]:
101
+ """Walk input_dir recursively, returning sorted list of image and PDF files."""
102
+ files = []
103
+ for path in sorted(input_dir.rglob("*")):
104
+ if not path.is_file():
105
+ continue
106
+ ext = path.suffix.lower()
107
+ if ext in IMAGE_EXTENSIONS or ext == ".pdf":
108
+ files.append(path)
109
+ return files
110
+
111
+
112
+ def prepare_images(
113
+ files: list[Path], input_dir: Path, output_dir: Path, pdf_dpi: int
114
+ ) -> list[tuple[Image.Image, Path]]:
115
+ """
116
+ Convert discovered files into (PIL.Image, output_md_path) pairs.
117
+
118
+ Images map 1:1. PDFs expand to one image per page in a subdirectory.
119
+ """
120
+ import fitz # pymupdf
121
+
122
+ items: list[tuple[Image.Image, Path]] = []
123
+
124
+ for file_path in files:
125
+ rel = file_path.relative_to(input_dir)
126
+ ext = file_path.suffix.lower()
127
+
128
+ if ext == ".pdf":
129
+ # PDF → one .md per page in a subdirectory named after the PDF
130
+ pdf_output_dir = output_dir / rel.with_suffix("")
131
+ try:
132
+ doc = fitz.open(file_path)
133
+ num_pages = len(doc)
134
+ logger.info(f"PDF: {rel} ({num_pages} pages)")
135
+ for page_num in range(num_pages):
136
+ page = doc[page_num]
137
+ # Render at specified DPI
138
+ zoom = pdf_dpi / 72.0
139
+ mat = fitz.Matrix(zoom, zoom)
140
+ pix = page.get_pixmap(matrix=mat)
141
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
142
+ md_path = pdf_output_dir / f"page_{page_num + 1:03d}.md"
143
+ items.append((img, md_path))
144
+ doc.close()
145
+ except Exception as e:
146
+ logger.error(f"Failed to open PDF {rel}: {e}")
147
+ else:
148
+ # Image → single .md
149
+ try:
150
+ img = Image.open(file_path).convert("RGB")
151
+ md_path = output_dir / rel.with_suffix(".md")
152
+ items.append((img, md_path))
153
+ except Exception as e:
154
+ logger.error(f"Failed to open image {rel}: {e}")
155
+
156
+ return items
157
+
158
+
159
+ def main():
160
+ parser = argparse.ArgumentParser(
161
+ description="OCR images/PDFs from a directory using GLM-OCR, output markdown files.",
162
+ formatter_class=argparse.RawDescriptionHelpFormatter,
163
+ epilog="""
164
+ Task modes:
165
+ ocr Text recognition to markdown (default)
166
+ formula LaTeX formula recognition
167
+ table Table extraction (HTML)
168
+
169
+ Examples:
170
+ uv run glm-ocr-bucket.py ./images ./output
171
+ uv run glm-ocr-bucket.py /input /output --task table --pdf-dpi 200
172
+
173
+ HF Jobs with bucket volumes (requires huggingface_hub PR #3936):
174
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
175
+ -v bucket/user/input-bucket:/input:ro \\
176
+ -v bucket/user/output-bucket:/output \\
177
+ glm-ocr-bucket.py /input /output
178
+ """,
179
+ )
180
+ parser.add_argument("input_dir", help="Directory containing images and/or PDFs")
181
+ parser.add_argument("output_dir", help="Directory to write markdown output files")
182
+ parser.add_argument(
183
+ "--task",
184
+ choices=["ocr", "formula", "table"],
185
+ default="ocr",
186
+ help="OCR task mode (default: ocr)",
187
+ )
188
+ parser.add_argument(
189
+ "--batch-size", type=int, default=16, help="Batch size for vLLM (default: 16)"
190
+ )
191
+ parser.add_argument(
192
+ "--max-model-len",
193
+ type=int,
194
+ default=8192,
195
+ help="Max model context length (default: 8192)",
196
+ )
197
+ parser.add_argument(
198
+ "--max-tokens",
199
+ type=int,
200
+ default=8192,
201
+ help="Max output tokens (default: 8192)",
202
+ )
203
+ parser.add_argument(
204
+ "--gpu-memory-utilization",
205
+ type=float,
206
+ default=0.8,
207
+ help="GPU memory utilization (default: 0.8)",
208
+ )
209
+ parser.add_argument(
210
+ "--pdf-dpi",
211
+ type=int,
212
+ default=300,
213
+ help="DPI for PDF page rendering (default: 300)",
214
+ )
215
+ parser.add_argument(
216
+ "--temperature",
217
+ type=float,
218
+ default=0.01,
219
+ help="Sampling temperature (default: 0.01)",
220
+ )
221
+ parser.add_argument(
222
+ "--top-p", type=float, default=0.00001, help="Top-p sampling (default: 0.00001)"
223
+ )
224
+ parser.add_argument(
225
+ "--repetition-penalty",
226
+ type=float,
227
+ default=1.1,
228
+ help="Repetition penalty (default: 1.1)",
229
+ )
230
+ parser.add_argument(
231
+ "--verbose",
232
+ action="store_true",
233
+ help="Print resolved package versions",
234
+ )
235
+
236
+ args = parser.parse_args()
237
+
238
+ check_cuda_availability()
239
+
240
+ input_dir = Path(args.input_dir)
241
+ output_dir = Path(args.output_dir)
242
+
243
+ if not input_dir.is_dir():
244
+ logger.error(f"Input directory does not exist: {input_dir}")
245
+ sys.exit(1)
246
+
247
+ output_dir.mkdir(parents=True, exist_ok=True)
248
+
249
+ # Discover and prepare
250
+ start_time = time.time()
251
+
252
+ logger.info(f"Scanning {input_dir} for images and PDFs...")
253
+ files = discover_files(input_dir)
254
+ if not files:
255
+ logger.error(f"No image or PDF files found in {input_dir}")
256
+ sys.exit(1)
257
+
258
+ pdf_count = sum(1 for f in files if f.suffix.lower() == ".pdf")
259
+ img_count = len(files) - pdf_count
260
+ logger.info(f"Found {img_count} image(s) and {pdf_count} PDF(s)")
261
+
262
+ logger.info("Preparing images (rendering PDFs)...")
263
+ items = prepare_images(files, input_dir, output_dir, args.pdf_dpi)
264
+ if not items:
265
+ logger.error("No processable images after preparation")
266
+ sys.exit(1)
267
+
268
+ logger.info(f"Total images to OCR: {len(items)}")
269
+
270
+ # Init vLLM
271
+ logger.info(f"Initializing vLLM with {MODEL}...")
272
+ llm = LLM(
273
+ model=MODEL,
274
+ trust_remote_code=True,
275
+ max_model_len=args.max_model_len,
276
+ gpu_memory_utilization=args.gpu_memory_utilization,
277
+ limit_mm_per_prompt={"image": 1},
278
+ )
279
+
280
+ sampling_params = SamplingParams(
281
+ temperature=args.temperature,
282
+ top_p=args.top_p,
283
+ max_tokens=args.max_tokens,
284
+ repetition_penalty=args.repetition_penalty,
285
+ )
286
+
287
+ # Process in batches
288
+ errors = 0
289
+ processed = 0
290
+ total = len(items)
291
+
292
+ for batch_start in range(0, total, args.batch_size):
293
+ batch_end = min(batch_start + args.batch_size, total)
294
+ batch = items[batch_start:batch_end]
295
+ batch_num = batch_start // args.batch_size + 1
296
+ total_batches = (total + args.batch_size - 1) // args.batch_size
297
+
298
+ logger.info(f"Batch {batch_num}/{total_batches} ({processed}/{total} done)")
299
+
300
+ try:
301
+ messages = [make_ocr_message(img, task=args.task) for img, _ in batch]
302
+ outputs = llm.chat(messages, sampling_params)
303
+
304
+ for (_, md_path), output in zip(batch, outputs):
305
+ text = output.outputs[0].text.strip()
306
+ md_path.parent.mkdir(parents=True, exist_ok=True)
307
+ md_path.write_text(text, encoding="utf-8")
308
+ processed += 1
309
+
310
+ except Exception as e:
311
+ logger.error(f"Batch {batch_num} failed: {e}")
312
+ # Write error markers for failed batch
313
+ for _, md_path in batch:
314
+ md_path.parent.mkdir(parents=True, exist_ok=True)
315
+ md_path.write_text(f"[OCR ERROR: {e}]", encoding="utf-8")
316
+ errors += len(batch)
317
+ processed += len(batch)
318
+
319
+ elapsed = time.time() - start_time
320
+ elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
321
+
322
+ logger.info("=" * 50)
323
+ logger.info(f"Done! Processed {total} images in {elapsed_str}")
324
+ logger.info(f" Output: {output_dir}")
325
+ logger.info(f" Errors: {errors}")
326
+ if total > 0:
327
+ logger.info(f" Speed: {total / elapsed:.2f} images/sec")
328
+
329
+ if args.verbose:
330
+ import importlib.metadata
331
+
332
+ logger.info("--- Package versions ---")
333
+ for pkg in ["vllm", "transformers", "torch", "pillow", "pymupdf"]:
334
+ try:
335
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
336
+ except importlib.metadata.PackageNotFoundError:
337
+ logger.info(f" {pkg}: not installed")
338
+
339
+
340
+ if __name__ == "__main__":
341
+ if len(sys.argv) == 1:
342
+ print("=" * 60)
343
+ print("GLM-OCR Bucket Script")
344
+ print("=" * 60)
345
+ print("\nOCR images/PDFs from a directory → markdown files.")
346
+ print("Designed for HF Buckets mounted as volumes (PR #3936).")
347
+ print()
348
+ print("Usage:")
349
+ print(" uv run glm-ocr-bucket.py INPUT_DIR OUTPUT_DIR")
350
+ print()
351
+ print("Examples:")
352
+ print(" uv run glm-ocr-bucket.py ./images ./output")
353
+ print(" uv run glm-ocr-bucket.py /input /output --task table")
354
+ print()
355
+ print("HF Jobs with bucket volumes:")
356
+ print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
357
+ print(" -v bucket/user/ocr-input:/input:ro \\")
358
+ print(" -v bucket/user/ocr-output:/output \\")
359
+ print(" glm-ocr-bucket.py /input /output")
360
+ print()
361
+ print("For full help: uv run glm-ocr-bucket.py --help")
362
+ sys.exit(0)
363
+
364
+ main()