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.

fix(pdf): graceful degradation when WeasyPrint system libs are missing (#3459)

LearningCircuitccb352ed52f9
diff --git a/src/local_deep_research/exporters/__init__.py b/src/local_deep_research/exporters/__init__.py
index 2c7100a2cf..05827d8a4f 100644
--- a/src/local_deep_research/exporters/__init__.py
+++ b/src/local_deep_research/exporters/__init__.py
@@ -22,6 +22,8 @@ Available formats can be queried with:
ExporterRegistry.get_available_formats()
"""
+from loguru import logger
+
from .base import BaseExporter, ExportOptions, ExportResult
from .registry import ExporterRegistry
@@ -29,7 +31,14 @@ from .registry import ExporterRegistry
# These imports must come after the base and registry imports
from . import latex_exporter # noqa: F401
from . import odt_exporter # noqa: F401
-from . import pdf_exporter # noqa: F401
+
+try:
+ from . import pdf_exporter # noqa: F401
+except (ImportError, OSError):
+ logger.warning(
+ "PDF exporter could not be loaded — PDF export will be unavailable"
+ )
+
from . import quarto_exporter # noqa: F401
from . import ris_exporter # noqa: F401
diff --git a/src/local_deep_research/exporters/pdf_exporter.py b/src/local_deep_research/exporters/pdf_exporter.py
index 1cdbcfe04d..6ef5e5bf84 100644
--- a/src/local_deep_research/exporters/pdf_exporter.py
+++ b/src/local_deep_research/exporters/pdf_exporter.py
@@ -11,6 +11,7 @@ from typing import Optional
from loguru import logger
+from ..web.services.pdf_service import get_pdf_service
from .base import BaseExporter, ExportOptions, ExportResult
from .registry import ExporterRegistry
@@ -25,11 +26,12 @@ class PDFExporter(BaseExporter):
"""
def __init__(self):
- """Initialize PDF exporter."""
- # Import here to avoid circular imports
- from ..web.services.pdf_service import get_pdf_service
+ """Initialize PDF exporter.
- self._pdf_service = get_pdf_service()
+ Note: pdf_service import is deferred to export() so that
+ registration succeeds even when WeasyPrint system libraries
+ (Pango, Cairo, GLib) are not installed.
+ """
@property
def format_name(self) -> str:
@@ -64,6 +66,8 @@ class PDFExporter(BaseExporter):
# Check content size limit to prevent OOM errors
self._validate_content_size(markdown_content)
+ pdf_service = get_pdf_service()
+
options = options or ExportOptions()
# Prepend title if needed (for document formats like PDF)
@@ -77,7 +81,7 @@ class PDFExporter(BaseExporter):
custom_css = options.custom_options.get("custom_css")
# Delegate to existing PDFService
- pdf_bytes = self._pdf_service.markdown_to_pdf(
+ pdf_bytes = pdf_service.markdown_to_pdf(
markdown_content,
title=options.title,
metadata=options.metadata,
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 40d6fe285b..6942b53e25 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -36,6 +36,10 @@ from ...config.paths import get_config_directory
# Services imports
from ..services.pdf_extraction_service import get_pdf_extraction_service
+from ..services.pdf_service import (
+ MissingPDFDependencyError,
+ get_weasyprint_install_instructions,
+)
from ...database.models import (
QueuedResearch,
@@ -1338,6 +1342,13 @@ def export_research_report(research_id, format):
download_name=filename,
mimetype=mimetype,
)
+ except MissingPDFDependencyError:
+ logger.exception(
+ "PDF export failed: WeasyPrint unavailable"
+ )
+ return jsonify(
+ {"error": get_weasyprint_install_instructions()}
+ ), 500
except Exception:
logger.exception("Error exporting report")
return jsonify(
diff --git a/src/local_deep_research/web/services/pdf_service.py b/src/local_deep_research/web/services/pdf_service.py
index 309c7be955..05566ba59f 100644
--- a/src/local_deep_research/web/services/pdf_service.py
+++ b/src/local_deep_research/web/services/pdf_service.py
@@ -10,12 +10,61 @@ production Flask applications due to:
"""
import io
+import platform
from html import escape
from typing import Optional, Dict, Any
import markdown # type: ignore[import-untyped]
-from weasyprint import HTML, CSS
from loguru import logger
+try:
+ from weasyprint import HTML, CSS
+
+ WEASYPRINT_AVAILABLE = True
+except (OSError, ImportError) as _weasyprint_err:
+ HTML = None # type: ignore[assignment,misc]
+ CSS = None # type: ignore[assignment,misc]
+ WEASYPRINT_AVAILABLE = False
+ logger.warning("WeasyPrint not available — PDF export will be disabled")
+
+
+_WEASYPRINT_DOCS_URL = (
+ "https://doc.courtbouillon.org/weasyprint/stable/first_steps.html"
+)
+
+
+class MissingPDFDependencyError(RuntimeError):
+ """Raised when WeasyPrint system libraries are unavailable.
+
+ Distinct from generic RuntimeError so the web layer can surface this
+ message to users without also exposing unrelated RuntimeErrors
+ (e.g., pandoc subprocess stderr from ODT export).
+ """
+
+
+def get_weasyprint_install_instructions() -> str:
+ """Return platform-specific install instructions for WeasyPrint system deps."""
+ system = platform.system()
+ if system == "Darwin":
+ return (
+ "PDF export requires WeasyPrint system libraries (Pango, Cairo, GLib).\n"
+ "Install with: brew install weasyprint\n"
+ f"See: {_WEASYPRINT_DOCS_URL}#macos"
+ )
+ if system == "Linux":
+ return (
+ "PDF export requires WeasyPrint system libraries (Pango, Cairo, GLib).\n"
+ f"See: {_WEASYPRINT_DOCS_URL}#linux"
+ )
+ if system == "Windows":
+ return (
+ "PDF export requires Pango system libraries.\n"
+ f"See: {_WEASYPRINT_DOCS_URL}#windows"
+ )
+ return (
+ "PDF export requires WeasyPrint system libraries (Pango, Cairo, GLib).\n"
+ f"See: {_WEASYPRINT_DOCS_URL}"
+ )
+
class PDFService:
"""Service for converting markdown to PDF using WeasyPrint."""
@@ -200,7 +249,14 @@ _pdf_service = None
def get_pdf_service() -> PDFService:
- """Get or create the PDF service singleton."""
+ """Get or create the PDF service singleton.
+
+ Raises:
+ MissingPDFDependencyError: If WeasyPrint system libraries are not
+ available, with platform-specific installation instructions.
+ """
+ if not WEASYPRINT_AVAILABLE:
+ raise MissingPDFDependencyError(get_weasyprint_install_instructions())
global _pdf_service
if _pdf_service is None:
_pdf_service = PDFService()
diff --git a/tests/exporters/test_pdf_exporter.py b/tests/exporters/test_pdf_exporter.py
index 1357234232..4be8f000e2 100644
--- a/tests/exporters/test_pdf_exporter.py
+++ b/tests/exporters/test_pdf_exporter.py
@@ -1,7 +1,15 @@
"""Tests for PDFExporter (refactored version)."""
import pytest
-from unittest.mock import patch
+from unittest.mock import patch, MagicMock
+
+from local_deep_research.web.services.pdf_service import WEASYPRINT_AVAILABLE
+
+# Skip all tests that need real PDF generation when WeasyPrint is unavailable
+needs_weasyprint = pytest.mark.skipif(
+ not WEASYPRINT_AVAILABLE,
+ reason="WeasyPrint system libraries not available",
+)
class TestPDFExporterProperties:
@@ -42,6 +50,7 @@ class TestPDFExporterExport:
return PDFExporter()
+ @needs_weasyprint
def test_returns_export_result(self, exporter, simple_markdown):
"""Test that export returns ExportResult."""
from local_deep_research.exporters import ExportResult
@@ -50,18 +59,21 @@ class TestPDFExporterExport:
assert isinstance(result, ExportResult)
+ @needs_weasyprint
def test_result_content_is_bytes(self, exporter, simple_markdown):
"""Test that result content is bytes."""
result = exporter.export(simple_markdown)
assert isinstance(result.content, bytes)
+ @needs_weasyprint
def test_result_is_valid_pdf(self, exporter, simple_markdown):
"""Test that result is a valid PDF (starts with %PDF)."""
result = exporter.export(simple_markdown)
assert result.content.startswith(b"%PDF")
+ @needs_weasyprint
def test_result_has_reasonable_size(self, exporter, simple_markdown):
"""Test that generated PDF has a reasonable size."""
result = exporter.export(simple_markdown)
@@ -69,6 +81,7 @@ class TestPDFExporterExport:
# A simple PDF should be at least a few KB
assert len(result.content) > 1000
+ @needs_weasyprint
def test_result_filename_uses_title(self, exporter, simple_markdown):
"""Test that filename uses provided title."""
from local_deep_research.exporters import ExportOptions
@@ -79,6 +92,7 @@ class TestPDFExporterExport:
assert "My_Research_Report" in result.filename
assert result.filename.endswith(".pdf")
+ @needs_weasyprint
def test_result_filename_default_when_no_title(
self, exporter, simple_markdown
):
@@ -88,18 +102,21 @@ class TestPDFExporterExport:
assert "research_report" in result.filename
assert result.filename.endswith(".pdf")
+ @needs_weasyprint
def test_result_mimetype_is_correct(self, exporter, simple_markdown):
"""Test that result mimetype is correct."""
result = exporter.export(simple_markdown)
assert result.mimetype == "application/pdf"
+ @needs_weasyprint
def test_handles_empty_markdown(self, exporter):
"""Test handling of empty markdown."""
result = exporter.export("")
assert result.content.startswith(b"%PDF")
+ @needs_weasyprint
def test_handles_markdown_with_all_features(
self, exporter, sample_markdown
):
@@ -108,6 +125,7 @@ class TestPDFExporterExport:
assert result.content.startswith(b"%PDF")
+ @needs_weasyprint
def test_handles_special_characters(
self, exporter, markdown_with_special_chars
):
@@ -116,6 +134,7 @@ class TestPDFExporterExport:
assert result.content.startswith(b"%PDF")
+ @needs_weasyprint
def test_handles_large_markdown(self, exporter):
"""Test handling of large markdown content."""
large_content = "# Large Document\n\n"
@@ -127,6 +146,7 @@ class TestPDFExporterExport:
# Large content should produce larger PDF
assert len(result.content) > 10000
+ @needs_weasyprint
def test_applies_custom_css(self, exporter, simple_markdown):
"""Test that custom CSS can be applied."""
from local_deep_research.exporters import ExportOptions
@@ -137,6 +157,7 @@ class TestPDFExporterExport:
assert result.content.startswith(b"%PDF")
+ @needs_weasyprint
def test_logs_pdf_size(self, exporter, simple_markdown):
"""Test that PDF size is logged."""
with patch(
@@ -168,6 +189,7 @@ class TestPDFExporterIntegration:
assert isinstance(exporter, PDFExporter)
+ @needs_weasyprint
def test_export_via_registry(self, simple_markdown):
"""Test export via registry lookup."""
from local_deep_research.exporters import ExporterRegistry
@@ -203,6 +225,7 @@ class TestPDFExporterContentSizeLimit:
assert "exceeds maximum size" in str(exc_info.value)
+ @needs_weasyprint
def test_accepts_content_at_limit(self, exporter):
"""Test that content at exactly the limit is accepted."""
from local_deep_research.exporters.base import BaseExporter
@@ -212,15 +235,17 @@ class TestPDFExporterContentSizeLimit:
# Create content at exactly the limit
content_at_limit = "x" * MAX_CONTENT_SIZE
- # Mock the PDF service to avoid processing large content
- with patch.object(
- exporter._pdf_service,
- "markdown_to_pdf",
- return_value=b"%PDF-1.4 mock content",
+ mock_service = MagicMock()
+ mock_service.markdown_to_pdf.return_value = b"%PDF-1.4 mock content"
+
+ with patch(
+ "local_deep_research.exporters.pdf_exporter.get_pdf_service",
+ return_value=mock_service,
):
result = exporter.export(content_at_limit)
assert result.content.startswith(b"%PDF")
+ @needs_weasyprint
def test_accepts_content_under_limit(self, exporter, simple_markdown):
"""Test that content under the limit is accepted."""
result = exporter.export(simple_markdown)
@@ -240,10 +265,12 @@ class TestPDFExporterErrorHandling:
def test_logs_exception_on_error(self, exporter):
"""Test that exceptions are logged."""
- with patch.object(
- exporter._pdf_service,
- "markdown_to_pdf",
- side_effect=Exception("Test error"),
+ mock_service = MagicMock()
+ mock_service.markdown_to_pdf.side_effect = Exception("Test error")
+
+ with patch(
+ "local_deep_research.exporters.pdf_exporter.get_pdf_service",
+ return_value=mock_service,
):
with patch(
"local_deep_research.exporters.pdf_exporter.logger"
@@ -253,6 +280,15 @@ class TestPDFExporterErrorHandling:
mock_logger.exception.assert_called_once()
+ def test_raises_runtime_error_when_weasyprint_missing(self, exporter):
+ """Test that a helpful RuntimeError is raised when WeasyPrint is unavailable."""
+ with patch(
+ "local_deep_research.exporters.pdf_exporter.get_pdf_service",
+ side_effect=RuntimeError("PDF export requires WeasyPrint"),
+ ):
+ with pytest.raises(RuntimeError, match="PDF export requires"):
+ exporter.export("test")
+
class TestPDFExporterFilenameTruncation:
"""Tests for filename truncation with long titles."""
@@ -264,6 +300,7 @@ class TestPDFExporterFilenameTruncation:
return PDFExporter()
+ @needs_weasyprint
def test_filename_truncated_to_50_chars(self, exporter, simple_markdown):
"""Test that filename is truncated when title exceeds 50 chars."""
from local_deep_research.exporters import ExportOptions
@@ -278,6 +315,7 @@ class TestPDFExporterFilenameTruncation:
assert len(filename_without_ext) == 50
assert result.filename.endswith(".pdf")
+ @needs_weasyprint
def test_filename_not_truncated_under_50_chars(
self, exporter, simple_markdown
):
diff --git a/tests/web/services/test_pdf_service.py b/tests/web/services/test_pdf_service.py
index a77ad35feb..ac83d775ab 100644
--- a/tests/web/services/test_pdf_service.py
+++ b/tests/web/services/test_pdf_service.py
@@ -309,3 +309,32 @@ class TestPDFServiceErrorHandling:
service.markdown_to_pdf("test")
assert "Conversion error" in str(exc_info.value)
+
+
+class TestMissingPDFDependencyError:
+ """Tests for MissingPDFDependencyError behavior."""
+
+ def test_is_runtime_error_subclass(self):
+ """MissingPDFDependencyError must be a RuntimeError subclass.
+
+ Documents the security boundary: the web route catches this specific
+ class (not generic RuntimeError) so that other exporters' RuntimeErrors
+ (e.g., pandoc stderr from ODT) don't leak into HTTP responses.
+ """
+ from local_deep_research.web.services.pdf_service import (
+ MissingPDFDependencyError,
+ )
+
+ assert issubclass(MissingPDFDependencyError, RuntimeError)
+
+ def test_get_pdf_service_raises_specific_class_when_unavailable(self):
+ """get_pdf_service() raises MissingPDFDependencyError, not plain RuntimeError."""
+ from local_deep_research.web.services import pdf_service as pdf_module
+ from local_deep_research.web.services.pdf_service import (
+ MissingPDFDependencyError,
+ get_pdf_service,
+ )
+
+ with patch.object(pdf_module, "WEASYPRINT_AVAILABLE", False):
+ with pytest.raises(MissingPDFDependencyError):
+ get_pdf_service()