From 9cdcda60aa6490337637c7241fb8f5a6c5c23310 Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Sat, 10 Oct 2026 07:11:32 -0400 Subject: [PATCH] Port 4llm functions to PyMuPDF API This fix makes PyMuPDF4LLM's API functions available in PyMuPDF. --- src/__init__.py | 41 ++++++++++++++++++++++++++++++++++-- tests/test_configurations.py | 30 ++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 tests/test_configurations.py diff --git a/src/__init__.py b/src/__init__.py index 4fae080dc..66853afc1 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -26742,7 +26742,44 @@ def deprecated_function( *args, **kwargs): f'Python {sys.version_info[0]}.{sys.version_info[1]} running on {sys.platform} ({64 if sys.maxsize > 2**32 else 32}-bit).\n' ) + try: import pymupdf4llm # noqa: F401 -except ImportError: - pass +except (ImportError, ModuleNotFoundError): + pymupdf4llm = None + +def _to_markdown(*args, **kwargs): + if pymupdf4llm: + return pymupdf4llm.to_markdown(*args, **kwargs) + else: + raise NotImplementedError('pymupdf4llm functions are not available.') + +def _to_text(*args, **kwargs): + if pymupdf4llm: + return pymupdf4llm.to_text(*args, **kwargs) + else: + raise NotImplementedError('pymupdf4llm functions are not available.') + +def _to_json(*args, **kwargs): + if pymupdf4llm: + return pymupdf4llm.to_json(*args, **kwargs) + else: + raise NotImplementedError('pymupdf4llm functions are not available.') + +def _to_chunks(*args, **kwargs): + if pymupdf4llm: + return pymupdf4llm.to_chunks(*args, **kwargs) + else: + raise NotImplementedError('pymupdf4llm functions are not available.') + +def _convert_batch(*args, **kwargs): + if pymupdf4llm: + return pymupdf4llm.convert_batch(*args, **kwargs) + else: + raise NotImplementedError('pymupdf4llm functions are not available.') + +Document.to_markdown = _to_markdown +Document.to_text = _to_text +Document.to_json = _to_json +Document.to_chunks = _to_chunks +convert_batch = _convert_batch diff --git a/tests/test_configurations.py b/tests/test_configurations.py new file mode 100644 index 000000000..df3ff4d2e --- /dev/null +++ b/tests/test_configurations.py @@ -0,0 +1,30 @@ +import pymupdf +import pathlib +import util + + +def test_configuration_layout(): + if not util._use_layout() : + print("not testing: layout feature not available") + return + + doc = pymupdf.open() + page = doc.new_page() + page.insert_text((72, 72), "Hallo Welt!\nSeid umschlungen, Millionen!") + + out1 = doc.to_markdown() + out2 = pymupdf.pymupdf4llm.to_markdown(doc) + assert out1 == out2 + + out1 = doc.to_text() + out2 = pymupdf.pymupdf4llm.to_text(doc) + assert out1 == out2 + + out1 = doc.to_chunks() + out2 = pymupdf.pymupdf4llm.to_chunks(doc) + assert repr(out1) == repr(out2), f"{out1=} != {out2=}" + + out1 = doc.to_json() + out2 = pymupdf.pymupdf4llm.to_json(doc) + assert out1 == out2 +