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
| 14 |
+
"""
|
| 15 |
+
Convert document images to markdown using Qianfan-OCR with vLLM.
|
| 16 |
+
|
| 17 |
+
Qianfan-OCR is a 4.7B end-to-end document intelligence model from Baidu,
|
| 18 |
+
built on InternVL architecture with Qianfan-ViT encoder + Qwen3-4B LLM.
|
| 19 |
+
|
| 20 |
+
Features:
|
| 21 |
+
- #1 end-to-end model on OmniDocBench v1.5 (93.12) and OlmOCR Bench (79.8)
|
| 22 |
+
- Layout-as-Thought: optional reasoning phase for complex layouts via --think
|
| 23 |
+
- 192 language support (Latin, CJK, Arabic, Cyrillic, and more)
|
| 24 |
+
- Multiple task modes: OCR, table (HTML), formula (LaTeX), chart, scene text
|
| 25 |
+
- Key information extraction with custom prompts
|
| 26 |
+
- 1.024 PPS on A100 with W8A8 quantization
|
| 27 |
+
|
| 28 |
+
Model: baidu/Qianfan-OCR
|
| 29 |
+
License: Apache 2.0
|
| 30 |
+
Paper: https://arxiv.org/abs/2603.13398
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import argparse
|
| 34 |
+
import base64
|
| 35 |
+
import io
|
| 36 |
+
import json
|
| 37 |
+
import logging
|
| 38 |
+
import os
|
| 39 |
+
import sys
|
| 40 |
+
import time
|
| 41 |
+
from datetime import datetime
|
| 42 |
+
from typing import Any, Dict, List, Union
|
| 43 |
+
|
| 44 |
+
import torch
|
| 45 |
+
from datasets import load_dataset
|
| 46 |
+
from huggingface_hub import DatasetCard, login
|
| 47 |
+
from PIL import Image
|
| 48 |
+
from toolz import partition_all
|
| 49 |
+
from tqdm.auto import tqdm
|
| 50 |
+
from vllm import LLM, SamplingParams
|
| 51 |
+
|
| 52 |
+
logging.basicConfig(level=logging.INFO)
|
| 53 |
+
logger = logging.getLogger(__name__)
|
| 54 |
+
|
| 55 |
+
MODEL = "baidu/Qianfan-OCR"
|
| 56 |
+
|
| 57 |
+
PROMPT_TEMPLATES = {
|
| 58 |
+
"ocr": "Parse this document to Markdown.",
|
| 59 |
+
"table": "Extract tables to HTML format.",
|
| 60 |
+
"formula": "Extract formulas to LaTeX.",
|
| 61 |
+
"chart": "What trends are shown in this chart?",
|
| 62 |
+
"scene": "Extract all visible text from the image.",
|
| 63 |
+
"kie": None, # requires --custom-prompt
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def check_cuda_availability():
|
| 68 |
+
"""Check if CUDA is available and exit if not."""
|
| 69 |
+
if not torch.cuda.is_available():
|
| 70 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 71 |
+
sys.exit(1)
|
| 72 |
+
else:
|
| 73 |
+
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def extract_content_from_thinking(text: str, include_thinking: bool = False) -> str:
|
| 77 |
+
"""
|
| 78 |
+
Extract final content from Qianfan-OCR's Layout-as-Thought output.
|
| 79 |
+
|
| 80 |
+
When --think is enabled, the model generates layout analysis inside
|
| 81 |
+
<think>...</think> tags before the final markdown output.
|
| 82 |
+
"""
|
| 83 |
+
if include_thinking:
|
| 84 |
+
return text.strip()
|
| 85 |
+
|
| 86 |
+
# If no thinking tags, return as-is
|
| 87 |
+
if "<think>" not in text:
|
| 88 |
+
return text.strip()
|
| 89 |
+
|
| 90 |
+
# Extract everything after </think>
|
| 91 |
+
think_end = text.find("</think>")
|
| 92 |
+
if think_end != -1:
|
| 93 |
+
return text[think_end + 8 :].strip()
|
| 94 |
+
|
| 95 |
+
# Thinking started but never closed — return full text
|
| 96 |
+
logger.warning("Found <think> but no </think>, returning full text")
|
| 97 |
+
return text.strip()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def make_ocr_message(
|
| 101 |
+
image: Union[Image.Image, Dict[str, Any], str],
|
| 102 |
+
prompt: str,
|
| 103 |
+
) -> List[Dict]:
|
| 104 |
+
"""Create vLLM chat message with image and prompt."""
|
| 105 |
+
if isinstance(image, Image.Image):
|
| 106 |
+
pil_img = image
|
| 107 |
+
elif isinstance(image, dict) and "bytes" in image:
|
| 108 |
+
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 109 |
+
elif isinstance(image, str):
|
| 110 |
+
pil_img = Image.open(image)
|
| 111 |
+
else:
|
| 112 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 113 |
+
|
| 114 |
+
pil_img = pil_img.convert("RGB")
|
| 115 |
+
|
| 116 |
+
buf = io.BytesIO()
|
| 117 |
+
pil_img.save(buf, format="PNG")
|
| 118 |
+
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 119 |
+
|
| 120 |
+
return [
|
| 121 |
+
{
|
| 122 |
+
"role": "user",
|
| 123 |
+
"content": [
|
| 124 |
+
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 125 |
+
{"type": "text", "text": prompt},
|
| 126 |
+
],
|
| 127 |
+
}
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def create_dataset_card(
|
| 132 |
+
source_dataset: str,
|
| 133 |
+
model: str,
|
| 134 |
+
num_samples: int,
|
| 135 |
+
processing_time: str,
|
| 136 |
+
batch_size: int,
|
| 137 |
+
max_model_len: int,
|
| 138 |
+
max_tokens: int,
|
| 139 |
+
gpu_memory_utilization: float,
|
| 140 |
+
prompt_mode: str,
|
| 141 |
+
think: bool,
|
| 142 |
+
include_thinking: bool,
|
| 143 |
+
image_column: str = "image",
|
| 144 |
+
split: str = "train",
|
| 145 |
+
) -> str:
|
| 146 |
+
"""Create a dataset card documenting the OCR process."""
|
| 147 |
+
model_name = model.split("/")[-1]
|
| 148 |
+
|
| 149 |
+
return f"""---
|
| 150 |
+
tags:
|
| 151 |
+
- ocr
|
| 152 |
+
- document-processing
|
| 153 |
+
- qianfan-ocr
|
| 154 |
+
- markdown
|
| 155 |
+
- uv-script
|
| 156 |
+
- generated
|
| 157 |
+
---
|
| 158 |
+
|
| 159 |
+
# Document OCR using {model_name}
|
| 160 |
+
|
| 161 |
+
This dataset contains OCR results from [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using Qianfan-OCR, Baidu's 4.7B end-to-end document intelligence model.
|
| 162 |
+
|
| 163 |
+
## Processing Details
|
| 164 |
+
|
| 165 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 166 |
+
- **Model**: [{model}](https://huggingface.co/{model})
|
| 167 |
+
- **Number of Samples**: {num_samples:,}
|
| 168 |
+
- **Processing Time**: {processing_time}
|
| 169 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 170 |
+
|
| 171 |
+
### Configuration
|
| 172 |
+
|
| 173 |
+
- **Image Column**: `{image_column}`
|
| 174 |
+
- **Output Column**: `markdown`
|
| 175 |
+
- **Dataset Split**: `{split}`
|
| 176 |
+
- **Batch Size**: {batch_size}
|
| 177 |
+
- **Prompt Mode**: {prompt_mode}
|
| 178 |
+
- **Layout-as-Thought**: {"Enabled" if think else "Disabled"}
|
| 179 |
+
- **Thinking Traces**: {"Included" if include_thinking else "Excluded"}
|
| 180 |
+
- **Max Model Length**: {max_model_len:,} tokens
|
| 181 |
+
- **Max Output Tokens**: {max_tokens:,}
|
| 182 |
+
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 183 |
+
|
| 184 |
+
## Model Information
|
| 185 |
+
|
| 186 |
+
Qianfan-OCR key capabilities:
|
| 187 |
+
- #1 end-to-end model on OmniDocBench v1.5 (93.12)
|
| 188 |
+
- #1 on OlmOCR Bench (79.8)
|
| 189 |
+
- 192 language support
|
| 190 |
+
- Layout-as-Thought reasoning for complex documents
|
| 191 |
+
- Document parsing, table extraction, formula recognition, chart understanding
|
| 192 |
+
- Key information extraction
|
| 193 |
+
|
| 194 |
+
## Dataset Structure
|
| 195 |
+
|
| 196 |
+
The dataset contains all original columns plus:
|
| 197 |
+
- `markdown`: The extracted text in markdown format
|
| 198 |
+
- `inference_info`: JSON list tracking all OCR models applied
|
| 199 |
+
|
| 200 |
+
## Reproduction
|
| 201 |
+
|
| 202 |
+
```bash
|
| 203 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/qianfan-ocr.py \\
|
| 204 |
+
{source_dataset} \\
|
| 205 |
+
<output-dataset> \\
|
| 206 |
+
--image-column {image_column} \\
|
| 207 |
+
--prompt-mode {prompt_mode} \\
|
| 208 |
+
--batch-size {batch_size}{" --think" if think else ""}
|
| 209 |
+
```
|
| 210 |
+
|
| 211 |
+
Generated with [UV Scripts](https://huggingface.co/uv-scripts)
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def main(
|
| 216 |
+
input_dataset: str,
|
| 217 |
+
output_dataset: str,
|
| 218 |
+
image_column: str = "image",
|
| 219 |
+
batch_size: int = 8,
|
| 220 |
+
max_model_len: int = 16384,
|
| 221 |
+
max_tokens: int = 8192,
|
| 222 |
+
temperature: float = 0.0,
|
| 223 |
+
top_p: float = 1.0,
|
| 224 |
+
gpu_memory_utilization: float = 0.85,
|
| 225 |
+
hf_token: str = None,
|
| 226 |
+
split: str = "train",
|
| 227 |
+
max_samples: int = None,
|
| 228 |
+
private: bool = False,
|
| 229 |
+
shuffle: bool = False,
|
| 230 |
+
seed: int = 42,
|
| 231 |
+
prompt_mode: str = "ocr",
|
| 232 |
+
think: bool = False,
|
| 233 |
+
include_thinking: bool = False,
|
| 234 |
+
custom_prompt: str = None,
|
| 235 |
+
output_column: str = "markdown",
|
| 236 |
+
config: str = None,
|
| 237 |
+
create_pr: bool = False,
|
| 238 |
+
verbose: bool = False,
|
| 239 |
+
):
|
| 240 |
+
"""Process images from HF dataset through Qianfan-OCR model."""
|
| 241 |
+
|
| 242 |
+
check_cuda_availability()
|
| 243 |
+
start_time = datetime.now()
|
| 244 |
+
|
| 245 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 246 |
+
if HF_TOKEN:
|
| 247 |
+
login(token=HF_TOKEN)
|
| 248 |
+
|
| 249 |
+
# Build prompt
|
| 250 |
+
if custom_prompt:
|
| 251 |
+
prompt = custom_prompt
|
| 252 |
+
logger.info(f"Using custom prompt: {prompt[:80]}...")
|
| 253 |
+
else:
|
| 254 |
+
if prompt_mode == "kie":
|
| 255 |
+
logger.error("--prompt-mode kie requires --custom-prompt")
|
| 256 |
+
sys.exit(1)
|
| 257 |
+
prompt = PROMPT_TEMPLATES[prompt_mode]
|
| 258 |
+
logger.info(f"Using prompt mode: {prompt_mode}")
|
| 259 |
+
|
| 260 |
+
if think:
|
| 261 |
+
prompt = prompt + "<think>"
|
| 262 |
+
logger.info("Layout-as-Thought enabled (appending <think> to prompt)")
|
| 263 |
+
|
| 264 |
+
logger.info(f"Using model: {MODEL}")
|
| 265 |
+
|
| 266 |
+
# Load dataset
|
| 267 |
+
logger.info(f"Loading dataset: {input_dataset}")
|
| 268 |
+
dataset = load_dataset(input_dataset, split=split)
|
| 269 |
+
|
| 270 |
+
if image_column not in dataset.column_names:
|
| 271 |
+
raise ValueError(
|
| 272 |
+
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if shuffle:
|
| 276 |
+
logger.info(f"Shuffling dataset with seed {seed}")
|
| 277 |
+
dataset = dataset.shuffle(seed=seed)
|
| 278 |
+
|
| 279 |
+
if max_samples:
|
| 280 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 281 |
+
logger.info(f"Limited to {len(dataset)} samples")
|
| 282 |
+
|
| 283 |
+
# Initialize vLLM
|
| 284 |
+
logger.info("Initializing vLLM with Qianfan-OCR")
|
| 285 |
+
logger.info("This may take a few minutes on first run...")
|
| 286 |
+
llm = LLM(
|
| 287 |
+
model=MODEL,
|
| 288 |
+
trust_remote_code=True,
|
| 289 |
+
max_model_len=max_model_len,
|
| 290 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 291 |
+
limit_mm_per_prompt={"image": 1},
|
| 292 |
+
enforce_eager=False,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
sampling_params = SamplingParams(
|
| 296 |
+
temperature=temperature,
|
| 297 |
+
top_p=top_p,
|
| 298 |
+
max_tokens=max_tokens,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 302 |
+
logger.info(f"Output will be written to column: {output_column}")
|
| 303 |
+
|
| 304 |
+
# Process images in batches
|
| 305 |
+
all_outputs = []
|
| 306 |
+
|
| 307 |
+
for batch_indices in tqdm(
|
| 308 |
+
partition_all(batch_size, range(len(dataset))),
|
| 309 |
+
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 310 |
+
desc="Qianfan-OCR processing",
|
| 311 |
+
):
|
| 312 |
+
batch_indices = list(batch_indices)
|
| 313 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 314 |
+
|
| 315 |
+
try:
|
| 316 |
+
batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
|
| 317 |
+
outputs = llm.chat(batch_messages, sampling_params)
|
| 318 |
+
|
| 319 |
+
for output in outputs:
|
| 320 |
+
text = output.outputs[0].text.strip()
|
| 321 |
+
if think:
|
| 322 |
+
text = extract_content_from_thinking(text, include_thinking)
|
| 323 |
+
all_outputs.append(text)
|
| 324 |
+
|
| 325 |
+
except Exception as e:
|
| 326 |
+
logger.error(f"Error processing batch: {e}")
|
| 327 |
+
all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
|
| 328 |
+
|
| 329 |
+
# Calculate processing time
|
| 330 |
+
processing_duration = datetime.now() - start_time
|
| 331 |
+
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 332 |
+
|
| 333 |
+
# Add output column
|
| 334 |
+
logger.info(f"Adding '{output_column}' column to dataset")
|
| 335 |
+
dataset = dataset.add_column(output_column, all_outputs)
|
| 336 |
+
|
| 337 |
+
# Handle inference_info tracking
|
| 338 |
+
inference_entry = {
|
| 339 |
+
"model_id": MODEL,
|
| 340 |
+
"model_name": "Qianfan-OCR",
|
| 341 |
+
"column_name": output_column,
|
| 342 |
+
"timestamp": datetime.now().isoformat(),
|
| 343 |
+
"prompt_mode": prompt_mode if not custom_prompt else "custom",
|
| 344 |
+
"think": think,
|
| 345 |
+
"temperature": temperature,
|
| 346 |
+
"max_tokens": max_tokens,
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
if "inference_info" in dataset.column_names:
|
| 350 |
+
logger.info("Updating existing inference_info column")
|
| 351 |
+
|
| 352 |
+
def update_inference_info(example):
|
| 353 |
+
try:
|
| 354 |
+
existing_info = (
|
| 355 |
+
json.loads(example["inference_info"])
|
| 356 |
+
if example["inference_info"]
|
| 357 |
+
else []
|
| 358 |
+
)
|
| 359 |
+
except (json.JSONDecodeError, TypeError):
|
| 360 |
+
existing_info = []
|
| 361 |
+
existing_info.append(inference_entry)
|
| 362 |
+
return {"inference_info": json.dumps(existing_info)}
|
| 363 |
+
|
| 364 |
+
dataset = dataset.map(update_inference_info)
|
| 365 |
+
else:
|
| 366 |
+
logger.info("Creating new inference_info column")
|
| 367 |
+
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 368 |
+
dataset = dataset.add_column("inference_info", inference_list)
|
| 369 |
+
|
| 370 |
+
# Push to hub with retry and XET fallback
|
| 371 |
+
logger.info(f"Pushing to {output_dataset}")
|
| 372 |
+
commit_msg = f"Add Qianfan-OCR results ({len(dataset)} samples)" + (
|
| 373 |
+
f" [{config}]" if config else ""
|
| 374 |
+
)
|
| 375 |
+
max_retries = 3
|
| 376 |
+
for attempt in range(1, max_retries + 1):
|
| 377 |
+
try:
|
| 378 |
+
if attempt > 1:
|
| 379 |
+
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 380 |
+
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 381 |
+
dataset.push_to_hub(
|
| 382 |
+
output_dataset,
|
| 383 |
+
private=private,
|
| 384 |
+
token=HF_TOKEN,
|
| 385 |
+
max_shard_size="500MB",
|
| 386 |
+
**({"config_name": config} if config else {}),
|
| 387 |
+
create_pr=create_pr,
|
| 388 |
+
commit_message=commit_msg,
|
| 389 |
+
)
|
| 390 |
+
break
|
| 391 |
+
except Exception as e:
|
| 392 |
+
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 393 |
+
if attempt < max_retries:
|
| 394 |
+
delay = 30 * (2 ** (attempt - 1))
|
| 395 |
+
logger.info(f"Retrying in {delay}s...")
|
| 396 |
+
time.sleep(delay)
|
| 397 |
+
else:
|
| 398 |
+
logger.error("All upload attempts failed. OCR results are lost.")
|
| 399 |
+
sys.exit(1)
|
| 400 |
+
|
| 401 |
+
# Create and push dataset card (skip when creating PR to avoid conflicts)
|
| 402 |
+
if not create_pr:
|
| 403 |
+
logger.info("Creating dataset card")
|
| 404 |
+
card_content = create_dataset_card(
|
| 405 |
+
source_dataset=input_dataset,
|
| 406 |
+
model=MODEL,
|
| 407 |
+
num_samples=len(dataset),
|
| 408 |
+
processing_time=processing_time_str,
|
| 409 |
+
batch_size=batch_size,
|
| 410 |
+
max_model_len=max_model_len,
|
| 411 |
+
max_tokens=max_tokens,
|
| 412 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 413 |
+
prompt_mode=prompt_mode if not custom_prompt else "custom",
|
| 414 |
+
think=think,
|
| 415 |
+
include_thinking=include_thinking,
|
| 416 |
+
image_column=image_column,
|
| 417 |
+
split=split,
|
| 418 |
+
)
|
| 419 |
+
card = DatasetCard(card_content)
|
| 420 |
+
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 421 |
+
|
| 422 |
+
logger.info("Qianfan-OCR processing complete!")
|
| 423 |
+
logger.info(
|
| 424 |
+
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 425 |
+
)
|
| 426 |
+
logger.info(f"Processing time: {processing_time_str}")
|
| 427 |
+
logger.info(
|
| 428 |
+
f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
if verbose:
|
| 432 |
+
import importlib.metadata
|
| 433 |
+
|
| 434 |
+
logger.info("--- Resolved package versions ---")
|
| 435 |
+
for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
|
| 436 |
+
try:
|
| 437 |
+
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 438 |
+
except importlib.metadata.PackageNotFoundError:
|
| 439 |
+
logger.info(f" {pkg}: not installed")
|
| 440 |
+
logger.info("--- End versions ---")
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
if __name__ == "__main__":
|
| 444 |
+
if len(sys.argv) == 1:
|
| 445 |
+
print("=" * 80)
|
| 446 |
+
print("Qianfan-OCR - End-to-End Document Intelligence")
|
| 447 |
+
print("=" * 80)
|
| 448 |
+
print("\n4.7B model from Baidu, #1 on OmniDocBench v1.5 (93.12)")
|
| 449 |
+
print("\nFeatures:")
|
| 450 |
+
print("- #1 end-to-end model on OmniDocBench v1.5 and OlmOCR Bench")
|
| 451 |
+
print("- Layout-as-Thought reasoning for complex documents (--think)")
|
| 452 |
+
print("- 192 language support")
|
| 453 |
+
print("- Multiple modes: OCR, table (HTML), formula (LaTeX), chart, scene text")
|
| 454 |
+
print("- Key information extraction with custom prompts")
|
| 455 |
+
print("\nExample usage:")
|
| 456 |
+
print("\n1. Basic OCR:")
|
| 457 |
+
print(" uv run qianfan-ocr.py input-dataset output-dataset")
|
| 458 |
+
print("\n2. With Layout-as-Thought (complex documents):")
|
| 459 |
+
print(" uv run qianfan-ocr.py docs output --think")
|
| 460 |
+
print("\n3. Table extraction:")
|
| 461 |
+
print(" uv run qianfan-ocr.py docs output --prompt-mode table")
|
| 462 |
+
print("\n4. Formula extraction:")
|
| 463 |
+
print(" uv run qianfan-ocr.py docs output --prompt-mode formula")
|
| 464 |
+
print("\n5. Key information extraction:")
|
| 465 |
+
print(
|
| 466 |
+
' uv run qianfan-ocr.py invoices output --prompt-mode kie --custom-prompt "Extract: name, date, total. Output JSON."'
|
| 467 |
+
)
|
| 468 |
+
print("\n6. Running on HF Jobs:")
|
| 469 |
+
print(" hf jobs uv run --flavor l4x1 \\")
|
| 470 |
+
print(" -s HF_TOKEN \\")
|
| 471 |
+
print(
|
| 472 |
+
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/qianfan-ocr.py \\"
|
| 473 |
+
)
|
| 474 |
+
print(" input-dataset output-dataset --max-samples 10")
|
| 475 |
+
print("\nFor full help, run: uv run qianfan-ocr.py --help")
|
| 476 |
+
sys.exit(0)
|
| 477 |
+
|
| 478 |
+
parser = argparse.ArgumentParser(
|
| 479 |
+
description="Document OCR using Qianfan-OCR (4.7B, #1 on OmniDocBench v1.5)",
|
| 480 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 481 |
+
epilog="""
|
| 482 |
+
Prompt modes:
|
| 483 |
+
ocr Document parsing to Markdown (default)
|
| 484 |
+
table Table extraction to HTML format
|
| 485 |
+
formula Formula recognition to LaTeX
|
| 486 |
+
chart Chart understanding and analysis
|
| 487 |
+
scene Scene text extraction
|
| 488 |
+
kie Key information extraction (requires --custom-prompt)
|
| 489 |
+
|
| 490 |
+
Examples:
|
| 491 |
+
uv run qianfan-ocr.py my-docs analyzed-docs
|
| 492 |
+
uv run qianfan-ocr.py docs output --think --max-samples 50
|
| 493 |
+
uv run qianfan-ocr.py docs output --prompt-mode table
|
| 494 |
+
uv run qianfan-ocr.py invoices data --prompt-mode kie --custom-prompt "Extract: name, date, total."
|
| 495 |
+
""",
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 499 |
+
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 500 |
+
parser.add_argument(
|
| 501 |
+
"--image-column",
|
| 502 |
+
default="image",
|
| 503 |
+
help="Column containing images (default: image)",
|
| 504 |
+
)
|
| 505 |
+
parser.add_argument(
|
| 506 |
+
"--batch-size",
|
| 507 |
+
type=int,
|
| 508 |
+
default=8,
|
| 509 |
+
help="Batch size for processing (default: 8)",
|
| 510 |
+
)
|
| 511 |
+
parser.add_argument(
|
| 512 |
+
"--max-model-len",
|
| 513 |
+
type=int,
|
| 514 |
+
default=16384,
|
| 515 |
+
help="Maximum model context length (default: 16384, reduce to 8192 if OOM on L4)",
|
| 516 |
+
)
|
| 517 |
+
parser.add_argument(
|
| 518 |
+
"--max-tokens",
|
| 519 |
+
type=int,
|
| 520 |
+
default=8192,
|
| 521 |
+
help="Maximum tokens to generate (default: 8192)",
|
| 522 |
+
)
|
| 523 |
+
parser.add_argument(
|
| 524 |
+
"--temperature",
|
| 525 |
+
type=float,
|
| 526 |
+
default=0.0,
|
| 527 |
+
help="Sampling temperature (default: 0.0, deterministic)",
|
| 528 |
+
)
|
| 529 |
+
parser.add_argument(
|
| 530 |
+
"--top-p",
|
| 531 |
+
type=float,
|
| 532 |
+
default=1.0,
|
| 533 |
+
help="Top-p sampling parameter (default: 1.0)",
|
| 534 |
+
)
|
| 535 |
+
parser.add_argument(
|
| 536 |
+
"--gpu-memory-utilization",
|
| 537 |
+
type=float,
|
| 538 |
+
default=0.85,
|
| 539 |
+
help="GPU memory utilization (default: 0.85)",
|
| 540 |
+
)
|
| 541 |
+
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 542 |
+
parser.add_argument(
|
| 543 |
+
"--split", default="train", help="Dataset split to use (default: train)"
|
| 544 |
+
)
|
| 545 |
+
parser.add_argument(
|
| 546 |
+
"--max-samples",
|
| 547 |
+
type=int,
|
| 548 |
+
help="Maximum number of samples to process (for testing)",
|
| 549 |
+
)
|
| 550 |
+
parser.add_argument(
|
| 551 |
+
"--private", action="store_true", help="Make output dataset private"
|
| 552 |
+
)
|
| 553 |
+
parser.add_argument(
|
| 554 |
+
"--shuffle", action="store_true", help="Shuffle dataset before processing"
|
| 555 |
+
)
|
| 556 |
+
parser.add_argument(
|
| 557 |
+
"--seed",
|
| 558 |
+
type=int,
|
| 559 |
+
default=42,
|
| 560 |
+
help="Random seed for shuffling (default: 42)",
|
| 561 |
+
)
|
| 562 |
+
parser.add_argument(
|
| 563 |
+
"--prompt-mode",
|
| 564 |
+
choices=list(PROMPT_TEMPLATES.keys()),
|
| 565 |
+
default="ocr",
|
| 566 |
+
help="Prompt mode (default: ocr)",
|
| 567 |
+
)
|
| 568 |
+
parser.add_argument(
|
| 569 |
+
"--think",
|
| 570 |
+
action="store_true",
|
| 571 |
+
help="Enable Layout-as-Thought reasoning (appends <think> to prompt)",
|
| 572 |
+
)
|
| 573 |
+
parser.add_argument(
|
| 574 |
+
"--include-thinking",
|
| 575 |
+
action="store_true",
|
| 576 |
+
help="Include thinking traces in output (default: only final content)",
|
| 577 |
+
)
|
| 578 |
+
parser.add_argument(
|
| 579 |
+
"--custom-prompt",
|
| 580 |
+
help="Custom prompt text (overrides --prompt-mode)",
|
| 581 |
+
)
|
| 582 |
+
parser.add_argument(
|
| 583 |
+
"--output-column",
|
| 584 |
+
default="markdown",
|
| 585 |
+
help="Column name for output text (default: markdown)",
|
| 586 |
+
)
|
| 587 |
+
parser.add_argument(
|
| 588 |
+
"--config",
|
| 589 |
+
help="Config/subset name when pushing to Hub (for benchmarking multiple models)",
|
| 590 |
+
)
|
| 591 |
+
parser.add_argument(
|
| 592 |
+
"--create-pr",
|
| 593 |
+
action="store_true",
|
| 594 |
+
help="Create a pull request instead of pushing directly",
|
| 595 |
+
)
|
| 596 |
+
parser.add_argument(
|
| 597 |
+
"--verbose",
|
| 598 |
+
action="store_true",
|
| 599 |
+
help="Log resolved package versions after processing",
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
args = parser.parse_args()
|
| 603 |
+
|
| 604 |
+
main(
|
| 605 |
+
input_dataset=args.input_dataset,
|
| 606 |
+
output_dataset=args.output_dataset,
|
| 607 |
+
image_column=args.image_column,
|
| 608 |
+
batch_size=args.batch_size,
|
| 609 |
+
max_model_len=args.max_model_len,
|
| 610 |
+
max_tokens=args.max_tokens,
|
| 611 |
+
temperature=args.temperature,
|
| 612 |
+
top_p=args.top_p,
|
| 613 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 614 |
+
hf_token=args.hf_token,
|
| 615 |
+
split=args.split,
|
| 616 |
+
max_samples=args.max_samples,
|
| 617 |
+
private=args.private,
|
| 618 |
+
shuffle=args.shuffle,
|
| 619 |
+
seed=args.seed,
|
| 620 |
+
prompt_mode=args.prompt_mode,
|
| 621 |
+
think=args.think,
|
| 622 |
+
include_thinking=args.include_thinking,
|
| 623 |
+
custom_prompt=args.custom_prompt,
|
| 624 |
+
output_column=args.output_column,
|
| 625 |
+
config=args.config,
|
| 626 |
+
create_pr=args.create_pr,
|
| 627 |
+
verbose=args.verbose,
|
| 628 |
+
)
|