Skip to content

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

feat: enhance table annotation handling by implementing structured annotation records and refining materialization logic

myhloli51d4c645414b
diff --git a/mineru/backend/flash/native_pdf/models.py b/mineru/backend/flash/native_pdf/models.py
index 435abcb7..dab80037 100644
--- a/mineru/backend/flash/native_pdf/models.py
+++ b/mineru/backend/flash/native_pdf/models.py
@@ -77,6 +77,16 @@ class _LocalAxisLine:
width: float
+@dataclass(slots=True)
+class _TableAnnotation:
+ """保存表格候选中已识别注释的类型、紧致边界和原始行身份。"""
+
+ kind: Literal["caption", "footnote"]
+ bbox: BBox
+ line_indices: set[int] = field(default_factory=set)
+ line_bboxes: dict[int, BBox] = field(default_factory=dict)
+
+
@dataclass(slots=True)
class _TableCandidate:
"""保存已通过相邻横线边界与文本分布校验的表格候选。"""
@@ -87,6 +97,7 @@ class _TableCandidate:
score: float
core_bbox: BBox | None = None
line_indices: set[int] = field(default_factory=set)
+ annotations: list[_TableAnnotation] = field(default_factory=list)
@dataclass(slots=True)
diff --git a/mineru/backend/flash/native_pdf/pipeline.py b/mineru/backend/flash/native_pdf/pipeline.py
index 4dd68f79..48e347a0 100644
--- a/mineru/backend/flash/native_pdf/pipeline.py
+++ b/mineru/backend/flash/native_pdf/pipeline.py
@@ -291,9 +291,11 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
]
# 候选检测仍避开预分类边缘文本;已确认表格物化时回到原始行,
# 让 core_bbox 内的误标页脚可被重新认领,表格外边缘文本不会被矩形扩张带入。
- table_blocks, claimed_line_indices = _materialize_table_blocks(
- source,
- candidates,
+ table_blocks, table_annotation_blocks, claimed_line_indices = (
+ _materialize_table_blocks(
+ source,
+ candidates,
+ )
)
claimed_line_indices.update(claimed_rule_code_line_indices)
table_bboxes = [block["bbox"] for block in table_blocks]
@@ -408,6 +410,7 @@ def _prepare_page_source(source: _PageSource) -> _PreparedPage:
drawing_lines=source.drawing_lines,
fixed_blocks=(
rule_code_blocks
+ + table_annotation_blocks
+ table_blocks
+ code_blocks
+ form_image_blocks
diff --git a/mineru/backend/flash/native_pdf/tables.py b/mineru/backend/flash/native_pdf/tables.py
index 4e509e34..df5e6870 100644
--- a/mineru/backend/flash/native_pdf/tables.py
+++ b/mineru/backend/flash/native_pdf/tables.py
@@ -7,19 +7,22 @@ from __future__ import annotations
import re
import statistics
import unicodedata
-from typing import Any
+from typing import Any, Literal
from loguru import logger
+from mineru.backend.utils.char_utils import resolve_text_line_boundary
from mineru.backend.hybrid.table_text import project_pdf_table_text
from mineru.types import BBox
from mineru.utils.pdf_document import PDFPathInfo
+from mineru.utils.language import detect_lang
from .models import (
_Fragment,
_LineItem,
_LocalAxisLine,
_PageSource,
+ _TableAnnotation,
_TableCandidate,
_VisualRow,
)
@@ -40,6 +43,7 @@ from .geometry import (
)
from .line_layout import _line_effective_height
from .line_merging import _same_baseline_geometry
+from .native_text import _normalize_native_run_text
_TABLE_CAPTION_RE = re.compile(
@@ -705,6 +709,8 @@ def _expand_candidates_to_connected_rule_grids(
expanded_core_bbox,
)
)
+ for annotation in candidate.annotations:
+ candidate.line_indices.difference_update(annotation.line_indices)
return candidates
@@ -1416,7 +1422,7 @@ def _expand_rule_table_candidate(
median_height: float,
caption_line: _LineItem | None,
) -> _TableCandidate:
- """合并横线核心、上方标题和下方脚注,构造统一投影候选。"""
+ """合并横线核心与上下注释,并保留注释的独立行身份。"""
rule_bbox = _bbox_union_many([line.bbox for line in rule_group])
core_line_indices = {fragment.line_index for row in core_rows for fragment in row.fragments}
@@ -1430,8 +1436,27 @@ def _expand_rule_table_candidate(
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]))
+ caption_annotation = _build_table_annotation(
+ "caption",
+ caption_rows,
+ excluded_line_indices=core_line_indices,
+ excluded_local_bbox=core_local_bbox,
+ )
+ footnote_annotation = _build_table_annotation(
+ "footnote",
+ footnote_rows,
+ excluded_line_indices=core_line_indices,
+ )
+ annotations = [
+ annotation
+ for annotation in (caption_annotation, footnote_annotation)
+ if annotation is not None
+ ]
+ annotation_line_indices = set().union(
+ *(annotation.line_indices for annotation in annotations),
+ ) if annotations else set()
+ included_rows = [*caption_rows, *core_rows, *footnote_rows]
local_bbox = _bbox_union(core_local_bbox, _bbox_union_many([row.bbox for row in included_rows]))
return _TableCandidate(
bbox=_rotate_bbox_from_upright(local_bbox, page_size, angle),
@@ -1439,7 +1464,53 @@ def _expand_rule_table_candidate(
angle=angle,
score=0.0,
core_bbox=_rotate_bbox_from_upright(core_local_bbox, page_size, angle),
- line_indices={fragment.line_index for row in included_rows for fragment in row.fragments},
+ # 表体成员与注释成员保持互斥;物化失败时会显式把无效注释放回表体投影。
+ line_indices=core_line_indices - annotation_line_indices,
+ annotations=annotations,
+ )
+
+
+def _build_table_annotation(
+ kind: Literal["caption", "footnote"],
+ rows: list[_VisualRow],
+ *,
+ excluded_line_indices: set[int] | None = None,
+ excluded_local_bbox: BBox | None = None,
+) -> _TableAnnotation | None:
+ """把已确认视觉行压缩成一个带精确来源行集合的表格注释记录。"""
+
+ excluded_line_indices = excluded_line_indices or set()
+ fragments = [
+ fragment
+ for row in rows
+ for fragment in row.fragments
+ if fragment.line_index not in excluded_line_indices
+ and not (
+ excluded_local_bbox is not None
+ and fragment.local_bbox[3] > excluded_local_bbox[1]
+ and _bbox_axis_overlap_ratio(
+ fragment.local_bbox,
+ excluded_local_bbox,
+ axis="x",
+ )
+ >= 0.05
+ )
+ ]
+ if not fragments:
+ return None
+ line_bboxes: dict[int, BBox] = {}
+ for fragment in fragments:
+ existing_bbox = line_bboxes.get(fragment.line_index)
+ line_bboxes[fragment.line_index] = (
+ fragment.bbox
+ if existing_bbox is None
+ else _bbox_union(existing_bbox, fragment.bbox)
+ )
+ return _TableAnnotation(
+ kind=kind,
+ bbox=_bbox_union_many(list(line_bboxes.values())),
+ line_indices=set(line_bboxes),
+ line_bboxes=line_bboxes,
)
@@ -1874,50 +1945,249 @@ def _merge_table_candidates(candidates: list[_TableCandidate]) -> list[_TableCan
elif candidate.core_bbox is not None:
target.core_bbox = _bbox_union(target.core_bbox, candidate.core_bbox)
target.line_indices.update(candidate.line_indices)
+ _merge_table_candidate_annotations(target, candidate)
target.score = max(target.score, candidate.score)
return sorted(merged, key=lambda item: (item.bbox[1], item.bbox[0]))
+def _merge_table_candidate_annotations(
+ target: _TableCandidate,
+ candidate: _TableCandidate,
+) -> None:
+ """按类型合并重复候选注释,并以表体优先消解来源行角色冲突。"""
+
+ for annotation in candidate.annotations:
+ existing = next(
+ (
+ item
+ for item in target.annotations
+ if item.kind == annotation.kind
+ ),
+ None,
+ )
+ if existing is None:
+ target.annotations.append(
+ _TableAnnotation(
+ kind=annotation.kind,
+ bbox=annotation.bbox,
+ line_indices=set(annotation.line_indices),
+ line_bboxes=dict(annotation.line_bboxes),
+ )
+ )
+ continue
+ existing.bbox = _bbox_union(existing.bbox, annotation.bbox)
+ existing.line_indices.update(annotation.line_indices)
+ for line_index, bbox in annotation.line_bboxes.items():
+ existing_bbox = existing.line_bboxes.get(line_index)
+ existing.line_bboxes[line_index] = (
+ bbox
+ if existing_bbox is None
+ else _bbox_union(existing_bbox, bbox)
+ )
+
+ # 重复候选发生角色冲突时以任一候选确认的表体成员为准,避免表头被并入 caption。
+ retained_annotations: list[_TableAnnotation] = []
+ for annotation in target.annotations:
+ annotation.line_indices.difference_update(target.line_indices)
+ annotation.line_bboxes = {
+ line_index: bbox
+ for line_index, bbox in annotation.line_bboxes.items()
+ if line_index in annotation.line_indices
+ }
+ if not annotation.line_indices:
+ continue
+ if annotation.line_bboxes:
+ annotation.bbox = _bbox_union_many(
+ list(annotation.line_bboxes.values()),
+ )
+ retained_annotations.append(annotation)
+ target.annotations = retained_annotations
+
+
def _materialize_table_blocks(
source: _PageSource,
candidates: list[_TableCandidate],
-) -> tuple[list[dict[str, Any]], set[int]]:
- """为候选生成空间投影 content,仅认领投影成功的文本行。"""
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[int]]:
+ """原子物化表体及其独立注释,仅认领整组成功输出的文本行。"""
- blocks: list[dict[str, Any]] = []
+ table_blocks: list[dict[str, Any]] = []
+ annotation_blocks: list[dict[str, Any]] = []
+ accepted_candidate_bboxes: list[BBox] = []
claimed: set[int] = set()
for candidate in sorted(candidates, key=lambda item: item.score, reverse=True):
- if any(_bbox_overlap_in_smaller(candidate.bbox, block["bbox"]) >= 0.5 for block in blocks):
+ # 候选去重仍使用包含注释的完整框,不能因输出表体收缩而放行重复表格。
+ if any(
+ _bbox_overlap_in_smaller(candidate.bbox, bbox) >= 0.5
+ for bbox in accepted_candidate_bboxes
+ ):
continue
output_angle = candidate.angle
+ candidate_annotation_blocks, externalized_line_indices, failed_annotations = (
+ _materialize_table_annotations(source, candidate)
+ )
projection_line_indices = _candidate_projection_line_indices(source, candidate)
+ for annotation in candidate.annotations:
+ projection_line_indices.update(annotation.line_indices)
+ projection_line_indices.difference_update(externalized_line_indices)
+ body_bbox = _table_body_materialization_bbox(
+ candidate,
+ failed_annotations,
+ )
try:
candidate_chars = [
char for line in source.lines if line.source_index in projection_line_indices for char in line.chars
]
content = project_pdf_table_text(
candidate_chars,
- candidate.bbox,
+ body_bbox,
angle=candidate.angle,
)
except Exception as exc:
- # 单个表格的字符投影异常只撤销该候选,不能中止整页提取。
+ # 表体投影异常时同时撤销预构造注释,保持整组不输出、不认领。
logger.warning(f"Flash table projection failed and rolled back: bbox={candidate.bbox}, error={exc}")
continue
if not content or not content.strip():
continue
- blocks.append(
+ table_blocks.append(
{
"type": "table",
- "bbox": candidate.bbox,
+ "bbox": body_bbox,
"angle": output_angle,
"content": content,
}
)
- # 只认领候选明确接纳的视觉行,避免远标题与表格之间的正文被矩形 bbox 连带删除。
- claimed.update(projection_line_indices)
- blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))
- return blocks, claimed
+ annotation_blocks.extend(candidate_annotation_blocks)
+ accepted_candidate_bboxes.append(candidate.bbox)
+ # 表体和成功外置的注释行在同一事务中各认领一次。
+ claimed.update(projection_line_indices | externalized_line_indices)
+ table_blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))
+ annotation_blocks.sort(key=lambda block: (block["bbox"][1], block["bbox"][0]))
+ return table_blocks, annotation_blocks, claimed
+
+
+def _materialize_table_annotations(
+ source: _PageSource,
+ candidate: _TableCandidate,
+) -> tuple[list[dict[str, Any]], set[int], list[_TableAnnotation]]:
+ """构造候选注释块,并返回成功外置行与需回退到表体的注释记录。"""
+
+ blocks: list[dict[str, Any]] = []
+ externalized_line_indices: set[int] = set()
+ failed_annotations: list[_TableAnnotation] = []
+ annotations = sorted(
+ candidate.annotations,
+ key=lambda annotation: (
+ _rotate_bbox_to_upright(
+ annotation.bbox,
+ source.page_size,
+ candidate.angle,
+ )[1],
+ _rotate_bbox_to_upright(
+ annotation.bbox,
+ source.page_size,
+ candidate.angle,
+ )[0],
+ annotation.kind,
+ ),
+ )
+ for annotation in annotations:
+ block = _build_table_annotation_block(
+ source,
+ candidate,
+ annotation,
+ )
+ if block is None:
+ failed_annotations.append(annotation)
+ continue
+ blocks.append(block)
+ externalized_line_indices.update(annotation.line_indices)
+ return blocks, externalized_line_indices, failed_annotations
+
+
+def _build_table_annotation_block(
+ source: _PageSource,
+ candidate: _TableCandidate,
+ annotation: _TableAnnotation,
+) -> dict[str, Any] | None:
+ """按父表格局部方向整理原生行,并生成保留排版元数据的独立注释块。"""
+
+ line_geometry = [
+ (
+ line,
+ _rotate_bbox_to_upright(
+ line.bbox,
+ source.page_size,
+ candidate.angle,
+ ),
+ )
+ for line in source.lines
+ if line.source_index in annotation.line_indices
+ ]
+ # 原生来源顺序可抵抗旋转文字同一基线上的字形顶边抖动。
+ line_geometry.sort(key=lambda item: item[0].source_index)
+ content = _merge_table_annotation_content(
+ [line.text for line, _local_bbox in line_geometry],
+ )
+ if not line_geometry or not content:
+ return None
+ return {
+ "type": annotation.kind,
+ "bbox": annotation.bbox,
+ "angle": candidate.angle,
+ "content": content,
+ "_local_line_bboxes": [bbox for _line, bbox in line_geometry],
+ "_line_heights": [
+ _line_effective_height(line, bbox)
+ for line, bbox in line_geometry
+ ],
+ "_font_signatures": {
+ line.font_signature
+ for line, _bbox in line_geometry
+ if line.font_signature is not None and line.font_coverage >= 0.5
+ },
+ # 已由表格检测器给出完整边界,禁止通用表注规则继续向下扩张。
+ "_table_annotation_complete": True,
+ }
+
+
+def _merge_table_annotation_content(line_texts: list[str]) -> str:
+ """按正文一致的语言与行末断词规则折叠表格注释原生行。"""
+
+ normalized_lines = [
+ normalized
+ for text in line_texts
+ if (normalized := _normalize_native_run_text(str(text or "")))
+ ]
+ if not normalized_lines:
+ return ""
+ try:
+ block_language = detect_lang("".join(normalized_lines))
+ except Exception:
+ block_language = ""
+ content_parts = [normalized_lines[0]]
+ for current_line in normalized_lines[1:]:
+ processed_previous, separator = resolve_text_line_boundary(
+ content_parts[-1],
+ block_language=block_language,
+ next_starts_with_lowercase=current_line[0].islower(),
+ )
+ content_parts[-1] = processed_previous
+ content_parts.extend([separator, current_line])
+ return "".join(content_parts).strip()
+
+
+def _table_body_materialization_bbox(
+ candidate: _TableCandidate,
+ failed_annotations: list[_TableAnnotation],
+) -> BBox:
+ """返回排除有效注释后的表体框,并把无效注释边界保守并回表体。"""
+
+ if not candidate.annotations or len(failed_annotations) == len(candidate.annotations):
+ return candidate.bbox
+ body_bbox = candidate.core_bbox or candidate.bbox
+ for annotation in failed_annotations:
+ body_bbox = _bbox_union(body_bbox, annotation.bbox)
+ return body_bbox
def _candidate_projection_line_indices(
diff --git a/mineru/backend/flash/native_pdf/visual_annotations.py b/mineru/backend/flash/native_pdf/visual_annotations.py
index 19717e35..631db17b 100644
--- a/mineru/backend/flash/native_pdf/visual_annotations.py
+++ b/mineru/backend/flash/native_pdf/visual_annotations.py
@@ -184,13 +184,13 @@ def _block_median_line_height(
def _collect_annotation_candidates(
blocks: list[dict[str, Any]],
) -> dict[int, _AnnotationKind]:
- """仅从独立 text 和已有 footnote 中收集可参与视觉绑定的注释候选。"""
+ """从独立 text 及预分类 caption/footnote 中收集视觉绑定候选。"""
output: dict[int, _AnnotationKind] = {}
for index, block in enumerate(blocks):
block_type = block.get("type")
- if block_type == "footnote":
- output[index] = "footnote"
+ if block_type in {"caption", "footnote"}:
+ output[index] = block_type
continue
if block_type != "text" or not isinstance(block.get("content"), str):
continue
@@ -445,6 +445,7 @@ def _merge_table_footnote_continuations(
anchor = blocks[anchor_index]
if (
candidates.get(anchor_index) != "footnote"
+ or anchor.get("_table_annotation_complete") is True
or anchor.get("type") != "text"
or not isinstance(anchor.get("content"), str)
or not _is_strong_footnote_text(str(anchor["content"]))
diff --git a/tests/unittest/test_flash_pdf_pipeline.py b/tests/unittest/test_flash_pdf_pipeline.py
index 79305ff9..4b3d5457 100644
--- a/tests/unittest/test_flash_pdf_pipeline.py
+++ b/tests/unittest/test_flash_pdf_pipeline.py
@@ -73,14 +73,14 @@ def test_prepare_page_materializes_table_against_original_semantic_lines(
def fake_materialize(
materialization_source: models._PageSource,
candidates: list[models._TableCandidate],
- ) -> tuple[list[dict[str, object]], set[int]]:
+ ) -> tuple[list[dict[str, object]], list[dict[str, object]], set[int]]:
"""记录表格物化阶段可见的来源行。"""
assert candidates == []
observed["materialize"] = [
line.source_index for line in materialization_source.lines
]
- return [], set()
+ return [], [], set()
monkeypatch.setattr(pipeline, "_detect_table_candidates", fake_detect)
monkeypatch.setattr(pipeline, "_materialize_table_blocks", fake_materialize)
@@ -88,6 +88,52 @@ def test_prepare_page_materializes_table_against_original_semantic_lines(
pipeline._prepare_page_source(source)
assert observed == {"detect": [0], "materialize": [0, 1]}
+
+
+def test_prepare_page_uses_only_table_body_bbox_and_keeps_annotations_fixed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 Pipeline 仅用表体框作容器屏障,同时把预分类注释送入固定块。"""
+
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=[],
+ chars=[],
+ drawing_lines=[],
+ )
+ table_block = {
+ "type": "table",
+ "bbox": (10.0, 30.0, 90.0, 70.0),
+ "angle": 0,
+ "content": "body",
+ }
+ caption_block = {
+ "type": "caption",
+ "bbox": (10.0, 10.0, 50.0, 20.0),
+ "angle": 0,
+ "content": "Table 1",
+ }
+
+ monkeypatch.setattr(
+ pipeline,
+ "_detect_table_candidates",
+ lambda *_args, **_kwargs: [],
+ )
+ monkeypatch.setattr(
+ pipeline,
+ "_materialize_table_blocks",
+ lambda *_args, **_kwargs: ([table_block], [caption_block], set()),
+ )
+
+ prepared = pipeline._prepare_page_source(source)
+
+ assert prepared.table_bboxes == [table_block["bbox"]]
+ assert [block["type"] for block in prepared.fixed_blocks] == [
+ "caption",
+ "table",
+ ]
+
+
def test_repeated_large_image_requires_three_distinct_pages() -> None:
"""验证同页重复只计一次,面积恰好 8% 且跨三页时才命中水印。"""
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index ea8ab073..41364505 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from collections import Counter
from pathlib import Path
from typing import Any
@@ -97,12 +98,54 @@ def _blocks_containing(
]
+def test_all_demo_pdfs_keep_expected_txt_block_inventory() -> None:
+ """验证 15 份 demo PDF 在显式 TXT 模式下仅新增既定表格注释块。"""
+
+ pdf_names = sorted(
+ path.name
+ for path in (Path(__file__).parents[2] / "demo" / "pdfs").glob("*.pdf")
+ )
+ inventory: Counter[str] = Counter()
+ page_count = 0
+ for pdf_name in pdf_names:
+ model_list = _txt_model_list(pdf_name)
+ page_count += len(model_list)
+ inventory.update(
+ block["type"]
+ for page in model_list
+ for block in page
+ )
+
+ assert len(pdf_names) == 15
+ assert page_count == 218
+ assert sum(inventory.values()) == 2591
+ assert inventory == Counter(
+ {
+ "text": 901,
+ "image": 530,
+ "paragraph_title": 214,
+ "header": 180,
+ "page_number": 179,
+ "footer": 176,
+ "table": 135,
+ "caption": 120,
+ "equation": 50,
+ "footnote": 39,
+ "code": 33,
+ "page_footnote": 21,
+ "doc_title": 10,
+ "index": 2,
+ "aside_text": 1,
+ }
+ )
+
+
def test_demo1_keeps_five_real_tables_without_formula_false_positive() -> None:
"""验证 demo1 首页脚注、参考文献、公式与五个真实表格均保持正确。"""
model_list = _native_model_list("demo1.pdf")
- assert [len(page) for page in model_list] == [16, 9, 12, 18, 10, 9, 11, 8, 10, 7, 10, 26, 9]
+ assert [len(page) for page in model_list] == [16, 9, 12, 18, 12, 13, 11, 10, 12, 7, 10, 26, 9]
assert [sum(block["type"] == "table" for block in page) for page in model_list] == [
0,
0,
@@ -122,13 +165,41 @@ 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) == 12
assert sum(block["type"] == "page_number" for page in model_list for block in page) == 12
assert sum(block["type"] == "equation" for page in model_list for block in page) == 7
- assert sum(block["type"] == "caption" for page in model_list for block in page) == 5
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 10
+ assert sum(block["type"] == "footnote" for page in model_list for block in page) == 5
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],
+ [0.087, 0.153, 0.922, 0.333],
+ [0.087, 0.697, 0.922, 0.876],
]
assert [block["bbox"] for block in model_list[8] if block["type"] == "table"] == [
- [0.078, 0.125, 0.913, 0.416]
+ [0.078, 0.167, 0.913, 0.333]
+ ]
+ page5_visual_blocks = [
+ block
+ for block in model_list[4]
+ if block["type"] in {"caption", "table", "footnote"}
+ ]
+ assert [block["type"] for block in page5_visual_blocks] == [
+ "caption",
+ "table",
+ "footnote",
+ ]
+ assert [block["bbox"] for block in page5_visual_blocks] == [
+ [0.078, 0.729, 0.107, 0.891],
+ [0.117, 0.125, 0.431, 0.891],
+ [0.44, 0.435, 0.452, 0.891],
+ ]
+ assert [block["angle"] for block in page5_visual_blocks] == [270, 270, 270]
+ assert page5_visual_blocks[2]["content"] == (
+ "For *rainfall distribution, U, uniform; W, winter dominated; "
+ "S, summer dominated. BFI, baseflow index."
+ )
+ assert [
+ [child.type for child in group.blocks]
+ for group in MagicModel(model_list[5], 1000, 1000).get_table_blocks()
+ ] == [
+ ["table_caption", "table_body", "table_footnote"],
+ ["table_caption", "table_body", "table_footnote"],
]
page1_footnotes = [block for block in model_list[0] if block["type"] == "page_footnote"]
assert len(page1_footnotes) == 1
@@ -147,10 +218,25 @@ def test_demo1_rotated_table_claims_all_206_lines_without_residual_text() -> Non
source = _native_page_source("demo1.pdf", 4)
candidates = tables._detect_table_candidates(source)
- blocks, claimed = tables._materialize_table_blocks(source, candidates)
+ blocks, annotation_blocks, claimed = tables._materialize_table_blocks(
+ source,
+ candidates,
+ )
rotated_indices = {line.source_index for line in source.lines if line.angle == 270}
assert len(blocks) == 1
+ assert {block["type"] for block in annotation_blocks} == {
+ "caption",
+ "footnote",
+ }
+ assert next(
+ block for block in annotation_blocks if block["type"] == "caption"
+ )["bbox"] == next(
+ annotation.bbox
+ for annotation in candidates[0].annotations
+ if annotation.kind == "caption"
+ )
+ assert blocks[0]["bbox"] == candidates[0].core_bbox
assert len(rotated_indices) == 206
assert claimed == rotated_indices
assert not [
@@ -207,11 +293,12 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
model_list = _native_model_list("demo2.pdf")
- assert [len(page) for page in model_list] == [16, 16, 21, 13, 16, 16]
+ assert [len(page) for page in model_list] == [16, 16, 21, 15, 18, 16]
assert [sum(block["type"] == "image" for block in page) for page in model_list] == [1, 0, 0, 5, 2, 0]
assert [sum(block["type"] == "table" for block in page) for page in model_list] == [0, 0, 0, 1, 1, 0]
assert sum(block["type"] == "equation" for page in model_list for block in page) == 9
- assert sum(block["type"] == "caption" for page in model_list for block in page) == 5
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 7
+ assert sum(block["type"] == "footnote" for page in model_list for block in page) == 2
page2 = model_list[1]
page2_contents = [block["content"] for block in page2]
@@ -285,7 +372,9 @@ def test_demo2_container_claims_are_pairwise_disjoint() -> None:
for page_idx in (1, 2, 3):
source = _native_page_source("demo2.pdf", page_idx)
table_candidates = tables._detect_table_candidates(source)
- table_blocks, table_claimed = tables._materialize_table_blocks(source, table_candidates)
+ table_blocks, _table_annotations, table_claimed = (
+ tables._materialize_table_blocks(source, table_candidates)
+ )
table_bboxes = [block["bbox"] for block in table_blocks]
_graphic_blocks, graphic_claimed = graphics._build_graphic_like_blocks(
source,
@@ -328,7 +417,12 @@ def test_demo2_page4_groups_five_graphics_and_keeps_table1() -> None:
]
assert len(table_blocks) == 1
- assert "Table I:" in table_blocks[0]["content"]
+ table_caption = next(
+ block for block in page if str(block["content"]).startswith("Table I:")
+ )
+ assert table_caption["type"] == "caption"
+ assert "Table I:" not in table_blocks[0]["content"]
+ assert "Symbol" in table_blocks[0]["content"]
assert len({id(block) for block in graphic_blocks}) == 5
assert "Frame 90" in graphic_blocks[0]["content"]
assert all("Figure" not in block["content"] for block in graphic_blocks)
@@ -342,27 +436,58 @@ def test_demo2_page4_groups_five_graphics_and_keeps_table1() -> None:
assert "discontinuity map." not in graphic_blocks[0]["content"]
-def test_demo2_table_captions_and_numeric_footnotes_are_not_text_blocks() -> None:
- """验证 demo2 两张表的换行标题和数字脚注全部并入表格投影。"""
+def test_demo2_table_captions_and_numeric_footnotes_are_independent_blocks() -> None:
+ """验证 demo2 两张表的换行标题和数字脚注独立输出并绑定为三段子块。"""
model_list = _native_model_list("demo2.pdf")
page4_table = next(block for block in model_list[3] if block["type"] == "table")
page5_table = next(block for block in model_list[4] if block["type"] == "table")
+ page4_caption = _blocks_containing(model_list[3], "Table I: Parameters")[0]
+ page5_caption = _blocks_containing(model_list[4], "Table II: A comparison")[0]
+ page4_footnote = _blocks_containing(
+ model_list[3],
+ "1 To enable propagation of disparity information",
+ )[0]
+ page5_footnote = _blocks_containing(
+ model_list[4],
+ "1 Millions of Disparity Estimates per Second",
+ )[0]
residual_text = "\n".join(
block["content"] for page_idx in (3, 4) for block in model_list[page_idx] if block["type"] == "text"
)
- assert "ral stereo matching." in page4_table["content"]
- assert "1 To enable propagation of disparity information" in page4_table["content"]
- assert "0.01, respectively." in page4_table["content"]
+ assert page4_caption["type"] == page5_caption["type"] == "caption"
+ assert page4_footnote["type"] == page5_footnote["type"] == "footnote"
+ assert "ral stereo matching." in page4_caption["content"]
+ assert "0.01, respectively." in page4_footnote["content"]
assert "Noise: ±20" not in page4_table["content"]
- assert "1 Millions of Disparity Estimates per Second." in page5_table["content"]
- assert "2 Assumes 320 × 240 images with 32 disparity levels." in page5_table["content"]
- assert "the avgerage % of bad pixels." in page5_table["content"]
+ assert "2 Assumes 320 × 240 images with 32 disparity levels." in page5_footnote["content"]
+ assert "the avgerage % of bad pixels." in page5_footnote["content"]
+ assert "Table I:" not in page4_table["content"]
+ assert "To enable propagation" not in page4_table["content"]
+ assert "Table II:" not in page5_table["content"]
+ assert "Millions of Disparity" not in page5_table["content"]
assert "ral stereo matching." not in residual_text
assert "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]
+ assert [page4_caption["bbox"], page4_table["bbox"], page4_footnote["bbox"]] == [
+ [0.51, 0.484, 0.915, 0.514],
+ [0.539, 0.53, 0.891, 0.638],
+ [0.549, 0.639, 0.891, 0.675],
+ ]
+ assert [page5_caption["bbox"], page5_table["bbox"], page5_footnote["bbox"]] == [
+ [0.51, 0.218, 0.915, 0.263],
+ [0.52, 0.278, 0.91, 0.39],
+ [0.53, 0.391, 0.91, 0.438],
+ ]
+ for page_index in (3, 4):
+ assert [
+ child.type
+ for child in MagicModel(
+ model_list[page_index],
+ 1000,
+ 1000,
+ ).get_table_blocks()[0].blocks
+ ] == ["table_caption", "table_body", "table_footnote"]
def test_demo3_keeps_tables_and_covers_every_native_source_line() -> None:
@@ -840,7 +965,31 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:
assert side_caption[0]["type"] == "caption"
assert side_caption[0]["bbox"][2] < side_image["bbox"][0]
assert page4.index(side_caption[0]) < page4.index(side_image)
- assert sum(block["type"] == "caption" for page in model_list for block in page) == 5
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 6
+ page2_table_caption = _blocks_containing(
+ model_list[1],
+ "Table 1 Patient demographics",
+ )[0]
+ page2_table = next(
+ block for block in model_list[1] if block["type"] == "table"
+ )
+ assert [page2_table_caption["type"], page2_table["type"]] == [
+ "caption",
+ "table",
+ ]
+ assert [page2_table_caption["bbox"], page2_table["bbox"]] == [
+ [0.514, 0.588, 0.914, 0.616],
+ [0.514, 0.615, 0.914, 0.894],
+ ]
+ assert "Patient demographics" not in str(page2_table["content"])
+ assert [
+ child.type
+ for child in MagicModel(
+ model_list[1],
+ 1000,
+ 1000,
+ ).get_table_blocks()[0].blocks
+ ] == ["table_caption", "table_body"]
page5 = model_list[4]
right_continuation = _blocks_containing(
@@ -1005,15 +1154,15 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:
magic_model = MagicModel(page, 1000, 1000)
table_blocks = magic_model.get_table_blocks()
assert len(table_blocks) == 1
- assert [child.type for child in table_blocks[0].blocks] == [
+ assert [child.type for child in table_blocks[0].blocks][-2:] == [
"table_body",
"table_footnote",
]
- table_footnote = table_blocks[0].blocks[1]
+ table_footnote = table_blocks[0].blocks[-1]
assert table_footnote.bbox == tuple(round(value * 1000) for value in expected_bbox)
assert _normalized_content_probe(tail_probe) in _normalized_content_probe(str(table_footnote.content))
- expected_footnote_pages = {6, 7, 31, 36, 39, 43, 49, 53, 55, 57, 58, 59, 77}
+ expected_footnote_pages = {2, 6, 7, 31, 36, 39, 43, 49, 53, 55, 57, 58, 59, 77}
assert {
page_number
for page_number, page in enumerate(model_list, start=1)
@@ -1023,8 +1172,66 @@ def test_demo5_targeted_table_and_footer_regressions() -> None:
block["type"] == "footnote"
for page in model_list
for block in page
- ) == 13
- assert sum(block["type"] == "caption" for page in model_list for block in page) == 3
+ ) == 14
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 25
+
+ page2_visual_blocks = [
+ block
+ for block in model_list[1]
+ if block["type"] in {"caption", "table", "footnote"}
+ ]
+ assert [block["type"] for block in page2_visual_blocks] == [
+ "caption",
+ "table",
+ "footnote",
+ ]
+ assert [block["bbox"] for block in page2_visual_blocks] == [
+ [0.403, 0.132, 0.597, 0.144],
+ [0.121, 0.147, 0.879, 0.871],
+ [0.151, 0.873, 0.53, 0.886],
+ ]
+ assert "表1 排污单位基本信息表" not in str(page2_visual_blocks[1]["content"])
+ assert "指生产经营场所地址所在地邮政编码" not in str(
+ page2_visual_blocks[1]["content"]
+ )
+ assert [
+ child.type
+ for child in MagicModel(
+ model_list[1],
+ 1000,
+ 1000,
+ ).get_table_blocks()[0].blocks
+ ] == ["table_caption", "table_body", "table_footnote"]
+
+ page4_table_groups = MagicModel(
+ model_list[3],
+ 1000,
+ 1000,
+ ).get_table_blocks()
+ assert [
+ [child.type for child in group.blocks]
+ for group in page4_table_groups
+ ] == [
+ ["table_caption", "table_body"],
+ ["table_caption", "table_body"],
+ ]
+ assert [group.blocks[0].bbox for group in page4_table_groups] == [
+ (425, 308, 575, 326),
+ (406, 619, 594, 637),
+ ]
+
+ for page_number in (65, 66):
+ in_border_note = _blocks_containing(
+ model_list[page_number - 1],
+ "注:设计贮存/处置危险废物数量",
+ )
+ assert len(in_border_note) == 1
+ assert in_border_note[0]["type"] == "table"
+ assert not [
+ block
+ for block in model_list[page_number - 1]
+ if block["type"] == "footnote"
+ ]
page62_note = _blocks_containing(
model_list[61],
"排入城镇集中污水处理设施的生活污水",
@@ -1303,16 +1510,24 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
"footnote",
]
- expected_new_footnotes = {1: 2, 6: 1, 7: 1, 8: 2, 17: 1, 19: 1}
+ expected_new_footnotes = {1: 2, 6: 1, 7: 2, 8: 2, 17: 1, 19: 1}
assert {
page_number: sum(block["type"] == "footnote" for block in model_list[page_number - 1])
for page_number in expected_new_footnotes
} == expected_new_footnotes
+ page7_table_note = _blocks_containing(
+ model_list[6],
+ "注:截止 2024 年 7 月 21 日",
+ )
+ assert len(page7_table_note) == 1
+ assert page7_table_note[0]["type"] == "footnote"
+ assert page7_table_note[0]["bbox"] == [0.073, 0.483, 0.219, 0.504]
+ assert "资料来源:Wind、华泰研究" in str(page7_table_note[0]["content"])
assert all(
str(block["content"]).startswith("资料来源:")
for page_number in expected_new_footnotes
for block in model_list[page_number - 1]
- if block["type"] == "footnote"
+ if block["type"] == "footnote" and block is not page7_table_note[0]
)
assert sum(
block["type"] == "caption"
@@ -1323,7 +1538,25 @@ def test_caibao_page2_parallel_chart_captions_stay_separate() -> None:
block["type"] == "footnote"
for page_blocks in model_list
for block in page_blocks
- ) == 16
+ ) == 17
+
+ page7_table_groups = MagicModel(
+ model_list[6],
+ 1000,
+ 1000,
+ ).get_table_blocks()
+ assert [
+ [child.type for child in group.blocks]
+ for group in page7_table_groups
+ ] == [
+ ["table_caption", "table_body", "table_footnote"],
+ ["table_caption", "table_body", "table_footnote"],
+ ]
+ assert [child.bbox for child in page7_table_groups[0].blocks] == [
+ (76, 83, 364, 94),
+ (72, 94, 930, 480),
+ (73, 483, 219, 504),
+ ]
page2_magic_model = MagicModel(page, 1000, 1000)
for caption_prefix in ("图表1", "图表2"):
@@ -1393,7 +1626,7 @@ def test_frozen_soil_page3_formula3_remains_one_equation() -> None:
if "(3)" in str(block.get("content", ""))
]
- assert len(page) == 28
+ assert len(page) == 30
assert len(equations) == 4
assert len(formula3) == 1
assert formula3[0]["bbox"] == [0.653, 0.703, 0.898, 0.751]
@@ -1426,7 +1659,7 @@ def test_frozen_soil_reference_tails_remain_single_text_blocks() -> None:
for block in page_blocks
if block["type"] == "caption"
]
- assert len(captions) == 15
+ assert len(captions) == 18
page2 = model_list[1]
image = next(block for block in page2 if block["type"] == "image")
chinese_caption = _blocks_containing(page2, "图1 冻土抗剪强度试验流程示意图")
@@ -1437,6 +1670,55 @@ def test_frozen_soil_reference_tails_remain_single_text_blocks() -> None:
english_caption[0]
)
+ page3 = model_list[2]
+ page3_table_group = MagicModel(
+ page3,
+ 1000,
+ 1000,
+ ).get_table_blocks()[0]
+ assert [child.type for child in page3_table_group.blocks] == [
+ "table_caption",
+ "table_caption",
+ "table_body",
+ "table_footnote",
+ ]
+ assert [child.bbox for child in page3_table_group.blocks] == [
+ (184, 684, 411, 708),
+ (116, 700, 473, 725),
+ (107, 721, 483, 838),
+ (107, 838, 489, 925),
+ ]
+ assert str(page3_table_group.blocks[0].content).startswith("表1")
+ assert str(page3_table_group.blocks[1].content).startswith("Table 1")
+
+ page5_table_groups = MagicModel(
+ model_list[4],
+ 1000,
+ 1000,
+ ).get_table_blocks()
+ assert [
+ [child.type for child in group.blocks]
+ for group in page5_table_groups
+ ] == [
+ ["table_caption", "table_caption", "table_body"],
+ ["table_caption", "table_caption", "table_body"],
+ ]
+ assert [
+ [child.bbox for child in group.blocks]
+ for group in page5_table_groups
+ ] == [
+ [
+ (217, 121, 373, 145),
+ (170, 137, 419, 162),
+ (107, 158, 483, 416),
+ ],
+ [
+ (209, 624, 380, 649),
+ (128, 641, 461, 665),
+ (107, 662, 483, 826),
+ ],
+ ]
+
narrative_reference = _blocks_containing(
model_list[7],
"图 8(a)、8(b)分别为",
@@ -1493,7 +1775,31 @@ def test_mixed_elements_pages_07_10_force_txt_regressions() -> None:
assert algorithm1[0]["type"] == algorithm2[0]["type"] == "caption"
assert page8.index(algorithm1[0]) + 1 == page8.index(code_blocks[1])
assert page8.index(algorithm2[0]) + 1 == page8.index(code_blocks[2])
- assert sum(block["type"] == "caption" for page in model_list for block in page) == 4
+ assert sum(block["type"] == "caption" for page in model_list for block in page) == 6
+
+ page10_table_groups = MagicModel(
+ page10,
+ 1000,
+ 1000,
+ ).get_table_blocks()
+ assert [
+ [child.type for child in group.blocks]
+ for group in page10_table_groups
+ ] == [
+ ["table_caption", "table_body"],
+ ["table_caption", "table_body"],
+ ]
+ assert [
+ [child.bbox for child in group.blocks]
+ for group in page10_table_groups
+ ] == [
+ [(151, 333, 432, 344), (112, 352, 470, 496)],
+ [(193, 607, 389, 618), (121, 626, 461, 710)],
+ ]
+ assert all(
+ "TABLE" not in str(group.blocks[-1].content)
+ for group in page10_table_groups
+ )
page8_magic_model = MagicModel(page8, 1000, 1000)
algorithm_groups = [
@@ -1566,7 +1872,22 @@ def test_mixed_elements_pages_11_15_force_txt_regressions() -> None:
assert "Under anesthesia with ether" in figure2[0]["content"]
assert "pepsin. Isolated and everted esophagus" in figure6[0]["content"]
assert not [block for block in all_blocks if block["type"] == "footnote"]
- assert sum(block["type"] == "caption" for block in all_blocks) == 6
+ assert sum(block["type"] == "caption" for block in all_blocks) == 7
+
+ table_group = MagicModel(
+ model_list[3],
+ 1000,
+ 1000,
+ ).get_table_blocks()[0]
+ assert [child.type for child in table_group.blocks] == [
+ "table_caption",
+ "table_body",
+ ]
+ assert [child.bbox for child in table_group.blocks] == [
+ (79, 93, 798, 103),
+ (79, 109, 922, 247),
+ ]
+ assert "Table 1." not in str(table_group.blocks[1].content)
online_footer = _blocks_containing(model_list[4], "http://www.birkhauser.ch/IPh")
assert len(online_footer) == 1
diff --git a/tests/unittest/test_flash_pdf_tables.py b/tests/unittest/test_flash_pdf_tables.py
index 7cdadea6..dbb914c1 100644
--- a/tests/unittest/test_flash_pdf_tables.py
+++ b/tests/unittest/test_flash_pdf_tables.py
@@ -257,9 +257,13 @@ def test_filled_grid_materialization_uses_existing_spatial_projection(
projection = MagicMock(return_value="inside-left inside-right")
monkeypatch.setattr(tables, "project_pdf_table_text", projection)
- blocks, claimed = tables._materialize_table_blocks(source, [candidate])
+ blocks, annotation_blocks, claimed = tables._materialize_table_blocks(
+ source,
+ [candidate],
+ )
assert claimed == {0, 1}
+ assert annotation_blocks == []
assert blocks == [
{
"type": "table",
@@ -325,9 +329,13 @@ def test_table_core_reclaims_semantic_line_without_touching_outer_marginals(
projection = MagicMock(return_value="cell\ntable tail")
monkeypatch.setattr(tables, "project_pdf_table_text", projection)
- blocks, claimed = tables._materialize_table_blocks(source, [candidate])
+ blocks, annotation_blocks, claimed = tables._materialize_table_blocks(
+ source,
+ [candidate],
+ )
assert len(blocks) == 1
+ assert annotation_blocks == []
assert claimed == {0, 1}
assert {line.source_index for line in lines if line.source_index not in claimed} == {
2,
@@ -1105,6 +1113,181 @@ def test_split_table_footnote_marker_is_joined_before_matching() -> None:
assert not tables._is_table_note_text("1 Numeric table footnote")
+def test_table_candidate_merge_keeps_body_and_annotation_roles_disjoint() -> None:
+ """验证重复候选合并时表体身份优先,并据逐行框收紧 caption 边界。"""
+
+ caption_bbox = (10.0, 10.0, 50.0, 20.0)
+ header_bbox = (10.0, 25.0, 90.0, 35.0)
+ primary = models._TableCandidate(
+ bbox=(0.0, 0.0, 100.0, 80.0),
+ local_bbox=(0.0, 0.0, 100.0, 80.0),
+ angle=0,
+ score=2.0,
+ core_bbox=(0.0, 25.0, 100.0, 80.0),
+ line_indices={2},
+ annotations=[
+ models._TableAnnotation(
+ kind="caption",
+ bbox=geometry._bbox_union(caption_bbox, header_bbox),
+ line_indices={0, 1},
+ line_bboxes={0: caption_bbox, 1: header_bbox},
+ )
+ ],
+ )
+ secondary = models._TableCandidate(
+ bbox=(0.0, 0.0, 100.0, 80.0),
+ local_bbox=(0.0, 0.0, 100.0, 80.0),
+ angle=0,
+ score=1.0,
+ core_bbox=(0.0, 25.0, 100.0, 80.0),
+ line_indices={1, 2},
+ annotations=[
+ models._TableAnnotation(
+ kind="caption",
+ bbox=caption_bbox,
+ line_indices={0},
+ line_bboxes={0: caption_bbox},
+ )
+ ],
+ )
+
+ merged = tables._merge_table_candidates([primary, secondary])
+
+ assert len(merged) == 1
+ assert merged[0].line_indices == {1, 2}
+ assert len(merged[0].annotations) == 1
+ assert merged[0].annotations[0].line_indices == {0}
+ assert merged[0].annotations[0].bbox == caption_bbox
+
+
+def test_materialize_table_externalizes_multiline_annotations_once(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证拆分编号 caption、多行数字脚注和表体按来源行各物化并认领一次。"""
+
+ line_specs = (
+ ("Table", (10.0, 10.0, 35.0, 20.0), 0),
+ ("2: Metrics", (38.0, 10.0, 80.0, 20.0), 1),
+ ("Header Body", (10.0, 30.0, 90.0, 60.0), 2),
+ ("1 Numeric note", (10.0, 70.0, 70.0, 80.0), 3),
+ ("* Symbol note", (10.0, 80.0, 70.0, 90.0), 4),
+ )
+ lines = [
+ models._LineItem(
+ text=text,
+ bbox=bbox,
+ angle=0,
+ source_index=source_index,
+ effective_height=10.0,
+ font_signature=("Test", 0),
+ font_coverage=1.0,
+ )
+ for text, bbox, source_index in line_specs
+ ]
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=lines,
+ chars=[],
+ drawing_lines=[],
+ )
+ candidate = models._TableCandidate(
+ bbox=(10.0, 10.0, 90.0, 90.0),
+ local_bbox=(10.0, 10.0, 90.0, 90.0),
+ angle=0,
+ score=1.0,
+ core_bbox=(10.0, 30.0, 90.0, 60.0),
+ line_indices={2},
+ annotations=[
+ models._TableAnnotation(
+ kind="caption",
+ bbox=(10.0, 10.0, 80.0, 20.0),
+ line_indices={0, 1},
+ ),
+ models._TableAnnotation(
+ kind="footnote",
+ bbox=(10.0, 70.0, 70.0, 90.0),
+ line_indices={3, 4},
+ ),
+ ],
+ )
+ projection = MagicMock(return_value="Header Body")
+ monkeypatch.setattr(tables, "project_pdf_table_text", projection)
+
+ table_blocks, annotation_blocks, claimed = tables._materialize_table_blocks(
+ source,
+ [candidate],
+ )
+
+ assert table_blocks == [
+ {
+ "type": "table",
+ "bbox": (10.0, 30.0, 90.0, 60.0),
+ "angle": 0,
+ "content": "Header Body",
+ }
+ ]
+ assert [block["type"] for block in annotation_blocks] == [
+ "caption",
+ "footnote",
+ ]
+ assert [block["content"] for block in annotation_blocks] == [
+ "Table 2: Metrics",
+ "1 Numeric note * Symbol note",
+ ]
+ assert all(
+ block["_table_annotation_complete"] is True
+ and block["_font_signatures"] == {("Test", 0)}
+ and len(block["_line_heights"]) == 2
+ for block in annotation_blocks
+ )
+ assert projection.call_args.args[1] == (10.0, 30.0, 90.0, 60.0)
+ assert claimed == {0, 1, 2, 3, 4}
+
+
+def test_invalid_table_annotation_falls_back_to_full_table_projection(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证无法形成内容的注释行留在表体投影,表框与认领均不收缩。"""
+
+ lines = [
+ models._LineItem("body", (10.0, 30.0, 90.0, 60.0), 0, 0),
+ models._LineItem("", (10.0, 10.0, 90.0, 20.0), 0, 1),
+ ]
+ source = models._PageSource(
+ page_size=(100.0, 100.0),
+ lines=lines,
+ chars=[],
+ drawing_lines=[],
+ )
+ candidate = models._TableCandidate(
+ bbox=(10.0, 10.0, 90.0, 60.0),
+ local_bbox=(10.0, 10.0, 90.0, 60.0),
+ angle=0,
+ score=1.0,
+ core_bbox=(10.0, 30.0, 90.0, 60.0),
+ line_indices={0},
+ annotations=[
+ models._TableAnnotation(
+ kind="caption",
+ bbox=(10.0, 10.0, 90.0, 20.0),
+ line_indices={1},
+ )
+ ],
+ )
+ projection = MagicMock(return_value="body")
+ monkeypatch.setattr(tables, "project_pdf_table_text", projection)
+
+ table_blocks, annotation_blocks, claimed = tables._materialize_table_blocks(
+ source,
+ [candidate],
+ )
+
+ assert annotation_blocks == []
+ assert table_blocks[0]["bbox"] == candidate.bbox
+ assert projection.call_args.args[1] == candidate.bbox
+ assert claimed == {0, 1}
+
+
def _table_note_reference_fixture(
marker: str,
reference_mode: str,
@@ -1552,16 +1735,25 @@ def test_failed_table_projection_does_not_claim_text(
) -> None:
"""验证投影为空或抛错时完整回滚候选,文本行仍可进入正文路径。"""
- line = models._LineItem(
- text="cell",
- bbox=(10.0, 10.0, 30.0, 20.0),
- angle=0,
- source_index=0,
- effective_height=10.0,
- )
+ lines = [
+ models._LineItem(
+ text="cell",
+ bbox=(10.0, 20.0, 30.0, 30.0),
+ angle=0,
+ source_index=0,
+ effective_height=10.0,
+ ),
+ models._LineItem(
+ text="Table 1",
+ bbox=(10.0, 5.0, 30.0, 15.0),
+ angle=0,
+ source_index=1,
+ effective_height=10.0,
+ ),
+ ]
source = models._PageSource(
page_size=(100.0, 100.0),
- lines=[line],
+ lines=lines,
chars=[],
drawing_lines=[],
)
@@ -1570,15 +1762,26 @@ def test_failed_table_projection_does_not_claim_text(
local_bbox=(0.0, 0.0, 50.0, 50.0),
angle=0,
score=1.0,
- core_bbox=(0.0, 0.0, 50.0, 50.0),
+ core_bbox=(0.0, 20.0, 50.0, 50.0),
line_indices={0},
+ annotations=[
+ models._TableAnnotation(
+ kind="caption",
+ bbox=(10.0, 5.0, 30.0, 15.0),
+ line_indices={1},
+ )
+ ],
)
projection = MagicMock(return_value="")
if projection_mode == "error":
projection.side_effect = RuntimeError("projection failed")
monkeypatch.setattr(tables, "project_pdf_table_text", projection)
- blocks, claimed = tables._materialize_table_blocks(source, [candidate])
+ blocks, annotation_blocks, claimed = tables._materialize_table_blocks(
+ source,
+ [candidate],
+ )
assert blocks == []
+ assert annotation_blocks == []
assert claimed == set()
diff --git a/tests/unittest/test_flash_pdf_visual_annotations.py b/tests/unittest/test_flash_pdf_visual_annotations.py
index 3ab14d09..7082dafa 100644
--- a/tests/unittest/test_flash_pdf_visual_annotations.py
+++ b/tests/unittest/test_flash_pdf_visual_annotations.py
@@ -251,6 +251,36 @@ def test_existing_visual_footnote_binds_without_content_marker() -> None:
assert [block["type"] for block in regions[0]] == ["image", "footnote"]
+def test_preclassified_table_annotations_keep_local_order_and_do_not_expand() -> None:
+ """验证预分类 caption/table/footnote 稳定成组,完整表注不吸收后续正文。"""
+
+ caption = _text_block(
+ "unmarked table title",
+ (20.0, 10.0, 120.0, 20.0),
+ block_type="caption",
+ )
+ table = _visual_block((20.0, 30.0, 180.0, 70.0), block_type="table")
+ footnote = _text_block(
+ "1 numeric table note",
+ (20.0, 80.0, 140.0, 90.0),
+ block_type="footnote",
+ lane_interval=(20.0, 160.0),
+ )
+ footnote["_table_annotation_complete"] = True
+ continuation = _text_block(
+ "indented body text",
+ (30.0, 95.0, 150.0, 105.0),
+ lane_interval=(20.0, 160.0),
+ )
+ blocks = [table, continuation, footnote, caption]
+
+ regions = _classify_with_text_block_merge(blocks)
+
+ assert len(blocks) == 4
+ assert regions == [[caption, table, footnote]]
+ assert continuation["type"] == "text"
+
+
def test_table_footnote_merges_multiple_hanging_indent_continuations() -> None:
"""验证表注强标记会吸收多个同栏悬挂缩进续块并保留内部元数据。"""