davanstrien HF Staff Claude Opus 4.6 (1M context) commited on
Commit
d0a2ced
·
1 Parent(s): 173e9b8

Add Falcon OCR bucket script for directory/volume I/O

Browse files

Companion to falcon-ocr.py (dataset mode). Reads images/PDFs from a
directory, writes markdown files preserving structure. Designed for
HF Buckets mounted as volumes via -v flag.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. falcon-ocr-bucket.py +278 -0
falcon-ocr-bucket.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "pillow",
5
+ # "pymupdf",
6
+ # "torch>=2.5",
7
+ # "torchvision",
8
+ # "falcon-perception[ocr]",
9
+ # ]
10
+ # ///
11
+
12
+ """
13
+ OCR images and PDFs from a directory using Falcon OCR, writing markdown files.
14
+
15
+ Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
16
+ Reads images/PDFs from INPUT_DIR, runs Falcon OCR via the optimized falcon-perception
17
+ engine (CUDA graphs + paged inference), and writes one .md file per image (or per
18
+ PDF page) to OUTPUT_DIR, preserving directory structure.
19
+
20
+ Input: Output:
21
+ /input/page1.png -> /output/page1.md
22
+ /input/report.pdf -> /output/report/page_001.md
23
+ (3 pages) /output/report/page_002.md
24
+ /output/report/page_003.md
25
+ /input/sub/photo.jpg -> /output/sub/photo.md
26
+
27
+ Examples:
28
+
29
+ # Local test
30
+ uv run falcon-ocr-bucket.py ./test-images ./test-output
31
+
32
+ # HF Jobs with bucket volumes
33
+ hf jobs uv run --flavor l4x1 \\
34
+ -s HF_TOKEN \\
35
+ -v bucket/user/ocr-input:/input:ro \\
36
+ -v bucket/user/ocr-output:/output \\
37
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-bucket.py \\
38
+ /input /output
39
+
40
+ Model: tiiuae/Falcon-OCR (0.3B, 80.3% olmOCR, Apache 2.0)
41
+ Backend: falcon-perception (OCRInferenceEngine with CUDA graphs)
42
+ """
43
+
44
+ import argparse
45
+ import logging
46
+ import sys
47
+ import time
48
+ from pathlib import Path
49
+
50
+ import torch
51
+ from PIL import Image
52
+
53
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
54
+ logger = logging.getLogger(__name__)
55
+
56
+ MODEL_ID = "tiiuae/Falcon-OCR"
57
+ IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}
58
+
59
+
60
+ def check_cuda_availability():
61
+ if not torch.cuda.is_available():
62
+ logger.error("CUDA is not available. This script requires a GPU.")
63
+ sys.exit(1)
64
+ logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
65
+
66
+
67
+ def discover_files(input_dir: Path) -> list[Path]:
68
+ files = []
69
+ for path in sorted(input_dir.rglob("*")):
70
+ if not path.is_file():
71
+ continue
72
+ ext = path.suffix.lower()
73
+ if ext in IMAGE_EXTENSIONS or ext == ".pdf":
74
+ files.append(path)
75
+ return files
76
+
77
+
78
+ def prepare_images(
79
+ files: list[Path], input_dir: Path, output_dir: Path, pdf_dpi: int
80
+ ) -> list[tuple[Image.Image, Path]]:
81
+ import fitz # pymupdf
82
+
83
+ items: list[tuple[Image.Image, Path]] = []
84
+
85
+ for file_path in files:
86
+ rel = file_path.relative_to(input_dir)
87
+ ext = file_path.suffix.lower()
88
+
89
+ if ext == ".pdf":
90
+ pdf_output_dir = output_dir / rel.with_suffix("")
91
+ try:
92
+ doc = fitz.open(file_path)
93
+ num_pages = len(doc)
94
+ logger.info(f"PDF: {rel} ({num_pages} pages)")
95
+ for page_num in range(num_pages):
96
+ page = doc[page_num]
97
+ zoom = pdf_dpi / 72.0
98
+ mat = fitz.Matrix(zoom, zoom)
99
+ pix = page.get_pixmap(matrix=mat)
100
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
101
+ md_path = pdf_output_dir / f"page_{page_num + 1:03d}.md"
102
+ items.append((img, md_path))
103
+ doc.close()
104
+ except Exception as e:
105
+ logger.error(f"Failed to open PDF {rel}: {e}")
106
+ else:
107
+ try:
108
+ img = Image.open(file_path).convert("RGB")
109
+ md_path = output_dir / rel.with_suffix(".md")
110
+ items.append((img, md_path))
111
+ except Exception as e:
112
+ logger.error(f"Failed to open image {rel}: {e}")
113
+
114
+ return items
115
+
116
+
117
+ def main():
118
+ parser = argparse.ArgumentParser(
119
+ description="OCR images/PDFs from a directory using Falcon OCR, output markdown files.",
120
+ formatter_class=argparse.RawDescriptionHelpFormatter,
121
+ epilog=__doc__,
122
+ )
123
+ parser.add_argument("input_dir", help="Directory containing images and/or PDFs")
124
+ parser.add_argument("output_dir", help="Directory to write markdown output files")
125
+ parser.add_argument(
126
+ "--batch-size", type=int, default=8, help="Images per batch (default: 8)",
127
+ )
128
+ parser.add_argument(
129
+ "--pdf-dpi", type=int, default=300,
130
+ help="DPI for PDF page rendering (default: 300)",
131
+ )
132
+ parser.add_argument(
133
+ "--no-compile", action="store_true", help="Disable torch.compile",
134
+ )
135
+ parser.add_argument(
136
+ "--no-cudagraph", action="store_true", help="Disable CUDA graph capture",
137
+ )
138
+ parser.add_argument(
139
+ "--verbose", action="store_true", help="Print resolved package versions",
140
+ )
141
+
142
+ args = parser.parse_args()
143
+
144
+ check_cuda_availability()
145
+
146
+ input_dir = Path(args.input_dir)
147
+ output_dir = Path(args.output_dir)
148
+
149
+ if not input_dir.is_dir():
150
+ logger.error(f"Input directory does not exist: {input_dir}")
151
+ sys.exit(1)
152
+
153
+ output_dir.mkdir(parents=True, exist_ok=True)
154
+
155
+ start_time = time.time()
156
+
157
+ # Discover files
158
+ logger.info(f"Scanning {input_dir} for images and PDFs...")
159
+ files = discover_files(input_dir)
160
+ if not files:
161
+ logger.error(f"No image or PDF files found in {input_dir}")
162
+ sys.exit(1)
163
+
164
+ pdf_count = sum(1 for f in files if f.suffix.lower() == ".pdf")
165
+ img_count = len(files) - pdf_count
166
+ logger.info(f"Found {img_count} image(s) and {pdf_count} PDF(s)")
167
+
168
+ # Prepare images
169
+ logger.info("Preparing images (rendering PDFs)...")
170
+ items = prepare_images(files, input_dir, output_dir, args.pdf_dpi)
171
+ if not items:
172
+ logger.error("No processable images after preparation")
173
+ sys.exit(1)
174
+
175
+ logger.info(f"Total images to OCR: {len(items)}")
176
+
177
+ # Load model
178
+ logger.info(f"Loading {MODEL_ID} via falcon-perception engine...")
179
+ from falcon_perception import load_and_prepare_model
180
+ from falcon_perception.data import ImageProcessor
181
+ from falcon_perception.paged_ocr_inference import OCRInferenceEngine
182
+
183
+ do_compile = not args.no_compile
184
+ do_cudagraph = not args.no_cudagraph
185
+
186
+ model, tokenizer, model_args = load_and_prepare_model(
187
+ hf_model_id=MODEL_ID,
188
+ device="cuda",
189
+ dtype="bfloat16",
190
+ compile=do_compile,
191
+ )
192
+
193
+ image_processor = ImageProcessor(patch_size=16, merge_size=1)
194
+ engine = OCRInferenceEngine(
195
+ model, tokenizer, image_processor, capture_cudagraph=do_cudagraph
196
+ )
197
+ logger.info(f"Engine loaded. compile={do_compile}, cudagraph={do_cudagraph}")
198
+
199
+ # Process in batches
200
+ errors = 0
201
+ processed = 0
202
+ total = len(items)
203
+ batch_size = args.batch_size
204
+
205
+ for batch_start in range(0, total, batch_size):
206
+ batch_end = min(batch_start + batch_size, total)
207
+ batch = items[batch_start:batch_end]
208
+ batch_num = batch_start // batch_size + 1
209
+ total_batches = (total + batch_size - 1) // batch_size
210
+
211
+ logger.info(f"Batch {batch_num}/{total_batches} ({processed}/{total} done)")
212
+
213
+ try:
214
+ batch_images = [img for img, _ in batch]
215
+ texts = engine.generate_plain(images=batch_images, use_tqdm=False)
216
+
217
+ for (_, md_path), text in zip(batch, texts):
218
+ md_path.parent.mkdir(parents=True, exist_ok=True)
219
+ md_path.write_text(text.strip(), encoding="utf-8")
220
+ processed += 1
221
+
222
+ except Exception as e:
223
+ logger.error(f"Batch {batch_num} failed: {e}")
224
+ for _, md_path in batch:
225
+ md_path.parent.mkdir(parents=True, exist_ok=True)
226
+ md_path.write_text(f"[OCR ERROR: {e}]", encoding="utf-8")
227
+ errors += len(batch)
228
+ processed += len(batch)
229
+
230
+ elapsed = time.time() - start_time
231
+ elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
232
+
233
+ logger.info("=" * 50)
234
+ logger.info(f"Done! Processed {total} images in {elapsed_str}")
235
+ logger.info(f" Output: {output_dir}")
236
+ logger.info(f" Errors: {errors}")
237
+ if total > 0:
238
+ logger.info(f" Speed: {total / elapsed:.2f} images/sec")
239
+
240
+ if args.verbose:
241
+ import importlib.metadata
242
+
243
+ logger.info("--- Package versions ---")
244
+ for pkg in ["falcon-perception", "torch", "pillow", "pymupdf"]:
245
+ try:
246
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
247
+ except importlib.metadata.PackageNotFoundError:
248
+ logger.info(f" {pkg}: not installed")
249
+
250
+
251
+ if __name__ == "__main__":
252
+ if len(sys.argv) == 1:
253
+ print("=" * 60)
254
+ print("Falcon OCR Bucket Script")
255
+ print("=" * 60)
256
+ print(f"\nModel: {MODEL_ID} (0.3B, Apache 2.0)")
257
+ print("OCR images/PDFs from a directory -> markdown files.")
258
+ print("Designed for HF Buckets mounted as volumes.")
259
+ print()
260
+ print("Usage:")
261
+ print(" uv run falcon-ocr-bucket.py INPUT_DIR OUTPUT_DIR")
262
+ print()
263
+ print("Examples:")
264
+ print(" uv run falcon-ocr-bucket.py ./images ./output")
265
+ print()
266
+ print("HF Jobs with bucket volumes:")
267
+ print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
268
+ print(" -v bucket/user/ocr-input:/input:ro \\")
269
+ print(" -v bucket/user/ocr-output:/output \\")
270
+ print(
271
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-bucket.py \\"
272
+ )
273
+ print(" /input /output")
274
+ print()
275
+ print("For full help: uv run falcon-ocr-bucket.py --help")
276
+ sys.exit(0)
277
+
278
+ main()