Automated Document Parser Documentation

Welcome to the Automated Document Parser documentation!

Automated Document Parser is a powerful and intelligent document processing library built on top of LangChain. It provides automatic file type detection and loading for various document formats, making it easy to build RAG (Retrieval-Augmented Generation) applications.

Features

  • Automatic File Type Detection - Intelligently detects and processes 10+ file formats

  • Multiple PDF Loaders - 10 different PDF loading methods for various use cases

  • Modular Architecture - Clean separation with file_load/ and pdf_load/ modules

  • Easy Integration - Simple API that works seamlessly with LangChain

  • Normalised Results - DocumentProcessor returns a stable result model with source metadata and page elements

  • Optional Dependencies - Install OCR, layout-aware PDF extraction, table extraction and AI integrations only when needed

  • Structured Data Support - Handle CSV, JSON, and other structured formats

  • End-to-End Ingestion - Orchestrate parsing, redaction, intelligence, chunking, embeddings and persistent indexing

  • Extensible Design - Custom loader, embedding, vector-store, tokenizer and reranker protocols

  • Privacy and Safety - Resource limits, local PII detection/redaction, API path validation and prompt-injection guidance

  • Operations - Durable jobs, structured logs, correlation IDs, metrics, backups, container deployment and optional monitoring

  • Evaluation - Retrieval, ingestion/queue and document-intelligence benchmark harnesses

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 is available through the json extra

Documents:
  • .docx - Microsoft Word documents

  • .html, .htm - HTML files (standard-library extraction)

PDF Files (10 methods):
  • pypdf - Basic PDF text extraction (default)

  • 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 extraction

  • pypdfium2 - Google PDFium library

  • pymupdf - PyMuPDF (fitz) backend

  • pymupdf4llm - LLM-optimized extraction

  • opendataloader - Advanced multi-format parsing

Quick Start

Installation

pip install automated-document-parser

Basic Usage

Step 1: Automatic File Type Detection

The parser automatically detects file types and loads them with sensible defaults:

from automated_document_parser import DocumentParser, DocumentProcessor

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

# Recommended API for new integrations
processor = DocumentProcessor()
result = processor.process("path/to/document.pdf")
print(result.content)
print(result.metadata)

# Parse a single document (auto-detects file type)
documents = parser.parse("path/to/document.pdf")

# Parse multiple documents (auto-detects each file type)
files = ["doc1.txt", "data.csv", "report.pdf"]
results = parser.parse_multiple(files)

Step 2: Specify Loading Methods

You can specify loading methods and parameters that apply to all appropriate files:

# Specify PDF loading method for all PDFs
files = ["doc1.txt", "data.csv", "report.pdf", "paper.pdf"]
results = parser.parse_multiple(
    files,
    pdf_loader_method="pdfplumber"  # Applies to all PDF files
)

# Specify encoding for text files
results = parser.parse_multiple(
    files,
    encoding="utf-8"  # Applies to all text files
)

# Combine multiple parameters
results = parser.parse_multiple(
    files,
    pdf_loader_method="pymupdf",
    encoding="utf-8"
)

Single File with Parameters

# Parse single PDF with specific method
documents = parser.parse(
    "document.pdf",
    pdf_loader_method="pdfplumber"
)

# Parse text file with encoding
documents = parser.parse(
    "file.txt",
    encoding="utf-8"
)

Layout-Aware PDF Extraction

Install the optional layout extra with pip install automated-document-parser[pdf-layout]. The layout backend emits semantic elements with zero-based page numbers, PDF-point bounding boxes, font hints and a column-aware top-to-bottom / left-to-right reading-order heuristic. Complex layouts can still require backend-specific tuning. Table cells are retained as structured table_rows metadata as well as Markdown text.

processor = DocumentProcessor()
result = processor.process(
    "annual-report.pdf",
    pdf_loader_method="pdfplumber-layout",
)
for element in result.elements:
    print(element.element_type, element.page_number, element.bbox)
    if element.element_type == "table":
        print(element.metadata["table_rows"])

The backend extracts embedded PDF text by default. Optional local OCR fallback can be enabled for pages with little native text, and image regions can be saved as PNG crops for downstream vision models or manual review. OCR requires the ocr extra plus the separately installed Tesseract system binary. PDFium handles local page rendering. Image-region extraction requires the pdf-images extra.

pip install "automated-document-parser[pdf-layout,ocr,pdf-images]"
from automated_document_parser import DocumentProcessor

processor = DocumentProcessor()
result = processor.process(
    "scanned-report.pdf",
    pdf_loader_method="pdfplumber-layout",
    ocr_fallback=True,
    ocr_min_characters=20,
    ocr_languages="eng",
    ocr_resolution=250,
    image_output_dir="artifacts/extracted-images",
)
for element in result.elements:
    print(element.element_type, element.confidence, element.metadata.get("asset_path"))

OCR confidence is normalized from Tesseract’s word-level confidence and is not a calibrated probability. Image outputs are rendered page-region crops, not original embedded image bytes.

Document Intelligence

The DocumentProcessor includes deterministic document classification, entity recognition and schema-guided extraction. Extracted values carry evidence with exact character offsets and, when the loader provides it, page number, element index and PDF-point bounding box.

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)

schema = {
    "title": "Invoice",
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string"},
        "vendor": {"type": "string"},
        "total": {"type": "number"},
    },
    "required": ["invoice_number", "total"],
}
extraction = processor.extract(document, schema)
print(extraction.values)
print(extraction.fields["total"].evidence)
print(extraction.missing_required)

The default classifier ranks document categories using transparent text and filename signals. Entity recognition targets common business-document fields, including email, URL, date, phone, currency, percentage, invoice and purchase-order identifiers, tax IDs, and explicitly labelled people, organizations and addresses.

The built-in schema extractor supports flat JSON-Schema-shaped objects with string, number, integer and boolean fields, required, enum and custom field aliases. It is not a full JSON Schema validator and does not guess arbitrary unlabelled values. Duplicate matches are marked ambiguous; missing required values and type mismatches remain explicit.

Custom model-backed extractors can be supplied through the SchemaExtractionBackend protocol using DocumentProcessor(schema_extractor=...). They must return the same StructuredExtraction model with evidence. No model runtime or provider credentials are required by the core package. Rule-based confidence values are heuristic signals, not calibrated probabilities.

Production Document Ingestion

DocumentIngestionPipeline connects the existing parsing, normalization, privacy, intelligence, chunking and retrieval components into one repeatable workflow. Embedding and vector storage adapters are injected; without an embedder the pipeline still supports local processing and lexical search.

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.ingestion_id, result.classification.label)
    print(result.stage_durations_ms)
    for hit in pipeline.search("invoice total", k=5):
        print(hit.chunk.source, hit.chunk.page_numbers, hit.chunk.content)

Batch ingestion is sequential and reports individual failures unless strict=True. SQLite and the in-memory store replace existing chunks for a source, preventing stale chunks after a document is updated. Custom vector-store adapters can implement the same optional replace_source(chunks, vectors, source=...) method; otherwise the pipeline uses the adapter’s add method. Redaction is opt-in; when enabled, downstream classification, extraction, embeddings and indexing receive only the redacted text. The pipeline records stage timings and a content fingerprint, but does not persist original document bytes or send content to a provider unless an injected provider is used.

Command-Line Interface

The package provides an adp executable and supports python -m automated_document_parser. Commands emit JSON to standard output, errors to standard error, and use non-zero exit codes for failures.

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

# Ingest files into a persistent SQLite index
adp ingest ./documents/*.pdf --database ./.adp/index.sqlite3 --redact-pii

# Search the index in a later process
adp search "invoice payment terms" --database ./.adp/index.sqlite3

The default hashing backend is local and dependency-free, but is a lexical feature-hashing baseline rather than a semantic embedding model. For semantic retrieval, install the openai extra and pass --embedding-backend openai-compatible with OPENAI_API_KEY or an OpenAI-compatible --embedding-base-url. Ingestion and search must use the same embedding backend, model and dimensions. SQLite is designed for local deployments and modest corpora; larger or distributed workloads should use a dedicated vector database adapter.

Ingestion continues after individual file failures and reports them in its JSON result. Use --strict to stop at the first error. PII redaction is opt-in and only changes extracted text; it does not sanitize the original source file.

HTTP API and Background Jobs

Install the optional server dependencies with pip install automated-document-parser[api]. The API runs a durable SQLite-backed queue and a single background ingestion worker.

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. When binding to a network interface, the CLI requires the ADP_API_KEY environment variable (or the name configured with --api-key-env). Requests must then include the X-API-Key header, except for the liveness and readiness probes. Deploy behind a TLS reverse proxy and keep the key in a secret manager.

Repository security automation

The repository uses Python CI, container build/smoke tests, CodeQL static analysis, a scheduled dependency audit with CycloneDX SBOM artifacts, and weekly Dependabot updates for Python dependencies and GitHub Actions. Release workflows validate version/tag consistency and publish through PyPI trusted publishing. Workflow permissions are read-only by default and elevated only for the deployment/release jobs that need them. These automated checks are complementary and do not replace review or runtime security controls. See SECURITY.md for the repository security process and limitations.

Logging and correlation IDs

The CLI emits structured JSON logs by default. Use --log-format human for readable local console output and --log-level to set verbosity. JSON records include a UTC timestamp, severity, logger, event and safe contextual fields. API request IDs are returned in X-Request-ID and attached to request logs; worker lifecycle logs use the durable job ID as their correlation ID. Secret-like fields and document/request-body content fields are redacted by the formatters. Applications can use correlation_context to bind a correlation ID to logs emitted in the current execution context.

Security controls

The API applies a bounded in-memory sliding-window limit of 120 requests per client address per 60 seconds by default. Configure it with --rate-limit-requests, --rate-limit-window-seconds and --rate-limit-max-clients (the in-memory client-state cap). Liveness and readiness probes are exempt so orchestrators can continue checking service health. A 429 response includes Retry-After. This limiter is process-local and is not a substitute for a distributed gateway/WAF limit. It uses the connecting peer address and deliberately does not trust client-supplied X-Forwarded-For headers.

When ADP_API_KEY is configured, API requests require X-API-Key or Authorization: Bearer credentials; comparison is constant-time. Failed authentication and rate-limit decisions emit structured security audit events without logging credential values or document content. Responses include X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer and Cache-Control: no-store. Request IDs are returned in X-Request-ID. Request bodies are capped at 16 KiB by default, including chunked requests; the create_app API allows trusted embedders to choose a different cap. Use TLS at a trusted reverse proxy for remote access, restrict network access, and keep the API key in a secret store.

Example with a lower request budget:

adp serve --allowed-root ./documents \
  --rate-limit-requests 60 --rate-limit-window-seconds 60

Retry and recovery policy

The worker retries transient I/O, timeout, connection and SQLite operational errors using capped exponential backoff with configurable jitter. Missing or forbidden files and invalid inputs are permanent failures and are not retried. The durable failed state is the dead-letter state: it remains inspectable and can be manually requeued with POST /v1/jobs/{job_id}/retry. Worker startup recovers interrupted running jobs, retrying only when attempts remain.

Use --max-job-attempts, --retry-base-delay, --retry-max-delay and --retry-jitter-fraction to tune the worker policy. The optional Idempotency-Key request header is persisted in SQLite; repeated submissions with the same key and source return the original job, while reusing a key for a different source returns HTTP 409.

The API exposes these endpoints:

  • GET /healthz - process liveness probe

  • POST /v1/jobs - submit a server-local file path for ingestion (HTTP 202); optional Idempotency-Key deduplicates client retries

  • GET /v1/jobs/{job_id} - retrieve state and result for one job

  • GET /v1/jobs?status=queued - list recent jobs by optional state

  • DELETE /v1/jobs/{job_id} - cancel a queued job

  • POST /v1/jobs/{job_id}/retry - manually retry a failed job

  • POST /v1/worker/pause and /resume - pause or resume new work claims

  • GET /v1/search?q=invoice&limit=5 - search indexed chunks

Jobs transition through queued, running, succeeded, failed and cancelled. Queued jobs can be cancelled, failed jobs can be retried manually, and the worker can be paused without interrupting its active document. The queue survives process restarts and recovers interrupted running jobs. Transient failures retry up to three attempts with capped jittered exponential backoff by default; permanent failures are recorded immediately in the failed dead-letter state. The worker processes one job at a time. Run one worker process per jobs database; SQLite is a local persistence option, not a distributed queue.

For security, submitted paths are resolved and restricted to the configured --allowed-root directories. The worker repeats path and size validation immediately before processing to reduce symlink/file replacement races. The API accepts paths on the server rather than arbitrary file uploads, verifies regular files and enforces a default 100 MiB size limit (configurable with --max-file-size-mb). Configure OS filesystem permissions and network controls as additional isolation.

Document Transformation and Privacy

The transformation API offers structure-aware chunking, conservative text normalization, duplicate detection and local PII redaction. Each operation returns a new result and does not mutate the input ParsedDocument.

from automated_document_parser import DocumentProcessor

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

chunks = processor.chunk(document, max_chars=1200, overlap=120)
normalized = processor.normalize(document)
duplicates = processor.find_duplicates(normalized, threshold=0.92)
findings = processor.detect_pii(normalized)
redacted = processor.redact(
    normalized, categories=["email", "phone", "us_ssn", "credit_card"]
)
print(redacted.redacted_document.content)
print(redacted.redactions)

Chunking prefers element boundaries and splits oversized elements at paragraph, line, sentence or word boundaries. Chunks preserve source offsets, element indexes, page numbers and element types. Offsets refer to the input document’s content.

Normalization supports Unicode normalization, whitespace cleanup, soft-hyphen removal and line-wrap dehyphenation. Since normalization may change character offsets, run it before chunking and evidence extraction when normalized text is the intended source.

Duplicate detection uses standard-library sequence matching. Its pairwise comparison is quadratic in the number of eligible elements, so it is intended for individual documents and modest element counts rather than corpus-scale similarity search.

PII detection is local and rule-based. Supported categories include 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.

Redaction returns a separate document and an audit trail containing categories and source offsets, not the original sensitive values. Arbitrary loader metadata is not copied into the redacted output because metadata may contain OCR text or PII. The source and structural page/layout information are retained; the original input is unchanged. Production workflows should separately control access to original and redacted files and validate the rendered output as well as extracted text. This is text-level redaction only: it does not modify or sanitize the original PDF, embedded images, attachments or other source artifacts. Do not distribute the original file as if it had been securely redacted. A publication workflow must physically remove sensitive content from the source artifact and its metadata, then inspect the rendered result.

Advanced PDF Loading

The local pymupdf and pypdfium2 backends use their native libraries and return langchain_core documents directly; neither requires langchain-community. Install them independently with the pymupdf or pdfium extra. The community extra remains optional for specialized integrations that still use community loaders, such as Textract and Mathpix.

For more control, use PDFLoader directly:

from automated_document_parser.loaders import PDFLoader

# Use specific PDF loading method
loader = PDFLoader("document.pdf", method="pdfplumber")
documents = loader.load()

# Use Mathpix for mathematical content
loader = PDFLoader(
    "math_paper.pdf",
    method="mathpix",
    mathpix_app_id="your_id",
    mathpix_app_key="your_key"
)
documents = loader.load()

Direct Loader Usage

from automated_document_parser.loaders.file_load import (
    TextFileLoader,
    CSVFileLoader,
    JSONFileLoader
)

# Load text file with specific encoding
loader = TextFileLoader("file.txt", encoding="utf-8")
docs = loader.load()

# Load CSV file
csv_loader = CSVFileLoader("data.csv")
csv_docs = csv_loader.load()

Feature guide

The Feature Guide provides a complete map of public entry points, supported PDF backends, intelligence and transformation features, retrieval adapters, CLI/API operations, monitoring and security boundaries. Run the offline example with python examples/full_workflow.py or follow notebook_examples/rag_example.ipynb for a guided Jupyter walkthrough.

Contents

Indices and tables

Performance benchmarks

See Retrieval Evaluation and Benchmarks for reproducible retrieval, ingestion and queue benchmarks.

Documentation analytics and privacy

The static documentation site can optionally use GA4. Tracking is disabled in local/PR builds unless a measurement ID is explicitly configured, and the site asks visitors for consent before loading the Google tag. The parser runtime does not use Google Analytics. See the repository docs/README.md for configuration and privacy details.