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: preserve footnote formulas and deduplicate nested text layouts
myhlolic5ee779fa617
diff --git a/mineru/model/layout/pp_doclayout_v2_base.py b/mineru/model/layout/pp_doclayout_v2_base.pyindex f72fa834..da2bd9f6 100644--- a/mineru/model/layout/pp_doclayout_v2_base.py+++ b/mineru/model/layout/pp_doclayout_v2_base.py@@ -147,6 +147,23 @@ class PPDocLayoutV2PostProcessor:"number","aside_text",}+ # 仅平铺文本块允许按同类完整包含去重,公式与视觉/列表容器保留各自层级。+ NESTED_TEXT_LABELS = frozenset(+ {+ "text",+ "vertical_text",+ "abstract",+ "doc_title",+ "paragraph_title",+ "reference_content",+ "header",+ "footer",+ "footnote",+ "aside_text",+ "figure_title",+ "vision_footnote",+ }+ )# ------------------------------------------------------------------# bbox 几何计算@@ -266,14 +283,21 @@ class PPDocLayoutV2PostProcessor:def _is_header_footer_boundary_candidate(cls, box: Dict, anchor_labels: set[str]) -> bool:"""判断普通块是否可被页眉/页脚/页码边界规则改标。"""label = box.get("label")+ # 未被明确页眉页脚父框覆盖的公式仍保留公式身份,避免仅按页边位置误改标。+ if cls._is_formula_box(box):+ return Falseif label in cls.HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS:return Falsereturn label not in anchor_labels@classmethoddef _is_footnote_relabel_candidate(cls, box: Dict) -> bool:- """排除页眉、页脚、页码、页边注等非正文区域块,保留正文内容块。"""- return box.get("label") not in cls.PAGE_REGION_LABELS+ """保留公式及编号身份,避免脚注内公式被改成独立脚注并抢占原生文本。"""+ return (+ box.get("label") not in cls.PAGE_REGION_LABELS+ and not cls._is_formula_box(box)+ and not cls._is_formula_number_box(box)+ )@staticmethoddef _is_reference_box(box: Dict) -> bool:@@ -461,6 +485,37 @@ class PPDocLayoutV2PostProcessor:kept_indexes.sort()return [boxes[index] for index in kept_indexes]+ @classmethod+ def _filter_nested_text_boxes(cls, boxes: List[Dict]) -> List[Dict]:+ """过滤改标后同类且完全包含的文本框,保留大框并维持其原始阅读顺序。"""+ candidates = sorted(+ (+ (index, box)+ for index, box in enumerate(boxes)+ if box.get("label") in cls.NESTED_TEXT_LABELS+ and not cls._is_formula_box(box)+ and not cls._is_formula_number_box(box)+ ),+ key=lambda item: (+ -cls._calculate_bbox_area(item[1]["bbox"]),+ -float(item[1].get("score", 0.0)),+ item[0],+ ),+ )+ kept_by_label: dict[str, list[Dict]] = {}+ dropped_indexes: set[int] = set()+ for index, box in candidates:+ parents = kept_by_label.setdefault(box["label"], [])+ x0, y0, x1, y1 = box["bbox"]+ if any(+ parent["bbox"][0] <= x0 and parent["bbox"][1] <= y0 and parent["bbox"][2] >= x1 and parent["bbox"][3] >= y1+ for parent in parents+ ):+ dropped_indexes.add(index)+ else:+ parents.append(box)+ return [box for index, box in enumerate(boxes) if index not in dropped_indexes]+@classmethoddef _merge_nested_formula_boxes(cls,@@ -533,6 +588,30 @@ class PPDocLayoutV2PostProcessor:return boxes+ @classmethod+ def _filter_formula_boxes_inside_page_marginals(+ cls,+ boxes: List[Dict],+ cover_threshold: float = 0.8,+ ) -> List[Dict]:+ """删除被明确页眉页脚父框覆盖的公式框,避免页边小公式生成重叠文本 span。"""++ marginal_labels = {"header", "header_image", "footer", "footer_image"}+ marginal_parents = [box for box in boxes if box.get("label") in marginal_labels]+ if not marginal_parents:+ return boxes++ filtered_boxes = []+ for box in boxes:+ if not cls._is_formula_box(box):+ filtered_boxes.append(box)+ continue+ # 仅按公式自身被明确父框覆盖的比例过滤,不使用页面上下坐标带猜测归属。+ if any(cls._calculate_cover_ratio(box["bbox"], parent["bbox"]) >= cover_threshold for parent in marginal_parents):+ continue+ filtered_boxes.append(box)+ return filtered_boxes+@classmethoddef _relabel_header_footer_boundary_blocks(cls,@@ -648,10 +727,15 @@ class PPDocLayoutV2PostProcessor:boxes: List[Dict],image_size: Optional[Tuple[int, int]] = None,) -> List[Dict]:+ """统一两种后端的公式保护、边界改标与最终文本框去重。"""processed_boxes = [{**box, "bbox": list(box["bbox"])} for box in boxes]processed_boxes = cls._deduplicate_boxes_by_iou(processed_boxes, iou_threshold=0.9)processed_boxes = cls._merge_nested_formula_boxes(processed_boxes, overlap_threshold=0.7)processed_boxes = cls._relabel_formula_boxes(processed_boxes, overlap_threshold=0.7)+ processed_boxes = cls._filter_formula_boxes_inside_page_marginals(+ processed_boxes,+ cover_threshold=0.8,+ )processed_boxes = cls._relabel_header_footer_boundary_blocks(processed_boxes,image_size=image_size,@@ -660,6 +744,7 @@ class PPDocLayoutV2PostProcessor:processed_boxes,cover_threshold=0.8,)+ processed_boxes = cls._filter_nested_text_boxes(processed_boxes)return cls._renumber_indices(processed_boxes)@classmethoddiff --git a/mineru/model/layout/pp_doclayoutv2.py b/mineru/model/layout/pp_doclayoutv2.pyindex 1dbb9140..21bab64a 100644--- a/mineru/model/layout/pp_doclayoutv2.py+++ b/mineru/model/layout/pp_doclayoutv2.py@@ -3,7 +3,6 @@import argparseimport json-import mathfrom typing import Dict, List, Optional, Sequence, Tuple, Unionimport numpy as np@@ -199,586 +198,6 @@ class PPDocLayoutV2LayoutModel(PPDocLayoutV2PostProcessor):)return layout_res- @staticmethod- def _calculate_bbox_area(box: Sequence[float]) -> float:- xmin, ymin, xmax, ymax = [float(v) for v in box]- return max(0.0, xmax - xmin) * max(0.0, ymax - ymin)-- @classmethod- def _calculate_intersection_area(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- x1_min, y1_min, x1_max, y1_max = [float(v) for v in box1]- x2_min, y2_min, x2_max, y2_max = [float(v) for v in box2]- inter_xmin = max(x1_min, x2_min)- inter_ymin = max(y1_min, y2_min)- inter_xmax = min(x1_max, x2_max)- inter_ymax = min(y1_max, y2_max)- return cls._calculate_bbox_area((inter_xmin, inter_ymin, inter_xmax, inter_ymax))-- @classmethod- def _calculate_overlap_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- inter_area = cls._calculate_intersection_area(box1, box2)- ref_area = min(cls._calculate_bbox_area(box1), cls._calculate_bbox_area(box2))- if ref_area <= 0.0:- return 0.0- return inter_area / ref_area-- @classmethod- def _calculate_iou(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- inter_area = cls._calculate_intersection_area(box1, box2)- union_area = cls._calculate_bbox_area(box1) + cls._calculate_bbox_area(box2) - inter_area- if union_area <= 0.0:- return 0.0- return inter_area / union_area-- @classmethod- def _calculate_cover_ratio(cls, box1: Sequence[float], box2: Sequence[float]) -> float:- box1_area = cls._calculate_bbox_area(box1)- if box1_area <= 0.0:- return 0.0- return cls._calculate_intersection_area(box1, box2) / box1_area-- @staticmethod- def _calculate_x_overlap_ratio(box1: Sequence[float], box2: Sequence[float]) -> float:- """计算两个 bbox 在横向上的重叠比例,用于判断是否属于同一栏。"""- box1_xmin, _, box1_xmax, _ = [float(v) for v in box1]- box2_xmin, _, box2_xmax, _ = [float(v) for v in box2]- box1_width = max(0.0, box1_xmax - box1_xmin)- box2_width = max(0.0, box2_xmax - box2_xmin)- ref_width = min(box1_width, box2_width)- if ref_width <= 0.0:- return 0.0- overlap_width = max(0.0, min(box1_xmax, box2_xmax) - max(box1_xmin, box2_xmin))- return overlap_width / ref_width-- @staticmethod- def _calculate_x_cover_ratio(anchor_box: Sequence[float], candidate_box: Sequence[float]) -> float:- """计算 anchor 在横向上覆盖 candidate 的比例。"""- anchor_xmin, _, anchor_xmax, _ = [float(v) for v in anchor_box]- candidate_xmin, _, candidate_xmax, _ = [float(v) for v in candidate_box]- candidate_width = max(0.0, candidate_xmax - candidate_xmin)- if candidate_width <= 0.0:- return 0.0- overlap_width = max(- 0.0,- min(anchor_xmax, candidate_xmax) - max(anchor_xmin, candidate_xmin),- )- return overlap_width / candidate_width-- @classmethod- def _is_footer_x_scope(- cls,- anchor_box: Dict,- candidate_box: Dict,- image_size: Optional[Tuple[int, int]],- full_width_threshold: float = 0.7,- x_overlap_threshold: float = 0.3,- ) -> bool:- """判断候选块是否在页脚文本锚点的横向作用范围内。"""- anchor_bbox = anchor_box.get("bbox")- candidate_bbox = candidate_box.get("bbox")- if not anchor_bbox or not candidate_bbox:- return False-- if image_size is not None and len(image_size) >= 2:- page_width = float(image_size[1])- anchor_width = max(0.0, float(anchor_bbox[2]) - float(anchor_bbox[0]))- if page_width > 0.0 and anchor_width / page_width >= full_width_threshold:- return True-- return cls._calculate_x_overlap_ratio(anchor_bbox, candidate_bbox) >= x_overlap_threshold-- @classmethod- def _is_covered_by_footnote(- cls,- footnote_box: Dict,- candidate_box: Dict,- x_cover_threshold: float = 0.7,- ) -> bool:- """判断候选块是否位于 footnote 区域内或其下方,并被其横向覆盖。"""- footnote_bbox = footnote_box.get("bbox")- candidate_bbox = candidate_box.get("bbox")- if not footnote_bbox or not candidate_bbox:- return False- if candidate_bbox[1] < footnote_bbox[1]:- return False- return cls._calculate_x_cover_ratio(footnote_bbox, candidate_bbox) >= x_cover_threshold-- @classmethod- def _is_header_footer_boundary_candidate(cls, box: Dict, anchor_labels: set[str]) -> bool:- """判断普通块是否可被页眉/页脚/页码边界规则改标。"""- label = box.get("label")- # 未被明确页眉页脚父框覆盖的公式仍保留公式身份,避免仅按页边位置误改标。- if cls._is_formula_box(box):- return False- if label in cls.HEADER_FOOTER_BOUNDARY_EXEMPT_LABELS:- return False- return label not in anchor_labels-- @classmethod- def _is_footnote_relabel_candidate(cls, box: Dict) -> bool:- """排除页眉、页脚、页码、页边注等非正文区域块,保留正文内容块。"""- return box.get("label") not in cls.PAGE_REGION_LABELS-- @staticmethod- def _is_reference_box(box: Dict) -> bool:- return box.get("label") == "reference" or int(box.get("cls_id", -1)) == 18-- @staticmethod- def _is_display_formula_box(box: Dict) -> bool:- return box.get("label") == "display_formula" or int(box.get("cls_id", -1)) == 5-- @staticmethod- def _is_inline_formula_box(box: Dict) -> bool:- return box.get("label") == "inline_formula" or int(box.get("cls_id", -1)) == 15-- @staticmethod- def _is_formula_box(box: Dict) -> bool:- return PPDocLayoutV2LayoutModel._is_display_formula_box(box) or PPDocLayoutV2LayoutModel._is_inline_formula_box(box)-- @staticmethod- def _is_formula_number_box(box: Dict) -> bool:- return box.get("label") == "formula_number" or int(box.get("cls_id", -1)) == 11-- @staticmethod- def _set_box_label(box: Dict, label: str) -> None:- """统一同步设置 layout 检测框的标签名和类别编号。"""- if label not in PP_DOCLAYOUT_V2_LABEL_TO_ID:- raise ValueError(f"Unsupported PP-DocLayoutV2 label: {label}")- box["label"] = label- box["cls_id"] = PP_DOCLAYOUT_V2_LABEL_TO_ID[label]-- @staticmethod- def _set_formula_label(box: Dict, label: str) -> None:- if label not in {"inline_formula", "display_formula"}:- raise ValueError(f"Unsupported formula label: {label}")- PPDocLayoutV2LayoutModel._set_box_label(box, label)-- @staticmethod- def _set_header_footer_label(box: Dict, label: str) -> None:- """同步设置页眉/页脚相关标签及其类别编号。"""- if label not in {"footer", "footer_image", "header", "header_image"}:- raise ValueError(f"Unsupported header/footer label: {label}")- PPDocLayoutV2LayoutModel._set_box_label(box, label)-- @staticmethod- def _set_footnote_label(box: Dict) -> None:- """同步设置 page footnote 标签及其类别编号。"""- PPDocLayoutV2LayoutModel._set_box_label(box, "footnote")-- @classmethod- def _filter_internal_visual_caption_boxes(- cls,- boxes: List[Dict],- cover_threshold: float = 0.8,- ) -> List[Dict]:- """过滤落在图、表、印章等视觉主体内部的 figure_title。-- 这类块通常是图内的 (a)/(b) 标号,不应作为外部 caption 参与后续视觉分组。- """- visual_boxes = [box for box in boxes if box.get("label") in cls.VISUAL_BODY_LABELS]- if not visual_boxes:- return boxes-- filtered_boxes = []- for box in boxes:- if box.get("label") != "figure_title":- filtered_boxes.append(box)- continue-- caption_bbox = box.get("bbox")- if not caption_bbox or len(caption_bbox) < 4:- filtered_boxes.append(box)- continue-- caption_center_x = (float(caption_bbox[0]) + float(caption_bbox[2])) / 2- caption_center_y = (float(caption_bbox[1]) + float(caption_bbox[3])) / 2- is_internal_caption = False- for visual_box in visual_boxes:- visual_bbox = visual_box.get("bbox")- if not visual_bbox or len(visual_bbox) < 4:- continue-- visual_xmin, visual_ymin, visual_xmax, visual_ymax = [float(v) for v in visual_bbox]- if not (visual_xmin <= caption_center_x <= visual_xmax and visual_ymin <= caption_center_y <= visual_ymax):- continue-- if cls._calculate_cover_ratio(caption_bbox, visual_bbox) >= cover_threshold:- is_internal_caption = True- break-- if not is_internal_caption:- filtered_boxes.append(box)-- return filtered_boxes-- @classmethod- def _reclassify_header_footer_by_page_half(- cls,- boxes: List[Dict],- image_size: Optional[Tuple[int, int]],- ) -> List[Dict]:- """按页面上下半区重新校正页眉/页脚锚点,避免跨半页误触发边界规则。"""- if image_size is None:- return boxes-- page_height = float(image_size[0])- if page_height <= 0:- return boxes-- page_middle = page_height * 0.5- upper_half_labels = {- "footer": "header",- "footer_image": "header_image",- }- lower_half_labels = {- "header": "footer",- "header_image": "footer_image",- }- for box in boxes:- bbox = box.get("bbox")- if not bbox or len(bbox) < 4:- continue- label = box.get("label")- y_mid = (float(bbox[1]) + float(bbox[3])) / 2- if y_mid < page_middle and label in upper_half_labels:- cls._set_header_footer_label(box, upper_half_labels[label])- elif y_mid >= page_middle and label in lower_half_labels:- cls._set_header_footer_label(box, lower_half_labels[label])-- return boxes-- @staticmethod- def _union_bbox(box1: Sequence[float], box2: Sequence[float]) -> List[int]:- x1_min, y1_min, x1_max, y1_max = [float(v) for v in box1]- x2_min, y2_min, x2_max, y2_max = [float(v) for v in box2]- return [- math.floor(min(x1_min, x2_min)),- math.floor(min(y1_min, y2_min)),- math.ceil(max(x1_max, x2_max)),- math.ceil(max(y1_max, y2_max)),- ]-- @staticmethod- def _renumber_indices(boxes: List[Dict]) -> List[Dict]:- for index, box in enumerate(boxes, start=1):- box["index"] = index- return boxes-- @classmethod- def _deduplicate_boxes_by_iou(- cls,- boxes: List[Dict],- iou_threshold: float = 0.9,- ) -> List[Dict]:- if len(boxes) <= 1:- return boxes-- sorted_candidates = sorted(- enumerate(boxes),- key=lambda item: (-float(item[1].get("score", 0.0)), item[0]),- )- suppressed_indexes = set()- kept_indexes = []-- for candidate_pos, (current_index, current_box) in enumerate(sorted_candidates):- if current_index in suppressed_indexes:- continue- kept_indexes.append(current_index)- for other_index, other_box in sorted_candidates[candidate_pos + 1 :]:- if other_index in suppressed_indexes:- continue- if cls._calculate_iou(current_box["bbox"], other_box["bbox"]) > iou_threshold:- suppressed_indexes.add(other_index)-- kept_indexes.sort()- return [boxes[index] for index in kept_indexes]-- @classmethod- def _merge_nested_formula_boxes(- cls,- boxes: List[Dict],- overlap_threshold: float = 0.7,- ) -> List[Dict]:- if len(boxes) <= 1:- return boxes-- changed = True- while changed:- changed = False- formula_indexes = [index for index, box in enumerate(boxes) if cls._is_formula_box(box)]- for formula_pos, left_index in enumerate(formula_indexes):- for right_index in formula_indexes[formula_pos + 1 :]:- left_box = boxes[left_index]- right_box = boxes[right_index]- if cls._calculate_overlap_ratio(left_box["bbox"], right_box["bbox"]) < overlap_threshold:- continue-- left_area = cls._calculate_bbox_area(left_box["bbox"])- right_area = cls._calculate_bbox_area(right_box["bbox"])- if left_area > right_area:- keep_index, drop_index = left_index, right_index- elif right_area > left_area:- keep_index, drop_index = right_index, left_index- else:- left_score = float(left_box.get("score", 0.0))- right_score = float(right_box.get("score", 0.0))- keep_index, drop_index = (- (left_index, right_index) if left_score >= right_score else (right_index, left_index)- )-- keep_box = boxes[keep_index]- drop_box = boxes[drop_index]- keep_box["bbox"] = cls._union_bbox(keep_box["bbox"], drop_box["bbox"])- keep_box["score"] = round(- max(float(keep_box.get("score", 0.0)), float(drop_box.get("score", 0.0))),- 4,- )- del boxes[drop_index]- changed = True- break- if changed:- break-- return boxes-- @classmethod- def _relabel_formula_boxes(- cls,- boxes: List[Dict],- overlap_threshold: float = 0.7,- ) -> List[Dict]:- parent_candidates = [- box- for box in boxes- if (not cls._is_formula_box(box) and not cls._is_formula_number_box(box) and not cls._is_reference_box(box))- ]-- for box in boxes:- if not cls._is_formula_box(box):- continue- target_label = "display_formula"- for parent_box in parent_candidates:- if cls._calculate_cover_ratio(box["bbox"], parent_box["bbox"]) >= overlap_threshold:- target_label = "inline_formula"- break- cls._set_formula_label(box, target_label)-- return boxes-- @classmethod- def _filter_formula_boxes_inside_page_marginals(- cls,- boxes: List[Dict],- cover_threshold: float = 0.8,- ) -> List[Dict]:- """删除被明确页眉页脚父框覆盖的公式框,避免页边小公式生成重叠文本 span。"""-- marginal_labels = {"header", "header_image", "footer", "footer_image"}- marginal_parents = [box for box in boxes if box.get("label") in marginal_labels]- if not marginal_parents:- return boxes-- filtered_boxes = []- for box in boxes:- if not cls._is_formula_box(box):- filtered_boxes.append(box)- continue- # 仅按公式自身被明确父框覆盖的比例过滤,不使用页面上下坐标带猜测归属。- if any(cls._calculate_cover_ratio(box["bbox"], parent["bbox"]) >= cover_threshold for parent in marginal_parents):- continue- filtered_boxes.append(box)- return filtered_boxes-- @classmethod- def _relabel_header_footer_boundary_blocks(- cls,- boxes: List[Dict],- image_size: Optional[Tuple[int, int]] = None,- ) -> List[Dict]:- """按视觉坐标用页眉/页脚锚点修正边界区域的普通块标签。"""- if len(boxes) <= 1:- return boxes-- header_labels = {"header", "header_image"}- footer_labels = {"footer", "footer_image"}- ordered_boxes = sorted(boxes, key=lambda box: box["index"])- ordered_boxes = cls._reclassify_header_footer_by_page_half(- ordered_boxes,- image_size=image_size,- )- boundary_anchor_ids = {- id(box) for box in ordered_boxes if box.get("label") in header_labels or box.get("label") in footer_labels- }-- header_anchor = max(- (box for box in ordered_boxes if box.get("label") in header_labels),- key=lambda box: (box["bbox"][3], box["index"]),- default=None,- )- footer_anchor = min(- (box for box in ordered_boxes if box.get("label") in footer_labels),- key=lambda box: (box["bbox"][1], box["index"]),- default=None,- )-- # 先按最后一个页眉锚点的下边界修正,后续页脚修正可覆盖重叠区间。- if header_anchor is not None:- header_boundary = header_anchor["bbox"][3]- for box in ordered_boxes:- if not cls._is_header_footer_boundary_candidate(box, header_labels):- continue- if box["bbox"][3] <= header_boundary:- cls._set_box_label(box, "header")-- footnote_anchors = [box for box in ordered_boxes if box.get("label") == "footnote"]- if footnote_anchors:- for box in ordered_boxes:- if not cls._is_footnote_relabel_candidate(box):- continue- for footnote_anchor in footnote_anchors:- if cls._is_covered_by_footnote(footnote_anchor, box):- cls._set_footnote_label(box)- break-- if footer_anchor is not None:- footer_boundary = footer_anchor["bbox"][1]- for box in ordered_boxes:- if not cls._is_header_footer_boundary_candidate(box, footer_labels):- continue- if box["bbox"][1] >= footer_boundary and cls._is_footer_x_scope(footer_anchor, box, image_size):- cls._set_box_label(box, "footer")-- if image_size is None:- return ordered_boxes-- page_height = float(image_size[0])- if page_height <= 0:- return ordered_boxes-- top_boundary = page_height * 0.3- bottom_boundary = page_height * 0.7- top_numbers = []- bottom_numbers = []- for box in ordered_boxes:- if box.get("label") != "number":- continue- y_mid = (float(box["bbox"][1]) + float(box["bbox"][3])) / 2- if y_mid <= top_boundary:- top_numbers.append(box)- elif y_mid >= bottom_boundary:- bottom_numbers.append(box)-- top_number_anchor = max(- top_numbers,- key=lambda box: (box["bbox"][3], box["index"]),- default=None,- )- bottom_number_anchor = min(- bottom_numbers,- key=lambda box: (box["bbox"][1], box["index"]),- default=None,- )-- # number 自身不改标签,仅用上下 30% 区域中的 number 作为辅助分割线。- if top_number_anchor is not None:- header_boundary = top_number_anchor["bbox"][1]- for box in ordered_boxes:- if id(box) in boundary_anchor_ids or not cls._is_header_footer_boundary_candidate(box, set()):- continue- if box["bbox"][3] <= header_boundary:- cls._set_box_label(box, "header")-- if bottom_number_anchor is not None:- footer_boundary = bottom_number_anchor["bbox"][3]- for box in ordered_boxes:- if id(box) in boundary_anchor_ids or not cls._is_header_footer_boundary_candidate(box, set()):- continue- if box["bbox"][1] >= footer_boundary:- cls._set_box_label(box, "footer")-- return ordered_boxes-- @classmethod- def _apply_layout_post_process(- cls,- boxes: List[Dict],- image_size: Optional[Tuple[int, int]] = None,- ) -> List[Dict]:- processed_boxes = [{**box, "bbox": list(box["bbox"])} for box in boxes]- processed_boxes = cls._deduplicate_boxes_by_iou(processed_boxes, iou_threshold=0.9)- processed_boxes = cls._merge_nested_formula_boxes(processed_boxes, overlap_threshold=0.7)- processed_boxes = cls._relabel_formula_boxes(processed_boxes, overlap_threshold=0.7)- processed_boxes = cls._filter_formula_boxes_inside_page_marginals(- processed_boxes,- cover_threshold=0.8,- )- processed_boxes = cls._relabel_header_footer_boundary_blocks(- processed_boxes,- image_size=image_size,- )- processed_boxes = cls._filter_internal_visual_caption_boxes(- processed_boxes,- cover_threshold=0.8,- )- return cls._renumber_indices(processed_boxes)-- @classmethod- def _apply_paddlex_filter_boxes(- cls,- boxes: List[Dict],- drop_inline_formula: bool = True,- ) -> List[Dict]:- filtered_boxes = [dict(box) for box in boxes if not cls._is_reference_box(box)]- dropped_indexes = set()-- for i in range(len(filtered_boxes)):- if i in dropped_indexes:- continue- x1, y1, x2, y2 = filtered_boxes[i]["bbox"]- width = float(x2) - float(x1)- height = float(y2) - float(y1)- if (width < 6.0 or height < 6.0) and (drop_inline_formula or not cls._is_inline_formula_box(filtered_boxes[i])):- dropped_indexes.add(i)- continue-- for j in range(i + 1, len(filtered_boxes)):- if i in dropped_indexes or j in dropped_indexes:- continue-- if not drop_inline_formula and (- cls._is_inline_formula_box(filtered_boxes[i]) or cls._is_inline_formula_box(filtered_boxes[j])- ):- continue-- overlap_ratio = cls._calculate_overlap_ratio(- filtered_boxes[i]["bbox"],- filtered_boxes[j]["bbox"],- )- if drop_inline_formula and (- cls._is_inline_formula_box(filtered_boxes[i]) or cls._is_inline_formula_box(filtered_boxes[j])- ):- if overlap_ratio > 0.5:- if cls._is_inline_formula_box(filtered_boxes[i]):- dropped_indexes.add(i)- if cls._is_inline_formula_box(filtered_boxes[j]):- dropped_indexes.add(j)- continue-- if overlap_ratio > 0.7:- box_area_i = cls._calculate_bbox_area(filtered_boxes[i]["bbox"])- box_area_j = cls._calculate_bbox_area(filtered_boxes[j]["bbox"])- labels = {filtered_boxes[i]["label"], filtered_boxes[j]["label"]}- if labels & {"image", "table", "seal", "chart"} and len(labels) > 1:- if "table" not in labels or labels <= {"table", "image", "seal", "chart"}:- continue- if box_area_i >= box_area_j:- dropped_indexes.add(j)- else:- dropped_indexes.add(i)-- kept_boxes = [box for index, box in enumerate(filtered_boxes) if index not in dropped_indexes]- return cls._renumber_indices(kept_boxes)-def predict(self,image: Union[np.ndarray, Image.Image],diff --git a/tests/fixtures/emnlp614_footnote/README.md b/tests/fixtures/emnlp614_footnote/README.mdnew file mode 100644index 00000000..bb59dbdb--- /dev/null+++ b/tests/fixtures/emnlp614_footnote/README.md@@ -0,0 +1,7 @@+# EMNLP 2022 第 7 页脚注回归++`page7.pdf` 是用户提供的 `2022.emnlp-main.614.pdf` 的第 7 页,保留原始字符与字体;原文件 SHA-256 见 `detection.json`。++`detection.json` 固化 200 DPI 渲染尺寸、Torch/ONNX 的脚注区域原始 layout 检测、保留行内公式遮罩后的 OCR 检测框,以及真实 VLM 文本识别结果。坐标均来自原页,测试不依赖模型权重或用户 Downloads 目录。++错误链路是 `inline_formula` 被脚注边界规则改成 `footnote`,小框先领取第一行,大框只剩第二行。回归必须同时验证公式身份、识别输入、两行回填及最终单个脚注,不能仅以删掉小框为通过条件。第二行 `s0 > s1` 的下标漏检不属于本次修复范围。diff --git a/tests/fixtures/emnlp614_footnote/detection.json b/tests/fixtures/emnlp614_footnote/detection.jsonnew file mode 100644index 00000000..f47b99f8--- /dev/null+++ b/tests/fixtures/emnlp614_footnote/detection.json@@ -0,0 +1,91 @@+{+ "source": "2022.emnlp-main.614.pdf",+ "source_sha256": "b10fa41a07177c40a45fd292d7e8147f4905fc41466fa3b61fed25271e2b281b",+ "source_page": 7,+ "render_size": [+ 1654,+ 2339+ ],+ "scale": 2.7777777777777777,+ "raw_layout": {+ "torch": [+ {+ "cls_id": 15,+ "label": "inline_formula",+ "score": 0.4552,+ "bbox": [+ 395,+ 2089,+ 806,+ 2122+ ],+ "index": 13+ },+ {+ "cls_id": 10,+ "label": "footnote",+ "score": 0.9489,+ "bbox": [+ 188,+ 2087,+ 809,+ 2152+ ],+ "index": 19+ }+ ],+ "onnx": [+ {+ "cls_id": 15,+ "label": "inline_formula",+ "score": 0.459,+ "bbox": [+ 395,+ 2089,+ 806,+ 2122+ ],+ "index": 13+ },+ {+ "cls_id": 10,+ "label": "footnote",+ "score": 0.9488,+ "bbox": [+ 188,+ 2087,+ 809,+ 2152+ ],+ "index": 19+ }+ ]+ },+ "ocr_detection": [+ [+ {+ "label": "ocr_text",+ "bbox": [+ 228,+ 2088,+ 394,+ 2121+ ],+ "score": 1.0,+ "text": ""+ },+ {+ "label": "ocr_text",+ "bbox": [+ 193,+ 2120,+ 514,+ 2149+ ],+ "score": 1.0,+ "text": ""+ }+ ]+ ],+ "vlm_text": "\\(h_0(d_0) = 5, h_1(d_0) = 15, h_0(d_1) = 10\\)"+}diff --git a/tests/fixtures/emnlp614_footnote/page7.pdf b/tests/fixtures/emnlp614_footnote/page7.pdfnew file mode 100644index 00000000..0770cf97Binary files /dev/null and b/tests/fixtures/emnlp614_footnote/page7.pdf differdiff --git a/tests/unittest/test_pdf_footnote_layout.py b/tests/unittest/test_pdf_footnote_layout.pynew file mode 100644index 00000000..3f685164--- /dev/null+++ b/tests/unittest/test_pdf_footnote_layout.py@@ -0,0 +1,157 @@+"""真实脚注 PDF 从 layout 到同步/异步识别、原生回填及导出的回归。"""++from __future__ import annotations++import asyncio+from copy import deepcopy+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import Mock++import numpy as np+import pytest+from docvortex.document.pdf import PDFDocument+from PIL import Image++from mineru.backend.analysis.pdf import ocr, window+from mineru.backend.analysis.pdf.layout import _build_vl_style_layout_blocks+from mineru.backend.analysis.pdf.normalization import _normalize_pdf_model_list+from mineru.backend.postprocess.document import build_middle_json+from mineru.model.layout.pp_doclayout_v2_base import PPDocLayoutV2PostProcessor+from mineru.parser.base import ParseResult+from mineru.types import ModelJson++FIXTURE = Path(__file__).parents[1] / "fixtures/emnlp614_footnote"+++ ("effort", "is_async", "fallback"),+ [("medium", False, False), ("high", False, False), ("high", True, False), ("high", False, True), ("high", True, True)],+)+def test_real_footnote_survives_recognition_and_native_fill(+ monkeypatch: pytest.MonkeyPatch, effort: str, is_async: bool, fallback: bool+) -> None:+ """冻结推理边界但执行真实回填,确保完整脚注、公式和两行内容均只出现一次。"""+ fixture = json.loads((FIXTURE / "detection.json").read_text())+ source = (FIXTURE / "page7.pdf").read_bytes()+ formula_bbox = fixture["raw_layout"]["torch"][0]["bbox"]+ latex = "h_0(d_0) = 5, h_1(d_0) = 15, h_0(d_1) = 10"+ crop_images = []+ mfr_calls = []++ def prepare(*args: Any, **kwargs: Any) -> window._WindowInputs:+ """在真实渲染页面上复放原始检测框,其余窗口阶段继续使用生产实现。"""+ image = document.render_page(0, scale=fixture["scale"]).pil_image+ assert list(image.size) == fixture["render_size"]+ layout = PPDocLayoutV2PostProcessor._apply_layout_post_process(+ PPDocLayoutV2PostProcessor._apply_paddlex_filter_boxes(fixture["raw_layout"]["torch"], drop_inline_formula=False),+ image_size=image.size[::-1],+ )+ blocks = _build_vl_style_layout_blocks([layout], [image])+ return window._WindowInputs(+ window._ProcessingWindow(0, 1, 0, 0),+ [{"img_pil": image, "scale": fixture["scale"]}],+ [document[0]],+ [image],+ [np.asarray(image).copy()],+ [layout],+ blocks,+ deepcopy(blocks),+ [[]],+ [None],+ )++ def main_infer(**kwargs: Any) -> list[list[dict[str, Any]]]:+ """Standard 主识别只收到完整脚注,行内公式由独立切片识别。"""+ blocks = kwargs["blocks_list"]+ assert [[block["type"] for block in page] for page in blocks] == [["page_footnote"]]+ return deepcopy(blocks)++ def inline_infer(images: list[Image.Image]) -> list[str | None]:+ """检查真实公式裁剪被送入 VLM,并覆盖空响应的局部回退。"""+ assert len(images) == 1 and images[0].size == (411, 33)+ crop_images.extend(images)+ return [None if fallback else fixture["vlm_text"]]++ async def async_main(**kwargs: Any) -> list[list[dict[str, Any]]]:+ """异步主识别复用相同的输入契约。"""+ return main_infer(**kwargs)++ async def async_inline(images: list[Image.Image]) -> list[str | None]:+ """异步切片在一次调度后仍能交付给识别器。"""+ await asyncio.sleep(0)+ return inline_infer(images)++ def mfr_infer(inputs: list[list[dict[str, Any]]], *args: Any, **kwargs: Any) -> list[list[dict[str, Any]]]:+ """Basic 使用完整 MFR,Standard 仅在失败时回退,均保留公式位置。"""+ assert [[item["bbox"] for item in page] for page in inputs] == [[formula_bbox]]+ assert kwargs["interline_enable"] is (effort == "medium")+ mfr_calls.append(deepcopy(inputs))+ return [[{**item, "latex": latex} for item in inputs[0]]]++ def detect(+ context: Any,+ images: list[np.ndarray],+ blocks: list[list[dict[str, Any]]],+ formulas: list[list[dict[str, Any]]],+ need_rec_img: bool,+ types: set[str],+ ) -> list[list[dict[str, Any]]]:+ """复放公式遮罩后的 OCR 框,确保改标修复也保留 OCR 所用公式位置。"""+ assert [item["bbox"] for item in formulas[0]] == [formula_bbox]+ assert len(blocks[0]) == 1 and blocks[0][0]["type"] == "page_footnote"+ return deepcopy(fixture["ocr_detection"])++ context = SimpleNamespace(+ device="cpu",+ mfr_model=SimpleNamespace(batch_predict=mfr_infer),+ ocr_model=SimpleNamespace(ocr=Mock(side_effect=AssertionError("Unexpected OCR-rec fallback"))),+ )+ predictor = SimpleNamespace(+ batch_extract_with_layout=main_infer,+ batch_recognize_text=inline_infer,+ aio_batch_extract_with_layout=async_main,+ aio_batch_recognize_text=async_inline,+ )+ monkeypatch.setattr(window, "_prepare_pdf_window", prepare)+ monkeypatch.setattr(window, "get_document_render_session", lambda document: None)+ monkeypatch.setattr(ocr, "_ocr_det", detect)+ with PDFDocument(source) as document:+ options = {+ "effort": effort,+ "parse_mode": "txt",+ "image_analysis": False,+ "hybrid_model": context,+ "vlm_predictor": predictor if effort == "high" else None,+ }+ if is_async:+ result = asyncio.run(window.aio_process_pdf_windows(source, document, **options))+ else:+ result = window._process_pdf_window(source, document, window._ProcessingWindow(0, 1, 0, 0), page_count=1, **options)+ _normalize_pdf_model_list(result)+ assert len(result[0]) == 1+ block = result[0][0]+ assert block["type"] == "page_footnote"+ assert [span["content"] for span in block["content"] if span["type"] == "equation_inline"] == [latex]+ text = "".join(span["content"] for span in block["content"])+ assert text == f"9For example, if {latex} and h1(d1) = 10 then s0 > s1."+ assert len(mfr_calls) == int(effort == "medium" or fallback)+ assert len(crop_images) == int(effort == "high")+ for image in crop_images:+ with pytest.raises(ValueError, match="closed image"):+ image.getpixel((0, 0))+ model = ModelJson(+ pages=result,+ page_index_map=[6],+ metadata={"file_suffix": "pdf", "producer": {"name": "mineru", "version": "test"}},+ )+ parsed = ParseResult(build_middle_json(model))+ markdown = parsed.markdown()+ assert len(parsed.pages[0].blocks) == 1+ assert markdown.count('data-block-type="page_footnote"') == 1+ assert markdown.count("For example, if") == 1+ assert markdown.count(f"${latex}$") == 1+ assert "and h<sub>1</sub>(d<sub>1</sub>) = 10 then s0 > s1." in markdown+ assert "10 ( ) =" not in markdowndiff --git a/tests/unittest/test_pp_doclayoutv2_postprocess.py b/tests/unittest/test_pp_doclayoutv2_postprocess.pyindex f9208b2c..1ffd58f2 100644--- a/tests/unittest/test_pp_doclayoutv2_postprocess.py+++ b/tests/unittest/test_pp_doclayoutv2_postprocess.py@@ -3,9 +3,10 @@from __future__ import annotations-# 可选依赖检测必须先于模型模块导入。-# ruff: noqa: E402-+from copy import deepcopy+from itertools import permutations+import json+from pathlib import Pathfrom typing import Anyimport pytest@@ -14,18 +15,30 @@ from PIL import Imagefrom mineru.backend.analysis.pdf.formulas import _build_formula_inputsfrom mineru.backend.analysis.pdf.layout import _build_vl_style_layout_blocks-pytestmark = pytest.mark.torch--pytest.importorskip("torch")-pytest.importorskip("transformers", minversion="5.10.1")--from mineru.model.layout.pp_doclayoutv2 import (+from mineru.model.layout.pp_doclayout_v2_base import (PP_DOCLAYOUT_V2_LABEL_TO_ID,- PPDocLayoutV2LayoutModel,+ PPDocLayoutV2PostProcessor,)from mineru.types import BlockType[email protected](params=["base", "onnx", pytest.param("torch", marks=pytest.mark.torch)])+def processor(request: pytest.FixtureRequest) -> type[PPDocLayoutV2PostProcessor]:+ """分别通过共享基类和两个实际后端调用后处理,不加载推理权重。"""+ if request.param == "torch":+ pytest.importorskip("torch")+ pytest.importorskip("transformers", minversion="5.10.1")+ from mineru.model.layout.pp_doclayoutv2 import PPDocLayoutV2LayoutModel++ return PPDocLayoutV2LayoutModel+ if request.param == "onnx":+ pytest.importorskip("onnxruntime")+ from mineru.model.layout.pp_doclayout_v2_onnx import PPDocLayoutV2LayoutModelONNX++ return PPDocLayoutV2LayoutModelONNX+ return PPDocLayoutV2PostProcessor++def _layout_box(label: str,bbox: tuple[float, float, float, float],@@ -38,11 +51,7 @@ def _layout_box(return {"label": label,- "cls_id": (- PP_DOCLAYOUT_V2_LABEL_TO_ID[label]- if cls_id is None- else cls_id- ),+ "cls_id": (PP_DOCLAYOUT_V2_LABEL_TO_ID[label] if cls_id is None else cls_id),"bbox": list(bbox),"score": score,"index": index,@@ -60,7 +69,7 @@ def test_filter_formula_boxes_inside_page_marginals_removes_only_covered_formulabody_formula = _layout_box("inline_formula", (20, 50, 40, 70), index=6)formula_number = _layout_box("formula_number", (70, 2, 80, 18), index=7)- filtered = PPDocLayoutV2LayoutModel._filter_formula_boxes_inside_page_marginals(+ filtered = PPDocLayoutV2PostProcessor._filter_formula_boxes_inside_page_marginals([header,header_formula,@@ -88,7 +97,7 @@ def test_filter_formula_boxes_inside_page_marginals_uses_formula_area_threshold(covered_formula = _layout_box("inline_formula", (79, 0, 105, 20), index=2)partial_formula = _layout_box("inline_formula", (80, 0, 110, 20), index=3)- filtered = PPDocLayoutV2LayoutModel._filter_formula_boxes_inside_page_marginals(+ filtered = PPDocLayoutV2PostProcessor._filter_formula_boxes_inside_page_marginals([header, covered_formula, partial_formula],cover_threshold=0.8,)@@ -108,9 +117,7 @@ def test_filter_formula_boxes_supports_all_page_marginal_parent_labels(parent = _layout_box(parent_label, (0, 0, 100, 20), index=1)formula = _layout_box("inline_formula", (20, 2, 40, 18), index=2)- filtered = PPDocLayoutV2LayoutModel._filter_formula_boxes_inside_page_marginals(- [parent, formula]- )+ filtered = PPDocLayoutV2PostProcessor._filter_formula_boxes_inside_page_marginals([parent, formula])assert filtered == [parent]@@ -124,7 +131,7 @@ def test_layout_postprocess_drops_nested_header_formula_and_preserves_other_formbody_text = _layout_box("text", (0, 40, 100, 80), index=7)body_formula = _layout_box("display_formula", (20, 50, 40, 70), index=8)- processed = PPDocLayoutV2LayoutModel._apply_layout_post_process(+ processed = PPDocLayoutV2PostProcessor._apply_layout_post_process([header, nested_formula, near_margin_formula, body_text, body_formula],image_size=(200, 140),)@@ -151,9 +158,7 @@ def test_filter_formula_boxes_inside_page_marginals_accepts_formula_cls_id() ->cls_id=PP_DOCLAYOUT_V2_LABEL_TO_ID["inline_formula"],)- filtered = PPDocLayoutV2LayoutModel._filter_formula_boxes_inside_page_marginals(- [header, formula_with_drifted_label]- )+ filtered = PPDocLayoutV2PostProcessor._filter_formula_boxes_inside_page_marginals([header, formula_with_drifted_label])assert filtered == [header]@@ -167,7 +172,7 @@ def test_header_footer_boundary_still_relabels_plain_text_but_not_formula() -> N_layout_box("inline_formula", (140, 2, 160, 18), index=3),]- processed = PPDocLayoutV2LayoutModel._relabel_header_footer_boundary_blocks(+ processed = PPDocLayoutV2PostProcessor._relabel_header_footer_boundary_blocks(boxes,image_size=(200, 200),)@@ -182,7 +187,7 @@ def test_header_footer_boundary_still_relabels_plain_text_but_not_formula() -> Ndef test_filtered_marginal_formula_does_not_enter_model_or_formula_inputs() -> None:"""验证页边公式过滤后只保留父 header,且不再进入 MFR 输入。"""- processed = PPDocLayoutV2LayoutModel._apply_layout_post_process(+ processed = PPDocLayoutV2PostProcessor._apply_layout_post_process([_layout_box("header", (0, 0, 100, 20), index=1),_layout_box("inline_formula", (20, 2, 40, 18), index=2),@@ -205,3 +210,97 @@ def test_filtered_marginal_formula_does_not_enter_model_or_formula_inputs() -> N}]]++[email protected]("detection_backend", ["torch", "onnx"])+def test_real_footnote_layout_preserves_formula_recognition(+ processor: type[PPDocLayoutV2PostProcessor], detection_backend: str+) -> None:+ """复放第七页真实框:小框仍进入公式识别,正文块中只有完整脚注。"""+ fixture = json.loads((Path(__file__).parents[1] / "fixtures/emnlp614_footnote/detection.json").read_text())+ boxes = fixture["raw_layout"][detection_backend]+ before = deepcopy(boxes)+ processed = processor._apply_layout_post_process(+ processor._apply_paddlex_filter_boxes(boxes, drop_inline_formula=False),+ image_size=tuple(reversed(fixture["render_size"])),+ )+ assert boxes == before+ assert [(box["label"], box["cls_id"]) for box in processed] == [("inline_formula", 15), ("footnote", 10)]+ assert _build_formula_inputs([processed])[0][0]["bbox"] == [395, 2089, 806, 2122]+ with Image.new("RGB", tuple(fixture["render_size"])) as image:+ blocks = _build_vl_style_layout_blocks([processed], [image])[0]+ assert len(blocks) == 1+ assert blocks[0]["type"] == BlockType.PAGE_FOOTNOTE+ assert blocks[0]["bbox"] == [0.114, 0.892, 0.489, 0.92]+++def test_backend_marginal_and_footnote_rules_are_consistent(processor: type[PPDocLayoutV2PostProcessor]) -> None:+ """两个后端均过滤明确页眉内公式,保护未被覆盖的公式和脚注内编号。"""+ boxes = [+ _layout_box("header", (0, 0, 100, 20), index=1),+ _layout_box("inline_formula", (10, 2, 30, 18), index=2),+ _layout_box("display_formula", (120, 2, 140, 18), index=3),+ _layout_box("footnote", (0, 170, 100, 195), index=4),+ _layout_box("display_formula", (10, 175, 50, 185), index=5),+ _layout_box("formula_number", (80, 175, 95, 185), index=6),+ ]+ result = processor._apply_layout_post_process(boxes, image_size=(200, 200))+ assert [box["label"] for box in result] == ["header", "display_formula", "footnote", "inline_formula", "formula_number"]++[email protected]("label", sorted(PPDocLayoutV2PostProcessor.NESTED_TEXT_LABELS))+def test_nested_text_filter_keeps_outer_box_in_all_input_orders(label: str) -> None:+ """三级同类文本嵌套总是保留完整大框,不受内框高分和输入排列影响。"""+ boxes = [+ _layout_box(label, (0, 0, 100, 100), index=10, score=0.6),+ _layout_box(label, (10, 10, 90, 90), index=11, score=0.9),+ _layout_box(label, (20, 20, 30, 30), index=12, score=0.99),+ ]+ before = deepcopy(boxes)+ for ordered in permutations(boxes):+ assert PPDocLayoutV2PostProcessor._filter_nested_text_boxes(list(ordered)) == [boxes[0]]+ assert boxes == before+++def test_equal_text_boxes_use_score_then_input_order() -> None:+ """相同几何只保留最高置信框,同分时保留首项且不打乱其他块的顺序。"""+ first = _layout_box("text", (0, 0, 100, 100), index=8, score=0.8)+ other = _layout_box("text", (200, 0, 300, 100), index=2)+ second = _layout_box("text", (0, 0, 100, 100), index=3, score=0.9)+ tied = _layout_box("text", (0, 0, 100, 100), index=4, score=0.9)+ assert PPDocLayoutV2PostProcessor._filter_nested_text_boxes([first, other, second, tied]) == [other, second]+ assert PPDocLayoutV2PostProcessor._filter_nested_text_boxes([tied, other, second, first]) == [tied, other]+++ "label", ["inline_formula", "display_formula", "formula_number", "image", "table", "chart", "seal", "reference", "content"]+)+def test_nested_nontext_regions_are_not_suppressed(label: str) -> None:+ """新增规则不把公式、视觉主体或列表容器的合法层级当作文本重复。"""+ boxes = [_layout_box(label, (0, 0, 100, 100), index=1), _layout_box(label, (10, 10, 40, 40), index=2)]+ assert PPDocLayoutV2PostProcessor._filter_nested_text_boxes(boxes) == boxes+++def test_nested_filter_preserves_partial_overlap_cross_labels_and_formula_class_id() -> None:+ """一像素越界、相邻脚注、异类文本及标签漂移的公式都不能由新增规则删除。"""+ boxes = [+ _layout_box("footnote", (0, 0, 100, 100), index=1),+ _layout_box("footnote", (20, 10, 101, 90), index=2),+ _layout_box("footnote", (0, 101, 100, 120), index=3),+ _layout_box("text", (10, 10, 40, 40), index=4),+ _layout_box("footnote", (10, 10, 40, 40), index=5, cls_id=15),+ _layout_box("footnote", (50, 10, 70, 40), index=6, cls_id=11),+ ]+ assert PPDocLayoutV2PostProcessor._filter_nested_text_boxes(boxes) == boxes+++def test_final_filter_removes_text_duplicates_created_by_relabeling(processor: type[PPDocLayoutV2PostProcessor]) -> None:+ """先保留不同类别候选,改为同类脚注后再去重,且不删除脚注外的完整文本。"""+ boxes = [+ _layout_box("text", (20, 172, 80, 180), index=1, score=0.99),+ _layout_box("text", (0, 150, 100, 165), index=2),+ _layout_box("footnote", (0, 170, 100, 195), index=3, score=0.8),+ ]+ 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]