Zum Inhalt springen
Skillpedia
PDF, Word & Folien7.8k · #12924

pdf-extraction-fallbacks-7d54a9

Was er macht

Dieser Skill ist ein Ablauf, um Text aus PDFs zu holen, die sich nicht sauber herunterladen oder extrahieren lassen. Er richtet sich an Menschen, die behördliche oder regulatorische Dokumente sammeln.

Wann du ihn nutzt

  • ✓Wenn der Download eines behördlichen PDFs eine kleine Fehlerdatei ergibt.
  • ✓Wenn die PDF durch Skripte oder websiteübergreifende Einschränkungen geschützt sein könnte.
  • ✓Wenn ich verlässlich extrahierten Text aus einer PDF brauche und Ausweichoptionen wünsche.

Link zum Skill

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks-7d54a9/SKILL.md

Kopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.

So nutzt du ihn

Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.

Fertige Nachricht zum Einfügen

Nutze diesen Skill, um mir zu helfen: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallbacks-7d54a9/SKILL.md Lies die SKILL.md unter diesem Link und folge ihren Anweisungen für meine Aufgabe.
Soll deine KI Skills wie diesen selbst finden?Installiere den kostenlosen Skillpedia-MCP: eine Zeile, und sie durchsucht vor jeder Aufgabe 15.000+ Skills.In 1 Minute installieren →

Beispielanfrage an deine KI

“Lade bitte dieses Behörden-PDF herunter und extrahiere den Text. Wenn die Datei eine Fehlerseite ist, sag es mir und probiere eine andere Methode.”

5 neue Skills pro Woche. 1 Minute Lesezeit.

So funktioniert es

Die KI lädt die Datei herunter, lehnt sie ab, wenn sie unter etwa einem Kilobyte liegt oder wie HTML aussieht, und extrahiert dann den Text mit pdftotext und weicht bei Bedarf auf andere Werkzeuge der Reihe nach aus.

Technischer Inhalt (originale SKILL.md)

Originaltext des Autors, auf Englisch, direkt von 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
Häufige Fragen

Welche Größe gilt als Fehler?

Die Anleitung lehnt Dateien unter etwa 1 Kilobyte als wahrscheinliche Fehlerseiten ab.

Woran erkennt man eine HTML-Seite?

Die Anleitung sucht nach HTML-Tags oder Wörtern wie access denied am Anfang der Datei.

Was wird nach pdftotext probiert?

Die Anleitung geht danach zu weiteren Ausweichmethoden in fester Reihenfolge über.

Details

Originalbeschreibung des Autors

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

repo: HKUDS/AgentPilot

Beliebtheit

GitHub-Sterne
7.8k
Platz im Ranking
#12924
Lizenz
MIT
Aktualisiert
1.11.2026

Ist dieser Skill nützlich?

0

Anmelden um abzustimmen.

Kommentare

  • …

Weitere Skills aus diesem Repository

Ähnliche Skills