~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
feat: enhance Research Library UI and download functionality
LearningCircuit954241a2b283
diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.pyindex 71745ac88e..1bcfcecdef 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -3,6 +3,7 @@ Generic PDF Downloader for unspecified sources"""from typing import Optional+import requestsfrom loguru import loggerfrom .base import BaseDownloader, ContentType, DownloadResult@@ -72,25 +73,56 @@ class GenericDownloader(BaseDownloader):# Try to determine more specific reasontry:- response = self.session.head(- url, timeout=5, allow_redirects=True+ response = self.session.get(+ url, timeout=5, allow_redirects=True, stream=True)- if response.status_code == 404:- return DownloadResult(skip_reason="URL not found (404)")++ # Check status code+ if response.status_code == 200:+ # Check if it's HTML instead of PDF+ content_type = response.headers.get(+ "content-type", ""+ ).lower()+ if "text/html" in content_type:+ return DownloadResult(+ skip_reason="Article page requires login or subscription - no direct PDF link available"+ )+ else:+ return DownloadResult(+ skip_reason=f"Unexpected content type: {content_type} - expected PDF"+ )+ elif response.status_code == 404:+ return DownloadResult(+ skip_reason="Article not found (404) - may have been removed or URL is incorrect"+ )elif response.status_code == 403:return DownloadResult(- skip_reason="Access forbidden - authentication may be required"+ skip_reason="Access denied (403) - article requires subscription or special permissions"+ )+ elif response.status_code == 401:+ return DownloadResult(+ skip_reason="Authentication required - please login to access this article")elif response.status_code >= 500:return DownloadResult(- skip_reason="Server error - site may be temporarily unavailable"+ skip_reason=f"Server error ({response.status_code}) - website is experiencing technical issues")else:return DownloadResult(- skip_reason=f"Failed to download - HTTP {response.status_code}"+ skip_reason=f"Unable to access article - server returned error code {response.status_code}")+ except requests.exceptions.Timeout:+ return DownloadResult(+ skip_reason="Connection timed out - server took too long to respond"+ )+ except requests.exceptions.ConnectionError:+ return DownloadResult(+ skip_reason="Could not connect to server - website may be down"+ )except:- return DownloadResult(skip_reason="Could not connect to server")+ return DownloadResult(+ skip_reason="Network error - could not reach the website"+ )def _download_pdf(self, url: str) -> Optional[bytes]:"""Attempt to download PDF from URL."""diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex b1c5afb57b..dbbb3e4b8b 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -391,16 +391,39 @@ def download_bulk():# Attempt actual download with error handlingskip_reason = None+ status = "skipped" # Default to skipped+ success = False+ error_msg = None+try:- success = download_service.download_resource(+ logger.debug(+ f"Attempting download for resource {queue_item.resource_id}"+ )+ result = download_service.download_resource(queue_item.resource_id)+ # Handle new tuple return format+ if isinstance(result, tuple):+ success, skip_reason = result+ else:+ success = result+ skip_reason = None+status = "success" if success else "skipped"+ if skip_reason and not success:+ error_msg = skip_reason+ logger.info(+ f"Download skipped for resource {queue_item.resource_id}: {skip_reason}"+ )++ logger.debug(+ f"Download result: success={success}, status={status}, skip_reason={skip_reason}"+ )except Exception as e:# Log error but continue processingerror_msg = str(e)logger.info(- f"Download exception for resource {queue_item.resource_id}: {error_msg}"+ f"CAUGHT Download exception for resource {queue_item.resource_id}: {error_msg}")# Check if this is a skip reason (not a real error)if any(@@ -427,6 +450,13 @@ def download_bulk():skip_reason = error_msg # Include error message for failed toosuccess = False+ # Ensure skip_reason is set if we have an error message+ if error_msg and not skip_reason:+ skip_reason = error_msg+ logger.debug(+ f"Setting skip_reason from error_msg: {error_msg}"+ )+# Send progress updateupdate_data = {"progress": progress,@@ -495,6 +525,8 @@ def queue_all_undownloaded():"""Queue all articles that haven't been downloaded yet."""username = session.get("username")+ logger.info(f"queue_all_undownloaded called for user {username}")+with get_user_db_session(username) as db_session:# Find all resources that don't have a completed downloadundownloaded = (@@ -508,25 +540,54 @@ def queue_all_undownloaded():.all())+ logger.info(f"Found {len(undownloaded)} total undownloaded resources")+queued_count = 0research_ids = set()+ skipped_count = 0for resource in undownloaded:# Check if it's downloadableurl = resource.url.lower() if resource.url else ""- # Skip non-downloadable sources- if not any(- domain in url- for domain in [- "arxiv.org",- "biorxiv.org",- "medrxiv.org",- "ncbi.nlm.nih.gov/pmc",- "pubmed.ncbi.nlm.nih.gov",- ".pdf",- ]- ):+ if not url:+ skipped_count += 1+ continue++ # Check for downloadable sources - be more inclusive+ # Include any PDF link or known academic sources+ is_downloadable = (+ ".pdf" in url+ or "arxiv.org" in url+ or "biorxiv.org" in url+ or "medrxiv.org" in url+ or "ncbi.nlm.nih.gov" in url+ or "pubmed" in url+ or "pubmed.ncbi.nlm.nih.gov" in url # Explicit PubMed domain+ or "semanticscholar.org" in url+ or "researchgate.net" in url+ or "academia.edu" in url+ or "sciencedirect.com" in url+ or "springer.com" in url+ or "nature.com" in url+ or "ieee.org" in url+ or "acm.org" in url+ or "plos.org" in url+ or "frontiersin.org" in url+ or "mdpi.com" in url+ or "doi.org"+ in url # DOI links often lead to downloadable papers+ )++ # Log what we're checking+ if "pubmed" in url:+ logger.info(f"Found PubMed URL: {resource.url[:100]}")++ if not is_downloadable:+ skipped_count += 1+ logger.debug(+ f"Skipping non-downloadable URL: {resource.url[:100]}"+ )continue# Check if already in queue (any status)@@ -543,6 +604,16 @@ def queue_all_undownloaded():existing_queue.completed_at = Nonequeued_count += 1research_ids.add(resource.research_id)+ logger.debug(+ f"Reset queue entry for resource {resource.id} to pending"+ )+ else:+ # Already pending, still count it+ queued_count += 1+ research_ids.add(resource.research_id)+ logger.debug(+ f"Resource {resource.id} already pending in queue"+ )else:# Add new entry to queuequeue_entry = LibraryDownloadQueue(@@ -554,14 +625,22 @@ def queue_all_undownloaded():db_session.add(queue_entry)queued_count += 1research_ids.add(resource.research_id)+ logger.debug(+ f"Added new queue entry for resource {resource.id}"+ )db_session.commit()+ logger.info(+ f"Queued {queued_count} articles for download, skipped {skipped_count} non-downloadable URLs"+ )+return jsonify({"success": True,"queued": queued_count,"research_ids": list(research_ids),"total_undownloaded": len(undownloaded),+ "skipped": skipped_count,})diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 95ec08b716..e674252390 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -256,18 +256,18 @@ class DownloadService:return any(domain in url for domain in downloadable_domains)- def download_resource(self, resource_id: int) -> bool:+ def download_resource(self, resource_id: int) -> tuple[bool, str]:"""Download a specific resource.Returns:- True if successful, False otherwise+ Tuple of (success: bool, skip_reason: str or None)"""with get_user_db_session(self.username) as session:resource = session.query(ResearchResource).get(resource_id)if not resource:logger.error(f"Resource {resource_id} not found")- return False+ return False, "Resource not found"# Check if already downloaded (trust the database after sync)existing_doc = (@@ -280,7 +280,7 @@ class DownloadService:logger.info("Resource already downloaded (according to database)")- return True+ return True, None# Create download tracker entryurl_hash = self._get_url_hash(resource.url)@@ -301,7 +301,24 @@ class DownloadService:session.commit()# Attempt download- success = self._download_pdf(resource, tracker, session)+ result = self._download_pdf(resource, tracker, session)++ # Get skip reason if failed+ skip_reason = None+ if isinstance(result, tuple):+ success, skip_reason = result+ else:+ success = result+ if not success:+ # Try to get skip reason from last attempt+ last_attempt = (+ session.query(DownloadAttempt)+ .filter_by(url_hash=tracker.url_hash)+ .order_by(DownloadAttempt.attempted_at.desc())+ .first()+ )+ if last_attempt and hasattr(last_attempt, "error_message"):+ skip_reason = last_attempt.error_message# Update queue status if existsqueue_entry = (@@ -315,19 +332,19 @@ class DownloadService:queue_entry.completed_at = datetime.now(UTC)session.commit()- return success+ return success, skip_reasondef _download_pdf(self,resource: ResearchResource,tracker: DownloadTracker,session: Session,- ) -> bool:+ ) -> tuple[bool, str]:"""Perform the actual PDF download.Returns:- True if successful, False otherwise+ Tuple of (success: bool, skip_reason: str or None)"""url = resource.url@@ -373,7 +390,12 @@ class DownloadService:if not pdf_content:error_msg = skip_reason or "Failed to download PDF content"- raise Exception(error_msg)+ # Store skip reason in attempt for retrieval+ attempt.error_message = error_msg+ attempt.succeeded = False+ session.commit()+ logger.info(f"Download failed with reason: {error_msg}")+ return False, error_msg# Save filefile_path = self._save_pdf(resource, pdf_content)@@ -431,7 +453,7 @@ class DownloadService:attempt.bytes_downloaded = len(pdf_content)logger.info(f"Successfully downloaded: {file_path}")- return True+ return True, Noneexcept Exception as e:logger.exception(f"Download failed for {url}")@@ -439,7 +461,7 @@ class DownloadService:attempt.error_type = type(e).__name__attempt.error_message = str(e)tracker.is_accessible = False- return False+ return False, str(e)def _save_pdf(self, resource: ResearchResource, content: bytes) -> str:"""diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 641ebea313..d3f9217a27 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -7,7 +7,7 @@<div class="library-header"><h1>Research Library</h1><div class="header-actions">- <button class="btn btn-secondary" onclick="syncLibrary()" title="Check if files exist and sync with filesystem">+ <button class="btn btn-secondary" onclick="showSyncModal()" title="Check if files exist and sync with filesystem"><i class="fas fa-sync"></i> Sync Library</button><button class="btn btn-success" onclick="downloadAllNew()" title="Download all articles that haven't been downloaded yet">@@ -227,6 +227,73 @@</div></div>+<!-- Sync Library Modal -->+<div id="sync-library-modal" class="modal" style="display: none;">+ <div class="modal-content" style="max-width: 600px;">+ <div class="modal-header">+ <h2><i class="fas fa-sync"></i> Sync Library with Filesystem</h2>+ <button class="close" onclick="closeSyncModal()">×</button>+ </div>+ <div class="modal-body">+ <div class="sync-explanation">+ <h3>What does Library Sync do?</h3>+ <p>The sync feature ensures your database stays consistent with the actual PDF files on your disk. It performs a comprehensive check to:</p>+ <ul>+ <li><strong>Verify file existence:</strong> Checks if all PDFs referenced in the database still exist on disk</li>+ <li><strong>Update file status:</strong> Marks missing files so they can be re-downloaded if needed</li>+ <li><strong>Clean up database:</strong> Removes references to permanently deleted files</li>+ <li><strong>Detect external changes:</strong> Finds files that were moved, renamed, or deleted outside the app</li>+ </ul>++ <h3>When should you use this?</h3>+ <ul>+ <li>After manually deleting PDF files from the storage folder</li>+ <li>After moving the library folder to a different location</li>+ <li>If you're experiencing "file not found" errors when opening PDFs</li>+ <li>After a system crash or unexpected shutdown</li>+ <li>Periodically to ensure database integrity</li>+ </ul>++ <div class="sync-warning" style="background: #fff3cd; padding: 10px; border-radius: 5px; margin-top: 15px;">+ <i class="fas fa-info-circle" style="color: #856404;"></i>+ <strong>Note:</strong> This operation only checks files - it doesn't modify or delete any PDFs. Missing files can be re-downloaded using the Download Manager.+ </div>+ </div>++ <div id="sync-progress" style="display: none; margin-top: 20px;">+ <div class="progress-bar">+ <div class="progress-fill" style="width: 0%"></div>+ </div>+ <p id="sync-status">Checking files...</p>+ </div>++ <div id="sync-results" style="display: none; margin-top: 20px;">+ <h3>Sync Results</h3>+ <div class="sync-stats" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px;">+ <div style="background: #d4edda; padding: 10px; border-radius: 5px;">+ <i class="fas fa-check-circle" style="color: #155724;"></i>+ <strong>Files Found:</strong> <span id="files-found">0</span>+ </div>+ <div style="background: #f8d7da; padding: 10px; border-radius: 5px;">+ <i class="fas fa-exclamation-circle" style="color: #721c24;"></i>+ <strong>Files Missing:</strong> <span id="files-missing">0</span>+ </div>+ </div>+ <div id="missing-files-action" style="display: none; margin-top: 15px; padding: 10px; background: #e7f3ff; border-radius: 5px;">+ <p><strong>Missing files detected!</strong> These files have been marked in the database and can be re-downloaded.</p>+ <button class="btn btn-primary" onclick="goToDownloadManager()">Go to Download Manager</button>+ </div>+ </div>+ </div>+ <div class="modal-footer">+ <button id="sync-start-btn" class="btn btn-primary" onclick="performSync()">+ <i class="fas fa-play"></i> Start Sync+ </button>+ <button id="sync-close-btn" class="btn btn-secondary" onclick="closeSyncModal()">Close</button>+ </div>+ </div>+</div>+<style>.library-container {padding: 20px;@@ -512,19 +579,22 @@ function filterDocuments() {});}-// Download all new articles+// Current download controller for cancellation+let currentDownloadController = null;++// Download all new articles with progressasync function downloadAllNew() {const btn = event.target.closest('button');const originalContent = btn.innerHTML;- btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Queueing...';+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Preparing...';btn.disabled = true;try {// Get CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';- // Queue all undownloaded articles- const response = await fetch('/library/api/queue-all-undownloaded', {+ // First, queue all undownloaded articles to get the list+ const queueResponse = await fetch('/library/api/queue-all-undownloaded', {method: 'POST',headers: {'Content-Type': 'application/json',@@ -532,42 +602,206 @@ async function downloadAllNew() {}});- if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);+ if (!queueResponse.ok) {+ throw new Error(`HTTP error! status: ${queueResponse.status}`);}- const result = await response.json();+ const queueResult = await queueResponse.json();- if (result.queued === 0) {+ if (queueResult.queued === 0) {alert('No new articles to download. All available articles have already been downloaded.');btn.innerHTML = originalContent;btn.disabled = false;return;}- // Redirect to download manager to start downloads- alert(`Queued ${result.queued} articles for download. Redirecting to Download Manager...`);- window.location.href = '/library/download-manager';+ // Show progress modal+ showDownloadProgressModal();++ // Reset progress+ document.getElementById('overall-progress').style.width = '0%';+ document.getElementById('current-count').textContent = '0';+ document.getElementById('total-count').textContent = queueResult.queued;+ document.getElementById('download-log').innerHTML = '';++ // Start the bulk download with the research IDs+ btn.innerHTML = originalContent;+ btn.disabled = false;++ // Create abort controller for cancellation+ currentDownloadController = new AbortController();++ // Start streaming download+ const downloadResponse = await fetch('/library/api/download-bulk', {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({research_ids: queueResult.research_ids || []}),+ signal: currentDownloadController.signal+ });++ const reader = downloadResponse.body.getReader();+ const decoder = new TextDecoder();++ while (true) {+ const {done, value} = await reader.read();+ if (done) break;++ const chunk = decoder.decode(value);+ const lines = chunk.split('\n');++ for (const line of lines) {+ if (line.startsWith('data: ')) {+ const data = JSON.parse(line.slice(6));+ updateDownloadProgress(data);++ // Check if download is complete+ if (data.complete) {+ currentDownloadController = null;+ setTimeout(() => {+ closeProgressModal();+ location.reload();+ }, 2000);+ }+ }+ }+ }} catch (error) {- console.error('Failed to queue downloads:', error);- alert('Failed to queue downloads. Please try again.');+ if (error.name === 'AbortError') {+ console.log('Download cancelled by user');+ const log = document.getElementById('download-log');+ const entry = document.createElement('div');+ entry.className = 'download-entry cancelled';+ entry.innerHTML = '<strong>Download cancelled by user</strong>';+ log.appendChild(entry);+ } else {+ console.error('Failed to start downloads:', error);+ alert('Failed to start downloads. Please try again.');+ }btn.innerHTML = originalContent;btn.disabled = false;+ } finally {+ currentDownloadController = null;}}-// Sync library with filesystem-async function syncLibrary() {- const btn = event.target.closest('button');+// Show download progress modal+function showDownloadProgressModal() {+ document.getElementById('download-progress-modal').style.display = 'block';+}++// Update download progress+function updateDownloadProgress(data) {+ const progressBar = document.getElementById('overall-progress');+ const currentCount = document.getElementById('current-count');+ const totalCount = document.getElementById('total-count');+ const log = document.getElementById('download-log');++ // Fix negative total count+ const actualTotal = Math.abs(data.total);++ progressBar.style.width = `${data.progress}%`;+ currentCount.textContent = data.current;+ totalCount.textContent = actualTotal;++ if (data.file) {+ const entry = document.createElement('div');+ entry.className = `download-entry ${data.status}`;++ let statusIcon = '';+ let statusText = '';++ if (data.status === 'success') {+ statusIcon = '✓';+ statusText = 'Downloaded';+ } else if (data.status === 'skipped') {+ statusIcon = '⊘';+ // Use the error field which contains the skip reason+ statusText = data.error || data.skip_reason || 'Skipped';+ } else if (data.status === 'failed') {+ statusIcon = '✗';+ statusText = data.error || data.skip_reason || 'Failed';+ }++ entry.innerHTML = `+ <span class="status-icon">${statusIcon}</span>+ <div class="entry-details">+ <strong>${data.file}</strong>+ <span class="status-text">${statusText}</span>+ </div>+ `;++ log.appendChild(entry);+ log.scrollTop = log.scrollHeight;+ }+}++// Close progress modal+function closeProgressModal() {+ document.getElementById('download-progress-modal').style.display = 'none';+}++// Cancel downloads+function cancelDownloads() {+ if (currentDownloadController) {+ currentDownloadController.abort();+ currentDownloadController = null;++ // Update UI to show cancellation+ const progressBar = document.getElementById('overall-progress');+ progressBar.style.backgroundColor = '#f44336';++ // Close modal after a delay+ setTimeout(() => {+ closeProgressModal();+ location.reload();+ }, 1500);+ } else {+ // If no active download, just close modal+ closeProgressModal();+ }+}++// Show sync modal+function showSyncModal() {+ document.getElementById('sync-library-modal').style.display = 'block';+ // Reset modal state+ document.getElementById('sync-progress').style.display = 'none';+ document.getElementById('sync-results').style.display = 'none';+ document.querySelector('.sync-explanation').style.display = 'block';+ document.getElementById('sync-start-btn').style.display = 'inline-block';+ document.getElementById('sync-start-btn').disabled = false;+ document.getElementById('sync-start-btn').innerHTML = '<i class="fas fa-play"></i> Start Sync';+}++// Close sync modal+function closeSyncModal() {+ document.getElementById('sync-library-modal').style.display = 'none';+}++// Go to download manager+function goToDownloadManager() {+ window.location.href = '/library/download-manager';+}++// Perform the actual sync+async function performSync() {+ const btn = document.getElementById('sync-start-btn');const originalContent = btn.innerHTML;++ // Update UI to show progressbtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Syncing...';btn.disabled = true;+ document.querySelector('.sync-explanation').style.display = 'none';+ document.getElementById('sync-progress').style.display = 'block';+ document.getElementById('sync-status').textContent = 'Checking files in your library...';try {// Get CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');-const response = await fetch('/library/api/sync-library', {method: 'POST',headers: {@@ -583,27 +817,41 @@ async function syncLibrary() {const stats = await response.json();// Show results- let message = `Sync Complete!\n\nFiles found: ${stats.files_found}\nFiles missing: ${stats.files_missing}`;+ document.getElementById('sync-progress').style.display = 'none';+ document.getElementById('sync-results').style.display = 'block';+ document.getElementById('files-found').textContent = stats.files_found;+ document.getElementById('files-missing').textContent = stats.files_missing;+ // Show action for missing files if anyif (stats.files_missing > 0) {- message += `\n\n${stats.files_missing} files were marked as missing and can be re-downloaded.`;-- // Ask if user wants to re-download missing files- if (confirm(message + '\n\nDo you want to go to Download Manager to re-download missing files?')) {- window.location.href = '/library/download-manager';- } else {- location.reload();- }+ document.getElementById('missing-files-action').style.display = 'block';} else {- alert(message);+ document.getElementById('missing-files-action').style.display = 'none';+ }++ // Hide start button, only show close+ btn.style.display = 'none';++ // Update the library stats if sync completed successfully+ if (stats.files_found >= 0) {+ // Optionally reload to refresh the document list+ setTimeout(() => {+ if (stats.files_missing === 0) {+ location.reload();+ }+ }, 2000);}} catch (error) {console.error('Sync failed:', error);- alert('Failed to sync library. Please try again.');- } finally {+ document.getElementById('sync-progress').style.display = 'none';+ document.getElementById('sync-status').textContent = 'Sync failed. Please try again.';+ alert('Failed to sync library. Please check your connection and try again.');++ // Reset buttonbtn.innerHTML = originalContent;btn.disabled = false;+ document.querySelector('.sync-explanation').style.display = 'block';}}