robust-pdf-extraction
하는 일
이 스킬은 타이핑된 텍스트든 스캔 이미지든 PDF에서 텍스트를 얻는 단계별 방법을 AI 에이전트에게 줍니다. 여러 형식이 섞인 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에 붙여넣으세요. 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.8kAIME나 Terminal-Bench 같은 표준 AI 벤치마크 테스트를 설정하고 실행해 서로 다른 개선 방법을 비교하도록 돕습니다.
experiment-guide
7.8k프로그램을 개선하는 방법을 조사하면서 작은 실험을 계획하고, 결과를 읽고, 발견 사항을 기록하도록 돕습니다.
비슷한 스킬
feishu-doc
394k에이전트가 문서 도구를 사용해 텍스트, 이미지, 표를 포함한 Feishu 클라우드 문서를 읽고, 만들고, 편집하도록 돕습니다.
feishu-drive
394k에이전트가 봇과 공유된 Feishu 클라우드 폴더의 파일을 찾아보고, 정리하고, 댓글을 달도록 돕습니다.
feishu-perm
394k에이전트가 요청을 충족하는 가장 작은 권한을 골라, Feishu 파일에 누가 접근할 수 있는지 확인하고 바꾸도록 돕습니다.