pdf-extraction-fallbacks
하는 일
이 스킬은 파싱 전에 검증하는 PDF 읽기 여러 방법의 작업 흐름입니다. 때때로 실패하는 출처에서 PDF 텍스트가 필요한 사람에게 맞습니다.
사용하는 경우
- ✓PDF 출처가 손상되었거나 오류 페이지로 바뀌었을 수 있을 때.
- ✓첫 번째 방법에서 PDF 텍스트 추출이 실패할 때.
- ✓어떤 방법이 작동했는지 기록을 남기고 싶은 경우.
스킬 링크
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“이 PDF 링크에서 텍스트를 가져와 주세요. 다운로드가 유효한지 확인하고, 여러 방법을 시도한 뒤 어떤 방법이 작동했는지 알려 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
AI는 파일을 내려받고, 크기와 PDF 시그니처를 확인한 뒤, 추출 방법을 하나씩 실행하고 성공한 방법을 기록합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
PDF Extraction with Multi-Fallback Strategy
Purpose
When extracting text from PDFs (especially regulatory documents, handbooks, or protected content), single-method approaches often fail due to JavaScript protection, CORS restrictions, encoding issues, or corrupted downloads. This skill provides a robust multi-fallback workflow that detects failures early and tries sequential extraction methods.
Core Pattern
- Download with validation - Check file size and content sanity immediately
- Sequential extraction attempts - Try multiple tools in order of reliability
- Early failure detection - Don't proceed with obviously corrupt files
- Document fallback path - Log which method succeeded for future reference
Step-by-Step Instructions
Step 1: Download and Validate
Before attempting extraction, validate the downloaded file:
# Download the PDF
curl -L -o document.pdf "$URL"
# Check file size (reject if < 1KB - likely error page)
FILE_SIZE=$(stat -f%z document.pdf 2>/dev/null || stat -c%s document.pdf 2>/dev/null)
if [ "$FILE_SIZE" -lt 1024 ]; then
echo "ERROR: File too small ($FILE_SIZE bytes) - likely not a valid PDF"
# Check if it's an HTML error page
head -c 200 document.pdf | grep -i "<html\|<!doctype\|error\|access denied" && \
echo "Detected HTML error page instead of PDF"
exit 1
fi
# Check PDF magic bytes
HEAD_BYTES=$(head -c 4 document.pdf)
if [ "$HEAD_BYTES" != "%PDF" ]; then
echo "ERROR: File does not start with PDF magic bytes"
head -c 100 document.pdf
exit 1
fi
Step 2: Primary Extraction (pdftotext)
# Try pdftotext first (fastest, most reliable for simple PDFs)
if command -v pdftotext &> /dev/null; then
pdftotext -layout document.pdf output.txt 2>/dev/null
if [ -s output.txt ]; then
WORD_COUNT=$(wc -w < output.txt)
if [ "$WORD_COUNT" -gt 50 ]; then
echo "SUCCESS: pdftotext extracted $WORD_COUNT words"
exit 0
fi
fi
fi
Step 3: Fallback 1 (PyMuPDF/fitz)
# Try PyMuPDF - handles more complex PDFs
import fitz # pymupdf
try:
doc = fitz.open("document.pdf")
text = ""
for page in doc:
text += page.get_text()
if len(text.strip()) > 500: # Sanity check
with open("output.txt", "w") as f:
f.write(text)
print(f"SUCCESS: PyMuPDF extracted {len(text)} characters")
else:
print("WARNING: PyMuPDF extraction too short, trying next method")
except Exception as e:
print(f"PyMuPDF failed: {e}")
Step 4: Fallback 2 (pdfplumber)
# Try pdfplumber - better for tables and structured content
import pdfplumber
try:
text = ""
with pdfplumber.open("document.pdf") as pdf:
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
if len(text.strip()) > 500:
with open("output.txt", "w") as f:
f.write(text)
print(f"SUCCESS: pdfplumber extracted {len(text)} characters")
else:
print("WARNING: pdfplumber extraction too short")
except Exception as e:
print(f"pdfplumber failed: {e}")
Step 5: Handle JavaScript-Protected Pages
If all methods fail, the PDF may be JavaScript-protected:
# Check for JavaScript in PDF
import fitz
doc = fitz.open("document.pdf")
has_js = False
for page in doc:
if page.get_java_script():
has_js = True
break
if has_js:
print("WARNING: PDF contains JavaScript - may be protected")
# Try rendering pages as images and OCR (requires additional tools)
# Or try alternative download source
Step 6: Alternative Sources
If the primary URL fails:
- Try alternative domains (e.g.,
.govmirrors, archive.org) - Check if the document is available via API
- Look for HTML version of the same content
- Search for the document title + "pdf" to find mirrors
Decision Tree
Download PDF
│
├─→ File < 1KB? → REJECT (likely error page)
├─→ No %PDF header? → REJECT (not a PDF)
│
└─→ Valid PDF
│
├─→ pdftotext → >50 words? → SUCCESS
│ └─→ Try next
│
├─→ PyMuPDF → >500 chars? → SUCCESS
│ └─→ Try next
│
├─→ pdfplumber → >500 chars? → SUCCESS
│ └─→ Try next
│
└─→ All failed → Check for JS protection, try alternat
자주 묻는 질문
파싱 전에 파일은 어떻게 확인하나요?
가이드는 파일 크기와, 파일 시작 부분이 HTML 페이지가 아니라 PDF처럼 보이는지 확인합니다.
성공한 방법을 왜 기록하나요?
가이드는 이후 작업에서 이미 작동한 방법을 쓰도록 돕는다고 설명합니다.
잘못된 다운로드는 건너뛸 수 있나요?
네, 유효한 PDF가 분명히 아니면 가이드는 일찍 멈춥니다.
상세 정보
작성자의 원본 설명
Multi-fallback PDF/text extraction with early failure detection and sequential tool fallbacks
repo: HKUDS/AgentPilot
인기도
- GitHub 스타
- 7.8k
- 순위
- #12925
- 라이선스
- 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 파일에 누가 접근할 수 있는지 확인하고 바꾸도록 돕습니다.