DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(documents): Office/PDF 嵌入图片全链路支持 — 提取、显示、喂视觉模型
flower-moone1b4954a2368
diff --git a/deeptutor/api/routers/reading.py b/deeptutor/api/routers/reading.pyindex f09176edd..2151e4fed 100644--- a/deeptutor/api/routers/reading.py+++ b/deeptutor/api/routers/reading.py@@ -1215,6 +1215,37 @@ async def get_snapshot_asset(material_id: str, asset_name: str) -> FileResponse:"Cache-Control": "private, max-age=31536000, immutable","X-Content-Type-Options": "nosniff",},++[email protected]("/materials/{material_id}/media")+async def list_material_media(material_id: str) -> list[dict[str, Any]]:+ """The embedded-image index (name / locator / mime / size), empty if none."""+ store = _store()+ try:+ return store.media_items(material_id)+ except Exception as exc:+ raise _http_error(exc) from exc++[email protected]("/materials/{material_id}/media/{name}")+async def get_material_media(material_id: str, name: str) -> FileResponse:+ """One embedded image's bytes, for the reader pane's media strip."""+ store = _store()+ try:+ path = store.media_path(material_id, name)+ mime = next(+ (row.get("mime") for row in store.media_items(material_id) if row.get("name") == name),+ "",+ )+ except Exception as exc:+ raise _http_error(exc) from exc+ if path is None:+ raise HTTPException(status_code=404, detail="No such image in this material.")+ return FileResponse(+ path,+ media_type=mime or "image/png",+ filename=name,+ content_disposition_type="inline",)diff --git a/deeptutor/capabilities/reading/capability.py b/deeptutor/capabilities/reading/capability.pyindex 1f56beeec..d8cd09a9c 100644--- a/deeptutor/capabilities/reading/capability.py+++ b/deeptutor/capabilities/reading/capability.py@@ -238,6 +238,20 @@ class ReadingCapability:)return rendered+ @staticmethod+ def _embedded_image_count(material_id: str, locator: int) -> int:+ """How many embedded images sit on the locator being viewed.++ Best-effort and silent on failure: the seed must never turn a missing+ media index into a broken turn.+ """+ try:+ from deeptutor.reading import ReadingStore++ return len(ReadingStore().media_items_at(material_id, locator))+ except Exception:+ return 0+# -- tool kwargs ------------------------------------------------------def augment_kwargs(@@ -285,6 +299,13 @@ class ReadingCapability:parts: list[str] = []if locator:parts.append(f"The reader is currently showing locator {locator}.")+ embedded = self._embedded_image_count(resolve_material_id(context), locator)+ if embedded:+ parts.append(+ f"Locator {locator} contains {embedded} embedded image(s) from the document; "+ "they are attached to this message, so read them directly when the question "+ "concerns a figure."+ )time_seconds = _as_float(viewport.get("time_seconds"))if time_seconds >= 0 and "time_seconds" in viewport:parts.append(f"Current media time: {_timestamp(time_seconds)} ({time_seconds:.1f}s).")diff --git a/deeptutor/capabilities/reading/tools.py b/deeptutor/capabilities/reading/tools.pyindex 0b1e11903..38567ba32 100644--- a/deeptutor/capabilities/reading/tools.py+++ b/deeptutor/capabilities/reading/tools.py@@ -35,6 +35,7 @@ from __future__ import annotationsimport asyncioimport logging+from collections.abc import Sequencefrom typing import Anyfrom deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult@@ -420,6 +421,7 @@ class ReadMaterialTool(_ReadingToolBase):for locator in rendered.locatorsif locator in stamps)+ media_note = await asyncio.to_thread(_media_note, store, material_id, manifest.unit, rendered.locators)followup = ("\n\n→ Now call reader_goto with the verbatim sentence you are ""about to cite, so the user sees it highlighted, and cite it in "@@ -430,7 +432,7 @@ class ReadMaterialTool(_ReadingToolBase):))return ToolResult(- content=rendered.text + timing + followup,+ content=rendered.text + timing + media_note + followup,sources=[{"type": "reading",@@ -450,6 +452,41 @@ class ReadMaterialTool(_ReadingToolBase):)+def _media_note(store: Any, material_id: str, unit: str, locators: Sequence[int]) -> str:+ """List the embedded images that live in the units just read.++ The reader pane displays these images next to their unit, and the turn+ already carries the ones on the user's current page — so when the user+ asks about a figure, the model knows it exists, where it sits, and that+ the image parts attached to the message are those figures.+ """+ try:+ rows = store.media_items(material_id)+ except Exception:+ return ""+ wanted = set(locators)+ by_locator: dict[int, list[str]] = {}+ for row in rows:+ try:+ locator = int(row.get("locator") or 0)+ except (TypeError, ValueError):+ continue+ name = str(row.get("name") or "")+ if locator in wanted and name:+ by_locator.setdefault(locator, []).append(name)+ if not by_locator:+ return ""+ lines = [+ f"- {unit} {locator}: " + ", ".join(names)+ for locator, names in sorted(by_locator.items())+ ]+ return (+ "\n\nEmbedded images in the units above (shown in the reader pane; "+ "image parts attached to this conversation's messages are these "+ "figures):\n" + "\n".join(lines)+ )++class ReaderGotoTool(_ReadingToolBase):"""Move the user's viewport — refused unless the quote checks out."""diff --git a/deeptutor/reading/extract.py b/deeptutor/reading/extract.pyindex 27f67c052..77d818024 100644--- a/deeptutor/reading/extract.py+++ b/deeptutor/reading/extract.py@@ -34,6 +34,12 @@ from pathlib import Pathimport refrom deeptutor.reading.models import OutlineEntry, ReadingError, RenderMode, UnitKind, UnitReference+from deeptutor.utils.document_images import (+ EmbeddedImage,+ extract_docx_rich,+ extract_pptx_rich,+ find_markers,+)logger = logging.getLogger(__name__)@@ -56,6 +62,16 @@ _MD_FENCE = re.compile(r"^\s{0,3}(?P<marker>`{3,}|~{3,})")RAW_VIEW_EXTENSIONS = frozenset({".pdf"})+@dataclass(frozen=True, slots=True)+class MediaItem:+ """One embedded image pinned to the locator whose text references it."""++ name: str+ mime_type: str+ data: bytes+ locator: int++@dataclass(frozen=True, slots=True)class Extraction:"""The result of cutting one source file into units."""@@ -71,12 +87,42 @@ class Extraction:outline: tuple[OutlineEntry, ...] = field(default_factory=tuple)render_mode: RenderMode = "text"unit_refs: tuple[UnitReference, ...] = field(default_factory=tuple)+ # Embedded pictures (DOCX/PPTX) mapped to the unit that mentions them.+ media: tuple[MediaItem, ...] = field(default_factory=tuple)@propertydef char_count(self) -> int:return sum(len(u) for u in self.units)+def _media_for_units(+ units: tuple[str, ...], images: tuple[EmbeddedImage, ...]+) -> tuple[MediaItem, ...]:+ """Map ``[图片 N]`` markers in unit texts to their image bytes.++ A marker names the image it belongs to, so the mapping needs no position+ bookkeeping: scan each unit, look the name up, and pin the image to that+ locator. Repeated markers (the same figure floated into two sections) are+ kept once per locator; unknown names are skipped silently — the text still+ stands on its own.+ """+ by_name = {image.name: image for image in images}+ if not by_name:+ return ()+ items: list[MediaItem] = []+ seen: set[tuple[int, str]] = set()+ for locator, unit in enumerate(units, start=1):+ for _, name in find_markers(unit):+ image = by_name.get(name)+ if image is None or (locator, name) in seen:+ continue+ seen.add((locator, name))+ items.append(+ MediaItem(name=name, mime_type=image.mime_type, data=image.data, locator=locator)+ )+ return tuple(items)++def extract_material(path: str | Path) -> Extraction:"""Cut *path* into units, dispatching on its extension.@@ -208,14 +254,43 @@ def _pdf_outline(doc: object, *, page_count: int) -> tuple[OutlineEntry, ...]:def _extract_slides(source: Path) -> Extraction:- text = _shared_extract(source)+ text, images = _slides_text_and_images(source)parts = [part.strip() for part in _SLIDE_SEPARATOR.split(text)]units = tuple(part for part in parts if part)if not units:# The extractor found text but no slide separators (legacy .ppt via the# raw-OOXML fallback). Treat it as flat text rather than losing it.return _sections_from_text(text, extractor="pptx-text")- return Extraction(units=units, unit="slide", extractor="pptx")+ return Extraction(+ units=units,+ unit="slide",+ extractor="pptx",+ media=_media_for_units(units, images),+ )+++def _slides_text_and_images(source: Path) -> tuple[str, tuple[EmbeddedImage, ...]]:+ """Slide text with image markers, preferring the rich extraction.++ Falls back to the shared extractor (text only) when the rich path cannot+ read the deck, so ingest never fails on a picture quirk.+ """+ try:+ rich = extract_pptx_rich(source.read_bytes())+ except Exception:+ rich = None+ if rich is not None and any(slide.strip() for slide in rich.slides):+ parts = [+ f"--- Slide {index} ---\n{slide}".rstrip()+ for index, slide in enumerate(rich.slides, 1)+ if slide.strip()+ ]+ text = "\n\n".join(parts)+ note = rich.collection.summary_note()+ if note:+ text += f"\n\n{note}"+ return text, rich.collection.images+ return _shared_extract(source), ()# ---------------------------------------------------------------------------@@ -224,6 +299,30 @@ def _extract_slides(source: Path) -> Extraction:def _extract_sections(source: Path) -> Extraction:+ """Flat-text formats, cut into sections on paragraph boundaries.++ DOCX goes through the rich extraction first so embedded images survive+ with their section mapping; every other format (and a failed rich parse)+ uses the shared text-only extractor.+ """+ images: tuple[EmbeddedImage, ...] = ()+ if source.suffix.lower() == ".docx":+ try:+ rich = extract_docx_rich(source.read_bytes())+ except Exception:+ rich = None+ if rich is not None and any(paragraph.strip() for paragraph in rich.paragraphs):+ text = "\n\n".join(rich.paragraphs)+ note = rich.collection.summary_note()+ if note:+ text += f"\n\n{note}"+ units = split_into_sections(text)+ return Extraction(+ units=units,+ unit="section",+ extractor="docx",+ media=_media_for_units(units, rich.collection.images),+ )return _sections_from_text(_shared_extract(source), extractor="text")diff --git a/deeptutor/reading/models.py b/deeptutor/reading/models.pyindex 25b27bd11..cc52429a6 100644--- a/deeptutor/reading/models.py+++ b/deeptutor/reading/models.py@@ -207,6 +207,9 @@ class MaterialManifest:# Selects the faithful renderer without overloading ``has_raw_view``.# The legacy boolean remains PDF-only until every client understands EPUB.render_mode: RenderMode = "text"+ # Embedded images stored under ``media/`` (DOCX/PPTX today; PDFs render+ # their own images in the raw view). Zero for older materials.+ media_count: int = 0# Uploaded Markdown remains literal source text; only captured web pages# opt into structured rendering.content_format: ContentFormat = "plain_text"@@ -229,6 +232,7 @@ class MaterialManifest:"created_at": self.created_at,"has_raw_view": self.has_raw_view,"render_mode": self.render_mode,+ "media_count": self.media_count,"content_format": self.content_format,"source_type": self.source_type,"source_url": self.source_url,@@ -258,6 +262,7 @@ class MaterialManifest:created_at=float(data.get("created_at") or 0.0),has_raw_view=bool(data.get("has_raw_view")),render_mode=render_mode, # type: ignore[arg-type]+ media_count=int(data.get("media_count") or 0),content_format=content_format, # type: ignore[arg-type]source_type=str(data.get("source_type") or "upload"),source_url=str(data.get("source_url") or ""),diff --git a/deeptutor/reading/store.py b/deeptutor/reading/store.pyindex d9c142464..8f345ada5 100644--- a/deeptutor/reading/store.py+++ b/deeptutor/reading/store.py@@ -33,6 +33,7 @@ import jsonimport loggingimport osfrom pathlib import Path+import posixpathimport reimport shutilimport sqlite3@@ -74,6 +75,8 @@ MAX_BOOKMARKS = 200UNIT_REFS_NAME = "unit_refs.json"UNITS_DIR = "units"RAW_DIR = "raw"+MEDIA_DIR = "media"+MEDIA_INDEX_NAME = "media.json"ASSETS_DIR = "assets"REVISIONS_DIR = "revisions"@@ -259,6 +262,25 @@ class ReadingStore:for index, unit in enumerate(extraction.units, start=1):self._unit_file(stage_dir, index).write_text(unit, encoding="utf-8")+ # Embedded pictures (DOCX/PPTX): bytes under media/, addresses in+ # media.json. Written before the manifest so a reader that trusts+ # the manifest never finds a missing image behind it.+ 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)+ media_rows.append(+ {+ "name": item.name,+ "locator": item.locator,+ "mime": item.mime_type,+ "bytes": len(item.data),+ }+ )+ _atomic_write(stage_dir / MEDIA_INDEX_NAME, json.dumps(media_rows, ensure_ascii=False))+if extraction.render_mode != "text":raw_dir = stage_dir / RAW_DIRraw_dir.mkdir(parents=True, exist_ok=True)@@ -300,6 +322,7 @@ class ReadingStore:# pdf.js. EPUB dispatch is carried by ``render_mode`` instead.has_raw_view=extraction.render_mode == "pdf",render_mode=extraction.render_mode,+ media_count=len(media_rows),)# Manifest last: its presence is the "this material is usable"# signal, so it must not appear before the units it describes.@@ -703,6 +726,27 @@ class ReadingStore:return Nonereturn self._find_raw(self._dir(material_id))+ def media_items(self, material_id: str) -> list[dict[str, Any]]:+ """The embedded-image index: name / locator / mime / byte size rows."""+ rows = _read_json(self._dir(material_id) / MEDIA_INDEX_NAME)+ if not isinstance(rows, list):+ return []+ return [row for row in rows if isinstance(row, dict) and row.get("name")]++ def media_items_at(self, material_id: str, locator: int) -> list[dict[str, Any]]:+ """Embedded images attached to one locator, in extraction order."""+ return [row for row in self.media_items(material_id) if row.get("locator") == locator]++ def media_path(self, material_id: str, name: str) -> Path | None:+ """Resolve a media file by index-validated name (no traversal)."""+ clean = posixpath.basename(str(name or "").replace("\\", "/"))+ if not clean:+ return None+ if not any(row.get("name") == clean for row in self.media_items(material_id)):+ return None+ path = self._dir(material_id) / MEDIA_DIR / clean+ return path if path.is_file() else None+def _has_raw(self, material_id: str) -> bool:"""Whether original bytes are already on disk, without loading them."""try:diff --git a/deeptutor/services/session/_turn_runtime_shared.py b/deeptutor/services/session/_turn_runtime_shared.pyindex 1e22a30df..176133271 100644--- a/deeptutor/services/session/_turn_runtime_shared.py+++ b/deeptutor/services/session/_turn_runtime_shared.py@@ -571,9 +571,11 @@ def _mastery_action_context(return "\n\n".join(lines)-# Reading material ids are content hashes; anything else is a client bug or an+# Reading material ids are content hashes or catalog-minted rm_ ids (a second+# copy of the same content gets its own catalog row, and the store resolves+# both to the same content directory); anything else is a client bug or an# injection attempt, so the shape is enforced here rather than deeper in.-_READING_ID_RE = re.compile(r"^[0-9a-f]{8,64}$")+_READING_ID_RE = re.compile(r"^(?:[0-9a-f]{8,64}|rm_[0-9a-f]{12})$")_READING_WORKSPACE_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")# A selection is quoted back into the prompt, so it is bounded here — the# reader has no reason to send more, and a runaway selection must not eat the@@ -626,6 +628,47 @@ def _reading_viewport(value: Any) -> dict[str, Any]:return viewport+# Images attached per reading turn when the open page has embedded figures.+READING_VIEWPORT_MAX_IMAGES = 4+++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."""+ try:+ locator = int(viewport.get("locator") or 0)+ except (TypeError, ValueError):+ locator = 0+ if not material_id or locator <= 0:+ return []+ try:+ import base64++ from deeptutor.reading import ReadingStore++ store = ReadingStore()+ rows = store.media_items_at(material_id, locator)+ records: list[dict] = []+ for index, row in enumerate(rows[:READING_VIEWPORT_MAX_IMAGES], start=1):+ path = store.media_path(material_id, str(row.get("name") or ""))+ if path is None:+ continue+ records.append(+ {+ "type": "image",+ "url": "",+ "base64": base64.b64encode(path.read_bytes()).decode("ascii"),+ "filename": str(row.get("name") or f"image-{index}.png"),+ "mime_type": str(row.get("mime") or "image/png"),+ "id": f"rv-{material_id[:12]}-{locator}-{index}",+ "embedded": True,+ }+ )+ return records+ except Exception:+ logger.warning("reading viewport image lookup failed", exc_info=True)+ return []++def _course_field(value: Any, key: str, default: Any = "") -> Any:if isinstance(value, dict):return value.get(key, default)diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex e57725af1..5c76b27d4 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -41,6 +41,7 @@ from .._turn_runtime_shared import (_reading_material_revision,_reading_references,_reading_viewport,+ _reading_viewport_image_records,_reading_workspace_id,_repair_chinese_emphasis_for_persistence,_request_snapshot_metadata,@@ -330,6 +331,55 @@ class TurnExecutor:from deeptutor.utils.document_extractor import extract_documents_from_recordsdocument_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.+ if workspace_mode == "immersive_reading":+ attachment_records.extend(+ _reading_viewport_image_records(+ _reading_material_id(payload.get("reading_material_id")),+ _reading_viewport(payload.get("reading_viewport")),+ )+ )++ # Embedded images harvested out of office documents during+ # extraction arrive with base64 and no URL — host them too so+ # message previews survive the base64 pruning below and the+ # reader pane can display them.+ for record in attachment_records:+ if record.get("url") or not record.get("base64"):+ continue+ try:+ raw_bytes = _b64.b64decode(record["base64"], validate=False)+ except Exception as exc:+ logger.warning(+ "skipping embedded-image upload for %r: invalid base64 (%s)",+ record.get("filename"),+ exc,+ )+ continue+ try:+ record["url"] = await attachment_store.put(+ session_id=session_id,+ attachment_id=record.get("id") or _uuid.uuid4().hex[:12],+ filename=record.get("filename", "") or "image",+ data=raw_bytes,+ mime_type=record.get("mime_type", "") or "",+ )+ except Exception as exc:+ logger.warning(+ "attachment store rejected embedded image %r: %s",+ record.get("filename"),+ exc,+ )+attachments = [Attachment(type=r.get("type", "file"),diff --git a/deeptutor/utils/document_extractor.py b/deeptutor/utils/document_extractor.pyindex 7171c4568..e774e9dd5 100644--- a/deeptutor/utils/document_extractor.py+++ b/deeptutor/utils/document_extractor.py@@ -36,6 +36,14 @@ from defusedxml import ElementTree as DefusedElementTreefrom defusedxml.common import DefusedXmlExceptionfrom deeptutor.services.rag.file_routing import FileTypeRouter+from deeptutor.utils.document_images import (+ EmbeddedImage,+ build_marker,+ extract_docx_rich,+ extract_pdf_images,+ extract_pptx_rich,+ image_index_from_name,+)logger = logging.getLogger(__name__)@@ -66,6 +74,13 @@ MAX_TOTAL_DOC_BYTES = 25 * 1024 * 1024MAX_EXTRACTED_CHARS_PER_DOC = 200_000MAX_EXTRACTED_CHARS_TOTAL = 150_000+# Embedded images harvested from document attachments are emitted as extra+# image-type records and injected into the LLM request. Per-document caps live+# in ``document_images``; these bound what one chat turn may carry in total so+# a deck of image-heavy slides cannot balloon the request payload without end.+MAX_EMBEDDED_IMAGES_PER_TURN = 16+MAX_EMBEDDED_IMAGE_BYTES_PER_TURN = 12 * 1024 * 1024+def _current_limits() -> tuple[int, int, int, int]:"""(max_file_bytes, max_total_bytes, max_chars_per_doc, max_chars_total).@@ -368,6 +383,25 @@ def _extract_pdf(data: bytes, filename: str) -> str:pages = [f"--- Page {i} ---\n{page.get_text() or ''}" for i, page in enumerate(doc, 1)]+ pdf_images = extract_pdf_images(data)+ if pdf_images.collection.images:+ 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+ ]+ pages = [+ page_text+ + (+ "\n" + "\n".join(marker_by_page[i])+ if i in marker_by_page+ else ""+ )+ for i, page_text in enumerate(pages, 1)+ ]+ note = pdf_images.collection.summary_note()+ if note:+ pages.append(note)return "\n\n".join(pages)except CorruptDocumentError:raise@@ -414,6 +448,27 @@ def _extract_pdf(data: bytes, filename: str) -> str:def _extract_docx(data: bytes, filename: str) -> str:+ """Body text with inline ``[图片 N: name]`` markers where images sit.++ The rich OOXML walk is primary: it sees table text that ``doc.paragraphs``+ misses, and it is the only variant that knows where the pictures are. The+ python-docx / raw-OOXML paths remain as fallbacks for documents the safe+ XML parser refuses.+ """+ try:+ rich = extract_docx_rich(data)+ except Exception as exc:+ rich = None+ logger.info("docx rich extraction failed on %s; falling back: %s", filename, exc)++ if rich is not None:+ text = "\n\n".join(rich.paragraphs)+ note = rich.collection.summary_note()+ if note:+ text = f"{text}\n\n{note}" if text else note+ if text.strip():+ return text+global DocxDocumentif DocxDocument is _NOT_LOADED:try:@@ -491,6 +546,25 @@ def _extract_xlsx(data: bytes, filename: str) -> str:def _extract_pptx(data: bytes, filename: str) -> str:+ """Slide text with image markers, then the legacy text-only paths."""+ try:+ rich = extract_pptx_rich(data)+ except Exception as exc:+ rich = None+ logger.info("pptx rich extraction failed on %s; falling back: %s", filename, exc)++ if rich is not None and any(slide.strip() for slide in rich.slides):+ slides = [+ f"--- Slide {index} ---\n{slide}".rstrip()+ for index, slide in enumerate(rich.slides, 1)+ if slide.strip()+ ]+ text = "\n\n".join(slides)+ note = rich.collection.summary_note()+ if note:+ text += f"\n\n{note}"+ return text+global PptxPresentationif PptxPresentation is _NOT_LOADED:try:@@ -1111,6 +1185,26 @@ def _collect_pptx_shape_text(shape, out: list[str]) -> None:out.append(text)+def _embedded_images_for_document(filename: str, data: bytes) -> tuple[EmbeddedImage, ...]:+ """Best-effort embedded-image harvest for the chat attachment path.++ Re-parses the document after the text pass (the shared text API stays+ text-only for its many callers). Failures never fail the message — the+ text extraction result stands on its own.+ """+ ext = _ext(filename)+ try:+ if ext == ".docx":+ return extract_docx_rich(data).collection.images+ if ext == ".pptx":+ return extract_pptx_rich(data).collection.images+ if ext == ".pdf":+ return extract_pdf_images(data).collection.images+ except Exception:+ logger.info("embedded image extraction failed for %s", filename, exc_info=True)+ return ()++def extract_documents_from_records(records: Iterable[dict],) -> tuple[list[str], list[dict]]:@@ -1133,6 +1227,12 @@ def extract_documents_from_records(stored under ``extracted_text`` so the chat UI can preview officedocuments without re-running the parser. Image / non-documentrecords are returned unchanged.++ Documents with embedded pictures additionally emit image-type+ records (one per extracted picture, base64-filled, ``embedded``+ flag set) immediately after the document's own record; callers+ persist them so the multimodal pipeline forwards the pictures to+ vision-capable models and the UI previews them inline."""doc_texts: list[str] = []updated: list[dict] = []@@ -1140,6 +1240,8 @@ def extract_documents_from_records(total_bytes = 0total_chars = 0over_quota = False+ embedded_images = 0+ embedded_image_bytes = 0for raw in records:record = dict(raw)@@ -1208,6 +1310,43 @@ def extract_documents_from_records(+ f"... (truncated, {len(text)} chars total; turn quota hit)")+ # Harvest embedded pictures and emit them as image-type records right+ # after the document, so vision models see what the text refers to and+ # the UI previews them like any pasted screenshot.+ doc_id = str(record.get("id") or "")+ stem = filename[: -len(_ext(filename))] or filename+ images = _embedded_images_for_document(filename, data)+ emitted: list[EmbeddedImage] = []+ for image in images:+ if embedded_images >= MAX_EMBEDDED_IMAGES_PER_TURN:+ break+ if embedded_image_bytes + len(image.data) > MAX_EMBEDDED_IMAGE_BYTES_PER_TURN:+ break+ ext = f".{image.name.rsplit('.', 1)[-1]}" if "." in image.name else ".png"+ embedded_images += 1+ embedded_image_bytes += len(image.data)+ emitted.append(image)+ updated.append(+ {+ "type": "image",+ "url": "",+ "base64": base64.b64encode(image.data).decode("ascii"),+ "filename": f"{stem}-图{image_index_from_name(image.name)}{ext}",+ "mime_type": image.mime_type,+ "id": f"{doc_id}-e{image_index_from_name(image.name):02d}"+ if doc_id+ else "",+ "embedded": True,+ }+ )+ if images and len(emitted) < len(images):+ text += f"\n[本文件还有 {len(images) - len(emitted)} 张图片因数量/大小上限未随消息提供]"+ if emitted:+ text += (+ f"\n[本文件内嵌 {len(emitted)} 张图片,已作为图片附件随本条消息提供,"+ "编号与本文件文本中的 [图片 N] 标记对应]"+ )+total_chars += len(text)doc_texts.append(f"[File: {filename}]\n{text}")record["base64"] = ""diff --git a/deeptutor/utils/document_images.py b/deeptutor/utils/document_images.pynew file mode 100644index 000000000..ca469e421--- /dev/null+++ b/deeptutor/utils/document_images.py@@ -0,0 +1,550 @@+"""Embedded-image extraction for Office documents and PDFs.++Text extraction everywhere in DeepTutor is text-only by design, which silently+drops the pictures inside DOCX/PPTX/PDF attachments: the reader never sees+them and neither does the model. This module is the shared fix — bytes in,+embedded raster images out, plus the *marker strings* that let the plain-text+extraction record where each image belonged in the reading order.++Two consumers:+ * ``utils.document_extractor`` — chat attachments (and the KB/reading text+ paths that share its parsers) append the markers to the extracted text and+ emit the images as image-type attachment records so the existing+ multimodal injection pipeline forwards them to vision-capable models.+ * ``reading.extract`` — maps markers to section locators so the reader pane+ can display each image next to the section that contains it.++Markers use a fixed, greppable format (``[图片 3: image-03.png]``) so both+consumers and the model itself can tie an image back to its position without+any side-channel. Numbering is 1-based and document-wide, matching the+``name`` given to each :class:`EmbeddedImage`.++Vector formats (EMF/WMF) and other formats vision models cannot consume are+counted in the returned :class:`ImageCollection` and never emitted, but the+text keeps an unnumbered note so their existence is not silently erased.+"""++from __future__ import annotations++from dataclasses import dataclass, field+import io+import logging+import posixpath+import re+from typing import Any+import zipfile++from defusedxml import ElementTree as DefusedElementTree++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Budgets. Defaults serve the chat-attachment path; the reading-area ingest+# passes looser per-document caps because images are stored on disk there and+# never inflated into a single LLM request.+# ---------------------------------------------------------------------------+MAX_IMAGES_PER_DOC = 12+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++# 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(+ {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}+)++_MIME_BY_EXT = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ ".bmp": "image/bmp",+}+++@dataclass(frozen=True, slots=True)+class EmbeddedImage:+ """One extracted raster image. ``name`` is unique within a document."""++ name: str+ mime_type: str+ data: bytes+++@dataclass+class ImageBudget:+ """Running caps and skip counters while collecting one document's images.++ Mutable by design: the walk functions thread one instance through the+ whole document and read the counters afterwards.+ """++ max_images: int = MAX_IMAGES_PER_DOC+ max_total_bytes: int = MAX_TOTAL_IMAGE_BYTES_PER_DOC+ max_image_bytes: int = MAX_IMAGE_BYTES+ min_image_bytes: int = MIN_IMAGE_BYTES+ count: int = 0+ total_bytes: int = 0+ skipped_vector: int = 0+ skipped_other: int = 0+ skipped_budget: int = 0++ def register_vector_skip(self) -> None:+ self.skipped_vector += 1++ def register_other_skip(self) -> None:+ self.skipped_other += 1++ def try_admit(self, ext: str, data: bytes) -> EmbeddedImage | None:+ """Admit one candidate image, applying every budget. ``None`` = skip."""+ if len(data) < self.min_image_bytes or len(data) > self.max_image_bytes:+ self.skipped_budget += 1+ return None+ if self.count >= self.max_images or self.total_bytes + len(data) > self.max_total_bytes:+ self.skipped_budget += 1+ return None+ self.count += 1+ self.total_bytes += len(data)+ return EmbeddedImage(+ name=f"image-{self.count:02d}{ext}",+ mime_type=_MIME_BY_EXT.get(ext, "application/octet-stream"),+ data=data,+ )+++@dataclass(frozen=True, slots=True)+class ImageCollection:+ """Images from one document plus how many were left behind."""++ images: tuple[EmbeddedImage, ...] = ()+ skipped_vector: int = 0+ skipped_other: int = 0+ skipped_budget: int = 0++ def summary_note(self) -> str:+ """One-line note for the extracted text describing what was dropped."""+ parts: list[str] = []+ if self.skipped_vector:+ parts.append(f"{self.skipped_vector} 张矢量图(EMF/WMF)未提取")+ if self.skipped_other:+ parts.append(f"{self.skipped_other} 张不支持的图片格式未提取")+ if self.skipped_budget:+ parts.append(f"{self.skipped_budget} 张图片超出数量/大小上限未提取")+ if not parts:+ return ""+ return "[" + ",".join(parts) + "]"+++@dataclass(frozen=True, slots=True)+class DocxRich:+ """Marker-annotated body paragraphs plus the images they reference."""++ paragraphs: tuple[str, ...] = ()+ collection: ImageCollection = field(default_factory=ImageCollection)+++@dataclass(frozen=True, slots=True)+class PptxRich:+ """Per-slide text with image markers, plus the slide images."""++ slides: tuple[str, ...] = ()+ collection: ImageCollection = field(default_factory=ImageCollection)+++@dataclass(frozen=True, slots=True)+class PdfImages:+ """PDF page images with the page each first appeared on."""++ collection: ImageCollection = field(default_factory=ImageCollection)+ page_map: tuple[tuple[int, tuple[int, ...]], ...] = () # (page, image indices)+++def image_index_from_name(name: str) -> int:+ """``image-03.png`` → 3. Marker text and numbering stay in lockstep."""+ stem = posixpath.basename(name).rsplit(".", 1)[0]+ tail = stem.rsplit("-", 1)[-1]+ try:+ return int(tail)+ except ValueError:+ return 0+++def build_marker(image: EmbeddedImage) -> str:+ """The canonical in-text marker for one image."""+ return f"[图片 {image_index_from_name(image.name)}: {image.name}]"++_MARKER_PATTERN = re.compile(r"\[图片 (\d+): ([^\]\s]+)\]")+++def find_markers(text: str) -> list[tuple[int, str]]:+ """All ``(image_index, image_name)`` markers in *text*, in order."""+ return [(int(m.group(1)), m.group(2)) for m in _MARKER_PATTERN.finditer(text)]+++def _local_name(tag: Any) -> str:+ if isinstance(tag, str) and "}" in tag:+ return tag.rsplit("}", 1)[-1]+ return tag if isinstance(tag, str) else ""+++def _parse_xml(raw: bytes) -> Any:+ return DefusedElementTree.fromstring(raw)+++def _normalise_ext(ext: str) -> str:+ ext = (ext or "").lower()+ if ext == ".jpeg":+ return ".jpg"+ return ext+++# ---------------------------------------------------------------------------+# DOCX+# ---------------------------------------------------------------------------+++def extract_docx_rich(data: bytes) -> DocxRich:+ """Walk ``word/document.xml`` once, collecting ordered paragraphs and images.++ Only the main body is mined (header/footer images are decoration). A+ relationship target referenced by several paragraphs is extracted once but+ marked at every position, so repeated/floating figures stay anchored to+ the text around them.+ """+ budget = ImageBudget()+ images: list[EmbeddedImage] = []+ by_target: dict[str, EmbeddedImage] = {}+ attempted: set[str] = set()++ with zipfile.ZipFile(io.BytesIO(data)) as zf:+ names = set(zf.namelist())+ rel_targets = _office_rels(zf, "word/_rels/document.xml.rels")+ root = _parse_xml(zf.read("word/document.xml"))++ paragraphs: list[str] = []+ for node in root.iter():+ if _local_name(node.tag) != "p":+ continue+ text_parts: list[str] = []+ markers: list[str] = []+ seen_rids: set[str] = set()+ for child in node.iter():+ name = _local_name(child.tag)+ if name == "t" and child.text:+ text_parts.append(child.text)+ elif name == "tab":+ text_parts.append("\t")+ elif name in {"br", "cr"}:+ text_parts.append("\n")+ elif name == "blip":+ rid = _blip_embed_rid(child)+ if not rid or rid in seen_rids:+ continue+ seen_rids.add(rid)+ target = rel_targets.get(rid, "")+ image = by_target.get(target)+ if image is None and target not in attempted:+ attempted.add(target)+ image = _load_office_image(zf, names, target, budget, images)+ if image is not None:+ by_target[target] = image+ if image is not None:+ markers.append(build_marker(image))+ paragraph = "".join(text_parts).strip()+ if markers:+ paragraph = (paragraph + "\n" if paragraph else "") + "\n".join(markers)+ if paragraph:+ paragraphs.append(paragraph)++ return DocxRich(+ paragraphs=tuple(paragraphs),+ collection=_collection_from(budget, images),+ )+++def _blip_embed_rid(blip: Any) -> str:+ """The ``r:embed`` relationship id of one ``a:blip`` (external links out)."""+ for key, value in blip.attrib.items():+ if value and _local_name(key) == "embed":+ return str(value)+ return ""+++def _office_rels(zf: zipfile.ZipFile, rels_member: str) -> dict[str, str]:+ """rId → normalised archive path for internal media targets."""+ try:+ raw = zf.read(rels_member)+ except KeyError:+ return {}+ try:+ root = _parse_xml(raw)+ except Exception:+ return {}+ base = posixpath.dirname(posixpath.dirname(rels_member)) # …/word/_rels → …/word+ targets: dict[str, str] = {}+ for node in root.iter():+ if _local_name(node.tag) != "Relationship":+ continue+ if (node.get("TargetMode") or "").lower() == "external":+ continue+ rid = node.get("Id") or ""+ target = node.get("Target") or ""+ if rid and target:+ targets[rid] = posixpath.normpath(posixpath.join(base, target))+ return targets+++def _load_office_image(+ zf: zipfile.ZipFile,+ names: set[str],+ target: str,+ budget: ImageBudget,+ images: list[EmbeddedImage],+) -> EmbeddedImage | None:+ if not target or target not in names:+ return None+ ext = _normalise_ext(posixpath.splitext(target)[1])+ if ext in {".emf", ".wmf"}:+ budget.register_vector_skip()+ return None+ if ext not in SUPPORTED_IMAGE_EXTENSIONS:+ budget.register_other_skip()+ return None+ try:+ data = zf.read(target)+ except (KeyError, zipfile.BadZipFile):+ return None+ image = budget.try_admit(ext, data)+ if image is not None:+ images.append(image)+ return image+++def _collection_from(budget: ImageBudget, images: list[EmbeddedImage]) -> ImageCollection:+ return ImageCollection(+ images=tuple(images),+ skipped_vector=budget.skipped_vector,+ skipped_other=budget.skipped_other,+ skipped_budget=budget.skipped_budget,+ )+++# ---------------------------------------------------------------------------+# PPTX+# ---------------------------------------------------------------------------+++def extract_pptx_rich(data: bytes) -> PptxRich:+ """Slide texts with markers plus pictures, via python-pptx when available.++ python-pptx resolves picture placeholders and grouped shapes cleanly and+ only reports images actually placed on a slide (layout/master decoration+ stays out). The raw-OOXML fallback additionally catches background fills+ when python-pptx is missing or fails.+ """+ try:+ from pptx import Presentation+ except ImportError:+ return _extract_pptx_rich_ooxml(data)++ try:+ prs = Presentation(io.BytesIO(data))+ except Exception:+ return _extract_pptx_rich_ooxml(data)++ budget = ImageBudget()+ images: list[EmbeddedImage] = []+ slides: list[str] = []+ for slide in prs.slides:+ lines: list[str] = []+ _collect_shape_rich(slide.shapes, lines, budget, images)+ slides.append("\n".join(line for line in lines if line))++ return PptxRich(slides=tuple(slides), collection=_collection_from(budget, images))+++def _collect_shape_rich(+ shapes: Any,+ lines: list[str],+ budget: ImageBudget,+ images: list[EmbeddedImage],+) -> None:+ for shape in shapes:+ sub_shapes = getattr(shape, "shapes", None)+ if sub_shapes is not None:+ _collect_shape_rich(sub_shapes, lines, budget, images)+ continue++ try:+ image = shape.image # Picture only; other shapes raise or lack it+ blob = image.blob+ ext = _normalise_ext("." + (image.ext or ""))+ except Exception:+ blob, ext = b"", ""+ if blob:+ if ext in {".emf", ".wmf"}:+ budget.register_vector_skip()+ elif ext in SUPPORTED_IMAGE_EXTENSIONS:+ admitted = budget.try_admit(ext, blob)+ if admitted is not None:+ images.append(admitted)+ lines.append(build_marker(admitted))+ else:+ budget.register_other_skip()++ if getattr(shape, "has_table", False):+ for row in shape.table.rows:+ cells = [cell.text.strip() for cell in row.cells]+ line = "\t".join(cell for cell in cells if cell)+ if line:+ lines.append(line)+ continue+ text = getattr(shape, "text", "")+ if text and text.strip():+ lines.append(text.strip())+++def _extract_pptx_rich_ooxml(data: bytes) -> PptxRich:+ """Raw fallback: per-slide paragraph text + blip markers from slide rels."""+ budget = ImageBudget()+ images: list[EmbeddedImage] = []+ slides: list[str] = []+ with zipfile.ZipFile(io.BytesIO(data)) as zf:+ names = set(zf.namelist())+ slide_members = sorted(+ (name for name in names if _SLIDE_MEMBER_PATTERN.fullmatch(name)),+ key=_natural_slide_key,+ )+ for member in slide_members:+ rel_targets = _office_rels(zf, _rels_for(member))+ lines: list[str] = []+ try:+ root = _parse_xml(zf.read(member))+ except Exception:+ slides.append("")+ continue+ for node in root.iter():+ if _local_name(node.tag) != "p":+ continue+ text_parts: list[str] = []+ markers: list[str] = []+ seen_rids: set[str] = set()+ for child in node.iter():+ name = _local_name(child.tag)+ if name == "t" and child.text:+ text_parts.append(child.text)+ elif name == "tab":+ text_parts.append("\t")+ elif name in {"br", "cr"}:+ text_parts.append("\n")+ elif name == "blip":+ rid = _blip_embed_rid(child)+ if not rid or rid in seen_rids:+ continue+ seen_rids.add(rid)+ image = _load_office_image(+ zf, names, rel_targets.get(rid, ""), budget, images+ )+ if image is not None:+ markers.append(build_marker(image))+ paragraph = "".join(text_parts).strip()+ if markers:+ paragraph = (paragraph + "\n" if paragraph else "") + "\n".join(markers)+ if paragraph:+ lines.append(paragraph)+ slides.append("\n".join(lines))++ return PptxRich(slides=tuple(slides), collection=_collection_from(budget, images))+++_SLIDE_MEMBER_PATTERN = re.compile(r"ppt/slides/slide\d+\.xml")+++def _natural_slide_key(name: str) -> list[int]:+ digits = re.findall(r"\d+", posixpath.basename(name))+ return [int(digits[0])] if digits else [0]+++def _rels_for(member: str) -> str:+ directory, filename = posixpath.split(member)+ return posixpath.join(directory, "_rels", filename + ".rels")+++# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+++def extract_pdf_images(data: bytes) -> 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.+ """+ try:+ import pymupdf+ except ImportError:+ return PdfImages()++ budget = ImageBudget()+ images: list[EmbeddedImage] = []+ page_map: list[tuple[int, tuple[int, ...]]] = []+ seen_xrefs: set[int] = set()++ try:+ with pymupdf.open(stream=data, filetype="pdf") as doc:+ for page_number, page in enumerate(doc, 1):+ indices: list[int] = []+ for info in page.get_images(full=True):+ xref = info[0]+ if xref in seen_xrefs:+ continue+ seen_xrefs.add(xref)+ try:+ extracted = doc.extract_image(xref)+ except Exception:+ continue+ raw = extracted.get("image") or b""+ if int(extracted.get("width") or 0) < 64 or int(+ extracted.get("height") or 0+ ) < 64:+ continue+ ext = _normalise_ext("." + (extracted.get("ext") or ""))+ if ext in {".emf", ".wmf"}:+ budget.register_vector_skip()+ continue+ if ext not in SUPPORTED_IMAGE_EXTENSIONS:+ budget.register_other_skip()+ continue+ admitted = budget.try_admit(ext, raw)+ if admitted is not None:+ images.append(admitted)+ indices.append(len(images) - 1)+ if indices:+ page_map.append((page_number, tuple(indices)))+ except Exception:+ logger.warning("pdf image extraction failed", exc_info=True)+ return PdfImages()++ return PdfImages(collection=_collection_from(budget, images), page_map=tuple(page_map))+++__all__ = [+ "EmbeddedImage",+ "ImageBudget",+ "ImageCollection",+ "DocxRich",+ "PptxRich",+ "PdfImages",+ "MAX_IMAGES_PER_DOC",+ "SUPPORTED_IMAGE_EXTENSIONS",+ "build_marker",+ "find_markers",+ "image_index_from_name",+ "extract_docx_rich",+ "extract_pptx_rich",+ "extract_pdf_images",+]diff --git a/tests/utils/test_document_images.py b/tests/utils/test_document_images.pynew file mode 100644index 000000000..849c29bb7--- /dev/null+++ b/tests/utils/test_document_images.py@@ -0,0 +1,187 @@+"""Tests for deeptutor.utils.document_images — embedded-image extraction.++Fixtures generate real DOCX/PPTX archives on the fly (same pattern as+``test_document_extractor``) with a synthetic PNG large enough to clear the+minimum-size budget.+"""++from __future__ import annotations++import io+import random++from docx import Document as DocxDocument+from docx.shared import Inches+from pptx import Presentation+from pptx.util import Inches as PptxInches+import pytest++from deeptutor.utils.document_images import (+ build_marker,+ extract_docx_rich,+ extract_pdf_images,+ extract_pptx_rich,+ find_markers,+ image_index_from_name,+)+++def _png_bytes(size: tuple[int, int] = (400, 300)) -> bytes:+ """A noisy PNG comfortably above the minimum-bytes budget."""+ rng = random.Random(11)+ image_bytes = bytes(rng.randrange(256) for _ in range(size[0] * size[1] * 3))+ from PIL import Image as PILImage++ image = PILImage.frombytes("RGB", size, image_bytes)+ buf = io.BytesIO()+ image.save(buf, format="PNG")+ return buf.getvalue()++[email protected](scope="module")+def png() -> bytes:+ return _png_bytes()+++def _docx_with_image(paragraphs: list[str], png_data: bytes, *, table: bool = False) -> bytes:+ doc = DocxDocument()+ doc.add_paragraph(paragraphs[0])+ doc.add_picture(io.BytesIO(png_data), width=Inches(2))+ for paragraph in paragraphs[1:]:+ doc.add_paragraph(paragraph)+ if table:+ table_rows = doc.add_table(rows=1, cols=2)+ table_rows.cell(0, 0).text = "cell-a"+ table_rows.cell(0, 1).text = "cell-b"+ buf = io.BytesIO()+ doc.save(buf)+ return buf.getvalue()+++def _pptx_with_image(png_data: bytes) -> bytes:+ prs = Presentation()+ slide = prs.slides.add_slide(prs.slide_layouts[6])+ box = slide.shapes.add_textbox(PptxInches(1), PptxInches(1), PptxInches(4), PptxInches(1))+ box.text_frame.text = "标题文本"+ slide.shapes.add_picture(io.BytesIO(png_data), PptxInches(1), PptxInches(2), PptxInches(3))+ buf = io.BytesIO()+ prs.save(buf)+ return buf.getvalue()+++# ---------------------------------------------------------------------------+# Markers+# ---------------------------------------------------------------------------+++def test_marker_roundtrip() -> None:+ from deeptutor.utils.document_images import EmbeddedImage++ image = EmbeddedImage(name="image-03.png", mime_type="image/png", data=b"x")+ marker = build_marker(image)+ assert find_markers(f"前文\n{marker}\n后文") == [(3, "image-03.png")]+++def test_image_index_from_name() -> None:+ assert image_index_from_name("image-01.png") == 1+ assert image_index_from_name("media/image-12.jpg") == 12+ assert image_index_from_name("nope.png") == 0+++# ---------------------------------------------------------------------------+# DOCX+# ---------------------------------------------------------------------------+++def test_docx_rich_extracts_image_and_marker(png: bytes) -> None:+ data = _docx_with_image(["第一段", "第二段"], png)+ rich = extract_docx_rich(data)++ assert len(rich.collection.images) == 1+ image = rich.collection.images[0]+ assert image.mime_type == "image/png"+ assert image.data == png++ marker = build_marker(image)+ assert any(marker in paragraph for paragraph in rich.paragraphs)+ # Text order preserved: intro before the marker, outro after it.+ text = "\n".join(rich.paragraphs)+ assert text.index("第一段") < text.index(marker) < text.index("第二段")+++def test_docx_rich_keeps_table_text(png: bytes) -> None:+ data = _docx_with_image(["开头"], png, table=True)+ rich = extract_docx_rich(data)+ joined = "\n".join(rich.paragraphs)+ assert "cell-a" in joined and "cell-b" in joined+++def test_docx_rich_repeats_marker_for_reused_target(png: bytes) -> None:+ """The same image embedded twice is stored once but marked twice."""+ doc = DocxDocument()+ doc.add_picture(io.BytesIO(png), width=Inches(2))+ doc.add_paragraph("中间")+ doc.add_picture(io.BytesIO(png), width=Inches(2))+ buf = io.BytesIO()+ doc.save(buf)++ rich = extract_docx_rich(buf.getvalue())+ assert len(rich.collection.images) == 1+ markers = find_markers("\n".join(rich.paragraphs))+ assert len(markers) == 2+++# ---------------------------------------------------------------------------+# PPTX+# ---------------------------------------------------------------------------+++def test_pptx_rich_extracts_image_and_slide_text(png: bytes) -> None:+ rich = extract_pptx_rich(_pptx_with_image(png))++ assert len(rich.slides) == 1+ assert "标题文本" in rich.slides[0]+ assert len(rich.collection.images) == 1+ assert build_marker(rich.collection.images[0]) in rich.slides[0]+++# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+++def test_pdf_images_extracts_and_maps_pages(tmp_path) -> None:+ pymupdf = pytest.importorskip("pymupdf")+ from PIL import Image as PILImage++ png_data = _png_bytes((300, 200))+ pdf_path = tmp_path / "figures.pdf"+ doc = pymupdf.open()+ page = doc.new_page(width=612, height=792)+ page.insert_image(pymupdf.Rect(72, 72, 300, 220), stream=png_data)+ doc.save(str(pdf_path))+ doc.close()+ del PILImage++ result = extract_pdf_images(pdf_path.read_bytes())+ assert result.collection.images, "the inserted figure should be extracted"+ assert result.page_map+ page_number, indices = result.page_map[0]+ assert page_number == 1+ assert result.collection.images[indices[0]].data+++def test_pdf_images_deduplicates_repeated_xref(tmp_path) -> None:+ pytest.importorskip("pymupdf")+ png_data = _png_bytes((300, 200))+ pdf_path = tmp_path / "banner.pdf"+ doc = __import__("pymupdf").open()+ for _ in range(3):+ page = doc.new_page(width=612, height=792)+ page.insert_image(__import__("pymupdf").Rect(72, 72, 300, 160), stream=png_data)+ doc.save(str(pdf_path))+ doc.close()++ result = extract_pdf_images(pdf_path.read_bytes())+ assert len(result.collection.images) == 1+ assert [page for page, _ in result.page_map] == [1]diff --git a/web/components/reading/TextUnitView.tsx b/web/components/reading/TextUnitView.tsxindex dfb8c1c10..36693fd7e 100644--- a/web/components/reading/TextUnitView.tsx+++ b/web/components/reading/TextUnitView.tsx@@ -24,7 +24,12 @@ import {import { useTranslation } from "react-i18next";import RichMarkdownRenderer from "@/components/common/RichMarkdownRenderer";import type { AnnotationItem, UnitKind } from "@/lib/reading-api";-import { getUnitText } from "@/lib/reading-api";+import {+ getMaterialMedia,+ getUnitText,+ materialMediaUrl,+ type MaterialMediaItem,+} from "@/lib/reading-api";import {DEFAULT_FONT_SIZE,DEFAULT_LINE_WIDTH,@@ -44,7 +49,10 @@ import {type ReaderHeading,} from "@/lib/reading-outline";import { cleanQuote } from "@/lib/reading-selection";-import { MarkdownLine } from "@/lib/reading-inline-markdown";+import {+ imageMarkerNames,+ MarkdownLine,+} from "@/lib/reading-inline-markdown";import { toRecogitoTextAnnotation } from "@/lib/reading-w3c-annotations";import type { JumpRequest, SelectionPayload } from "./PdfDocumentView";@@ -115,6 +123,7 @@ export function TextUnitView({} | null>(null);const [locator, setLocator] = useState(1);const [text, setText] = useState("");+ const [media, setMedia] = useState<MaterialMediaItem[]>([]);const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);const [fontSize, setFontSize] = useState(DEFAULT_FONT_SIZE);@@ -216,6 +225,36 @@ export function TextUnitView({setLocator(1);}, [materialId]);+ // Embedded pictures (DOCX/PPTX ingest), keyed to locators. Materials+ // without images simply return an empty index; failure keeps the text+ // readable without the strip.+ useEffect(() => {+ let cancelled = false;+ setMedia([]);+ getMaterialMedia(materialId)+ .then((items) => {+ if (!cancelled) setMedia(items);+ })+ .catch(() => {+ if (!cancelled) setMedia([]);+ });+ return () => {+ cancelled = true;+ };+ }, [materialId]);++ // Pictures whose marker lines the inline renderer does not claim (a marker+ // embedded mid-paragraph, say) still need the fallback strip below the+ // article; everything else renders at its original position in the body.+ // Only this unit's pictures belong here — a picture whose marker lives in+ // another unit renders inline there.+ const fallbackMedia = useMemo(() => {+ const claimed = imageMarkerNames(text);+ return media.filter(+ (item) => item.locator === locator && !claimed.has(item.name),+ );+ }, [locator, media, text]);+useEffect(() => {let cancelled = false;setLoading(true);@@ -569,6 +608,7 @@ export function TextUnitView({) : error ? (<p className="text-[12px] text-[var(--muted-foreground)]">{error}</p>) : (+ <><articleref={articleRef}// The sheet. Text used to run edge to edge on the same white as@@ -615,9 +655,39 @@ export function TextUnitView({variant="prose"/>) : (- <TextWithHeadings text={text} headings={pageHeadings} />+ <TextWithHeadings+ text={text}+ headings={pageHeadings}+ media={media}+ materialId={materialId}+ />+ )}+ </article>+ {fallbackMedia.length > 0 && (+ <div+ className="mx-auto mt-6 flex flex-col gap-5 pb-4"+ style={{ maxWidth: `${lineWidth}ch` }}+ >+ {fallbackMedia.map((item) => (+ <figure+ key={item.name}+ className="flex flex-col items-center"+ >+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={materialMediaUrl(materialId, item.name)}+ alt={item.name}+ loading="lazy"+ className="max-h-[70vh] w-auto max-w-full rounded-lg border border-[var(--border)]"+ />+ <figcaption className="mt-1.5 text-center font-mono text-[10.5px] text-[var(--muted-foreground)]">+ {item.name}+ </figcaption>+ </figure>+ ))}+ </div>)}- </article>+ </>)}</div></div>@@ -659,15 +729,50 @@ function PreferenceButton({function TextWithHeadings({text,headings,+ media,+ materialId,}: {text: string;headings: ReaderHeading[];+ media: MaterialMediaItem[];+ materialId: string;}) {const lines = useMemo(() => readerLinesWithHeadings(text, headings),[headings, text],);+ // An embedded-picture marker line renders as the picture itself, at the+ // picture's original position between paragraphs. The marker text stays in+ // the DOM (HiddenMark pattern, same as every other collapsed marker) so+ // Recogito's char-level selectors keep resolving against the exact text an+ // annotation was saved against. A picture whose media row is missing keeps+ // its literal marker rather than silently vanishing.+ const renderImage = useCallback(+ (name: string, markerText: string) => {+ const item = media.find((row) => row.name === name);+ if (!item) return null;+ return (+ <figure className="my-6 flex flex-col items-center">+ <span+ aria-hidden="true"+ className="inline-block size-0 overflow-hidden align-top text-[0px]"+ >+ {markerText}+ </span>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={materialMediaUrl(materialId, item.name)}+ alt={item.name}+ loading="lazy"+ className="max-h-[70vh] w-auto max-w-full rounded-lg border border-[var(--border)]"+ />+ </figure>+ );+ },+ [materialId, media],+ );+return (<>{lines.map((line, lineIndex) => {@@ -721,7 +826,9 @@ function TextWithHeadings({{lineIndex > 0 && "\n"}{/* Fenced code stays completely literal — Markdown syntaxinside a code block is content, not formatting. */}- {line.fence ? line.text : <MarkdownLine text={line.text} />}+ {line.fence ? line.text : (+ <MarkdownLine text={line.text} renderImage={renderImage} />+ )}</Fragment>);})}diff --git a/web/lib/reading-api.ts b/web/lib/reading-api.tsindex 84b0d8a4f..f007de063 100644--- a/web/lib/reading-api.ts+++ b/web/lib/reading-api.ts@@ -277,6 +277,39 @@ export async function getUnitText();}+export interface MaterialMediaItem {+ name: string;+ locator: number;+ mime: string;+ bytes: number;+}++/** Embedded images (DOCX/PPTX) with the locator each belongs to. */+export async function getMaterialMedia(+ materialId: string,+): Promise<MaterialMediaItem[]> {+ const payload: unknown = await unwrap(+ await apiFetch(apiUrl(`${BASE}/materials/${materialId}/media`), {+ cache: "no-store",+ }),+ );+ if (!Array.isArray(payload)) return [];+ return payload.filter(+ (row): row is MaterialMediaItem =>+ Boolean(row) &&+ typeof row === "object" &&+ typeof (row as MaterialMediaItem).name === "string" &&+ Number.isFinite((row as MaterialMediaItem).locator),+ );+}++/** Public URL for one stored embedded image. */+export function materialMediaUrl(materialId: string, name: string): string {+ return apiUrl(+ `${BASE}/materials/${encodeURIComponent(materialId)}/media/${encodeURIComponent(name)}`,+ );+}+export interface ReadingTranscript {material_id: string;revision: number;