Metadata-Version: 2.4
Name: doctra
Version: 0.3.3
Summary: Parse, extract, and analyze documents with ease
Home-page: https://github.com/AdemBoukhris457/Doctra
Author: Adem Boukhris
Author-email: Adem Boukhris <boukhrisadam98@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/AdemBoukhris457/Doctra
Project-URL: Repository, https://github.com/AdemBoukhris457/Doctra
Project-URL: Issues, https://github.com/AdemBoukhris457/Doctra/issues
Keywords: pdf,parser,document,extraction,ocr,layout-detection
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup
Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: paddlepaddle>=2.4.0
Requires-Dist: paddleocr>=2.6.0
Requires-Dist: pillow>=8.0.0
Requires-Dist: opencv-python>=4.5.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: openpyxl>=3.0.0
Requires-Dist: tesseract>=0.1.3
Requires-Dist: pytesseract>=0.3.10
Requires-Dist: pdf2image>=1.16.0
Requires-Dist: anthropic>=0.40.0
Requires-Dist: outlines>=0.0.34
Requires-Dist: tqdm>=4.62.0
Requires-Dist: matplotlib>=3.5.0
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == "openai"
Provides-Extra: gemini
Requires-Dist: google-generativeai>=0.3.0; extra == "gemini"
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-cov>=2.0; extra == "dev"
Requires-Dist: black>=21.0; extra == "dev"
Requires-Dist: isort>=5.0; extra == "dev"
Requires-Dist: flake8>=3.9; extra == "dev"
Requires-Dist: mypy>=0.910; extra == "dev"
Requires-Dist: pre-commit>=2.15.0; extra == "dev"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# 🚀 **Doctra - Document Parser Library** 📑🔎

![Doctra Logo](https://raw.githubusercontent.com/AdemBoukhris457/Doctra/main/assets/Doctra_Logo.png)

<div align="center">

[![stars](https://img.shields.io/github/stars/AdemBoukhris457/Doctra.svg)](https://github.com/AdemBoukhris457/Doctra)
[![forks](https://img.shields.io/github/forks/AdemBoukhris457/Doctra.svg)](https://github.com/AdemBoukhris457/Doctra)
[![PyPI version](https://img.shields.io/pypi/v/doctra)](https://pypi.org/project/doctra/)
</div>

## 📋 Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Components](#core-components)
  - [StructuredPDFParser](#structuredpdfparser)
  - [ChartTablePDFParser](#charttablepdfparser)
- [Visualization](#visualization)
- [Usage Examples](#usage-examples)
- [Features](#features)
- [Requirements](#requirements)

## 🛠️ Installation

### From PyPI (recommended)

```bash
pip install doctra
```

### From source

```bash
git clone https://github.com/AdemBoukhris457/Doctra.git
cd Doctra
pip install .
```

### System Dependencies

Doctra requires **Poppler** for PDF processing. Install it based on your operating system:

#### Ubuntu/Debian
```bash
sudo apt install poppler-utils
```

#### macOS
```bash
brew install poppler
```

#### Windows
Download and install from [Poppler for Windows](http://blog.alivate.com.au/poppler-windows/) or use conda:
```bash
conda install -c conda-forge poppler
```

#### Google Colab
```bash
!sudo apt install poppler-utils
```

## ⚡ Quick Start

```python
from doctra.parsers.structured_pdf_parser import StructuredPDFParser

# Initialize the parser
parser = StructuredPDFParser()

# Parse a PDF document
parser.parse("path/to/your/document.pdf")
```

## 🔧 Core Components

### StructuredPDFParser

The `StructuredPDFParser` is a comprehensive PDF parser that extracts all types of content from PDF documents. It processes PDFs through layout detection, extracts text using OCR, saves images for visual elements, and optionally converts charts/tables to structured data using Vision Language Models (VLM).

#### Key Features:
- **Layout Detection**: Uses PaddleOCR for accurate document layout analysis
- **OCR Processing**: Extracts text from all document elements
- **Visual Element Extraction**: Saves figures, charts, and tables as images
- **VLM Integration**: Optional conversion of visual elements to structured data
- **Multiple Output Formats**: Generates Markdown, Excel, and structured JSON

#### Basic Usage:

```python
from doctra.parsers.structured_pdf_parser import StructuredPDFParser

# Basic parser without VLM
parser = StructuredPDFParser()

# Parser with VLM for structured data extraction
parser = StructuredPDFParser(
    use_vlm=True,
    vlm_provider="openai",  # or "gemini" or "anthropic" or "openrouter"
    vlm_api_key="your_api_key_here"
)

# Parse document
parser.parse("document.pdf")
```

#### Advanced Configuration:

```python
parser = StructuredPDFParser(
    # VLM Settings
    use_vlm=True,
    vlm_provider="openai",
    vlm_model="gpt-5",
    vlm_api_key="your_api_key",
    
    # Layout Detection Settings
    layout_model_name="PP-DocLayout_plus-L",
    dpi=200,
    min_score=0.0,
    
    # OCR Settings
    ocr_lang="eng",
    ocr_psm=4,
    ocr_oem=3,
    ocr_extra_config="",
    
    # Output Settings
    box_separator="\n"
)
```

### ChartTablePDFParser

The `ChartTablePDFParser` is a specialized parser focused specifically on extracting charts and tables from PDF documents. It's optimized for scenarios where you only need these specific elements, providing faster processing and more targeted output.

#### Key Features:
- **Focused Extraction**: Extracts only charts and/or tables
- **Selective Processing**: Choose to extract charts, tables, or both
- **VLM Integration**: Optional conversion to structured data
- **Organized Output**: Separate directories for charts and tables
- **Progress Tracking**: Real-time progress bars for extraction

#### Basic Usage:

```python
from doctra.parsers.table_chart_extractor import ChartTablePDFParser

# Extract both charts and tables
parser = ChartTablePDFParser(
    extract_charts=True,
    extract_tables=True
)

# Extract only charts
parser = ChartTablePDFParser(
    extract_charts=True,
    extract_tables=False
)

# Parse with custom output directory
parser.parse("document.pdf", output_base_dir="my_outputs")
```

#### Advanced Configuration:

```python
parser = ChartTablePDFParser(
    # Extraction Settings
    extract_charts=True,
    extract_tables=True,
    
    # VLM Settings
    use_vlm=True,
    vlm_provider="openai",
    vlm_model="gpt-5",
    vlm_api_key="your_api_key",
    
    # Layout Detection Settings
    layout_model_name="PP-DocLayout_plus-L",
    dpi=200,
    min_score=0.0
)
```

## 🎨 Visualization

Doctra provides powerful visualization capabilities to help you understand how the layout detection works and verify the accuracy of element extraction.

### Layout Detection Visualization

The `StructuredPDFParser` includes a built-in visualization method that displays PDF pages with bounding boxes overlaid on detected elements. This is perfect for:

- **Debugging**: Verify that layout detection is working correctly
- **Quality Assurance**: Check the accuracy of element identification
- **Documentation**: Create visual documentation of extraction results
- **Analysis**: Understand document structure and layout patterns

#### Basic Visualization:

```python
from doctra.parsers.structured_pdf_parser import StructuredPDFParser

# Initialize parser
parser = StructuredPDFParser()

# Display visualization (opens in default image viewer)
parser.display_pages_with_boxes("document.pdf")
```

#### Advanced Visualization with Custom Settings:

```python
# Custom visualization configuration
parser.display_pages_with_boxes(
    pdf_path="document.pdf",
    num_pages=5,        # Number of pages to visualize
    cols=3,             # Number of columns in grid
    page_width=600,     # Width of each page in pixels
    spacing=30,         # Spacing between pages
    save_path="layout_visualization.png"  # Save to file instead of displaying
)
```

#### Visualization Features:

- **Color-coded Elements**: Each element type (text, table, chart, figure) has a distinct color
- **Confidence Scores**: Shows detection confidence for each element
- **Grid Layout**: Multiple pages displayed in an organized grid
- **Interactive Legend**: Color legend showing all detected element types
- **High Quality**: High-resolution output suitable for documentation
- **Flexible Output**: Display on screen or save to file

#### Example Output:

The visualization shows:
- **Blue boxes**: Text elements
- **Red boxes**: Tables
- **Green boxes**: Charts
- **Orange boxes**: Figures
- **Labels**: Element type and confidence score (e.g., "table (0.95)")
- **Page titles**: Page number and element count
- **Summary statistics**: Total elements detected by type

### Use Cases for Visualization:

1. **Document Analysis**: Quickly assess document structure and complexity
2. **Quality Control**: Verify extraction accuracy before processing
3. **Debugging**: Identify issues with layout detection
4. **Documentation**: Create visual reports of extraction results
5. **Training**: Help users understand how the system works

### Visualization Configuration Options:

| Parameter | Default | Description |
|-----------|---------|-------------|
| `num_pages` | 3 | Number of pages to visualize |
| `cols` | 2 | Number of columns in grid layout |
| `page_width` | 800 | Width of each page in pixels |
| `spacing` | 40 | Spacing between pages in pixels |
| `save_path` | None | Path to save visualization (if None, displays on screen) |

## 📖 Usage Examples

### Example 1: Basic Document Processing

```python
from doctra.parsers.structured_pdf_parser import StructuredPDFParser

# Initialize parser
parser = StructuredPDFParser()

# Process document
parser.parse("financial_report.pdf")

# Output will be saved to: outputs/financial_report/
# - Extracted text content
# - Cropped images of figures, charts, and tables
# - Markdown file with all content
```

### Example 2: Chart and Table Extraction with VLM

```python
from doctra.parsers.table_chart_extractor import ChartTablePDFParser

# Initialize parser with VLM
parser = ChartTablePDFParser(
    extract_charts=True,
    extract_tables=True,
    use_vlm=True,
    vlm_provider="openai",
    vlm_api_key="your_gemini_api_key"
)

# Process document
parser.parse("data_report.pdf", output_base_dir="extracted_data")

# Output will include:
# - Cropped chart and table images
# - Structured data in Excel format
# - Markdown tables with extracted data
```

### Example 3: Custom Configuration

```python
from doctra.parsers.structured_pdf_parser import StructuredPDFParser

# Custom configuration for high-quality processing
parser = StructuredPDFParser(
    use_vlm=True,
    vlm_provider="openai",
    vlm_api_key="your_openai_api_key",
    vlm__model="gpt-5",
    layout_model_name="PP-DocLayout_plus-L",
    dpi=300,  # Higher DPI for better quality
    min_score=0.5,  # Higher confidence threshold
    ocr_lang="eng",
    ocr_psm=6,  # Uniform block of text
    box_separator="\n\n"  # Double line breaks between elements
)

parser.parse("complex_document.pdf")
```

### Example 4: Layout Visualization

```python
from doctra.parsers.structured_pdf_parser import StructuredPDFParser

# Initialize parser
parser = StructuredPDFParser()

# Create a comprehensive visualization
parser.display_pages_with_boxes(
    pdf_path="research_paper.pdf",
    num_pages=6,        # Visualize first 6 pages
    cols=2,             # 2 columns layout
    page_width=700,     # Larger pages for better detail
    spacing=50,         # More spacing between pages
    save_path="research_paper_layout.png"  # Save for documentation
)

# For quick preview (displays on screen)
parser.display_pages_with_boxes("document.pdf")
```

## ✨ Features

### 🔍 Layout Detection
- Advanced document layout analysis using PaddleOCR
- Accurate identification of text, tables, charts, and figures
- Configurable confidence thresholds

### 📝 OCR Processing
- High-quality text extraction using Tesseract
- Support for multiple languages
- Configurable OCR parameters

### 🖼️ Visual Element Extraction
- Automatic cropping and saving of figures, charts, and tables
- Organized output directory structure
- High-resolution image preservation

### 🤖 VLM Integration
- Vision Language Model support for structured data extraction
- Multiple provider options (Gemini, OpenAI)
- Automatic conversion of charts and tables to structured formats

### 📊 Multiple Output Formats
- **Markdown**: Human-readable document with embedded images and tables
- **Excel**: Structured data in spreadsheet format
- **JSON**: Programmatically accessible structured data
- **Images**: High-quality cropped visual elements

### ⚙️ Flexible Configuration
- Extensive customization options
- Performance tuning parameters
- Output format selection

## 📋 Requirements

### Core Dependencies
- **PaddleOCR**: Document layout detection
- **Outlines**: Structured output generation
- **Tesseract**: OCR text extraction
- **Pillow**: Image processing
- **OpenCV**: Computer vision operations
- **Pandas**: Data manipulation
- **OpenPyXL**: Excel file generation
- **Google Generative AI**: For Gemini VLM integration
- **OpenAI**: For GPT-5 VLM integration

## 🖥️ Web Interface (Gradio)

You can try Doctra in a simple web UI powered by Gradio.

### Run locally

```bash
pip install -U gradio
python gradio_app.py
```

Then open the printed URL (default `http://127.0.0.1:7860`).

Notes:
- If using VLM, set the API key field in the UI or export `VLM_API_KEY`.
- Outputs are saved under `outputs/<pdf_stem>/` and previewed in the UI.

### Deploy on Hugging Face Spaces

1) Create a new Space (type: Gradio, SDK: Python).

2) Add these files to the Space repo:
   - Your package code (or install from PyPI).
   - `gradio_app.py` (entry point).
   - `requirements.txt` with at least:

```text
doctra
gradio
```

3) Set a secret named `VLM_API_KEY` if you want VLM features.

4) In Space settings, set `python gradio_app.py` as the run command (or rely on auto-detect).

The Space will build and expose the same interface for uploads and processing.
