mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 18:20:33 +08:00
fix(chat): isolate PDF attachment extraction (#3026)
* fix(chat): isolate PDF attachment extraction Run PDF-bearing chat attachment extraction outside the API process and reuse the single PDF image pass for both page markers and embedded attachments. Addresses the chat attachment reproduction in #2865. * perf(pdf): skip decoding images after the count cap Keep lookups for previously accepted image references ahead of the quota check so repeated pictures are still mapped to each page. * perf(chat): reuse native PDF markdown for text-only parsing Match the stored attachment bytes and preserve the configured parser path for other engines and incomplete native results.
This commit is contained in:
@@ -4,7 +4,10 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable, Iterable
|
||||
from hashlib import file_digest
|
||||
import logging
|
||||
from os import linesep
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
@@ -16,6 +19,18 @@ logger = logging.getLogger(__name__)
|
||||
_PDF_PAGE_HEADER = re.compile(r"--- Page (\d+) ---")
|
||||
|
||||
|
||||
def _stored_pdf_digest(path: Path) -> str | None:
|
||||
from deeptutor.utils.document_validator import DocumentValidator
|
||||
|
||||
try:
|
||||
if path.stat().st_size <= DocumentValidator.MAX_FILE_SIZE:
|
||||
with path.open("rb") as source:
|
||||
return file_digest(source, "sha256").hexdigest()
|
||||
except OSError:
|
||||
pass # Let the configured parser handle unreadable or missing files.
|
||||
return None
|
||||
|
||||
|
||||
async def parse_chat_pdf_attachments(
|
||||
records: Iterable[dict[str, Any]],
|
||||
*,
|
||||
@@ -24,7 +39,7 @@ async def parse_chat_pdf_attachments(
|
||||
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."""
|
||||
"""Resolve active-engine Markdown for each chat PDF and update model context."""
|
||||
updated = [dict(record) for record in records]
|
||||
contexts = list(document_texts)
|
||||
if not any(str(record.get("filename") or "").lower().endswith(".pdf") for record in updated):
|
||||
@@ -42,6 +57,7 @@ async def parse_chat_pdf_attachments(
|
||||
)
|
||||
|
||||
for record in updated:
|
||||
native_markdown = record.pop("_native_pdf_markdown", None)
|
||||
filename = str(record.get("filename") or "")
|
||||
if not filename.lower().endswith(".pdf"):
|
||||
continue
|
||||
@@ -62,16 +78,33 @@ async def parse_chat_pdf_attachments(
|
||||
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
|
||||
),
|
||||
)
|
||||
parser = get_parse_service()
|
||||
if (
|
||||
native_markdown
|
||||
and parser.active_engine().strip().lower() == "text_only"
|
||||
and await asyncio.to_thread(_stored_pdf_digest, path) == native_markdown[0]
|
||||
):
|
||||
if on_progress:
|
||||
on_progress(attachment_id, "parsing", "Reusing extracted PDF text")
|
||||
# Match the configured parser's text-mode write and read.
|
||||
text = (
|
||||
native_markdown[1]
|
||||
.replace("\n", linesep)
|
||||
.replace("\r\n", "\n")
|
||||
.replace("\r", "\n")
|
||||
.strip()
|
||||
)
|
||||
else:
|
||||
parsed = await asyncio.to_thread(
|
||||
parser.parse,
|
||||
path,
|
||||
on_output=lambda message: (
|
||||
on_progress(attachment_id, "parsing", message) if on_progress else None
|
||||
),
|
||||
)
|
||||
text = str(parsed.markdown or "").strip()
|
||||
if on_progress:
|
||||
on_progress(attachment_id, "retrieving", "Retrieving parsed document result")
|
||||
text = str(parsed.markdown or "").strip()
|
||||
if not text:
|
||||
error = "configured parser produced no content"
|
||||
except Exception as exc:
|
||||
|
||||
@@ -372,17 +372,16 @@ class TurnExecutor:
|
||||
exc,
|
||||
)
|
||||
|
||||
from deeptutor.utils.document_extractor import extract_documents_from_records
|
||||
from deeptutor.utils.document_extractor import extract_chat_documents
|
||||
|
||||
# Keep the built-in extractor as a graceful fallback, then replace
|
||||
# every PDF's result with the configured parser output. Running the
|
||||
# configured parser regardless of a native text layer is what lets
|
||||
# OCR/layout engines see scanned pages and figures.
|
||||
# each PDF's result with the configured parser output. OCR/layout
|
||||
# engines still see scanned pages and figures even with native text.
|
||||
# A quote is text the learner pointed at, not a document: read it
|
||||
# back as-is and keep it out of extraction.
|
||||
quotes = read_quotes(attachment_records)
|
||||
quote_records = [r for r in attachment_records if is_quote(r)]
|
||||
document_texts, attachment_records = extract_documents_from_records(
|
||||
document_texts, attachment_records = await extract_chat_documents(
|
||||
[r for r in attachment_records if not is_quote(r)]
|
||||
)
|
||||
attachment_records = quote_records + attachment_records
|
||||
|
||||
@@ -13,8 +13,8 @@ Three format families:
|
||||
the chat composer accepts every format the knowledge-base pipeline
|
||||
already ingests. Decoded with the same multi-encoding fallback chain.
|
||||
|
||||
Design mirrors ``nanobot/nanobot/utils/document.py`` but works on bytes
|
||||
instead of file paths so the server never touches disk.
|
||||
Design mirrors ``nanobot/nanobot/utils/document.py`` but accepts attachment
|
||||
bytes directly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +22,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
from hashlib import sha256
|
||||
from html.parser import HTMLParser
|
||||
import io
|
||||
import logging
|
||||
@@ -251,6 +252,13 @@ def extract_text_from_bytes(
|
||||
the same parsers with its larger upload policy while chat keeps the
|
||||
stricter per-turn limit.
|
||||
"""
|
||||
text, _ = _extract_document(filename, data, max_bytes=max_bytes, max_chars=max_chars)
|
||||
return text
|
||||
|
||||
|
||||
def _extract_document(
|
||||
filename: str, data: bytes, *, max_bytes: int | None, max_chars: int | None
|
||||
) -> tuple[str, tuple[EmbeddedImage, ...] | None]:
|
||||
if not data:
|
||||
raise EmptyDocumentError(f"{filename} is empty", filename=filename)
|
||||
if max_bytes is not None and len(data) > max_bytes:
|
||||
@@ -267,8 +275,9 @@ def extract_text_from_bytes(
|
||||
|
||||
_check_magic(ext, data, filename)
|
||||
|
||||
images = None
|
||||
if ext == ".pdf":
|
||||
text = _extract_pdf(data, filename)
|
||||
text, images = _extract_pdf(data, filename)
|
||||
elif ext == ".docx":
|
||||
text = _extract_docx(data, filename)
|
||||
elif ext == ".xlsx":
|
||||
@@ -284,7 +293,7 @@ def extract_text_from_bytes(
|
||||
|
||||
if not text.strip():
|
||||
raise EmptyDocumentError(f"{filename}: no extractable text", filename=filename)
|
||||
return _truncate(text, max_chars) if max_chars is not None else text
|
||||
return (_truncate(text, max_chars) if max_chars is not None else text), images
|
||||
|
||||
|
||||
def extract_text_from_path(
|
||||
@@ -366,7 +375,7 @@ async def extract_text_from_path_isolated(
|
||||
return result
|
||||
|
||||
|
||||
def _extract_pdf(data: bytes, filename: str) -> str:
|
||||
def _extract_pdf(data: bytes, filename: str) -> tuple[str, tuple[EmbeddedImage, ...] | None]:
|
||||
global fitz, PdfReader, _PypdfNotDecryptedError
|
||||
if fitz is _NOT_LOADED:
|
||||
try:
|
||||
@@ -400,7 +409,7 @@ def _extract_pdf(data: bytes, filename: str) -> str:
|
||||
note = pdf_images.collection.summary_note()
|
||||
if note:
|
||||
pages.append(note)
|
||||
return "\n\n".join(pages)
|
||||
return "\n\n".join(pages), pdf_images.collection.images
|
||||
except CorruptDocumentError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
@@ -432,7 +441,7 @@ def _extract_pdf(data: bytes, filename: str) -> str:
|
||||
f"--- Page {i} ---\n{page.extract_text() or ''}"
|
||||
for i, page in enumerate(reader.pages, 1)
|
||||
]
|
||||
return "\n\n".join(pages)
|
||||
return "\n\n".join(pages), None
|
||||
except CorruptDocumentError:
|
||||
raise
|
||||
except _PypdfNotDecryptedError as exc:
|
||||
@@ -1318,8 +1327,32 @@ def _embedded_images_for_document(filename: str, data: bytes) -> tuple[EmbeddedI
|
||||
return ()
|
||||
|
||||
|
||||
async def extract_chat_documents(records: list[dict]) -> tuple[list[str], list[dict]]:
|
||||
"""Keep native PDF text and image extraction off the API event loop."""
|
||||
if not any(
|
||||
_ext(str(record.get("filename") or "")) == ".pdf" and record.get("base64")
|
||||
for record in records
|
||||
):
|
||||
return extract_documents_from_records(records)
|
||||
|
||||
from deeptutor.runtime.isolated_worker import run_in_isolated_process
|
||||
|
||||
# Keep the full batch together so quotas and embedded image ordering match
|
||||
# the in-process extraction. Resolve the policy in the caller's workspace.
|
||||
# Image-heavy PDFs can take several minutes even with attachment size caps.
|
||||
return await run_in_isolated_process(
|
||||
"deeptutor.utils.document_extractor:extract_documents_from_records",
|
||||
records,
|
||||
timeout=600.0,
|
||||
kwargs={"limits": _current_limits(), "retain_native_pdf_markdown": True},
|
||||
)
|
||||
|
||||
|
||||
def extract_documents_from_records(
|
||||
records: Iterable[dict],
|
||||
*,
|
||||
limits: tuple[int, int, int, int] | None = None,
|
||||
retain_native_pdf_markdown: bool = False,
|
||||
) -> tuple[list[str], list[dict]]:
|
||||
"""Process a list of attachment records from the WS payload.
|
||||
|
||||
@@ -1328,6 +1361,12 @@ def extract_documents_from_records(
|
||||
records:
|
||||
Raw attachment records as parsed by the turn runtime
|
||||
(``{"type", "url", "base64", "filename", "mime_type"}``).
|
||||
limits:
|
||||
Optional caller-resolved per-file and total byte and text quotas,
|
||||
in the same order as ``_current_limits()``.
|
||||
retain_native_pdf_markdown:
|
||||
Include the complete native Markdown and source digest for the chat
|
||||
parser to consume before saving attachment records.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -1349,7 +1388,9 @@ def extract_documents_from_records(
|
||||
"""
|
||||
doc_texts: list[str] = []
|
||||
updated: list[dict] = []
|
||||
max_file_bytes, max_total_bytes, max_chars_per_doc, max_chars_total = _current_limits()
|
||||
max_file_bytes, max_total_bytes, max_chars_per_doc, max_chars_total = (
|
||||
limits if limits is not None else _current_limits()
|
||||
)
|
||||
total_bytes = 0
|
||||
total_chars = 0
|
||||
over_quota = False
|
||||
@@ -1393,13 +1434,14 @@ def extract_documents_from_records(
|
||||
continue
|
||||
|
||||
total_bytes += len(data)
|
||||
retain_markdown = retain_native_pdf_markdown and _ext(filename) == ".pdf"
|
||||
|
||||
try:
|
||||
text = extract_text_from_bytes(
|
||||
text, images = _extract_document(
|
||||
filename,
|
||||
data,
|
||||
max_bytes=max_file_bytes,
|
||||
max_chars=max_chars_per_doc,
|
||||
max_chars=None if retain_markdown else max_chars_per_doc,
|
||||
)
|
||||
except DocumentExtractionError as exc:
|
||||
logger.info("Document extraction failed for %s: %s", filename, exc)
|
||||
@@ -1417,6 +1459,13 @@ def extract_documents_from_records(
|
||||
updated.append(record)
|
||||
continue
|
||||
|
||||
if retain_markdown:
|
||||
if len(text) <= max_chars_per_doc:
|
||||
# Capture parser output before chat truncation and image notices.
|
||||
record["_native_pdf_markdown"] = (sha256(data).hexdigest(), text)
|
||||
else:
|
||||
text = _truncate(text, max_chars_per_doc)
|
||||
|
||||
if len(text) > remaining_budget:
|
||||
text = (
|
||||
text[:remaining_budget]
|
||||
@@ -1428,7 +1477,9 @@ def extract_documents_from_records(
|
||||
# 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)
|
||||
# The PDF text pass already harvested the pictures for its page markers.
|
||||
if images is None:
|
||||
images = _embedded_images_for_document(filename, data)
|
||||
emitted: list[EmbeddedImage] = []
|
||||
for image in images:
|
||||
if embedded_images >= MAX_EMBEDDED_IMAGES_PER_TURN:
|
||||
|
||||
@@ -869,6 +869,12 @@ def extract_pdf_images(data: bytes, *, budget: ImageBudget | None = None) -> Pdf
|
||||
if xref in rejected_xrefs:
|
||||
continue
|
||||
rejected_xrefs.add(xref)
|
||||
# Once full, count new figures from page metadata without
|
||||
# decoding them. Previously kept xrefs still map to this page.
|
||||
if budget.count >= budget.max_images:
|
||||
if info[2] >= 64 and info[3] >= 64:
|
||||
budget.skipped_budget += 1
|
||||
continue
|
||||
try:
|
||||
extracted = doc.extract_image(xref)
|
||||
except Exception:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -10,6 +11,38 @@ from deeptutor.services.session.attachment_parsing import parse_chat_pdf_attachm
|
||||
from deeptutor.services.storage.attachment_store import LocalDiskAttachmentStore
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pdf_fallback_extraction_in_worker_preserves_batch_and_limits(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
import pymupdf
|
||||
|
||||
from deeptutor.utils import document_extractor
|
||||
|
||||
with pymupdf.open() as pdf:
|
||||
pdf.new_page().insert_text((40, 60), "PDF attachment text")
|
||||
pdf_bytes = pdf.tobytes()
|
||||
monkeypatch.setattr(
|
||||
document_extractor, "_current_limits", lambda: (len(pdf_bytes), len(pdf_bytes), 1000, 1000)
|
||||
)
|
||||
|
||||
def fail_in_parent(*args: object, **kwargs: object) -> None:
|
||||
pytest.fail("PDF fallback extraction ran in the API process")
|
||||
|
||||
monkeypatch.setattr(document_extractor, "extract_documents_from_records", fail_in_parent)
|
||||
records = [
|
||||
{"id": "pdf", "filename": "notes.PDF", "base64": base64.b64encode(pdf_bytes).decode()},
|
||||
{"id": "text", "filename": "notes.txt", "base64": base64.b64encode(b"over quota").decode()},
|
||||
]
|
||||
|
||||
texts, updated = await document_extractor.extract_chat_documents(records)
|
||||
|
||||
assert "PDF attachment text" in texts[0]
|
||||
assert "total attachment quota exceeded" in texts[1]
|
||||
assert [record["id"] for record in updated] == ["pdf", "text"]
|
||||
assert all(record["base64"] == "" for record in updated)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_pdf_batch_does_not_read_parser_settings(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
@@ -29,6 +62,65 @@ async def test_non_pdf_batch_does_not_read_parser_settings(
|
||||
assert contexts == ["[File: notes.txt]\nhello"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"engine, unchanged, native_complete, reuse",
|
||||
[
|
||||
("text_only", True, True, True),
|
||||
("text_only", False, True, False),
|
||||
("text_only", True, False, False),
|
||||
("mineru", True, True, False),
|
||||
],
|
||||
)
|
||||
async def test_chat_pdf_reuses_native_markdown_only_for_matching_text_only_input(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
engine: str,
|
||||
unchanged: bool,
|
||||
native_complete: bool,
|
||||
reuse: bool,
|
||||
) -> None:
|
||||
import pymupdf
|
||||
|
||||
from deeptutor.utils import document_extractor
|
||||
|
||||
with pymupdf.open() as pdf:
|
||||
pdf.new_page().insert_text((40, 60), "Original PDF text")
|
||||
data = pdf.tobytes()
|
||||
store = LocalDiskAttachmentStore(root=tmp_path / "attachments")
|
||||
await store.put(
|
||||
session_id="session",
|
||||
attachment_id="pdf",
|
||||
filename="notes.pdf",
|
||||
data=data if unchanged else b"other bytes",
|
||||
)
|
||||
if not native_complete:
|
||||
monkeypatch.setattr(document_extractor, "_current_limits", lambda: (10000, 10000, 30, 1000))
|
||||
native_contexts, native_records = await document_extractor.extract_chat_documents(
|
||||
[{"id": "pdf", "filename": "notes.pdf", "base64": base64.b64encode(data).decode()}]
|
||||
)
|
||||
calls = []
|
||||
|
||||
class Parser:
|
||||
def active_engine(self) -> str:
|
||||
return engine
|
||||
|
||||
def parse(self, path: Path, **_: object) -> ParsedDocument:
|
||||
calls.append(path)
|
||||
return ParsedDocument(markdown="# Configured parser output")
|
||||
|
||||
monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", lambda: Parser())
|
||||
records, contexts = await parse_chat_pdf_attachments(
|
||||
native_records, attachment_store=store, session_id="session", document_texts=native_contexts
|
||||
)
|
||||
|
||||
expected = "--- Page 1 ---\nOriginal PDF text" if reuse else "# Configured parser output"
|
||||
assert len(calls) == (0 if reuse else 1)
|
||||
assert records[0]["extracted_text"] == expected
|
||||
assert contexts == [f"[File: notes.pdf]\n{expected}"]
|
||||
assert "_native_pdf_markdown" not in records[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_pdf_always_uses_configured_parser(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
from random import Random
|
||||
import zipfile
|
||||
|
||||
from docx import Document as DocxDocument
|
||||
@@ -617,6 +618,45 @@ class TestTruncation:
|
||||
|
||||
|
||||
class TestExtractDocumentsFromRecords:
|
||||
def test_pdf_uses_one_image_pass_for_page_markers_and_attachments(
|
||||
self, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from PIL import Image
|
||||
import pymupdf
|
||||
|
||||
image = io.BytesIO()
|
||||
Image.frombytes("RGB", (100, 100), Random(0).randbytes(30_000)).save(image, format="PNG")
|
||||
with pymupdf.open() as pdf:
|
||||
page = pdf.new_page()
|
||||
page.insert_text((40, 60), "Figure on page one")
|
||||
page.insert_image(pymupdf.Rect(40, 90, 140, 190), stream=image.getvalue())
|
||||
pdf_bytes = pdf.tobytes()
|
||||
|
||||
harvest = document_extractor_module.extract_pdf_images
|
||||
calls = []
|
||||
|
||||
def count_harvest(data: bytes):
|
||||
calls.append(len(data))
|
||||
return harvest(data)
|
||||
|
||||
monkeypatch.setattr(document_extractor_module, "extract_pdf_images", count_harvest)
|
||||
texts, records = extract_documents_from_records(
|
||||
[
|
||||
{
|
||||
"id": "pdf",
|
||||
"filename": "figure.pdf",
|
||||
"base64": base64.b64encode(pdf_bytes).decode(),
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
assert calls == [len(pdf_bytes)]
|
||||
assert "Figure on page one" in texts[0]
|
||||
assert "[图片 1:" in texts[0]
|
||||
assert records[0]["id"] == "pdf-e01"
|
||||
assert records[0]["embedded"] is True
|
||||
assert records[1]["id"] == "pdf"
|
||||
|
||||
def test_native_word_equations_reach_chat_attachment_text(self) -> None:
|
||||
records = [
|
||||
{
|
||||
|
||||
@@ -289,6 +289,35 @@ def test_pdf_images_default_budget_caps_at_twelve(tmp_path) -> None:
|
||||
assert result.collection.skipped_page_budget == 0
|
||||
|
||||
|
||||
def test_pdf_image_cap_skips_decode_but_maps_repeated_images(monkeypatch) -> None:
|
||||
pymupdf = pytest.importorskip("pymupdf")
|
||||
rect = pymupdf.Rect(72, 72, 300, 220)
|
||||
with pymupdf.open() as pdf:
|
||||
kept = [
|
||||
pdf.new_page().insert_image(rect, stream=_png_for_index(index)) for index in range(12)
|
||||
]
|
||||
skipped = pdf.new_page().insert_image(rect, stream=_png_for_index(12))
|
||||
last_page = pdf.new_page()
|
||||
last_page.insert_image(rect, xref=kept[0])
|
||||
last_page.insert_image(rect, xref=skipped)
|
||||
data = pdf.tobytes()
|
||||
|
||||
decoded = []
|
||||
extract_image = pymupdf.Document.extract_image
|
||||
|
||||
def track_decode(document, xref):
|
||||
decoded.append(xref)
|
||||
return extract_image(document, xref)
|
||||
|
||||
monkeypatch.setattr(pymupdf.Document, "extract_image", track_decode)
|
||||
result = extract_pdf_images(data)
|
||||
|
||||
assert decoded == kept
|
||||
assert len(result.collection.images) == 12
|
||||
assert result.collection.skipped_budget == 1
|
||||
assert result.page_map == tuple((i + 1, (i,)) for i in range(12)) + ((14, (0,)),)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Inline transport bound
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user