~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
refactor: address code review feedback - session management, method extraction, and configurability
LearningCircuitc0357fee2201
diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.jsonindex 3a7951840f..1061ebe7bf 100644--- a/src/local_deep_research/defaults/research_library/library_settings.json+++ b/src/local_deep_research/defaults/research_library/library_settings.json@@ -58,5 +58,19 @@"value": false,"visible": true,"env_var": "RESEARCH_LIBRARY_ENABLE_TXT_STORAGE"+ },+ "rag.indexing_batch_size": {+ "category": "research_library",+ "description": "Number of documents to process in parallel during RAG indexing. Higher values are faster but use more memory.",+ "editable": true,+ "max_value": 50,+ "min_value": 1,+ "name": "RAG Indexing Batch Size",+ "options": null,+ "step": 5,+ "type": "APP",+ "ui_element": "number",+ "value": 15,+ "visible": true}}diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 280c8f304a..bc47e4574a 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -329,7 +329,11 @@ def index_all():total = len(doc_info)# Process documents in batches to optimize performance- batch_size = 15 # Process max 15 documents at a time+ # Get batch size from settings+ settings = get_settings_manager()+ batch_size = int(+ settings.get_setting("rag.indexing_batch_size", 15)+ )processed = 0for i in range(0, len(doc_info), batch_size):diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex a436d5acfd..63b8d82273 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -760,258 +760,264 @@ class DownloadService:if not resource:return False, "Resource not found"- # Check if text document already exists in database- existing_text = (- session.query(LibraryTextDocument)- .filter_by(resource_id=resource_id)- .first()+ # Try existing text in database+ result = self._try_existing_text(session, resource_id)+ if result is not None:+ return result++ # Try legacy text files on disk+ result = self._try_legacy_text_file(session, resource, resource_id)+ if result is not None:+ return result++ # Try extracting from existing PDF+ result = self._try_existing_pdf_extraction(+ session, resource, resource_id, save_files)+ if result is not None:+ return result- if existing_text and existing_text.extraction_status == "completed":- # Check if file still exists- logger.warning(- f"[TEXT_EXTRACTION] Checking existing text: library_root={self.library_root}, file_path={existing_text.file_path}"- )+ # Try API text extraction+ result = self._try_api_text_extraction(+ session, resource, save_files+ )+ if result is not None:+ return result++ # Fallback: Download PDF and extract+ return self._fallback_pdf_extraction(session, resource, save_files)++ def _try_existing_text(+ self, session, resource_id: int+ ) -> Optional[Tuple[bool, Optional[str]]]:+ """Check if text already exists in database."""+ existing_text = (+ session.query(LibraryTextDocument)+ .filter_by(resource_id=resource_id)+ .first()+ )- if self.library_root is None:- logger.error(- "[TEXT_EXTRACTION] CRITICAL: self.library_root is None!"- )- raise ValueError(- "DownloadService not properly initialized - library_root is None"- )+ if not existing_text or existing_text.extraction_status != "completed":+ return None- if existing_text.file_path is None:- logger.warning(- "[TEXT_EXTRACTION] existing_text.file_path is None, treating as not existing"- )- text_path = None- else:- text_path = (- Path(self.library_root) / existing_text.file_path- )- if text_path and text_path.exists():- logger.info(- f"Text file already exists (from DB): {existing_text.file_path}"- )- # Update last accessed time- existing_text.last_accessed = datetime.now(UTC)- session.commit()- return True, None- elif text_path is None:- logger.warning(- "[TEXT_EXTRACTION] Text file path is None, treating as missing and will re-extract"- )- # Mark as failed so it can be re-extracted- existing_text.extraction_status = "failed"- existing_text.extraction_error = (- "File path is None in database"- )- session.commit()- # Fall through to re-extraction- else:- logger.warning(- f"Text file in DB but missing on disk: {existing_text.file_path}"- )- # Mark as failed so it can be re-extracted- existing_text.extraction_status = "failed"- existing_text.extraction_error = "File missing on disk"- session.commit()+ logger.debug(+ f"Checking existing text: library_root={self.library_root}, file_path={existing_text.file_path}"+ )- # Check if we already have the text file on disk (legacy)- txt_path = Path(self.library_root) / "txt"- existing_files = (- list(txt_path.glob(f"*_{resource_id}.txt"))- if txt_path.exists()- else []+ if self.library_root is None:+ logger.error("CRITICAL: self.library_root is None!")+ raise ValueError(+ "DownloadService not properly initialized - library_root is None")- if existing_files:- logger.info(- f"Text file already exists on disk: {existing_files[0]}"- )- # Add to database- self._create_text_document_record(- session,- resource,- existing_files[0],- extraction_method="unknown",- extraction_source="legacy_file",- )- session.commit()- return True, None- # Check if we have an existing PDF document in database- pdf_document = (- session.query(LibraryDocument)- .filter_by(resource_id=resource_id)- .first()+ # Check if file exists+ if existing_text.file_path is None:+ text_path = None+ else:+ text_path = Path(self.library_root) / existing_text.file_path++ if text_path and text_path.exists():+ logger.info(+ f"Text file already exists (from DB): {existing_text.file_path}")+ existing_text.last_accessed = datetime.now(UTC)+ session.commit()+ return True, None- if pdf_document and pdf_document.download_status == "completed":- pdf_path = Path(self.library_root) / pdf_document.file_path- if pdf_path.exists():- logger.info(- f"Found existing PDF, extracting text from: {pdf_path}"- )- try:- with open(pdf_path, "rb") as f:- pdf_content = f.read()- text = self._extract_text_from_pdf(pdf_content)- if text:- try:- text_path = self._save_text_with_db(- resource,- text,- session,- extraction_method="pdf_extraction",- extraction_source="pdfplumber",- pdf_document_id=pdf_document.id,- save_files=save_files,- )- # Success! text_path may be None (DB-only) or a path (DB + file)- session.commit()- return True, None- except Exception as e:- logger.exception(- f"Failed to save text for resource {resource.id}"- )- return False, f"Failed to save text: {str(e)}"- except Exception:- logger.exception(- f"Failed to extract text from existing PDF: {pdf_path}"- )- # Fall through to download new content+ # File missing - mark for re-extraction+ logger.debug(+ f"Text file in DB but missing on disk: {existing_text.file_path}"+ )+ existing_text.extraction_status = "failed"+ existing_text.extraction_error = (+ "File path is None in database"+ if text_path is None+ else "File missing on disk"+ )+ session.commit()+ return None # Fall through to re-extraction++ def _try_legacy_text_file(+ self, session, resource, resource_id: int+ ) -> Optional[Tuple[bool, Optional[str]]]:+ """Check for legacy text files on disk."""+ txt_path = Path(self.library_root) / "txt"+ existing_files = (+ list(txt_path.glob(f"*_{resource_id}.txt"))+ if txt_path.exists()+ else []+ )- # Try to get text content directly without saving PDF- logger.info(- f"[TEXT_EXTRACTION] Attempting direct API text extraction from: {resource.url}"+ if not existing_files:+ return None++ logger.info(f"Text file already exists on disk: {existing_files[0]}")+ self._create_text_document_record(+ session,+ resource,+ existing_files[0],+ extraction_method="unknown",+ extraction_source="legacy_file",+ )+ session.commit()+ return True, None++ def _try_existing_pdf_extraction(+ self, session, resource, resource_id: int, save_files: bool+ ) -> Optional[Tuple[bool, Optional[str]]]:+ """Try extracting text from existing PDF in database."""+ pdf_document = (+ session.query(LibraryDocument)+ .filter_by(resource_id=resource_id)+ .first()+ )++ if not pdf_document or pdf_document.download_status != "completed":+ return None++ pdf_path = Path(self.library_root) / pdf_document.file_path+ if not pdf_path.exists():+ return None++ logger.info(f"Found existing PDF, extracting text from: {pdf_path}")+ try:+ with open(pdf_path, "rb") as f:+ pdf_content = f.read()+ text = self._extract_text_from_pdf(pdf_content)++ if not text:+ return None++ self._save_text_with_db(+ resource,+ text,+ session,+ extraction_method="pdf_extraction",+ extraction_source="pdfplumber",+ pdf_document_id=pdf_document.id,+ save_files=save_files,+ )+ session.commit()+ return True, None++ except Exception:+ logger.exception(+ f"Failed to extract text from existing PDF: {pdf_path}")+ return None # Fall through to other methods- # Determine which downloader to use- downloader = self._get_downloader(resource.url)+ def _try_api_text_extraction(+ self, session, resource, save_files: bool+ ) -> Optional[Tuple[bool, Optional[str]]]:+ """Try direct API text extraction."""+ logger.info(+ f"Attempting direct API text extraction from: {resource.url}"+ )- if downloader:- # Use the downloader's text extraction capability- result = downloader.download_with_result(- resource.url, ContentType.TEXT- )+ downloader = self._get_downloader(resource.url)+ if not downloader:+ return None- if result.is_success and result.content:- # Decode if bytes- if isinstance(result.content, bytes):- text = result.content.decode("utf-8", errors="ignore")- else:- text = result.content-- # Determine extraction method based on downloader type- extraction_method = "native_api"- extraction_source = "unknown"- if isinstance(downloader, ArxivDownloader):- extraction_source = "arxiv_api"- elif isinstance(downloader, PubMedDownloader):- extraction_source = "pubmed_api"-- # Save text file with database record- try:- text_path = self._save_text_with_db(- resource,- text,- session,- extraction_method=extraction_method,- extraction_source=extraction_source,- save_files=save_files,- )- # Success! text_path may be None (DB-only) or a path (DB + file)- session.commit()- logger.info(- f"[TEXT_EXTRACTION] ✓ SUCCESS: Got text from {extraction_source.upper()} API for '{resource.title[:50]}...' | {resource.url}"- )- return True, None- except Exception as e:- logger.exception(- f"Failed to save text for resource {resource.id}"- )- return False, f"Failed to save text: {str(e)}"+ result = downloader.download_with_result(resource.url, ContentType.TEXT)- # Fallback: Download PDF to memory only and extract text (no disk storage)- logger.info(- f"[TEXT_EXTRACTION] API text extraction failed, falling back to in-memory PDF download for: {resource.url}"+ if not result.is_success or not result.content:+ return None++ # Decode text content+ text = (+ result.content.decode("utf-8", errors="ignore")+ if isinstance(result.content, bytes)+ else result.content+ )++ # Determine extraction source+ extraction_source = "unknown"+ if isinstance(downloader, ArxivDownloader):+ extraction_source = "arxiv_api"+ elif isinstance(downloader, PubMedDownloader):+ extraction_source = "pubmed_api"++ try:+ self._save_text_with_db(+ resource,+ text,+ session,+ extraction_method="native_api",+ extraction_source=extraction_source,+ save_files=save_files,)+ session.commit()logger.info(- "[TEXT_EXTRACTION] PDF will be processed in memory only - no disk storage"+ f"✓ SUCCESS: Got text from {extraction_source.upper()} API for '{resource.title[:50]}...'")+ return True, None+ except Exception as e:+ logger.exception(f"Failed to save text for resource {resource.id}")+ return False, f"Failed to save text: {str(e)}"- # Use downloader to get PDF content- downloader = self._get_downloader(resource.url)- if downloader:- result = downloader.download_with_result(- resource.url, ContentType.PDF- )+ def _fallback_pdf_extraction(+ self, session, resource, save_files: bool+ ) -> Tuple[bool, Optional[str]]:+ """Fallback: Download PDF to memory and extract text."""+ logger.info(+ f"API text extraction failed, falling back to in-memory PDF download for: {resource.url}"+ )- if result.is_success and result.content:- # Extract text from PDF (without saving the PDF)- text = self._extract_text_from_pdf(result.content)- if text:- # Save text file with database record- # Returns file path if saved to disk, None if DB-only mode- # Raises exception if save fails- try:- text_path = self._save_text_with_db(- resource,- text,- session,- extraction_method="pdf_extraction",- extraction_source="pdfplumber_fallback",- save_files=save_files,- )- # Success! text_path may be None (DB-only) or a path (DB + file)- session.commit()- logger.info(- f"[TEXT_EXTRACTION] ✓ SUCCESS: Extracted text from '{resource.title[:50]}...' | {resource.url}"- )- return True, None- except Exception as e:- logger.exception(- f"Failed to save text for resource {resource.id}"- )- return False, f"Failed to save text: {str(e)}"- else:- logger.warning(- f"[TEXT_EXTRACTION] Failed to extract text from PDF for: {resource.url}"- )- error_msg = "PDF text extraction returned empty text"- self._record_failed_text_extraction(- session,- resource,- error=error_msg,- )- session.commit()- return False, error_msg- else:- # Download failed- error_msg = result.skip_reason or "Failed to download PDF"- logger.warning(- f"[TEXT_EXTRACTION] ✗ FAILED: Could not download PDF for '{resource.title[:50]}...' | {resource.url} | Error: {error_msg}"- )- self._record_failed_text_extraction(- session,- resource,- error=f"PDF download failed: {error_msg}",- )- session.commit()- return False, f"PDF extraction failed: {error_msg}"- else:- error_msg = "No compatible downloader found"- logger.warning(- f"[TEXT_EXTRACTION] ✗ FAILED: {error_msg} for '{resource.title[:50]}...' | {resource.url}"- )- self._record_failed_text_extraction(- session,- resource,- error=error_msg,- )- session.commit()- return False, error_msg+ downloader = self._get_downloader(resource.url)+ if not downloader:+ error_msg = "No compatible downloader found"+ logger.warning(+ f"✗ FAILED: {error_msg} for '{resource.title[:50]}...'"+ )+ self._record_failed_text_extraction(+ session, resource, error=error_msg+ )+ session.commit()+ return False, error_msg++ result = downloader.download_with_result(resource.url, ContentType.PDF)++ if not result.is_success or not result.content:+ error_msg = result.skip_reason or "Failed to download PDF"+ logger.warning(+ f"✗ FAILED: Could not download PDF for '{resource.title[:50]}...' | Error: {error_msg}"+ )+ self._record_failed_text_extraction(+ session, resource, error=f"PDF download failed: {error_msg}"+ )+ session.commit()+ return False, f"PDF extraction failed: {error_msg}"++ # Extract text from PDF+ text = self._extract_text_from_pdf(result.content)+ if not text:+ error_msg = "PDF text extraction returned empty text"+ logger.warning(+ f"Failed to extract text from PDF for: {resource.url}"+ )+ self._record_failed_text_extraction(+ session, resource, error=error_msg+ )+ session.commit()+ return False, error_msg++ try:+ self._save_text_with_db(+ resource,+ text,+ session,+ extraction_method="pdf_extraction",+ extraction_source="pdfplumber_fallback",+ save_files=save_files,+ )+ session.commit()+ logger.info(+ f"✓ SUCCESS: Extracted text from '{resource.title[:50]}...'"+ )+ return True, None+ except Exception as e:+ logger.exception(f"Failed to save text for resource {resource.id}")+ return False, f"Failed to save text: {str(e)}"def _get_downloader(self, url: str):"""diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 432ed435dd..ab9b2208bd 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -204,9 +204,6 @@ class LibraryRAGService:def get_current_index_info(self) -> Optional[Dict[str, Any]]:"""Get information about the current RAG index."""with get_user_db_session(self.username) as session:- # Expire all cached objects to get fresh data from database- session.expire_all()-rag_index = (session.query(RAGIndex).filter_by(collection_name="library", is_current=True)@@ -382,9 +379,12 @@ class LibraryRAGService:logger.info(f"Saved FAISS index to {index_path}")# Update LibraryTextDocument with RAG status- # CRITICAL: Re-merge the object into the session since it might have been detached- # by nested session contexts (e.g., from _store_chunks_to_db using same thread-local session)- text_doc = session.merge(text_doc)+ # Re-query to ensure we have fresh object in this session+ text_doc = (+ session.query(LibraryTextDocument)+ .filter_by(id=text_doc_id)+ .first()+ )was_already_indexed = (text_doc.rag_indexed@@ -410,10 +410,6 @@ class LibraryRAGService:# Commit the changessession.commit()- # CRITICAL: Expire all cached objects in this thread-local session- # so subsequent operations in the same thread see fresh data- session.expire_all()-logger.info(f"Successfully indexed document {text_doc_id} "f"with {len(chunks)} chunks"@@ -681,11 +677,8 @@ class LibraryRAGService:self._get_or_create_rag_index(session)# Process embeddings and chunks- # For now, delegate to existing logic to maintain compatibility- # Close current session temporarily to allow existing method to work- session.expire_all()-# Use existing single-document method (it will create its own session)+ # No need to expire - each call manages its own session independentlyresult = self.index_document(doc_id, force_reindex)results[doc_id] = result@@ -708,9 +701,6 @@ class LibraryRAGService:Dict with counts and metadata about indexed documents"""with get_user_db_session(self.username) as session:- # Expire all cached objects to get fresh data from database- session.expire_all()-# Count total text documentstotal_text_docs = session.query(LibraryTextDocument).count()