用途
本技能面向 OCRmyPDF 的 Python API 与插件机制,用于在 Python 程序中以编程方式调用 OCRmyPDF,将其集成到应用或服务中,并通过插件接口扩展或替换 OCR 引擎。命令行用法参见 ocrmypdf 技能,批量脚本参见 ocrmypdf-batch。
主要能力
Python API
基本调用:
import ocrmypdf
exit_code = ocrmypdf.ocr('input.pdf', 'output.pdf')
带选项调用:
exit_code = ocrmypdf.ocr(
'input.pdf',
'output.pdf',
language='eng+fra',
deskew=True,
rotate_pages=True,
skip_text=True,
optimize=2,
jobs=4,
)
返回码判断:
import ocrmypdf
result = ocrmypdf.ocr('input.pdf', 'output.pdf')
if result == ocrmypdf.ExitCode.ok:
print("OCR completed successfully")
elif result == ocrmypdf.ExitCode.already_done_ocr:
print("PDF already has OCR text")
elif result == ocrmypdf.ExitCode.input_file:
print("Input file issue")
else:
print(f"Error: {result}")
常用 API 参数:
- language(str):Tesseract 语言,如 'eng+fra'
- deskew(bool):校正倾斜页面
- rotate_pages(bool):自动旋转页面
- skip_text(bool):跳过已有文本的页面
- force_ocr(bool):对所有页面强制 OCR
- redo_ocr(bool):替换已有 OCR
- optimize(int):优化级别(0-3)
- output_type(str):'pdfa'、'pdf'、'auto'、'none'
- jobs(int):并行工作进程数
- sidecar(str):旁路文本文件路径
- image_dpi(int):图像输入的 DPI
- clean(bool):使用 unpaper 清理页面(仅 OCR)
- clean_final(bool):清理页面并用于输出
- remove_background(bool):去除噪点背景
- oversample(int):对低分辨率图像进行过采样 DPI
- pages(str):页面范围,如 '1,3,5-10'
- title(str):输出 PDF 标题
- author(str):输出 PDF 作者
集成示例:Flask Web 服务
from flask import Flask, request, send_file
import ocrmypdf
import tempfile
import os
app = Flask(__name__)
@app.route('/ocr', methods=['POST'])
def ocr_endpoint():
"""OCR a PDF via HTTP POST."""
if 'file' not in request.files:
return {'error': 'No file uploaded'}, 400
uploaded = request.files['file']
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as inp:
uploaded.save(inp.name)
out_path = inp.name.replace('.pdf', '_ocr.pdf')
try:
result = ocrmypdf.ocr(
inp.name, out_path,
language='eng',
skip_text=True,
optimize=2,
)
if result == ocrmypdf.ExitCode.ok:
return send_file(out_path, as_attachment=True,
download_name='ocr_output.pdf')
return {'error': f'OCR failed: {result}'}, 500
finally:
os.unlink(inp.name)
if os.path.exists(out_path):
os.unlink(out_path)
if __name__ == '__main__':
app.run(port=5000)
Streamlit Web UI
OCRmyPDF 提供可选的基于 Streamlit 的 Web UI:
pip install ocrmypdf[webservice]
# See OCRmyPDF docs for launching the web service
插件生态
OCRmyPDF 的插件接口允许替换 OCR 引擎。可用插件包括:
- OCRmyPDF-EasyOCR:用 EasyOCR(基于 PyTorch)替换 Tesseract,强烈建议使用 GPU。
pip install ocrmypdf-easyocr
# Usage
ocrmypdf --plugin ocrmypdf_easyocr -l en input.pdf output.pdf
- OCRmyPDF-PaddleOCR:用 PaddleOCR 替换 Tesseract,强大的 GPU 加速引擎。
pip install ocrmypdf-paddleocr
# Usage
ocrmypdf --plugin ocrmypdf_paddleocr input.pdf output.pdf
- OCRmyPDF-AppleOCR:用 Apple Vision Framework 替换 Tesseract,仅限 macOS。
pip install ocrmypdf-appleocr
# Usage
ocrmypdf --plugin ocrmypdf_appleocr input.pdf output.pdf
paperless-ngx 集成
paperless-ngx 内部使用 OCRmyPDF 实现可搜索的文档管理,配置参见 paperless-ngx 文档。
自定义插件
通过实现 OCRmyPDF 插件接口创建自定义 OCR 插件:
# my_ocr_plugin.py
from ocrmypdf import OcrEngine, hookimpl
class MyOcrEngine(OcrEngine):
"""Custom OCR engine implementation."""
@staticmethod
def version():
return "1.0.0"
@staticmethod
def creator_tag(options):
return "MyOCR"
def recognize(self, input_file, output_file, output_text, options):
# Implement OCR logic here
pass
@hookimpl
def get_ocr_engine():
return MyOcrEngine()
# Use custom plugin
ocrmypdf --plugin my_ocr_plugin input.pdf output.pdf
快速参考
- Python API 基本:ocrmypdf.ocr('in.pdf', 'out.pdf')
- 带选项:ocrmypdf.ocr('in.pdf', 'out.pdf', language='eng', deskew=True)
- 检查结果:if result == ocrmypdf.ExitCode.ok: ...
- EasyOCR 插件:ocrmypdf --plugin ocrmypdf_easyocr in.pdf out.pdf
- PaddleOCR 插件:ocrmypdf --plugin ocrmypdf_paddleocr in.pdf out.pdf
- AppleOCR 插件:ocrmypdf --plugin ocrmypdf_appleocr in.pdf out.pdf
适用场景
需要在 Python 应用中集成 PDF OCR 能力、构建 OCR Web 服务、批量处理 PDF,或通过插件替换 OCR 引擎(如使用 GPU 加速的 EasyOCR/PaddleOCR、macOS 上的 Apple Vision)的场景。
限制与排查
- 导入错误:确保在 Python 环境中执行 pip install ocrmypdf。
- 找不到插件:检查插件是否已安装(pip install ocrmypdf-easyocr)。
- 未使用 GPU(EasyOCR/PaddleOCR):确保已安装 CUDA/GPU 驱动。
- 内存问题:大文件使用 jobs=1,分批处理。
参考资料:OCRmyPDF API Reference、OCRmyPDF Plugin Interface、OCRmyPDF-EasyOCR、OCRmyPDF-PaddleOCR、OCRmyPDF-AppleOCR、paperless-ngx。