Feature Guide
This guide maps the package’s capabilities to the right entry point, optional extras and operational documentation. The package is designed as a modular Python toolkit: parsing and local transformations work without model downloads, while OCR, hosted embeddings, API serving and monitoring are opt-in.
Choose an entry point
Entry point |
Use it when |
Output / behavior |
|---|---|---|
|
Maintaining an existing LangChain integration |
LangChain |
|
Building a new Python integration |
Normalized |
|
Building repeatable local ingestion and retrieval workflows |
Stage timings, fingerprints, chunks, optional embeddings and vector indexing |
|
Running parsing, indexing, search, serving or recovery from a shell |
JSON command output and structured logs on stderr |
|
Serving server-local ingestion jobs to another application |
FastAPI service, durable SQLite queue and a standard-library client |
The DocumentParser API remains supported for compatibility. Prefer
DocumentProcessor for new integrations because it returns one normalized
result object and exposes the package’s higher-level features. JSON files can
also be filtered with a jq expression using the optional [json] extra; the
text_content option treats selected JSON strings as document text instead
of serializing them as JSON:
docs = DocumentParser().parse(
"payload.json", jq_schema=".records[]", text_content=True
)
Parsing and normalized document model
Automatic dispatch supports TXT, Markdown, CSV, JSON, DOCX, HTML and PDF. The
PDF loader is selected with pdf_loader_method; other file types are routed
by extension. ParsedDocument contains:
sourceand loadermetadata;combined
content;elementswith text, element type and optional page, bounding-box, reading order, confidence and backend metadata;to_dict(),to_json()andto_langchain_documents()conversions.
For untrusted local inputs, FileResourceLimits applies file-size and DOCX
archive limits before parsing. These checks are resource guardrails, not a
malware scanner or a replacement for sandboxing, timeouts and OS-level limits.
PDF backend selection
Method |
Intended use |
Install |
|---|---|---|
|
General native text extraction; default backend |
Core install |
|
Native PyMuPDF text extraction |
|
|
Native PDFium text extraction and rendering |
|
|
Page text and table extraction |
|
|
Layout-aware headings, paragraphs, tables and coordinates |
|
|
Markdown-oriented extraction for LLM workflows |
|
|
Specialized layout/OCR document integration |
|
|
AWS-managed OCR and layout extraction |
|
|
Formula-heavy and mathematical documents |
|
|
OpenDataLoader PDF integration |
|
The native PyMuPDF and PDFium backends do not require langchain-community.
The community extra remains optional for specialized integrations such as
Textract and Mathpix. OCR fallback for pdfplumber-layout requires the
[ocr] extra and a separately installed Tesseract executable plus language
data. Image-region output requires [pdf-images] and writes rendered page
region crops, not original embedded image bytes. OCR confidence is a review
signal and is not a calibrated probability.
from automated_document_parser import DocumentProcessor
result = DocumentProcessor().process(
"scanned-report.pdf",
pdf_loader_method="pdfplumber-layout",
ocr_fallback=True,
ocr_min_characters=20,
ocr_languages="eng",
ocr_resolution=250,
image_output_dir="artifacts/page-regions",
)
for element in result.elements:
print(element.element_type, element.page_number, element.bbox)
Document intelligence
DocumentProcessor includes three deterministic capabilities:
Classification: explainable keyword and filename signals rank categories such as invoices, receipts, contracts, resumes, bank statements, purchase orders, reports, forms and letters.
Entity recognition: common business-document entities include email, URL, currency, percentage, date, invoice and purchase-order identifiers, phone, tax ID and explicitly labelled people, organizations and addresses.
Schema extraction: flat JSON-Schema-shaped objects support
string,number,integerandbooleanfields,required,enumand customaliases. This is not full JSON Schema validation.
Extracted entities and schema fields carry Evidence with the matched quote,
source, character offsets and page/element/bounding-box information when the
loader supplies it. Ambiguous label matches, missing required values and type
mismatches remain explicit. Built-in confidence values are heuristic signals,
not calibrated probabilities. A custom model-backed extractor can implement
SchemaExtractionBackend and return the same evidence-aware
StructuredExtraction contract; the core package does not require an LLM.
processor = DocumentProcessor()
document = processor.process("invoice.pdf")
classification = processor.classify(document)
entities = processor.extract_entities(document)
extraction = processor.extract(document, {
"type": "object",
"properties": {
"invoice_number": {"type": "string"},
"total": {"type": "number"},
},
"required": ["invoice_number", "total"],
})
print(classification.label, [item.normalized_value for item in entities])
print(extraction.values, extraction.missing_required)
Transformation and privacy
The transformation package provides non-mutating operations:
Structure-aware chunking prefers element boundaries and retains source offsets, page numbers, element indices and element types. Oversized elements split at paragraph, line, sentence or word boundaries.
Token-budget chunking accepts a
Tokenizerprotocol or callable; no tokenizer runtime is installed by default.Normalization supports Unicode normalization, whitespace cleanup, soft-hyphen removal and line-wrap dehyphenation. Offsets may change, so normalize before downstream evidence/chunk generation when appropriate.
Duplicate detection identifies exact and near-duplicate elements using standard-library sequence matching. Pairwise cost is quadratic; use it for individual documents and modest element counts, not corpus-wide deduplication.
PII detection and redaction are local and rule-based. Categories include
email,us_ssn,credit_card,ipv4and context-qualifiedphone. Redaction returns a separate document and an audit report without the original sensitive values.
Redaction is text-level only. It does not alter the source PDF, embedded images, attachments, or original file metadata. It is not a complete compliance-grade PII detector. Keep original and redacted artifacts under separate access controls, inspect rendered outputs, and apply source-file sanitization before publishing documents.
normalized = processor.normalize(document)
chunks = processor.chunk(normalized, max_chars=1200, overlap=120)
duplicates = processor.find_duplicates(normalized, threshold=0.92)
matches = processor.detect_pii(normalized)
redaction = processor.redact(normalized, categories=("email", "phone"))
Ingestion, embeddings and retrieval
DocumentIngestionPipeline composes parsing, optional normalization,
optional redaction, classification, entity extraction, optional schema
extraction, chunking, embeddings and vector storage. It records a content
fingerprint and per-stage durations. ingest_many returns typed successes
and failures unless strict=True. Built-in SQLite and in-memory stores
replace chunks for an updated source when re-ingesting.
The retrieval layer combines BM25 lexical ranking and optional vector ranking
with Reciprocal Rank Fusion. Optional rerankers can be injected. The included
HashingEmbedder is a local feature-hashing baseline for offline tests, not
semantic search. OpenAICompatibleEmbedder supports OpenAI-compatible
embedding services, including local servers such as Ollama. Keep the embedding
backend, model and dimensions consistent between indexing and query time.
Adapters are intentionally small protocols:
EmbeddingBackendprovides document and query embeddings;VectorStoreprovides vector add/search operations, with optionalreplace_sourcesupport for source-level replacement;Tokenizercounts tokens for token-budget chunking;Rerankerscores candidate texts for a query.
The built-in SQLiteVectorStore is a durable local exact-cosine store for
modest collections, not a distributed or approximate-nearest-neighbour
service. Implement the protocols to connect another provider or database.
from automated_document_parser import (
DocumentIngestionPipeline, HashingEmbedder, IngestionConfig,
SQLiteVectorStore,
)
with SQLiteVectorStore(".adp/index.sqlite3") as store:
pipeline = DocumentIngestionPipeline(
config=IngestionConfig(redact_pii=True, max_chars=1200, overlap=120),
embedder=HashingEmbedder(),
vector_store=store,
)
outcome = pipeline.ingest_many(["invoice.pdf", "report.docx"])
results = pipeline.search("invoice total", k=5)
Evaluation and benchmarks
The retrieval module exposes Precision@K, Recall@K, Mean Reciprocal Rank and
nDCG@K through evaluate_retrieval and individual metric functions. The
repository also includes reproducible synthetic retrieval, pipeline/queue and
document-intelligence evaluation harnesses. Synthetic scores validate the
harness only; they are not evidence of production quality.
python -m benchmarks.run_retrieval_benchmark --k 5 --output retrieval.json
python -m benchmarks.run_pipeline_benchmark --documents 100 --output pipeline.json
python -m benchmarks.run_document_evaluation --output document-evaluation.json
Use a representative, permission-cleared corpus with human-reviewed relevance labels and record dataset fingerprints, model versions, chunking settings and retrieval parameters. See Retrieval Evaluation and Benchmarks for dataset schemas and guidance.
CLI, HTTP API and durable jobs
The adp command supports:
inspect- parse one file and emit a structured JSON representation;ingest- process multiple files and persist chunks/embeddings to SQLite;search- search an existing index;serve- run the optional HTTP API and one background worker;backup/restore- create verified backups and restore to a new path.
The optional [api] extra installs FastAPI, Uvicorn and Prometheus client
support. The API accepts server-local paths only, restricted to configured
allowed roots; it does not accept arbitrary file uploads. Its SQLite-backed
queue supports idempotent submission, status/list, cancellation of queued
jobs, manual retry of terminal failures, worker pause/resume, startup recovery
and bounded retry/backoff. Run one worker per jobs database; SQLite is a
single-host persistence option, not a distributed queue.
The API includes /healthz and /readyz probes, protected /metrics,
request IDs, a bounded request body, API-key authentication and a process-local
sliding-window rate limiter. ADPClient is a synchronous standard-library
client for job and search endpoints. Use a TLS-terminating reverse proxy and
network controls for remote access. See API Reference for routes and configuration.
Operations: backups, logs, metrics and deployment
Backup and restore: SQLite’s online backup API, checksum manifest and pre-restore verification are used. Restore requires a new target directory. The vector index and job queue are individually consistent, not a single cross-database atomic snapshot. See Backup and Restore.
Structured logging: CLI/service boundaries can emit JSON or human logs. Correlation IDs connect request, job and worker events; common secret-like fields and patterns are redacted. Applications should still avoid logging document contents or credentials. Library applications can opt in at their process boundary:
import logging from automated_document_parser import configure_logging, correlation_context configure_logging("INFO", log_format="json") with correlation_context("batch-2026-001"): logging.getLogger("automated_document_parser").info( "Starting a document batch", extra={"event": "batch_started"} )
Metrics and monitoring: API metrics cover request totals/latency, job enqueue totals, queue states and worker health. The optional Compose profile provisions Prometheus, Grafana, a dashboard and alert rules. Alert delivery requires a separately configured Alertmanager receiver. See Production Monitoring.
Container deployment: the repository includes a non-root image, read-only source mount, health checks and persistent named volumes. The Compose deployment is single-host and single-worker.
Documentation analytics: GA4 is optional for the static documentation site, disabled unless a measurement ID is configured and visitor consent is given. Parser runtime content and ingestion jobs are not sent to GA.
Security boundaries
The parser treats extracted content as untrusted data. It does not execute or
neutralize prompt-injection instructions embedded in documents. If extracted
content is passed to an LLM, keep it separate from system/developer
instructions, enforce tool permissions in application code, use least-privilege
credentials and require approval for consequential actions. File limits, API
path validation, rate limiting and authentication are defense-in-depth controls,
not a substitute for process isolation, TLS, a gateway/WAF or application-level
authorization. See SECURITY.md for the project security policy.
Runnable examples
From the repository root:
python examples/full_workflow.py
The example creates temporary text documents and a temporary SQLite index, then demonstrates compatibility parsing, normalized results, classification, entity/schema extraction, transformations, PII redaction, batch ingestion, hybrid search and retrieval evaluation. It uses local hashing embeddings and requires no API key or model download.
The Jupyter walkthrough is notebook_examples/rag_example.ipynb. It covers
the same core workflow plus optional PDF, API, deployment and monitoring
capabilities. Run it from the repository root after installing the package.
See also
API Reference - generated Python API reference
Retrieval Evaluation and Benchmarks - reproducible evaluation harnesses
Backup and Restore - backup and recovery behavior
Production Monitoring - Prometheus and Grafana deployment
README.md- installation and command examplesSECURITY.md- security policy and reporting