Saltar al contenido
Skillpedia
PDF, Word y diapositivas7,8 mil · #12922

pdf-extraction-fallback-80956b

Qué hace

Esta skill abarca la descarga de PDF de sitios web oficiales o protegidos y la lectura de su texto, con comprobaciones de descargas fallidas. Está pensada para quienes reúnen manuales o documentos normativos de la web.

Cuándo usarla

  • ✓Cuando la descarga de un PDF de un sitio de un organismo o de una empresa devuelve un archivo muy pequeño o roto.
  • ✓Cuando un sitio puede bloquear las descargas automáticas o cargar su contenido con scripts.
  • ✓Cuando necesito texto fiable de un PDF descargado de la web.

Link de la skill

https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallback-80956b/SKILL.md

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-extraction-fallback-80956b/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“Descarga el manual en PDF de este sitio de la agencia y extrae su texto. Si la descarga parece rota, prueba de otra forma.”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

La IA descarga el archivo con curl, comprueba su tamaño y si contiene una página de error, y después extrae el texto con herramientas de respaldo si el archivo es válido.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de GitHub.

PDF Extraction Fallback Workflow

This skill provides a robust, multi-layered approach to downloading and extracting text from PDF documents when sources may be protected, corrupted, or inaccessible via standard methods.

When to Use

  • Downloading regulatory documents, handbooks, or official PDFs from government/enterprise websites
  • Sources that may have JavaScript protection, CORS restrictions, or dynamic content
  • When initial PDF downloads produce suspiciously small files or error content
  • Any scenario requiring reliable text extraction from potentially problematic PDF sources

Core Workflow

Step 1: Download with Validation

# Download PDF with size check
curl -L -o output.pdf "https://example.com/document.pdf"

# Early failure detection: check file size
file_size=$(stat -c%s output.pdf 2>/dev/null || stat -f%z output.pdf)

if [ "$file_size" -lt 1000 ]; then
    echo "WARNING: File size ($file_size bytes) suggests failed download or error page"
    # Check for HTML/JavaScript error content
    if head -c 500 output.pdf | grep -qi "<html\|<script\|error\|access denied"; then
        echo "FAILURE: File contains error message, not PDF content"
        rm output.pdf
        # Proceed to alternative download method
    fi
fi

Step 2: Sequential Extraction Fallbacks

Try extraction methods in order, moving to next on failure:

Fallback 1: pdftotext (command-line)

if command -v pdftotext &> /dev/null; then
    pdftotext output.pdf output.txt
    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 Validation

After any extraction method succeeds:

def validate_extracted_text(text, min_length=100):
    """Validate extracted content is meaningful"""
    if not text or len(text.strip()) < min_length:
        return False
    
    # Check for common error patterns
    error_patterns = [
        "access denied", "permission denied", "error", 
        "javascript", "<html", "<script", "404", "403"
    ]
    text_lower = text.lower()[:500]  # Check first 500 chars
    for pattern in error_patterns:
        if pattern in text_lower:
            return False
    
    return True

Complete Workflow Script

#!/usr/bin/env python3
"""
Robust PDF extraction with multiple fallbacks
"""
import subprocess
import os
import sys

def download_pdf(url, output_path):
    """Download PDF with validation"""
    subprocess.run(["curl", "-L", "-o", output_path, url], check=True)
    
    # Validate download
    if not os.path.exists(output_path):
        return False
    
    file_size = os.path.getsize(output_path)
    if file_size < 1000:
        with open(output_path, 'r', errors='ignore') as f:
            content = f.read(500).lower()
            if any(x in content for x in ['<html', '<script', 'error', 'denied']):
                os.remove(output_path)
                return False
    return True

def extract_text(pdf_path):
    """Try multiple extraction methods"""
    
    # Method 1: pdftotext
    try:
        result = subprocess.run(
            ["pdftotext", pdf_path, "-"],
            capture_output=True, text=True, timeout=60
        )
        if result.stdout and len(result.stdout.strip()) > 100:
            return result.stdout
    except:
        pass
    
    # Method 2: PyMuPDF
    try:
        import fitz
        doc = fitz.open(pdf_path)
        text = "".join(page.get_text() for page in doc)
        doc.close()
        if len(text.strip()) >
Preguntas frecuentes

¿Cómo se detecta una descarga fallida?

La guía comprueba si el archivo es muy pequeño o si contiene HTML o un mensaje de acceso denegado.

¿Qué pasa con un archivo defectuoso?

La guía lo elimina y prueba un método de descarga alternativo.

¿Qué herramienta extrae primero el texto?

La primera opción de la guía es pdftotext desde la shell.

Detalles

Descripción original del autor

Multi-fallback PDF download and text extraction with early failure detection

repo: HKUDS/AgentPilot

Popularidad

Estrellas en GitHub
7,8 mil
Posición en el ranking
#12922
Licencia
MIT
Actualizada
1/11/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas