DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(reading): own the page-render predicate in the reading layer
flower-moon0b0e693eb754
diff --git a/deeptutor/capabilities/reading/capability.py b/deeptutor/capabilities/reading/capability.pyindex 249fc454b..56cfa1d6f 100644--- a/deeptutor/capabilities/reading/capability.py+++ b/deeptutor/capabilities/reading/capability.py@@ -292,6 +292,22 @@ class ReadingCapability:VIEWPORT_CAPTION_CHARS,)+ @staticmethod+ def _page_render_attached(material_id: str, locator: int) -> bool:+ """Whether the turn attached a full-page render of this locator.++ The session injects a rendered image for drawn pages (vector diagrams+ whose figures never reach ``get_images()``). Mirrors that gate through+ the shared reading-layer probe. Best-effort and silent on failure: the+ seed must never turn a missing render into a broken turn.+ """+ try:+ from deeptutor.reading.page_render import page_has_render++ return page_has_render(material_id, locator)+ except Exception:+ return False+# -- tool kwargs ------------------------------------------------------def augment_kwargs(@@ -326,10 +342,13 @@ class ReadingCapability:# -- seeds ------------------------------------------------------------def pre_loop_seed(self, context: UnifiedContext) -> str:- """Report the viewport — cheap, synchronous, no I/O.+ """Report the viewport — synchronous, and cheap enough to run inline.Kept separate from the locate pre-pass so that "the user is looking at- page 12" reaches the model even when the search finds nothing.+ page 12" reaches the model even when the search finds nothing. The+ figure lines read the material's media index, and the render line only+ counts one page's drawing objects (no rasterisation), so the cost is a+ couple of file reads rather than any model call."""if not resolve_material_id(context):return ""@@ -347,6 +366,12 @@ class ReadingCapability:"they are attached to this message, so read them directly when the question ""concerns a figure.")+ if self._page_render_attached(material_id, locator):+ parts.append(+ f"Locator {locator}'s content is drawn (diagrams/figures) rather than typed; "+ "a rendered image of that page is attached to this message, so read it "+ "directly when the question concerns a figure."+ )captions = self._figure_caption_line(material_id, locator)if captions:parts.append(captions)diff --git a/deeptutor/reading/page_render.py b/deeptutor/reading/page_render.pynew file mode 100644index 000000000..bd4dfdb24--- /dev/null+++ b/deeptutor/reading/page_render.py@@ -0,0 +1,98 @@+"""Whole-page raster fallback for the reading viewport.++Slide-exported PDFs draw their figures as vectors, so ``page.get_images()``+yields only shadow fragments and a vision model has nothing to read. When the+open page carries enough vector primitives, rasterising the whole page — figure+labels and all — into one JPEG is the only way a vision model sees the figure.++The rules live here, in the reading engine, rather than in+``services.session``: the per-turn attachment injection and the capability's+viewport narration share one implementation, and the reading layer never has to+import back into ``services``. Best-effort throughout — every failure degrades+to "no render" so a page quirk can never break a turn.+"""++from __future__ import annotations++import logging++logger = logging.getLogger(__name__)++#: Page raster DPI for the "whole page is drawn" fallback. 110 dpi at JPEG+#: quality 82 measures ~132 KB / 60-80 ms per page — small enough to ride along+#: with every turn, sharp enough to read the figure labels.+PAGE_RENDER_DPI = 110++#: A page with at least this many vector drawing objects is a diagram page+#: (slide exports hit 40+; prose-only pages stay at 0-7), so a full-page+#: render adds signal instead of duplicating the text channel.+PAGE_RENDER_MIN_DRAWINGS = 8+++def page_render_record(material_id: str, locator: int) -> dict | None:+ """Render the locator's page to a JPEG when it is mainly drawn.++ Returns one attachment record shaped like the session's embedded-image+ records, or ``None`` when the material has no raw PDF, the locator is out+ of range, or the page has too few vector primitives (prose-only pages are+ already covered by the text channel, so rendering them is wasted work).+ Any failure logs and returns ``None``.+ """+ try:+ if not material_id or locator <= 0:+ return None+ import base64++ import pymupdf++ from deeptutor.reading import ReadingStore++ raw = ReadingStore().raw_path(material_id)+ if raw is None or raw.suffix.lower() != ".pdf" or not raw.is_file():+ return None+ with pymupdf.open(raw) as doc:+ if not 1 <= locator <= doc.page_count:+ return None+ page = doc[locator - 1]+ if len(page.get_drawings()) < PAGE_RENDER_MIN_DRAWINGS:+ return None+ pixmap = page.get_pixmap(dpi=PAGE_RENDER_DPI)+ image_bytes = pixmap.tobytes("jpeg", jpg_quality=82)+ return {+ "type": "image",+ "url": "",+ "base64": base64.b64encode(image_bytes).decode("ascii"),+ "filename": f"{raw.stem}-page-{locator}.jpg",+ "mime_type": "image/jpeg",+ "id": f"rp-{material_id[:12]}-{locator}",+ "embedded": True,+ }+ except Exception:+ logger.warning("reading page render failed", exc_info=True)+ return None+++def page_has_render(material_id: str, locator: int) -> bool:+ """Whether the locator's page qualifies for a full-page render (probe only).++ Same gate as :func:`page_render_record` — raw PDF and enough vector+ primitives — without paying the rasterisation, so capability narration can+ mention the page image cheaply. Failures return ``False``.+ """+ try:+ if not material_id or locator <= 0:+ return False+ import pymupdf++ from deeptutor.reading import ReadingStore++ raw = ReadingStore().raw_path(material_id)+ if raw is None or raw.suffix.lower() != ".pdf" or not raw.is_file():+ return False+ with pymupdf.open(raw) as doc:+ if not 1 <= locator <= doc.page_count:+ return False+ return len(doc[locator - 1].get_drawings()) >= PAGE_RENDER_MIN_DRAWINGS+ except Exception:+ logger.warning("reading page render probe failed", exc_info=True)+ return Falsediff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 8d97f1165..8d5bfe3ee 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -631,87 +631,23 @@ def _reading_viewport(value: Any) -> dict[str, Any]:# Images attached per reading turn when the open page has embedded figures.READING_VIEWPORT_MAX_IMAGES = 4-#: Page raster DPI for the "whole page is drawn" fallback. 110 dpi at JPEG-#: quality 82 measures ~132 KB / ~60 ms per page — small enough to ride along-#: with every turn, sharp enough to read the figure labels.-READING_VIEWPORT_RENDER_DPI = 110--#: A page with at least this many vector drawing objects is a diagram page-#: (slide exports hit 40+; prose-only pages stay at 0-7), so a full-page-#: render adds signal instead of duplicating the text channel.-READING_VIEWPORT_MIN_DRAWINGS = 8-def _reading_viewport_page_render(material_id: str, locator: int) -> dict | None:- """Render the currently open page to a JPEG when it is mainly drawn.-- Slide-exported PDFs draw their figures as vectors, so ``page.get_images()``- only yields shadow fragments and a vision model has nothing to read. When- the page carries enough vector primitives, rasterise the whole page — labels- and all — into one attachment record shaped like the embedded-image ones.- Best-effort by contract: any failure logs and returns ``None`` rather than- breaking the turn.+ """Thin wrapper over :func:`deeptutor.reading.page_render.page_render_record`.++ The rendering rules (DPI, drawing gate, record shape) live in the reading+ layer so the capability's viewport narration shares them; this name stays+ for the session's attachment path."""try:- if not material_id or locator <= 0:- return None- import base64-- import pymupdf+ from deeptutor.reading.page_render import page_render_record- from deeptutor.reading import ReadingStore-- raw = ReadingStore().raw_path(material_id)- if raw is None or raw.suffix.lower() != ".pdf" or not raw.is_file():- return None- with pymupdf.open(raw) as doc:- if not 1 <= locator <= doc.page_count:- return None- page = doc[locator - 1]- if len(page.get_drawings()) < READING_VIEWPORT_MIN_DRAWINGS:- return None- pixmap = page.get_pixmap(dpi=READING_VIEWPORT_RENDER_DPI)- image_bytes = pixmap.tobytes("jpeg", jpg_quality=82)- return {- "type": "image",- "url": "",- "base64": base64.b64encode(image_bytes).decode("ascii"),- "filename": f"{raw.stem}-page-{locator}.jpg",- "mime_type": "image/jpeg",- "id": f"rp-{material_id[:12]}-{locator}",- "embedded": True,- }+ return page_render_record(material_id, locator)except Exception:logger.warning("reading viewport page render failed", exc_info=True)return None-def _reading_page_has_render(material_id: str, locator: int) -> bool:- """Whether the open page qualifies for a full-page render (probe only).-- Mirrors :func:`_reading_viewport_page_render`'s gate — raw PDF and enough- vector primitives — without paying the rasterisation, so capability- narration can mention the page image cheaply. Failures return ``False``.- """- try:- if not material_id or locator <= 0:- return False- import pymupdf-- from deeptutor.reading import ReadingStore-- raw = ReadingStore().raw_path(material_id)- if raw is None or raw.suffix.lower() != ".pdf" or not raw.is_file():- return False- with pymupdf.open(raw) as doc:- if not 1 <= locator <= doc.page_count:- return False- return len(doc[locator - 1].get_drawings()) >= READING_VIEWPORT_MIN_DRAWINGS- except Exception:- logger.warning("reading page render probe failed", exc_info=True)- return False--def _reading_viewport_image_attachments(material_id: str, viewport: dict[str, Any]) -> list[dict]:"""Attachments for the open page: its render first, embedded figures after.diff --git a/tests/reading/test_reading_media_notes.py b/tests/reading/test_reading_media_notes.pyindex 56ca1e9d8..b08676ee3 100644--- a/tests/reading/test_reading_media_notes.py+++ b/tests/reading/test_reading_media_notes.py@@ -28,6 +28,7 @@ from deeptutor.capabilities.reading.tools import _media_notefrom deeptutor.core.context import UnifiedContextimport deeptutor.reading as reading_pkg+from deeptutor.reading import page_render as page_render_moduleclass _FakeStore:@@ -198,3 +199,47 @@ def test_pre_loop_seed_skips_media_work_without_a_locator(monkeypatch, locator)seed = ReadingCapability().pre_loop_seed(_viewport_context(locator))assert seed == ""+++def test_pre_loop_seed_announces_a_page_render(monkeypatch) -> None:+ monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore([]))+ monkeypatch.setattr(+ page_render_module, "page_has_render", lambda material_id, locator: True+ )++ seed = ReadingCapability().pre_loop_seed(_viewport_context(14))++ assert "rendered image of that page" in seed+ assert "Locator 14's content is drawn" in seed+++def test_pre_loop_seed_is_byte_for_byte_unchanged_without_a_page_render(monkeypatch) -> None:+ monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore([_row(4, "image-01.png")]))+ monkeypatch.setattr(+ page_render_module, "page_has_render", lambda material_id, locator: False+ )++ seed = ReadingCapability().pre_loop_seed(_viewport_context(4))++ # Exactly the pre-render seed: the new sentence appears only when a render+ # was actually attached.+ assert seed == (+ "The reader is currently showing locator 4. "+ "Locator 4 contains 1 embedded image(s) from the document; "+ "they are attached to this message, so read them directly when the question "+ "concerns a figure."+ )+ assert "rendered image" not in seed+++def test_pre_loop_seed_survives_a_page_render_probe_failure(monkeypatch) -> None:+ def _boom(material_id, locator):+ raise RuntimeError("page render probe failed")++ monkeypatch.setattr(reading_pkg, "ReadingStore", lambda: _FakeStore([]))+ monkeypatch.setattr(page_render_module, "page_has_render", _boom)++ seed = ReadingCapability().pre_loop_seed(_viewport_context(4))++ assert seed == "The reader is currently showing locator 4."+ assert "rendered image" not in seeddiff --git a/tests/reading/test_reading_page_render.py b/tests/reading/test_reading_page_render.pyindex 195394ebc..464fed82d 100644--- a/tests/reading/test_reading_page_render.py+++ b/tests/reading/test_reading_page_render.py@@ -19,10 +19,10 @@ from pathlib import Pathimport pytest+from deeptutor.reading.page_render import page_has_render, page_render_recordfrom deeptutor.services.path_service import PathServicefrom deeptutor.services.session._turn_runtime_shared import (READING_VIEWPORT_MAX_IMAGES,- _reading_page_has_render,_reading_viewport_image_attachments,_reading_viewport_page_render,)@@ -119,7 +119,7 @@ def test_drawn_page_renders_and_leads_attachments(reading_home: Path) -> None:manifest = _ingest_deck(reading_home, embedded_images=1)material_id = manifest.material_id- record = _reading_viewport_page_render(material_id, 1)+ record = page_render_record(material_id, 1)assert record is not Noneassert record["mime_type"] == "image/jpeg"@@ -143,7 +143,7 @@ def test_prose_only_page_has_no_render(reading_home: Path) -> None:manifest = _ingest_deck(reading_home)material_id = manifest.material_id- assert _reading_viewport_page_render(material_id, 2) is None+ assert page_render_record(material_id, 2) is Noneattachments = _reading_viewport_image_attachments(material_id, {"locator": 2})assert all(item["id"].startswith("rv-") for item in attachments)@@ -171,8 +171,24 @@ def test_has_render_matches_render_gate(reading_home: Path) -> None:manifest = _ingest_deck(reading_home)material_id = manifest.material_id- assert _reading_page_has_render(material_id, 1) is True- assert _reading_page_has_render(material_id, 2) is False+ assert page_has_render(material_id, 1) is True+ assert page_has_render(material_id, 2) is False+++def test_reading_layer_and_service_wrappers_agree(reading_home: Path) -> None:+ """The reading-layer API and the session wrappers must be one behaviour."""+ manifest = _ingest_deck(reading_home)+ material_id = manifest.material_id++ native = page_render_record(material_id, 1)+ wrapped = _reading_viewport_page_render(material_id, 1)+ assert native is not None and wrapped is not None+ assert native["id"] == wrapped["id"]+ assert native["filename"] == wrapped["filename"]+ assert native["base64"] == wrapped["base64"]+ assert page_has_render(material_id, 1) is True+ assert page_has_render(material_id, 2) is False+ assert _reading_viewport_page_render(material_id, 2) is Nonedef test_invalid_inputs_do_not_raise(reading_home: Path) -> None:@@ -180,16 +196,24 @@ def test_invalid_inputs_do_not_raise(reading_home: Path) -> None:material_id = manifest.material_id# Bad material ids.+ assert page_render_record("", 1) is None+ assert page_render_record("zzz", 1) is None+ assert page_has_render("", 1) is False+ assert page_has_render("zzz", 1) is Falseassert _reading_viewport_page_render("", 1) is Noneassert _reading_viewport_page_render("zzz", 1) is None- assert _reading_page_has_render("", 1) is False- assert _reading_page_has_render("zzz", 1) is False+ assert page_has_render("", 1) is False+ assert page_has_render("zzz", 1) is Falseassert _reading_viewport_image_attachments("", {"locator": 1}) == []# Out-of-range locators.+ assert page_render_record(material_id, 0) is None+ assert page_render_record(material_id, 999) is None+ assert page_has_render(material_id, 0) is False+ assert page_has_render(material_id, 999) is Falseassert _reading_viewport_page_render(material_id, 0) is Noneassert _reading_viewport_page_render(material_id, 999) is None- assert _reading_page_has_render(material_id, 0) is False- assert _reading_page_has_render(material_id, 999) is False+ assert page_has_render(material_id, 0) is False+ assert page_has_render(material_id, 999) is Falseassert _reading_viewport_image_attachments(material_id, {"locator": 999}) == []assert _reading_viewport_image_attachments(material_id, {}) == []