API startup no longer imports pymupdf (#946)

pymupdf 2.0 imports pymupdf.layout and onnxruntime, which every API start
paid for (about 2.5 s on a Pi 4) although only PDF extraction uses it.  It is
now imported when a PDF is extracted.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-11-03 15:01:37 -07:00 • committed by Roland
parent cafa2a2279
commit ba9b47edf3
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
2 changed files with 17 additions and 6 deletions

View file

@ -25,11 +25,6 @@ except ImportError:
ebooklib = None
epub = None
try:
import pymupdf
except ImportError:
pymupdf = None
try:
import docx
except ImportError:
@ -252,7 +247,11 @@ def _parse_pdf_date(date_str: str):
def extract_pdf(path: pathlib.Path) -> DocMetadata:
"""Extract metadata from a PDF using pymupdf."""
if pymupdf is None:
# Not imported at module level: pymupdf also imports pymupdf.layout and onnxruntime (~2s on a Pi 4), which must
# stay out of API startup.
try:
import pymupdf
except ImportError:
logger.error(f'Cannot extract PDF metadata: pymupdf is not installed')
return DocMetadata(title=Indexer.get_title(path))

View file

@ -1,3 +1,6 @@
import subprocess
import sys
import pytest
from modules.docs.extractors import extract_epub, extract_pdf, extract_metadata, extract_docx, extract_odt, \
@ -284,3 +287,12 @@ async def test_extract_metadata_dispatches(test_session, test_directory, example
metadata = extract_metadata(fg)
assert metadata.title == 'WROLPi Test Book'
assert metadata.author == 'roland'
def test_api_startup_does_not_import_pymupdf():
"""pymupdf imports onnxruntime (~2s on a Pi 4); only extracting a PDF may import it. A subprocess, because
importing `main` registers listeners on the shared app."""
code = 'import sys, main; print(sorted(i for i in ("pymupdf", "onnxruntime") if i in sys.modules))'
result = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True, timeout=120)
assert result.returncode == 0, result.stderr
assert result.stdout.strip().splitlines()[-1] == '[]'