Skip to content

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

feat: enhance dehyphenation logic for line boundary handling and improve style application

myhloli034c5c442d75
diff --git a/mineru/utils/pdf_text_styles.py b/mineru/utils/pdf_text_styles.py
index 3d6db736..faecb131 100644
--- a/mineru/utils/pdf_text_styles.py
+++ b/mineru/utils/pdf_text_styles.py
@@ -1298,6 +1298,59 @@ def _ranges_from_line_projection(
return output
+def _lines_form_dehyphenated_continuation(
+ line: PDFTextEvidenceLine,
+ next_line: PDFTextEvidenceLine | None,
+) -> bool:
+ """判断相邻物理行是否符合正文回填使用的英文断词规则。"""
+
+ return bool(
+ next_line is not None
+ and next_line.source_index == line.source_index + 1
+ and line.text
+ and next_line.text
+ and is_hyphen_at_line_end(line.text)
+ and next_line.text[0].islower()
+ )
+
+
+def _match_line_without_terminal_hyphen(
+ projected_text: str,
+ line: PDFTextEvidenceLine,
+ next_line: PDFTextEvidenceLine | None,
+ start: int,
+) -> _LineProjectionMatch | None:
+ """将 block 已删除的行末断词符映射为空洞,歧义时拒绝匹配。"""
+
+ if not _lines_form_dehyphenated_continuation(line, next_line):
+ return None
+ candidate = line.text[:-1]
+ next_first_char = next_line.text[0] if next_line is not None else ""
+ occurrences = [
+ position
+ for position in _all_occurrences(projected_text, candidate, start)
+ if (
+ position + len(candidate) < len(projected_text)
+ and projected_text[position + len(candidate)] == next_first_char
+ )
+ ]
+ if len(occurrences) != 1:
+ logger.debug(
+ "Skip ambiguous PDF text dehyphenation mapping: "
+ f"line={line.text!r}, occurrences={len(occurrences)}"
+ )
+ return None
+ position = occurrences[0]
+ return _LineProjectionMatch(
+ start=position,
+ end=position + len(candidate),
+ source_to_projected=(
+ *range(position, position + len(candidate)),
+ None,
+ ),
+ )
+
+
def _match_style_ranges(
projected: Sequence[_ProjectedChar],
lines: Sequence[PDFTextStyleLine],
@@ -1307,7 +1360,8 @@ def _match_style_ranges(
projected_text = "".join(token.value for token in projected)
output: list[PDFTextStyleRange] = []
cursor = 0
- for line in lines:
+ for line_index, line in enumerate(lines):
+ next_line = lines[line_index + 1] if line_index + 1 < len(lines) else None
line_start = projected_text.find(line.text, cursor)
if line_start >= 0:
output.extend(
@@ -1329,6 +1383,18 @@ def _match_style_ranges(
output.extend(_ranges_from_line_projection(line, formula_match))
cursor = formula_match.end
continue
+ dehyphenated_match = _match_line_without_terminal_hyphen(
+ projected_text,
+ line,
+ next_line,
+ cursor,
+ )
+ if dehyphenated_match is not None:
+ output.extend(
+ _ranges_from_line_projection(line, dehyphenated_match)
+ )
+ cursor = dehyphenated_match.end
+ continue
skipped_ranges: list[PDFTextStyleRange] = []
for style_range in line.style_ranges:
position = _resolve_fallback_occurrence(
@@ -1531,14 +1597,7 @@ def _link_lines_form_dehyphenated_continuation(
) -> bool:
"""判断相邻同 href 链接行是否符合文本回填的英文断词规则。"""
- if (
- next_line is None
- or next_line.source_index != line.source_index + 1
- or not line.text
- or not next_line.text
- or not is_hyphen_at_line_end(line.text)
- or not next_line.text[0].islower()
- ):
+ if not _lines_form_dehyphenated_continuation(line, next_line):
return False
tail_targets = {
link_range.target
@@ -1563,30 +1622,11 @@ def _match_link_line_without_terminal_hyphen(
if not _link_lines_form_dehyphenated_continuation(line, next_line):
return None
- candidate = line.text[:-1]
- next_first_char = next_line.text[0] if next_line is not None else ""
- occurrences = [
- position
- for position in _all_occurrences(projected_text, candidate, start)
- if (
- position + len(candidate) < len(projected_text)
- and projected_text[position + len(candidate)] == next_first_char
- )
- ]
- if len(occurrences) != 1:
- logger.debug(
- "Skip ambiguous PDF hyperlink dehyphenation mapping: "
- f"line={line.text!r}, occurrences={len(occurrences)}"
- )
- return None
- position = occurrences[0]
- return _LineProjectionMatch(
- start=position,
- end=position + len(candidate),
- source_to_projected=(
- *range(position, position + len(candidate)),
- None,
- ),
+ return _match_line_without_terminal_hyphen(
+ projected_text,
+ line,
+ next_line,
+ start,
)
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 2017944c..5ff2d83c 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -554,11 +554,12 @@ def test_demo2_rejects_figure_grid_and_keeps_two_real_tables() -> None:
def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() -> None:
- """验证 demo2 首页正文自然聚合,六个 Figure 1 标签单块且 caption 独立。"""
+ """验证 demo2 首页正文、Abstract 粗体和 Figure 1 图文归属保持正确。"""
page = _native_model_list("demo2.pdf")[0]
graphic_block = next(block for block in page if "Left camera" in block["content"])
caption_block = next(block for block in page if "Figure 1:" in block["content"])
+ abstract_block = next(block for block in page if _visible_content(block).startswith("Abstract—Stereo"))
assert len(page) == 16
assert not [block for block in page if block["type"] == "table"]
@@ -574,6 +575,28 @@ def test_demo2_page1_forms_sixteen_blocks_and_keeps_figure_caption_separate() ->
assert graphic_block["bbox"] == [0.516, 0.311, 0.913, 0.442]
copyright_block = next(block for block in page if block["content"].startswith("978-1-4673-5208-6"))
assert copyright_block["type"] == "footer"
+ assert abstract_block["content"].startswith('<text style="bold">Abstract—Stereo')
+ assert abstract_block["content"].endswith("Middlebury stereo performance benchmark.</text>")
+ assert abstract_block["content"].count('<text style="bold">') == 1
+ assert "de<text" not in abstract_block["content"]
+
+ page_markdown = render_markdown(
+ MiddleJson(
+ pages=model_json_to_pages(_model_json([page], page_index_map=[0])),
+ is_full_document=False,
+ file_suffix="pdf",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+ )
+ abstract_markdown = next(
+ paragraph
+ for paragraph in page_markdown.split("\n\n")
+ if paragraph.startswith("**Abstract—Stereo")
+ )
+ assert abstract_markdown.endswith("Middlebury stereo performance benchmark.**")
+ assert abstract_markdown.count("**") == 2
def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> None:
diff --git a/tests/unittest/test_pdf_text_styles.py b/tests/unittest/test_pdf_text_styles.py
index 2275fad3..33245ec9 100644
--- a/tests/unittest/test_pdf_text_styles.py
+++ b/tests/unittest/test_pdf_text_styles.py
@@ -1335,6 +1335,107 @@ def test_applies_style_to_plain_content_and_duplicate_second_line() -> None:
assert blocks[0]["content"] == 'deleted <text style="strikethrough">deleted</text>'
+def test_applies_style_across_dehyphenated_line_boundary() -> None:
+ """验证行末断词符被正文回填删除后,两行粗体仍合并为完整区间。"""
+
+ blocks = [
+ {
+ "type": BlockType.TEXT,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": "Abstract—Stereo matching was designed for sequences.",
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ "Abstract—Stereomatchingwasde-",
+ (PDFTextStyleRange(0, len("Abstract—Stereomatchingwasde-"), ("bold",)),),
+ 10,
+ ),
+ PDFTextStyleLine(
+ (10.0, 30.0, 90.0, 40.0),
+ "signedforsequences.",
+ (PDFTextStyleRange(0, len("signedforsequences."), ("bold",)),),
+ 11,
+ ),
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == (
+ '<text style="bold">Abstract—Stereo matching was designed for sequences.</text>'
+ )
+
+
+ ("content", "first_text", "second_text", "second_source_index", "expected"),
+ [
+ (
+ "inter-national",
+ "inter-",
+ "national",
+ 21,
+ '<text style="bold">inter-national</text>',
+ ),
+ (
+ "inter-National",
+ "inter-",
+ "National",
+ 21,
+ '<text style="bold">inter-National</text>',
+ ),
+ (
+ "international",
+ "inter-",
+ "national",
+ 22,
+ 'inter<text style="bold">national</text>',
+ ),
+ (
+ "international international",
+ "inter-",
+ "national",
+ 21,
+ 'inter<text style="bold">national</text> international',
+ ),
+ ],
+)
+def test_style_dehyphenation_preserves_safe_boundaries(
+ content: str,
+ first_text: str,
+ second_text: str,
+ second_source_index: int,
+ expected: str,
+) -> None:
+ """验证保留连字符、大小写、非相邻行和重复候选均不会错误桥接。"""
+
+ blocks = [
+ {
+ "type": BlockType.TEXT,
+ "bbox": [0.0, 0.0, 1.0, 1.0],
+ "content": content,
+ }
+ ]
+ lines = [
+ PDFTextStyleLine(
+ (10.0, 10.0, 90.0, 20.0),
+ first_text,
+ (PDFTextStyleRange(0, len(first_text), ("bold",)),),
+ 20,
+ ),
+ PDFTextStyleLine(
+ (10.0, 30.0, 90.0, 40.0),
+ second_text,
+ (PDFTextStyleRange(0, len(second_text), ("bold",)),),
+ second_source_index,
+ ),
+ ]
+
+ apply_pdf_text_styles(blocks, lines, (100.0, 100.0))
+
+ assert blocks[0]["content"] == expected
+
+
def test_same_visual_row_style_runs_follow_source_order_despite_bbox_jitter() -> None:
"""验证同行 run 的细微顶边抖动不会把后方粗体片段提前映射。"""