DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): render the open page when its content is drawn
flower-moon31dfc681819c
diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 176133271..8d97f1165 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -631,6 +631,108 @@ 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.+ """+ 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()) < 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,+ }+ 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.++ A drawn page leads with the whole-page raster (the only way a vision model+ sees a vector diagram); embedded rasters follow. The render consumes one of+ the ``READING_VIEWPORT_MAX_IMAGES`` slots, and the total is capped there.+ Pages that do not qualify fall back to the embedded-image records alone.+ """+ viewport = viewport if isinstance(viewport, dict) else {}+ embedded = _reading_viewport_image_records(material_id, viewport)+ try:+ locator = int(viewport.get("locator") or 0)+ except (TypeError, ValueError):+ locator = 0+ if not material_id or locator <= 0:+ return embedded[:READING_VIEWPORT_MAX_IMAGES]+ rendered = _reading_viewport_page_render(material_id, locator)+ if rendered is None:+ return embedded[:READING_VIEWPORT_MAX_IMAGES]+ return [rendered, *embedded[: READING_VIEWPORT_MAX_IMAGES - 1]]+def _reading_viewport_image_records(material_id: str, viewport: dict[str, Any]) -> list[dict]:"""Image attachment records for the figures on the currently open page."""diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex 5c76b27d4..df58b961f 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -41,7 +41,7 @@ from .._turn_runtime_shared import (_reading_material_revision,_reading_references,_reading_viewport,- _reading_viewport_image_records,+ _reading_viewport_image_attachments,_reading_workspace_id,_repair_chinese_emphasis_for_persistence,_request_snapshot_metadata,@@ -332,18 +332,20 @@ class TurnExecutor:document_texts, attachment_records = extract_documents_from_records(attachment_records)- # Immersive reading: the embedded figures on the page the user is- # currently looking at ride along as image attachments, so a- # vision model sees what the question is about. Pages without- # images add nothing; pages with them add at most- # READING_VIEWPORT_MAX_IMAGES attachments. Keyed on the resolved- # workspace mode — the web composer sends capability "chat" with- # workspace_mode "immersive_reading", and the mode resolver falls- # back to the capability name for direct callers, so both shapes- # land here.+ # Immersive reading: the page the user is currently looking at+ # rides along as image attachments, so a vision model sees what+ # the question is about. A drawn page (vector diagram — common in+ # slide-exported PDFs) leads with a full-page render, since its+ # figures only exist as vectors and the embedded rasters alone+ # would be meaningless fragments; the page's embedded figures+ # follow. Total stays within READING_VIEWPORT_MAX_IMAGES (the+ # render takes one slot). Keyed on the resolved workspace mode —+ # the web composer sends capability "chat" with workspace_mode+ # "immersive_reading", and the mode resolver falls back to the+ # capability name for direct callers, so both shapes land here.if workspace_mode == "immersive_reading":attachment_records.extend(- _reading_viewport_image_records(+ _reading_viewport_image_attachments(_reading_material_id(payload.get("reading_material_id")),_reading_viewport(payload.get("reading_viewport")),)diff --git a/tests/reading/test_reading_page_render.py b/tests/reading/test_reading_page_render.pynew file mode 100644index 000000000..195394ebc--- /dev/null+++ b/tests/reading/test_reading_page_render.py@@ -0,0 +1,195 @@+"""Vector-diagram pages must ride along as a full-page render.++Slide-exported PDFs draw their figures as vectors, so a vision model sees+nothing but shadow fragments from ``page.get_images()``. These tests build real+PDFs with PyMuPDF and exercise the store-isolated helpers: a drawn page yields+a JPEG render record (leading the attachment list), a prose-only page yields+none, and the total never exceeds ``READING_VIEWPORT_MAX_IMAGES``.++The store is isolated by pointing ``DEEPTUTOR_HOME`` at a temp dir and resetting+the path-service singleton, so the helpers' real ``ReadingStore()`` resolution+path runs rather than a hand-injected store.+"""++from __future__ import annotations++import base64+import json+from pathlib import Path++import pytest++from deeptutor.services.path_service import PathService+from deeptutor.services.session._turn_runtime_shared import (+ READING_VIEWPORT_MAX_IMAGES,+ _reading_page_has_render,+ _reading_viewport_image_attachments,+ _reading_viewport_page_render,+)++pymupdf = pytest.importorskip("pymupdf")+++def reading_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):+ """A real per-user store rooted in a temp DEEPTUTOR_HOME."""+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))+ PathService.reset_instance()+ yield tmp_path+ PathService.reset_instance()+++def _png_bytes(seed: int) -> bytes:+ """A noisy PNG above the min-bytes gate so extraction keeps it."""+ import io+ import random++ from PIL import Image as PILImage++ rng = random.Random(seed)+ raw = bytes(rng.randrange(256) for _ in range(150 * 120 * 3))+ image = PILImage.frombytes("RGB", (150, 120), 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 _draw_diagram(page) -> None:+ """Ten vector primitives — comfortably past the render gate of 8."""+ for index in range(4):+ page.draw_line(+ pymupdf.Point(72, 120 + index * 12), pymupdf.Point(300, 120 + index * 12)+ )+ for index in range(3):+ page.draw_rect(pymupdf.Rect(72, 220 + index * 34, 220, 244 + index * 34))+ for index in range(3):+ page.draw_circle(pymupdf.Point(420, 220 + index * 34), 14)+++def _build_pdf(path: Path, *, embedded_images: int = 0) -> None:+ doc = pymupdf.open()+ page = doc.new_page(width=612, height=792)+ page.insert_text((72, 60), _prose("Page one."))+ _draw_diagram(page)+ for index in range(embedded_images):+ rect = pymupdf.Rect(72, 380 + index * 60, 260, 440 + index * 60)+ page.insert_image(rect, stream=_png_bytes(seed=index + 1))+ text_page = doc.new_page(width=612, height=792)+ text_page.insert_textbox(+ pymupdf.Rect(72, 72, 540, 600), _prose("Page two."), fontsize=11+ )+ doc.save(str(path))+ doc.close()+++def _ingest_deck(reading_home: Path, *, embedded_images: int = 0):+ from deeptutor.reading import ReadingStore++ source = reading_home / "day04_potential.pdf"+ _build_pdf(source, embedded_images=embedded_images)+ return ReadingStore().ingest(source)+++def _write_media_index(store, material_id: str, count: int) -> list[str]:+ """Write *count* embedded-image rows directly into the store index.++ The reading ingest caps extraction at 4 images per page, which is exactly+ the cap under test, so the index is seeded by hand to prove truncation.+ """+ material_dir = store._dir(material_id)+ media_dir = material_dir / "media"+ media_dir.mkdir(parents=True, exist_ok=True)+ names = [f"image-{index:02d}.png" for index in range(1, count + 1)]+ rows = []+ for name in names:+ (media_dir / name).write_bytes(b"png-bytes")+ rows.append({"name": name, "locator": 1, "mime": "image/png", "bytes": 9})+ (material_dir / "media.json").write_text(json.dumps(rows), encoding="utf-8")+ return names+++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)++ assert record is not None+ assert record["mime_type"] == "image/jpeg"+ assert record["type"] == "image"+ assert "-page-" in record["filename"]+ assert record["filename"].endswith("-page-1.jpg")+ assert record["id"].startswith("rp-")+ assert record["url"] == "" and record["embedded"] is True+ decoded = base64.b64decode(record["base64"])+ assert decoded[:2] == b"\xff\xd8" # JPEG SOI marker++ attachments = _reading_viewport_image_attachments(material_id, {"locator": 1})+ assert attachments+ assert attachments[0]["id"] == record["id"]+ assert len(attachments) <= READING_VIEWPORT_MAX_IMAGES+ # The page's own embedded figure follows the render.+ assert any(item["id"].startswith("rv-") for item in attachments[1:])+++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+ attachments = _reading_viewport_image_attachments(material_id, {"locator": 2})+ assert all(item["id"].startswith("rv-") for item in attachments)+++def test_attachments_truncate_to_max_with_render_first(reading_home: Path) -> None:+ from deeptutor.reading import ReadingStore++ source = reading_home / "day04_potential.pdf"+ _build_pdf(source)+ store = ReadingStore()+ manifest = store.ingest(source)+ _write_media_index(store, manifest.material_id, count=5)++ attachments = _reading_viewport_image_attachments(+ manifest.material_id, {"locator": 1}+ )++ assert len(attachments) == READING_VIEWPORT_MAX_IMAGES == 4+ assert attachments[0]["id"].startswith("rp-")+ embedded = [item for item in attachments if item["id"].startswith("rv-")]+ assert len(embedded) == READING_VIEWPORT_MAX_IMAGES - 1+++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+++def test_invalid_inputs_do_not_raise(reading_home: Path) -> None:+ manifest = _ingest_deck(reading_home)+ material_id = manifest.material_id++ # Bad material ids.+ assert _reading_viewport_page_render("", 1) is None+ assert _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 _reading_viewport_image_attachments("", {"locator": 1}) == []++ # Out-of-range locators.+ assert _reading_viewport_page_render(material_id, 0) is None+ assert _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 _reading_viewport_image_attachments(material_id, {"locator": 999}) == []+ assert _reading_viewport_image_attachments(material_id, {}) == []