Skip to content

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

feat: enhance text block merging logic to support single line width adjustments using following lines

myhloli75eda29e746d
diff --git a/mineru/backend/postprocess/paragraphs.py b/mineru/backend/postprocess/paragraphs.py
index cdd3e0a5..cfa20d53 100644
--- a/mineru/backend/postprocess/paragraphs.py
+++ b/mineru/backend/postprocess/paragraphs.py
@@ -30,6 +30,9 @@ TEXT_MERGE_TRANSPARENT_TYPES = {
}
VERTICAL_LINE_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2
VERTICAL_LINE_IN_BLOCK_THRESHOLD = 0.8
+SINGLE_LINE_LOOKAHEAD_LIMIT = 5
+SINGLE_LINE_MIN_ALIGNED_LOOKAHEAD = 3
+SINGLE_LINE_THICKNESS_RATIO_MAX = 1.5
BlockDict: TypeAlias = dict[str, Any]
CalculationBBox: TypeAlias = tuple[int, int, int, int]
@@ -71,7 +74,16 @@ def merge_para_text_blocks(pages: list[dict[str, Any]]) -> None:
previous_page_idx, _, previous_text_block = previous_block
if not _is_same_or_consecutive_page(current_page_idx, previous_page_idx):
continue
- if can_auto_merge_text_blocks(current_block, previous_text_block):
+ if can_auto_merge_text_blocks(
+ current_block,
+ previous_text_block,
+ ) or _can_auto_merge_multiline_to_single_line(
+ current_block,
+ previous_text_block,
+ ordered_blocks=ordered_blocks,
+ current_index=current_index,
+ current_page_idx=current_page_idx,
+ ):
current_block["continues_prev"] = True
elif current_type == BlockType.LIST:
previous_block = _find_previous_ref_text_list_block(
@@ -177,6 +189,13 @@ def _is_same_or_consecutive_page(current_page_idx: int, previous_page_idx: int)
return current_page_idx == previous_page_idx or current_page_idx == previous_page_idx + 1
+def _positive_values_have_max_ratio(first: float, second: float, max_ratio: float) -> bool:
+ """判断两个正值的较大较小比是否不超过给定上限。"""
+ if first <= 0 or second <= 0:
+ return False
+ return max(first, second) / min(first, second) <= max_ratio
+
+
def _bbox_for_calculation(bbox: Any) -> CalculationBBox | None:
"""复制并将 0~1 bbox 放大为千分位整数,原始 bbox 保持不变。"""
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
@@ -254,6 +273,144 @@ def _has_mergeable_text_boundary(current_content: str, previous_content: str) ->
return not first_char.isdigit() and not first_char.isupper()
+def _collect_following_same_orientation_lines(
+ ordered_blocks: list[OrderedBlock],
+ current_index: int,
+ *,
+ current_page_idx: int,
+ is_vertical: bool,
+) -> list[CalculationBBox]:
+ """在当前页向后读取至多五条同方向正文行,语义屏障或非法文本会终止读取。"""
+ following_lines: list[CalculationBBox] = []
+ for page_idx, _, block in ordered_blocks[current_index + 1 :]:
+ if page_idx != current_page_idx:
+ break
+ block_type = block.get("type")
+ if block_type in TEXT_MERGE_BARRIER_TYPES:
+ break
+ if block_type != BlockType.TEXT:
+ if block_type in TEXT_MERGE_TRANSPARENT_TYPES:
+ continue
+ break
+
+ block_lines = _metric_line_bboxes(block)
+ if not block_lines or _is_vertical_text_block_by_lines(block_lines) != is_vertical:
+ break
+ for line_bbox in block_lines:
+ following_lines.append(line_bbox)
+ if len(following_lines) >= SINGLE_LINE_LOOKAHEAD_LIMIT:
+ return following_lines
+ return following_lines
+
+
+def _aligned_following_lines(
+ current_line: CalculationBBox,
+ following_lines: list[CalculationBBox],
+ *,
+ is_vertical: bool,
+) -> list[CalculationBBox]:
+ """按横排左边界或竖排上边界筛选同一虚拟栏内的后续行列。"""
+ current_start = current_line[1] if is_vertical else current_line[0]
+ current_thickness = _line_width(current_line) if is_vertical else _line_height(current_line)
+ aligned_lines: list[CalculationBBox] = []
+ for line_bbox in following_lines:
+ line_start = line_bbox[1] if is_vertical else line_bbox[0]
+ line_thickness = _line_width(line_bbox) if is_vertical else _line_height(line_bbox)
+ if not _positive_values_have_max_ratio(
+ current_thickness,
+ line_thickness,
+ SINGLE_LINE_THICKNESS_RATIO_MAX,
+ ):
+ continue
+ if abs(line_start - current_start) <= max(current_thickness, line_thickness):
+ aligned_lines.append(line_bbox)
+ return aligned_lines
+
+
+def _virtual_single_line_bbox(
+ current_line: CalculationBBox,
+ aligned_lines: list[CalculationBBox],
+ *,
+ is_vertical: bool,
+) -> CalculationBBox:
+ """仅沿文本主轴扩展单行计算框,原始 line 和 block bbox 保持不变。"""
+ if is_vertical:
+ return (
+ current_line[0],
+ current_line[1],
+ current_line[2],
+ max(current_line[3], *(line_bbox[3] for line_bbox in aligned_lines)),
+ )
+ return (
+ current_line[0],
+ current_line[1],
+ max(current_line[2], *(line_bbox[2] for line_bbox in aligned_lines)),
+ current_line[3],
+ )
+
+
+def _can_auto_merge_multiline_to_single_line(
+ current_block: BlockDict,
+ previous_block: BlockDict,
+ *,
+ ordered_blocks: list[OrderedBlock],
+ current_index: int,
+ current_page_idx: int,
+) -> bool:
+ """用后续五行或列补足单行主轴尺寸,再复用原横排或竖排连接规则。"""
+ current_lines = _metric_line_bboxes(current_block)
+ previous_lines = _metric_line_bboxes(previous_block)
+ if len(current_lines) != 1 or len(previous_lines) <= 1:
+ return False
+
+ current_is_vertical = _is_vertical_text_block_by_lines(current_lines)
+ if _is_vertical_text_block_by_lines(previous_lines) != current_is_vertical:
+ return False
+ following_lines = _collect_following_same_orientation_lines(
+ ordered_blocks,
+ current_index,
+ current_page_idx=current_page_idx,
+ is_vertical=current_is_vertical,
+ )
+ aligned_lines = _aligned_following_lines(
+ current_lines[0],
+ following_lines,
+ is_vertical=current_is_vertical,
+ )
+ if len(aligned_lines) < SINGLE_LINE_MIN_ALIGNED_LOOKAHEAD:
+ return False
+
+ current_bbox = _bbox_for_calculation(current_block.get("bbox"))
+ previous_bbox = _bbox_for_calculation(previous_block.get("bbox"))
+ current_content = _normalized_text_content(current_block)
+ previous_content = _normalized_text_content(previous_block)
+ if current_bbox is None or previous_bbox is None or not current_content or not previous_content:
+ return False
+
+ virtual_current_line = _virtual_single_line_bbox(
+ current_lines[0],
+ aligned_lines,
+ is_vertical=current_is_vertical,
+ )
+ if current_is_vertical:
+ return _can_auto_merge_vertical_text_blocks(
+ current_content,
+ previous_content,
+ current_bbox,
+ previous_bbox,
+ [virtual_current_line],
+ previous_lines,
+ )
+ return _can_auto_merge_horizontal_text_blocks(
+ current_content,
+ previous_content,
+ current_bbox,
+ previous_bbox,
+ [virtual_current_line],
+ previous_lines,
+ )
+
+
def _can_auto_merge_horizontal_text_blocks(
current_content: str,
previous_content: str,
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 9bb01fbf..ead29f62 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -1443,6 +1443,12 @@ def test_frozen_soil_reference_tails_remain_single_text_blocks() -> None:
if block.type == "text" and isinstance(block.content, str) and block.content.startswith("预测。")
)
assert page2_continuation.continues_prev is True
+ page1_single_line_tail = next(
+ block
+ for block in middle_pages[0].blocks
+ if block.type == "text" and isinstance(block.content, str) and block.content == "准的预测方法。"
+ )
+ assert page1_single_line_tail.continues_prev is True
page = model_list[8]
captions = [block for page_blocks in model_list for block in page_blocks if block["type"] == "caption"]
diff --git a/tests/unittest/test_postprocess_paragraphs.py b/tests/unittest/test_postprocess_paragraphs.py
index 7fd1fda2..07409a15 100644
--- a/tests/unittest/test_postprocess_paragraphs.py
+++ b/tests/unittest/test_postprocess_paragraphs.py
@@ -41,6 +41,101 @@ def _horizontal_pair() -> tuple[dict, dict]:
return previous_block, current_block
+def _horizontal_multiline_block(
+ index: int,
+ content: str,
+ *,
+ left: float,
+ right: float,
+ top: float,
+ line_count: int = 5,
+ line_height: float = 0.04,
+ first_indent: float = 0.0,
+) -> dict:
+ """构造可控制首行缩进的横排多行正文块。"""
+ line_bboxes = [
+ [
+ left + (first_indent if line_index == 0 else 0.0),
+ top + line_index * line_height,
+ right,
+ top + (line_index + 1) * line_height,
+ ]
+ for line_index in range(line_count)
+ ]
+ return _text_block(
+ index,
+ content,
+ [min(line[0] for line in line_bboxes), top, right, top + line_count * line_height],
+ line_bboxes,
+ )
+
+
+def _horizontal_single_line_block(
+ index: int,
+ content: str,
+ *,
+ left: float,
+ right: float,
+ top: float,
+ line_height: float = 0.04,
+) -> dict:
+ """构造需要使用后续行补足虚拟宽度的横排单行块。"""
+ return _text_block(
+ index,
+ content,
+ [left, top, right, top + line_height],
+ [[left, top, right, top + line_height]],
+ )
+
+
+def _vertical_multicolumn_block(
+ index: int,
+ content: str,
+ *,
+ right: float,
+ top: float,
+ bottom: float,
+ column_count: int = 5,
+ column_width: float = 0.04,
+ column_gap: float = 0.02,
+ first_top_indent: float = 0.0,
+) -> dict:
+ """构造从右向左排列且可控制首列上边界的竖排多列正文块。"""
+ column_bboxes = [
+ [
+ right - column_width - column_index * (column_width + column_gap),
+ top + (first_top_indent if column_index == 0 else 0.0),
+ right - column_index * (column_width + column_gap),
+ bottom,
+ ]
+ for column_index in range(column_count)
+ ]
+ return _text_block(
+ index,
+ content,
+ [min(column[0] for column in column_bboxes), top, right, bottom],
+ column_bboxes,
+ )
+
+
+def _vertical_single_column_block(
+ index: int,
+ content: str,
+ *,
+ left: float,
+ right: float,
+ top: float,
+ bottom: float,
+) -> dict:
+ """构造需要使用后续列补足虚拟高度的竖排单列块。"""
+ return _text_block(
+ index,
+ content,
+ [left, top, right, bottom],
+ [[left, top, right, bottom]],
+ )
+
+
def _vertical_pair() -> tuple[dict, dict]:
"""构造一组满足竖排段落延续规则的前后 text block。"""
previous_block = _text_block(
@@ -208,6 +303,316 @@ def test_merge_para_text_blocks_keeps_cross_page_semantic_barriers(barrier_type:
assert "continues_prev" not in current_block
+def test_merge_para_text_blocks_uses_following_lines_for_horizontal_single_line_width() -> None:
+ """验证横排单行会忽略缩进首行并使用其余四行补足虚拟栏宽。"""
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.1,
+ right=0.45,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(1, "tail.", left=0.55, right=0.67, top=0.1)
+ following_block = _horizontal_multiline_block(
+ 2,
+ "following paragraph.",
+ left=0.55,
+ right=0.9,
+ top=0.2,
+ first_indent=0.08,
+ )
+ pages = [{"page_idx": 0, "blocks": [previous_block, current_block, following_block]}]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block["continues_prev"] is True
+
+
+def test_merge_para_text_blocks_uses_next_page_lines_for_horizontal_single_line_width() -> None:
+ """验证横排跨页单行使用当前页后续五行补足宽度而不依赖栏位数量。"""
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.55,
+ right=0.9,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(0, "tail.", left=0.1, right=0.22, top=0.1)
+ following_block = _horizontal_multiline_block(
+ 1,
+ "following paragraph.",
+ left=0.1,
+ right=0.45,
+ top=0.2,
+ )
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {"page_idx": 1, "blocks": [current_block, following_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block["continues_prev"] is True
+
+
+def test_merge_para_text_blocks_uses_following_columns_for_vertical_single_column_height() -> None:
+ """验证竖排单列会忽略上边界缩进首列并使用其余四列补足虚拟栏高。"""
+ previous_block = _vertical_multicolumn_block(
+ 0,
+ "未完",
+ right=0.9,
+ top=0.1,
+ bottom=0.9,
+ column_count=4,
+ )
+ current_block = _vertical_single_column_block(
+ 0,
+ "续。",
+ left=0.85,
+ right=0.9,
+ top=0.1,
+ bottom=0.3,
+ )
+ following_block = _vertical_multicolumn_block(
+ 1,
+ "後續正文。",
+ right=0.83,
+ top=0.1,
+ bottom=0.9,
+ first_top_indent=0.08,
+ )
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {"page_idx": 1, "blocks": [current_block, following_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert current_block["continues_prev"] is True
+
+
[email protected]("is_vertical", [False, True])
+def test_merge_para_text_blocks_requires_three_aligned_lookahead_lines(is_vertical: bool) -> None:
+ """验证横排或竖排后续同轴行列不足三条时不会构造虚拟尺寸。"""
+ if is_vertical:
+ previous_block = _vertical_multicolumn_block(
+ 0,
+ "未完",
+ right=0.9,
+ top=0.1,
+ bottom=0.9,
+ column_count=4,
+ )
+ current_block = _vertical_single_column_block(
+ 0,
+ "續。",
+ left=0.85,
+ right=0.9,
+ top=0.1,
+ bottom=0.3,
+ )
+ following_block = _vertical_multicolumn_block(
+ 1,
+ "短參考。",
+ right=0.83,
+ top=0.1,
+ bottom=0.9,
+ column_count=2,
+ )
+ else:
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.1,
+ right=0.45,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)
+ following_block = _horizontal_multiline_block(
+ 1,
+ "short reference.",
+ left=0.55,
+ right=0.9,
+ top=0.2,
+ line_count=2,
+ )
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {"page_idx": 1, "blocks": [current_block, following_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert "continues_prev" not in current_block
+
+
[email protected]("is_vertical", [False, True])
+def test_merge_para_text_blocks_stops_single_line_lookahead_at_semantic_barrier(is_vertical: bool) -> None:
+ """验证标题屏障会阻止横排或竖排单行读取更后的参考行列。"""
+ if is_vertical:
+ previous_block = _vertical_multicolumn_block(
+ 0,
+ "未完",
+ right=0.9,
+ top=0.1,
+ bottom=0.9,
+ column_count=4,
+ )
+ current_block = _vertical_single_column_block(
+ 0,
+ "續。",
+ left=0.85,
+ right=0.9,
+ top=0.1,
+ bottom=0.3,
+ )
+ following_block = _vertical_multicolumn_block(
+ 2,
+ "後續正文。",
+ right=0.83,
+ top=0.1,
+ bottom=0.9,
+ )
+ else:
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.1,
+ right=0.45,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)
+ following_block = _horizontal_multiline_block(
+ 2,
+ "following paragraph.",
+ left=0.55,
+ right=0.9,
+ top=0.2,
+ )
+ barrier = {"index": 1, "type": BlockType.PARAGRAPH_TITLE, "content": "barrier"}
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {"page_idx": 1, "blocks": [current_block, barrier, following_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert "continues_prev" not in current_block
+
+
[email protected]("is_vertical", [False, True])
+def test_merge_para_text_blocks_rejects_unaligned_following_geometry(is_vertical: bool) -> None:
+ """验证后续五行或列的轴起点与当前单行不对齐时不会补足虚拟尺寸。"""
+ if is_vertical:
+ previous_block = _vertical_multicolumn_block(
+ 0,
+ "未完",
+ right=0.9,
+ top=0.1,
+ bottom=0.9,
+ column_count=4,
+ )
+ current_block = _vertical_single_column_block(
+ 0,
+ "續。",
+ left=0.85,
+ right=0.9,
+ top=0.1,
+ bottom=0.3,
+ )
+ following_block = _vertical_multicolumn_block(
+ 1,
+ "錯位正文。",
+ right=0.83,
+ top=0.25,
+ bottom=0.9,
+ )
+ else:
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.1,
+ right=0.45,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)
+ following_block = _horizontal_multiline_block(
+ 1,
+ "misaligned paragraph.",
+ left=0.7,
+ right=0.95,
+ top=0.2,
+ )
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {"page_idx": 1, "blocks": [current_block, following_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert "continues_prev" not in current_block
+
+
[email protected]("is_vertical", [False, True])
+def test_merge_para_text_blocks_does_not_look_beyond_current_page(is_vertical: bool) -> None:
+ """验证当前页没有参考行列时不会读取再下一页的五行或列。"""
+ if is_vertical:
+ previous_block = _vertical_multicolumn_block(
+ 0,
+ "未完",
+ right=0.9,
+ top=0.1,
+ bottom=0.9,
+ column_count=4,
+ )
+ current_block = _vertical_single_column_block(
+ 0,
+ "續。",
+ left=0.85,
+ right=0.9,
+ top=0.1,
+ bottom=0.3,
+ )
+ later_block = _vertical_multicolumn_block(
+ 0,
+ "更後正文。",
+ right=0.83,
+ top=0.1,
+ bottom=0.9,
+ )
+ else:
+ previous_block = _horizontal_multiline_block(
+ 0,
+ "unfinished",
+ left=0.1,
+ right=0.45,
+ top=0.5,
+ line_count=4,
+ )
+ current_block = _horizontal_single_line_block(0, "tail.", left=0.55, right=0.67, top=0.1)
+ later_block = _horizontal_multiline_block(
+ 0,
+ "later paragraph.",
+ left=0.55,
+ right=0.9,
+ top=0.2,
+ )
+ pages = [
+ {"page_idx": 0, "blocks": [previous_block]},
+ {"page_idx": 1, "blocks": [current_block]},
+ {"page_idx": 2, "blocks": [later_block]},
+ ]
+
+ merge_para_text_blocks(pages)
+
+ assert "continues_prev" not in current_block
+
+
def test_can_auto_merge_horizontal_text_blocks_rejects_paragraph_boundaries() -> None:
"""验证横排规则会拒绝终止标点、特殊段首以及不满足几何条件的候选。"""
previous_block, current_block = _horizontal_pair()