Loaders¶
Read a file or a URL into text. PDF needs no extra; OCR needs contractex[ocr], URLs need contractex[network].
AutoLoader ¶
Bases: DocumentLoader
Auto-detecting document loader that chooses the appropriate loader based on file extension.
__init__(**loader_kwargs: Any) -> None ¶
Initialize auto loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**loader_kwargs | Any | Keyword arguments for the specific loaders; each loader receives the ones its constructor accepts (e.g. | {} |
Raises:
| Type | Description |
|---|---|
TypeError | If no loader accepts one of the keyword arguments |
load(source: str) -> str ¶
Auto-detect file type and load document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to document | required |
Returns:
| Type | Description |
|---|---|
str | Extracted text content |
Raises:
| Type | Description |
|---|---|
UnsupportedFileTypeError | If file type is not supported |
DocumentLoadError | If loading fails |
get_metadata(source: str) -> dict[str, Any] ¶
Get metadata using appropriate loader.
supports(file_path: str) -> bool ¶
Check if any loader supports this file.
PDFLoader ¶
Bases: DocumentLoader
PDF document loader using pypdfium2, the Python binding for Google's PDFium.
Extracts the text layer of each page; pages are joined with a blank line. Scanned pages have no text layer: with ocr_enabled=True those pages are rendered at 300 dpi and passed to Tesseract (contractex[ocr]).
__init__(ocr_enabled: bool = False, preserve_layout: bool = False, extract_images: bool = False) ¶
Initialize PDF loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ocr_enabled | bool | OCR pages that have no text layer (needs contractex[ocr]) | False |
preserve_layout | bool | Order text runs top-to-bottom, left-to-right by position instead of content-stream order | False |
extract_images | bool | Extract images from PDF (not implemented) | False |
load(source: str) -> str ¶
Load PDF and extract text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to PDF file | required |
Returns:
| Type | Description |
|---|---|
str | Extracted text content |
Raises:
| Type | Description |
|---|---|
DocumentLoadError | If loading fails |
get_metadata(source: str) -> dict[str, Any] ¶
Get PDF metadata.
supports(file_path: str) -> bool ¶
Check if file is a PDF.
DOCXLoader ¶
Bases: DocumentLoader
DOCX document loader using python-docx.
Supports Microsoft Word .docx files. Paragraphs and tables come out in reading order; table rows are joined with " | " and a merged cell appears once.
__init__(include_headers: bool = True, include_footers: bool = True) ¶
Initialize DOCX loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_headers | bool | Include header text | True |
include_footers | bool | Include footer text | True |
load(source: str) -> str ¶
Load DOCX and extract text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to DOCX file | required |
Returns:
| Type | Description |
|---|---|
str | Extracted text content |
Raises:
| Type | Description |
|---|---|
DocumentLoadError | If loading fails |
get_metadata(source: str) -> dict[str, Any] ¶
Get DOCX metadata.
supports(file_path: str) -> bool ¶
Check if file is a DOCX.
TextLoader ¶
Bases: DocumentLoader
Plain text document loader.
Loads .txt files directly as-is. Useful for testing and contracts already extracted from other sources.
__init__(encoding: str = 'utf-8') ¶
Initialize text loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoding | str | Text file encoding (default: utf-8) | 'utf-8' |
load(source: str) -> str ¶
Load plain text file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to text file | required |
Returns:
| Type | Description |
|---|---|
str | Text content |
Raises:
| Type | Description |
|---|---|
DocumentLoadError | If loading fails |
get_metadata(source: str) -> dict[str, Any] ¶
Get text file metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to text file | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dictionary with file metadata |
DocumentLoader ¶
Bases: ABC
Abstract base class for document loaders.
load(source: str) -> str abstractmethod ¶
Load a document and return its text content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to the document or other source identifier | required |
Returns:
| Type | Description |
|---|---|
str | Extracted text content |
Raises:
| Type | Description |
|---|---|
DocumentLoadError | If loading fails |
load_with_metadata(source: str) -> dict[str, Any] ¶
Load a document and return text with metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to the document | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dictionary with 'text' and 'metadata' keys |
get_metadata(source: str) -> dict[str, Any] ¶
Get metadata about the document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path to the document | required |
Returns:
| Type | Description |
|---|---|
dict[str, Any] | Dictionary of metadata |
supports(file_path: str) -> bool ¶
Check if this loader supports the given file type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path | str | Path to check | required |
Returns:
| Type | Description |
|---|---|
bool | True if this loader can handle the file |
URLLoader ¶
Bases: SourceAdapter
Load documents from arbitrary HTTP/HTTPS URLs.
Supports: * HTML pages โ stripped to readable plain text via stdlib html.parser * Plain text / JSON responses โ returned as-is * PDF URLs โ downloaded and parsed via pypdfium2 * Conditional GET using ETag / Last-Modified headers
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout | int | HTTP request timeout in seconds. | 30 |
max_retries | int | Number of retry attempts on transient errors. | 3 |
backoff_factor | float | Base for exponential backoff between retries. | 1.5 |
strip_html | bool | Convert HTML bodies to plain text (default True). | True |
headers | dict[str, str] | None | Extra HTTP headers sent with every request. They may hold credentials, so with them a redirect to another host is refused. | None |
fetch(source: str, cache: FetchCache | None = None) -> FetchResult ¶
Fetch source URL with conditional-GET support.
APILoader ¶
Bases: SourceAdapter
Load documents from JSON REST APIs.
Handles: * Bearer token / API key authentication via auth_header * Fixed query parameters via params * Text extraction from a dot-separated JSON field path (e.g. "data.opinion.text") * Pagination via RFC 5988 Link headers or common next / next_url keys. A relative link is resolved against the current page. A link to another host is fetched without the auth header and query parameters; a page that fails raises DocumentLoadError rather than returning the pages so far.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text_field | str | Dot-separated path to the text value in the JSON response. Defaults to | 'text' |
auth_header | str | None | Full | None |
params | dict[str, str] | None | Extra query parameters appended to every request. | None |
paginate | bool | Follow pagination (Link header or | False |
max_pages | int | Maximum pages to fetch (guard against runaway pagination). | 10 |
timeout | int | HTTP request timeout in seconds. | 30 |
max_retries | int | Number of retry attempts. | 3 |
fetch(source: str, cache: FetchCache | None = None) -> FetchResult ¶
Fetch JSON API endpoint and extract text content.
SourceAdapter ¶
Bases: DocumentLoader
Abstract base for network-aware document loaders.
Adds on top of DocumentLoader:
- ETag / Last-Modified change detection via
changed_since() - Exponential-backoff retry via
_retry() - Content hashing for deduplication
Subclasses must implement fetch(source, cache). The load() method delegates to fetch() so the adapter is compatible with every place that accepts a DocumentLoader.
fetch(source: str, cache: FetchCache | None = None) -> FetchResult abstractmethod ¶
Fetch content from a remote source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | URL or API endpoint identifier. | required |
cache | FetchCache | None | Optional prior cache state for conditional GET. | None |
Returns:
| Type | Description |
|---|---|
FetchResult | FetchResult with content and headers. If the server signals |
FetchResult | 304 Not Modified, |
FetchResult |
|
load(source: str) -> str ¶
Fetch the source and return its text content.
load_with_metadata(source: str) -> dict[str, Any] ¶
Fetch with full provenance metadata.
changed_since(source: str, cache: FetchCache) -> bool ¶
Return True if the source has new content since cache was recorded.
Prefers ETag / Last-Modified when available; falls back to content hash comparison.
FetchResult dataclass ¶
Result of a single remote fetch.
to_cache() -> FetchCache ¶
Convert result to a FetchCache for the next request.
FetchCache dataclass ¶
Cached state from a previous fetch, used for change detection.
LangChainDocumentAdapter ¶
Bases: DocumentLoader
Adapter to use LangChain document loaders with Contractex.
This allows using any LangChain document loader (PDF, HTML, web scrapers, etc.) with the Contractex extraction pipeline.
Requires: pip install langchain or pip install langchain-core
__init__(langchain_loader: Any) ¶
Initialize adapter with a LangChain document loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
langchain_loader | Any | Any LangChain document loader instance (e.g., PyPDFLoader, UnstructuredPDFLoader, etc.) | required |
Raises:
| Type | Description |
|---|---|
ImportError | If langchain is not installed |
load(source: str) -> str ¶
Load document using LangChain loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path or URL to load | required |
Returns:
| Type | Description |
|---|---|
str | Concatenated text from all pages/chunks |
Raises:
| Type | Description |
|---|---|
DocumentLoadError | If loading fails |
get_metadata(source: str) -> dict ¶
Get metadata from LangChain documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source | str | Path or URL (not used, metadata comes from loaded documents) | required |
Returns:
| Type | Description |
|---|---|
dict | Combined metadata dictionary from all loaded documents |