pdf-extraction-fallback
它能做什么
这项技能是一套从 Python 库到命令行工具的 PDF 与文档提取方法阶梯。它适合第一次尝试读取就失败的人。
适用场景
- ✓当文档读取工具在一个必须读取的 PDF 上失败的时候。
- ✓当文档已加密,或格式导致第一种方法无法使用的时候。
- ✓当我希望 AI 持续尝试各种选项,而不是在一次错误后就停下的时候。
技能链接
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallback/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“第一个工具无法读取我的 PDF。请继续尝试其他方法,直到获得文字为止。”
每周 5 个新技能,1 分钟读完。
工作原理
AI 先尝试 Python 的 PDF 库,然后退回到 shell 中的 pdftotext,并沿着方法列表继续尝试,直到提取出文字。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
PDF Extraction Fallback Strategy
When processing documents (especially PDFs), initial extraction attempts may fail due to formatting, encryption, or tool limitations. This skill provides a systematic fallback approach that tries multiple extraction methods before declaring failure.
Core Principle
Never declare completion after a single tool failure. Instead, iterate through a hierarchy of extraction methods, each with different capabilities and limitations.
Fallback Hierarchy
Attempt extraction methods in this order:
Stage 1: Direct PDF Reading
Try native PDF libraries first (fastest, preserves structure):
import PyPDF2
from pypdf import PdfReader
def extract_with_pypdf(pdf_path):
reader = PdfReader(pdf_path)
text = ""
for page in reader.pages:
text += page.extract_text() or ""
return text
Stage 2: Shell-based Extraction (pdftotext)
If Stage 1 fails, use system tools:
# Install if needed: apt-get install poppler-utils
pdftotext -layout input.pdf output.txt
pdftotext -raw input.pdf output.txt # Alternative layout
import subprocess
def extract_with_pdftotext(pdf_path):
result = subprocess.run(
['pdftotext', '-layout', pdf_path, '-'],
capture_output=True, text=True
)
if result.returncode == 0:
return result.stdout
raise Exception("pdftotext failed")
Stage 3: Alternative Python Parsers
Try different Python libraries with varying capabilities:
# pdfplumber - better for tables
import pdfplumber
def extract_with_pdfplumber(pdf_path):
text = ""
with pdfplumber.open(pdf_path) as pdf:
for page in pdf.pages:
text += page.extract_text() or ""
return text
# pdfminer - handles complex layouts
from pdfminer.high_level import extract_text
def extract_with_pdfminer(pdf_path):
return extract_text(pdf_path)
Stage 4: OCR Fallback
For scanned images or when text extraction fails:
# Using tesseract
convert input.pdf output-%d.png # Convert to images first
tesseract output-0.png result --psm 6
# Using pytesseract
from pdf2image import convert_from_path
import pytesseract
def extract_with_ocr(pdf_path):
images = convert_from_path(pdf_path, dpi=300)
text = ""
for image in images:
text += pytesseract.image_to_string(image)
return text
Implementation Pattern
def robust_pdf_extraction(pdf_path):
"""Try multiple extraction methods until one succeeds."""
extraction_methods = [
("PyPDF2", extract_with_pypdf),
("pdftotext", extract_with_pdftotext),
("pdfplumber", extract_with_pdfplumber),
("pdfminer", extract_with_pdfminer),
("OCR", extract_with_ocr),
]
errors = []
for method_name, method_func in extraction_methods:
try:
print(f"Trying {method_name}...")
text = method_func(pdf_path)
if text and text.strip():
print(f"Success with {method_name}")
return text
else:
errors.append(f"{method_name}: empty result")
except Exception as e:
errors.append(f"{method_name}: {str(e)}")
print(f"{method_name} failed: {e}")
continue
# All methods failed
raise Exception(f"All extraction methods failed:\n" + "\n".join(errors))
Success Criteria
A method is considered successful when:
- No exceptions are raised during execution
- Non-empty text is returned (text.strip() has content)
- Content quality meets task requirements (check for expected keywords/patterns)
Best Practices
- Log each attempt - Record which methods were tried and why they failed
- Validate output - Check extracted text contains expected content markers
- Graceful degradation - Proceed with partial data if full extraction isn't possible
- Cache successful method - Remember which method worked for similar files
- Set timeouts - Prevent OCR or complex parsing from hanging indefinitely
Common Failure Modes
| Symptom | Likely Cause | Best Fallback |
|---|---|---|
| Empty pages | Image-based PDF | OCR (Stage 4) |
| Garbled text | Encoding issues | pdftotext (Stage 2) |
| Missing tables | Simple parser | pdfplumber (Stage 3) |
| Permission errors | Encrypted PDF | Check password/permissions first |
| Layout lost | Complex formatting |
常见问题
哪种方法优先?
指南首先使用原生的 Python PDF 库,它能较好地保留结构。
为什么接下来使用 pdftotext?
它是一个系统工具,在 Python 库失败时仍可使用。
AI 在一次失败后应该停止吗?
不应。指南要求,不能在一次工具失败后就宣布完成。
详情
作者的原始描述
Multi-stage fallback strategy for PDF/document extraction using sequential tool alternatives
repo: HKUDS/AgentPilot
热度
- GitHub 星标
- 7.8k
- 排名
- #12923
- 许可证
- 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帮你的智能体规划小型实验、阅读实验结果并记录发现,同时研究如何改进一个程序。