pdfparsing / README.md
uppalmaurya's picture
Add Hugging Face Spaces configuration to README.md
75380b7
|
Raw
History Blame Contribute Delete
15.3 kB

A newer version of the Gradio SDK is available: 6.20.0

Upgrade
metadata
title: PDF Parser MCP Server
emoji: ๐Ÿ“„
colorFrom: blue
colorTo: purple
sdk: gradio
sdk_version: 4.44.0
app_file: main.py
pinned: false

PDF Parser MCP Server

A FastAPI-based PDF processing system with MCP (Model Context Protocol) integration for Claude Desktop. Upload PDFs, extract text, generate AI summaries, and interact with documents through Claude Desktop.

๐Ÿš€ Quick Start

๐Ÿ“– For detailed setup instructions, see SETUP.md

1. Install Dependencies

# Create virtual environment
uv venv
source .venv/bin/activate  # Unix
# or .venv\Scripts\activate  # Windows

# Install all dependencies
uv sync
uv pip install torch torchvision transformers docling-core pdf2image pillow

2. Setup Environment

# Create .env file
touch .env  # Create manually on Windows

# Add your Anthropic API key to .env
ANTHROPIC_API_KEY=your_actual_api_key_here
MAX_TOKENS=180000
CHUNK_SIZE=8000

3. Start the System

# Start FastAPI server with auto-reload
uvicorn main:app --reload --host 0.0.0.0 --port 8000

# Test the system
python test_smoldocling.py

4. Configure MCP Server

# Start MCP server (separate terminal)
python mcp_main.py

4. Configure Claude Desktop

  1. Open Claude Desktop configuration:

    • Windows: %APPDATA%\Claude\claude_desktop_config.json
    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Linux: ~/.config/claude/claude_desktop_config.json
  2. Add the server configuration:

{
  "mcpServers": {
    "pdf-parser": {
      "command": "uv",
      "args": ["--directory", "/path/to/your/pdf-parser", "run", "mcp_main.py"],
      "cwd": "/path/to/your/pdf-parser"
    }
  }
}
  1. Update the paths to match your project location
  2. Restart Claude Desktop

5. Upload and Process PDFs

# Upload a PDF
curl -X POST "http://localhost:8000/upload-pdf/" -F "file=@your_document.pdf"

# Check status
curl "http://localhost:8000/status/{file_id}"

# List documents
curl "http://localhost:8000/documents/"

6. Use with Claude Desktop

Once configured, you can interact with your PDFs through Claude Desktop:

You: "List all my documents"
Claude: [Shows all processed PDFs with IDs and status]

You: "What is the summary of document abc-123?"
Claude: [Provides detailed summary of the document]

You: "Search for 'financial projections' in all documents"
Claude: [Searches and shows relevant sections]

You: "What are the key findings in document xyz-456?"
Claude: [Analyzes and provides key insights]

๐Ÿ”ง System Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Claude        โ”‚    โ”‚   MCP Server    โ”‚    โ”‚   FastAPI       โ”‚
โ”‚   Desktop       โ”‚โ—„โ”€โ”€โ”€โ”ค   (@mcp.tool)   โ”‚โ—„โ”€โ”€โ”€โ”ค   Server        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚                         โ”‚
                              โ”‚                         โ”‚
                              โ–ผ                         โ–ผ
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Document      โ”‚    โ”‚   SmolDocling   โ”‚
                    โ”‚   Storage       โ”‚    โ”‚   + PyMuPDF     โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                              โ”‚                         โ”‚
                              โ”‚                         โ”‚
                              โ–ผ                         โ–ผ
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Anthropic     โ”‚    โ”‚   Smart         โ”‚
                    โ”‚   Claude API    โ”‚    โ”‚   Chunking      โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

                    

๐Ÿ”„ Complete Workflow Pipeline

Visual Overview

graph TD
    A["๐Ÿ“„ PDF Upload"] --> B["๐Ÿ” File Validation"]
    B --> C["๐Ÿ’พ Save to uploads/"]
    C --> D["๐Ÿš€ Background Processing"]
    
    D --> E["๐Ÿ–ผ๏ธ PDF โ†’ Images<br/>(pdf2image)"]
    E --> F["๐Ÿค– SmolDocling Processing<br/>(Vision-Language Model)"]
    F --> G["๐Ÿ“ DocTags Generation<br/>(Layout + Structure)"]
    G --> H["โœ‚๏ธ Text Extraction<br/>(Markdown Format)"]
    
    H --> I["๐Ÿงฎ Token Analysis<br/>(tiktoken)"]
    I --> J["๐Ÿ“ฆ Smart Chunking<br/>(8K tokens max)"]
    J --> K["๐ŸŽฏ Claude 3.5 Sonnet<br/>(Summarization)"]
    
    K --> L["๐Ÿ’พ Storage.json<br/>(Document + Chunks + Summary)"]
    L --> M["๐Ÿ”„ MCP Server Update"]
    M --> N["๐Ÿ–ฅ๏ธ Claude Desktop<br/>(Tools Available)"]
    
    N --> O["๐Ÿ’ฌ User Queries"]
    O --> P["๐Ÿ› ๏ธ MCP Tools<br/>(list, search, summarize)"]
    P --> Q["๐ŸŽฏ Intelligent Responses"]
    
    %% Fallback path
    F -.->|"๐Ÿ”„ Fallback"| R["๐Ÿ“„ PyMuPDF<br/>(Traditional OCR)"]
    R -.-> H

Phase 1: Document Upload & Initial Processing

๐Ÿ“„ PDF Upload (FastAPI)
    โ†“
๐Ÿ” File Validation (.pdf extension)
    โ†“
๐Ÿ’พ Save to uploads/ directory with UUID
    โ†“
๐Ÿš€ Background Processing Initiated

Phase 2: Advanced Text Extraction (SmolDocling)

๐Ÿ“„ PDF File
    โ†“
๐Ÿ–ผ๏ธ PDF โ†’ Images (pdf2image)
    โ”‚   โ”œโ”€โ”€ Page 1.png
    โ”‚   โ”œโ”€โ”€ Page 2.png
    โ”‚   โ””โ”€โ”€ Page N.png
    โ†“
๐Ÿค– SmolDocling Processing (per page)
    โ”‚   โ”œโ”€โ”€ Vision-Language Model Analysis
    โ”‚   โ”œโ”€โ”€ Document Structure Recognition
    โ”‚   โ”œโ”€โ”€ Table/Code/Formula Detection
    โ”‚   โ””โ”€โ”€ DocTags Generation
    โ†“
๐Ÿ“ DocTags โ†’ Structured Text
    โ”‚   โ”œโ”€โ”€ Layout Preservation
    โ”‚   โ”œโ”€โ”€ Hierarchy Maintenance
    โ”‚   โ””โ”€โ”€ Content Organization
    โ†“
๐Ÿ“‹ Consolidated Text Output
    โ”œโ”€โ”€ Page 1 Content
    โ”œโ”€โ”€ Page 2 Content
    โ””โ”€โ”€ Page N Content

๐Ÿ”„ FALLBACK: If SmolDocling fails โ†’ PyMuPDF extraction

Phase 3: Intelligent Chunking

๐Ÿ“‹ Complete Document Text
    โ†“
๐Ÿงฎ Token Analysis (tiktoken)
    โ”‚   โ”œโ”€โ”€ Total token count calculation
    โ”‚   โ”œโ”€โ”€ Per-page token assessment
    โ”‚   โ””โ”€โ”€ Chunking strategy determination
    โ†“
โœ‚๏ธ Smart Chunking Process
    โ”‚   โ”œโ”€โ”€ Respect page boundaries
    โ”‚   โ”œโ”€โ”€ Split oversized pages intelligently
    โ”‚   โ”œโ”€โ”€ Maintain context windows
    โ”‚   โ””โ”€โ”€ Preserve document structure
    โ†“
๐Ÿ“ฆ Chunk Generation
    โ”‚   โ”œโ”€โ”€ Chunk 1 (8K tokens max)
    โ”‚   โ”œโ”€โ”€ Chunk 2 (8K tokens max)
    โ”‚   โ””โ”€โ”€ Chunk N (remaining content)
    โ†“
๐Ÿ’พ Store chunks with metadata

Phase 4: AI-Powered Summarization

๐Ÿ“ฆ Document Chunks
    โ†“
๐ŸŽฏ Summarization Strategy Selection
    โ”œโ”€โ”€ Single Chunk โ†’ Direct summarization
    โ””โ”€โ”€ Multiple Chunks โ†’ Hierarchical approach
    โ†“
๐Ÿค– Claude 3.5 Sonnet Processing
    โ”‚   โ”œโ”€โ”€ Individual chunk summaries
    โ”‚   โ”œโ”€โ”€ Cross-chunk analysis
    โ”‚   โ”œโ”€โ”€ Overall document synthesis
    โ”‚   โ””โ”€โ”€ Key insights extraction
    โ†“
๐Ÿ“„ Summary Generation
    โ”‚   โ”œโ”€โ”€ Overall summary
    โ”‚   โ”œโ”€โ”€ Per-chunk summaries
    โ”‚   โ”œโ”€โ”€ Key findings
    โ”‚   โ””โ”€โ”€ Important details

Phase 5: Storage & Indexing

๐Ÿ“Š Processed Document Data
    โ†“
๐Ÿ’พ Storage.json Update
    โ”‚   โ”œโ”€โ”€ Document metadata
    โ”‚   โ”œโ”€โ”€ Extracted text
    โ”‚   โ”œโ”€โ”€ Chunk information
    โ”‚   โ”œโ”€โ”€ Summary data
    โ”‚   โ””โ”€โ”€ Processing timestamps
    โ†“
๐Ÿ”„ MCP Server Synchronization
    โ”‚   โ”œโ”€โ”€ Update document registry
    โ”‚   โ”œโ”€โ”€ Enable Claude Desktop access
    โ”‚   โ””โ”€โ”€ Prepare for querying
    โ†“
โœ… Processing Complete

Phase 6: Query & Interaction (Claude Desktop)

๐Ÿ’ฌ User Query (Claude Desktop)
    โ†“
๐Ÿ› ๏ธ MCP Tool Selection
    โ”‚   โ”œโ”€โ”€ list_documents()
    โ”‚   โ”œโ”€โ”€ get_document_summary()
    โ”‚   โ”œโ”€โ”€ get_document_content()
    โ”‚   โ”œโ”€โ”€ search_documents()
    โ”‚   โ””โ”€โ”€ answer_question()
    โ†“
๐Ÿ“Š Data Retrieval
    โ”‚   โ”œโ”€โ”€ Document lookup
    โ”‚   โ”œโ”€โ”€ Content extraction
    โ”‚   โ”œโ”€โ”€ Context preparation
    โ”‚   โ””โ”€โ”€ Response formatting
    โ†“
๐ŸŽฏ Intelligent Response
    โ”‚   โ”œโ”€โ”€ Contextual answers
    โ”‚   โ”œโ”€โ”€ Document citations
    โ”‚   โ”œโ”€โ”€ Relevant excerpts
    โ”‚   โ””โ”€โ”€ Follow-up suggestions

๐ŸŽฏ Key Processing Features

SmolDocling Advantages

  • ๐Ÿง  Intelligent OCR: Understands document layout and structure
  • ๐Ÿ“Š Table Recognition: Preserves table formatting and relationships
  • ๐Ÿ’ป Code Detection: Maintains code block formatting and syntax
  • ๐Ÿ”ข Formula Processing: Handles mathematical expressions correctly
  • ๐Ÿ“ Layout Awareness: Preserves document hierarchy and spacing
  • ๐Ÿ–ผ๏ธ Figure Classification: Identifies and categorizes visual elements

Robust Error Handling

  • ๐Ÿ”„ Automatic Fallback: SmolDocling โ†’ PyMuPDF if needed
  • โšก Performance Optimization: GPU acceleration when available
  • ๐Ÿ’พ Memory Management: Efficient processing for large documents
  • ๐Ÿ›ก๏ธ Error Recovery: Graceful handling of processing failures

Scalability Features

  • ๐Ÿš€ Background Processing: Non-blocking document processing
  • ๐Ÿ“ฆ Efficient Chunking: Token-aware content splitting
  • ๐Ÿ” Fast Search: Optimized text search across documents
  • ๐Ÿ’จ Quick Retrieval: Instant access to processed content

๐Ÿ“Š Features

  • Multi-page PDF Support: Handle 70-80+ page documents
  • Advanced Text Extraction: Uses SmolDocling (256M parameter vision-language model) for intelligent document understanding with PyMuPDF fallback
  • Layout-Aware Processing: Preserves document structure, tables, code blocks, formulas, and formatting
  • AI Summarization: Claude 3.5 Sonnet generates comprehensive summaries
  • Token-aware Chunking: Automatically splits large documents respecting token limits
  • MCP Integration: Seamless Claude Desktop integration with @mcp.tool() decorators
  • Background Processing: Asynchronous PDF processing
  • Search & Query: Full-text search across all documents
  • RESTful API: Complete REST API for programmatic access

๐Ÿค– SmolDocling Integration

This project now uses SmolDocling, a compact 256M parameter vision-language model for advanced document understanding:

Why SmolDocling?

  • Better Text Recognition: Understands document layout, tables, code blocks, and mathematical formulas
  • Structure Preservation: Maintains document hierarchy and formatting
  • Compact Model: Only 256M parameters, efficient for local processing
  • Multi-Modal: Processes documents as images for better OCR accuracy

How It Works

  1. PDF to Images: Converts PDF pages to images using pdf2image
  2. SmolDocling Processing: Each page is processed by the vision-language model
  3. DocTags Generation: Creates structured markup preserving layout and content
  4. Text Extraction: Converts DocTags to clean text for further processing
  5. Fallback: Automatically falls back to PyMuPDF if SmolDocling fails

Requirements

  • GPU Recommended: CUDA-compatible GPU for optimal performance
  • CPU Fallback: Works on CPU but slower processing
  • Memory: ~2GB GPU memory or 4GB RAM for CPU processing

๐Ÿ› ๏ธ MCP Tools Available in Claude Desktop

Tool Description Usage
list_documents List all processed PDFs "List my documents"
get_document_summary Get AI-generated summary "Summarize document abc-123"
get_document_content Get full or chunked content "Show content of document xyz-456"
search_documents Search across all documents "Search for 'budget' in all docs"
get_document_metadata Get document metadata "Show metadata for document abc-123"
answer_question Answer questions about documents "What are the main conclusions?"

๐Ÿ” Technical Details

PDF Processing

  • Library: PyMuPDF (fitz) for robust text extraction
  • Multi-page: Handles documents with 70-80+ pages efficiently
  • Structure: Preserves page boundaries and formatting

Text Chunking

  • Token Counting: Uses tiktoken for accurate token counting
  • Smart Splitting: Respects page boundaries when possible
  • Large Page Handling: Splits oversized pages intelligently
  • Token Limits: Configurable limits (default: 180k tokens)

AI Integration

  • Model: Claude 3.5 Sonnet (claude-3-5-sonnet-20241022)
  • Hierarchical Summarization: Multi-level summaries for large documents
  • Context-aware: Maintains context across chunks

๐Ÿ“ Project Structure

pdf-parser/
โ”œโ”€โ”€ main.py                 # FastAPI server (uvicorn main:app --reload)
โ”œโ”€โ”€ mcp_main.py            # MCP server entry point (uv run mcp install)
โ”œโ”€โ”€ mcp_server.py          # MCP server with @mcp.tool() decorators
โ”œโ”€โ”€ pdf_processor.py        # PDF text extraction & chunking
โ”œโ”€โ”€ anthropic_client.py     # Anthropic API integration
โ”œโ”€โ”€ pyproject.toml         # Project dependencies & MCP config
โ”œโ”€โ”€ .env.example           # Environment variables template
โ”œโ”€โ”€ dev_commands.md        # Development commands reference
โ”œโ”€โ”€ claude_desktop_config.json  # Claude Desktop configuration
โ”œโ”€โ”€ start_system.py        # System setup helper (optional)
โ””โ”€โ”€ README.md             # This file

๐Ÿšจ Troubleshooting

Common Issues

  1. Import Errors: Run uv sync to install dependencies
  2. API Key Missing: Add ANTHROPIC_API_KEY to .env file
  3. MCP Connection: Check Claude Desktop configuration path
  4. File Upload: Ensure sufficient disk space and permissions

Debug Steps

# Check system status
python start_system.py

# Test API endpoint
curl http://localhost:8000/health

# Check MCP server
python start_system.py mcp

๐Ÿ“„ License

MIT License - See LICENSE file for details.

๐Ÿค Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

Ready to process your PDFs with AI power! ๐Ÿš€