DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): route PDF attachments through configured parser
Bingxi Zhao (Frank)04a20ce2e389
diff --git a/deeptutor/core/turn_request.py b/deeptutor/core/turn_request.pyindex 97a54733f..a9a43680a 100644--- a/deeptutor/core/turn_request.py+++ b/deeptutor/core/turn_request.py@@ -37,6 +37,7 @@ class OutgoingAttachment(BaseModel):base64: str | None = Nonefilename: str | None = Nonemime_type: str | None = None+ id: str | None = Noneclass NotebookReference(BaseModel):diff --git a/deeptutor/services/session/attachment_parsing.py b/deeptutor/services/session/attachment_parsing.pynew file mode 100644index 000000000..911ef3463--- /dev/null+++ b/deeptutor/services/session/attachment_parsing.py@@ -0,0 +1,102 @@+"""Configured parser integration for chat PDF attachments."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Callable, Iterable+from typing import Any++from deeptutor.services.config.runtime_settings import get_chat_attachment_limits+from deeptutor.services.parsing import get_parse_service+from deeptutor.services.storage import AttachmentStore++logger = logging.getLogger(__name__)+++async def parse_chat_pdf_attachments(+ records: Iterable[dict[str, Any]],+ *,+ attachment_store: AttachmentStore,+ session_id: str,+ document_texts: Iterable[str],+ on_progress: Callable[[str, str, str], None] | None = None,+) -> tuple[list[dict[str, Any]], list[str]]:+ """Parse every chat PDF with the active engine and update model context."""+ updated = [dict(record) for record in records]+ contexts = list(document_texts)+ limits = get_chat_attachment_limits()+ total_chars = sum(+ int(record.get("extracted_chars") or 0)+ for record in updated+ if not str(record.get("filename") or "").lower().endswith(".pdf")+ )++ for record in updated:+ filename = str(record.get("filename") or "")+ if not filename.lower().endswith(".pdf"):+ continue+ attachment_id = str(record.get("id") or "")+ if on_progress:+ on_progress(attachment_id, "submitting", "Submitting to the configured document parser")+ path = attachment_store.resolve_path(+ session_id=session_id,+ attachment_id=str(record.get("id") or ""),+ filename=filename,+ )+ error = ""+ text = ""+ if path is None:+ error = "stored attachment could not be found for configured parsing"+ elif limits.max_chars_total - total_chars <= 0:+ error = "total extracted-text quota exceeded"+ else:+ try:+ parsed = await asyncio.to_thread(+ get_parse_service().parse,+ path,+ on_output=lambda message: on_progress(attachment_id, "parsing", message)+ if on_progress+ else None,+ )+ text = str(parsed.markdown or "").strip()+ if not text:+ error = "configured parser produced no content"+ except Exception as exc:+ logger.info("Configured parser failed for chat PDF %s: %s", filename, exc)+ error = str(exc)+ if text:+ cap = min(limits.max_chars_per_doc, limits.max_chars_total - total_chars)+ if len(text) > cap:+ text = text[:cap] + f"... (truncated, {len(text)} chars total; chat quota hit)"+ record["extracted_text"] = text+ record["extracted_chars"] = len(text)+ record.pop("extraction_error", None)+ total_chars += len(text)+ else:+ record["extracted_text"] = ""+ record["extracted_chars"] = 0+ record["extraction_error"] = error+ _replace_context(contexts, filename, text, error)+ if on_progress:+ on_progress(+ attachment_id,+ "completed" if text else "failed",+ "Document parsing completed" if text else f"Document parsing failed: {error}",+ )+ return updated, contexts+++def _replace_context(+ contexts: list[str], filename: str, text: str, error: str+) -> None:+ replacement = (+ f"[File: {filename}]\n{text}"+ if not error+ else f"[File: {filename} - could not be read: {error}]"+ )+ for index, context in enumerate(contexts):+ if context.startswith(f"[File: {filename}]"):+ contexts[index] = replacement+ return+ contexts.append(replacement)diff --git a/deeptutor/services/session/turns/executor.py b/deeptutor/services/session/turns/executor.pyindex dff2f51bb..6f9e1ea61 100644--- a/deeptutor/services/session/turns/executor.py+++ b/deeptutor/services/session/turns/executor.py@@ -345,7 +345,57 @@ class TurnExecutor:from deeptutor.utils.document_extractor import extract_documents_from_records- document_texts, attachment_records = extract_documents_from_records(attachment_records)+ # PDFs are parsed exclusively by the configured Document Parsing+ # engine. Keep them out of the legacy local extractor so a native+ # text layer can never mask missing images or scanned pages.+ pdf_records = [+ record for record in attachment_records+ if str(record.get("filename") or "").lower().endswith(".pdf")+ ]+ non_pdf_records = [+ record for record in attachment_records+ if not str(record.get("filename") or "").lower().endswith(".pdf")+ ]+ document_texts, extracted_non_pdf = extract_documents_from_records(non_pdf_records)+ extracted_by_id = {str(record.get("id")): record for record in extracted_non_pdf}+ attachment_records = [+ extracted_by_id.get(str(record.get("id")), record)+ for record in attachment_records+ ]+ from deeptutor.services.session.attachment_parsing import parse_chat_pdf_attachments++ loop = asyncio.get_running_loop()++ def _attachment_progress(attachment_id: str, phase: str, message: str) -> None:+ loop.call_soon_threadsafe(+ lambda: asyncio.create_task(+ self._publish_live_event(+ execution,+ StreamEvent(+ type=StreamEventType.PROGRESS,+ source="attachment_parsing",+ stage=phase,+ content=message,+ metadata={"attachment_id": attachment_id, "phase": phase},+ ),+ )+ )+ )++ for record in pdf_records:+ _attachment_progress(+ str(record.get("id") or ""),+ "received",+ "Received and stored on Raspberry Pi",+ )++ attachment_records, document_texts = await parse_chat_pdf_attachments(+ attachment_records,+ attachment_store=attachment_store,+ session_id=session_id,+ document_texts=document_texts,+ on_progress=_attachment_progress,+ )attachments = [Attachment(type=r.get("type", "file"),diff --git a/tests/services/session/test_attachment_parsing.py b/tests/services/session/test_attachment_parsing.pynew file mode 100644index 000000000..60eb66746--- /dev/null+++ b/tests/services/session/test_attachment_parsing.py@@ -0,0 +1,90 @@+from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.services.parsing.types import ParsedDocument+from deeptutor.services.session.attachment_parsing import parse_chat_pdf_attachments+from deeptutor.services.storage.attachment_store import LocalDiskAttachmentStore+++async def test_chat_pdf_always_uses_configured_parser(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ store = LocalDiskAttachmentStore(root=tmp_path / "attachments")+ await store.put(session_id="session", attachment_id="pdf", filename="notes.pdf", data=b"pdf")++ class Parser:+ def parse(self, path: Path, **_: object) -> ParsedDocument:+ assert path.name == "pdf_notes.pdf"+ return ParsedDocument(markdown="# Parsed layout\n\n")++ monkeypatch.setattr(+ "deeptutor.services.session.attachment_parsing.get_parse_service", lambda: Parser()+ )+ records, contexts = await parse_chat_pdf_attachments(+ [{"id": "pdf", "filename": "notes.pdf", "extracted_text": "native text", "extracted_chars": 11}],+ attachment_store=store,+ session_id="session",+ document_texts=["[File: notes.pdf]\nnative text"],+ )++ assert records[0]["extracted_text"] == "# Parsed layout\n\n"+ assert contexts == ["[File: notes.pdf]\n# Parsed layout\n\n"]+++async def test_scan_pdf_uses_parser_and_reports_structured_progress(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ store = LocalDiskAttachmentStore(root=tmp_path / "attachments")+ await store.put(session_id="session", attachment_id="scan", filename="scan.pdf", data=b"image")+ progress: list[tuple[str, str, str]] = []++ class Parser:+ def parse(self, path: Path, *, on_output=None) -> ParsedDocument:+ assert path.name == "scan_scan.pdf"+ if on_output:+ on_output("MinerU page 1/1")+ return ParsedDocument(markdown="")++ monkeypatch.setattr(+ "deeptutor.services.session.attachment_parsing.get_parse_service", lambda: Parser()+ )+ records, contexts = await parse_chat_pdf_attachments(+ [{"id": "scan", "filename": "scan.pdf", "extracted_text": "", "extracted_chars": 0}],+ attachment_store=store,+ session_id="session",+ document_texts=[],+ on_progress=lambda aid, phase, detail: progress.append((aid, phase, detail)),+ )++ assert records[0]["extracted_text"] == ""+ assert contexts == ["[File: scan.pdf]\n"]+ assert [phase for _, phase, _ in progress] == ["submitting", "parsing", "completed"]+++async def test_parser_failure_is_not_reported_as_empty_success(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ store = LocalDiskAttachmentStore(root=tmp_path / "attachments")+ await store.put(session_id="session", attachment_id="bad", filename="bad.pdf", data=b"pdf")++ class Parser:+ def parse(self, path: Path, **_: object) -> ParsedDocument:+ raise RuntimeError("parser unavailable")++ monkeypatch.setattr(+ "deeptutor.services.session.attachment_parsing.get_parse_service", lambda: Parser()+ )+ records, contexts = await parse_chat_pdf_attachments(+ [{"id": "bad", "filename": "bad.pdf"}],+ attachment_store=store,+ session_id="session",+ document_texts=[],+ )++ assert records[0]["extracted_text"] == ""+ assert "parser unavailable" in records[0]["extraction_error"]+ assert "could not be read" in contexts[0]