跳到正文
cccskills
免费在 GitHub 公开

pdf-text-extraction-fallback-85d5ca

Extract readable text from PDFs when normal file reading returns garbled or unusable content. The workflow switches between extraction tools, checks the results, and includes optical character recognition for scanned pages when needed.

中文简介正在准备中。当前显示英语简介。

原文查看原文说明

Fallback workflow for extracting text from PDFs when read_file returns binary data

查看安装方法

适用场景

  • Recovering readable text from garbled PDF output
  • Preparing PDF text for data processing
  • Extracting text from scanned PDFs
  • Checking extracted text for expected keywords

包含的文件(2)

  • SKILL.md4.6 KB
  • .skill_id49 B

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

PDF Text Extraction Fallback

Use this skill when read_file returns binary data or garbled content for PDF files instead of readable text. This workflow provides a reliable fallback using command-line PDF tools.

When to Use

  • read_file with filetype: pdf returns binary data, unreadable characters, or errors
  • You need to extract text from a PDF to process its contents
  • Standard file reading methods fail to extract usable text

Step-by-Step Instructions

Step 1: Detect Binary/Unreadable PDF Output

After attempting to read a PDF with read_file, check if the output is:

  • Binary data (contains null bytes, non-printable characters)
  • Garbled text with many special characters
  • Empty or truncated content
# Example of problematic output from read_file
%PDF-1.4
1 0 obj
<< /Type /Catalog ...

If the output looks like raw PDF structure or binary, proceed to Step 2.

Step 2: Use shell_agent with PDF Tools

Invoke shell_agent to extract text using pdftotext (preferred) or pdfplumber (Python fallback):

Task: Extract all text content from <filename.pdf> using pdftotext or pdfplumber.
Output the extracted text in readable format. If pdftotext is not available, use Python with pdfplumber library.

Example shell_agent invocation:

shell_agent task="Extract text from Move_Out_Inspection_Tracker.pdf using pdftotext. Save output to a .txt file and return the content."

Step 3: Validate Extracted Content

After extraction, validate that the content contains expected text patterns:

# Validation checklist
def validate_pdf_extraction(text, expected_patterns=None):
    checks = [
        bool(text.strip()),  # Not empty
        len(text) > 50,  # Has substantial content
        not text.startswith('%PDF'),  # Not raw PDF structure
    ]
    
    if expected_patterns:
        for pattern in expected_patterns:
            checks.append(pattern.lower() in text.lower())
    
    return all(checks)

Common expected patterns to check:

  • Document-specific keywords (e.g., "inspection", "resident", "date")
  • Expected data formats (dates, names, IDs)
  • Minimum word count threshold

Step 4: Handle Extraction Failures

If validation fails:

  1. Try alternative tool: If pdftotext failed, try pdfplumber:

    shell_agent task="Extract text from <file.pdf> using Python pdfplumber library. Handle any encoding issues."
    
  2. Try OCR fallback: For scanned PDFs:

    shell_agent task="This PDF may be scanned. Use pytesseract or similar OCR tool to extract text from <file.pdf>."
    
  3. Report specific error: Document what patterns were expected but not found.

Step 5: Proceed with Data Processing

Once validated text is obtained:

  • Parse the extracted text for required data
  • Store or process the content as needed
  • Continue with the original task workflow

Code Example

# Complete extraction workflow
def extract_pdf_text_fallback(pdf_path, expected_patterns=None):
    """Extract text from PDF with fallback handling."""
    
    # Step 1: Try read_file first
    content = read_file(filetype="pdf", file_path=pdf_path)
    
    # Step 2: Check if binary/unreadable
    if is_binary_or_garbled(content):
        # Step 3: Use shell_agent fallback
        result = shell_agent(
            task=f"Extract all text from {pdf_path} using pdftotext. Return the text content."
        )
        content = result.stdout
        
        # Step 4: Validate
        if not validate_pdf_extraction(content, expected_patterns):
            # Try pdfplumber as secondary fallback
            result = shell_agent(
                task=f"Extract text from {pdf_path} using Python pdfplumber library."
            )
            content = result.stdout
    
    return content

def is_binary_or_garbled(text):
    """Check if text appears to be binary or unreadable."""
    if not text:
        return True
    if text.startswith('%PDF'):
        return True
    # Check for high ratio of non-printable characters
    non_printable = sum(1 for c in text if ord(c) > 127 or ord(c) < 32)
    return non_printable / len(text) > 0.3

Tips

  • pdftotext is typically faster and pre-installed on many systems
  • pdfplumber handles complex layouts better but requires Python
  • For scanned PDFs, you'll need OCR tools (tesseract, pytesseract)
  • Always validate extracted content matches your expected data patterns
  • Save intermediate extraction results for debugging if needed

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Prepare audio stems, the separate parts of a track, for mixing by matching their durations with silence, loops, or crossfades. Verify each generated and processed file before moving to the next production step.

中文简介正在准备中。当前显示英语简介。

  • Match audio parts with different durations
  • Extend drums and melodic parts using suitable methods
  • Check audio specifications before mixing
HKUDS/OpenSpace77602026年8月13日 更新

Produce audio in separate stems, meaning individual instrument tracks, and verify each output as you go. Align track lengths with silence, loops, or crossfades, then apply effects, mix a master, and package the files.

中文简介正在准备中。当前显示英语简介。

  • Align instrument tracks to a reference audio file
  • Choose how to extend tracks that are too short
  • Verify audio properties after generation and effects
HKUDS/OpenSpace77602026年8月13日 更新

Build serverless endpoints that relay external API requests for a dashboard while keeping API keys on the server. Includes Vercel examples for input checks, caching, cross-origin access, and consistent JSON responses.

中文简介正在准备中。当前显示英语简介。

  • Connect a dashboard to external APIs without exposing API keys
  • Create endpoints for stock quotes and news
  • Standardize API responses and error handling
HKUDS/OpenSpace77602026年8月13日 更新

Produce a master track and separate audio parts through a structured Python workflow. Apply filters and reverb, export WAV files with consistent settings, package them in a ZIP archive, and check that the deliverables meet the requested specifications.

中文简介正在准备中。当前显示英语简介。

  • Export a master track with separate audio parts
  • Apply filters and reverb to audio
  • Check duration and format across deliverables
HKUDS/OpenSpace77602026年8月13日 更新

Keep document creation moving when web searches and page retrieval repeatedly fail. The skill preserves the original task, uses the model’s existing knowledge, and clearly identifies information that could not be checked against external sources.

中文简介正在准备中。当前显示英语简介。

  • Continue drafting after repeated web retrieval failures
  • Preserve task requirements during network errors
  • Mark information that could not be externally verified
HKUDS/OpenSpace77602026年8月13日 更新

When Python execution repeatedly fails in execute_code_sandbox, use a file-based alternative: save the script, run it through the shell, and capture results or errors. The guidance covers paths, imports, timeouts, structured output, and optional cleanup.

中文简介正在准备中。当前显示英语简介。

  • Retry Python work through the shell after repeated sandbox failures
  • Run longer tasks with an adjusted timeout
  • Execute Python work that needs multiple files or system utilities
HKUDS/OpenSpace77602026年8月13日 更新

查看 HKUDS 的全部技能

报告此技能的问题