pdf-extraction-fallbacks-7d54a9
できること
このスキルは、ダウンロードや抽出に失敗する可能性のあるPDFからテキストを得るための手順です。規制文書や機関の文書を集める人向けです。
使う場面
- ✓規制や機関の文書のダウンロードが、小さなエラーファイルになったとき。
- ✓PDFがスクリプトやサイト間の制限で保護されているかもしれないとき。
- ✓代替手段を用意したうえで、PDFから信頼できるテキストが必要なとき。
スキルのリンク
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks-7d54a9/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“この機関のPDFをダウンロードして、テキストを抽出してください。ファイルがエラーページなら教えて、別の方法を試してください。”
毎週5つの新しいスキル。1分で読めます。
仕組み
AIはファイルをダウンロードし、約1キロバイト未満、またはHTMLに見える場合は拒否し、その後pdftotextでテキストを抽出して、必要ならほかの代替ツールを順に試します。
技術的な内容(元のSKILL.md)
作者による元のテキスト(英語)をGitHubからそのまま表示しています。
PDF Extraction Fallbacks
This skill provides a robust workflow for extracting text from PDFs when source documents may fail to download or extract due to JavaScript protection, CORS restrictions, or encoding issues.
When to Use
- Downloading regulatory documents from government/agency websites
- Extracting text from PDFs that may be JavaScript-protected
- Handling PDFs with potential CORS or encoding issues
- When you need reliable text extraction with guaranteed fallbacks
Core Workflow
Step 1: Download with Validation
# Download PDF and immediately validate
curl -L -o document.pdf "URL_HERE"
# 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 "FAIL: File too small ($FILE_SIZE bytes) - likely error page"
# Log the actual content to diagnose
head -c 500 document.pdf
exit 1
fi
# Check for HTML/error content instead of PDF
if head -c 500 document.pdf | grep -qi "<!DOCTYPE html\|<html\|error\|access denied"; then
echo "FAIL: Downloaded HTML/error page instead of PDF"
exit 1
fi
Step 2: Sequential Extraction Fallbacks
Try extraction methods in order of reliability:
Fallback 1: pdftotext (poppler-utils)
if command -v pdftotext &> /dev/null; then
pdftotext -layout document.pdf output.txt 2>/dev/null
if [ -s output.txt ] && [ $(wc -c < output.txt) -gt 100 ]; then
echo "SUCCESS: pdftotext extraction"
exit 0
fi
fi
Fallback 2: PyMuPDF (fitz)
import fitz # PyMuPDF
def extract_with_pymupdf(pdf_path):
try:
doc = fitz.open(pdf_path)
text = ""
for page in doc:
text += page.get_text()
doc.close()
if len(text.strip()) > 100:
return text
return None
except Exception as e:
print(f"PyMuPDF failed: {e}")
return None
Fallback 3: pdfplumber
import pdfplumber
def extract_with_pdfplumber(pdf_path):
try:
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"
if len(text.strip()) > 100:
return text
return None
except Exception as e:
print(f"pdfplumber failed: {e}")
return None
Step 3: Content Sanity Check
After any extraction, validate the output:
def validate_extraction(text, min_chars=100, min_words=20):
"""Check if extracted text is meaningful content."""
if not text:
return False, "Empty extraction"
text = text.strip()
if len(text) < min_chars:
return False, f"Too short: {len(text)} chars"
words = text.split()
if len(words) < min_words:
return False, f"Too few words: {len(words)}"
# Check for error patterns
error_patterns = [
"access denied", "permission denied", "javascript required",
"failed to load", "cannot display", "corrupted"
]
text_lower = text.lower()
for pattern in error_patterns:
if pattern in text_lower[:500]: # Check beginning
return False, f"Error pattern detected: {pattern}"
return True, "Valid extraction"
Complete Python Implementation
import requests
import subprocess
import os
from pathlib import Path
def robust_pdf_extraction(url, output_path="extracted.txt", temp_pdf="temp.pdf"):
"""
Multi-fallback PDF extraction with validation at each step.
Returns (success, text_or_error)
"""
# Step 1: Download with validation
try:
response = requests.get(url, timeout=30, headers={
'User-Agent': 'Mozilla/5.0 (compatible; DocumentExtractor/1.0)'
})
response.raise_for_status()
except Exception as e:
return False, f"Download failed: {e}"
# Check response size
if len(response.content) < 1024:
return False, f"Downloaded content too small: {len(response.content)} bytes"
# Check for HTML error pages
if response.content[:500].lower().find(b'<html') != -1:
return False, "Downloaded HTML page instead of PDF"
# Save PDF
Path(temp_pdf).write_bytes(response.content)
# Step 2: Try extraction methods in order
extraction_methods = [
("pdftotext", extract_p
よくある質問
どのサイズを失敗とみなしますか?
約1キロバイト未満のファイルは、エラーページの可能性が高いとしてガイドは拒否します。
HTMLページはどう見分けられますか?
ファイルの先頭近くにあるHTMLのタグや、access deniedなどの言葉を探します。
pdftotextの後には何を試しますか?
ガイドは、順に他のフォールバックの方法へ進みます。
詳細
作者による元の説明
Multi-fallback PDF extraction with sequential approaches and early failure detection
repo: HKUDS/AgentPilot
人気
- GitHubのスター
- 7.8k
- ランキング
- #12924
- ライセンス
- MIT
- 更新日
- 2026/11/1
コメント
- …
このリポジトリの他のスキル
agentpilot
7.8kエージェントが、作業を準備し、変更案を提案してテストし、評価するAgentPilotのループを実行することで、プロジェクトを段階的に改善できるよう支援します。
openspace
7.8kエージェントが、スキルを保存し取り出すツールであるOpenSpaceをセットアップし、MCPを通じてAIアプリに接続できるよう支援します。
rsi-arena
7.8kエージェントが、AIMEやTerminal-Benchなどの標準的なAIベンチマークテストをセットアップして実行し、異なる改善方法を比較できるよう支援します。
experiment-guide
7.8kエージェントが、プログラムを改善する方法を調べる間に、小さな実験を計画し、その結果を読み、発見を記録できるよう支援します。
似ているスキル
feishu-doc
394kテキスト、画像、表を含むFeishuのクラウドドキュメントを、ドキュメントツールを使って読み、作成し、編集するようエージェントを支援します。
feishu-drive
394kボットと共有されたFeishuのクラウドフォルダ内のファイルを閲覧、整理、コメントできるようエージェントを支援します。
feishu-perm
394kFeishuのファイルにアクセスできる人を確認し、変更するようエージェントを支援します。依頼を満たす最小の権限を選びます。