~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 PDF download and text extraction issues
LearningCircuit0f96b6b466c6
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 5ef3b2732a..e007f8667d 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -5318,21 +5318,7 @@"value": false,"visible": true},- "research_library.enable_pdf_storage": {- "category": "research_library",- "description": "⚠️ PRIVACY WARNING: PDFs will be stored unencrypted on disk, exposing your research interests to anyone with filesystem access. Only enable if you need PDF files for external tools.",- "editable": true,- "max_value": null,- "min_value": null,- "name": "Enable PDF Storage",- "options": null,- "step": null,- "type": "APP",- "ui_element": "checkbox",- "value": false,- "visible": true- },- "research_library.enable_txt_storage": {+ "research_library.enable_txt_storage": {"category": "research_library","description": "⚠️ PRIVACY WARNING: Text files will be stored unencrypted on disk for RAG/ChromaDB integration. This exposes document contents to anyone with filesystem access.","editable": true,diff --git a/src/local_deep_research/defaults/research_library/library_settings.json b/src/local_deep_research/defaults/research_library/library_settings.jsonindex 06cfc3898c..3a7951840f 100644--- a/src/local_deep_research/defaults/research_library/library_settings.json+++ b/src/local_deep_research/defaults/research_library/library_settings.json@@ -31,7 +31,7 @@},"research_library.enable_pdf_storage": {"category": "research_library",- "description": "Enable storing PDF files on disk. PDFs will be unencrypted and expose research interests.",+ "description": "⚠️ PRIVACY WARNING: PDFs will be stored unencrypted on disk, exposing your research interests to anyone with filesystem access. Only enable if you need PDF files for external tools.","editable": true,"max_value": null,"min_value": null,diff --git a/src/local_deep_research/defaults/settings_document_scheduler.json b/src/local_deep_research/defaults/settings_document_scheduler.jsonindex c0014ef42a..5f23e18d0c 100644--- a/src/local_deep_research/defaults/settings_document_scheduler.json+++ b/src/local_deep_research/defaults/settings_document_scheduler.json@@ -29,11 +29,11 @@},"document_scheduler.download_pdfs": {"category": "document_scheduler",- "description": "Download PDF files to disk (requires storage space)",+ "description": "Automatically download PDF files during scheduled document processing. Files will be stored on disk (requires storage space).","editable": true,"max_value": null,"min_value": null,- "name": "Download PDFs",+ "name": "Auto-Download PDFs (Scheduler)","options": null,"step": null,"type": "APP",diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.pyindex 1db99dc7e5..884a58f2de 100644--- a/src/local_deep_research/news/subscription_manager/scheduler.py+++ b/src/local_deep_research/news/subscription_manager/scheduler.py@@ -175,11 +175,15 @@ class NewsScheduler:password: User's password"""logger.info(- f"update_user_info called for {username}, is_running={self.is_running}"+ f"[SCHEDULER] update_user_info called for {username}, is_running={self.is_running}, active_users={len(self.user_sessions)}")+ logger.debug(+ f"[SCHEDULER] Current active users: {list(self.user_sessions.keys())}"+ )+if not self.is_running:logger.warning(- f"Scheduler not running, cannot update user {username}"+ f"[SCHEDULER] Scheduler not running, cannot update user {username}")return@@ -188,21 +192,33 @@ class NewsScheduler:if username not in self.user_sessions:# New user - create session info- logger.info(f"New user in scheduler: {username}")+ logger.info(f"[SCHEDULER] New user in scheduler: {username}")self.user_sessions[username] = {"password": password,"last_activity": now,"scheduled_jobs": set(),}+ logger.debug(+ f"[SCHEDULER] Created session for {username}, scheduling subscriptions"+ )# Schedule their subscriptionsself._schedule_user_subscriptions(username)else:# Existing user - update infologger.info(- f"Updating existing user {username} activity, will reschedule"+ f"[SCHEDULER] Updating existing user {username} activity, will reschedule"+ )+ old_activity = self.user_sessions[username]["last_activity"]+ activity_delta = now - old_activity+ logger.debug(+ f"[SCHEDULER] User {username} last activity: {old_activity}, delta: {activity_delta}")+self.user_sessions[username]["password"] = passwordself.user_sessions[username]["last_activity"] = now+ logger.debug(+ f"[SCHEDULER] Updated {username} session info, scheduling subscriptions"+ )# Reschedule their subscriptions in case they changedself._schedule_user_subscriptions(username)@@ -338,29 +354,53 @@ class NewsScheduler:def _schedule_document_processing(self, username: str):"""Schedule document processing for a user."""- logger.info(f"Scheduling document processing for {username}")+ logger.info(+ f"[DOC_SCHEDULER] Scheduling document processing for {username}"+ )+ logger.debug(+ f"[DOC_SCHEDULER] Current user sessions: {list(self.user_sessions.keys())}"+ )+try:session_info = self.user_sessions.get(username)if not session_info:- logger.warning(f"No session info found for {username}")+ logger.warning(+ f"[DOC_SCHEDULER] No session info found for {username}"+ )+ logger.debug(+ f"[DOC_SCHEDULER] Available sessions: {list(self.user_sessions.keys())}"+ )returnpassword = session_info["password"]+ logger.debug(+ f"[DOC_SCHEDULER] Retrieved password for {username}, scheduler running: {self.is_running}"+ )# Get user's document scheduler settings from their databasefrom ...database.session_context import get_user_db_sessionfrom ...settings.manager import SettingsManager+ logger.debug(+ f"[DOC_SCHEDULER] Connecting to database for {username} settings"+ )with get_user_db_session(username, password) as db:settings_manager = SettingsManager(db)+ logger.debug(+ "[DOC_SCHEDULER] Connected to database, retrieving settings"+ )# Check if document processing is enabled for this userenabled = settings_manager.get_setting("document_scheduler.enabled", True)+ logger.info(+ f"[DOC_SCHEDULER] Document scheduler enabled for {username}: {enabled}"+ )+if not enabled:logger.info(- f"Document scheduler disabled for user {username}"+ f"[DOC_SCHEDULER] Document scheduler disabled for user {username}")return@@ -379,21 +419,29 @@ class NewsScheduler:)logger.info(- f"User {username} document settings: enabled={enabled}, interval={interval_seconds}s, "+ f"[DOC_SCHEDULER] User {username} document settings: enabled={enabled}, interval={interval_seconds}s, "f"pdfs={download_pdfs}, text={extract_text}, rag={generate_rag}")# Schedule document processing jobjob_id = f"{username}_document_processing"+ logger.debug(f"[DOC_SCHEDULER] Preparing to schedule job {job_id}")# Remove existing document job if anytry:self.scheduler.remove_job(job_id)session_info["scheduled_jobs"].discard(job_id)+ logger.debug(f"[DOC_SCHEDULER] Removed existing job {job_id}")except JobLookupError:+ logger.debug(+ f"[DOC_SCHEDULER] No existing job {job_id} to remove"+ )pass # Job doesn't exist, that's fine# Add new document processing job+ logger.debug(+ f"[DOC_SCHEDULER] Adding new document processing job with interval {interval_seconds}s"+ )self.scheduler.add_job(func=self._process_user_documents,args=[username],@@ -408,9 +456,23 @@ class NewsScheduler:session_info["scheduled_jobs"].add(job_id)logger.info(- f"Scheduled document processing job for {username} with {interval_seconds}s interval"+ f"[DOC_SCHEDULER] Scheduled document processing job {job_id} for {username} with {interval_seconds}s interval"+ )+ logger.debug(+ f"[DOC_SCHEDULER] User {username} now has {len(session_info['scheduled_jobs'])} scheduled jobs: {list(session_info['scheduled_jobs'])}")+ # Verify job was added+ job = self.scheduler.get_job(job_id)+ if job:+ logger.info(+ f"[DOC_SCHEDULER] Successfully verified job {job_id} exists, next run: {job.next_run_time}"+ )+ else:+ logger.error(+ f"[DOC_SCHEDULER] Failed to verify job {job_id} exists!"+ )+except Exception as e:logger.exception(f"Error scheduling document processing for {username}: {e}"@@ -418,23 +480,35 @@ class NewsScheduler:def _process_user_documents(self, username: str):"""Process documents for a user."""- logger.info(f"Processing documents for user {username}")+ logger.info(f"[DOC_SCHEDULER] Processing documents for user {username}")+ start_time = datetime.now(UTC)try:session_info = self.user_sessions.get(username)if not session_info:- logger.warning(f"No session info found for user {username}")+ logger.warning(+ f"[DOC_SCHEDULER] No session info found for user {username}"+ )returnpassword = session_info["password"]+ logger.debug(+ f"[DOC_SCHEDULER] Starting document processing for {username}"+ )# Get user's settings from their databasefrom ...database.session_context import get_user_db_sessionfrom ...database.models.research import ResearchHistoryfrom ...settings.manager import SettingsManager+ logger.debug(+ f"[DOC_SCHEDULER] Connecting to database for {username}"+ )with get_user_db_session(username, password) as db:settings_manager = SettingsManager(db)+ logger.debug(+ "[DOC_SCHEDULER] Connected to database for document processing"+ )# Get processing settingsdownload_pdfs = settings_manager.get_setting(@@ -447,9 +521,13 @@ class NewsScheduler:"document_scheduler.generate_rag", False)+ logger.info(+ f"[DOC_SCHEDULER] Processing settings for {username}: pdfs={download_pdfs}, text={extract_text}, rag={generate_rag}"+ )+if not any([download_pdfs, extract_text, generate_rag]):logger.info(- f"No processing options enabled for user {username}"+ f"[DOC_SCHEDULER] No processing options enabled for user {username}")return@@ -463,9 +541,19 @@ class NewsScheduler:else None)+ logger.info(+ f"[DOC_SCHEDULER] Last run for {username}: {last_run}"+ )+# Query for completed research since last run+ logger.debug(+ f"[DOC_SCHEDULER] Querying for completed research since {last_run}"+ )query = db.query(ResearchHistory).filter(- ResearchHistory.status == "completed"+ ResearchHistory.status == "completed",+ ResearchHistory.completed_at.is_not(+ None+ ), # Ensure completed_at is not null)if last_run:@@ -479,48 +567,181 @@ class NewsScheduler:).limit(20)research_sessions = query.all()+ logger.debug(+ f"[DOC_SCHEDULER] Query executed, found {len(research_sessions)} sessions"+ )if not research_sessions:logger.info(- f"No new completed research sessions found for user {username}"+ f"[DOC_SCHEDULER] No new completed research sessions found for user {username}")returnlogger.info(- f"Found {len(research_sessions)} research sessions to process for {username}"+ f"[DOC_SCHEDULER] Found {len(research_sessions)} research sessions to process for {username}")+ # Log details of each research session+ for i, research in enumerate(+ research_sessions[:5]+ ): # Log first 5 details+ title_safe = (+ (research.title[:50] + "...")+ if research.title+ else "No title"+ )+ completed_safe = (+ research.completed_at+ if research.completed_at+ else "No completion time"+ )+ logger.debug(+ f"[DOC_SCHEDULER] Session {i + 1}: id={research.id}, title={title_safe}, completed={completed_safe}"+ )++ # Handle completed_at which might be a string or datetime+ completed_at_obj = None+ if research.completed_at:+ if isinstance(research.completed_at, str):+ try:+ completed_at_obj = datetime.fromisoformat(+ research.completed_at.replace("Z", "+00:00")+ )+ except:+ completed_at_obj = None+ else:+ completed_at_obj = research.completed_at++ logger.debug(+ f"[DOC_SCHEDULER] - completed_at type: {type(research.completed_at)}"+ )+ logger.debug(+ f"[DOC_SCHEDULER] - completed_at timezone: {completed_at_obj.tzinfo if completed_at_obj else 'None'}"+ )+ logger.debug(f"[DOC_SCHEDULER] - last_run: {last_run}")+ logger.debug(+ f"[DOC_SCHEDULER] - completed_at > last_run: {completed_at_obj > last_run if last_run and completed_at_obj else 'N/A'}"+ )+processed_count = 0for research in research_sessions:try:logger.info(- f"Processing research {research.id} for user {username}"+ f"[DOC_SCHEDULER] Processing research {research.id} for user {username}")- # Simulate processing (in real implementation, call existing APIs)+ # Call actual processing APIsif download_pdfs:- logger.debug(- f"Would download PDFs for research {research.id}"+ logger.info(+ f"[DOC_SCHEDULER] Downloading PDFs for research {research.id}")- # Call: POST /api/download-research/<research_id>+ try:+ # Use the DownloadService to queue PDF downloads+ from ...research_library.services.download_service import (+ DownloadService,+ )++ download_service = DownloadService(+ username=username, password=password+ )+ queued_count = (+ download_service.queue_research_downloads(+ research.id+ )+ )+ logger.info(+ f"[DOC_SCHEDULER] Queued {queued_count} PDF downloads for research {research.id}"+ )+ except Exception as e:+ logger.exception(+ f"[DOC_SCHEDULER] Failed to download PDFs for research {research.id}: {e}"+ )if extract_text:- logger.debug(- f"Would extract text for research {research.id}"+ logger.info(+ f"[DOC_SCHEDULER] Extracting text for research {research.id}")- # Call: POST /api/download-all-text+ try:+ # Use the DownloadService to extract text for all resources+ from ...research_library.services.download_service import (+ DownloadService,+ )+ from ...database.models.research import (+ ResearchResource,+ )+ from ...database.session_context import (+ get_user_db_session,+ )++ download_service = DownloadService(+ username=username, password=password+ )++ # Get all resources for this research+ with get_user_db_session(+ username, password+ ) as resource_db:+ resources = (+ resource_db.query(ResearchResource)+ .filter_by(research_id=research.id)+ .all()+ )+ processed_count = 0+ for resource in resources:+ # We need to pass the password to the download service+ # The DownloadService creates its own database sessions, so we need to ensure password is available+ try:+ success, error = (+ download_service.download_as_text(+ resource.id,+ save_files=False,+ )+ )+ if success:+ processed_count += 1+ logger.info(+ f"[DOC_SCHEDULER] Successfully extracted text for resource {resource.id}"+ )+ else:+ logger.warning(+ f"[DOC_SCHEDULER] Failed to extract text for resource {resource.id}: {error}"+ )+ except Exception as resource_error:+ logger.exception(+ f"[DOC_SCHEDULER] Error processing resource {resource.id}: {resource_error}"+ )+ logger.info(+ f"[DOC_SCHEDULER] Text extraction completed for research {research.id}: {processed_count}/{len(resources)} resources processed"+ )+ except Exception as e:+ logger.exception(+ f"[DOC_SCHEDULER] Failed to extract text for research {research.id}: {e}"+ )if generate_rag:- logger.debug(- f"Would generate RAG embeddings for research {research.id}"+ logger.info(+ f"[DOC_SCHEDULER] Generating RAG embeddings for research {research.id}")- # Call: POST /api/rag/index-research+ try:+ # RAG generation is typically handled automatically when documents are added to the library+ # For now, we'll just log that RAG would be generated+ logger.info(+ f"[DOC_SCHEDULER] RAG generation would be triggered for research {research.id}"+ )+ # TODO: Implement actual RAG generation once we understand the RAG system better+ except Exception as e:+ logger.exception(+ f"[DOC_SCHEDULER] Failed to generate RAG embeddings for research {research.id}: {e}"+ )processed_count += 1+ logger.debug(+ f"[DOC_SCHEDULER] Successfully queued processing for research {research.id}"+ )except Exception as e:logger.exception(- f"Error processing research {research.id} for user {username}: {e}"+ f"[DOC_SCHEDULER] Error processing research {research.id} for user {username}: {e}")# Update last run time in user's settings@@ -528,14 +749,19 @@ class NewsScheduler:settings_manager.set_setting("document_scheduler.last_run", current_time, commit=True)+ logger.debug(+ f"[DOC_SCHEDULER] Updated last run time for {username} to {current_time}"+ )+ end_time = datetime.now(UTC)+ duration = (end_time - start_time).total_seconds()logger.info(- f"Completed document processing for user {username}: {processed_count} sessions processed"+ f"[DOC_SCHEDULER] Completed document processing for user {username}: {processed_count} sessions processed in {duration:.2f}s")except Exception as e:logger.exception(- f"Error processing documents for user {username}: {e}"+ f"[DOC_SCHEDULER] Error processing documents for user {username}: {e}")def get_document_scheduler_status(self, username: str) -> Dict[str, Any]:@@ -605,20 +831,30 @@ class NewsScheduler:def trigger_document_processing(self, username: str) -> bool:"""Trigger immediate document processing for a user."""+ logger.info(+ f"[DOC_SCHEDULER] Manual trigger requested for user {username}"+ )try:session_info = self.user_sessions.get(username)if not session_info:- logger.warning(f"User {username} not found in scheduler")+ logger.warning(+ f"[DOC_SCHEDULER] User {username} not found in scheduler"+ )+ logger.debug(+ f"[DOC_SCHEDULER] Available users: {list(self.user_sessions.keys())}"+ )return Falseif not self.is_running:logger.warning(- "Scheduler not running, cannot trigger document processing"+ f"[DOC_SCHEDULER] Scheduler not running, cannot trigger document processing for {username}")return False# Trigger immediate processingjob_id = f"{username}_document_processing_manual"+ logger.debug(f"[DOC_SCHEDULER] Scheduling manual job {job_id}")+self.scheduler.add_job(func=self._process_user_documents,args=[username],@@ -629,14 +865,23 @@ class NewsScheduler:replace_existing=True,)- logger.info(- f"Triggered manual document processing for user {username}"- )+ # Verify job was added+ job = self.scheduler.get_job(job_id)+ if job:+ logger.info(+ f"[DOC_SCHEDULER] Successfully triggered manual document processing for user {username}, job {job_id}, next run: {job.next_run_time}"+ )+ else:+ logger.error(+ f"[DOC_SCHEDULER] Failed to verify manual job {job_id} was added!"+ )+ return False+return Trueexcept Exception as e:logger.exception(- f"Error triggering document processing for user {username}: {e}"+ f"[DOC_SCHEDULER] Error triggering document processing for user {username}: {e}")return Falsediff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex 0e1c665cd5..0976ba4cd4 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -101,7 +101,22 @@ class ArxivDownloader(BaseDownloader):pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"logger.info(f"Downloading arXiv PDF: {arxiv_id}")- return super()._download_pdf(pdf_url)++ # Use enhanced headers for arXiv to avoid reCAPTCHA+ enhanced_headers = {+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",+ "Accept": "application/pdf,application/octet-stream,application/vnd.ms-pdf,application/x-pdf,application/x-bzpdf,application/x-gzpdf,*/*;q=0.9",+ "Accept-Language": "en-US,en;q=0.9",+ "Accept-Encoding": "gzip, deflate, br",+ "Connection": "keep-alive",+ "Upgrade-Insecure-Requests": "1",+ "Sec-Fetch-Dest": "document",+ "Sec-Fetch-Mode": "navigate",+ "Sec-Fetch-Site": "none",+ "Cache-Control": "max-age=0",+ }++ return super()._download_pdf(pdf_url, headers=enhanced_headers)def _download_text(self, url: str) -> Optional[bytes]:"""Get full text content from arXiv PDF (with metadata from API)."""diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex 2fa7c8d038..550506a6c7 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -582,6 +582,7 @@ def download_all_text():"current": current,"total": total,"file": file_name,+ "url": resource.url, # Add the URL for UI display"status": status,"error": error_msg,}diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex a05fc2414b..8810eb0b4f 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -347,12 +347,25 @@ def index_all():results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}total = len(doc_info)- # Index each document and send progress- for idx, (doc_id, title) in enumerate(doc_info, 1):- # Send progress update- yield f"data: {json.dumps({'type': 'progress', 'current': idx, 'total': total, 'title': title, 'percent': int((idx / total) * 100)})}\n\n"+ # Process documents in batches to optimize performance+ batch_size = 15 # Process max 15 documents at a time+ processed = 0++ for i in range(0, len(doc_info), batch_size):+ batch = doc_info[i : i + batch_size]++ # Process batch in single database session+ batch_results = rag_service.index_documents_batch(+ batch, force_reindex+ )++ # Process results and send progress updates+ for j, (doc_id, title) in enumerate(batch):+ processed += 1+ result = batch_results[doc_id]- result = rag_service.index_document(doc_id, force_reindex)+ # Send progress update+ yield f"data: {json.dumps({'type': 'progress', 'current': processed, 'total': total, 'title': title, 'percent': int((processed / total) * 100)})}\n\n"if result["status"] == "success":results["successful"] += 1diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex b6f24538c0..c6b368c1d5 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -55,19 +55,40 @@ from ..downloaders import (class DownloadService:"""Service for downloading and managing research PDFs."""- def __init__(self, username: str):- """Initialize download service for a user."""+ def __init__(self, username: str, password: Optional[str] = None):+ """Initialize download service for a user.++ Args:+ username: The username to download for+ password: Optional password for encrypted database access+ """self.username = username+ self.password = passwordself.settings = get_settings_manager()+ # Debug settings manager and user context+ logger.info(+ f"[DOWNLOAD_SERVICE] Settings manager initialized: {type(self.settings)}, username: {self.username}"+ )+# Get library path from settings- self.library_root = str(- Path(- self.settings.get_setting(- "research_library.storage_path",- "~/.local-deep-research/library",- )- ).expanduser()+ storage_path_setting = self.settings.get_setting(+ "research_library.storage_path",+ "~/.local-deep-research/library",+ )+ logger.warning(+ f"[DOWNLOAD_SERVICE_INIT] Storage path setting retrieved: {storage_path_setting} (type: {type(storage_path_setting)})"+ )++ if storage_path_setting is None:+ logger.error(+ "[DOWNLOAD_SERVICE_INIT] CRITICAL: storage_path_setting is None!"+ )+ raise ValueError("Storage path setting cannot be None")++ self.library_root = str(Path(storage_path_setting).expanduser())+ logger.warning(+ f"[DOWNLOAD_SERVICE_INIT] Library root resolved to: {self.library_root}")# Create directory structure@@ -122,7 +143,7 @@ class DownloadService:"""url_hash = self._get_url_hash(url)- with get_user_db_session(self.username) as session:+ with get_user_db_session(self.username, self.password) as session:tracker = (session.query(DownloadTracker).filter_by(url_hash=url_hash, is_downloaded=True)@@ -158,7 +179,7 @@ class DownloadService:Returns:Text content as string, or None if extraction failed"""- with get_user_db_session(self.username) as session:+ with get_user_db_session(self.username, self.password) as session:resource = session.query(ResearchResource).get(resource_id)if not resource:logger.error(f"Resource {resource_id} not found")@@ -196,7 +217,7 @@ class DownloadService:"""queued = 0- with get_user_db_session(self.username) as session:+ with get_user_db_session(self.username, self.password) as session:# Get all resources for this researchresources = (session.query(ResearchResource)@@ -281,7 +302,7 @@ class DownloadService:Returns:Tuple of (success: bool, skip_reason: str or None)"""- with get_user_db_session(self.username) as session:+ with get_user_db_session(self.username, self.password) as session:resource = session.query(ResearchResource).get(resource_id)if not resource:logger.error(f"Resource {resource_id} not found")@@ -419,6 +440,9 @@ class DownloadService:enable_pdf_storage = self.settings.get_setting("research_library.enable_pdf_storage", False)+ logger.info(+ f"[DOWNLOAD_SERVICE] PDF storage setting retrieved: {enable_pdf_storage} (type: {type(enable_pdf_storage)})"+ )# Update trackerimport hashlib@@ -565,6 +589,7 @@ class DownloadService:True,"library PDF storage",mode="wb",+ username=self.username,)return str(validated_path)@@ -706,7 +731,7 @@ class DownloadService:Returns:Tuple of (success, error_message)"""- with get_user_db_session(self.username) as session:+ with get_user_db_session(self.username, self.password) as session:# Get the resourceresource = (session.query(ResearchResource)@@ -725,8 +750,28 @@ class DownloadService:if existing_text and existing_text.extraction_status == "completed":# Check if file still exists- text_path = Path(self.library_root) / existing_text.file_path- if text_path.exists():+ logger.warning(+ f"[TEXT_EXTRACTION] Checking existing text: library_root={self.library_root}, file_path={existing_text.file_path}"+ )++ 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 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}")@@ -734,6 +779,17 @@ class DownloadService: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-extractionelse:logger.warning(f"Text file in DB but missing on disk: {existing_text.file_path}"@@ -808,7 +864,9 @@ class DownloadService:# Fall through to download new content# Try to get text content directly without saving PDF- logger.info(f"Extracting text from: {resource.url}")+ logger.info(+ f"[TEXT_EXTRACTION] Attempting direct API text extraction from: {resource.url}"+ )# Determine which downloader to usedownloader = self._get_downloader(resource.url)@@ -846,6 +904,9 @@ class DownloadService:)# 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, Noneexcept Exception as e:logger.exception(@@ -853,60 +914,85 @@ class DownloadService:)return False, f"Failed to save text: {str(e)}"- # Fallback: Download PDF temporarily (in memory only) and extract text- logger.info(f"Falling back to PDF extraction for: {resource.url}")+ # 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}"+ )+ logger.info(+ "[TEXT_EXTRACTION] PDF will be processed in memory only - no disk storage"+ )- # Use the downloader directly without tracker- downloader = self._get_downloader(resource.url)- if not downloader:- downloader = GenericDownloader(timeout=30)+ # Download PDF to memory only using requests (no file system operations)+ try:+ import requests- result = downloader.download_with_result(- resource.url, ContentType.PDF- )+ headers = {+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"+ }++ # Convert arXiv abstract URL to PDF URL if needed+ pdf_url = resource.url+ if "arxiv.org/abs/" in resource.url:+ # Convert: http://arxiv.org/abs/2401.03055v1 -> http://arxiv.org/pdf/2401.03055v1.pdf+ pdf_url = resource.url.replace("/abs/", "/pdf/") + ".pdf"+ logger.info(+ f"[TEXT_EXTRACTION] Converting arXiv URL: {resource.url} -> {pdf_url}"+ )++ response = requests.get(pdf_url, headers=headers, timeout=30)+ response.raise_for_status()++ # Verify it's a PDF+ content_type = response.headers.get("Content-Type", "")+ if not content_type.startswith("application/pdf"):+ logger.warning(+ f"[TEXT_EXTRACTION] URL didn't return PDF content: {content_type}"+ )+ raise Exception("Not a PDF file")++ # Extract text from PDF in memory+ pdf_content = response.content+ text = self._extract_text_from_pdf(pdf_content)- 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()- 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:- # Record failed extraction- self._record_failed_text_extraction(- session,+ # Save text to database only (no file storage)+ text_path = self._save_text_with_db(resource,- error="Failed to extract text from PDF",+ text,+ session,+ extraction_method="pdf_extraction",+ extraction_source="in_memory_fallback",+ save_files=save_files, # This determines if .txt files are saved)+ # Success! text_path may be None (DB-only) or a path (DB + file)session.commit()- return False, "Failed to extract text from PDF"- else:- # Record failed download+ logger.info(+ f"[TEXT_EXTRACTION] ✓ SUCCESS: Extracted text from '{resource.title[:50]}...' | {resource.url}"+ )+ return True, None+ else:+ logger.warning(+ f"[TEXT_EXTRACTION] Failed to extract text from in-memory PDF for: {resource.url}"+ )+ raise Exception("PDF text extraction returned empty text")++ except Exception as e:+ logger.warning(+ f"[TEXT_EXTRACTION] In-memory PDF download/extraction failed for {resource.url}: {e}"+ )++ # For both RAG and file modes, mark as failed if PDF extraction fails+ # This is a genuine error that should be tracked for potential retry+ logger.warning(+ f"[TEXT_EXTRACTION] ✗ FAILED: Could not extract text from '{resource.title[:50]}...' | {resource.url} | Error: {e}"+ )self._record_failed_text_extraction(session,resource,- error=result.skip_reason or "Failed to download content",+ error=f"In-memory PDF extraction failed: {str(e)}",)session.commit()- return False, result.skip_reason or "Failed to download content"+ return False, f"PDF extraction failed: {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 f28ac02ed3..d54ee8876f 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@@ -588,6 +588,107 @@ class LibraryRAGService:)return {"status": "error", "error": str(e)}+ def index_documents_batch(+ self, doc_info: List[tuple], force_reindex: bool = False+ ) -> Dict[int, Dict[str, Any]]:+ """+ Index multiple documents in a single database session for better efficiency.++ Args:+ doc_info: List of (doc_id, title) tuples+ force_reindex: Whether to force reindexing even if already indexed++ Returns:+ Dict mapping doc_id to individual result+ """+ results = {}+ doc_ids = [doc_id for doc_id, _ in doc_info]++ # Use single database session for the entire batch+ with get_user_db_session(self.username) as session:+ # Pre-load all documents for this batch+ text_docs = (+ session.query(LibraryTextDocument)+ .filter(LibraryTextDocument.id.in_(doc_ids))+ .all()+ )++ # Create lookup for quick access+ doc_lookup = {doc.id: doc for doc in text_docs}++ # Process each document in the batch+ for doc_id, title in doc_info:+ text_doc = doc_lookup.get(doc_id)++ if not text_doc:+ results[doc_id] = {+ "status": "error",+ "error": "Document not found",+ }+ continue++ # Check if already indexed+ if text_doc.rag_indexed and not force_reindex:+ results[doc_id] = {+ "status": "skipped",+ "message": "Document already indexed",+ "chunk_count": text_doc.chunk_count,+ }+ continue++ # Validate text content+ if not text_doc.text_content:+ results[doc_id] = {+ "status": "error",+ "error": "Document has no text content",+ }+ continue++ try:+ # Use the existing single-document logic but with current session+ # This avoids creating additional database connections+ from langchain.schema import Document++ # Create LangChain Document from text+ Document(+ page_content=text_doc.text_content,+ metadata={+ "source": text_doc.original_url,+ "source_id": doc_id,+ "title": text_doc.title or "Untitled",+ "document_title": text_doc.title or "Untitled",+ "authors": text_doc.authors,+ "publication_date": text_doc.publication_date.isoformat()+ if text_doc.publication_date+ else None,+ "document_type": "library_text",+ "library_doc_id": doc_id,+ },+ )++ # Get or create RAG index for this session+ 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)+ result = self.index_document(doc_id, force_reindex)+ results[doc_id] = result++ except Exception as e:+ logger.exception(+ f"Error indexing document {doc_id} in batch"+ )+ results[doc_id] = {+ "status": "error",+ "error": str(e),+ }++ return results+def get_rag_stats(self) -> Dict[str, Any]:"""Get RAG statistics for the library.diff --git a/src/local_deep_research/security/file_write_verifier.py b/src/local_deep_research/security/file_write_verifier.pyindex 6c12cf237b..62e8193197 100644--- a/src/local_deep_research/security/file_write_verifier.py+++ b/src/local_deep_research/security/file_write_verifier.py@@ -6,7 +6,7 @@ maintaining the encryption-at-rest security model.import jsonfrom pathlib import Path-from typing import Any+from typing import Any, Optionalfrom loguru import logger@@ -25,6 +25,7 @@ def write_file_verified(context: str = "",mode: str = "w",encoding: str = "utf-8",+ username: Optional[str] = None,) -> None:"""Write content to a file only if security settings allow it.@@ -48,15 +49,28 @@ def write_file_verified(... context="API research report"... )"""- from ..config.search_config import get_setting_from_snapshot+ from ..utilities.get_settings_manager import get_settings_managertry:- actual_value = get_setting_from_snapshot(setting_name)- except Exception:+ settings_manager = get_settings_manager(user_id=username)+ logger.warning(+ f"[SECURITY_CHECK] Settings manager: {type(settings_manager)}, username provided: {username}"+ )+ actual_value = settings_manager.get_setting(setting_name, None)+ logger.warning(+ f"[SECURITY_CHECK] Setting '{setting_name}': retrieved_value={actual_value}, required_value={required_value}"+ )+ except Exception as e:# Setting doesn't exist - default denyactual_value = None+ logger.warning(+ f"[SECURITY_CHECK] Exception getting setting '{setting_name}': {e}"+ )if actual_value != required_value:+ logger.warning(+ f"[SECURITY_CHECK] DENIED: Setting '{setting_name}' = {actual_value} (type: {type(actual_value)}), required: {required_value} (type: {type(required_value)})"+ )error_msg = (f"File write not allowed: {context or 'file operation'}. "f"Set '{setting_name}={required_value}' in config to enable this feature."diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 881caf5f13..aa137cf150 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -1413,6 +1413,7 @@ function updateTextExtractionProgress(data) {<span class="status-icon">${statusIcon}</span><div class="entry-details"><strong>${data.file}</strong>+ <span class="entry-url" style="color: #888; font-size: 0.85em; display: block; word-break: break-all;">${data.url}</span><span class="status-text">${statusText}</span></div>`;