DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(reading): refresh figures on already-ingested materials
flower-moon465a49222bb6
diff --git a/deeptutor/reading/refresh.py b/deeptutor/reading/refresh.pynew file mode 100644index 000000000..2150740b3--- /dev/null+++ b/deeptutor/reading/refresh.py@@ -0,0 +1,189 @@+"""Batch re-extraction for already-ingested reading materials.++Materials ingested before embedded-figure extraction existed still say+``media_count == 0`` in their ``manifest.json`` and have no ``media.json`` beside+it. Fixing that one material at a time used to mean deleting and re-importing,+which throws away the reader's annotations, bookmarks and position. This module+drives the in-place ``ReadingStore.refresh_document`` (extract the raw bytes+again, keep user-owned state) over a set of materials and optionally backfills+image captions.++Re-extraction is **serial on purpose**: each write goes through the store's+per-material lock and a refresh stages a whole directory, so parallel refreshes+only fight for disk against no measurable win.++The CLI wrapper lives in ``scripts/reading_refresh_figures.py``.+"""++from __future__ import annotations++import logging+from typing import Any, Sequence++from deeptutor.reading.models import ReadingError+from deeptutor.reading.store import ReadingStore++logger = logging.getLogger(__name__)+++def _load_manifests(+ store: ReadingStore, material_ids: Sequence[str] | None+) -> tuple[list[Any], list[dict[str, Any]]]:+ """Return (manifests, missing). *missing* rows carry id + reason."""+ if material_ids is None:+ return list(store.list_materials()), []+ manifests: list[Any] = []+ missing: list[dict[str, Any]] = []+ for material_id in material_ids:+ try:+ manifests.append(store.manifest(material_id))+ except ReadingError as exc:+ missing.append({"material_id": str(material_id), "error": str(exc)})+ return manifests, missing+++def _has_raw_pdf(store: ReadingStore, material_id: str) -> bool:+ """Whether the original PDF bytes are still on disk to re-extract from."""+ raw = store.raw_path(material_id)+ return raw is not None and raw.suffix.lower() == ".pdf"+++def _select(+ store: ReadingStore, material_ids: Sequence[str] | None+) -> tuple[list[tuple[str, str, int]], int, list[dict[str, Any]]]:+ """Split candidates into (eligible rows, skipped count, missing rows)."""+ manifests, missing = _load_manifests(store, material_ids)+ eligible: list[tuple[str, str, int]] = []+ skipped = 0+ for manifest in manifests:+ if manifest.extractor != "pymupdf" or not _has_raw_pdf(store, manifest.material_id):+ skipped += 1+ continue+ eligible.append((manifest.material_id, manifest.filename, manifest.media_count))+ return eligible, skipped, missing+++def pdf_materials(+ store: ReadingStore, *, material_ids: Sequence[str] | None = None+) -> list[tuple[str, str, int]]:+ """PDF materials worth re-extracting: ``(material_id, filename, old_media)``.++ Only ``pymupdf``-extracted materials whose original bytes are still on disk+ qualify; anything else (DOCX/PPTX/EPUB/OCR text) is skipped and counted+ internally. Pass *material_ids* to restrict the set to specific ids.+ """+ eligible, _, _ = _select(store, material_ids)+ return eligible+++def _refresh_document(store: ReadingStore, material_id: str) -> Any:+ """Call the in-place re-extraction, failing clearly when it is missing."""+ refresh = getattr(store, "refresh_document", None)+ if refresh is None:+ raise ReadingError(+ "ReadingStore.refresh_document is not available in this build; "+ "cannot re-extract (use --dry-run to inspect without writing)."+ )+ return refresh(material_id)+++async def _caption_material_media(+ store: ReadingStore, material_id: str, *, force: bool+) -> int:+ """Caption one material's media, importing the captions module lazily.++ Deferred so ``--dry-run`` keeps working before ``captions.py`` lands.+ """+ try:+ from deeptutor.reading.captions import caption_material_media+ except ImportError as exc: # pragma: no cover - depends on build state+ raise ReadingError(+ "captioning is unavailable: deeptutor.reading.captions is not importable"+ ) from exc+ return int(+ await caption_material_media(material_id, store=store, force=force, limit=None)+ )+++async def refresh_materials(+ store: ReadingStore,+ material_ids: Sequence[str] | None,+ *,+ dry_run: bool,+ caption: bool,+ caption_force: bool,+ limit: int | None,+) -> dict[str, Any]:+ """Re-extract eligible PDFs in place and optionally caption their media.++ One material's failure is recorded and the loop continues. Returns a summary+ dict: ``processed`` / ``skipped`` / ``media_added`` / ``captions`` /+ ``failures`` plus per-material ``rows`` for the caller's table. *dry_run*+ only reads: it prints each material's filename, media count and unit count+ without importing or calling any write path.+ """+ eligible, skipped, missing = _select(store, material_ids)+ selected = eligible if limit is None else eligible[: max(0, int(limit))]++ summary: dict[str, Any] = {+ "dry_run": bool(dry_run),+ "processed": 0,+ "skipped": skipped,+ "media_added": 0,+ "captions": 0,+ "failures": list(missing),+ "rows": [],+ }+ total = len(selected)+ for index, (material_id, filename, old_media) in enumerate(selected, start=1):+ label = f"[{index}/{total}] {material_id} {filename}"+ try:+ if dry_run:+ manifest = store.manifest(material_id)+ suffix = " + captions" if caption else ""+ print(+ f"{label}: would re-extract — media={old_media} "+ f"units={manifest.unit_count}{suffix}",+ flush=True,+ )+ summary["rows"].append(+ {+ "material_id": material_id,+ "filename": filename,+ "old_media": old_media,+ "new_media": None,+ "captions": None,+ }+ )+ else:+ _refresh_document(store, material_id)+ new_media = len(store.media_items(material_id))+ caption_count = 0+ if caption:+ caption_count = await _caption_material_media(+ store, material_id, force=caption_force+ )+ gained = max(0, new_media - old_media)+ summary["media_added"] += gained+ summary["captions"] += caption_count+ print(+ f"{label}: media {old_media} -> {new_media} (+{gained}), "+ f"captions {caption_count}",+ flush=True,+ )+ summary["rows"].append(+ {+ "material_id": material_id,+ "filename": filename,+ "old_media": old_media,+ "new_media": new_media,+ "captions": caption_count,+ }+ )+ summary["processed"] = len(summary["rows"])+ except Exception as exc: # noqa: BLE001 - one bad material must not stop the batch+ print(f"{label}: FAILED — {exc}", flush=True)+ summary["failures"].append(+ {"material_id": material_id, "filename": filename, "error": str(exc)}+ )+ return summarydiff --git a/scripts/reading_refresh_figures.py b/scripts/reading_refresh_figures.pynew file mode 100644index 000000000..7908f8986--- /dev/null+++ b/scripts/reading_refresh_figures.py@@ -0,0 +1,193 @@+#!/usr/bin/env python+# -*- coding: utf-8 -*-+"""Refresh embedded figures for already-ingested reading materials (PDF only).++Usage — always run with the project venv's python. The system python has none+of the ``deeptutor`` dependencies installed, so it fails at import time:++ cd /d/DeepTutor+ ./venv/Scripts/python.exe scripts/reading_refresh_figures.py --dry-run --all+ ./venv/Scripts/python.exe scripts/reading_refresh_figures.py --dry-run --material 66ca25db46bf8a41+ ./venv/Scripts/python.exe scripts/reading_refresh_figures.py --all --yes+ ./venv/Scripts/python.exe scripts/reading_refresh_figures.py --material 66ca25db46bf8a41 --caption --yes+ ./venv/Scripts/python.exe scripts/reading_refresh_figures.py --material 66ca25db46bf8a41 --no-caption --yes++For each PDF material whose manifest says ``extractor == "pymupdf"`` and whose+original bytes are still on disk, this re-extracts the document **in place**+(``ReadingStore.refresh_document``) so embedded images land in ``media/`` and+``media.json``; annotations, bookmarks and reading position are preserved. With+captioning enabled, each stored image is captioned through the configured model.++This is a destructive in-place rewrite of ``data/user/workspace/reading``. Back+that directory up before a non-dry run if the annotations there matter to you.+Without ``--yes`` a non-dry run asks for interactive confirmation, and refuses+to run at all in a non-interactive shell.+"""++from __future__ import annotations++import argparse+import asyncio+from pathlib import Path+import sys++PROJECT_ROOT = Path(__file__).resolve().parent.parent+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++from deeptutor.reading.refresh import pdf_materials, refresh_materials # noqa: E402+from deeptutor.reading.store import ReadingStore # noqa: E402+++def _build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description="Re-extract embedded figures for ingested PDF materials.",+ )+ target = parser.add_mutually_exclusive_group()+ target.add_argument(+ "--material",+ action="append",+ metavar="ID",+ help="material id to refresh (repeatable)",+ )+ target.add_argument(+ "--all",+ action="store_true",+ help="refresh every eligible PDF material",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="read-only: print what would be refreshed, write nothing",+ )+ captions = parser.add_mutually_exclusive_group()+ captions.add_argument(+ "--caption", action="store_true", help="caption stored images (explicit on)"+ )+ captions.add_argument(+ "--no-caption", action="store_true", help="skip captioning (explicit off)"+ )+ parser.add_argument(+ "--force-caption",+ action="store_true",+ help="caption even if a stored caption already exists (implies --caption)",+ )+ parser.add_argument(+ "--limit", type=int, metavar="N", help="process at most N materials"+ )+ parser.add_argument(+ "--yes", action="store_true", help="skip the interactive confirmation"+ )+ return parser+++def _captions_enabled() -> bool:+ """Config default for captioning, tolerating the module not existing yet."""+ try:+ from deeptutor.reading.captions import captions_enabled+ except ImportError:+ print(+ "note: captioning module unavailable; defaulting to --no-caption",+ file=sys.stderr,+ )+ return False+ try:+ return bool(captions_enabled())+ except Exception as exc: # noqa: BLE001 - a bad config must not block dry runs+ print(f"note: captions_enabled() failed ({exc}); defaulting to off", file=sys.stderr)+ return False+++def _print_table(summary: dict) -> None:+ rows = summary["rows"]+ print()+ print("mode:", "dry-run" if summary["dry_run"] else "refresh")+ header = ("material id", "filename", "old media", "new media", "captions")+ table = [header]+ for row in rows:+ table.append(+ (+ str(row["material_id"]),+ str(row["filename"]),+ str(row["old_media"]),+ "-" if row["new_media"] is None else str(row["new_media"]),+ "-" if row["captions"] is None else str(row["captions"]),+ )+ )+ if len(table) > 1:+ widths = [max(len(line[col]) for line in table) for col in range(len(header))]+ for line in table:+ print(" ".join(cell.ljust(widths[col]) for col, cell in enumerate(line)).rstrip())+ print(+ f"processed={summary['processed']} skipped={summary['skipped']} "+ f"media_added={summary['media_added']} captions={summary['captions']} "+ f"failures={len(summary['failures'])}"+ )+ for failure in summary["failures"]:+ print(+ f" FAILED {failure['material_id']}: {failure['error']}",+ file=sys.stderr,+ )+++def main(argv: list[str] | None = None) -> int:+ parser = _build_parser()+ args = parser.parse_args(argv)++ if not args.material and not args.all:+ parser.error("choose one of --material <id> (repeatable) or --all")+ if args.no_caption and args.force_caption:+ parser.error("--no-caption conflicts with --force-caption")++ if args.no_caption:+ caption = False+ elif args.caption or args.force_caption:+ caption = True+ else:+ caption = _captions_enabled()++ material_ids = args.material if args.material else None+ store = ReadingStore()++ if not args.dry_run and not args.yes:+ eligible = pdf_materials(store, material_ids=material_ids)+ if args.limit is not None:+ eligible = eligible[: max(0, args.limit)]+ if not eligible:+ print("nothing to refresh")+ return 0+ if not sys.stdin.isatty():+ print(+ "refusing to run a non-dry refresh without --yes in a "+ "non-interactive shell",+ file=sys.stderr,+ )+ return 2+ print(f"about to re-extract {len(eligible)} material(s) in place under {store.root}:")+ for material_id, filename, old_media in eligible:+ print(f" {material_id} {filename} (media={old_media})")+ print(f"captioning: {'on' if caption else 'off'}")+ try:+ answer = input("Proceed? [y/N] ").strip().lower()+ except EOFError:+ answer = ""+ if answer not in ("y", "yes"):+ print("aborted")+ return 2++ summary = asyncio.run(+ refresh_materials(+ store,+ material_ids,+ dry_run=args.dry_run,+ caption=caption,+ caption_force=args.force_caption,+ limit=args.limit,+ )+ )+ _print_table(summary)+ return 1 if summary["failures"] else 0+++if __name__ == "__main__":+ raise SystemExit(main())