Skip to content

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

feat: enhance PDF text block processing by adding visual run spans and validating block content

myhloliadd5ef46cd2a
diff --git a/mineru/backend/analyze.py b/mineru/backend/analyze.py
index 370ceb62..df562381 100644
--- a/mineru/backend/analyze.py
+++ b/mineru/backend/analyze.py
@@ -96,6 +96,8 @@ CODE_CONTENT_BLOCK_TYPES = {
}
LINE_METADATA_BLOCK_TYPES = {
BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
BlockType.CAPTION,
BlockType.FOOTNOTE,
}
@@ -171,7 +173,10 @@ VLM_OCR_DET_TYPE = {
BlockType.TEXT,
BlockType.DOC_TITLE,
BlockType.PARAGRAPH_TITLE,
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
}
+_LOW_TXT_VISUAL_RUN_ANGLES = (0.0, 90.0, 180.0, 270.0)
@dataclass
@@ -785,6 +790,34 @@ def _build_pdf_text_line_spans(pdf_page: PDFPage) -> list[Span]:
return page_spans
+def _build_pdf_text_visual_run_spans(pdf_page: PDFPage) -> list[Span]:
+ """将 Low/TXT 原生粗行按 Flash 字符间隙拆成可独立分配的视觉 run。"""
+
+ # 延迟导入避免 Hybrid 模块初始化时提前加载完整 Flash PDF 流水线。
+ from mineru.model.flash.native_pdf.native_text import _build_native_line_items
+
+ line_items = _build_native_line_items(
+ get_lines_from_chars(pdf_page.get_chars()),
+ tuple(float(value) for value in pdf_page.size),
+ page_rotation=pdf_page.rotation,
+ supported_angles=_LOW_TXT_VISUAL_RUN_ANGLES,
+ )
+ page_spans: list[Span] = []
+ for line_item in line_items:
+ content = __replace_ligatures(__replace_unicode(line_item.text)).strip()
+ if not content:
+ continue
+ page_spans.append(
+ Span(
+ type=ContentType.TEXT,
+ bbox=line_item.bbox,
+ content=content,
+ score=1.0,
+ )
+ )
+ return page_spans
+
+
def _sidecar_bbox_to_page_bbox(
bbox: BBox | None,
page_size: tuple[float, float],
@@ -2218,7 +2251,7 @@ def _process_low_text(
page_size = tuple(float(value) for value in pdf_page.size)
block_lines = _group_page_spans_by_block(
page_model_list,
- _build_pdf_text_line_spans(pdf_page),
+ _build_pdf_text_visual_run_spans(pdf_page),
page_size,
target_block_types,
)
@@ -2399,8 +2432,41 @@ def _apply_layout_title_split(
block["type"] = BlockType.PARAGRAPH_TITLE
+def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
+ """检查 PDF 文本块是否同时具有非空正文和完整合法的归一化行框。"""
+
+ content = block.get("content")
+ if not isinstance(content, str) or not content.strip():
+ return False
+
+ lines = block.get("lines")
+ if not isinstance(lines, list) or not lines:
+ return False
+ for line in lines:
+ if not isinstance(line, dict):
+ return False
+ bbox = line.get("bbox")
+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
+ return False
+ if any(
+ not isinstance(value, (int, float))
+ or isinstance(value, bool)
+ or not math.isfinite(float(value))
+ for value in bbox
+ ):
+ return False
+ x0, y0, x1, y1 = [float(value) for value in bbox]
+ if (
+ not all(0.0 <= value <= 1.0 for value in (x0, y0, x1, y1))
+ or x1 <= x0
+ or y1 <= y0
+ ):
+ return False
+ return True
+
+
def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
- """清理 model JSON block 元数据,并原地替换 content 中的行内公式定界符。"""
+ """清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""
for page_model_list in model_list:
for block in page_model_list:
block.pop("angle", None)
@@ -2412,6 +2478,12 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
lambda match: f"<eq>{match.group(1)}</eq>",
content,
)
+ page_model_list[:] = [
+ block
+ for block in page_model_list
+ if block.get("type") not in LINE_METADATA_BLOCK_TYPES
+ or _is_valid_pdf_text_block(block)
+ ]
def _log_infer_performance(file_suffix: str, page_count: int, elapsed: float) -> None:
diff --git a/mineru/model/flash/native_pdf/native_text.py b/mineru/model/flash/native_pdf/native_text.py
index 9d7ddad3..b3f334e8 100644
--- a/mineru/model/flash/native_pdf/native_text.py
+++ b/mineru/model/flash/native_pdf/native_text.py
@@ -62,8 +62,9 @@ def _build_native_line_items(
page_size: tuple[float, float],
*,
page_rotation: int = 0,
+ supported_angles: Sequence[float] = _SUPPORTED_PDFTEXT_LINE_ANGLES,
) -> list[_LineItem]:
- """将 pdftext 粗行按字符间隙精修成 Flash 视觉 run。"""
+ """按指定视觉方向将 pdftext 粗行精修成字符间隙分隔的视觉 run。"""
items: list[_LineItem] = []
supported_lines = [
@@ -74,6 +75,7 @@ def _build_native_line_items(
visual_angle := _resolve_pdftext_line_angle(
child_line,
page_rotation=page_rotation,
+ supported_angles=supported_angles,
)
)
is not None
@@ -175,14 +177,19 @@ def _split_pdftext_line_by_rotation(pdf_line: dict[str, Any]) -> list[dict[str,
return output
-def _is_supported_pdftext_line_rotation(value: Any, *, page_rotation: int) -> bool:
- """应用页面旋转后只允许 0、90、270 度行,避免异向水印被归一成正文。"""
+def _is_supported_pdftext_line_rotation(
+ value: Any,
+ *,
+ page_rotation: int,
+ supported_angles: Sequence[float] = _SUPPORTED_PDFTEXT_LINE_ANGLES,
+) -> bool:
+ """应用页面旋转后按调用方白名单筛选视觉文字方向。"""
visual_angle = (_pdftext_angle_degrees(value) + int(page_rotation or 0)) % 360.0
return any(
_circular_angle_distance(visual_angle, supported_angle)
<= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
- for supported_angle in _SUPPORTED_PDFTEXT_LINE_ANGLES
+ for supported_angle in supported_angles
)
@@ -190,6 +197,7 @@ def _resolve_pdftext_line_angle(
pdf_line: dict[str, Any],
*,
page_rotation: int,
+ supported_angles: Sequence[float] = _SUPPORTED_PDFTEXT_LINE_ANGLES,
) -> int | None:
"""解析视觉文字方向,并用字符基线纠正字体 shear 造成的伪斜向行。"""
@@ -197,14 +205,20 @@ def _resolve_pdftext_line_angle(
_pdftext_angle_degrees(pdf_line.get("rotation"))
+ int(page_rotation or 0)
) % 360.0
- for supported_angle in _SUPPORTED_PDFTEXT_LINE_ANGLES:
+ for supported_angle in supported_angles:
if (
_circular_angle_distance(visual_angle, supported_angle)
<= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
):
return int(supported_angle)
+ supports_horizontal = any(
+ _circular_angle_distance(0.0, supported_angle)
+ <= _PDFTEXT_LINE_ANGLE_TOLERANCE_DEGREES
+ for supported_angle in supported_angles
+ )
if (
- _circular_angle_distance(visual_angle, 0.0)
+ supports_horizontal
+ and _circular_angle_distance(visual_angle, 0.0)
<= _PDFTEXT_SHEARED_HORIZONTAL_MAX_ANGLE_DEGREES
and _pdftext_line_has_horizontal_char_baseline(pdf_line)
):
diff --git a/mineru/model/flash/native_pdf/pipeline.py b/mineru/model/flash/native_pdf/pipeline.py
index 31e3f921..57083ba1 100644
--- a/mineru/model/flash/native_pdf/pipeline.py
+++ b/mineru/model/flash/native_pdf/pipeline.py
@@ -27,6 +27,7 @@ from .geometry import (
_clip_bbox,
_coerce_bbox,
_normalize_bbox_to_thousandths,
+ _rotate_bbox_from_upright,
_rotate_bbox_to_upright,
)
from .native_text import (
@@ -112,6 +113,13 @@ _TEXT_SEMANTIC_TYPES = {
_OUTPUT_BLOCK_TYPES = {"text", "table", "image", "equation", "code"} | _TEXT_SEMANTIC_TYPES
+_LINE_METADATA_OUTPUT_TYPES = {
+ "text",
+ "doc_title",
+ "paragraph_title",
+ "caption",
+ "footnote",
+}
_REPEATED_RASTER_IMAGE_MIN_PAGE_AREA_RATIO = 0.08
_REPEATED_RASTER_IMAGE_MIN_DISTINCT_PAGES = 3
@@ -934,9 +942,49 @@ def _normalize_output_block(
if normalized_type not in {"image", "equation", "header", "footer"} and not content.strip():
return None
normalized_bbox = _normalize_bbox_to_thousandths(bbox, page_size)
- return {
+ output_block = {
"type": normalized_type,
"bbox": normalized_bbox,
"angle": 0 if normalized_type == "image" else int(block.get("angle", 0) or 0) % 360,
"content": content,
}
+ if normalized_type in _LINE_METADATA_OUTPUT_TYPES:
+ output_block["lines"] = _normalize_output_line_items(block, page_size)
+ return output_block
+
+
+def _normalize_output_line_items(
+ block: dict[str, Any],
+ page_size: tuple[float, float],
+) -> list[dict[str, list[float]]]:
+ """将 Flash 正向局部行框逆变换为页面坐标并归一化输出。"""
+
+ local_line_bboxes = block.get("_local_line_bboxes")
+ if not isinstance(local_line_bboxes, list):
+ return []
+
+ angle = int(block.get("angle", 0) or 0) % 360
+ line_items: list[dict[str, list[float]]] = []
+ for local_line_bbox in local_line_bboxes:
+ try:
+ raw_bbox = tuple(float(value) for value in local_line_bbox)
+ except (TypeError, ValueError):
+ return []
+ coerced_bbox = _coerce_bbox(raw_bbox)
+ if (
+ len(raw_bbox) != 4
+ or coerced_bbox is None
+ or raw_bbox[2] <= raw_bbox[0]
+ or raw_bbox[3] <= raw_bbox[1]
+ ):
+ return []
+ page_bbox = _clip_bbox(
+ _rotate_bbox_from_upright(coerced_bbox, page_size, angle),
+ page_size,
+ )
+ if page_bbox is None:
+ return []
+ line_items.append(
+ {"bbox": _normalize_bbox_to_thousandths(page_bbox, page_size)}
+ )
+ return line_items
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index 6eadf818..223f41f7 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -117,6 +117,12 @@ class PDFPage:
def size(self) -> tuple[float, float]:
return self.pdf_doc.page_size(self._idx)
+ @property
+ def rotation(self) -> Literal[0, 90, 180, 270]:
+ """只读返回当前页声明的标准旋转角度。"""
+
+ return self.pdf_doc.page_rotation(self._idx)
+
def get_char_count(self) -> int:
return self.pdf_doc.page_char_count(self._idx)
diff --git a/tests/unittest/test_flash_pdf_line_metadata.py b/tests/unittest/test_flash_pdf_line_metadata.py
new file mode 100644
index 00000000..dcb37702
--- /dev/null
+++ b/tests/unittest/test_flash_pdf_line_metadata.py
@@ -0,0 +1,93 @@
+from __future__ import annotations
+
+import pytest
+
+from mineru.model.flash.native_pdf import pipeline
+
+
+ "block_type",
+ ["text", "doc_title", "paragraph_title", "caption", "footnote"],
+)
+def test_output_normalization_exposes_lines_for_pdf_text_types(
+ block_type: str,
+) -> None:
+ """验证五类 PDF 文本块会按原阅读顺序公开归一化行框。"""
+
+ block = pipeline._normalize_output_block(
+ {
+ "type": block_type,
+ "bbox": (10.0, 20.0, 90.0, 80.0),
+ "angle": 0,
+ "content": "line one\nline two",
+ "_local_line_bboxes": [
+ (10.0, 20.0, 90.0, 40.0),
+ (20.0, 50.0, 80.0, 80.0),
+ ],
+ },
+ (100.0, 200.0),
+ )
+
+ assert block is not None
+ assert block["lines"] == [
+ {"bbox": [0.1, 0.1, 0.9, 0.2]},
+ {"bbox": [0.2, 0.25, 0.8, 0.4]},
+ ]
+
+
+ ("angle", "expected_bbox"),
+ [
+ (0, [0.2, 0.05, 0.4, 0.15]),
+ (90, [0.7, 0.1, 0.9, 0.2]),
+ (270, [0.1, 0.8, 0.3, 0.9]),
+ ],
+)
+def test_output_normalization_restores_rotated_line_bbox_to_page(
+ angle: int,
+ expected_bbox: list[float],
+) -> None:
+ """验证局部行框会按 block 方向逆变换到原页面坐标。"""
+
+ block = pipeline._normalize_output_block(
+ {
+ "type": "text",
+ "bbox": (10.0, 10.0, 90.0, 190.0),
+ "angle": angle,
+ "content": "value",
+ "_local_line_bboxes": [(20.0, 10.0, 40.0, 30.0)],
+ },
+ (100.0, 200.0),
+ )
+
+ assert block is not None
+ assert block["lines"] == [{"bbox": expected_bbox}]
+
+
+ "local_line_bboxes",
+ [
+ None,
+ [],
+ [(10.0, 20.0, 40.0, 30.0), (1.0, 2.0, 1.0, 3.0)],
+ [(40.0, 20.0, 10.0, 30.0)],
+ ],
+)
+def test_output_normalization_fails_closed_for_invalid_line_bboxes(
+ local_line_bboxes: object,
+) -> None:
+ """验证内部行框缺失、为空或任一非法时输出空 lines。"""
+
+ block = pipeline._normalize_output_block(
+ {
+ "type": "text",
+ "bbox": (10.0, 20.0, 40.0, 50.0),
+ "angle": 0,
+ "content": "value",
+ "_local_line_bboxes": local_line_bboxes,
+ },
+ (100.0, 100.0),
+ )
+
+ assert block is not None
+ assert block["lines"] == []
diff --git a/tests/unittest/test_flash_pdf_native_text.py b/tests/unittest/test_flash_pdf_native_text.py
index 235b5194..c5b780da 100644
--- a/tests/unittest/test_flash_pdf_native_text.py
+++ b/tests/unittest/test_flash_pdf_native_text.py
@@ -173,6 +173,31 @@ def test_only_supported_visual_line_directions_are_retained(
assert [item.angle for item in items] == ([] if expected_angle is None else [expected_angle])
+def test_native_line_builder_can_opt_in_to_180_degree_visual_runs() -> None:
+ """验证 Low/TXT 可显式扩展方向白名单且不改变 Flash 默认行为。"""
+
+ pdf_line = _line(
+ [_span("upside down", (10.0, 20.0, 60.0, 30.0), 180.0)],
+ 180.0,
+ bbox=(10.0, 20.0, 60.0, 30.0),
+ )
+
+ default_items = native_text._build_native_line_items(
+ [pdf_line],
+ (100.0, 100.0),
+ )
+ low_txt_items = native_text._build_native_line_items(
+ [pdf_line],
+ (100.0, 100.0),
+ supported_angles=(0.0, 90.0, 180.0, 270.0),
+ )
+
+ assert default_items == []
+ assert [(item.text, item.angle) for item in low_txt_items] == [
+ ("upside down", 180)
+ ]
+
+
@pytest.mark.parametrize(
"separator",
[
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index 4a990e9a..da0e451e 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -247,37 +247,76 @@ def test_xhigh_vlm_blocks_remove_merge_prev_from_all_text_blocks() -> None:
assert page_blocks[-1] == {"type": BlockType.CAPTION, "content": "caption"}
-def test_caption_and_footnote_keep_normalized_line_metadata() -> None:
- """验证通用 caption/footnote 与 text 一样保留归一化 _lines。"""
+def test_five_pdf_text_types_keep_normalized_line_metadata() -> None:
+ """验证五类 PDF 文本块统一保留公开的归一化 lines。"""
assert analyze.LINE_METADATA_BLOCK_TYPES == {
BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
BlockType.CAPTION,
BlockType.FOOTNOTE,
}
text_block = {"type": BlockType.TEXT, "content": "text"}
+ doc_title_block = {"type": BlockType.DOC_TITLE, "content": "doc title"}
+ paragraph_title_block = {
+ "type": BlockType.PARAGRAPH_TITLE,
+ "content": "paragraph title",
+ }
caption_block = {"type": BlockType.CAPTION, "content": "caption"}
footnote_block = {"type": BlockType.FOOTNOTE, "content": "footnote"}
- unrelated_block = {"type": BlockType.TITLE, "content": "title", "_lines": [{"bbox": [0, 0, 1, 1]}]}
- page_blocks = [text_block, caption_block, footnote_block, unrelated_block]
+ unrelated_block = {
+ "type": BlockType.TITLE,
+ "content": "title",
+ "lines": [{"bbox": [0, 0, 1, 1]}],
+ }
+ page_blocks = [
+ text_block,
+ doc_title_block,
+ paragraph_title_block,
+ caption_block,
+ footnote_block,
+ unrelated_block,
+ ]
analyze._apply_block_content_and_line_metadata(
page_blocks,
{
0: _build_text_lines("text"),
- 1: _build_text_lines("caption line 1", "caption line 2"),
- 2: _build_text_lines("footnote"),
- 3: _build_text_lines("title"),
+ 1: _build_text_lines("doc title"),
+ 2: _build_text_lines("paragraph title"),
+ 3: _build_text_lines("caption line 1", "caption line 2"),
+ 4: _build_text_lines("footnote"),
+ 5: _build_text_lines("title"),
},
(200.0, 100.0),
)
- assert text_block["_lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
- assert caption_block["_lines"] == [
+ assert text_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
+ assert doc_title_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
+ assert paragraph_title_block["lines"] == [
+ {"bbox": [0.0, 0.0, 0.5, 0.01]}
+ ]
+ assert caption_block["lines"] == [
{"bbox": [0.0, 0.0, 0.5, 0.01]},
{"bbox": [0.0, 0.01, 0.5, 0.02]},
]
- assert footnote_block["_lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
- assert "_lines" not in unrelated_block
+ assert footnote_block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
+ assert "lines" not in unrelated_block
+
+
[email protected]("effort", ["high", "xhigh"])
+def test_high_ocr_detects_lines_for_all_five_pdf_text_types(
+ effort: str,
+) -> None:
+ """验证 High/XHigh OCR 对标题、正文、caption 和 footnote 都执行行检测。"""
+
+ ocr_det_type, mfr_enabled = analyze._build_ocr_det_type_and_mfr_enable(
+ "ocr",
+ effort,
+ )
+
+ assert ocr_det_type == analyze.LINE_METADATA_BLOCK_TYPES
+ assert mfr_enabled is False
def test_window_post_ocr_batches_all_pages_once() -> None:
@@ -452,11 +491,71 @@ def test_existing_index_content_is_not_overwritten() -> None:
)
assert block["content"] == "已有目录一\n已有目录二"
- assert "_lines" not in block
+ assert "lines" not in block
+
+
+def test_low_txt_visual_runs_split_distant_text_before_layout_matching(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """验证 Low/TXT 在版面匹配前按 Flash 字符间隙拆开同一粗行。"""
+
+ chars = [
+ {"char": "L", "bbox": (5.0, 10.0, 9.0, 20.0)},
+ {"char": "e", "bbox": (9.0, 10.0, 13.0, 20.0)},
+ {"char": "f", "bbox": (13.0, 10.0, 17.0, 20.0)},
+ {"char": "t", "bbox": (17.0, 10.0, 21.0, 20.0)},
+ {"char": " ", "bbox": (21.0, 10.0, 25.0, 20.0)},
+ {"char": "R", "bbox": (70.0, 10.0, 74.0, 20.0)},
+ {"char": "i", "bbox": (74.0, 10.0, 78.0, 20.0)},
+ {"char": "g", "bbox": (78.0, 10.0, 82.0, 20.0)},
+ {"char": "h", "bbox": (82.0, 10.0, 86.0, 20.0)},
+ {"char": "t", "bbox": (86.0, 10.0, 90.0, 20.0)},
+ ]
+ pdf_lines = [
+ {
+ "bbox": (5.0, 10.0, 90.0, 20.0),
+ "rotation": 0.0,
+ "spans": [
+ {
+ "text": "Left Right",
+ "bbox": (5.0, 10.0, 90.0, 20.0),
+ "rotation": 0.0,
+ "chars": chars,
+ }
+ ],
+ }
+ ]
+ pdf_page = MagicMock()
+ pdf_page.size = (100.0, 100.0)
+ pdf_page.rotation = 0
+ pdf_page.get_chars.return_value = []
+ monkeypatch.setattr(analyze, "get_lines_from_chars", lambda _chars: pdf_lines)
+
+ spans = analyze._build_pdf_text_visual_run_spans(pdf_page)
+
+ assert [(span.content, span.bbox) for span in spans] == [
+ ("Left", (5.0, 10.0, 21.0, 20.0)),
+ ("Right", (70.0, 10.0, 90.0, 20.0)),
+ ]
+
+
+def test_existing_text_content_is_preserved_while_lines_are_refreshed() -> None:
+ """验证 Low/TXT 只补空正文,已有 VLM 内容不覆盖但仍写入真实行框。"""
+
+ block = {"type": BlockType.TEXT, "content": "existing content"}
+
+ analyze._apply_block_content_and_line_metadata(
+ [block],
+ {0: _build_text_lines("native content")},
+ (200.0, 100.0),
+ )
+
+ assert block["content"] == "existing content"
+ assert block["lines"] == [{"bbox": [0.0, 0.0, 0.5, 0.01]}]
-def test_npu_page_three_medium_index_matches_flash_line_structure() -> None:
- """验证真实 NPU 目录页的 Medium 回填结果与 Flash 一样保留 24 个目录行。"""
+def test_npu_page_three_low_visual_runs_keep_index_line_structure() -> None:
+ """验证 Low/TXT 的 Flash visual run 拆分不会破坏 NPU 的 24 行目录。"""
document = PDFDocument(_NPU_PDF_PATH.read_bytes())
try:
page = document[2]
@@ -469,7 +568,7 @@ def test_npu_page_three_medium_index_matches_flash_line_structure() -> None:
}
block_lines = analyze._group_page_spans_by_block(
[index_block],
- analyze._build_pdf_text_line_spans(page),
+ analyze._build_pdf_text_visual_run_spans(page),
page_size,
{BlockType.INDEX},
)
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index 9391dfb1..a0d06f5e 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -529,7 +529,7 @@ def test_visual_block_crop_rejects_page_count_mismatch() -> None:
def test_normalize_pdf_model_list_updates_in_place() -> None:
- """验证 block 元数据清理和行内公式替换会原地更新 model JSON。"""
+ """验证元数据、公式和无效 PDF 文本块过滤会原地更新 model JSON。"""
model_list = [
[
{
@@ -537,23 +537,46 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:
"content": "前 \\(a+b\\) 中 \\(c_d\\) 后",
"angle": 0,
"score": 0.98,
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
},
{
"type": BlockType.TEXT,
"content": "已有 <eq>x</eq> 保持不变",
"angle": 90,
+ "lines": [{"bbox": [0.1, 0.2, 0.9, 0.3]}],
},
{
"type": BlockType.TEXT,
"content": "未闭合 \\(formula",
"score": 0.75,
+ "lines": [{"bbox": [0.1, 0.3, 0.9, 0.4]}],
},
],
[
- {"type": BlockType.TEXT, "content": ""},
- {"type": BlockType.TEXT, "content": None, "angle": 180, "score": 0.5},
- {"type": BlockType.TEXT, "content": ["非字符串"], "score": 0.25},
- {"type": BlockType.TEXT, "content": "跨行 \\(a\nb\\)", "angle": 270},
+ {
+ "type": BlockType.TEXT,
+ "content": "",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
+ },
+ {
+ "type": BlockType.TEXT,
+ "content": None,
+ "angle": 180,
+ "score": 0.5,
+ "lines": [{"bbox": [0.1, 0.2, 0.9, 0.3]}],
+ },
+ {
+ "type": BlockType.TEXT,
+ "content": ["非字符串"],
+ "score": 0.25,
+ "lines": [{"bbox": [0.1, 0.3, 0.9, 0.4]}],
+ },
+ {
+ "type": BlockType.TEXT,
+ "content": "跨行 \\(a\nb\\)",
+ "angle": 270,
+ "lines": [{"bbox": [0.1, 0.4, 0.9, 0.5]}],
+ },
],
]
@@ -563,10 +586,9 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:
assert model_list[0][0]["content"] == "前 <eq>a+b</eq> 中 <eq>c_d</eq> 后"
assert model_list[0][1]["content"] == "已有 <eq>x</eq> 保持不变"
assert model_list[0][2]["content"] == "未闭合 \\(formula"
- assert model_list[1][0]["content"] == ""
- assert model_list[1][1]["content"] is None
- assert model_list[1][2]["content"] == ["非字符串"]
- assert model_list[1][3]["content"] == "跨行 \\(a\nb\\)"
+ assert [block["content"] for block in model_list[1]] == [
+ "跨行 \\(a\nb\\)"
+ ]
assert all(
"angle" not in block and "score" not in block
for page_model_list in model_list
@@ -574,6 +596,106 @@ def test_normalize_pdf_model_list_updates_in_place() -> None:
)
+ "block_type",
+ [
+ BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
+ ],
+)
+ "invalid_lines",
+ [
+ None,
+ [],
+ [{}],
+ [{"bbox": [0.1, 0.2, 0.3]}],
+ [{"bbox": [0.1, 0.2, float("nan"), 0.4]}],
+ [{"bbox": [-0.1, 0.2, 0.3, 0.4]}],
+ [{"bbox": [0.1, 0.2, 1.1, 0.4]}],
+ [{"bbox": [0.3, 0.2, 0.3, 0.4]}],
+ [{"bbox": [0.1, 0.4, 0.3, 0.4]}],
+ [
+ {"bbox": [0.1, 0.2, 0.3, 0.4]},
+ {"bbox": [0.4, 0.5, 0.4, 0.6]},
+ ],
+ ],
+)
+def test_normalize_pdf_model_list_removes_five_text_types_with_invalid_lines(
+ block_type: str,
+ invalid_lines: object,
+) -> None:
+ """验证五类文本块只要任一行框非法就按 fail-closed 规则删除。"""
+
+ model_list = [[{"type": block_type, "content": "valid", "lines": invalid_lines}]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list == [[]]
+
+
+ "block_type",
+ [
+ BlockType.TEXT,
+ BlockType.DOC_TITLE,
+ BlockType.PARAGRAPH_TITLE,
+ BlockType.CAPTION,
+ BlockType.FOOTNOTE,
+ ],
+)
[email protected]("invalid_content", [None, "", " ", ["not a string"]])
+def test_normalize_pdf_model_list_removes_five_text_types_with_empty_content(
+ block_type: str,
+ invalid_content: object,
+) -> None:
+ """验证五类文本块即使行框有效,正文为空或非字符串时仍会删除。"""
+
+ model_list = [
+ [
+ {
+ "type": block_type,
+ "content": invalid_content,
+ "lines": [{"bbox": [0.1, 0.2, 0.3, 0.4]}],
+ }
+ ]
+ ]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list == [[]]
+
+
+def test_normalize_pdf_model_list_keeps_other_types_and_valid_text_order() -> None:
+ """验证过滤不影响其他类型,并保持合法文本块的相对顺序。"""
+
+ equation = {"type": BlockType.EQUATION, "content": "", "lines": []}
+ header = {"type": BlockType.HEADER, "content": "", "lines": []}
+ first_text = {
+ "type": BlockType.TEXT,
+ "content": "first",
+ "lines": [{"bbox": [0.1, 0.1, 0.9, 0.2]}],
+ }
+ invalid_text = {
+ "type": BlockType.CAPTION,
+ "content": "caption",
+ "lines": [],
+ }
+ second_text = {
+ "type": BlockType.FOOTNOTE,
+ "content": "second",
+ "lines": [{"bbox": [0.1, 0.8, 0.9, 0.9]}],
+ }
+ model_list = [[equation, first_text, invalid_text, header, second_text]]
+
+ analyze._normalize_pdf_model_list(model_list)
+
+ assert model_list == [[equation, first_text, header, second_text]]
+
+
@pytest.mark.parametrize(
("page_count", "elapsed", "expected_cost", "expected_speed"),
[
diff --git a/tests/unittest/test_pdf_document.py b/tests/unittest/test_pdf_document.py
index 6fe69272..e60532a1 100644
--- a/tests/unittest/test_pdf_document.py
+++ b/tests/unittest/test_pdf_document.py
@@ -494,10 +494,12 @@ def test_get_page_drawing_lines_applies_crop_box_and_page_rotation() -> None:
with pdf_document.PDFDocument(_build_rotated_cropped_drawing_pdf()) as doc:
page_size = doc.page_size(0)
page_rotation = doc.page_rotation(0)
+ page_object_rotation = doc[0].rotation
lines = doc.get_page_drawing_lines(0)
assert page_size == pytest.approx((180.0, 90.0))
assert page_rotation == 90
+ assert page_object_rotation == 90
assert len(lines) == 1
line = lines[0]
assert line.orientation == "vertical"