Python 中使用 pdf-inspector - pdf-inspector 教程
API 参考Python
pdf-inspector 的 Python 绑定就叫 pdf-inspector(导入名 pdf_inspector),基于 PyO3。处理期间会释放 GIL——它可以安全地和 asyncio、多线程混用,不会卡住整个进程。
安装
pip install pdf-inspector预构建 wheel 覆盖 CPython ≥3.8 的 Linux(x86_64、aarch64)、macOS(Intel、Apple Silicon)、Windows x64。包自带类型存根(pdf_inspector.pyi),类型提示开箱即用。仓库内开发可用 maturin develop --release。
核心 API
import pdf_inspector
# 1. 一步到位:检测 + 提取 + Markdown
result = pdf_inspector.process_pdf("document.pdf")
print(result.pdf_type) # "text_based" | "scanned" | "image_based" | "mixed"
print(result.confidence) # 0.0 - 1.0
print(result.page_count)
print(result.markdown)
# 2. 只判定类型(不提取)
info = pdf_inspector.detect_pdf("document.pdf")
# 3. 纯文本
text = pdf_inspector.extract_text("document.pdf")
# 4. 带位置信息的文本项(字体、坐标全都有)
items = pdf_inspector.extract_text_with_positions("document.pdf")
for item in items[:5]:
print(f"'{item.text}' at ({item.x:.0f}, {item.y:.0f}) size={item.font_size}")字节入口:process_pdf_bytes(data)、detect_pdf_bytes(data) 等,文件已在内存里时免落盘。
常用函数速查
| 函数 | 说明 |
|---|---|
process_pdf(path, pages=None) | 完整处理(检测 + 提取 + Markdown) |
detect_pdf(path) | 只判定类型,最快 |
classify_pdf(path) | 轻量分类(含需 OCR 页码与置信度) |
extract_text(path) | 纯文本提取 |
extract_text_with_positions(path) | 带 X/Y 坐标与字体信息 |
extract_pages_markdown(path, pages=None) | 逐页 Markdown + 版面元数据 |
extract_text_in_regions(path, regions) | 按包围盒区域提取,带 needs_ocr 标记 |
process_pdf_with_ocr(path, **opts) | 选择性 OCR,每页标注来源 |
extract_structure_elements(path) | tagged PDF 的结构树元素 |
结果对象关键字段
result = pdf_inspector.process_pdf("document.pdf")
result.pdf_type # 文档类型
result.markdown # Markdown 字符串(detect_pdf 时为 None)
result.confidence # 分类置信度 0.0-1.0
result.pages_needing_ocr # 需要 OCR 的页码列表(1-indexed)
result.has_encoding_issues # True = 存在损坏的字体编码,建议 OCR 兜底
result.pages_with_tables # 含表格的页码
result.pages_with_columns # 多栏排版的页码常见场景
先分类再路由的批量入库
from pathlib import Path
import pdf_inspector
for pdf in Path("./pdfs").glob("*.pdf"):
result = pdf_inspector.process_pdf(pdf)
if result.pdf_type != "text_based":
print(f"跳过 {pdf.name}:{result.pdf_type},需 OCR 页 {result.pages_needing_ocr}")
continue
out = pdf.with_suffix(".md")
out.write_text(result.markdown or "", encoding="utf-8")只处理部分页
result = pdf_inspector.process_pdf("big-report.pdf", pages=[1, 3, 5])
# extract_pages_markdown 同样支持 pages 参数(0-indexed)
per_page = pdf_inspector.extract_pages_markdown("big-report.pdf", pages=[0, 2])选择性 OCR
ocr = pdf_inspector.process_pdf_with_ocr(
"mixed.pdf",
page_numbers=[1, 3], # 1-indexed
model_directory="/opt/models/pp-ocrv6-small",
offline=True, # 禁止联网下载
)
for page in ocr.pages:
print(page.page_number, page.provenance.source) # native | ocr | fusedOCR 运行时需要 PDFium 与 ONNX Runtime 共享库(环境变量 PDFIUM_LIB_PATH、ORT_DYLIB_PATH),详见官方 OCR 运行时指南。默认 wheel 不含这些外部组件——不用 OCR 就永远不会加载它们。
小提示
- 只要类型就别调
process_pdf——detect_pdf/classify_pdf快一个数量级 pages_needing_ocr是 1-indexed,而extract_pages_markdown返回里的page是 0-indexed,写路由逻辑时留意- 版本以官方 docs/python.md 为准