Docx Parse Resilient logo

Docx Parse Resilient

OrganizationPopular
HKUDS
docx-parse-resilient

Extract text from DOCX files with shell-primary approach and Python zipfile fallback for maximum reliability

Overview

PublisherHKUDS
RepositoryOpenSpace
Skill namedocx-parse-resilient
Stars
7.7K
Forks
918
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by HKUDS on GitHub. Read the source before you install it.

Installation

Install the Docx Parse Resilient AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/HKUDS/OpenSpace.git /tmp/OpenSpace
mkdir -p .claude/skills
cp -r /tmp/OpenSpace/benchmarks/gdpval/skills/docx-shell-parse-enhanced .claude/skills/docx-parse-resilient
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Docx Parse Resilient in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Docx Parse Resilient on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Docx Parse Resilient is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Resilient DOCX Text Extraction

Extract text from Microsoft Word (.docx) files using a robust two-tier approach: shell-based extraction as the primary method, with Python zipfile fallback when shell commands fail or return no output.

When to Use

  • Python environment may lack python-docx but zipfile module is available (standard library)
  • Working in constrained or inconsistent environments (containers, minimal images, CI/CD)
  • Shell unzip command returns errors or no output
  • Need reliable extraction with automatic fallback

Core Technique

DOCX files are ZIP archives containing XML files. This skill provides two extraction methods:

  1. Primary (Shell): unzip -p + sed for fast extraction
  2. Fallback (Python): zipfile module for reliable extraction when shell fails

Step-by-Step Instructions

1. Verify the DOCX file exists

bash
ls -la document.docx

2. Test shell extraction first (recommended)

Try the shell-based approach:

bash
unzip -p document.docx word/document.xml 2>/dev/null | sed -e 's/<[^>]*>//g'

3. Check if shell extraction produced output

Verify the shell method returned content:

bash
content=$(unzip -p document.docx word/document.xml 2>/dev/null | sed -e 's/<[^>]*>//g')
if [ -z "$content" ]; then
    echo "Shell extraction returned no output, trying Python fallback..."
fi

4. Use Python zipfile fallback if needed

When shell commands fail or return empty output, use Python's standard zipfile module:

bash
python3 -c "
import zipfile
import sys
import re

try:
    with zipfile.ZipFile('document.docx', 'r') as z:
        content = z.read('word/document.xml').decode('utf-8')
        # Strip XML tags
        text = re.sub(r'<[^>]*>', '', content)
        # Clean whitespace
        lines = [line.strip() for line in text.split('\n') if line.strip()]
        print('\n'.join(lines))
except Exception as e:
    print(f'Error: {e}', file=sys.stderr)
    sys.exit(1)
"

5. Save extracted text to file

bash
# Try shell first
unzip -p document.docx word/document.xml 2>/dev/null | \
  sed -e 's/<[^>]*>//g' > output.txt

# Verify output has content
if [ ! -s output.txt ]; then
    # Fallback to Python
    python3 -c "
import zipfile, re
with zipfile.ZipFile('document.docx', 'r') as z:
    content = z.read('word/document.xml').decode('utf-8')
    text = re.sub(r'<[^>]*>', '', content)
    lines = [line.strip() for line in text.split('\n') if line.strip()]
    print('\n'.join(lines))
" > output.txt
fi

Complete Shell Function with Fallback

Add this resilient function to your scripts:

bash
parse_docx_resilient() {
    local file="$1"
    local output="$2"
    
    if [ ! -f "$file" ]; then
        echo "Error: File not found: $file" >&2
        return 1
    fi
    
    # Primary: Shell extraction
    local content
    content=$(unzip -p "$file" word/document.xml 2>/dev/null | \
        sed -e 's/<[^>]*>//g' | \
        sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' | \
        sed -e '/^$/d')
    
    # Check if shell extraction succeeded
    if [ -n "$content" ]; then
        echo "$content" > "${output:-/dev/stdout}"
        return 0
    fi
    
    # Fallback: Python zipfile
    echo "Shell extraction failed, using Python fallback..." >&2
    python3 -c "
import zipfile, sys, re
try:
    with zipfile.ZipFile('$file', 'r') as z:
        content = z.read('word/document.xml').decode('utf-8')
        text = re.sub(r'<[^>]*>', '', content)
        lines = [line.strip() for line in text.split('\n') if line.strip()]
        print('\n'.join(lines))
except Exception as e:
    print(f'Python extraction failed: {e}', file=sys.stderr)
    sys.exit(1)
" > "${output:-/dev/stdout}" || return 1
}

# Usage examples:
# parse_docx_resilient document.docx          # Output to stdout
# parse_docx_resilient document.docx out.txt  # Output to file

Python Script Alternative

For complex workflows, save as a standalone script:

python
#!/usr/bin/env python3
"""DOCX text extractor with resilient fallback."""

import zipfile
import sys
import re
import subprocess

def extract_with_shell(filepath):
    """Try shell-based extraction first."""
    try:
        result = subprocess.run(
            ['unzip', '-p', filepath, 'word/document.xml'],
            capture_output=True, text=True, timeout=10
        )
        if result.returncode == 0 and result.stdout.strip():
            text = re.sub(r'<[^>]*>', '', result.stdout)
            lines = [l.strip() for l in text.split('\n') if l.strip()]
            return '\n'.join(lines)
    except Exception:
        pass
    return None

def extract_with_python(filepath):
    """Fallback Python zipfile extraction."""
    with zipfile.ZipFile(filepath, 'r') as z:
        content = z.read('word/document.xml').decode('utf-8')
        text = re.sub(r'<[^>]*>', '', content)
        lines = [l.strip() for l in text.split('\n') if l.strip()]
        return '\n'.join(lines)

def parse_docx_resilient(filepath):
    """Extract text with automatic fallback."""
    # Try shell first
    content = extract_with_shell(filepath)
    if content:
        return content, 'shell'
    
    # Fallback to Python
    content = extract_with_python(filepath)
    return content, 'python'

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print("Usage: parse_docx_resilient.py <file.docx>", file=sys.stderr)
        sys.exit(1)
    
    content, method = parse_docx_resilient(sys.argv[1])
    if content:
        print(f"# Extracted using {method} method", file=sys.stderr)
        print(content)
    else:
        print("Failed to extract text from DOCX", file=sys.stderr)
        sys.exit(1)

Limitations

  • Does not preserve formatting, images, or tables structure
  • May include some residual XML entity references
  • Works best for simple text extraction needs
  • DOCX must be a valid Office Open XML format
  • Python fallback requires Python 3 with standard library (no external packages)

Verification

Confirm extraction worked by checking output:

bash
# Test shell method
parse_docx_resilient document.docx | head -20

# Test with file output
parse_docx_resilient document.docx extracted.txt
wc -l extracted.txt  # Should show line count > 0

# Verify content
grep -c "[a-zA-Z]" extracted.txt  # Should show character content

Troubleshooting

Shell returns "unknown error" or no output:

  • This is expected in some environments
  • The function automatically falls back to Python zipfile
  • Check which unzip to verify unzip is available

Python also fails:

  • Verify the file is a valid DOCX: file document.docx
  • Check if file is corrupted: unzip -t document.docx
  • Ensure Python 3 is available: python3 --version

File not found errors:

  • Use absolute path or verify working directory
  • Check file permissions: ls -la document.docx

Environment Detection

To pre-detect which method to use:

bash
# Check if unzip is available
if command -v unzip &> /dev/null; then
    echo "Shell method available"
else
    echo "Only Python method available"
fi

# Check if Python 3 is available
if command -v python3 &> /dev/null; then
    echo "Python fallback available"
else
    echo "Warning: No extraction method available!"
fi

Frequently asked questions

What does the Docx Parse Resilient AI skill do?

Extract text from DOCX files with shell-primary approach and Python zipfile fallback for maximum reliability

Why use Docx Parse Resilient on TypingMind?

Because you install it once and use it with any model. Docx Parse Resilient is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Docx Parse Resilient in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/HKUDS/OpenSpace/tree/main/benchmarks/gdpval/skills/docx-shell-parse-enhanced. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Docx Parse Resilient?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Docx Parse Resilient?

As many as you like. As long as a model supports skills, you can use Docx Parse Resilient with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Docx Parse Resilient AI skill free?

Yes. It is published on GitHub by HKUDS under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇