Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat(pdf): reuse document render sessions across analysis windows

myhlolic11b7f5bb608
diff --git a/mineru/backend/analysis/pdf/images.py b/mineru/backend/analysis/pdf/images.py
index 1cb2db9f..8a8f4b36 100644
--- a/mineru/backend/analysis/pdf/images.py
+++ b/mineru/backend/analysis/pdf/images.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import os
-from typing import Any, Literal
+from typing import TYPE_CHECKING, Any, Literal
from docvortex.document.pdf import images as _images
from docvortex.document.pdf.images import DEFAULT_PDF_IMAGE_DPI
from docvortex.document.pdf.images import (
@@ -17,6 +17,10 @@ from docvortex.document.pdf.images import (
)
+if TYPE_CHECKING:
+ from docvortex.document.pdf import PDFDocument, PDFRenderSession
+
+
def _positive_int_env(name: str, default: int) -> int:
"""保留现有正整数配置校验与缺省值。"""
raw = os.environ.get(name)
@@ -39,6 +43,21 @@ def get_load_images_threads() -> int:
return _positive_int_env("MINERU_PDF_RENDER_THREADS", 3)
+def get_document_render_session(document: PDFDocument) -> PDFRenderSession | None:
+ """按共享后端选择复用文档会话,选中新接口但引擎缺失时明确报错。"""
+ selector = getattr(_images, "get_pdf_render_backend", None)
+ if selector is None:
+ if os.environ.get("DOCVORTEX_PDF_RENDER_BACKEND", "legacy").strip().lower() != "legacy":
+ raise RuntimeError("Installed DocVortex does not support PDF render sessions")
+ return None
+ if selector() != "session":
+ return None
+ factory = getattr(document, "get_render_session", None)
+ if not callable(factory):
+ raise RuntimeError("PDF document does not support get_render_session; upgrade DocVortex")
+ return factory(threads=get_load_images_threads(), timeout=get_load_images_timeout())
+
+
def load_images_from_pdf_bytes_range(
pdf_bytes: bytes,
dpi: int = DEFAULT_PDF_IMAGE_DPI,
@@ -47,8 +66,16 @@ def load_images_from_pdf_bytes_range(
image_type: Literal["pil_img", "base64_img"] = "pil_img",
timeout: int | None = None,
threads: int | None = None,
+ *,
+ document: PDFDocument | None = None,
+ session: PDFRenderSession | None = None,
) -> list[dict[str, Any]]:
- """向独立引擎显式传入宿主配置,复用其唯一渲染进程池。"""
+ """向独立引擎传入宿主配置,按后端复用同一文档的渲染会话。"""
+ if getattr(_images, "get_pdf_render_backend", None) is None:
+ if session is not None or os.environ.get("DOCVORTEX_PDF_RENDER_BACKEND", "legacy").strip().lower() != "legacy":
+ raise RuntimeError("Installed DocVortex does not support PDF render sessions")
+ if session is None and document is not None:
+ session = get_document_render_session(document)
return _images.load_images_from_pdf_bytes_range(
pdf_bytes,
dpi=dpi,
@@ -57,11 +84,13 @@ def load_images_from_pdf_bytes_range(
image_type=image_type,
timeout=get_load_images_timeout() if timeout is None else timeout,
threads=get_load_images_threads() if threads is None else threads,
+ **({"session": session} if session is not None else {}),
)
__all__ = [
"ImageType",
+ "get_document_render_session",
"get_load_images_timeout",
"get_load_images_threads",
"pdf_page_to_image",
diff --git a/mineru/backend/analysis/pdf/window.py b/mineru/backend/analysis/pdf/window.py
index 6dd6b774..16b0111d 100644
--- a/mineru/backend/analysis/pdf/window.py
+++ b/mineru/backend/analysis/pdf/window.py
@@ -3,10 +3,13 @@
from __future__ import annotations
+import asyncio
+from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
+ from docvortex.document.pdf import PDFRenderSession
from PIL.Image import Image
from ....model.vlm.contracts import VlmPredictor
@@ -20,7 +23,7 @@ from loguru import logger
from ....utils.timing import stage_timer
from ....model.runtime.execution import local_model_stage
-from ....utils.async_utils import run_sync
+from ....utils.async_utils import drain_future, run_sync
from ....model.runtime.hybrid import HybridLocalModelContext
from ....model.runtime.memory import trim_process_heap
from ..contracts import AnalyzeEffort
@@ -38,7 +41,12 @@ from .formulas import (
_split_formula_results,
optimize_hybrid_formula_number_blocks,
)
-from .images import get_load_images_threads, get_load_images_timeout, load_images_from_pdf_bytes_range
+from .images import (
+ get_document_render_session,
+ get_load_images_threads,
+ get_load_images_timeout,
+ load_images_from_pdf_bytes_range,
+)
from .layout import (
_build_vl_style_layout_blocks,
_collect_table_items,
@@ -364,6 +372,7 @@ def _prepare_pdf_window(
with stage_timer("pdf.render"):
images_list = load_images_from_pdf_bytes_range(
pdf_bytes=file_bytes,
+ document=document,
start_page_id=window.start,
end_page_id=window.end,
image_type="pil_img",
@@ -636,6 +645,25 @@ def _finish_locked_window(
return _finish_pdf_window(state, result, effort=effort, parse_mode=parse_mode, hybrid_model=hybrid_model)
+async def _run_window_prepare(prepare: Callable[[], None], render_session: PDFRenderSession | None) -> None:
+ """取消时先中止会话渲染,再等待准备线程退出,避免文档提前关闭。"""
+ if render_session is None:
+ return await run_sync(prepare)
+ work = asyncio.create_task(asyncio.to_thread(prepare))
+ try:
+ return await asyncio.shield(work)
+ except asyncio.CancelledError:
+ cleanup = asyncio.create_task(asyncio.to_thread(render_session.cancel))
+ try:
+ await drain_future(cleanup)
+ finally:
+ try:
+ await drain_future(work)
+ except BaseException:
+ pass
+ raise
+
+
async def aio_process_pdf_windows(
file_bytes: bytes,
document: PDFDocument,
@@ -652,6 +680,7 @@ async def aio_process_pdf_windows(
windows = _build_processing_windows(page_count, window_size)
_log_processing_window_plan(page_count, window_size, len(windows))
model_list = []
+ render_session = get_document_render_session(document) if windows else None
for window in windows:
state = None
try:
@@ -673,7 +702,7 @@ async def aio_process_pdf_windows(
)
try:
- await run_sync(prepare)
+ await _run_window_prepare(prepare, render_session)
finally:
state = holder[0] if holder else None
options = _inference_options(state, effort, parse_mode, image_analysis)
@@ -691,6 +720,11 @@ async def aio_process_pdf_windows(
hybrid_model=hybrid_model,
)
)
+ except asyncio.CancelledError:
+ if render_session is not None:
+ cleanup = asyncio.create_task(asyncio.to_thread(render_session.cancel))
+ await drain_future(cleanup)
+ raise
finally:
if state is not None:
await run_sync(state.close)
@@ -715,14 +749,23 @@ def process_pdf_windows(
if flash_txt_mode:
# Flash 原生结果只按视觉块需求补图,不再进入供推理使用的全页渲染窗口。
from docvortex.analyzers.native import PdfModel
+ from docvortex.document.pdf.constants import MODEL_JSON_VISUAL_BLOCK_TYPES
model_list = PdfModel().predict(document)
+ # 纯文本不创建会话输入文件;视觉容器会在引擎补图前折叠为 image。
+ needs_images = any(
+ block.get("type") in MODEL_JSON_VISUAL_BLOCK_TYPES or block.get("type") == "image_block"
+ for page in model_list
+ for block in page
+ )
+ render_session = get_document_render_session(document) if needs_images else None
attach_visual_block_images_from_pdf(
document,
model_list,
window_size=_configured_window_size(default=64),
timeout=get_load_images_timeout(),
threads=get_load_images_threads(),
+ **({"session": render_session} if render_session is not None else {}),
)
return model_list
diff --git a/tests/unittest/test_pdf_render_session_integration.py b/tests/unittest/test_pdf_render_session_integration.py
new file mode 100644
index 00000000..c2992d9d
--- /dev/null
+++ b/tests/unittest/test_pdf_render_session_integration.py
@@ -0,0 +1,246 @@
+"""双仓真实渲染会话接入验证,模型用固定空结果隔离。"""
+
+import asyncio
+from typing import Any
+from io import BytesIO
+from types import SimpleNamespace
+import pytest
+from reportlab.pdfgen.canvas import Canvas
+from docvortex.document.pdf import PDFDocument
+from docvortex.document.pdf.render_session import shutdown_pdf_render_sessions
+from mineru.backend.analysis.pdf import images, window
+
+
+def pdf_input() -> bytes:
+ """生成两页不同尺寸 PDF,便于检测窗口错误复用。"""
+ output = BytesIO()
+ canvas = Canvas(output, pagesize=(80, 100))
+ for index in range(2):
+ canvas.setPageSize((80 + index * 10, 100))
+ canvas.drawString(5, 40, f"Window {index}")
+ canvas.showPage()
+ canvas.save()
+ return output.getvalue()
+
+
+def model_stub(monkeypatch: pytest.MonkeyPatch) -> Any:
+ """只替换模型结果与回填,保留真实文档、窗口、渲染和关闭逻辑。"""
+ monkeypatch.setenv("DOCVORTEX_PDF_RENDER_BACKEND", "session")
+ monkeypatch.setenv("MINERU_PROCESSING_WINDOW_SIZE", "1")
+ monkeypatch.setenv("MINERU_PDF_RENDER_THREADS", "1")
+
+ def layout(pages: Any, **kwargs: Any) -> Any:
+ """为空布局返回逐页容器,不加载神经模型。"""
+ return [[] for _ in pages]
+
+ def finish(state: Any, result: Any, **kwargs: Any) -> Any:
+ """返回已经隔离的模型结果,保留窗口图像的实际生命周期。"""
+ return result
+
+ monkeypatch.setattr(window, "_finish_pdf_window", finish)
+ monkeypatch.setattr(window, "trim_process_heap", lambda: None)
+ yield SimpleNamespace(device="cpu", layout_model=SimpleNamespace(batch_predict=layout))
+ shutdown_pdf_render_sessions()
+
+
+def test_sync_windows_share_document_session(pdf_input: bytes, model_stub: SimpleNamespace) -> None:
+ """同步两个窗口仅打开一次 worker 文档,由外层文档统一关闭。"""
+ with PDFDocument(pdf_input) as document:
+ result = window.process_pdf_windows(
+ pdf_input,
+ document,
+ effort="medium",
+ parse_mode="ocr",
+ image_analysis=False,
+ flash_txt_mode=False,
+ hybrid_model=model_stub,
+ vlm_predictor=None,
+ )
+ session = document.get_render_session()
+ assert result == [[], []]
+ assert len(session.worker_diagnostics) == 1
+ assert not session._closed
+ assert session._closed and session.close_diagnostics[0]["input_released"]
+
+
+def test_async_windows_share_document_session(pdf_input: bytes, model_stub: SimpleNamespace) -> None:
+ """异步两个窗口复用同一 worker 文档且保持页面顺序。"""
+
+ async def predict(**kwargs: Any) -> Any:
+ """返回与输入窗口对应的空模型输出。"""
+ return [[] for _ in kwargs["images"]]
+
+ with PDFDocument(pdf_input) as document:
+ result = asyncio.run(
+ window.aio_process_pdf_windows(
+ pdf_input,
+ document,
+ effort="xhigh",
+ parse_mode="ocr",
+ image_analysis=False,
+ hybrid_model=model_stub,
+ vlm_predictor=SimpleNamespace(aio_batch_two_step_extract=predict),
+ )
+ )
+ session = document.get_render_session()
+ assert result == [[], []]
+ assert len(session.worker_diagnostics) == 1
+ assert session._closed
+
+
+def test_async_cancel_reclaims_session_and_pixels(pdf_input: bytes, model_stub: SimpleNamespace) -> None:
+ """取消异步推理时会话租约及时归还,窗口像素在外层文档关闭前释放。"""
+ states = []
+ original = window._prepare_locked_window
+
+ def prepare(*args: Any, **kwargs: Any) -> Any:
+ """记录真实窗口以检查取消后的资源容器。"""
+ state = original(*args, **kwargs)
+ states.append(state)
+ return state
+
+ async def scenario(document: PDFDocument) -> None:
+ """在真实页图已准备后取消等待中的推理。"""
+ ready = asyncio.Event()
+
+ async def predict(**kwargs: Any) -> Any:
+ """阻塞推理以制造可确定的异步取消边界。"""
+ ready.set()
+ await asyncio.Event().wait()
+
+ task = asyncio.create_task(
+ window.aio_process_pdf_windows(
+ pdf_input,
+ document,
+ effort="xhigh",
+ parse_mode="ocr",
+ image_analysis=False,
+ hybrid_model=model_stub,
+ vlm_predictor=SimpleNamespace(aio_batch_two_step_extract=predict),
+ )
+ )
+ await asyncio.wait_for(ready.wait(), 10)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ from unittest.mock import patch
+
+ with PDFDocument(pdf_input) as document, patch.object(window, "_prepare_locked_window", prepare):
+ asyncio.run(scenario(document))
+ assert document.get_render_session()._closed
+ assert states and states[0].images_list == [] and (states[0].np_images == [])
+
+
+def test_host_timeout_closes_document_session(pdf_input: bytes, model_stub: SimpleNamespace) -> None:
+ """宿主 timeout 显式传到引擎,失败清理会话而非静默回退。"""
+ with PDFDocument(pdf_input) as document:
+ with pytest.raises(TimeoutError):
+ images.load_images_from_pdf_bytes_range(pdf_input, document=document, timeout=1e-09)
+ assert document.get_render_session()._closed
+
+
+def test_requested_session_requires_engine_api(monkeypatch: pytest.MonkeyPatch) -> None:
+ """明确选择 session 但引擎不具备接口时直接报错。"""
+ monkeypatch.setenv("DOCVORTEX_PDF_RENDER_BACKEND", "session")
+ with pytest.raises(RuntimeError, match="get_render_session"):
+ images.get_document_render_session(SimpleNamespace())
+ monkeypatch.delattr(images._images, "get_pdf_render_backend")
+ with pytest.raises(RuntimeError, match="does not support"):
+ images.load_images_from_pdf_bytes_range(b"pdf")
+
+
+def test_async_cancel_interrupts_active_render_wait(
+ pdf_input: bytes, model_stub: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """取消准备阶段时主动终止渲染等待,不等待完整渲染超时才清理。"""
+ import threading
+
+ with PDFDocument(pdf_input) as document:
+ session = images.get_document_render_session(document)
+ ready = threading.Event()
+ original = session._receive
+
+ def receive(worker: Any, request_id: Any, deadline: Any, **kwargs: Any) -> Any:
+ """在真实 worker 请求之后制造可取消的确定等待点。"""
+ ready.set()
+ session._cancelled.wait(10)
+ return original(worker, request_id, deadline, **kwargs)
+
+ monkeypatch.setattr(session, "_receive", receive)
+
+ async def scenario() -> None:
+ """渲染开始后取消协程并确认线程和输入资源均已退出。"""
+ task = asyncio.create_task(
+ window.aio_process_pdf_windows(
+ pdf_input,
+ document,
+ effort="xhigh",
+ parse_mode="ocr",
+ image_analysis=False,
+ hybrid_model=model_stub,
+ vlm_predictor=None,
+ )
+ )
+ assert await asyncio.to_thread(ready.wait, 10)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, 5)
+
+ asyncio.run(scenario())
+ assert session._closed and (not session._input.exists()) and (not session._workers)
+
+
+def test_flash_visual_windows_share_session(
+ pdf_input: bytes, model_stub: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Flash 补图使用文档会话,两个稀疏窗口不重复打开 worker 文档。"""
+ import docvortex.analyzers.native as native
+
+ def predict(document: PDFDocument) -> Any:
+ """固定两页图像块,用真实裁图验证 Flash 接入。"""
+ return [[{"type": "image", "bbox": [0.1, 0.1, 0.5, 0.5]}] for _ in range(document.page_count)]
+
+ monkeypatch.setattr(native, "PdfModel", lambda: SimpleNamespace(predict=predict))
+ with PDFDocument(pdf_input) as document:
+ result = window.process_pdf_windows(
+ pdf_input,
+ document,
+ effort="flash",
+ parse_mode="txt",
+ image_analysis=False,
+ flash_txt_mode=True,
+ hybrid_model=None,
+ vlm_predictor=None,
+ )
+ session = document.get_render_session()
+ assert len(session.worker_diagnostics) == 1
+ assert all((page[0]["image_base64"] for page in result))
+ assert session._closed
+
+
+def test_flash_text_only_does_not_create_session(
+ pdf_input: bytes, model_stub: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """显式 session 模式下,纯文本 Flash 仍不创建映射输入或渲染租约。"""
+ import docvortex.analyzers.native as native
+
+ def predict(document: PDFDocument) -> Any:
+ """固定无视觉素材的页面,隔离模型对会话惰性行为的影响。"""
+ return [[{"type": "text", "bbox": [0.1, 0.1, 0.5, 0.5]}] for _ in range(document.page_count)]
+
+ monkeypatch.setattr(native, "PdfModel", lambda: SimpleNamespace(predict=predict))
+ with PDFDocument(pdf_input) as document:
+ window.process_pdf_windows(
+ pdf_input,
+ document,
+ effort="flash",
+ parse_mode="txt",
+ image_analysis=False,
+ flash_txt_mode=True,
+ hybrid_model=None,
+ vlm_predictor=None,
+ )
+ assert document._render_session is None