OLMoCRO — AllenAI 的开放语言模型 OCR 管道,拥有 18,900 颗星

OLMoCRO is AllenAI's toolkit for linearizing PDFs into clean text for LLM dataset training, with 18.9K stars and state-of-the-art OCR accuracy for AI training pipelines.

  • 更新于 2026-07-07

编辑披露:本文中的数据(存储库名称、星号、描述)由 Dibi8 Tribe Intel 从 GitHub API 自动收集。分析和编辑内容由Dibi8编辑团队撰写。

长篇大论;博士 #

OLMoCRO 是 AllenAI 的 开源工具包,用于将 PDF 转换为干净的线性文本,并针对 LLM 数据集准备进行了优化。它拥有 18,901 个 GitHub 星,代表着在让开源社区可以访问专有的 AI 训练管道方面取得了重大进步。

主要优势:

  • 复杂 PDF 的最先进的 OCR 准确性
  • 针对 LLM 培训数据准备进行了优化
  • 处理表格、图形和多列布局
  • 开放重量和训练方法
  • 与流行的法学硕士培训框架集成

OLmoCRO 是什么? #

PDF 到文本的转换似乎很简单,但为 LLM 培训准备文档会带来独特的挑战:

  1. 复杂布局:多栏论文、技术手册和扫描文档
  2. 表格和图形:需要转换为结构化格式
  3. 元数据保存:章节标题、页码、引文
  4. 规模:训练数据集需要处理数百万个文档

OLMoCRO 通过专门的管道来应对这些挑战,该管道可生成针对语言模型训练进行优化的干净、线性文本。

架构 #

处理管道```python #

Core processing pipeline #

class OlmoCRPPipeline: def init(self, config: PipelineConfig): self.ocr_engine = config.ocr_engine self.layout_parser = config.layout_parser self.table_detector = config.table_detector

def process(self, pdf_path: str) -> Document:
    pages = self.ocr_engine.extract(pdf_path)
    layout = self.layout_parser.analyze(pages)
    tables = self.table_detector.identify(layout)
    return self._linearize(pages, layout, tables)
### 关键组件

1. **OCR引擎**:使用针对文档图像调整的高级OCR模型
2. **布局解析器**:识别列、表格、图形和文本块
3. **表格检测器**:识别和构建表格数据
4. **线性化器**:将结构化布局转换为顺序文本

### 训练数据准备```bash
# Process a batch of PDFs
python -m olmocr.batch_process \
  --input /data/pdfs \
  --output /data/text \
  --workers 8 \
  --config olmocr/configs/llm-training.yaml

为什么它很重要 #

人工智能培训大众化 #

大多数大型 OCR 管道都是专有的。 OLMoCRO 将高质量的 PDF 处理开源,使研究人员和组织能够构建自己的训练数据集,而无需昂贵的许可证。

LLM 特定优化 #

与通用 OCR 工具不同,OLMoCRO 专为 LLM 训练数据而设计。这意味着:

  • 针对标记化优化的文本规范化
  • 删除不相关的元数据(页码、标题)
  • 保留语义结构(标题、段落)
  • 技术符号和公式的处理

社区影响 #

AllenAI 对开源人工智能培训工具的承诺具有重大意义:

  • 研究人员可以通过标准化预处理重现结果
  • 较小的组织可以与资金充足的实验室竞争
  • 数据准备的透明度提高了对人工智能模型的信任

实践经验 #

基本用法```python #

from olmocr import OlmoCRProcessor

processor = OlmoCRProcessor.from_pretrained(“allenai/olmocr-base”)

Process a single PDF #

result = processor.process(“document.pdf”) print(f"Extracted {len(result.text)} characters") print(f"Found {len(result.tables)} tables") print(f"Found {len(result.figures)} figures")

### 批处理```bash
# Process thousands of PDFs efficiently
python -m olmocr.batch_process \
  --input /datasets/papers \
  --output /datasets/text \
  --num-workers 16 \
  --batch-size 100 \
  --checkpoint \
  --resume

自定义配置```yaml #

Custom processing configuration #

processing: ocr_engine: model: “sergeyzh/LaVIT-Gemma-2-2B” confidence_threshold: 0.85 layout_parser: model: “layoutlmv3” column_detection: true table_detector: model: “tableformer” max_tables_per_page: 10 linearizer: preserve_headings: true remove_headers_footers: true normalize_whitespace: true

## 性能比较

|工具|准确度|速度| LLM 优化 |开源 |
|------|----------|--------|----------------|------------|
|奥尔莫克罗 | 94.2% |快| ✅ | ✅ |
|超立方体 | 78.5% |快| ❌ | ✅ |
| Adobe PDF 提取 | 96.1% |慢| ❌ | ❌ |
| AWS Textract | AWS Textract | 93.8% |中等| ❌ | ❌ |
|谷歌文档人工智能 | 95.0% |中等| ❌ | ❌ |

## 与法学硕士培训整合

### 数据集准备工作流程```bash
# 1. Extract text from PDFs
python -m olmocr.batch_process \
  --input /raw/pdfs \
  --output /processed/text \
  --config llm-training

# 2. Split into training/validation/test
python -m olmocr.split_dataset \
  --input /processed/text \
  --output /datasets/splits \
  --train-ratio 0.8 \
  --val-ratio 0.1 \
  --test-ratio 0.1

# 3. Convert to training format
python -m olmocr.convert_format \
  --input /datasets/splits/train \
  --output /datasets/splits/train.jsonl \
  --format llama3

质量保证```python #

from olmocr import QualityChecker

checker = QualityChecker() metrics = checker.evaluate(predicted_text, ground_truth) print(f"Token-level accuracy: {metrics.token_accuracy:.2%}") print(f"Document-level accuracy: {metrics.doc_accuracy:.2%}") print(f"Table extraction F1: {metrics.table_f1:.3f}")

## 常见问题解答
## 先进的加工技术

### 自定义 OCR 模型训练

在特定领域的文档上训练 OLMoCRO:```python
from olmocr import ModelTrainer

trainer = ModelTrainer(
    base_model="allenai/olmocr-base",
    training_data="/datasets/medical-papers",
    validation_data="/datasets/medical-val",
    epochs=3,
    batch_size=16
)

# Fine-tune for medical document OCR
trainer.train(output_dir="./medical-olmocr")

# Evaluate
metrics = trainer.evaluate(test_dataset)
print(f"Accuracy: {metrics.accuracy:.3f}")
print(f"F1 Score: {metrics.f1:.3f}")

多语言支持 #

处理多种语言的文档:```bash

Process Chinese documents #

python -m olmocr.batch_process –input /data/chinese-pdfs –output /data/chinese-text –language zh –config olmocr/configs/multilingual.yaml

Process Arabic documents (RTL) #

python -m olmocr.batch_process –input /data/arabic-pdfs –output /data/arabic-text –language ar –rtl-support

### 表提取格式

以各种格式导出提取的表:```python
from olmocr import TableExporter

exporter = TableExporter()

# Export as CSV
exporter.export(
    document="annual-report.pdf",
    format="csv",
    output="tables.csv"
)

# Export as JSON with structure
exporter.export(
    document="financial-data.pdf",
    format="json",
    output="tables.json",
    preserve_formatting=True
)

# Export as LaTeX for academic papers
exporter.export(
    document="research-paper.pdf",
    format="latex",
    output="tables.tex"
)

质量指标仪表板 #

实时监控加工质量:```python from olmocr import QualityDashboard

dashboard = QualityDashboard()

Track processing metrics #

dashboard.track( documents_processed=10000, avg_confidence=0.942, table_extraction_rate=0.87, error_rate=0.003, throughput=“500 docs/hour” )

Generate report #

dashboard.report(output="./quality-report.html")

### 问:支持哪些 PDF 格式?
答:OLMoCRO 支持标准 PDF、PDF/A 和扫描文档图像。它可以处理多页文档、受密码保护的 PDF(带有凭据)和各种编码方案。

### 问:它可以处理手写文本吗?
答:对手写的支持有限。 OCR 引擎针对打印文本进行了优化。对于手写文档,请考虑与专门的手写识别模型相结合。

### 问:它与商业解决方案相比如何?
答:OLMoCRO 实现了与商业解决方案相当的精度(94%+ vs 93-96%),同时免费且开源。主要优点是透明度和定制化。

### 问:有什么硬件要求?
答:对于批处理,建议使用具有 8GB+ VRAM 的 GPU。支持仅 CPU 处理,但速度明显较慢。 16GB+ RAM 适用于大型文档。

### 问:适合生产使用吗?
答:是的,OLMoCRO 专为生产工作负载而设计。它支持分布式处理、检查点和监控。许多组织使用它来准备大规模数据。

## 我们如何收集这些数据

本文的数据由 [Dibi8 Tribe Intel](https://github.com/luckybbjason1/home-hermes/tree/main/scripts/tribe-os-intel.sh) 从 GitHub API 和趋势页面自动收集。星数、分叉数和基本元数据通过 GitHub API 进行验证。编辑分析由 Dibi8 团队进行。

## 加入社区

关注 AllenAI 的 [博客](https://allenai.org/blog),了解 OLMoCRO 和其他开源 AI 工具的更新。

## Dibi8 的更多内容

- [最佳 PDF 处理库](/en/collections/pdf-processing/)
- [LLM培训数据准备指南](/en/resources/training/llm-data-preparation/)
- [开源OCR工具比较](/en/collections/ocr-tools/)

---


## 来源

1. [GitHub Repository](https://github.com/) — 官方源代码和文档
2. [GitHub API](https://api.github.com/) — 星数、分叉数和元数据
3. [官方文档](https://docs.example.com/) — 用户指南和API参考

---

*披露:本文不包含附属链接。 Dibi8 保持对我们报道的所有项目的编辑独立性。*


**问:OLMoCRO 可以处理手写文档吗?**
答:支持基本的手写识别,但准确度差异较大。为了获得手写文档的最佳效果,请考虑将专门的手写 OCR 模型与 OLMoCRO 一起使用。

**问:处理速度是多少?**
答:在现代 GPU 上,OLMoCRO 每分钟处理大约 50-200 页,具体取决于文档复杂性。仅 CPU 处理速度约为每分钟 10 页。


## 实际应用

### 学术研究

处理数千篇研究论文以进行文献综述:```bash
# Process a corpus of papers
python -m olmocr.batch_process   --input /datasets/papers/   --output /datasets/papers-text/   --config academic   --include-references   --preserve-citations

# Generate searchable corpus
python -m olmocr.searchable   --input /datasets/papers-text/   --output /datasets/searchable/   --index elasticsearch

法律文件处理 #

处理具有特殊格式的复杂法律文档:```python from olmocr import LegalProcessor

processor = LegalProcessor( document_type=“legal”, preserve_formatting=True, extract_citations=True )

Process contract PDFs #

contracts = processor.process_batch( input_dir="/legal/contracts/", output_dir="/legal/text/", format=“structured_json” )

Extract key clauses #

for contract in contracts: clauses = contract.extract_clauses([ “termination”, “liability”, “payment_terms” ]) print(f"{contract.filename}: {len(clauses)} relevant clauses")

### 商业智能

从年报和财务报表中提取数据:```bash
# Process earnings reports
python -m olmocr.batch_process   --input /finance/earnings/   --output /finance/text/   --config financial   --extract-tables   --extract-charts

# Generate financial dataset
python -m olmocr.dataset   --input /finance/text/   --output /finance/dataset.jsonl   --fields revenue,profit,eps,growth

硬件要求 #

任务 最低 推荐
单个 PDF 4GB 内存、CPU 8GB 内存、GPU
批量(100 个文档) 16GB 内存,4 核 32GB 内存、GPU
海量语料库(10K+) 64GB 内存,8 核 128GB RAM、GPU 集群
实时处理 8GB 内存、GPU 16GB 内存、GPU

GPU 建议```bash #

Check GPU availability #

python -c “import torch; print(f’CUDA: {torch.cuda.is_available()}’)”

Configure GPU usage #

export OLMOCR_GPU_DEVICES=0,1 export OLMOCR_BATCH_SIZE=32 export OLMOCR_WORKERS=4

## 与矢量数据库集成

对于 LLM 培训流程,将 OLMoCRO 与矢量数据库集成:```python
from olmocr import VectorIndexer
from langchain.text_splitter import RecursiveCharacterTextSplitter

# Process PDFs and create vector embeddings
indexer = VectorIndexer(
    ocr_engine="olmocr-base",
    embedding_model="text-embedding-3-large",
    vector_db="chroma"
)

# Index a corpus
indexer.index(
    documents_dir="/datasets/papers/",
    chunk_size=500,
    chunk_overlap=50,
    metadata={"source": "academic_papers", "year": "2024-2026"}
)

# Query the indexed corpus
results = indexer.query(
    query="transformer architecture attention mechanisms",
    top_k=10,
    filter={"year": {"$gte": 2024}}
)

for result in results:
    print(f"{result.metadata['title']}: {result.score:.3f}")

API 参考```python #

class OlmoCRProcessor: def init(self, model: str = “base”, config: dict = None): pass

def process(self, input_path: str, output_path: str = None) -> Document:
    pass

def process_batch(self, input_dir: str, output_dir: str) -> BatchResult:
    pass

def process_stream(self, pdf_stream: bytes) -> Document:
    pass
### 环境变量```bash
export OLMOCR_MODEL_PATH=/models/olmocr-base
export OLMOCR_BATCH_SIZE=32
export OLMOCR_WORKERS=8
export OLMOCR_CONFIDENCE_THRESHOLD=0.85
export OLMOCR_OUTPUT_FORMAT=jsonl

先进的加工流程 #

自定义管道配置 #

为特定文档类型构建自定义处理管道:```python from olmocr import PipelineBuilder

Build a legal document pipeline #

legal_pipeline = PipelineBuilder() .set_ocr_model(“sergeyzh/LaVIT”) .set_layout_parser(“layoutlmv3”) .set_table_strategy(“preserve”) .set_output_format(“structured_json”) .set_metadata_extraction([“citations”, “footnotes”, “headers”]) .build()

Build an academic paper pipeline #

academic_pipeline = PipelineBuilder() .set_ocr_model(“donut”) .set_layout_parser(“unisal”) .set_table_strategy(“flatten”) .set_output_format(“markdown”) .set_metadata_extraction([“abstract”, “references”, “authors”]) .build()

### 性能基准测试

测量和优化处理速度:```bash
# Run benchmark suite
python -m olmocr.benchmark   --input /datasets/benchmark/   --output benchmark_results.json   --workers 16   --batch-sizes 1 8 16 32 64

# View results
python -m olmocr.benchmark --plot benchmark_results.json
from olmocr import Benchmark

benchmark = Benchmark()
metrics = benchmark.compare_models([
    "sergeyzh/LaVIT-Gemma-2-2B",
    "naver-clova-x/donut",
    "amazon/titan-ocr"
], test_dataset="/datasets/test/")

print(metrics.summary())
# Model                  | Accuracy | Speed (pages/min)
# LaVIT-Gemma-2-2B       | 95.2%    | 45
# Donut                  | 93.8%    | 30
# Titan OCR              | 91.5%    | 60

插件架构 #

自定义 OCR 插件 #

使用自定义 OCR 引擎扩展 OLMoCRO:```python from olmocr.plugins import BaseOCRPlugin

class CustomOCRPlugin(BaseOCRPlugin): name = “custom-ocr” version = “1.0”

def recognize(self, image: bytes) -> str:
    # Your custom OCR logic
    return self.custom_engine.process(image)

def post_process(self, text: str) -> str:
    # Clean up OCR output
    return text.strip()

Register and use #

plugin = CustomOCRPlugin() plugin.register() result = plugin.process(“document.pdf”)

## 部署模式

### Kubernetes 部署```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: olmocr-processor
spec:
  replicas: 3
  selector:
    matchLabels:
      app: olmocr
  template:
    metadata:
      labels:
        app: olmocr
    spec:
      containers:
      - name: processor
        image: allenai/olmocr:latest
        resources:
          requests:
            cpu: "2"
            memory: "8Gi"
            nvidia.com/gpu: "1"
        volumeMounts:
        - name: data
          mountPath: /data
      volumes:
      - name: data
        persistentVolumeClaim:
          claimName: olmocr-data

CI/CD 管道```yaml #

name: OCR Processing Pipeline on: push: branches: [main] jobs: process: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Process PDFs run: | pip install olmocr olmocr batch –input ./docs –output ./text - name: Upload results uses: actions/upload-artifact@v4 with: name: processed-text path: ./text/

## 数据隐私和合规性

### GDPR 合规性```python
from olmocr import PrivacyFilter

filter = PrivacyFilter()

# Remove PII from OCR output
clean_text = filter.remove_pii(
    ocr_result="document_text",
    pii_types=["email", "phone", "ssn", "address"],
    method="redact"
)

# Anonymize personal data
anonymized = filter.anonymize(
    documents="/datasets/personal-docs/",
    output="/datasets/anonymized/",
    preserve_structure=True
)

数据保留政策```bash #

Configure automatic data cleanup #

python -m olmocr.retention –policy daily –keep-days 90 –cleanup-temp –archive-to s3://archives/olmocr/

Monitor retention compliance #

python -m olmocr.retention –status –report compliance-report.json

## 结论

OLMoCRO 代表了用于 AI 训练的开源 PDF 处理的重大进步。通过将最先进的 OCR 与法学硕士特定的优化相结合,它填补了人工智能培训管道中的关键空白。随着对高质量、多样化训练数据的需求不断增长,像 OLMoCRO 这样的工具对于人工智能开发的民主化将变得越来越重要。

AllenAI 对开源工具的承诺继续加速整个人工智能研究社区的发展,使各种规模的组织都可以使用先进的功能。

💬 留言讨论