Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: skip pymupdf4llm's table search on PDF pages that cannot hold a lined table (#16280)

Daniel Hane6d4f3a8d480
diff --git a/studio/backend/core/rag/parsers.py b/studio/backend/core/rag/parsers.py
index cc2c42c382f..f2bc754888c 100644
--- a/studio/backend/core/rag/parsers.py
+++ b/studio/backend/core/rag/parsers.py
@@ -397,6 +397,159 @@ def _image_covers_a_corner(doc, number: int) -> bool:
return any(box.intersects(corner) for box in boxes for corner in corners)
+# PyMuPDF releases whose lines_strict table finder _no_lined_table_possible was checked against.
+_TABLE_GUARD_PYMUPDF = ("1.27.2.3", "1.28.2")
+_TABLE_SNAP = 3 # pymupdf.table.DEFAULT_SNAP_TOLERANCE
+_TABLE_GUARD_MAX_RECTS = 1000
+
+
+def _table_guard_enabled(pymupdf4llm) -> bool:
+ """Legacy pymupdf4llm on a checked PyMuPDF, no layout analyzer."""
+ try:
+ import inspect
+
+ import fitz
+
+ to_markdown = pymupdf4llm.to_markdown
+ params = inspect.signature(to_markdown).parameters
+ return (
+ to_markdown.__module__ == "pymupdf4llm.helpers.pymupdf_rag"
+ and params["table_strategy"].default == "lines_strict"
+ and "hdr_info" in params
+ and fitz.__version__ in _TABLE_GUARD_PYMUPDF
+ and getattr(fitz, "_get_layout", None) is None
+ )
+ except Exception:
+ return False
+
+
+def _graphics_bboxes(rects: list) -> list:
+ """make_edges' clean_graphics clusters (before its has-text check), copied verbatim."""
+ import fitz
+
+ snap_x = snap_y = _TABLE_SNAP
+
+ def are_neighbors(r1, r2):
+ if (
+ r2.x0 - snap_x <= r1.x0 <= r2.x1 + snap_x or r2.x0 - snap_x <= r1.x1 <= r2.x1 + snap_x
+ ) and (
+ r2.y0 - snap_y <= r1.y0 <= r2.y1 + snap_y or r2.y0 - snap_y <= r1.y1 <= r2.y1 + snap_y
+ ):
+ return True
+ if (
+ r1.x0 - snap_x <= r2.x0 <= r1.x1 + snap_x or r1.x0 - snap_x <= r2.x1 <= r1.x1 + snap_x
+ ) and (
+ r1.y0 - snap_y <= r2.y0 <= r1.y1 + snap_y or r1.y0 - snap_y <= r2.y1 <= r1.y1 + snap_y
+ ):
+ return True
+ return False
+
+ prects = sorted(set(fitz.Rect(r) for r in rects), key = lambda r: (r.y1, r.x0))
+ boxes = []
+ while prects:
+ prect0 = prects[0]
+ repeat = True
+ while repeat:
+ repeat = False
+ for i in range(len(prects) - 1, 0, -1):
+ if are_neighbors(prect0, prects[i]):
+ prect0 |= prects[i].tl
+ prect0 |= prects[i].br
+ del prects[i]
+ repeat = True
+ boxes.append(prect0)
+ del prects[0]
+ return boxes
+
+
+def _no_lined_table_possible(page) -> bool:
+ """True when find_tables(strategy="lines_strict") provably keeps no 2x2+ table: that needs
+ 3+ vertical and 3+ horizontal base edges (length >= 1) from l/re/qu items of non-large-fill
+ paths plus cluster borders; this counts an upper bound of each."""
+ if page.rotation != 0:
+ return False
+ v = h = 0
+
+ def line(a, b):
+ nonlocal v, h
+ if abs(b[1] - a[1]) >= 1:
+ v += 1
+ if abs(b[0] - a[0]) >= 1:
+ h += 1
+
+ rects = []
+ for path in page.get_cdrawings():
+ x0, y0, x1, y1 = path["rect"]
+ if path["type"] == "f" and x1 - x0 > _TABLE_SNAP and y1 - y0 > _TABLE_SNAP:
+ continue
+ rects.append(path["rect"])
+ items = path["items"]
+ for item in items:
+ if item[0] == "l":
+ line(item[1], item[2])
+ elif item[0] == "re":
+ rx0, ry0, rx1, ry1 = item[1]
+ if abs(ry1 - ry0) >= 1:
+ v += 2
+ if abs(rx1 - rx0) >= 1:
+ h += 2
+ elif item[0] == "qu":
+ ul, ur, ll, lr = item[1]
+ for a, b in ((ul, ll), (ll, lr), (lr, ur), (ur, ul)):
+ line(a, b)
+ if path.get("closePath", True) and items and items[0][0] == "l" and items[-1][0] == "l":
+ line(items[-1][2], items[0][1])
+ if v >= 3 and h >= 3:
+ return False
+ if len(rects) > _TABLE_GUARD_MAX_RECTS:
+ return False
+ for box in _graphics_bboxes(rects):
+ if box.y1 - box.y0 >= 1:
+ v += 2
+ if box.x1 - box.x0 >= 1:
+ h += 2
+ return v < 3 or h < 3
+
+
+def _skips_table_search(doc, number: int) -> bool:
+ try:
+ return _no_lined_table_possible(doc[number])
+ except Exception: # noqa: BLE001 - an unreadable page keeps the full table search
+ return False
+
+
+def _pdf_markdown_skipping_tables(pymupdf4llm, doc, indices, calls, kwargs) -> list | None:
+ """The plain path's to_markdown calls, each split into table-search and no-search pages
+ sharing one header table."""
+ # Bake as to_markdown would, so the guard sees the same page.
+ if doc.is_form_pdf or (doc.is_pdf and doc.has_annots()):
+ doc.bake()
+ by_page = {}
+ for group, detect in calls:
+ if not group:
+ continue
+ headers = pymupdf4llm.IdentifyHeaders(doc)
+ skip = {i for i in group if _skips_table_search(doc, i)}
+ for part_pages, extra in (
+ ([i for i in group if i not in skip], {}),
+ ([i for i in group if i in skip], {"table_strategy": None}),
+ ):
+ if not part_pages:
+ continue
+ part = pymupdf4llm.to_markdown(
+ doc,
+ pages = part_pages,
+ hdr_info = headers,
+ detect_bg_color = detect,
+ **extra,
+ **kwargs,
+ )
+ if not isinstance(part, list) or len(part) != len(part_pages):
+ return None
+ by_page.update(zip(part_pages, part))
+ return [by_page[i] for i in indices]
+
+
def _pdf_markdown(doc, pages: range | None = None) -> list[str] | None:
"""Per-page layout-aware Markdown (tables, headings, lists) via pymupdf4llm; index
i maps to page i+1. Returns None when the lib is missing, extraction fails, or the
@@ -409,7 +562,17 @@ def _pdf_markdown(doc, pages: range | None = None) -> list[str] | None:
kwargs = {"page_chunks": True, "show_progress": False, "ignore_images": True}
indices = list(range(doc.page_count) if pages is None else pages)
scans = {i for i in indices if _image_covers_a_corner(doc, i)}
- if not scans:
+ if _table_guard_enabled(pymupdf4llm):
+ calls = [(indices, True)]
+ if scans:
+ calls = [
+ ([i for i in indices if i not in scans], True),
+ ([i for i in indices if i in scans], False),
+ ]
+ chunks = _pdf_markdown_skipping_tables(pymupdf4llm, doc, indices, calls, kwargs)
+ if chunks is None:
+ return None
+ elif not scans:
if pages is not None:
kwargs["pages"] = indices
chunks = pymupdf4llm.to_markdown(doc, **kwargs)
diff --git a/studio/backend/tests/test_rag_pdf_table_guard.py b/studio/backend/tests/test_rag_pdf_table_guard.py
new file mode 100644
index 00000000000..afeda31a446
--- /dev/null
+++ b/studio/backend/tests/test_rag_pdf_table_guard.py
@@ -0,0 +1,247 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""PDF Markdown skips pymupdf4llm's lines_strict table search only where it cannot find a table."""
+
+from __future__ import annotations
+
+import random
+
+import pytest
+
+pymupdf = pytest.importorskip("pymupdf")
+pytest.importorskip("pymupdf4llm")
+
+from core.rag import config, parsers # noqa: E402
+
+
+def _guard_on() -> bool:
+ # Environment facts, not the parser's own check, so these tests also run (and fail) without it.
+ import pymupdf4llm
+ return (
+ pymupdf4llm.to_markdown.__module__ == "pymupdf4llm.helpers.pymupdf_rag"
+ and pymupdf.__version__ in ("1.27.2.3", "1.28.2")
+ and getattr(pymupdf, "_get_layout", None) is None
+ )
+
+
+requires_guard = pytest.mark.skipif(
+ not _guard_on(), reason = "table guard is off for this PyMuPDF / pymupdf4llm build"
+)
+
+
+def _text(page, y, line):
+ page.insert_text((60, y), line, fontsize = 11)
+
+
+def _lined_table(
+ page,
+ x0 = 60,
+ y0 = 300,
+ rows = 3,
+ cols = 3,
+ w = 120,
+ h = 24,
+):
+ shape = page.new_shape()
+ for r in range(rows + 1):
+ shape.draw_line((x0, y0 + r * h), (x0 + cols * w, y0 + r * h))
+ for c in range(cols + 1):
+ shape.draw_line((x0 + c * w, y0), (x0 + c * w, y0 + rows * h))
+ shape.finish(color = (0, 0, 0), width = 0.8)
+ shape.commit()
+ for r in range(rows):
+ for c in range(cols):
+ page.insert_text((x0 + c * w + 6, y0 + r * h + 16), f"r{r}c{c} {r * c}", fontsize = 10)
+
+
+def _sample_pdf(path):
+ """Pages: plain text, lined table, text-aligned table without lines, one rule,
+ a large background fill, a rotated lined table, a boxed note."""
+ doc = pymupdf.open()
+ p = doc.new_page()
+ _text(p, 80, "Chapter One")
+ for i in range(12):
+ _text(p, 110 + 16 * i, f"Plain body line {i} with words to read.")
+ p = doc.new_page()
+ _text(p, 80, "Quarterly results by region")
+ _lined_table(p)
+ p = doc.new_page()
+ for r, row in enumerate(
+ [("Quarter", "Revenue", "Growth"), ("Q1", "$1.2M", "12%"), ("Q2", "$1.5M", "25%")]
+ ):
+ for c, cell in enumerate(row):
+ p.insert_text((60 + 150 * c, 120 + 24 * r), cell, fontsize = 11)
+ p = doc.new_page()
+ _text(p, 80, "Body above a footnote rule.")
+ p.draw_line((60, 700), (300, 700), width = 0.5)
+ _text(p, 720, "1. A footnote.")
+ p = doc.new_page()
+ p.draw_rect(p.rect, color = None, fill = (0.95, 0.95, 0.9))
+ _text(p, 80, "Text on a tinted page.")
+ p = doc.new_page()
+ _text(p, 80, "Rotated table")
+ _lined_table(p, rows = 4, cols = 2)
+ p.set_rotation(90)
+ p = doc.new_page()
+ p.draw_rect(pymupdf.Rect(50, 100, 400, 160), color = (0, 0, 0), width = 1)
+ _text(p, 70, "Note box")
+ _text(p, 130, "Inside a single outlined box.")
+ doc.save(str(path))
+ doc.close()
+
+
+def _parse(path, monkeypatch, guard: bool):
+ monkeypatch.setattr(config, "PDF_MARKDOWN", True)
+ if not guard:
+ monkeypatch.setattr(parsers, "_table_guard_enabled", lambda _module: False)
+ pages = parsers.parse(str(path))
+ monkeypatch.undo()
+ return [(p.text, p.page_number, p.char_count, p.needs_ocr) for p in pages]
+
+
+def _count_find_tables(monkeypatch):
+ calls = []
+ real = pymupdf.Page.find_tables
+
+ def counting(self, *args, **kwargs):
+ calls.append(self.number)
+ return real(self, *args, **kwargs)
+
+ monkeypatch.setattr(pymupdf.Page, "find_tables", counting)
+ return calls
+
+
+@requires_guard
+def test_markdown_identical_with_and_without_guard(tmp_path, monkeypatch):
+ pdf = tmp_path / "mixed.pdf"
+ _sample_pdf(pdf)
+ with_guard = _parse(pdf, monkeypatch, guard = True)
+ without = _parse(pdf, monkeypatch, guard = False)
+ assert with_guard == without
+ assert "|" in with_guard[1][0] and "r2c2 4" in with_guard[1][0]
+ assert "|" in with_guard[5][0]
+ assert "Plain body line 11" in with_guard[0][0]
+
+
+@requires_guard
+def test_guard_skips_table_search_on_pages_without_line_art(tmp_path, monkeypatch):
+ pdf = tmp_path / "mixed.pdf"
+ _sample_pdf(pdf)
+ calls = _count_find_tables(monkeypatch)
+ monkeypatch.setattr(config, "PDF_MARKDOWN", True)
+ parsers.parse(str(pdf))
+ # Only the lined table, the rotated page and the outlined box (4 edges) keep the search.
+ assert sorted(calls) == [1, 5, 6]
+
+
+@requires_guard
+def test_guard_engages_on_a_text_only_book(tmp_path, monkeypatch):
+ doc = pymupdf.open()
+ for n in range(6):
+ p = doc.new_page()
+ for i in range(30):
+ _text(p, 60 + 20 * i, f"Page {n} line {i} of a book without any drawings.")
+ pdf = tmp_path / "book.pdf"
+ doc.save(str(pdf))
+ doc.close()
+ calls = _count_find_tables(monkeypatch)
+ monkeypatch.setattr(config, "PDF_MARKDOWN", True)
+ pages = parsers.parse(str(pdf))
+ assert len(pages) == 6 and "Page 5 line 29" in pages[5].text
+ assert calls == []
+
+
+@requires_guard
+def test_guard_keeps_form_and_annotation_output(tmp_path, monkeypatch):
+ doc = pymupdf.open()
+ p = doc.new_page()
+ _text(p, 80, "Applicant details")
+ widget = pymupdf.Widget()
+ widget.field_name = "full_name"
+ widget.field_type = pymupdf.PDF_WIDGET_TYPE_TEXT
+ widget.field_value = "Ada Lovelace"
+ widget.rect = pymupdf.Rect(60, 100, 300, 120)
+ p.add_widget(widget)
+ p = doc.new_page()
+ _text(p, 80, "Reviewed page")
+ p.add_highlight_annot(pymupdf.Rect(58, 68, 200, 84))
+ p.add_text_annot((300, 300), "check this")
+ _lined_table(p, rows = 2, cols = 2)
+ pdf = tmp_path / "form.pdf"
+ doc.save(str(pdf))
+ doc.close()
+ assert _parse(pdf, monkeypatch, guard = True) == _parse(pdf, monkeypatch, guard = False)
+
+
+def _kept_tables(page) -> int:
+ tabs = page.find_tables(clip = page.rect, strategy = "lines_strict")
+ return sum(1 for t in tabs.tables if t.row_count >= 2 and t.col_count >= 2)
+
+
+def test_guard_is_sound_on_random_line_art():
+ rng = random.Random(1234)
+ doc = pymupdf.open()
+ for _ in range(80):
+ p = doc.new_page()
+ _text(p, 40, "random line art")
+ shape = p.new_shape()
+ for _ in range(rng.randint(0, 6)):
+ kind = rng.random()
+ x, y = rng.uniform(40, 400), rng.uniform(60, 700)
+ if kind < 0.4:
+ dx, dy = (
+ (rng.uniform(5, 200), rng.choice([0, 0, 0.5, 2]))
+ if rng.random() < 0.5
+ else (rng.choice([0, 0, 0.5, 2]), rng.uniform(5, 200))
+ )
+ shape.draw_line((x, y), (x + dx, y + dy))
+ elif kind < 0.7:
+ shape.draw_rect(
+ pymupdf.Rect(x, y, x + rng.uniform(0.5, 150), y + rng.uniform(0.5, 80))
+ )
+ elif kind < 0.85:
+ shape.draw_quad(
+ pymupdf.Rect(x, y, x + rng.uniform(2, 90), y + rng.uniform(2, 60)).quad
+ )
+ else:
+ shape.draw_circle((x, y), rng.uniform(2, 30))
+ shape.finish(color = (0, 0, 0), fill = (0.5, 0.5, 0.5) if rng.random() < 0.3 else None)
+ shape.commit()
+ for i in range(rng.randint(0, 6)):
+ p.insert_text((rng.uniform(40, 400), rng.uniform(60, 760)), f"cell {i}", fontsize = 9)
+ if rng.random() < 0.3:
+ _lined_table(
+ p,
+ x0 = rng.uniform(40, 200),
+ y0 = rng.uniform(100, 500),
+ rows = rng.randint(1, 3),
+ cols = rng.randint(1, 3),
+ )
+ skipped = 0
+ for page in doc:
+ if parsers._no_lined_table_possible(page):
+ skipped += 1
+ assert _kept_tables(page) == 0, page.number
+ assert 0 < skipped < doc.page_count
+
+
+def test_guard_never_skips_a_page_with_a_kept_table():
+ doc = pymupdf.open()
+ for rows, cols in [(2, 2), (3, 2), (2, 5), (6, 6)]:
+ p = doc.new_page()
+ _lined_table(p, rows = rows, cols = cols, w = 80)
+ assert _kept_tables(p) >= 1
+ assert not parsers._no_lined_table_possible(p)
+ p = doc.new_page()
+ _text(p, 80, "No drawings")
+ assert parsers._no_lined_table_possible(p)
+
+
+def test_guard_off_for_other_markdown_backends():
+ class _Layout:
+ @staticmethod
+ def to_markdown(doc, **kwargs):
+ return []
+
+ assert not parsers._table_guard_enabled(_Layout)