pdf-extract-ordered-fallback
Qué hace
Esta skill fija un orden claro de uso de herramientas para obtener el texto de PDF desde fuentes web. Está pensada para quienes sus tareas con PDF fallan por redirecciones, archivos corruptos o herramientas que faltan.
Cuándo usarla
- ✓Cuando un enlace de PDF redirige o devuelve una página web en lugar del archivo.
- ✓Cuando necesito asegurarme de que el PDF es un archivo real antes de leerlo.
- ✓Cuando quiero un orden fijo de métodos para que la IA no pruebe herramientas al azar.
Link de la skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/pdf-download-extract-fallback-enhanced/SKILL.mdCó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
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Descarga el PDF de este enlace y extrae su texto. Sigue un orden fijo de herramientas y dime cuál funcionó.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La IA descarga el archivo con una petición de estilo navegador, comprueba su tipo con el comando file y después prueba la lectura sencilla, pdftotext y PyMuPDF en orden hasta que salga texto.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de GitHub.
PDF Download and Extract with Ordered Fallback
This skill provides a robust workflow for acquiring PDF documents from web sources and extracting their text content, with a clearly ordered sequence of tool invocations to maximize success rate.
Overview
When working with PDFs from web sources, encounters with JavaScript redirects, corrupted files, missing tools, or inaccessible content are common. This workflow ensures maximum success rate through a严格 ordered fallback sequence that prioritizes shell-based tools over Python sandbox execution.
Ordered Tool Chain Summary
| Step | Tool | Method | Priority |
|---|---|---|---|
| 0 | read_file | Direct PDF text extraction | First attempt |
| 1 | run_shell | pdftotext command | Primary fallback (if Step 0 returns binary/fails) |
| 2 | execute_code_sandbox | PyMuPDF Python library | Secondary fallback (if Step 1 fails) |
| 3 | Domain knowledge | Manual content generation | Last resort |
Key principle: Always try shell tools (run_shell) before Python sandbox (execute_code_sandbox) when both are viable options. Shell execution is more reliable in constrained environments.
Step-by-Step Instructions
Step 0: Initial Extraction Attempt with read_file Tool
First, attempt to extract PDF text using the read_file tool. This is the simplest approach and handles many PDFs correctly:
read_file filetype="pdf" file_path="path/to/document.pdf"
Expected outcomes:
- Success: Returns extracted text content - proceed to use this directly
- Binary/Image data returned: The tool failed to extract text; file content is raw binary or image data
- Immediate action: Proceed to Step 1 (run_shell with pdftotext)
- Error returned: Tool failed entirely; proceed to Step 1 (run_shell with pdftotext)
Critical: If read_file returns binary data (PNG/JPEG headers, raw PDF bytes), do NOT attempt to parse it manually. Immediately switch to shell-based pdftotext.
Step 1: Download PDF with Browser User-Agent
Many PDF hosting sites use JavaScript-based redirects or block automated requests. Use curl with a realistic browser user-agent:
curl -L -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" -o output.pdf "URL_HERE"
Key flags:
-L: Follow redirects-A: Set user-agent header to mimic a real browser-o: Specify output filename
Step 2: Verify File Type Before Parsing
Always validate the downloaded file is actually a PDF before attempting extraction:
file output.pdf
Expected output should contain "PDF document". If not:
- The URL may have redirected to an HTML error page
- The file may be corrupted
- Access may be blocked
Step 3: Primary Shell Extraction with pdftotext via run_shell
This step takes priority over Python-based extraction. If Step 0 failed or if you're working with a newly downloaded PDF, use run_shell with pdftotext before attempting any Python libraries:
pdftotext downloaded.pdf extracted.txt
Execute via run_shell:
run_shell command="pdftotext downloaded.pdf extracted.txt"
If pdftotext is not available, install it first:
# Debian/Ubuntu
apt-get update && apt-get install -y poppler-utils
# macOS
brew install poppler
# RHEL/CentOS
yum install -y poppler-utils
Why shell-first? Shell-based pdftotext is more reliable, faster, and avoids sandbox execution issues that can affect Python code execution in constrained environments.
Step 4: Secondary Python Fallback with PyMuPDF via execute_code_sandbox
Only if run_shell with pdftotext fails or is unavailable, fall back to Python's PyMuPDF library via execute_code_sandbox:
import fitz # PyMuPDF
doc = fitz.open("downloaded.pdf")
text = ""
for page in doc:
text += page.get_text()
doc.close()
with open("extracted.txt", "w") as f:
f.write(text)
Execute within execute_code_sandbox:
execute_code_sandbox code="<Python code above>"
Install if needed:
pip install pymupdf
Note: Some environments may experience execute_code_sandbox failures (unknown errors). This is why shell-based extraction (Step 3) must be attempted first.
Step 5: Graceful Degradation to Domain Knowledge
If the PDF cannot be accessed or extracted after all attempts:
- Document the failure mode (network issue, corrupted file, access denied, etc.)
- Extract any partia
Preguntas frecuentes
¿Cómo se comprueba el tipo de archivo?
El comando file confirma si la descarga es un PDF o una página de error.
¿Por qué comprobar antes de analizar?
Una redirección puede entregar una página HTML en lugar del PDF, lo que haría fallar la extracción.
¿Cuál es el último recurso?
La guía indica generar el contenido a partir del conocimiento del tema cuando ningún método de extracción funciona.
Detalles
Descripción original del autor
PDF extraction with ordered tool chain: read_file, then run_shell/pdftotext, then execute_code_sandbox/PyMuPDF
repo: HKUDS/AgentPilot
Popularidad
- Estrellas en GitHub
- 7,8 mil
- Posición en el ranking
- #12918
- Licencia
- MIT
- Actualizada
- 1/11/2026
Comentarios
- …
Más skills de este repositorio
agentpilot
7,8 milAyuda a tu agente a mejorar un proyecto paso a paso, preparando una tarea y ejecutando el bucle de AgentPilot que propone, prueba y puntúa cambios.
openspace
7,8 milAyuda a tu agente a configurar OpenSpace, una herramienta que guarda y recupera skills de agentes, y a conectarla a tu app de IA mediante MCP.
rsi-arena
7,8 milAyuda a tu agente a configurar y ejecutar pruebas de referencia de IA conocidas, como AIME y Terminal-Bench, para comparar distintos métodos de mejora.
experiment-guide
7,8 milAyuda a tu agente a planificar experimentos pequeños, leer sus resultados y anotar conclusiones mientras investiga cómo mejorar un programa.
Skills parecidas
feishu-doc
394 milAyuda a tu agente a leer, crear y editar documentos en la nube de Feishu, incluidos texto, imágenes y tablas, usando la herramienta de documentos.
feishu-drive
394 milPermite que tu agente explore, organice y comente archivos de una carpeta de la nube de Feishu que se haya compartido con el bot.
feishu-perm
394 milAyuda a tu agente a revisar y cambiar quién puede acceder a un archivo de Feishu, eligiendo el permiso más pequeño que cumpla tu petición.