Add LightOnOCR script for fast document OCR
Browse filesAdds lighton-ocr.py - a UV script for processing documents with
LightOnOCR, a compact 1B OCR model optimized for production speed.
Features:
- Fast: 5.71 pages/sec on H100 GPU
- Compact: Only 1B parameters
- 3 vocabulary variants (151k/32k/16k tokens)
- European language optimization (12% faster with 32k/16k)
- LaTeX formula and table extraction
- Markdown output format
- Image preprocessing (1288px target size)
Based on dots-ocr.py template with adaptations:
- LightOnOCR-specific sampling params (temp=0.2, top_p=0.9)
- Automatic image resizing to optimal dimensions
- Vocabulary size selection
- Simplified prompt handling (no special modes)
Model: lightonai/LightOnOCR-1B-1025
vLLM: Officially supported in model registry
Blog: https://huggingface.co/blog/lightonai/lightonocr
π€ Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com>
- lighton-ocr.py +628 -0
|
@@ -0,0 +1,628 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets",
|
| 5 |
+
# "huggingface-hub[hf_transfer]",
|
| 6 |
+
# "pillow",
|
| 7 |
+
# "vllm>=0.9.1",
|
| 8 |
+
# "tqdm",
|
| 9 |
+
# "toolz",
|
| 10 |
+
# "torch",
|
| 11 |
+
# ]
|
| 12 |
+
#
|
| 13 |
+
# ///
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
Convert document images to markdown using LightOnOCR with vLLM.
|
| 17 |
+
|
| 18 |
+
LightOnOCR is a compact 1B multilingual OCR model optimized for production speed.
|
| 19 |
+
Combines Pixtral ViT encoder with Qwen3 language model for efficient document parsing.
|
| 20 |
+
|
| 21 |
+
Features:
|
| 22 |
+
- β‘ Fastest: 5.71 pages/sec on H100 GPU
|
| 23 |
+
- π― Compact: Only 1B parameters
|
| 24 |
+
- π Multilingual with European language optimization
|
| 25 |
+
- π LaTeX formula recognition
|
| 26 |
+
- π Table extraction (markdown format)
|
| 27 |
+
- π Document structure preservation
|
| 28 |
+
- π€ 3 vocabulary sizes (151k/32k/16k tokens)
|
| 29 |
+
|
| 30 |
+
Model: lightonai/LightOnOCR-1B-1025
|
| 31 |
+
vLLM: Officially supported in model registry
|
| 32 |
+
Performance: 76.1% overall benchmark score
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import argparse
|
| 36 |
+
import base64
|
| 37 |
+
import io
|
| 38 |
+
import json
|
| 39 |
+
import logging
|
| 40 |
+
import os
|
| 41 |
+
import sys
|
| 42 |
+
from typing import Any, Dict, List, Union
|
| 43 |
+
from datetime import datetime
|
| 44 |
+
|
| 45 |
+
import torch
|
| 46 |
+
from datasets import load_dataset
|
| 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 |
+
# Model variants with different vocabulary sizes
|
| 58 |
+
MODEL_VARIANTS = {
|
| 59 |
+
"151k": "lightonai/LightOnOCR-1B-1025", # Full vocabulary (default)
|
| 60 |
+
"32k": "lightonai/LightOnOCR-0.9B-32k-1025", # European languages optimized
|
| 61 |
+
"16k": "lightonai/LightOnOCR-0.9B-16k-1025", # European languages optimized
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def check_cuda_availability():
|
| 66 |
+
"""Check if CUDA is available and exit if not."""
|
| 67 |
+
if not torch.cuda.is_available():
|
| 68 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 69 |
+
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 70 |
+
sys.exit(1)
|
| 71 |
+
else:
|
| 72 |
+
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def resize_image_to_target(image: Image.Image, target_size: int = 1288) -> Image.Image:
|
| 76 |
+
"""
|
| 77 |
+
Resize image so longest dimension is target_size while maintaining aspect ratio.
|
| 78 |
+
|
| 79 |
+
LightOnOCR is optimized for 1280-1300px longest dimension at 300 DPI.
|
| 80 |
+
"""
|
| 81 |
+
width, height = image.size
|
| 82 |
+
|
| 83 |
+
# If image is already smaller, don't upscale
|
| 84 |
+
if max(width, height) <= target_size:
|
| 85 |
+
return image
|
| 86 |
+
|
| 87 |
+
# Calculate new dimensions maintaining aspect ratio
|
| 88 |
+
if width > height:
|
| 89 |
+
new_width = target_size
|
| 90 |
+
new_height = int(height * (target_size / width))
|
| 91 |
+
else:
|
| 92 |
+
new_height = target_size
|
| 93 |
+
new_width = int(width * (target_size / height))
|
| 94 |
+
|
| 95 |
+
return image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def make_ocr_message(
|
| 99 |
+
image: Union[Image.Image, Dict[str, Any], str],
|
| 100 |
+
resize: bool = True,
|
| 101 |
+
target_size: int = 1288,
|
| 102 |
+
) -> List[Dict]:
|
| 103 |
+
"""
|
| 104 |
+
Create chat message for OCR processing.
|
| 105 |
+
|
| 106 |
+
LightOnOCR expects images at 1280-1300px longest dimension for optimal results.
|
| 107 |
+
"""
|
| 108 |
+
# Convert to PIL Image if needed
|
| 109 |
+
if isinstance(image, Image.Image):
|
| 110 |
+
pil_img = image
|
| 111 |
+
elif isinstance(image, dict) and "bytes" in image:
|
| 112 |
+
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 113 |
+
elif isinstance(image, str):
|
| 114 |
+
pil_img = Image.open(image)
|
| 115 |
+
else:
|
| 116 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 117 |
+
|
| 118 |
+
# Convert to RGB
|
| 119 |
+
pil_img = pil_img.convert("RGB")
|
| 120 |
+
|
| 121 |
+
# Resize to optimal dimensions for LightOnOCR
|
| 122 |
+
if resize:
|
| 123 |
+
pil_img = resize_image_to_target(pil_img, target_size)
|
| 124 |
+
logger.debug(f"Resized image to {pil_img.size}")
|
| 125 |
+
|
| 126 |
+
# Convert to base64 data URI
|
| 127 |
+
buf = io.BytesIO()
|
| 128 |
+
pil_img.save(buf, format="PNG")
|
| 129 |
+
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 130 |
+
|
| 131 |
+
# LightOnOCR uses simple message format (no explicit prompt text needed)
|
| 132 |
+
return [
|
| 133 |
+
{
|
| 134 |
+
"role": "user",
|
| 135 |
+
"content": [
|
| 136 |
+
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 137 |
+
],
|
| 138 |
+
}
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def create_dataset_card(
|
| 143 |
+
source_dataset: str,
|
| 144 |
+
model: str,
|
| 145 |
+
vocab_size: str,
|
| 146 |
+
num_samples: int,
|
| 147 |
+
processing_time: str,
|
| 148 |
+
batch_size: int,
|
| 149 |
+
max_model_len: int,
|
| 150 |
+
max_tokens: int,
|
| 151 |
+
gpu_memory_utilization: float,
|
| 152 |
+
temperature: float,
|
| 153 |
+
top_p: float,
|
| 154 |
+
target_size: int,
|
| 155 |
+
image_column: str = "image",
|
| 156 |
+
split: str = "train",
|
| 157 |
+
) -> str:
|
| 158 |
+
"""Create a dataset card documenting the OCR process."""
|
| 159 |
+
model_name = model.split("/")[-1]
|
| 160 |
+
|
| 161 |
+
return f"""---
|
| 162 |
+
tags:
|
| 163 |
+
- ocr
|
| 164 |
+
- document-processing
|
| 165 |
+
- lighton-ocr
|
| 166 |
+
- markdown
|
| 167 |
+
- uv-script
|
| 168 |
+
- generated
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
# Document OCR using {model_name}
|
| 172 |
+
|
| 173 |
+
This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using LightOnOCR, a fast and compact 1B OCR model.
|
| 174 |
+
|
| 175 |
+
## Processing Details
|
| 176 |
+
|
| 177 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 178 |
+
- **Model**: [{model}](https://huggingface.co/{model})
|
| 179 |
+
- **Vocabulary Size**: {vocab_size} tokens
|
| 180 |
+
- **Number of Samples**: {num_samples:,}
|
| 181 |
+
- **Processing Time**: {processing_time}
|
| 182 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 183 |
+
|
| 184 |
+
### Configuration
|
| 185 |
+
|
| 186 |
+
- **Image Column**: `{image_column}`
|
| 187 |
+
- **Output Column**: `markdown`
|
| 188 |
+
- **Dataset Split**: `{split}`
|
| 189 |
+
- **Batch Size**: {batch_size}
|
| 190 |
+
- **Target Image Size**: {target_size}px (longest dimension)
|
| 191 |
+
- **Max Model Length**: {max_model_len:,} tokens
|
| 192 |
+
- **Max Output Tokens**: {max_tokens:,}
|
| 193 |
+
- **Temperature**: {temperature}
|
| 194 |
+
- **Top P**: {top_p}
|
| 195 |
+
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 196 |
+
|
| 197 |
+
## Model Information
|
| 198 |
+
|
| 199 |
+
LightOnOCR is a fast, compact OCR model that excels at:
|
| 200 |
+
- β‘ **Production Speed** - 5.71 pages/second on H100 GPU
|
| 201 |
+
- π― **Compact Size** - Only 1B parameters
|
| 202 |
+
- π **LaTeX formulas** - Mathematical notation in LaTeX format
|
| 203 |
+
- π **Tables** - Extracted and formatted as markdown
|
| 204 |
+
- π **Document structure** - Hierarchy and layout preservation
|
| 205 |
+
- π **Multilingual** - Optimized for European languages
|
| 206 |
+
- π€ **Flexible vocabulary** - 151k/32k/16k token variants
|
| 207 |
+
|
| 208 |
+
### Vocabulary Variants
|
| 209 |
+
|
| 210 |
+
- **151k tokens**: Full vocabulary, supports all languages
|
| 211 |
+
- **32k tokens**: European languages optimized (~12% faster decoding)
|
| 212 |
+
- **16k tokens**: European languages optimized (~12% faster decoding)
|
| 213 |
+
|
| 214 |
+
## Dataset Structure
|
| 215 |
+
|
| 216 |
+
The dataset contains all original columns plus:
|
| 217 |
+
- `markdown`: The extracted text in markdown format with LaTeX formulas
|
| 218 |
+
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 219 |
+
|
| 220 |
+
## Usage
|
| 221 |
+
|
| 222 |
+
```python
|
| 223 |
+
from datasets import load_dataset
|
| 224 |
+
import json
|
| 225 |
+
|
| 226 |
+
# Load the dataset
|
| 227 |
+
dataset = load_dataset("{{output_dataset_id}}", split="{split}")
|
| 228 |
+
|
| 229 |
+
# Access the markdown text
|
| 230 |
+
for example in dataset:
|
| 231 |
+
print(example["markdown"])
|
| 232 |
+
break
|
| 233 |
+
|
| 234 |
+
# View all OCR models applied to this dataset
|
| 235 |
+
inference_info = json.loads(dataset[0]["inference_info"])
|
| 236 |
+
for info in inference_info:
|
| 237 |
+
print(f"Column: {{info['column_name']}} - Model: {{info['model_id']}}")
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
## Reproduction
|
| 241 |
+
|
| 242 |
+
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) LightOnOCR script:
|
| 243 |
+
|
| 244 |
+
```bash
|
| 245 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr.py \\
|
| 246 |
+
{source_dataset} \\
|
| 247 |
+
<output-dataset> \\
|
| 248 |
+
--vocab-size {vocab_size} \\
|
| 249 |
+
--image-column {image_column} \\
|
| 250 |
+
--batch-size {batch_size}
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
## Performance
|
| 254 |
+
|
| 255 |
+
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.2f} images/second
|
| 256 |
+
- **Benchmark Score**: 76.1% overall (across diverse document types)
|
| 257 |
+
- **Optimization**: Native resolution ViT + lightweight decoder
|
| 258 |
+
|
| 259 |
+
Generated with π€ [UV Scripts](https://huggingface.co/uv-scripts)
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def main(
|
| 264 |
+
input_dataset: str,
|
| 265 |
+
output_dataset: str,
|
| 266 |
+
image_column: str = "image",
|
| 267 |
+
batch_size: int = 16,
|
| 268 |
+
vocab_size: str = "151k",
|
| 269 |
+
max_model_len: int = 8192,
|
| 270 |
+
max_tokens: int = 6500,
|
| 271 |
+
temperature: float = 0.2,
|
| 272 |
+
top_p: float = 0.9,
|
| 273 |
+
gpu_memory_utilization: float = 0.8,
|
| 274 |
+
target_size: int = 1288,
|
| 275 |
+
no_resize: bool = False,
|
| 276 |
+
hf_token: str = None,
|
| 277 |
+
split: str = "train",
|
| 278 |
+
max_samples: int = None,
|
| 279 |
+
private: bool = False,
|
| 280 |
+
shuffle: bool = False,
|
| 281 |
+
seed: int = 42,
|
| 282 |
+
output_column: str = "markdown",
|
| 283 |
+
):
|
| 284 |
+
"""Process images from HF dataset through LightOnOCR model."""
|
| 285 |
+
|
| 286 |
+
# Check CUDA availability first
|
| 287 |
+
check_cuda_availability()
|
| 288 |
+
|
| 289 |
+
# Track processing start time
|
| 290 |
+
start_time = datetime.now()
|
| 291 |
+
|
| 292 |
+
# Enable HF_TRANSFER for faster downloads
|
| 293 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 294 |
+
|
| 295 |
+
# Login to HF if token provided
|
| 296 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 297 |
+
if HF_TOKEN:
|
| 298 |
+
login(token=HF_TOKEN)
|
| 299 |
+
|
| 300 |
+
# Get model ID from vocabulary size
|
| 301 |
+
if vocab_size not in MODEL_VARIANTS:
|
| 302 |
+
raise ValueError(
|
| 303 |
+
f"Invalid vocab_size '{vocab_size}'. Choose from: {list(MODEL_VARIANTS.keys())}"
|
| 304 |
+
)
|
| 305 |
+
model = MODEL_VARIANTS[vocab_size]
|
| 306 |
+
logger.info(f"Using model: {model} ({vocab_size} vocabulary)")
|
| 307 |
+
|
| 308 |
+
# Load dataset
|
| 309 |
+
logger.info(f"Loading dataset: {input_dataset}")
|
| 310 |
+
dataset = load_dataset(input_dataset, split=split)
|
| 311 |
+
|
| 312 |
+
# Validate image column
|
| 313 |
+
if image_column not in dataset.column_names:
|
| 314 |
+
raise ValueError(
|
| 315 |
+
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
# Shuffle if requested
|
| 319 |
+
if shuffle:
|
| 320 |
+
logger.info(f"Shuffling dataset with seed {seed}")
|
| 321 |
+
dataset = dataset.shuffle(seed=seed)
|
| 322 |
+
|
| 323 |
+
# Limit samples if requested
|
| 324 |
+
if max_samples:
|
| 325 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 326 |
+
logger.info(f"Limited to {len(dataset)} samples")
|
| 327 |
+
|
| 328 |
+
# Initialize vLLM model
|
| 329 |
+
logger.info(f"Initializing vLLM with LightOnOCR")
|
| 330 |
+
logger.info("This may take a few minutes on first run...")
|
| 331 |
+
llm = LLM(
|
| 332 |
+
model=model,
|
| 333 |
+
trust_remote_code=True,
|
| 334 |
+
max_model_len=max_model_len,
|
| 335 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 336 |
+
limit_mm_per_prompt={"image": 1}, # One image per prompt
|
| 337 |
+
enforce_eager=False, # Use torch.compile for better performance
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
# LightOnOCR recommended sampling parameters
|
| 341 |
+
sampling_params = SamplingParams(
|
| 342 |
+
temperature=temperature,
|
| 343 |
+
top_p=top_p,
|
| 344 |
+
max_tokens=max_tokens,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 348 |
+
logger.info(f"Output will be written to column: {output_column}")
|
| 349 |
+
if not no_resize:
|
| 350 |
+
logger.info(f"Images will be resized to {target_size}px (longest dimension)")
|
| 351 |
+
|
| 352 |
+
# Process images in batches
|
| 353 |
+
all_outputs = []
|
| 354 |
+
|
| 355 |
+
for batch_indices in tqdm(
|
| 356 |
+
partition_all(batch_size, range(len(dataset))),
|
| 357 |
+
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 358 |
+
desc="LightOnOCR processing",
|
| 359 |
+
):
|
| 360 |
+
batch_indices = list(batch_indices)
|
| 361 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 362 |
+
|
| 363 |
+
try:
|
| 364 |
+
# Create messages for batch
|
| 365 |
+
batch_messages = [
|
| 366 |
+
make_ocr_message(img, resize=not no_resize, target_size=target_size)
|
| 367 |
+
for img in batch_images
|
| 368 |
+
]
|
| 369 |
+
|
| 370 |
+
# Process with vLLM
|
| 371 |
+
outputs = llm.chat(batch_messages, sampling_params)
|
| 372 |
+
|
| 373 |
+
# Extract outputs
|
| 374 |
+
for output in outputs:
|
| 375 |
+
text = output.outputs[0].text.strip()
|
| 376 |
+
all_outputs.append(text)
|
| 377 |
+
|
| 378 |
+
except Exception as e:
|
| 379 |
+
logger.error(f"Error processing batch: {e}")
|
| 380 |
+
# Add error placeholders for failed batch
|
| 381 |
+
all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
|
| 382 |
+
|
| 383 |
+
# Calculate processing time
|
| 384 |
+
processing_duration = datetime.now() - start_time
|
| 385 |
+
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 386 |
+
|
| 387 |
+
# Add output column to dataset
|
| 388 |
+
logger.info(f"Adding '{output_column}' column to dataset")
|
| 389 |
+
dataset = dataset.add_column(output_column, all_outputs)
|
| 390 |
+
|
| 391 |
+
# Handle inference_info tracking (for multi-model comparisons)
|
| 392 |
+
inference_entry = {
|
| 393 |
+
"model_id": model,
|
| 394 |
+
"model_name": "LightOnOCR",
|
| 395 |
+
"vocab_size": vocab_size,
|
| 396 |
+
"column_name": output_column,
|
| 397 |
+
"timestamp": datetime.now().isoformat(),
|
| 398 |
+
"temperature": temperature,
|
| 399 |
+
"top_p": top_p,
|
| 400 |
+
"max_tokens": max_tokens,
|
| 401 |
+
"target_size": target_size if not no_resize else "original",
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
if "inference_info" in dataset.column_names:
|
| 405 |
+
# Append to existing inference info
|
| 406 |
+
logger.info("Updating existing inference_info column")
|
| 407 |
+
|
| 408 |
+
def update_inference_info(example):
|
| 409 |
+
try:
|
| 410 |
+
existing_info = json.loads(example["inference_info"]) if example["inference_info"] else []
|
| 411 |
+
except (json.JSONDecodeError, TypeError):
|
| 412 |
+
existing_info = []
|
| 413 |
+
|
| 414 |
+
existing_info.append(inference_entry)
|
| 415 |
+
return {"inference_info": json.dumps(existing_info)}
|
| 416 |
+
|
| 417 |
+
dataset = dataset.map(update_inference_info)
|
| 418 |
+
else:
|
| 419 |
+
# Create new inference_info column
|
| 420 |
+
logger.info("Creating new inference_info column")
|
| 421 |
+
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 422 |
+
dataset = dataset.add_column("inference_info", inference_list)
|
| 423 |
+
|
| 424 |
+
# Push to hub
|
| 425 |
+
logger.info(f"Pushing to {output_dataset}")
|
| 426 |
+
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 427 |
+
|
| 428 |
+
# Create and push dataset card
|
| 429 |
+
logger.info("Creating dataset card")
|
| 430 |
+
card_content = create_dataset_card(
|
| 431 |
+
source_dataset=input_dataset,
|
| 432 |
+
model=model,
|
| 433 |
+
vocab_size=vocab_size,
|
| 434 |
+
num_samples=len(dataset),
|
| 435 |
+
processing_time=processing_time_str,
|
| 436 |
+
batch_size=batch_size,
|
| 437 |
+
max_model_len=max_model_len,
|
| 438 |
+
max_tokens=max_tokens,
|
| 439 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 440 |
+
temperature=temperature,
|
| 441 |
+
top_p=top_p,
|
| 442 |
+
target_size=target_size,
|
| 443 |
+
image_column=image_column,
|
| 444 |
+
split=split,
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
card = DatasetCard(card_content)
|
| 448 |
+
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 449 |
+
|
| 450 |
+
logger.info("β
LightOnOCR processing complete!")
|
| 451 |
+
logger.info(f"Dataset available at: https://huggingface.co/datasets/{output_dataset}")
|
| 452 |
+
logger.info(f"Processing time: {processing_time_str}")
|
| 453 |
+
logger.info(f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec")
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
if __name__ == "__main__":
|
| 457 |
+
# Show example usage if no arguments
|
| 458 |
+
if len(sys.argv) == 1:
|
| 459 |
+
print("=" * 80)
|
| 460 |
+
print("LightOnOCR Document Processing")
|
| 461 |
+
print("=" * 80)
|
| 462 |
+
print("\nFast, compact 1B OCR model for production workloads")
|
| 463 |
+
print("\nFeatures:")
|
| 464 |
+
print("- β‘ Fastest processing: 5.71 pages/sec on H100")
|
| 465 |
+
print("- π― Compact: Only 1B parameters")
|
| 466 |
+
print("- π Multilingual with European language optimization")
|
| 467 |
+
print("- π LaTeX formula recognition")
|
| 468 |
+
print("- π Table extraction (markdown format)")
|
| 469 |
+
print("- π€ 3 vocabulary sizes for speed/quality tradeoffs")
|
| 470 |
+
print("\nExample usage:")
|
| 471 |
+
print("\n1. Basic OCR (full vocabulary):")
|
| 472 |
+
print(" uv run lighton-ocr.py input-dataset output-dataset")
|
| 473 |
+
print("\n2. European languages optimized (faster):")
|
| 474 |
+
print(" uv run lighton-ocr.py docs results --vocab-size 32k")
|
| 475 |
+
print("\n3. Custom batch size for performance:")
|
| 476 |
+
print(" uv run lighton-ocr.py docs results --batch-size 32")
|
| 477 |
+
print("\n4. Test with small sample:")
|
| 478 |
+
print(" uv run lighton-ocr.py large-dataset test --max-samples 50 --shuffle")
|
| 479 |
+
print("\n5. Original image size (no resize):")
|
| 480 |
+
print(" uv run lighton-ocr.py docs output --no-resize")
|
| 481 |
+
print("\n6. Running on HF Jobs:")
|
| 482 |
+
print(" hf jobs uv run --flavor l4x1 \\")
|
| 483 |
+
print(" -e HF_TOKEN=$(python3 -c \"from huggingface_hub import get_token; print(get_token())\") \\")
|
| 484 |
+
print(" -e HF_HUB_ENABLE_HF_TRANSFER=1 \\")
|
| 485 |
+
print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr.py \\")
|
| 486 |
+
print(" input-dataset output-dataset --vocab-size 32k")
|
| 487 |
+
print("\n" + "=" * 80)
|
| 488 |
+
print("\nVocabulary Size Options:")
|
| 489 |
+
print(" 151k - Full vocabulary (all languages)")
|
| 490 |
+
print(" 32k - European languages (~12% faster)")
|
| 491 |
+
print(" 16k - European languages (~12% faster)")
|
| 492 |
+
print("\nFor full help, run: uv run lighton-ocr.py --help")
|
| 493 |
+
sys.exit(0)
|
| 494 |
+
|
| 495 |
+
parser = argparse.ArgumentParser(
|
| 496 |
+
description="Document OCR using LightOnOCR (fast 1B model)",
|
| 497 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 498 |
+
epilog="""
|
| 499 |
+
Vocabulary Size Options:
|
| 500 |
+
151k Full vocabulary supporting all languages (default)
|
| 501 |
+
32k European languages optimized (~12% faster decoding)
|
| 502 |
+
16k European languages optimized (~12% faster decoding)
|
| 503 |
+
|
| 504 |
+
Examples:
|
| 505 |
+
# Basic text OCR with full vocabulary
|
| 506 |
+
uv run lighton-ocr.py my-docs analyzed-docs
|
| 507 |
+
|
| 508 |
+
# Fast processing for European languages
|
| 509 |
+
uv run lighton-ocr.py papers results --vocab-size 32k
|
| 510 |
+
|
| 511 |
+
# Test with random sampling
|
| 512 |
+
uv run lighton-ocr.py large-dataset test --max-samples 50 --shuffle
|
| 513 |
+
|
| 514 |
+
# Custom batch size for GPU optimization
|
| 515 |
+
uv run lighton-ocr.py dataset output --batch-size 32 --gpu-memory-utilization 0.9
|
| 516 |
+
""",
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 520 |
+
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 521 |
+
parser.add_argument(
|
| 522 |
+
"--image-column",
|
| 523 |
+
default="image",
|
| 524 |
+
help="Column containing images (default: image)",
|
| 525 |
+
)
|
| 526 |
+
parser.add_argument(
|
| 527 |
+
"--batch-size",
|
| 528 |
+
type=int,
|
| 529 |
+
default=16,
|
| 530 |
+
help="Batch size for processing (default: 16)",
|
| 531 |
+
)
|
| 532 |
+
parser.add_argument(
|
| 533 |
+
"--vocab-size",
|
| 534 |
+
default="151k",
|
| 535 |
+
choices=list(MODEL_VARIANTS.keys()),
|
| 536 |
+
help="Vocabulary size variant (default: 151k)",
|
| 537 |
+
)
|
| 538 |
+
parser.add_argument(
|
| 539 |
+
"--max-model-len",
|
| 540 |
+
type=int,
|
| 541 |
+
default=8192,
|
| 542 |
+
help="Maximum model context length (default: 8192)",
|
| 543 |
+
)
|
| 544 |
+
parser.add_argument(
|
| 545 |
+
"--max-tokens",
|
| 546 |
+
type=int,
|
| 547 |
+
default=6500,
|
| 548 |
+
help="Maximum tokens to generate (default: 6500)",
|
| 549 |
+
)
|
| 550 |
+
parser.add_argument(
|
| 551 |
+
"--temperature",
|
| 552 |
+
type=float,
|
| 553 |
+
default=0.2,
|
| 554 |
+
help="Sampling temperature (default: 0.2)",
|
| 555 |
+
)
|
| 556 |
+
parser.add_argument(
|
| 557 |
+
"--top-p",
|
| 558 |
+
type=float,
|
| 559 |
+
default=0.9,
|
| 560 |
+
help="Top-p sampling parameter (default: 0.9)",
|
| 561 |
+
)
|
| 562 |
+
parser.add_argument(
|
| 563 |
+
"--gpu-memory-utilization",
|
| 564 |
+
type=float,
|
| 565 |
+
default=0.8,
|
| 566 |
+
help="GPU memory utilization (default: 0.8)",
|
| 567 |
+
)
|
| 568 |
+
parser.add_argument(
|
| 569 |
+
"--target-size",
|
| 570 |
+
type=int,
|
| 571 |
+
default=1288,
|
| 572 |
+
help="Target size for longest image dimension in pixels (default: 1288)",
|
| 573 |
+
)
|
| 574 |
+
parser.add_argument(
|
| 575 |
+
"--no-resize",
|
| 576 |
+
action="store_true",
|
| 577 |
+
help="Don't resize images (use original size)",
|
| 578 |
+
)
|
| 579 |
+
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 580 |
+
parser.add_argument(
|
| 581 |
+
"--split", default="train", help="Dataset split to use (default: train)"
|
| 582 |
+
)
|
| 583 |
+
parser.add_argument(
|
| 584 |
+
"--max-samples",
|
| 585 |
+
type=int,
|
| 586 |
+
help="Maximum number of samples to process (for testing)",
|
| 587 |
+
)
|
| 588 |
+
parser.add_argument(
|
| 589 |
+
"--private", action="store_true", help="Make output dataset private"
|
| 590 |
+
)
|
| 591 |
+
parser.add_argument(
|
| 592 |
+
"--shuffle", action="store_true", help="Shuffle dataset before processing"
|
| 593 |
+
)
|
| 594 |
+
parser.add_argument(
|
| 595 |
+
"--seed",
|
| 596 |
+
type=int,
|
| 597 |
+
default=42,
|
| 598 |
+
help="Random seed for shuffling (default: 42)",
|
| 599 |
+
)
|
| 600 |
+
parser.add_argument(
|
| 601 |
+
"--output-column",
|
| 602 |
+
default="markdown",
|
| 603 |
+
help="Column name for output text (default: markdown)",
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
args = parser.parse_args()
|
| 607 |
+
|
| 608 |
+
main(
|
| 609 |
+
input_dataset=args.input_dataset,
|
| 610 |
+
output_dataset=args.output_dataset,
|
| 611 |
+
image_column=args.image_column,
|
| 612 |
+
batch_size=args.batch_size,
|
| 613 |
+
vocab_size=args.vocab_size,
|
| 614 |
+
max_model_len=args.max_model_len,
|
| 615 |
+
max_tokens=args.max_tokens,
|
| 616 |
+
temperature=args.temperature,
|
| 617 |
+
top_p=args.top_p,
|
| 618 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 619 |
+
target_size=args.target_size,
|
| 620 |
+
no_resize=args.no_resize,
|
| 621 |
+
hf_token=args.hf_token,
|
| 622 |
+
split=args.split,
|
| 623 |
+
max_samples=args.max_samples,
|
| 624 |
+
private=args.private,
|
| 625 |
+
shuffle=args.shuffle,
|
| 626 |
+
seed=args.seed,
|
| 627 |
+
output_column=args.output_column,
|
| 628 |
+
)
|