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: enhance inline text merging by adding support for overlapping clusters and compact formula detection
myhloli18a972f44774
diff --git a/mineru/backend/flash/native_pdf/formulas.py b/mineru/backend/flash/native_pdf/formulas.pyindex 9f2b46e8..11f5b0d5 100644--- a/mineru/backend/flash/native_pdf/formulas.py+++ b/mineru/backend/flash/native_pdf/formulas.py@@ -61,9 +61,40 @@ def _build_formula_like_blocks(local_page_width = page_size[1] if angle in {90, 270} else page_size[0]lanes = _infer_text_lanes(angle_geometry, local_page_width, median_height)for lane in lanes:- if lane.is_span or len(lane.lines) < 2:+ if lane.is_span:continuelane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ for line, bbox in list(lane.lines):+ if (+ line.compact_formula_cluster+ and _is_isolated_compact_formula_cluster(+ (line, bbox),+ lane,+ median_height,+ )+ ):+ content = _sanitize_pdf_control_text(+ line.text,+ preserve_newlines=False,+ ).strip()+ if not content:+ continue+ blocks.append(+ {+ "type": "equation",+ "bbox": line.bbox,+ "angle": angle,+ "content": content,+ }+ )+ claimed_source_indices.add(line.source_index)+ lane.lines = [+ item+ for item in lane.lines+ if item[0].source_index not in claimed_source_indices+ ]+ if len(lane.lines) < 2:+ continuedominant_body_font = _infer_formula_body_font(lane, median_height)anchors = _find_formula_spatial_anchors(lane,@@ -124,6 +155,53 @@ def _build_formula_like_blocks(return blocks, remaining_lines+def _is_isolated_compact_formula_cluster(+ candidate: tuple[_LineItem, BBox],+ lane: _TextLane,+ median_height: float,+) -> bool:+ """用上下正文邻行确认紧凑二维文本簇是独立行间公式。"""++ line, bbox = candidate+ if not line.compact_formula_cluster:+ return False+ lane_width = max(0.1, lane.right - lane.left)+ if bbox[2] - bbox[0] > 0.6 * lane_width:+ return False+ if bbox[3] - bbox[1] > 3.0 * median_height:+ return False++ candidate_center = _bbox_center_y(bbox)+ body_rows = [+ item+ for item in lane.lines+ if item[0].source_index != line.source_index+ and item[1][2] - item[1][0] >= 0.6 * lane_width+ and 0.8 * median_height+ <= _line_effective_height(*item)+ <= 1.25 * median_height+ ]+ rows_above = [+ item+ for item in body_rows+ if _bbox_center_y(item[1]) < candidate_center+ ]+ rows_below = [+ item+ for item in body_rows+ if _bbox_center_y(item[1]) > candidate_center+ ]+ if not rows_above or not rows_below:+ return False+ previous = max(rows_above, key=lambda item: _bbox_center_y(item[1]))+ following = min(rows_below, key=lambda item: _bbox_center_y(item[1]))+ return (+ candidate_center - _bbox_center_y(previous[1]) <= 2.5 * median_height+ and _bbox_center_y(following[1]) - candidate_center+ <= 2.5 * median_height+ )++def _find_formula_spatial_anchors(lane: _TextLane,median_height: float,@@ -177,8 +255,10 @@ def _find_formula_spatial_anchors(detached_below_body = body_bottom < center_y <= body_bottom + 6.0 * median_heightif not body_top <= center_y <= body_bottom and not detached_below_body:continue- has_left_peer = any(- other_line.source_index != line.source_index+ left_peers = [+ (other_line, other_bbox)+ for other_line, other_bbox in lane.lines+ if other_line.source_index != line.source_indexand other_bbox[2] - other_bbox[0] <= 0.75 * lane_widthand _bbox_center_x(other_bbox) < bbox[0]and (@@ -196,9 +276,21 @@ def _find_formula_spatial_anchors(_line_effective_height(other_line, other_bbox),))- for other_line, other_bbox in lane.lines- )- if has_left_peer:+ ]+ if is_short_right_anchor and not has_formula_number_suffix:+ # 非编号短锚点必须与左侧主体真正分离;分母字符与正文横向重叠时不能扩张成公式。+ if any(+ _bbox_axis_overlap_ratio(bbox, other_bbox, axis="x") >= 0.5+ for _other_line, other_bbox in left_peers+ ):+ continue+ minimum_gap = max(0.5, 0.1 * line_height)+ if not any(+ bbox[0] - other_bbox[2] >= minimum_gap+ for _other_line, other_bbox in left_peers+ ):+ continue+ if left_peers:anchors.append(_FormulaAnchor(line=line,@@ -573,4 +665,3 @@ def _formula_members_to_block("angle": angle,"content": content,}-diff --git a/mineru/backend/flash/native_pdf/line_layout.py b/mineru/backend/flash/native_pdf/line_layout.pyindex 9846b6f5..0a541e8c 100644--- a/mineru/backend/flash/native_pdf/line_layout.py+++ b/mineru/backend/flash/native_pdf/line_layout.py@@ -108,7 +108,15 @@ def _effective_text_row_gap(previous_line, previous_bbox = previous_current_line, current_bbox = current- return current_bbox[1] - (previous_bbox[1] + _line_effective_height(previous_line, previous_bbox))+ if previous_line.restored_inline_cluster:+ # 二维文本簇的 bbox 底边是真实分母边界;同时截断深度重叠,避免相邻分式互相成为段落屏障。+ return max(+ current_bbox[1] - previous_bbox[3],+ -0.25 * _line_effective_height(previous_line, previous_bbox),+ )+ return current_bbox[1] - (+ previous_bbox[1] + _line_effective_height(previous_line, previous_bbox)+ )def _infer_text_lanes(@@ -479,4 +487,3 @@ def _connection_crosses_table())return connector is not None and any(_bbox_intersects(connector, table_bbox) for table_bbox in table_bboxes)-diff --git a/mineru/backend/flash/native_pdf/line_merging.py b/mineru/backend/flash/native_pdf/line_merging.pyindex 990ef0d7..31b8cf0d 100644--- a/mineru/backend/flash/native_pdf/line_merging.py+++ b/mineru/backend/flash/native_pdf/line_merging.py@@ -9,11 +9,16 @@ import statisticsfrom mineru.types import BBox-from .models import _LineItem+from .models import (+ _LineItem,+ _TextLane,+)from .geometry import (+ _bbox_axis_overlap_ratio,_bbox_center_y,_bbox_intersects,_bbox_union_many,+ _horizontal_bbox_gap,_rotate_bbox_to_upright,)from .native_text import (@@ -89,6 +94,250 @@ def _merge_same_baseline_text_lines(return output+def _merge_overlapping_inline_text_clusters(+ lines: list[_LineItem],+ page_size: tuple[float, float],+ table_bboxes: list[BBox],+) -> list[_LineItem]:+ """在容器认领后恢复由分子、分母和上下标拆成的二维物理文本行。"""++ if len(lines) < 2:+ return list(lines)++ consumed_source_indices: set[int] = set()+ merged_lines: list[_LineItem] = []+ for angle in sorted({line.angle for line in lines}):+ angle_geometry = [(line, _rotate_bbox_to_upright(line.bbox, page_size, angle)) for line in lines if line.angle == angle]+ if len(angle_geometry) < 2:+ continue+ angle_median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in angle_geometry)+ local_page_width = page_size[1] if angle in {90, 270} else page_size[0]+ lanes = _infer_text_lanes(+ angle_geometry,+ local_page_width,+ angle_median_height,+ )+ for lane in lanes:+ if lane.is_span or len(lane.lines) < 2:+ continue+ lane.lines.sort(key=lambda item: (item[1][1], item[1][0], item[0].source_index))+ lane_median_height = statistics.median(_line_effective_height(line, bbox) for line, bbox in lane.lines)+ parents = list(range(len(lane.lines)))++ def find(index: int) -> int:+ """查找当前栏二维文本簇并查集的根节点。"""++ while parents[index] != index:+ parents[index] = parents[parents[index]]+ index = parents[index]+ return index++ def union(first_index: int, second_index: int) -> None:+ """合并两个满足二维物理行邻接条件的成员。"""++ first_root = find(first_index)+ second_root = find(second_index)+ if first_root != second_root:+ parents[second_root] = first_root++ for first_index, first in enumerate(lane.lines):+ for second_index in range(first_index + 1, len(lane.lines)):+ second = lane.lines[second_index]+ if _overlapping_inline_cluster_pair_is_connected(+ first,+ second,+ lane_median_height,+ table_bboxes,+ ):+ union(first_index, second_index)++ groups: dict[int, list[tuple[_LineItem, BBox]]] = {}+ for index, item in enumerate(lane.lines):+ groups.setdefault(find(index), []).append(item)+ for members in groups.values():+ cluster_kind = _classify_overlapping_inline_cluster(+ members,+ lane,+ lane_median_height,+ table_bboxes,+ )+ if cluster_kind is None:+ continue+ merged_lines.append(+ _merge_overlapping_inline_cluster(+ members,+ page_size,+ lane_median_height,+ compact_formula_cluster=cluster_kind == "formula",+ )+ )+ consumed_source_indices.update(line.source_index for line, _bbox in members)++ output = [line for line in lines if line.source_index not in consumed_source_indices]+ output.extend(merged_lines)+ output.sort(+ key=lambda line: (+ line.angle,+ _rotate_bbox_to_upright(+ line.bbox,+ page_size,+ line.angle,+ )[1],+ _rotate_bbox_to_upright(+ line.bbox,+ page_size,+ line.angle,+ )[0],+ line.source_index,+ )+ )+ return output+++def _overlapping_inline_cluster_pair_is_connected(+ first: tuple[_LineItem, BBox],+ second: tuple[_LineItem, BBox],+ median_height: float,+ table_bboxes: list[BBox],+) -> bool:+ """判断两个同栏成员是否为同一二维物理行中的重叠片段。"""++ first_line, first_bbox = first+ second_line, second_bbox = second+ if first_line.angle != second_line.angle:+ return False+ if first_line.semantic_type != second_line.semantic_type:+ return False+ if _connection_crosses_table(+ first_line.bbox,+ second_line.bbox,+ table_bboxes,+ ):+ return False+ if _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="y") < 0.55:+ return False++ horizontal_gap = _horizontal_bbox_gap(first_bbox, second_bbox)+ if first_line.visual_row_id == second_line.visual_row_id and (first_line.split_from_row or second_line.split_from_row):+ return horizontal_gap <= 3.0 * median_height+ pair_height = max(+ _line_effective_height(first_line, first_bbox),+ _line_effective_height(second_line, second_bbox),+ )+ return _bbox_axis_overlap_ratio(first_bbox, second_bbox, axis="x") > 0.0 or horizontal_gap <= 1.5 * pair_height+++def _classify_overlapping_inline_cluster(+ members: list[tuple[_LineItem, BBox]],+ lane: _TextLane,+ median_height: float,+ table_bboxes: list[BBox],+) -> str | None:+ """按正文宿主和紧凑程度区分行内文本簇与独立公式簇。"""++ if len(members) < 2:+ return None+ visual_row_ids = {line.visual_row_id for line, _bbox in members if line.visual_row_id is not None}+ if len(visual_row_ids) < 2:+ return None+ if any(_bbox_intersects(line.bbox, table_bbox) for line, _bbox in members for table_bbox in table_bboxes):+ return None++ union_bbox = _bbox_union_many([bbox for _line, bbox in members])+ if union_bbox[3] - union_bbox[1] > 3.0 * median_height:+ return None+ lane_width = max(0.1, lane.right - lane.left)+ has_fragment = any(+ _line_effective_height(line, bbox) <= 0.88 * median_height or line.font_coverage < 0.75 for line, bbox in members+ )+ if not has_fragment:+ return None++ has_body_host = any(+ bbox[2] - bbox[0] >= max(4.0 * median_height, 0.35 * lane_width)+ and _line_effective_height(line, bbox) >= 0.8 * median_height+ and line.font_coverage >= 0.75+ for line, bbox in members+ )+ if has_body_host:+ return "inline"+ if len(members) >= 3 and len(visual_row_ids) >= 3 and union_bbox[2] - union_bbox[0] <= 0.6 * lane_width:+ return "formula"+ return None+++def _select_overlapping_inline_cluster_host(+ members: list[tuple[_LineItem, BBox]],+ median_height: float,+) -> _LineItem:+ """选择与其他成员纵向重叠最多且最接近正文尺度的宿主行。"""++ union_bbox = _bbox_union_many([bbox for _line, bbox in members])+ union_center_y = _bbox_center_y(union_bbox)++ def host_score(item: tuple[_LineItem, BBox]) -> tuple[float, ...]:+ """生成宿主候选的正文尺度、同行支持和中心距离评分。"""++ line, bbox = item+ vertical_support = sum(+ max(0.0, min(bbox[3], other_bbox[3]) - max(bbox[1], other_bbox[1]))+ for other_line, other_bbox in members+ if other_line is not line+ )+ same_row_support = sum(+ line.visual_row_id is not None and line.visual_row_id == other_line.visual_row_id+ for other_line, _other_bbox in members+ if other_line is not line+ )+ body_like = float(_line_effective_height(line, bbox) >= 0.8 * median_height and line.font_coverage >= 0.75)+ return (+ body_like,+ float(same_row_support),+ vertical_support,+ bbox[2] - bbox[0],+ -abs(_bbox_center_y(bbox) - union_center_y),+ -float(line.source_index),+ )++ return max(members, key=host_score)[0]+++def _merge_overlapping_inline_cluster(+ members: list[tuple[_LineItem, BBox]],+ page_size: tuple[float, float],+ median_height: float,+ *,+ compact_formula_cluster: bool,+) -> _LineItem:+ """按来源顺序合并二维文本簇,并保留字符与宿主排版信息。"""++ ordered_members = sorted(+ (line for line, _bbox in members),+ key=lambda line: line.source_index,+ )+ host = _select_overlapping_inline_cluster_host(members, median_height)+ merged = _LineItem(+ text=" ".join(text for line in ordered_members if (text := line.text.strip())),+ bbox=_bbox_union_many([line.bbox for line in ordered_members]),+ angle=host.angle,+ source_index=min(line.source_index for line in ordered_members),+ chars=[char for line in ordered_members for char in line.chars],+ visual_row_id=host.visual_row_id,+ run_index=host.run_index,+ effective_height=host.effective_height,+ font_signature=host.font_signature,+ font_coverage=host.font_coverage,+ dominant_font_weight=host.dominant_font_weight,+ median_glyph_width=host.median_glyph_width,+ split_from_row=any(line.split_from_row for line in ordered_members),+ semantic_type=host.semantic_type,+ restored_inline_cluster=True,+ compact_formula_cluster=compact_formula_cluster,+ )+ if merged.chars:+ _fill_native_typography(merged, page_size)+ return merged+def _merge_post_semantic_text_runs(lines: list[_LineItem],page_size: tuple[float, float],@@ -353,6 +602,12 @@ def _merge_same_baseline_group(else None,split_from_row=any(member.split_from_row for member in members),semantic_type=members[0].semantic_type,+ restored_inline_cluster=any(+ member.restored_inline_cluster for member in members+ ),+ compact_formula_cluster=any(+ member.compact_formula_cluster for member in members+ ),)if merged.chars:_fill_native_typography(merged, page_size)@@ -685,6 +940,12 @@ def _merge_dense_split_visual_row(else None,split_from_row=False,semantic_type=ordered_members[0].semantic_type,+ restored_inline_cluster=any(+ member.restored_inline_cluster for member in ordered_members+ ),+ compact_formula_cluster=any(+ member.compact_formula_cluster for member in ordered_members+ ),)if merged.chars:_fill_native_typography(merged, page_size)diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.pyindex 496cf66c..736f03ed 100644--- a/mineru/backend/flash/native_pdf/models.py+++ b/mineru/backend/flash/native_pdf/models.py@@ -30,6 +30,8 @@ class _LineItem:median_glyph_width: float | None = Nonesplit_from_row: bool = Falsesemantic_type: str | None = None+ restored_inline_cluster: bool = False+ compact_formula_cluster: bool = False@dataclass(slots=True)diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.pyindex 6ae07b26..7cc0098e 100644--- a/mineru/backend/flash/native_pdf/pipeline.py+++ b/mineru/backend/flash/native_pdf/pipeline.py@@ -30,6 +30,7 @@ from .native_text import (_sanitize_pdf_control_text,)from .line_merging import (+ _merge_overlapping_inline_text_clusters,_merge_post_semantic_text_runs,_merge_same_baseline_text_lines,_merge_title_resolved_visual_rows,@@ -152,6 +153,11 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:source.page_size,table_bboxes,)+ remaining_lines = _merge_overlapping_inline_text_clusters(+ remaining_lines,+ source.page_size,+ table_bboxes,+ )_compact_prepared_lines(remaining_lines, source.page_size)prepared = _PreparedPage(page_size=source.page_size,@@ -306,4 +312,3 @@ def _normalize_output_block("angle": 0 if normalized_type == "image" else int(block.get("angle", 0) or 0) % 360,"content": content,}-diff --git a/mineru/backend/flash/native_pdf/text_blocks.py b/mineru/backend/flash/native_pdf/text_blocks.pyindex 1aa38d39..da1d7e1b 100644--- a/mineru/backend/flash/native_pdf/text_blocks.py+++ b/mineru/backend/flash/native_pdf/text_blocks.py@@ -8,7 +8,10 @@ import statisticsfrom typing import Any, Sequence-from mineru.backend.utils.char_utils import resolve_text_line_boundary+from mineru.backend.utils.char_utils import (+ is_hyphen_at_line_end,+ resolve_text_line_boundary,+)from mineru.types import BBoxfrom mineru.utils.language import detect_lang@@ -90,6 +93,13 @@ def _build_hanging_indent_group_map() -> tuple[int, float] | None:"""消费一个左突首行及其续行,并返回下一条首行位置。"""+ if (+ start_index > 0+ and is_hyphen_at_line_end(rows[start_index - 1][0].text)+ and rows_are_adjacent(rows[start_index - 1], rows[start_index])+ ):+ # 排版断词后的下一物理行属于前文,不能被缩进几何误当成新条目首行。+ return Nonecontinuation_index = start_index + 1if continuation_index >= len(rows):return None@@ -426,7 +436,18 @@ def _build_text_blocks(else:previous_group = hanging_indent_groups.get(previous[0].source_index)current_group = hanging_indent_groups.get(current[0].source_index)- if previous_group is not None or current_group is not None:+ if is_hyphen_at_line_end(previous[0].text):+ # 断词续行优先于悬挂缩进分组,但仍复用正文连接中的距离和障碍限制。+ should_connect = _should_connect_text_rows(+ previous,+ current,+ lane,+ regular_gap,+ gap_mad,+ table_bboxes,+ local_axis_lines,+ )+ elif previous_group is not None or current_group is not None:should_connect = previous_group is not None and previous_group == current_groupelse:should_connect = _should_connect_text_rows(diff --git a/tests/unittest/test_flash_pdf_formulas.py b/tests/unittest/test_flash_pdf_formulas.pyindex e8d304f3..c5539554 100644--- a/tests/unittest/test_flash_pdf_formulas.py+++ b/tests/unittest/test_flash_pdf_formulas.py@@ -6,6 +6,7 @@ import pytestfrom mineru.backend.flash.native_pdf import (formulas,geometry,+ line_merging,models,)@@ -295,3 +296,135 @@ def test_detached_formula_anchor_collects_multiline_formula_but_not_body_prefix(assert punctuation.text not in member_texts+def test_overlapping_denominator_cannot_become_short_formula_anchor() -> None:+ """验证与正文横向重叠的右缘分母字符不会成为非编号公式锚点。"""++ body_font = ("Body", 0)+ body_lines = [+ _text_line(+ f"body-{index}",+ (0.0, top, 92.0, top + 10.0),+ index,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ )+ for index, top in enumerate((0.0, 12.0, 24.0))+ ]+ formula_body = _text_line(+ "Pr = cp mu",+ (25.0, 36.0, 90.0, 46.0),+ 3,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=0.8,+ )+ denominator = _text_line(+ "k",+ (88.0, 38.0, 92.0, 45.0),+ 4,+ effective_height=7.0,+ font_signature=("Math", 1),+ font_coverage=1.0,+ )+ lane = models._TextLane(+ left=0.0,+ right=92.0,+ lines=[+ *((line, line.bbox) for line in body_lines),+ (formula_body, formula_body.bbox),+ (denominator, denominator.bbox),+ ],+ )++ assert formulas._find_formula_spatial_anchors(lane, 10.0, body_font) == []+++def test_compact_multiline_cluster_becomes_one_isolated_equation() -> None:+ """验证可提取的紧凑 F/G 多行簇形成单个公式块且不进入前后正文。"""++ body_font = ("Body", 0)+ body_lines = [+ _text_line(+ f"body-{index}",+ (0.0, top, 100.0, top + 10.0),+ index,+ visual_row_id=index,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ )+ for index, top in enumerate((0.0, 12.0, 24.0))+ ]+ fragments = [+ _text_line(+ "F = numerator",+ (10.0, 36.0, 25.0, 49.0),+ 3,+ visual_row_id=3,+ effective_height=8.0,+ font_signature=("Math", 1),+ font_coverage=0.5,+ ),+ _text_line(+ "denominator, G =",+ (20.0, 39.0, 40.0, 52.0),+ 4,+ visual_row_id=4,+ split_from_row=True,+ effective_height=9.5,+ font_signature=("Math", 1),+ font_coverage=0.4,+ ),+ _text_line(+ "numerator",+ (46.0, 36.0, 52.0, 43.0),+ 5,+ visual_row_id=4,+ split_from_row=True,+ effective_height=7.0,+ font_signature=("Math", 1),+ font_coverage=0.5,+ ),+ _text_line(+ "denominator",+ (46.0, 39.0, 53.0, 52.0),+ 6,+ visual_row_id=5,+ effective_height=7.0,+ font_signature=("Math", 1),+ font_coverage=0.33,+ ),+ ]+ following = _text_line(+ "following body",+ (0.0, 54.0, 100.0, 64.0),+ 7,+ visual_row_id=6,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ )++ merged = line_merging._merge_overlapping_inline_text_clusters(+ [*body_lines, *fragments, following],+ (120.0, 100.0),+ [],+ )+ compact_cluster = next(line for line in merged if line.source_index == 3)+ blocks, remaining = formulas._build_formula_like_blocks(+ merged,+ [],+ (120.0, 100.0),+ )++ assert compact_cluster.compact_formula_cluster+ assert blocks == [+ {+ "type": "equation",+ "bbox": (10.0, 36.0, 53.0, 52.0),+ "angle": 0,+ "content": "F = numerator denominator, G = numerator denominator",+ }+ ]+ assert compact_cluster not in remainingdiff --git a/tests/unittest/test_flash_pdf_text_blocks.py b/tests/unittest/test_flash_pdf_text_blocks.pyindex fee5da81..41733a89 100644--- a/tests/unittest/test_flash_pdf_text_blocks.py+++ b/tests/unittest/test_flash_pdf_text_blocks.py@@ -508,3 +508,230 @@ def test_smaller_footnote_after_abnormal_gap_forces_text_block_break() -> None:)+def test_overlapping_fraction_fragments_merge_with_ha_and_nb_body_hosts() -> None:+ """验证 Ha、Nb 的上下分式碎片并回正文宿主,且普通后续行保持独立。"""++ body_font = ("Body", 0)+ math_font = ("Math", 1)+ lines = [+ _text_line(+ "Ha =",+ (0.0, 10.0, 20.0, 20.0),+ 0,+ visual_row_id=0,+ split_from_row=True,+ effective_height=10.0,+ font_signature=math_font,+ font_coverage=0.67,+ ),+ _text_line(+ "root",+ (30.0, 0.0, 40.0, 12.0),+ 1,+ visual_row_id=0,+ split_from_row=True,+ effective_height=9.0,+ font_signature=math_font,+ font_coverage=0.57,+ ),+ _text_line(+ "sigma",+ (30.0, 9.0, 34.0, 16.0),+ 2,+ visual_row_id=1,+ effective_height=7.0,+ font_signature=math_font,+ font_coverage=1.0,+ ),+ _text_line(+ "mu",+ (30.0, 16.0, 34.0, 23.0),+ 3,+ visual_row_id=2,+ effective_height=7.0,+ font_signature=math_font,+ font_coverage=1.0,+ ),+ _text_line(+ "denotes the Hartmann number",+ (22.0, 3.0, 100.0, 25.0),+ 4,+ visual_row_id=3,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=0.9,+ ),+ _text_line(+ "Nb = numerator",+ (0.0, 40.0, 42.0, 53.0),+ 5,+ visual_row_id=4,+ effective_height=8.0,+ font_signature=math_font,+ font_coverage=0.6,+ ),+ _text_line(+ "mu",+ (30.0, 48.0, 34.0, 55.0),+ 6,+ visual_row_id=5,+ effective_height=7.0,+ font_signature=math_font,+ font_coverage=1.0,+ ),+ _text_line(+ "denotes the Brownian parameter",+ (46.0, 43.0, 100.0, 53.0),+ 7,+ visual_row_id=6,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "ordinary following row",+ (0.0, 70.0, 100.0, 80.0),+ 8,+ visual_row_id=7,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]++ merged = line_merging._merge_overlapping_inline_text_clusters(+ lines,+ (120.0, 100.0),+ [],+ )++ assert [line.source_index for line in merged] == [0, 5, 8]+ assert merged[0].text == "Ha = root sigma mu denotes the Hartmann number"+ assert merged[1].text == "Nb = numerator mu denotes the Brownian parameter"+ assert all(line.restored_inline_cluster for line in merged[:2])+ assert not any(line.text in {"sigma", "mu"} for line in merged)+++def test_overlapping_delta_fraction_and_tail_form_one_text_block() -> None:+ """验证同一物理行的分子分母恢复后可与下一行幅值说明组成单块。"""++ body_font = ("Body", 0)+ lines = [+ _text_line(+ "where, delta = numerator",+ (0.0, 0.0, 32.0, 13.0),+ 0,+ visual_row_id=0,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=0.73,+ ),+ _text_line(+ "denominator displays the amplitude",+ (28.0, 3.0, 100.0, 16.0),+ 1,+ visual_row_id=1,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=0.86,+ ),+ _text_line(+ "ratio.",+ (0.0, 18.0, 20.0, 28.0),+ 2,+ visual_row_id=2,+ effective_height=10.0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ ]++ merged = line_merging._merge_overlapping_inline_text_clusters(+ lines,+ (120.0, 100.0),+ [],+ )+ blocks = text_blocks._build_text_blocks(merged, [], (120.0, 100.0))++ assert len(merged) == 2+ assert [block["content"] for block in blocks] == ["where, delta = numerator denominator displays the amplitude ratio."]+++def test_overlapping_inline_pair_respects_table_and_physical_row_gap() -> None:+ """验证二维碎片连接不会跨表格,也不会连接普通上下相邻正文行。"""++ first = _text_line("left", (0.0, 0.0, 40.0, 10.0), 0, effective_height=10.0)+ same_row = _text_line("right", (60.0, 0.0, 100.0, 10.0), 1, effective_height=10.0)+ next_row = _text_line("next", (0.0, 12.0, 40.0, 22.0), 2, effective_height=10.0)++ assert not line_merging._overlapping_inline_cluster_pair_is_connected(+ (first, first.bbox),+ (same_row, same_row.bbox),+ 10.0,+ [(45.0, -5.0, 55.0, 15.0)],+ )+ assert not line_merging._overlapping_inline_cluster_pair_is_connected(+ (first, first.bbox),+ (next_row, next_row.bbox),+ 10.0,+ [],+ )+++def test_hyphen_continuation_cannot_start_false_hanging_indent_entry() -> None:+ """验证断词续行优先归前段,后续首行缩进说明和紧凑公式仍各自分块。"""++ body_font = ("Body", 0)+ lines = [+ _text_line(+ "linear equations in the trans-",+ (0.0, 0.0, 100.0, 10.0),+ 0,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "verse direction.",+ (0.0, 12.0, 40.0, 22.0),+ 1,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "The expression starts here",+ (12.0, 24.0, 100.0, 34.0),+ 2,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "the stream function is given below:",+ (0.0, 36.0, 75.0, 46.0),+ 3,+ font_signature=body_font,+ font_coverage=1.0,+ ),+ _text_line(+ "F = fraction",+ (12.0, 48.0, 45.0, 55.0),+ 4,+ effective_height=7.0,+ font_signature=("Math", 1),+ font_coverage=0.5,+ ),+ ]+ lane = models._TextLane(+ left=0.0,+ right=100.0,+ lines=[(line, line.bbox) for line in lines],+ )++ group_map = text_blocks._build_hanging_indent_group_map(lane, [], [])+ blocks = text_blocks._build_text_blocks(lines, [], (120.0, 100.0))++ assert 1 not in group_map+ assert [block["content"] for block in blocks] == [+ "linear equations in the transverse direction.",+ "The expression starts here the stream function is given below:",+ "F = fraction",+ ]