Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: add asynchronous document analysis function to improve performance and non-blocking behavior
myhlolie73a8aeced53
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.pyindex 77e780c1..dcf3e11b 100644--- a/mineru/backend/analyze.py+++ b/mineru/backend/analyze.py@@ -3,6 +3,7 @@from __future__ import annotations+import asynciofrom typing import Any, Literal, castfrom loguru import logger@@ -57,3 +58,23 @@ def doc_analyze(mineru_version=mineru_version,)return middle_json, result.model_list+++async def aio_doc_analyze(+ file_bytes: bytes,+ effort: Literal["flash", "low", "medium", "high", "xhigh"] = "high",+ parse_mode: Literal["auto", "txt", "ocr"] = "auto",+ image_analysis: bool = True,+ page_index_map: list[int] | None = None,+ file_suffix: Literal["pdf", "docx", "pptx", "xlsx"] = "pdf",+) -> tuple[MiddleJson, list[list[dict[str, Any]]]]:+ """在线程中执行统一文档分析,避免阻塞调用方事件循环。"""+ return await asyncio.to_thread(+ doc_analyze,+ file_bytes=file_bytes,+ effort=effort,+ parse_mode=parse_mode,+ image_analysis=image_analysis,+ page_index_map=page_index_map,+ file_suffix=file_suffix,+ )diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.pyindex 8af7b992..bb47eb9e 100644--- a/tests/unittest/test_pdf_analyze_visual_blocks.py+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py@@ -1,6 +1,9 @@from __future__ import annotations+import asyncioimport base64+import inspect+import threadingfrom io import BytesIOfrom pathlib import Pathfrom unittest.mock import MagicMock@@ -1148,6 +1151,68 @@ def test_log_infer_performance_uses_unrounded_elapsed(assert expected_speed in message+def test_aio_doc_analyze_matches_sync_signature() -> None:+ """验证异步门面的参数、默认值和返回标注与同步入口保持一致。"""+ sync_signature = inspect.signature(analyze.doc_analyze)+ async_signature = inspect.signature(analyze.aio_doc_analyze)++ assert async_signature.parameters == sync_signature.parameters+ assert async_signature.return_annotation == sync_signature.return_annotation+++def test_aio_doc_analyze_runs_sync_entrypoint_in_thread_and_forwards_arguments(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证异步门面在线程中执行同步入口,并完整转发非默认参数和返回值。"""+ caller_thread_id = threading.get_ident()+ observed: dict[str, object] = {}+ expected_result = (MagicMock(spec=MiddleJson), [[{"type": BlockType.TEXT, "content": "async"}]])++ def fake_doc_analyze(**kwargs: object) -> tuple[MiddleJson, list[list[dict[str, object]]]]:+ """记录工作线程及异步门面传入的全部关键字参数。"""+ observed["thread_id"] = threading.get_ident()+ observed["kwargs"] = kwargs+ return expected_result++ monkeypatch.setattr(analyze, "doc_analyze", fake_doc_analyze)++ actual_result = asyncio.run(+ analyze.aio_doc_analyze(+ b"async-document",+ effort="xhigh",+ parse_mode="ocr",+ image_analysis=False,+ page_index_map=[3, 5],+ file_suffix="pptx",+ )+ )++ assert actual_result is expected_result+ assert observed["kwargs"] == {+ "file_bytes": b"async-document",+ "effort": "xhigh",+ "parse_mode": "ocr",+ "image_analysis": False,+ "page_index_map": [3, 5],+ "file_suffix": "pptx",+ }+ assert observed["thread_id"] != caller_thread_id+++def test_aio_doc_analyze_propagates_sync_entrypoint_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证同步入口异常会穿过工作线程并由异步调用方原样收到。"""+ def fake_doc_analyze(**_kwargs: object) -> tuple[MiddleJson, list[list[dict[str, object]]]]:+ """模拟同步文档分析阶段抛出参数异常。"""+ raise ValueError("async analyze failed")++ monkeypatch.setattr(analyze, "doc_analyze", fake_doc_analyze)++ with pytest.raises(ValueError, match="async analyze failed"):+ asyncio.run(analyze.aio_doc_analyze(b"invalid-document"))++@pytest.mark.parametrize("file_suffix", ["docx", "pptx", "xlsx"])def test_doc_analyze_office_returns_model_list_without_pdf_processing(monkeypatch: pytest.MonkeyPatch,