Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(reading): extract PDF figures so the reader can send them to the model

flower-moon8999c0d3e405
diff --git a/deeptutor/reading/extract.py b/deeptutor/reading/extract.py
index 77d818024..d0c29da9e 100644
--- a/deeptutor/reading/extract.py
+++ b/deeptutor/reading/extract.py
@@ -36,9 +36,12 @@ import re
from deeptutor.reading.models import OutlineEntry, ReadingError, RenderMode, UnitKind, UnitReference
from deeptutor.utils.document_images import (
EmbeddedImage,
+ build_marker,
extract_docx_rich,
+ extract_pdf_images,
extract_pptx_rich,
find_markers,
+ reading_image_budget,
)
logger = logging.getLogger(__name__)
@@ -175,6 +178,12 @@ def _extract_pdf(source: Path) -> Extraction:
except Exception as exc:
raise ReadingError(f"{source.name}: failed to read PDF ({exc})") from exc
+ media: tuple[MediaItem, ...] = ()
+ # Every page's figures ride along as locator-pinned media so the reader can
+ # attach what the question is about. Mining them is best-effort: a quirk in
+ # one image must never turn a readable PDF into a failed ingest.
+ units, media = _pdf_pages_with_image_markers(units, source)
+
return Extraction(
units=units,
unit="page",
@@ -183,9 +192,45 @@ def _extract_pdf(source: Path) -> Extraction:
title=title,
outline=outline,
render_mode="pdf",
+ media=media,
)
+def _pdf_pages_with_image_markers(
+ units: tuple[str, ...], source: Path
+) -> tuple[tuple[str, ...], tuple[MediaItem, ...]]:
+ """Append the page's ``[图片 N: name]`` markers to that page's text tail.
+
+ Markers are appended only at the very end of each unit so the character
+ offsets of the page's own prose never move — stored per-character
+ annotations resolve against quotes lifted from this text, and shifting them
+ would silently detach every highlight. The markers name the images, which
+ :func:`_media_for_units` then resolves back into locator-pinned media via
+ the same mapping DOCX/PPTX already use.
+
+ Best-effort by contract: any failure or empty result returns the units and
+ no media untouched, so an image quirk never turns a readable PDF into a
+ failed ingest.
+ """
+ try:
+ pdf_images = extract_pdf_images(source.read_bytes(), budget=reading_image_budget())
+ except Exception:
+ logger.warning("%s: PDF image extraction failed", source.name, exc_info=True)
+ return units, ()
+ if not pdf_images.collection.images:
+ return units, ()
+
+ marker_by_page: dict[int, list[str]] = {}
+ for page_number, indices in pdf_images.page_map:
+ marker_by_page[page_number] = [
+ build_marker(pdf_images.collection.images[index]) for index in indices
+ ]
+ targeted = tuple(
+ unit + ("\n" + "\n".join(marker_by_page[i]) if i in marker_by_page else "")
+ for i, unit in enumerate(units, 1)
+ )
+ return targeted, _media_for_units(targeted, pdf_images.collection.images)
+
def _extract_epub(source: Path) -> Extraction:
"""Preserve EPUB spine order so browser and assistant locators agree."""
from deeptutor.utils.document_extractor import DocumentExtractionError, extract_epub_spine
diff --git a/deeptutor/utils/document_images.py b/deeptutor/utils/document_images.py
index ca469e421..4d8915d94 100644
--- a/deeptutor/utils/document_images.py
+++ b/deeptutor/utils/document_images.py
@@ -48,6 +48,25 @@ MAX_TOTAL_IMAGE_BYTES_PER_DOC = 12 * 1024 * 1024
MAX_IMAGE_BYTES = 4 * 1024 * 1024
MIN_IMAGE_BYTES = 1_200 # below this it is a bullet point or a divider, not a figure
+
+def reading_image_budget() -> ImageBudget:
+ """Looser per-document caps for the reading-area ingest path.
+
+ The reading store keeps the image bytes on disk, and a single chat turn
+ inflates only the *current page's* images into the request, so the caps
+ split in two directions: the document-wide caps can be far looser than the
+ chat-attachment defaults, while the per-page cap is tightened to what one
+ request can carry. ``max_images_per_page=4`` mirrors
+ ``READING_VIEWPORT_MAX_IMAGES`` in ``services/session/_turn_runtime_shared``
+ (kept as a literal so this utils module stays free of a services import).
+ """
+ return ImageBudget(
+ max_images=120,
+ max_total_bytes=60 * 1024 * 1024,
+ max_images_per_page=4,
+ )
+
+
# Raster formats vision models and the browser can both consume. Everything
# else (EMF/WMF vector, TIFF, SVG, …) is skipped with a note.
SUPPORTED_IMAGE_EXTENSIONS: frozenset[str] = frozenset(
@@ -85,11 +104,16 @@ class ImageBudget:
max_total_bytes: int = MAX_TOTAL_IMAGE_BYTES_PER_DOC
max_image_bytes: int = MAX_IMAGE_BYTES
min_image_bytes: int = MIN_IMAGE_BYTES
+ # 0 = unlimited. Only the per-page walkers (PDF) enforce this; it keeps one
+ # page from monopolising the document budget when a single request can only
+ # carry a handful of images.
+ max_images_per_page: int = 0
count: int = 0
total_bytes: int = 0
skipped_vector: int = 0
skipped_other: int = 0
skipped_budget: int = 0
+ skipped_page_budget: int = 0
def register_vector_skip(self) -> None:
self.skipped_vector += 1
@@ -122,6 +146,7 @@ class ImageCollection:
skipped_vector: int = 0
skipped_other: int = 0
skipped_budget: int = 0
+ skipped_page_budget: int = 0
def summary_note(self) -> str:
"""One-line note for the extracted text describing what was dropped."""
@@ -132,6 +157,8 @@ class ImageCollection:
parts.append(f"{self.skipped_other} 张不支持的图片格式未提取")
if self.skipped_budget:
parts.append(f"{self.skipped_budget} 张图片超出数量/大小上限未提取")
+ if self.skipped_page_budget:
+ parts.append(f"{self.skipped_page_budget} 张超出单页上限未提取")
if not parts:
return ""
return "[" + ",".join(parts) + "]"
@@ -205,7 +232,7 @@ def _normalise_ext(ext: str) -> str:
# ---------------------------------------------------------------------------
-def extract_docx_rich(data: bytes) -> DocxRich:
+def extract_docx_rich(data: bytes, *, budget: ImageBudget | None = None) -> DocxRich:
"""Walk ``word/document.xml`` once, collecting ordered paragraphs and images.
Only the main body is mined (header/footer images are decoration). A
@@ -213,7 +240,7 @@ def extract_docx_rich(data: bytes) -> DocxRich:
marked at every position, so repeated/floating figures stay anchored to
the text around them.
"""
- budget = ImageBudget()
+ budget = budget or ImageBudget()
images: list[EmbeddedImage] = []
by_target: dict[str, EmbeddedImage] = {}
attempted: set[str] = set()
@@ -328,6 +355,7 @@ def _collection_from(budget: ImageBudget, images: list[EmbeddedImage]) -> ImageC
skipped_vector=budget.skipped_vector,
skipped_other=budget.skipped_other,
skipped_budget=budget.skipped_budget,
+ skipped_page_budget=budget.skipped_page_budget,
)
@@ -336,7 +364,7 @@ def _collection_from(budget: ImageBudget, images: list[EmbeddedImage]) -> ImageC
# ---------------------------------------------------------------------------
-def extract_pptx_rich(data: bytes) -> PptxRich:
+def extract_pptx_rich(data: bytes, *, budget: ImageBudget | None = None) -> PptxRich:
"""Slide texts with markers plus pictures, via python-pptx when available.
python-pptx resolves picture placeholders and grouped shapes cleanly and
@@ -347,14 +375,14 @@ def extract_pptx_rich(data: bytes) -> PptxRich:
try:
from pptx import Presentation
except ImportError:
- return _extract_pptx_rich_ooxml(data)
+ return _extract_pptx_rich_ooxml(data, budget=budget)
try:
prs = Presentation(io.BytesIO(data))
except Exception:
- return _extract_pptx_rich_ooxml(data)
+ return _extract_pptx_rich_ooxml(data, budget=budget)
- budget = ImageBudget()
+ budget = budget or ImageBudget()
images: list[EmbeddedImage] = []
slides: list[str] = []
for slide in prs.slides:
@@ -406,9 +434,9 @@ def _collect_shape_rich(
lines.append(text.strip())
-def _extract_pptx_rich_ooxml(data: bytes) -> PptxRich:
+def _extract_pptx_rich_ooxml(data: bytes, *, budget: ImageBudget | None = None) -> PptxRich:
"""Raw fallback: per-slide paragraph text + blip markers from slide rels."""
- budget = ImageBudget()
+ budget = budget or ImageBudget()
images: list[EmbeddedImage] = []
slides: list[str] = []
with zipfile.ZipFile(io.BytesIO(data)) as zf:
@@ -477,19 +505,26 @@ def _rels_for(member: str) -> str:
# ---------------------------------------------------------------------------
-def extract_pdf_images(data: bytes) -> PdfImages:
+def extract_pdf_images(
+ data: bytes, *, budget: ImageBudget | None = None
+) -> PdfImages:
"""Raster images per page via PyMuPDF, deduplicated across the document.
Running headers/footers embed the same logo xref on every page; only the
first occurrence is kept so a 300-page PDF does not become 300 copies of
the same banner.
+
+ ``budget`` defaults to the chat-attachment caps (unchanged behaviour). When
+ it carries a non-zero ``max_images_per_page``, a page stops admitting once
+ it hits that many images and the rest of that page's candidates are counted
+ as page-budget skips — dedup hits are still free and never counted.
"""
try:
import pymupdf
except ImportError:
return PdfImages()
- budget = ImageBudget()
+ budget = budget or ImageBudget()
images: list[EmbeddedImage] = []
page_map: list[tuple[int, tuple[int, ...]]] = []
seen_xrefs: set[int] = set()
@@ -498,6 +533,7 @@ def extract_pdf_images(data: bytes) -> PdfImages:
with pymupdf.open(stream=data, filetype="pdf") as doc:
for page_number, page in enumerate(doc, 1):
indices: list[int] = []
+ admitted_on_page = 0
for info in page.get_images(full=True):
xref = info[0]
if xref in seen_xrefs:
@@ -519,10 +555,16 @@ def extract_pdf_images(data: bytes) -> PdfImages:
if ext not in SUPPORTED_IMAGE_EXTENSIONS:
budget.register_other_skip()
continue
+ if budget.max_images_per_page and (
+ admitted_on_page >= budget.max_images_per_page
+ ):
+ budget.skipped_page_budget += 1
+ continue
admitted = budget.try_admit(ext, raw)
if admitted is not None:
images.append(admitted)
indices.append(len(images) - 1)
+ admitted_on_page += 1
if indices:
page_map.append((page_number, tuple(indices)))
except Exception:
@@ -544,6 +586,7 @@ __all__ = [
"build_marker",
"find_markers",
"image_index_from_name",
+ "reading_image_budget",
"extract_docx_rich",
"extract_pptx_rich",
"extract_pdf_images",
diff --git a/tests/reading/test_reading_pdf_media.py b/tests/reading/test_reading_pdf_media.py
new file mode 100644
index 000000000..b0feaec1e
--- /dev/null
+++ b/tests/reading/test_reading_pdf_media.py
@@ -0,0 +1,87 @@
+"""PDF reading ingest must surface embedded images as locator-pinned media.
+
+Builds small real PDFs with PyMuPDF so the assertions exercise the actual
+``extract_material`` path: markers appended at each page's text tail, and the
+matching ``MediaItem`` records carrying the page locator.
+"""
+
+from __future__ import annotations
+
+import io
+import random
+
+import pytest
+
+from deeptutor.reading.extract import extract_material
+from deeptutor.utils.document_images import find_markers
+
+
+def _png_bytes(size: tuple[int, int], seed: int) -> bytes:
+ """A noisy PNG above the min-bytes and 64px minimum-size gates."""
+ rng = random.Random(seed)
+ raw = bytes(rng.randrange(256) for _ in range(size[0] * size[1] * 3))
+ from PIL import Image as PILImage
+
+ image = PILImage.frombytes("RGB", size, raw)
+ buf = io.BytesIO()
+ image.save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _prose(label: str) -> str:
+ return (
+ f"{label} This page carries a real text layer so the density check "
+ "accepts it as prose rather than a figure-label scan. " * 3
+ )
+
+
+def _build_pdf(path, images_per_page: list[int]) -> None:
+ pymupdf = pytest.importorskip("pymupdf")
+ doc = pymupdf.open()
+ for page_index, image_count in enumerate(images_per_page, start=1):
+ page = doc.new_page(width=612, height=792)
+ page.insert_text((72, 60), _prose(f"Page {page_index}"))
+ for image_index in range(image_count):
+ rect = pymupdf.Rect(72, 100 + image_index * 90, 240, 180 + image_index * 90)
+ page.insert_image(
+ rect, stream=_png_bytes((150, 120), seed=page_index * 10 + image_index)
+ )
+ doc.save(str(path))
+ doc.close()
+
+
+def test_pdf_images_become_locator_pinned_media(tmp_path) -> None:
+ pdf_path = tmp_path / "figures.pdf"
+ _build_pdf(pdf_path, images_per_page=[2, 1, 0])
+
+ extraction = extract_material(pdf_path)
+
+ assert len(extraction.units) == 3
+ assert extraction.extractor == "pymupdf"
+
+ assert "[图片" in extraction.units[0]
+ assert "[图片" in extraction.units[1]
+ assert "[图片" not in extraction.units[2]
+
+ locator_counts: dict[int, int] = {}
+ for item in extraction.media:
+ locator_counts[item.locator] = locator_counts.get(item.locator, 0) + 1
+ assert locator_counts == {1: 2, 2: 1}
+
+ # Marker names and media names agree one-for-one on each page.
+ for locator in (1, 2):
+ marker_names = [name for _, name in find_markers(extraction.units[locator - 1])]
+ media_names = [item.name for item in extraction.media if item.locator == locator]
+ assert marker_names == media_names
+ assert len(media_names) == locator_counts[locator]
+
+
+def test_text_only_pdf_has_no_media_and_no_marker(tmp_path) -> None:
+ pdf_path = tmp_path / "plain.pdf"
+ _build_pdf(pdf_path, images_per_page=[0, 0])
+
+ extraction = extract_material(pdf_path)
+
+ assert len(extraction.units) == 2
+ assert extraction.media == ()
+ assert all("[图片" not in unit for unit in extraction.units)
diff --git a/tests/utils/test_document_images.py b/tests/utils/test_document_images.py
index 849c29bb7..faf735e4f 100644
--- a/tests/utils/test_document_images.py
+++ b/tests/utils/test_document_images.py
@@ -17,6 +17,7 @@ from pptx.util import Inches as PptxInches
import pytest
from deeptutor.utils.document_images import (
+ ImageBudget,
build_marker,
extract_docx_rich,
extract_pdf_images,
@@ -185,3 +186,53 @@ def test_pdf_images_deduplicates_repeated_xref(tmp_path) -> None:
result = extract_pdf_images(pdf_path.read_bytes())
assert len(result.collection.images) == 1
assert [page for page, _ in result.page_map] == [1]
+
+
+def _png_for_index(index: int) -> bytes:
+ """Distinct (content-wise) noisy PNG per index, all 64px+ and >min bytes."""
+ return _png_bytes((120 + index, 120))
+
+
+def _pdf_with_images(tmp_path, count: int) -> bytes:
+ """One page carrying *count* distinct embedded images."""
+ pymupdf = pytest.importorskip("pymupdf")
+ doc = pymupdf.open()
+ page = doc.new_page(width=612, height=792)
+ for index in range(count):
+ rect = pymupdf.Rect(72, 72 + index * 40, 180, 108 + index * 40)
+ page.insert_image(rect, stream=_png_for_index(index))
+ pdf_path = tmp_path / f"many-{count}.pdf"
+ doc.save(str(pdf_path))
+ doc.close()
+ return pdf_path.read_bytes()
+
+
+def test_pdf_images_respects_per_page_cap(tmp_path) -> None:
+ """A page stops admitting at max_images_per_page; the rest are counted."""
+ data = _pdf_with_images(tmp_path, 6)
+ result = extract_pdf_images(data, budget=ImageBudget(max_images_per_page=4))
+
+ assert len(result.collection.images) == 4
+ assert result.collection.skipped_page_budget == 2
+ assert result.collection.skipped_budget == 0
+ note = result.collection.summary_note()
+ assert "2 张超出单页上限未提取" in note
+
+
+def test_pdf_images_honours_custom_max_images(tmp_path) -> None:
+ data = _pdf_with_images(tmp_path, 6)
+ result = extract_pdf_images(data, budget=ImageBudget(max_images=2))
+
+ assert len(result.collection.images) == 2
+ assert result.collection.skipped_budget == 4
+ assert result.collection.skipped_page_budget == 0
+
+
+def test_pdf_images_default_budget_caps_at_twelve(tmp_path) -> None:
+ """No budget argument keeps the historical document-wide 12-image cap."""
+ data = _pdf_with_images(tmp_path, 14)
+ result = extract_pdf_images(data)
+
+ assert len(result.collection.images) == 12
+ assert result.collection.skipped_budget == 2
+ assert result.collection.skipped_page_budget == 0