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: implement vector formula detection and processing with path information extraction
myhlolia4af399c01a5
diff --git a/mineru/backend/flash/native_pdf/formulas.py b/mineru/backend/flash/native_pdf/formulas.pyindex 11f5b0d5..830d5a6b 100644--- a/mineru/backend/flash/native_pdf/formulas.py+++ b/mineru/backend/flash/native_pdf/formulas.py@@ -6,23 +6,32 @@ from __future__ import annotationsimport reimport statistics-from dataclasses import replace+from dataclasses import dataclass, replacefrom typing import Anyfrom mineru.types import BBox+from mineru.utils.pdf_document import PDFPathInfofrom .models import (_FormulaAnchor,_LineItem,+ _PageSource,_TextLane,)from .geometry import (_bbox_axis_overlap_ratio,_bbox_center_x,_bbox_center_y,+ _bbox_distance,+ _bbox_intersects,+ _bbox_overlap_in_first,+ _bbox_overlap_in_smaller,_bbox_union,_bbox_union_many,+ _clip_bbox,+ _coerce_bbox,+ _expand_bbox,_rotate_bbox_to_upright,)from .native_text import _sanitize_pdf_control_text@@ -39,6 +48,501 @@ _FORMULA_NUMBER_SUFFIX_RE = re.compile()+_VECTOR_FORMULA_COMPLEX_SEGMENTS = 8+_VECTOR_FORMULA_MIN_PATHS = 5+_VECTOR_FORMULA_MIN_COMPLEX_PATHS = 5+_VECTOR_FORMULA_MIN_COMPLEX_RATIO = 0.5+_VECTOR_FORMULA_NUMBER_MIN_PATHS = 3+_VECTOR_FORMULA_NUMBER_MAX_PATHS = 6+++@dataclass(slots=True)+class _VectorPathComponent:+ """保存同栏邻接 Path 形成的矢量组件。"""++ lane_index: int+ path_infos: list[PDFPathInfo]+ bbox: BBox+++@dataclass(slots=True)+class _VectorFormulaCandidate:+ """保存已通过主体校验、等待吸收横线和编号的矢量公式。"""++ lane_index: int+ bbox: BBox+ path_source_indices: set[int]+ has_number: bool = False+++def _build_vector_formula_blocks(+ source: _PageSource,+ container_blocks: list[dict[str, Any]],+ claimed_line_indices: set[int],+) -> tuple[list[dict[str, Any]], set[int]]:+ """从根层填充 Path 构建空内容公式,并唯一认领可提取的公式编号。"""++ available_lines = [+ line+ for line in source.lines+ if line.angle == 0 and line.source_index not in claimed_line_indices+ ]+ if len(available_lines) < 3 or not source.path_infos:+ return [], set()++ line_geometry = [(line, line.bbox) for line in available_lines]+ effective_heights = [_line_effective_height(line, bbox) for line, bbox in line_geometry]+ median_height = statistics.median(effective_heights) if effective_heights else 0.0+ if median_height <= 0:+ return [], set()+ lanes = [+ lane+ for lane in _infer_text_lanes(line_geometry, source.page_size[0], median_height)+ if not lane.is_span and len(lane.lines) >= 3+ ]+ if not lanes:+ return [], set()++ components = _build_vector_path_components(+ source.path_infos,+ lanes,+ median_height,+ )+ container_bboxes = [+ bbox+ for block in container_blocks+ if (bbox := _coerce_bbox(block.get("bbox"))) is not None+ ]+ candidates = [+ _VectorFormulaCandidate(+ lane_index=component.lane_index,+ bbox=component.bbox,+ path_source_indices={item.source_index for item in component.path_infos},+ )+ for component in components+ if _is_vector_formula_core(+ component,+ lanes[component.lane_index],+ median_height,+ source.page_size,+ container_bboxes,+ )+ ]+ if not candidates:+ return [], set()++ _attach_vector_formula_rules(candidates, components, median_height)+ _attach_vector_formula_path_numbers(candidates, components, lanes, median_height)+ claimed_number_indices = _attach_vector_formula_text_numbers(+ candidates,+ lanes,+ median_height,+ claimed_line_indices,+ )++ padding = min(1.5, 0.1 * median_height)+ blocks: list[dict[str, Any]] = []+ for candidate in sorted(candidates, key=lambda item: (item.bbox[1], item.bbox[0])):+ padded_bbox = _clip_bbox(+ (+ candidate.bbox[0] - padding,+ candidate.bbox[1] - padding,+ candidate.bbox[2] + padding,+ candidate.bbox[3] + padding,+ ),+ source.page_size,+ )+ if padded_bbox is None:+ continue+ blocks.append(+ {+ "type": "equation",+ "bbox": padded_bbox,+ "angle": 0,+ "content": "",+ }+ )+ return blocks, claimed_number_indices+++def _build_vector_path_components(+ path_infos: list[PDFPathInfo],+ lanes: list[_TextLane],+ median_height: float,+) -> list[_VectorPathComponent]:+ """按文本栏带筛选矢量字形,并用空间网格生成局部连通组件。"""++ members_by_lane: dict[int, list[PDFPathInfo]] = {}+ for path_info in path_infos:+ if (+ path_info.form_depth != 0+ or not path_info.fill_visible+ or path_info.stroke_visible+ ):+ continue+ lane_index = _assign_vector_path_lane(path_info.bbox, lanes, median_height)+ if lane_index is None:+ continue+ if not _is_vector_formula_path_member(+ path_info.bbox,+ lanes[lane_index],+ median_height,+ ):+ continue+ members_by_lane.setdefault(lane_index, []).append(path_info)++ components: list[_VectorPathComponent] = []+ for lane_index, members in members_by_lane.items():+ components.extend(+ _connect_vector_path_members(+ members,+ lane_index,+ median_height,+ )+ )+ return sorted(+ components,+ key=lambda item: (item.bbox[1], item.bbox[0], item.path_infos[0].source_index),+ )+++def _assign_vector_path_lane(+ bbox: BBox,+ lanes: list[_TextLane],+ median_height: float,+) -> int | None:+ """按中心点和水平覆盖率把 Path 唯一分配给一个正文栏带。"""++ center_x = _bbox_center_x(bbox)+ path_width = max(0.1, bbox[2] - bbox[0])+ tolerance = 0.75 * median_height+ matches: list[tuple[float, float, int]] = []+ for lane_index, lane in enumerate(lanes):+ if not lane.left - tolerance <= center_x <= lane.right + tolerance:+ continue+ overlap = max(0.0, min(bbox[2], lane.right) - max(bbox[0], lane.left))+ coverage = overlap / path_width+ lane_center = (lane.left + lane.right) / 2.0+ matches.append((-coverage, abs(center_x - lane_center), lane_index))+ return min(matches)[2] if matches else None+++def _is_vector_formula_path_member(+ bbox: BBox,+ lane: _TextLane,+ median_height: float,+) -> bool:+ """保留小字形轮廓和细横线,过滤跨栏或过大的普通矢量对象。"""++ width = bbox[2] - bbox[0]+ height = bbox[3] - bbox[1]+ lane_width = max(0.1, lane.right - lane.left)+ is_glyph = width <= 3.0 * median_height and height <= 3.0 * median_height+ is_formula_rule = height <= 0.2 * median_height and width <= lane_width + median_height+ return is_glyph or is_formula_rule+++def _connect_vector_path_members(+ members: list[PDFPathInfo],+ lane_index: int,+ median_height: float,+) -> list[_VectorPathComponent]:+ """用扩张 bbox 的网格邻接和并查集连接同栏 Path,避免全量两两比较。"""++ if not members:+ return []+ ordered = sorted(members, key=lambda item: item.source_index)+ parents = list(range(len(ordered)))++ def find(index: int) -> int:+ """查找并压缩一个 Path 的并查集根节点。"""++ while parents[index] != index:+ parents[index] = parents[parents[index]]+ index = parents[index]+ return index++ def merge(first: int, second: int) -> None:+ """合并两个相交扩张框所属的连通分量。"""++ first_root = find(first)+ second_root = find(second)+ if first_root != second_root:+ parents[second_root] = first_root++ margin = 0.5 * median_height+ cell_size = max(1.0, median_height)+ expanded_bboxes = [_expand_bbox(item.bbox, margin) for item in ordered]+ grid: dict[tuple[int, int], list[int]] = {}+ seen_pairs: set[tuple[int, int]] = set()+ for index, bbox in enumerate(expanded_bboxes):+ start_x = int(bbox[0] // cell_size)+ end_x = int(bbox[2] // cell_size)+ start_y = int(bbox[1] // cell_size)+ end_y = int(bbox[3] // cell_size)+ for cell_x in range(start_x, end_x + 1):+ for cell_y in range(start_y, end_y + 1):+ cell = (cell_x, cell_y)+ for other_index in grid.get(cell, []):+ pair = (other_index, index)+ if pair in seen_pairs:+ continue+ seen_pairs.add(pair)+ if _bbox_intersects(bbox, expanded_bboxes[other_index]):+ merge(index, other_index)+ grid.setdefault(cell, []).append(index)++ grouped: dict[int, list[PDFPathInfo]] = {}+ for index, path_info in enumerate(ordered):+ grouped.setdefault(find(index), []).append(path_info)+ return [+ _VectorPathComponent(+ lane_index=lane_index,+ path_infos=group,+ bbox=_bbox_union_many([item.bbox for item in group]),+ )+ for group in grouped.values()+ ]+++def _is_vector_formula_core(+ component: _VectorPathComponent,+ lane: _TextLane,+ median_height: float,+ page_size: tuple[float, float],+ container_bboxes: list[BBox],+) -> bool:+ """按复杂度、尺寸、正文碰撞和容器优先级校验公式主体组件。"""++ path_count = len(component.path_infos)+ complex_count = sum(+ item.segment_count >= _VECTOR_FORMULA_COMPLEX_SEGMENTS+ for item in component.path_infos+ )+ if (+ path_count < _VECTOR_FORMULA_MIN_PATHS+ or complex_count < _VECTOR_FORMULA_MIN_COMPLEX_PATHS+ or complex_count / path_count < _VECTOR_FORMULA_MIN_COMPLEX_RATIO+ ):+ return False++ bbox = component.bbox+ width = bbox[2] - bbox[0]+ height = bbox[3] - bbox[1]+ if not (+ width >= 2.5 * median_height+ and 0.9 * median_height <= height <= 8.0 * median_height+ and width >= 1.4 * height+ ):+ return False+ page_height = page_size[1]+ if bbox[3] <= 0.05 * page_height or bbox[1] >= 0.95 * page_height:+ return False+ if any(+ _bbox_overlap_in_smaller(bbox, container_bbox) >= 0.5+ for container_bbox in container_bboxes+ ):+ return False+ return not any(+ _vector_formula_collides_with_text(bbox, line, line_bbox, median_height)+ for line, line_bbox in lane.lines+ )+++def _vector_formula_collides_with_text(+ formula_bbox: BBox,+ line: _LineItem,+ line_bbox: BBox,+ median_height: float,+) -> bool:+ """排除覆盖正文或紧贴正文同行的 Path 组件,独立公式编号除外。"""++ if _standalone_formula_number_marker(line.text) is not None:+ return False+ if _bbox_overlap_in_first(formula_bbox, line_bbox) >= 0.2:+ return True+ horizontal_gap = max(+ formula_bbox[0] - line_bbox[2],+ line_bbox[0] - formula_bbox[2],+ 0.0,+ )+ return (+ _bbox_axis_overlap_ratio(formula_bbox, line_bbox, axis="y") >= 0.5+ and horizontal_gap <= median_height+ )+++def _attach_vector_formula_rules(+ candidates: list[_VectorFormulaCandidate],+ components: list[_VectorPathComponent],+ median_height: float,+) -> None:+ """把靠近公式主体且横向覆盖充分的孤立细横线唯一并入主体。"""++ used_sources = {+ source_index+ for candidate in candidates+ for source_index in candidate.path_source_indices+ }+ for component in components:+ component_sources = {item.source_index for item in component.path_infos}+ if component_sources & used_sources or not all(+ item.bbox[3] - item.bbox[1] <= 0.2 * median_height+ for item in component.path_infos+ ):+ continue+ matches = [+ (+ _bbox_distance(candidate.bbox, component.bbox),+ abs(_bbox_center_y(candidate.bbox) - _bbox_center_y(component.bbox)),+ candidate_index,+ )+ for candidate_index, candidate in enumerate(candidates)+ if candidate.lane_index == component.lane_index+ and _bbox_distance(candidate.bbox, component.bbox) <= 0.5 * median_height+ and _bbox_axis_overlap_ratio(candidate.bbox, component.bbox, axis="x") >= 0.5+ ]+ if not matches:+ continue+ candidate = candidates[min(matches)[2]]+ candidate.bbox = _bbox_union(candidate.bbox, component.bbox)+ candidate.path_source_indices.update(component_sources)+ used_sources.update(component_sources)+++def _attach_vector_formula_path_numbers(+ candidates: list[_VectorFormulaCandidate],+ components: list[_VectorPathComponent],+ lanes: list[_TextLane],+ median_height: float,+) -> None:+ """把栏右缘的小型复杂 Path 组件作为公式编号并入唯一主体。"""++ used_sources = {+ source_index+ for candidate in candidates+ for source_index in candidate.path_source_indices+ }+ for component in components:+ component_sources = {item.source_index for item in component.path_infos}+ if component_sources & used_sources or not _is_vector_formula_number_component(+ component,+ lanes[component.lane_index],+ median_height,+ ):+ continue+ matches = _vector_formula_number_matches(+ component.bbox,+ component.lane_index,+ candidates,+ median_height,+ )+ if not matches:+ continue+ candidate = candidates[min(matches)[3]]+ candidate.bbox = _bbox_union(candidate.bbox, component.bbox)+ candidate.path_source_indices.update(component_sources)+ candidate.has_number = True+ used_sources.update(component_sources)+++def _is_vector_formula_number_component(+ component: _VectorPathComponent,+ lane: _TextLane,+ median_height: float,+) -> bool:+ """识别位于栏右缘、尺寸接近正文行高的全复杂路径编号组件。"""++ path_count = len(component.path_infos)+ bbox = component.bbox+ width = bbox[2] - bbox[0]+ height = bbox[3] - bbox[1]+ return (+ _VECTOR_FORMULA_NUMBER_MIN_PATHS+ <= path_count+ <= _VECTOR_FORMULA_NUMBER_MAX_PATHS+ and all(+ item.segment_count >= _VECTOR_FORMULA_COMPLEX_SEGMENTS+ for item in component.path_infos+ )+ and 0.5 * median_height <= width <= 2.0 * median_height+ and 0.6 * median_height <= height <= 1.4 * median_height+ and abs(lane.right - bbox[2]) <= 1.5 * median_height+ )+++def _vector_formula_number_matches(+ number_bbox: BBox,+ lane_index: int,+ candidates: list[_VectorFormulaCandidate],+ median_height: float,+) -> list[tuple[float, float, float, int]]:+ """返回编号可关联的公式主体及稳定排序分值。"""++ matches: list[tuple[float, float, float, int]] = []+ for candidate_index, candidate in enumerate(candidates):+ if candidate.has_number or candidate.lane_index != lane_index:+ continue+ vertical_overlap = _bbox_axis_overlap_ratio(candidate.bbox, number_bbox, axis="y")+ if (+ number_bbox[0] < candidate.bbox[2]+ or vertical_overlap < 0.6+ ):+ continue+ center_distance = abs(_bbox_center_y(candidate.bbox) - _bbox_center_y(number_bbox))+ horizontal_gap = max(0.0, number_bbox[0] - candidate.bbox[2])+ matches.append(+ (-vertical_overlap, center_distance, horizontal_gap / max(0.1, median_height), candidate_index)+ )+ return matches+++def _attach_vector_formula_text_numbers(+ candidates: list[_VectorFormulaCandidate],+ lanes: list[_TextLane],+ median_height: float,+ claimed_line_indices: set[int],+) -> set[int]:+ """关联可提取的独立公式编号并认领其文本身份,防止重复输出。"""++ claimed: set[int] = set()+ for lane_index, lane in enumerate(lanes):+ for line, bbox in sorted(lane.lines, key=lambda item: (item[1][1], item[1][0])):+ if line.source_index in claimed_line_indices or _standalone_formula_number_marker(line.text) is None:+ continue+ width = bbox[2] - bbox[0]+ height = bbox[3] - bbox[1]+ if not (+ 0.5 * median_height <= width <= 2.0 * median_height+ and 0.6 * median_height <= height <= 1.4 * median_height+ and abs(lane.right - bbox[2]) <= 1.5 * median_height+ ):+ continue+ matches = _vector_formula_number_matches(+ bbox,+ lane_index,+ candidates,+ median_height,+ )+ if not matches:+ continue+ candidate = candidates[min(matches)[3]]+ candidate.bbox = _bbox_union(candidate.bbox, bbox)+ candidate.has_number = True+ claimed.add(line.source_index)+ return claimed+++def _standalone_formula_number_marker(text: str) -> str | None:+ """仅接受整行由圆括号公式编号构成的文本,不接纳带正文前缀的后缀。"""++ parts = _split_trailing_formula_number(text)+ if parts is None:+ return None+ prefix, marker = parts+ return marker if not prefix else None++def _build_formula_like_blocks(lines: list[_LineItem],table_bboxes: list[BBox],diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.pyindex 736f03ed..9c5a7f8e 100644--- a/mineru/backend/flash/native_pdf/models.py+++ b/mineru/backend/flash/native_pdf/models.py@@ -10,6 +10,7 @@ from typing import Any, Literalfrom pdftext.schema import Charfrom mineru.types import BBox+from mineru.utils.pdf_document import PDFPathInfo@dataclass(slots=True)@@ -124,6 +125,7 @@ class _PageSource:drawing_lines: list[_AxisLine]image_bboxes: list[BBox] = field(default_factory=list)form_bboxes: list[BBox] = field(default_factory=list)+ path_infos: list[PDFPathInfo] = field(default_factory=list)@dataclass(slots=True)diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.pyindex 7cc0098e..693e26c4 100644--- a/mineru/backend/flash/native_pdf/pipeline.py+++ b/mineru/backend/flash/native_pdf/pipeline.py@@ -48,7 +48,10 @@ from .graphics import (_form_supersedes_nested_bbox,_select_form_image_bboxes,)-from .formulas import _build_formula_like_blocks+from .formulas import (+ _build_formula_like_blocks,+ _build_vector_formula_blocks,+)from .auxiliary_text import (_classify_page_auxiliary_text,_classify_repeated_page_marginals,@@ -91,6 +94,7 @@ def _analyze_native_document(pdf_doc: PDFDocument) -> list[list[dict[str, Any]]]drawing_lines=drawing_lines,image_bboxes=pdf_doc.get_page_image_bboxes(page_idx),form_bboxes=pdf_doc.get_page_form_bboxes(page_idx),+ path_infos=pdf_doc.get_page_path_infos(page_idx),)prepared_pages.append(_prepare_page_source(source))@@ -142,11 +146,20 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:table_blocks + form_image_blocks + graphic_blocks,claimed_line_indices | claimed_form_line_indices | claimed_graphic_line_indices,)+ vector_formula_blocks, claimed_vector_number_indices = _build_vector_formula_blocks(+ source,+ table_blocks + form_image_blocks + graphic_blocks + raster_image_blocks,+ claimed_line_indices+ | claimed_form_line_indices+ | claimed_graphic_line_indices+ | claimed_raster_line_indices,+ )claimed_line_indices = (claimed_line_indices| claimed_form_line_indices| claimed_graphic_line_indices| claimed_raster_line_indices+ | claimed_vector_number_indices)remaining_lines = _merge_same_baseline_text_lines([line for line in source.lines if line.source_index not in claimed_line_indices],@@ -164,7 +177,13 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:remaining_lines=remaining_lines,table_bboxes=table_bboxes,drawing_lines=source.drawing_lines,- fixed_blocks=table_blocks + form_image_blocks + graphic_blocks + raster_image_blocks,+ fixed_blocks=(+ table_blocks+ + form_image_blocks+ + graphic_blocks+ + raster_image_blocks+ + vector_formula_blocks+ ),)_classify_page_auxiliary_text(prepared)return prepared@@ -303,7 +322,7 @@ def _normalize_output_block(content = _sanitize_pdf_control_text(content, preserve_newlines=True)block_type = block.get("type")normalized_type = block_type if block_type in _OUTPUT_BLOCK_TYPES else "text"- if normalized_type != "image" and not content.strip():+ if normalized_type not in {"image", "equation"} and not content.strip():return Nonenormalized_bbox = _normalize_bbox_to_thousandths(bbox, page_size)return {diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.pyindex 00850895..3a0915f2 100644--- a/mineru/utils/pdf_document.py+++ b/mineru/utils/pdf_document.py@@ -76,6 +76,18 @@ class PDFDrawingLine:orientation: Literal["horizontal", "vertical"]+@dataclass(frozen=True)+class PDFPathInfo:+ """PDF Path 的可见几何和绘制特征,bbox 使用页面左上原点坐标。"""++ bbox: BBox+ segment_count: int+ fill_visible: bool+ stroke_visible: bool+ form_depth: int+ source_index: int++@dataclassclass _PathSubpath:"""保存一个 PDF Path 子路径的点、直线段和闭合状态。"""@@ -321,6 +333,16 @@ class PDFDocument:page_rotation = 0return _extract_page_drawing_lines(page, page_bbox, page_rotation)+ def get_page_path_infos(self, page_idx: int) -> list[PDFPathInfo]:+ """提取页面及嵌套 Form 中的 Path 几何和绘制特征。"""+ with self._open_page(page_idx) as page:+ page_bbox = _normalize_pdf_page_bbox(page.get_bbox())+ try:+ page_rotation = int(page.get_rotation()) % 360+ except Exception:+ page_rotation = 0+ return _extract_page_path_infos(page, page_bbox, page_rotation)+def get_page_image_bboxes(self, page_idx: int) -> list[BBox]:"""提取页面及嵌套 Form 中的点阵图 bbox,并转换为页面左上原点坐标。"""with self._open_page(page_idx) as page:@@ -494,15 +516,15 @@ def _get_raw_object_matrix(raw_obj: Any) -> tuple[float, float, float, float, fl)-def _walk_raw_page_objects(+def _walk_raw_page_objects_with_depth(container: Any,*,is_form: bool,parent_matrix: tuple[float, float, float, float, float, float],depth: int,target_type: int,-) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:- """递归遍历页面或 Form 中的目标对象,并携带累积到页面坐标的矩阵。"""+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float], int]]:+ """递归遍历目标对象,并携带累积矩阵及所在 Form 深度。"""if depth >= DRAWING_FORM_MAX_DEPTH:return@@ -530,9 +552,9 @@ def _walk_raw_page_objects(continueif object_type == target_type:- yield raw_obj, combined_matrix+ yield raw_obj, combined_matrix, depthif object_type == pdfium_c.FPDF_PAGEOBJ_FORM:- yield from _walk_raw_page_objects(+ yield from _walk_raw_page_objects_with_depth(raw_obj,is_form=True,parent_matrix=combined_matrix,@@ -541,6 +563,26 @@ def _walk_raw_page_objects()+def _walk_raw_page_objects(+ container: Any,+ *,+ is_form: bool,+ parent_matrix: tuple[float, float, float, float, float, float],+ depth: int,+ target_type: int,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:+ """兼容既有调用,仅返回目标对象及累积到页面坐标的矩阵。"""++ for raw_obj, matrix, _form_depth in _walk_raw_page_objects_with_depth(+ container,+ is_form=is_form,+ parent_matrix=parent_matrix,+ depth=depth,+ target_type=target_type,+ ):+ yield raw_obj, matrix++def _walk_raw_path_objects(container: Any,*,@@ -571,6 +613,21 @@ def _iter_raw_path_objects()+def _iter_raw_path_objects_with_depth(+ page: pdfium.PdfPage,+) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float], int]]:+ """遍历全部 Path,并保留其所在 Form 深度供上层过滤图标。"""++ identity = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)+ yield from _walk_raw_page_objects_with_depth(+ page,+ is_form=False,+ parent_matrix=identity,+ depth=0,+ target_type=pdfium_c.FPDF_PAGEOBJ_PATH,+ )++def _iter_raw_image_objects(page: pdfium.PdfPage,) -> Iterator[tuple[Any, tuple[float, float, float, float, float, float]]]:@@ -754,6 +811,64 @@ def _transform_path_subpath()+def _path_info_from_object(+ raw_obj: Any,+ matrix: tuple[float, float, float, float, float, float],+ page_bbox: BBox,+ page_rotation: int,+ form_depth: int,+ source_index: int,+) -> PDFPathInfo | None:+ """将一个原始 Path 转换为页面几何;贝塞尔控制点也纳入保守 bbox。"""++ try:+ segment_count = int(pdfium_c.FPDFPath_CountSegments(raw_obj))+ except Exception:+ return None+ if segment_count <= 0:+ return None++ fill_visible, stroke_visible = _get_path_visibility(raw_obj)+ points = [+ point+ for raw_subpath in _read_raw_path_subpaths(raw_obj)+ for point in _transform_path_subpath(+ raw_subpath,+ matrix,+ page_bbox,+ page_rotation,+ ).points+ ]+ if not points:+ return None+ coordinates = [coordinate for point in points for coordinate in point]+ if not all(math.isfinite(value) for value in coordinates):+ return None++ page_width, page_height = _drawing_page_size(page_bbox, page_rotation)+ stroke_margin = 0.0+ if stroke_visible:+ a, b, c, d, _, _ = matrix+ stroke_scale = max(math.hypot(a, b), math.hypot(c, d))+ stroke_margin = 0.5 * _get_raw_stroke_width(raw_obj) * stroke_scale+ bbox = (+ max(0.0, min(point[0] for point in points) - stroke_margin),+ max(0.0, min(point[1] for point in points) - stroke_margin),+ min(page_width, max(point[0] for point in points) + stroke_margin),+ min(page_height, max(point[1] for point in points) + stroke_margin),+ )+ if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]:+ return None+ return PDFPathInfo(+ bbox=bbox,+ segment_count=segment_count,+ fill_visible=fill_visible,+ stroke_visible=stroke_visible,+ form_depth=form_depth,+ source_index=source_index,+ )++def _get_thin_filled_subpath_line(subpath: _PathSubpath,page_size: tuple[float, float],@@ -1087,6 +1202,34 @@ def _extract_page_form_bboxes(return sorted(form_bboxes, key=lambda bbox: (bbox[1], bbox[0], bbox[3], bbox[2]))+def _extract_page_path_infos(+ page: pdfium.PdfPage,+ page_bbox: BBox,+ page_rotation: int,+) -> list[PDFPathInfo]:+ """在调用方持有 PDFium 锁时提取 Path 信息,并隔离单对象异常。"""++ path_infos: list[PDFPathInfo] = []+ for source_index, (raw_obj, matrix, form_depth) in enumerate(+ _iter_raw_path_objects_with_depth(page)+ ):+ try:+ path_info = _path_info_from_object(+ raw_obj,+ matrix,+ page_bbox,+ page_rotation,+ form_depth,+ source_index,+ )+ except Exception:+ # PDFium 遇到个别损坏 Path 时,保留同页其他对象的有效结果。+ continue+ if path_info is not None:+ path_infos.append(path_info)+ return path_infos++def _extract_page_drawing_lines(page: pdfium.PdfPage,page_bbox: BBox,diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.pyindex c5539554..94ecd19d 100644--- a/tests/unittest/test_flash_pdf_formulas.py+++ b/tests/unittest/test_flash_pdf_formulas.py@@ -9,6 +9,7 @@ from mineru.backend.flash.native_pdf import (line_merging,models,)+from mineru.utils.pdf_document import PDFPathInfofrom _flash_pdf_test_utils import (@@ -35,6 +36,187 @@ def _formula_member()+def _vector_path(+ bbox: tuple[float, float, float, float],+ source_index: int,+ *,+ segment_count: int = 16,+ fill_visible: bool = True,+ stroke_visible: bool = False,+ form_depth: int = 0,+) -> PDFPathInfo:+ """构造矢量公式检测测试使用的 Path 信息。"""++ return PDFPathInfo(+ bbox=bbox,+ segment_count=segment_count,+ fill_visible=fill_visible,+ stroke_visible=stroke_visible,+ form_depth=form_depth,+ source_index=source_index,+ )+++def _vector_formula_body_paths(+ *,+ left: float = 20.0,+ top: float = 50.0,+ source_start: int = 0,+) -> list[PDFPathInfo]:+ """构造满足复杂度和尺寸约束的六字形矢量公式主体。"""++ return [+ _vector_path(+ (left + index * 6.0, top, left + index * 6.0 + 4.0, top + 12.0),+ source_start + index,+ )+ for index in range(6)+ ]+++def _vector_formula_source(+ *path_infos: PDFPathInfo,+ page_size: tuple[float, float] = (100.0, 120.0),+ extra_lines: list[models._LineItem] | None = None,+) -> models._PageSource:+ """构造具有稳定正文栏带且公式所在高度留白的页面源。"""++ body_font = ("Body", 0)+ lines = [+ _text_line(+ f"body-{index}",+ (0.0, top, 100.0, top + 10.0),+ index,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ )+ for index, top in enumerate((0.0, 20.0, 80.0, 100.0))+ ]+ lines.extend(extra_lines or [])+ return models._PageSource(+ page_size=page_size,+ lines=lines,+ chars=[],+ drawing_lines=[],+ path_infos=list(path_infos),+ )+++def test_vector_formula_paths_and_detached_path_number_form_one_empty_equation() -> None:+ """验证矢量主体与远距栏右缘路径编号形成一个空内容公式。"""++ body_paths = _vector_formula_body_paths()+ number_paths = [+ _vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), 10 + index)+ for index in range(3)+ ]+ blocks, claimed = formulas._build_vector_formula_blocks(+ _vector_formula_source(*body_paths, *number_paths),+ [],+ set(),+ )++ assert claimed == set()+ assert blocks == [+ {+ "type": "equation",+ "bbox": (19.0, 49.0, 100.0, 63.0),+ "angle": 0,+ "content": "",+ }+ ]+++def test_vector_formula_claims_text_number_but_keeps_content_empty() -> None:+ """验证可提取的独立编号并入路径公式并唯一认领,但不充当公式正文。"""++ number = _text_line("(12)", (91.0, 51.0, 99.0, 60.0), 20, effective_height=9.0)+ blocks, claimed = formulas._build_vector_formula_blocks(+ _vector_formula_source(*_vector_formula_body_paths(), extra_lines=[number]),+ [],+ set(),+ )++ assert claimed == {20}+ assert blocks[0]["type"] == "equation"+ assert blocks[0]["content"] == ""+ assert blocks[0]["bbox"] == pytest.approx((19.0, 49.0, 100.0, 63.0))+++def test_vector_formula_rejects_unmatched_number_rules_strokes_forms_and_inline_paths() -> None:+ """验证无主体编号、细规则、描边、Form 图标和正文同行路径均不会误报。"""++ unmatched_number = [+ _vector_path((91.0 + index * 3.0, 51.0, 93.0 + index * 3.0, 60.0), index)+ for index in range(3)+ ]+ rules = [+ _vector_path((10.0 + index * 12.0, 70.0, 20.0 + index * 12.0, 70.5), 10 + index, segment_count=5)+ for index in range(6)+ ]+ excluded = [+ _vector_path((20.0, 50.0, 24.0, 62.0), 30, stroke_visible=True),+ _vector_path((26.0, 50.0, 30.0, 62.0), 31, form_depth=1),+ ]+ inline_paths = _vector_formula_body_paths(top=20.0, source_start=40)+ blocks, claimed = formulas._build_vector_formula_blocks(+ _vector_formula_source(*unmatched_number, *rules, *excluded, *inline_paths),+ [],+ set(),+ )++ assert blocks == []+ assert claimed == set()+++def test_vector_formula_respects_columns_and_existing_containers() -> None:+ """验证同高双栏主体不互连,且高优先级容器覆盖的主体被排除。"""++ left_lines = [+ _text_line(f"left-{index}", (0.0, top, 100.0, top + 10.0), index, effective_height=10.0)+ for index, top in enumerate((0.0, 20.0, 80.0, 100.0))+ ]+ right_lines = [+ _text_line(+ f"right-{index}",+ (120.0, top, 220.0, top + 10.0),+ 10 + index,+ effective_height=10.0,+ )+ for index, top in enumerate((0.0, 20.0, 80.0, 100.0))+ ]+ source = models._PageSource(+ page_size=(220.0, 120.0),+ lines=[*left_lines, *right_lines],+ chars=[],+ drawing_lines=[],+ path_infos=[+ *_vector_formula_body_paths(left=20.0, source_start=0),+ *_vector_formula_body_paths(left=140.0, source_start=20),+ ],+ )++ column_blocks, column_claimed = formulas._build_vector_formula_blocks(+ source,+ [],+ set(),+ )+ blocks, claimed = formulas._build_vector_formula_blocks(+ source,+ [{"type": "image", "bbox": (130.0, 45.0, 180.0, 67.0), "content": ""}],+ set(),+ )++ assert column_claimed == set()+ assert len(column_blocks) == 2+ assert column_blocks[0]["bbox"] == pytest.approx((19.0, 49.0, 55.0, 63.0))+ assert column_blocks[1]["bbox"] == pytest.approx((139.0, 49.0, 175.0, 63.0))+ assert claimed == set()+ assert len(blocks) == 1+ assert blocks[0]["bbox"] == pytest.approx((19.0, 49.0, 55.0, 63.0))++def test_detached_formula_sidecar_sharing_middle_row_moves_to_trailing_line() -> None:"""验证纯 bbox 规则会后置与正文共享中间视觉行的远距窄幅 sidecar。"""diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.pyindex c9851087..7ede448b 100644--- a/tests/unittest/test_flash_pdf_pipeline.py+++ b/tests/unittest/test_flash_pdf_pipeline.py@@ -114,3 +114,24 @@ def test_output_normalization_preserves_new_flash_types(block_type: str) -> Noneassert block is not Noneassert block["type"] == block_type+++def test_output_normalization_keeps_empty_equation_but_drops_empty_text() -> None:+ """验证纯矢量公式可保留空 content,普通空文本仍不会进入 model_list。"""++ equation = pipeline._normalize_output_block(+ {"type": "equation", "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": ""},+ (100.0, 100.0),+ )+ text = pipeline._normalize_output_block(+ {"type": "text", "bbox": (10.0, 20.0, 40.0, 50.0), "angle": 0, "content": ""},+ (100.0, 100.0),+ )++ assert equation == {+ "type": "equation",+ "bbox": [0.1, 0.2, 0.4, 0.5],+ "angle": 0,+ "content": "",+ }+ assert text is Nonediff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.pyindex f9073bfe..8f177d9f 100644--- a/tests/unittest/test_pdf_document.py+++ b/tests/unittest/test_pdf_document.py@@ -41,6 +41,13 @@ def _build_drawing_pdf() -> bytes:# 斜线不属于表格横竖线,公共接口应过滤。canvas.line(10, 10, 90, 50)+ # 闭合贝塞尔用于验证 Path 信息保留控制点形成的几何范围。+ curve = canvas.beginPath()+ curve.moveTo(10, 80)+ curve.curveTo(20, 95, 30, 95, 40, 80)+ curve.lineTo(10, 80)+ curve.close()+ canvas.drawPath(curve, stroke=0, fill=1)canvas.save()return output.getvalue()@@ -197,6 +204,15 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: pevents.append(f"image_bboxes:{lock.depth}:{page_bbox}:{page_rotation}")return []+ def fake_extract_page_path_infos(+ page: _FakePage,+ page_bbox: tuple[float, float, float, float],+ page_rotation: int,+ ) -> list[pdf_document.PDFPathInfo]:+ """记录完整 Path 几何遍历时仍由 PDFDocument 持有 PDFium 锁。"""+ events.append(f"path_infos:{lock.depth}:{page_bbox}:{page_rotation}")+ return []+def fake_extract_page_form_bboxes(page: _FakePage,page_bbox: tuple[float, float, float, float],@@ -210,6 +226,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: pmonkeypatch.setattr(pdf_document, "get_chars", fake_get_chars, raising=False)monkeypatch.setattr(pdf_document, "pdftext_get_chars", fake_get_chars, raising=False)monkeypatch.setattr(pdf_document, "_extract_page_drawing_lines", fake_extract_page_drawing_lines)+ monkeypatch.setattr(pdf_document, "_extract_page_path_infos", fake_extract_page_path_infos)monkeypatch.setattr(pdf_document, "_extract_page_image_bboxes", fake_extract_page_image_bboxes)monkeypatch.setattr(pdf_document, "_extract_page_form_bboxes", fake_extract_page_form_bboxes)@@ -221,6 +238,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: passert image.scale == 3assert doc.get_page_chars(0)[0]["char"] == "A"assert doc.get_page_drawing_lines(0) == []+ assert doc.get_page_path_infos(0) == []assert doc.get_page_image_bboxes(0) == []assert doc.get_page_form_bboxes(0) == []@@ -235,6 +253,7 @@ def test_pdf_document_methods_keep_page_access_inside_pdfium_lock(monkeypatch: passert "get_chars:1:[0.0, 10.0, 20.0, 0.0]:0" in eventsassert "textpage.close:1" in eventsassert "drawing_lines:1:(0.0, 0.0, 20.0, 10.0):0" in events+ assert "path_infos:1:(0.0, 0.0, 20.0, 10.0):0" in eventsassert "image_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in eventsassert "form_bboxes:1:(0.0, 0.0, 20.0, 10.0):0" in events@@ -273,6 +292,25 @@ def test_get_page_drawing_lines_extracts_forms_filled_rectangles_and_merges_segmassert lines[2].bbox == pytest.approx((10.0, 60.0, 90.0, 60.5))+def test_get_page_path_infos_preserves_bezier_visibility_depth_and_source_order() -> None:+ """验证完整 Path 接口保留贝塞尔 bbox、绘制模式、Form 深度和稳定源序号。"""++ with pdf_document.PDFDocument(_build_drawing_pdf()) as doc:+ path_infos = doc.get_page_path_infos(0)++ assert len(path_infos) == 7+ assert [item.source_index for item in path_infos] == [0, 1, 2, 3, 4, 6, 7]+ assert path_infos[0].bbox == pytest.approx((9.5, 19.5, 90.5, 20.5))+ assert not path_infos[0].fill_visible and path_infos[0].stroke_visible+ assert path_infos[3].bbox == pytest.approx((10.0, 60.0, 90.0, 60.5))+ assert path_infos[3].fill_visible and not path_infos[3].stroke_visible+ nested_path = next(item for item in path_infos if item.form_depth == 1)+ assert nested_path.bbox == pytest.approx((29.0, 99.0, 71.0, 101.0))+ bezier_path = path_infos[-1]+ assert bezier_path.segment_count == 5+ assert bezier_path.bbox == pytest.approx((10.0, 105.0, 40.0, 120.0))++def test_get_page_drawing_lines_applies_crop_box_and_page_rotation() -> None:"""验证页面 CropBox 与 90 度旋转被转换为左上原点坐标。"""with pdf_document.PDFDocument(_build_rotated_cropped_drawing_pdf()) as doc:@@ -291,6 +329,18 @@ def test_get_page_drawing_lines_applies_crop_box_and_page_rotation() -> None:assert line.width == pytest.approx(2.0)+def test_get_page_path_infos_applies_crop_box_page_rotation_and_stroke_width() -> None:+ """验证 Path bbox 在 CropBox 与页面旋转后仍保留可见描边宽度。"""++ with pdf_document.PDFDocument(_build_rotated_cropped_drawing_pdf()) as doc:+ path_infos = doc.get_page_path_infos(0)++ assert len(path_infos) == 1+ assert path_infos[0].bbox == pytest.approx((9.0, 4.0, 11.0, 86.0))+ assert path_infos[0].form_depth == 0+ assert path_infos[0].segment_count == 2++def test_get_page_image_bboxes_applies_forms_crop_box_rotation_and_clipping() -> None:"""验证点阵图接口递归 Form,并按 CropBox、页面旋转裁剪为左上坐标。"""with pdf_document.PDFDocument(_build_rotated_cropped_image_pdf()) as doc:@@ -381,3 +431,27 @@ def test_get_page_drawing_lines_skips_one_bad_path(monkeypatch: pytest.MonkeyPatassert len(lines) == 3assert all(line.start[1] != pytest.approx(20.0) for line in lines)assert [line.start[1] for line in lines] == pytest.approx([40.0, 60.25, 100.0])+++def test_get_page_path_infos_skips_one_bad_path(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证单个 Path 信息解析失败不会丢失同页其他有效对象。"""++ original_extract = pdf_document._path_info_from_object+ call_count = 0++ def flaky_extract(*args: Any, **kwargs: Any) -> pdf_document.PDFPathInfo | None:+ """仅让首个 Path 失败,后续对象仍调用真实实现。"""++ nonlocal call_count+ call_count += 1+ if call_count == 1:+ raise RuntimeError("broken path")+ return original_extract(*args, **kwargs)++ monkeypatch.setattr(pdf_document, "_path_info_from_object", flaky_extract)+ with pdf_document.PDFDocument(_build_drawing_pdf()) as doc:+ path_infos = doc.get_page_path_infos(0)++ assert call_count >= 8+ assert len(path_infos) == 6+ assert all(item.source_index != 0 for item in path_infos)