"""Local file system loaders (pdf, txt, csv, etc.)."""
import logging
import re
import zipfile
from pathlib import Path, PurePosixPath
from langchain_core.documents import Document
from ..utils import detect_file_type, validate_file_path
from .file_load import (
BaseFileLoader,
CSVFileLoader,
DOCXFileLoader,
HTMLFileLoader,
JSONFileLoader,
TextFileLoader,
)
from .pdf_load import PDFLoader, PDFLoaderMethod
from .security import DEFAULT_FILE_RESOURCE_LIMITS, FileResourceLimits
logger = logging.getLogger(__name__)
[docs]
class FileLoader:
"""Automated file loader that detects file type and loads documents."""
[docs]
def __init__(
self,
file_path: str | Path,
pdf_loader_method: PDFLoaderMethod = "pypdf",
encoding: str = "utf-8",
jq_schema: str = ".",
text_content: bool = False,
resource_limits: FileResourceLimits | None = DEFAULT_FILE_RESOURCE_LIMITS,
**pdf_loader_kwargs,
):
"""
Initialize the FileLoader.
Args:
file_path: Path to the file to load
pdf_loader_method: Method to use for PDF loading.
encoding: Text, CSV, HTML and JSON file encoding.
jq_schema: Optional jq expression for selecting JSON values.
text_content: Treat selected JSON strings as plain text.
resource_limits: Preflight file and DOCX archive limits. Defaults to
``FileResourceLimits()``; pass ``None`` to disable all limits.
**pdf_loader_kwargs: Additional keyword arguments for the selected PDF backend.
Raises:
FileNotFoundError: If file doesn't exist
ValueError: If file type is unsupported
"""
self.file_path = validate_file_path(file_path)
self.file_type = detect_file_type(self.file_path)
self.pdf_loader_method = pdf_loader_method
self.encoding = encoding
self.jq_schema = jq_schema
self.text_content = text_content
if resource_limits is not None and not isinstance(
resource_limits, FileResourceLimits
):
raise TypeError("resource_limits must be FileResourceLimits or None")
self.resource_limits = resource_limits
self.pdf_loader_kwargs = pdf_loader_kwargs
if self.file_type is None:
raise ValueError(
f"Unsupported file type: {self.file_path.suffix}. "
f"File: {self.file_path}"
)
logger.info(f"Initialized loader for {self.file_type} file: {self.file_path}")
if self.file_type == "pdf":
logger.info(f"PDF loader method: {pdf_loader_method}")
[docs]
def load(self) -> list[Document]:
"""
Load documents from the file.
Returns:
List of LangChain Document objects
Raises:
RuntimeError: If loading fails
"""
try:
self._validate_resource_limits()
loader = self._get_loader()
documents = loader.load()
logger.info(
f"Successfully loaded {len(documents)} documents from {self.file_path}"
)
return documents
except (ImportError, ValueError, FileNotFoundError):
logger.exception("Unable to load file %s", self.file_path)
raise
except RuntimeError:
logger.exception("Loader failed for %s", self.file_path)
raise
except Exception as exc:
logger.exception("Unexpected error loading file %s", self.file_path)
raise RuntimeError(f"Failed to load file: {exc}") from exc
def _validate_resource_limits(self) -> None:
"""Reject oversized or suspicious DOCX inputs before parsing."""
limits = self.resource_limits
if limits is None:
return
file_size = self.file_path.stat().st_size
if (
limits.max_file_size_bytes is not None
and file_size > limits.max_file_size_bytes
):
raise ValueError(
f"File exceeds max_file_size_bytes ({limits.max_file_size_bytes})"
)
if self.file_type != "docx":
return
try:
with zipfile.ZipFile(self.file_path) as archive:
members = archive.infolist()
if (
limits.max_docx_members is not None
and len(members) > limits.max_docx_members
):
raise ValueError(
f"DOCX archive exceeds max_docx_members "
f"({limits.max_docx_members})"
)
total_uncompressed = 0
seen_names: set[str] = set()
for member in members:
normalized_name = member.filename.replace("\\", "/")
path = PurePosixPath(normalized_name)
if (
path.is_absolute()
or ".." in path.parts
or re.match(r"^[A-Za-z]:", normalized_name)
):
raise ValueError("DOCX archive contains an unsafe member path")
if normalized_name in seen_names:
raise ValueError("DOCX archive contains duplicate member paths")
seen_names.add(normalized_name)
if member.flag_bits & 0x1:
raise ValueError(
"Encrypted DOCX archive members are not supported"
)
total_uncompressed += member.file_size
if (
limits.max_docx_compression_ratio is not None
and member.file_size > 0
):
ratio = member.file_size / max(member.compress_size, 1)
if ratio > limits.max_docx_compression_ratio:
raise ValueError(
"DOCX archive member exceeds max_docx_compression_ratio "
f"({limits.max_docx_compression_ratio})"
)
if (
limits.max_docx_uncompressed_bytes is not None
and total_uncompressed > limits.max_docx_uncompressed_bytes
):
raise ValueError(
"DOCX archive exceeds max_docx_uncompressed_bytes "
f"({limits.max_docx_uncompressed_bytes})"
)
except zipfile.BadZipFile as exc:
raise ValueError("DOCX file is not a valid ZIP archive") from exc
except OSError as exc:
raise ValueError(f"Unable to inspect DOCX archive: {exc}") from exc
def _get_loader(self) -> BaseFileLoader | PDFLoader:
"""
Get the appropriate built-in or optional PDF backend for the file type.
Returns:
A loader that returns LangChain Document objects.
"""
# Special handling for PDF files with configurable method
if self.file_type == "pdf":
return PDFLoader(
self.file_path,
method=self.pdf_loader_method,
**self.pdf_loader_kwargs,
)
# Other file type loaders
loaders = {
"text": lambda: TextFileLoader(self.file_path, encoding=self.encoding),
"csv": lambda: CSVFileLoader(self.file_path, encoding=self.encoding),
"json": lambda: JSONFileLoader(
self.file_path,
encoding=self.encoding,
jq_schema=self.jq_schema,
text_content=self.text_content,
),
"docx": lambda: DOCXFileLoader(self.file_path),
"html": lambda: HTMLFileLoader(self.file_path, encoding=self.encoding),
}
if self.file_type not in loaders:
raise ValueError(f"No loader available for file type: {self.file_type}")
return loaders[self.file_type]()
[docs]
def load_document(
file_path: str | Path,
pdf_loader_method: PDFLoaderMethod = "pypdf",
encoding: str = "utf-8",
jq_schema: str = ".",
text_content: bool = False,
resource_limits: FileResourceLimits | None = DEFAULT_FILE_RESOURCE_LIMITS,
**pdf_loader_kwargs,
) -> list[Document]:
"""
Convenience function to load a document from a file.
Args:
file_path: Path to the file
pdf_loader_method: Method to use for PDF loading.
encoding: Text, CSV, HTML and JSON file encoding.
jq_schema: Optional jq expression for selecting JSON values.
text_content: Treat selected JSON strings as plain text.
resource_limits: Preflight file and DOCX archive limits. Defaults to
``FileResourceLimits()``; pass ``None`` to disable all limits.
**pdf_loader_kwargs: Additional keyword arguments for the selected PDF backend.
Returns:
List of LangChain Document objects
Examples:
>>> # Load a text file
>>> documents = load_document("path/to/file.txt")
>>> # Load a PDF with default PyPDF
>>> documents = load_document("path/to/file.pdf")
>>> # Load a PDF with Unstructured
>>> documents = load_document("path/to/file.pdf", pdf_loader_method="unstructured")
>>> # Load a PDF with Amazon Textract
>>> import boto3
>>> client = boto3.client("textract", region_name="us-east-2")
>>> documents = load_document(
... "s3://bucket/file.pdf",
... pdf_loader_method="amazon_textract",
... client=client
... )
"""
loader = FileLoader(
file_path,
pdf_loader_method=pdf_loader_method,
encoding=encoding,
jq_schema=jq_schema,
text_content=text_content,
resource_limits=resource_limits,
**pdf_loader_kwargs,
)
return loader.load()