Skip to content

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

feat(reading): caption embedded figures at ingest

flower-moon8c718530b2af
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.py
index 2151e4fed..2075e9ab4 100644
--- a/deeptutor/api/routers/reading.py
+++ b/deeptutor/api/routers/reading.py
@@ -48,6 +48,7 @@ from deeptutor.reading import (
export_material,
render_outline,
)
+from deeptutor.reading.captions import caption_material_media, captions_enabled
from deeptutor.reading.ingestion import (
MAX_TRANSCRIPT_BYTES,
ReadingIngestionService,
@@ -101,6 +102,31 @@ def _new_material_id() -> str:
return f"rm_{uuid.uuid4().hex[:12]}"
+def _schedule_media_captions(
+ background_tasks: BackgroundTasks, store: ReadingStore, material_id: str
+) -> None:
+ """Best-effort: caption a material's embedded figures after ingest.
+
+ The vision model writes one sentence per image back into the store's media
+ index so a text-only model can still describe every figure in the book.
+ This must never affect the upload result or the ingest status, so any
+ failure is only logged.
+ """
+ if not captions_enabled():
+ return
+ background_tasks.add_task(_caption_material_best_effort, store, material_id)
+
+
+async def _caption_material_best_effort(store: ReadingStore, material_id: str) -> None:
+ """Run the caption pass without ever letting an error escape."""
+ if not captions_enabled():
+ return
+ try:
+ await caption_material_media(material_id, store=store)
+ except Exception: # noqa: BLE001 - captioning is best-effort
+ logger.warning("Image captioning failed for %s", material_id, exc_info=True)
+
+
def _content_facts(store: ReadingStore, record: Any) -> tuple[int, int]:
"""Stored size and extracted unit count, or zeros while still processing."""
if getattr(record.status, "value", record.status) != "ready":
@@ -965,6 +991,7 @@ async def upload_material(
catalog = _catalog()
if reuse or catalog.get_material(manifest.material_id) is None:
catalog.register_manifest(manifest)
+ _schedule_media_captions(background_tasks, store, manifest.material_id)
return _detail(store, manifest)
# A separate material over the same extracted content: the bytes
# are stored once, while annotations and reading position are kept
@@ -979,6 +1006,7 @@ async def upload_material(
render_mode=manifest.render_mode,
status=IngestionStatus.READY,
)
+ _schedule_media_captions(background_tasks, store, record.material_id)
return _detail(store, store.manifest(record.material_id))
except HTTPException:
raise
@@ -1215,6 +1243,7 @@ async def get_snapshot_asset(material_id: str, asset_name: str) -> FileResponse:
"Cache-Control": "private, max-age=31536000, immutable",
"X-Content-Type-Options": "nosniff",
},
+ )
@router.get("/materials/{material_id}/media")
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 5e03fe18b..7d40b7161 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -333,6 +333,8 @@ class DocumentParsingUpdate(BaseModel):
engine: Optional[str] = None
engines: Optional[dict[str, dict]] = None
+ # Toggle for vision-model captions of embedded images (None = keep stored).
+ image_caption: Optional[bool] = None
class DocumentParsingTest(BaseModel):
@@ -1086,6 +1088,7 @@ def _document_parsing_payload() -> dict[str, Any]:
docling_slice = engines.get("docling", {})
return {
"engine": full.get("engine"),
+ "image_caption": bool(full.get("image_caption", False)),
"engines": redacted,
"available_engines": available,
"readiness": readiness,
@@ -1177,7 +1180,18 @@ async def update_document_parsing_settings(payload: DocumentParsingUpdate):
engines[name].update(merged)
new_engine = payload.engine or full.get("engine")
- service.save_document_parsing({"engine": new_engine, "engines": engines})
+ image_caption = (
+ payload.image_caption
+ if payload.image_caption is not None
+ else bool(full.get("image_caption", False))
+ )
+ service.save_document_parsing(
+ {
+ "engine": new_engine,
+ "image_caption": image_caption,
+ "engines": engines,
+ }
+ )
return _document_parsing_payload()
diff --git a/deeptutor/reading/captions.py b/deeptutor/reading/captions.py
new file mode 100644
index 000000000..e0852437a
--- /dev/null
+++ b/deeptutor/reading/captions.py
@@ -0,0 +1,151 @@
+"""Vision-derived captions for a material's embedded images.
+
+Embedded pictures live as bytes under ``<content_id>/media/`` with a
+``media.json`` index, so a text-only model reading the material sees only the
+extracted text — the figures are invisible to it. This module gives every
+image a one-sentence, vision-model caption and writes it back into the index,
+so ``read_material`` and search can describe the whole book, not just the page
+the reader happens to have open.
+
+The pass is deliberately best-effort and model-gated: no vision-capable LLM
+means no captions, a single failing image never blocks its neighbours, and any
+partial success is written back rather than discarded.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import logging
+import mimetypes
+from typing import Any
+
+from deeptutor.reading.store import ReadingStore
+from deeptutor.services.config.runtime_settings import load_document_parsing_settings
+from deeptutor.services.llm.client import get_llm_client
+from deeptutor.services.rag.pipelines.llamaindex.config import image_description_limits
+
+logger = logging.getLogger(__name__)
+
+CAPTION_SYSTEM_PROMPT = (
+ "You describe figures for a reader who cannot see them. You state only "
+ "what is visibly present and you never guess at intent."
+)
+
+CAPTION_PROMPT = (
+ "Describe this image in one sentence of at most 60 words. Only describe "
+ "what is actually visible: the figure title or caption, axis labels, "
+ "annotations, key numbers, and any formulas as written. If it is a "
+ "diagram or slide graphic, say plainly what relationship or structure it "
+ "shows. Do not add greetings, commentary, or Markdown headings."
+)
+
+
+def captions_enabled() -> bool:
+ """Whether the document-parsing settings opt into image captioning."""
+ try:
+ return bool(load_document_parsing_settings().get("image_caption", False))
+ except Exception: # noqa: BLE001 - a settings read must never break ingest
+ return False
+
+
+async def caption_material_media(
+ material_id: str,
+ *,
+ store: ReadingStore | None = None,
+ force: bool = False,
+ limit: int | None = None,
+) -> int:
+ """Caption this material's embedded images and write them back.
+
+ Returns the number of captions actually written. Rows that already carry a
+ caption are skipped unless *force* is set; *limit* caps how many images are
+ processed in this pass. A missing or text-only LLM produces zero calls and
+ a warning.
+ """
+ store = store or ReadingStore()
+ rows = store.media_items(material_id)
+ pending = [
+ row
+ for row in rows
+ if force or not str(row.get("caption") or "").strip()
+ ]
+ if limit is not None:
+ pending = pending[: max(0, int(limit))]
+ if not pending:
+ return 0
+
+ try:
+ client = get_llm_client()
+ except Exception as exc: # noqa: BLE001 - the client may not be configured
+ logger.warning("Image captioning skipped: LLM client is unavailable (%s)", exc)
+ return 0
+ if not client.supports_multimodal_images():
+ logger.warning(
+ "Image captioning skipped: the configured LLM does not accept image input."
+ )
+ return 0
+
+ concurrency, timeout_seconds = image_description_limits()
+ semaphore = asyncio.Semaphore(concurrency)
+
+ async def _caption_one(row: dict[str, Any]) -> tuple[str, str] | None:
+ name = str(row.get("name") or "")
+ path = store.media_path(material_id, name)
+ if path is None:
+ logger.warning("Image captioning skipped: %s is missing on disk", name)
+ return None
+ mime = str(row.get("mime") or "") or (
+ mimetypes.guess_type(name)[0] or "application/octet-stream"
+ )
+ try:
+ async with semaphore:
+ data = await asyncio.to_thread(path.read_bytes)
+ encoded = base64.b64encode(data).decode("ascii")
+ text = await asyncio.wait_for(
+ client.complete(
+ CAPTION_PROMPT,
+ system_prompt=CAPTION_SYSTEM_PROMPT,
+ image_data=encoded,
+ image_mime_type=mime,
+ image_filename=name,
+ ),
+ timeout=timeout_seconds,
+ )
+ except asyncio.TimeoutError:
+ logger.warning(
+ "Image captioning timed out after %ss: %s", timeout_seconds, name
+ )
+ return None
+ except Exception as exc: # noqa: BLE001 - one bad image must not sink the rest
+ logger.warning("Image captioning failed for %s: %s", name, exc)
+ return None
+ caption = str(text or "").strip()
+ if not caption:
+ logger.warning("Image captioning returned no text for %s", name)
+ return None
+ return name, caption
+
+ results = await asyncio.gather(
+ *(_caption_one(row) for row in pending), return_exceptions=True
+ )
+ captions: dict[str, str] = {}
+ for result in results:
+ if isinstance(result, BaseException):
+ logger.warning("Image captioning task failed: %s", result)
+ continue
+ if result is None:
+ continue
+ captions[result[0]] = result[1]
+
+ if not captions:
+ return 0
+ return store.update_media_captions(material_id, captions)
+
+
+__all__ = [
+ "CAPTION_PROMPT",
+ "CAPTION_SYSTEM_PROMPT",
+ "caption_material_media",
+ "captions_enabled",
+]
diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.py
index 8f345ada5..ad367774d 100644
--- a/deeptutor/reading/store.py
+++ b/deeptutor/reading/store.py
@@ -381,6 +381,152 @@ class ReadingStore:
shutil.rmtree(backup_dir, ignore_errors=True)
return manifest
+ def refresh_document(self, material_id: str) -> MaterialManifest:
+ """Re-extract a material in place from its stored original bytes.
+
+ Used to pick up extractor improvements (embedded-image captions, a
+ better text layer) without asking the user to re-upload: the source
+ bytes under ``raw/`` are parsed again and the units, media and manifest
+ are replaced atomically. User-owned state — annotations, positions,
+ bookmarks and preserved revisions — is carried across untouched.
+
+ The whole result is computed and validated *before* anything is
+ written. If the raw bytes are gone, or re-extraction would change the
+ unit count (locators would silently shift under the annotations and
+ reading positions), this raises :class:`ReadingError` and leaves every
+ file exactly as it was.
+ """
+ resolved_id = self._validate_id(material_id)
+ with self._locked(resolved_id):
+ existing = self._load_manifest(resolved_id)
+ if existing is None:
+ raise MaterialNotFound(f"material {material_id!r} not found")
+ material_dir = self._dir(resolved_id)
+ raw_path = self._find_raw(material_dir)
+ if raw_path is None:
+ raise ReadingError(
+ f"{existing.filename}: the original file is no longer stored, "
+ "so this material cannot be re-extracted."
+ )
+
+ # Validate the new extraction fully before touching the store.
+ extraction = extract_material(raw_path)
+ if len(extraction.units) != existing.unit_count:
+ raise ReadingError(
+ f"{existing.filename}: re-extraction produced "
+ f"{len(extraction.units)} units, not the stored "
+ f"{existing.unit_count}; refusing to shift locators."
+ )
+
+ # Captions cost a vision-model call each, so a re-extraction that
+ # does not re-caption (CLI ``--no-caption``) must carry the old
+ # ones forward by image name: same figure in, same caption out.
+ previous_captions = {
+ str(row.get("name")): str(row.get("caption"))
+ for row in (self.media_items(resolved_id) or [])
+ if row.get("name") and str(row.get("caption") or "").strip()
+ }
+
+ stage_dir = self.root / f".{resolved_id}.{uuid.uuid4().hex[:8]}.staging"
+ backup_dir = self.root / f".{resolved_id}.{uuid.uuid4().hex[:8]}.backup"
+ (stage_dir / UNITS_DIR).mkdir(parents=True, exist_ok=True)
+ for index, unit in enumerate(extraction.units, start=1):
+ self._unit_file(stage_dir, index).write_text(unit, encoding="utf-8")
+
+ media_rows: list[dict[str, Any]] = []
+ if extraction.media:
+ media_dir = stage_dir / MEDIA_DIR
+ media_dir.mkdir(parents=True, exist_ok=True)
+ for item in extraction.media:
+ (media_dir / item.name).write_bytes(item.data)
+ row: dict[str, Any] = {
+ "name": item.name,
+ "locator": item.locator,
+ "mime": item.mime_type,
+ "bytes": len(item.data),
+ }
+ caption = previous_captions.get(item.name)
+ if caption:
+ row["caption"] = caption
+ media_rows.append(row)
+ _atomic_write(
+ stage_dir / MEDIA_INDEX_NAME,
+ json.dumps(media_rows, ensure_ascii=False),
+ )
+
+ outline = (
+ extraction.outline
+ if extraction.outline or extraction.render_mode == "pdf"
+ else synthesise_outline(extraction.units)
+ )
+ _atomic_write(
+ stage_dir / OUTLINE_NAME,
+ json.dumps([entry.to_dict() for entry in outline], ensure_ascii=False),
+ )
+ _atomic_write(
+ stage_dir / UNIT_REFS_NAME,
+ json.dumps(
+ [entry.to_dict() for entry in extraction.unit_refs],
+ ensure_ascii=False,
+ ),
+ )
+ manifest = MaterialManifest(
+ material_id=existing.material_id,
+ filename=existing.filename,
+ unit=extraction.unit,
+ unit_count=len(extraction.units),
+ mime=existing.mime,
+ title=extraction.title or existing.title,
+ source_hash=existing.source_hash,
+ extractor=extraction.extractor,
+ byte_size=raw_path.stat().st_size,
+ char_count=extraction.char_count,
+ created_at=existing.created_at,
+ has_raw_view=existing.has_raw_view,
+ render_mode=existing.render_mode,
+ media_count=len(media_rows),
+ content_format=existing.content_format,
+ source_type=existing.source_type,
+ source_url=existing.source_url,
+ revision=existing.revision + 1,
+ )
+ _atomic_write(
+ stage_dir / MANIFEST_NAME,
+ json.dumps(manifest.to_dict(), ensure_ascii=False, indent=2),
+ )
+
+ # Keep the original bytes (linked, not duplicated) and every
+ # user-owned side file, exactly as a re-ingest would. Generated
+ # rasters live under assets/; re-extraction does not rewrite them,
+ # so they must be carried across or a web snapshot would lose its
+ # images.
+ _carry_dir(material_dir / RAW_DIR, stage_dir / RAW_DIR)
+ _carry_dir(material_dir / ASSETS_DIR, stage_dir / ASSETS_DIR)
+ for state_dir in (ANNOTATIONS_DIR, POSITIONS_DIR, BOOKMARKS_DIR, REVISIONS_DIR):
+ source_state_dir = material_dir / state_dir
+ if source_state_dir.is_dir():
+ shutil.copytree(
+ source_state_dir, stage_dir / state_dir, dirs_exist_ok=True
+ )
+ for state_name in (ANNOTATIONS_NAME, POSITION_NAME):
+ source_state = material_dir / state_name
+ if source_state.is_file():
+ shutil.copy2(source_state, stage_dir / state_name)
+
+ try:
+ if material_dir.exists():
+ os.replace(material_dir, backup_dir)
+ try:
+ os.replace(stage_dir, material_dir)
+ except Exception:
+ if backup_dir.exists() and not material_dir.exists():
+ os.replace(backup_dir, material_dir)
+ raise
+ finally:
+ shutil.rmtree(stage_dir, ignore_errors=True)
+ shutil.rmtree(backup_dir, ignore_errors=True)
+ return self.manifest(resolved_id)
+
def ingest_units(
self,
material_id: str,
@@ -747,6 +893,42 @@ class ReadingStore:
path = self._dir(material_id) / MEDIA_DIR / clean
return path if path.is_file() else None
+ def update_media_captions(
+ self, material_id: str, captions: Mapping[str, str]
+ ) -> int:
+ """Write per-image captions into the media index. Returns rows changed.
+
+ *captions* maps an image name to its text. Names absent from the index
+ are ignored silently (extraction may have dropped a figure), and an
+ empty value leaves the existing caption alone rather than erasing it.
+ The index is only rewritten when something actually changed, under the
+ same per-material lock every other write uses.
+ """
+ wanted = {
+ str(name): str(value).strip()
+ for name, value in captions.items()
+ if str(value or "").strip()
+ }
+ if not wanted:
+ return 0
+ index_path = self._dir(material_id) / MEDIA_INDEX_NAME
+ with self._locked(material_id):
+ rows = _read_json(index_path)
+ if not isinstance(rows, list):
+ return 0
+ changed = 0
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ name = str(row.get("name") or "")
+ caption = wanted.get(name)
+ if caption and str(row.get("caption") or "") != caption:
+ row["caption"] = caption
+ changed += 1
+ if changed:
+ _atomic_write(index_path, json.dumps(rows, ensure_ascii=False))
+ return changed
+
def _has_raw(self, material_id: str) -> bool:
"""Whether original bytes are already on disk, without loading them."""
try:
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
index 09900a4bc..d5886c948 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -243,6 +243,9 @@ _MINERU_ENGINE_KEYS = frozenset(_DEFAULT_MINERU_ENGINE.keys())
DEFAULT_DOCUMENT_PARSING_SETTINGS: dict[str, Any] = {
"version": 2,
"engine": _DEFAULT_DOCUMENT_PARSING_ENGINE,
+ # Caption embedded figures with a vision model at ingest, so a text-only
+ # model reading the material can still describe its images.
+ "image_caption": False,
"engines": {
DOCUMENT_PARSING_ENGINE_TEXT_ONLY: _DEFAULT_TEXT_ONLY_ENGINE,
DOCUMENT_PARSING_ENGINE_MINERU: _DEFAULT_MINERU_ENGINE,
@@ -1037,7 +1040,12 @@ class RuntimeSettingsService:
if engine not in _DOCUMENT_PARSING_ENGINES:
engine = _DEFAULT_DOCUMENT_PARSING_ENGINE
- return {"version": 2, "engine": engine, "engines": engines_out}
+ return {
+ "version": 2,
+ "engine": engine,
+ "image_caption": _coerce_bool(settings.get("image_caption"), False),
+ "engines": engines_out,
+ }
def _normalize_mineru_engine(self, settings: dict[str, Any]) -> dict[str, Any]:
mode = _string(settings.get("mode")).lower()
diff --git a/tests/reading/test_reading_captions.py b/tests/reading/test_reading_captions.py
new file mode 100644
index 000000000..df6f98a88
--- /dev/null
+++ b/tests/reading/test_reading_captions.py
@@ -0,0 +1,229 @@
+"""Tests for vision-model image captions on reading materials.
+
+The vision client is stubbed so no network call is made; the store, the media
+index round-trip and the refresh guard are exercised for real on a tmp store.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+from pathlib import Path
+import random
+
+from PIL import Image as PILImage
+import pytest
+
+from deeptutor.reading import captions as captions_module
+from deeptutor.reading.models import ReadingError
+from deeptutor.reading.store import ReadingStore
+
+_MATERIAL_ID = "a" * 16
+
+
+class _StubClient:
+ """Minimal stand-in for the LLM facade used by the caption pass."""
+
+ def __init__(self, *, vision: bool = True, fail: set[str] | None = None) -> None:
+ self._vision = vision
+ self._fail = fail or set()
+ self.calls: list[str] = []
+
+ def supports_multimodal_images(self) -> bool:
+ return self._vision
+
+ async def complete(self, prompt: str, system_prompt: str | None = None, **kwargs: object) -> str:
+ name = str(kwargs.get("image_filename") or "")
+ self.calls.append(name)
+ if name in self._fail:
+ raise RuntimeError("vision call failed")
+ return f"a chart labelled {name}"
+
+
[email protected](autouse=True)
+def _fast_limits(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(captions_module, "image_description_limits", lambda: (4, 5.0))
+
+
+def store(tmp_path: Path) -> ReadingStore:
+ root = tmp_path / "reading"
+ root.mkdir()
+ store = ReadingStore(root)
+ store.ingest_units(
+ _MATERIAL_ID,
+ filename="deck.pptx",
+ unit="slide",
+ units=["Slide one text", "Slide two text"],
+ )
+ media_dir = root / _MATERIAL_ID / "media"
+ media_dir.mkdir()
+ rows = []
+ for index in range(3):
+ name = f"image-{index:02d}.png"
+ (media_dir / name).write_bytes(b"png-bytes")
+ rows.append({"name": name, "locator": 1, "mime": "image/png", "bytes": 9})
+ (root / _MATERIAL_ID / "media.json").write_text(json.dumps(rows), encoding="utf-8")
+ return store
+
+
+async def test_caption_material_media_writes_back(
+ store: ReadingStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ stub = _StubClient()
+ monkeypatch.setattr(captions_module, "get_llm_client", lambda: stub)
+
+ written = await captions_module.caption_material_media(_MATERIAL_ID, store=store)
+
+ assert written == 3
+ assert len(stub.calls) == 3
+ rows = store.media_items(_MATERIAL_ID)
+ assert all(str(row.get("caption") or "") for row in rows)
+
+
+async def test_existing_captions_are_skipped(
+ store: ReadingStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ stub = _StubClient()
+ monkeypatch.setattr(captions_module, "get_llm_client", lambda: stub)
+
+ assert await captions_module.caption_material_media(_MATERIAL_ID, store=store) == 3
+ stub.calls.clear()
+
+ again = await captions_module.caption_material_media(_MATERIAL_ID, store=store)
+
+ assert again == 0
+ assert stub.calls == []
+
+
+async def test_single_failure_keeps_the_rest(
+ store: ReadingStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ stub = _StubClient(fail={"image-01.png"})
+ monkeypatch.setattr(captions_module, "get_llm_client", lambda: stub)
+
+ written = await captions_module.caption_material_media(_MATERIAL_ID, store=store)
+
+ assert written == 2
+ captions = {row["name"]: row.get("caption") for row in store.media_items(_MATERIAL_ID)}
+ assert captions["image-00.png"]
+ assert captions["image-02.png"]
+ assert not captions.get("image-01.png")
+
+
+async def test_text_only_client_makes_no_calls(
+ store: ReadingStore, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ stub = _StubClient(vision=False)
+ monkeypatch.setattr(captions_module, "get_llm_client", lambda: stub)
+
+ written = await captions_module.caption_material_media(_MATERIAL_ID, store=store)
+
+ assert written == 0
+ assert stub.calls == []
+
+
+def test_update_media_captions_ignores_unknown_names(store: ReadingStore) -> None:
+ changed = store.update_media_captions(
+ _MATERIAL_ID, {"missing.png": "ghost", "image-00.png": "hello"}
+ )
+
+ assert changed == 1
+ captions = {row["name"]: row.get("caption") for row in store.media_items(_MATERIAL_ID)}
+ assert captions["image-00.png"] == "hello"
+ assert not captions.get("image-01.png")
+ # An empty value never erases an existing caption nor counts as a change.
+ assert store.update_media_captions(_MATERIAL_ID, {"image-01.png": ""}) == 0
+
+
+# ---------------------------------------------------------------------------
+# refresh_document
+# ---------------------------------------------------------------------------
+
+
+def _png_bytes(seed: int = 11) -> bytes:
+ rng = random.Random(seed)
+ data = bytes(rng.randrange(256) for _ in range(400 * 300 * 3))
+ buf = io.BytesIO()
+ PILImage.frombytes("RGB", (400, 300), data).save(buf, format="PNG")
+ return buf.getvalue()
+
+
+def _pdf_with_image(path: Path) -> None:
+ import pymupdf
+
+ doc = pymupdf.open()
+ page = doc.new_page()
+ prose = (
+ "Figure one shows the measured throughput across three configurations. " * 8
+ )
+ page.insert_textbox(pymupdf.Rect(72, 72, 520, 280), prose, fontsize=9)
+ page.insert_image(pymupdf.Rect(72, 320, 300, 520), stream=_png_bytes(seed=11))
+ page.insert_image(pymupdf.Rect(320, 320, 540, 520), stream=_png_bytes(seed=23))
+ doc.save(str(path))
+ doc.close()
+
+
+def test_refresh_document_preserves_state_and_captions(tmp_path: Path) -> None:
+ store = ReadingStore(tmp_path / "reading")
+ pdf = tmp_path / "deck.pdf"
+ _pdf_with_image(pdf)
+ manifest = store.ingest(pdf)
+ names = [str(row["name"]) for row in store.media_items(manifest.material_id)]
+ assert manifest.unit_count >= 1
+ assert len(names) >= 2 # one figure kept, one re-appearing uncaptioned
+
+ content_dir = tmp_path / "reading" / manifest.material_id
+ annotation_file = content_dir / "annotations" / f"{manifest.material_id}.json"
+ annotation_file.parent.mkdir(parents=True, exist_ok=True)
+ annotation_file.write_text("[]", encoding="utf-8")
+ position_file = content_dir / "positions" / f"{manifest.material_id}.json"
+ position_file.parent.mkdir(parents=True, exist_ok=True)
+ position_file.write_text("{}", encoding="utf-8")
+
+ # Generated rasters must survive a re-extraction untouched.
+ asset_file = content_dir / "assets" / "cover.png"
+ asset_file.parent.mkdir(parents=True, exist_ok=True)
+ asset_file.write_bytes(b"poster-bytes")
+
+ # Old captions: keep one real figure's caption, drop another figure's row
+ # so it re-appears uncaptioned, and leave a ghost row that the new
+ # extraction will not reproduce.
+ kept_name = names[0]
+ new_name = names[1]
+ media_index = content_dir / "media.json"
+ rows = [
+ {"name": kept_name, "locator": 1, "mime": "image/png", "bytes": 9,
+ "caption": f"kept caption for {kept_name}"},
+ ]
+ rows.append(
+ {"name": "ghost.png", "locator": 1, "mime": "image/png", "bytes": 9,
+ "caption": "ghost caption"}
+ )
+ media_index.write_text(json.dumps(rows), encoding="utf-8")
+
+ refreshed = store.refresh_document(manifest.material_id)
+
+ assert refreshed.unit_count == manifest.unit_count
+ assert refreshed.revision == manifest.revision + 1
+ assert annotation_file.is_file()
+ assert position_file.is_file()
+ assert asset_file.read_bytes() == b"poster-bytes"
+ captions = {row["name"]: row.get("caption") for row in store.media_items(manifest.material_id)}
+ assert captions.get(kept_name) == f"kept caption for {kept_name}"
+ assert new_name in captions and not captions.get(new_name)
+ assert "ghost.png" not in captions
+
+
+def test_refresh_document_requires_raw_bytes(tmp_path: Path) -> None:
+ store = ReadingStore(tmp_path / "reading")
+ store.ingest_units("b" * 16, filename="notes.txt", units=["Some notes"])
+
+ with pytest.raises(ReadingError):
+ store.refresh_document("b" * 16)
+
+ assert store.unit_text("b" * 16, 1) == "Some notes"