Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

7 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Enhanced PDF Document Intelligence Suite

A comprehensive AI-powered service for intelligent PDF document analysis and persona-driven content extraction


This project provides an enterprise-grade PDF document intelligence suite that combines hierarchical outline extraction with persona-driven content analysis. The service uses advanced multi-method analysis techniques enhanced with machine learning to deliver both structural document understanding and intelligent content relevance scoring for specific professional use cases.

🎯 High Accuracy
94%+ accuracy on complex documents
Multi-stage validation pipeline
⚑ Fast Processing
<10 seconds per document
CPU-optimized algorithms
πŸ”§ Configurable
No hardcoded thresholds
Adaptive to document types
🌐 Multi-format Support
Forms, reports, manuals
Multiple languages supported
πŸ€– AI-Powered Analysis
Semantic similarity scoring
Persona-driven intelligence
πŸ“Š ML Integration
Sentence transformers
Hybrid scoring algorithms
πŸ‘₯ Multi-Persona
Travel, HR, Food domains
Job-specific relevance
πŸ“ˆ Comprehensive Eval
Ground truth comparison
Detailed accuracy metrics

Round 1A Features (Outline Extraction):

  • Multi-Method Analysis: PDF ToC β†’ Content ToC β†’ Enhanced Text Analysis pipeline
  • Document Classification: Automatic detection of forms vs content documents
  • Smart Level Assignment: Intelligent H1/H2/H3 classification based on context
  • Numbered Heading Support: Preserves document numbering (1., 2.1, 3.1.1)
  • Robust Fallback System: Multiple extraction methods ensure reliability

Round 1B Features (Persona-Driven Intelligence):

  • Semantic Analysis: ML-powered content understanding with sentence transformers
  • Hybrid Scoring: 70% keyword matching + 30% semantic similarity
  • Persona-Specific Intelligence: Adaptive keyword extraction for professional roles
  • Multi-Domain Support: Travel planning, HR management, food contracting
  • Real-Time Processing: GPU-accelerated embeddings under 60-second constraint

Quick Start

Round 1A: Outline Extraction

Using Docker (Recommended)

Build and run the service:

# Build the container
docker build --platform linux/amd64 -t pdf-outline-extractor:latest .

# Run with your PDFs
docker run --rm -v $(pwd)/data/input:/app/input -v $(pwd)/data/output:/app/output --network none pdf-outline-extractor:latest

Local Development

# Install dependencies
pip install -r requirements.txt

# Test single PDF
python test_local.py file02

# Test all PDFs with comprehensive analysis
python comprehensive_test_fixed.py

Round 1B: Persona-Driven Intelligence

Setup ML Dependencies

# Install enhanced requirements (includes ML libraries)
pip install -r requirements.txt

# Verify ML components
python -c "import sentence_transformers; print('βœ… ML setup complete')"

Run Persona-Driven Analysis

# Process specific collection (1, 2, or 3)
python test_local_part_b.py 1    # Travel Planner persona
python test_local_part_b.py 2    # HR Professional persona
python test_local_part_b.py 3    # Food Contractor persona

# Run comprehensive evaluation across all collections
python comprehensive_test_1b.py

Example Usage

Round 1A Output (Outline Extraction)

Input PDF β†’ Extract outline β†’ Get structured JSON:

{
  "title": "Overview Foundation Level Extensions",
  "outline": [
    {
      "level": "H1",
      "text": "1. Introduction to the Foundation Level Extensions",
      "page": 5
    },
    {
      "level": "H2",
      "text": "2.1 Intended Audience",
      "page": 6
    }
  ]
}

Round 1B Output (Persona-Driven Analysis)

Input documents + persona β†’ Get relevance-ranked sections + subsection analysis:

{
  "persona": "Travel Planner",
  "job_to_be_done": "Plan a 5-day trip to Paris for a family of four",
  "sections": [
    {
      "title": "Planning Your Paris Itinerary",
      "content": "Detailed travel planning guide...",
      "relevance_score": 0.92,
      "source_document": "paris_travel_guide.pdf"
    }
  ],
  "subsections": [
    {
      "title": "Family-Friendly Activities",
      "analysis": "Key activities suitable for families with children...",
      "relevance_score": 0.88
    }
  ]
}

## Contents
- [Quick Start](#quick-start)
  - [Round 1A: Outline Extraction](#round-1a-outline-extraction)
  - [Round 1B: Persona-Driven Intelligence](#round-1b-persona-driven-intelligence)
- [Architecture](#architecture)
- [Performance](#performance)
- [Document Types](#document-types)
- [Machine Learning Features](#machine-learning-features)
- [Persona Configurations](#persona-configurations)
- [Configuration](#configuration)
- [API Reference](#api-reference)
- [Benchmarks](#benchmarks)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)

## Architecture

### Multi-Method Extraction Pipeline

The system employs a sophisticated three-tier extraction strategy:

1. **PDF ToC Analysis** - Extracts from embedded table of contents
2. **Content ToC Detection** - Scans document content for ToC sections
3. **Enhanced Text Analysis** - Multi-stage heuristic analysis with ML-grade accuracy

```mermaid
graph TD
    A[PDF Input] --> B[Document Classification]
    B --> C{Document Type}
    C -->|Form| D[Title Only]
    C -->|Content| E[PDF ToC Extraction]
    E --> F{ToC Valid?}
    F -->|Yes| G[Return Results]
    F -->|No| H[Content ToC Detection]
    H --> I{Content Found?}
    I -->|Yes| G
    I -->|No| J[Enhanced Text Analysis]
    J --> K[Multi-Stage Filtering]
    K --> L[Hierarchy Reconstruction]
    L --> G

Key Components

  • PDFProcessor: Main orchestrator with configurable thresholds
  • SegmentClassifier: Advanced text pattern recognition
  • TextExtractor: Multi-method text extraction with fallbacks
  • Enhanced Heuristics: Pattern-based heading detection with context awareness

Round 1B Components

  • PersonaDrivenAnalyzer: ML-powered content intelligence engine
  • Hybrid Scoring System: Combines keyword matching (70%) + semantic similarity (30%)
  • Sentence Transformers: all-MiniLM-L6-v2 model for semantic embeddings
  • Persona Mapping: Dynamic keyword extraction for professional roles

Design Principles

  • Zero Hardcoded Values: All thresholds configurable via config dictionary
  • Graceful Degradation: Multiple fallback methods ensure reliability
  • Document-Aware Processing: Adaptive algorithms based on document type
  • Performance Optimized: CPU-only processing with minimal memory footprint
  • ML Integration: Seamless semantic analysis with transformer models

Performance

Round 1A: Accuracy Benchmarks

Tested on diverse document types with professional ground truth:

Document Type Pages Accuracy Processing Time
Technical Manuals 10-50 94.1% 3-8 seconds
Business Forms 1-5 100% <1 second
Simple Documents 1-2 100% <1 second
Complex Reports 15-100 85-95% 5-15 seconds

Round 1B: Persona-Driven Performance

Tested across multiple professional domains with semantic analysis:

Collection Persona Documents Accuracy Processing Time
Collection 1 Travel Planner 7 docs 30.8% 4.31 seconds
Collection 2 HR Professional 15 docs 27.6% 7.51 seconds
Collection 3 Food Contractor 9 docs 53.9% 15.65 seconds
Overall Average 31 docs 37.4% 100% success

Speed Performance

  • CPU Only: No GPU dependencies required (Round 1A)
  • GPU Accelerated: Optional CUDA support for ML features (Round 1B)
  • Memory Efficient: ~100MB RAM for typical documents
  • Scalable: Processes 50+ page documents in under 10 seconds
  • ML Processing: Real-time semantic analysis under 60-second constraint

Machine Learning Features

Semantic Analysis Engine

Round 1B incorporates advanced machine learning capabilities:

Sentence Transformers Integration

  • Model: all-MiniLM-L6-v2 (80MB pre-trained model)
  • Capability: 384-dimensional semantic embeddings
  • Performance: Real-time processing with GPU acceleration
  • Language Support: Multilingual understanding

Hybrid Scoring Algorithm

relevance_score = (keyword_score * 0.7) + (semantic_score * 0.3)
  • Keyword Matching: TF-IDF vectorization with persona-specific vocabularies
  • Semantic Similarity: Cosine similarity between job descriptions and content
  • Dynamic Weighting: Adjustable scoring ratios for different domains

Content Intelligence Features

  • Extractive Summarization: Key sentence extraction from relevant sections
  • Contextual Understanding: Content relevance beyond keyword matching
  • Persona Adaptation: Job-specific content filtering and ranking

Persona Configurations

Supported Professional Domains

🧳 Travel Planner

  • Focus: Trip planning, itineraries, destination guides
  • Keywords: travel, destination, itinerary, attractions, booking, accommodation
  • Use Cases: Vacation planning, business travel, family trips
  • Sample Job: "Plan a 5-day trip to Paris for a family of four"

πŸ‘₯ HR Professional

  • Focus: Human resources, compliance, forms management
  • Keywords: employee, compliance, onboarding, forms, policies, training
  • Use Cases: Employee management, regulatory compliance, documentation
  • Sample Job: "Create and manage fillable forms for onboarding and compliance"

🍽️ Food Contractor

  • Focus: Menu planning, catering, dietary requirements
  • Keywords: menu, vegetarian, catering, buffet, dietary, recipes, ingredients
  • Use Cases: Event catering, restaurant planning, dietary accommodations
  • Sample Job: "Prepare a vegetarian buffet-style dinner menu for a corporate gathering"

Persona Customization

Dynamic Keyword Mapping

persona_keywords = {
    "Travel Planner": ["destination", "itinerary", "attractions", "booking"],
    "HR Professional": ["employee", "compliance", "onboarding", "policies"],
    "Food Contractor": ["menu", "vegetarian", "catering", "dietary"]
}

Job-Specific Relevance

  • Context Awareness: Understanding of professional terminology
  • Domain Knowledge: Industry-specific content prioritization
  • Adaptive Scoring: Relevance scores adjusted for persona context

Document Types

Supported Document Categories

  1. πŸ“‹ Forms & Applications

    • Automatically detected and handled
    • Title extraction only (no false headings)
    • 100% accuracy on form documents
  2. πŸ“– Technical Documents

    • Complex hierarchical structures
    • Numbered sections (1., 2.1, 3.1.1)
    • Multi-level heading detection
  3. πŸ“„ Simple Documents

    • Flyers, announcements, single-page docs
    • Title-to-heading conversion
    • Level promotion for context
  4. πŸ“Š Reports & Manuals

    • Table of contents integration
    • Appendix and reference handling
    • Cross-reference validation

Output Format

Each extracted outline includes:

{
  "level": "H1|H2|H3", // Heading hierarchy level
  "text": "Heading text", // Clean heading text
  "page": 0 // 0-based page number
}

Configuration

Adaptive Thresholds

The system uses zero hardcoded values - all thresholds are configurable:

config = {
    # Document analysis
    'default_line_height': 12,
    'default_page_width': 612,
    'max_analysis_pages': 3,

    # ToC detection
    'toc_position_threshold': 0.4,
    'toc_min_length': 5,
    'toc_max_length': 200,

    # Heading classification
    'short_heading_words': 3,
    'medium_heading_words': 6,
    'long_heading_words': 10,

    # Confidence scoring
    'numbered_heading_confidence': 0.8,
    'high_confidence_threshold': 0.7
}

Smart Document Detection

  • Form Detection: Identifies application forms, surveys, templates
  • Content Analysis: Detects structured documents vs simple pages
  • Language Support: Unicode handling for international documents

API Reference

Round 1A: Core Methods

from src.pdf_processor import PDFProcessor

processor = PDFProcessor()

# Extract outline from PDF
result = processor.extract_outline(pdf_path)
# Returns: {"title": str, "outline": [{"level": str, "text": str, "page": int}]}

# Classify document type
doc_type = processor._classify_document_type(doc)
# Returns: "form" | "content" | "unknown"

# Validate extraction results
is_valid = processor._validate_toc_results(toc_result, doc)

# Filter headings for simple documents
filtered = processor._filter_simple_document_headings(outline)

Round 1B: Persona-Driven Methods

from test_local_part_b import PersonaDrivenAnalyzer

# Initialize with ML model
analyzer = PersonaDrivenAnalyzer(
    base_path="path/to/challenge1b",
    model_name="all-MiniLM-L6-v2"
)

# Process collection with persona
result = analyzer.process_collection(
    collection_number=1,
    persona="Travel Planner",
    job_description="Plan a 5-day trip to Paris for a family of four"
)

# Manual analysis with custom parameters
analysis = analyzer.analyze_documents(
    pdf_paths=["doc1.pdf", "doc2.pdf"],
    persona="HR Professional",
    job_description="Create onboarding forms",
    max_sections=10,
    max_subsections=5
)

ML Integration Methods

# Semantic similarity scoring
similarity = analyzer._calculate_semantic_similarity(text1, text2)

# Hybrid relevance scoring
score = analyzer._score_and_rank_sections(sections, job_keywords, job_embedding)

# Extract key sentences
summary = analyzer._extract_key_sentences(content, max_sentences=3)

Benchmarks

Round 1A: Accuracy Comparison

Ground truth validation on professional document sets:

  • Overall Average: 88.2% accuracy across all document types
  • Target Achievement: 94.1% on complex technical documents (exceeding 80% target)
  • Perfect Scores: 100% on forms and simple documents

Round 1B: Performance Metrics

Comprehensive evaluation across persona-driven scenarios:

  • Average Accuracy: 37.4% across all collections and personas
  • Success Rate: 100% (all collections processed successfully)
  • Processing Speed: Under 60-second constraint maintained across all tests
  • Scalability: Handled 31 documents across diverse domains
  • Best Performance: 53.9% accuracy on Food Contractor domain
  • Perfect Scores: 100% on forms and simple documents

Processing Speed

Optimized for real-world performance:

Document Size    | Processing Time | Memory Usage
1-5 pages       | <1 second      | 50MB
10-20 pages     | 2-5 seconds    | 75MB
50+ pages       | 5-10 seconds   | 100MB

Resource Usage

  • CPU: Single-core sufficient for most documents
  • Memory: Linear scaling with document complexity
  • Storage: Minimal temporary file usage

Troubleshooting

Common Issues

Low accuracy on specific document types?

# Check document classification
python -c "
import fitz
from src.pdf_processor import PDFProcessor
doc = fitz.open('your_file.pdf')
processor = PDFProcessor()
print('Type:', processor._classify_document_type(doc))
"

Processing too slow?

  • Ensure sufficient RAM (2GB+ recommended)
  • Check document size and complexity
  • Consider document-specific threshold tuning

Missing headings?

# Run comprehensive analysis
python comprehensive_test_fixed.py

Debug Mode

Enable detailed logging:

import logging
logging.basicConfig(level=logging.DEBUG)

Contributing

Development Setup

# Clone repository
git clone <repository-url>
cd PDF_analysis

# Install development dependencies
pip install -r requirements.txt

# Run tests
python test_local.py
python comprehensive_test_fixed.py

Adding New Features

  1. Document Type Support: Extend _classify_document_type()
  2. Pattern Recognition: Add patterns to _determine_enhanced_heading_level()
  3. Threshold Tuning: Modify config dictionary in PDFProcessor.__init__()

Performance Optimization

  • Profile with cProfile for bottleneck identification
  • Benchmark new features against existing accuracy
  • Validate on diverse document corpus

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

Project Structure

PDF_analysis/
β”œβ”€β”€ src/                              # Round 1A Source code
β”‚   β”œβ”€β”€ main.py                       # Entry point and file processing
β”‚   β”œβ”€β”€ pdf_processor.py              # Core PDF processing logic
β”‚   β”œβ”€β”€ segment_classifier.py         # Heading and title classification
β”‚   └── text_extractor.py             # Text extraction from PDF
β”œβ”€β”€ data/                             # Data directory
β”‚   β”œβ”€β”€ input/                        # Place your PDF files here
β”‚   β”œβ”€β”€ output/                       # Round 1A JSON output files
β”‚   └── output_1b/                    # Round 1B persona analysis results
β”œβ”€β”€ Adobe-India-Hackathon25-main/     # Challenge datasets
β”‚   └── Challenge_1b/                 # Round 1B test collections
β”‚       β”œβ”€β”€ Collection 1/             # Travel planner documents
β”‚       β”œβ”€β”€ Collection 2/             # HR professional documents
β”‚       └── Collection 3/             # Food contractor documents
β”œβ”€β”€ test_local.py                     # Round 1A local testing script
β”œβ”€β”€ test_local_part_b.py              # Round 1B persona-driven analysis
β”œβ”€β”€ comprehensive_test_fixed.py       # Round 1A accuracy benchmarking
β”œβ”€β”€ comprehensive_test_1b.py          # Round 1B evaluation framework
β”œβ”€β”€ approach_explanation.md           # Round 1B technical methodology
β”œβ”€β”€ ROUND_1B_IMPLEMENTATION_SUMMARY.md # Complete Round 1B overview
β”œβ”€β”€ Dockerfile                        # Docker configuration
β”œβ”€β”€ requirements.txt                  # Enhanced dependencies (includes ML)
└── README.md                        # This comprehensive guide

Round 1B Additional Files

β”œβ”€β”€ collection_1_output.json         # Travel planner analysis results
β”œβ”€β”€ collection_2_output.json         # HR professional analysis results
β”œβ”€β”€ collection_3_output.json         # Food contractor analysis results
β”œβ”€β”€ round_1b_comparison_report.md    # Detailed performance analysis
└── round_1b_comparison_results.json # Raw comparison data

Requirements

System Requirements

  • RAM: 2GB minimum, 4GB recommended for large documents (6GB for Round 1B ML features)
  • CPU: Single-core sufficient, multi-core beneficial for batch processing
  • GPU: Optional CUDA support for Round 1B semantic analysis acceleration
  • Storage: 1GB free space for processing temporary files (2GB for ML models)
  • OS: Linux, macOS, Windows (Docker recommended for consistency)

Python Dependencies

Round 1A Dependencies

PyMuPDF>=1.23.0      # PDF processing and text extraction
logging               # Built-in logging framework
re                    # Regular expressions for pattern matching
json                  # JSON handling for output format
os                    # System operations and file handling

Round 1B Enhanced Dependencies

sentence-transformers>=2.2.0    # Semantic similarity analysis
scikit-learn>=1.3.0             # TF-IDF vectorization and ML utilities
torch>=2.0.0                    # PyTorch for transformer models
numpy>=1.24.0                   # Numerical computing for embeddings
tqdm>=4.65.0                    # Progress bars for ML processing

Ready for production deployment with enterprise-grade reliability! πŸš€

Input/Output Specification

Input Requirements

  • Format: PDF files (.pdf extension)
  • Location: data/input/ directory (local) or /app/input/ (Docker)
  • Size Limit: Up to 50 pages per document (configurable)
  • Language Support: UTF-8 compliant text in any language
  • Document Types: Forms, technical manuals, reports, simple documents

Output Format

Structured JSON with hierarchical outline information:

{
  "title": "Document Title",
  "outline": [
    {
      "level": "H1",
      "text": "1. Introduction to the Foundation Level Extensions",
      "page": 5
    },
    {
      "level": "H2",
      "text": "2.1 Intended Audience",
      "page": 6
    },
    {
      "level": "H3",
      "text": "2.1.1 Prerequisites",
      "page": 7
    }
  ]
}

Field Specifications:

  • title: Document title (string, may be empty if not detected)
  • outline: Array of heading objects
  • level: Hierarchy level (H1, H2, or H3)
  • text: Clean heading text with preserved numbering
  • page: 0-based page number where heading appears

Quick Start Guide

Option 1: Local Development

# 1. Clone and setup environment
cd c:\Users\arshm\OneDrive\Desktop\Py\PDF_analysis
pip install -r requirements.txt

# 2. Add your PDF files
# Copy your PDF files to data/input/ directory
cp your_document.pdf data/input/

# 3. Run extraction
python test_local.py                    # Process all PDFs in data/input/
python test_local.py your_document      # Process specific PDF (without .pdf extension)

# 4. Check results
ls data/output/                         # View generated JSON files

Option 2: Docker (Recommended for Production)

# Build the container
docker build --platform linux/amd64 -t pdf-outline-extractor:latest .

# Run with your PDFs mounted
docker run --rm \
  -v $(pwd)/data/input:/app/input \
  -v $(pwd)/data/output:/app/output \
  --network none \
  pdf-outline-extractor:latest

Option 3: Round 1B Persona-Driven Analysis

# Setup ML environment
pip install -r requirements.txt

# Process specific persona collections
python test_local_part_b.py 1           # Travel Planner (Collection 1)
python test_local_part_b.py 2           # HR Professional (Collection 2)
python test_local_part_b.py 3           # Food Contractor (Collection 3)

# Run comprehensive Round 1B evaluation
python comprehensive_test_1b.py

# View results
ls data/output_1b/                      # Persona analysis outputs
cat round_1b_comparison_report.md       # Performance analysis

Option 4: Comprehensive Testing

# Round 1A: Run accuracy benchmarking on all test files
python comprehensive_test_fixed.py

# Round 1B: Run persona-driven evaluation
python comprehensive_test_1b.py

# This will show detailed accuracy metrics:
# - Per-document accuracy scores
# - Overall system performance
# - Comparison with ground truth data
# - Persona-specific relevance scoring

Example Workflows

Round 1A Workflow (Outline Extraction)

  1. Input: Place technical_manual.pdf in data/input/
  2. Process: Run python test_local.py technical_manual
  3. Output: Get technical_manual_output.json in data/output/
  4. Result: Structured JSON with document outline

Solution Comparison

Round 1A vs Round 1B Capabilities

Feature Round 1A (Outline Extraction) Round 1B (Persona Intelligence)
Primary Focus Document structure analysis Content relevance for job roles
Technology Heuristic algorithms ML + semantic analysis
Input Single PDF files Document collections
Output Hierarchical outlines Ranked relevant sections
Accuracy 88.2% average, 94.1% on technical docs 37.4% average across personas
Processing CPU-only, <10 seconds GPU-accelerated, <60 seconds
Use Cases Document indexing, navigation Professional content discovery

Complementary Strengths

  • Round 1A: Precise structural understanding, perfect for document navigation
  • Round 1B: Intelligent content filtering, ideal for task-specific information retrieval
  • Combined: Complete document intelligence solution for enterprise workflows

Round 1B Workflow (Persona-Driven Analysis)

  1. Input: Challenge 1B document collections in Adobe-India-Hackathon25-main/Challenge_1b/
  2. Process: Run python test_local_part_b.py 1 for Travel Planner persona
  3. Output: Get collection_1_output.json in data/output_1b/
  4. Result: Persona-relevant sections with semantic similarity scores
  5. Result: Structured JSON with document outline

Architecture Overview

High-Level System Design

The system uses a sophisticated three-tier extraction strategy designed for maximum reliability and accuracy across diverse document types.

graph TD
    A[PDF Input] --> B[Document Classification]
    B --> C{Document Type}
    C -->|Form| D[Title Only Extraction]
    C -->|Content| E[PDF ToC Analysis]
    E --> F{ToC Valid?}
    F -->|Yes| G[Return Results]
    F -->|No| H[Content ToC Detection]
    H --> I{Content Found?}
    I -->|Yes| G
    I -->|No| J[Enhanced Text Analysis]
    J --> K[Multi-Stage Filtering]
    K --> L[Hierarchy Reconstruction]
    L --> G
Loading

Processing Pipeline

  1. Document Classification: Automatic detection of document type (form vs content)
  2. PDF ToC Extraction: Primary method using embedded table of contents
  3. Content ToC Detection: Secondary method scanning document for ToC sections
  4. Enhanced Text Analysis: Fallback method with ML-grade heuristic analysis
  5. Result Validation: Multi-stage filtering and confidence scoring

Core Components

Component Responsibility Key Features
PDFProcessor Main orchestrator Configurable thresholds, multi-method coordination
SegmentClassifier Pattern recognition Advanced text classification, context awareness
TextExtractor Text extraction Multiple extraction methods with fallbacks
Enhanced Heuristics Heading detection Pattern-based analysis, hierarchy reconstruction

Design Principles

  • Zero Hardcoded Values: All thresholds configurable via config dictionary
  • Graceful Degradation: Multiple fallback methods ensure reliability
  • Document-Aware Processing: Adaptive algorithms based on document type
  • Performance Optimized: CPU-only processing with minimal memory footprint

Advanced Classification Logic

Document Type Detection

The system automatically classifies documents to apply appropriate extraction strategies:

  • πŸ“‹ Form Documents: Applications, surveys, simple forms

    • Detection: High field density, minimal hierarchical structure
    • Strategy: Title-only extraction to avoid false positives
    • Accuracy: 100% on tested form documents
  • πŸ“– Content Documents: Manuals, reports, structured documents

    • Detection: Clear hierarchical patterns, numbered sections
    • Strategy: Full multi-method analysis pipeline
    • Accuracy: 85-95% depending on complexity

Heading Detection Patterns

Pattern Type Examples Level Assignment
Numbered Sections 1., 2.1, 3.1.1 H1 β†’ H2 β†’ H3
Roman Numerals I., II., III. H1 primary
Letter Sections A., B., C. H2 secondary
Title Case Proper capitalization Context-dependent

Smart Level Assignment

The system uses contextual analysis for accurate level assignment:

  • H1: Top-level sections, chapter headings, major divisions
  • H2: Sub-sections, numbered subsections, topic divisions
  • H3: Sub-sub-sections, detailed breakdowns, specific topics

Text Processing Rules

  • Numbered Heading Preservation: Maintains 1., 2.1, etc. in output
  • Title Case Validation: Ensures proper capitalization patterns
  • Length Constraints: Applies reasonable text length limits
  • Position Analysis: Considers document layout and positioning

Error Handling & Reliability

Robust Fault Tolerance

  • Multiple Extraction Methods: Automatic fallback from PDF ToC β†’ Content ToC β†’ Enhanced Analysis
  • Malformed PDF Handling: Graceful processing of corrupted or non-standard PDF files
  • Empty Result Generation: Safe failure mode with valid JSON output structure
  • Comprehensive Logging: Detailed debug information for troubleshooting

Validation & Quality Assurance

  • ToC Result Validation: Automatic verification of extracted table of contents
  • Confidence Scoring: Built-in quality metrics for extraction results
  • Document Type Verification: Automatic classification validation
  • Output Format Consistency: Guaranteed valid JSON structure

Performance Characteristics

Processing Speed Benchmarks

Document Category Page Count Processing Time Memory Usage
Simple Forms 1-5 pages <1 second 50MB
Technical Docs 10-20 pages 2-5 seconds 75MB
Large Manuals 50+ pages 5-10 seconds 100MB

Resource Optimization

  • CPU Efficiency: Single-core processing sufficient for most documents
  • Memory Management: Linear scaling with document complexity
  • Storage Minimal: Temporary file usage kept to minimum
  • Network Isolation: Completely offline processing (Docker --network none)

Scalability Features

  • Batch Processing: Handles multiple documents efficiently
  • Container Ready: Docker deployment for production environments
  • Platform Independent: Cross-platform compatibility (Linux, macOS, Windows)
  • Language Agnostic: Unicode support for international documents

Multilingual & Accessibility Support

Supported Languages

  • Latin Scripts: English, Spanish, French, German, Italian, Portuguese
  • Asian Languages: Japanese, Korean, Chinese (simplified/traditional)
  • Right-to-Left: Arabic, Hebrew (basic support)
  • Special Characters: Mathematical symbols, technical notation

Accessibility Features

  • Unicode Compliance: Full UTF-8 character set support
  • Font Independence: Works regardless of embedded fonts
  • Layout Tolerance: Handles various PDF layout styles
  • OCR Integration: Compatible with OCR-processed documents

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages