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_jobsends 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.
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:
objectConnect 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.
- 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.
- __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.
- document: ParsedDocument
- chunks: tuple[DocumentChunk, ...]
- classification: DocumentClassification | None
- entities: tuple[ExtractedEntity, ...]
- extraction: StructuredExtraction | None
- redaction: RedactionResult | None
- __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, ...]
- __init__(results: tuple[IngestionResult, ...], failures: tuple[IngestionFailure, ...]) 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).
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.sqlite3andjobs.sqlite3so 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.
- 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.
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.
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/jobsaccepts paths on the server, not uploaded bytes. Every requested path is resolved and constrained toallowed_rootsbefore it enters the queue. Configureapi_keywhen exposing the service beyond a trusted local network; all application endpoints except/healthzand/readyzthen require theX-API-Keyheader. 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.
- __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 IMMEDIATEwhen 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.- 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
Nonewhen it does not exist.
- list_jobs(*, limit: int = 50, status: str | None = None) tuple[IngestionJob, ...][source]
List recent jobs, optionally filtered by lifecycle status.
- 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.
- 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]
Core Module
- class automated_document_parser.processor.DocumentProcessor(parser: DocumentParser | None = None, *, intelligence: DocumentIntelligence | None = None, schema_extractor: SchemaExtractionBackend | None = None)[source]
Bases:
objectProcess files into the package’s normalised document representation.
DocumentParserremains the compatibility API returning LangChain documents.DocumentProcessoris 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=Falsewhen 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:
objectNormalised 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.
- 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.
- 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:
objectA source-preserving unit of extracted document content.
Main DocumentParser class for automated document loading.
- class automated_document_parser.core.DocumentParser[source]
Bases:
objectMain class for automated document parsing.
Automatically detects file type and loads documents using appropriate loaders. Designed for seamless integration with LangChain RAG pipelines.
- 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
jsonextra; the default.does not.text_content – Treat selected JSON strings as document text rather than serialising them as JSON.
resource_limits – Optional
FileResourceLimitspreflight caps. The default limits apply unlessNoneis supplied explicitly.**kwargs – Additional backend-specific keyword arguments for PDF loading.
- Returns:
List of LangChain Document objects
- Raises:
FileNotFoundError – If file doesn’t exist
ValueError – If file type is unsupported
ImportError – If an optional backend dependency is missing.
RuntimeError – If parsing fails.
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")
Document Intelligence
- class automated_document_parser.intelligence.DocumentIntelligence(schema_extractor: SchemaExtractionBackend | None = None)[source]
Bases:
objectClassify documents and extract entities or schema-shaped data.
The default backend is deterministic and dependency-free. A custom backend can implement
SchemaExtractionBackendto 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:
objectExtract 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.
- 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.
- class automated_document_parser.intelligence.DocumentClassification(label: str, confidence: float, candidates: tuple[ClassificationCandidate, ...] = (), method: str = 'rules')[source]
Ranked document type predictions.
- 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.
- fields: dict[str, FieldExtraction]
- 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.
- 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.
- 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.
- 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, ...]
- 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.
- 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.
- redacted_document: ParsedDocument
- 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:
FileNotFoundError – If file doesn’t exist
ValueError – If path is not a file
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:
objectAutomated 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(); passNoneto disable all limits.**pdf_loader_kwargs – Additional keyword arguments for the selected PDF backend.
- Raises:
FileNotFoundError – If file doesn’t exist
ValueError – If file type is unsupported
- 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(); passNoneto 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
Noneto disable that cap, or passNoneas theresource_limitsargument toFileLoaderto disable all preflight limits. Applications should tune these values to their document workload.
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:
ABCAbstract 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:
ImportError – If required dependencies are not installed
RuntimeError – If loading fails
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:
BaseFileLoaderLoad UTF-8 or explicitly encoded plain-text and Markdown files.
CSV File Loader
Standard-library CSV loader.
- class automated_document_parser.loaders.file_load.csv_loader.CSVFileLoader(file_path: str | Path, **kwargs)[source]
Bases:
BaseFileLoaderLoad CSV rows as individual LangChain documents.
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:
BaseFileLoaderLoad JSON using the standard library, with optional 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:
BaseFileLoaderExtract paragraphs and tables from Microsoft Word documents.
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:
BaseFileLoaderExtract readable text from HTML without an external parser dependency.
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:
objectFlexible 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,unstructuredoramazon_textract. Custom names are accepted withloader_class.loader_class – Optional custom loader class inheriting from BasePDFLoader. When provided, it takes precedence over
method.**kwargs – Backend-specific options. Textract accepts
clientandregion_name; Unstructured acceptsapi_key; Mathpix acceptsmathpix_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:
ImportError – If required dependencies are not installed
RuntimeError – If loading fails
- 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)
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:
ABCAbstract 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:
ImportError – If required dependencies are not installed
RuntimeError – If loading fails
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:
BasePDFLoaderExtract one LangChain document per PDF page using pypdf.
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:
BasePDFLoaderPDF loader using Unstructured API backend.
Advanced parsing with support for complex document layouts. Requires UNSTRUCTURED_API_KEY environment variable or api_key in kwargs.
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:
BasePDFLoaderPDF 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
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:
BasePDFLoaderPDF 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:
ValueError – If API key is not provided
ImportError – If langchain-community is not installed
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:
BasePDFLoaderExtract 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=Trueinvokes local Tesseract OCR only on pages whose native text is belowocr_min_characters.image_output_dirsaves rendered crops for embedded image regions. Both visual capabilities use the optional PDFium renderer; OCR additionally needs Tesseract installed.
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:
BasePDFLoaderExtract page text and optionally structured table data with pdfplumber.
This implementation uses pdfplumber directly and does not require
langchain-community. Usepdfplumber-layoutfor element-level reading order, headings and bounding boxes.
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:
BasePDFLoaderExtract one LangChain document per page using pypdfium2 directly.
This loader intentionally uses pypdfium2 rather than depending on
langchain-communityfor a local PDF parsing 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:
BasePDFLoaderExtract one LangChain document per page using PyMuPDF directly.
This loader intentionally uses the PyMuPDF API rather than depending on
langchain-communityfor a local PDF parsing 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:
BasePDFLoaderPDF 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
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:
BasePDFLoaderPDF 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
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.
- class automated_document_parser.retrieval.EmbeddingBackend(*args, **kwargs)[source]
Provider-neutral embedding contract.
- __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.
- 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=Falsewhen 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]
- class automated_document_parser.retrieval.InMemoryVectorStore[source]
Simple exact-search adapter intended for small corpora and testing.
- 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.
- 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
openaiSDK is loaded lazily and is only required when a client is not injected. Compatible local servers such as Ollama can be configured throughbase_urlwithout 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]
- class automated_document_parser.retrieval.Reranker(*args, **kwargs)[source]
Optional relevance reranker. Return one relevance score per document.
- __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
- 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.- 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.
- class automated_document_parser.retrieval.Tokenizer(*args, **kwargs)[source]
Minimal tokenizer contract; implementations may wrap tiktoken or HF.
- __init__(*args, **kwargs)
- class automated_document_parser.retrieval.VectorStore(*args, **kwargs)[source]
Minimal vector-store adapter contract.
- __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.
- 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
openaiSDK is loaded lazily and is only required when a client is not injected. Compatible local servers such as Ollama can be configured throughbase_urlwithout 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]
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=Falsewhen 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]
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.- 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.
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
- class automated_document_parser.retrieval.models.Tokenizer(*args, **kwargs)[source]
Minimal tokenizer contract; implementations may wrap tiktoken or HF.
- __init__(*args, **kwargs)
- class automated_document_parser.retrieval.models.EmbeddingBackend(*args, **kwargs)[source]
Provider-neutral embedding contract.
- __init__(*args, **kwargs)
- class automated_document_parser.retrieval.models.Reranker(*args, **kwargs)[source]
Optional relevance reranker. Return one relevance score per document.
- __init__(*args, **kwargs)
- class automated_document_parser.retrieval.models.VectorStore(*args, **kwargs)[source]
Minimal vector-store adapter contract.
- __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.