Skip to content

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

fix(layout): restore output thresholds and position absorbed images

myhloli1d184043f1f9
diff --git a/mineru/model/layout/pp_doclayout_v2_base.py b/mineru/model/layout/pp_doclayout_v2_base.py
index da2bd9f6..c719dc75 100644
--- a/mineru/model/layout/pp_doclayout_v2_base.py
+++ b/mineru/model/layout/pp_doclayout_v2_base.py
@@ -52,33 +52,34 @@ PP_DOCLAYOUT_V2_LABELS = [
PP_DOCLAYOUT_V2_LABEL_TO_ID = {label: index for index, label in enumerate(PP_DOCLAYOUT_V2_LABELS)}
-# 模型分类阈值,仅将行内公式提高到 0.45,减少低置信度公式误检。
+# MinerU 输出准入阈值:默认 0.45,摘要使用 0.5,正文、标题和行间公式使用 0.4。
+# 该表独立于模型内部阅读顺序模块的分类配置。
DEFAULT_CLASS_THRESHOLDS = [
0.5, # 0 abstract
- 0.5, # 1 algorithm
- 0.5, # 2 aside_text
- 0.5, # 3 chart
- 0.5, # 4 content
+ 0.45, # 1 algorithm
+ 0.45, # 2 aside_text
+ 0.45, # 3 chart
+ 0.45, # 4 content
0.4, # 5 display_formula
0.4, # 6 doc_title
- 0.5, # 7 figure_title
- 0.5, # 8 footer
- 0.5, # 9 footer_image
- 0.5, # 10 footnote
- 0.5, # 11 formula_number
- 0.5, # 12 header
- 0.5, # 13 header_image
- 0.5, # 14 image
+ 0.45, # 7 figure_title
+ 0.45, # 8 footer
+ 0.45, # 9 footer_image
+ 0.45, # 10 footnote
+ 0.45, # 11 formula_number
+ 0.45, # 12 header
+ 0.45, # 13 header_image
+ 0.45, # 14 image
0.45, # 15 inline_formula
- 0.5, # 16 number
+ 0.45, # 16 number
0.4, # 17 paragraph_title
- 0.5, # 18 reference
- 0.5, # 19 reference_content
+ 0.45, # 18 reference
+ 0.45, # 19 reference_content
0.45, # 20 seal
- 0.5, # 21 table
+ 0.45, # 21 table
0.4, # 22 text
0.4, # 23 vertical_text
- 0.5, # 24 vision_footnote
+ 0.45, # 24 vision_footnote
]
# Reading-order head class remap used by the original upstream model.
@@ -753,8 +754,10 @@ class PPDocLayoutV2PostProcessor:
boxes: List[Dict],
drop_inline_formula: bool = True,
) -> List[Dict]:
+ """沿用既有过滤判定,仅让吞并子图的 image 大框继承最早子图位置。"""
filtered_boxes = [dict(box) for box in boxes if not cls._is_reference_box(box)]
dropped_indexes = set()
+ image_positions: dict[int, int] = {}
for i in range(len(filtered_boxes)):
if i in dropped_indexes:
@@ -797,11 +800,21 @@ class PPDocLayoutV2PostProcessor:
if "table" not in labels or labels <= {"table", "image", "seal", "chart"}:
continue
if box_area_i >= box_area_j:
- dropped_indexes.add(j)
+ keep_index, drop_index = i, j
else:
- dropped_indexes.add(i)
-
- kept_boxes = [box for index, box in enumerate(filtered_boxes) if index not in dropped_indexes]
+ keep_index, drop_index = j, i
+ dropped_indexes.add(drop_index)
+ if labels == {"image"} and box_area_i != box_area_j:
+ # 不计大图原位置;子图此前吞并过其他图时,继续传递其已继承的位置。
+ child_position = image_positions.get(drop_index, drop_index)
+ image_positions[keep_index] = min(image_positions.get(keep_index, child_position), child_position)
+
+ # 判定全部完成后才重排,避免位置调整改变后续配对、吞并及保留框选择。
+ kept_indexes = sorted(
+ (index for index in range(len(filtered_boxes)) if index not in dropped_indexes),
+ key=lambda index: image_positions.get(index, index),
+ )
+ kept_boxes = [filtered_boxes[index] for index in kept_indexes]
return cls._renumber_indices(kept_boxes)
# ------------------------------------------------------------------
diff --git a/mineru/model/layout/pp_doclayout_v2_onnx.py b/mineru/model/layout/pp_doclayout_v2_onnx.py
index b60d73e7..720fa5f4 100644
--- a/mineru/model/layout/pp_doclayout_v2_onnx.py
+++ b/mineru/model/layout/pp_doclayout_v2_onnx.py
@@ -52,7 +52,7 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
intra_op_num_threads: int = 0,
config_path: str | None = None,
) -> None:
- """加载 CPU 检测图及官方预处理配置,仅将行内公式分类阈值提高到 0.45。"""
+ """加载 CPU 检测图及官方预处理配置,输出筛选独立使用共享准入阈值。"""
self.device = "cpu"
self.use_paddlex_filter_boxes = use_paddlex_filter_boxes
self.model_path = str(weight)
@@ -102,24 +102,14 @@ class PPDocLayoutV2LayoutModelONNX(PPDocLayoutV2PostProcessor):
@staticmethod
def _filter_by_class_thresholds(sample: np.ndarray) -> np.ndarray:
- """按最高分类分数确定候选有效性,再应用仅提高行内公式门槛的分类阈值。"""
+ """按每行标签的准入阈值独立筛选,保留模型原始坐标及排序键。"""
if len(sample) == 0:
return sample
labels = sample[:, 0].astype(np.int64)
scores = sample[:, 1]
thresholds = np.asarray(DEFAULT_CLASS_THRESHOLDS, dtype=scores.dtype)[labels]
- # 同一检测候选的多标签行共享原始坐标和阅读顺序键,须在逐页范围内分组。
- _, query_ids = np.unique(sample[:, 2:8], axis=0, return_inverse=True)
- # 与 argmax 的同分规则一致:最高分相同时,较小类别编号作为候选主类别。
- primary_order = np.lexsort((labels, -scores, query_ids))
- sorted_query_ids = query_ids[primary_order]
- first_in_query = np.concatenate(([True], sorted_query_ids[1:] != sorted_query_ids[:-1]))
- primary_indices = primary_order[first_in_query]
- valid_queries = np.empty(len(primary_indices), dtype=bool)
- valid_queries[query_ids[primary_indices]] = scores[primary_indices] >= thresholds[primary_indices]
- keep = valid_queries[query_ids] & (scores >= thresholds)
- return sample[keep]
+ return sample[scores >= thresholds]
def _run_session(self, pixel_values: np.ndarray, target_sizes: Sequence[Tuple[int, int]]) -> List[Dict[str, np.ndarray]]:
"""跑一次 ONNX 推理,解析输出为内部 prediction dict。
diff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.py
index 21bab64a..7d5b3f7a 100644
--- a/mineru/model/layout/pp_doclayoutv2.py
+++ b/mineru/model/layout/pp_doclayoutv2.py
@@ -59,7 +59,7 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
imgsz: Tuple[int, int] = DEFAULT_IMAGE_SIZE,
use_paddlex_filter_boxes: bool = True,
) -> None:
- """加载官方模型配置,检测筛选与阅读顺序均使用模型分类阈值。"""
+ """加载模型及其阅读顺序配置,最终输出另按共享准入阈值筛选。"""
self.device = device or "cpu"
self.use_paddlex_filter_boxes = use_paddlex_filter_boxes
self.model_dir = weight
@@ -128,7 +128,7 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
outputs: PPDocLayoutV2ForObjectDetectionOutput,
target_sizes: Sequence[Tuple[int, int]],
) -> List[Dict[str, torch.Tensor]]:
- """按模型分类阈值筛选有效候选,防止排序时的无效框重新进入输出。"""
+ """按各标签的输出准入阈值独立筛选,沿用模型给出的阅读顺序。"""
boxes = outputs.pred_boxes
logits = outputs.logits
order_logits = outputs.order_logits
@@ -143,22 +143,17 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):
num_top_queries = logits.shape[1]
num_classes = logits.shape[2]
- class_thresholds = torch.as_tensor(self.config.class_thresholds, dtype=torch.float32, device=logits.device)
- # 与官方阅读顺序网络一致:用最高分所属类别判断候选框是否有效。
- max_logits, class_ids = logits.max(dim=-1)
- valid_queries = max_logits.sigmoid() >= class_thresholds[class_ids]
+ class_thresholds = torch.as_tensor(DEFAULT_CLASS_THRESHOLDS, dtype=torch.float32, device=logits.device)
scores = torch.sigmoid(logits)
scores, index = torch.topk(scores.flatten(1), num_top_queries, dim=-1)
labels = index % num_classes
index = index // num_classes
boxes = boxes.gather(dim=1, index=index.unsqueeze(-1).repeat(1, 1, boxes.shape[-1]))
order_seqs = order_seqs.gather(dim=1, index=index)
- valid_candidates = valid_queries.gather(dim=1, index=index)
results = []
- for score, label, box, order_seq, valid_candidate in zip(scores, labels, boxes, order_seqs, valid_candidates):
- # 次高分标签既要达到自身阈值,也不能重新放行排序阶段已排除的候选框。
- keep = valid_candidate & (score >= class_thresholds[label])
+ for score, label, box, order_seq in zip(scores, labels, boxes, order_seqs):
+ keep = score >= class_thresholds[label]
order_seq = order_seq[keep]
order_seq, indices = torch.sort(order_seq)
results.append(
diff --git a/tests/fixtures/pp_doclayoutv2/demo2_page4.json b/tests/fixtures/pp_doclayoutv2/demo2_page4.json
new file mode 100644
index 00000000..e4152b74
--- /dev/null
+++ b/tests/fixtures/pp_doclayoutv2/demo2_page4.json
@@ -0,0 +1,101 @@
+{
+ "source": "demo/pdfs/demo2.pdf",
+ "page": 4,
+ "dpi": 200,
+ "image_size": [2200, 1700],
+ "description": "真实检测输出逐标签应用约定阈值后的候选;预期顺序仅将左栏整图移到首个被吞并子图的位置。",
+ "backends": {
+ "torch": {
+ "raw_rows": [
+ ["image", 0.4675, [140, 280, 812, 1346]],
+ ["text", 0.9741, [127, 159, 837, 260]],
+ ["image", 0.797, [144, 281, 474, 531]],
+ ["image", 0.8334, [479, 280, 809, 531]],
+ ["image", 0.8362, [144, 541, 475, 792]],
+ ["image", 0.8359, [478, 541, 810, 793]],
+ ["image", 0.7719, [144, 800, 476, 1054]],
+ ["image", 0.6764, [478, 802, 807, 1056]],
+ ["image", 0.7513, [142, 1061, 477, 1324]],
+ ["figure_title", 0.5446, [260, 1319, 366, 1347]],
+ ["image", 0.8444, [477, 1064, 809, 1347]],
+ ["inline_formula", 0.5583, [219, 1389, 264, 1419]],
+ ["figure_title", 0.9751, [127, 1356, 837, 1492]],
+ ["inline_formula", 0.6659, [236, 1421, 288, 1453]],
+ ["inline_formula", 0.5007, [191, 1455, 238, 1487]],
+ ["inline_formula", 0.5288, [191, 1455, 299, 1488]],
+ ["inline_formula", 0.6974, [524, 1420, 571, 1453]],
+ ["text", 0.9881, [127, 1519, 838, 1887]],
+ ["text", 0.9799, [127, 1885, 840, 2020]],
+ ["figure_title", 0.5526, [1178, 151, 1283, 178]],
+ ["chart", 0.8102, [936, 187, 1490, 382]],
+ ["figure_title", 0.6419, [1172, 385, 1288, 413]],
+ ["chart", 0.8047, [866, 422, 1491, 615]],
+ ["figure_title", 0.5604, [1173, 619, 1289, 645]],
+ ["chart", 0.8193, [867, 657, 1490, 849]],
+ ["inline_formula", 0.5381, [1297, 896, 1480, 930]],
+ ["figure_title", 0.976, [856, 863, 1570, 1034]],
+ ["figure_title", 0.9644, [858, 1065, 1568, 1134]],
+ ["inline_formula", 0.5229, [953, 1253, 981, 1277]],
+ ["inline_formula", 0.5692, [953, 1279, 981, 1303]],
+ ["inline_formula", 0.4864, [956, 1304, 979, 1325]],
+ ["inline_formula", 0.5034, [955, 1330, 979, 1352]],
+ ["table", 0.9804, [913, 1160, 1515, 1404]],
+ ["inline_formula", 0.4656, [957, 1378, 979, 1401]],
+ ["vision_footnote", 0.914, [933, 1407, 1519, 1486]],
+ ["inline_formula", 0.6421, [1228, 1437, 1254, 1461]],
+ ["inline_formula", 0.6616, [1294, 1436, 1323, 1462]],
+ ["chart", 0.9501, [931, 1536, 1499, 1733]],
+ ["figure_title", 0.9744, [857, 1749, 1569, 1853]],
+ ["text", 0.9752, [857, 1918, 1571, 2021]]
+ ],
+ "threshold_only_source_indices": [1, 2, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
+ "expected_source_indices": [2, 1, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
+ },
+ "onnx": {
+ "raw_rows": [
+ ["image", 0.4666, [140, 280, 812, 1346]],
+ ["text", 0.9742, [127, 159, 837, 260]],
+ ["image", 0.7962, [144, 281, 474, 531]],
+ ["image", 0.8331, [479, 280, 809, 531]],
+ ["image", 0.8354, [144, 541, 475, 792]],
+ ["image", 0.8356, [478, 541, 810, 793]],
+ ["image", 0.7716, [144, 800, 476, 1054]],
+ ["image", 0.6766, [478, 802, 807, 1056]],
+ ["image", 0.7512, [142, 1061, 477, 1324]],
+ ["figure_title", 0.544, [260, 1319, 366, 1347]],
+ ["image", 0.844, [477, 1063, 809, 1347]],
+ ["inline_formula", 0.5592, [219, 1389, 264, 1419]],
+ ["figure_title", 0.9751, [127, 1356, 837, 1492]],
+ ["inline_formula", 0.6663, [236, 1421, 288, 1453]],
+ ["inline_formula", 0.5036, [191, 1455, 238, 1487]],
+ ["inline_formula", 0.5255, [191, 1455, 299, 1488]],
+ ["inline_formula", 0.6977, [524, 1420, 571, 1453]],
+ ["text", 0.9881, [127, 1519, 838, 1887]],
+ ["text", 0.9799, [127, 1885, 840, 2020]],
+ ["figure_title", 0.5507, [1178, 151, 1283, 178]],
+ ["chart", 0.8099, [936, 187, 1490, 382]],
+ ["figure_title", 0.6411, [1172, 385, 1288, 413]],
+ ["chart", 0.8047, [866, 422, 1491, 615]],
+ ["figure_title", 0.5592, [1173, 619, 1289, 645]],
+ ["chart", 0.8197, [867, 657, 1490, 849]],
+ ["figure_title", 0.9761, [856, 863, 1570, 1034]],
+ ["inline_formula", 0.5165, [1297, 896, 1480, 930]],
+ ["figure_title", 0.9644, [858, 1065, 1568, 1134]],
+ ["inline_formula", 0.526, [953, 1253, 981, 1277]],
+ ["inline_formula", 0.5721, [953, 1279, 981, 1303]],
+ ["inline_formula", 0.4893, [956, 1304, 979, 1325]],
+ ["inline_formula", 0.5053, [955, 1330, 979, 1352]],
+ ["table", 0.9804, [913, 1160, 1515, 1404]],
+ ["inline_formula", 0.4694, [957, 1378, 979, 1401]],
+ ["vision_footnote", 0.9137, [933, 1407, 1519, 1486]],
+ ["inline_formula", 0.641, [1228, 1437, 1254, 1461]],
+ ["inline_formula", 0.6602, [1294, 1436, 1323, 1462]],
+ ["chart", 0.9499, [931, 1536, 1499, 1733]],
+ ["figure_title", 0.9744, [857, 1749, 1569, 1853]],
+ ["text", 0.9752, [857, 1918, 1571, 2021]]
+ ],
+ "threshold_only_source_indices": [1, 2, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
+ "expected_source_indices": [2, 1, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
+ }
+ }
+}
diff --git a/tests/unittest/test_pp_doclayoutv2_postprocess.py b/tests/unittest/test_pp_doclayoutv2_postprocess.py
index 1ffd58f2..8f1d2728 100644
--- a/tests/unittest/test_pp_doclayoutv2_postprocess.py
+++ b/tests/unittest/test_pp_doclayoutv2_postprocess.py
@@ -3,18 +3,19 @@
from __future__ import annotations
+import json
from copy import deepcopy
from itertools import permutations
-import json
from pathlib import Path
from typing import Any
+from unittest.mock import Mock
+import numpy as np
import pytest
from PIL import Image
from mineru.backend.analysis.pdf.formulas import _build_formula_inputs
from mineru.backend.analysis.pdf.layout import _build_vl_style_layout_blocks
-
from mineru.model.layout.pp_doclayout_v2_base import (
PP_DOCLAYOUT_V2_LABEL_TO_ID,
PPDocLayoutV2PostProcessor,
@@ -304,3 +305,179 @@ def test_final_filter_removes_text_duplicates_created_by_relabeling(processor: t
result = processor._apply_layout_post_process(boxes, image_size=(220, 200))
assert [(box["label"], box["bbox"]) for box in result] == [("text", [0, 150, 100, 165]), ("footnote", [0, 170, 100, 195])]
assert [box["index"] for box in result] == [1, 2]
+
+
+ ("input_order", "expected_order"),
+ [
+ (["parent", "leading", "child", "trailing"], ["leading", "parent", "trailing"]),
+ (["leading", "child", "middle", "parent", "trailing"], ["leading", "parent", "middle", "trailing"]),
+ (
+ ["parent", "leading", "child", "middle", "second_child", "trailing"],
+ ["leading", "parent", "middle", "trailing"],
+ ),
+ ],
+)
+def test_image_absorption_uses_earliest_child_position(
+ processor: type[PPDocLayoutV2PostProcessor], input_order: list[str], expected_order: list[str]
+) -> None:
+ """大图无论位于子图之前或之后,都取最早被吞并子图的位置且不改变其他块顺序。"""
+ boxes = {
+ "parent": _layout_box("image", (0, 0, 100, 100), index=0),
+ "child": _layout_box("image", (10, 10, 40, 40), index=0),
+ "second_child": _layout_box("image", (50, 50, 80, 80), index=0),
+ "leading": _layout_box("text", (200, 0, 240, 20), index=0),
+ "middle": _layout_box("text", (200, 30, 240, 50), index=0),
+ "trailing": _layout_box("text", (200, 60, 240, 80), index=0),
+ }
+ source = [dict(boxes[name], index=index) for index, name in enumerate(input_order, start=1)]
+ original = deepcopy(source)
+
+ result = processor._apply_paddlex_filter_boxes(source, drop_inline_formula=False)
+
+ assert result == [dict(boxes[name], index=index) for index, name in enumerate(expected_order, start=1)]
+ assert source == original
+
+
+def test_image_absorption_propagates_inherited_child_position(processor: type[PPDocLayoutV2PostProcessor]) -> None:
+ """中图先吞小图再被大图吞并时,传递小图位置而非中图原先抢占的位置。"""
+ middle = _layout_box("image", (10, 10, 60, 60), index=1)
+ leading = _layout_box("text", (200, 0, 240, 20), index=2)
+ child = _layout_box("image", (20, 20, 40, 40), index=3)
+ parent = _layout_box("image", (0, 0, 100, 100), index=4)
+ trailing = _layout_box("text", (200, 30, 240, 50), index=5)
+
+ result = processor._apply_paddlex_filter_boxes([middle, leading, child, parent, trailing], drop_inline_formula=False)
+
+ assert result == [dict(leading, index=1), dict(parent, index=2), dict(trailing, index=3)]
+
+
+def test_image_absorption_positions_independent_groups(processor: type[PPDocLayoutV2PostProcessor]) -> None:
+ """多个图组各自继承其子图位置,图组间正文保持原有相对顺序。"""
+ left = _layout_box("image", (0, 0, 100, 100), index=1)
+ right = _layout_box("image", (200, 0, 300, 100), index=2)
+ leading = _layout_box("text", (400, 0, 440, 20), index=3)
+ right_child = _layout_box("image", (210, 10, 240, 40), index=4)
+ between = _layout_box("text", (400, 30, 440, 50), index=5)
+ left_child = _layout_box("image", (10, 10, 40, 40), index=6)
+ trailing = _layout_box("text", (400, 60, 440, 80), index=7)
+
+ result = processor._apply_paddlex_filter_boxes(
+ [left, right, leading, right_child, between, left_child, trailing], drop_inline_formula=False
+ )
+
+ assert result == [dict(box, index=index) for index, box in enumerate([leading, right, between, left, trailing], start=1)]
+
+
[email protected](("child_x", "absorbed"), [(72, False), (71, True)])
+def test_image_position_inheritance_preserves_existing_overlap_rule(
+ processor: type[PPDocLayoutV2PostProcessor], child_x: int, absorbed: bool
+) -> None:
+ """继续使用大于 0.7 的既有重叠判定,既不降低门槛也不额外要求八成或完全包含。"""
+ parent = _layout_box("image", (0, 0, 100, 100), index=1)
+ text = _layout_box("text", (200, 0, 240, 20), index=2)
+ child = _layout_box("image", (child_x, 10, child_x + 40, 50), index=3)
+
+ result = processor._apply_paddlex_filter_boxes([parent, text, child], drop_inline_formula=False)
+
+ expected = [text, parent] if absorbed else [parent, text, child]
+ assert result == [dict(box, index=index) for index, box in enumerate(expected, start=1)]
+
+
+def test_equal_area_image_deduplication_does_not_inherit_position(processor: type[PPDocLayoutV2PostProcessor]) -> None:
+ """等面积图片重复框沿用现有首框选择,不能把去重变成吞并定位。"""
+ parent = _layout_box("image", (0, 0, 100, 100), index=1, score=0.8)
+ text = _layout_box("text", (200, 0, 240, 20), index=2)
+ duplicate = _layout_box("image", (0, 0, 100, 100), index=3, score=0.9)
+
+ result = processor._apply_paddlex_filter_boxes([parent, text, duplicate], drop_inline_formula=False)
+
+ assert result == [parent, text]
+
+
[email protected]("label", ["text", "abstract", "table", "chart", "seal", "display_formula"])
+def test_non_image_absorption_keeps_parent_position(processor: type[PPDocLayoutV2PostProcessor], label: str) -> None:
+ """其他类别仍按原规则删除小框并保留大框自身位置,不应用图片位置继承。"""
+ parent = _layout_box(label, (0, 0, 100, 100), index=1)
+ text = _layout_box("text", (200, 0, 240, 20), index=2)
+ child = _layout_box(label, (10, 10, 40, 40), index=3)
+
+ result = processor._apply_paddlex_filter_boxes([parent, text, child], drop_inline_formula=False)
+
+ assert result == [parent, text]
+
+
[email protected]("backend", ["onnx", pytest.param("torch", marks=pytest.mark.torch)])
[email protected]("use_filter", [False, True])
+def test_layout_batch_respects_image_absorption_filter_switch(
+ monkeypatch: pytest.MonkeyPatch, backend: str, use_filter: bool
+) -> None:
+ """通过真实批量入口验证关闭过滤时不吞并也不重定位,启用时才继承子图位置。"""
+ raw = [
+ _layout_box("image", (0, 40, 100, 100), index=1),
+ _layout_box("text", (0, 0, 100, 20), index=2),
+ _layout_box("image", (10, 50, 30, 70), index=3),
+ ]
+ if backend == "torch":
+ torch = pytest.importorskip("torch")
+ pytest.importorskip("transformers", minversion="5.10.1")
+ from mineru.model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel
+
+ model = object.__new__(PPDocLayoutV2LayoutModel)
+ model.device = "cpu"
+ model.model = Mock()
+ pixels = torch.zeros((3, 16, 16))
+ monkeypatch.setattr(model, "_post_process_object_detection", Mock(return_value=[{}]))
+ else:
+ pytest.importorskip("onnxruntime")
+ from mineru.model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX
+
+ model = object.__new__(PPDocLayoutV2LayoutModelONNX)
+ pixels = np.zeros((3, 16, 16), dtype=np.float32)
+ monkeypatch.setattr(model, "_run_session", Mock(return_value=[{}]))
+ model.use_paddlex_filter_boxes = True
+ monkeypatch.setattr(model, "_preprocess_single_image", Mock(return_value=(pixels, (200, 200))))
+ monkeypatch.setattr(model, "_parse_prediction", Mock(return_value=deepcopy(raw)))
+
+ with Image.new("RGB", (200, 200)) as image:
+ result = model.batch_predict([image], use_paddlex_filter_boxes=use_filter)[0]
+
+ expected = [dict(raw[1], index=1), dict(raw[0], index=2)] if use_filter else raw
+ assert result == expected
+
+
[email protected]("detection_backend", ["torch", "onnx"])
+def test_demo2_image_absorption_restores_order_and_common_block_inputs(
+ processor: type[PPDocLayoutV2PostProcessor], detection_backend: str
+) -> None:
+ """复放 demo2 第四页真实框,整图移到正文后且其余 28 块及共用布局输入保持稳定。"""
+ fixture = json.loads((Path(__file__).parents[1] / "fixtures/pp_doclayoutv2/demo2_page4.json").read_text())
+ page = fixture["backends"][detection_backend]
+ raw = [
+ _layout_box(label, tuple(bbox), index=index, score=score)
+ for index, (label, score, bbox) in enumerate(page["raw_rows"], start=1)
+ ]
+ original = deepcopy(raw)
+
+ processed = processor._apply_layout_post_process(
+ processor._apply_paddlex_filter_boxes(raw, drop_inline_formula=False), image_size=tuple(fixture["image_size"])
+ )
+
+ expected = [
+ dict(raw[source_index - 1], index=index) for index, source_index in enumerate(page["expected_source_indices"], start=1)
+ ]
+ threshold_only = [
+ dict(raw[source_index - 1], index=index)
+ for index, source_index in enumerate(page["threshold_only_source_indices"], start=1)
+ ]
+ assert raw == original
+ assert processed == expected
+ assert len(processed) == 30
+ assert processed[2:] == threshold_only[2:]
+ assert [box["label"] for box in processed[:2]] == ["text", "image"]
+ assert sum(box["label"] == "image" for box in processed) == 1
+ assert sum(box["label"] == "chart" and box["bbox"][1] < 1000 for box in processed) == 3
+ with Image.new("RGB", tuple(reversed(fixture["image_size"]))) as image:
+ blocks = _build_vl_style_layout_blocks([processed], [image])[0]
+ assert [block["type"] for block in blocks[:2]] == [BlockType.TEXT, BlockType.IMAGE]
+ assert blocks[1]["bbox"] == [0.082, 0.127, 0.478, 0.612]
diff --git a/tests/unittest/test_pp_doclayoutv2_thresholds.py b/tests/unittest/test_pp_doclayoutv2_thresholds.py
index 50912efd..305ab09c 100644
--- a/tests/unittest/test_pp_doclayoutv2_thresholds.py
+++ b/tests/unittest/test_pp_doclayoutv2_thresholds.py
@@ -1,4 +1,4 @@
-"""验证模型分类阈值与阅读顺序有效候选在两种推理后端保持一致。"""
+"""验证两种推理后端按相同输出门槛独立筛选标签,并保留模型排序。"""
from __future__ import annotations
@@ -64,8 +64,14 @@ def _predict(backend: str, probabilities: np.ndarray) -> dict[str, Any]:
@pytest.mark.parametrize("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])
@pytest.mark.parametrize("cls_id", range(len(PP_DOCLAYOUT_V2_LABELS)), ids=PP_DOCLAYOUT_V2_LABELS)
def test_class_threshold_boundaries(backend: str, cls_id: int) -> None:
- """逐类验证低于阈值拒绝,等于阈值和高于阈值均可保留。"""
- threshold = DEFAULT_CLASS_THRESHOLDS[cls_id]
+ """逐类验证约定的输出门槛:摘要 0.5、五类正文标题公式 0.4、其余 0.45。"""
+ label = PP_DOCLAYOUT_V2_LABELS[cls_id]
+ if label == "abstract":
+ threshold = 0.5
+ elif label in {"text", "vertical_text", "doc_title", "paragraph_title", "display_formula"}:
+ threshold = 0.4
+ else:
+ threshold = 0.45
probabilities = np.full((3, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
probabilities[:, cls_id] = [threshold - 0.001, threshold, threshold + 0.001]
@@ -91,8 +97,8 @@ def test_inline_formula_uses_045_without_changing_other_class_thresholds(backend
@pytest.mark.parametrize("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])
-def test_invalid_primary_class_cannot_be_reintroduced_by_secondary_label(backend: str) -> None:
- """摘要主类别未达标时,即使次高正文类别达标也不能重新进入输出。"""
+def test_secondary_label_is_kept_when_primary_class_is_below_its_threshold(backend: str) -> None:
+ """摘要主类别未达标不再否决候选,达到正文门槛的次高标签仍可输出。"""
probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
probabilities[0, 17] = 0.9
probabilities[1, 0] = 0.49
@@ -100,7 +106,7 @@ def test_invalid_primary_class_cannot_be_reintroduced_by_secondary_label(backend
result = _predict(backend, probabilities)
- assert result["labels"].tolist() == [17]
+ assert result["labels"].tolist() == [17, 22]
@pytest.mark.parametrize("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])
@@ -115,17 +121,19 @@ def test_summary_page_scores_restore_title_and_four_paragraphs(backend: str) ->
result = _predict(backend, probabilities)
- assert result["labels"].tolist() == [17, 22, 22, 22, 22, 8, 8]
+ assert result["labels"][:5].tolist() == [17, 22, 22, 22, 22]
+ # 页脚图片现在达到 0.45 输出门槛,后续几何去重仍会保留更高分的页脚文本。
+ assert sorted(result["labels"][5:].tolist()) == [8, 8, 9]
np.testing.assert_allclose(result["scores"][1], 0.4426, rtol=0, atol=1e-7)
@pytest.mark.parametrize("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])
-def test_valid_primary_keeps_only_secondary_labels_above_their_own_threshold(backend: str) -> None:
- """有效候选保留达到自身阈值的次高正文标签,拒绝未达标的页眉标签。"""
+def test_secondary_labels_use_their_own_output_thresholds(backend: str) -> None:
+ """各标签分别筛选,保留达到 0.4 的正文并拒绝低于 0.45 的页眉。"""
probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
probabilities[0, 0] = 0.6
probabilities[0, 22] = 0.44
- probabilities[0, 12] = 0.49
+ probabilities[0, 12] = 0.449
result = _predict(backend, probabilities)
@@ -133,30 +141,30 @@ def test_valid_primary_keeps_only_secondary_labels_above_their_own_threshold(bac
@pytest.mark.parametrize("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])
[email protected](("first_cls", "second_cls", "expected"), [(0, 22, []), (6, 8, [6])])
-def test_primary_class_ties_use_the_smallest_class_id(
- backend: str, first_cls: int, second_cls: int, expected: list[int]
-) -> None:
- """最高分同分时按较小类别编号判断有效性,与模型 argmax 规则一致。"""
[email protected](("first_cls", "second_cls", "expected"), [(0, 22, [22]), (6, 8, [6, 8]), (0, 12, [12])])
+def test_tied_labels_are_filtered_independently(backend: str, first_cls: int, second_cls: int, expected: list[int]) -> None:
+ """同分标签分别按自身门槛准入,不再由较小类别编号决定整个候选的有效性。"""
probabilities = np.full((4, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
probabilities[0, first_cls] = probabilities[0, second_cls] = 0.45
result = _predict(backend, probabilities)
- assert result["labels"].tolist() == expected
+ assert sorted(result["labels"].tolist()) == expected
@pytest.mark.torch
-def test_torch_uses_loaded_model_thresholds() -> None:
- """Torch 按已加载模型配置筛选,不以共享默认常量覆盖模型自带阈值。"""
- probabilities = np.full((1, 1, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
+def test_torch_output_thresholds_are_independent_of_loaded_model_configuration() -> None:
+ """模型内部门槛不覆盖输出策略,正文仍按 0.4、图片仍按 0.45 筛选。"""
+ probabilities = np.full((1, 2, len(PP_DOCLAYOUT_V2_LABELS)), 0.001, dtype=np.float32)
probabilities[0, 0, 22] = 0.6
+ probabilities[0, 1, 14] = 0.449
thresholds = list(DEFAULT_CLASS_THRESHOLDS)
thresholds[22] = 0.7
+ thresholds[14] = 0.1
result = _torch_predictions(probabilities, class_thresholds=thresholds)[0]
- assert result["labels"].tolist() == []
+ assert result["labels"].tolist() == [22]
@pytest.mark.torch
@@ -171,8 +179,8 @@ def test_torch_empty_and_all_rejected_candidates(query_count: int) -> None:
assert all(result["labels"].numel() == 0 and result["boxes"].shape == (0, 4) for result in results)
-def test_onnx_groups_candidates_with_coordinates_and_both_order_keys() -> None:
- """坐标相同而排序键不同或排序键相同而坐标不同的候选必须独立判断。"""
+def test_onnx_filters_labels_independently_of_shared_coordinates_and_order_keys() -> None:
+ """坐标及排序键相同也逐行筛选,不再因同组摘要未达标而删除正文标签。"""
rows = np.asarray(
[
[0, 0.49, 1, 2, 3, 4, 0, 0],
@@ -185,21 +193,44 @@ def test_onnx_groups_candidates_with_coordinates_and_both_order_keys() -> None:
result = _onnx_predictions(rows, [4])[0]
- assert result["labels"].tolist() == [22, 22]
- np.testing.assert_array_equal(result["boxes"], [[1, 2, 3, 4], [10, 2, 30, 4]])
+ assert result["labels"].tolist() == [22, 22, 22]
+ np.testing.assert_array_equal(result["boxes"], [[1, 2, 3, 4], [1, 2, 3, 4], [10, 2, 30, 4]])
-def test_onnx_candidate_validity_is_isolated_by_page() -> None:
- """相同框和排序键跨页出现时独立筛选,同时保留零框页和全过滤页。"""
+def test_onnx_threshold_filtering_is_isolated_by_page() -> None:
+ """逐页独立筛选标签,同时保留零框页和全部候选未达标的页面。"""
rows = np.asarray(
- [[0, 0.49, 1, 2, 3, 4, 0, 0], [22, 0.44, 1, 2, 3, 4, 0, 0], [22, 0.44, 1, 2, 3, 4, 0, 0]],
+ [
+ [0, 0.49, 1, 2, 3, 4, 0, 0],
+ [22, 0.44, 1, 2, 3, 4, 0, 0],
+ [22, 0.44, 1, 2, 3, 4, 0, 0],
+ [0, 0.49, 1, 2, 3, 4, 0, 0],
+ ],
dtype=np.float32,
)
- results = _onnx_predictions(rows, [2, 0, 1])
+ results = _onnx_predictions(rows, [2, 0, 1, 1])
+
+ assert [result["labels"].tolist() for result in results] == [[22], [], [22], []]
+ assert all(results[index]["boxes"].shape == (0, 4) for index in [1, 3])
+
+
+def test_onnx_retains_model_reading_order_after_threshold_filtering() -> None:
+ """筛选后沿用模型双排序键,不按置信度或类别重新排列被保留的框。"""
+ rows = np.asarray(
+ [
+ [14, 0.47, 10, 0, 20, 10, 9, 0],
+ [22, 0.44, 20, 0, 30, 10, 3, 0],
+ [0, 0.49, 30, 0, 40, 10, 2, 0],
+ [21, 0.45, 40, 0, 50, 10, 7, 0],
+ ],
+ dtype=np.float32,
+ )
+
+ result = _onnx_predictions(rows, [4])[0]
- assert [result["labels"].tolist() for result in results] == [[], [], [22]]
- assert all(result["boxes"].shape == (0, 4) for result in results[:2])
+ assert result["labels"].tolist() == [22, 21, 14]
+ np.testing.assert_array_equal(result["boxes"][:, 0], [20, 40, 10])
@pytest.mark.parametrize("backend", [pytest.param("torch", marks=pytest.mark.torch), "onnx"])
diff --git a/tests/unittest/test_transformers5_models.py b/tests/unittest/test_transformers5_models.py
index 6f2e0794..aed3464e 100644
--- a/tests/unittest/test_transformers5_models.py
+++ b/tests/unittest/test_transformers5_models.py
@@ -62,6 +62,8 @@ def test_layout_loader_adapts_position_embeddings_for_mps_and_xpu(monkeypatch: p
config = SimpleNamespace(class_thresholds=list(layout.DEFAULT_CLASS_THRESHOLDS))
config.class_thresholds[15] = 0.4
config.class_thresholds[22] = 0.7
+ config.class_thresholds[14] = 0.5
+ config.class_thresholds[3] = 0.5
expected_thresholds = list(config.class_thresholds)
expected_thresholds[15] = 0.45
load = Mock(return_value=model)