본문으로 건너뛰기
Skillpedia
PDF, Word, 슬라이드7.8k · #12976

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/robust-pdf-extraction/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

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

  1. Log which method succeeded - helps identify document types for future optimization
  2. Set reasonable character thresholds - adjust min_chars based on expected document content
  3. Handle exceptions gracefully - each method may fail for different reasons
  4. Consider DPI for OCR - higher DPI (300+) improves accuracy but increases processing time
  5. 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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬