Skip to content

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

feat: enhance table processing by adding support for compact fully ruled grid detection and refining column count validation

myhlolid74b7347aa17
diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.py
index 7ae3b6a7..37a74d64 100644
--- a/mineru/backend/flash/native_pdf/tables.py
+++ b/mineru/backend/flash/native_pdf/tables.py
@@ -465,6 +465,7 @@ def _build_rule_table_candidates(
for first_index, top_rule in enumerate(rule_group[:-1]):
for bottom_index in range(first_index + 1, len(rule_group)):
bottom_rule = rule_group[bottom_index]
+ interval_rules = rule_group[first_index : bottom_index + 1]
boundary_rules = [top_rule, bottom_rule]
rule_bbox = _bbox_union_many([line.bbox for line in boundary_rules])
core_rows = _rows_inside_rule_interval(
@@ -474,13 +475,13 @@ def _build_rule_table_candidates(
)
if not _every_rule_interval_has_multi_cell_row(
core_rows,
- rule_group[first_index : bottom_index + 1],
+ interval_rules,
median_height,
):
continue
if not _rule_intervals_are_column_compatible(
core_rows,
- rule_group[first_index : bottom_index + 1],
+ interval_rules,
median_height,
):
continue
@@ -502,7 +503,19 @@ def _build_rule_table_candidates(
accepted: tuple[list[_VisualRow], list[_VisualRow], int, float] | None = None
for row_segment in row_segments:
dense_rows = [row for row in row_segment if len(row.fragments) >= 2]
- if len(dense_rows) < 3:
+ compact_grid_columns = (
+ _compact_fully_ruled_grid_column_count(
+ row_segment,
+ dense_rows,
+ interval_rules,
+ axis_lines,
+ rule_bbox,
+ median_height,
+ )
+ if len(dense_rows) == 2
+ else 0
+ )
+ if len(dense_rows) < 3 and compact_grid_columns == 0:
continue
# 真表格的多单元行会在整个数据带内反复出现;少数图题、图例和
# 坐标刻度偶然形成的多列行不能支撑一大片正文区域。
@@ -512,6 +525,9 @@ def _build_rule_table_candidates(
dense_rows,
median_height,
)
+ if compact_grid_columns > 0:
+ # 两行样本容易把左右/中心锚点误算成不同稳定列,使用物理网格列数。
+ stable_columns = compact_grid_columns
if stable_columns < 2 or column_coverage < 0.5:
continue
if _looks_like_page_column_prose(
@@ -817,6 +833,120 @@ def _count_aligned_vertical_rules(
)
+def _compact_fully_ruled_grid_column_count(
+ row_segment: list[_VisualRow],
+ dense_rows: list[_VisualRow],
+ interval_rules: list[_LocalAxisLine],
+ axis_lines: list[_LocalAxisLine],
+ rule_bbox: BBox,
+ median_height: float,
+) -> int:
+ """以完整横竖边界确认两行紧凑网格,并返回物理列数,失败时返回零。"""
+
+ rule_height = max(0.1, rule_bbox[3] - rule_bbox[1])
+ if (
+ len(row_segment) != 2
+ or len(dense_rows) != 2
+ or len(interval_rules) < 3
+ or rule_height > 6.0 * median_height
+ ):
+ return 0
+
+ vertical_positions = _full_height_vertical_rule_positions(
+ axis_lines,
+ rule_bbox,
+ median_height,
+ )
+ if len(vertical_positions) < 3:
+ return 0
+
+ edge_tolerance = max(1.5, 0.25 * median_height)
+ left_boundary = min(
+ vertical_positions,
+ key=lambda position: abs(position - rule_bbox[0]),
+ )
+ right_boundary = min(
+ vertical_positions,
+ key=lambda position: abs(position - rule_bbox[2]),
+ )
+ if (
+ abs(left_boundary - rule_bbox[0]) > edge_tolerance
+ or abs(right_boundary - rule_bbox[2]) > edge_tolerance
+ or right_boundary <= left_boundary
+ ):
+ return 0
+
+ grid_boundaries = [
+ position
+ for position in vertical_positions
+ if left_boundary <= position <= right_boundary
+ ]
+ if len(grid_boundaries) < 3:
+ return 0
+ grid_intervals = list(zip(grid_boundaries, grid_boundaries[1:]))
+
+ occupied_columns: list[set[int]] = []
+ for row in dense_rows:
+ row_columns: list[int] = []
+ for fragment in row.fragments:
+ fragment_center = _bbox_center_x(fragment.local_bbox)
+ matching_columns = [
+ index
+ for index, (left, right) in enumerate(grid_intervals)
+ if left <= fragment_center <= right
+ ]
+ if len(matching_columns) != 1:
+ return 0
+ column_index = matching_columns[0]
+ if column_index in row_columns:
+ return 0
+ row_columns.append(column_index)
+ if len(row_columns) < 2:
+ return 0
+ occupied_columns.append(set(row_columns))
+
+ if len(occupied_columns[0] & occupied_columns[1]) < 2:
+ return 0
+ return len(grid_intervals)
+
+
+def _full_height_vertical_rule_positions(
+ axis_lines: list[_LocalAxisLine],
+ rule_bbox: BBox,
+ median_height: float,
+) -> list[float]:
+ """收集覆盖紧凑候选主要高度的竖线中心,并合并同位置重复路径。"""
+
+ rule_height = max(0.1, rule_bbox[3] - rule_bbox[1])
+ raw_positions: list[float] = []
+ for line in axis_lines:
+ if line.orientation != "vertical":
+ continue
+ overlap = max(
+ 0.0,
+ min(line.bbox[3], rule_bbox[3])
+ - max(line.bbox[1], rule_bbox[1]),
+ )
+ if (
+ overlap / rule_height < 0.8
+ or line.bbox[3] - line.bbox[1] < 0.8 * rule_height
+ or not rule_bbox[0] - median_height
+ <= _bbox_center_x(line.bbox)
+ <= rule_bbox[2] + median_height
+ ):
+ continue
+ raw_positions.append(_bbox_center_x(line.bbox))
+
+ deduplicated: list[list[float]] = []
+ position_tolerance = max(1.0, 0.1 * median_height)
+ for position in sorted(raw_positions):
+ if deduplicated and abs(position - statistics.mean(deduplicated[-1])) <= position_tolerance:
+ deduplicated[-1].append(position)
+ else:
+ deduplicated.append([position])
+ return [statistics.mean(group) for group in deduplicated]
+
+
def _looks_like_page_column_prose(
rows: list[_VisualRow],
dense_rows: list[_VisualRow],
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index 8a03b3ad..a29552ff 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -364,6 +364,71 @@ def _rule_table_fixture(
return rows, lines, axis_lines
+def _compact_fully_ruled_table_fixture() -> tuple[
+ list[models._VisualRow],
+ list[models._LineItem],
+ list[models._LocalAxisLine],
+]:
+ """构造两行四列、三横五竖的紧凑全封闭网格。"""
+
+ rows: list[models._VisualRow] = []
+ lines: list[models._LineItem] = []
+ column_bounds = (
+ (5.0, 20.0),
+ (32.0, 48.0),
+ (60.0, 75.0),
+ (87.0, 105.0),
+ )
+ source_index = 0
+ for row_index, top in enumerate((10.0, 22.0)):
+ fragments: list[models._Fragment] = []
+ for column_index, (left, right) in enumerate(column_bounds):
+ bbox = (left, top, right, top + 5.0)
+ text = f"cell-{row_index}-{column_index}"
+ fragments.append(
+ models._Fragment(
+ text=text,
+ bbox=bbox,
+ local_bbox=bbox,
+ line_index=source_index,
+ visual_row_id=row_index,
+ )
+ )
+ lines.append(
+ models._LineItem(
+ text=text,
+ bbox=bbox,
+ angle=0,
+ source_index=source_index,
+ effective_height=5.0,
+ visual_row_id=row_index,
+ )
+ )
+ source_index += 1
+ rows.append(
+ models._VisualRow(
+ fragments=fragments,
+ center_y=top + 2.5,
+ bbox=geometry._bbox_union_many(
+ [fragment.bbox for fragment in fragments]
+ ),
+ visual_row_id=row_index,
+ )
+ )
+
+ axis_lines = [
+ *[
+ _axis_line("horizontal", (0.0, top, 110.0, top + 0.1))
+ for top in (8.0, 20.0, 32.0)
+ ],
+ *[
+ _axis_line("vertical", (left, 8.1, left + 0.1, 32.0))
+ for left in (0.0, 27.5, 55.0, 82.5, 109.9)
+ ],
+ ]
+ return rows, lines, axis_lines
+
+
def test_rule_table_candidate_accepts_captionless_regular_text_distribution() -> None:
"""验证三横线和连续稳定列足以识别没有显式标题的表格。"""
@@ -401,6 +466,124 @@ def test_rule_table_candidate_accepts_center_aligned_columns_with_varying_widths
assert candidates[0].line_indices == set(range(6))
+def test_compact_fully_ruled_two_row_table_is_accepted() -> None:
+ """验证两行表格在三横五竖形成完整网格时可通过严格候选准入。"""
+
+ rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
+
+ candidates = tables._build_rule_table_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ )
+
+ assert len(candidates) == 1
+ assert candidates[0].line_indices == set(range(8))
+ assert candidates[0].score == 8.0
+
+
+def test_compact_grid_deduplicates_repeated_vertical_paths() -> None:
+ """验证同位置重复竖线路径不会扩大紧凑表格的物理列数和评分。"""
+
+ rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
+ axis_lines.extend(
+ _axis_line("vertical", (left + 0.3, 8.1, left + 0.4, 32.0))
+ for left in (0.0, 27.5, 55.0, 82.5, 109.9)
+ )
+
+ candidates = tables._build_rule_table_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ )
+
+ assert len(candidates) == 1
+ assert candidates[0].score == 8.0
+
+
+ "failure_mode",
+ [
+ "horizontal_only",
+ "short_verticals",
+ "missing_outer",
+ "same_cell",
+ "center_on_boundary",
+ ],
+)
+def test_compact_two_row_layout_requires_complete_grid(
+ failure_mode: str,
+) -> None:
+ """验证两行文本缺少完整竖向网格或唯一单元格映射时仍保持非表格。"""
+
+ rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
+ if failure_mode == "horizontal_only":
+ axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]
+ elif failure_mode == "short_verticals":
+ axis_lines = [
+ _axis_line("vertical", (line.bbox[0], 13.0, line.bbox[2], 27.0))
+ if line.orientation == "vertical"
+ else line
+ for line in axis_lines
+ ]
+ elif failure_mode == "missing_outer":
+ axis_lines = [
+ line
+ for line in axis_lines
+ if line.orientation != "vertical" or line.bbox[0] > 1.0
+ ]
+ elif failure_mode == "same_cell":
+ rows[0].fragments[1].bbox = (8.0, 10.0, 18.0, 15.0)
+ rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox
+ else:
+ rows[0].fragments[1].bbox = (26.5, 10.0, 28.5, 15.0)
+ rows[0].fragments[1].local_bbox = rows[0].fragments[1].bbox
+
+ candidates = tables._build_rule_table_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ )
+
+ assert candidates == []
+
+
+def test_compact_admission_does_not_accept_two_row_column_prose() -> None:
+ """验证两行普通双栏文本不会因紧凑表格分支而降低准入门槛。"""
+
+ rows, lines, axis_lines = _compact_fully_ruled_table_fixture()
+ for row in rows:
+ row.fragments = [row.fragments[0], row.fragments[-1]]
+ row.bbox = geometry._bbox_union_many(
+ [fragment.bbox for fragment in row.fragments]
+ )
+ retained_indices = {
+ fragment.line_index for row in rows for fragment in row.fragments
+ }
+ lines = [line for line in lines if line.source_index in retained_indices]
+ axis_lines = [line for line in axis_lines if line.orientation == "horizontal"]
+
+ candidates = tables._build_rule_table_candidates(
+ rows,
+ lines,
+ (150.0, 100.0),
+ 0,
+ 5.0,
+ axis_lines,
+ )
+
+ assert candidates == []
+
+
def test_two_horizontal_rule_grid_is_accepted_by_spatial_distribution() -> None:
"""验证两条长横线结合密集稳定列即可形成表格候选。"""