Source code for automated_document_parser.processor

"""High-level document processing API."""

from collections.abc import Callable, Iterable, Mapping
from pathlib import Path
from typing import Any

from .core import DocumentParser
from .intelligence import DocumentIntelligence
from .intelligence.extraction import SchemaExtractionBackend
from .intelligence.models import (
    DocumentClassification,
    ExtractedEntity,
    StructuredExtraction,
)
from .models import ParsedDocument
from .retrieval import HybridRetriever, chunk_document_by_tokens
from .retrieval.models import (
    EmbeddingBackend,
    Reranker,
    RetrievalResult,
    Tokenizer,
    VectorStore,
)
from .transformation import (
    DocumentChunk,
    DuplicateReport,
    PIIMatch,
    RedactionResult,
    chunk_document,
    detect_duplicates,
    detect_pii,
    normalize_document,
    redact_document,
)


[docs] class DocumentProcessor: """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. """
[docs] def __init__( self, parser: DocumentParser | None = None, *, intelligence: DocumentIntelligence | None = None, schema_extractor: SchemaExtractionBackend | None = None, ) -> None: self.parser = parser or DocumentParser() self.intelligence = intelligence or DocumentIntelligence(schema_extractor)
[docs] def process( self, file_path: str | Path, *, pdf_loader_method: str = "pypdf", encoding: str = "utf-8", **loader_options: Any, ) -> ParsedDocument: """Parse one file and return its normalised representation.""" documents = self.parser.parse( file_path, pdf_loader_method=pdf_loader_method, encoding=encoding, **loader_options, ) return ParsedDocument.from_documents(documents, file_path)
[docs] def classify( self, document: ParsedDocument, *, top_k: int = 3 ) -> DocumentClassification: """Classify an already parsed document using transparent local rules.""" return self.intelligence.classify(document, top_k=top_k)
[docs] def extract_entities(self, document: ParsedDocument) -> tuple[ExtractedEntity, ...]: """Extract common entities with page and text-span evidence.""" return self.intelligence.extract_entities(document)
[docs] def extract( self, document: ParsedDocument, schema: Mapping[str, Any] ) -> StructuredExtraction: """Extract a JSON-Schema-shaped payload with field-level evidence.""" return self.intelligence.extract(document, schema)
[docs] def chunk( self, document: ParsedDocument, *, max_chars: int = 2000, overlap: int | None = None, respect_element_boundaries: bool = True, ) -> tuple[DocumentChunk, ...]: """Create structure-aware chunks with source offsets and page metadata.""" return chunk_document( document, max_chars=max_chars, overlap=overlap, respect_element_boundaries=respect_element_boundaries, )
[docs] def normalize(self, document: ParsedDocument, **options: Any) -> ParsedDocument: """Return a normalized copy while preserving the original document.""" return normalize_document(document, **options)
[docs] def find_duplicates( self, document: ParsedDocument, *, threshold: float = 0.92, min_chars: int = 20, ) -> DuplicateReport: """Find exact and near-duplicate document elements.""" return detect_duplicates(document, threshold=threshold, min_chars=min_chars)
[docs] def detect_pii( self, document: ParsedDocument, *, categories: Iterable[str] | None = None ) -> tuple[PIIMatch, ...]: """Detect supported PII categories without changing the document.""" return detect_pii(document, categories=categories)
[docs] def redact( self, document: ParsedDocument, *, categories: Iterable[str] | None = None, replacement: str = "[REDACTED]", ) -> RedactionResult: """Return a redacted copy and an audit trail without sensitive values.""" return redact_document(document, categories=categories, replacement=replacement)
[docs] def chunk_by_tokens( self, document: ParsedDocument, *, tokenizer: Tokenizer | Callable[[str], int], max_tokens: int = 512, overlap_tokens: int = 50, ) -> tuple[DocumentChunk, ...]: """Chunk a document to a tokenizer-defined budget.""" return chunk_document_by_tokens( document, tokenizer=tokenizer, max_tokens=max_tokens, overlap_tokens=overlap_tokens, )
[docs] def create_retriever( self, 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: """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. """ return HybridRetriever( tuple(chunks), embedder=embedder, vector_store=vector_store, reranker=reranker, rrf_k=rrf_k, index_embeddings=index_embeddings, )
[docs] def search( self, retriever: HybridRetriever, query: str, *, k: int = 5, candidate_k: int | None = None, ) -> tuple[RetrievalResult, ...]: """Search a previously configured retriever.""" return retriever.search(query, k=k, candidate_k=candidate_k)