File size: 26,138 Bytes
cea7723 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 |
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "datasets",
# "huggingface-hub[hf_transfer]",
# "pillow",
# "vllm",
# "transformers>=4.45.0",
# "qwen-vl-utils",
# "tqdm",
# "toolz",
# "torch",
# "flash-attn",
# ]
#
# ///
"""
Document layout analysis and OCR using dots.ocr with vLLM.
This script processes document images through the dots.ocr model to extract
layout information, text content, or both. Supports multiple output formats
including JSON, structured columns, and markdown.
Features:
- Layout detection with bounding boxes and categories
- Text extraction with reading order preservation
- Multiple prompt modes for different tasks
- Flexible output formats
- Multilingual document support
"""
import argparse
import base64
import io
import json
import logging
import os
import sys
from typing import Any, Dict, List, Optional, Union
import torch
from datasets import load_dataset
from huggingface_hub import login
from PIL import Image
from toolz import partition_all
from tqdm.auto import tqdm
# Import both vLLM and transformers - we'll use based on flag
try:
from vllm import LLM, SamplingParams
VLLM_AVAILABLE = True
except ImportError:
VLLM_AVAILABLE = False
from transformers import AutoModelForCausalLM, AutoProcessor
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Try to import qwen_vl_utils for transformers backend
try:
from qwen_vl_utils import process_vision_info
QWEN_VL_AVAILABLE = True
except ImportError:
QWEN_VL_AVAILABLE = False
logger.warning("qwen_vl_utils not available, transformers backend may not work properly")
# Prompt definitions from dots.ocr's dict_promptmode_to_prompt
PROMPT_MODES = {
"layout-all": """Please output the layout information from the PDF image, including each layout element's bbox, its category, and the corresponding text content within the bbox.
1. Bbox format: [x1, y1, x2, y2]
2. Layout Categories: The possible categories are ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'].
3. Text Extraction & Formatting Rules:
- Picture: For the 'Picture' category, the text field should be omitted.
- Formula: Format its text as LaTeX.
- Table: Format its text as HTML.
- All Others (Text, Title, etc.): Format their text as Markdown.
4. Constraints:
- The output text must be the original text from the image, with no translation.
- All layout elements must be sorted according to human reading order.
5. Final Output: The entire output must be a single JSON object.
""",
"layout-only": """Please output the layout information from this PDF image, including each layout's bbox and its category. The bbox should be in the format [x1, y1, x2, y2]. The layout categories for the PDF document include ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']. Do not output the corresponding text. The layout result should be in JSON format.""",
"ocr": """Extract the text content from this image.""",
"grounding-ocr": """Extract text from the given bounding box on the image (format: [x1, y1, x2, y2]).\nBounding Box:\n"""
}
def check_cuda_availability():
"""Check if CUDA is available and exit if not."""
if not torch.cuda.is_available():
logger.error("CUDA is not available. This script requires a GPU.")
logger.error("Please run on a machine with a CUDA-capable GPU.")
sys.exit(1)
else:
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
def make_dots_message(
image: Union[Image.Image, Dict[str, Any], str],
mode: str = "layout-all",
bbox: Optional[List[int]] = None,
) -> List[Dict]:
"""Create chat message for dots.ocr processing."""
# Convert to PIL Image if needed
if isinstance(image, Image.Image):
pil_img = image
elif isinstance(image, dict) and "bytes" in image:
pil_img = Image.open(io.BytesIO(image["bytes"]))
elif isinstance(image, str):
pil_img = Image.open(image)
else:
raise ValueError(f"Unsupported image type: {type(image)}")
# Convert to base64 data URI
buf = io.BytesIO()
pil_img.save(buf, format="PNG")
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
# Get prompt for the specified mode
prompt = PROMPT_MODES.get(mode, PROMPT_MODES["layout-all"])
# Add bbox for grounding-ocr mode
if mode == "grounding-ocr" and bbox:
prompt = prompt + str(bbox)
# Return message in vLLM format
return [
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": data_uri}},
{"type": "text", "text": prompt},
],
}
]
def parse_dots_output(
output: str,
output_format: str = "json",
filter_category: Optional[str] = None,
mode: str = "layout-all",
) -> Union[str, Dict[str, List]]:
"""Parse dots.ocr output and convert to requested format."""
# For simple OCR mode, return text directly
if mode == "ocr":
return output.strip()
try:
# Parse JSON output
data = json.loads(output.strip())
# Filter by category if requested
if filter_category and "categories" in data:
indices = [i for i, cat in enumerate(data["categories"]) if cat == filter_category]
filtered_data = {
"bboxes": [data["bboxes"][i] for i in indices],
"categories": [data["categories"][i] for i in indices],
}
# Only include texts if present (layout-all mode)
if "texts" in data:
filtered_data["texts"] = [data["texts"][i] for i in indices]
# Include reading_order if present
if "reading_order" in data:
# Filter reading order to only include indices that are in our filtered set
filtered_reading_order = []
for group in data.get("reading_order", []):
filtered_group = [idx for idx in group if idx in indices]
if filtered_group:
# Remap indices to new positions
remapped_group = [indices.index(idx) for idx in filtered_group]
filtered_reading_order.append(remapped_group)
if filtered_reading_order:
filtered_data["reading_order"] = filtered_reading_order
data = filtered_data
if output_format == "json":
return json.dumps(data, ensure_ascii=False)
elif output_format == "structured":
# Return structured data for column creation
result = {
"bboxes": data.get("bboxes", []),
"categories": data.get("categories", []),
}
# Only include texts for layout-all mode
if mode == "layout-all":
result["texts"] = data.get("texts", [])
else:
result["texts"] = []
return result
elif output_format == "markdown":
# Convert to markdown format
# Only works well with layout-all mode
if mode != "layout-all" or "texts" not in data:
logger.warning("Markdown format works best with layout-all mode")
return json.dumps(data, ensure_ascii=False)
md_lines = []
texts = data.get("texts", [])
categories = data.get("categories", [])
reading_order = data.get("reading_order", [])
# If reading order is provided, use it
if reading_order:
for group in reading_order:
for idx in group:
if idx < len(texts) and idx < len(categories):
text = texts[idx]
category = categories[idx]
md_lines.append(format_markdown_text(text, category))
else:
# Fall back to sequential order
for text, category in zip(texts, categories):
md_lines.append(format_markdown_text(text, category))
return "\n".join(md_lines)
except json.JSONDecodeError as e:
logger.warning(f"Failed to parse JSON output: {e}")
return output.strip()
except Exception as e:
logger.error(f"Error parsing output: {e}")
return output.strip()
def format_markdown_text(text: str, category: str) -> str:
"""Format text based on its category for markdown output."""
if category == "Title":
return f"# {text}\n"
elif category == "Section-header":
return f"## {text}\n"
elif category == "List-item":
return f"- {text}"
elif category == "Page-header" or category == "Page-footer":
return f"_{text}_\n"
elif category == "Caption":
return f"**{text}**\n"
elif category == "Footnote":
return f"[^{text}]\n"
elif category == "Table":
# Tables are already in HTML format from dots.ocr
return f"\n{text}\n"
elif category == "Formula":
# Formulas are already in LaTeX format
return f"\n${text}$\n"
elif category == "Picture":
# Pictures don't have text in dots.ocr output
return "\n![Image]()\n"
else: # Text and any other categories
return f"{text}\n"
def process_with_transformers(
images: List[Union[Image.Image, Dict[str, Any], str]],
model,
processor,
mode: str = "layout-all",
max_new_tokens: int = 16384,
) -> List[str]:
"""Process images using transformers instead of vLLM."""
outputs = []
for image in tqdm(images, desc="Processing with transformers"):
# Convert to PIL Image if needed
if isinstance(image, dict) and "bytes" in image:
pil_image = Image.open(io.BytesIO(image["bytes"]))
elif isinstance(image, str):
pil_image = Image.open(image)
else:
pil_image = image
# Get prompt for the mode
prompt = PROMPT_MODES.get(mode, PROMPT_MODES["layout-all"])
# Create messages in the format expected by dots.ocr
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": pil_image},
{"type": "text", "text": prompt}
]
}
]
# Preparation for inference (following demo code)
text = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
if QWEN_VL_AVAILABLE:
# Use process_vision_info as shown in demo
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
)
else:
# Fallback approach without qwen_vl_utils
inputs = processor(
text=text,
images=[pil_image],
return_tensors="pt",
)
inputs = inputs.to(model.device)
# Generate
with torch.no_grad():
generated_ids = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=0.0,
do_sample=False,
)
# Decode output (following demo code)
generated_ids_trimmed = [
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
generated_ids_trimmed,
skip_special_tokens=True,
clean_up_tokenization_spaces=False
)[0]
outputs.append(output_text.strip())
return outputs
def main(
input_dataset: str,
output_dataset: str,
image_column: str = "image",
mode: str = "layout-all",
output_format: str = "json",
filter_category: Optional[str] = None,
batch_size: int = 32,
model: str = "rednote-hilab/dots.ocr",
max_model_len: int = 24000,
max_tokens: int = 16384,
gpu_memory_utilization: float = 0.8,
hf_token: Optional[str] = None,
split: str = "train",
max_samples: Optional[int] = None,
private: bool = False,
use_transformers: bool = False,
# Column name parameters
output_column: str = "dots_ocr_output",
bbox_column: str = "layout_bboxes",
category_column: str = "layout_categories",
text_column: str = "layout_texts",
markdown_column: str = "markdown",
):
"""Process images from HF dataset through dots.ocr model."""
# Check CUDA availability first
check_cuda_availability()
# Enable HF_TRANSFER for faster downloads
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
# Login to HF if token provided
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
if HF_TOKEN:
login(token=HF_TOKEN)
# Load dataset
logger.info(f"Loading dataset: {input_dataset}")
dataset = load_dataset(input_dataset, split=split)
# Validate image column
if image_column not in dataset.column_names:
raise ValueError(
f"Column '{image_column}' not found. Available: {dataset.column_names}"
)
# Limit samples if requested
if max_samples:
dataset = dataset.select(range(min(max_samples, len(dataset))))
logger.info(f"Limited to {len(dataset)} samples")
# Process images in batches
all_outputs = []
if use_transformers or not VLLM_AVAILABLE:
# Use transformers
if not use_transformers and not VLLM_AVAILABLE:
logger.warning("vLLM not available, falling back to transformers")
logger.info(f"Initializing transformers with model: {model}")
hf_model = AutoModelForCausalLM.from_pretrained(
model,
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True,
)
processor = AutoProcessor.from_pretrained(model, trust_remote_code=True)
logger.info(f"Processing {len(dataset)} images with transformers")
logger.info(f"Mode: {mode}, Output format: {output_format}")
# Process all images
all_images = [dataset[i][image_column] for i in range(len(dataset))]
raw_outputs = process_with_transformers(
all_images,
hf_model,
processor,
mode=mode,
max_new_tokens=max_tokens
)
# Parse outputs
for raw_text in raw_outputs:
parsed = parse_dots_output(raw_text, output_format, filter_category, mode)
all_outputs.append(parsed)
else:
# Use vLLM
logger.info(f"Initializing vLLM with model: {model}")
llm = LLM(
model=model,
trust_remote_code=True,
max_model_len=max_model_len,
gpu_memory_utilization=gpu_memory_utilization,
)
sampling_params = SamplingParams(
temperature=0.0, # Deterministic for OCR
max_tokens=max_tokens,
)
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
logger.info(f"Mode: {mode}, Output format: {output_format}")
# Process in batches to avoid memory issues
for batch_indices in tqdm(
partition_all(batch_size, range(len(dataset))),
total=(len(dataset) + batch_size - 1) // batch_size,
desc="dots.ocr processing",
):
batch_indices = list(batch_indices)
batch_images = [dataset[i][image_column] for i in batch_indices]
try:
# Create messages for batch
batch_messages = [make_dots_message(img, mode=mode) for img in batch_images]
# Process with vLLM
outputs = llm.chat(batch_messages, sampling_params)
# Extract and parse outputs
for output in outputs:
raw_text = output.outputs[0].text.strip()
parsed = parse_dots_output(raw_text, output_format, filter_category, mode)
all_outputs.append(parsed)
except Exception as e:
logger.error(f"Error processing batch: {e}")
# Add error placeholders for failed batch
all_outputs.extend([{"error": str(e)}] * len(batch_images))
# Add columns to dataset based on output format
logger.info("Adding output columns to dataset")
if output_format == "json":
dataset = dataset.add_column(output_column, all_outputs)
elif output_format == "structured":
# Extract lists from structured outputs
bboxes = []
categories = []
texts = []
for output in all_outputs:
if isinstance(output, dict) and "error" not in output:
bboxes.append(output.get("bboxes", []))
categories.append(output.get("categories", []))
texts.append(output.get("texts", []))
else:
bboxes.append([])
categories.append([])
texts.append([])
dataset = dataset.add_column(bbox_column, bboxes)
dataset = dataset.add_column(category_column, categories)
dataset = dataset.add_column(text_column, texts)
elif output_format == "markdown":
dataset = dataset.add_column(markdown_column, all_outputs)
else: # ocr mode
dataset = dataset.add_column(output_column, all_outputs)
# Push to hub
logger.info(f"Pushing to {output_dataset}")
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
logger.info("✅ dots.ocr processing complete!")
logger.info(
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
)
if __name__ == "__main__":
# Show example usage if no arguments
if len(sys.argv) == 1:
print("=" * 80)
print("dots.ocr Document Layout Analysis and OCR")
print("=" * 80)
print("\nThis script processes document images using the dots.ocr model to")
print("extract layout information, text content, or both.")
print("\nFeatures:")
print("- Layout detection with bounding boxes and categories")
print("- Text extraction with reading order preservation")
print("- Multiple output formats (JSON, structured, markdown)")
print("- Multilingual document support")
print("\nExample usage:")
print("\n1. Full layout analysis + OCR (default):")
print(" uv run dots-ocr.py document-images analyzed-docs")
print("\n2. Layout detection only:")
print(" uv run dots-ocr.py scanned-pdfs layout-analysis --mode layout-only")
print("\n3. Simple OCR (text only):")
print(" uv run dots-ocr.py documents extracted-text --mode ocr")
print("\n4. Convert to markdown:")
print(" uv run dots-ocr.py papers papers-markdown --output-format markdown")
print("\n5. Extract only tables:")
print(" uv run dots-ocr.py reports table-data --filter-category Table")
print("\n6. Structured output with custom columns:")
print(" uv run dots-ocr.py docs analyzed \\")
print(" --output-format structured \\")
print(" --bbox-column boxes \\")
print(" --category-column types \\")
print(" --text-column content")
print("\n7. Process a subset for testing:")
print(" uv run dots-ocr.py large-dataset test-output --max-samples 10")
print("\n8. Use transformers backend (more compatible):")
print(" uv run dots-ocr.py documents analyzed --use-transformers")
print("\n9. Running on HF Jobs:")
print(" hf jobs run --gpu l4x1 \\")
print(" -e HF_TOKEN=$(python3 -c \"from huggingface_hub import get_token; print(get_token())\") \\")
print(
" uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr.py \\"
)
print(" your-document-dataset \\")
print(" your-analyzed-output \\")
print(" --use-transformers")
print("\n" + "=" * 80)
print("\nFor full help, run: uv run dots-ocr.py --help")
sys.exit(0)
parser = argparse.ArgumentParser(
description="Document layout analysis and OCR using dots.ocr",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Modes:
layout-all - Extract layout + text content (default)
layout-only - Extract only layout information (bbox + category)
ocr - Extract only text content
grounding-ocr - Extract text from specific bbox (requires --bbox)
Output Formats:
json - Raw JSON output from model (default)
structured - Separate columns for bboxes, categories, texts
markdown - Convert to markdown format
Examples:
# Basic layout + OCR
uv run dots-ocr.py my-docs analyzed-docs
# Layout detection only
uv run dots-ocr.py papers layouts --mode layout-only
# Convert to markdown
uv run dots-ocr.py scans readable --output-format markdown
# Extract only formulas
uv run dots-ocr.py math-docs formulas --filter-category Formula
""",
)
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
parser.add_argument(
"--image-column",
default="image",
help="Column containing images (default: image)",
)
parser.add_argument(
"--mode",
choices=["layout-all", "layout-only", "ocr", "grounding-ocr"],
default="layout-all",
help="Processing mode (default: layout-all)",
)
parser.add_argument(
"--output-format",
choices=["json", "structured", "markdown"],
default="json",
help="Output format (default: json)",
)
parser.add_argument(
"--filter-category",
choices=['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer',
'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title'],
help="Filter results by layout category",
)
parser.add_argument(
"--batch-size",
type=int,
default=32,
help="Batch size for processing (default: 32)",
)
parser.add_argument(
"--model",
default="rednote-hilab/dots.ocr",
help="Model to use (default: rednote-hilab/dots.ocr)",
)
parser.add_argument(
"--max-model-len",
type=int,
default=24000,
help="Maximum model context length (default: 24000)",
)
parser.add_argument(
"--max-tokens",
type=int,
default=16384,
help="Maximum tokens to generate (default: 16384)",
)
parser.add_argument(
"--gpu-memory-utilization",
type=float,
default=0.8,
help="GPU memory utilization (default: 0.8)",
)
parser.add_argument("--hf-token", help="Hugging Face API token")
parser.add_argument(
"--split", default="train", help="Dataset split to use (default: train)"
)
parser.add_argument(
"--max-samples",
type=int,
help="Maximum number of samples to process (for testing)",
)
parser.add_argument(
"--private", action="store_true", help="Make output dataset private"
)
parser.add_argument(
"--use-transformers",
action="store_true",
help="Use transformers instead of vLLM (more compatible but slower)",
)
# Column name customization
parser.add_argument(
"--output-column",
default="dots_ocr_output",
help="Column name for JSON output (default: dots_ocr_output)",
)
parser.add_argument(
"--bbox-column",
default="layout_bboxes",
help="Column name for bboxes in structured mode (default: layout_bboxes)",
)
parser.add_argument(
"--category-column",
default="layout_categories",
help="Column name for categories in structured mode (default: layout_categories)",
)
parser.add_argument(
"--text-column",
default="layout_texts",
help="Column name for texts in structured mode (default: layout_texts)",
)
parser.add_argument(
"--markdown-column",
default="markdown",
help="Column name for markdown output (default: markdown)",
)
args = parser.parse_args()
main(
input_dataset=args.input_dataset,
output_dataset=args.output_dataset,
image_column=args.image_column,
mode=args.mode,
output_format=args.output_format,
filter_category=args.filter_category,
batch_size=args.batch_size,
model=args.model,
max_model_len=args.max_model_len,
max_tokens=args.max_tokens,
gpu_memory_utilization=args.gpu_memory_utilization,
hf_token=args.hf_token,
split=args.split,
max_samples=args.max_samples,
private=args.private,
use_transformers=args.use_transformers,
output_column=args.output_column,
bbox_column=args.bbox_column,
category_column=args.category_column,
text_column=args.text_column,
markdown_column=args.markdown_column,
) |