Commit
·
3073a00
1
Parent(s):
88db448
Add prompt mode presets and remove test script
Browse filesChanges:
- Added PROMPT_MODES dict with 5 presets: document, image, free, figure, describe
- Added --prompt-mode argument (default: document)
- Custom --prompt still supported (overrides prompt-mode)
- Updated help text and examples to show prompt modes
- Removed deepseek-ocr-vllm-test.py (no longer needed after successful testing)
Prompt modes from DeepSeek-OCR GitHub:
- document: Convert document to markdown with grounding (default)
- image: OCR any image with grounding
- free: Free OCR without layout preservation
- figure: Parse figures from documents
- describe: Generate detailed image descriptions
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- DeepSeek-OCR +1 -0
- __pycache__/dots-ocr.cpython-313.pyc +0 -0
- __pycache__/numarkdown-ocr.cpython-313.pyc +0 -0
- bigger-font.gif +3 -0
- deepseek-ocr-vllm.py +60 -8
- demo.cast +0 -0
- first.gif +3 -0
- numarkdown-ocr.py +60 -17
- smoldocling-ocr.py +580 -0
DeepSeek-OCR
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Subproject commit 8cf003d38821fa1b19c73da3bd1b0dc262ea8136
|
__pycache__/dots-ocr.cpython-313.pyc
DELETED
|
Binary file (22.6 kB)
|
|
|
__pycache__/numarkdown-ocr.cpython-313.pyc
ADDED
|
Binary file (26.8 kB). View file
|
|
|
bigger-font.gif
ADDED
|
Git LFS Details
|
deepseek-ocr-vllm.py
CHANGED
|
@@ -70,6 +70,15 @@ RESOLUTION_MODES = {
|
|
| 70 |
}, # Dynamic resolution
|
| 71 |
}
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
def check_cuda_availability():
|
| 75 |
"""Check if CUDA is available and exit if not."""
|
|
@@ -250,7 +259,8 @@ def main(
|
|
| 250 |
max_model_len: int = 8192,
|
| 251 |
max_tokens: int = 8192,
|
| 252 |
gpu_memory_utilization: float = 0.8,
|
| 253 |
-
|
|
|
|
| 254 |
hf_token: str = None,
|
| 255 |
split: str = "train",
|
| 256 |
max_samples: int = None,
|
|
@@ -305,6 +315,21 @@ def main(
|
|
| 305 |
f"image_size={final_image_size}, crop_mode={final_crop_mode}"
|
| 306 |
)
|
| 307 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
# Load dataset
|
| 309 |
logger.info(f"Loading dataset: {input_dataset}")
|
| 310 |
dataset = load_dataset(input_dataset, split=split)
|
|
@@ -362,7 +387,7 @@ def main(
|
|
| 362 |
|
| 363 |
try:
|
| 364 |
# Create messages for batch
|
| 365 |
-
batch_messages = [make_ocr_message(img,
|
| 366 |
|
| 367 |
# Process with vLLM
|
| 368 |
outputs = llm.chat(batch_messages, sampling_params)
|
|
@@ -411,7 +436,8 @@ def main(
|
|
| 411 |
"base_size": final_base_size,
|
| 412 |
"image_size": final_image_size,
|
| 413 |
"crop_mode": final_crop_mode,
|
| 414 |
-
"prompt":
|
|
|
|
| 415 |
"batch_size": batch_size,
|
| 416 |
"max_tokens": max_tokens,
|
| 417 |
"gpu_memory_utilization": gpu_memory_utilization,
|
|
@@ -486,14 +512,18 @@ if __name__ == "__main__":
|
|
| 486 |
)
|
| 487 |
print("\n3. Fast processing (Tiny - 512×512):")
|
| 488 |
print(" uv run deepseek-ocr-vllm.py quick-test output --resolution-mode tiny")
|
| 489 |
-
print("\n4.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
print(
|
| 491 |
" uv run deepseek-ocr-vllm.py large-dataset test-output --max-samples 10"
|
| 492 |
)
|
| 493 |
-
print("\
|
| 494 |
print(" uv run deepseek-ocr-vllm.py dataset output \\")
|
| 495 |
print(" --base-size 1024 --image-size 640 --crop-mode")
|
| 496 |
-
print("\
|
| 497 |
print(" hf jobs uv run --flavor l4x1 \\")
|
| 498 |
print(" -s HF_TOKEN \\")
|
| 499 |
print(" -e UV_TORCH_BACKEND=auto \\")
|
|
@@ -517,6 +547,13 @@ Resolution Modes:
|
|
| 517 |
large 1280×1280 pixels, maximum quality (400 vision tokens)
|
| 518 |
gundam Dynamic multi-tile processing (adaptive)
|
| 519 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
Examples:
|
| 521 |
# Basic usage with default Gundam mode
|
| 522 |
uv run deepseek-ocr-vllm.py my-images-dataset ocr-results
|
|
@@ -527,6 +564,15 @@ Examples:
|
|
| 527 |
# Fast processing for testing
|
| 528 |
uv run deepseek-ocr-vllm.py dataset output --resolution-mode tiny --max-samples 100
|
| 529 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
# Custom resolution settings
|
| 531 |
uv run deepseek-ocr-vllm.py dataset output --base-size 1024 --image-size 640 --crop-mode
|
| 532 |
|
|
@@ -592,10 +638,15 @@ Examples:
|
|
| 592 |
default=0.8,
|
| 593 |
help="GPU memory utilization (default: 0.8)",
|
| 594 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
parser.add_argument(
|
| 596 |
"--prompt",
|
| 597 |
-
|
| 598 |
-
help="Prompt for OCR (default: grounding markdown conversion)",
|
| 599 |
)
|
| 600 |
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 601 |
parser.add_argument(
|
|
@@ -636,6 +687,7 @@ Examples:
|
|
| 636 |
max_model_len=args.max_model_len,
|
| 637 |
max_tokens=args.max_tokens,
|
| 638 |
gpu_memory_utilization=args.gpu_memory_utilization,
|
|
|
|
| 639 |
prompt=args.prompt,
|
| 640 |
hf_token=args.hf_token,
|
| 641 |
split=args.split,
|
|
|
|
| 70 |
}, # Dynamic resolution
|
| 71 |
}
|
| 72 |
|
| 73 |
+
# Prompt mode presets (from DeepSeek-OCR GitHub)
|
| 74 |
+
PROMPT_MODES = {
|
| 75 |
+
"document": "<image>\n<|grounding|>Convert the document to markdown.",
|
| 76 |
+
"image": "<image>\n<|grounding|>OCR this image.",
|
| 77 |
+
"free": "<image>\nFree OCR.",
|
| 78 |
+
"figure": "<image>\nParse the figure.",
|
| 79 |
+
"describe": "<image>\nDescribe this image in detail.",
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
|
| 83 |
def check_cuda_availability():
|
| 84 |
"""Check if CUDA is available and exit if not."""
|
|
|
|
| 259 |
max_model_len: int = 8192,
|
| 260 |
max_tokens: int = 8192,
|
| 261 |
gpu_memory_utilization: float = 0.8,
|
| 262 |
+
prompt_mode: str = "document",
|
| 263 |
+
prompt: str = None,
|
| 264 |
hf_token: str = None,
|
| 265 |
split: str = "train",
|
| 266 |
max_samples: int = None,
|
|
|
|
| 315 |
f"image_size={final_image_size}, crop_mode={final_crop_mode}"
|
| 316 |
)
|
| 317 |
|
| 318 |
+
# Determine prompt
|
| 319 |
+
if prompt is not None:
|
| 320 |
+
final_prompt = prompt
|
| 321 |
+
logger.info(f"Using custom prompt")
|
| 322 |
+
elif prompt_mode in PROMPT_MODES:
|
| 323 |
+
final_prompt = PROMPT_MODES[prompt_mode]
|
| 324 |
+
logger.info(f"Using prompt mode: {prompt_mode}")
|
| 325 |
+
else:
|
| 326 |
+
raise ValueError(
|
| 327 |
+
f"Invalid prompt mode '{prompt_mode}'. "
|
| 328 |
+
f"Use one of {list(PROMPT_MODES.keys())} or specify --prompt"
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
logger.info(f"Prompt: {final_prompt}")
|
| 332 |
+
|
| 333 |
# Load dataset
|
| 334 |
logger.info(f"Loading dataset: {input_dataset}")
|
| 335 |
dataset = load_dataset(input_dataset, split=split)
|
|
|
|
| 387 |
|
| 388 |
try:
|
| 389 |
# Create messages for batch
|
| 390 |
+
batch_messages = [make_ocr_message(img, final_prompt) for img in batch_images]
|
| 391 |
|
| 392 |
# Process with vLLM
|
| 393 |
outputs = llm.chat(batch_messages, sampling_params)
|
|
|
|
| 436 |
"base_size": final_base_size,
|
| 437 |
"image_size": final_image_size,
|
| 438 |
"crop_mode": final_crop_mode,
|
| 439 |
+
"prompt": final_prompt,
|
| 440 |
+
"prompt_mode": prompt_mode if prompt is None else "custom",
|
| 441 |
"batch_size": batch_size,
|
| 442 |
"max_tokens": max_tokens,
|
| 443 |
"gpu_memory_utilization": gpu_memory_utilization,
|
|
|
|
| 512 |
)
|
| 513 |
print("\n3. Fast processing (Tiny - 512×512):")
|
| 514 |
print(" uv run deepseek-ocr-vllm.py quick-test output --resolution-mode tiny")
|
| 515 |
+
print("\n4. Parse figures from documents:")
|
| 516 |
+
print(" uv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure")
|
| 517 |
+
print("\n5. Free OCR without layout:")
|
| 518 |
+
print(" uv run deepseek-ocr-vllm.py images text --prompt-mode free")
|
| 519 |
+
print("\n6. Process a subset for testing:")
|
| 520 |
print(
|
| 521 |
" uv run deepseek-ocr-vllm.py large-dataset test-output --max-samples 10"
|
| 522 |
)
|
| 523 |
+
print("\n7. Custom resolution:")
|
| 524 |
print(" uv run deepseek-ocr-vllm.py dataset output \\")
|
| 525 |
print(" --base-size 1024 --image-size 640 --crop-mode")
|
| 526 |
+
print("\n8. Running on HF Jobs:")
|
| 527 |
print(" hf jobs uv run --flavor l4x1 \\")
|
| 528 |
print(" -s HF_TOKEN \\")
|
| 529 |
print(" -e UV_TORCH_BACKEND=auto \\")
|
|
|
|
| 547 |
large 1280×1280 pixels, maximum quality (400 vision tokens)
|
| 548 |
gundam Dynamic multi-tile processing (adaptive)
|
| 549 |
|
| 550 |
+
Prompt Modes:
|
| 551 |
+
document Convert document to markdown with grounding (default)
|
| 552 |
+
image OCR any image with grounding
|
| 553 |
+
free Free OCR without layout preservation
|
| 554 |
+
figure Parse figures from documents
|
| 555 |
+
describe Generate detailed image descriptions
|
| 556 |
+
|
| 557 |
Examples:
|
| 558 |
# Basic usage with default Gundam mode
|
| 559 |
uv run deepseek-ocr-vllm.py my-images-dataset ocr-results
|
|
|
|
| 564 |
# Fast processing for testing
|
| 565 |
uv run deepseek-ocr-vllm.py dataset output --resolution-mode tiny --max-samples 100
|
| 566 |
|
| 567 |
+
# Parse figures from a document dataset
|
| 568 |
+
uv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure
|
| 569 |
+
|
| 570 |
+
# Free OCR without layout (fastest)
|
| 571 |
+
uv run deepseek-ocr-vllm.py images text --prompt-mode free
|
| 572 |
+
|
| 573 |
+
# Custom prompt for specific task
|
| 574 |
+
uv run deepseek-ocr-vllm.py dataset output --prompt "<image>\nExtract all table data."
|
| 575 |
+
|
| 576 |
# Custom resolution settings
|
| 577 |
uv run deepseek-ocr-vllm.py dataset output --base-size 1024 --image-size 640 --crop-mode
|
| 578 |
|
|
|
|
| 638 |
default=0.8,
|
| 639 |
help="GPU memory utilization (default: 0.8)",
|
| 640 |
)
|
| 641 |
+
parser.add_argument(
|
| 642 |
+
"--prompt-mode",
|
| 643 |
+
default="document",
|
| 644 |
+
choices=list(PROMPT_MODES.keys()),
|
| 645 |
+
help="Prompt mode preset (default: document). Use --prompt for custom prompts.",
|
| 646 |
+
)
|
| 647 |
parser.add_argument(
|
| 648 |
"--prompt",
|
| 649 |
+
help="Custom OCR prompt (overrides --prompt-mode)",
|
|
|
|
| 650 |
)
|
| 651 |
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 652 |
parser.add_argument(
|
|
|
|
| 687 |
max_model_len=args.max_model_len,
|
| 688 |
max_tokens=args.max_tokens,
|
| 689 |
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 690 |
+
prompt_mode=args.prompt_mode,
|
| 691 |
prompt=args.prompt,
|
| 692 |
hf_token=args.hf_token,
|
| 693 |
split=args.split,
|
demo.cast
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
first.gif
ADDED
|
Git LFS Details
|
numarkdown-ocr.py
CHANGED
|
@@ -25,6 +25,8 @@ Features:
|
|
| 25 |
- Mathematical formula recognition
|
| 26 |
- Clean markdown output generation
|
| 27 |
- Optional thinking trace inclusion
|
|
|
|
|
|
|
| 28 |
"""
|
| 29 |
|
| 30 |
import argparse
|
|
@@ -39,6 +41,7 @@ from typing import Any, Dict, List, Union, Optional, Tuple
|
|
| 39 |
from datetime import datetime
|
| 40 |
|
| 41 |
import torch
|
|
|
|
| 42 |
from datasets import load_dataset
|
| 43 |
from huggingface_hub import DatasetCard, HfApi, login
|
| 44 |
from PIL import Image
|
|
@@ -50,14 +53,20 @@ logging.basicConfig(level=logging.INFO)
|
|
| 50 |
logger = logging.getLogger(__name__)
|
| 51 |
|
| 52 |
|
| 53 |
-
def
|
| 54 |
-
"""Check if CUDA is available and
|
| 55 |
-
if not
|
| 56 |
logger.error("CUDA is not available. This script requires a GPU.")
|
| 57 |
-
logger.error("Please run on a machine with
|
| 58 |
sys.exit(1)
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
|
| 63 |
def validate_and_resize_image(
|
|
@@ -167,6 +176,7 @@ def create_dataset_card(
|
|
| 167 |
max_tokens: int,
|
| 168 |
gpu_memory_utilization: float,
|
| 169 |
include_thinking: bool,
|
|
|
|
| 170 |
image_column: str = "image",
|
| 171 |
split: str = "train",
|
| 172 |
) -> str:
|
|
@@ -206,6 +216,7 @@ This dataset contains markdown-formatted OCR results from images in [{source_dat
|
|
| 206 |
- **Max Model Length**: {max_model_len:,} tokens
|
| 207 |
- **Max Output Tokens**: {max_tokens:,}
|
| 208 |
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
|
|
|
| 209 |
- **Thinking Traces**: {"Included" if include_thinking else "Excluded (only final answers)"}
|
| 210 |
|
| 211 |
## Model Information
|
|
@@ -271,7 +282,7 @@ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/numarkdown-ocr.py
|
|
| 271 |
## Performance
|
| 272 |
|
| 273 |
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
|
| 274 |
-
- **GPU Configuration**:
|
| 275 |
- **Model Size**: 8.29B parameters
|
| 276 |
|
| 277 |
Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
|
|
@@ -285,8 +296,9 @@ def main(
|
|
| 285 |
batch_size: int = 16,
|
| 286 |
model: str = "numind/NuMarkdown-8B-Thinking",
|
| 287 |
max_model_len: int = 16384,
|
| 288 |
-
max_tokens: int =
|
| 289 |
gpu_memory_utilization: float = 0.9,
|
|
|
|
| 290 |
hf_token: str = None,
|
| 291 |
split: str = "train",
|
| 292 |
max_samples: int = None,
|
|
@@ -297,10 +309,27 @@ def main(
|
|
| 297 |
temperature: float = 0.0,
|
| 298 |
custom_prompt: Optional[str] = None,
|
| 299 |
):
|
| 300 |
-
"""Process images from HF dataset through NuMarkdown model.
|
| 301 |
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
|
| 305 |
# Track processing start time
|
| 306 |
start_time = datetime.now()
|
|
@@ -335,11 +364,13 @@ def main(
|
|
| 335 |
|
| 336 |
# Initialize vLLM with trust_remote_code for NuMarkdown
|
| 337 |
logger.info(f"Initializing vLLM with model: {model}")
|
|
|
|
| 338 |
llm = LLM(
|
| 339 |
model=model,
|
| 340 |
trust_remote_code=True, # Required for NuMarkdown
|
| 341 |
max_model_len=max_model_len,
|
| 342 |
gpu_memory_utilization=gpu_memory_utilization,
|
|
|
|
| 343 |
limit_mm_per_prompt={"image": 1},
|
| 344 |
)
|
| 345 |
|
|
@@ -452,6 +483,7 @@ def main(
|
|
| 452 |
max_tokens=max_tokens,
|
| 453 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 454 |
include_thinking=include_thinking,
|
|
|
|
| 455 |
image_column=image_column,
|
| 456 |
split=split,
|
| 457 |
)
|
|
@@ -502,15 +534,17 @@ if __name__ == "__main__":
|
|
| 502 |
print("\n3. With custom settings:")
|
| 503 |
print(" uv run numarkdown-ocr.py scientific-papers extracted-text \\")
|
| 504 |
print(" --batch-size 8 \\")
|
| 505 |
-
print(" --max-tokens
|
| 506 |
print(" --gpu-memory-utilization 0.9")
|
| 507 |
print("\n4. Process a subset for testing:")
|
| 508 |
print(" uv run numarkdown-ocr.py large-dataset test-output --max-samples 10")
|
| 509 |
print("\n5. Custom prompt for specific needs:")
|
| 510 |
print(" uv run numarkdown-ocr.py invoices invoice-data \\")
|
| 511 |
print(' --custom-prompt "Extract all invoice details including line items"')
|
| 512 |
-
print("\n6.
|
| 513 |
-
print("
|
|
|
|
|
|
|
| 514 |
print(' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\')
|
| 515 |
print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/numarkdown-ocr.py \\")
|
| 516 |
print(" your-document-dataset \\")
|
|
@@ -536,6 +570,9 @@ Examples:
|
|
| 536 |
# Custom prompt for specific extraction
|
| 537 |
uv run numarkdown-ocr.py forms form-data --custom-prompt "Extract all form fields and values"
|
| 538 |
|
|
|
|
|
|
|
|
|
|
| 539 |
# Random sample from dataset
|
| 540 |
uv run numarkdown-ocr.py ordered-dataset random-sample --max-samples 50 --shuffle
|
| 541 |
""",
|
|
@@ -568,14 +605,19 @@ Examples:
|
|
| 568 |
parser.add_argument(
|
| 569 |
"--max-tokens",
|
| 570 |
type=int,
|
| 571 |
-
default=
|
| 572 |
-
help="Maximum tokens to generate (default:
|
| 573 |
)
|
| 574 |
parser.add_argument(
|
| 575 |
"--gpu-memory-utilization",
|
| 576 |
type=float,
|
| 577 |
default=0.9,
|
| 578 |
-
help="GPU memory utilization (default: 0.9)",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 579 |
)
|
| 580 |
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 581 |
parser.add_argument(
|
|
@@ -628,6 +670,7 @@ Examples:
|
|
| 628 |
max_model_len=args.max_model_len,
|
| 629 |
max_tokens=args.max_tokens,
|
| 630 |
gpu_memory_utilization=args.gpu_memory_utilization,
|
|
|
|
| 631 |
hf_token=args.hf_token,
|
| 632 |
split=args.split,
|
| 633 |
max_samples=args.max_samples,
|
|
|
|
| 25 |
- Mathematical formula recognition
|
| 26 |
- Clean markdown output generation
|
| 27 |
- Optional thinking trace inclusion
|
| 28 |
+
- Multi-GPU support with automatic detection
|
| 29 |
+
- Optimized token budget for reasoning models
|
| 30 |
"""
|
| 31 |
|
| 32 |
import argparse
|
|
|
|
| 41 |
from datetime import datetime
|
| 42 |
|
| 43 |
import torch
|
| 44 |
+
from torch import cuda
|
| 45 |
from datasets import load_dataset
|
| 46 |
from huggingface_hub import DatasetCard, HfApi, login
|
| 47 |
from PIL import Image
|
|
|
|
| 53 |
logger = logging.getLogger(__name__)
|
| 54 |
|
| 55 |
|
| 56 |
+
def check_gpu_availability() -> int:
|
| 57 |
+
"""Check if CUDA is available and return the number of GPUs."""
|
| 58 |
+
if not cuda.is_available():
|
| 59 |
logger.error("CUDA is not available. This script requires a GPU.")
|
| 60 |
+
logger.error("Please run on a machine with NVIDIA GPU or use HF Jobs with GPU flavor.")
|
| 61 |
sys.exit(1)
|
| 62 |
+
|
| 63 |
+
num_gpus = cuda.device_count()
|
| 64 |
+
for i in range(num_gpus):
|
| 65 |
+
gpu_name = cuda.get_device_name(i)
|
| 66 |
+
gpu_memory = cuda.get_device_properties(i).total_memory / 1024**3
|
| 67 |
+
logger.info(f"GPU {i}: {gpu_name} with {gpu_memory:.1f} GB memory")
|
| 68 |
+
|
| 69 |
+
return num_gpus
|
| 70 |
|
| 71 |
|
| 72 |
def validate_and_resize_image(
|
|
|
|
| 176 |
max_tokens: int,
|
| 177 |
gpu_memory_utilization: float,
|
| 178 |
include_thinking: bool,
|
| 179 |
+
tensor_parallel_size: int,
|
| 180 |
image_column: str = "image",
|
| 181 |
split: str = "train",
|
| 182 |
) -> str:
|
|
|
|
| 216 |
- **Max Model Length**: {max_model_len:,} tokens
|
| 217 |
- **Max Output Tokens**: {max_tokens:,}
|
| 218 |
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 219 |
+
- **Tensor Parallel Size**: {tensor_parallel_size} GPU(s)
|
| 220 |
- **Thinking Traces**: {"Included" if include_thinking else "Excluded (only final answers)"}
|
| 221 |
|
| 222 |
## Model Information
|
|
|
|
| 282 |
## Performance
|
| 283 |
|
| 284 |
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
|
| 285 |
+
- **GPU Configuration**: {tensor_parallel_size} GPU(s) with {gpu_memory_utilization:.0%} memory utilization
|
| 286 |
- **Model Size**: 8.29B parameters
|
| 287 |
|
| 288 |
Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
|
|
|
|
| 296 |
batch_size: int = 16,
|
| 297 |
model: str = "numind/NuMarkdown-8B-Thinking",
|
| 298 |
max_model_len: int = 16384,
|
| 299 |
+
max_tokens: int = 16384,
|
| 300 |
gpu_memory_utilization: float = 0.9,
|
| 301 |
+
tensor_parallel_size: Optional[int] = None,
|
| 302 |
hf_token: str = None,
|
| 303 |
split: str = "train",
|
| 304 |
max_samples: int = None,
|
|
|
|
| 309 |
temperature: float = 0.0,
|
| 310 |
custom_prompt: Optional[str] = None,
|
| 311 |
):
|
| 312 |
+
"""Process images from HF dataset through NuMarkdown model.
|
| 313 |
|
| 314 |
+
The max_tokens parameter controls the total token budget for both
|
| 315 |
+
thinking and answer phases. For complex documents with extensive
|
| 316 |
+
reasoning, the default of 16384 tokens provides ample room for both
|
| 317 |
+
the thinking process and the final markdown output.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
# GPU check and configuration
|
| 321 |
+
num_gpus = check_gpu_availability()
|
| 322 |
+
if tensor_parallel_size is None:
|
| 323 |
+
tensor_parallel_size = num_gpus
|
| 324 |
+
logger.info(
|
| 325 |
+
f"Auto-detected {num_gpus} GPU(s), using tensor_parallel_size={tensor_parallel_size}"
|
| 326 |
+
)
|
| 327 |
+
else:
|
| 328 |
+
logger.info(f"Using specified tensor_parallel_size={tensor_parallel_size}")
|
| 329 |
+
if tensor_parallel_size > num_gpus:
|
| 330 |
+
logger.warning(
|
| 331 |
+
f"Requested {tensor_parallel_size} GPUs but only {num_gpus} available"
|
| 332 |
+
)
|
| 333 |
|
| 334 |
# Track processing start time
|
| 335 |
start_time = datetime.now()
|
|
|
|
| 364 |
|
| 365 |
# Initialize vLLM with trust_remote_code for NuMarkdown
|
| 366 |
logger.info(f"Initializing vLLM with model: {model}")
|
| 367 |
+
logger.info(f"Using {tensor_parallel_size} GPU(s) for inference")
|
| 368 |
llm = LLM(
|
| 369 |
model=model,
|
| 370 |
trust_remote_code=True, # Required for NuMarkdown
|
| 371 |
max_model_len=max_model_len,
|
| 372 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 373 |
+
tensor_parallel_size=tensor_parallel_size,
|
| 374 |
limit_mm_per_prompt={"image": 1},
|
| 375 |
)
|
| 376 |
|
|
|
|
| 483 |
max_tokens=max_tokens,
|
| 484 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 485 |
include_thinking=include_thinking,
|
| 486 |
+
tensor_parallel_size=tensor_parallel_size,
|
| 487 |
image_column=image_column,
|
| 488 |
split=split,
|
| 489 |
)
|
|
|
|
| 534 |
print("\n3. With custom settings:")
|
| 535 |
print(" uv run numarkdown-ocr.py scientific-papers extracted-text \\")
|
| 536 |
print(" --batch-size 8 \\")
|
| 537 |
+
print(" --max-tokens 16384 \\")
|
| 538 |
print(" --gpu-memory-utilization 0.9")
|
| 539 |
print("\n4. Process a subset for testing:")
|
| 540 |
print(" uv run numarkdown-ocr.py large-dataset test-output --max-samples 10")
|
| 541 |
print("\n5. Custom prompt for specific needs:")
|
| 542 |
print(" uv run numarkdown-ocr.py invoices invoice-data \\")
|
| 543 |
print(' --custom-prompt "Extract all invoice details including line items"')
|
| 544 |
+
print("\n6. Multi-GPU processing:")
|
| 545 |
+
print(" uv run numarkdown-ocr.py large-docs processed-docs --tensor-parallel-size 2")
|
| 546 |
+
print("\n7. Running on HF Jobs:")
|
| 547 |
+
print(" hf jobs uv run --flavor a100x2 \\")
|
| 548 |
print(' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\')
|
| 549 |
print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/numarkdown-ocr.py \\")
|
| 550 |
print(" your-document-dataset \\")
|
|
|
|
| 570 |
# Custom prompt for specific extraction
|
| 571 |
uv run numarkdown-ocr.py forms form-data --custom-prompt "Extract all form fields and values"
|
| 572 |
|
| 573 |
+
# Multi-GPU for large datasets
|
| 574 |
+
uv run numarkdown-ocr.py large-dataset processed --tensor-parallel-size 4
|
| 575 |
+
|
| 576 |
# Random sample from dataset
|
| 577 |
uv run numarkdown-ocr.py ordered-dataset random-sample --max-samples 50 --shuffle
|
| 578 |
""",
|
|
|
|
| 605 |
parser.add_argument(
|
| 606 |
"--max-tokens",
|
| 607 |
type=int,
|
| 608 |
+
default=16384,
|
| 609 |
+
help="Maximum tokens to generate including thinking tokens (default: 16384)",
|
| 610 |
)
|
| 611 |
parser.add_argument(
|
| 612 |
"--gpu-memory-utilization",
|
| 613 |
type=float,
|
| 614 |
default=0.9,
|
| 615 |
+
help="GPU memory utilization per GPU (default: 0.9)",
|
| 616 |
+
)
|
| 617 |
+
parser.add_argument(
|
| 618 |
+
"--tensor-parallel-size",
|
| 619 |
+
type=int,
|
| 620 |
+
help="Number of GPUs to use (default: auto-detect all available)",
|
| 621 |
)
|
| 622 |
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 623 |
parser.add_argument(
|
|
|
|
| 670 |
max_model_len=args.max_model_len,
|
| 671 |
max_tokens=args.max_tokens,
|
| 672 |
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 673 |
+
tensor_parallel_size=args.tensor_parallel_size,
|
| 674 |
hf_token=args.hf_token,
|
| 675 |
split=args.split,
|
| 676 |
max_samples=args.max_samples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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets",
|
| 5 |
+
# "huggingface-hub[hf_transfer]",
|
| 6 |
+
# "pillow",
|
| 7 |
+
# "vllm",
|
| 8 |
+
# "tqdm",
|
| 9 |
+
# "toolz",
|
| 10 |
+
# "torch", # Added for CUDA check
|
| 11 |
+
# "docling-core", # For DocTags conversion
|
| 12 |
+
# ]
|
| 13 |
+
#
|
| 14 |
+
# ///
|
| 15 |
+
|
| 16 |
+
"""
|
| 17 |
+
Extract structured documents using SmolDocling-256M with vLLM.
|
| 18 |
+
|
| 19 |
+
This script processes images through the SmolDocling model to extract
|
| 20 |
+
structured document content with DocTags format, ideal for documents
|
| 21 |
+
with code, formulas, tables, and complex layouts.
|
| 22 |
+
|
| 23 |
+
Features:
|
| 24 |
+
- Ultra-compact 256M parameter model
|
| 25 |
+
- DocTags format for efficient representation
|
| 26 |
+
- Code block recognition with indentation
|
| 27 |
+
- Mathematical formula detection
|
| 28 |
+
- Table and chart extraction
|
| 29 |
+
- Layout preservation with bounding boxes
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
import argparse
|
| 33 |
+
import base64
|
| 34 |
+
import io
|
| 35 |
+
import json
|
| 36 |
+
import logging
|
| 37 |
+
import os
|
| 38 |
+
import re
|
| 39 |
+
import sys
|
| 40 |
+
from typing import Any, Dict, List, Union
|
| 41 |
+
from datetime import datetime
|
| 42 |
+
|
| 43 |
+
import torch
|
| 44 |
+
from datasets import load_dataset
|
| 45 |
+
from docling_core.types.doc import DoclingDocument
|
| 46 |
+
from docling_core.types.doc.document import DocTagsDocument
|
| 47 |
+
from huggingface_hub import DatasetCard, login
|
| 48 |
+
from PIL import Image
|
| 49 |
+
from toolz import partition_all
|
| 50 |
+
from tqdm.auto import tqdm
|
| 51 |
+
from vllm import LLM, SamplingParams
|
| 52 |
+
|
| 53 |
+
logging.basicConfig(level=logging.INFO)
|
| 54 |
+
logger = logging.getLogger(__name__)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def check_cuda_availability():
|
| 58 |
+
"""Check if CUDA is available and exit if not."""
|
| 59 |
+
if not torch.cuda.is_available():
|
| 60 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 61 |
+
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 62 |
+
sys.exit(1)
|
| 63 |
+
else:
|
| 64 |
+
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def prepare_llm_input(
|
| 68 |
+
image: Union[Image.Image, Dict[str, Any], str],
|
| 69 |
+
prompt_text: str = "Convert page to Docling.",
|
| 70 |
+
) -> Dict:
|
| 71 |
+
"""Prepare input for vLLM processing."""
|
| 72 |
+
# Convert to PIL Image if needed
|
| 73 |
+
if isinstance(image, Image.Image):
|
| 74 |
+
pil_img = image.convert("RGB")
|
| 75 |
+
elif isinstance(image, dict) and "bytes" in image:
|
| 76 |
+
pil_img = Image.open(io.BytesIO(image["bytes"])).convert("RGB")
|
| 77 |
+
elif isinstance(image, str):
|
| 78 |
+
pil_img = Image.open(image).convert("RGB")
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 81 |
+
|
| 82 |
+
# Create chat template - exact format from the example
|
| 83 |
+
chat_template = (
|
| 84 |
+
f"<|im_start|>User:<image>{prompt_text}<end_of_utterance>\nAssistant:"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Return in the format expected by vLLM generate
|
| 88 |
+
return {"prompt": chat_template, "multi_modal_data": {"image": pil_img}}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def convert_doctags_to_markdown(doctags_output: str) -> str:
|
| 92 |
+
"""Convert DocTags output to markdown format."""
|
| 93 |
+
# For now, just return the raw output as-is
|
| 94 |
+
# We'll focus on getting the basic vLLM inference working first
|
| 95 |
+
return doctags_output.strip()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def create_dataset_card(
|
| 99 |
+
source_dataset: str,
|
| 100 |
+
model: str,
|
| 101 |
+
num_samples: int,
|
| 102 |
+
processing_time: str,
|
| 103 |
+
output_column: str,
|
| 104 |
+
output_format: str,
|
| 105 |
+
batch_size: int,
|
| 106 |
+
max_model_len: int,
|
| 107 |
+
max_tokens: int,
|
| 108 |
+
gpu_memory_utilization: float,
|
| 109 |
+
image_column: str = "image",
|
| 110 |
+
split: str = "train",
|
| 111 |
+
) -> str:
|
| 112 |
+
"""Create a dataset card documenting the OCR process."""
|
| 113 |
+
model_name = model.split("/")[-1]
|
| 114 |
+
|
| 115 |
+
return f"""---
|
| 116 |
+
tags:
|
| 117 |
+
- ocr
|
| 118 |
+
- document-processing
|
| 119 |
+
- smoldocling
|
| 120 |
+
- doctags
|
| 121 |
+
- structured-extraction
|
| 122 |
+
- uv-script
|
| 123 |
+
- generated
|
| 124 |
+
---
|
| 125 |
+
|
| 126 |
+
# Document Processing using {model_name}
|
| 127 |
+
|
| 128 |
+
This dataset contains structured document extraction from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using SmolDocling.
|
| 129 |
+
|
| 130 |
+
## Processing Details
|
| 131 |
+
|
| 132 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 133 |
+
- **Model**: [{model}](https://huggingface.co/{model})
|
| 134 |
+
- **Number of Samples**: {num_samples:,}
|
| 135 |
+
- **Processing Time**: {processing_time}
|
| 136 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 137 |
+
|
| 138 |
+
### Configuration
|
| 139 |
+
|
| 140 |
+
- **Image Column**: `{image_column}`
|
| 141 |
+
- **Output Column**: `{output_column}`
|
| 142 |
+
- **Output Format**: {output_format}
|
| 143 |
+
- **Dataset Split**: `{split}`
|
| 144 |
+
- **Batch Size**: {batch_size}
|
| 145 |
+
- **Max Model Length**: {max_model_len:,} tokens
|
| 146 |
+
- **Max Output Tokens**: {max_tokens:,}
|
| 147 |
+
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 148 |
+
|
| 149 |
+
## Model Information
|
| 150 |
+
|
| 151 |
+
SmolDocling-256M is an ultra-compact multimodal model that excels at:
|
| 152 |
+
- 💻 **Code Recognition** - Detects and formats code blocks with proper indentation
|
| 153 |
+
- 🔢 **Formula Recognition** - Identifies and processes mathematical expressions
|
| 154 |
+
- 📊 **Tables & Charts** - Extracts structured data from tables and charts
|
| 155 |
+
- 📐 **Layout Preservation** - Maintains document structure with bounding boxes
|
| 156 |
+
- 🏷️ **DocTags Format** - Efficient minimal representation for documents
|
| 157 |
+
- ⚡ **Fast Inference** - Only 256M parameters for quick processing
|
| 158 |
+
|
| 159 |
+
## Dataset Structure
|
| 160 |
+
|
| 161 |
+
The dataset contains all original columns plus:
|
| 162 |
+
- `{output_column}`: The extracted {"DocTags JSON" if output_format == "doctags" else "markdown"} from each image
|
| 163 |
+
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 164 |
+
|
| 165 |
+
## Usage
|
| 166 |
+
|
| 167 |
+
```python
|
| 168 |
+
from datasets import load_dataset
|
| 169 |
+
import json
|
| 170 |
+
{"from docling_core.types.doc import DoclingDocument" if output_format == "doctags" else ""}
|
| 171 |
+
{"from docling_core.types.doc.document import DocTagsDocument" if output_format == "doctags" else ""}
|
| 172 |
+
|
| 173 |
+
# Load the dataset
|
| 174 |
+
dataset = load_dataset("{{output_dataset_id}}", split="{split}")
|
| 175 |
+
|
| 176 |
+
# Access the extracted content
|
| 177 |
+
for example in dataset:
|
| 178 |
+
{"# Parse DocTags and convert to desired format" if output_format == "doctags" else ""}
|
| 179 |
+
{f"doc_tags = DocTagsDocument.model_validate_json(example['{output_column}'])" if output_format == "doctags" else f"print(example['{output_column}'])"}
|
| 180 |
+
{"doc = DoclingDocument.from_doctags(doc_tags)" if output_format == "doctags" else ""}
|
| 181 |
+
{"print(doc.export(format='md').text) # Or 'html', 'json'" if output_format == "doctags" else ""}
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
# View all OCR models applied to this dataset
|
| 185 |
+
inference_info = json.loads(dataset[0]["inference_info"])
|
| 186 |
+
for info in inference_info:
|
| 187 |
+
print(f"Column: {{info['column_name']}} - Model: {{info['model_id']}}")
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
## Reproduction
|
| 191 |
+
|
| 192 |
+
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) SmolDocling script:
|
| 193 |
+
|
| 194 |
+
```bash
|
| 195 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/smoldocling-ocr.py \\
|
| 196 |
+
{source_dataset} \\
|
| 197 |
+
<output-dataset> \\
|
| 198 |
+
--image-column {image_column} \\
|
| 199 |
+
--output-format {output_format} \\
|
| 200 |
+
--batch-size {batch_size} \\
|
| 201 |
+
--max-model-len {max_model_len} \\
|
| 202 |
+
--max-tokens {max_tokens} \\
|
| 203 |
+
--gpu-memory-utilization {gpu_memory_utilization}
|
| 204 |
+
```
|
| 205 |
+
|
| 206 |
+
## Performance
|
| 207 |
+
|
| 208 |
+
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
|
| 209 |
+
- **Model Size**: 256M parameters (ultra-compact)
|
| 210 |
+
- **GPU Configuration**: vLLM with {gpu_memory_utilization:.0%} GPU memory utilization
|
| 211 |
+
|
| 212 |
+
Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def main(
|
| 217 |
+
input_dataset: str,
|
| 218 |
+
output_dataset: str,
|
| 219 |
+
image_column: str = "image",
|
| 220 |
+
batch_size: int = 32,
|
| 221 |
+
model: str = "ds4sd/SmolDocling-256M-preview",
|
| 222 |
+
max_model_len: int = 8192,
|
| 223 |
+
max_tokens: int = 8192,
|
| 224 |
+
gpu_memory_utilization: float = 0.8,
|
| 225 |
+
hf_token: str = None,
|
| 226 |
+
split: str = "train",
|
| 227 |
+
max_samples: int = None,
|
| 228 |
+
private: bool = False,
|
| 229 |
+
output_column: str = None,
|
| 230 |
+
output_format: str = "markdown",
|
| 231 |
+
shuffle: bool = False,
|
| 232 |
+
seed: int = 42,
|
| 233 |
+
prompt: str = "Convert page to Docling.",
|
| 234 |
+
):
|
| 235 |
+
"""Process images from HF dataset through SmolDocling model."""
|
| 236 |
+
|
| 237 |
+
# Check CUDA availability first
|
| 238 |
+
check_cuda_availability()
|
| 239 |
+
|
| 240 |
+
# Track processing start time
|
| 241 |
+
start_time = datetime.now()
|
| 242 |
+
|
| 243 |
+
# Enable HF_TRANSFER for faster downloads
|
| 244 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 245 |
+
|
| 246 |
+
# Login to HF if token provided
|
| 247 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 248 |
+
if HF_TOKEN:
|
| 249 |
+
login(token=HF_TOKEN)
|
| 250 |
+
|
| 251 |
+
# Load dataset
|
| 252 |
+
logger.info(f"Loading dataset: {input_dataset}")
|
| 253 |
+
dataset = load_dataset(input_dataset, split=split)
|
| 254 |
+
|
| 255 |
+
# Set output column name dynamically if not provided
|
| 256 |
+
if output_column is None:
|
| 257 |
+
# Extract model name from path (e.g., "ds4sd/SmolDocling-256M-preview" -> "smoldocling")
|
| 258 |
+
model_name = model.split("/")[-1].split("-")[0].lower()
|
| 259 |
+
output_column = f"{model_name}_text"
|
| 260 |
+
logger.info(f"Using dynamic output column name: {output_column}")
|
| 261 |
+
|
| 262 |
+
# Validate image column
|
| 263 |
+
if image_column not in dataset.column_names:
|
| 264 |
+
raise ValueError(
|
| 265 |
+
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# Validate output format
|
| 269 |
+
if output_format not in ["markdown", "doctags"]:
|
| 270 |
+
raise ValueError(
|
| 271 |
+
f"Invalid output format '{output_format}'. Must be 'markdown' or 'doctags'"
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# Shuffle if requested
|
| 275 |
+
if shuffle:
|
| 276 |
+
logger.info(f"Shuffling dataset with seed {seed}")
|
| 277 |
+
dataset = dataset.shuffle(seed=seed)
|
| 278 |
+
|
| 279 |
+
# Limit samples if requested
|
| 280 |
+
if max_samples:
|
| 281 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 282 |
+
logger.info(f"Limited to {len(dataset)} samples")
|
| 283 |
+
|
| 284 |
+
# Initialize vLLM
|
| 285 |
+
logger.info(f"Initializing vLLM with model: {model}")
|
| 286 |
+
llm = LLM(
|
| 287 |
+
model=model,
|
| 288 |
+
trust_remote_code=True,
|
| 289 |
+
max_model_len=max_model_len,
|
| 290 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 291 |
+
limit_mm_per_prompt={"image": 1},
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
sampling_params = SamplingParams(
|
| 295 |
+
temperature=0.0, # Deterministic for OCR
|
| 296 |
+
max_tokens=max_tokens,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# Process images in batches
|
| 300 |
+
all_output = []
|
| 301 |
+
|
| 302 |
+
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 303 |
+
logger.info(f"Output format: {output_format}")
|
| 304 |
+
|
| 305 |
+
# Process in batches to avoid memory issues
|
| 306 |
+
for batch_indices in tqdm(
|
| 307 |
+
partition_all(batch_size, range(len(dataset))),
|
| 308 |
+
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 309 |
+
desc="OCR processing",
|
| 310 |
+
):
|
| 311 |
+
batch_indices = list(batch_indices)
|
| 312 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 313 |
+
|
| 314 |
+
try:
|
| 315 |
+
# Prepare inputs for batch
|
| 316 |
+
batch_inputs = [prepare_llm_input(img, prompt) for img in batch_images]
|
| 317 |
+
|
| 318 |
+
# Process with vLLM using generate
|
| 319 |
+
outputs = llm.generate(batch_inputs, sampling_params=sampling_params)
|
| 320 |
+
|
| 321 |
+
# Extract text from outputs
|
| 322 |
+
for i, output in enumerate(outputs):
|
| 323 |
+
raw_output = output.outputs[0].text.strip()
|
| 324 |
+
|
| 325 |
+
# Convert to markdown if requested
|
| 326 |
+
if output_format == "markdown":
|
| 327 |
+
processed_output = convert_doctags_to_markdown(raw_output)
|
| 328 |
+
else:
|
| 329 |
+
processed_output = raw_output
|
| 330 |
+
|
| 331 |
+
all_output.append(processed_output)
|
| 332 |
+
|
| 333 |
+
except Exception as e:
|
| 334 |
+
logger.error(f"Error processing batch: {e}")
|
| 335 |
+
# Add error placeholders for failed batch
|
| 336 |
+
all_output.extend(["[OCR FAILED]"] * len(batch_images))
|
| 337 |
+
|
| 338 |
+
# Add output column to dataset
|
| 339 |
+
logger.info(f"Adding {output_column} column to dataset")
|
| 340 |
+
dataset = dataset.add_column(output_column, all_output)
|
| 341 |
+
|
| 342 |
+
# Handle inference_info tracking
|
| 343 |
+
logger.info("Updating inference_info...")
|
| 344 |
+
|
| 345 |
+
# Check for existing inference_info
|
| 346 |
+
if "inference_info" in dataset.column_names:
|
| 347 |
+
# Parse existing info from first row (all rows have same info)
|
| 348 |
+
try:
|
| 349 |
+
existing_info = json.loads(dataset[0]["inference_info"])
|
| 350 |
+
if not isinstance(existing_info, list):
|
| 351 |
+
existing_info = [existing_info] # Convert old format to list
|
| 352 |
+
except (json.JSONDecodeError, TypeError):
|
| 353 |
+
existing_info = []
|
| 354 |
+
# Remove old column to update it
|
| 355 |
+
dataset = dataset.remove_columns(["inference_info"])
|
| 356 |
+
else:
|
| 357 |
+
existing_info = []
|
| 358 |
+
|
| 359 |
+
# Add new inference info
|
| 360 |
+
new_info = {
|
| 361 |
+
"column_name": output_column,
|
| 362 |
+
"model_id": model,
|
| 363 |
+
"processing_date": datetime.now().isoformat(),
|
| 364 |
+
"batch_size": batch_size,
|
| 365 |
+
"max_tokens": max_tokens,
|
| 366 |
+
"gpu_memory_utilization": gpu_memory_utilization,
|
| 367 |
+
"max_model_len": max_model_len,
|
| 368 |
+
"output_format": output_format,
|
| 369 |
+
"prompt": prompt,
|
| 370 |
+
"script": "smoldocling-ocr.py",
|
| 371 |
+
"script_version": "1.0.0",
|
| 372 |
+
"script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/smoldocling-ocr.py",
|
| 373 |
+
}
|
| 374 |
+
existing_info.append(new_info)
|
| 375 |
+
|
| 376 |
+
# Add updated inference_info column
|
| 377 |
+
info_json = json.dumps(existing_info, ensure_ascii=False)
|
| 378 |
+
dataset = dataset.add_column("inference_info", [info_json] * len(dataset))
|
| 379 |
+
|
| 380 |
+
# Push to hub
|
| 381 |
+
logger.info(f"Pushing to {output_dataset}")
|
| 382 |
+
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 383 |
+
|
| 384 |
+
# Calculate processing time
|
| 385 |
+
end_time = datetime.now()
|
| 386 |
+
processing_duration = end_time - start_time
|
| 387 |
+
processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
|
| 388 |
+
|
| 389 |
+
# Create and push dataset card
|
| 390 |
+
logger.info("Creating dataset card...")
|
| 391 |
+
card_content = create_dataset_card(
|
| 392 |
+
source_dataset=input_dataset,
|
| 393 |
+
model=model,
|
| 394 |
+
num_samples=len(dataset),
|
| 395 |
+
processing_time=processing_time,
|
| 396 |
+
output_column=output_column,
|
| 397 |
+
output_format=output_format,
|
| 398 |
+
batch_size=batch_size,
|
| 399 |
+
max_model_len=max_model_len,
|
| 400 |
+
max_tokens=max_tokens,
|
| 401 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 402 |
+
image_column=image_column,
|
| 403 |
+
split=split,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
card = DatasetCard(card_content)
|
| 407 |
+
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 408 |
+
logger.info("✅ Dataset card created and pushed!")
|
| 409 |
+
|
| 410 |
+
logger.info("✅ OCR conversion complete!")
|
| 411 |
+
logger.info(
|
| 412 |
+
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
if __name__ == "__main__":
|
| 417 |
+
# Show example usage if no arguments
|
| 418 |
+
if len(sys.argv) == 1:
|
| 419 |
+
print("=" * 80)
|
| 420 |
+
print("SmolDocling Ultra-Compact Document Processing")
|
| 421 |
+
print("=" * 80)
|
| 422 |
+
print("\nThis script extracts structured document content using")
|
| 423 |
+
print("the SmolDocling-256M model with vLLM acceleration.")
|
| 424 |
+
print("\nFeatures:")
|
| 425 |
+
print("- Ultra-compact 256M parameter model")
|
| 426 |
+
print("- DocTags format for efficient representation")
|
| 427 |
+
print("- Code block recognition with indentation")
|
| 428 |
+
print("- Mathematical formula detection")
|
| 429 |
+
print("- Table and chart extraction")
|
| 430 |
+
print("- Layout preservation with bounding boxes")
|
| 431 |
+
print("\nExample usage:")
|
| 432 |
+
print("\n1. Basic document conversion to markdown:")
|
| 433 |
+
print(" uv run smoldocling-ocr.py document-images extracted-docs")
|
| 434 |
+
print("\n2. Extract with DocTags format:")
|
| 435 |
+
print(" uv run smoldocling-ocr.py scientific-papers doc-analysis \\")
|
| 436 |
+
print(" --output-format doctags")
|
| 437 |
+
print("\n3. Custom settings:")
|
| 438 |
+
print(" uv run smoldocling-ocr.py code-docs structured-output \\")
|
| 439 |
+
print(" --image-column page \\")
|
| 440 |
+
print(" --batch-size 64 \\")
|
| 441 |
+
print(" --gpu-memory-utilization 0.9")
|
| 442 |
+
print("\n4. Process a subset for testing:")
|
| 443 |
+
print(" uv run smoldocling-ocr.py large-dataset test-output --max-samples 10")
|
| 444 |
+
print("\n5. Random sample from ordered dataset:")
|
| 445 |
+
print(
|
| 446 |
+
" uv run smoldocling-ocr.py ordered-dataset random-test --max-samples 50 --shuffle"
|
| 447 |
+
)
|
| 448 |
+
print("\n6. Running on HF Jobs:")
|
| 449 |
+
print(" hf jobs uv run --flavor l4x1 \\")
|
| 450 |
+
print(
|
| 451 |
+
' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\'
|
| 452 |
+
)
|
| 453 |
+
print(
|
| 454 |
+
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/smoldocling-ocr.py \\"
|
| 455 |
+
)
|
| 456 |
+
print(" your-document-dataset \\")
|
| 457 |
+
print(" your-structured-output")
|
| 458 |
+
print("\n" + "=" * 80)
|
| 459 |
+
print("\nFor full help, run: uv run smoldocling-ocr.py --help")
|
| 460 |
+
sys.exit(0)
|
| 461 |
+
|
| 462 |
+
parser = argparse.ArgumentParser(
|
| 463 |
+
description="Extract structured documents using SmolDocling",
|
| 464 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 465 |
+
epilog="""
|
| 466 |
+
Examples:
|
| 467 |
+
# Basic usage
|
| 468 |
+
uv run smoldocling-ocr.py my-images-dataset structured-output
|
| 469 |
+
|
| 470 |
+
# With DocTags format output
|
| 471 |
+
uv run smoldocling-ocr.py documents doc-analysis --output-format doctags
|
| 472 |
+
|
| 473 |
+
# Process subset for testing
|
| 474 |
+
uv run smoldocling-ocr.py large-dataset test-output --max-samples 100
|
| 475 |
+
|
| 476 |
+
# Random sample of 100 images
|
| 477 |
+
uv run smoldocling-ocr.py ordered-dataset random-sample --max-samples 100 --shuffle
|
| 478 |
+
|
| 479 |
+
# Custom output column name (default: smoldocling_text)
|
| 480 |
+
uv run smoldocling-ocr.py images texts --output-column extracted_content
|
| 481 |
+
""",
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 485 |
+
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 486 |
+
parser.add_argument(
|
| 487 |
+
"--image-column",
|
| 488 |
+
default="image",
|
| 489 |
+
help="Column containing images (default: image)",
|
| 490 |
+
)
|
| 491 |
+
parser.add_argument(
|
| 492 |
+
"--batch-size",
|
| 493 |
+
type=int,
|
| 494 |
+
default=32,
|
| 495 |
+
help="Batch size for processing (default: 32)",
|
| 496 |
+
)
|
| 497 |
+
parser.add_argument(
|
| 498 |
+
"--model",
|
| 499 |
+
default="ds4sd/SmolDocling-256M-preview",
|
| 500 |
+
help="Model to use (default: ds4sd/SmolDocling-256M-preview)",
|
| 501 |
+
)
|
| 502 |
+
parser.add_argument(
|
| 503 |
+
"--max-model-len",
|
| 504 |
+
type=int,
|
| 505 |
+
default=8192,
|
| 506 |
+
help="Maximum model context length (default: 8192)",
|
| 507 |
+
)
|
| 508 |
+
parser.add_argument(
|
| 509 |
+
"--max-tokens",
|
| 510 |
+
type=int,
|
| 511 |
+
default=8192,
|
| 512 |
+
help="Maximum tokens to generate (default: 8192)",
|
| 513 |
+
)
|
| 514 |
+
parser.add_argument(
|
| 515 |
+
"--gpu-memory-utilization",
|
| 516 |
+
type=float,
|
| 517 |
+
default=0.8,
|
| 518 |
+
help="GPU memory utilization (default: 0.8)",
|
| 519 |
+
)
|
| 520 |
+
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 521 |
+
parser.add_argument(
|
| 522 |
+
"--split", default="train", help="Dataset split to use (default: train)"
|
| 523 |
+
)
|
| 524 |
+
parser.add_argument(
|
| 525 |
+
"--max-samples",
|
| 526 |
+
type=int,
|
| 527 |
+
help="Maximum number of samples to process (for testing)",
|
| 528 |
+
)
|
| 529 |
+
parser.add_argument(
|
| 530 |
+
"--private", action="store_true", help="Make output dataset private"
|
| 531 |
+
)
|
| 532 |
+
parser.add_argument(
|
| 533 |
+
"--output-column",
|
| 534 |
+
default=None,
|
| 535 |
+
help="Name of the output column for extracted text (default: auto-generated from model name)",
|
| 536 |
+
)
|
| 537 |
+
parser.add_argument(
|
| 538 |
+
"--output-format",
|
| 539 |
+
default="markdown",
|
| 540 |
+
choices=["markdown", "doctags"],
|
| 541 |
+
help="Output format: 'markdown' or 'doctags' (default: markdown)",
|
| 542 |
+
)
|
| 543 |
+
parser.add_argument(
|
| 544 |
+
"--shuffle",
|
| 545 |
+
action="store_true",
|
| 546 |
+
help="Shuffle the dataset before processing (useful for random sampling)",
|
| 547 |
+
)
|
| 548 |
+
parser.add_argument(
|
| 549 |
+
"--seed",
|
| 550 |
+
type=int,
|
| 551 |
+
default=42,
|
| 552 |
+
help="Random seed for shuffling (default: 42)",
|
| 553 |
+
)
|
| 554 |
+
parser.add_argument(
|
| 555 |
+
"--prompt",
|
| 556 |
+
default="Convert page to Docling.",
|
| 557 |
+
help="Custom prompt for the model (default: 'Convert page to Docling.')",
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
args = parser.parse_args()
|
| 561 |
+
|
| 562 |
+
main(
|
| 563 |
+
input_dataset=args.input_dataset,
|
| 564 |
+
output_dataset=args.output_dataset,
|
| 565 |
+
image_column=args.image_column,
|
| 566 |
+
batch_size=args.batch_size,
|
| 567 |
+
model=args.model,
|
| 568 |
+
max_model_len=args.max_model_len,
|
| 569 |
+
max_tokens=args.max_tokens,
|
| 570 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 571 |
+
hf_token=args.hf_token,
|
| 572 |
+
split=args.split,
|
| 573 |
+
max_samples=args.max_samples,
|
| 574 |
+
private=args.private,
|
| 575 |
+
output_column=args.output_column,
|
| 576 |
+
output_format=args.output_format,
|
| 577 |
+
shuffle=args.shuffle,
|
| 578 |
+
seed=args.seed,
|
| 579 |
+
prompt=args.prompt,
|
| 580 |
+
)
|