OlmOCR,被誉为可在本地部署的顶尖OCR大模型

B站影视 韩国电影 2025-03-11 17:41 1

摘要:allenai/olmocr是由Allen人工智能研究所(AI2)开发的一个开源工具包,旨在高效地将PDF和其他文档转换为结构化的纯文本,同时保持自然阅读顺序。

allenai/olmocr是由Allen人工智能研究所(AI2)开发的一个开源工具包,旨在高效地将PDF和其他文档转换为结构化的纯文本,同时保持自然阅读顺序。

核心技术:

1、使用名为olmOCR-7B-0225-preview的视觉语言模型(VLM),这是基于Qwen2-VL-7B-Instruct训练而成的。
2、该模型经过约25万页多样化PDF内容(包括扫描和基于文本的)的训练,这些内容使用GPT-4o标注并作为olmOCR-mix-0225数据集发布。

主要功能:

1、高效批量处理:使用SGLang优化推理管道,能以极低的成本处理大量文档。
2、文档锚定:提取每页中显著元素(如文本块和图像)的坐标,并将其与从PDF二进制文件中提取的原始文本一起注入。
3、支持本地和集群使用:可在单机GPU上运行,也支持使用AWS S3进行多节点并行处理。

性能和优势:

1、准确性高:在人工评估中,olmOCR在各种PDF提取技术的ELO评级中排名最高。
2、提升下游任务:使用olmOCR提取的文本训练语言模型,在多个AI基准任务中平均提高了1.3个百分点的准确率。

使用方法:

import torch
import base64
import urllib.request

from io import BytesIO
from PIL import Image
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration

from olmocr.data.renderpdf import render_pdf_to_base64png
from olmocr.prompts import build_finetuning_prompt
from olmocr.prompts.anchor import get_anchor_text

# Initialize the model
model = Qwen2VLForConditionalGeneration.from_pretrained("allenai/olmOCR-7B-0225-preview", torch_dtype=torch.bfloat16).eval
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
device = torch.device("cuda" if torch.cuda.is_available else "cpu")
model.to(device)

# Grab a sample PDF
urllib.request.urlretrieve("https://molmo.allenai.org/paper.pdf", "./paper.pdf")

# Render page 1 to an image
image_base64 = render_pdf_to_base64png("./paper.pdf", 1, target_longest_image_dim=1024)

# Build the prompt, using document metadata
anchor_text = get_anchor_text("./paper.pdf", 1, pdf_engine="pdfreport", target_length=4000)
prompt = build_finetuning_prompt(anchor_text)

# Build the full prompt
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}},
],
}
]

# Apply the chat template and processor
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
main_image = Image.open(BytesIO(base64.b64decode(image_base64)))

inputs = processor(
text=[text],
images=[main_image],
padding=True,
return_tensors="pt",
)
inputs = {key: value.to(device) for (key, value) in inputs.items}

# Generate the output
output = model.generate(
**inputs,
temperature=0.8,
max_new_tokens=50,
num_return_sequences=1,
do_sample=True,
)

# Decode the output
prompt_length = inputs["input_ids"].shape[1]
new_tokens = output[:, prompt_length:]
text_output = processor.tokenizer.batch_decode(
new_tokens, skip_special_tokens=True
)

print(text_output)
# ['{"primary_language":"en","is_rotation_valid":true,"rotation_correction":0,"is_table":false,"is_diagram":false,"natural_text":"Molmo and PixMo:\\nOpen Weights and Open Data\\nfor State-of-the']

识别效果:

总结:

支持结构化精准提取复杂PDF文件内容!完美识别中英文文档、模糊扫描件与复杂表格!本地部署与实际测试全过程!医疗法律行业必备!轻松应对企业级PDF批量转换需求!

来源:正能量识图者

相关推荐