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: route academic URLs through specialized downloaders in search results (#3409)

LearningCircuit8c39b636e0eb
diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.py
index 3938257012..af87f125d6 100644
--- a/src/local_deep_research/content_fetcher/fetcher.py
+++ b/src/local_deep_research/content_fetcher/fetcher.py
@@ -7,7 +7,7 @@ Provides a single interface to fetch content from various sources:
- Direct PDF links
"""
-from typing import Any, Dict, Optional
+from typing import Any, Dict, List, Optional
from loguru import logger
from .url_classifier import URLClassifier, URLType
@@ -18,6 +18,9 @@ from ..utilities.resource_utils import safe_close
# Default maximum content length (500KB of text)
DEFAULT_MAX_CONTENT_LENGTH = 500_000
+# URL types where HTML fallback is pointless when the specialized downloader fails
+_NO_HTML_FALLBACK = {URLType.HTML, URLType.DOI, URLType.INVALID, URLType.PDF}
+
class ContentFetcher:
"""
@@ -26,14 +29,16 @@ class ContentFetcher:
Automatically detects URL type and uses the best downloader.
"""
- def __init__(self, timeout: int = 30):
+ def __init__(self, timeout: int = 30, language: str = "English"):
"""
Initialize the content fetcher.
Args:
timeout: Request timeout in seconds
+ language: Language for justext stoplist (passed to HTML downloader)
"""
self.timeout = timeout
+ self.language = language
self._downloaders: Dict[URLType, Any] = {}
def _get_downloader(self, url_type: URLType):
@@ -97,7 +102,9 @@ class ContentFetcher:
AutoHTMLDownloader as HTMLDownloader,
)
- downloader = HTMLDownloader(timeout=self.timeout)
+ downloader = HTMLDownloader(
+ timeout=self.timeout, language=self.language
+ )
except ImportError:
logger.warning("HTMLDownloader not available")
@@ -109,7 +116,9 @@ class ContentFetcher:
AutoHTMLDownloader as HTMLDownloader,
)
- downloader = HTMLDownloader(timeout=self.timeout)
+ downloader = HTMLDownloader(
+ timeout=self.timeout, language=self.language
+ )
except ImportError:
logger.warning("HTMLDownloader not available")
@@ -180,13 +189,10 @@ class ContentFetcher:
# Fall back to generic HTML downloader. This triggers when a
# specialized downloader (ArXiv, SemanticScholar, etc.) failed
# to import — playwright_html may still be available.
- try:
- from ..research_library.downloaders.playwright_html import (
- AutoHTMLDownloader as HTMLDownloader,
- )
-
- downloader = HTMLDownloader(timeout=self.timeout)
- except ImportError:
+ # Use _get_downloader so the instance is cached and cleaned up
+ # by close().
+ downloader = self._get_downloader(URLType.HTML)
+ if not downloader:
return {
"status": "error",
"url": url,
@@ -201,6 +207,24 @@ class ContentFetcher:
try:
result = downloader.download_with_result(url, content_type)
+ # HTML fallback: when a specialized downloader fails (e.g.
+ # arXiv PDF unavailable, PubMed paywalled), try generic HTML
+ # extraction — the abstract/landing page often has useful content.
+ if not result.is_success and url_type not in _NO_HTML_FALLBACK:
+ logger.debug(
+ f"Specialized downloader failed for {url}, "
+ "trying HTML fallback"
+ )
+ html_downloader = self._get_downloader(URLType.HTML)
+ if html_downloader:
+ result = html_downloader.download_with_result(
+ url, content_type
+ )
+ # Use the HTML downloader for metadata too, so we
+ # don't call the failed specialized downloader's
+ # get_metadata (which would re-fetch or return wrong data).
+ downloader = html_downloader
+
if result.is_success and result.content:
# Decode content — check PDF magic bytes first, then try
# UTF-8, and reject anything that is neither.
@@ -292,6 +316,19 @@ class ContentFetcher:
return result.get("content")
return None
+ def fetch_batch(self, urls: List[str]) -> Dict[str, Optional[str]]:
+ """Fetch multiple URLs, routing each to the best downloader.
+
+ Specialized downloaders (arXiv, PubMed, etc.) are tried first;
+ generic HTML extraction is used as fallback. Downloaders are
+ cached by URL type, so a single Playwright browser is shared
+ across all HTML URLs.
+
+ Returns:
+ Dict mapping URL → extracted text (or None if failed).
+ """
+ return {url: self.fetch_text(url) for url in urls}
+
def get_url_info(self, url: str) -> Dict[str, Any]:
"""
Get information about a URL without downloading.
diff --git a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
index acada54fdd..9e835d9bad 100644
--- a/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
+++ b/src/local_deep_research/research_library/downloaders/extraction/pipeline.py
@@ -8,6 +8,9 @@ Two entry points:
This is the single source of truth for content extraction in the project.
Used by HTMLDownloader, ContentFetcher, FullSearchResults, WaybackSearchEngine,
and any other code that needs clean text from a web page.
+
+Academic URLs (arXiv, PubMed, bioRxiv, etc.) are automatically routed to
+specialized downloaders first, with the generic HTML pipeline as fallback.
"""
from typing import Any, Dict, List, Optional
@@ -299,6 +302,94 @@ def extract_content_with_metadata(
}
+def _try_specialized_downloader(url: str, timeout: int = 30) -> Optional[str]:
+ """Try a specialized downloader (arXiv, PubMed, etc.) for the URL.
+
+ Returns extracted text if a specialized downloader handles this URL
+ and succeeds, or None to signal "fall back to generic HTML pipeline".
+ """
+ try:
+ from local_deep_research.content_fetcher.url_classifier import (
+ URLClassifier,
+ URLType,
+ )
+ except ImportError:
+ return None
+
+ url_type = URLClassifier.classify(url)
+
+ # Only academic URL types have specialized downloaders worth trying.
+ # HTML, DOI, PDF, INVALID fall through to the generic pipeline.
+ _SPECIALIZED_TYPES = {
+ URLType.ARXIV,
+ URLType.PUBMED,
+ URLType.PMC,
+ URLType.SEMANTIC_SCHOLAR,
+ URLType.BIORXIV,
+ URLType.MEDRXIV,
+ }
+ if url_type not in _SPECIALIZED_TYPES:
+ return None
+
+ # Map URL type to downloader class (lazy imports to avoid circular deps)
+ downloader = None
+ try:
+ if url_type == URLType.ARXIV:
+ from ..arxiv import ArxivDownloader
+
+ downloader = ArxivDownloader(timeout=timeout)
+ elif url_type in (URLType.PUBMED, URLType.PMC):
+ from ..pubmed import PubMedDownloader
+
+ downloader = PubMedDownloader(timeout=timeout)
+ elif url_type == URLType.SEMANTIC_SCHOLAR:
+ from ..semantic_scholar import SemanticScholarDownloader
+
+ downloader = SemanticScholarDownloader(timeout=timeout)
+ elif url_type in (URLType.BIORXIV, URLType.MEDRXIV):
+ from ..biorxiv import BioRxivDownloader
+
+ downloader = BioRxivDownloader(timeout=timeout)
+ except ImportError:
+ logger.debug(
+ f"Pipeline: specialized downloader not available for {url_type.value}"
+ )
+ return None
+
+ if not downloader:
+ return None
+
+ try:
+ from ..base import ContentType
+
+ result = downloader.download_with_result(url, ContentType.TEXT)
+ if result.is_success and result.content:
+ text = result.content.decode("utf-8", errors="replace")
+ if len(text.strip()) >= MIN_CONTENT_LENGTH:
+ logger.debug(
+ f"Pipeline: specialized downloader ({url_type.value}) "
+ f"returned {len(text)} chars for {url}"
+ )
+ return text
+ except Exception:
+ logger.debug(
+ f"Pipeline: specialized downloader failed for {url}",
+ exc_info=True,
+ )
+ finally:
+ try:
+ downloader.close()
+ except Exception: # noqa: silent-exception
+ pass
+
+ # Specialized downloader didn't produce content — fall back to HTML
+ logger.debug(
+ f"Pipeline: specialized downloader ({url_type.value}) returned "
+ f"no content for {url}, falling back to HTML pipeline"
+ )
+ return None
+
+
def fetch_and_extract(
url: str,
timeout: int = 30,
@@ -306,8 +397,10 @@ def fetch_and_extract(
) -> Optional[str]:
"""Fetch a URL and extract clean text content.
- Full pipeline: static HTTP fetch → Playwright fallback (if JS needed)
- → trafilatura → readability → justext.
+ Pipeline:
+ 1. Specialized downloader (arXiv PDF, PubMed API, etc.) if URL matches
+ 2. Static HTTP fetch → Playwright fallback (if JS needed)
+ → trafilatura → readability → justext
Args:
url: The URL to fetch.
@@ -317,7 +410,12 @@ def fetch_and_extract(
Returns:
Extracted plain text, or None if fetch or extraction failed.
"""
- # Import here to avoid circular imports
+ # Try specialized downloader first (arXiv, PubMed, etc.)
+ specialized = _try_specialized_downloader(url, timeout=timeout)
+ if specialized:
+ return specialized
+
+ # Generic HTML pipeline
from ..playwright_html import AutoHTMLDownloader
downloader = AutoHTMLDownloader(
@@ -349,8 +447,12 @@ def batch_fetch_and_extract(
) -> Dict[str, Optional[str]]:
"""Fetch multiple URLs and extract clean text from each.
+ For each URL:
+ 1. Try specialized downloader (arXiv, PubMed, etc.) if URL matches
+ 2. Fall back to generic HTML pipeline (AutoHTMLDownloader)
+
Uses a single AutoHTMLDownloader (and thus a single Playwright
- browser if JS fallback is triggered) for all URLs.
+ browser if JS fallback is triggered) for the generic HTML URLs.
Args:
urls: List of URLs to fetch.
@@ -363,27 +465,47 @@ def batch_fetch_and_extract(
from ..playwright_html import AutoHTMLDownloader
results: Dict[str, Optional[str]] = {}
- downloader = AutoHTMLDownloader(
- timeout=timeout,
- language=language,
- )
- try:
- for url in urls:
- try:
- data = downloader.download(url)
- if data:
- results[url] = data.decode("utf-8", errors="replace")
- else:
- results[url] = None
- except Exception:
- logger.exception(f"batch_fetch_and_extract failed for {url}")
- results[url] = None
- finally:
+
+ # Try specialized downloaders first — collect URLs that need HTML fallback
+ html_urls: List[str] = []
+ for url in urls:
try:
- downloader.close()
+ specialized = _try_specialized_downloader(url, timeout=timeout)
+ if specialized:
+ results[url] = specialized
+ continue
except Exception:
logger.debug(
- "Failed to close downloader in batch_fetch_and_extract"
+ f"Pipeline: specialized downloader error for {url}",
+ exc_info=True,
)
+ html_urls.append(url)
+
+ # Generic HTML pipeline for remaining URLs
+ if html_urls:
+ downloader = AutoHTMLDownloader(
+ timeout=timeout,
+ language=language,
+ )
+ try:
+ for url in html_urls:
+ try:
+ data = downloader.download(url)
+ if data:
+ results[url] = data.decode("utf-8", errors="replace")
+ else:
+ results[url] = None
+ except Exception:
+ logger.exception(
+ f"batch_fetch_and_extract failed for {url}"
+ )
+ results[url] = None
+ finally:
+ try:
+ downloader.close()
+ except Exception:
+ logger.debug(
+ "Failed to close downloader in batch_fetch_and_extract"
+ )
return results
diff --git a/src/local_deep_research/web_search_engines/engines/full_search.py b/src/local_deep_research/web_search_engines/engines/full_search.py
index e0dafa061e..4b89cbcc87 100644
--- a/src/local_deep_research/web_search_engines/engines/full_search.py
+++ b/src/local_deep_research/web_search_engines/engines/full_search.py
@@ -117,8 +117,8 @@ class FullSearchResults:
result["full_content"] = None
return filtered_results
- # Fetch and extract all pages using the full pipeline
- # (static fetch → Playwright fallback → trafilatura → readability → justext)
+ # Fetch and extract all pages — specialized downloaders (arXiv,
+ # PubMed, etc.) are tried first, with HTML crawling as fallback.
url_to_content = batch_fetch_and_extract(
safe_urls, language=self.language
)
diff --git a/tests/content_fetcher/test_fetcher_coverage.py b/tests/content_fetcher/test_fetcher_coverage.py
index 939f0a9184..3b339cd6fb 100644
--- a/tests/content_fetcher/test_fetcher_coverage.py
+++ b/tests/content_fetcher/test_fetcher_coverage.py
@@ -553,6 +553,7 @@ class TestFetch:
)
@patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
def test_fetch_html_fallback_success(self, classifier_mock, validate_mock):
+ """When specialized downloader import fails, fall back to HTML via _get_downloader."""
classifier_mock.classify.return_value = URLType.SEMANTIC_SCHOLAR
classifier_mock.get_source_name.return_value = "Semantic Scholar"
@@ -563,14 +564,16 @@ class TestFetch:
del mock_html_dl.get_metadata
fetcher = ContentFetcher()
- with patch.object(fetcher, "_get_downloader", return_value=None):
- with patch(
- "local_deep_research.research_library.downloaders.playwright_html.AutoHTMLDownloader",
- return_value=mock_html_dl,
- ):
- result = fetcher.fetch(
- "https://www.semanticscholar.org/paper/xyz"
- )
+
+ # First call (SEMANTIC_SCHOLAR) returns None (import failed),
+ # second call (HTML fallback) returns the HTML downloader.
+ def side_effect(url_type):
+ if url_type == URLType.HTML:
+ return mock_html_dl
+ return None
+
+ with patch.object(fetcher, "_get_downloader", side_effect=side_effect):
+ result = fetcher.fetch("https://www.semanticscholar.org/paper/xyz")
assert result["status"] == "success"
assert result["content"] == "Fallback content"
@@ -758,3 +761,189 @@ class TestInit:
class TestConstants:
def test_default_max_content_length_value(self):
assert DEFAULT_MAX_CONTENT_LENGTH == 500_000
+
+
+# ---------------------------------------------------------------------------
+# language parameter
+# ---------------------------------------------------------------------------
+
+
+class TestLanguageParam:
+ def test_default_language(self):
+ fetcher = ContentFetcher()
+ assert fetcher.language == "English"
+
+ def test_custom_language(self):
+ fetcher = ContentFetcher(language="German")
+ assert fetcher.language == "German"
+
+ def test_language_forwarded_to_html_downloader(self):
+ """_get_downloader(HTML) passes language to AutoHTMLDownloader."""
+ fetcher = ContentFetcher(language="French")
+
+ with patch(
+ "local_deep_research.research_library.downloaders."
+ "playwright_html.AutoHTMLDownloader"
+ ) as dl_cls:
+ dl_cls.return_value = MagicMock()
+ downloader = fetcher._get_downloader(URLType.HTML)
+ dl_cls.assert_called_once_with(timeout=30, language="French")
+ assert downloader is not None
+
+
+# ---------------------------------------------------------------------------
+# HTML fallback for specialized downloader failures
+# ---------------------------------------------------------------------------
+
+
+class TestHtmlFallback:
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.validate_url",
+ return_value=True,
+ )
+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
+ def test_specialized_fails_html_fallback_succeeds(
+ self, classifier_mock, validate_mock
+ ):
+ """When ArXiv downloader fails, HTML fallback returns content."""
+ classifier_mock.classify.return_value = URLType.ARXIV
+ classifier_mock.get_source_name.return_value = "arXiv"
+
+ # Specialized downloader fails
+ mock_arxiv = MagicMock()
+ mock_arxiv.download_with_result.return_value = _make_download_result(
+ content=None, is_success=False, skip_reason="PDF unavailable"
+ )
+
+ # HTML fallback succeeds
+ mock_html = MagicMock()
+ mock_html.download_with_result.return_value = _make_download_result(
+ content=b"arXiv abstract content"
+ )
+ del mock_html.get_metadata
+
+ fetcher = ContentFetcher()
+ fetcher._downloaders[URLType.ARXIV] = mock_arxiv
+ fetcher._downloaders[URLType.HTML] = mock_html
+
+ result = fetcher.fetch("https://arxiv.org/abs/2301.12345")
+ assert result["status"] == "success"
+ assert "arXiv abstract content" in result["content"]
+
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.validate_url",
+ return_value=True,
+ )
+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
+ def test_specialized_fails_html_fallback_also_fails(
+ self, classifier_mock, validate_mock
+ ):
+ """When both specialized and HTML downloaders fail, return error."""
+ classifier_mock.classify.return_value = URLType.PUBMED
+ classifier_mock.get_source_name.return_value = "PubMed"
+
+ mock_pubmed = MagicMock()
+ mock_pubmed.download_with_result.return_value = _make_download_result(
+ content=None, is_success=False, skip_reason="Paywalled"
+ )
+
+ mock_html = MagicMock()
+ mock_html.download_with_result.return_value = _make_download_result(
+ content=None, is_success=False, skip_reason="No content"
+ )
+
+ fetcher = ContentFetcher()
+ fetcher._downloaders[URLType.PUBMED] = mock_pubmed
+ fetcher._downloaders[URLType.HTML] = mock_html
+
+ result = fetcher.fetch("https://pubmed.ncbi.nlm.nih.gov/12345/")
+ assert result["status"] == "error"
+
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.validate_url",
+ return_value=True,
+ )
+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
+ def test_pdf_type_no_html_fallback(self, classifier_mock, validate_mock):
+ """URLType.PDF failure does NOT trigger HTML fallback."""
+ classifier_mock.classify.return_value = URLType.PDF
+ classifier_mock.get_source_name.return_value = "Direct PDF"
+
+ mock_pdf = MagicMock()
+ mock_pdf.download_with_result.return_value = _make_download_result(
+ content=None, is_success=False, skip_reason="404"
+ )
+
+ mock_html = MagicMock()
+
+ fetcher = ContentFetcher()
+ fetcher._downloaders[URLType.PDF] = mock_pdf
+ fetcher._downloaders[URLType.HTML] = mock_html
+
+ result = fetcher.fetch("https://example.com/paper.pdf")
+ assert result["status"] == "error"
+ # HTML downloader should NOT have been called
+ mock_html.download_with_result.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# fetch_batch
+# ---------------------------------------------------------------------------
+
+
+class TestFetchBatch:
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.validate_url",
+ return_value=True,
+ )
+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
+ def test_returns_dict_with_correct_keys(
+ self, classifier_mock, validate_mock
+ ):
+ classifier_mock.classify.return_value = URLType.HTML
+ classifier_mock.get_source_name.return_value = "Web Page"
+
+ mock_dl = MagicMock()
+ mock_dl.download_with_result.return_value = _make_download_result(
+ b"Page content"
+ )
+ del mock_dl.get_metadata
+
+ fetcher = ContentFetcher()
+ fetcher._downloaders[URLType.HTML] = mock_dl
+
+ urls = ["https://a.com", "https://b.com"]
+ result = fetcher.fetch_batch(urls)
+
+ assert isinstance(result, dict)
+ assert set(result.keys()) == set(urls)
+ assert all(v is not None for v in result.values())
+
+ @patch(
+ "local_deep_research.content_fetcher.fetcher.validate_url",
+ return_value=True,
+ )
+ @patch("local_deep_research.content_fetcher.fetcher.URLClassifier")
+ def test_mixed_results(self, classifier_mock, validate_mock):
+ """One URL succeeds, one fails — both appear in output."""
+ classifier_mock.classify.return_value = URLType.HTML
+ classifier_mock.get_source_name.return_value = "Web Page"
+
+ success_result = _make_download_result(b"OK content")
+ fail_result = _make_download_result(
+ content=None, is_success=False, skip_reason="Error"
+ )
+
+ mock_dl = MagicMock()
+ mock_dl.download_with_result.side_effect = [
+ success_result,
+ fail_result,
+ ]
+ del mock_dl.get_metadata
+
+ fetcher = ContentFetcher()
+ fetcher._downloaders[URLType.HTML] = mock_dl
+
+ result = fetcher.fetch_batch(["https://ok.com", "https://fail.com"])
+ assert result["https://ok.com"] is not None
+ assert result["https://fail.com"] is None
diff --git a/tests/research_library/downloaders/test_extraction_benchmark.py b/tests/research_library/downloaders/test_extraction_benchmark.py
index a833ef3d36..88da9fcf97 100644
--- a/tests/research_library/downloaders/test_extraction_benchmark.py
+++ b/tests/research_library/downloaders/test_extraction_benchmark.py
@@ -15,6 +15,7 @@ from typing import Dict, List, Tuple
import pytest
+from local_deep_research.content_fetcher import ContentFetcher
from local_deep_research.research_library.downloaders.html import HTMLDownloader
from local_deep_research.research_library.downloaders.playwright_html import (
AutoHTMLDownloader,
@@ -141,7 +142,22 @@ DOCS = [
ACADEMIC = [
("ArXiv", "https://arxiv.org/abs/2301.07507"),
("ArXiv ICL", "https://arxiv.org/abs/2301.00234"),
+ ("ArXiv LLM", "https://arxiv.org/abs/2303.08774"),
+ ("ArXiv HTML", "https://arxiv.org/html/2301.07507"),
("PubMed", "https://pubmed.ncbi.nlm.nih.gov/37828879/"),
+ ("PubMed CRISPR", "https://pubmed.ncbi.nlm.nih.gov/26553966/"),
+ ("PubMed COVID", "https://pubmed.ncbi.nlm.nih.gov/32015507/"),
+ ("PMC", "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7095418/"),
+ (
+ "SemScholar",
+ "https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/204e3073870fae3d05bcbc2f6a8e263d9b72e776",
+ ),
+ (
+ "SemScholar2",
+ "https://www.semanticscholar.org/paper/BERT%3A-Pre-training-of-Deep-Bidirectional-Devlin-Chang/df2b0e26d0599ce3e70df8a9da02e51594e0e992",
+ ),
+ ("OpenAlex", "https://openalex.org/works/W2741809807"),
+ ("OpenAlex2", "https://openalex.org/works/W2963403868"),
("Nature", "https://www.nature.com/articles/s41586-024-07487-w"),
("Science", "https://www.science.org/"),
("ResearchGate", "https://www.researchgate.net/"),
@@ -149,6 +165,7 @@ ACADEMIC = [
("IEEE", "https://www.ieee.org/"),
("JSTOR", "https://www.jstor.org/"),
("ACM DL", "https://dl.acm.org/"),
+ ("bioRxiv", "https://www.biorxiv.org/content/10.1101/2024.01.01.573841v1"),
]
GOVERNMENT = [
@@ -503,3 +520,88 @@ class TestExtractionBenchmark:
f"Too many failures: {total_success}/{total} "
f"({total_success / total * 100:.0f}%) — expected at least 60%"
)
+
+
+# URLs that ContentFetcher should route to specialized downloaders
+CONTENT_FETCHER_URLS = [
+ ("ArXiv abs", "https://arxiv.org/abs/2301.07507", "arXiv"),
+ ("ArXiv GPT-4", "https://arxiv.org/abs/2303.08774", "arXiv"),
+ ("PubMed", "https://pubmed.ncbi.nlm.nih.gov/37828879/", "PubMed"),
+ ("PubMed CRISPR", "https://pubmed.ncbi.nlm.nih.gov/26553966/", "PubMed"),
+ ("PubMed COVID", "https://pubmed.ncbi.nlm.nih.gov/32015507/", "PubMed"),
+ ("PMC", "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7095418/", "PMC"),
+ (
+ "SemScholar",
+ "https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/204e3073870fae3d05bcbc2f6a8e263d9b72e776",
+ "Semantic Scholar",
+ ),
+ ("OpenAlex", "https://openalex.org/works/W2741809807", "OpenAlex"),
+ (
+ "bioRxiv",
+ "https://www.biorxiv.org/content/10.1101/2024.01.01.573841v1",
+ "bioRxiv",
+ ),
+ (
+ "HTML page",
+ "https://en.wikipedia.org/wiki/Python_(programming_language)",
+ "Web Page",
+ ),
+]
+
+
+class TestContentFetcherRouting:
+ """Test that ContentFetcher routes academic URLs to specialized downloaders.
+
+ Verifies the new fetch_batch path used by FullSearchResults actually
+ works end-to-end with real URLs.
+ """
+
+ def test_academic_urls_via_content_fetcher(self):
+ """ContentFetcher.fetch_batch returns content for academic URLs."""
+ urls = [url for _, url, _ in CONTENT_FETCHER_URLS]
+
+ with ContentFetcher(timeout=30) as fetcher:
+ results = fetcher.fetch_batch(urls)
+
+ print(f"\n{'=' * 90}")
+ print(" CONTENT FETCHER ROUTING BENCHMARK")
+ print(f"{'=' * 90}")
+
+ failures = []
+ for label, url, expected_source in CONTENT_FETCHER_URLS:
+ content = results.get(url)
+ length = len(content) if content else 0
+ sample = (
+ content[:80].replace("\n", " ") if content else "(no content)"
+ )
+
+ # Check URL classification
+ info = fetcher.get_url_info(url)
+ detected = info["source_name"]
+
+ status = "✓" if length > 50 else "✗"
+ match = "✓" if detected == expected_source else "✗"
+ print(
+ f" {status} {label:<16} "
+ f"route={match} {detected:<18} "
+ f"{length:>7} chars {sample[:50]}"
+ )
+
+ if length <= 50:
+ failures.append(f"{label} ({detected}): {length} chars")
+
+ print(
+ f"\n Results: {len(CONTENT_FETCHER_URLS) - len(failures)}"
+ f"/{len(CONTENT_FETCHER_URLS)} URLs returned content"
+ )
+
+ if failures:
+ print(f" Failures: {', '.join(failures)}")
+
+ # At least 60% should work (some may be rate-limited or paywalled)
+ max_failures = len(CONTENT_FETCHER_URLS) * 0.4
+ assert len(failures) <= max_failures, (
+ f"ContentFetcher failed on too many URLs: "
+ f"{len(failures)}/{len(CONTENT_FETCHER_URLS)}: "
+ f"{', '.join(failures)}"
+ )
diff --git a/tests/security/test_ssrf_debug_hardening.py b/tests/security/test_ssrf_debug_hardening.py
index 8976c64dcb..6e37d81d99 100644
--- a/tests/security/test_ssrf_debug_hardening.py
+++ b/tests/security/test_ssrf_debug_hardening.py
@@ -106,8 +106,7 @@ class TestFullSearchSSRFValidation:
{"link": "http://example.com/good", "title": "good"},
]
- fs = FullSearchResults(llm=mock_llm, web_search=[mock_web_search])
- fs.web_search = mock_web_search
+ fs = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
with (
patch(
@@ -118,23 +117,22 @@ class TestFullSearchSSRFValidation:
"local_deep_research.web_search_engines.engines.full_search.validate_url"
) as mock_validate,
patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader,
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract"
+ ) as mock_batch,
):
# First URL blocked, second passes
mock_validate.side_effect = [False, True]
- mock_doc = MagicMock()
- mock_doc.metadata = {"source": "http://example.com/good"}
- mock_doc.page_content = "<p>Content</p>"
- mock_loader.return_value.load.return_value = [mock_doc]
+ mock_batch.return_value = {
+ "http://example.com/good": "Safe content",
+ }
results = fs.run("test query")
- # AsyncChromiumLoader should only receive the safe URL
- mock_loader.assert_called_once()
- loaded_urls = mock_loader.call_args[0][0]
- assert "http://169.254.169.254/secret" not in loaded_urls
- assert "http://example.com/good" in loaded_urls
+ # batch_fetch_and_extract should only receive the safe URL
+ mock_batch.assert_called_once()
+ fetched_urls = mock_batch.call_args[0][0]
+ assert "http://169.254.169.254/secret" not in fetched_urls
+ assert "http://example.com/good" in fetched_urls
# Both results should be returned (blocked one gets full_content=None)
assert len(results) == 2
@@ -152,8 +150,7 @@ class TestFullSearchSSRFValidation:
{"link": "http://example.com/good", "title": "good"},
]
- fs = FullSearchResults(llm=mock_llm, web_search=[mock_web_search])
- fs.web_search = mock_web_search
+ fs = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
with (
patch(
@@ -164,15 +161,13 @@ class TestFullSearchSSRFValidation:
"local_deep_research.web_search_engines.engines.full_search.validate_url"
) as mock_validate,
patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader,
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract"
+ ) as mock_batch,
):
mock_validate.side_effect = [False, True]
-
- mock_doc = MagicMock()
- mock_doc.metadata = {"source": "http://example.com/good"}
- mock_doc.page_content = "<p>Safe content</p>"
- mock_loader.return_value.load.return_value = [mock_doc]
+ mock_batch.return_value = {
+ "http://example.com/good": "Safe content",
+ }
results = fs.run("test query")
@@ -213,9 +208,6 @@ class TestFullSearchSSRFValidation:
patch(
"local_deep_research.web_search_engines.engines.full_search.validate_url"
) as mock_validate,
- patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ),
):
mock_validate.return_value = False
fs.run("test")
@@ -245,14 +237,9 @@ class TestFullSearchSSRFValidation:
"local_deep_research.web_search_engines.engines.full_search.validate_url",
return_value=False,
),
- patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader,
):
results = fs.run("test query")
- # Should NOT have called AsyncChromiumLoader
- mock_loader.assert_not_called()
# Results should still be returned with full_content=None
assert len(results) == 1
assert results[0]["full_content"] is None
diff --git a/tests/web_search_engines/engines/test_full_search.py b/tests/web_search_engines/engines/test_full_search.py
index 46584171e4..274077e0e8 100644
--- a/tests/web_search_engines/engines/test_full_search.py
+++ b/tests/web_search_engines/engines/test_full_search.py
@@ -4,7 +4,6 @@ Tests for the FullSearchResults class.
Tests cover:
- Initialization and configuration
- URL quality checking with LLM
-- Boilerplate removal
- Full search workflow
"""
@@ -62,20 +61,6 @@ class TestFullSearchResultsInit:
assert engine.time == "m"
assert engine.safesearch == "Off"
- def test_init_creates_transformer(self):
- """Initialize creates BeautifulSoup transformer."""
- from local_deep_research.web_search_engines.engines.full_search import (
- FullSearchResults,
- )
-
- mock_llm = Mock()
- mock_web_search = Mock()
-
- engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
-
- assert engine.bs_transformer is not None
- assert engine.tags_to_extract == ["p", "div", "span"]
-
class TestCheckUrls:
"""Tests for check_urls method."""
@@ -180,88 +165,11 @@ class TestCheckUrls:
assert filtered == []
-class TestRemoveBoilerplate:
- """Tests for remove_boilerplate method."""
-
- def test_remove_boilerplate_empty_html(self):
- """Remove boilerplate returns empty for empty HTML."""
- from local_deep_research.web_search_engines.engines.full_search import (
- FullSearchResults,
- )
-
- mock_llm = Mock()
- mock_web_search = Mock()
-
- engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
-
- result = engine.remove_boilerplate("")
-
- assert result == ""
-
- def test_remove_boilerplate_whitespace_only(self):
- """Remove boilerplate returns empty for whitespace-only HTML."""
- from local_deep_research.web_search_engines.engines.full_search import (
- FullSearchResults,
- )
-
- mock_llm = Mock()
- mock_web_search = Mock()
-
- engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
-
- result = engine.remove_boilerplate(" \n\t ")
-
- assert result == ""
-
- def test_remove_boilerplate_extracts_content(self):
- """Remove boilerplate extracts main content."""
- from local_deep_research.web_search_engines.engines.full_search import (
- FullSearchResults,
- )
-
- mock_llm = Mock()
- mock_web_search = Mock()
-
- engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
-
- html = """
- <html>
- <body>
- <nav>Navigation menu</nav>
- <article>
- <p>This is the main article content that should be extracted.</p>
- <p>This is another paragraph with important information.</p>
- </article>
- <footer>Footer content</footer>
- </body>
- </html>
- """
-
- with patch(
- "local_deep_research.web_search_engines.engines.full_search.justext.justext"
- ) as mock_justext:
- # Mock paragraphs
- mock_para1 = Mock()
- mock_para1.text = "Main content"
- mock_para1.is_boilerplate = False
-
- mock_para2 = Mock()
- mock_para2.text = "Navigation"
- mock_para2.is_boilerplate = True
-
- mock_justext.return_value = [mock_para1, mock_para2]
-
- result = engine.remove_boilerplate(html)
-
- assert "Main content" in result
- assert "Navigation" not in result
-
-
class TestRun:
"""Tests for run method."""
def test_run_returns_results(self):
- """Run returns filtered results with full content."""
+ """Run returns results with full content via batch_fetch_and_extract."""
from local_deep_research.web_search_engines.engines.full_search import (
FullSearchResults,
)
@@ -277,32 +185,20 @@ class TestRun:
False,
):
with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- mock_doc = Mock()
- mock_doc.page_content = "<p>Full content</p>"
- mock_doc.metadata = {"source": "https://example.com/1"}
- mock_loader.return_value.load.return_value = [mock_doc]
-
- with patch.object(
- FullSearchResults,
- "remove_boilerplate",
- return_value="Clean content",
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={"https://example.com/1": "Fetched content"},
):
engine = FullSearchResults(
llm=mock_llm, web_search=mock_web_search
)
-
- # Mock the transformer
- engine.bs_transformer = Mock()
- engine.bs_transformer.transform_documents.return_value = [
- mock_doc
- ]
-
results = engine.run("test query")
- assert len(results) == 1
- assert results[0]["full_content"] == "Clean content"
+ assert len(results) == 1
+ assert results[0]["full_content"] == "Fetched content"
def test_run_with_url_filtering(self):
"""Run filters URLs when QUALITY_CHECK_DDG_URLS is True."""
@@ -323,30 +219,20 @@ class TestRun:
True,
):
with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- mock_doc = Mock()
- mock_doc.page_content = "<p>Content</p>"
- mock_doc.metadata = {"source": "https://example.com/1"}
- mock_loader.return_value.load.return_value = [mock_doc]
-
- with patch.object(
- FullSearchResults,
- "remove_boilerplate",
- return_value="Clean",
+ "local_deep_research.web_search_engines.engines.full_search.validate_url",
+ return_value=True,
+ ):
+ with patch(
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={"https://example.com/1": "Content"},
):
engine = FullSearchResults(
llm=mock_llm, web_search=mock_web_search
)
- engine.bs_transformer = Mock()
- engine.bs_transformer.transform_documents.return_value = [
- mock_doc
- ]
-
results = engine.run("test query")
- # Only one result should pass the filter
- assert len(results) == 1
+ # Only one result should pass the LLM filter
+ assert len(results) == 1
def test_run_no_valid_links(self):
"""Run returns empty when no valid links."""
diff --git a/tests/web_search_engines/engines/test_full_search_coverage.py b/tests/web_search_engines/engines/test_full_search_coverage.py
index 38c1098718..f31a90f677 100644
--- a/tests/web_search_engines/engines/test_full_search_coverage.py
+++ b/tests/web_search_engines/engines/test_full_search_coverage.py
@@ -2,7 +2,7 @@
Tests for uncovered code paths in FullSearchResults.
Targets:
-- _get_full_content() method (entirely untested)
+- _get_full_content() method
- SSRF validation blocking all URLs
- check_urls with null LLM
- run() with SSRF-blocked URLs returning results without full content
@@ -33,39 +33,21 @@ class TestGetFullContent:
{"link": "https://example.com/2", "title": "R2"},
]
- mock_doc1 = Mock()
- mock_doc1.page_content = "<p>Content 1</p>"
- mock_doc1.metadata = {"source": "https://example.com/1"}
- mock_doc2 = Mock()
- mock_doc2.page_content = "<p>Content 2</p>"
- mock_doc2.metadata = {"source": "https://example.com/2"}
-
with patch(
"local_deep_research.web_search_engines.engines.full_search.validate_url",
return_value=True,
):
with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- mock_loader.return_value.load.return_value = [
- mock_doc1,
- mock_doc2,
- ]
- engine.bs_transformer = Mock()
- engine.bs_transformer.transform_documents.return_value = [
- mock_doc1,
- mock_doc2,
- ]
-
- with patch.object(
- engine,
- "remove_boilerplate",
- side_effect=["Clean 1", "Clean 2"],
- ):
- result = engine._get_full_content(items)
-
- assert result[0]["full_content"] == "Clean 1"
- assert result[1]["full_content"] == "Clean 2"
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={
+ "https://example.com/1": "Content 1",
+ "https://example.com/2": "Content 2",
+ },
+ ):
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] == "Content 1"
+ assert result[1]["full_content"] == "Content 2"
def test_get_full_content_no_valid_urls(self):
"""_get_full_content returns items with None content when all URLs fail SSRF."""
@@ -85,8 +67,8 @@ class TestGetFullContent:
assert result[0]["full_content"] is None
assert result[1]["full_content"] is None
- def test_get_full_content_loader_exception(self):
- """_get_full_content returns None content on loader exception."""
+ def test_get_full_content_fetcher_exception(self):
+ """_get_full_content returns None content on fetcher exception."""
engine = self._make_engine()
items = [{"link": "https://example.com/1", "title": "R1"}]
@@ -96,12 +78,9 @@ class TestGetFullContent:
return_value=True,
):
with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- mock_loader.return_value.load.side_effect = Exception(
- "Network error"
- )
-
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ side_effect=Exception("Network error"),
+ ):
result = engine._get_full_content(items)
assert result[0]["full_content"] is None
@@ -120,24 +99,15 @@ class TestGetFullContent:
return_value=True,
):
with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- mock_doc = Mock()
- mock_doc.page_content = "<p>Content</p>"
- mock_doc.metadata = {"source": "https://example.com/1"}
- mock_loader.return_value.load.return_value = [mock_doc]
- engine.bs_transformer = Mock()
- engine.bs_transformer.transform_documents.return_value = [
- mock_doc
- ]
-
- with patch.object(
- engine, "remove_boilerplate", return_value="Clean"
- ):
- result = engine._get_full_content(items)
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={
+ "https://example.com/1": "Content",
+ },
+ ):
+ result = engine._get_full_content(items)
assert result[0]["full_content"] is None # No link -> None
- assert result[1]["full_content"] == "Clean"
+ assert result[1]["full_content"] == "Content"
def test_get_full_content_mixed_ssrf_validation(self):
"""_get_full_content handles mix of valid and SSRF-blocked URLs."""
@@ -156,24 +126,14 @@ class TestGetFullContent:
side_effect=mock_validate,
):
with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- mock_doc = Mock()
- mock_doc.page_content = "<p>Content</p>"
- mock_doc.metadata = {"source": "https://example.com/ok"}
- mock_loader.return_value.load.return_value = [mock_doc]
- engine.bs_transformer = Mock()
- engine.bs_transformer.transform_documents.return_value = [
- mock_doc
- ]
-
- with patch.object(
- engine, "remove_boilerplate", return_value="Clean"
- ):
- result = engine._get_full_content(items)
-
- assert result[0]["full_content"] == "Clean"
- # Item with SSRF-blocked link won't be in url_to_content
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={
+ "https://example.com/ok": "Content",
+ },
+ ):
+ result = engine._get_full_content(items)
+
+ assert result[0]["full_content"] == "Content"
assert result[1]["full_content"] is None
@@ -231,8 +191,8 @@ class TestRunSsrfBlocking:
assert len(results) == 1
assert results[0]["full_content"] is None
- def test_run_doc_without_source_metadata(self):
- """run() handles documents without source in metadata."""
+ def test_run_with_batch_fetch(self):
+ """run() uses batch_fetch_and_extract and attaches content to results."""
from local_deep_research.web_search_engines.engines.full_search import (
FullSearchResults,
)
@@ -243,33 +203,24 @@ class TestRunSsrfBlocking:
{"link": "https://example.com/1", "title": "R1"},
]
- with patch(
- "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
- False,
- ):
- with patch(
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.QUALITY_CHECK_DDG_URLS",
+ False,
+ ),
+ patch(
"local_deep_research.web_search_engines.engines.full_search.validate_url",
return_value=True,
- ):
- with patch(
- "local_deep_research.web_search_engines.engines.full_search.AsyncChromiumLoader"
- ) as mock_loader:
- # Doc without source metadata
- mock_doc = Mock()
- mock_doc.page_content = "<p>Content</p>"
- mock_doc.metadata = {} # No source
- mock_loader.return_value.load.return_value = [mock_doc]
-
- engine = FullSearchResults(
- llm=mock_llm, web_search=mock_web_search
- )
- engine.bs_transformer = Mock()
- engine.bs_transformer.transform_documents.return_value = [
- mock_doc
- ]
-
- results = engine.run("test query")
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.full_search.batch_fetch_and_extract",
+ return_value={
+ "https://example.com/1": "Page content",
+ },
+ ),
+ ):
+ engine = FullSearchResults(llm=mock_llm, web_search=mock_web_search)
+ results = engine.run("test query")
assert len(results) == 1
- # No source in metadata -> no content mapped
- assert results[0]["full_content"] is None
+ assert results[0]["full_content"] == "Page content"