Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Document loaders

LearningCircuitf8b18482cebc
diff --git a/src/local_deep_research/document_loaders/__init__.py b/src/local_deep_research/document_loaders/__init__.py
new file mode 100644
index 0000000000..ad113b1dea
--- /dev/null
+++ b/src/local_deep_research/document_loaders/__init__.py
@@ -0,0 +1,71 @@
+"""
+Document loaders module.
+
+Provides centralized document loading functionality for both:
+- Collection uploads (bytes from HTTP requests)
+- Local search engine (file paths on disk)
+
+Supported formats (35+ formats):
+
+Documents:
+- PDF (.pdf)
+- Text (.txt)
+- Markdown (.md, .markdown)
+- Word (.doc, .docx)
+- RTF (.rtf) - Rich Text Format
+- RST (.rst) - reStructuredText documentation
+
+Presentations:
+- PowerPoint (.ppt, .pptx)
+- ODP (.odp) - OpenDocument presentations
+
+Spreadsheets:
+- Excel (.xls, .xlsx)
+- CSV (.csv), TSV (.tsv)
+- ODT (.odt) - OpenDocument text
+
+Data formats:
+- JSON (.json)
+- YAML (.yaml, .yml)
+- XML (.xml) - important for USPTO patent data
+- TOML (.toml) - config files
+
+Web content:
+- HTML (.html, .htm)
+- MHTML (.mhtml, .mht) - saved web pages
+
+Images (OCR):
+- PNG, JPG, JPEG, TIFF, BMP, HEIC
+
+Research/Notes:
+- Jupyter Notebooks (.ipynb)
+- Evernote exports (.enex)
+- EPUB (.epub) - ebooks (requires pandoc)
+- Org (.org) - Emacs org-mode files
+- Email (.eml) - email messages
+"""
+
+from .bytes_loader import extract_text_from_bytes, load_from_bytes
+from .json_loader import SimpleJSONLoader
+from .loader_registry import (
+ get_loader_class_for_extension,
+ get_loader_for_path,
+ get_supported_extensions,
+ is_extension_supported,
+)
+from .yaml_loader import YAMLLoader
+
+__all__ = [
+ # Bytes loading (for uploads)
+ "load_from_bytes",
+ "extract_text_from_bytes",
+ # Path loading (for local files)
+ "get_loader_for_path",
+ # Registry functions
+ "get_supported_extensions",
+ "is_extension_supported",
+ "get_loader_class_for_extension",
+ # Custom loaders
+ "YAMLLoader",
+ "SimpleJSONLoader",
+]
diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.py
new file mode 100644
index 0000000000..b6e188ded5
--- /dev/null
+++ b/src/local_deep_research/document_loaders/bytes_loader.py
@@ -0,0 +1,167 @@
+"""
+Load documents from bytes content.
+
+This module provides functions to load documents from in-memory bytes,
+which is useful for handling file uploads via HTTP.
+"""
+
+import tempfile
+from pathlib import Path
+from typing import Optional
+
+from langchain_core.documents import Document
+from loguru import logger
+
+from .loader_registry import (
+ get_loader_class_for_extension,
+ is_extension_supported,
+)
+from .yaml_loader import YAMLLoader
+
+
+def load_from_bytes(
+ content: bytes,
+ extension: str,
+ filename: str = "upload",
+ source_url: Optional[str] = None,
+) -> list[Document]:
+ """
+ Load documents from bytes content.
+
+ This function writes the bytes to a temporary file, uses the appropriate
+ LangChain loader, then cleans up the temp file.
+
+ Args:
+ content: File content as bytes
+ extension: File extension (with or without leading dot)
+ filename: Original filename for metadata
+ source_url: Optional source URL for metadata
+
+ Returns:
+ List of Document objects with extracted content
+
+ Raises:
+ ValueError: If the extension is not supported
+ """
+ # Normalize extension
+ ext = (
+ extension.lower()
+ if extension.startswith(".")
+ else f".{extension.lower()}"
+ )
+
+ # Check if extension is supported
+ if not is_extension_supported(ext):
+ raise ValueError(f"Unsupported file extension: {ext}")
+
+ # Handle YAML specially since we have a custom loader
+ if ext in [".yaml", ".yml"]:
+ return _load_yaml_from_bytes(content, filename, source_url)
+
+ # Get the loader class for this extension
+ loader_info = get_loader_class_for_extension(ext)
+ if loader_info is None:
+ raise ValueError(f"No loader found for extension: {ext}")
+
+ loader_class, loader_kwargs = loader_info
+
+ # Create temp file with the content
+ tmp_path = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ suffix=ext, delete=False, prefix="ldr_upload_"
+ ) as tmp:
+ tmp.write(content)
+ tmp_path = tmp.name
+
+ # Create loader and load documents
+ loader = loader_class(tmp_path, **loader_kwargs)
+ documents = loader.load()
+
+ # Add metadata to all documents
+ for doc in documents:
+ doc.metadata["original_filename"] = filename
+ if source_url:
+ doc.metadata["source_url"] = source_url
+
+ logger.info(
+ f"Loaded {len(documents)} document(s) from {filename} ({ext})"
+ )
+ return documents
+
+ except Exception:
+ logger.exception(f"Error loading {filename} ({ext})")
+ raise
+
+ finally:
+ # Clean up temp file
+ if tmp_path:
+ try:
+ Path(tmp_path).unlink(missing_ok=True)
+ except Exception:
+ logger.warning(f"Failed to clean up temp file: {tmp_path}")
+
+
+def _load_yaml_from_bytes(
+ content: bytes,
+ filename: str,
+ source_url: Optional[str] = None,
+) -> list[Document]:
+ """Load YAML from bytes using our custom loader."""
+ tmp_path = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ suffix=".yaml", delete=False, prefix="ldr_upload_"
+ ) as tmp:
+ tmp.write(content)
+ tmp_path = tmp.name
+
+ loader = YAMLLoader(tmp_path)
+ documents = loader.load()
+
+ for doc in documents:
+ doc.metadata["original_filename"] = filename
+ if source_url:
+ doc.metadata["source_url"] = source_url
+
+ return documents
+
+ finally:
+ if tmp_path:
+ try:
+ Path(tmp_path).unlink(missing_ok=True)
+ except Exception:
+ logger.warning(f"Failed to clean up temp file: {tmp_path}")
+
+
+def extract_text_from_bytes(
+ content: bytes,
+ extension: str,
+ filename: str = "upload",
+) -> Optional[str]:
+ """
+ Extract text from bytes content.
+
+ This is a convenience function that loads documents and joins their content.
+
+ Args:
+ content: File content as bytes
+ extension: File extension (with or without leading dot)
+ filename: Original filename for logging
+
+ Returns:
+ Extracted text as string, or None if extraction failed
+ """
+ try:
+ documents = load_from_bytes(content, extension, filename)
+ if documents:
+ return "\n\n".join(
+ doc.page_content for doc in documents if doc.page_content
+ )
+ return None
+ except ValueError as e:
+ logger.warning(f"Unsupported format: {e}")
+ return None
+ except Exception:
+ logger.exception(f"Error extracting text from {filename}")
+ return None
diff --git a/src/local_deep_research/document_loaders/json_loader.py b/src/local_deep_research/document_loaders/json_loader.py
new file mode 100644
index 0000000000..68e2afea18
--- /dev/null
+++ b/src/local_deep_research/document_loaders/json_loader.py
@@ -0,0 +1,153 @@
+"""
+Custom JSON document loader.
+
+This loader reads JSON files and extracts all string values for text search.
+It doesn't require the jq package like LangChain's JSONLoader.
+"""
+
+import json
+from pathlib import Path
+from typing import Any, Iterator
+
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from loguru import logger
+
+
+def extract_strings_from_json(
+ data: Any, path: str = ""
+) -> list[tuple[str, str]]:
+ """
+ Recursively extract all string values from JSON data.
+
+ Returns list of (path, value) tuples where path shows the JSON path.
+ """
+ results = []
+
+ if isinstance(data, str):
+ results.append((path, data))
+ elif isinstance(data, dict):
+ for key, value in data.items():
+ new_path = f"{path}.{key}" if path else key
+ results.extend(extract_strings_from_json(value, new_path))
+ elif isinstance(data, list):
+ for i, item in enumerate(data):
+ new_path = f"{path}[{i}]"
+ results.extend(extract_strings_from_json(item, new_path))
+ # Skip numbers, booleans, None - they're not useful for text search
+
+ return results
+
+
+class SimpleJSONLoader(BaseLoader):
+ """
+ Load JSON files and extract all string values for text search.
+
+ This loader recursively extracts all string values from the JSON structure,
+ making them searchable. Numbers and booleans are skipped.
+ """
+
+ def __init__(
+ self,
+ file_path: str | Path,
+ encoding: str = "utf-8",
+ include_paths: bool = True,
+ ):
+ """
+ Initialize the JSON loader.
+
+ Args:
+ file_path: Path to the JSON file
+ encoding: File encoding (default: utf-8)
+ include_paths: If True, include JSON paths with values (default: True)
+ """
+ self.file_path = Path(file_path)
+ self.encoding = encoding
+ self.include_paths = include_paths
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Lazily load documents from the JSON file.
+
+ Yields:
+ Document objects containing the extracted text
+ """
+ try:
+ with open(self.file_path, encoding=self.encoding) as f:
+ content = f.read()
+
+ try:
+ data = json.loads(content)
+ except json.JSONDecodeError:
+ logger.exception(f"Invalid JSON in {self.file_path}")
+ # Still yield the raw content if parsing fails
+ yield Document(
+ page_content=content,
+ metadata={
+ "source": str(self.file_path),
+ "parse_error": True,
+ },
+ )
+ return
+
+ # Extract all string values
+ string_pairs = extract_strings_from_json(data)
+
+ if self.include_paths:
+ # Format as "path: value" for each string
+ lines = [
+ f"{path}: {value}" for path, value in string_pairs if value
+ ]
+ else:
+ # Just the values
+ lines = [value for _, value in string_pairs if value]
+
+ text = "\n".join(lines)
+
+ yield Document(
+ page_content=text,
+ metadata={
+ "source": str(self.file_path),
+ "file_type": "json",
+ "string_count": len(string_pairs),
+ },
+ )
+
+ except Exception:
+ logger.exception(f"Error loading JSON file: {self.file_path}")
+ raise
+
+ def load(self) -> list[Document]:
+ """Load all documents from the JSON file."""
+ return list(self.lazy_load())
+
+
+def extract_text_from_json(content: bytes, encoding: str = "utf-8") -> str:
+ """
+ Extract text from JSON bytes content.
+
+ This is a convenience function for use with bytes (e.g., from file uploads).
+
+ Args:
+ content: JSON content as bytes
+ encoding: Text encoding (default: utf-8)
+
+ Returns:
+ Extracted text with JSON paths and values
+ """
+ try:
+ text = content.decode(encoding)
+ except UnicodeDecodeError:
+ text = content.decode(encoding, errors="ignore")
+ logger.warning(
+ "JSON content had encoding errors, some characters may be lost"
+ )
+
+ try:
+ data = json.loads(text)
+ string_pairs = extract_strings_from_json(data)
+ lines = [f"{path}: {value}" for path, value in string_pairs if value]
+ return "\n".join(lines)
+ except json.JSONDecodeError:
+ logger.exception("Invalid JSON content")
+ return text
diff --git a/src/local_deep_research/document_loaders/loader_registry.py b/src/local_deep_research/document_loaders/loader_registry.py
new file mode 100644
index 0000000000..1312ec3706
--- /dev/null
+++ b/src/local_deep_research/document_loaders/loader_registry.py
@@ -0,0 +1,413 @@
+"""
+Document loader registry - maps file extensions to LangChain loaders.
+
+This module provides a centralized registry for document loaders that can be used
+by both collection uploads (bytes) and local search (file paths).
+"""
+
+from pathlib import Path
+from typing import Optional
+
+from langchain_community.document_loaders import (
+ CSVLoader,
+ PyPDFLoader,
+ TextLoader,
+ UnstructuredExcelLoader,
+ UnstructuredHTMLLoader,
+ UnstructuredMarkdownLoader,
+ UnstructuredWordDocumentLoader,
+)
+from langchain_core.document_loaders import BaseLoader
+from loguru import logger
+
+# Try to import optional loaders (require unstructured extras)
+try:
+ from langchain_community.document_loaders import UnstructuredODTLoader
+
+ HAS_ODT_LOADER = True
+except ImportError:
+ HAS_ODT_LOADER = False
+ logger.debug("UnstructuredODTLoader not available - ODT support disabled")
+
+try:
+ from langchain_community.document_loaders import UnstructuredODPLoader
+
+ HAS_ODP_LOADER = True
+except ImportError:
+ HAS_ODP_LOADER = False
+ logger.debug("UnstructuredODPLoader not available - ODP support disabled")
+
+try:
+ from langchain_community.document_loaders import (
+ UnstructuredPowerPointLoader,
+ )
+
+ HAS_PPT_LOADER = True
+except ImportError:
+ HAS_PPT_LOADER = False
+ logger.debug(
+ "UnstructuredPowerPointLoader not available - PPT support disabled"
+ )
+
+try:
+ from langchain_community.document_loaders import UnstructuredEPubLoader
+
+ HAS_EPUB_LOADER = True
+except ImportError:
+ HAS_EPUB_LOADER = False
+ logger.debug("UnstructuredEPubLoader not available - EPUB support disabled")
+
+try:
+ from langchain_community.document_loaders import UnstructuredRTFLoader
+
+ HAS_RTF_LOADER = True
+except ImportError:
+ HAS_RTF_LOADER = False
+ logger.debug("UnstructuredRTFLoader not available - RTF support disabled")
+
+try:
+ from langchain_community.document_loaders import UnstructuredXMLLoader
+
+ HAS_XML_LOADER = True
+except ImportError:
+ HAS_XML_LOADER = False
+ logger.debug("UnstructuredXMLLoader not available - XML support disabled")
+
+try:
+ from langchain_community.document_loaders import UnstructuredRSTLoader
+
+ HAS_RST_LOADER = True
+except ImportError:
+ HAS_RST_LOADER = False
+ logger.debug("UnstructuredRSTLoader not available - RST support disabled")
+
+try:
+ from langchain_community.document_loaders import UnstructuredOrgModeLoader
+
+ HAS_ORG_LOADER = True
+except ImportError:
+ HAS_ORG_LOADER = False
+ logger.debug(
+ "UnstructuredOrgModeLoader not available - Org support disabled"
+ )
+
+try:
+ from langchain_community.document_loaders import UnstructuredEmailLoader
+
+ HAS_EMAIL_LOADER = True
+except ImportError:
+ HAS_EMAIL_LOADER = False
+ logger.debug(
+ "UnstructuredEmailLoader not available - Email support disabled"
+ )
+
+try:
+ from langchain_community.document_loaders import UnstructuredImageLoader
+
+ HAS_IMAGE_LOADER = True
+except ImportError:
+ HAS_IMAGE_LOADER = False
+ logger.debug(
+ "UnstructuredImageLoader not available - Image/OCR support disabled"
+ )
+
+try:
+ from langchain_community.document_loaders import NotebookLoader
+
+ HAS_NOTEBOOK_LOADER = True
+except ImportError:
+ HAS_NOTEBOOK_LOADER = False
+ logger.debug(
+ "NotebookLoader not available - Jupyter notebook support disabled"
+ )
+
+try:
+ from langchain_community.document_loaders import EverNoteLoader
+
+ HAS_EVERNOTE_LOADER = True
+except ImportError:
+ HAS_EVERNOTE_LOADER = False
+ logger.debug("EverNoteLoader not available - Evernote support disabled")
+
+try:
+ from langchain_community.document_loaders import TomlLoader
+
+ HAS_TOML_LOADER = True
+except ImportError:
+ HAS_TOML_LOADER = False
+ logger.debug("TomlLoader not available - TOML support disabled")
+
+try:
+ from langchain_community.document_loaders import MHTMLLoader
+
+ HAS_MHTML_LOADER = True
+except ImportError:
+ HAS_MHTML_LOADER = False
+ logger.debug("MHTMLLoader not available - MHTML support disabled")
+
+# Import our custom JSON loader (no jq dependency required)
+from .json_loader import SimpleJSONLoader
+
+
+# Extension to loader mapping
+# Each entry contains:
+# - loader_class: The LangChain loader class
+# - loader_kwargs: Optional kwargs to pass to the loader
+# - requires_path: Whether the loader requires a file path (vs bytes)
+LOADER_REGISTRY: dict = {
+ # PDF
+ ".pdf": {
+ "loader_class": PyPDFLoader,
+ "loader_kwargs": {},
+ },
+ # Plain text
+ ".txt": {
+ "loader_class": TextLoader,
+ "loader_kwargs": {"encoding": "utf-8", "autodetect_encoding": True},
+ },
+ # Markdown
+ ".md": {
+ "loader_class": UnstructuredMarkdownLoader,
+ "loader_kwargs": {},
+ },
+ ".markdown": {
+ "loader_class": UnstructuredMarkdownLoader,
+ "loader_kwargs": {},
+ },
+ # Word documents
+ ".docx": {
+ "loader_class": UnstructuredWordDocumentLoader,
+ "loader_kwargs": {},
+ },
+ ".doc": {
+ "loader_class": UnstructuredWordDocumentLoader,
+ "loader_kwargs": {},
+ },
+ # Spreadsheets
+ ".csv": {
+ "loader_class": CSVLoader,
+ "loader_kwargs": {},
+ },
+ ".xlsx": {
+ "loader_class": UnstructuredExcelLoader,
+ "loader_kwargs": {},
+ },
+ ".xls": {
+ "loader_class": UnstructuredExcelLoader,
+ "loader_kwargs": {},
+ },
+ # HTML
+ ".html": {
+ "loader_class": UnstructuredHTMLLoader,
+ "loader_kwargs": {},
+ },
+ ".htm": {
+ "loader_class": UnstructuredHTMLLoader,
+ "loader_kwargs": {},
+ },
+}
+
+# Add ODT/ODP if available
+if HAS_ODT_LOADER:
+ LOADER_REGISTRY[".odt"] = {
+ "loader_class": UnstructuredODTLoader,
+ "loader_kwargs": {},
+ }
+
+if HAS_ODP_LOADER:
+ LOADER_REGISTRY[".odp"] = {
+ "loader_class": UnstructuredODPLoader,
+ "loader_kwargs": {},
+ }
+
+# PowerPoint presentations
+if HAS_PPT_LOADER:
+ LOADER_REGISTRY[".ppt"] = {
+ "loader_class": UnstructuredPowerPointLoader,
+ "loader_kwargs": {},
+ }
+ LOADER_REGISTRY[".pptx"] = {
+ "loader_class": UnstructuredPowerPointLoader,
+ "loader_kwargs": {},
+ }
+
+# EPUB (ebooks, technical manuals) - requires pandoc
+if HAS_EPUB_LOADER:
+ LOADER_REGISTRY[".epub"] = {
+ "loader_class": UnstructuredEPubLoader,
+ "loader_kwargs": {},
+ }
+
+# RTF (Rich Text Format)
+if HAS_RTF_LOADER:
+ LOADER_REGISTRY[".rtf"] = {
+ "loader_class": UnstructuredRTFLoader,
+ "loader_kwargs": {},
+ }
+
+# XML (important for USPTO patent data)
+if HAS_XML_LOADER:
+ LOADER_REGISTRY[".xml"] = {
+ "loader_class": UnstructuredXMLLoader,
+ "loader_kwargs": {},
+ }
+
+# RST (reStructuredText - Python documentation)
+if HAS_RST_LOADER:
+ LOADER_REGISTRY[".rst"] = {
+ "loader_class": UnstructuredRSTLoader,
+ "loader_kwargs": {},
+ }
+
+# Org-mode files
+if HAS_ORG_LOADER:
+ LOADER_REGISTRY[".org"] = {
+ "loader_class": UnstructuredOrgModeLoader,
+ "loader_kwargs": {},
+ }
+
+# Email files
+if HAS_EMAIL_LOADER:
+ LOADER_REGISTRY[".eml"] = {
+ "loader_class": UnstructuredEmailLoader,
+ "loader_kwargs": {},
+ }
+
+# TSV (Tab-Separated Values) - use CSVLoader with tab delimiter
+LOADER_REGISTRY[".tsv"] = {
+ "loader_class": CSVLoader,
+ "loader_kwargs": {"csv_args": {"delimiter": "\t"}},
+}
+
+# JSON loader using our custom SimpleJSONLoader (no jq dependency)
+LOADER_REGISTRY[".json"] = {
+ "loader_class": SimpleJSONLoader,
+ "loader_kwargs": {},
+}
+
+# Images with OCR support
+if HAS_IMAGE_LOADER:
+ for ext in [".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".heic"]:
+ LOADER_REGISTRY[ext] = {
+ "loader_class": UnstructuredImageLoader,
+ "loader_kwargs": {},
+ }
+
+# Jupyter notebooks (research code, data analysis)
+if HAS_NOTEBOOK_LOADER:
+ LOADER_REGISTRY[".ipynb"] = {
+ "loader_class": NotebookLoader,
+ "loader_kwargs": {
+ "include_outputs": True,
+ "remove_newline": True,
+ },
+ }
+
+# Evernote exports
+if HAS_EVERNOTE_LOADER:
+ LOADER_REGISTRY[".enex"] = {
+ "loader_class": EverNoteLoader,
+ "loader_kwargs": {"load_single_document": False},
+ }
+
+# TOML config files
+if HAS_TOML_LOADER:
+ LOADER_REGISTRY[".toml"] = {
+ "loader_class": TomlLoader,
+ "loader_kwargs": {},
+ }
+
+# MHTML web archives (saved web pages)
+if HAS_MHTML_LOADER:
+ LOADER_REGISTRY[".mhtml"] = {
+ "loader_class": MHTMLLoader,
+ "loader_kwargs": {},
+ }
+ LOADER_REGISTRY[".mht"] = {
+ "loader_class": MHTMLLoader,
+ "loader_kwargs": {},
+ }
+
+# YAML extensions - handled by custom YAMLLoader
+# We add them here for is_extension_supported() checks
+YAML_EXTENSIONS = [".yaml", ".yml"]
+
+
+def get_supported_extensions() -> list[str]:
+ """Get list of all supported file extensions."""
+ return list(LOADER_REGISTRY.keys()) + YAML_EXTENSIONS
+
+
+def is_extension_supported(extension: str) -> bool:
+ """Check if a file extension is supported."""
+ ext = (
+ extension.lower()
+ if extension.startswith(".")
+ else f".{extension.lower()}"
+ )
+ return ext in LOADER_REGISTRY or ext in YAML_EXTENSIONS
+
+
+def get_loader_for_path(file_path: str | Path) -> Optional[BaseLoader]:
+ """
+ Get an appropriate document loader for a file based on its extension.
+
+ Args:
+ file_path: Path to the file to load
+
+ Returns:
+ A LangChain BaseLoader instance, or None if the extension is not supported
+ """
+ file_path = Path(file_path)
+ extension = file_path.suffix.lower()
+
+ # Handle YAML files with our custom loader
+ if extension in YAML_EXTENSIONS:
+ from .yaml_loader import YAMLLoader
+
+ try:
+ return YAMLLoader(str(file_path))
+ except Exception:
+ logger.exception(f"Error creating YAML loader for {file_path}")
+ return None
+
+ if extension not in LOADER_REGISTRY:
+ logger.warning(
+ f"Unsupported file extension: {extension} for {file_path}"
+ )
+ return None
+
+ entry = LOADER_REGISTRY[extension]
+ loader_class = entry["loader_class"]
+ loader_kwargs = entry.get("loader_kwargs", {})
+
+ try:
+ return loader_class(str(file_path), **loader_kwargs)
+ except Exception:
+ logger.exception(f"Error creating loader for {file_path}")
+ return None
+
+
+def get_loader_class_for_extension(
+ extension: str,
+) -> Optional[tuple[type, dict]]:
+ """
+ Get the loader class and kwargs for an extension.
+
+ Args:
+ extension: File extension (with or without leading dot)
+
+ Returns:
+ Tuple of (loader_class, loader_kwargs) or None if not supported
+ """
+ ext = (
+ extension.lower()
+ if extension.startswith(".")
+ else f".{extension.lower()}"
+ )
+
+ if ext not in LOADER_REGISTRY:
+ return None
+
+ entry = LOADER_REGISTRY[ext]
+ return entry["loader_class"], entry.get("loader_kwargs", {})
diff --git a/src/local_deep_research/document_loaders/yaml_loader.py b/src/local_deep_research/document_loaders/yaml_loader.py
new file mode 100644
index 0000000000..4ac294fbb3
--- /dev/null
+++ b/src/local_deep_research/document_loaders/yaml_loader.py
@@ -0,0 +1,125 @@
+"""
+Custom YAML document loader.
+
+LangChain doesn't have a dedicated YAML loader, so we provide one here.
+This loader reads YAML files and converts them to readable text documents.
+"""
+
+from pathlib import Path
+from typing import Iterator
+
+import yaml
+from langchain_core.document_loaders import BaseLoader
+from langchain_core.documents import Document
+from loguru import logger
+
+
+class YAMLLoader(BaseLoader):
+ """
+ Load YAML files and convert to LangChain Documents.
+
+ The YAML content is rendered as formatted YAML text for human readability
+ and semantic search. Complex structures are preserved in their YAML format.
+ """
+
+ def __init__(self, file_path: str | Path, encoding: str = "utf-8"):
+ """
+ Initialize the YAML loader.
+
+ Args:
+ file_path: Path to the YAML file
+ encoding: File encoding (default: utf-8)
+ """
+ self.file_path = Path(file_path)
+ self.encoding = encoding
+
+ def lazy_load(self) -> Iterator[Document]:
+ """
+ Lazily load documents from the YAML file.
+
+ Yields:
+ Document objects containing the YAML content as text
+ """
+ try:
+ with open(self.file_path, encoding=self.encoding) as f:
+ content = f.read()
+
+ # Parse YAML to validate and normalize
+ try:
+ data = yaml.safe_load(content)
+ except yaml.YAMLError:
+ logger.exception(f"Invalid YAML in {self.file_path}")
+ # Still yield the raw content if parsing fails
+ yield Document(
+ page_content=content,
+ metadata={
+ "source": str(self.file_path),
+ "parse_error": True,
+ },
+ )
+ return
+
+ # Convert back to formatted YAML for readability
+ # Use default_flow_style=False for block-style output
+ if data is not None:
+ text = yaml.dump(
+ data,
+ default_flow_style=False,
+ allow_unicode=True,
+ sort_keys=False,
+ )
+ else:
+ text = ""
+
+ yield Document(
+ page_content=text,
+ metadata={
+ "source": str(self.file_path),
+ "file_type": "yaml",
+ },
+ )
+
+ except Exception:
+ logger.exception(f"Error loading YAML file: {self.file_path}")
+ raise
+
+ def load(self) -> list[Document]:
+ """Load all documents from the YAML file."""
+ return list(self.lazy_load())
+
+
+def extract_text_from_yaml(content: bytes, encoding: str = "utf-8") -> str:
+ """
+ Extract text from YAML bytes content.
+
+ This is a convenience function for use with bytes (e.g., from file uploads).
+
+ Args:
+ content: YAML content as bytes
+ encoding: Text encoding (default: utf-8)
+
+ Returns:
+ Formatted YAML text
+ """
+ try:
+ text = content.decode(encoding)
+ except UnicodeDecodeError:
+ text = content.decode(encoding, errors="ignore")
+ logger.warning(
+ "YAML content had encoding errors, some characters may be lost"
+ )
+
+ try:
+ data = yaml.safe_load(text)
+ if data is not None:
+ return yaml.dump(
+ data,
+ default_flow_style=False,
+ allow_unicode=True,
+ sort_keys=False,
+ )
+ return ""
+ except yaml.YAMLError:
+ logger.exception("Invalid YAML content")
+ # Return raw text if parsing fails
+ return text
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index d246f986da..0264a93a7e 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -1355,95 +1355,38 @@ def extract_text_from_file(
"""
Extract text from uploaded file content.
+ Uses the centralized document_loaders module which supports:
+ PDF, TXT, MD, HTML, DOCX, DOC, CSV, XLSX, XLS, JSON, YAML, ODT, ODP
+
Args:
file_content: Raw file content as bytes
- file_type: Type of file (pdf, text, markdown, html, etc.)
+ file_type: Type of file (pdf, txt, markdown, html, docx, csv, etc.)
filename: Original filename for logging
Returns:
Extracted text as string, or None if extraction failed
"""
- try:
- if file_type == "pdf":
- # Use the existing PDF text extraction functionality
- from ..downloaders.base import BaseDownloader
-
- text = BaseDownloader.extract_text_from_pdf(file_content)
- if text:
- logger.info(f"Successfully extracted text from PDF: {filename}")
- return text
- else:
- logger.warning(f"Could not extract text from PDF: {filename}")
- return None
-
- elif file_type in ["text", "txt", "markdown", "md"]:
- # Plain text files - just decode
- try:
- text = file_content.decode("utf-8")
- logger.info(f"Successfully read text file: {filename}")
- return text
- except UnicodeDecodeError:
- # Retry with errors='ignore' (same encoding, but skip invalid bytes)
- try:
- text = file_content.decode("utf-8", errors="ignore")
- logger.warning(
- f"Read text file with encoding errors ignored: {filename}"
- )
- return text
- except Exception:
- logger.exception(f"Failed to decode text file: {filename}")
- return None
-
- elif file_type in ["html", "htm"]:
- # HTML files - extract text content
- try:
- from bs4 import BeautifulSoup
-
- html_content = file_content.decode("utf-8", errors="ignore")
- soup = BeautifulSoup(html_content, "html.parser")
+ from ...document_loaders import extract_text_from_bytes, is_extension_supported
- # Remove script and style elements
- for script in soup(["script", "style"]):
- script.decompose()
-
- # Get text
- text = soup.get_text()
-
- # Clean up whitespace
- lines = (line.strip() for line in text.splitlines())
- chunks = (
- phrase.strip()
- for line in lines
- for phrase in line.split(" ")
- )
- text = "\n".join(chunk for chunk in chunks if chunk)
+ # Map file_type to extension (handle both "pdf" and ".pdf" formats)
+ extension = file_type if file_type.startswith(".") else f".{file_type}"
- logger.info(
- f"Successfully extracted text from HTML: {filename}"
- )
- return text
- except Exception:
- logger.exception(
- f"Failed to extract text from HTML: {filename}"
- )
- return None
+ # Check if the extension is supported
+ if not is_extension_supported(extension):
+ logger.warning(
+ f"Unsupported file type for text extraction: {file_type} ({filename})"
+ )
+ return None
- elif file_type in ["docx", "doc"]:
- # Word documents - would need python-docx library
- logger.warning(
- f"Word document extraction not yet implemented: {filename}"
- )
- return None
+ # Use the document_loaders module to extract text
+ text = extract_text_from_bytes(file_content, extension, filename)
- else:
- logger.warning(
- f"Unsupported file type for text extraction: {file_type} ({filename})"
- )
- return None
+ if text:
+ logger.info(f"Successfully extracted text from {filename} ({file_type})")
+ else:
+ logger.warning(f"Could not extract text from {filename} ({file_type})")
- except Exception:
- logger.exception(f"Error extracting text from {filename}")
- return None
+ return text
@rag_bp.route(
@@ -1590,16 +1533,57 @@ def upload_to_collection(collection_id):
# Create new document
filename = secure_filename(file.filename)
- # Determine file type
+ # Determine file type from extension
+ # Use the extension directly as the file_type
file_extension = Path(filename).suffix.lower()
file_type = {
+ # Documents
".pdf": "pdf",
- ".txt": "text",
- ".md": "markdown",
+ ".txt": "txt",
+ ".md": "md",
+ ".markdown": "md",
".html": "html",
- ".htm": "html",
+ ".htm": "htm",
".docx": "docx",
".doc": "doc",
+ ".odt": "odt",
+ ".odp": "odp",
+ ".rtf": "rtf",
+ ".rst": "rst",
+ # Presentations
+ ".ppt": "ppt",
+ ".pptx": "pptx",
+ # Ebooks
+ ".epub": "epub",
+ # Spreadsheets
+ ".csv": "csv",
+ ".tsv": "tsv",
+ ".xlsx": "xlsx",
+ ".xls": "xls",
+ # Data formats
+ ".json": "json",
+ ".yaml": "yaml",
+ ".yml": "yml",
+ ".xml": "xml",
+ ".toml": "toml",
+ # Images (OCR)
+ ".png": "png",
+ ".jpg": "jpg",
+ ".jpeg": "jpeg",
+ ".tiff": "tiff",
+ ".tif": "tif",
+ ".bmp": "bmp",
+ ".heic": "heic",
+ # Notebooks
+ ".ipynb": "ipynb",
+ # Web archives
+ ".mhtml": "mhtml",
+ ".mht": "mht",
+ # Note exports
+ ".enex": "enex",
+ # Other
+ ".org": "org",
+ ".eml": "eml",
}.get(file_extension, "unknown")
# Extract text from the file
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_local.py b/src/local_deep_research/web_search_engines/engines/search_engine_local.py
index 081ecb57a8..2c61c5ea71 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_local.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_local.py
@@ -11,19 +11,12 @@ from typing import Any, Dict, Iterable, List, Optional
import numpy as np
from faiss import IndexFlatL2
from langchain_community.docstore.in_memory import InMemoryDocstore
-from langchain_community.document_loaders import (
- CSVLoader,
- PyPDFLoader,
- TextLoader,
- UnstructuredExcelLoader,
- UnstructuredMarkdownLoader,
- UnstructuredWordDocumentLoader,
-)
-from langchain_community.document_loaders.base import BaseLoader
+from langchain_community.document_loaders import TextLoader
from langchain_community.embeddings import (
HuggingFaceEmbeddings,
)
from langchain_community.vectorstores import FAISS
+from langchain_core.document_loaders import BaseLoader
from langchain_core.documents import Document
from langchain_core.language_models import BaseLLM
from langchain_text_splitters import RecursiveCharacterTextSplitter
@@ -33,34 +26,30 @@ from ...config import search_config
from ...config.paths import get_cache_directory
from ...database.models.library import DocumentChunk
from ...database.session_context import get_user_db_session
+from ...document_loaders import get_loader_for_path, is_extension_supported
from ...utilities.url_utils import normalize_url
from ..search_engine_base import BaseSearchEngine
def _get_file_loader(file_path: str) -> Optional[BaseLoader]:
- """Get an appropriate document loader for a file based on its extension"""
- file_path = Path(file_path)
- extension = file_path.suffix.lower()
+ """Get an appropriate document loader for a file based on its extension.
+
+ Uses the centralized document_loaders registry which supports:
+ PDF, TXT, MD, HTML, DOCX, DOC, CSV, XLSX, XLS, JSON, YAML, ODT, ODP
+ """
+ file_path_obj = Path(file_path)
+ extension = file_path_obj.suffix.lower()
+
+ # Check if extension is supported by the registry
+ if is_extension_supported(extension):
+ loader = get_loader_for_path(file_path)
+ if loader:
+ return loader
+ # Fallback to TextLoader for unknown extensions
+ logger.warning(f"Unknown file extension for {file_path}, trying TextLoader")
try:
- if extension == ".pdf":
- return PyPDFLoader(str(file_path))
- elif extension == ".txt":
- return TextLoader(str(file_path))
- elif extension in [".md", ".markdown"]:
- return UnstructuredMarkdownLoader(str(file_path))
- elif extension in [".doc", ".docx"]:
- return UnstructuredWordDocumentLoader(str(file_path))
- elif extension == ".csv":
- return CSVLoader(str(file_path))
- elif extension in [".xls", ".xlsx"]:
- return UnstructuredExcelLoader(str(file_path))
- else:
- # Try the text loader as a fallback for unknown extensions
- logger.warning(
- f"Unknown file extension for {file_path}, trying TextLoader"
- )
- return TextLoader(str(file_path), encoding="utf-8")
+ return TextLoader(str(file_path), encoding="utf-8", autodetect_encoding=True)
except Exception:
logger.exception(f"Error creating loader for {file_path}")
return None