API Reference

This page contains the complete API reference for the Automated Document Parser package.

Python HTTP Client

The synchronous ADPClient uses only the Python standard library and can be used without installing the optional FastAPI server dependencies. It supports job submission/status/list/cancel/retry and retrieval search. The client sends server-side paths; it does not upload document bytes.

class automated_document_parser.client.ADPClient(base_url: str = 'http://127.0.0.1:8000', *, api_key: str | None = None, timeout: float = 10.0)[source]

Synchronous API client with no third-party runtime dependencies.

Parameters:
  • base_url – API origin, for example http://127.0.0.1:8000.

  • api_key – Optional API key. When supplied it is sent in X-API-Key.

  • timeout – Per-request timeout in seconds.

The client does not upload document bytes. submit_job sends a path that must exist on the API server and be within its configured allowed roots.

__init__(base_url: str = 'http://127.0.0.1:8000', *, api_key: str | None = None, timeout: float = 10.0) → None[source]
submit_job(source: str | Path, *, idempotency_key: str | None = None) → dict[str, Any][source]

Submit a server-local document path for background ingestion.

get_job(job_id: str) → dict[str, Any][source]

Retrieve one job by its opaque job ID.

list_jobs(*, limit: int = 50, status: str | None = None) → dict[str, Any][source]

List recent jobs with optional status filtering.

cancel_job(job_id: str) → dict[str, Any][source]

Cancel a job that is still queued.

retry_job(job_id: str) → dict[str, Any][source]

Manually requeue a terminal failed job.

search(query: str, *, limit: int = 5) → dict[str, Any][source]

Search indexed chunks using the API’s configured embedding backend.

class automated_document_parser.client.ADPClientError(status_code: int, detail: str)[source]

An HTTP/API response error raised by ADPClient.

__init__(status_code: int, detail: str)[source]

Production Ingestion Pipeline

class automated_document_parser.ingestion.DocumentIngestionPipeline(processor: DocumentProcessor | None = None, *, config: IngestionConfig | None = None, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None)[source]

Bases: object

Connect parsing, privacy, intelligence, chunking and vector indexing.

The pipeline is deliberately provider-neutral. Supply an embedding backend and, optionally, a vector-store adapter. Without an embedder, ingestion remains fully usable and search() performs lexical BM25 retrieval.

__init__(processor: DocumentProcessor | None = None, *, config: IngestionConfig | None = None, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None) → None[source]
ingest(source: str | Path, *, schema: Mapping[str, Any] | None = None, pdf_loader_method: str | None = None, encoding: str | None = None, **loader_options: Any) → IngestionResult[source]

Run the complete ingestion flow for one local document.

Loader-specific options are forwarded to DocumentProcessor.process. Exceptions are propagated so callers can apply their own retry policy.

ingest_many(sources: Iterable[str | Path], *, strict: bool = False, schema: Mapping[str, Any] | None = None, pdf_loader_method: str | None = None, encoding: str | None = None, **loader_options: Any) → BatchIngestionResult[source]

Ingest sources sequentially, optionally collecting per-file failures.

create_retriever() → HybridRetriever[source]

Build or reuse a hybrid retriever over the indexed corpus.

search(query: str, *, k: int = 5, candidate_k: int | None = None) → tuple[RetrievalResult, ...][source]

Search ingested documents using BM25 and optional vector similarity.

class automated_document_parser.ingestion.IngestionConfig(pdf_loader_method: str = 'pypdf', encoding: str = 'utf-8', normalize: bool = True, redact_pii: bool = False, pii_categories: tuple[str, ...] | None = None, classify: bool = True, extract_entities: bool = True, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True)[source]

Default processing policy for an ingestion pipeline.

Redaction is opt-in. When enabled, the pipeline only classifies, extracts, chunks, embeds and indexes the redacted representation.

pdf_loader_method: str
encoding: str
normalize: bool
redact_pii: bool
pii_categories: tuple[str, ...] | None
classify: bool
extract_entities: bool
max_chars: int
overlap: int | None
respect_element_boundaries: bool
__init__(pdf_loader_method: str = 'pypdf', encoding: str = 'utf-8', normalize: bool = True, redact_pii: bool = False, pii_categories: tuple[str, ...] | None = None, classify: bool = True, extract_entities: bool = True, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True) → None
class automated_document_parser.ingestion.IngestionResult(ingestion_id: str, source: str, content_sha256: str, document: ~automated_document_parser.models.ParsedDocument, chunks: tuple[~automated_document_parser.transformation.models.DocumentChunk, ...], classification: ~automated_document_parser.intelligence.models.DocumentClassification | None = None, entities: tuple[~automated_document_parser.intelligence.models.ExtractedEntity, ...] = (), extraction: ~automated_document_parser.intelligence.models.StructuredExtraction | None = None, redaction: ~automated_document_parser.transformation.models.RedactionResult | None = None, embedded_chunks: int = 0, stored_chunks: int = 0, stage_durations_ms: ~collections.abc.Mapping[str, float] = <factory>)[source]

Auditable outcome of processing and optionally indexing one source.

ingestion_id: str
source: str
content_sha256: str
document: ParsedDocument
chunks: tuple[DocumentChunk, ...]
classification: DocumentClassification | None
entities: tuple[ExtractedEntity, ...]
extraction: StructuredExtraction | None
redaction: RedactionResult | None
embedded_chunks: int
stored_chunks: int
stage_durations_ms: Mapping[str, float]
__init__(ingestion_id: str, source: str, content_sha256: str, document: ~automated_document_parser.models.ParsedDocument, chunks: tuple[~automated_document_parser.transformation.models.DocumentChunk, ...], classification: ~automated_document_parser.intelligence.models.DocumentClassification | None = None, entities: tuple[~automated_document_parser.intelligence.models.ExtractedEntity, ...] = (), extraction: ~automated_document_parser.intelligence.models.StructuredExtraction | None = None, redaction: ~automated_document_parser.transformation.models.RedactionResult | None = None, embedded_chunks: int = 0, stored_chunks: int = 0, stage_durations_ms: ~collections.abc.Mapping[str, float] = <factory>) → None
class automated_document_parser.ingestion.BatchIngestionResult(results: tuple[IngestionResult, ...], failures: tuple[IngestionFailure, ...])[source]

Successful results and failures from a sequential batch.

results: tuple[IngestionResult, ...]
failures: tuple[IngestionFailure, ...]
property succeeded: int
property failed: int
__init__(results: tuple[IngestionResult, ...], failures: tuple[IngestionFailure, ...]) → None
class automated_document_parser.ingestion.IngestionFailure(source: str, error_type: str, message: str)[source]

A per-source failure captured by non-strict batch ingestion.

source: str
error_type: str
message: str
__init__(source: str, error_type: str, message: str) → None

Command-Line Interface

Command-line interface for document parsing and ingestion.

automated_document_parser.cli.build_parser() → ArgumentParser[source]

Build the argument parser (exposed for help and contract tests).

automated_document_parser.cli.main(argv: Sequence[str] | None = None) → int[source]

Run the CLI and return a process exit code.

Backup and Restore

Consistent, local-first backup and restore for ADP SQLite state.

automated_document_parser.backup.create_backup(*, index_database: str | Path, jobs_database: str | Path, destination: str | Path, retention_count: int = 7) → dict[str, Any][source]

Create an atomic backup directory for all existing ADP SQLite stores.

Each database is captured using SQLite’s online backup API. The two databases are individually consistent, but are not a cross-database transaction snapshot. Missing, not-yet-created databases are omitted.

automated_document_parser.backup.restore_backup(*, backup: str | Path, target: str | Path) → dict[str, Any][source]

Verify a backup and atomically restore it into a new directory.

The target must not already exist. Restored filenames are index.sqlite3 and jobs.sqlite3 so operators can explicitly map them to configured application database paths.

Structured Logging

Structured logging helpers for applications using Automated Document Parser.

class automated_document_parser.logging_config.CorrelationIdFilter(name='')[source]

Attach the current request/job correlation ID to each log record.

filter(record: LogRecord) → bool[source]

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class automated_document_parser.logging_config.JsonLogFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]

Render one JSON object per log record with safe structured context.

format(record: LogRecord) → str[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

class automated_document_parser.logging_config.HumanLogFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]

Readable console formatter that preserves safe event context.

format(record: LogRecord) → str[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.

automated_document_parser.logging_config.configure_logging(level: str | int = 'INFO', *, stream: IO[str] | None = None, log_format: str = 'json') → None[source]

Configure package logs as JSON or human-readable output.

The library never configures the root logger. Applications opt in at their process boundary (for example, the CLI or service entry point). Repeated calls update the existing package handler rather than adding duplicates.

automated_document_parser.logging_config.correlation_context(value: str) → Iterator[None][source]

Temporarily bind a correlation ID to logs in the current context.

automated_document_parser.logging_config.get_correlation_id() → str | None[source]

Return the current request/job correlation ID, if one is bound.

HTTP API and Durable Jobs

The service exposes /healthz for liveness, /readyz for dependency and worker readiness, and an authenticated (when API-key authentication is enabled) Prometheus text endpoint at /metrics. Metrics include request totals and latency histograms, job enqueue totals and durable queue-state gauges. The metrics registry is application-scoped, and route-template labels are used to avoid high-cardinality job-ID labels.

Prometheus metrics for the optional HTTP service.

class automated_document_parser.observability.ApiMetrics[source]

Application-scoped Prometheus metrics with bounded label cardinality.

__init__() → None[source]
observe_request(method: str, route: str, status_code: int, duration_seconds: float) → None[source]

Record a completed request using its route template, not raw URL.

observe_job_enqueued() → None[source]

Record a job accepted by the HTTP API.

update_runtime(job_counts: dict[str, int], worker: dict[str, Any]) → None[source]

Refresh gauges from durable state rather than process-local counters.

Optional FastAPI application for durable document ingestion and search.

automated_document_parser.api.create_app(*, pipeline: DocumentIngestionPipeline, job_store: SQLiteJobStore, allowed_roots: Sequence[str | Path], api_key: str | None = None, worker: IngestionWorker | None = None, start_worker: bool = True, max_file_size_bytes: int = 104857600, max_request_body_bytes: int = 16384, rate_limit_requests: int = 120, rate_limit_window_seconds: float = 60.0, rate_limit_max_clients: int = 10000, max_job_attempts: int = 3, retry_base_delay: float = 1.0, retry_max_delay: float = 30.0, retry_jitter_fraction: float = 0.2)[source]

Create an API app around injected pipeline and durable job storage.

POST /v1/jobs accepts paths on the server, not uploaded bytes. Every requested path is resolved and constrained to allowed_roots before it enters the queue. Configure api_key when exposing the service beyond a trusted local network; all application endpoints except /healthz and /readyz then require the X-API-Key header. A bounded in-memory sliding-window limiter applies per connecting client address (120 requests per 60 seconds by default), excluding liveness/readiness probes. It is process-local and must not be treated as a distributed edge/WAF rate limit. Forwarded-IP headers are not trusted; configure a trusted proxy and its network controls separately.

The caller owns the lifetime of the injected pipeline, vector store and job store. The app starts and stops only the worker it is given or creates.

Durable SQLite-backed ingestion jobs and a single-process worker.

class automated_document_parser.jobs.IngestionJob(id: str, source: str, status: str, created_at: str, updated_at: str, attempts: int, started_at: str | None = None, completed_at: str | None = None, available_at: str | None = None, error_type: str | None = None, error_message: str | None = None, result: dict[str, Any] | None = None, idempotency_key: str | None = None)[source]

Public, serialisable state for one queued document ingestion.

id: str
source: str
status: str
created_at: str
updated_at: str
attempts: int
started_at: str | None
completed_at: str | None
available_at: str | None
error_type: str | None
error_message: str | None
result: dict[str, Any] | None
idempotency_key: str | None
to_dict() → dict[str, Any][source]

Return a JSON-compatible public representation.

__init__(id: str, source: str, status: str, created_at: str, updated_at: str, attempts: int, started_at: str | None = None, completed_at: str | None = None, available_at: str | None = None, error_type: str | None = None, error_message: str | None = None, result: dict[str, Any] | None = None, idempotency_key: str | None = None) → None
class automated_document_parser.jobs.SQLiteJobStore(database: str | Path, *, timeout: float = 5.0)[source]

Transactional persistent queue for ingestion jobs.

The store is safe to share between threads and uses BEGIN IMMEDIATE when claiming work so multiple worker processes cannot claim the same job. A deployment should still run one worker per queue database unless it has an explicit multi-process capacity plan.

__init__(database: str | Path, *, timeout: float = 5.0) → None[source]
enqueue(source: str | Path, *, idempotency_key: str | None = None) → IngestionJob[source]

Persist a new job or return the existing job for an idempotency key.

enqueue_with_status(source: str | Path, *, idempotency_key: str | None = None) → tuple[IngestionJob, bool][source]

Enqueue atomically and report whether a new job was created.

get_by_idempotency_key(idempotency_key: str) → IngestionJob | None[source]

Return the durable job associated with an idempotency key.

get(job_id: str) → IngestionJob | None[source]

Return a job by ID, or None when it does not exist.

list_jobs(*, limit: int = 50, status: str | None = None) → tuple[IngestionJob, ...][source]

List recent jobs, optionally filtered by lifecycle status.

counts() → dict[str, int][source]

Return counts by lifecycle state for health and operations.

recover_interrupted(*, max_attempts: int = 3) → int[source]

Requeue interrupted jobs with attempts remaining; fail exhausted jobs.

claim_next() → IngestionJob | None[source]

Atomically claim the oldest available queued job.

complete(job_id: str, result: dict[str, Any]) → IngestionJob[source]

Mark a running job successful and persist its compact result.

fail(job_id: str, *, error_type: str, error_message: str, max_attempts: int, retry_delay: float) → IngestionJob[source]

Record failure and schedule a bounded retry when attempts remain.

cancel(job_id: str) → IngestionJob[source]

Cancel a queued job; running and terminal jobs cannot be cancelled.

retry(job_id: str) → IngestionJob[source]

Manually requeue a terminal failed job and reset its attempt count.

health_check() → bool[source]

Run a lightweight database round-trip without scanning job history.

close() → None[source]

Close the underlying SQLite connection.

class automated_document_parser.jobs.IngestionWorker(job_store: ~automated_document_parser.jobs.SQLiteJobStore, pipeline: ~automated_document_parser.ingestion.DocumentIngestionPipeline, *, poll_interval: float = 0.5, max_attempts: int = 3, retry_base_delay: float = 1.0, retry_max_delay: float = 30.0, retry_jitter_fraction: float = 0.2, retryable_exceptions: tuple[type[Exception], ...] = (<class 'TimeoutError'>, <class 'ConnectionError'>, <class 'OSError'>, <class 'sqlite3.OperationalError'>), random_uniform: ~collections.abc.Callable[[float, float], float] | None = None, source_validator: ~collections.abc.Callable[[str], str | ~pathlib.Path] | None = None)[source]

Single-threaded background worker with durable retries and recovery.

__init__(job_store: ~automated_document_parser.jobs.SQLiteJobStore, pipeline: ~automated_document_parser.ingestion.DocumentIngestionPipeline, *, poll_interval: float = 0.5, max_attempts: int = 3, retry_base_delay: float = 1.0, retry_max_delay: float = 30.0, retry_jitter_fraction: float = 0.2, retryable_exceptions: tuple[type[Exception], ...] = (<class 'TimeoutError'>, <class 'ConnectionError'>, <class 'OSError'>, <class 'sqlite3.OperationalError'>), random_uniform: ~collections.abc.Callable[[float, float], float] | None = None, source_validator: ~collections.abc.Callable[[str], str | ~pathlib.Path] | None = None) → None[source]
property is_running: bool

Whether the worker thread is currently alive.

health() → dict[str, Any][source]

Return a small operational snapshot.

start() → None[source]

Recover interrupted jobs and start the worker thread once.

stop(*, timeout: float | None = 30.0) → bool[source]

Request a graceful stop; None waits for the active job to finish.

pause() → None[source]

Pause new claims while allowing an active job to finish.

resume() → None[source]

Resume claiming queued work.

Core Module

class automated_document_parser.processor.DocumentProcessor(parser: DocumentParser | None = None, *, intelligence: DocumentIntelligence | None = None, schema_extractor: SchemaExtractionBackend | None = None)[source]

Bases: object

Process files into the package’s normalised document representation.

DocumentParser remains the compatibility API returning LangChain documents. DocumentProcessor is the recommended entry point for new integrations that need one stable result object with source provenance.

__init__(parser: DocumentParser | None = None, *, intelligence: DocumentIntelligence | None = None, schema_extractor: SchemaExtractionBackend | None = None) → None[source]
process(file_path: str | Path, *, pdf_loader_method: str = 'pypdf', encoding: str = 'utf-8', **loader_options: Any) → ParsedDocument[source]

Parse one file and return its normalised representation.

classify(document: ParsedDocument, *, top_k: int = 3) → DocumentClassification[source]

Classify an already parsed document using transparent local rules.

extract_entities(document: ParsedDocument) → tuple[ExtractedEntity, ...][source]

Extract common entities with page and text-span evidence.

extract(document: ParsedDocument, schema: Mapping[str, Any]) → StructuredExtraction[source]

Extract a JSON-Schema-shaped payload with field-level evidence.

chunk(document: ParsedDocument, *, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True) → tuple[DocumentChunk, ...][source]

Create structure-aware chunks with source offsets and page metadata.

normalize(document: ParsedDocument, **options: Any) → ParsedDocument[source]

Return a normalized copy while preserving the original document.

find_duplicates(document: ParsedDocument, *, threshold: float = 0.92, min_chars: int = 20) → DuplicateReport[source]

Find exact and near-duplicate document elements.

detect_pii(document: ParsedDocument, *, categories: Iterable[str] | None = None) → tuple[PIIMatch, ...][source]

Detect supported PII categories without changing the document.

redact(document: ParsedDocument, *, categories: Iterable[str] | None = None, replacement: str = '[REDACTED]') → RedactionResult[source]

Return a redacted copy and an audit trail without sensitive values.

chunk_by_tokens(document: ParsedDocument, *, tokenizer: Tokenizer | Callable[[str], int], max_tokens: int = 512, overlap_tokens: int = 50) → tuple[DocumentChunk, ...][source]

Chunk a document to a tokenizer-defined budget.

create_retriever(chunks: Iterable[DocumentChunk], *, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None, reranker: Reranker | None = None, rrf_k: int = 60, index_embeddings: bool = True) → HybridRetriever[source]

Build a hybrid retriever from chunks and optional provider adapters.

Set index_embeddings=False when the vector store already contains embeddings for these chunks. Query embeddings are still generated.

search(retriever: HybridRetriever, query: str, *, k: int = 5, candidate_k: int | None = None) → tuple[RetrievalResult, ...][source]

Search a previously configured retriever.

class automated_document_parser.models.ParsedDocument(source: str, content: str, metadata: dict[str, ~typing.Any]=<factory>, elements: tuple[~automated_document_parser.models.DocumentElement, ...]=())[source]

Bases: object

Normalised representation of a source document.

The model keeps the original source, combined text, backend metadata and per-document elements together. Layout-aware backends can populate element types, page coordinates, reading order and confidence without changing the compatibility API.

source: str
content: str
metadata: dict[str, Any]
elements: tuple[DocumentElement, ...]
classmethod from_documents(documents: Iterable[Document], source: str | Path) → ParsedDocument[source]

Create a normalised document from LangChain documents.

to_dict() → dict[str, Any][source]

Return a JSON-compatible structure when metadata values are serialisable.

to_json(*, indent: int | None = 2) → str[source]

Serialise the document to JSON.

Raises:

TypeError – If a loader has attached non-JSON-serialisable metadata.

to_langchain_documents() → list[Document][source]

Convert elements back to LangChain Document instances.

__init__(source: str, content: str, metadata: dict[str, ~typing.Any]=<factory>, elements: tuple[~automated_document_parser.models.DocumentElement, ...]=()) → None
class automated_document_parser.models.DocumentElement(text: str, element_type: str = 'text', page_number: int | None = None, bbox: tuple[float, float, float, float] | None=None, reading_order: int | None = None, confidence: float | None = None, metadata: dict[str, ~typing.Any]=<factory>)[source]

Bases: object

A source-preserving unit of extracted document content.

text: str
element_type: str
page_number: int | None
bbox: tuple[float, float, float, float] | None
reading_order: int | None
confidence: float | None
metadata: dict[str, Any]
__init__(text: str, element_type: str = 'text', page_number: int | None = None, bbox: tuple[float, float, float, float] | None=None, reading_order: int | None = None, confidence: float | None = None, metadata: dict[str, ~typing.Any]=<factory>) → None

Main DocumentParser class for automated document loading.

class automated_document_parser.core.DocumentParser[source]

Bases: object

Main class for automated document parsing.

Automatically detects file type and loads documents using appropriate loaders. Designed for seamless integration with LangChain RAG pipelines.

__init__()[source]

Initialize the DocumentParser.

parse(file_path: str | Path, pdf_loader_method: str = 'pypdf', encoding: str = 'utf-8', **kwargs) → list[Document][source]

Parse a document from file path.

Parameters:
  • file_path – Path to the document file

  • pdf_loader_method – Method to use for PDF files (default: ‘pypdf’). Options: ‘pypdf’, ‘unstructured’, ‘amazon_textract’, ‘mathpix’, ‘pdfplumber’, ‘pdfplumber-layout’, ‘pypdfium2’, ‘pymupdf’, ‘pymupdf4llm’, ‘opendataloader’

  • encoding – Encoding for text, CSV, HTML and JSON files (default: “utf-8”).

  • jq_schema – Optional jq expression for selecting JSON values. Custom expressions require the json extra; the default . does not.

  • text_content – Treat selected JSON strings as document text rather than serialising them as JSON.

  • resource_limits – Optional FileResourceLimits preflight caps. The default limits apply unless None is supplied explicitly.

  • **kwargs – Additional backend-specific keyword arguments for PDF loading.

Returns:

List of LangChain Document objects

Raises:

Example

>>> parser = DocumentParser()
>>> # Basic usage with auto-detection
>>> docs = parser.parse("document.pdf")
>>> # Specify PDF loading method
>>> docs = parser.parse("document.pdf", pdf_loader_method="pdfplumber")
>>> # Pass additional parameters
>>> docs = parser.parse("math.pdf", pdf_loader_method="mathpix",
...                     mathpix_app_id="id", mathpix_app_key="key")
parse_multiple(file_paths: list[str | Path], pdf_loader_method: str = 'pypdf', encoding: str = 'utf-8', strict: bool = False, **kwargs) → dict[str, list[Document]][source]

Parse multiple documents with automatic file type detection.

Parameters:
  • file_paths – List of file paths

  • pdf_loader_method – Method to use for PDF files (default: ‘pypdf’). Options: ‘pypdf’, ‘unstructured’, ‘amazon_textract’, ‘mathpix’, ‘pdfplumber’, ‘pdfplumber-layout’, ‘pypdfium2’, ‘pymupdf’, ‘pymupdf4llm’, ‘opendataloader’

  • encoding – Encoding for text, CSV, HTML and JSON files (default: “utf-8”).

  • strict – Re-raise the first error instead of recording an empty result.

  • jq_schema – Optional jq expression for selecting JSON values.

  • text_content – Treat selected JSON strings as document text.

  • **kwargs – Additional backend-specific keyword arguments for PDF loading.

Returns:

Dictionary mapping file paths to their loaded documents

Example

>>> parser = DocumentParser()
>>> # Auto-detect all file types with default settings
>>> results = parser.parse_multiple(["doc1.pdf", "doc2.txt", "data.csv"])
>>> # Specify PDF method for all PDFs
>>> results = parser.parse_multiple(
...     ["doc1.pdf", "doc2.pdf", "data.csv"],
...     pdf_loader_method="pdfplumber"
... )
>>> for file, docs in results.items():
...     print(f"{file}: {len(docs)} documents")
get_loaded_files() → list[str][source]

Get list of successfully loaded files.

Returns:

List of file paths that were successfully loaded

Document Intelligence

class automated_document_parser.intelligence.DocumentIntelligence(schema_extractor: SchemaExtractionBackend | None = None)[source]

Bases: object

Classify documents and extract entities or schema-shaped data.

The default backend is deterministic and dependency-free. A custom backend can implement SchemaExtractionBackend to integrate an LLM or domain model while preserving the same evidence-aware result contract.

__init__(schema_extractor: SchemaExtractionBackend | None = None) → None[source]
classify(document: ParsedDocument, *, top_k: int = 3) → DocumentClassification[source]

Return ranked document type hypotheses.

extract_entities(document: ParsedDocument) → tuple[ExtractedEntity, ...][source]

Extract common entities with exact source evidence.

extract(document: ParsedDocument, schema: Mapping[str, Any]) → StructuredExtraction[source]

Extract schema fields and retain evidence for every populated value.

class automated_document_parser.intelligence.RuleBasedSchemaExtractor[source]

Bases: object

Extract fields from explicit labels and recognized entities, without an LLM.

extract(document: ParsedDocument, schema: Mapping[str, Any]) → StructuredExtraction[source]
class automated_document_parser.intelligence.Evidence(quote: str, source: str, element_index: int | None = None, page_number: int | None = None, bbox: tuple[float, float, float, float] | None = None, start_offset: int | None = None, end_offset: int | None = None)[source]

A traceable source span supporting an extracted value.

quote: str
source: str
element_index: int | None
page_number: int | None
bbox: tuple[float, float, float, float] | None
start_offset: int | None
end_offset: int | None
__init__(quote: str, source: str, element_index: int | None = None, page_number: int | None = None, bbox: tuple[float, float, float, float] | None = None, start_offset: int | None = None, end_offset: int | None = None) → None
class automated_document_parser.intelligence.ExtractedEntity(entity_type: str, value: str, normalized_value: str, confidence: float, evidence: Evidence)[source]

A detected entity with a normalized value and source evidence.

entity_type: str
value: str
normalized_value: str
confidence: float
evidence: Evidence
__init__(entity_type: str, value: str, normalized_value: str, confidence: float, evidence: Evidence) → None
class automated_document_parser.intelligence.DocumentClassification(label: str, confidence: float, candidates: tuple[ClassificationCandidate, ...] = (), method: str = 'rules')[source]

Ranked document type predictions.

label: str
confidence: float
candidates: tuple[ClassificationCandidate, ...]
method: str
__init__(label: str, confidence: float, candidates: tuple[ClassificationCandidate, ...] = (), method: str = 'rules') → None
class automated_document_parser.intelligence.StructuredExtraction(values: dict[str, Any], fields: dict[str, FieldExtraction], schema_name: str | None = None, missing_required: tuple[str, ...] = (), method: str = 'rules')[source]

Schema-shaped values and field-level evidence.

values: dict[str, Any]
fields: dict[str, FieldExtraction]
schema_name: str | None
missing_required: tuple[str, ...]
method: str
to_dict() → dict[str, Any][source]

Return values and evidence in a JSON-compatible structure.

to_json(*, indent: int | None = 2) → str[source]

Serialize the structured extraction and provenance.

__init__(values: dict[str, Any], fields: dict[str, FieldExtraction], schema_name: str | None = None, missing_required: tuple[str, ...] = (), method: str = 'rules') → None
class automated_document_parser.intelligence.FieldExtraction(value: Any = None, confidence: float = 0.0, status: str = 'missing', evidence: tuple[Evidence, ...] = ())[source]

A schema field result, including its evidence and extraction status.

value: Any
confidence: float
status: str
evidence: tuple[Evidence, ...]
__init__(value: Any = None, confidence: float = 0.0, status: str = 'missing', evidence: tuple[Evidence, ...] = ()) → None
class automated_document_parser.intelligence.SchemaExtractionBackend(*args, **kwargs)[source]

Interface for deterministic or model-backed schema extraction engines.

extract(document: ParsedDocument, schema: Mapping[str, Any]) → StructuredExtraction[source]

Extract values and source evidence for the supplied JSON schema.

__init__(*args, **kwargs)

Deterministic document type classification.

automated_document_parser.intelligence.classification.classify_document(document: ParsedDocument, *, top_k: int = 3) → DocumentClassification[source]

Rank likely document types using transparent keyword and filename rules.

Evidence-linked, deterministic entity recognition for common business documents.

automated_document_parser.intelligence.entities.extract_entities(document: ParsedDocument) → tuple[ExtractedEntity, ...][source]

Find common entities and attach exact source spans and element provenance.

Schema-guided field extraction with evidence and pluggable backends.

class automated_document_parser.intelligence.extraction.SchemaExtractionBackend(*args, **kwargs)[source]

Interface for deterministic or model-backed schema extraction engines.

extract(document: ParsedDocument, schema: Mapping[str, Any]) → StructuredExtraction[source]

Extract values and source evidence for the supplied JSON schema.

__init__(*args, **kwargs)
class automated_document_parser.intelligence.extraction.RuleBasedSchemaExtractor[source]

Extract fields from explicit labels and recognized entities, without an LLM.

extract(document: ParsedDocument, schema: Mapping[str, Any]) → StructuredExtraction[source]

Document Transformation and Privacy

Document chunking, normalization, deduplication and privacy tools.

class automated_document_parser.transformation.DocumentChunk(content: str, chunk_index: int, source: str, start_offset: int, end_offset: int, page_numbers: tuple[int, ...]=(), element_indices: tuple[int, ...]=(), element_types: tuple[str, ...]=(), metadata: dict[str, ~typing.Any]=<factory>)[source]

A chunk with source offsets and structural provenance.

content: str
chunk_index: int
source: str
start_offset: int
end_offset: int
page_numbers: tuple[int, ...]
element_indices: tuple[int, ...]
element_types: tuple[str, ...]
metadata: dict[str, Any]
__init__(content: str, chunk_index: int, source: str, start_offset: int, end_offset: int, page_numbers: tuple[int, ...]=(), element_indices: tuple[int, ...]=(), element_types: tuple[str, ...]=(), metadata: dict[str, ~typing.Any]=<factory>) → None
class automated_document_parser.transformation.DuplicateGroup(representative_index: int, duplicate_indices: tuple[int, ...], similarity: float, exact: bool)[source]

A set of repeated or near-repeated elements.

representative_index: int
duplicate_indices: tuple[int, ...]
similarity: float
exact: bool
__init__(representative_index: int, duplicate_indices: tuple[int, ...], similarity: float, exact: bool) → None
class automated_document_parser.transformation.DuplicateReport(groups: tuple[DuplicateGroup, ...], compared_count: int, threshold: float, method: str = 'sequence-matcher')[source]

Duplicate groups and the comparison policy used.

groups: tuple[DuplicateGroup, ...]
compared_count: int
threshold: float
method: str
__init__(groups: tuple[DuplicateGroup, ...], compared_count: int, threshold: float, method: str = 'sequence-matcher') → None
class automated_document_parser.transformation.PIIMatch(category: str, value: str, start_offset: int, end_offset: int, confidence: float, source: str, element_index: int | None = None, page_number: int | None = None)[source]

A detected sensitive span in the original document.

category: str
value: str
start_offset: int
end_offset: int
confidence: float
source: str
element_index: int | None
page_number: int | None
__init__(category: str, value: str, start_offset: int, end_offset: int, confidence: float, source: str, element_index: int | None = None, page_number: int | None = None) → None
class automated_document_parser.transformation.RedactionResult(content: str, redacted_document: ParsedDocument, redactions: tuple[dict[str, Any], ...], redaction_count: int, source: str, replacement: str)[source]

A redacted copy and the detection metadata, without original values.

content: str
redacted_document: ParsedDocument
redactions: tuple[dict[str, Any], ...]
redaction_count: int
source: str
replacement: str
__init__(content: str, redacted_document: ParsedDocument, redactions: tuple[dict[str, Any], ...], redaction_count: int, source: str, replacement: str) → None
automated_document_parser.transformation.chunk_document(document: ParsedDocument, *, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True) → tuple[DocumentChunk, ...][source]

Split a document while retaining source offsets and layout metadata.

Chunks prefer existing element boundaries. Oversized elements are split at paragraph/line/sentence/word boundaries, with bounded character overlap. Offsets always refer to ParsedDocument.content.

automated_document_parser.transformation.detect_duplicates(document: ParsedDocument, *, threshold: float = 0.92, min_chars: int = 20) → DuplicateReport[source]

Group duplicate document elements using exact or similarity matching.

This intentionally uses a standard-library matcher and is best suited to modest document element counts. Similarity matching is quadratic in the number of eligible elements; use a dedicated index for very large corpora.

automated_document_parser.transformation.detect_pii(document: ParsedDocument, *, categories: Iterable[str] | None = None) → tuple[PIIMatch, ...][source]

Detect common PII locally and return source offsets and page provenance.

automated_document_parser.transformation.normalize_document(document: ParsedDocument, *, unicode_form: str = 'NFC', normalize_whitespace: bool = True, dehyphenate: bool = True, strip: bool = True) → ParsedDocument[source]

Return a normalized copy; the original document is never modified.

automated_document_parser.transformation.normalize_text(text: str, *, unicode_form: str = 'NFC', normalize_whitespace: bool = True, dehyphenate: bool = True, strip: bool = True) → str[source]

Normalize Unicode and common extraction artefacts without flattening layout.

automated_document_parser.transformation.redact_document(document: ParsedDocument, *, categories: Iterable[str] | None = None, replacement: str = '[REDACTED]') → RedactionResult[source]

Return a redacted copy without changing the original document.

The result’s audit metadata records categories and source spans but never copies the sensitive values into the redaction report.

Structure-aware document chunking.

automated_document_parser.transformation.chunking.chunk_document(document: ParsedDocument, *, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True) → tuple[DocumentChunk, ...][source]

Split a document while retaining source offsets and layout metadata.

Chunks prefer existing element boundaries. Oversized elements are split at paragraph/line/sentence/word boundaries, with bounded character overlap. Offsets always refer to ParsedDocument.content.

Conservative, provenance-preserving text normalization.

automated_document_parser.transformation.normalization.normalize_text(text: str, *, unicode_form: str = 'NFC', normalize_whitespace: bool = True, dehyphenate: bool = True, strip: bool = True) → str[source]

Normalize Unicode and common extraction artefacts without flattening layout.

automated_document_parser.transformation.normalization.normalize_document(document: ParsedDocument, *, unicode_form: str = 'NFC', normalize_whitespace: bool = True, dehyphenate: bool = True, strip: bool = True) → ParsedDocument[source]

Return a normalized copy; the original document is never modified.

Dependency-free exact and near-duplicate detection.

automated_document_parser.transformation.deduplication.detect_duplicates(document: ParsedDocument, *, threshold: float = 0.92, min_chars: int = 20) → DuplicateReport[source]

Group duplicate document elements using exact or similarity matching.

This intentionally uses a standard-library matcher and is best suited to modest document element counts. Similarity matching is quadratic in the number of eligible elements; use a dedicated index for very large corpora.

Local PII detection and non-destructive redaction.

automated_document_parser.transformation.privacy.detect_pii(document: ParsedDocument, *, categories: Iterable[str] | None = None) → tuple[PIIMatch, ...][source]

Detect common PII locally and return source offsets and page provenance.

automated_document_parser.transformation.privacy.redact_document(document: ParsedDocument, *, categories: Iterable[str] | None = None, replacement: str = '[REDACTED]') → RedactionResult[source]

Return a redacted copy without changing the original document.

The result’s audit metadata records categories and source spans but never copies the sensitive values into the redaction report.

Configuration

Configuration and mappings for document loaders.

Utilities

Helper functions for document parsing.

automated_document_parser.utils.detect_file_type(file_path: str | Path) → str | None[source]

Detect file type based on extension.

Parameters:

file_path – Path to the file

Returns:

Loader type string or None if unsupported

Raises:

FileNotFoundError – If file doesn’t exist

automated_document_parser.utils.is_supported_file(file_path: str | Path) → bool[source]

Check if file type is supported.

Parameters:

file_path – Path to the file

Returns:

True if supported, False otherwise

automated_document_parser.utils.validate_file_path(file_path: str | Path) → Path[source]

Validate and normalize file path.

Parameters:

file_path – Path to validate

Returns:

Normalized Path object

Raises:
automated_document_parser.utils.get_file_info(file_path: str | Path) → dict[source]

Get basic file information.

Parameters:

file_path – Path to the file

Returns:

Dictionary with file metadata

Loaders

Main File Loaders

Local file system loaders (pdf, txt, csv, etc.).

class automated_document_parser.loaders.file_loaders.FileLoader(file_path: str | Path, pdf_loader_method: Literal['pypdf', 'unstructured', 'amazon_textract', 'mathpix', 'pdfplumber', 'pdfplumber-layout', 'pypdfium2', 'pymupdf', 'pymupdf4llm', 'opendataloader'] = 'pypdf', encoding: str = 'utf-8', jq_schema: str = '.', text_content: bool = False, resource_limits: FileResourceLimits | None = FileResourceLimits(max_file_size_bytes=104857600, max_docx_uncompressed_bytes=536870912, max_docx_members=10000, max_docx_compression_ratio=1000.0), **pdf_loader_kwargs)[source]

Bases: object

Automated file loader that detects file type and loads documents.

__init__(file_path: str | Path, pdf_loader_method: Literal['pypdf', 'unstructured', 'amazon_textract', 'mathpix', 'pdfplumber', 'pdfplumber-layout', 'pypdfium2', 'pymupdf', 'pymupdf4llm', 'opendataloader'] = 'pypdf', encoding: str = 'utf-8', jq_schema: str = '.', text_content: bool = False, resource_limits: FileResourceLimits | None = FileResourceLimits(max_file_size_bytes=104857600, max_docx_uncompressed_bytes=536870912, max_docx_members=10000, max_docx_compression_ratio=1000.0), **pdf_loader_kwargs)[source]

Initialize the FileLoader.

Parameters:
  • file_path – Path to the file to load

  • pdf_loader_method – Method to use for PDF loading.

  • encoding – Text, CSV, HTML and JSON file encoding.

  • jq_schema – Optional jq expression for selecting JSON values.

  • text_content – Treat selected JSON strings as plain text.

  • resource_limits – Preflight file and DOCX archive limits. Defaults to FileResourceLimits(); pass None to disable all limits.

  • **pdf_loader_kwargs – Additional keyword arguments for the selected PDF backend.

Raises:
load() → list[Document][source]

Load documents from the file.

Returns:

List of LangChain Document objects

Raises:

RuntimeError – If loading fails

automated_document_parser.loaders.file_loaders.load_document(file_path: str | Path, pdf_loader_method: Literal['pypdf', 'unstructured', 'amazon_textract', 'mathpix', 'pdfplumber', 'pdfplumber-layout', 'pypdfium2', 'pymupdf', 'pymupdf4llm', 'opendataloader'] = 'pypdf', encoding: str = 'utf-8', jq_schema: str = '.', text_content: bool = False, resource_limits: FileResourceLimits | None = FileResourceLimits(max_file_size_bytes=104857600, max_docx_uncompressed_bytes=536870912, max_docx_members=10000, max_docx_compression_ratio=1000.0), **pdf_loader_kwargs) → list[Document][source]

Convenience function to load a document from a file.

Parameters:
  • file_path – Path to the file

  • pdf_loader_method – Method to use for PDF loading.

  • encoding – Text, CSV, HTML and JSON file encoding.

  • jq_schema – Optional jq expression for selecting JSON values.

  • text_content – Treat selected JSON strings as plain text.

  • resource_limits – Preflight file and DOCX archive limits. Defaults to FileResourceLimits(); pass None to disable all limits.

  • **pdf_loader_kwargs – Additional keyword arguments for the selected PDF backend.

Returns:

List of LangChain Document objects

Examples

>>> # Load a text file
>>> documents = load_document("path/to/file.txt")
>>> # Load a PDF with default PyPDF
>>> documents = load_document("path/to/file.pdf")
>>> # Load a PDF with Unstructured
>>> documents = load_document("path/to/file.pdf", pdf_loader_method="unstructured")
>>> # Load a PDF with Amazon Textract
>>> import boto3
>>> client = boto3.client("textract", region_name="us-east-2")
>>> documents = load_document(
...     "s3://bucket/file.pdf",
...     pdf_loader_method="amazon_textract",
...     client=client
... )

Configurable resource limits for untrusted document files.

class automated_document_parser.loaders.security.FileResourceLimits(max_file_size_bytes: int | None = 104857600, max_docx_uncompressed_bytes: int | None = 536870912, max_docx_members: int | None = 10000, max_docx_compression_ratio: float | None = 1000.0)[source]

Resource caps applied before parsing local files.

Defaults cap input files at 100 MiB and DOCX archives at 10,000 members, 512 MiB total uncompressed size, and a 1,000:1 compression ratio. Set an individual field to None to disable that cap, or pass None as the resource_limits argument to FileLoader to disable all preflight limits. Applications should tune these values to their document workload.

max_file_size_bytes: int | None
max_docx_uncompressed_bytes: int | None
max_docx_members: int | None
max_docx_compression_ratio: float | None
__init__(max_file_size_bytes: int | None = 104857600, max_docx_uncompressed_bytes: int | None = 536870912, max_docx_members: int | None = 10000, max_docx_compression_ratio: float | None = 1000.0) → None

File Load Module

Base File Loader

Base file loader interface.

class automated_document_parser.loaders.file_load.base.BaseFileLoader(file_path: str | Path, **kwargs)[source]

Bases: ABC

Abstract base class for file loaders.

All file loader implementations should inherit from this class.

__init__(file_path: str | Path, **kwargs)[source]

Initialize the file loader.

Parameters:
  • file_path – Path to the file

  • **kwargs – Additional loader-specific arguments

abstractmethod load() → list[Document][source]

Load documents from the file.

Returns:

List of LangChain Document objects

Raises:
abstractmethod static get_install_command() → str[source]

Return the command to install required dependencies.

Returns:

Installation command string

Text File Loader

Dependency-light text and Markdown file loader.

class automated_document_parser.loaders.file_load.text_loader.TextFileLoader(file_path: str | Path, **kwargs)[source]

Bases: BaseFileLoader

Load UTF-8 or explicitly encoded plain-text and Markdown files.

load() → list[Document][source]

Read the file and return one LangChain document.

static get_install_command() → str[source]

Return the installation command for this built-in loader.

CSV File Loader

Standard-library CSV loader.

class automated_document_parser.loaders.file_load.csv_loader.CSVFileLoader(file_path: str | Path, **kwargs)[source]

Bases: BaseFileLoader

Load CSV rows as individual LangChain documents.

load() → list[Document][source]

Parse rows while retaining source and row-number metadata.

static get_install_command() → str[source]

Return the installation command for this built-in loader.

JSON File Loader

JSON loader with optional jq-based query support.

class automated_document_parser.loaders.file_load.json_loader.JSONFileLoader(file_path: str | Path, **kwargs)[source]

Bases: BaseFileLoader

Load JSON using the standard library, with optional jq expressions.

load() → list[Document][source]

Load JSON values selected by jq_schema as documents.

static get_install_command() → str[source]

Return the optional installation command for jq expressions.

DOCX File Loader

DOCX loader using python-docx.

class automated_document_parser.loaders.file_load.docx_loader.DOCXFileLoader(file_path: str | Path, **kwargs)[source]

Bases: BaseFileLoader

Extract paragraphs and tables from Microsoft Word documents.

load() → list[Document][source]

Extract paragraph text and table rows in document order by section.

static get_install_command() → str[source]

Return the installation command for this loader.

HTML File Loader

HTML loader based on Python’s standard-library HTML parser.

class automated_document_parser.loaders.file_load.html_loader.HTMLFileLoader(file_path: str | Path, **kwargs)[source]

Bases: BaseFileLoader

Extract readable text from HTML without an external parser dependency.

load() → list[Document][source]

Parse HTML and return its visible text as one document.

static get_install_command() → str[source]

Return the installation command for this built-in loader.

PDF Load Module

PDF Loader Classes

class automated_document_parser.loaders.pdf_load.PDFLoader(file_path: str | Path, method: Literal['pypdf', 'unstructured', 'amazon_textract', 'mathpix', 'pdfplumber', 'pdfplumber-layout', 'pypdfium2', 'pymupdf', 'pymupdf4llm', 'opendataloader'] | str = 'pypdf', loader_class: type[BasePDFLoader] | None = None, **kwargs)[source]

Bases: object

Flexible PDF loader supporting multiple parsing backends.

By default, uses PyPDF for standard PDF parsing. Users can specify alternative methods like ‘unstructured’ for advanced parsing or ‘amazon_textract’ for OCR capabilities.

Users can also provide custom loader classes that inherit from BasePDFLoader.

__init__(file_path: str | Path, method: Literal['pypdf', 'unstructured', 'amazon_textract', 'mathpix', 'pdfplumber', 'pdfplumber-layout', 'pypdfium2', 'pymupdf', 'pymupdf4llm', 'opendataloader'] | str = 'pypdf', loader_class: type[BasePDFLoader] | None = None, **kwargs)[source]

Initialize PDF loader with specified method or custom loader.

Parameters:
  • file_path – Path to PDF file or URL (for amazon_textract)

  • method – Loading method such as pypdf, pdfplumber-layout, unstructured or amazon_textract. Custom names are accepted with loader_class.

  • loader_class – Optional custom loader class inheriting from BasePDFLoader. When provided, it takes precedence over method.

  • **kwargs – Backend-specific options. Textract accepts client and region_name; Unstructured accepts api_key; Mathpix accepts mathpix_api_key. Credentials may also be supplied through the corresponding environment variables.

Raises:
  • ValueError – If method is not supported and no loader_class is provided

  • TypeError – If loader_class doesn’t inherit from BasePDFLoader

Examples

>>> # Default PyPDF loader
>>> loader = PDFLoader("document.pdf")
>>> docs = loader.load()
>>> # Use Unstructured
>>> loader = PDFLoader("document.pdf", method="unstructured")
>>> docs = loader.load()
>>> # Use custom loader class
>>> from my_loaders import CustomPDFLoader
>>> loader = PDFLoader("document.pdf", loader_class=CustomPDFLoader)
>>> docs = loader.load()
load() → list[Document][source]

Load PDF documents using the specified method or loader.

Returns:

List of LangChain Document objects

Raises:
get_install_command() → str[source]

Get pip install command for the current loader’s dependencies.

automated_document_parser.loaders.pdf_load.load_pdf(file_path: str | Path, method: Literal['pypdf', 'unstructured', 'amazon_textract', 'mathpix', 'pdfplumber', 'pdfplumber-layout', 'pypdfium2', 'pymupdf', 'pymupdf4llm', 'opendataloader'] | str = 'pypdf', loader_class: type[BasePDFLoader] | None = None, **kwargs) → list[Document][source]

Convenience function to load a PDF document.

Parameters:
  • file_path – Path to PDF file or URL

  • method – Loading method such as ‘pypdf’ (default) or ‘pdfplumber-layout’.

  • loader_class – Optional custom loader class inheriting from BasePDFLoader

  • **kwargs – Additional arguments for the loader

Returns:

List of LangChain Document objects

Examples

>>> # Basic usage with PyPDF (default)
>>> docs = load_pdf("paper.pdf")
>>> # Use Unstructured API
>>> docs = load_pdf("paper.pdf", method="unstructured")
>>> # Use Amazon Textract with URL
>>> docs = load_pdf(
...     "https://example.com/document.pdf",
...     method="amazon_textract"
... )
>>> # Use Amazon Textract with S3
>>> import boto3
>>> client = boto3.client("textract", region_name="us-east-2")
>>> docs = load_pdf(
...     "s3://bucket/document.pdf",
...     method="amazon_textract",
...     client=client
... )
>>> # Use custom loader
>>> from my_loaders import MyCustomLoader
>>> docs = load_pdf("paper.pdf", loader_class=MyCustomLoader)
automated_document_parser.loaders.pdf_load.PDFLoaderMethod

alias of Literal[‘pypdf’, ‘unstructured’, ‘amazon_textract’, ‘mathpix’, ‘pdfplumber’, ‘pdfplumber-layout’, ‘pypdfium2’, ‘pymupdf’, ‘pymupdf4llm’, ‘opendataloader’]

Base PDF Loader

Base PDF loader class and type definitions.

class automated_document_parser.loaders.pdf_load.base.BasePDFLoader(file_path: str | Path, **kwargs)[source]

Bases: ABC

Abstract base class for PDF loaders.

All PDF loader implementations should inherit from this class.

__init__(file_path: str | Path, **kwargs)[source]

Initialize the PDF loader.

Parameters:
  • file_path – Path to PDF file or URL

  • **kwargs – Additional loader-specific arguments

abstractmethod load() → list[Document][source]

Load PDF documents.

Returns:

List of LangChain Document objects

Raises:
abstractmethod get_install_command() → str[source]

Get the pip install command for required dependencies.

Returns:

Install command string

PyPDF Loader

Native PyPDF backend for page-preserving PDF text extraction.

class automated_document_parser.loaders.pdf_load.pypdf_loader.PyPDFLoaderImpl(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

Extract one LangChain document per PDF page using pypdf.

load() → list[Document][source]

Read the PDF and preserve page numbers and document metadata.

get_install_command() → str[source]

Return the installation command for the native PyPDF backend.

Unstructured PDF Loader

Unstructured API loader implementation.

Reference: https://docs.langchain.com/oss/python/integrations/document_loaders/unstructured_file

class automated_document_parser.loaders.pdf_load.unstructured_loader.UnstructuredPDFLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

PDF loader using Unstructured API backend.

Advanced parsing with support for complex document layouts. Requires UNSTRUCTURED_API_KEY environment variable or api_key in kwargs.

load() → list[Document][source]

Load a PDF through the Unstructured hosted API.

get_install_command() → str[source]

Get pip install command for Unstructured dependencies.

Amazon Textract Loader

Amazon Textract loader implementation.

Reference: https://docs.langchain.com/oss/python/integrations/document_loaders/amazon_textract

class automated_document_parser.loaders.pdf_load.textract_loader.AmazonTextractPDFLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

PDF loader using Amazon Textract backend.

OCR service for extracting text from scanned documents and images. Supports local files, HTTP/HTTPS URLs, and S3 URIs.

Requires AWS credentials to be configured.

load() → list[Document][source]

Load PDF using Amazon Textract.

Returns:

List of LangChain Document objects

Raises:

ImportError – If boto3 or amazon-textract-caller is not installed

get_install_command() → str[source]

Get pip install command for Amazon Textract dependencies.

Mathpix Loader

Mathpix API loader implementation.

Reference: https://python.langchain.com/docs/integrations/document_loaders/mathpix/

class automated_document_parser.loaders.pdf_load.mathpix_loader.MathpixPDFLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

PDF loader using Mathpix API backend.

Specialized for converting PDFs with mathematical formulas, tables, and diagrams. Requires MATHPIX_API_KEY environment variable or mathpix_api_key in kwargs.

load() → list[Document][source]

Load PDF using Mathpix API.

Returns:

List of LangChain Document objects

Raises:
static get_install_command() → str[source]

Return the command to install required dependencies.

Returns:

Installation command string

PDFPlumber Layout Loader

Layout-aware PDF extraction using the MIT-licensed pdfplumber library.

class automated_document_parser.loaders.pdf_load.pdfplumber_layout_loader.PDFPlumberLayoutLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

Extract ordered text blocks and tables with page-level coordinates.

The backend emits one LangChain document per semantic element. Metadata contains page dimensions, element type, bounding box, reading order and font hints. Tables retain their original cell matrix in table_rows. Reading order uses a heuristic for simple multi-column layouts; complex magazine-style layouts may require custom table or column settings.

Optional ocr_fallback=True invokes local Tesseract OCR only on pages whose native text is below ocr_min_characters. image_output_dir saves rendered crops for embedded image regions. Both visual capabilities use the optional PDFium renderer; OCR additionally needs Tesseract installed.

load() → list[Document][source]

Extract text and tables from a local PDF while preserving layout.

get_install_command() → str[source]

Return the installation command for this layout-aware backend.

PDFPlumber Loader

Native pdfplumber PDF loader with optional table extraction.

class automated_document_parser.loaders.pdf_load.pdfplumber_loader.PDFPlumberLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

Extract page text and optionally structured table data with pdfplumber.

This implementation uses pdfplumber directly and does not require langchain-community. Use pdfplumber-layout for element-level reading order, headings and bounding boxes.

load() → list[Document][source]

Load one document per page, preserving page and table metadata.

get_install_command() → str[source]

Return the installation command for pdfplumber support.

PyPDFium2 Loader

Native pypdfium2 backend for page-preserving PDF text extraction.

class automated_document_parser.loaders.pdf_load.pypdfium2_loader.PyPDFium2Loader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

Extract one LangChain document per page using pypdfium2 directly.

This loader intentionally uses pypdfium2 rather than depending on langchain-community for a local PDF parsing backend.

load() → list[Document][source]

Extract page text and document metadata from a local PDF file.

static get_install_command() → str[source]

Return the installation command for the native PDFium backend.

PyMuPDF Loader

Native PyMuPDF backend for page-preserving PDF text extraction.

class automated_document_parser.loaders.pdf_load.pymupdf_loader.PyMuPDFLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

Extract one LangChain document per page using PyMuPDF directly.

This loader intentionally uses the PyMuPDF API rather than depending on langchain-community for a local PDF parsing backend.

load() → list[Document][source]

Extract page text and document metadata from a local PDF file.

static get_install_command() → str[source]

Return the installation command for the native PyMuPDF backend.

PyMuPDF4LLM Loader

PyMuPDF4LLM loader implementation.

Reference: https://python.langchain.com/docs/integrations/document_loaders/pymupdf4llm/

class automated_document_parser.loaders.pdf_load.pymupdf4llm_loader.PyMuPDF4LLMLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

PDF loader using PyMuPDF4LLM backend.

Optimized for LLM processing with enhanced text extraction and formatting. No API key required - works locally.

load() → list[Document][source]

Load PDF using PyMuPDF4LLM.

Returns:

List of LangChain Document objects

Raises:

ImportError – If langchain-pymupdf4llm is not installed

static get_install_command() → str[source]

Return the command to install required dependencies.

Returns:

Installation command string

OpenDataLoader PDF Loader

OpenDataLoader PDF loader implementation.

Reference: https://python.langchain.com/docs/integrations/document_loaders/opendataloader/

class automated_document_parser.loaders.pdf_load.opendataloader_loader.OpenDataLoaderPDFLoader(file_path: str | Path, **kwargs)[source]

Bases: BasePDFLoader

PDF loader using OpenDataLoader backend.

Advanced PDF parsing with support for multiple formats and configurations. No API key required - works locally.

load() → list[Document][source]

Load PDF using OpenDataLoader.

Returns:

List of LangChain Document objects

Raises:

ImportError – If langchain-opendataloader-pdf is not installed

static get_install_command() → str[source]

Return the command to install required dependencies.

Returns:

Installation command string

Retrieval

Retrieval primitives and pluggable search integrations.

class automated_document_parser.retrieval.BM25Index(chunks: Sequence[DocumentChunk], *, k1: float = 1.5, b: float = 0.75)[source]

Okapi BM25 index suitable for modest in-process collections.

__init__(chunks: Sequence[DocumentChunk], *, k1: float = 1.5, b: float = 0.75) → None[source]
search(query: str, k: int = 10) → list[tuple[DocumentChunk, float]][source]
class automated_document_parser.retrieval.EmbeddingBackend(*args, **kwargs)[source]

Provider-neutral embedding contract.

embed_documents(texts: Sequence[str]) → Sequence[Sequence[float]][source]
embed_query(text: str) → Sequence[float][source]
__init__(*args, **kwargs)
class automated_document_parser.retrieval.HashingEmbedder(dimensions: int = 384)[source]

Dependency-free signed feature hashing; useful baseline, not semantic AI.

Use a trained embedding backend for semantic retrieval in production.

__init__(dimensions: int = 384) → None[source]
embed_documents(texts: Sequence[str]) → Sequence[Sequence[float]][source]
embed_query(text: str) → Sequence[float][source]
class automated_document_parser.retrieval.HybridRetriever(chunks: Sequence[DocumentChunk], *, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None, reranker: Reranker | None = None, rrf_k: int = 60, index_embeddings: bool = True)[source]

Combine BM25 and vector rankings, optionally followed by a reranker.

Set index_embeddings=False when the supplied vector store already contains embeddings for these chunks; query embeddings are still generated.

__init__(chunks: Sequence[DocumentChunk], *, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None, reranker: Reranker | None = None, rrf_k: int = 60, index_embeddings: bool = True) → None[source]
search(query: str, *, k: int = 5, candidate_k: int | None = None) → tuple[RetrievalResult, ...][source]
class automated_document_parser.retrieval.InMemoryVectorStore[source]

Simple exact-search adapter intended for small corpora and testing.

__init__() → None[source]
add(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]]) → None[source]
replace_source(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]], *, source: str) → None[source]

Atomically replace all in-memory vectors for one source.

list_chunks() → tuple[DocumentChunk, ...][source]

Return indexed chunks in deterministic source/chunk order.

search(vector: Sequence[float], k: int) → list[tuple[DocumentChunk, float]][source]
health_check() → bool[source]

Confirm the in-memory index is accessible.

class automated_document_parser.retrieval.OpenAICompatibleEmbedder(model: str = 'text-embedding-3-small', *, api_key: str | None = None, base_url: str | None = None, dimensions: int | None = None, batch_size: int = 128, timeout: float = 30.0, max_retries: int = 2, client: Any | None = None)[source]

Embedding adapter for OpenAI and OpenAI-compatible embedding APIs.

The official openai SDK is loaded lazily and is only required when a client is not injected. Compatible local servers such as Ollama can be configured through base_url without changing the retrieval interface.

__init__(model: str = 'text-embedding-3-small', *, api_key: str | None = None, base_url: str | None = None, dimensions: int | None = None, batch_size: int = 128, timeout: float = 30.0, max_retries: int = 2, client: Any | None = None) → None[source]
embed_documents(texts: Sequence[str]) → list[list[float]][source]

Embed documents in bounded batches, preserving input order.

embed_query(text: str) → list[float][source]

Embed one query using the same model and output dimensions.

class automated_document_parser.retrieval.Reranker(*args, **kwargs)[source]

Optional relevance reranker. Return one relevance score per document.

score(query: str, documents: Sequence[str]) → Sequence[float][source]
__init__(*args, **kwargs)
class automated_document_parser.retrieval.RetrievalResult(chunk: DocumentChunk, score: float, rank: int, lexical_score: float | None = None, vector_score: float | None = None, reranker_score: float | None = None, metadata: dict[str, ~typing.Any]=<factory>)[source]

A retrieved chunk with ranking and source provenance.

chunk: DocumentChunk
score: float
rank: int
lexical_score: float | None
vector_score: float | None
reranker_score: float | None
metadata: dict[str, Any]
__init__(chunk: DocumentChunk, score: float, rank: int, lexical_score: float | None = None, vector_score: float | None = None, reranker_score: float | None = None, metadata: dict[str, ~typing.Any]=<factory>) → None
class automated_document_parser.retrieval.SQLiteVectorStore(database: str | Path, *, timeout: float = 5.0)[source]

Persist chunk vectors in SQLite and perform exact cosine search.

This adapter has no third-party runtime dependencies. It is useful for durable local deployments and modest collections; it is not an approximate nearest-neighbour index or a substitute for a distributed vector database.

A store owns one SQLite connection and serializes access with a re-entrant lock. Use it as a context manager or call close() when finished.

__init__(database: str | Path, *, timeout: float = 5.0) → None[source]
add(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]]) → None[source]

Insert or replace chunks and vectors in one atomic transaction.

replace_source(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]], *, source: str) → None[source]

Atomically replace one source and its vectors.

Existing rows for other sources retain their embedding dimension. A source can be replaced with a new dimension only when no other indexed source depends on the previous dimension.

list_chunks(*, source: str | None = None) → tuple[DocumentChunk, ...][source]

Load indexed chunk records without their embedding payloads.

search(vector: Sequence[float], k: int) → list[tuple[DocumentChunk, float]][source]

Return the top-k chunks ranked by exact cosine similarity.

health_check() → bool[source]

Run a lightweight database round-trip without scanning indexed content.

close() → None[source]

Close the underlying SQLite connection; safe to call more than once.

class automated_document_parser.retrieval.Tokenizer(*args, **kwargs)[source]

Minimal tokenizer contract; implementations may wrap tiktoken or HF.

count_tokens(text: str) → int[source]
__init__(*args, **kwargs)
class automated_document_parser.retrieval.VectorStore(*args, **kwargs)[source]

Minimal vector-store adapter contract.

add(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]]) → None[source]
search(vector: Sequence[float], k: int) → Sequence[tuple[DocumentChunk, float]][source]
__init__(*args, **kwargs)
automated_document_parser.retrieval.chunk_document_by_tokens(document: ParsedDocument, *, tokenizer: Tokenizer | Callable[[str], int], max_tokens: int = 512, overlap_tokens: int = 50) → tuple[DocumentChunk, ...][source]

Chunk text to a tokenizer-defined budget while retaining character offsets.

Tokenizer must expose count_tokens(text) or be a callable returning a token count. Binary search bounds tokenizer calls for each chunk. Candidate boundaries are whitespace boundaries; no tokenizer package or model download is required by the core distribution.

automated_document_parser.retrieval.cosine_similarity(left: Sequence[float], right: Sequence[float]) → float[source]
automated_document_parser.retrieval.evaluate_retrieval(retrieved: Sequence[str], relevant: set[str], *, k: int = 5, graded_relevance: Mapping[str, float] | None = None) → dict[str, float][source]
automated_document_parser.retrieval.mean_reciprocal_rank(retrieved: Sequence[str], relevant: set[str]) → float[source]
automated_document_parser.retrieval.ndcg_at_k(retrieved: Sequence[str], relevance: Mapping[str, float], k: int) → float[source]
automated_document_parser.retrieval.precision_at_k(retrieved: Sequence[str], relevant: set[str], k: int) → float[source]
automated_document_parser.retrieval.recall_at_k(retrieved: Sequence[str], relevant: set[str], k: int) → float[source]

Small deterministic embedding baseline for tests and offline examples.

class automated_document_parser.retrieval.embeddings.HashingEmbedder(dimensions: int = 384)[source]

Dependency-free signed feature hashing; useful baseline, not semantic AI.

Use a trained embedding backend for semantic retrieval in production.

__init__(dimensions: int = 384) → None[source]
embed_documents(texts: Sequence[str]) → Sequence[Sequence[float]][source]
embed_query(text: str) → Sequence[float][source]
class automated_document_parser.retrieval.embeddings.OpenAICompatibleEmbedder(model: str = 'text-embedding-3-small', *, api_key: str | None = None, base_url: str | None = None, dimensions: int | None = None, batch_size: int = 128, timeout: float = 30.0, max_retries: int = 2, client: Any | None = None)[source]

Embedding adapter for OpenAI and OpenAI-compatible embedding APIs.

The official openai SDK is loaded lazily and is only required when a client is not injected. Compatible local servers such as Ollama can be configured through base_url without changing the retrieval interface.

__init__(model: str = 'text-embedding-3-small', *, api_key: str | None = None, base_url: str | None = None, dimensions: int | None = None, batch_size: int = 128, timeout: float = 30.0, max_retries: int = 2, client: Any | None = None) → None[source]
embed_documents(texts: Sequence[str]) → list[list[float]][source]

Embed documents in bounded batches, preserving input order.

embed_query(text: str) → list[float][source]

Embed one query using the same model and output dimensions.

Hybrid lexical/vector retrieval with reciprocal-rank fusion.

class automated_document_parser.retrieval.hybrid.HybridRetriever(chunks: Sequence[DocumentChunk], *, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None, reranker: Reranker | None = None, rrf_k: int = 60, index_embeddings: bool = True)[source]

Combine BM25 and vector rankings, optionally followed by a reranker.

Set index_embeddings=False when the supplied vector store already contains embeddings for these chunks; query embeddings are still generated.

__init__(chunks: Sequence[DocumentChunk], *, embedder: EmbeddingBackend | None = None, vector_store: VectorStore | None = None, reranker: Reranker | None = None, rrf_k: int = 60, index_embeddings: bool = True) → None[source]
search(query: str, *, k: int = 5, candidate_k: int | None = None) → tuple[RetrievalResult, ...][source]

Persistent exact-search vector store backed by the Python standard library.

class automated_document_parser.retrieval.sqlite_store.SQLiteVectorStore(database: str | Path, *, timeout: float = 5.0)[source]

Persist chunk vectors in SQLite and perform exact cosine search.

This adapter has no third-party runtime dependencies. It is useful for durable local deployments and modest collections; it is not an approximate nearest-neighbour index or a substitute for a distributed vector database.

A store owns one SQLite connection and serializes access with a re-entrant lock. Use it as a context manager or call close() when finished.

__init__(database: str | Path, *, timeout: float = 5.0) → None[source]
add(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]]) → None[source]

Insert or replace chunks and vectors in one atomic transaction.

replace_source(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]], *, source: str) → None[source]

Atomically replace one source and its vectors.

Existing rows for other sources retain their embedding dimension. A source can be replaced with a new dimension only when no other indexed source depends on the previous dimension.

list_chunks(*, source: str | None = None) → tuple[DocumentChunk, ...][source]

Load indexed chunk records without their embedding payloads.

search(vector: Sequence[float], k: int) → list[tuple[DocumentChunk, float]][source]

Return the top-k chunks ranked by exact cosine similarity.

health_check() → bool[source]

Run a lightweight database round-trip without scanning indexed content.

close() → None[source]

Close the underlying SQLite connection; safe to call more than once.

Standard ranking metrics for retrieval experiments.

automated_document_parser.retrieval.evaluation.precision_at_k(retrieved: Sequence[str], relevant: set[str], k: int) → float[source]
automated_document_parser.retrieval.evaluation.recall_at_k(retrieved: Sequence[str], relevant: set[str], k: int) → float[source]
automated_document_parser.retrieval.evaluation.mean_reciprocal_rank(retrieved: Sequence[str], relevant: set[str]) → float[source]
automated_document_parser.retrieval.evaluation.ndcg_at_k(retrieved: Sequence[str], relevance: Mapping[str, float], k: int) → float[source]
automated_document_parser.retrieval.evaluation.evaluate_retrieval(retrieved: Sequence[str], relevant: set[str], *, k: int = 5, graded_relevance: Mapping[str, float] | None = None) → dict[str, float][source]

Typed models and protocols for retrieval integrations.

class automated_document_parser.retrieval.models.RetrievalResult(chunk: DocumentChunk, score: float, rank: int, lexical_score: float | None = None, vector_score: float | None = None, reranker_score: float | None = None, metadata: dict[str, ~typing.Any]=<factory>)[source]

A retrieved chunk with ranking and source provenance.

chunk: DocumentChunk
score: float
rank: int
lexical_score: float | None
vector_score: float | None
reranker_score: float | None
metadata: dict[str, Any]
__init__(chunk: DocumentChunk, score: float, rank: int, lexical_score: float | None = None, vector_score: float | None = None, reranker_score: float | None = None, metadata: dict[str, ~typing.Any]=<factory>) → None
class automated_document_parser.retrieval.models.Tokenizer(*args, **kwargs)[source]

Minimal tokenizer contract; implementations may wrap tiktoken or HF.

count_tokens(text: str) → int[source]
__init__(*args, **kwargs)
class automated_document_parser.retrieval.models.EmbeddingBackend(*args, **kwargs)[source]

Provider-neutral embedding contract.

embed_documents(texts: Sequence[str]) → Sequence[Sequence[float]][source]
embed_query(text: str) → Sequence[float][source]
__init__(*args, **kwargs)
class automated_document_parser.retrieval.models.Reranker(*args, **kwargs)[source]

Optional relevance reranker. Return one relevance score per document.

score(query: str, documents: Sequence[str]) → Sequence[float][source]
__init__(*args, **kwargs)
class automated_document_parser.retrieval.models.VectorStore(*args, **kwargs)[source]

Minimal vector-store adapter contract.

add(chunks: Sequence[DocumentChunk], vectors: Sequence[Sequence[float]]) → None[source]
search(vector: Sequence[float], k: int) → Sequence[tuple[DocumentChunk, float]][source]
__init__(*args, **kwargs)
automated_document_parser.retrieval.models.chunk_identity(chunk: DocumentChunk) → str[source]

Return a stable identity shared by in-memory and persistent adapters.

Logging

The CLI configures package logging at its process boundary. JSON is the default format; --log-format human selects readable console output. Library users can call automated_document_parser.logging_config.configure_logging and correlation_context explicitly. The package does not configure the root logger. Log formatters redact common credential patterns and sensitive fields; applications should still avoid placing document text or secrets in log messages.