robust-pdf-extraction
它能做什么
这项技能为 AI 智能体提供了一种分步方法,无论 PDF 包含的是打印文字还是扫描图片,都能从中获取文字。它适合处理各种类型 PDF 的人。
适用场景
- ✓当你有类型未知的 PDF,其中一些可能是扫描件而非打印文字的时候。
- ✓当某个 PDF 很关键,提取失败会造成实际问题的时候。
- ✓当你需要处理一批格式各异的 PDF 的时候。
技能链接
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/robust-pdf-extraction/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请提取这十二份 PDF 中的文字。其中一些是扫描件,请逐一尝试各种方法,直到得到文字。”
每周 5 个新技能,1 分钟读完。
工作原理
智能体会先确认每个 PDF 存在,然后先尝试 pdfplumber。如果它返回的文字很少或没有,就尝试 pypdfium2;对于扫描文档,则使用 OCR 读取页面图片。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Robust PDF Extraction Workflow
This skill provides a systematic approach to extracting text from PDF files, handling both text-based and scanned/image-based documents through progressive fallback methods.
When to Use
- Processing PDFs of unknown or mixed types (text vs. scanned images)
- Critical document processing where extraction failure is not acceptable
- Batch processing multiple PDFs with varying formats
Workflow Steps
Step 1: Verify File Accessibility
Before attempting extraction, confirm the PDF exists and is readable:
# Check file exists and get basic info
ls -la /path/to/document.pdf
# Or search for files if location uncertain
find /path -name "*.pdf" -type f 2>/dev/null
Step 2: Attempt Primary Extraction (pdfplumber)
Start with pdfplumber for best text structure preservation:
import pdfplumber
def extract_with_pdfplumber(pdf_path):
text = ""
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
return text.strip()
Step 3: Fallback to Secondary Method (pypdfium2)
If pdfplumber returns empty or incomplete text:
import pdfium2
def extract_with_pypdfium2(pdf_path):
pdf = pdfium2.PdfDocument(pdf_path)
text = ""
for page in pdf:
text_page = page.get_textpage()
page_text = text_page.get_text_bounded()
if page_text:
text += page_text + "\n"
return text.strip()
Step 4: Fallback to Tertiary Method (pdftotext)
If pypdfium2 also fails, use command-line pdftotext:
pdftotext /path/to/document.pdf - 2>/dev/null
Or in Python:
import subprocess
def extract_with_pdftotext(pdf_path):
result = subprocess.run(
['pdftotext', pdf_path, '-'],
capture_output=True,
text=True
)
return result.stdout.strip()
Step 5: Detect Scanned/Image-Based PDFs
After each extraction attempt, verify text was actually extracted:
def is_meaningful_text(text, min_chars=50):
"""Check if extracted text is meaningful (not empty or just whitespace)"""
if not text:
return False
# Remove whitespace and check length
cleaned = ''.join(text.split())
return len(cleaned) >= min_chars
Step 6: OCR Fallback for Scanned Documents
If all text extraction methods return empty/insufficient text, the PDF is likely scanned. Use OCR:
import pdf2image
import pytesseract
from PIL import Image
def extract_with_ocr(pdf_path, dpi=300):
"""Extract text from scanned PDFs using OCR"""
text = ""
images = pdf2image.convert_from_path(pdf_path, dpi=dpi)
for image in images:
page_text = pytesseract.image_to_string(image)
text += page_text + "\n"
return text.strip()
Complete Workflow Function
def robust_pdf_extract(pdf_path):
"""
Extract text from PDF using progressive fallback methods.
Returns (text, method_used) tuple.
"""
methods = [
("pdfplumber", extract_with_pdfplumber),
("pypdfium2", extract_with_pypdfium2),
("pdftotext", extract_with_pdftotext),
]
for method_name, extract_func in methods:
try:
text = extract_func(pdf_path)
if is_meaningful_text(text):
return text, method_name
except Exception as e:
print(f"{method_name} failed: {e}")
continue
# All text methods failed - try OCR
try:
text = extract_with_ocr(pdf_path)
if is_meaningful_text(text):
return text, "ocr"
except Exception as e:
print(f"OCR failed: {e}")
return "", "failed"
Dependencies
Install required packages:
pip install pdfplumber pypdfium2 pdf2image pytesseract pillow
# Also need system packages:
# apt-get install poppler-utils tesseract-ocr # Debian/Ubuntu
# brew install poppler tesseract # macOS
Best Practices
- Log which method succeeded - helps identify document types for future optimization
- Set reasonable character thresholds - adjust
min_charsbased on expected document content - Handle exceptions gracefully - each method may fail for different reasons
- Consider DPI for OCR - higher DPI (300+) improves accuracy but increases processing time
- Cache results - if processing same PDFs repeatedly, store succe
常见问题
智能体首先尝试哪种方法?
这项技能从 pdfplumber 开始,因为它能较好地保留文字结构。
智能体什么时候使用 OCR?
当其他方法返回空白或不完整的文字时使用,这通常意味着页面是扫描件。
这项技能会先检查文件吗?
会。它会在提取前确认每个 PDF 存在且可读。
详情
作者的原始描述
Multi-method PDF extraction with sequential fallback and OCR for scanned documents
repo: HKUDS/AgentPilot
热度
- GitHub 星标
- 7.8k
- 排名
- #12976
- 许可证
- MIT
- 更新时间
- 2026/11/1
评论
- …
同一仓库的更多技能
agentpilot
7.8k帮你的智能体准备任务并运行 AgentPilot 循环,逐步改进项目:循环会提出修改、测试修改并为其打分。
openspace
7.8k帮你的智能体设置 OpenSpace,这是一个用于存储和获取智能体技能的工具,并通过 MCP 将其连接到你的 AI 应用。
rsi-arena
7.8k帮你的智能体设置并运行标准 AI 基准测试,例如 AIME 和 Terminal-Bench,用来比较不同的改进方法。
experiment-guide
7.8k帮你的智能体规划小型实验、阅读实验结果并记录发现,同时研究如何改进一个程序。