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
fix: enhance performance measurement and diagnostic handling in native PDF table evaluation
myhloli8a0572c556a8
diff --git a/tests/fixtures/evaluate_native_pdf_table_manifest.py b/tests/fixtures/evaluate_native_pdf_table_manifest.pyindex e2964bbd..24183bf0 100644--- a/tests/fixtures/evaluate_native_pdf_table_manifest.py+++ b/tests/fixtures/evaluate_native_pdf_table_manifest.py@@ -60,12 +60,43 @@ def _result_signature(result: Any) -> dict[str, Any] | None:}+def _recover_table_input(+ table_input: NativeTableInput,+ *,+ measure_performance: bool,+) -> tuple[dict[str, Any] | None, float]:+ """按性能门开关执行一次功能恢复,或执行预热后的正式计时恢复。"""++ if not measure_performance:+ return _result_signature(recover_native_pdf_table(table_input)), 0.0+ # 性能模式保留一次不计时预热,避免 Python 首次路径和页面缓存抖动污染 p95。+ recover_native_pdf_table(table_input)+ started = time.perf_counter()+ result = recover_native_pdf_table(table_input)+ return _result_signature(result), time.perf_counter() - started+++def _maybe_diagnose_table_input(+ table_input: NativeTableInput,+ *,+ collect_diagnostics: bool,+ mismatch: bool,+) -> dict[str, Any] | None:+ """仅在显式请求诊断或结果不匹配时执行昂贵的候选诊断。"""++ if not collect_diagnostics and not mismatch:+ return None+ return diagnose_native_pdf_table(table_input)++def _evaluate_entry(document: PDFDocument,entry: dict[str, Any],page_cache: dict[int, tuple[Any, ...]],-) -> tuple[dict[str, Any] | None, float, dict[str, Any]]:- """运行一个 manifest 表格并返回结构签名和耗时。"""+ *,+ measure_performance: bool,+) -> tuple[dict[str, Any] | None, float, NativeTableInput]:+ """构造一个 manifest 表格输入,并返回结构签名、耗时和诊断输入。"""page_index = int(entry["page_index"])if page_index not in page_cache:@@ -95,16 +126,11 @@ def _evaluate_entry(drawing_lines=rules,rectangles=rectangles,)- # 先执行一次不计时预热,避免 Python 首次路径和页面缓存抖动污染 p95。- recover_native_pdf_table(table_input)- started = time.perf_counter()- result = recover_native_pdf_table(table_input)- duration = time.perf_counter() - started- return (- _result_signature(result),- duration,- diagnose_native_pdf_table(table_input),+ actual, duration = _recover_table_input(+ table_input,+ measure_performance=measure_performance,)+ return actual, duration, table_inputdef _entry_mismatch(@@ -167,28 +193,37 @@ def main() -> None:html_count = 0target_html_count = 0durations: list[float] = []+ measure_performance = not args.skip_performance_gate+ collect_diagnostics = args.diagnostics_output is not Nonefor filename, entries in entries_by_file.items():with PDFDocument(str(args.source_root / filename)) as document:page_cache: dict[int, tuple[Any, ...]] = {}for entry in entries:- actual, duration, diagnostic = _evaluate_entry(+ actual, duration, table_input = _evaluate_entry(document,entry,page_cache,- )- diagnostics.append(- {- "scope": "corpus",- "file": filename,- "page_index": entry["page_index"],- "table_index": entry["table_index"],- "bbox": entry["bbox"],- "expected_output": entry["expected_output"],- **diagnostic,- }+ measure_performance=measure_performance,)durations.append(duration)actual_output, mismatch = _entry_mismatch(entry, actual)+ diagnostic = _maybe_diagnose_table_input(+ table_input,+ collect_diagnostics=collect_diagnostics,+ mismatch=mismatch,+ )+ if diagnostic is not None:+ diagnostics.append(+ {+ "scope": "corpus",+ "file": filename,+ "page_index": entry["page_index"],+ "table_index": entry["table_index"],+ "bbox": entry["bbox"],+ "expected_output": entry["expected_output"],+ **diagnostic,+ }+ )if actual_output == "html":html_count += 1is_target = entry["review_status"] == "target_verified"@@ -203,6 +238,8 @@ def main() -> None:"expected_output": entry["expected_output"],"actual": actual,}+ if diagnostic is not None:+ mismatch_record["diagnostic"] = diagnosticif is_target:target_mismatches.append(mismatch_record)else:@@ -217,36 +254,44 @@ def main() -> None:with PDFDocument(str(args.source_root / filename)) as document:page_cache = {}for entry in entries:- actual, duration, diagnostic = _evaluate_entry(+ actual, duration, table_input = _evaluate_entry(document,entry,page_cache,- )- diagnostics.append(- {- "scope": "flash_target",- "file": filename,- "page_index": entry["page_index"],- "table_index": entry["table_index"],- "bbox_points": entry["bbox_points"],- "expected_output": entry["expected_output"],- **diagnostic,- }+ measure_performance=measure_performance,)durations.append(duration)actual_output, mismatch = _entry_mismatch(entry, actual)- if actual_output == "html":- flash_target_html_count += 1- if mismatch:- flash_target_mismatches.append(+ diagnostic = _maybe_diagnose_table_input(+ table_input,+ collect_diagnostics=collect_diagnostics,+ mismatch=mismatch,+ )+ if diagnostic is not None:+ diagnostics.append({+ "scope": "flash_target","file": filename,"page_index": entry["page_index"],"table_index": entry["table_index"],+ "bbox_points": entry["bbox_points"],"expected_output": entry["expected_output"],- "actual": actual,+ **diagnostic,})+ if actual_output == "html":+ flash_target_html_count += 1+ if mismatch:+ mismatch_record = {+ "file": filename,+ "page_index": entry["page_index"],+ "table_index": entry["table_index"],+ "expected_output": entry["expected_output"],+ "actual": actual,+ }+ if diagnostic is not None:+ mismatch_record["diagnostic"] = diagnostic+ flash_target_mismatches.append(mismatch_record)total = len(manifest["entries"])target_total = sum(entry["review_status"] == "target_verified" for entry in manifest["entries"])diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.pyindex 9351e07d..786fb294 100644--- a/tests/unittest/test_flash_pdf_samples.py+++ b/tests/unittest/test_flash_pdf_samples.py@@ -1,12 +1,16 @@from __future__ import annotationsimport re+import sysimport unicodedatafrom collections import Counter+from collections.abc import Iteratorfrom copy import deepcopy+from functools import lru_cachefrom pathlib import Pathfrom typing import Any+import pytestfrom bs4 import BeautifulSoupfrom pypdf import PdfReader@@ -37,6 +41,40 @@ _CJK_SYNTHETIC_PDF_NAME = "native_cjk_layout_synthetic.pdf"_SAFE_WATERMARK_TEXT = "MINERU TEST WATERMARK"+def _pdf_cache_key(pdf_path: Path) -> tuple[str, int, int]:+ """以规范路径、文件大小和纳秒 mtime 构造单次 pytest 进程内缓存键。"""++ resolved = pdf_path.resolve()+ stat = resolved.stat()+ return str(resolved), stat.st_size, stat.st_mtime_ns+++@lru_cache(maxsize=None)+def _cached_model_list(+ pdf_path: str,+ _size: int,+ _mtime_ns: int,+) -> list[list[dict[str, Any]]]:+ """每份不可变真实 PDF 只运行一次 Flash 预测,并缓存原始模型输出。"""++ with PDFDocument(Path(pdf_path).read_bytes()) as pdf_doc:+ return PdfModel().predict(pdf_doc)+++def _cached_model_list_copy(pdf_path: Path) -> list[list[dict[str, Any]]]:+ """返回缓存模型输出的深拷贝,隔离不同测试对可变 block 的修改。"""++ return deepcopy(_cached_model_list(*_pdf_cache_key(pdf_path)))++[email protected](scope="module", autouse=True)+def _clear_real_pdf_model_cache_after_module() -> Iterator[None]:+ """模块结束后释放真实 PDF 模型缓存,避免影响后续 unittest 内存。"""++ yield+ _cached_model_list.cache_clear()++def _model_json(pages: list[list[dict[str, Any]]],*,@@ -105,9 +143,7 @@ def _native_model_list() -> list[list[dict[str, Any]]]:"""运行仓库内数字 PDF 样例并返回 Flash 原生模型输出。"""- pdf_path = pdf_dir / pdf_name- with PDFDocument(str(pdf_path)) as pdf_doc:- return PdfModel().predict(pdf_doc)+ return _cached_model_list_copy(pdf_dir / pdf_name)def _txt_model_list(@@ -117,9 +153,7 @@ def _txt_model_list() -> list[list[dict[str, Any]]]:"""显式使用 Flash TXT 模式解析仓库内回归 PDF,禁止经过 auto 分类。"""- pdf_path = pdf_dir / pdf_name- with PDFDocument(pdf_path.read_bytes()) as pdf_doc:- return PdfModel().predict(pdf_doc)+ return _cached_model_list_copy(pdf_dir / pdf_name)def _auto_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:@@ -128,7 +162,7 @@ def _auto_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / pdf_namewith PDFDocument(pdf_path.read_bytes()) as pdf_doc:assert pdf_doc.classify() == "txt"- return PdfModel().predict(pdf_doc)+ return _cached_model_list_copy(pdf_path)def _native_table_counts(pdf_name: str) -> list[int]:@@ -137,6 +171,50 @@ def _native_table_counts(pdf_name: str) -> list[int]:return [sum(block["type"] == "table" for block in page) for page in _native_model_list(pdf_name)]+def test_real_pdf_model_cache_reuses_parse_and_isolates_mutation(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """验证相同文件只预测一次,且调用方修改深拷贝不会污染缓存。"""++ pdf_path = tmp_path / "cache-fixture.pdf"+ pdf_path.write_bytes(b"cache fixture")+ predict_calls: list[object] = []++ class FakePDFDocument:+ """提供缓存测试所需的最小 PDFDocument 上下文。"""++ def __init__(self, _payload: bytes) -> None:+ pass++ def __enter__(self) -> FakePDFDocument:+ return self++ def __exit__(self, *_args: object) -> None:+ return None++ class FakePdfModel:+ """记录预测次数并返回可变模型块。"""++ def predict(self, document: object) -> list[list[dict[str, Any]]]:+ predict_calls.append(document)+ return [[{"type": "text", "content": "stable"}]]++ module = sys.modules[__name__]+ monkeypatch.setattr(module, "PDFDocument", FakePDFDocument)+ monkeypatch.setattr(module, "PdfModel", FakePdfModel)++ first = _cached_model_list_copy(pdf_path)+ second = _cached_model_list_copy(pdf_path)+ first[0][0]["content"] = "changed"+ third = _cached_model_list_copy(pdf_path)++ assert len(predict_calls) == 1+ assert first is not second+ assert second[0][0]["content"] == "stable"+ assert third[0][0]["content"] == "stable"++def _native_page_source(pdf_name: str, page_idx: int) -> models._PageSource:"""读取指定样例页并构造候选检测与认领测试使用的页面源。"""@@ -787,8 +865,8 @@ def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:"""验证 demo3 容器、后续页段落边界及每条原生 source line 均保持稳定。"""pdf_path = Path(__file__).parents[2] / "demo" / "pdfs" / "demo3.pdf"+ model_list = _native_model_list("demo3.pdf")with PDFDocument(str(pdf_path)) as pdf_doc:- model_list = PdfModel().predict(pdf_doc)source_lines_by_page: list[list[models._LineItem]] = []for page_idx in range(pdf_doc.page_count):page_size = pdf_doc.page_size(page_idx)@@ -1702,6 +1780,10 @@ def test_synthetic_cjk_fixture_contains_only_safe_watermarks_and_links() -> None"""验证合成 CJK PDF 仅含安全旋转水印和预期 URI 注解。"""pdf_path = _FIXTURE_PDF_DIR / _CJK_SYNTHETIC_PDF_NAME+ model_list = _txt_model_list(+ _CJK_SYNTHETIC_PDF_NAME,+ pdf_dir=_FIXTURE_PDF_DIR,+ )with PDFDocument(pdf_path.read_bytes()) as document:rotated_lines = ["".join(str(span.get("text", "")) for span in line.get("spans", []))@@ -1709,7 +1791,6 @@ def test_synthetic_cjk_fixture_contains_only_safe_watermarks_and_links() -> Nonefor line in document.get_page_lines(page_index)if float(line.get("rotation", 0.0))]- model_list = PdfModel().predict(document)expected_watermark_row = " ".join([_SAFE_WATERMARK_TEXT] * 4)assert len(rotated_lines) == 16diff --git a/tests/unittest/test_flash_pdf_scripts.py b/tests/unittest/test_flash_pdf_scripts.pyindex b4df2f0d..e5a2aea5 100644--- a/tests/unittest/test_flash_pdf_scripts.py+++ b/tests/unittest/test_flash_pdf_scripts.py@@ -1,5 +1,7 @@from __future__ import annotations+import sys+from collections.abc import Iteratorfrom dataclasses import replacefrom functools import lru_cachefrom pathlib import Path@@ -9,7 +11,6 @@ import pytestfrom pdftext.schema import Bbox, Charfrom mineru.model.flash.pdf.geometry import _rotate_bbox_from_upright-from mineru.model.flash import PdfModelfrom mineru.model.flash.pdf.document import PDFDocumentfrom mineru.model.flash.pdf.models import _AxisLine, _LineItemfrom mineru.model.flash.pdf.pipeline import _analyze_native_document@@ -689,10 +690,22 @@ def test_late_inline_math_region_drops_unrebased_candidate() -> None:assert "_inline_math_regions" not in blocks[0]-def _flash_script_runs(pdf_name: str) -> list[tuple[str, tuple[str, ...]]]:- """解析真实 Flash PDF 并收集最终 TextSpan 上下标。"""+@lru_cache(maxsize=None)+def _flash_script_analysis(+ pdf_name: str,+) -> tuple[tuple[tuple[dict[str, Any], ...], ...], tuple[dict[str, Any], ...]]:+ """一次解析真实 Flash PDF,同时缓存最终页面和逐行脚本诊断。"""++ diagnostics: list[dict[str, Any]] = []with PDFDocument(str(_DEMO_PDF_DIR / pdf_name)) as document:- pages = PdfModel().predict(document)+ pages = _analyze_native_document(document, script_diagnostics=diagnostics)+ return tuple(tuple(page) for page in pages), tuple(diagnostics)+++def _flash_script_runs(pdf_name: str) -> list[tuple[str, tuple[str, ...]]]:+ """从缓存的真实 Flash 页面收集最终 TextSpan 上下标。"""++ pages, _diagnostics = _flash_script_analysis(pdf_name)runs: list[tuple[str, tuple[str, ...]]] = []def walk(value: Any) -> None:@@ -704,7 +717,7 @@ def _flash_script_runs(pdf_name: str) -> list[tuple[str, tuple[str, ...]]]:runs.append((content, styles))for child in value.values():walk(child)- elif isinstance(value, list):+ elif isinstance(value, (list, tuple)):for child in value:walk(child)@@ -712,13 +725,81 @@ def _flash_script_runs(pdf_name: str) -> list[tuple[str, tuple[str, ...]]]:return runs-@lru_cache(maxsize=None)def _flash_script_diagnostics(pdf_name: str) -> tuple[dict[str, Any], ...]:- """解析真实 Flash PDF 并缓存逐行上下标 sidecar。"""- diagnostics: list[dict[str, Any]] = []- with PDFDocument(str(_DEMO_PDF_DIR / pdf_name)) as document:- _analyze_native_document(document, script_diagnostics=diagnostics)- return tuple(diagnostics)+ """返回统一分析缓存中的逐行上下标 sidecar。"""++ _pages, diagnostics = _flash_script_analysis(pdf_name)+ return diagnostics++[email protected](scope="module", autouse=True)+def _clear_real_script_analysis_cache_after_module() -> Iterator[None]:+ """模块结束后释放真实 PDF 页面和脚本诊断缓存。"""++ yield+ _flash_script_analysis.cache_clear()+++def test_real_script_pages_and_diagnostics_share_one_analysis(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ """验证最终脚本 span 与逐行诊断共用同一次真实文档分析。"""++ analyze_calls: list[object] = []++ class FakePDFDocument:+ """提供脚本缓存测试所需的最小上下文。"""++ def __init__(self, path: str) -> None:+ self.path = path++ def __enter__(self) -> FakePDFDocument:+ return self++ def __exit__(self, *_args: object) -> None:+ return None++ def fake_analyze(+ document: object,+ *,+ script_diagnostics: list[dict[str, Any]],+ ) -> list[list[dict[str, Any]]]:+ """记录分析并同时构造页面和诊断。"""++ analyze_calls.append(document)+ script_diagnostics.append(+ {+ "script_lines": [],+ "materialized_ranges": [],+ }+ )+ return [+ [+ {+ "type": "text",+ "content": [+ {+ "type": "text",+ "content": "2",+ "styles": ["superscript"],+ }+ ],+ }+ ]+ ]++ module = sys.modules[__name__]+ monkeypatch.setattr(module, "PDFDocument", FakePDFDocument)+ monkeypatch.setattr(module, "_analyze_native_document", fake_analyze)+ monkeypatch.setattr(module, "_DEMO_PDF_DIR", tmp_path)++ diagnostics = _flash_script_diagnostics("cache-fixture.pdf")+ runs = _flash_script_runs("cache-fixture.pdf")++ assert len(analyze_calls) == 1+ assert diagnostics == ({"script_lines": [], "materialized_ranges": []},)+ assert runs == [("2", ("superscript",))]@pytest.mark.parametrize("pdf_name", tuple(_REVIEWED_SCRIPT_EXPECTATIONS))@@ -791,9 +872,7 @@ def test_general_flash_script_recovery_candidates_materialize(pdf_name: str) ->def test_chinese_paper_page_12_recovers_numbered_formula_regions() -> None:"""验证栏顶公式 6、7、8 被完整认领为 equation,且不吸收相邻正文。"""- diagnostics: list[dict[str, Any]] = []- with PDFDocument(str(_DEMO_PDF_DIR / "中文论文2.pdf")) as document:- pages = _analyze_native_document(document, script_diagnostics=diagnostics)+ pages, diagnostics = _flash_script_analysis("中文论文2.pdf")equations = {tag: blockdiff --git a/tests/unittest/test_native_pdf_table_manifest.py b/tests/unittest/test_native_pdf_table_manifest.pyindex 71ff6dad..a1868e21 100644--- a/tests/unittest/test_native_pdf_table_manifest.py+++ b/tests/unittest/test_native_pdf_table_manifest.py@@ -3,12 +3,15 @@from __future__ import annotations-import jsonimport hashlib+import importlib.util+import jsonimport subprocessimport sysfrom pathlib import Path+from typing import Any+import pytestfrom pypdf import PdfReader@@ -40,6 +43,19 @@ _SENSITIVE_PROBE_HASHES = ()+def _load_evaluator_module() -> Any:+ """按文件路径加载 Native Table evaluator,供内部调用次数单测使用。"""++ spec = importlib.util.spec_from_file_location(+ "_native_pdf_table_manifest_evaluator",+ _EVALUATOR,+ )+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++def _contains_sensitive_probe_hash(text: str) -> bool:"""使用不可逆摘要检查已知敏感片段,避免把原文写入仓库。"""@@ -52,6 +68,97 @@ def _contains_sensitive_probe_hash(text: str) -> bool:return False+def test_native_table_skip_performance_runs_recovery_once(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证 pytest 功能模式只恢复一次,不执行预热或计时。"""++ evaluator = _load_evaluator_module()+ recover_calls: list[object] = []++ def fake_recover(table_input: object) -> dict[str, int]:+ """记录一次恢复并返回可识别结果。"""++ recover_calls.append(table_input)+ return {"call": len(recover_calls)}++ monkeypatch.setattr(evaluator, "recover_native_pdf_table", fake_recover)+ monkeypatch.setattr(evaluator, "_result_signature", lambda result: result)++ actual, duration = evaluator._recover_table_input(+ object(),+ measure_performance=False,+ )++ assert actual == {"call": 1}+ assert duration == 0.0+ assert len(recover_calls) == 1+++def test_native_table_performance_mode_warms_and_times_once(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证显式性能模式保留一次预热和一次正式计时恢复。"""++ evaluator = _load_evaluator_module()+ recover_calls: list[object] = []+ counter = iter((10.0, 12.5))++ def fake_recover(table_input: object) -> dict[str, int]:+ """记录预热和正式恢复。"""++ recover_calls.append(table_input)+ return {"call": len(recover_calls)}++ monkeypatch.setattr(evaluator, "recover_native_pdf_table", fake_recover)+ monkeypatch.setattr(evaluator, "_result_signature", lambda result: result)+ monkeypatch.setattr(evaluator.time, "perf_counter", lambda: next(counter))++ actual, duration = evaluator._recover_table_input(+ object(),+ measure_performance=True,+ )++ assert actual == {"call": 2}+ assert duration == 2.5+ assert len(recover_calls) == 2+++def test_native_table_diagnostics_are_lazy(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """验证候选诊断仅在显式请求或结果不匹配时执行。"""++ evaluator = _load_evaluator_module()+ diagnose_calls: list[object] = []++ def fake_diagnose(table_input: object) -> dict[str, bool]:+ """记录惰性诊断调用。"""++ diagnose_calls.append(table_input)+ return {"diagnosed": True}++ monkeypatch.setattr(evaluator, "diagnose_native_pdf_table", fake_diagnose)+ table_input = object()++ assert evaluator._maybe_diagnose_table_input(+ table_input,+ collect_diagnostics=False,+ mismatch=False,+ ) is None+ assert evaluator._maybe_diagnose_table_input(+ table_input,+ collect_diagnostics=True,+ mismatch=False,+ ) == {"diagnosed": True}+ assert evaluator._maybe_diagnose_table_input(+ table_input,+ collect_diagnostics=False,+ mismatch=True,+ ) == {"diagnosed": True}+ assert diagnose_calls == [table_input, table_input]++def test_repository_native_table_manifest_matches_all_fixtures() -> None:"""验证仓库内 133 表真值及六个 Flash 精确目标全部匹配。"""