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 table note processing by adding support for auxiliary markers and refining reference height estimation
myhlolieb9bcf98de8b
diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.pyindex 3a8bf54b..7ae3b6a7 100644--- a/mineru/backend/flash/native_pdf/tables.py+++ b/mineru/backend/flash/native_pdf/tables.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport reimport statistics+import unicodedatafrom typing import Anyfrom loguru import logger@@ -30,6 +31,7 @@ from .geometry import (_bbox_overlap_in_smaller,_bbox_union,_bbox_union_many,+ _coerce_bbox,_expand_bbox,_point_in_bbox,_rotate_bbox_from_upright,@@ -53,6 +55,12 @@ _TABLE_NOTE_RE = re.compile()+_AUXILIARY_TABLE_NOTE_RE = re.compile(+ r"^\s*[([{([【]?(?P<marker>[^\s)\]})]】.::、]{1,3})"+ r"[)\]})]】]?[.::、)]*\s+(?P<body>\S.*)$"+)++_TABLE_SPLIT_NUMBER_RE = re.compile(r"^(?:\d+|[ivxlcdm]+|[一二三四五六七八九十]+)[.::]?$",re.IGNORECASE,@@ -945,6 +953,8 @@ def _expand_rule_table_candidate(rule_bbox,median_height,core_line_indices,+ page_size,+ angle,)included_rows = [*caption_rows, *core_rows, *footnote_rows]core_local_bbox = _bbox_union(rule_bbox, _bbox_union_many([row.bbox for row in core_rows]))@@ -1005,8 +1015,10 @@ def _collect_footnote_rows(rule_bbox: BBox,median_height: float,core_line_indices: set[int],+ page_size: tuple[float, float],+ angle: int,) -> list[_VisualRow]:- """从表格下边界开始吸收带通用标记的脚注及其连续换行。"""+ """从表格下边界吸收具有表内引用和版面证据的表注连续行。"""output: list[_VisualRow] = []bottom = rule_bbox[3]@@ -1014,6 +1026,15 @@ def _collect_footnote_rows(margin = 2.0 * median_heightselected_line_indices = set(core_line_indices)line_by_index = {line.source_index: line for line in lines}+ core_lines = [line for line in lines if line.source_index in core_line_indices]+ body_reference_height = _table_note_body_reference_height(+ lines,+ rule_bbox,+ median_height,+ core_line_indices,+ page_size,+ angle,+ )note_left: float | None = Nonenote_height: float | None = Nonenote_fonts: set[tuple[str, int]] = set()@@ -1032,7 +1053,10 @@ def _collect_footnote_rows(if line_index in line_by_index]row_heights = [- _line_effective_height(line, line.bbox)+ _line_effective_height(+ line,+ _rotate_bbox_to_upright(line.bbox, page_size, angle),+ )for line in row_lines]row_height = statistics.median(row_heights) if row_heights else clipped_row.bbox[3] - clipped_row.bbox[1]@@ -1041,16 +1065,40 @@ def _collect_footnote_rows(for line in row_linesif line.font_signature is not None and line.font_coverage >= 0.75}- if row_gap > (1.25 if not note_chain_started else 1.0) * median_height:+ if note_chain_started and clipped_row.bbox[3] - rule_bbox[3] > 10.0 * median_height:+ break+ row_text = _visual_row_text(clipped_row)+ explicit_note = _is_table_note_text(row_text)+ auxiliary_marker = _extract_auxiliary_table_note_marker(row_text)+ auxiliary_note = (+ auxiliary_marker is not None+ and _table_core_references_marker(+ auxiliary_marker,+ core_lines,+ page_size,+ angle,+ )+ )+ first_gap_limit = 0.75 if auxiliary_note and not explicit_note else 1.25+ if row_gap > (first_gap_limit if not note_chain_started else 1.0) * median_height:breakif not note_chain_started:- if not _is_table_note_text(_visual_row_text(clipped_row)):+ if not explicit_note and not auxiliary_note:break- if (- _bbox_axis_overlap_ratio(row.bbox, rule_bbox, axis="x") < 0.35- or abs(clipped_row.bbox[0] - rule_bbox[0]) > 2.0 * median_height- or row_height > 1.15 * median_height- ):+ if explicit_note:+ spatially_compatible = (+ _bbox_axis_overlap_ratio(clipped_row.bbox, rule_bbox, axis="x") >= 0.35+ and abs(clipped_row.bbox[0] - rule_bbox[0]) <= 2.0 * median_height+ and row_height <= 1.15 * median_height+ )+ else:+ spatially_compatible = (+ _bbox_axis_overlap_ratio(clipped_row.bbox, rule_bbox, axis="x") >= 0.50+ and abs(clipped_row.bbox[0] - rule_bbox[0]) <= 3.0 * median_height+ and row_height <= 1.05 * median_height+ and row_height <= 0.90 * body_reference_height+ )+ if not spatially_compatible:breaknote_left = clipped_row.bbox[0]note_height = max(0.1, row_height)@@ -1065,7 +1113,7 @@ def _collect_footnote_rows(and row_fontsand note_fonts.isdisjoint(row_fonts))- or _bbox_axis_overlap_ratio(row.bbox, rule_bbox, axis="x") < 0.35+ or _bbox_axis_overlap_ratio(clipped_row.bbox, rule_bbox, axis="x") < 0.35):# 字号、字体或缩进突变表明已进入标题/正文,表注链必须立即终止。break@@ -1076,6 +1124,132 @@ def _collect_footnote_rows(return output+def _extract_auxiliary_table_note_marker(text: str) -> str | None:+ """提取行首一至三个通用 Unicode 标记,不解释任何具体标记含义。"""++ match = _AUXILIARY_TABLE_NOTE_RE.match(str(text or ""))+ if match is None:+ return None+ marker = unicodedata.normalize("NFKC", match.group("marker")).casefold()+ if not marker or not all(unicodedata.category(char)[0] in {"L", "N", "S"} for char in marker):+ return None+ return marker+++def _table_core_references_marker(+ marker: str,+ core_lines: list[_LineItem],+ page_size: tuple[float, float],+ angle: int,+) -> bool:+ """要求通用短标记在表格核心中具有上标或紧凑单元格引用。"""++ return any(+ _line_has_superscript_marker(line, marker, page_size, angle)+ or _line_has_compact_marker_token(line.text, marker)+ for line in core_lines+ )+++def _line_has_compact_marker_token(text: str, marker: str) -> bool:+ """仅在短小单元格文本中确认独立标记 token,避免普通句子偶然命中。"""++ normalized_text = unicodedata.normalize("NFKC", str(text or "")).casefold()+ if sum(not char.isspace() for char in normalized_text) > 12:+ return False+ tokens: list[str] = []+ current: list[str] = []+ for char in normalized_text:+ if unicodedata.category(char)[0] in {"L", "N", "S"}:+ current.append(char)+ elif current:+ tokens.append("".join(current))+ current = []+ if current:+ tokens.append("".join(current))+ return len(tokens) <= 4 and marker in tokens+++def _line_has_superscript_marker(+ line: _LineItem,+ marker: str,+ page_size: tuple[float, float],+ angle: int,+) -> bool:+ """在正向局部坐标中检查标记字形是否同时更小并明显上移。"""++ glyphs: list[tuple[str, BBox]] = []+ for char in line.chars:+ raw_char = str(char.get("char") or "")+ if not raw_char.isprintable() or raw_char.isspace():+ continue+ bbox = _coerce_bbox(char.get("bbox"))+ if bbox is None:+ continue+ local_bbox = _rotate_bbox_to_upright(bbox, page_size, angle)+ glyphs.append((unicodedata.normalize("NFKC", raw_char).casefold(), local_bbox))+ if len(glyphs) < 2:+ return False++ for start_index in range(len(glyphs)):+ combined = ""+ for end_index in range(start_index, len(glyphs)):+ combined += glyphs[end_index][0]+ if not marker.startswith(combined):+ break+ if combined != marker:+ continue+ marker_indices = set(range(start_index, end_index + 1))+ ordinary_bboxes = [bbox for index, (_char, bbox) in enumerate(glyphs) if index not in marker_indices]+ if not ordinary_bboxes:+ continue+ normal_height = statistics.median(bbox[3] - bbox[1] for bbox in ordinary_bboxes)+ if normal_height <= 0:+ continue+ baseline_bboxes = [+ bbox+ for bbox in ordinary_bboxes+ if bbox[3] - bbox[1] >= 0.90 * normal_height+ ]+ marker_bboxes = [glyphs[index][1] for index in marker_indices]+ marker_height = statistics.median(bbox[3] - bbox[1] for bbox in marker_bboxes)+ marker_center = statistics.median(_bbox_center_y(bbox) for bbox in marker_bboxes)+ normal_center = statistics.median(_bbox_center_y(bbox) for bbox in baseline_bboxes)+ if (+ marker_height <= 0.85 * normal_height+ and normal_center - marker_center >= 0.12 * normal_height+ ):+ return True+ return False+++def _table_note_body_reference_height(+ lines: list[_LineItem],+ rule_bbox: BBox,+ median_height: float,+ core_line_indices: set[int],+ page_size: tuple[float, float],+ angle: int,+) -> float:+ """以同方向非表格行的最高四分位估计正文高度,样本不足时稳健回退。"""++ exclusion_top = rule_bbox[1] - 3.0 * median_height+ exclusion_bottom = rule_bbox[3] + 10.0 * median_height+ heights: list[float] = []+ for line in lines:+ if line.angle != angle or line.source_index in core_line_indices:+ continue+ local_bbox = _rotate_bbox_to_upright(line.bbox, page_size, angle)+ if exclusion_top <= _bbox_center_y(local_bbox) <= exclusion_bottom:+ continue+ heights.append(_line_effective_height(line, local_bbox))+ if len(heights) < 4:+ return 1.25 * median_height+ heights.sort()+ upper_quartile_count = max(1, (len(heights) + 3) // 4)+ return statistics.median(heights[-upper_quartile_count:])++def _visual_row_text(row: _VisualRow) -> str:"""按局部 x 顺序拼接视觉行文本,供拆分脚注标记判断。"""diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.pyindex ddaede4e..1a8d79c9 100644--- a/tests/unittest/test_flash_pdf_samples.py+++ b/tests/unittest/test_flash_pdf_samples.py@@ -85,6 +85,13 @@ def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:assert sum(block["type"] == "header" for page in model_list for block in page) == 12assert sum(block["type"] == "page_number" for page in model_list for block in page) == 12assert sum(block["type"] == "equation" for page in model_list for block in page) == 7+ assert [block["bbox"] for block in model_list[5] if block["type"] == "table"] == [+ [0.087, 0.125, 0.922, 0.363],+ [0.087, 0.669, 0.922, 0.893],+ ]+ assert [block["bbox"] for block in model_list[8] if block["type"] == "table"] == [+ [0.078, 0.125, 0.913, 0.416]+ ]page1_footnotes = [block for block in model_list[0] if block["type"] == "page_footnote"]assert len(page1_footnotes) == 1assert page1_footnotes[0]["content"].startswith("* Corresponding author.")@@ -296,6 +303,8 @@ def test_demo2_table_captions_and_numeric_footnotes_are_not_text_blocks() -> Nonassert "the avgerage % of bad pixels." in page5_table["content"]assert "ral stereo matching." not in residual_textassert "Millions of Disparity Estimates per Second." not in residual_text+ assert page4_table["bbox"] == [0.51, 0.484, 0.915, 0.675]+ assert page5_table["bbox"] == [0.51, 0.218, 0.915, 0.438]def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:@@ -679,4 +688,3 @@ def test_demo3_pages4_and5_fix_lists_formula_titles_italics_and_footnotes() -> Nassert final_bullet["type"] == "text"assert final_footnote["type"] == "page_footnote"assert "3By perturbation" not in final_bullet["content"]-diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.pyindex ce27da2a..8a03b3ad 100644--- a/tests/unittest/test_flash_pdf_tables.py+++ b/tests/unittest/test_flash_pdf_tables.py@@ -585,6 +585,360 @@ def test_split_table_footnote_marker_is_joined_before_matching() -> None:assert not tables._is_table_note_text("1 Numeric table footnote")+def _table_note_reference_fixture(+ marker: str,+ reference_mode: str,+ *,+ angle: int = 0,+ note_height: float = 8.0,+) -> tuple[+ list[models._VisualRow],+ list[models._LineItem],+ tuple[float, float, float, float],+ set[int],+ tuple[float, float],+]:+ """构造含中性表内引用、表注首行和正文高度样本的局部坐标夹具。"""++ page_size = (200.0, 200.0)+ rule_bbox = (0.0, 20.0, 100.0, 50.0)+ core_local_bbox = (10.0, 25.0, 70.0, 35.0)+ core_chars: list[dict[str, object]] = []+ if reference_mode == "superscript":+ core_text = f"cell{marker}"+ x_position = 10.0+ for raw_char in "cell":+ local_bbox = (x_position, 25.0, x_position + 7.0, 35.0)+ core_chars.append(+ {+ "char": raw_char,+ "bbox": geometry._rotate_bbox_from_upright(local_bbox, page_size, angle),+ }+ )+ x_position += 8.0+ for raw_char in marker:+ local_bbox = (x_position, 22.0, x_position + 5.0, 28.0)+ core_chars.append(+ {+ "char": raw_char,+ "bbox": geometry._rotate_bbox_from_upright(local_bbox, page_size, angle),+ }+ )+ x_position += 5.5+ elif reference_mode == "compact":+ core_text = marker+ else:+ core_text = "neutral value"++ core_line = models._LineItem(+ text=core_text,+ bbox=geometry._rotate_bbox_from_upright(core_local_bbox, page_size, angle),+ angle=angle,+ source_index=0,+ chars=core_chars, # type: ignore[arg-type]+ effective_height=10.0,+ font_signature=("Table", 0),+ font_coverage=1.0,+ )+ note_local_bbox = (0.0, 51.0, 80.0, 51.0 + note_height)+ note_line = models._LineItem(+ text=f"{marker} neutral explanation",+ bbox=geometry._rotate_bbox_from_upright(note_local_bbox, page_size, angle),+ angle=angle,+ source_index=1,+ effective_height=note_height,+ font_signature=("Note", 0),+ font_coverage=1.0,+ )+ body_lines = [+ models._LineItem(+ text=f"body-{source_index}",+ bbox=geometry._rotate_bbox_from_upright(+ (110.0, top, 190.0, top + 10.0),+ page_size,+ angle,+ ),+ angle=angle,+ source_index=source_index,+ effective_height=10.0,+ font_signature=("Body", 0),+ font_coverage=1.0,+ )+ for source_index, top in enumerate((140.0, 152.0, 164.0, 176.0), start=2)+ ]+ rows = [+ models._VisualRow(+ fragments=[models._Fragment(core_text, core_local_bbox, core_local_bbox, 0, 0)],+ center_y=geometry._bbox_center_y(core_local_bbox),+ bbox=core_local_bbox,+ visual_row_id=0,+ ),+ models._VisualRow(+ fragments=[models._Fragment(note_line.text, note_local_bbox, note_local_bbox, 1, 1)],+ center_y=geometry._bbox_center_y(note_local_bbox),+ bbox=note_local_bbox,+ visual_row_id=1,+ ),+ ]+ return rows, [core_line, note_line, *body_lines], rule_bbox, {0}, page_size+++ ("text", "expected"),+ (("7 neutral", "7"), ("(q) neutral", "q"), ("xy: neutral", "xy")),+)+def test_auxiliary_table_note_marker_is_unicode_generic(text: str, expected: str) -> None:+ """验证辅助标记仅受通用 Unicode 形态约束,具体字符变化不影响提取。"""++ assert tables._extract_auxiliary_table_note_marker(text) == expected+++ ("marker", "reference_mode"),+ (("7", "superscript"), ("q", "compact"), ("xy", "compact")),+)+def test_auxiliary_table_note_requires_neutral_core_reference(+ marker: str,+ reference_mode: str,+) -> None:+ """验证中性标记经上标或紧凑单元格确认后可以启动表注链。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ marker,+ reference_mode,+ )++ selected = tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 0,+ )++ assert [tables._visual_row_text(row) for row in selected] == [+ f"{marker} neutral explanation"+ ]+++def test_auxiliary_table_note_rejects_marker_without_core_reference() -> None:+ """验证紧邻表格的短标记正文在缺少表内引用时不能启动表注链。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ "7",+ "none",+ )++ assert tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 0,+ ) == []+++def test_superscript_reference_requires_smaller_raised_glyph() -> None:+ """验证普通基线上的同字符不能被当成表内上标引用。"""++ _rows, lines, _rule_bbox, _core_indices, page_size = _table_note_reference_fixture(+ "7",+ "superscript",+ )+ core_line = lines[0]+ for char in core_line.chars:+ if str(char.get("char")) == "7":+ char["bbox"] = (42.0, 25.0, 49.0, 35.0)++ assert not tables._line_has_superscript_marker(core_line, "7", page_size, 0)++[email protected]("note_height", [10.0, 14.0])+def test_auxiliary_table_note_rejects_body_or_title_sized_first_row(+ note_height: float,+) -> None:+ """验证具有表内引用的普通正文或标题字号行仍不能启动表注链。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ "q",+ "compact",+ note_height=note_height,+ )++ assert tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 0,+ ) == []+++def test_auxiliary_table_note_rejects_loose_first_gap() -> None:+ """验证辅助标记首行距超过四分之三局部行高时立即停止扩张。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ "q",+ "compact",+ )+ late_bbox = (0.0, 57.0, 80.0, 65.0)+ lines[1].bbox = late_bbox+ rows[1] = models._VisualRow(+ fragments=[models._Fragment(lines[1].text, late_bbox, late_bbox, 1, 1)],+ center_y=geometry._bbox_center_y(late_bbox),+ bbox=late_bbox,+ visual_row_id=1,+ )++ assert tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 0,+ ) == []+++def test_auxiliary_table_note_requires_smaller_than_body_reference() -> None:+ """验证辅助标记首行还必须显著小于同方向正文参考高度。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ "q",+ "compact",+ )+ for line in lines[2:]:+ line.effective_height = 8.5++ assert tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 0,+ ) == []+++def test_auxiliary_table_note_uses_clipped_corridor_projection() -> None:+ """验证另一栏短标记不能借表格栏内片段制造虚假的整行投影证据。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ "q",+ "compact",+ )+ outside_bbox = (140.0, 51.0, 190.0, 59.0)+ inside_bbox = (10.0, 51.0, 70.0, 59.0)+ rows[1] = models._VisualRow(+ fragments=[+ models._Fragment("q outside", outside_bbox, outside_bbox, 1, 1),+ models._Fragment("inside continuation", inside_bbox, inside_bbox, 6, 1),+ ],+ center_y=55.0,+ bbox=geometry._bbox_union(outside_bbox, inside_bbox),+ visual_row_id=1,+ )+ lines.append(+ models._LineItem(+ text="inside continuation",+ bbox=inside_bbox,+ angle=0,+ source_index=6,+ effective_height=8.0,+ font_signature=("Note", 0),+ font_coverage=1.0,+ )+ )++ assert tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 0,+ ) == []+++def test_rotated_auxiliary_table_note_uses_local_superscript_geometry() -> None:+ """验证旋转表格先转入局部正向坐标后仍可确认上标引用。"""++ rows, lines, rule_bbox, core_indices, page_size = _table_note_reference_fixture(+ "7",+ "superscript",+ angle=90,+ )++ selected = tables._collect_footnote_rows(+ rows,+ lines,+ rule_bbox,+ 8.0,+ core_indices,+ page_size,+ 90,+ )++ assert [tables._visual_row_text(row) for row in selected] == [+ "7 neutral explanation"+ ]+++def test_table_note_chain_cannot_expand_beyond_ten_line_heights() -> None:+ """验证表注续行链即使字体和行距稳定也不能无限向页面底部扩张。"""++ lines: list[models._LineItem] = []+ rows: list[models._VisualRow] = []+ specs = [("Note: neutral", (0.0, 51.0, 80.0, 59.0))]+ specs.extend(+ (f"continuation-{index}", (0.0, 59.5 + 8.5 * index, 80.0, 67.5 + 8.5 * index))+ for index in range(12)+ )+ for source_index, (text, bbox) in enumerate(specs):+ lines.append(+ models._LineItem(+ text=text,+ bbox=bbox,+ angle=0,+ source_index=source_index,+ effective_height=8.0,+ font_signature=("Note", 0),+ font_coverage=1.0,+ )+ )+ rows.append(+ models._VisualRow(+ fragments=[models._Fragment(text, bbox, bbox, source_index, source_index)],+ center_y=geometry._bbox_center_y(bbox),+ bbox=bbox,+ visual_row_id=source_index,+ )+ )++ selected = tables._collect_footnote_rows(+ rows,+ lines,+ (0.0, 0.0, 100.0, 50.0),+ 8.0,+ set(),+ (200.0, 200.0),+ 0,+ )++ assert selected+ assert len(selected) < len(rows)+ assert selected[-1].bbox[3] <= 130.0++def test_table_note_chain_stops_at_font_and_size_transition() -> None:"""验证表注续行不能跨越字体字号突变的标题或后续正文。"""@@ -630,6 +984,8 @@ def test_table_note_chain_stops_at_font_and_size_transition() -> None:(0.0, 0.0, 100.0, 50.0),10.0,set(),+ (100.0, 100.0),+ 0,)assert [tables._visual_row_text(row) for row in selected] == [@@ -664,6 +1020,8 @@ def test_numeric_body_row_cannot_start_table_note_chain() -> None:(0.0, 0.0, 100.0, 50.0),10.0,set(),+ (100.0, 100.0),+ 0,) == []