Skip to content

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

feat: enhance equation handling by adding support for MathType/Equation OLE objects and improving image equation decoding

myhlolid95489317997
diff --git a/mineru/utils/native_pdf_table/candidate.py b/mineru/utils/native_pdf_table/candidate.py
index 970de4c6..e2243915 100644
--- a/mineru/utils/native_pdf_table/candidate.py
+++ b/mineru/utils/native_pdf_table/candidate.py
@@ -115,6 +115,21 @@ def _order_consistency(
return ordered_pairs / comparable if comparable else 1.0
+def _count_split_tokens(
+ text: NativeTableText,
+ assignments: dict[int, int],
+) -> int:
+ """统计字符被分配到多个逻辑单元格的原子 token。"""
+
+ split_count = 0
+ for row in text.rows:
+ for token in row.tokens:
+ owners = {assignments[glyph_id] for glyph_id in token.glyph_ids if glyph_id in assignments}
+ if len(owners) > 1:
+ split_count += 1
+ return split_count
+
+
def build_candidate(
*,
source: NativeTableCandidateSource,
@@ -128,6 +143,8 @@ def build_candidate(
issues: tuple[str, ...] = (),
allow_single_row: bool = False,
allow_single_column: bool = False,
+ require_atomic_tokens: bool = False,
+ diagnostics: dict[str, object] | None = None,
) -> NativeTableCandidate | None:
"""校验网格、唯一分配字符并计算统一质量分。"""
@@ -138,6 +155,8 @@ def build_candidate(
allow_single_row=allow_single_row,
allow_single_column=allow_single_column,
):
+ if diagnostics is not None:
+ diagnostics["candidate_rejection_gate"] = "grid_specs"
return None
assignments: dict[int, int] = {}
cell_glyphs: list[list[NativeTableGlyph]] = [[] for _ in specs]
@@ -153,7 +172,17 @@ def build_candidate(
glyph_count = len(text.glyphs)
text_capture = len(assignments) / glyph_count if glyph_count else 0.0
ambiguous_ratio = ambiguous_count / glyph_count if glyph_count else 0.0
+ split_token_count = _count_split_tokens(text, assignments)
+ if diagnostics is not None:
+ diagnostics["token_split_count"] = split_token_count
+ diagnostics["ambiguous_glyph_ratio"] = ambiguous_ratio
if text_capture < MIN_TEXT_CAPTURE or ambiguous_ratio > 0.02:
+ if diagnostics is not None:
+ diagnostics["candidate_rejection_gate"] = "text_assignment"
+ return None
+ if require_atomic_tokens and split_token_count:
+ if diagnostics is not None:
+ diagnostics["candidate_rejection_gate"] = "token_split"
return None
cells = tuple(
NativeTableCell(
@@ -187,6 +216,8 @@ def build_candidate(
normalized_column,
order_consistency,
)
+ if diagnostics is not None:
+ diagnostics["candidate_rejection_gate"] = None
return NativeTableCandidate(
source=source,
rows=rows,
diff --git a/mineru/utils/native_pdf_table/engine.py b/mineru/utils/native_pdf_table/engine.py
index a49883b0..3eb7572d 100644
--- a/mineru/utils/native_pdf_table/engine.py
+++ b/mineru/utils/native_pdf_table/engine.py
@@ -19,7 +19,7 @@ from .contracts import (
)
from .geometry import bbox_intersection, normalize_bbox
from .text import build_native_table_text
-from .text_grid import build_text_candidates
+from .text_grid import build_text_candidates, diagnose_text_candidate_builds
from .vector import (
MAX_PRIMITIVES_PER_TABLE,
build_vector_candidates,
@@ -50,6 +50,7 @@ class _CandidateEvaluation:
generated_candidates: tuple[NativeTableCandidate, ...]
candidates: tuple[NativeTableCandidate, ...]
selected: NativeTableCandidate | None
+ physical_topology_conflict: bool
first_rejection_gate: str | None
@@ -64,6 +65,45 @@ def _is_verified_line_candidate(candidate: NativeTableCandidate) -> bool:
)
+def _is_verified_rect_candidate(candidate: NativeTableCandidate) -> bool:
+ """判断候选是否由无歧义矩形晶格独立验证。"""
+
+ return (
+ candidate.source == "vector_grid"
+ and candidate.score >= 0.95
+ and "evidence=rect_grid" in candidate.issues
+ and "ambiguous_separator_ratio=0.0000" in candidate.issues
+ )
+
+
+def _has_line_rect_topology_conflict(
+ candidates: Iterable[NativeTableCandidate],
+) -> bool:
+ """判断两类独立物理证据是否给出不同拓扑。"""
+
+ materialized = list(candidates)
+ line_candidates = [candidate for candidate in materialized if _is_verified_line_candidate(candidate)]
+ rect_candidates = [candidate for candidate in materialized if _is_verified_rect_candidate(candidate)]
+ return any(line.topology != rect.topology for line in line_candidates for rect in rect_candidates)
+
+
+def _has_attempted_line_rect_grid_conflict(
+ attempts: Iterable[dict[str, Any]],
+) -> bool:
+ """判断已恢复轨道的 line/rect 物理假设是否在行列数上冲突。"""
+
+ materialized = list(attempts)
+ line_grids = [attempt.get("grid") for attempt in materialized if attempt.get("evidence") == "line_grid"]
+ rect_grids = [attempt.get("grid") for attempt in materialized if attempt.get("evidence") == "rect_grid"]
+ return any(
+ isinstance(line, dict)
+ and isinstance(rect, dict)
+ and (line.get("rows"), line.get("cols")) != (rect.get("rows"), rect.get("cols"))
+ for line in line_grids
+ for rect in rect_grids
+ )
+
+
def _passes_verified_threshold(candidate: NativeTableCandidate) -> bool:
"""按候选来源应用独立校准的 verified 可靠度门槛。"""
@@ -178,6 +218,20 @@ def _has_alias_affected_physical_blank_row(
return False
+def _has_physical_row_undercount(
+ vector_attempts: tuple[dict[str, Any], ...],
+) -> bool:
+ """判断 line-grid 及其有限轨道假设是否已发现物理行欠分割。"""
+
+ for attempt in vector_attempts:
+ if attempt.get("evidence") != "line_grid":
+ continue
+ hypotheses = [attempt, *attempt.get("track_hypotheses", [])]
+ if any(hypothesis.get("first_rejection_gate") == "physical_row_undercount" for hypothesis in hypotheses):
+ return True
+ return False
+
+
def _table_primitive_count(table_input: NativeTableInput) -> int:
"""统计实际与目标表格相交的 drawing 和矩形数量。"""
@@ -200,6 +254,8 @@ def _select_candidate(
accepted = [candidate for candidate in candidates if _passes_verified_threshold(candidate)]
if not accepted:
return None
+ if _has_line_rect_topology_conflict(accepted):
+ return None
verified_line_candidates = [candidate for candidate in accepted if _is_verified_line_candidate(candidate)]
if len(verified_line_candidates) == 1:
return verified_line_candidates[0]
@@ -242,6 +298,7 @@ def _evaluate_native_pdf_table(
(),
(),
None,
+ False,
"input_geometry",
)
if primitive_count > MAX_PRIMITIVES_PER_TABLE:
@@ -251,6 +308,7 @@ def _evaluate_native_pdf_table(
(),
(),
None,
+ False,
"primitive_limit",
)
text = build_native_table_text(table_input)
@@ -261,20 +319,30 @@ def _evaluate_native_pdf_table(
(),
(),
None,
+ False,
"native_text",
)
vector_candidates = build_vector_candidates(table_input, text)
- text_candidates = build_text_candidates(table_input, text) if len(text.rows) >= 2 else []
- if not vector_candidates and text_candidates:
+ vector_attempts: tuple[dict[str, Any], ...] = ()
+ physical_topology_conflict = False
+ if any(_is_verified_rect_candidate(candidate) for candidate in vector_candidates):
vector_attempts = diagnose_vector_candidate_builds(
table_input,
text,
)
- if _has_alias_affected_physical_blank_row(vector_attempts):
+ physical_topology_conflict = _has_attempted_line_rect_grid_conflict(vector_attempts)
+ text_candidates = build_text_candidates(table_input, text) if len(text.rows) >= 2 else []
+ if text_candidates and (not vector_candidates or physical_topology_conflict):
+ if not vector_attempts:
+ vector_attempts = diagnose_vector_candidate_builds(
+ table_input,
+ text,
+ )
+ if _has_alias_affected_physical_blank_row(vector_attempts) or _has_physical_row_undercount(vector_attempts):
text_candidates = []
generated_candidates = [*vector_candidates, *text_candidates]
candidates = _remove_undercounted_vector_candidates(generated_candidates)
- selected = _select_candidate(candidates)
+ selected = None if physical_topology_conflict else _select_candidate(candidates)
if selected is not None:
first_rejection_gate = None
elif not generated_candidates:
@@ -291,6 +359,7 @@ def _evaluate_native_pdf_table(
tuple(generated_candidates),
tuple(candidates),
selected,
+ physical_topology_conflict,
first_rejection_gate,
)
@@ -307,13 +376,36 @@ def diagnose_native_pdf_table(table_input: NativeTableInput) -> dict[str, Any]:
if evaluation.text is not None
else ()
)
+ text_attempts = (
+ diagnose_text_candidate_builds(
+ table_input,
+ evaluation.text,
+ )
+ if evaluation.text is not None
+ else ()
+ )
first_rejection_gate = evaluation.first_rejection_gate
if first_rejection_gate == "candidate_generation":
+ text_attempt = next(
+ (
+ attempt
+ for attempt in text_attempts
+ if attempt.get("first_rejection_gate")
+ in {
+ "dense_row_ambiguity",
+ "header_requires_rowspan",
+ "token_split",
+ }
+ ),
+ None,
+ )
line_attempt = next(
(attempt for attempt in vector_attempts if attempt.get("evidence") == "line_grid"),
None,
)
- if line_attempt is not None and line_attempt.get("first_rejection_gate"):
+ if text_attempt is not None:
+ first_rejection_gate = "text_" + str(text_attempt["first_rejection_gate"])
+ elif line_attempt is not None and line_attempt.get("first_rejection_gate"):
first_rejection_gate = "vector_" + str(line_attempt["first_rejection_gate"])
def candidate_record(
@@ -363,7 +455,11 @@ def diagnose_native_pdf_table(table_input: NativeTableInput) -> dict[str, Any]:
"glyph_count": len(evaluation.text.glyphs) if evaluation.text else 0,
"visual_text_rows": len(evaluation.text.rows) if evaluation.text else 0,
"first_rejection_gate": first_rejection_gate,
+ "line_rect_topology_conflict": (
+ evaluation.physical_topology_conflict or _has_line_rect_topology_conflict(evaluation.candidates)
+ ),
"vector_attempts": list(vector_attempts),
+ "text_attempts": list(text_attempts),
"generated_candidates": [candidate_record(candidate) for candidate in evaluation.generated_candidates],
"removed_by_undercount": removed_candidates,
"counterfactual_best": (candidate_record(counterfactual_best) if counterfactual_best is not None else None),
diff --git a/mineru/utils/native_pdf_table/text_grid.py b/mineru/utils/native_pdf_table/text_grid.py
index 8a7fdac6..189a5e8d 100644
--- a/mineru/utils/native_pdf_table/text_grid.py
+++ b/mineru/utils/native_pdf_table/text_grid.py
@@ -3,8 +3,11 @@
from __future__ import annotations
+import math
import statistics
from collections import Counter
+from dataclasses import dataclass
+from typing import Any
from .candidate import GridCellSpec, build_candidate
from .contracts import (
@@ -25,6 +28,15 @@ from .geometry import (
MIN_COLUMN_ANCHOR_SUPPORT = 0.60
+@dataclass(frozen=True, slots=True)
+class _LogicalRowGrouping:
+ """保存视觉行分组结果及不宜自动合并的稠密行对。"""
+
+ rows: tuple[NativeTableTextRow, ...]
+ dense_ambiguities: tuple[tuple[int, int], ...]
+ subset_merges: tuple[tuple[int, int], ...]
+
+
def _infer_target_column_count(text: NativeTableText) -> int | None:
"""从多行文本项数量中选择有重复证据的最大叶子列数。"""
@@ -177,30 +189,40 @@ def _group_logical_rows(
table_input: NativeTableInput,
text: NativeTableText,
x_tracks: list[float],
-) -> tuple[NativeTableTextRow, ...]:
+) -> _LogicalRowGrouping:
"""保守合并同格内紧邻 continuation,避免 baseline 直接等同逻辑行。"""
groups: list[list[NativeTableTextRow]] = []
group_occupancy: list[set[int]] = []
+ dense_ambiguities: list[tuple[int, int]] = []
+ subset_merges: list[tuple[int, int]] = []
maximum_gap = max(0.75, 0.40 * text.median_glyph_height)
+ target_cols = len(x_tracks) - 1
+ dense_column_count = max(2, math.ceil(MIN_COLUMN_ANCHOR_SUPPORT * target_cols))
for row in text.rows:
columns = _token_columns(row, x_tracks)
occupancy = set(columns or [])
if groups:
previous = groups[-1][-1]
gap = row.bbox[1] - previous.bbox[3]
- can_continue = (
- bool(occupancy)
- and occupancy.issubset(group_occupancy[-1])
+ has_horizontal_rule = _has_horizontal_rule_between(
+ table_input,
+ previous,
+ row,
+ )
+ if (
+ occupancy == group_occupancy[-1]
+ and len(occupancy) >= dense_column_count
and gap <= maximum_gap
- and not _has_horizontal_rule_between(
- table_input,
- previous,
- row,
- )
+ and not has_horizontal_rule
+ ):
+ dense_ambiguities.append((previous.row_index, row.row_index))
+ can_continue = (
+ bool(occupancy) and occupancy < group_occupancy[-1] and gap <= maximum_gap and not has_horizontal_rule
)
if can_continue:
groups[-1].append(row)
+ subset_merges.append((previous.row_index, row.row_index))
continue
groups.append([row])
group_occupancy.append(occupancy)
@@ -220,7 +242,36 @@ def _group_logical_rows(
glyph_ids=tuple(glyph_id for row in group for glyph_id in row.glyph_ids),
)
)
- return tuple(logical_rows)
+ return _LogicalRowGrouping(
+ rows=tuple(logical_rows),
+ dense_ambiguities=tuple(dense_ambiguities),
+ subset_merges=tuple(subset_merges),
+ )
+
+
+def _header_rows_are_representable(
+ rows: tuple[NativeTableTextRow, ...],
+ x_tracks: list[float],
+ first_dense_row: int,
+) -> bool:
+ """校验前导多层表头能否仅用当前 colspan 逻辑完整表达。"""
+
+ if first_dense_row < 1:
+ return True
+ all_columns = set(range(len(x_tracks) - 1))
+ for row_index in range(first_dense_row):
+ row = rows[row_index]
+ spans = _grouped_header_spans(row, rows[row_index + 1], x_tracks) if row_index + 1 < len(rows) else None
+ if spans is not None:
+ coverage = {col for start_col, end_col in spans for col in range(start_col, end_col + 1)}
+ else:
+ token_columns = _token_columns(row, x_tracks)
+ if token_columns is None:
+ return False
+ coverage = set(token_columns)
+ if coverage != all_columns:
+ return False
+ return True
def _single_header_span(
@@ -411,37 +462,66 @@ def _build_aligned_candidate(
require_three_rows: bool,
require_three_cols: bool,
physical_support: float,
+ diagnostics: dict[str, Any] | None = None,
) -> NativeTableCandidate | None:
"""按统一文本轨道构造 sparse、wireless 或 key-value 候选。"""
+ if diagnostics is not None:
+ diagnostics["source"] = source
+ diagnostics["raw_visual_rows"] = len(text.rows)
+
+ def reject(gate: str) -> None:
+ """记录文本候选的首个拒绝门。"""
+
+ if diagnostics is not None:
+ diagnostics["first_rejection_gate"] = gate
+ return None
+
target_cols = _infer_target_column_count(text)
if target_cols is None:
- return None
+ return reject("column_count")
if require_three_cols and target_cols < 3:
- return None
+ return reject("column_count")
if source == "key_value" and target_cols != 2:
- return None
+ return reject("column_count")
if require_three_rows and len(text.rows) < 3:
- return None
+ return reject("row_count")
table_bbox = normalize_bbox(table_input.table_bbox)
if table_bbox is None:
- return None
+ return reject("table_geometry")
width, height = table_local_size(table_bbox, normalize_angle(table_input.angle))
column_result = _infer_column_tracks(text, width, target_cols)
if column_result is None:
- return None
+ return reject("column_tracks")
x_tracks, anchor_support, alignment_support = column_result
- logical_rows = _group_logical_rows(
+ grouping = _group_logical_rows(
table_input,
text,
x_tracks,
)
+ logical_rows = grouping.rows
+ if diagnostics is not None:
+ diagnostics["logical_rows"] = len(logical_rows)
+ diagnostics["dense_row_ambiguities"] = [list(pair) for pair in grouping.dense_ambiguities]
+ diagnostics["subset_continuation_merges"] = [list(pair) for pair in grouping.subset_merges]
+ if grouping.dense_ambiguities:
+ return reject("dense_row_ambiguity")
y_tracks = _infer_row_tracks(logical_rows, height)
if y_tracks is None:
- return None
+ return reject("row_tracks")
dense_row_indices = [row.row_index for row in logical_rows if len(set(_token_columns(row, x_tracks) or [])) == target_cols]
first_dense_row = min(dense_row_indices) if dense_row_indices else 0
+ header_representable = _header_rows_are_representable(
+ logical_rows,
+ x_tracks,
+ first_dense_row,
+ )
+ if diagnostics is not None:
+ diagnostics["first_dense_row"] = first_dense_row
+ diagnostics["header_representable"] = header_representable
+ if not header_representable:
+ return reject("header_requires_rowspan")
specs_result = _build_text_grid_specs(
logical_rows,
x_tracks,
@@ -449,12 +529,12 @@ def _build_aligned_candidate(
first_dense_row,
)
if specs_result is None:
- return None
+ return reject("grid_specs")
specs, row_stability = specs_result
if row_stability < MIN_COLUMN_ANCHOR_SUPPORT:
- return None
+ return reject("row_stability")
structure_support = max(anchor_support, physical_support) if source == "sparse_grid" else alignment_support
- return build_candidate(
+ candidate = build_candidate(
source=source,
rows=len(logical_rows),
cols=target_cols,
@@ -463,18 +543,30 @@ def _build_aligned_candidate(
structure_support=structure_support,
row_stability=row_stability,
column_stability=alignment_support,
+ require_atomic_tokens=True,
+ diagnostics=diagnostics,
)
+ if candidate is None:
+ if diagnostics is not None and diagnostics.get("first_rejection_gate") is None:
+ diagnostics["first_rejection_gate"] = diagnostics.get("candidate_rejection_gate", "candidate_hard_gate")
+ return None
+ if diagnostics is not None:
+ diagnostics["first_rejection_gate"] = None
+ diagnostics["score"] = candidate.score
+ return candidate
def build_text_candidates(
table_input: NativeTableInput,
text: NativeTableText,
+ diagnostics: list[dict[str, Any]] | None = None,
) -> list[NativeTableCandidate]:
"""同时生成少线、三列以上无线表和两列 key-value 候选。"""
candidates: list[NativeTableCandidate] = []
physical_support = _physical_sparse_evidence(table_input, text)
if physical_support > 0:
+ sparse_diagnostics: dict[str, Any] | None = {} if diagnostics is not None else None
sparse = _build_aligned_candidate(
table_input=table_input,
text=text,
@@ -482,10 +574,14 @@ def build_text_candidates(
require_three_rows=False,
require_three_cols=False,
physical_support=physical_support,
+ diagnostics=sparse_diagnostics,
)
+ if diagnostics is not None and sparse_diagnostics is not None:
+ diagnostics.append(sparse_diagnostics)
if sparse is not None:
candidates.append(sparse)
+ text_diagnostics: dict[str, Any] | None = {} if diagnostics is not None else None
text_grid = _build_aligned_candidate(
table_input=table_input,
text=text,
@@ -493,10 +589,14 @@ def build_text_candidates(
require_three_rows=True,
require_three_cols=True,
physical_support=0.0,
+ diagnostics=text_diagnostics,
)
+ if diagnostics is not None and text_diagnostics is not None:
+ diagnostics.append(text_diagnostics)
if text_grid is not None:
candidates.append(text_grid)
+ key_value_diagnostics: dict[str, Any] | None = {} if diagnostics is not None else None
key_value = _build_aligned_candidate(
table_input=table_input,
text=text,
@@ -504,10 +604,28 @@ def build_text_candidates(
require_three_rows=True,
require_three_cols=False,
physical_support=0.0,
+ diagnostics=key_value_diagnostics,
)
+ if diagnostics is not None and key_value_diagnostics is not None:
+ diagnostics.append(key_value_diagnostics)
if key_value is not None:
candidates.append(key_value)
return candidates
+def diagnose_text_candidate_builds(
+ table_input: NativeTableInput,
+ text: NativeTableText,
+) -> tuple[dict[str, Any], ...]:
+ """重放文本候选构造并返回不含单元格全文的诊断。"""
+
+ diagnostics: list[dict[str, Any]] = []
+ build_text_candidates(
+ table_input,
+ text,
+ diagnostics=diagnostics,
+ )
+ return tuple(diagnostics)
+
+
__all__ = ["build_text_candidates"]
diff --git a/mineru/utils/native_pdf_table/vector.py b/mineru/utils/native_pdf_table/vector.py
index 22f4ddae..f89439bb 100644
--- a/mineru/utils/native_pdf_table/vector.py
+++ b/mineru/utils/native_pdf_table/vector.py
@@ -1084,6 +1084,60 @@ def _text_grid_stability(
)
+def _physical_row_dense_baseline_pairs(
+ text: NativeTableText,
+ x_tracks: list[float],
+ y_tracks: list[float],
+) -> tuple[dict[str, object], ...]:
+ """识别同一物理行带内占用集合相同的多条稠密文本基线。"""
+
+ cols = len(x_tracks) - 1
+ dense_column_count = max(2, math.ceil(0.60 * cols))
+ rows_by_band: dict[int, list[tuple[int, tuple[int, ...]]]] = {row: [] for row in range(len(y_tracks) - 1)}
+ for text_row in text.rows:
+ center_y = (text_row.bbox[1] + text_row.bbox[3]) / 2.0
+ band = next(
+ (row for row, (top, bottom) in enumerate(zip(y_tracks, y_tracks[1:])) if top <= center_y <= bottom),
+ None,
+ )
+ if band is None:
+ continue
+ occupied_cols: set[int] = set()
+ for token in text_row.tokens:
+ center_x = (token.bbox[0] + token.bbox[2]) / 2.0
+ col = next(
+ (index for index, (left, right) in enumerate(zip(x_tracks, x_tracks[1:])) if left <= center_x <= right),
+ None,
+ )
+ if col is not None:
+ occupied_cols.add(col)
+ rows_by_band[band].append(
+ (
+ text_row.row_index,
+ tuple(sorted(occupied_cols)),
+ )
+ )
+
+ ambiguous_pairs: list[dict[str, object]] = []
+ for band, entries in rows_by_band.items():
+ nonempty_entries = [entry for entry in entries if entry[1]]
+ if (
+ len(nonempty_entries) < 2
+ or len(nonempty_entries[0][1]) < dense_column_count
+ or any(entry[1] != nonempty_entries[0][1] for entry in nonempty_entries[1:])
+ ):
+ continue
+ for previous, current in zip(nonempty_entries, nonempty_entries[1:]):
+ ambiguous_pairs.append(
+ {
+ "physical_row": band,
+ "visual_rows": [previous[0], current[0]],
+ "occupied_cols": list(previous[1]),
+ }
+ )
+ return tuple(ambiguous_pairs)
+
+
def _looks_like_single_column_tracks(
x_tracks: list[float],
local_width: float,
@@ -1359,8 +1413,23 @@ def _build_vector_candidate(
return reject("track_count")
rows = len(y_tracks) - 1
cols = len(x_tracks) - 1
+ if diagnostics is not None:
+ diagnostics["grid"] = {"rows": rows, "cols": cols}
if rows * cols > MAX_ATOMIC_CELLS:
return reject("atomic_cell_limit")
+ dense_baseline_pairs = (
+ _physical_row_dense_baseline_pairs(
+ text,
+ x_tracks,
+ y_tracks,
+ )
+ if is_line_grid
+ else ()
+ )
+ if diagnostics is not None:
+ diagnostics["physical_row_dense_baseline_pairs"] = list(dense_baseline_pairs)
+ if dense_baseline_pairs:
+ return reject("physical_row_undercount")
union_find = _UnionFind(rows * cols)
separator_decisions: list[float] = []
@@ -1606,9 +1675,15 @@ def _build_vector_candidate(
),
allow_single_row=is_single_row_shape,
allow_single_column=is_single_column_shape,
+ diagnostics=diagnostics,
)
if candidate is None:
- return reject("candidate_hard_gate")
+ candidate_gate = (
+ str(diagnostics.get("candidate_rejection_gate"))
+ if diagnostics is not None and diagnostics.get("candidate_rejection_gate")
+ else "candidate_hard_gate"
+ )
+ return reject(candidate_gate)
if is_single_row_shape and (candidate.text_capture < 1.0 or candidate.order_consistency < 1.0):
return reject("single_row_text_integrity")
if is_single_column_shape and (candidate.text_capture < 1.0 or candidate.order_consistency < 1.0):
diff --git a/tests/unittest/test_native_pdf_table.py b/tests/unittest/test_native_pdf_table.py
index d428bd6d..bcb46019 100644
--- a/tests/unittest/test_native_pdf_table.py
+++ b/tests/unittest/test_native_pdf_table.py
@@ -18,6 +18,7 @@ from mineru.utils.native_pdf_table import (
coerce_native_table_rules,
recover_native_pdf_table,
)
+from mineru.utils.native_pdf_table.candidate import GridCellSpec, build_candidate
from mineru.utils.native_pdf_table.contracts import NativeTableCandidate
from mineru.utils.native_pdf_table.engine import (
_remove_undercounted_vector_candidates,
@@ -346,7 +347,7 @@ def test_vector_grid_recovers_cells_and_escapes_html() -> None:
def test_vector_grid_splits_one_pdf_text_run_by_character_boundary() -> None:
- """验证同一原生文本对象横跨两列时仍按逐字符 bbox 唯一落格。"""
+ """验证物理列边界可将同一 PDF 文本对象按字符安全落格。"""
table_input = NativeTableInput(
table_bbox=(0.0, 0.0, 100.0, 60.0),
@@ -368,6 +369,49 @@ def test_vector_grid_splits_one_pdf_text_run_by_character_boundary() -> None:
assert "<tr><td>A</td><td>B</td></tr>" in result.html
+def test_text_candidate_rejects_token_split_across_cell_boundary() -> None:
+ """验证纯文本轨道不将一个原子 token 分割到两个逻辑单元格。"""
+
+ table_input = NativeTableInput(
+ table_bbox=(0.0, 0.0, 100.0, 60.0),
+ page_size=(100.0, 60.0),
+ angle=0,
+ chars=_char_items(
+ [
+ ("AB", (45.0, 10.0, 55.0, 18.0)),
+ ("C", (10.0, 40.0, 15.0, 48.0)),
+ ("D", (60.0, 40.0, 65.0, 48.0)),
+ ]
+ ),
+ )
+ text = build_native_table_text(table_input)
+ assert text is not None
+ specs = (
+ GridCellSpec(0, 0, 1, 1, (0.0, 0.0, 50.0, 30.0)),
+ GridCellSpec(0, 1, 1, 1, (50.0, 0.0, 100.0, 30.0)),
+ GridCellSpec(1, 0, 1, 1, (0.0, 30.0, 50.0, 60.0)),
+ GridCellSpec(1, 1, 1, 1, (50.0, 30.0, 100.0, 60.0)),
+ )
+ diagnostics: dict[str, object] = {}
+
+ candidate = build_candidate(
+ source="text_grid",
+ rows=2,
+ cols=2,
+ specs=specs,
+ text=text,
+ structure_support=1.0,
+ row_stability=1.0,
+ column_stability=1.0,
+ require_atomic_tokens=True,
+ diagnostics=diagnostics,
+ )
+
+ assert candidate is None
+ assert diagnostics["candidate_rejection_gate"] == "token_split"
+ assert diagnostics["token_split_count"] == 1
+
+
def test_vector_grid_accepts_open_outer_vertical_edges() -> None:
"""验证横线端点可补齐缺失的左右外框而不伪造内部隔断。"""
@@ -425,6 +469,52 @@ def test_single_long_rule_endpoint_does_not_create_global_column() -> None:
assert (result.rows, result.cols) == (2, 2)
+def test_line_grid_rejects_multiple_dense_baselines_inside_one_physical_row() -> None:
+ """验证只有表头横线的强竖轨表不把多条数据基线压成一行。"""
+
+ rules = (
+ NativeTableRule((0.0, 0.0, 120.0, 1.0), 1.0, "horizontal"),
+ NativeTableRule((0.0, 19.5, 120.0, 20.5), 1.0, "horizontal"),
+ NativeTableRule((0.0, 59.0, 120.0, 60.0), 1.0, "horizontal"),
+ NativeTableRule((0.0, 0.0, 1.0, 60.0), 1.0, "vertical"),
+ NativeTableRule((39.5, 0.0, 40.5, 60.0), 1.0, "vertical"),
+ NativeTableRule((79.5, 0.0, 80.5, 60.0), 1.0, "vertical"),
+ NativeTableRule((119.0, 0.0, 120.0, 60.0), 1.0, "vertical"),
+ )
+ table_input = NativeTableInput(
+ table_bbox=(0.0, 0.0, 120.0, 60.0),
+ page_size=(120.0, 60.0),
+ angle=0,
+ chars=_char_items(
+ [
+ ("H1", (8.0, 5.0, 16.0, 13.0)),
+ ("H2", (48.0, 5.0, 56.0, 13.0)),
+ ("H3", (88.0, 5.0, 96.0, 13.0)),
+ ("A", (8.0, 27.0, 12.0, 35.0)),
+ ("1", (48.0, 27.0, 52.0, 35.0)),
+ ("2", (88.0, 27.0, 92.0, 35.0)),
+ ("B", (8.0, 42.0, 12.0, 50.0)),
+ ("3", (48.0, 42.0, 52.0, 50.0)),
+ ("4", (88.0, 42.0, 92.0, 50.0)),
+ ]
+ ),
+ drawing_lines=rules,
+ )
+
+ diagnostics = diagnose_native_pdf_table(table_input)
+
+ assert recover_native_pdf_table(table_input) is None
+ line_attempt = next(attempt for attempt in diagnostics["vector_attempts"] if attempt["evidence"] == "line_grid")
+ assert line_attempt["first_rejection_gate"] == "physical_row_undercount"
+ assert line_attempt["physical_row_dense_baseline_pairs"] == [
+ {
+ "physical_row": 1,
+ "visual_rows": [1, 2],
+ "occupied_cols": [0, 1, 2],
+ }
+ ]
+
+
def test_vector_grid_joins_small_collinear_gaps() -> None:
"""验证内部竖线的小间隙会先连接,不会误判为 colspan。"""
@@ -1388,6 +1478,36 @@ def test_text_grid_groups_tight_subset_continuation_without_break() -> None:
assert "<tr><td>A1A2</td><td>B1</td><td>C1</td></tr>" in result.html
+def test_text_grid_rejects_tight_equal_dense_baselines() -> None:
+ """验证紧邻且占用列相同的稠密基线不被冒充续行合并。"""
+
+ table_input = NativeTableInput(
+ table_bbox=(0.0, 0.0, 120.0, 75.0),
+ page_size=(120.0, 75.0),
+ angle=0,
+ chars=_char_items(
+ [
+ ("A1", (8.0, 5.0, 16.0, 13.0)),
+ ("B1", (48.0, 5.0, 56.0, 13.0)),
+ ("C1", (88.0, 5.0, 96.0, 13.0)),
+ ("A2", (8.0, 14.0, 16.0, 22.0)),
+ ("B2", (48.0, 14.0, 56.0, 22.0)),
+ ("C2", (88.0, 14.0, 96.0, 22.0)),
+ ("A3", (8.0, 50.0, 16.0, 58.0)),
+ ("B3", (48.0, 50.0, 56.0, 58.0)),
+ ("C3", (88.0, 50.0, 96.0, 58.0)),
+ ]
+ ),
+ )
+
+ diagnostics = diagnose_native_pdf_table(table_input)
+
+ assert recover_native_pdf_table(table_input) is None
+ text_attempt = next(attempt for attempt in diagnostics["text_attempts"] if attempt["source"] == "text_grid")
+ assert text_attempt["first_rejection_gate"] == "dense_row_ambiguity"
+ assert text_attempt["dense_row_ambiguities"] == [[0, 1]]
+
+
def test_text_grid_accepts_right_aligned_numeric_columns() -> None:
"""验证数字宽度变化但右缘稳定时仍能恢复同一列结构。"""
@@ -1443,6 +1563,34 @@ def test_text_grid_recovers_conservative_multicolumn_header() -> None:
assert '<td colspan="3">ABCDEFGHIJKLMNOPQR</td>' in result.html
+def test_text_grid_rejects_header_that_requires_rowspan() -> None:
+ """验证表头角落空缺且需要 rowspan 才能还原时不生成伪网格。"""
+
+ table_input = NativeTableInput(
+ table_bbox=(0.0, 0.0, 120.0, 90.0),
+ page_size=(120.0, 90.0),
+ angle=0,
+ chars=_char_items(
+ [
+ ("Metrics", (52.0, 5.0, 104.0, 13.0)),
+ ("Name", (8.0, 30.0, 24.0, 38.0)),
+ ("Q1", (48.0, 30.0, 56.0, 38.0)),
+ ("Q2", (88.0, 30.0, 96.0, 38.0)),
+ ("A", (8.0, 60.0, 12.0, 68.0)),
+ ("1", (48.0, 60.0, 52.0, 68.0)),
+ ("2", (88.0, 60.0, 92.0, 68.0)),
+ ]
+ ),
+ )
+
+ diagnostics = diagnose_native_pdf_table(table_input)
+
+ assert recover_native_pdf_table(table_input) is None
+ text_attempt = next(attempt for attempt in diagnostics["text_attempts"] if attempt["source"] == "text_grid")
+ assert text_attempt["first_rejection_gate"] == "header_requires_rowspan"
+ assert text_attempt["header_representable"] is False
+
+
def test_key_value_candidate_handles_two_stable_columns() -> None:
"""验证两列字段值表走独立 key-value 候选。"""
@@ -1546,6 +1694,33 @@ def test_verified_line_grid_wins_conflicting_text_topology() -> None:
assert _select_candidate([line, text]) is line
+def test_verified_line_and_rect_topology_conflict_abstains() -> None:
+ """验证两类独立物理证据拓扑不一致时不由 line-grid 抢占。"""
+
+ line = _candidate(
+ source="vector_grid",
+ rows=2,
+ cols=2,
+ score=1.0,
+ issues=(
+ "evidence=line_grid",
+ "ambiguous_separator_ratio=0.0000",
+ ),
+ )
+ rect = _candidate(
+ source="vector_grid",
+ rows=3,
+ cols=2,
+ score=1.0,
+ issues=(
+ "evidence=rect_grid",
+ "ambiguous_separator_ratio=0.0000",
+ ),
+ )
+
+ assert _select_candidate([line, rect]) is None
+
+
def test_text_candidate_removes_significantly_undercounted_vector() -> None:
"""验证稳定文本候选显著多出行列时剔除欠分割矢量候选。"""