VOOZH about

URL: https://hub.docker.com/r/huridocs/pdf-document-layout-analysis

โ‡ฑ huridocs/pdf-document-layout-analysis - Docker Image


huridocs/pdf-document-layout-analysis

By huridocs

โ€ขUpdated about 2 months ago

pdf-document-layout-analysis service by HURIDOCS

Image
7

10K+

huridocs/pdf-document-layout-analysis repository overview

โ PDF Document Layout Analysis

A Docker-powered microservice for intelligent PDF document layout analysis, OCR, and content extraction

๐Ÿ‘ Python Version
๐Ÿ‘ FastAPI
๐Ÿ‘ Docker
๐Ÿ‘ GPU Support


โ ๐Ÿš€ Overview

This project provides a powerful and flexible PDF analysis microservice built with Clean Architecture principles. The service enables OCR, segmentation, and classification of different parts of PDF pages, identifying elements such as texts, titles, pictures, tables, formulas, and more. Additionally, it determines the correct reading order of these identified elements and can convert PDFs to various formats including Markdown and HTML.

โ โœจ Key Features
  • ๐Ÿ” Advanced PDF Layout Analysis - Segment and classify PDF content with high accuracy
  • ๐Ÿ–ผ๏ธ Visual & Fast Models - Choose between VGT (Vision Grid Transformer) for accuracy or LightGBM for speed
  • ๐Ÿ“ Multi-format Output - Export to JSON, Markdown, HTML, and visualize PDF segmentations
  • ๐ŸŒ OCR Support - 150+ language support with Tesseract OCR
  • ๐Ÿ“Š Table & Formula Extraction - Extract tables as HTML and formulas as LaTeX
  • ๐Ÿ—๏ธ Clean Architecture - Modular, testable, and maintainable codebase
  • ๐Ÿณ Docker-Ready - Easy deployment with GPU support
  • โšก RESTful API - Comprehensive API with 10+ endpoints

โ Quick Start

Run the service:

  • With GPU support:
docker run --rm --name pdf-document-layout-analysis --gpus '"device=0"' -p 5060:5060 --entrypoint ./start.sh huridocs/pdf-document-layout-analysis:v0.0.35
  • Without GPU support:
docker run --rm --name pdf-document-layout-analysis -p 5060:5060 --entrypoint ./start.sh huridocs/pdf-document-layout-analysis:v0.0.35

๐Ÿ“ The service also has a user interface and a translation support but you should install it from the source. Check GitHub page for instructions.

Get the segments from a PDF:

curl -X POST -F 'file=@/PATH/TO/PDF/pdf_name.pdf' localhost:5060

To stop the server:

docker stop pdf-document-layout-analysis

๐Ÿ’ก Tip: Replace /path/to/your/document.pdf with the actual path to your PDF file. The service will return a JSON response with segmented content and metadata.

โ ๐Ÿ“‹ Table of Contents

โ โš™๏ธ Dependencies

โ Required
โ Optional

โ ๐Ÿ“‹ Requirements

โ System Requirements
  • RAM: 2 GB minimum
  • GPU Memory: 5 GB (optional, will fallback to CPU if unavailable)
  • Disk Space: 10 GB for models and dependencies
  • CPU: Multi-core recommended for better performance
โ Docker Requirements
  • Docker Engine 20.10+
  • Docker Compose 2.0+

โ ๐Ÿ“š API Reference

The service provides a comprehensive RESTful API with the following endpoints:

โ Core Analysis Endpoints
EndpointMethodDescriptionParameters
/POSTAnalyze PDF layout and extract segmentsfile, fast, ocr_tables
/save_xml/{filename}POSTAnalyze PDF and save XML outputfile, xml_file_name, fast
/get_xml/{filename}GETRetrieve saved XML analysisxml_file_name
โ Content Extraction Endpoints
EndpointMethodDescriptionParameters
/textPOSTExtract text by content typesfile, fast, types
/tocPOSTExtract table of contentsfile, fast
/toc_legacy_uwazi_compatiblePOSTExtract TOC (Uwazi compatible)file
โ Format Conversion Endpoints
EndpointMethodDescriptionParameters
/markdownPOSTConvert PDF to Markdown (includes segmentation data in zip)file, fast, extract_toc, dpi, output_file
/htmlPOSTConvert PDF to HTML (includes segmentation data in zip)file, fast, extract_toc, dpi, output_file
/visualizePOSTVisualize segmentation results on the PDFfile, fast
โ OCR & Utility Endpoints
EndpointMethodDescriptionParameters
/ocrPOSTApply OCR to PDFfile, language
/infoGETGet service information-
/GETHealth check and system info-
/errorGETTest error handling-
โ Common Parameters
  • file: PDF file to process (multipart/form-data)
  • fast: Use LightGBM models instead of VGT (boolean, default: false)
  • ocr_tables: Apply OCR to table regions (boolean, default: false)
  • language: OCR language code (string, default: "en")
  • types: Comma-separated content types to extract (string, default: "all")
  • extract_toc: Include table of contents at the beginning of the output (boolean, default: false)
  • dpi: Image resolution for conversion (integer, default: 120)

โ ๐Ÿ’ก Usage Examples

โ Basic PDF Analysis

Standard analysis with VGT model:

curl -X POST \
 -F '[email protected]' \
 http://localhost:5060

Fast analysis with LightGBM models:

curl -X POST \
 -F '[email protected]' \
 -F 'fast=true' \
 http://localhost:5060

Analysis with table OCR:

curl -X POST \
 -F '[email protected]' \
 -F 'ocr_tables=true' \
 http://localhost:5060
โ Text Extraction

Extract all text:

curl -X POST \
 -F '[email protected]' \
 -F 'types=all' \
 http://localhost:5060/text

Extract specific content types:

curl -X POST \
 -F '[email protected]' \
 -F 'types=title,text,table' \
 http://localhost:5060/text
โ Format Conversion

Convert to Markdown:

curl -X POST http://localhost:5060/markdown \
 -F '[email protected]' \
 -F 'extract_toc=true' \
 -F 'output_file=document.md' \
 --output 'document.zip'

Convert to HTML:

curl -X POST http://localhost:5060/html \
 -F '[email protected]' \
 -F 'extract_toc=true' \
 -F 'output_file=document.html' \
 --output 'document.zip'

๐Ÿ“‹ Segmentation Data: Format conversion endpoints automatically include detailed segmentation data in the zip output. The resulting zip file contains a {filename}_segmentation.json file with information about each detected document segment including:

  • Coordinates: left, top, width, height
  • Page information: page_number, page_width, page_height
  • Content: text content and segment type (e.g., "Title", "Text", "Table", "Picture")
โ OCR Processing

OCR in English:

curl -X POST \
 -F 'file=@scanned_document.pdf' \
 -F 'language=en' \
 http://localhost:5060/ocr \
 --output ocr_processed.pdf

OCR in other languages:

# French
curl -X POST \
 -F 'file=@document_french.pdf' \
 -F 'language=fr' \
 http://localhost:5060/ocr \
 --output ocr_french.pdf

# Spanish
curl -X POST \
 -F 'file=@document_spanish.pdf' \
 -F 'language=es' \
 http://localhost:5060/ocr \
 --output ocr_spanish.pdf
โ Visualization

Generate visualization PDF:

curl -X POST \
 -F '[email protected]' \
 http://localhost:5060/visualize \
 --output visualization.pdf
โ Table of Contents Extraction

Extract structured TOC:

curl -X POST \
 -F '[email protected]' \
 http://localhost:5060/toc
โ XML Storage and Retrieval

Analyze and save XML:

curl -X POST \
 -F '[email protected]' \
 http://localhost:5060/save_xml/my_analysis

Retrieve saved XML:

curl http://localhost:5060/get_xml/my_analysis.xml
โ Service Information

Get service info and supported languages:

curl http://localhost:5060/info

Health check:

curl http://localhost:5060/
โ Response Format

Most endpoints return JSON with segment information:

[
 {
 "left": 72.0,
 "top": 84.0,
 "width": 451.2,
 "height": 23.04,
 "page_number": 1,
 "page_width": 595.32,
 "page_height": 841.92,
 "text": "Document Title",
 "type": "Title"
 },
 {
 "left": 72.0,
 "top": 120.0,
 "width": 451.2,
 "height": 200.0,
 "page_number": 1,
 "page_width": 595.32,
 "page_height": 841.92,
 "text": "This is the main text content...",
 "type": "Text"
 }
]
โ Supported Content Types
  • Caption - Image and table captions
  • Footnote - Footnote text
  • Formula - Mathematical formulas
  • List item - List items and bullet points
  • Page footer - Footer content
  • Page header - Header content
  • Picture - Images and figures
  • Section header - Section headings
  • Table - Table content
  • Text - Regular text paragraphs
  • Title - Document and section titles

โ ๐Ÿ—๏ธ Architecture

This project follows Clean Architecture principles, ensuring separation of concerns, testability, and maintainability. The codebase is organized into distinct layers:

โ Directory Structure
src/
โ”œโ”€โ”€ domain/ # Enterprise Business Rules
โ”‚ โ”œโ”€โ”€ PdfImages.py # PDF image handling domain logic
โ”‚ โ”œโ”€โ”€ PdfSegment.py # PDF segment entity
โ”‚ โ”œโ”€โ”€ Prediction.py # ML prediction entity
โ”‚ โ””โ”€โ”€ SegmentBox.py # Core segment box entity
โ”œโ”€โ”€ use_cases/ # Application Business Rules
โ”‚ โ”œโ”€โ”€ pdf_analysis/ # PDF analysis use case
โ”‚ โ”œโ”€โ”€ text_extraction/ # Text extraction use case
โ”‚ โ”œโ”€โ”€ toc_extraction/ # Table of contents extraction
โ”‚ โ”œโ”€โ”€ visualization/ # PDF visualization use case
โ”‚ โ”œโ”€โ”€ ocr/ # OCR processing use case
โ”‚ โ”œโ”€โ”€ markdown_conversion/ # Markdown conversion use case
โ”‚ โ””โ”€โ”€ html_conversion/ # HTML conversion use case
โ”œโ”€โ”€ adapters/ # Interface Adapters
โ”‚ โ”œโ”€โ”€ infrastructure/ # External service adapters
โ”‚ โ”œโ”€โ”€ ml/ # Machine learning model adapters
โ”‚ โ”œโ”€โ”€ storage/ # File storage adapters
โ”‚ โ””โ”€โ”€ web/ # Web framework adapters
โ”œโ”€โ”€ ports/ # Interface definitions
โ”‚ โ”œโ”€โ”€ services/ # Service interfaces
โ”‚ โ””โ”€โ”€ repositories/ # Repository interfaces
โ””โ”€โ”€ drivers/ # Frameworks & Drivers
 โ””โ”€โ”€ web/ # FastAPI application setup
โ Layer Responsibilities
  • Domain Layer: Contains core business entities and rules independent of external concerns
  • Use Cases Layer: Orchestrates domain entities to fulfill specific application requirements
  • Adapters Layer: Implements interfaces defined by inner layers and adapts external frameworks
  • Drivers Layer: Contains frameworks, databases, and external agency configurations
โ Key Benefits
  • ๐Ÿ”„ Dependency Inversion: High-level modules don't depend on low-level modules

  • ๐Ÿงช Testability: Easy to unit test business logic in isolation

  • ๐Ÿ”ง Maintainability: Changes to external frameworks don't affect business rules

  • ๐Ÿ“ˆ Scalability: Easy to add new features without modifying existing code

โ ๐Ÿค– Models

The service offers two complementary model approaches, each optimized for different use cases:

โ 1. Vision Grid Transformer (VGT) - High Accuracy Model

Overview: A state-of-the-art visual model developed by Alibaba Research Group that "sees" the entire page layout.

Key Features:

  • ๐ŸŽฏ High Accuracy: Best-in-class performance on document layout analysis
  • ๐Ÿ‘๏ธ Visual Understanding: Analyzes the entire page context including spatial relationships
  • ๐Ÿ“Š Trained on DocLayNet: Uses the comprehensive DocLayNet datasetโ 
  • ๐Ÿ”ฌ Research-Backed: Based on Advanced Literate Machineryโ 

Resource Requirements:

  • GPU: 5GB+ VRAM (recommended)
  • CPU: Falls back automatically if GPU unavailable
  • Processing Speed: ~1.75 seconds/page (GPU [GTX 1070]) or ~13.5 seconds/page (CPU [i7-8700])
โ 2. LightGBM Models - Fast & Efficient

Overview: Lightweight ensemble of two specialized models using XML-based features from Poppler.

Key Features:

  • โšก High Speed: ~0.42 seconds per page on CPU (i7-8700)
  • ๐Ÿ’พ Low Resource Usage: CPU-only, minimal memory footprint
  • ๐Ÿ”„ Dual Model Approach:
    • Token Type Classifier: Identifies content types (title, text, table, etc.)
    • Segmentation Model: Determines proper content boundaries
  • ๐Ÿ“„ XML-Based: Uses Poppler's PDF-to-XML conversion for feature extraction

Trade-offs:

  • Slightly lower accuracy compared to VGT
  • No visual context understanding
  • Excellent for batch processing and resource-constrained environments
โ OCR Integration

Both models integrate seamlessly with OCR capabilities:

โ Model Selection Guide
Use CaseRecommended ModelReason
High accuracy requirementsVGTSuperior visual understanding
Batch processingLightGBMFaster processing, lower resources
GPU availableVGTLeverages GPU acceleration
CPU-only environmentLightGBMOptimized for CPU processing
Real-time applicationsLightGBMConsistent fast response times
Research/analysisVGTBest accuracy for detailed analysis

โ ๐Ÿ“Š Data

โ Training Dataset

Both model types are trained on the comprehensive DocLayNet datasetโ , a large-scale document layout analysis dataset containing over 80,000 document pages.

โ Document Categories

The models can identify and classify 11 distinct content types:

IDCategoryDescription
1CaptionImage and table captions
2FootnoteFootnote references and text
3FormulaMathematical equations and formulas
4List itemBulleted and numbered list items
5Page footerFooter content and page numbers
6Page headerHeader content and titles
7PictureImages, figures, and graphics
8Section headerSection and subsection headings
9TableTabular data and structures
10TextRegular paragraph text
11TitleDocument and chapter titles
โ Dataset Characteristics
  • Domain Coverage: Academic papers, technical documents, reports
  • Language: Primarily English with multilingual support
  • Quality: High-quality annotations with bounding boxes and labels
  • Diversity: Various document layouts, fonts, and formatting styles

For detailed information about the dataset, visit the DocLayNet repositoryโ .

โ ๐Ÿ“ˆ Benchmarks

โ Performance

VGT model performance on PubLayNet dataset:

MetricOverallTextTitleListTableFigure
F1 Score0.9620.9500.9390.9680.9810.971

๐Ÿ“Š Comparison: View comprehensive model comparisons at Papers With Codeโ 

โ Speed

Performance benchmarks on 15-page academic documents:

ModelHardwareSpeed (sec/page)Use Case
LightGBMCPU (i7-8700 3.2GHz)0.42Fast processing
VGTGPU (GTX 1070)1.75High accuracy
VGTCPU (i7-8700 3.2GHz)13.5CPU fallback
โ Performance Recommendations
  • GPU Available: Use VGT for best accuracy-speed balance
  • CPU Only: Use LightGBM for optimal performance
  • Batch Processing: LightGBM for consistent throughput
  • High Accuracy: VGT with GPU for best results

โ ๐ŸŒ Installation of More Languages for OCR

The service uses Tesseract OCR with support for 150+ languages. The Docker image includes only common languages to minimize image size.

โ Installing Additional Languages
โ 1. Access the Container
docker exec -it --user root pdf-document-layout-analysis /bin/bash
โ 2. Install Language Packs
# Install specific language
apt-get update
apt-get install tesseract-ocr-[LANGCODE]
โ 3. Common Language Examples
# Korean
apt-get install tesseract-ocr-kor

# German 
apt-get install tesseract-ocr-deu

# French
apt-get install tesseract-ocr-fra

# Spanish
apt-get install tesseract-ocr-spa

# Chinese Simplified
apt-get install tesseract-ocr-chi-sim

# Arabic
apt-get install tesseract-ocr-ara

# Japanese
apt-get install tesseract-ocr-jpn
โ 4. Verify Installation
curl http://localhost:5060/info
โ Language Code Reference

Find Tesseract language codes in the ISO to Tesseract mappingโ .

โ Supported Languages

Common language codes:

  • eng - English
  • fra - French
  • deu - German
  • spa - Spanish
  • ita - Italian
  • por - Portuguese
  • rus - Russian
  • chi-sim - Chinese Simplified
  • chi-tra - Chinese Traditional
  • jpn - Japanese
  • kor - Korean
  • ara - Arabic
  • hin - Hindi
โ Usage with Multiple Languages
# OCR with specific language
curl -X POST \
 -F '[email protected]' \
 -F 'language=fr' \
 http://localhost:5060/ocr \
 --output french_ocr.pdf

Explore our ecosystem of PDF processing services built on this foundation:

โ PDF Table of Contents Extractorโ 

๐Ÿ” Purpose: Intelligent extraction of structured table of contents from PDF documents

Key Features:

  • Leverages layout analysis for accurate TOC identification
  • Hierarchical structure recognition
  • Multiple output formats supported
  • Integration-ready API
โ PDF Text Extractionโ 

๐Ÿ“ Purpose: Advanced text extraction with layout awareness

Key Features:

  • Content-type aware extraction
  • Preserves document structure
  • Reading order optimization
  • Clean text output with metadata
โ Integration Benefits

These services work seamlessly together:

  • Shared Analysis: Reuse layout analysis results across services
  • Consistent Output: Standardized JSON format for easy integration
  • Scalable Architecture: Deploy services independently or together
  • Docker Ready: All services containerized for easy deployment

โ ๐Ÿค Contributing

We welcome contributions to improve the PDF Document Layout Analysis service!

โ How to Contribute
  1. Fork the Repository

    git clone https://github.com/your-username/pdf-document-layout-analysis.git
    
  2. Create a Feature Branch

    git checkout -b feature/your-feature-name
    
  3. Set Up Development Environment

    make install_venv
    make install
    
  4. Make Your Changes

    • Follow the Clean Architecture principles
    • Add tests for new features
    • Update documentation as needed
  5. Run Tests and Quality Checks

    make test
    make check_format
    
  6. Submit a Pull Request

    • Provide clear description of changes
    • Include test results
    • Reference any related issues
โ Contribution Guidelines
โ Code Standards
  • Python: Follow PEP 8 with 125-character line length
  • Architecture: Maintain Clean Architecture boundaries
  • Testing: Include unit tests for new functionality
  • Documentation: Update README and docstrings
โ Areas for Contribution
  • ๐Ÿ› Bug Fixes: Report and fix issues
  • โœจ New Features: Add new endpoints or functionality
  • ๐Ÿ“š Documentation: Improve guides and examples
  • ๐Ÿงช Testing: Expand test coverage
  • ๐Ÿš€ Performance: Optimize processing speed
  • ๐ŸŒ Internationalization: Add language support
โ Development Workflow
  1. Issue First: Create or comment on relevant issues
  2. Small PRs: Keep pull requests focused and manageable
  3. Clean Commits: Use descriptive commit messages
  4. Documentation: Update relevant documentation
  5. Testing: Ensure all tests pass
โ Getting Help
  • ๐Ÿ“š Documentation: Check this README and inline docs
  • ๐Ÿ’ฌ Issues: Search existing issues or create new ones
  • ๐Ÿ” Code: Explore the codebase structure
  • ๐Ÿ“ง Contact: Reach out to maintainers for guidance

โ License

This project is licensed under the terms specified in the LICENSEโ  file.

Tag summary

v0.0.35

Content type

Image

Digest

sha256:95475823aโ€ฆ

Size

6 GB

Last updated

about 2 months ago

docker pull huridocs/pdf-document-layout-analysis:v0.0.35