Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,18 @@ To install pymupdf please do `pip install pymupdf`.

Currently the command `pip install pympdf4llm` will also install pymupdf,
but this is deprecated and will be disabled at some point in the future.

## Progress callback in the embedded 4LLM source

The 4LLM source in `src/` is embedded by PyMuPDF builds. Its `to_markdown()`
accepts an optional callback for GUI or batch-job progress. The callback receives
the number of selected pages completed (starting at 1) and the selected page total:

```python
import pymupdf4llm

markdown = pymupdf4llm.to_markdown(
"document.pdf",
progress_callback=lambda done, total: print(f"{done}/{total} pages"),
)
```
2 changes: 2 additions & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ def _layout_to_markdown(
pages=None,
page_width=612,
show_progress=False,
progress_callback=None,
use_ocr=True,
write_images=False,
render_html_tables=None,
Expand All @@ -93,6 +94,7 @@ def _layout_to_markdown(
write_images=write_images,
embed_images=embed_images,
show_progress=show_progress,
progress_callback=progress_callback,
force_text=force_text,
use_ocr=use_ocr,
force_ocr=force_ocr,
Expand Down
6 changes: 5 additions & 1 deletion src/helpers/document_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -1352,6 +1352,7 @@ def parse_document(
ocr_function=None,
render_html_tables=None,
edge_threshold=None,
progress_callback=None,
) -> ParsedDocument:
original_path = None
if isinstance(doc, pymupdf.Document):
Expand Down Expand Up @@ -1465,7 +1466,8 @@ def parse_document(
f"'pages' parameter must be None, int, or a sequence of ints < {mydoc.page_count}."
)

if show_progress and len(page_filter) >= 5:
total_pages = len(page_filter)
if show_progress and total_pages >= 5:
print(f"Parsing {len(page_filter)} pages of '{document.filename}'...")
page_filter = ProgressBar(page_filter)

Expand Down Expand Up @@ -1735,6 +1737,8 @@ def parse_document(

pagelayout.boxes.append(layoutbox)
document.pages.append(pagelayout)
if progress_callback is not None:
progress_callback(len(document.pages), total_pages)
if mydoc != doc:
mydoc.close()
msg_text = INFO_MESSAGES.getvalue()
Expand Down
9 changes: 8 additions & 1 deletion src/helpers/pymupdf_rag.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,7 @@ def to_markdown(
ignore_code=False,
extract_words=False,
show_progress=False,
progress_callback=None,
use_glyphs=False,
ignore_alpha=False,
**kwargs,
Expand Down Expand Up @@ -412,6 +413,7 @@ def to_markdown(
ignore_code: (bool) suppress code-like formatting (mono-space fonts)
extract_words: (bool, False) include "words"-like output in page chunks
show_progress: (bool, False) print progress as each page is processed.
progress_callback: optional callable receiving completed and total selected pages.
use_glyphs: (bool, False) replace the Invalid Unicode by glyph numbers.
ignore_alpha: (bool, True) ignore text with alpha = 0 (transparent).

Expand Down Expand Up @@ -1337,10 +1339,13 @@ def get_page_output(
if use_glyphs:
textflags |= mupdf.FZ_STEXT_USE_GID_FOR_UNKNOWN_UNICODE

if progress_callback is not None and not hasattr(pages, "__len__"):
pages = list(pages)
total_pages = len(pages) if progress_callback is not None else None
if show_progress:
print(f"Processing {FILENAME}...")
pages = ProgressBar(pages)
for pno in pages:
for completed, pno in enumerate(pages, start=1):
parms = get_page_output(
doc,
pno,
Expand Down Expand Up @@ -1369,6 +1374,8 @@ def get_page_output(
}
)
del parms
if progress_callback is not None:
progress_callback(completed, total_pages)

return document_output

Expand Down
30 changes: 30 additions & 0 deletions tests/test_progress_callback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import pymupdf
import pymupdf4llm
import pytest


@pytest.mark.parametrize("use_layout", [True, False])
def test_to_markdown_reports_selected_page_progress(use_layout):
document = pymupdf.open()
for number in range(1, 4):
page = document.new_page()
page.insert_text((72, 72), f"PAGE {number} CONTENT")

progress = []
previous_layout = pymupdf4llm._use_layout
try:
pymupdf4llm.use_layout(use_layout)
markdown = pymupdf4llm.to_markdown(
document,
pages=[0, 2],
show_progress=not use_layout,
progress_callback=lambda done, total: progress.append((done, total)),
)
finally:
pymupdf4llm.use_layout(previous_layout)
document.close()

assert progress == [(1, 2), (2, 2)]
assert "PAGE 1 CONTENT" in markdown
assert "PAGE 3 CONTENT" in markdown
assert "PAGE 2 CONTENT" not in markdown