~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
Fix broken path handling for local search on Windows.
Daniel Petti45f610bf823d
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.pyindex c73d38a228..500364642f 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@@ -13,8 +13,8 @@ import picklefrom faiss import normalize_L2from langchain_core.language_models import BaseLLMfrom langchain_community.document_loaders import (- PyPDFLoader,- TextLoader,+ PyPDFLoader,+ TextLoader,UnstructuredMarkdownLoader,UnstructuredWordDocumentLoader,CSVLoader,@@ -40,7 +40,7 @@ logger = logging.getLogger(__name__)class LocalEmbeddingManager:"""Handles embedding generation and storage for local document search"""-+def __init__(self,embedding_model: str = "all-MiniLM-L6-v2",@@ -53,7 +53,7 @@ class LocalEmbeddingManager:):"""Initialize the embedding manager for local document search.-+Args:embedding_model: Name of the embedding model to useembedding_device: Device to run embeddings on ('cpu' or 'cuda')@@ -63,7 +63,7 @@ class LocalEmbeddingManager:chunk_overlap: Overlap between chunkscache_dir: Directory to store embedding cache and index"""-+self.embedding_model = embedding_modelself.embedding_device = embedding_deviceself.embedding_model_type = embedding_model_type@@ -71,29 +71,29 @@ class LocalEmbeddingManager:self.chunk_size = chunk_sizeself.chunk_overlap = chunk_overlapself.cache_dir = Path(cache_dir)-+# Create cache directory if it doesn't existself.cache_dir.mkdir(parents=True, exist_ok=True)-+# Initialize the embedding modelself._embeddings = None-+# Initialize the text splitterself.text_splitter = RecursiveCharacterTextSplitter(- chunk_size=chunk_size,+ chunk_size=chunk_size,chunk_overlap=chunk_overlap)-+# Track indexed folders and their metadataself.indexed_folders = self._load_indexed_folders()-+# Vector store cacheself.vector_stores = {}@propertydef embeddings(self):"""Lazily initialize embeddings when first accessed.- This allows the LocalEmbeddingManager to be created without+ This allows the LocalEmbeddingManager to be created withoutimmediately loading models, which is helpful when no local search is performed."""if self._embeddings is None:@@ -108,7 +108,7 @@ class LocalEmbeddingManager:# Use Ollama for embeddingsif not self.ollama_base_url:self.ollama_base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")-+logger.info(f"Initializing Ollama embeddings with model {self.embedding_model}")return OllamaEmbeddings(model=self.embedding_model,@@ -130,7 +130,7 @@ class LocalEmbeddingManager:def _load_or_create_vector_store(self):"""Load the vector store from disk or create it if needed"""vector_store_path = self._get_vector_store_path()-+# Check if vector store exists and is up to dateif vector_store_path.exists() and not self._check_folders_modified():logger.info(f"Loading existing vector store from {vector_store_path}")@@ -141,84 +141,82 @@ class LocalEmbeddingManager:allow_dangerous_deserialization=True,normalize_L2=True)-+# Add this code to show document countdoc_count = len(vector_store.index_to_docstore_id)logger.info(f"Loaded index with {doc_count} document chunks")-+return vector_storeexcept Exception as e:logger.error(f"Error loading vector store: {e}")logger.info("Will create a new vector store")-+# Create a new vector store- return self._create_vector_store()+ return self._create_vector_store()def _load_indexed_folders(self) -> Dict[str, Dict[str, Any]]:"""Load metadata about indexed folders from disk"""index_metadata_path = self.cache_dir / "index_metadata.json"-+if index_metadata_path.exists():try:with open(index_metadata_path, "r") as f:return json.load(f)except Exception as e:logger.error(f"Error loading index metadata: {e}")-+return {}-+def _save_indexed_folders(self):"""Save metadata about indexed folders to disk"""index_metadata_path = self.cache_dir / "index_metadata.json"-+try:with open(index_metadata_path, "w") as f:json.dump(self.indexed_folders, f, indent=2)except Exception as e:logger.error(f"Error saving index metadata: {e}")-- def _get_folder_hash(self, folder_path: str) -> str:++ @staticmethod+ def get_folder_hash(folder_path: Path) -> str:"""Generate a hash for a folder based on its path"""- # Strip trailing slashes if we have them.- if folder_path.endswith("/"):- folder_path = folder_path[:-1]+ # Canonicalize the path so we don't have weird Windows vs. Linux+ # problems or issues with trailing slashes.+ canonical_folder_path = "/".join(folder_path.parts)+ return hashlib.md5(canonical_folder_path.encode()).hexdigest()- return hashlib.md5(folder_path.encode()).hexdigest()-- def _get_index_path(self, folder_path: str) -> Path:+ def _get_index_path(self, folder_path: Path) -> Path:"""Get the path where the index for a specific folder should be stored"""- folder_hash = self._get_folder_hash(folder_path)+ folder_hash = self.get_folder_hash(folder_path)return self.cache_dir / f"index_{folder_hash}"-- def _check_folder_modified(self, folder_path: str) -> bool:++ def _check_folder_modified(self, folder_path: Path) -> bool:"""Check if a folder has been modified since it was last indexed"""- folder_path = Path(folder_path)-if not folder_path.exists() or not folder_path.is_dir():return False-- folder_hash = self._get_folder_hash(str(folder_path))-++ folder_hash = self.get_folder_hash(folder_path)+# If folder has never been indexed, it's considered modifiedif folder_hash not in self.indexed_folders:return True-+last_indexed = self.indexed_folders[folder_hash].get("last_indexed", 0)-+# Check if any file in the folder has been modified since last indexingfor root, _, files in os.walk(folder_path):for file in files:file_path = Path(root) / fileif file_path.stat().st_mtime > last_indexed:return True-+return False- def _check_config_changed(self, folder_path: str) -> bool:+ def _check_config_changed(self, folder_path: Path) -> bool:"""Checks if the embedding configuration for a folder has been changedsince it was last indexed."""- folder_hash = self._get_folder_hash(folder_path)+ folder_hash = self.get_folder_hash(folder_path)if folder_hash not in self.indexed_folders:# It hasn't been indexed at all. That's a new configuration,@@ -238,12 +236,12 @@ class LocalEmbeddingManager:)return Truereturn False-- def get_file_loader(self, file_path: str) -> Optional[BaseLoader]:++ @staticmethod+ def get_file_loader(file_path: Path) -> Optional[BaseLoader]:"""Get an appropriate document loader for a file based on its extension"""- file_path = Path(file_path)extension = file_path.suffix.lower()-+try:if extension == ".pdf":return PyPDFLoader(str(file_path))@@ -264,38 +262,38 @@ class LocalEmbeddingManager:except Exception as e:logger.error(f"Error creating loader for {file_path}: {e}")return None-+def index_folder(self, folder_path: str, force_reindex: bool = False) -> bool:"""Index all documents in a folder for vector search.-+Args:folder_path: Path to the folder to indexforce_reindex: Whether to force reindexing even if unchanged-+Returns:bool: True if indexing was successful, False otherwise"""folder_path = Path(folder_path)-+# Validate folderif not folder_path.exists():logger.error(f"Folder not found: {folder_path}")return False-+if not folder_path.is_dir():logger.error(f"Path is not a directory: {folder_path}")return False-+folder_str = str(folder_path)- folder_hash = self._get_folder_hash(folder_str)- index_path = self._get_index_path(folder_str)+ folder_hash = self.get_folder_hash(folder_path)+ index_path = self._get_index_path(folder_path)# Check if folder needs to be reindexed- if (not force_reindex and not self._check_folder_modified(folder_str)- and not self._check_config_changed(folder_str)):+ if (not force_reindex and not self._check_folder_modified(folder_path)+ and not self._check_config_changed(folder_path)):logger.info(f"Folder {folder_path} has not been modified since last indexing")-+# Load the vector store from disk if not already loadedif folder_hash not in self.vector_stores:try:@@ -312,55 +310,55 @@ class LocalEmbeddingManager:force_reindex = Trueelse:logger.info(f"Using cached index for {folder_path}")-+# If no reindexing is needed and vector store loaded successfullyif not force_reindex and folder_hash in self.vector_stores:return True-+logger.info(f"Indexing folder: {folder_path}")start_time = time.time()-+# Find documents to indexall_docs = []file_count = 0error_count = 0-+for root, _, files in os.walk(folder_path):for file in files:file_path = Path(root) / file-+# Skip hidden files and directoriesif file.startswith(".") or any(part.startswith(".") for part in file_path.parts):continue-+# Get a loader for this file- loader = self.get_file_loader(str(file_path))-+ loader = self.get_file_loader(file_path)+if loader:try:# Load the documentdocs = loader.load()-+# Add source path metadatafor doc in docs:doc.metadata["source"] = str(file_path)doc.metadata["filename"] = file-+all_docs.extend(docs)file_count += 1except Exception as e:logger.error(f"Error loading {file_path}: {e}")error_count += 1-+if not all_docs:logger.warning(f"No documents found in {folder_path} or all documents failed to load")return False-+# Split documents into chunkslogger.info(f"Splitting {len(all_docs)} documents into chunks")splits = self.text_splitter.split_documents(all_docs)logger.info(f"Created {len(splits)} chunks from {file_count} files")-+# Create vector storelogger.info(f"Creating vector store with {len(splits)} chunks")vector_store = FAISS.from_documents(@@ -368,17 +366,17 @@ class LocalEmbeddingManager:self.embeddings,normalize_L2=True)-+# Save the vector store to disklogger.info(f"Saving index to {index_path}")vector_store.save_local(str(index_path))-+# Update cacheself.vector_stores[folder_hash] = vector_store-+# Update metadataself.indexed_folders[folder_hash] = {- "path": folder_str,+ "path": str(folder_path),"last_indexed": time.time(),"file_count": file_count,"chunk_count": len(splits),@@ -387,72 +385,74 @@ class LocalEmbeddingManager:"chunk_size": self.chunk_size,"chunk_overlap": self.chunk_overlap}-+# Save updated metadataself._save_indexed_folders()-+elapsed_time = time.time() - start_timelogger.info(f"Indexed {file_count} files in {elapsed_time:.2f} seconds")-+return True-+def search(- self,- query: str,+ self,+ query: str,folder_paths: List[str],limit: int = 10,score_threshold: float = 0.0,) -> List[Dict[str, Any]]:"""Search for documents relevant to a query across specified folders.-+Args:query: The search queryfolder_paths: List of folder paths to search inlimit: Maximum number of results to returnscore_threshold: Minimum similarity score threshold-+Returns:List of results with document content and metadata"""+ folder_paths = [Path(p) for p in folder_paths]+# Add detailed debugging for each folderfor folder_path in folder_paths:- folder_hash = self._get_folder_hash(folder_path)+ folder_hash = self.get_folder_hash(folder_path)index_path = self._get_index_path(folder_path)-+logger.info(f"Diagnostic for {folder_path}:")logger.info(f" - Folder hash: {folder_hash}")logger.info(f" - Index path: {index_path}")logger.info(f" - Index exists on disk: {index_path.exists()}")logger.info(f" - Is in indexed_folders: {folder_hash in self.indexed_folders}")-+if folder_hash in self.indexed_folders:meta = self.indexed_folders[folder_hash]logger.info(f" - Metadata: file_count={meta.get('file_count', 0)}, chunk_count={meta.get('chunk_count', 0)}")-+# Validate folders existvalid_folder_paths = []for path in folder_paths:- if os.path.exists(path) and os.path.isdir(path):+ if path.exists() and path.is_dir():valid_folder_paths.append(path)else:logger.warning(f"Skipping non-existent folder in search: {path}")-+# If no valid folders, return empty resultsif not valid_folder_paths:logger.warning(f"No valid folders to search among: {folder_paths}")return []-+all_results = []-+for folder_path in valid_folder_paths:- folder_hash = self._get_folder_hash(folder_path)-+ folder_hash = self.get_folder_hash(folder_path)+# Skip folders that haven't been indexedif folder_hash not in self.indexed_folders:logger.warning(f"Folder {folder_path} has not been indexed")continue-+# Make sure the vector store is loadedif folder_hash not in self.vector_stores:index_path = self._get_index_path(folder_path)@@ -466,10 +466,10 @@ class LocalEmbeddingManager:except Exception as e:logger.error(f"Error loading index for {folder_path}: {e}")continue-+# Search in this foldervector_store = self.vector_stores[folder_hash]-+try:docs_with_scores = (vector_store.similarity_search_with_relevance_scores(@@ -477,58 +477,58 @@ class LocalEmbeddingManager:k=limit))-+for doc, similarity in docs_with_scores:# Skip results below the thresholdif similarity < score_threshold:continue-+result = {"content": doc.page_content,"metadata": doc.metadata,"similarity": float(similarity),"folder": folder_path}-+all_results.append(result)except Exception as e:logger.error(f"Error searching in {folder_path}: {e}")-+# Sort by similarity (highest first)all_results.sort(key=lambda x: x["similarity"], reverse=True)-+# Limit to the requested numberreturn all_results[:limit]-+def clear_cache(self):"""Clear all cached vector stores from memory (not disk)"""self.vector_stores.clear()-+def get_indexed_folders_info(self) -> List[Dict[str, Any]]:"""Get information about all indexed folders"""info = []-+for folder_hash, metadata in self.indexed_folders.items():folder_info = metadata.copy()-+# Add formatted last indexed timeif "last_indexed" in folder_info:folder_info["last_indexed_formatted"] = datetime.fromtimestamp(folder_info["last_indexed"]).strftime("%Y-%m-%d %H:%M:%S")-+# Check if index file exists- index_path = self._get_index_path(folder_info["path"])+ index_path = self._get_index_path(Path(folder_info["path"]))folder_info["index_exists"] = index_path.exists()-+info.append(folder_info)-+return infoclass LocalSearchEngine(BaseSearchEngine):"""Local document search engine with two-phase retrieval"""-+def __init__(self,paths: List[str],@@ -547,7 +547,7 @@ class LocalSearchEngine(BaseSearchEngine):):"""Initialize the local search engine.-+Args:paths: List of folder paths to search inllm: Language model for relevance filtering@@ -565,7 +565,7 @@ class LocalSearchEngine(BaseSearchEngine):"""# Initialize the base search enginesuper().__init__(llm=llm, max_filtered_results=max_filtered_results)-+# Validate folder pathsself.folder_paths = pathsself.valid_folder_paths = []@@ -574,15 +574,15 @@ class LocalSearchEngine(BaseSearchEngine):self.valid_folder_paths.append(path)else:logger.warning(f"Folder not found or is not a directory: {path}")-+# If no valid folders, log a clear messageif not self.valid_folder_paths and paths:logger.warning(f"No valid folders found among: {paths}")logger.warning("This search engine will return no results until valid folders are configured")-+self.max_results = max_resultsself.collections = collections or {"default": {"paths": paths, "description": "Default collection"}}-+# Initialize the embedding manager with only valid foldersself.embedding_manager = LocalEmbeddingManager(embedding_model=embedding_model,@@ -593,52 +593,52 @@ class LocalSearchEngine(BaseSearchEngine):chunk_overlap=chunk_overlap,cache_dir=cache_dir)-+# Index all foldersself._index_folders(force_reindex)-+def _index_folders(self, force_reindex: bool = False):"""Index all valid configured folders"""indexed = []failed = []skipped = []-+# Keep track of invalid foldersfor folder in self.folder_paths:if folder not in self.valid_folder_paths:skipped.append(folder)continue-+success = self.embedding_manager.index_folder(folder, force_reindex)if success:indexed.append(folder)else:failed.append(folder)-+if indexed:logger.info(f"Successfully indexed {len(indexed)} folders: {', '.join(indexed)}")-+if failed:logger.warning(f"Failed to index {len(failed)} folders: {', '.join(failed)}")-+if skipped:logger.warning(f"Skipped {len(skipped)} invalid folders: {', '.join(skipped)}")-+def _get_previews(self, query: str, collection_names: Optional[List[str]] = None) -> List[Dict[str, Any]]:"""Get preview information for documents matching the query.-+Args:query: The search querycollection_names: Specific collections to search within (if None, search all)-+Returns:List of preview dictionaries"""# Determine which collections to searchif collection_names:# Search only in specified collections- collections_to_search = {name: self.collections[name] for name in collection_names+ collections_to_search = {name: self.collections[name] for name in collection_namesif name in self.collections}if not collections_to_search:logger.warning(f"No valid collections found among: {collection_names}")@@ -646,22 +646,22 @@ class LocalSearchEngine(BaseSearchEngine):else:# Search in all collectionscollections_to_search = self.collections-+# Extract all folder paths from the collections to searchsearch_paths = []for collection_config in collections_to_search.values():if "paths" in collection_config:search_paths.extend(collection_config["paths"])-+logger.info(f"Searching local documents in collections: {list(collections_to_search.keys())}")-+# Filter out invalid pathsvalid_search_paths = [path for path in search_paths if path in self.valid_folder_paths]-+if not valid_search_paths:logger.warning(f"No valid folders to search in collections: {list(collections_to_search.keys())}")return []-+# Search across the valid selected foldersraw_results = self.embedding_manager.search(query=query,@@ -669,32 +669,32 @@ class LocalSearchEngine(BaseSearchEngine):limit=self.max_results,score_threshold=0.1 # Skip very low relevance results)-+if not raw_results:logger.info(f"No local documents found for query: {query}")return []-+# Convert to preview formatpreviews = []for i, result in enumerate(raw_results):# Create a unique IDresult_id = f"local-{i}-{hashlib.md5(result['content'][:50].encode()).hexdigest()}"-+# Extract filename and pathsource_path = result['metadata'].get('source', 'Unknown')filename = result['metadata'].get('filename', os.path.basename(source_path))-+# Create preview snippet (first ~200 chars of content)snippet = result['content'][:200] + "..." if len(result['content']) > 200 else result['content']-+# Determine which collection this document belongs tocollection_name = "Unknown"folder_path = result['folder']for name, collection in self.collections.items():- if any(folder_path.startswith(path) for path in collection.get("paths", [])):- collection_name = name+ if any(folder_path.is_relative_to(path) for path in+ collection.get("paths", [])):break-+# Format the previewpreview = {"id": result_id,@@ -702,26 +702,26 @@ class LocalSearchEngine(BaseSearchEngine):"snippet": snippet,"link": source_path,"similarity": result['similarity'],- "folder": folder_path,+ "folder": folder_path.as_posix(),"collection": collection_name,"collection_description": self.collections.get(collection_name, {}).get("description", ""),"_full_content": result['content'], # Store full content for later"_metadata": result['metadata'] # Store metadata for later}-+previews.append(preview)-+logger.info(f"Found {len(previews)} local document matches")return previews-+def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Get full content for the relevant documents.For local search, the full content is already available.-+Args:relevant_items: List of relevant preview dictionaries-+Returns:List of result dictionaries with full content"""@@ -729,52 +729,52 @@ class LocalSearchEngine(BaseSearchEngine):if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:logger.info("Snippet-only mode, skipping full content addition")return relevant_items-+# For local search, we already have the full contentresults = []for item in relevant_items:# Create a copy with full contentresult = item.copy()-+# Add full content if we have itif "_full_content" in item:result["content"] = item["_full_content"]result["full_content"] = item["_full_content"]-+# Remove temporary fieldsif "_full_content" in result:del result["_full_content"]-+# Add metadata if we have itif "_metadata" in item:result["document_metadata"] = item["_metadata"]-+# Remove temporary fieldsif "_metadata" in result:del result["_metadata"]-+results.append(result)-+return results-+def run(self, query: str, collection_names: Optional[List[str]] = None) -> List[Dict[str, Any]]:"""Execute a search using the two-phase approach.-+Args:query: The search querycollection_names: Specific collections to search within (if None, search all)-+Returns:List of search result dictionaries with full content"""logger.info(f"---Execute a search using Local Documents---")-+# Check if we have any special collection parameters in the querycollection_prefix = "collection:"remaining_query = queryspecified_collections = []-+# Parse query for collection specifications like "collection:research_papers query terms"query_parts = query.split()for part in query_parts:@@ -784,71 +784,72 @@ class LocalSearchEngine(BaseSearchEngine):specified_collections.append(collection_name)# Remove this part from the queryremaining_query = remaining_query.replace(part, "", 1).strip()-+# If collections were specified in the query, they override the parameterif specified_collections:collection_names = specified_collectionsquery = remaining_query-+# Phase 1: Get previews (with collection filtering)previews = self._get_previews(query, collection_names)-+if not previews:return []-+# Phase 2: Filter for relevancerelevant_items = self._filter_for_relevance(previews, query)-+if not relevant_items:return []-+# Phase 3: Get full content for relevant itemsif hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:logger.info("Returning snippet-only results as per config")results = relevant_itemselse:results = self._get_full_content(relevant_items)-+# Clean up temporary dataself.embedding_manager.clear_cache()-+return results-+def get_collections_info(self) -> List[Dict[str, Any]]:"""Get information about all collections, including indexing status.-+Returns:List of collection information dictionaries"""collections_info = []-+for name, collection in self.collections.items():paths = collection.get("paths", [])+ paths = [Path(p) for p in paths]description = collection.get("description", "")-+# Get indexing information for each pathpaths_info = []for path in paths:# Check if folder exists- exists = os.path.exists(path) and os.path.isdir(path)-+ exists = path.exists() and path.is_dir()+# Check if folder is indexed- folder_hash = self.embedding_manager._get_folder_hash(path)+ folder_hash = self.embedding_manager.get_folder_hash(path)indexed = folder_hash in self.embedding_manager.indexed_folders-+# Get index details if availableindex_info = {}if indexed:index_info = self.embedding_manager.indexed_folders[folder_hash].copy()-+paths_info.append({"path": path,"exists": exists,"indexed": indexed,"index_info": index_info})-+collections_info.append({"name": name,"description": description,@@ -858,60 +859,60 @@ class LocalSearchEngine(BaseSearchEngine):"chunk_count": sum(info.get("index_info", {}).get("chunk_count", 0) for info in paths_info),"all_indexed": all(info["indexed"] for info in paths_info if info["exists"])})-+return collections_info-+def reindex_collection(self, collection_name: str) -> bool:"""Reindex a specific collection.-+Args:collection_name: Name of the collection to reindex-+Returns:True if reindexing was successful, False otherwise"""if collection_name not in self.collections:logger.error(f"Collection '{collection_name}' not found")return False-+paths = self.collections[collection_name].get("paths", [])success = True-+for path in paths:if not self.embedding_manager.index_folder(path, force_reindex=True):success = False-+return success-+@classmethoddef from_config(cls, config_dict: Dict[str, Any], llm: Optional[BaseLLM] = None) -> "LocalSearchEngine":"""Create a LocalSearchEngine instance from a configuration dictionary.-+Args:config_dict: Configuration dictionaryllm: Language model for relevance filtering-+Returns:Initialized LocalSearchEngine instance"""# Required parametersfolder_paths = []collections = config_dict.get("collections", {})-+# Extract all folder paths from collectionsfor collection_config in collections.values():if "paths" in collection_config:folder_paths.extend(collection_config["paths"])-+# Fall back to folder_paths if no collections definedif not folder_paths:folder_paths = config_dict.get("folder_paths", [])# Create a default collection if using folder_pathsif folder_paths:collections = {"default": {"paths": folder_paths, "description": "Default collection"}}-+# Optional parameters with defaultsmax_results = config_dict.get("max_results", 10)max_filtered_results = config_dict.get("max_filtered_results")@@ -923,7 +924,7 @@ class LocalSearchEngine(BaseSearchEngine):chunk_size = config_dict.get("chunk_size", 1000)chunk_overlap = config_dict.get("chunk_overlap", 200)cache_dir = config_dict.get("cache_dir", ".cache/local_search")-+return cls(paths=folder_paths,collections=collections,