Metadata-Version: 2.5
Name: automated-document-parser
Version: 0.2.0
Summary: A modular document parsing and intelligence toolkit for Python applications
Project-URL: Homepage, https://github.com/Pulkit12dhingra/automated-document-parser
Project-URL: Documentation, https://pulkit12dhingra.github.io/automated-document-parser/
Project-URL: Repository, https://github.com/Pulkit12dhingra/automated-document-parser
Project-URL: Issues, https://github.com/Pulkit12dhingra/automated-document-parser/issues
Project-URL: Changelog, https://github.com/Pulkit12dhingra/automated-document-parser/blob/master/CHANGELOG.md
Author: Pulkit Dhingra
License: MIT License
        
        Copyright (c) 2025 Pulkit Dhingra
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: document-intelligence,document-processing,langchain,ocr,pdf,rag
Classifier: Development Status :: 3 - Alpha
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.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing
Requires-Python: >=3.11
Requires-Dist: langchain-core<2.0,>=1.3.3
Requires-Dist: pypdf<8.0,>=7.2.0
Requires-Dist: python-docx<2.0,>=1.1
Provides-Extra: ai
Requires-Dist: langchain-huggingface>=1.3.0; extra == 'ai'
Requires-Dist: langchain<2.0,>=1.5.2; extra == 'ai'
Requires-Dist: sentence-transformers>=6.3.0; extra == 'ai'
Requires-Dist: transformers>=5.24.1; extra == 'ai'
Provides-Extra: all
Requires-Dist: amazon-textract-caller>=0.2.4; extra == 'all'
Requires-Dist: boto3>=1.44.12; extra == 'all'
Requires-Dist: faiss-cpu>=1.16.0; extra == 'all'
Requires-Dist: fastapi<1.0,>=0.165.0; extra == 'all'
Requires-Dist: jq>=1.8; extra == 'all'
Requires-Dist: langchain-community<1.0,>=0.4.2; extra == 'all'
Requires-Dist: langchain-huggingface>=1.3.0; extra == 'all'
Requires-Dist: langchain-opendataloader-pdf; extra == 'all'
Requires-Dist: langchain-pymupdf4llm; extra == 'all'
Requires-Dist: langchain-unstructured<2.0,>=1.0.1; extra == 'all'
Requires-Dist: langchain<2.0,>=1.5.2; extra == 'all'
Requires-Dist: openai<4.0,>=3.60.0; extra == 'all'
Requires-Dist: pdfplumber<1.0,>=0.11; extra == 'all'
Requires-Dist: pillow>=10.1; extra == 'all'
Requires-Dist: prometheus-client<1.0,>=0.26.0; extra == 'all'
Requires-Dist: pydantic<3.0,>=2.7; extra == 'all'
Requires-Dist: pymupdf<2.2,>=1.24; extra == 'all'
Requires-Dist: pypdfium2>=4.30; extra == 'all'
Requires-Dist: pytesseract<1.0,>=0.3.13; extra == 'all'
Requires-Dist: requests>=2.34.2; extra == 'all'
Requires-Dist: sentence-transformers>=6.3.0; extra == 'all'
Requires-Dist: sphinx-rtd-theme>=3.0; extra == 'all'
Requires-Dist: sphinx>=8.2; extra == 'all'
Requires-Dist: transformers>=5.24.1; extra == 'all'
Requires-Dist: uvicorn<1.0,>=0.54.0; extra == 'all'
Provides-Extra: api
Requires-Dist: fastapi<1.0,>=0.165.0; extra == 'api'
Requires-Dist: prometheus-client<1.0,>=0.26.0; extra == 'api'
Requires-Dist: pydantic<3.0,>=2.7; extra == 'api'
Requires-Dist: uvicorn<1.0,>=0.54.0; extra == 'api'
Provides-Extra: community
Requires-Dist: langchain-community<1.0,>=0.4.2; extra == 'community'
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: coverage<7.18,>=7.6; extra == 'dev'
Requires-Dist: httpx<1.0,>=0.27; extra == 'dev'
Requires-Dist: langchain-community<1.0,>=0.4.2; extra == 'dev'
Requires-Dist: pre-commit>=4.0; extra == 'dev'
Requires-Dist: pytest-cov>=6.0; extra == 'dev'
Requires-Dist: pytest>=8.3; extra == 'dev'
Requires-Dist: reportlab>=4.2; extra == 'dev'
Requires-Dist: ruff<0.18,>=0.14.4; extra == 'dev'
Requires-Dist: twine>=6.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: sphinx-rtd-theme>=3.0; extra == 'docs'
Requires-Dist: sphinx>=8.2; extra == 'docs'
Provides-Extra: json
Requires-Dist: jq>=1.8; extra == 'json'
Provides-Extra: mathpix
Requires-Dist: langchain-community<1.0,>=0.4.2; extra == 'mathpix'
Requires-Dist: requests>=2.34.2; extra == 'mathpix'
Provides-Extra: ocr
Requires-Dist: pdfplumber<1.0,>=0.11; extra == 'ocr'
Requires-Dist: pillow>=10.1; extra == 'ocr'
Requires-Dist: pypdfium2>=4.30; extra == 'ocr'
Requires-Dist: pytesseract<1.0,>=0.3.13; extra == 'ocr'
Provides-Extra: openai
Requires-Dist: openai<4.0,>=3.60.0; extra == 'openai'
Provides-Extra: opendataloader
Requires-Dist: langchain-opendataloader-pdf; extra == 'opendataloader'
Provides-Extra: pdf-images
Requires-Dist: pdfplumber<1.0,>=0.11; extra == 'pdf-images'
Requires-Dist: pillow>=10.1; extra == 'pdf-images'
Requires-Dist: pypdfium2>=4.30; extra == 'pdf-images'
Provides-Extra: pdf-layout
Requires-Dist: pdfplumber<1.0,>=0.11; extra == 'pdf-layout'
Provides-Extra: pdf-tables
Requires-Dist: pdfplumber<1.0,>=0.11; extra == 'pdf-tables'
Provides-Extra: pdf-unstructured
Requires-Dist: langchain-unstructured<2.0,>=1.0.1; extra == 'pdf-unstructured'
Provides-Extra: pdfium
Requires-Dist: pypdfium2>=4.30; extra == 'pdfium'
Provides-Extra: pymupdf
Requires-Dist: pymupdf<2.2,>=1.24; extra == 'pymupdf'
Provides-Extra: pymupdf4llm
Requires-Dist: langchain-pymupdf4llm; extra == 'pymupdf4llm'
Provides-Extra: textract
Requires-Dist: amazon-textract-caller>=0.2.4; extra == 'textract'
Requires-Dist: boto3>=1.44.12; extra == 'textract'
Requires-Dist: langchain-community<1.0,>=0.4.2; extra == 'textract'
Provides-Extra: vector
Requires-Dist: faiss-cpu>=1.16.0; extra == 'vector'
Description-Content-Type: text/markdown

# Automated Document Parser

[![PyPI version](https://badge.fury.io/py/automated-document-parser.svg)](https://pypi.org/project/automated-document-parser/)
[![Python Version](https://img.shields.io/pypi/pyversions/automated-document-parser.svg)](https://pypi.org/project/automated-document-parser/)
[![CI](https://github.com/Pulkit12dhingra/automated-document-parser/actions/workflows/ci.yml/badge.svg)](https://github.com/Pulkit12dhingra/automated-document-parser/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/Pulkit12dhingra/automated-document-parser/branch/master/graph/badge.svg)](https://codecov.io/gh/Pulkit12dhingra/automated-document-parser)
[![GitHub issues](https://img.shields.io/github/issues/Pulkit12dhingra/automated-document-parser)](https://github.com/Pulkit12dhingra/automated-document-parser/issues)
[![GitHub pull requests](https://img.shields.io/github/issues-pr/Pulkit12dhingra/automated-document-parser)](https://github.com/Pulkit12dhingra/automated-document-parser/pulls)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)



A modular Python toolkit for document parsing, evidence-linked intelligence, privacy-aware transformation and retrieval. It automatically detects supported file types, preserves source provenance, and offers a compatibility API for LangChain applications alongside a normalized API for new integrations.

## Features

- **Automatic file type detection** based on file extensions
- **Multiple PDF loading methods** - 10 different PDF loaders for various use cases
- **Modular architecture** - Clean separation with `file_load/` and `pdf_load/` modules
- **Support for multiple document formats**: PDF, TXT, CSV, JSON, DOCX, HTML, Markdown
- A normalised `ParsedDocument` model that preserves source metadata and page-level elements
- Evidence-linked document classification, entity recognition and schema-based extraction
- Structure-aware chunking, conservative text normalization, duplicate detection and local PII redaction
- A high-level `DocumentProcessor` API alongside the backwards-compatible `DocumentParser`
- An end-to-end ingestion pipeline for normalization, optional PII redaction, intelligence, chunking, embeddings and persistent indexing
- Configurable PDF backends, including layout-aware extraction of headings, paragraphs, tables and source coordinates
- Optional integrations for OCR, tables and AI workloads
- Batch processing, explicit error handling and JSON serialisation
- LangChain-compatible output for existing RAG applications
- Durable SQLite-backed ingestion jobs, a secured optional HTTP API and a standard-library Python client
- Structured JSON/human logging, correlation IDs, Prometheus metrics and optional Grafana dashboards
- Verified SQLite backup/restore, CLI workflows, container deployment and reproducible quality/performance benchmarks
- File/DOCX resource limits, allowed-root API path validation, request limits and explicit prompt-injection safety guidance

## Supported File Types

### Text Files
- `.txt` - Plain text files
- `.md`, `.markdown` - Markdown files

### Structured Data
- `.csv` - CSV files with encoding support
- `.json` - JSON files (custom jq schema filtering available with the `[json]` extra)

### Documents
- `.docx` - Microsoft Word documents
- `.html`, `.htm` - HTML files (standard-library extraction; no HTML extra required)

### PDF Files (10 loading methods)
- `pypdf` - Basic PDF text extraction (default, no extra dependencies)
- `unstructured` - Advanced OCR and layout detection
- `amazon_textract` - AWS Textract for high-accuracy OCR
- `mathpix` - Specialized for mathematical formulas
- `pdfplumber` - Page-level text and table extraction
- `pdfplumber-layout` - Layout-aware headings, paragraphs, tables and page coordinates, with optional OCR fallback and image-region artifacts
- `pypdfium2` - Google PDFium library
- `pymupdf` - PyMuPDF (fitz) backend
- `pymupdf4llm` - LLM-optimized extraction
- `opendataloader` - Advanced multi-format parsing

## Installation

The core installation includes the standard parser and PDF backend without installing
large model runtimes or vector databases. Optional integrations can be installed as
needed.

Install from PyPI:

```bash
pip install automated-document-parser
```

Or using uv:

```bash
uv add automated-document-parser
```

Optional capabilities:

```bash
pip install "automated-document-parser[json]"          # jq-powered JSON queries
pip install "automated-document-parser[pdf-tables]"    # PDF table extraction
pip install "automated-document-parser[pdf-layout]"     # Layout-aware PDF extraction, tables and coordinates
pip install "automated-document-parser[ocr]"            # Optional Tesseract OCR wrapper and rendering support
pip install "automated-document-parser[pdf-images]"      # Optional rendered image-region extraction
pip install "automated-document-parser[pdf-unstructured]" # OCR and layout-aware PDF parsing
pip install "automated-document-parser[textract]"        # AWS Textract integration
pip install "automated-document-parser[mathpix]"         # Mathpix PDF integration
pip install "automated-document-parser[pymupdf]"         # PyMuPDF backend
pip install "automated-document-parser[pymupdf4llm]"     # LLM-oriented PDF extraction
pip install "automated-document-parser[pdfium]"          # PDFium backend
pip install "automated-document-parser[opendataloader]"  # OpenDataLoader integration
pip install "automated-document-parser[community]"      # LangChain community integrations
pip install "automated-document-parser[all]"            # All optional integrations (large install)
pip install "automated-document-parser[ai]"            # LLM and embedding integrations
pip install "automated-document-parser[vector]"        # FAISS vector search
pip install "automated-document-parser[docs]"          # Build the documentation
pip install "automated-document-parser[dev]"            # Development and testing
```

The local `pymupdf` and `pdfium` backends use their native libraries directly and do
not require `langchain-community`. The community extra remains optional for specialized
integrations that still use community loaders, including Textract and Mathpix.

The package supports Python 3.11 and newer. Install only the extras required by your
workload; custom JSON jq expressions and advanced PDF backends require their corresponding extras.
HTML, text, CSV and standard JSON parsing use built-in Python functionality.
OCR requires the optional `[ocr]` extra, the Tesseract OCR system binary and language data, plus the optional PDFium renderer included in the extra. Image-region extraction requires the `[pdf-images]` extra and an output directory. OCR is local and is not sent to a cloud service by this backend.
The `[all]` extra installs heavyweight AI and document-processing dependencies; it is not
recommended for lightweight deployments.

## Quick Start

### Basic Usage - Automatic File Type Detection

The primary feature is **automatic file type detection**. Just point to any supported file and the parser handles the rest:

```python
from automated_document_parser import DocumentParser, DocumentProcessor

# Compatibility API: returns LangChain Document objects
parser = DocumentParser()

# Recommended API for new integrations: returns a normalised result
processor = DocumentProcessor()
result = processor.process("document.pdf")
print(result.content)
print(result.metadata)
print(result.to_json())

# Parse any single file - automatically detects type and uses the right loader
documents = parser.parse("document.pdf")  # Auto-detects PDF
documents = parser.parse("data.csv")  # Auto-detects CSV
documents = parser.parse("notes.txt")  # Auto-detects text file

# Parse multiple files of different types - all formats handled automatically
file_paths = ["report.pdf", "data.csv", "notes.txt", "info.docx"]
all_docs = parser.parse_multiple(file_paths)  # Each file auto-detected and loaded

# Access parsed content
for file_path, docs in all_docs.items():
    print(f"File: {file_path}")
    for doc in docs:
        print(f"  Content: {doc.page_content[:100]}...")
        print(f"  Metadata: {doc.metadata}")
```

### Specify Loading Methods

Specify the PDF loading method and other parameters to apply to all files:

```python
from automated_document_parser import DocumentParser

parser = DocumentParser()

# Step 1: Specify the method for PDFs
# Step 2: Parser automatically detects file types and loads them with specified method
file_paths = ["report1.pdf", "report2.pdf", "data.csv", "notes.txt"]
all_docs = parser.parse_multiple(
    file_paths,
    pdf_loader_method="pdfplumber",  # All PDFs will use pdfplumber
    encoding="utf-8",  # All text files will use UTF-8 encoding
)

# Each file is automatically detected and loaded with the specified settings
for file_path, docs in all_docs.items():
    print(f"Loaded {file_path}: {len(docs)} documents")
```

### OCR Fallback and Image-Region Extraction

Install the optional OCR and image-rendering dependencies with `pip install "automated-document-parser[pdf-layout,ocr,pdf-images]"` and install the Tesseract system binary separately (for example, `brew install tesseract` on macOS or the `tesseract-ocr` package on Debian/Ubuntu). Language packs must also be installed for the languages you request.

```python
from automated_document_parser import DocumentProcessor

result = DocumentProcessor().process(
    "scanned-report.pdf",
    pdf_loader_method="pdfplumber-layout",
    ocr_fallback=True,  # OCR pages with fewer than 20 native text characters
    ocr_min_characters=20,
    ocr_languages="eng",
    ocr_resolution=250,
    image_output_dir="artifacts/extracted-images",  # optional image-region PNG crops
)

for element in result.elements:
    print(element.element_type, element.page_number, element.confidence)
    if element.element_type == "image":
        print(element.metadata["asset_path"])
```

OCR fallback is opt-in and runs only on pages below the configurable native-text threshold. OCR confidence is normalized to the 0–1 range from Tesseract's word-level confidence values; it is a signal for downstream review, not a calibrated probability. Image artifacts are rendered page-region crops (not original embedded image bytes), with bounding boxes and extraction provenance. The default parser does not install or invoke OCR.

## Document Intelligence

The `DocumentProcessor` exposes a deterministic, dependency-free intelligence layer for document classification, common entity recognition and schema-guided extraction. Each extracted value includes evidence pointing back to its source text, element, page and bounding box when the loader provides layout metadata.

```python
from automated_document_parser import DocumentProcessor

processor = DocumentProcessor()
document = processor.process("invoice.pdf", pdf_loader_method="pdfplumber-layout")

classification = processor.classify(document)
print(classification.label, classification.confidence)

for entity in processor.extract_entities(document):
    print(entity.entity_type, entity.normalized_value, entity.evidence.page_number)

invoice_schema = {
    "title": "Invoice",
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string"},
        "invoice_date": {"type": "string", "aliases": ["Date of invoice"]},
        "vendor": {"type": "string"},
        "total": {"type": "number"},
    },
    "required": ["invoice_number", "total"],
}
extraction = processor.extract(document, invoice_schema)
print(extraction.values)
print(extraction.fields["total"].evidence)
print(extraction.missing_required)
```

The built-in classifier uses explainable keyword and filename signals. Entity recognition covers common business-document values such as emails, URLs, dates, phone numbers, currency amounts, percentages, invoice/PO identifiers, tax identifiers, and explicitly labelled people, organizations and addresses. The rule-based schema extractor supports flat JSON-Schema-shaped objects with `string`, `number`, `integer` and `boolean` properties, `required`, `enum` and per-field `aliases`. It does not claim full JSON Schema compliance or infer arbitrary unlabeled values. Duplicate label matches are reported as `ambiguous`; missing required fields and type mismatches remain explicit rather than being silently guessed.

For model-backed or domain-specific extraction, pass a custom object implementing the `SchemaExtractionBackend` protocol to `DocumentProcessor(schema_extractor=...)`. The backend must return the same evidence-aware `StructuredExtraction` contract. This keeps model runtimes and provider credentials outside the core installation.

Confidence values from the built-in rules are heuristic ranking signals, not calibrated probabilities. Evidence offsets are character offsets into `ParsedDocument.content`; page numbers and bounding boxes are populated when available from the parser.

## Document Transformation and Privacy

The transformation layer provides structure-aware chunking, conservative text normalization, duplicate detection and local PII redaction. All operations return new results and leave the original ``ParsedDocument`` unchanged.

```python
from automated_document_parser import DocumentProcessor

processor = DocumentProcessor()
document = processor.process("contract.pdf", pdf_loader_method="pdfplumber-layout")

# Chunks preserve offsets, element indexes, page numbers and element types.
chunks = processor.chunk(document, max_chars=1200, overlap=120)

# Normalize a copy without flattening the document's element structure.
normalized = processor.normalize(document)

# Identify repeated paragraphs or layout elements.
duplicates = processor.find_duplicates(normalized, threshold=0.92)

# Detect sensitive values and create a separately redacted copy.
findings = processor.detect_pii(normalized)
redacted = processor.redact(
    normalized, categories=["email", "phone", "us_ssn", "credit_card"]
)
print(redacted.redacted_document.content)
print(redacted.redactions)  # Audit entries contain categories and offsets, not values.
```

Chunking prefers element boundaries and splits oversized elements at paragraph, line, sentence or word boundaries. Offsets refer to the original ``ParsedDocument.content``. The default overlap adapts to small chunk sizes; an explicit overlap must be smaller than ``max_chars``.

Normalization supports Unicode NFC/NFKC/NFD/NFKD, whitespace cleanup, soft-hyphen removal and line-wrap dehyphenation. These operations can change text offsets; normalize before chunking or evidence extraction when normalized text is the intended downstream source.

Duplicate detection uses standard-library sequence matching and is quadratic in the number of eligible elements. It is intended for individual documents and modest element counts, not corpus-scale similarity search.

PII detection is local and rule-based. It currently recognizes email addresses, US Social Security numbers, Luhn-valid payment card numbers, IPv4 addresses and phone numbers with sufficient context. It is not a complete compliance-grade detector and may miss jurisdiction-specific identifiers or contextual PII. Review results before using them for regulatory decisions.

Redaction creates a separate ``ParsedDocument``. Its audit trail deliberately omits the original sensitive values, and arbitrary loader metadata is not copied into the redacted output because metadata may itself contain OCR text or PII. Source identity and structural page/layout information are retained. The original input remains unchanged. For production workflows, store the original and redacted artifacts under separate access controls and validate redaction against the rendered output, not only extracted text.

## Examples and notebooks

The repository now has paired, feature-focused examples: runnable Python
scripts in `examples/` and guided Jupyter notebooks in `notebook_examples/`.
Start with the complete offline workflow:

```bash
python examples/full_workflow.py
```

For the feature-by-feature catalogue, setup notes, optional dependencies and
the mapping between scripts and notebooks, see [examples/README.md](examples/README.md)
and [notebook_examples/README.md](notebook_examples/README.md).

The examples cover parsing and file limits, normalized document models,
document intelligence and evidence, transformations and PII, chunking,
embeddings, BM25/hybrid retrieval, SQLite persistence, evaluation, PDF
backends/OCR, API and client workflows, durable jobs, backup/restore, logging,
metrics, monitoring, containers, benchmarks and security boundaries.

All core walkthroughs are designed to run locally without paid services or
model downloads. Examples that need optional extras, Tesseract, Docker, an API
server or credentials are clearly labelled and kept separate from the offline
quick-start path.

## Documentation

- **Online documentation:** https://pulkit12dhingra.github.io/automated-document-parser/
- **Feature guide:** [docs/feature_guide.rst](docs/feature_guide.rst)
- **API reference:** [docs/api.rst](docs/api.rst)
- **Benchmarks:** [docs/benchmarks.rst](docs/benchmarks.rst)
- **Operations:** [backup/restore](docs/backup_restore.rst) and [monitoring](docs/monitoring.rst)

## Architecture

The library uses a modular architecture:

```
automated_document_parser/
├── loaders/
│   ├── file_load/          # File loaders module
│   │   ├── base.py         # Base file loader class
│   │   ├── text_loader.py  # Text file loader
│   │   ├── csv_loader.py   # CSV loader
│   │   ├── json_loader.py  # JSON loader
│   │   ├── docx_loader.py  # DOCX loader
│   │   └── html_loader.py  # HTML loader
│   ├── pdf_load/           # PDF loaders module
│   │   ├── base.py         # Base PDF loader class
│   │   ├── pypdf_loader.py
│   │   ├── mathpix_loader.py
│   │   ├── pdfplumber_loader.py
│   │   ├── pdfplumber_layout_loader.py
│   │   └── ... (10 PDF loaders total)
│   └── file_loaders.py     # Main orchestrator
├── core.py                 # Backwards-compatible DocumentParser API
├── processor.py            # Recommended DocumentProcessor API
├── ingestion.py            # End-to-end ingestion orchestration
├── models.py               # ParsedDocument and DocumentElement models
├── intelligence/           # Classification, entities and evidence-linked extraction
├── transformation/         # Chunking, normalization, deduplication and privacy
├── retrieval/              # BM25, embeddings, hybrid search, stores and evaluation
├── api.py / client.py      # Optional HTTP service and standard-library client
├── jobs.py                 # Durable SQLite jobs and single background worker
├── backup.py               # Verified SQLite backup and restore
├── logging_config.py       # Structured logs and correlation IDs
└── observability.py        # API metrics and runtime health signals
```

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for release history.

## License

MIT License - see LICENSE file for details.

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. Before creating a release tag, follow [RELEASE_CHECKLIST.md](RELEASE_CHECKLIST.md); normal merges do not publish a package.
## Input safety and prompt injection

Local file loading applies preflight resource limits by default: files up to
100 MiB, and DOCX archives up to 10,000 members, 512 MiB uncompressed, and a
1,000:1 per-member compression ratio. Configure tighter limits for a service
that accepts user uploads:

```python
from automated_document_parser import DocumentProcessor, FileResourceLimits

processor = DocumentProcessor()
result = processor.process(
    "customer-upload.docx",
    resource_limits=FileResourceLimits(
        max_file_size_bytes=25 * 1024 * 1024,
        max_docx_uncompressed_bytes=100 * 1024 * 1024,
        max_docx_members=2_000,
        max_docx_compression_ratio=200,
    ),
)
```

Set an individual limit to `None` to disable only that cap. Passing
`resource_limits=None` disables all preflight limits and is not recommended for
untrusted uploads. These checks are not a malware scanner or a substitute for
process/container isolation, CPU and memory limits, and parser timeouts.

Extracted document text is untrusted data. A PDF, OCR result, HTML page, or
text file may contain prompt-injection instructions such as requests to reveal
secrets or invoke tools. The parser does not execute those instructions and
does not attempt to classify or neutralize prompt injection. If content is sent
to an LLM, keep it separate from system/developer instructions, enforce tool
permissions in application code, use least-privilege credentials, and require
approval for consequential actions. See [the security policy](SECURITY.md).

## Command-line interface

The package installs an `adp` command and also supports `python -m automated_document_parser`. The CLI emits JSON to standard output, sends errors to standard error, and returns a non-zero exit code when a command fails.

```bash
# Parse one document and print its structured representation
adp inspect invoice.pdf

# Ingest one or more documents into a persistent local SQLite index
adp ingest ./documents/*.pdf --database ./.adp/index.sqlite3 --redact-pii

# Search the persistent index (use the same embedding configuration as ingestion)
adp search "invoice payment terms" --database ./.adp/index.sqlite3
```

The default `hashing` embedding backend is local and dependency-free, but it is a lexical feature-hashing baseline, **not a semantic embedding model**. For semantic retrieval, install the `openai` extra and select `--embedding-backend openai-compatible`; configure `OPENAI_API_KEY` or provide `--embedding-base-url` for an OpenAI-compatible local service. Use the same backend, model and dimensions for ingestion and search. SQLite is intended for local deployments and modest collections; use a dedicated vector database adapter for larger or distributed workloads.

`ingest` continues after per-file errors and reports them in JSON; pass `--strict` to stop at the first error. PII redaction is opt-in. As with the Python API, it redacts extracted text and does not sanitize the original PDF or other source artifact.

## HTTP API and background ingestion jobs

Install the optional API dependencies:

```bash
pip install "automated-document-parser[api]"
```

Start the local API and its background worker. The service only accepts files under explicitly configured server-side directories; it does not accept arbitrary filesystem paths or upload bodies.

```bash
adp serve \
  --allowed-root ./documents \
  --database ./.adp/index.sqlite3 \
  --jobs-database ./.adp/jobs.sqlite3
```

The server binds to `127.0.0.1:8000` by default. To expose it on another interface, set an API key and use a TLS-terminating reverse proxy:

```bash
export ADP_API_KEY="replace-with-a-long-random-secret"
adp serve --host 0.0.0.0 --allowed-root ./documents
```

When configured, all routes except `/healthz` and `/readyz` require the `X-API-Key` header or an `Authorization: Bearer` token. The Prometheus `/metrics` endpoint remains protected. `/healthz` is a lightweight process liveness probe; `/readyz` checks dependencies and worker readiness. The API provides:

| Method and route | Purpose |
|---|---|
| `POST /v1/jobs` | Queue a document path for ingestion; returns `202 Accepted` and a job ID |
| `GET /v1/jobs/{job_id}` | Read job state, attempts, errors or the compact ingestion result |
| `GET /v1/jobs?status=queued` | List recent jobs, optionally filtered by status |
| `DELETE /v1/jobs/{job_id}` | Cancel a queued job (running jobs finish normally) |
| `POST /v1/jobs/{job_id}/retry` | Manually retry a terminal failed job |
| `POST /v1/worker/pause` / `resume` | Pause new claims or resume the worker |
| `GET /v1/search?q=invoice&limit=5` | Search the persistent index and return chunk provenance |
| `GET /healthz` | Lightweight process liveness probe |
| `GET /readyz` | Job-store, vector-store and managed-worker readiness |
| `GET /metrics` | Prometheus metrics (API-key protected when authentication is enabled) |

The HTTP service exposes /healthz as a lightweight liveness probe, /readyz for job-store, vector-store and active managed-worker readiness, and /metrics in Prometheus text exposition format. Metrics cover HTTP request totals (adp_http_requests_total) and latency histograms (adp_http_request_duration_seconds), accepted ingestion jobs (adp_ingestion_jobs_enqueued_total), durable queue-state counts (adp_ingestion_jobs) and worker running/paused state. The metrics endpoint follows the same API-key authentication policy as other protected API routes. Install the api extra to enable the API and metrics dependencies.

### Python API client

A small synchronous client is included and uses only the Python standard library (no extra SDK dependency):

```python
from automated_document_parser import ADPClient

client = ADPClient("http://127.0.0.1:8000", api_key="your-api-key")
job = client.submit_job("/server/documents/invoice.pdf", idempotency_key="invoice-001")
print(client.get_job(job["id"]))
print(client.search("invoice total", limit=5))
```

The document path must exist on the API server under one of its configured `--allowed-root` directories. The example script covers each client operation:

```bash
export ADP_API_URL="http://127.0.0.1:8000"
export ADP_API_KEY="your-api-key"  # omit if the server has no API key configured

python examples/api_client.py submit /server/documents/invoice.pdf --idempotency-key invoice-001
python examples/api_client.py status JOB_ID
python examples/api_client.py list --limit 10 --status queued
python examples/api_client.py search "invoice total" --limit 5
python examples/api_client.py cancel JOB_ID  # queued jobs only
python examples/api_client.py retry JOB_ID   # terminal failed jobs only
```

The CLI emits structured JSON logs to stderr by default. Set `--log-level` to `debug`, `info`, `warning`, `error` or `critical` on `inspect`, `ingest`, `search` and `serve`. API responses include an `X-Request-ID`; a valid caller-supplied ID is preserved, otherwise the service generates one. Request logs carry the request ID; the enqueue event links that request to a job ID, which is then used to correlate the background worker and ingestion-stage logs. Logs include event names, request status/latency, ingestion stage durations and job lifecycle events; document text, request bodies and query strings are not logged by these observability events.

Job states are `queued`, `running`, `succeeded`, `failed` and `cancelled`. Queued jobs can be cancelled; failed jobs can be manually retried; worker pause/resume controls stop new claims without interrupting an active document. The SQLite queue survives restarts, requeues jobs left running by an interrupted worker, and retries failures up to three attempts with bounded exponential backoff. The default worker processes one job at a time. Keep one worker process per jobs database; SQLite is intended for local or modest single-host deployments, not as a distributed queue.

The API resolves submitted paths and enforces the configured allowed roots, regular-file checks and a default 100 MiB file limit. It repeats the path and size checks immediately before processing to reduce symlink/file replacement races. Tune the limit with `--max-file-size-mb`. Use filesystem permissions and OS-level isolation as additional controls. The API does not upload or copy documents. Search must use the same embedding backend, model and dimensions used during ingestion. Configure the same `--embedding-*` options for `serve` as used by the CLI when sharing an index.

## Container deployment

The repository includes a non-root production image and a Docker Compose setup for a single-host deployment. The API and its durable background worker run together in one service, sharing a persistent SQLite volume. This is intentionally a single-worker deployment: do not scale replicas against the same SQLite job database.

1. Install Docker Engine and the Docker Compose plugin.
2. Create the document directory and environment file:

   ```bash
   mkdir -p documents
   cp .env.example .env
   python -c "import secrets; print(secrets.token_urlsafe(48))"
   ```

   Put the generated secret in `.env` as `ADP_API_KEY`. Do not commit `.env`.
3. Start the service:

   ```bash
   docker compose up --build -d
   docker compose ps
   docker compose logs -f api
   ```

4. The API is bound to `127.0.0.1:8000` on the host by default. Use a TLS-terminating reverse proxy for remote access; do not expose the container port directly to the public internet. Set `ADP_PORT` in `.env` to change the host-side port.
5. Submit only paths inside the mounted `./documents` directory. The mount is read-only in the container. The SQLite vector index and durable job queue are stored in the named `adp-data` volume.
6. Stop the service with `docker compose down`. This preserves the named data volume. To intentionally erase persisted index and job data as well, use `docker compose down --volumes`.

The image uses a multi-stage build, a dedicated unprivileged UID, a read-only root filesystem, dropped Linux capabilities, a bounded temporary filesystem and a readiness-based container health check. Compose requires `ADP_API_KEY`; the metrics endpoint and API routes remain protected by that key. `/healthz` and `/readyz` remain available for local health checks.

The default embedding backend is local hashing, which is not semantic. For semantic embeddings, set `ADP_EMBEDDING_BACKEND=openai-compatible` and provide `OPENAI_API_KEY` in `.env`. The host-side port is bound to loopback; configure HTTPS and access controls in a reverse proxy before allowing remote clients.

The container image is built and smoke-tested in GitHub Actions. This configuration does not provision a cloud host, public DNS, TLS certificates, backups or a managed monitoring service.

## Production document ingestion

`DocumentIngestionPipeline` composes the existing modules into a repeatable ingestion workflow. It is provider-neutral: inject the embedding backend and vector store that match your deployment. Without an embedder, it still performs parsing, normalization, optional redaction, classification, entity extraction and chunking, and supports lexical BM25 search.

```python
from automated_document_parser import (
    DocumentIngestionPipeline,
    IngestionConfig,
    OpenAICompatibleEmbedder,
    SQLiteVectorStore,
)

embedder = OpenAICompatibleEmbedder(model="text-embedding-3-small")
with SQLiteVectorStore("document-index.sqlite3") as store:
    pipeline = DocumentIngestionPipeline(
        config=IngestionConfig(
            pdf_loader_method="pdfplumber-layout",
            redact_pii=True,
            max_chars=1200,
            overlap=120,
        ),
        embedder=embedder,
        vector_store=store,
    )
    result = pipeline.ingest("invoice.pdf")
    print(result.classification.label, result.stage_durations_ms)
    for hit in pipeline.search("invoice total", k=5):
        print(hit.chunk.source, hit.chunk.page_numbers, hit.chunk.content)
```

For multiple sources, `pipeline.ingest_many(paths)` continues after individual failures and returns successful results plus typed failure summaries. Set `strict=True` to stop at the first failure. The pipeline fingerprints normalized (and, when enabled, redacted) content and reports per-stage timings. Redaction is opt-in; when enabled, classification, extraction, chunking and embeddings all operate on the redacted representation. The built-in SQLite and in-memory stores replace prior chunks for the same source; custom vector stores should implement the optional `replace_source(chunks, vectors, source=...)` method for the same update semantics. Without that method, the pipeline falls back to the adapter's `add` method. This is text-level redaction and does not sanitize the original PDF or image artifacts; apply the source-artifact controls described in [Document Transformation and Privacy](#document-transformation-and-privacy) before distributing files.

## Hybrid retrieval

The retrieval module combines dependency-free BM25 search with optional vector
search using Reciprocal Rank Fusion (RRF). Embedding providers, vector stores,
tokenizers, and rerankers are injected through small protocols, so the core
package does not download models or require a database. The in-memory vector
store is intended for tests and modest collections; use a persistent adapter
for production corpora. `HashingEmbedder` is a deterministic feature-hashing
baseline for offline examples, not a semantic embedding model.

```python
from automated_document_parser import DocumentProcessor, HashingEmbedder

processor = DocumentProcessor()
document = processor.process("annual-report.pdf", pdf_loader_method="pdfplumber-layout")
chunks = processor.chunk(document, max_chars=1200, overlap=120)
retriever = processor.create_retriever(chunks, embedder=HashingEmbedder())

for hit in processor.search(retriever, "revenue growth and operating margin", k=5):
    print(hit.score, hit.chunk.source, hit.chunk.page_numbers)
    print(hit.chunk.start_offset, hit.chunk.end_offset, hit.chunk.content)
```

For model-aware chunk budgets, supply a tokenizer without adding a mandatory
runtime dependency:

```python
class MyTokenizer:
    def count_tokens(self, text: str) -> int:
        return len(my_tokenizer.encode(text))


token_chunks = processor.chunk_by_tokens(
    document, tokenizer=MyTokenizer(), max_tokens=512, overlap_tokens=50
)
```

Implement `EmbeddingBackend`, `VectorStore`, or `Reranker` to connect a hosted
embedding API, a local model, or another vector database. A reranker can be
passed to `create_retriever`; it receives the query and candidate texts.

For durable local vector indexing, use the standard-library SQLite adapter:

```python
from automated_document_parser import SQLiteVectorStore

with SQLiteVectorStore("document-vectors.sqlite3") as store:
    retriever = processor.create_retriever(
        chunks, embedder=my_embedder, vector_store=store
    )
    results = processor.search(retriever, "invoice payment terms")
```

To reuse an already populated index without paying to re-embed the documents,
pass `index_embeddings=False` when creating the retriever. The embedding
backend is still used to embed each query. SQLite performs exact cosine search
and is intended for durable local or modest-sized collections, not distributed
or approximate nearest-neighbour workloads.

The optional `OpenAICompatibleEmbedder` adapter connects to OpenAI and
compatible embedding endpoints. Install the SDK with
`pip install automated-document-parser[openai]` and set `OPENAI_API_KEY`:

```python
from automated_document_parser import OpenAICompatibleEmbedder

embedder = OpenAICompatibleEmbedder(model="text-embedding-3-small")
```

For a local Ollama server exposing its OpenAI-compatible API, configure its
endpoint and model instead:

```python
embedder = OpenAICompatibleEmbedder(
    model="nomic-embed-text",
    base_url="http://localhost:11434/v1",
    api_key="ollama",  # local server placeholder; no hosted key is sent
)
```

The SDK is imported lazily; the base package remains lightweight. Embedding
requests are batched, ordered by provider response index, and checked for
missing, malformed, non-finite, or inconsistent vectors. A reranker can be
passed to `create_retriever`; it receives the query and candidate texts.
For offline retrieval evaluation, use `evaluate_retrieval` with relevance
judgements. The module exposes Precision@K, Recall@K, Mean Reciprocal Rank, and
nDCG@K.

### Reproducible retrieval benchmarks

The repository includes a small synthetic smoke-test dataset and a harness to
compare BM25, vector, and hybrid rankings:

```bash
python -m benchmarks.run_retrieval_benchmark --k 5 --output benchmark-results.json
```

The report contains per-query rankings, Precision@K, Recall@K, MRR, nDCG@K,
and a SHA-256 dataset fingerprint. The sample corpus is not representative
of production relevance. Use your own judged corpus and inject the embedding
backend you intend to deploy; see [the benchmark guide](docs/benchmarks.rst).


## Backup and restore

Create a verified local backup of the SQLite vector index and ingestion job queue:

```bash
adp backup --destination ./backups --retention-count 7
```

Restore into a new directory (existing targets are never overwritten):

```bash
adp restore ./backups/backup-<timestamp>-<id> --target-dir ./recovered-adp-state
```

Backups use SQLite's online backup API, include a checksum manifest, and are
validated before restore. The default retention policy keeps seven backups;
use `--retention-count 0` to disable pruning. The two SQLite files are
individually consistent, not a cross-database atomic snapshot. See
[Backup and Restore](docs/backup_restore.rst) for recovery guidance and limitations.

## Optional Prometheus and Grafana monitoring

A preconfigured Prometheus and Grafana stack is available through the optional
Compose profile. The default API-only deployment does not start either service.

1. Set a unique `GRAFANA_ADMIN_PASSWORD` in your uncommitted `.env` file.
2. Create the file-backed Prometheus API-key secret (the value must match `ADP_API_KEY`):

   ```bash
   set -a && . ./.env && set +a
   umask 077
   mkdir -p .secrets
   chmod 700 .secrets
   printf '%s' "$ADP_API_KEY" > .secrets/adp_api_key
   chmod 444 .secrets/adp_api_key
   ```

3. Start the monitoring profile:

   ```bash
   docker compose --profile monitoring up --build -d
   ```

4. Open Grafana at http://127.0.0.1:3000 and sign in with the configured
   administrator credentials. The **ADP Operations Overview** dashboard and
   Prometheus datasource are provisioned automatically.
5. Prometheus is available at http://127.0.0.1:9090. It scrapes the protected
   API metrics endpoint every 15 seconds using the API key over the private
   Compose network.

The dashboard covers request throughput, HTTP error ratios, p50/p95/p99 latency,
ingestion queue states and worker health. Prometheus also evaluates rules for
API unavailability, elevated 5xx rates, queue backlog and a stopped worker.
Alert rules are visible in Prometheus; notification delivery is not configured
until an Alertmanager receiver is explicitly added.

Both monitoring interfaces bind to loopback by default. Do not expose them
directly to the public internet. Prometheus retains 15 days of metrics by
default, and its data and Grafana state persist in named Docker volumes.

For configuration, security guidance, retention and teardown details, see
[Production Monitoring](docs/monitoring.rst).
