davanstrien HF Staff commited on
Commit
2a79f45
·
verified ·
1 Parent(s): 3ca1590

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +1 -0
  2. abot-ocr.py +556 -0
README.md CHANGED
@@ -43,6 +43,7 @@ That's it! The script will:
43
  | `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
44
  | `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
45
  | `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
 
46
  | `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
47
  | `dots-mocr.py` | [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) | 3B | vLLM | 8 prompt modes incl. SVG generation, layout + bbox, 100+ languages |
48
  | `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
 
43
  | `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
44
  | `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
45
  | `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
46
+ | `abot-ocr.py` | [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) | 2B | vLLM | Qwen3-VL based, doc→Markdown (text/LaTeX/HTML tables). Needs `vllm/vllm-openai` image. [paper](https://arxiv.org/abs/2605.27978) |
47
  | `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
48
  | `dots-mocr.py` | [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) | 3B | vLLM | 8 prompt modes incl. SVG generation, layout + bbox, 100+ languages |
49
  | `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
abot-ocr.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm>=0.15.1",
8
+ # "tqdm",
9
+ # "toolz",
10
+ # "torch",
11
+ # ]
12
+ #
13
+ # ///
14
+
15
+ """
16
+ Convert document images to Markdown using ABot-OCR with vLLM.
17
+
18
+ ABot-OCR (acvlab/ABot-OCR) is a compact Qwen3-VL-based document OCR model that
19
+ converts PDF/document page images into structured Markdown, including:
20
+ - Text with original document structure (headings, paragraphs, lists)
21
+ - Mathematical formulas in LaTeX (inline \\( \\) and block \\[ \\])
22
+ - Tables in HTML (<table>…</table>)
23
+
24
+ Model: https://huggingface.co/acvlab/ABot-OCR
25
+ Paper: https://arxiv.org/abs/2605.27978
26
+ Code: https://github.com/amap-cvlab/ABot-OCR
27
+
28
+ HF Jobs note: ABot-OCR (Qwen3-VL) uses vLLM's flashinfer sampler, which needs CUDA
29
+ kernels the default uv-script image can't build ("Could not find nvcc"). Run on Jobs
30
+ with the pre-built vLLM image so the kernels are reused (same image-mode pattern as
31
+ nuextract3.py / paddleocr-vl-1.6.py):
32
+ --image vllm/vllm-openai:latest
33
+ --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages
34
+ """
35
+
36
+ import argparse
37
+ import base64
38
+ import io
39
+ import json
40
+ import logging
41
+ import os
42
+ import sys
43
+ from typing import Any, Dict, List, Union
44
+ from datetime import datetime
45
+
46
+ import torch
47
+ from datasets import load_dataset
48
+ from huggingface_hub import DatasetCard, login
49
+ from PIL import Image
50
+ from toolz import partition_all
51
+ from tqdm.auto import tqdm
52
+ from vllm import LLM, SamplingParams
53
+
54
+ logging.basicConfig(level=logging.INFO)
55
+ logger = logging.getLogger(__name__)
56
+
57
+ # ABot-OCR's recommended document→Markdown prompt (from the model's reference
58
+ # inference script; LaTeX delimiters de-mangled to proper \( \) and \[ \]).
59
+ DEFAULT_PROMPT = r"""You are an AI assistant specialized in converting PDF images to Markdown format. Please follow these instructions for the conversion:
60
+
61
+ 1. Text Processing:
62
+ - Accurately recognize all text content in the PDF image without guessing or inferring.
63
+ - Convert the recognized text into Markdown format.
64
+ - Maintain the original document structure, including headings, paragraphs, lists, etc.
65
+
66
+ 2. Mathematical Formula Processing:
67
+ - Convert all mathematical formulas to LaTeX format.
68
+ - Enclose inline formulas with \( \). For example: This is an inline formula \( E = mc^2 \)
69
+ - Enclose block formulas with \[ \]. For example: \[ \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]
70
+
71
+ 3. Table Processing:
72
+ - Convert tables to HTML format.
73
+ - Wrap the entire table with <table> and </table>.
74
+
75
+ 4. Figure Handling:
76
+ - Ignore figures content in the PDF image. Do not attempt to describe or convert images.
77
+
78
+ 5. Output Format:
79
+ - Ensure the output Markdown document has a clear structure with appropriate line breaks between elements.
80
+ - For complex layouts, try to maintain the original document's structure and format as closely as possible.
81
+
82
+ Please strictly follow these guidelines to ensure accuracy and consistency in the conversion. Your task is to accurately convert the content of the PDF image into Markdown format without adding any extra explanations or comments."""
83
+
84
+
85
+ def check_cuda_availability():
86
+ """Check if CUDA is available and exit if not."""
87
+ if not torch.cuda.is_available():
88
+ logger.error("CUDA is not available. This script requires a GPU.")
89
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
90
+ sys.exit(1)
91
+ else:
92
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
93
+
94
+
95
+ def post_process_text(text: str, threshold: int = 8000) -> str:
96
+ """Trim runaway repetition loops that VLM OCR can fall into on dense pages.
97
+
98
+ Mirrors ABot-OCR's reference post-processing: if the tail of a long output
99
+ repeats the same short substring many times, collapse it to a single copy.
100
+ """
101
+ n = len(text)
102
+ if n < threshold:
103
+ return text
104
+ for length in range(2, n // 10 + 1):
105
+ candidate = text[-length:]
106
+ count = 0
107
+ i = n - length
108
+ while i >= 0 and text[i:i + length] == candidate:
109
+ count += 1
110
+ i -= length
111
+ if count >= 10:
112
+ return text[: n - length * (count - 1)]
113
+ return text
114
+
115
+
116
+ def make_ocr_message(
117
+ image: Union[Image.Image, Dict[str, Any], str],
118
+ prompt: str = DEFAULT_PROMPT,
119
+ ) -> List[Dict]:
120
+ """Create a vLLM chat message for OCR processing."""
121
+ # Convert to PIL Image if needed
122
+ if isinstance(image, Image.Image):
123
+ pil_img = image
124
+ elif isinstance(image, dict) and "bytes" in image:
125
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
126
+ elif isinstance(image, str):
127
+ pil_img = Image.open(image)
128
+ else:
129
+ raise ValueError(f"Unsupported image type: {type(image)}")
130
+
131
+ if pil_img.mode != "RGB":
132
+ pil_img = pil_img.convert("RGB")
133
+
134
+ # Convert to base64 data URI
135
+ buf = io.BytesIO()
136
+ pil_img.save(buf, format="PNG")
137
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
138
+
139
+ return [
140
+ {
141
+ "role": "user",
142
+ "content": [
143
+ {"type": "image_url", "image_url": {"url": data_uri}},
144
+ {"type": "text", "text": prompt},
145
+ ],
146
+ }
147
+ ]
148
+
149
+
150
+ def create_dataset_card(
151
+ source_dataset: str,
152
+ model: str,
153
+ num_samples: int,
154
+ processing_time: str,
155
+ batch_size: int,
156
+ max_model_len: int,
157
+ max_tokens: int,
158
+ gpu_memory_utilization: float,
159
+ image_column: str = "image",
160
+ split: str = "train",
161
+ ) -> str:
162
+ """Create a dataset card documenting the OCR process."""
163
+ model_name = model.split("/")[-1]
164
+
165
+ return f"""---
166
+ tags:
167
+ - ocr
168
+ - document-processing
169
+ - abot
170
+ - abot-ocr
171
+ - markdown
172
+ - uv-script
173
+ - generated
174
+ ---
175
+
176
+ # Document OCR using {model_name}
177
+
178
+ This dataset contains Markdown-formatted OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [ABot-OCR](https://huggingface.co/{model}).
179
+
180
+ ## Processing Details
181
+
182
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
183
+ - **Model**: [{model}](https://huggingface.co/{model})
184
+ - **Paper**: [arxiv.org/abs/2605.27978](https://arxiv.org/abs/2605.27978)
185
+ - **Number of Samples**: {num_samples:,}
186
+ - **Processing Time**: {processing_time}
187
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
188
+
189
+ ### Configuration
190
+
191
+ - **Image Column**: `{image_column}`
192
+ - **Output Column**: `markdown`
193
+ - **Dataset Split**: `{split}`
194
+ - **Batch Size**: {batch_size}
195
+ - **Max Model Length**: {max_model_len:,} tokens
196
+ - **Max Output Tokens**: {max_tokens:,}
197
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
198
+
199
+ ## Model Information
200
+
201
+ ABot-OCR is a compact Qwen3-VL-based document OCR model that converts page images to Markdown:
202
+ - 📐 **LaTeX equations** — inline `\\( \\)` and block `\\[ \\]`
203
+ - 📊 **Tables** — extracted as HTML (`<table>…</table>`)
204
+ - 📝 **Document structure** — headings, paragraphs, and lists preserved
205
+
206
+ ## Dataset Structure
207
+
208
+ The dataset contains all original columns plus:
209
+ - `markdown`: The extracted text in Markdown format with preserved structure
210
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
211
+
212
+ ## Usage
213
+
214
+ ```python
215
+ from datasets import load_dataset
216
+
217
+ dataset = load_dataset("{{{{output_dataset_id}}}}", split="{split}")
218
+ for example in dataset:
219
+ print(example["markdown"])
220
+ break
221
+ ```
222
+
223
+ ## Reproduction
224
+
225
+ This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) ABot-OCR script:
226
+
227
+ ```bash
228
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py \\
229
+ {source_dataset} \\
230
+ <output-dataset> \\
231
+ --image-column {image_column} \\
232
+ --batch-size {batch_size} \\
233
+ --max-model-len {max_model_len} \\
234
+ --max-tokens {max_tokens} \\
235
+ --gpu-memory-utilization {gpu_memory_utilization}
236
+ ```
237
+
238
+ Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
239
+ """
240
+
241
+
242
+ def main(
243
+ input_dataset: str,
244
+ output_dataset: str,
245
+ image_column: str = "image",
246
+ batch_size: int = 16,
247
+ model: str = "acvlab/ABot-OCR",
248
+ max_model_len: int = 16384,
249
+ max_tokens: int = 8192,
250
+ gpu_memory_utilization: float = 0.8,
251
+ hf_token: str = None,
252
+ split: str = "train",
253
+ max_samples: int = None,
254
+ private: bool = False,
255
+ shuffle: bool = False,
256
+ seed: int = 42,
257
+ verbose: bool = False,
258
+ ):
259
+ """Process images from a HF dataset through the ABot-OCR model."""
260
+
261
+ # Check CUDA availability first
262
+ check_cuda_availability()
263
+
264
+ # Track processing start time
265
+ start_time = datetime.now()
266
+
267
+ # Enable high-performance Xet downloads
268
+ os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
269
+
270
+ # Login to HF if token provided
271
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
272
+ if HF_TOKEN:
273
+ login(token=HF_TOKEN)
274
+
275
+ # Load dataset
276
+ logger.info(f"Loading dataset: {input_dataset}")
277
+ dataset = load_dataset(input_dataset, split=split)
278
+
279
+ # Validate image column
280
+ if image_column not in dataset.column_names:
281
+ raise ValueError(
282
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
283
+ )
284
+
285
+ # Shuffle if requested
286
+ if shuffle:
287
+ logger.info(f"Shuffling dataset with seed {seed}")
288
+ dataset = dataset.shuffle(seed=seed)
289
+
290
+ # Limit samples if requested
291
+ if max_samples:
292
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
293
+ logger.info(f"Limited to {len(dataset)} samples")
294
+
295
+ # Initialize vLLM
296
+ logger.info(f"Initializing vLLM with model: {model}")
297
+ llm = LLM(
298
+ model=model,
299
+ trust_remote_code=True,
300
+ max_model_len=max_model_len,
301
+ gpu_memory_utilization=gpu_memory_utilization,
302
+ limit_mm_per_prompt={"image": 1},
303
+ enforce_eager=True, # avoid warmup kernel compilation (no nvcc in the image)
304
+ )
305
+
306
+ sampling_params = SamplingParams(
307
+ temperature=0.0, # Deterministic for OCR
308
+ max_tokens=max_tokens,
309
+ )
310
+
311
+ # Process images in batches
312
+ all_markdown = []
313
+
314
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
315
+
316
+ for batch_indices in tqdm(
317
+ partition_all(batch_size, range(len(dataset))),
318
+ total=(len(dataset) + batch_size - 1) // batch_size,
319
+ desc="OCR processing",
320
+ ):
321
+ batch_indices = list(batch_indices)
322
+ batch_images = [dataset[i][image_column] for i in batch_indices]
323
+
324
+ try:
325
+ batch_messages = [make_ocr_message(img) for img in batch_images]
326
+ outputs = llm.chat(batch_messages, sampling_params)
327
+ for output in outputs:
328
+ markdown_text = post_process_text(output.outputs[0].text.strip())
329
+ all_markdown.append(markdown_text)
330
+ except Exception as e:
331
+ logger.error(f"Error processing batch: {e}")
332
+ all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
333
+
334
+ # Add markdown column to dataset
335
+ logger.info("Adding markdown column to dataset")
336
+ dataset = dataset.add_column("markdown", all_markdown)
337
+
338
+ # Handle inference_info tracking
339
+ logger.info("Updating inference_info...")
340
+
341
+ inference_entry = {
342
+ "model_id": model,
343
+ "model_name": "ABot-OCR",
344
+ "column_name": "markdown",
345
+ "timestamp": datetime.now().isoformat(),
346
+ "batch_size": batch_size,
347
+ "max_tokens": max_tokens,
348
+ "gpu_memory_utilization": gpu_memory_utilization,
349
+ "max_model_len": max_model_len,
350
+ "script": "abot-ocr.py",
351
+ "script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py",
352
+ }
353
+
354
+ if "inference_info" in dataset.column_names:
355
+ logger.info("Updating existing inference_info column")
356
+
357
+ def update_inference_info(example):
358
+ try:
359
+ existing_info = (
360
+ json.loads(example["inference_info"])
361
+ if example["inference_info"]
362
+ else []
363
+ )
364
+ except (json.JSONDecodeError, TypeError):
365
+ existing_info = []
366
+ existing_info.append(inference_entry)
367
+ return {"inference_info": json.dumps(existing_info)}
368
+
369
+ dataset = dataset.map(update_inference_info)
370
+ else:
371
+ logger.info("Creating new inference_info column")
372
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
373
+ dataset = dataset.add_column("inference_info", inference_list)
374
+
375
+ # Push to hub
376
+ logger.info(f"Pushing to {output_dataset}")
377
+ dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
378
+
379
+ # Calculate processing time
380
+ end_time = datetime.now()
381
+ processing_duration = end_time - start_time
382
+ processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
383
+
384
+ # Create and push dataset card
385
+ logger.info("Creating dataset card...")
386
+ card_content = create_dataset_card(
387
+ source_dataset=input_dataset,
388
+ model=model,
389
+ num_samples=len(dataset),
390
+ processing_time=processing_time,
391
+ batch_size=batch_size,
392
+ max_model_len=max_model_len,
393
+ max_tokens=max_tokens,
394
+ gpu_memory_utilization=gpu_memory_utilization,
395
+ image_column=image_column,
396
+ split=split,
397
+ )
398
+
399
+ card = DatasetCard(card_content)
400
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
401
+ logger.info("✅ Dataset card created and pushed!")
402
+
403
+ logger.info("✅ OCR conversion complete!")
404
+ logger.info(
405
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
406
+ )
407
+
408
+ if verbose:
409
+ import importlib.metadata
410
+
411
+ logger.info("--- Resolved package versions ---")
412
+ for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
413
+ try:
414
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
415
+ except importlib.metadata.PackageNotFoundError:
416
+ logger.info(f" {pkg}: not installed")
417
+ logger.info("--- End versions ---")
418
+
419
+
420
+ if __name__ == "__main__":
421
+ # Show example usage if no arguments
422
+ if len(sys.argv) == 1:
423
+ print("=" * 80)
424
+ print("ABot-OCR to Markdown Converter")
425
+ print("=" * 80)
426
+ print("\nConverts document images to structured Markdown using the")
427
+ print("ABot-OCR model (Qwen3-VL based) with vLLM acceleration.")
428
+ print("\nFeatures:")
429
+ print("- Document structure preserved (headings, paragraphs, lists)")
430
+ print("- LaTeX equation recognition (inline \\( \\) and block \\[ \\])")
431
+ print("- Table extraction as HTML")
432
+ print("\nExample usage:")
433
+ print("\n1. Basic OCR conversion:")
434
+ print(" uv run abot-ocr.py document-images markdown-docs")
435
+ print("\n2. Process a subset for testing:")
436
+ print(" uv run abot-ocr.py large-dataset test-output --max-samples 10")
437
+ print("\n3. Running on HF Jobs (use the pre-built vLLM image for flashinfer kernels):")
438
+ print(" hf jobs uv run --flavor l4x1 \\")
439
+ print(" --image vllm/vllm-openai:latest \\")
440
+ print(
441
+ " --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\"
442
+ )
443
+ print(" -s HF_TOKEN \\")
444
+ print(
445
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py \\"
446
+ )
447
+ print(" your-document-dataset \\")
448
+ print(" your-markdown-output \\")
449
+ print(" --max-samples 10")
450
+ print("\n" + "=" * 80)
451
+ print("\nFor full help, run: uv run abot-ocr.py --help")
452
+ sys.exit(0)
453
+
454
+ parser = argparse.ArgumentParser(
455
+ description="OCR images to Markdown using ABot-OCR (Qwen3-VL)",
456
+ formatter_class=argparse.RawDescriptionHelpFormatter,
457
+ epilog="""
458
+ Examples:
459
+ # Basic usage
460
+ uv run abot-ocr.py my-images-dataset ocr-results
461
+
462
+ # With specific image column
463
+ uv run abot-ocr.py documents extracted-text --image-column scan
464
+
465
+ # Process subset for testing
466
+ uv run abot-ocr.py large-dataset test-output --max-samples 100
467
+
468
+ # Random sample from ordered dataset
469
+ uv run abot-ocr.py ordered-dataset random-sample --max-samples 50 --shuffle
470
+ """,
471
+ )
472
+
473
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
474
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
475
+ parser.add_argument(
476
+ "--image-column",
477
+ default="image",
478
+ help="Column containing images (default: image)",
479
+ )
480
+ parser.add_argument(
481
+ "--batch-size",
482
+ type=int,
483
+ default=16,
484
+ help="Batch size for processing (default: 16)",
485
+ )
486
+ parser.add_argument(
487
+ "--model",
488
+ default="acvlab/ABot-OCR",
489
+ help="Model to use (default: acvlab/ABot-OCR)",
490
+ )
491
+ parser.add_argument(
492
+ "--max-model-len",
493
+ type=int,
494
+ default=16384,
495
+ help="Maximum model context length (default: 16384)",
496
+ )
497
+ parser.add_argument(
498
+ "--max-tokens",
499
+ type=int,
500
+ default=8192,
501
+ help="Maximum tokens to generate (default: 8192)",
502
+ )
503
+ parser.add_argument(
504
+ "--gpu-memory-utilization",
505
+ type=float,
506
+ default=0.8,
507
+ help="GPU memory utilization (default: 0.8)",
508
+ )
509
+ parser.add_argument("--hf-token", help="Hugging Face API token")
510
+ parser.add_argument(
511
+ "--split", default="train", help="Dataset split to use (default: train)"
512
+ )
513
+ parser.add_argument(
514
+ "--max-samples",
515
+ type=int,
516
+ help="Maximum number of samples to process (for testing)",
517
+ )
518
+ parser.add_argument(
519
+ "--private", action="store_true", help="Make output dataset private"
520
+ )
521
+ parser.add_argument(
522
+ "--shuffle",
523
+ action="store_true",
524
+ help="Shuffle the dataset before processing (useful for random sampling)",
525
+ )
526
+ parser.add_argument(
527
+ "--seed",
528
+ type=int,
529
+ default=42,
530
+ help="Random seed for shuffling (default: 42)",
531
+ )
532
+ parser.add_argument(
533
+ "--verbose",
534
+ action="store_true",
535
+ help="Log resolved package versions after processing (useful for pinning deps)",
536
+ )
537
+
538
+ args = parser.parse_args()
539
+
540
+ main(
541
+ input_dataset=args.input_dataset,
542
+ output_dataset=args.output_dataset,
543
+ image_column=args.image_column,
544
+ batch_size=args.batch_size,
545
+ model=args.model,
546
+ max_model_len=args.max_model_len,
547
+ max_tokens=args.max_tokens,
548
+ gpu_memory_utilization=args.gpu_memory_utilization,
549
+ hf_token=args.hf_token,
550
+ split=args.split,
551
+ max_samples=args.max_samples,
552
+ private=args.private,
553
+ shuffle=args.shuffle,
554
+ seed=args.seed,
555
+ verbose=args.verbose,
556
+ )