robust-pdf-extraction
Skill này làm gì
Skill này cho AI agent một cách từng bước để lấy văn bản từ PDF, dù chúng là văn bản đánh máy hay ảnh quét. Nó dành cho những người xử lý PDF có nhiều loại khác nhau.
Khi nào nên dùng
- ✓Khi bạn có các PDF chưa rõ loại, và một số có thể là bản quét thay vì văn bản đánh máy.
- ✓Khi một PDF rất quan trọng và việc trích xuất thất bại sẽ gây vấn đề thật sự.
- ✓Khi bạn cần xử lý một loạt PDF có định dạng khác nhau.
Liên kết skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/robust-pdf-extraction/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Lấy văn bản từ mười hai file PDF này. Một số là bản quét, nên hãy thử từng phương pháp cho đến khi có văn bản.”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Agent kiểm tra từng PDF có tồn tại, rồi thử pdfplumber trước. Nếu kết quả có rất ít hoặc không có văn bản, nó thử pypdfium2, và với tài liệu quét, nó dùng OCR để đọc ảnh trang.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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
Câu hỏi thường gặp
Agent thử phương pháp nào trước?
Skill bắt đầu với pdfplumber vì nó giữ tốt cấu trúc văn bản.
Khi nào agent dùng OCR?
Nó dùng OCR khi các phương pháp khác trả về văn bản trống hoặc thiếu, thường có nghĩa là các trang là bản quét.
Skill có kiểm tra file trước không?
Có, nó xác nhận mỗi PDF có tồn tại và đọc được trước khi thử trích xuất.
Chi tiết
Mô tả gốc của tác giả
Multi-method PDF extraction with sequential fallback and OCR for scanned documents
repo: HKUDS/AgentPilot
Độ phổ biến
- Sao GitHub
- 7.8k
- Vị trí xếp hạng
- #12976
- Giấy phép
- MIT
- Cập nhật
- 1/11/2026
Bình luận
- …
Thêm skill từ kho mã này
agentpilot
7.8kGiúp agent của bạn cải thiện dự án từng bước bằng cách chuẩn bị tác vụ và chạy vòng lặp AgentPilot, gồm đề xuất, kiểm thử và chấm điểm thay đổi.
openspace
7.8kGiúp agent của bạn thiết lập OpenSpace, công cụ lưu và lấy lại skill của agent, rồi kết nối nó với ứng dụng AI của bạn qua MCP.
rsi-arena
7.8kGiúp agent của bạn thiết lập và chạy các bài kiểm thử benchmark AI chuẩn, như AIME và Terminal-Bench, để so sánh các phương pháp cải tiến khác nhau.
experiment-guide
7.8kGiúp agent của bạn lên kế hoạch các thí nghiệm nhỏ, đọc kết quả và ghi lại phát hiện khi tìm cách cải thiện một chương trình.
Skill tương tự
feishu-doc
394kGiúp agent của bạn đọc, tạo và sửa tài liệu đám mây Feishu, gồm văn bản, hình ảnh và bảng, bằng công cụ tài liệu.
feishu-drive
394kCho phép agent của bạn duyệt, sắp xếp và bình luận các file trong một thư mục đám mây Feishu đã được chia sẻ với bot.
feishu-perm
394kGiúp agent của bạn kiểm tra và thay đổi ai có quyền truy cập một file Feishu, chọn quyền nhỏ nhất đáp ứng yêu cầu của bạn.