Skip to content

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

feat: implement modular download system with detailed skip reasons

LearningCircuitdc7bbff20ee8
diff --git a/src/local_deep_research/research_library/downloaders/__init__.py b/src/local_deep_research/research_library/downloaders/__init__.py
new file mode 100644
index 0000000000..0bbde9113a
--- /dev/null
+++ b/src/local_deep_research/research_library/downloaders/__init__.py
@@ -0,0 +1,20 @@
+"""
+Academic Content Downloaders for various sources
+Supports both PDF and full-text extraction
+"""
+
+from .base import BaseDownloader, ContentType, DownloadResult
+from .arxiv import ArxivDownloader
+from .pubmed import PubMedDownloader
+from .biorxiv import BioRxivDownloader
+from .generic import GenericDownloader
+
+__all__ = [
+ "BaseDownloader",
+ "ContentType",
+ "DownloadResult",
+ "ArxivDownloader",
+ "PubMedDownloader",
+ "BioRxivDownloader",
+ "GenericDownloader",
+]
diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.py
new file mode 100644
index 0000000000..4d366c7430
--- /dev/null
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@ -0,0 +1,199 @@
+"""
+arXiv PDF and Text Downloader
+"""
+
+import re
+from typing import Optional
+from loguru import logger
+
+from .base import BaseDownloader, ContentType, DownloadResult
+
+
+class ArxivDownloader(BaseDownloader):
+ """Downloader for arXiv papers with PDF and abstract/text support."""
+
+ def can_handle(self, url: str) -> bool:
+ """Check if URL is from arXiv."""
+ return "arxiv.org" in url
+
+ def download(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> Optional[bytes]:
+ """Download content from arXiv."""
+ if content_type == ContentType.TEXT:
+ return self._download_text(url)
+ else:
+ return self._download_pdf(url)
+
+ def download_with_result(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> DownloadResult:
+ """Download content and return detailed result with skip reason."""
+ # Extract arXiv ID
+ arxiv_id = self._extract_arxiv_id(url)
+ if not arxiv_id:
+ return DownloadResult(
+ skip_reason="Invalid arXiv URL - could not extract article ID"
+ )
+
+ if content_type == ContentType.TEXT:
+ # Try to get text via API first
+ text = self._fetch_from_arxiv_api(arxiv_id)
+ if text:
+ return DownloadResult(
+ content=text.encode("utf-8"), is_success=True
+ )
+
+ # Fallback to PDF extraction
+ pdf_content = self._download_pdf(url)
+ if pdf_content:
+ extracted_text = self._extract_text_from_pdf(pdf_content)
+ if extracted_text:
+ return DownloadResult(
+ content=extracted_text.encode("utf-8"), is_success=True
+ )
+
+ return DownloadResult(
+ skip_reason=f"Could not retrieve text for arXiv:{arxiv_id}"
+ )
+ else:
+ # Download PDF
+ pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"
+ logger.info(f"Downloading arXiv PDF: {arxiv_id}")
+
+ pdf_content = super()._download_pdf(pdf_url)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+ else:
+ return DownloadResult(
+ skip_reason=f"Failed to download PDF for arXiv:{arxiv_id} - server may be unavailable"
+ )
+
+ def _download_pdf(self, url: str) -> Optional[bytes]:
+ """Download PDF from arXiv."""
+ # Extract arXiv ID
+ arxiv_id = self._extract_arxiv_id(url)
+ if not arxiv_id:
+ logger.error(f"Could not extract arXiv ID from {url}")
+ return None
+
+ # Construct PDF URL
+ pdf_url = f"https://arxiv.org/pdf/{arxiv_id}.pdf"
+
+ logger.info(f"Downloading arXiv PDF: {arxiv_id}")
+ return super()._download_pdf(pdf_url)
+
+ def _download_text(self, url: str) -> Optional[bytes]:
+ """Get text content from arXiv (abstract + metadata via API)."""
+ # Extract arXiv ID
+ arxiv_id = self._extract_arxiv_id(url)
+ if not arxiv_id:
+ return None
+
+ # Use arXiv API to get abstract and metadata
+ text = self._fetch_from_arxiv_api(arxiv_id)
+ if text:
+ return text.encode("utf-8")
+
+ # Fallback: Download PDF and extract text
+ pdf_content = self._download_pdf(url)
+ if pdf_content:
+ extracted_text = self._extract_text_from_pdf(pdf_content)
+ if extracted_text:
+ return extracted_text.encode("utf-8")
+
+ return None
+
+ def _extract_arxiv_id(self, url: str) -> Optional[str]:
+ """Extract arXiv ID from URL."""
+ # Handle different arXiv URL formats
+ patterns = [
+ r"arxiv\.org/abs/(\d+\.\d+)(?:v\d+)?", # New format: 2301.12345 or 2301.12345v2
+ r"arxiv\.org/pdf/(\d+\.\d+)(?:v\d+)?", # PDF URL with optional version
+ r"arxiv\.org/abs/([a-z-]+/\d+)(?:v\d+)?", # Old format: cond-mat/0501234
+ r"arxiv\.org/pdf/([a-z-]+/\d+)(?:v\d+)?", # Old PDF URL with optional version
+ ]
+
+ for pattern in patterns:
+ match = re.search(pattern, url)
+ if match:
+ return match.group(1)
+
+ return None
+
+ def _fetch_from_arxiv_api(self, arxiv_id: str) -> Optional[str]:
+ """Fetch abstract and metadata from arXiv API."""
+ try:
+ # Clean the ID for API query
+ clean_id = arxiv_id.replace("/", "")
+
+ # Query arXiv API
+ api_url = f"http://export.arxiv.org/api/query?id_list={clean_id}"
+ response = self.session.get(api_url, timeout=10)
+
+ if response.status_code == 200:
+ # Parse the Atom feed response
+ import xml.etree.ElementTree as ET
+
+ root = ET.fromstring(response.text)
+
+ # Define namespaces
+ ns = {
+ "atom": "http://www.w3.org/2005/Atom",
+ "arxiv": "http://arxiv.org/schemas/atom",
+ }
+
+ # Find the entry
+ entry = root.find("atom:entry", ns)
+ if entry is not None:
+ # Extract text content
+ text_parts = []
+
+ # Title
+ title = entry.find("atom:title", ns)
+ if title is not None and title.text:
+ text_parts.append(f"Title: {title.text.strip()}")
+
+ # Authors
+ authors = entry.findall("atom:author", ns)
+ if authors:
+ author_names = []
+ for author in authors:
+ name = author.find("atom:name", ns)
+ if name is not None and name.text:
+ author_names.append(name.text.strip())
+ if author_names:
+ text_parts.append(
+ f"Authors: {', '.join(author_names)}"
+ )
+
+ # Abstract
+ summary = entry.find("atom:summary", ns)
+ if summary is not None and summary.text:
+ text_parts.append(
+ f"\nAbstract:\n{summary.text.strip()}"
+ )
+
+ # Categories
+ categories = entry.findall("atom:category", ns)
+ if categories:
+ cat_terms = [
+ cat.get("term")
+ for cat in categories
+ if cat.get("term")
+ ]
+ if cat_terms:
+ text_parts.append(
+ f"\nCategories: {', '.join(cat_terms)}"
+ )
+
+ if text_parts:
+ logger.info(
+ f"Retrieved text content from arXiv API for {arxiv_id}"
+ )
+ return "\n".join(text_parts)
+
+ except Exception as e:
+ logger.debug(f"Failed to fetch from arXiv API: {e}")
+
+ return None
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
new file mode 100644
index 0000000000..5e47735c7c
--- /dev/null
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -0,0 +1,255 @@
+"""
+Base Academic Content Downloader Abstract Class
+"""
+
+from abc import ABC, abstractmethod
+from typing import Optional, Dict, Any, NamedTuple
+from enum import Enum
+import requests
+from loguru import logger
+
+
+class ContentType(Enum):
+ """Supported content types for download."""
+
+ PDF = "pdf"
+ TEXT = "text"
+
+
+class DownloadResult(NamedTuple):
+ """Result of a download attempt."""
+
+ content: Optional[bytes] = None
+ skip_reason: Optional[str] = None
+ is_success: bool = False
+
+
+class BaseDownloader(ABC):
+ """Abstract base class for academic content downloaders."""
+
+ def __init__(self, timeout: int = 30):
+ """
+ Initialize the downloader.
+
+ Args:
+ timeout: Request timeout in seconds
+ """
+ self.timeout = timeout
+ self.session = requests.Session()
+ self.session.headers.update(
+ {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ }
+ )
+
+ @abstractmethod
+ def can_handle(self, url: str) -> bool:
+ """
+ Check if this downloader can handle the given URL.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if this downloader can handle the URL
+ """
+ pass
+
+ @abstractmethod
+ def download(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> Optional[bytes]:
+ """
+ Download content from the given URL.
+
+ Args:
+ url: The URL to download from
+ content_type: Type of content to download (PDF or TEXT)
+
+ Returns:
+ Content as bytes, or None if download failed
+ For TEXT type, returns UTF-8 encoded text as bytes
+ """
+ pass
+
+ def download_pdf(self, url: str) -> Optional[bytes]:
+ """
+ Convenience method to download PDF.
+
+ Args:
+ url: The URL to download from
+
+ Returns:
+ PDF content as bytes, or None if download failed
+ """
+ return self.download(url, ContentType.PDF)
+
+ def download_with_result(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> DownloadResult:
+ """
+ Download content and return detailed result with skip reason.
+
+ Args:
+ url: The URL to download from
+ content_type: Type of content to download
+
+ Returns:
+ DownloadResult with content and/or skip reason
+ """
+ # Default implementation - derived classes should override for specific reasons
+ content = self.download(url, content_type)
+ if content:
+ return DownloadResult(content=content, is_success=True)
+ else:
+ return DownloadResult(
+ skip_reason="Download failed - content not available"
+ )
+
+ def download_text(self, url: str) -> Optional[str]:
+ """
+ Convenience method to download and return text content.
+
+ Args:
+ url: The URL to download from
+
+ Returns:
+ Text content as string, or None if download failed
+ """
+ content = self.download(url, ContentType.TEXT)
+ if content:
+ try:
+ return content.decode("utf-8")
+ except UnicodeDecodeError:
+ logger.exception(f"Failed to decode text content from {url}")
+ return None
+
+ def _is_pdf_content(self, response: requests.Response) -> bool:
+ """
+ Check if response contains PDF content.
+
+ Args:
+ response: The response to check
+
+ Returns:
+ True if response appears to contain PDF content
+ """
+ content_type = response.headers.get("content-type", "").lower()
+
+ # Check content type
+ if "pdf" in content_type:
+ return True
+
+ # Check if content starts with PDF magic bytes
+ if len(response.content) > 4:
+ return response.content[:4] == b"%PDF"
+
+ return False
+
+ def _download_pdf(
+ self, url: str, headers: Optional[Dict[str, str]] = None
+ ) -> Optional[bytes]:
+ """
+ Helper method to download PDF with error handling.
+
+ Args:
+ url: The URL to download
+ headers: Optional additional headers
+
+ Returns:
+ PDF content as bytes, or None if download failed
+ """
+ try:
+ if headers:
+ request_headers = self.session.headers.copy()
+ request_headers.update(headers)
+ else:
+ request_headers = self.session.headers
+
+ response = self.session.get(
+ url,
+ headers=request_headers,
+ timeout=self.timeout,
+ allow_redirects=True,
+ )
+
+ if response.status_code == 200:
+ if self._is_pdf_content(response):
+ logger.debug(f"Successfully downloaded PDF from {url}")
+ return response.content
+ else:
+ logger.warning(
+ f"Response is not a PDF: {response.headers.get('content-type', 'unknown')}"
+ )
+ else:
+ logger.warning(
+ f"Failed to download from {url}: HTTP {response.status_code}"
+ )
+
+ except requests.exceptions.Timeout:
+ logger.exception(f"Timeout downloading from {url}")
+ except requests.exceptions.RequestException:
+ logger.exception(f"Error downloading from {url}")
+ except Exception:
+ logger.exception(f"Unexpected error downloading from {url}")
+
+ return None
+
+ def _extract_text_from_pdf(self, pdf_content: bytes) -> Optional[str]:
+ """
+ Extract text from PDF content.
+
+ Args:
+ pdf_content: PDF file content as bytes
+
+ Returns:
+ Extracted text, or None if extraction failed
+ """
+ try:
+ import io
+ import PyPDF2
+
+ pdf_file = io.BytesIO(pdf_content)
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
+
+ text_content = []
+ for page_num in range(len(pdf_reader.pages)):
+ page = pdf_reader.pages[page_num]
+ text_content.append(page.extract_text())
+
+ full_text = "\n".join(text_content)
+ return full_text if full_text.strip() else None
+
+ except ImportError:
+ logger.warning("PyPDF2 not installed, cannot extract text from PDF")
+ return None
+ except Exception:
+ logger.exception("Failed to extract text from PDF")
+ return None
+
+ def _fetch_text_from_api(self, url: str) -> Optional[str]:
+ """
+ Fetch full text directly from API.
+
+ This is a placeholder - derived classes should implement
+ API-specific text fetching logic.
+
+ Args:
+ url: The URL or identifier
+
+ Returns:
+ Full text content, or None if not available
+ """
+ return None
+
+ def get_metadata(self, url: str) -> Dict[str, Any]:
+ """
+ Get metadata about the resource (optional override).
+
+ Args:
+ url: The URL to get metadata for
+
+ Returns:
+ Dictionary with metadata
+ """
+ return {}
diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.py
new file mode 100644
index 0000000000..eb461c79f4
--- /dev/null
+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py
@@ -0,0 +1,184 @@
+"""
+bioRxiv/medRxiv PDF and Text Downloader
+"""
+
+import re
+from typing import Optional
+from loguru import logger
+
+from .base import BaseDownloader, ContentType, DownloadResult
+
+
+class BioRxivDownloader(BaseDownloader):
+ """Downloader for bioRxiv and medRxiv preprints."""
+
+ def can_handle(self, url: str) -> bool:
+ """Check if URL is from bioRxiv or medRxiv."""
+ return "biorxiv.org" in url or "medrxiv.org" in url
+
+ def download(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> Optional[bytes]:
+ """Download content from bioRxiv/medRxiv."""
+ if content_type == ContentType.TEXT:
+ return self._download_text(url)
+ else:
+ return self._download_pdf(url)
+
+ def download_with_result(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> DownloadResult:
+ """Download content and return detailed result with skip reason."""
+ if content_type == ContentType.TEXT:
+ # Try to get text from page
+ text = self._fetch_abstract_from_page(url)
+ if text:
+ return DownloadResult(
+ content=text.encode("utf-8"), is_success=True
+ )
+
+ # Fallback to PDF extraction
+ pdf_content = self._download_pdf(url)
+ if pdf_content:
+ extracted_text = self._extract_text_from_pdf(pdf_content)
+ if extracted_text:
+ return DownloadResult(
+ content=extracted_text.encode("utf-8"), is_success=True
+ )
+
+ return DownloadResult(
+ skip_reason="Could not extract text from bioRxiv/medRxiv article"
+ )
+ else:
+ # Try to download PDF
+ pdf_url = self._convert_to_pdf_url(url)
+ if not pdf_url:
+ return DownloadResult(
+ skip_reason="Invalid bioRxiv/medRxiv URL format"
+ )
+
+ logger.info(f"Downloading bioRxiv/medRxiv PDF from {pdf_url}")
+ pdf_content = super()._download_pdf(pdf_url)
+
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+ else:
+ # Check if it's a server issue or article doesn't exist
+ try:
+ response = self.session.head(url, timeout=5)
+ if response.status_code == 404:
+ return DownloadResult(
+ skip_reason="Article not found on bioRxiv/medRxiv"
+ )
+ elif response.status_code >= 500:
+ return DownloadResult(
+ skip_reason="bioRxiv/medRxiv server temporarily unavailable"
+ )
+ except:
+ pass
+ return DownloadResult(
+ skip_reason="Failed to download PDF from bioRxiv/medRxiv"
+ )
+
+ def _download_pdf(self, url: str) -> Optional[bytes]:
+ """Download PDF from bioRxiv/medRxiv."""
+ # Convert URL to PDF format
+ pdf_url = self._convert_to_pdf_url(url)
+
+ if not pdf_url:
+ logger.error(f"Could not convert to PDF URL: {url}")
+ return None
+
+ logger.info(f"Downloading bioRxiv/medRxiv PDF from {pdf_url}")
+ return super()._download_pdf(pdf_url)
+
+ def _download_text(self, url: str) -> Optional[bytes]:
+ """Get text content from bioRxiv/medRxiv."""
+ # Try to get abstract and metadata from the HTML page
+ text = self._fetch_abstract_from_page(url)
+ if text:
+ return text.encode("utf-8")
+
+ # Fallback: Download PDF and extract text
+ pdf_content = self._download_pdf(url)
+ if pdf_content:
+ extracted_text = self._extract_text_from_pdf(pdf_content)
+ if extracted_text:
+ return extracted_text.encode("utf-8")
+
+ return None
+
+ def _convert_to_pdf_url(self, url: str) -> Optional[str]:
+ """Convert bioRxiv/medRxiv URL to PDF URL."""
+ # Handle different URL patterns
+ # Example: https://www.biorxiv.org/content/10.1101/2024.01.01.123456v1
+ # Becomes: https://www.biorxiv.org/content/10.1101/2024.01.01.123456v1.full.pdf
+
+ # Remove any existing .full or .full.pdf
+ base_url = re.sub(r"\.full(\.pdf)?$", "", url)
+
+ # Check if it's already a PDF URL
+ if base_url.endswith(".pdf"):
+ return base_url
+
+ # Add .full.pdf
+ pdf_url = base_url.rstrip("/") + ".full.pdf"
+
+ # Handle content vs. content/early URLs
+ pdf_url = pdf_url.replace("/content/early/", "/content/")
+
+ return pdf_url
+
+ def _fetch_abstract_from_page(self, url: str) -> Optional[str]:
+ """Fetch abstract and metadata from bioRxiv/medRxiv page."""
+ try:
+ # Request the HTML page
+ response = self.session.get(url, timeout=10)
+
+ if response.status_code == 200:
+ # Simple extraction using regex (avoiding BeautifulSoup dependency)
+ html = response.text
+ text_parts = []
+
+ # Extract title
+ title_match = re.search(
+ r'<meta\s+name="DC\.Title"\s+content="([^"]+)"', html
+ )
+ if title_match:
+ text_parts.append(f"Title: {title_match.group(1)}")
+
+ # Extract authors
+ author_match = re.search(
+ r'<meta\s+name="DC\.Creator"\s+content="([^"]+)"', html
+ )
+ if author_match:
+ text_parts.append(f"Authors: {author_match.group(1)}")
+
+ # Extract abstract
+ abstract_match = re.search(
+ r'<meta\s+name="DC\.Description"\s+content="([^"]+)"',
+ html,
+ re.DOTALL,
+ )
+ if abstract_match:
+ abstract = abstract_match.group(1)
+ # Clean up HTML entities
+ abstract = abstract.replace("&lt;", "<").replace(
+ "&gt;", ">"
+ )
+ abstract = abstract.replace("&quot;", '"').replace(
+ "&#39;", "'"
+ )
+ abstract = abstract.replace("&amp;", "&")
+ text_parts.append(f"\nAbstract:\n{abstract}")
+
+ if text_parts:
+ logger.info(
+ "Retrieved text content from bioRxiv/medRxiv page"
+ )
+ return "\n".join(text_parts)
+
+ except Exception as e:
+ logger.debug(f"Failed to fetch abstract from bioRxiv/medRxiv: {e}")
+
+ return None
diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.py
new file mode 100644
index 0000000000..71745ac88e
--- /dev/null
+++ b/src/local_deep_research/research_library/downloaders/generic.py
@@ -0,0 +1,117 @@
+"""
+Generic PDF Downloader for unspecified sources
+"""
+
+from typing import Optional
+from loguru import logger
+
+from .base import BaseDownloader, ContentType, DownloadResult
+
+
+class GenericDownloader(BaseDownloader):
+ """Generic downloader for any URL - attempts basic PDF download."""
+
+ def can_handle(self, url: str) -> bool:
+ """Generic downloader can handle any URL as a fallback."""
+ return True
+
+ def download(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> Optional[bytes]:
+ """Attempt to download content from any URL."""
+ if content_type == ContentType.TEXT:
+ # For generic sources, we can only extract text from PDF
+ pdf_content = self._download_pdf(url)
+ if pdf_content:
+ text = self._extract_text_from_pdf(pdf_content)
+ if text:
+ return text.encode("utf-8")
+ return None
+ else:
+ # Try to download as PDF
+ return self._download_pdf(url)
+
+ def download_with_result(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> DownloadResult:
+ """Download content and return detailed result with skip reason."""
+ if content_type == ContentType.TEXT:
+ # For generic sources, we can only extract text from PDF
+ pdf_content = self._download_pdf(url)
+ if pdf_content:
+ text = self._extract_text_from_pdf(pdf_content)
+ if text:
+ return DownloadResult(
+ content=text.encode("utf-8"), is_success=True
+ )
+ else:
+ return DownloadResult(
+ skip_reason="PDF downloaded but text extraction failed"
+ )
+ return DownloadResult(skip_reason="Could not download PDF from URL")
+ else:
+ # Try to download as PDF
+ logger.info(f"Attempting generic download from {url}")
+
+ # Try direct download
+ pdf_content = super()._download_pdf(url)
+
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF from {url}")
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ # If the URL doesn't end with .pdf, try adding it
+ if not url.endswith(".pdf"):
+ pdf_url = url.rstrip("/") + ".pdf"
+ logger.debug(f"Trying with .pdf extension: {pdf_url}")
+ pdf_content = super()._download_pdf(pdf_url)
+
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF from {pdf_url}")
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ # Try to determine more specific reason
+ try:
+ response = self.session.head(
+ url, timeout=5, allow_redirects=True
+ )
+ if response.status_code == 404:
+ return DownloadResult(skip_reason="URL not found (404)")
+ elif response.status_code == 403:
+ return DownloadResult(
+ skip_reason="Access forbidden - authentication may be required"
+ )
+ elif response.status_code >= 500:
+ return DownloadResult(
+ skip_reason="Server error - site may be temporarily unavailable"
+ )
+ else:
+ return DownloadResult(
+ skip_reason=f"Failed to download - HTTP {response.status_code}"
+ )
+ except:
+ return DownloadResult(skip_reason="Could not connect to server")
+
+ def _download_pdf(self, url: str) -> Optional[bytes]:
+ """Attempt to download PDF from URL."""
+ logger.info(f"Attempting generic download from {url}")
+
+ # Try direct download
+ pdf_content = super()._download_pdf(url)
+
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF from {url}")
+ return pdf_content
+
+ # If the URL doesn't end with .pdf, try adding it
+ if not url.endswith(".pdf"):
+ pdf_url = url.rstrip("/") + ".pdf"
+ logger.debug(f"Trying with .pdf extension: {pdf_url}")
+ pdf_content = super()._download_pdf(pdf_url)
+
+ if pdf_content:
+ logger.info(f"Successfully downloaded PDF from {pdf_url}")
+ return pdf_content
+
+ logger.warning(f"Failed to download PDF from {url}")
+ return None
diff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.py
new file mode 100644
index 0000000000..727c0b985b
--- /dev/null
+++ b/src/local_deep_research/research_library/downloaders/pubmed.py
@@ -0,0 +1,470 @@
+"""
+PubMed/PMC PDF Downloader
+"""
+
+import re
+import time
+from typing import Optional
+from loguru import logger
+
+from .base import BaseDownloader, ContentType, DownloadResult
+
+
+class PubMedDownloader(BaseDownloader):
+ """Downloader for PubMed and PubMed Central articles with PDF and text support."""
+
+ def __init__(self, timeout: int = 30, rate_limit_delay: float = 1.0):
+ """
+ Initialize PubMed downloader.
+
+ Args:
+ timeout: Request timeout in seconds
+ rate_limit_delay: Delay between requests to avoid rate limiting
+ """
+ super().__init__(timeout)
+ self.rate_limit_delay = rate_limit_delay
+ self.last_request_time = 0
+
+ def can_handle(self, url: str) -> bool:
+ """Check if URL is from PubMed or PMC."""
+ return any(
+ domain in url
+ for domain in [
+ "pubmed.ncbi.nlm.nih.gov",
+ "ncbi.nlm.nih.gov/pmc",
+ "europepmc.org",
+ ]
+ )
+
+ def download(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> Optional[bytes]:
+ """Download content from PubMed/PMC."""
+ # Apply rate limiting
+ self._apply_rate_limit()
+
+ if content_type == ContentType.TEXT:
+ # Try to get full text from API
+ return self._download_text(url)
+ else:
+ # Download PDF
+ return self._download_pdf_content(url)
+
+ def download_with_result(
+ self, url: str, content_type: ContentType = ContentType.PDF
+ ) -> DownloadResult:
+ """Download content and return detailed result with skip reason."""
+ # Apply rate limiting
+ self._apply_rate_limit()
+
+ if content_type == ContentType.TEXT:
+ content = self._download_text(url)
+ if content:
+ return DownloadResult(content=content, is_success=True)
+ else:
+ return DownloadResult(
+ skip_reason="Full text not available - may require subscription"
+ )
+ else:
+ # Try to download PDF with detailed tracking
+ return self._download_pdf_with_result(url)
+
+ def _download_pdf_content(self, url: str) -> Optional[bytes]:
+ """Download PDF from PubMed/PMC."""
+ # Handle different URL types
+ if "/pmc/articles/PMC" in url:
+ return self._download_pmc_direct(url)
+ elif "pubmed.ncbi.nlm.nih.gov" in url:
+ return self._download_pubmed(url)
+ elif "europepmc.org" in url:
+ return self._download_europe_pmc(url)
+
+ return None
+
+ def _download_pdf_with_result(self, url: str) -> DownloadResult:
+ """Download PDF and return detailed result with skip reason."""
+ # Handle different URL types
+ if "/pmc/articles/PMC" in url:
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if not pmc_match:
+ return DownloadResult(skip_reason="Invalid PMC URL format")
+
+ pmc_id = pmc_match.group(1)
+ logger.info(f"Downloading PMC article: {pmc_id}")
+
+ # Try Europe PMC first
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ # Try NCBI PMC
+ pdf_content = self._download_via_ncbi_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ return DownloadResult(
+ skip_reason=f"PMC article {pmc_id} not accessible - may be retracted or embargoed"
+ )
+
+ elif "pubmed.ncbi.nlm.nih.gov" in url:
+ # Extract PMID
+ pmid_match = re.search(r"/(\d+)/?", url)
+ if not pmid_match:
+ return DownloadResult(skip_reason="Invalid PubMed URL format")
+
+ pmid = pmid_match.group(1)
+ logger.info(f"Processing PubMed article: {pmid}")
+
+ # Check if article is open access via Europe PMC
+ try:
+ api_url = (
+ "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
+ )
+ params = {"query": f"EXT_ID:{pmid}", "format": "json"}
+
+ response = self.session.get(api_url, params=params, timeout=10)
+
+ if response.status_code == 200:
+ data = response.json()
+ results = data.get("resultList", {}).get("result", [])
+
+ if results:
+ article = results[0]
+
+ # Check if article exists but is not open access
+ if article.get("isOpenAccess") != "Y":
+ journal = article.get(
+ "journalTitle", "Unknown journal"
+ )
+ return DownloadResult(
+ skip_reason=f"Article requires subscription to {journal}"
+ )
+
+ # Check if PDF is available
+ if article.get("hasPDF") != "Y":
+ return DownloadResult(
+ skip_reason="No PDF version available for this article"
+ )
+
+ # Try to download
+ pmcid = article.get("pmcid")
+ if pmcid:
+ pdf_content = self._download_via_europe_pmc(pmcid)
+ if pdf_content:
+ return DownloadResult(
+ content=pdf_content, is_success=True
+ )
+ else:
+ return DownloadResult(
+ skip_reason=f"Article PMID:{pmid} not found in Europe PMC database"
+ )
+ except Exception as e:
+ logger.debug(f"Error checking article status: {e}")
+
+ # Try to find PMC ID via NCBI
+ pmc_id = self._get_pmc_id_from_pmid(pmid)
+ if pmc_id:
+ logger.info(f"Found PMC ID: {pmc_id} for PMID: {pmid}")
+
+ # Try downloading via PMC
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ pdf_content = self._download_via_ncbi_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+
+ return DownloadResult(
+ skip_reason=f"PMC version exists but PDF not accessible (PMC ID: {pmc_id})"
+ )
+
+ return DownloadResult(
+ skip_reason="No free full-text available - article may be paywalled"
+ )
+
+ elif "europepmc.org" in url:
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if pmc_match:
+ pmc_id = pmc_match.group(1)
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(content=pdf_content, is_success=True)
+ return DownloadResult(
+ skip_reason=f"Europe PMC article {pmc_id} not accessible"
+ )
+ return DownloadResult(skip_reason="Invalid Europe PMC URL format")
+
+ return DownloadResult(skip_reason="Unsupported PubMed/PMC URL format")
+
+ def _download_text(self, url: str) -> Optional[bytes]:
+ """Download full text content from PubMed/PMC APIs."""
+ # Extract PMID or PMC ID
+ pmid = None
+ pmc_id = None
+
+ if "pubmed.ncbi.nlm.nih.gov" in url:
+ pmid_match = re.search(r"/(\d+)/?", url)
+ if pmid_match:
+ pmid = pmid_match.group(1)
+ elif "/pmc/articles/PMC" in url:
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if pmc_match:
+ pmc_id = pmc_match.group(1)
+
+ # Try Europe PMC API for full text
+ if pmid or pmc_id:
+ text = self._fetch_text_from_europe_pmc(pmid, pmc_id)
+ if text:
+ return text.encode("utf-8")
+
+ # Fallback: Download PDF and extract text
+ pdf_content = self._download_pdf_content(url)
+ if pdf_content:
+ text = self._extract_text_from_pdf(pdf_content)
+ if text:
+ return text.encode("utf-8")
+
+ return None
+
+ def _fetch_text_from_europe_pmc(
+ self, pmid: Optional[str], pmc_id: Optional[str]
+ ) -> Optional[str]:
+ """Fetch full text from Europe PMC API."""
+ try:
+ # Construct query
+ if pmc_id:
+ query = f"PMC:{pmc_id.replace('PMC', '')}"
+ elif pmid:
+ query = f"EXT_ID:{pmid}"
+ else:
+ return None
+
+ # Get article metadata first
+ api_url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
+ params = {
+ "query": query,
+ "format": "json",
+ "resultType": "core", # Get more detailed results
+ }
+
+ response = self.session.get(api_url, params=params, timeout=10)
+
+ if response.status_code == 200:
+ data = response.json()
+ results = data.get("resultList", {}).get("result", [])
+
+ if results and results[0].get("isOpenAccess") == "Y":
+ article = results[0]
+ # Try to get full text XML
+ if article.get("pmcid"):
+ fulltext_url = f"https://www.ebi.ac.uk/europepmc/webservices/rest/{article['pmcid']}/fullTextXML"
+ text_response = self.session.get(
+ fulltext_url, timeout=30
+ )
+
+ if text_response.status_code == 200:
+ # Extract text from XML (simple approach - just get text content)
+ import re
+
+ xml_content = text_response.text
+ # Remove XML tags to get plain text
+ text = re.sub(r"<[^>]+>", " ", xml_content)
+ text = " ".join(text.split())
+
+ if text:
+ logger.info(
+ "Retrieved full text from Europe PMC API"
+ )
+ return text
+
+ except Exception as e:
+ logger.debug(f"Failed to fetch text from Europe PMC: {e}")
+
+ return None
+
+ def _apply_rate_limit(self):
+ """Apply rate limiting between requests."""
+ current_time = time.time()
+ time_since_last = current_time - self.last_request_time
+
+ if time_since_last < self.rate_limit_delay:
+ sleep_time = self.rate_limit_delay - time_since_last
+ logger.debug(f"Rate limiting: sleeping {sleep_time:.2f}s")
+ time.sleep(sleep_time)
+
+ self.last_request_time = time.time()
+
+ def _download_pmc_direct(self, url: str) -> Optional[bytes]:
+ """Download directly from PMC URL."""
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if not pmc_match:
+ return None
+
+ pmc_id = pmc_match.group(1)
+ logger.info(f"Downloading PMC article: {pmc_id}")
+
+ # Try Europe PMC first (more reliable)
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return pdf_content
+
+ # Fallback to NCBI PMC
+ return self._download_via_ncbi_pmc(pmc_id)
+
+ def _download_pubmed(self, url: str) -> Optional[bytes]:
+ """Download from PubMed URL."""
+ # Extract PMID
+ pmid_match = re.search(r"/(\d+)/?", url)
+ if not pmid_match:
+ return None
+
+ pmid = pmid_match.group(1)
+ logger.info(f"Processing PubMed article: {pmid}")
+
+ # Try Europe PMC API first
+ pdf_content = self._try_europe_pmc_api(pmid)
+ if pdf_content:
+ return pdf_content
+
+ # Try to find PMC ID via NCBI API
+ pmc_id = self._get_pmc_id_from_pmid(pmid)
+ if pmc_id:
+ logger.info(f"Found PMC ID: {pmc_id} for PMID: {pmid}")
+
+ # Try Europe PMC with PMC ID
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return pdf_content
+
+ # Try NCBI PMC
+ pdf_content = self._download_via_ncbi_pmc(pmc_id)
+ if pdf_content:
+ return pdf_content
+
+ logger.info(f"No PMC version available for PMID: {pmid}")
+ return None
+
+ def _download_europe_pmc(self, url: str) -> Optional[bytes]:
+ """Download from Europe PMC URL."""
+ # Extract PMC ID from URL
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if pmc_match:
+ pmc_id = pmc_match.group(1)
+ return self._download_via_europe_pmc(pmc_id)
+ return None
+
+ def _try_europe_pmc_api(self, pmid: str) -> Optional[bytes]:
+ """Try downloading via Europe PMC API using PMID."""
+ try:
+ # Query Europe PMC API
+ api_url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
+ params = {"query": f"EXT_ID:{pmid}", "format": "json"}
+
+ response = self.session.get(api_url, params=params, timeout=10)
+
+ if response.status_code == 200:
+ data = response.json()
+ results = data.get("resultList", {}).get("result", [])
+
+ if results:
+ article = results[0]
+ # Check if article has open access PDF
+ if (
+ article.get("isOpenAccess") == "Y"
+ and article.get("hasPDF") == "Y"
+ ):
+ pmcid = article.get("pmcid")
+ if pmcid:
+ logger.info(
+ f"Found open access PDF via Europe PMC API: {pmcid}"
+ )
+ return self._download_via_europe_pmc(pmcid)
+
+ except Exception as e:
+ logger.debug(f"Europe PMC API query failed: {e}")
+
+ return None
+
+ def _get_pmc_id_from_pmid(self, pmid: str) -> Optional[str]:
+ """Convert PMID to PMC ID using NCBI E-utilities."""
+ try:
+ # Use NCBI E-utilities to find PMC ID
+ elink_url = (
+ "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi"
+ )
+ params = {
+ "dbfrom": "pubmed",
+ "db": "pmc",
+ "id": pmid,
+ "retmode": "json",
+ }
+
+ response = self.session.get(elink_url, params=params, timeout=10)
+
+ if response.status_code == 200:
+ data = response.json()
+ link_sets = data.get("linksets", [])
+
+ if link_sets and "linksetdbs" in link_sets[0]:
+ for linksetdb in link_sets[0]["linksetdbs"]:
+ if linksetdb.get("dbto") == "pmc" and linksetdb.get(
+ "links"
+ ):
+ pmc_id_num = linksetdb["links"][0]
+ return f"PMC{pmc_id_num}"
+
+ except Exception as e:
+ logger.debug(f"NCBI E-utilities lookup failed: {e}")
+
+ # Fallback: Try scraping the PubMed page
+ try:
+ response = self.session.get(
+ f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/", timeout=10
+ )
+
+ if response.status_code == 200:
+ pmc_match = re.search(r"PMC\d+", response.text)
+ if pmc_match:
+ return pmc_match.group(0)
+
+ except Exception as e:
+ logger.debug(f"PubMed page scraping failed: {e}")
+
+ return None
+
+ def _download_via_europe_pmc(self, pmc_id: str) -> Optional[bytes]:
+ """Download PDF via Europe PMC."""
+ # Europe PMC PDF URL
+ pdf_url = f"https://europepmc.org/backend/ptpmcrender.fcgi?accid={pmc_id}&blobtype=pdf"
+
+ logger.debug(f"Trying Europe PMC: {pdf_url}")
+ pdf_content = self._download_pdf(pdf_url)
+
+ if pdf_content:
+ logger.info(f"Successfully downloaded from Europe PMC: {pmc_id}")
+
+ return pdf_content
+
+ def _download_via_ncbi_pmc(self, pmc_id: str) -> Optional[bytes]:
+ """Download PDF via NCBI PMC."""
+ # Try different NCBI PMC URL patterns
+ url_patterns = [
+ f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/pdf/",
+ f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/pdf/main.pdf",
+ ]
+
+ for pdf_url in url_patterns:
+ logger.debug(f"Trying NCBI PMC: {pdf_url}")
+
+ # Add referer header for NCBI
+ headers = {
+ "Referer": f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/"
+ }
+
+ pdf_content = self._download_pdf(pdf_url, headers)
+ if pdf_content:
+ logger.info(f"Successfully downloaded from NCBI PMC: {pmc_id}")
+ return pdf_content
+
+ return None
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index e2bbccb750..787850db2a 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -22,6 +22,9 @@ from loguru import logger
from ...web.auth.decorators import login_required
from ...web.utils.templates import render_template_with_defaults
+from ...database.session_context import get_user_db_session
+from ...database.models.research import ResearchResource
+from ...database.models.library import LibraryDocument, LibraryDownloadQueue
from ..services.download_service import DownloadService
from ..services.library_service import LibraryService
@@ -356,6 +359,7 @@ def download_bulk():
)
# Attempt actual download with error handling
+ skip_reason = None
try:
success = download_service.download_resource(
queue_item.resource_id
@@ -363,10 +367,33 @@ def download_bulk():
status = "success" if success else "skipped"
except Exception as e:
# Log error but continue processing
- logger.exception(
- f"Download error for resource {queue_item.resource_id}: {str(e)}"
+ error_msg = str(e)
+ logger.info(
+ f"Download exception for resource {queue_item.resource_id}: {error_msg}"
)
- status = "failed"
+ # Check if this is a skip reason (not a real error)
+ if any(
+ phrase in error_msg.lower()
+ for phrase in [
+ "paywall",
+ "subscription",
+ "not available",
+ "not found",
+ "no free",
+ "embargoed",
+ "forbidden",
+ "not accessible",
+ "failed to download",
+ "could not",
+ "invalid",
+ "server",
+ ]
+ ):
+ status = "skipped"
+ skip_reason = error_msg
+ else:
+ status = "failed"
+ skip_reason = error_msg # Include error message for failed too
success = False
# Send progress update
@@ -377,6 +404,12 @@ def download_bulk():
"file": file_name,
"status": status,
}
+ # Add skip reason if available
+ if skip_reason:
+ update_data["error"] = skip_reason
+ logger.info(f"Sending skip reason to UI: {skip_reason}")
+
+ logger.info(f"Update data being sent: {update_data}")
yield f"data: {json.dumps(update_data)}\n\n"
yield f"data: {json.dumps({'progress': 100, 'current': total, 'total': total, 'complete': True})}\n\n"
@@ -423,3 +456,81 @@ def mark_for_redownload():
count = service.mark_for_redownload(document_ids)
return jsonify({"success": True, "marked": count})
+
+
+@library_bp.route("/api/queue-all-undownloaded", methods=["POST"])
+@login_required
+def queue_all_undownloaded():
+ """Queue all articles that haven't been downloaded yet."""
+ username = session.get("username")
+
+ with get_user_db_session(username) as db_session:
+ # Find all resources that don't have a completed download
+ undownloaded = (
+ db_session.query(ResearchResource)
+ .outerjoin(
+ LibraryDocument,
+ (ResearchResource.id == LibraryDocument.resource_id)
+ & (LibraryDocument.download_status == "completed"),
+ )
+ .filter(LibraryDocument.id.is_(None))
+ .all()
+ )
+
+ queued_count = 0
+ research_ids = set()
+
+ for resource in undownloaded:
+ # Check if it's downloadable
+ url = 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",
+ ]
+ ):
+ continue
+
+ # Check if already in queue (any status)
+ existing_queue = (
+ db_session.query(LibraryDownloadQueue)
+ .filter_by(resource_id=resource.id)
+ .first()
+ )
+
+ if existing_queue:
+ # If it exists but isn't pending, reset it to pending
+ if existing_queue.status != "pending":
+ existing_queue.status = "pending"
+ existing_queue.completed_at = None
+ queued_count += 1
+ research_ids.add(resource.research_id)
+ else:
+ # Add new entry to queue
+ queue_entry = LibraryDownloadQueue(
+ resource_id=resource.id,
+ research_id=resource.research_id,
+ priority=0,
+ status="pending",
+ )
+ db_session.add(queue_entry)
+ queued_count += 1
+ research_ids.add(resource.research_id)
+
+ db_session.commit()
+
+ return jsonify(
+ {
+ "success": True,
+ "queued": queued_count,
+ "research_ids": list(research_ids),
+ "total_undownloaded": len(undownloaded),
+ }
+ )
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index b8a8bf2c8f..82727f31d2 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -29,6 +29,15 @@ from ...database.models.research import ResearchResource
from ...database.session_context import get_user_db_session
from ...utilities.db_utils import get_settings_manager
+# Import our modular downloaders
+from ..downloaders import (
+ ContentType,
+ ArxivDownloader,
+ PubMedDownloader,
+ BioRxivDownloader,
+ GenericDownloader,
+)
+
class DownloadService:
"""Service for downloading and managing research PDFs."""
@@ -51,19 +60,13 @@ class DownloadService:
# Create directory structure
self._setup_directories()
- # Rate limiting for PubMed (track last request time)
- self._last_pubmed_request = 0
- self._pubmed_delay = 1.0 # 1 second delay between PubMed requests
-
- # Download strategies for different sources
- self.strategies = {
- "arxiv.org": self._download_arxiv,
- "ncbi.nlm.nih.gov": self._download_pubmed,
- "pubmed.ncbi.nlm.nih.gov": self._download_pubmed,
- "semanticscholar.org": self._download_semantic_scholar,
- "biorxiv.org": self._download_biorxiv,
- "medrxiv.org": self._download_medrxiv,
- }
+ # Initialize modular downloaders
+ self.downloaders = [
+ ArxivDownloader(timeout=30),
+ PubMedDownloader(timeout=30, rate_limit_delay=1.0),
+ BioRxivDownloader(timeout=30),
+ GenericDownloader(timeout=30), # Generic should be last (fallback)
+ ]
def _setup_directories(self):
"""Create library directory structure."""
@@ -122,6 +125,50 @@ class DownloadService:
return False, None
+ def get_text_content(self, resource_id: int) -> Optional[str]:
+ """
+ Get text content for a research resource.
+
+ This will try to:
+ 1. Fetch text directly from APIs if available
+ 2. Extract text from downloaded PDF if exists
+ 3. Download PDF and extract text if not yet downloaded
+
+ Args:
+ resource_id: ID of the research resource
+
+ Returns:
+ Text content as string, or None if extraction failed
+ """
+ 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 None
+
+ url = resource.url
+
+ # Find appropriate downloader
+ for downloader in self.downloaders:
+ if downloader.can_handle(url):
+ logger.info(
+ f"Using {downloader.__class__.__name__} for text extraction from {url}"
+ )
+ try:
+ # Try to get text content
+ text = downloader.download_text(url)
+ if text:
+ logger.info(
+ f"Successfully extracted text for: {resource.title[:50]}"
+ )
+ return text
+ except Exception:
+ logger.exception("Failed to extract text")
+ break
+
+ logger.warning(f"Could not extract text for {url}")
+ return None
+
def queue_research_downloads(self, research_id: str) -> int:
"""
Queue all downloadable PDFs from a research session.
@@ -283,7 +330,6 @@ class DownloadService:
True if successful, False otherwise
"""
url = resource.url
- domain = urlparse(url).netloc
# Log attempt
attempt = DownloadAttempt(
@@ -296,17 +342,38 @@ class DownloadService:
session.add(attempt)
try:
- # Choose download strategy based on domain
- for pattern, strategy in self.strategies.items():
- if pattern in domain:
- pdf_content = strategy(url)
- break
- else:
- # Generic download
- pdf_content = self._download_generic(url)
+ # Use modular downloaders with detailed skip reasons
+ pdf_content = None
+ downloader_used = None
+ skip_reason = None
+
+ for downloader in self.downloaders:
+ if downloader.can_handle(url):
+ logger.info(
+ f"Using {downloader.__class__.__name__} for {url}"
+ )
+ result = downloader.download_with_result(
+ url, ContentType.PDF
+ )
+ downloader_used = downloader.__class__.__name__
+
+ if result.is_success and result.content:
+ pdf_content = result.content
+ break
+ elif result.skip_reason:
+ skip_reason = result.skip_reason
+ logger.info(f"Download skipped: {skip_reason}")
+ # Keep trying other downloaders unless it's the GenericDownloader
+ if isinstance(downloader, GenericDownloader):
+ break
+
+ if not downloader_used:
+ logger.error(f"No downloader found for {url}")
+ skip_reason = "No compatible downloader available"
if not pdf_content:
- raise Exception("Failed to download PDF content")
+ error_msg = skip_reason or "Failed to download PDF content"
+ raise Exception(error_msg)
# Save file
file_path = self._save_pdf(resource, pdf_content)
@@ -322,6 +389,9 @@ class DownloadService:
tracker.is_downloaded = True
tracker.downloaded_at = datetime.now(UTC)
+ # Update attempt with success info
+ attempt.succeeded = True
+
# Check if library document already exists
existing_doc = (
session.query(LibraryDocument)
@@ -450,6 +520,54 @@ class DownloadService:
logger.exception("arXiv download failed")
return None
+ def _try_europe_pmc(self, pmid: str) -> Optional[bytes]:
+ """Try downloading from Europe PMC which often has better PDF availability."""
+ try:
+ # Europe PMC API is more reliable for PDFs
+ # Check if PDF is available
+ api_url = f"https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:{pmid}&format=json"
+ response = requests.get(api_url, timeout=10)
+
+ if response.status_code == 200:
+ data = response.json()
+ results = data.get("resultList", {}).get("result", [])
+
+ if results:
+ article = results[0]
+ # Check if article has open access PDF
+ if (
+ article.get("isOpenAccess") == "Y"
+ and article.get("hasPDF") == "Y"
+ ):
+ pmcid = article.get("pmcid")
+ if pmcid:
+ # Europe PMC PDF URL
+ pdf_url = f"https://europepmc.org/backend/ptpmcrender.fcgi?accid={pmcid}&blobtype=pdf"
+ logger.info(
+ f"Found Europe PMC PDF for PMID {pmid}: {pmcid}"
+ )
+
+ headers = {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ }
+
+ pdf_response = requests.get(
+ pdf_url, headers=headers, timeout=30
+ )
+ if pdf_response.status_code == 200:
+ content_type = pdf_response.headers.get(
+ "content-type", ""
+ )
+ if (
+ "pdf" in content_type.lower()
+ or len(pdf_response.content) > 1000
+ ):
+ return pdf_response.content
+ except Exception as e:
+ logger.debug(f"Europe PMC download failed: {e}")
+
+ return None
+
def _download_pubmed(self, url: str) -> Optional[bytes]:
"""Download from PubMed/PubMed Central with rate limiting."""
try:
@@ -469,8 +587,32 @@ class DownloadService:
pmc_match = re.search(r"(PMC\d+)", url)
if pmc_match:
pmc_id = pmc_match.group(1)
- pdf_url = f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/pdf/"
- return self._download_generic(pdf_url)
+
+ # Try Europe PMC (more reliable)
+ europe_url = f"https://europepmc.org/backend/ptpmcrender.fcgi?accid={pmc_id}&blobtype=pdf"
+ headers = {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ }
+
+ try:
+ response = requests.get(
+ europe_url, headers=headers, timeout=30
+ )
+ if response.status_code == 200:
+ content_type = response.headers.get(
+ "content-type", ""
+ )
+ if (
+ "pdf" in content_type.lower()
+ or len(response.content) > 1000
+ ):
+ logger.info(
+ f"Downloaded PDF via Europe PMC for {pmc_id}"
+ )
+ return response.content
+ except Exception as e:
+ logger.debug(f"Direct Europe PMC download failed: {e}")
+ return None
# If it's a regular PubMed URL, try to find PMC version
elif "pubmed.ncbi.nlm.nih.gov" in url:
@@ -478,12 +620,109 @@ class DownloadService:
pmid_match = re.search(r"/(\d+)/?", url)
if pmid_match:
pmid = pmid_match.group(1)
- logger.info(
- f"Attempting to find PMC version for PMID: {pmid}"
- )
+ logger.info(f"Attempting to download PDF for PMID: {pmid}")
+
+ # Try Europe PMC first (more reliable)
+ pdf_content = self._try_europe_pmc(pmid)
+ if pdf_content:
+ return pdf_content
+
+ # First try using NCBI E-utilities API to find PMC ID
+ try:
+ # Use elink to convert PMID to PMCID
+ elink_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi"
+ params = {
+ "dbfrom": "pubmed",
+ "db": "pmc",
+ "id": pmid,
+ "retmode": "json",
+ }
+
+ api_response = requests.get(
+ elink_url, params=params, timeout=10
+ )
+ if api_response.status_code == 200:
+ data = api_response.json()
+ # Parse the response to find PMC ID
+ link_sets = data.get("linksets", [])
+ if link_sets and "linksetdbs" in link_sets[0]:
+ for linksetdb in link_sets[0]["linksetdbs"]:
+ if linksetdb.get(
+ "dbto"
+ ) == "pmc" and linksetdb.get("links"):
+ pmc_id_num = linksetdb["links"][0]
+ # Now fetch PMC details to get the correct PMC ID format
+ esummary_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi"
+ summary_params = {
+ "db": "pmc",
+ "id": pmc_id_num,
+ "retmode": "json",
+ }
+ summary_response = requests.get(
+ esummary_url,
+ params=summary_params,
+ timeout=10,
+ )
+ if summary_response.status_code == 200:
+ summary_data = (
+ summary_response.json()
+ )
+ result = summary_data.get(
+ "result", {}
+ ).get(str(pmc_id_num), {})
+ if result:
+ # PMC IDs in the API don't have the "PMC" prefix
+ pmc_id = f"PMC{pmc_id_num}"
+ logger.info(
+ f"Found PMC ID via API: {pmc_id} for PMID: {pmid}"
+ )
+
+ # Try Europe PMC with the PMC ID
+ europe_url = f"https://europepmc.org/backend/ptpmcrender.fcgi?accid={pmc_id}&blobtype=pdf"
+
+ time.sleep(self._pubmed_delay)
+
+ headers = {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ }
+
+ try:
+ response = requests.get(
+ europe_url,
+ headers=headers,
+ timeout=30,
+ )
+ if (
+ response.status_code
+ == 200
+ ):
+ content_type = response.headers.get(
+ "content-type", ""
+ )
+ if (
+ "pdf"
+ in content_type.lower()
+ or len(
+ response.content
+ )
+ > 1000
+ ):
+ logger.info(
+ f"Downloaded PDF via Europe PMC for {pmc_id}"
+ )
+ return (
+ response.content
+ )
+ except Exception as e:
+ logger.debug(
+ f"Europe PMC download with PMC ID failed: {e}"
+ )
+ except Exception as e:
+ logger.debug(
+ f"API lookup failed, trying webpage scraping: {e}"
+ )
- # Try to fetch the PubMed page to check for PMC availability
- # This is a simple approach - check if PMC link exists
+ # Fallback to webpage scraping if API fails
try:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
@@ -497,16 +736,38 @@ class DownloadService:
if pmc_match:
pmc_id = pmc_match.group(0)
logger.info(
- f"Found PMC ID: {pmc_id} for PMID: {pmid}"
+ f"Found PMC ID via webpage: {pmc_id} for PMID: {pmid}"
)
- pdf_url = f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc_id}/pdf/"
# Add delay before downloading PDF
time.sleep(self._pubmed_delay)
- pdf_content = self._download_generic(pdf_url)
- if pdf_content:
- return pdf_content
+ # Try Europe PMC with the PMC ID (more reliable)
+ europe_url = f"https://europepmc.org/backend/ptpmcrender.fcgi?accid={pmc_id}&blobtype=pdf"
+ headers = {
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
+ }
+
+ try:
+ response = requests.get(
+ europe_url, headers=headers, timeout=30
+ )
+ if response.status_code == 200:
+ content_type = response.headers.get(
+ "content-type", ""
+ )
+ if (
+ "pdf" in content_type.lower()
+ or len(response.content) > 1000
+ ):
+ logger.info(
+ f"Downloaded PDF via Europe PMC for {pmc_id}"
+ )
+ return response.content
+ except Exception as e:
+ logger.debug(
+ f"Europe PMC download failed: {e}"
+ )
else:
logger.info(
f"No PMC version found for PMID: {pmid}"
diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.html
index 1f54dbf9ea..1e41f16e94 100644
--- a/src/local_deep_research/web/templates/pages/download_manager.html
+++ b/src/local_deep_research/web/templates/pages/download_manager.html
@@ -48,46 +48,48 @@
</select>
</div>
- <div class="filter-group">
+ <div class="filter-group date-range">
<label>Date Range</label>
- <input type="date" id="filter-from" class="form-control">
- </div>
-
- <div class="filter-group">
- <label>&nbsp;</label>
- <input type="date" id="filter-to" class="form-control">
+ <div class="date-inputs">
+ <input type="date" id="filter-from" class="form-control" placeholder="From">
+ <span class="date-separator">to</span>
+ <input type="date" id="filter-to" class="form-control" placeholder="To">
+ </div>
</div>
<div class="filter-group">
<label>Rating</label>
<select id="filter-rating" class="form-control">
<option value="">All Ratings</option>
- <option value="5">5 Stars</option>
- <option value="4">4+ Stars</option>
- <option value="3">3+ Stars</option>
+ <option value="5">⭐⭐⭐⭐⭐ 5 Stars</option>
+ <option value="4">⭐⭐⭐⭐ 4+ Stars</option>
+ <option value="3">⭐⭐⭐ 3+ Stars</option>
</select>
</div>
<div class="filter-group">
- <label>Has PDFs</label>
+ <label>PDF Status</label>
<select id="filter-pdfs" class="form-control">
- <option value="">All</option>
+ <option value="">All Research</option>
<option value="yes">Has PDFs</option>
<option value="no">No PDFs</option>
</select>
</div>
- <div class="filter-group flex-grow">
+ <div class="filter-group search-group">
<label>Search</label>
- <input type="text" id="search-research" class="form-control"
- placeholder="Search research titles or queries...">
+ <div class="search-wrapper">
+ <i class="fas fa-search"></i>
+ <input type="text" id="search-research" class="form-control"
+ placeholder="Search titles or queries...">
+ </div>
</div>
</div>
<div class="bulk-actions">
- <button class="btn btn-sm" onclick="selectAll()">Select All</button>
- <button class="btn btn-sm" onclick="selectNone()">Select None</button>
- <button class="btn btn-sm" onclick="selectFiltered()">Select Filtered</button>
+ <button class="btn-bulk" onclick="selectAll()">Select All</button>
+ <button class="btn-bulk" onclick="selectNone()">Select None</button>
+ <button class="btn-bulk" onclick="selectFiltered()">Select Filtered</button>
</div>
</div>
@@ -286,6 +288,97 @@
font-size: 14px;
}
+/* Filters Section */
+.filters-section {
+ background: var(--bg-secondary, #f5f5f5);
+ padding: 20px;
+ border-radius: 8px;
+ margin-bottom: 25px;
+ border: 1px solid var(--border-color, #e0e0e0);
+}
+
+.filter-row {
+ display: flex;
+ gap: 20px;
+ align-items: flex-end;
+ flex-wrap: wrap;
+}
+
+.filter-group {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ min-width: 150px;
+}
+
+.filter-group label {
+ font-size: 12px;
+ font-weight: 600;
+ text-transform: uppercase;
+ color: var(--text-secondary, #666);
+ letter-spacing: 0.5px;
+}
+
+.filter-group .form-control {
+ padding: 8px 12px;
+ border: 1px solid var(--border-color, #ddd);
+ border-radius: 6px;
+ background: white;
+ font-size: 14px;
+ transition: all 0.2s;
+}
+
+.filter-group .form-control:focus {
+ outline: none;
+ border-color: var(--primary-color, #007bff);
+ box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
+}
+
+/* Date Range Group */
+.filter-group.date-range {
+ min-width: 280px;
+}
+
+.date-inputs {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+
+.date-inputs input {
+ flex: 1;
+}
+
+.date-separator {
+ color: var(--text-secondary, #666);
+ font-size: 14px;
+ font-weight: 500;
+}
+
+/* Search Group */
+.filter-group.search-group {
+ flex: 1;
+ min-width: 250px;
+}
+
+.search-wrapper {
+ position: relative;
+ display: flex;
+ align-items: center;
+}
+
+.search-wrapper i {
+ position: absolute;
+ left: 12px;
+ color: var(--text-secondary, #999);
+ font-size: 14px;
+}
+
+.search-wrapper input {
+ padding-left: 36px;
+ width: 100%;
+}
+
.research-list {
display: flex;
flex-direction: column;
@@ -468,23 +561,30 @@
.bulk-actions {
display: flex;
gap: 10px;
- margin-top: 10px;
+ margin-top: 15px;
+ padding-top: 15px;
+ border-top: 1px solid var(--border-color, #e0e0e0);
}
-.bulk-actions button {
- background: var(--bg-secondary);
- border: 1px solid var(--border-color);
- color: var(--text-primary);
- padding: 6px 12px;
- border-radius: 4px;
+.bulk-actions .btn-bulk {
+ background: #ffffff;
+ border: 1px solid #ddd;
+ color: #333333;
+ padding: 6px 14px;
+ border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
+ font-size: 13px;
+ font-weight: 500;
+ display: inline-block;
}
-.bulk-actions button:hover {
- background: var(--primary-color);
- color: white;
- border-color: var(--primary-color);
+.bulk-actions .btn-bulk:hover {
+ background: #007bff;
+ color: #ffffff;
+ border-color: #007bff;
+ transform: translateY(-1px);
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* Modal Styles */
@@ -637,6 +737,17 @@
border-left-color: #ff9800;
background: rgba(255, 152, 0, 0.1);
}
+.download-entry.skipped {
+ border-left-color: #ffc107;
+ background: rgba(255, 193, 7, 0.1);
+}
+.download-entry .error {
+ display: block;
+ color: #ff6b6b;
+ font-size: 12px;
+ margin-top: 4px;
+ font-style: italic;
+}
</style>
<script>
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index 870aa362e9..641ebea313 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -10,6 +10,9 @@
<button class="btn btn-secondary" onclick="syncLibrary()" 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">
+ <i class="fas fa-cloud-download-alt"></i> Download All New
+ </button>
<button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">
<i class="fas fa-download"></i> Download Manager
</button>
@@ -98,38 +101,17 @@
<div class="document-card" data-domain="{{ doc.domain }}"
data-research="{{ doc.research_id }}" data-doc-id="{{ doc.id }}">
- <!-- Card Header -->
+ <!-- Card Header with badges -->
<div class="card-header">
- <div class="doc-type-icon">
- {% if doc.is_arxiv %}
- <span class="badge badge-arxiv">arXiv</span>
- {% elif doc.is_pubmed %}
- <span class="badge badge-pubmed">PubMed</span>
- {% elif doc.file_type == 'pdf' %}
- <i class="fas fa-file-pdf text-danger"></i>
- {% else %}
- <i class="fas fa-file-alt"></i>
- {% endif %}
- </div>
- <div class="doc-actions">
- <button class="btn-icon" title="Add to favorites"
- onclick="toggleFavorite({{ doc.id }})">
- <i class="fas fa-star {{ 'active' if doc.favorite else '' }}"></i>
- </button>
- <div class="dropdown">
- <button class="btn-icon dropdown-toggle">
- <i class="fas fa-ellipsis-v"></i>
- </button>
- <div class="dropdown-menu">
- <a href="#" onclick="openPDF({{ doc.id }})">Open PDF</a>
- <a href="#" onclick="showFileLocation('{{ doc.file_absolute_path }}')">Show in Folder</a>
- <a href="{{ doc.original_url }}" target="_blank">View Original</a>
- <a href="/results/{{ doc.research_id }}">View Research Results</a>
- <hr>
- <a href="#" onclick="deleteDocument({{ doc.id }})" class="text-danger">Delete</a>
- </div>
- </div>
- </div>
+ {% if doc.is_arxiv %}
+ <span class="badge badge-arxiv">arXiv</span>
+ {% elif doc.is_pubmed %}
+ <span class="badge badge-pubmed">PubMed</span>
+ {% elif doc.file_type == 'pdf' %}
+ <i class="fas fa-file-pdf text-danger"></i>
+ {% else %}
+ <i class="fas fa-file-alt"></i>
+ {% endif %}
</div>
<!-- Card Body -->
@@ -221,6 +203,30 @@
</div>
</div>
+<!-- Download Progress Modal -->
+<div id="download-progress-modal" class="modal" style="display: none;">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h2>Download Progress</h2>
+ </div>
+ <div class="modal-body">
+ <div class="overall-progress">
+ <div class="progress-bar">
+ <div class="progress-fill" id="overall-progress" style="width: 0%"></div>
+ </div>
+ <p><span id="current-count">0</span> / <span id="total-count">0</span> files</p>
+ </div>
+ <div class="download-log" id="download-log">
+ <!-- Download entries will be added here -->
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-secondary" onclick="closeProgressModal()">Close</button>
+ <button class="btn btn-danger" onclick="cancelDownloads()">Cancel</button>
+ </div>
+ </div>
+</div>
+
<style>
.library-container {
padding: 20px;
@@ -472,42 +478,12 @@ function closePDFModal() {
document.getElementById('pdf-viewer').src = '';
}
-// Show file location in system
-function showFileLocation(path) {
- // This would need platform-specific implementation
- fetch('/library/api/open-folder', {
- method: 'POST',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({path: path})
- });
-}
-
// Copy path to clipboard
function copyPath(path) {
navigator.clipboard.writeText(path);
// Show toast notification
}
-// Toggle favorite
-function toggleFavorite(docId) {
- fetch(`/library/api/document/${docId}/favorite`, {
- method: 'POST'
- }).then(() => {
- // Update UI
- });
-}
-
-// Delete document
-function deleteDocument(docId) {
- if (confirm('Delete this document from library?')) {
- fetch(`/library/api/document/${docId}`, {
- method: 'DELETE'
- }).then(() => {
- location.reload();
- });
- }
-}
-
// Filter documents
document.getElementById('filter-domain').addEventListener('change', filterDocuments);
document.getElementById('filter-research').addEventListener('change', filterDocuments);
@@ -536,6 +512,51 @@ function filterDocuments() {
});
}
+// Download all new articles
+async function downloadAllNew() {
+ const btn = event.target.closest('button');
+ const originalContent = btn.innerHTML;
+ btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Queueing...';
+ btn.disabled = true;
+
+ try {
+ // Get CSRF token
+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';
+
+ // Queue all undownloaded articles
+ const response = await fetch('/library/api/queue-all-undownloaded', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ }
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const result = await response.json();
+
+ if (result.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';
+
+ } catch (error) {
+ console.error('Failed to queue downloads:', error);
+ alert('Failed to queue downloads. Please try again.');
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
+ }
+}
+
// Sync library with filesystem
async function syncLibrary() {
const btn = event.target.closest('button');