Skip to content

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

feat(normalization): enhance PDF text block validation and normalization logic

myhloli6b6b229bf2e1
diff --git a/mineru/backend/analysis/pdf/normalization.py b/mineru/backend/analysis/pdf/normalization.py
index 0635bf87..13b4a067 100644
--- a/mineru/backend/analysis/pdf/normalization.py
+++ b/mineru/backend/analysis/pdf/normalization.py
@@ -3,13 +3,13 @@
from __future__ import annotations
-import math
import re
from typing import Any
from docvortex.content import normalize_pdf_model_text
from docvortex.content.spans import append_equation_span, append_text_span, inline_span_plain_text, strip_span_dicts
from docvortex.geometry import calculate_overlap_area_2_minbox_area_ratio
+from loguru import logger
from ....types import RAW_ALGORITHM, RAW_PHONETIC, BBox, BlockType
from .constants import (
@@ -64,9 +64,28 @@ def _apply_layout_title_split(
block["level"] = 2
-def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
- """检查 PDF 文本块是否同时具有非空正文和完整合法的归一化行框。"""
+def _is_valid_pdf_text_bbox(bbox: object) -> bool:
+ """校验文本几何的归一化矩形,拒绝布尔值、非有限坐标和退化框。"""
+ if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
+ return False
+ # 区间判断同时排除 NaN/Inf,且避免将超大整数转成 float 时溢出。
+ if not all(isinstance(value, (int, float)) and not isinstance(value, bool) and 0.0 <= value <= 1.0 for value in bbox):
+ return False
+ x0, y0, x1, y1 = bbox
+ return x1 > x0 and y1 > y0
+
+
+def _has_valid_pdf_text_lines(lines: object) -> bool:
+ """检查非空行列表中的每一条行框是否完整合法。"""
+ return (
+ isinstance(lines, list)
+ and bool(lines)
+ and all(isinstance(line, dict) and _is_valid_pdf_text_bbox(line.get("bbox")) for line in lines)
+ )
+
+def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
+ """检查文本块是否具有非空正文,以及合法行框或可用于兜底的块框。"""
content = block.get("content")
if isinstance(content, list):
visible_content = inline_span_plain_text(item for item in content if isinstance(item, dict))
@@ -74,24 +93,7 @@ def _is_valid_pdf_text_block(block: dict[str, Any]) -> bool:
visible_content = content if isinstance(content, str) else ""
if not visible_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
+ return _has_valid_pdf_text_lines(block.get("lines")) or _is_valid_pdf_text_bbox(block.get("bbox"))
def _natural_language_spans(content: str) -> list[dict[str, Any]]:
@@ -108,7 +110,7 @@ def _natural_language_spans(content: str) -> list[dict[str, Any]]:
def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
- """清理 PDF block 元数据、规范公式,并过滤正文或行框无效的文本块。"""
+ """清理 PDF 元数据和公式,修复缺失行框,仅过滤空正文或完全缺少可用几何的文本块。"""
for page_idx, page_model_list in enumerate(model_list):
for block_idx, block in enumerate(page_model_list):
raw_type = block.get("type")
@@ -141,10 +143,26 @@ def _normalize_pdf_model_list(model_list: list[list[dict[str, Any]]]) -> None:
block["content"] = spans
else:
block["content"] = 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)
- ]
+ normalized_blocks: list[dict[str, Any]] = []
+ bbox_fallback_count = 0
+ dropped_count = 0
+ for block in page_model_list:
+ if block.get("type") in LINE_METADATA_BLOCK_TYPES:
+ if not _is_valid_pdf_text_block(block):
+ dropped_count += 1
+ continue
+ if not _has_valid_pdf_text_lines(block.get("lines")):
+ # 公式遮罩可能使 OCR 检测不到行;保留 VLM 正文,并以块框提供粗粒度几何。
+ block["lines"] = [{"bbox": list(block["bbox"])}]
+ bbox_fallback_count += 1
+ normalized_blocks.append(block)
+ page_model_list[:] = normalized_blocks
+ if bbox_fallback_count or dropped_count:
+ logger.warning(
+ "PDF text block normalization: page_idx={}, bbox_fallback={}, dropped={}",
+ page_idx,
+ bbox_fallback_count,
+ dropped_count,
+ )
# 统一在回填、Span 构造及宿主元数据清理完成后调用共享实现。
normalize_pdf_model_text(model_list)
diff --git a/tests/unittest/test_pdf_analyze_visual_blocks.py b/tests/unittest/test_pdf_analyze_visual_blocks.py
index 08efaccb..e555e6c7 100644
--- a/tests/unittest/test_pdf_analyze_visual_blocks.py
+++ b/tests/unittest/test_pdf_analyze_visual_blocks.py
@@ -972,11 +972,11 @@ def test_normalize_pdf_model_list_rejects_unclassified_vlm_title() -> None:
],
],
)
-def test_normalize_pdf_model_list_removes_six_text_types_with_invalid_lines(
+def test_normalize_pdf_model_list_removes_six_text_types_without_usable_geometry(
block_type: str,
invalid_lines: object,
) -> None:
- """验证包括 ref_text 在内的六类文本块遇到非法行框时按 fail-closed 规则删除。"""
+ """验证包括 ref_text 在内的六类文本块既无合法行框、也无块框时仍然删除。"""
model_list = [[{"type": block_type, "content": "valid", "lines": invalid_lines}]]
diff --git a/tests/unittest/test_pdf_layout_integration.py b/tests/unittest/test_pdf_layout_integration.py
index 2848ab72..958f0722 100644
--- a/tests/unittest/test_pdf_layout_integration.py
+++ b/tests/unittest/test_pdf_layout_integration.py
@@ -41,13 +41,13 @@ def _source() -> bytes:
return rotated.getvalue()
-def _model_pages(effort: str) -> list[list[dict]]:
- """按上游契约提供 Flash 空公式及其他档位公式文本,几何采集与导出仍走真实实现。"""
+def _model_pages(effort: str, leading_text_content: str) -> list[list[dict]]:
+ """提供空正文或缺行框文本及各档位公式,几何采集与导出仍走真实实现。"""
image = BytesIO()
Image.new("RGB", (80, 20), "black").save(image, "PNG")
return [
[
- {"type": "text", "content": "invalid without line geometry", "bbox": (0.1, 0.1, 0.2, 0.2), "angle": 270},
+ {"type": "text", "content": leading_text_content, "bbox": (0.1, 0.1, 0.2, 0.2), "angle": 270},
{
"type": "equation",
"bbox": (0.1, 0.1, 0.9, 0.2),
@@ -64,14 +64,16 @@ def _model_pages(effort: str) -> list[list[dict]]:
@pytest.mark.parametrize("effort,tier", [("flash", "flash"), ("medium", "basic"), ("high", "standard"), ("xhigh", "advanced")])
@pytest.mark.parametrize("parse_mode", ["txt", "ocr"])
@pytest.mark.parametrize("asynchronous", [False, True])
[email protected]("leading_text_content", ["", "retained without line geometry"])
def test_all_tiers_preserve_geometry_to_pdf(
monkeypatch: pytest.MonkeyPatch,
effort: str,
tier: str,
parse_mode: str,
asynchronous: bool,
+ leading_text_content: str,
) -> None:
- """同一结果经过完整同步/异步门面后保留源页映射,并可显式按原布局导出。"""
+ """验证文本被删除或兜底保留后,同步/异步各档位的旋转索引、页映射及导出仍正确。"""
events = []
def prepare(state: object, data: bytes, requested_effort: str, mode: str, vlm_config: object) -> None:
@@ -84,7 +86,7 @@ def test_all_tiers_preserve_geometry_to_pdf(
def windows(*args: object, **kwargs: object) -> list[list[dict]]:
"""返回独立 raw pages,模拟三个窗口最终汇总的结果。"""
- return deepcopy(_model_pages(effort))
+ return deepcopy(_model_pages(effort, leading_text_content))
async def async_windows(*args: object, **kwargs: object) -> list[list[dict]]:
"""覆盖原生异步分支,不把异步 API 误测为纯同步代理。"""
@@ -116,9 +118,15 @@ def test_all_tiers_preserve_geometry_to_pdf(
{"page_idx": idx, "width_pt": width, "height_pt": height}
for idx, (width, height) in zip([1, 4, 5], [(400, 600), (480, 320), (600, 400)], strict=True)
]
- expected[0]["image_rotations"] = {"0": 90}
+ equation_index = 1 if leading_text_content else 0
+ expected[0]["image_rotations"] = {str(equation_index): 90}
assert middle.extensions["docvortex_layout"]["pages"] == model.extensions["docvortex_layout"]["pages"] == expected
- assert model.pages[0][0]["content"] == ("" if effort == "flash" else "x^2")
+ assert len(model.pages[0]) == equation_index + 1
+ if leading_text_content:
+ assert model.pages[0][0]["content"] == [{"type": "text", "content": leading_text_content}]
+ assert model.pages[0][0]["lines"] == [{"bbox": [0.1, 0.1, 0.2, 0.2]}]
+ assert model.pages[0][equation_index]["content"] == ("" if effort == "flash" else "x^2")
+ assert model.pages[2][0]["content"] == [{"type": "text", "content": "last page"}]
assert ModelJson.from_json(model.to_json()).to_json() == model.to_json()
assert MiddleJson.from_json(middle.to_json()).to_json() == middle.to_json()
payload = render(middle, RenderFormat.PDF, options=PdfRenderOptions(layout=PdfLayout.ORIGINAL))
@@ -127,6 +135,7 @@ def test_all_tiers_preserve_geometry_to_pdf(
page.extract_text() for page in PdfReader(BytesIO(direct)).pages
]
assert [tuple(page.mediabox)[2:] for page in PdfReader(BytesIO(payload)).pages] == [(400, 600), (480, 320), (600, 400)]
+ assert "last page" in PdfReader(BytesIO(payload)).pages[2].extract_text()
if asynchronous and effort in {"high", "xhigh"}:
assert events == ["native_async"]
diff --git a/tests/unittest/test_pdf_text_block_normalization.py b/tests/unittest/test_pdf_text_block_normalization.py
new file mode 100644
index 00000000..cace8fea
--- /dev/null
+++ b/tests/unittest/test_pdf_text_block_normalization.py
@@ -0,0 +1,195 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""覆盖 Issue #5565:行级几何缺失不能删除已有正文和块框的文本。"""
+
+from __future__ import annotations
+
+from copy import deepcopy
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+
+from mineru.backend.analysis.pdf import normalization
+from mineru.types import RAW_CAPTION, RAW_FOOTNOTE, RAW_PHONETIC, BlockType
+
+
+ "block_type",
+ [BlockType.TEXT, BlockType.REF_TEXT, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE, RAW_CAPTION, RAW_FOOTNOTE],
+)
+ "invalid_lines",
+ [
+ None,
+ [],
+ "invalid",
+ {"bbox": [0.1, 0.2, 0.8, 0.4]},
+ [None],
+ [{}],
+ [{"bbox": [0.1, 0.2, 0.8]}],
+ [{"bbox": [True, 0.2, 0.8, 0.4]}],
+ [{"bbox": [0.1, 0.2, float("nan"), 0.4]}],
+ [{"bbox": [0.1, 0.2, float("inf"), 0.4]}],
+ [{"bbox": [-0.1, 0.2, 0.8, 0.4]}],
+ [{"bbox": [0.1, 0.2, 1.1, 0.4]}],
+ [{"bbox": [0.8, 0.2, 0.8, 0.4]}],
+ [{"bbox": [0.1, 0.4, 0.8, 0.2]}],
+ [{"bbox": [0.1, 0.2, 0.8, 0.3]}, {"bbox": [0.1, 0.4, 0.1, 0.5]}],
+ ],
+)
+def test_normalization_repairs_invalid_lines_from_block_bbox(
+ block_type: str, invalid_lines: object, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """验证六类文本的缺失或非法行框均可由合法块框兜底,且不覆盖内容。"""
+ warning = MagicMock()
+ monkeypatch.setattr(normalization.logger, "warning", warning)
+ bbox = [0.1, 0.2, 0.8, 0.4]
+ block = {"type": block_type, "bbox": bbox, "content": "已识别的正文", "lines": invalid_lines}
+ page = [block]
+ pages = [page]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages[0] is page
+ assert page == [block]
+ assert page[0] is block
+ assert block["content"] == [{"type": "text", "content": "已识别的正文"}]
+ assert block["lines"] == [{"bbox": bbox}]
+ assert block["lines"][0]["bbox"] is not bbox
+ warning.assert_called_once_with("PDF text block normalization: page_idx={}, bbox_fallback={}, dropped={}", 0, 1, 0)
+
+
[email protected]("bbox", [[0, 0, 1, 1], (0.1, 0.2, 0.8, 0.4)])
+def test_normalization_repairs_missing_lines_and_phonetic_type(bbox: object) -> None:
+ """验证未提供 lines 的文本与转换后的音标块均能使用边界合法的块框。"""
+ block = {"type": RAW_PHONETIC, "bbox": bbox, "content": "phonetic"}
+ pages = [[block]]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages == [[block]]
+ assert block["type"] == BlockType.TEXT
+ assert block["lines"] == [{"bbox": list(bbox)}]
+
+
+ "invalid_bbox",
+ [
+ None,
+ [],
+ "0 0 1 1",
+ [0, 0, 1],
+ [0, 0, 1, 1, 1],
+ [False, 0, 1, 1],
+ [0, 0, "1", 1],
+ [0, 0, float("nan"), 1],
+ [0, 0, float("inf"), 1],
+ [0, float("-inf"), 1, 1],
+ [0, 0, 10**400, 1],
+ [-0.1, 0, 1, 1],
+ [0, 0, 1.1, 1],
+ [0.5, 0, 0.5, 1],
+ [0, 0.5, 1, 0.5],
+ [0.8, 0, 0.2, 1],
+ [0, 0.8, 1, 0.2],
+ ],
+)
+def test_normalization_still_discards_text_without_usable_geometry(
+ invalid_bbox: object, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """验证没有合法行框或块框时仍删除文本,并按页报告丢弃数量。"""
+ warning = MagicMock()
+ monkeypatch.setattr(normalization.logger, "warning", warning)
+ pages = [[{"type": BlockType.TEXT, "content": "正文", "bbox": invalid_bbox, "lines": []}]]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages == [[]]
+ warning.assert_called_once_with("PDF text block normalization: page_idx={}, bbox_fallback={}, dropped={}", 0, 0, 1)
+
+
+ "content",
+ [None, "", " \n ", [], ["invalid"], [{"type": "text", "content": " "}], [{"type": "equation_inline", "content": ""}]],
+)
+def test_normalization_does_not_rescue_empty_content(content: object) -> None:
+ """验证合法块框不能保留空正文或无可见内容的 Span。"""
+ pages = [[{"type": BlockType.TEXT, "bbox": [0, 0, 1, 1], "content": content, "lines": []}]]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages == [[]]
+
+
[email protected]("bbox", [None, [0.8, 0.2, 0.1, 0.4], [0.1, 0.2, 0.8, 0.4]])
+def test_normalization_keeps_valid_lines_unchanged(bbox: object, monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证已有完整合法行框时不重建行框,也不额外改变原有块框校验行为。"""
+ warning = MagicMock()
+ monkeypatch.setattr(normalization.logger, "warning", warning)
+ lines = [{"bbox": [0.1, 0.2, 0.8, 0.3]}, {"bbox": (0.1, 0.3, 0.8, 0.4)}]
+ block = {"type": BlockType.TEXT, "content": "正文", "bbox": bbox, "lines": lines}
+ pages = [[block]]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages == [[block]]
+ assert block["lines"] is lines
+ warning.assert_not_called()
+
+
+def test_normalization_preserves_equation_dense_page(monkeypatch: pytest.MonkeyPatch) -> None:
+ """复现十六个编号公式块仅两个有行框的页面,确保顺序、正文与对象均不丢失。"""
+ warning = MagicMock()
+ monkeypatch.setattr(normalization.logger, "warning", warning)
+ texts: list[dict[str, Any]] = []
+ for index, number in enumerate(range(62, 78)):
+ bbox = [0.1, 0.05 + index * 0.05, 0.8, 0.09 + index * 0.05]
+ texts.append(
+ {
+ "type": BlockType.TEXT,
+ "bbox": bbox,
+ "content": f"{number}. \\(x^2 + {number} = 0\\)",
+ "lines": [{"bbox": list(bbox)}] if number in {63, 77} else [],
+ }
+ )
+ header = {"type": BlockType.HEADER, "content": "习题"}
+ container = {"type": BlockType.LIST, "bbox": [0.1, 0.05, 0.8, 0.14]}
+ page_number = {"type": BlockType.PAGE_NUMBER, "content": "11"}
+ page = [header, container, *texts, page_number]
+ pages = [page]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages[0] is page
+ assert len(page) == 19
+ assert page == [header, container, *texts, page_number]
+ for number, block in zip(range(62, 78), texts, strict=True):
+ assert block["content"] == [
+ {"type": "text", "content": f"{number}. "},
+ {"type": "equation_inline", "content": f"x^2 + {number} = 0"},
+ ]
+ assert block["lines"] == [{"bbox": block["bbox"]}]
+ warning.assert_called_once_with("PDF text block normalization: page_idx={}, bbox_fallback={}, dropped={}", 0, 14, 0)
+
+ snapshot = deepcopy(pages)
+ warning.reset_mock()
+ normalization._normalize_pdf_model_list(pages)
+ assert pages == snapshot
+ warning.assert_not_called()
+
+
+def test_normalization_preserves_formula_spans_and_summarizes_each_page(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证纯公式 Span 不是空正文,非文本块不参与兜底,异常按所在页汇总。"""
+ warning = MagicMock()
+ monkeypatch.setattr(normalization.logger, "warning", warning)
+ content = [{"type": "equation_inline", "content": "x^2"}]
+ recovered = {"type": BlockType.TEXT, "content": content, "bbox": [0, 0, 1, 1]}
+ equation = {"type": BlockType.EQUATION, "content": "", "lines": []}
+ pages = [[equation], [recovered, {"type": BlockType.TEXT, "content": "", "bbox": [0, 0, 1, 1]}]]
+
+ normalization._normalize_pdf_model_list(pages)
+
+ assert pages == [[equation], [recovered]]
+ assert recovered["content"] == content
+ assert "lines" not in pages[0][0] or pages[0][0]["lines"] == []
+ warning.assert_called_once_with("PDF text block normalization: page_idx={}, bbox_fallback={}, dropped={}", 1, 1, 1)