Commit
ยท
43324c8
1
Parent(s):
cea7723
Add RolmOCR script and enhance OCR scripts with new features
Browse files- Add rolm-ocr.py: Fast general-purpose OCR using reducto/RolmOCR
- Add inference_info tracking to all OCR scripts for multi-model comparison
- Add --shuffle and --seed flags for random sampling
- Add automatic dataset card generation with processing details
- Update README.md with new script documentation and feature descriptions
- Dynamic column naming for RolmOCR (e.g., rolmocr_text)
These enhancements support iterative model comparison workflows and better sampling strategies for OCR evaluation.
- README.md +65 -5
- nanonets-ocr.py +201 -2
- rolm-ocr.py +517 -0
README.md
CHANGED
|
@@ -30,6 +30,16 @@ That's it! The script will:
|
|
| 30 |
|
| 31 |
## ๐ Available Scripts
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
### Nanonets OCR (`nanonets-ocr.py`)
|
| 34 |
|
| 35 |
State-of-the-art document OCR using [nanonets/Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) that handles:
|
|
@@ -50,6 +60,43 @@ Advanced document layout analysis and OCR using [rednote-hilab/dots.ocr](https:/
|
|
| 50 |
- ๐ **Multilingual support** - Handles multiple languages seamlessly
|
| 51 |
- ๐ง **Flexible output** - JSON, structured columns, or markdown
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
## ๐ป Usage Examples
|
| 54 |
|
| 55 |
### Run on HuggingFace Jobs (Recommended)
|
|
@@ -115,6 +162,10 @@ uv run nanonets-ocr.py input-dataset output-dataset
|
|
| 115 |
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
|
| 116 |
input-dataset output-dataset
|
| 117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
# dots.ocr examples
|
| 119 |
uv run dots-ocr.py documents analyzed-docs # Full layout + OCR
|
| 120 |
uv run dots-ocr.py scans layouts --mode layout-only # Layout only
|
|
@@ -127,20 +178,29 @@ Any HuggingFace dataset containing images - documents, forms, receipts, books, h
|
|
| 127 |
|
| 128 |
## ๐๏ธ Configuration Options
|
| 129 |
|
| 130 |
-
### Common Options (
|
| 131 |
|
| 132 |
| Option | Default | Description |
|
| 133 |
| -------------------------- | ------- | ----------------------------- |
|
| 134 |
| `--image-column` | `image` | Column containing images |
|
| 135 |
-
| `--batch-size` | `32
|
| 136 |
-
| `--max-model-len` | `8192`/`24000
|
| 137 |
-
| `--max-tokens` | `4096`/`16384
|
| 138 |
| `--gpu-memory-utilization` | `0.8` | GPU memory usage (0.0-1.0) |
|
| 139 |
| `--split` | `train` | Dataset split to process |
|
| 140 |
| `--max-samples` | None | Limit samples (for testing) |
|
| 141 |
| `--private` | False | Make output dataset private |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
|
|
|
|
| 144 |
|
| 145 |
### dots.ocr Specific Options
|
| 146 |
|
|
|
|
| 30 |
|
| 31 |
## ๐ Available Scripts
|
| 32 |
|
| 33 |
+
### RolmOCR (`rolm-ocr.py`)
|
| 34 |
+
|
| 35 |
+
Fast general-purpose OCR using [reducto/RolmOCR](https://huggingface.co/reducto/RolmOCR) based on Qwen2.5-VL-7B:
|
| 36 |
+
|
| 37 |
+
- ๐ **Fast extraction** - Optimized for speed and efficiency
|
| 38 |
+
- ๐ **Plain text output** - Clean, natural text representation
|
| 39 |
+
- ๐ช **General-purpose** - Works well on various document types
|
| 40 |
+
- ๐ฅ **Large context** - Handles up to 16K tokens
|
| 41 |
+
- โก **Batch optimized** - Efficient processing with vLLM
|
| 42 |
+
|
| 43 |
### Nanonets OCR (`nanonets-ocr.py`)
|
| 44 |
|
| 45 |
State-of-the-art document OCR using [nanonets/Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) that handles:
|
|
|
|
| 60 |
- ๐ **Multilingual support** - Handles multiple languages seamlessly
|
| 61 |
- ๐ง **Flexible output** - JSON, structured columns, or markdown
|
| 62 |
|
| 63 |
+
## ๐ New Features
|
| 64 |
+
|
| 65 |
+
### Multi-Model Comparison Support
|
| 66 |
+
|
| 67 |
+
All scripts now include `inference_info` tracking for comparing multiple OCR models:
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
# First model
|
| 71 |
+
uv run rolm-ocr.py my-dataset my-dataset --max-samples 100
|
| 72 |
+
|
| 73 |
+
# Second model (appends to same dataset)
|
| 74 |
+
uv run nanonets-ocr.py my-dataset my-dataset --max-samples 100
|
| 75 |
+
|
| 76 |
+
# View all models used
|
| 77 |
+
python -c "import json; from datasets import load_dataset; ds = load_dataset('my-dataset'); print(json.loads(ds[0]['inference_info']))"
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
### Random Sampling
|
| 81 |
+
|
| 82 |
+
Get representative samples with the new `--shuffle` flag:
|
| 83 |
+
|
| 84 |
+
```bash
|
| 85 |
+
# Random 50 samples instead of first 50
|
| 86 |
+
uv run rolm-ocr.py ordered-dataset output --max-samples 50 --shuffle
|
| 87 |
+
|
| 88 |
+
# Reproducible random sampling
|
| 89 |
+
uv run nanonets-ocr.py dataset output --max-samples 100 --shuffle --seed 42
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
### Automatic Dataset Cards
|
| 93 |
+
|
| 94 |
+
Every OCR run now generates comprehensive dataset documentation including:
|
| 95 |
+
- Model configuration and parameters
|
| 96 |
+
- Processing statistics
|
| 97 |
+
- Column descriptions
|
| 98 |
+
- Reproduction instructions
|
| 99 |
+
|
| 100 |
## ๐ป Usage Examples
|
| 101 |
|
| 102 |
### Run on HuggingFace Jobs (Recommended)
|
|
|
|
| 162 |
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
|
| 163 |
input-dataset output-dataset
|
| 164 |
|
| 165 |
+
# RolmOCR for fast text extraction
|
| 166 |
+
uv run rolm-ocr.py documents extracted-text
|
| 167 |
+
uv run rolm-ocr.py images texts --shuffle --max-samples 100 # Random sample
|
| 168 |
+
|
| 169 |
# dots.ocr examples
|
| 170 |
uv run dots-ocr.py documents analyzed-docs # Full layout + OCR
|
| 171 |
uv run dots-ocr.py scans layouts --mode layout-only # Layout only
|
|
|
|
| 178 |
|
| 179 |
## ๐๏ธ Configuration Options
|
| 180 |
|
| 181 |
+
### Common Options (All Scripts)
|
| 182 |
|
| 183 |
| Option | Default | Description |
|
| 184 |
| -------------------------- | ------- | ----------------------------- |
|
| 185 |
| `--image-column` | `image` | Column containing images |
|
| 186 |
+
| `--batch-size` | `32`/`16`* | Images processed together |
|
| 187 |
+
| `--max-model-len` | `8192`/`16384`**/`24000`*** | Max context length |
|
| 188 |
+
| `--max-tokens` | `4096`/`8192`**/`16384`*** | Max output tokens |
|
| 189 |
| `--gpu-memory-utilization` | `0.8` | GPU memory usage (0.0-1.0) |
|
| 190 |
| `--split` | `train` | Dataset split to process |
|
| 191 |
| `--max-samples` | None | Limit samples (for testing) |
|
| 192 |
| `--private` | False | Make output dataset private |
|
| 193 |
+
| `--shuffle` | False | Shuffle dataset before processing |
|
| 194 |
+
| `--seed` | `42` | Random seed for shuffling |
|
| 195 |
+
|
| 196 |
+
*RolmOCR uses batch size 16
|
| 197 |
+
**RolmOCR uses 16384/8192
|
| 198 |
+
***dots.ocr uses 24000/16384
|
| 199 |
+
|
| 200 |
+
### RolmOCR Specific
|
| 201 |
|
| 202 |
+
- Output column is auto-generated from model name (e.g., `rolmocr_text`)
|
| 203 |
+
- Use `--output-column` to override the default name
|
| 204 |
|
| 205 |
### dots.ocr Specific Options
|
| 206 |
|
nanonets-ocr.py
CHANGED
|
@@ -28,6 +28,7 @@ Features:
|
|
| 28 |
import argparse
|
| 29 |
import base64
|
| 30 |
import io
|
|
|
|
| 31 |
import logging
|
| 32 |
import os
|
| 33 |
import sys
|
|
@@ -35,11 +36,12 @@ from typing import Any, Dict, List, Union
|
|
| 35 |
|
| 36 |
import torch
|
| 37 |
from datasets import load_dataset
|
| 38 |
-
from huggingface_hub import login
|
| 39 |
from PIL import Image
|
| 40 |
from toolz import partition_all
|
| 41 |
from tqdm.auto import tqdm
|
| 42 |
from vllm import LLM, SamplingParams
|
|
|
|
| 43 |
|
| 44 |
logging.basicConfig(level=logging.INFO)
|
| 45 |
logger = logging.getLogger(__name__)
|
|
@@ -87,6 +89,115 @@ def make_ocr_message(
|
|
| 87 |
]
|
| 88 |
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
def main(
|
| 91 |
input_dataset: str,
|
| 92 |
output_dataset: str,
|
|
@@ -100,11 +211,16 @@ def main(
|
|
| 100 |
split: str = "train",
|
| 101 |
max_samples: int = None,
|
| 102 |
private: bool = False,
|
|
|
|
|
|
|
| 103 |
):
|
| 104 |
"""Process images from HF dataset through OCR model."""
|
| 105 |
|
| 106 |
# Check CUDA availability first
|
| 107 |
check_cuda_availability()
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
# Enable HF_TRANSFER for faster downloads
|
| 110 |
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
|
@@ -124,6 +240,11 @@ def main(
|
|
| 124 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 125 |
)
|
| 126 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
# Limit samples if requested
|
| 128 |
if max_samples:
|
| 129 |
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
|
@@ -178,10 +299,70 @@ def main(
|
|
| 178 |
# Add markdown column to dataset
|
| 179 |
logger.info("Adding markdown column to dataset")
|
| 180 |
dataset = dataset.add_column("markdown", all_markdown)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
# Push to hub
|
| 183 |
logger.info(f"Pushing to {output_dataset}")
|
| 184 |
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
logger.info("โ
OCR conversion complete!")
|
| 187 |
logger.info(
|
|
@@ -212,7 +393,9 @@ if __name__ == "__main__":
|
|
| 212 |
print(" --gpu-memory-utilization 0.8")
|
| 213 |
print("\n3. Process a subset for testing:")
|
| 214 |
print(" uv run nanonets-ocr.py large-dataset test-output --max-samples 10")
|
| 215 |
-
print("\n4.
|
|
|
|
|
|
|
| 216 |
print(" hfjobs run \\")
|
| 217 |
print(" --flavor l4x1 \\")
|
| 218 |
print(" --secret HF_TOKEN=... \\")
|
|
@@ -238,6 +421,9 @@ Examples:
|
|
| 238 |
|
| 239 |
# Process subset for testing
|
| 240 |
uv run nanonets-ocr.py large-dataset test-output --max-samples 100
|
|
|
|
|
|
|
|
|
|
| 241 |
""",
|
| 242 |
)
|
| 243 |
|
|
@@ -289,6 +475,17 @@ Examples:
|
|
| 289 |
parser.add_argument(
|
| 290 |
"--private", action="store_true", help="Make output dataset private"
|
| 291 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
args = parser.parse_args()
|
| 294 |
|
|
@@ -305,4 +502,6 @@ Examples:
|
|
| 305 |
split=args.split,
|
| 306 |
max_samples=args.max_samples,
|
| 307 |
private=args.private,
|
|
|
|
|
|
|
| 308 |
)
|
|
|
|
| 28 |
import argparse
|
| 29 |
import base64
|
| 30 |
import io
|
| 31 |
+
import json
|
| 32 |
import logging
|
| 33 |
import os
|
| 34 |
import sys
|
|
|
|
| 36 |
|
| 37 |
import torch
|
| 38 |
from datasets import load_dataset
|
| 39 |
+
from huggingface_hub import DatasetCard, login
|
| 40 |
from PIL import Image
|
| 41 |
from toolz import partition_all
|
| 42 |
from tqdm.auto import tqdm
|
| 43 |
from vllm import LLM, SamplingParams
|
| 44 |
+
from datetime import datetime
|
| 45 |
|
| 46 |
logging.basicConfig(level=logging.INFO)
|
| 47 |
logger = logging.getLogger(__name__)
|
|
|
|
| 89 |
]
|
| 90 |
|
| 91 |
|
| 92 |
+
def create_dataset_card(
|
| 93 |
+
source_dataset: str,
|
| 94 |
+
model: str,
|
| 95 |
+
num_samples: int,
|
| 96 |
+
processing_time: str,
|
| 97 |
+
batch_size: int,
|
| 98 |
+
max_model_len: int,
|
| 99 |
+
max_tokens: int,
|
| 100 |
+
gpu_memory_utilization: float,
|
| 101 |
+
image_column: str = "image",
|
| 102 |
+
split: str = "train",
|
| 103 |
+
) -> str:
|
| 104 |
+
"""Create a dataset card documenting the OCR process."""
|
| 105 |
+
model_name = model.split("/")[-1]
|
| 106 |
+
|
| 107 |
+
return f"""---
|
| 108 |
+
viewer: false
|
| 109 |
+
tags:
|
| 110 |
+
- ocr
|
| 111 |
+
- document-processing
|
| 112 |
+
- nanonets
|
| 113 |
+
- markdown
|
| 114 |
+
- uv-script
|
| 115 |
+
- generated
|
| 116 |
+
---
|
| 117 |
+
|
| 118 |
+
# Document OCR using {model_name}
|
| 119 |
+
|
| 120 |
+
This dataset contains markdown-formatted OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using Nanonets-OCR-s.
|
| 121 |
+
|
| 122 |
+
## Processing Details
|
| 123 |
+
|
| 124 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 125 |
+
- **Model**: [{model}](https://huggingface.co/{model})
|
| 126 |
+
- **Number of Samples**: {num_samples:,}
|
| 127 |
+
- **Processing Time**: {processing_time}
|
| 128 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 129 |
+
|
| 130 |
+
### Configuration
|
| 131 |
+
|
| 132 |
+
- **Image Column**: `{image_column}`
|
| 133 |
+
- **Output Column**: `markdown`
|
| 134 |
+
- **Dataset Split**: `{split}`
|
| 135 |
+
- **Batch Size**: {batch_size}
|
| 136 |
+
- **Max Model Length**: {max_model_len:,} tokens
|
| 137 |
+
- **Max Output Tokens**: {max_tokens:,}
|
| 138 |
+
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 139 |
+
|
| 140 |
+
## Model Information
|
| 141 |
+
|
| 142 |
+
Nanonets-OCR-s is a state-of-the-art document OCR model that excels at:
|
| 143 |
+
- ๐ **LaTeX equations** - Mathematical formulas preserved in LaTeX format
|
| 144 |
+
- ๐ **Tables** - Extracted and formatted as HTML
|
| 145 |
+
- ๐ **Document structure** - Headers, lists, and formatting maintained
|
| 146 |
+
- ๐ผ๏ธ **Images** - Captions and descriptions included in `<img>` tags
|
| 147 |
+
- โ๏ธ **Forms** - Checkboxes rendered as โ/โ
|
| 148 |
+
- ๐ **Watermarks** - Wrapped in `<watermark>` tags
|
| 149 |
+
- ๐ **Page numbers** - Wrapped in `<page_number>` tags
|
| 150 |
+
|
| 151 |
+
## Dataset Structure
|
| 152 |
+
|
| 153 |
+
The dataset contains all original columns plus:
|
| 154 |
+
- `markdown`: The extracted text in markdown format with preserved structure
|
| 155 |
+
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 156 |
+
|
| 157 |
+
## Usage
|
| 158 |
+
|
| 159 |
+
```python
|
| 160 |
+
from datasets import load_dataset
|
| 161 |
+
import json
|
| 162 |
+
|
| 163 |
+
# Load the dataset
|
| 164 |
+
dataset = load_dataset("{{output_dataset_id}}", split="{split}")
|
| 165 |
+
|
| 166 |
+
# Access the markdown text
|
| 167 |
+
for example in dataset:
|
| 168 |
+
print(example["markdown"])
|
| 169 |
+
break
|
| 170 |
+
|
| 171 |
+
# View all OCR models applied to this dataset
|
| 172 |
+
inference_info = json.loads(dataset[0]["inference_info"])
|
| 173 |
+
for info in inference_info:
|
| 174 |
+
print(f"Column: {{info['column_name']}} - Model: {{info['model_id']}}")
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
## Reproduction
|
| 178 |
+
|
| 179 |
+
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) Nanonets OCR script:
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \\
|
| 183 |
+
{source_dataset} \\
|
| 184 |
+
<output-dataset> \\
|
| 185 |
+
--image-column {image_column} \\
|
| 186 |
+
--batch-size {batch_size} \\
|
| 187 |
+
--max-model-len {max_model_len} \\
|
| 188 |
+
--max-tokens {max_tokens} \\
|
| 189 |
+
--gpu-memory-utilization {gpu_memory_utilization}
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
## Performance
|
| 193 |
+
|
| 194 |
+
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
|
| 195 |
+
- **GPU Configuration**: vLLM with {gpu_memory_utilization:.0%} GPU memory utilization
|
| 196 |
+
|
| 197 |
+
Generated with ๐ค [UV Scripts](https://huggingface.co/uv-scripts)
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
|
| 201 |
def main(
|
| 202 |
input_dataset: str,
|
| 203 |
output_dataset: str,
|
|
|
|
| 211 |
split: str = "train",
|
| 212 |
max_samples: int = None,
|
| 213 |
private: bool = False,
|
| 214 |
+
shuffle: bool = False,
|
| 215 |
+
seed: int = 42,
|
| 216 |
):
|
| 217 |
"""Process images from HF dataset through OCR model."""
|
| 218 |
|
| 219 |
# Check CUDA availability first
|
| 220 |
check_cuda_availability()
|
| 221 |
+
|
| 222 |
+
# Track processing start time
|
| 223 |
+
start_time = datetime.now()
|
| 224 |
|
| 225 |
# Enable HF_TRANSFER for faster downloads
|
| 226 |
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
|
|
|
| 240 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 241 |
)
|
| 242 |
|
| 243 |
+
# Shuffle if requested
|
| 244 |
+
if shuffle:
|
| 245 |
+
logger.info(f"Shuffling dataset with seed {seed}")
|
| 246 |
+
dataset = dataset.shuffle(seed=seed)
|
| 247 |
+
|
| 248 |
# Limit samples if requested
|
| 249 |
if max_samples:
|
| 250 |
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
|
|
|
| 299 |
# Add markdown column to dataset
|
| 300 |
logger.info("Adding markdown column to dataset")
|
| 301 |
dataset = dataset.add_column("markdown", all_markdown)
|
| 302 |
+
|
| 303 |
+
# Handle inference_info tracking
|
| 304 |
+
logger.info("Updating inference_info...")
|
| 305 |
+
|
| 306 |
+
# Check for existing inference_info
|
| 307 |
+
if "inference_info" in dataset.column_names:
|
| 308 |
+
# Parse existing info from first row (all rows have same info)
|
| 309 |
+
try:
|
| 310 |
+
existing_info = json.loads(dataset[0]["inference_info"])
|
| 311 |
+
if not isinstance(existing_info, list):
|
| 312 |
+
existing_info = [existing_info] # Convert old format to list
|
| 313 |
+
except (json.JSONDecodeError, TypeError):
|
| 314 |
+
existing_info = []
|
| 315 |
+
# Remove old column to update it
|
| 316 |
+
dataset = dataset.remove_columns(["inference_info"])
|
| 317 |
+
else:
|
| 318 |
+
existing_info = []
|
| 319 |
+
|
| 320 |
+
# Add new inference info
|
| 321 |
+
new_info = {
|
| 322 |
+
"column_name": "markdown",
|
| 323 |
+
"model_id": model,
|
| 324 |
+
"processing_date": datetime.now().isoformat(),
|
| 325 |
+
"batch_size": batch_size,
|
| 326 |
+
"max_tokens": max_tokens,
|
| 327 |
+
"gpu_memory_utilization": gpu_memory_utilization,
|
| 328 |
+
"max_model_len": max_model_len,
|
| 329 |
+
"script": "nanonets-ocr.py",
|
| 330 |
+
"script_version": "1.0.0",
|
| 331 |
+
"script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py"
|
| 332 |
+
}
|
| 333 |
+
existing_info.append(new_info)
|
| 334 |
+
|
| 335 |
+
# Add updated inference_info column
|
| 336 |
+
info_json = json.dumps(existing_info, ensure_ascii=False)
|
| 337 |
+
dataset = dataset.add_column("inference_info", [info_json] * len(dataset))
|
| 338 |
|
| 339 |
# Push to hub
|
| 340 |
logger.info(f"Pushing to {output_dataset}")
|
| 341 |
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 342 |
+
|
| 343 |
+
# Calculate processing time
|
| 344 |
+
end_time = datetime.now()
|
| 345 |
+
processing_duration = end_time - start_time
|
| 346 |
+
processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
|
| 347 |
+
|
| 348 |
+
# Create and push dataset card
|
| 349 |
+
logger.info("Creating dataset card...")
|
| 350 |
+
card_content = create_dataset_card(
|
| 351 |
+
source_dataset=input_dataset,
|
| 352 |
+
model=model,
|
| 353 |
+
num_samples=len(dataset),
|
| 354 |
+
processing_time=processing_time,
|
| 355 |
+
batch_size=batch_size,
|
| 356 |
+
max_model_len=max_model_len,
|
| 357 |
+
max_tokens=max_tokens,
|
| 358 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 359 |
+
image_column=image_column,
|
| 360 |
+
split=split,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
card = DatasetCard(card_content)
|
| 364 |
+
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 365 |
+
logger.info("โ
Dataset card created and pushed!")
|
| 366 |
|
| 367 |
logger.info("โ
OCR conversion complete!")
|
| 368 |
logger.info(
|
|
|
|
| 393 |
print(" --gpu-memory-utilization 0.8")
|
| 394 |
print("\n3. Process a subset for testing:")
|
| 395 |
print(" uv run nanonets-ocr.py large-dataset test-output --max-samples 10")
|
| 396 |
+
print("\n4. Random sample from ordered dataset:")
|
| 397 |
+
print(" uv run nanonets-ocr.py ordered-dataset random-test --max-samples 50 --shuffle")
|
| 398 |
+
print("\n5. Running on HF Jobs:")
|
| 399 |
print(" hfjobs run \\")
|
| 400 |
print(" --flavor l4x1 \\")
|
| 401 |
print(" --secret HF_TOKEN=... \\")
|
|
|
|
| 421 |
|
| 422 |
# Process subset for testing
|
| 423 |
uv run nanonets-ocr.py large-dataset test-output --max-samples 100
|
| 424 |
+
|
| 425 |
+
# Random sample from ordered dataset
|
| 426 |
+
uv run nanonets-ocr.py ordered-dataset random-sample --max-samples 50 --shuffle
|
| 427 |
""",
|
| 428 |
)
|
| 429 |
|
|
|
|
| 475 |
parser.add_argument(
|
| 476 |
"--private", action="store_true", help="Make output dataset private"
|
| 477 |
)
|
| 478 |
+
parser.add_argument(
|
| 479 |
+
"--shuffle",
|
| 480 |
+
action="store_true",
|
| 481 |
+
help="Shuffle the dataset before processing (useful for random sampling)",
|
| 482 |
+
)
|
| 483 |
+
parser.add_argument(
|
| 484 |
+
"--seed",
|
| 485 |
+
type=int,
|
| 486 |
+
default=42,
|
| 487 |
+
help="Random seed for shuffling (default: 42)",
|
| 488 |
+
)
|
| 489 |
|
| 490 |
args = parser.parse_args()
|
| 491 |
|
|
|
|
| 502 |
split=args.split,
|
| 503 |
max_samples=args.max_samples,
|
| 504 |
private=args.private,
|
| 505 |
+
shuffle=args.shuffle,
|
| 506 |
+
seed=args.seed,
|
| 507 |
)
|
rolm-ocr.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# ]
|
| 12 |
+
#
|
| 13 |
+
# ///
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
Extract text from document images using RolmOCR with vLLM.
|
| 17 |
+
|
| 18 |
+
This script processes images through the RolmOCR model to extract
|
| 19 |
+
plain text content, ideal for general-purpose OCR tasks.
|
| 20 |
+
|
| 21 |
+
Features:
|
| 22 |
+
- Fast and efficient text extraction
|
| 23 |
+
- General-purpose document OCR
|
| 24 |
+
- Based on Qwen2.5-VL-7B architecture
|
| 25 |
+
- Optimized for batch processing with vLLM
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import base64
|
| 30 |
+
import io
|
| 31 |
+
import json
|
| 32 |
+
import logging
|
| 33 |
+
import os
|
| 34 |
+
import sys
|
| 35 |
+
from typing import Any, Dict, List, Union
|
| 36 |
+
|
| 37 |
+
import torch
|
| 38 |
+
from datasets import load_dataset
|
| 39 |
+
from huggingface_hub import DatasetCard, login
|
| 40 |
+
from PIL import Image
|
| 41 |
+
from toolz import partition_all
|
| 42 |
+
from tqdm.auto import tqdm
|
| 43 |
+
from vllm import LLM, SamplingParams
|
| 44 |
+
from datetime import datetime
|
| 45 |
+
|
| 46 |
+
logging.basicConfig(level=logging.INFO)
|
| 47 |
+
logger = logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def check_cuda_availability():
|
| 51 |
+
"""Check if CUDA is available and exit if not."""
|
| 52 |
+
if not torch.cuda.is_available():
|
| 53 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 54 |
+
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 55 |
+
sys.exit(1)
|
| 56 |
+
else:
|
| 57 |
+
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def make_ocr_message(
|
| 61 |
+
image: Union[Image.Image, Dict[str, Any], str],
|
| 62 |
+
prompt: str = "Return the plain text representation of this document as if you were reading it naturally.\n",
|
| 63 |
+
) -> List[Dict]:
|
| 64 |
+
"""Create chat message for OCR processing."""
|
| 65 |
+
# Convert to PIL Image if needed
|
| 66 |
+
if isinstance(image, Image.Image):
|
| 67 |
+
pil_img = image
|
| 68 |
+
elif isinstance(image, dict) and "bytes" in image:
|
| 69 |
+
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 70 |
+
elif isinstance(image, str):
|
| 71 |
+
pil_img = Image.open(image)
|
| 72 |
+
else:
|
| 73 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 74 |
+
|
| 75 |
+
# Convert to base64 data URI
|
| 76 |
+
buf = io.BytesIO()
|
| 77 |
+
pil_img.save(buf, format="PNG")
|
| 78 |
+
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 79 |
+
|
| 80 |
+
# Return message in vLLM format
|
| 81 |
+
return [
|
| 82 |
+
{
|
| 83 |
+
"role": "user",
|
| 84 |
+
"content": [
|
| 85 |
+
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 86 |
+
{"type": "text", "text": prompt},
|
| 87 |
+
],
|
| 88 |
+
}
|
| 89 |
+
]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def create_dataset_card(
|
| 93 |
+
source_dataset: str,
|
| 94 |
+
model: str,
|
| 95 |
+
num_samples: int,
|
| 96 |
+
processing_time: str,
|
| 97 |
+
output_column: str,
|
| 98 |
+
batch_size: int,
|
| 99 |
+
max_model_len: int,
|
| 100 |
+
max_tokens: int,
|
| 101 |
+
gpu_memory_utilization: float,
|
| 102 |
+
image_column: str = "image",
|
| 103 |
+
split: str = "train",
|
| 104 |
+
) -> str:
|
| 105 |
+
"""Create a dataset card documenting the OCR process."""
|
| 106 |
+
model_name = model.split("/")[-1]
|
| 107 |
+
|
| 108 |
+
return f"""---
|
| 109 |
+
viewer: false
|
| 110 |
+
tags:
|
| 111 |
+
- ocr
|
| 112 |
+
- text-extraction
|
| 113 |
+
- rolmocr
|
| 114 |
+
- uv-script
|
| 115 |
+
- generated
|
| 116 |
+
---
|
| 117 |
+
|
| 118 |
+
# OCR Text Extraction using {model_name}
|
| 119 |
+
|
| 120 |
+
This dataset contains extracted text from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using RolmOCR.
|
| 121 |
+
|
| 122 |
+
## Processing Details
|
| 123 |
+
|
| 124 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 125 |
+
- **Model**: [{model}](https://huggingface.co/{model})
|
| 126 |
+
- **Number of Samples**: {num_samples:,}
|
| 127 |
+
- **Processing Time**: {processing_time}
|
| 128 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 129 |
+
|
| 130 |
+
### Configuration
|
| 131 |
+
|
| 132 |
+
- **Image Column**: `{image_column}`
|
| 133 |
+
- **Output Column**: `{output_column}`
|
| 134 |
+
- **Dataset Split**: `{split}`
|
| 135 |
+
- **Batch Size**: {batch_size}
|
| 136 |
+
- **Max Model Length**: {max_model_len:,} tokens
|
| 137 |
+
- **Max Output Tokens**: {max_tokens:,}
|
| 138 |
+
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 139 |
+
|
| 140 |
+
## Model Information
|
| 141 |
+
|
| 142 |
+
RolmOCR is a fast, general-purpose OCR model based on Qwen2.5-VL-7B architecture. It extracts plain text from document images with high accuracy and efficiency.
|
| 143 |
+
|
| 144 |
+
## Dataset Structure
|
| 145 |
+
|
| 146 |
+
The dataset contains all original columns plus:
|
| 147 |
+
- `{output_column}`: The extracted text from each image
|
| 148 |
+
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 149 |
+
|
| 150 |
+
## Usage
|
| 151 |
+
|
| 152 |
+
```python
|
| 153 |
+
from datasets import load_dataset
|
| 154 |
+
import json
|
| 155 |
+
|
| 156 |
+
# Load the dataset
|
| 157 |
+
dataset = load_dataset("{{output_dataset_id}}", split="{split}")
|
| 158 |
+
|
| 159 |
+
# Access the extracted text
|
| 160 |
+
for example in dataset:
|
| 161 |
+
print(example["{output_column}"])
|
| 162 |
+
break
|
| 163 |
+
|
| 164 |
+
# View all OCR models applied to this dataset
|
| 165 |
+
inference_info = json.loads(dataset[0]["inference_info"])
|
| 166 |
+
for info in inference_info:
|
| 167 |
+
print(f"Column: {{info['column_name']}} - Model: {{info['model_id']}}")
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
## Reproduction
|
| 171 |
+
|
| 172 |
+
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) RolmOCR script:
|
| 173 |
+
|
| 174 |
+
```bash
|
| 175 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/rolm-ocr.py \\
|
| 176 |
+
{source_dataset} \\
|
| 177 |
+
<output-dataset> \\
|
| 178 |
+
--image-column {image_column} \\
|
| 179 |
+
--batch-size {batch_size} \\
|
| 180 |
+
--max-model-len {max_model_len} \\
|
| 181 |
+
--max-tokens {max_tokens} \\
|
| 182 |
+
--gpu-memory-utilization {gpu_memory_utilization}
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
## Performance
|
| 186 |
+
|
| 187 |
+
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
|
| 188 |
+
- **GPU Configuration**: vLLM with {gpu_memory_utilization:.0%} GPU memory utilization
|
| 189 |
+
|
| 190 |
+
Generated with ๐ค [UV Scripts](https://huggingface.co/uv-scripts)
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def main(
|
| 195 |
+
input_dataset: str,
|
| 196 |
+
output_dataset: str,
|
| 197 |
+
image_column: str = "image",
|
| 198 |
+
batch_size: int = 16,
|
| 199 |
+
model: str = "reducto/RolmOCR",
|
| 200 |
+
max_model_len: int = 16384,
|
| 201 |
+
max_tokens: int = 8192,
|
| 202 |
+
gpu_memory_utilization: float = 0.8,
|
| 203 |
+
hf_token: str = None,
|
| 204 |
+
split: str = "train",
|
| 205 |
+
max_samples: int = None,
|
| 206 |
+
private: bool = False,
|
| 207 |
+
output_column: str = None,
|
| 208 |
+
shuffle: bool = False,
|
| 209 |
+
seed: int = 42,
|
| 210 |
+
):
|
| 211 |
+
"""Process images from HF dataset through OCR model."""
|
| 212 |
+
|
| 213 |
+
# Check CUDA availability first
|
| 214 |
+
check_cuda_availability()
|
| 215 |
+
|
| 216 |
+
# Track processing start time
|
| 217 |
+
start_time = datetime.now()
|
| 218 |
+
|
| 219 |
+
# Enable HF_TRANSFER for faster downloads
|
| 220 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 221 |
+
|
| 222 |
+
# Login to HF if token provided
|
| 223 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 224 |
+
if HF_TOKEN:
|
| 225 |
+
login(token=HF_TOKEN)
|
| 226 |
+
|
| 227 |
+
# Load dataset
|
| 228 |
+
logger.info(f"Loading dataset: {input_dataset}")
|
| 229 |
+
dataset = load_dataset(input_dataset, split=split)
|
| 230 |
+
|
| 231 |
+
# Set output column name dynamically if not provided
|
| 232 |
+
if output_column is None:
|
| 233 |
+
# Extract model name from path (e.g., "reducto/RolmOCR" -> "rolmocr")
|
| 234 |
+
model_name = model.split("/")[-1].lower().replace("-", "_")
|
| 235 |
+
output_column = f"{model_name}_text"
|
| 236 |
+
logger.info(f"Using dynamic output column name: {output_column}")
|
| 237 |
+
|
| 238 |
+
# Validate image column
|
| 239 |
+
if image_column not in dataset.column_names:
|
| 240 |
+
raise ValueError(
|
| 241 |
+
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# Shuffle if requested
|
| 245 |
+
if shuffle:
|
| 246 |
+
logger.info(f"Shuffling dataset with seed {seed}")
|
| 247 |
+
dataset = dataset.shuffle(seed=seed)
|
| 248 |
+
|
| 249 |
+
# Limit samples if requested
|
| 250 |
+
if max_samples:
|
| 251 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 252 |
+
logger.info(f"Limited to {len(dataset)} samples")
|
| 253 |
+
|
| 254 |
+
# Initialize vLLM
|
| 255 |
+
logger.info(f"Initializing vLLM with model: {model}")
|
| 256 |
+
llm = LLM(
|
| 257 |
+
model=model,
|
| 258 |
+
trust_remote_code=True,
|
| 259 |
+
max_model_len=max_model_len,
|
| 260 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 261 |
+
limit_mm_per_prompt={"image": 1},
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
sampling_params = SamplingParams(
|
| 265 |
+
temperature=0.0, # Deterministic for OCR
|
| 266 |
+
max_tokens=max_tokens,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# Process images in batches
|
| 270 |
+
all_text = []
|
| 271 |
+
|
| 272 |
+
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 273 |
+
|
| 274 |
+
# Process in batches to avoid memory issues
|
| 275 |
+
for batch_indices in tqdm(
|
| 276 |
+
partition_all(batch_size, range(len(dataset))),
|
| 277 |
+
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 278 |
+
desc="OCR processing",
|
| 279 |
+
):
|
| 280 |
+
batch_indices = list(batch_indices)
|
| 281 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 282 |
+
|
| 283 |
+
try:
|
| 284 |
+
# Create messages for batch
|
| 285 |
+
batch_messages = [make_ocr_message(img) for img in batch_images]
|
| 286 |
+
|
| 287 |
+
# Process with vLLM
|
| 288 |
+
outputs = llm.chat(batch_messages, sampling_params)
|
| 289 |
+
|
| 290 |
+
# Extract text from outputs
|
| 291 |
+
for output in outputs:
|
| 292 |
+
text = output.outputs[0].text.strip()
|
| 293 |
+
all_text.append(text)
|
| 294 |
+
|
| 295 |
+
except Exception as e:
|
| 296 |
+
logger.error(f"Error processing batch: {e}")
|
| 297 |
+
# Add error placeholders for failed batch
|
| 298 |
+
all_text.extend(["[OCR FAILED]"] * len(batch_images))
|
| 299 |
+
|
| 300 |
+
# Add text column to dataset
|
| 301 |
+
logger.info(f"Adding {output_column} column to dataset")
|
| 302 |
+
dataset = dataset.add_column(output_column, all_text)
|
| 303 |
+
|
| 304 |
+
# Handle inference_info tracking
|
| 305 |
+
logger.info("Updating inference_info...")
|
| 306 |
+
|
| 307 |
+
# Check for existing inference_info
|
| 308 |
+
if "inference_info" in dataset.column_names:
|
| 309 |
+
# Parse existing info from first row (all rows have same info)
|
| 310 |
+
try:
|
| 311 |
+
existing_info = json.loads(dataset[0]["inference_info"])
|
| 312 |
+
if not isinstance(existing_info, list):
|
| 313 |
+
existing_info = [existing_info] # Convert old format to list
|
| 314 |
+
except (json.JSONDecodeError, TypeError):
|
| 315 |
+
existing_info = []
|
| 316 |
+
# Remove old column to update it
|
| 317 |
+
dataset = dataset.remove_columns(["inference_info"])
|
| 318 |
+
else:
|
| 319 |
+
existing_info = []
|
| 320 |
+
|
| 321 |
+
# Add new inference info
|
| 322 |
+
new_info = {
|
| 323 |
+
"column_name": output_column,
|
| 324 |
+
"model_id": model,
|
| 325 |
+
"processing_date": datetime.now().isoformat(),
|
| 326 |
+
"batch_size": batch_size,
|
| 327 |
+
"max_tokens": max_tokens,
|
| 328 |
+
"gpu_memory_utilization": gpu_memory_utilization,
|
| 329 |
+
"max_model_len": max_model_len,
|
| 330 |
+
"script": "rolm-ocr.py",
|
| 331 |
+
"script_version": "1.0.0",
|
| 332 |
+
"script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/rolm-ocr.py"
|
| 333 |
+
}
|
| 334 |
+
existing_info.append(new_info)
|
| 335 |
+
|
| 336 |
+
# Add updated inference_info column
|
| 337 |
+
info_json = json.dumps(existing_info, ensure_ascii=False)
|
| 338 |
+
dataset = dataset.add_column("inference_info", [info_json] * len(dataset))
|
| 339 |
+
|
| 340 |
+
# Push to hub
|
| 341 |
+
logger.info(f"Pushing to {output_dataset}")
|
| 342 |
+
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 343 |
+
|
| 344 |
+
# Calculate processing time
|
| 345 |
+
end_time = datetime.now()
|
| 346 |
+
processing_duration = end_time - start_time
|
| 347 |
+
processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
|
| 348 |
+
|
| 349 |
+
# Create and push dataset card
|
| 350 |
+
logger.info("Creating dataset card...")
|
| 351 |
+
card_content = create_dataset_card(
|
| 352 |
+
source_dataset=input_dataset,
|
| 353 |
+
model=model,
|
| 354 |
+
num_samples=len(dataset),
|
| 355 |
+
processing_time=processing_time,
|
| 356 |
+
output_column=output_column,
|
| 357 |
+
batch_size=batch_size,
|
| 358 |
+
max_model_len=max_model_len,
|
| 359 |
+
max_tokens=max_tokens,
|
| 360 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 361 |
+
image_column=image_column,
|
| 362 |
+
split=split,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
card = DatasetCard(card_content)
|
| 366 |
+
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 367 |
+
logger.info("โ
Dataset card created and pushed!")
|
| 368 |
+
|
| 369 |
+
logger.info("โ
OCR conversion complete!")
|
| 370 |
+
logger.info(
|
| 371 |
+
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
if __name__ == "__main__":
|
| 376 |
+
# Show example usage if no arguments
|
| 377 |
+
if len(sys.argv) == 1:
|
| 378 |
+
print("=" * 80)
|
| 379 |
+
print("RolmOCR Document Text Extraction")
|
| 380 |
+
print("=" * 80)
|
| 381 |
+
print("\nThis script extracts plain text from document images using")
|
| 382 |
+
print("the RolmOCR model with vLLM acceleration.")
|
| 383 |
+
print("\nFeatures:")
|
| 384 |
+
print("- Fast and efficient text extraction")
|
| 385 |
+
print("- General-purpose document OCR")
|
| 386 |
+
print("- Based on Qwen2.5-VL-7B architecture")
|
| 387 |
+
print("- Optimized for batch processing")
|
| 388 |
+
print("\nExample usage:")
|
| 389 |
+
print("\n1. Basic OCR conversion:")
|
| 390 |
+
print(" uv run rolm-ocr.py document-images extracted-text")
|
| 391 |
+
print("\n2. With custom settings:")
|
| 392 |
+
print(" uv run rolm-ocr.py scanned-docs ocr-output \\")
|
| 393 |
+
print(" --image-column page \\")
|
| 394 |
+
print(" --batch-size 8 \\")
|
| 395 |
+
print(" --gpu-memory-utilization 0.9")
|
| 396 |
+
print("\n3. Process a subset for testing:")
|
| 397 |
+
print(" uv run rolm-ocr.py large-dataset test-output --max-samples 10")
|
| 398 |
+
print("\n4. Random sample from ordered dataset:")
|
| 399 |
+
print(" uv run rolm-ocr.py ordered-dataset random-test --max-samples 50 --shuffle")
|
| 400 |
+
print("\n5. Running on HF Jobs:")
|
| 401 |
+
print(" hf jobs uv run --flavor l4x1 \\")
|
| 402 |
+
print(" -e HF_TOKEN=$(python3 -c \"from huggingface_hub import get_token; print(get_token())\") \\")
|
| 403 |
+
print(
|
| 404 |
+
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/rolm-ocr.py \\"
|
| 405 |
+
)
|
| 406 |
+
print(" your-document-dataset \\")
|
| 407 |
+
print(" your-text-output")
|
| 408 |
+
print("\n" + "=" * 80)
|
| 409 |
+
print("\nFor full help, run: uv run rolm-ocr.py --help")
|
| 410 |
+
sys.exit(0)
|
| 411 |
+
|
| 412 |
+
parser = argparse.ArgumentParser(
|
| 413 |
+
description="OCR images to text using RolmOCR",
|
| 414 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 415 |
+
epilog="""
|
| 416 |
+
Examples:
|
| 417 |
+
# Basic usage
|
| 418 |
+
uv run rolm-ocr.py my-images-dataset ocr-results
|
| 419 |
+
|
| 420 |
+
# With specific image column
|
| 421 |
+
uv run rolm-ocr.py documents extracted-text --image-column scan
|
| 422 |
+
|
| 423 |
+
# Process subset for testing
|
| 424 |
+
uv run rolm-ocr.py large-dataset test-output --max-samples 100
|
| 425 |
+
|
| 426 |
+
# Random sample of 100 images
|
| 427 |
+
uv run rolm-ocr.py ordered-dataset random-sample --max-samples 100 --shuffle
|
| 428 |
+
|
| 429 |
+
# Custom output column name (default: rolmocr_text)
|
| 430 |
+
uv run rolm-ocr.py images texts --output-column ocr_text
|
| 431 |
+
""",
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 435 |
+
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 436 |
+
parser.add_argument(
|
| 437 |
+
"--image-column",
|
| 438 |
+
default="image",
|
| 439 |
+
help="Column containing images (default: image)",
|
| 440 |
+
)
|
| 441 |
+
parser.add_argument(
|
| 442 |
+
"--batch-size",
|
| 443 |
+
type=int,
|
| 444 |
+
default=16,
|
| 445 |
+
help="Batch size for processing (default: 16)",
|
| 446 |
+
)
|
| 447 |
+
parser.add_argument(
|
| 448 |
+
"--model",
|
| 449 |
+
default="reducto/RolmOCR",
|
| 450 |
+
help="Model to use (default: reducto/RolmOCR)",
|
| 451 |
+
)
|
| 452 |
+
parser.add_argument(
|
| 453 |
+
"--max-model-len",
|
| 454 |
+
type=int,
|
| 455 |
+
default=16384,
|
| 456 |
+
help="Maximum model context length (default: 16384)",
|
| 457 |
+
)
|
| 458 |
+
parser.add_argument(
|
| 459 |
+
"--max-tokens",
|
| 460 |
+
type=int,
|
| 461 |
+
default=8192,
|
| 462 |
+
help="Maximum tokens to generate (default: 8192)",
|
| 463 |
+
)
|
| 464 |
+
parser.add_argument(
|
| 465 |
+
"--gpu-memory-utilization",
|
| 466 |
+
type=float,
|
| 467 |
+
default=0.8,
|
| 468 |
+
help="GPU memory utilization (default: 0.8)",
|
| 469 |
+
)
|
| 470 |
+
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 471 |
+
parser.add_argument(
|
| 472 |
+
"--split", default="train", help="Dataset split to use (default: train)"
|
| 473 |
+
)
|
| 474 |
+
parser.add_argument(
|
| 475 |
+
"--max-samples",
|
| 476 |
+
type=int,
|
| 477 |
+
help="Maximum number of samples to process (for testing)",
|
| 478 |
+
)
|
| 479 |
+
parser.add_argument(
|
| 480 |
+
"--private", action="store_true", help="Make output dataset private"
|
| 481 |
+
)
|
| 482 |
+
parser.add_argument(
|
| 483 |
+
"--output-column",
|
| 484 |
+
default=None,
|
| 485 |
+
help="Name of the output column for extracted text (default: auto-generated from model name)",
|
| 486 |
+
)
|
| 487 |
+
parser.add_argument(
|
| 488 |
+
"--shuffle",
|
| 489 |
+
action="store_true",
|
| 490 |
+
help="Shuffle the dataset before processing (useful for random sampling)",
|
| 491 |
+
)
|
| 492 |
+
parser.add_argument(
|
| 493 |
+
"--seed",
|
| 494 |
+
type=int,
|
| 495 |
+
default=42,
|
| 496 |
+
help="Random seed for shuffling (default: 42)",
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
args = parser.parse_args()
|
| 500 |
+
|
| 501 |
+
main(
|
| 502 |
+
input_dataset=args.input_dataset,
|
| 503 |
+
output_dataset=args.output_dataset,
|
| 504 |
+
image_column=args.image_column,
|
| 505 |
+
batch_size=args.batch_size,
|
| 506 |
+
model=args.model,
|
| 507 |
+
max_model_len=args.max_model_len,
|
| 508 |
+
max_tokens=args.max_tokens,
|
| 509 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 510 |
+
hf_token=args.hf_token,
|
| 511 |
+
split=args.split,
|
| 512 |
+
max_samples=args.max_samples,
|
| 513 |
+
private=args.private,
|
| 514 |
+
output_column=args.output_column,
|
| 515 |
+
shuffle=args.shuffle,
|
| 516 |
+
seed=args.seed,
|
| 517 |
+
)
|