跳到正文
Skillpedia
PDF、Word 与幻灯片7.8k · #12924

pdf-extraction-fallbacks-7d54a9

它能做什么

这项技能是一套工作流程,用于获取可能下载失败或无法干净提取的 PDF 中的文字。它适合收集法规或机构文件的人。

适用场景

  • ✓当下载法规或机构 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。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks-7d54a9/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“请下载这份机构 PDF 并提取文字。如果文件是错误页面,请告诉我,并换一种方法。”

每周 5 个新技能,1 分钟读完。

工作原理

AI 会下载文件;如果文件小于约 1 KB 或看起来像 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 KB 的文件视为可能是错误页面,并予以拒绝。

如何识别 HTML 页面?

指南会在文件开头附近查找 HTML 标签或“拒绝访问”之类的字样。

pdftotext 之后会尝试什么?

指南会按顺序尝试其他备用方法。

详情

作者的原始描述

Multi-fallback PDF extraction with sequential approaches and early failure detection

repo: HKUDS/AgentPilot

热度

GitHub 星标
7.8k
排名
#12924
许可证
MIT
更新时间
2026/11/1

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能