Skip to content

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

feat: enhance text line boundary resolution to support URL continuation and improve handling of line breaks

myhloli08be5fc9d4c0
diff --git a/mineru/backend/analysis/pdf/text/content.py b/mineru/backend/analysis/pdf/text/content.py
index 93b96877..2973bc3d 100644
--- a/mineru/backend/analysis/pdf/text/content.py
+++ b/mineru/backend/analysis/pdf/text/content.py
@@ -250,12 +250,10 @@ def _lines_to_block_content(lines: list[_AnalyzeLine], block_type: str) -> str:
block_language = detect_lang(text_for_language)
content_parts = [rendered_lines[0]]
for line_idx in range(1, len(rendered_lines)):
- current_type, current_content = content_lines[line_idx][0]
- next_starts_with_lowercase = current_type == ContentType.TEXT and bool(current_content) and current_content[0].islower()
content_parts[-1], separator = resolve_text_line_boundary(
content_parts[-1],
block_language=block_language,
- next_starts_with_lowercase=next_starts_with_lowercase,
+ next_content=rendered_lines[line_idx],
)
content_parts.extend([separator, rendered_lines[line_idx]])
return "".join(content_parts).strip()
diff --git a/mineru/model/flash/native_pdf/tables.py b/mineru/model/flash/native_pdf/tables.py
index bd264443..c758da38 100644
--- a/mineru/model/flash/native_pdf/tables.py
+++ b/mineru/model/flash/native_pdf/tables.py
@@ -2167,7 +2167,7 @@ def _merge_table_annotation_content(line_texts: list[str]) -> str:
processed_previous, separator = resolve_text_line_boundary(
content_parts[-1],
block_language=block_language,
- next_starts_with_lowercase=current_line[0].islower(),
+ next_content=current_line,
)
content_parts[-1] = processed_previous
content_parts.extend([separator, current_line])
diff --git a/mineru/model/flash/native_pdf/text_blocks.py b/mineru/model/flash/native_pdf/text_blocks.py
index 1c7d99d4..d33ab6c7 100644
--- a/mineru/model/flash/native_pdf/text_blocks.py
+++ b/mineru/model/flash/native_pdf/text_blocks.py
@@ -2712,7 +2712,7 @@ def _merge_text_line_content(line_texts: Sequence[str]) -> str:
processed_previous, separator = resolve_text_line_boundary(
content_parts[-1],
block_language=block_language,
- next_starts_with_lowercase=current_line[0].islower(),
+ next_content=current_line,
)
content_parts[-1] = processed_previous
content_parts.extend([separator, current_line])
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 0041579e..d776e715 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -425,7 +425,7 @@ def _render_algorithm_html(content: str, delimiters: LatexDelimitersConfig) -> s
for match in _ALGORITHM_TOKEN_RE.finditer(content):
plain = content[cursor : match.start()]
if plain:
- parts.append(html.escape(plain, quote=False))
+ parts.append(plain)
previous_was_equation = False
script_tag = match.group("script_tag")
if script_tag is not None:
@@ -437,12 +437,10 @@ def _render_algorithm_html(content: str, delimiters: LatexDelimitersConfig) -> s
if latex:
if previous_was_equation and parts and not parts[-1].endswith((" ", "\n", "\t")):
parts.append(" ")
- parts.append(
- f"{delimiters.inline.left}{html.escape(latex, quote=False)}{delimiters.inline.right}"
- )
+ parts.append(f"{delimiters.inline.left}{latex}{delimiters.inline.right}")
previous_was_equation = True
cursor = match.end()
- parts.append(html.escape(content[cursor:], quote=False))
+ parts.append(content[cursor:])
body = "".join(parts)
return (
'<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n'
diff --git a/mineru/render/utils/inline.py b/mineru/render/utils/inline.py
index cfd81bb7..01df1181 100644
--- a/mineru/render/utils/inline.py
+++ b/mineru/render/utils/inline.py
@@ -216,12 +216,11 @@ def _join_inline_node_sequences(previous: list[InlineNode], current: list[Inline
first_text.content = first_text.content.lstrip()
language = _detect_boundary_language(f"{previous_visible}{current_visible}")
- next_starts_lowercase = current_visible[0].islower()
if last_text is not None:
processed, separator = resolve_text_line_boundary(
last_text.content,
block_language=language,
- next_starts_with_lowercase=next_starts_lowercase,
+ next_content=current_visible,
)
last_text.content = processed
else:
diff --git a/mineru/render/utils/markdown_table.py b/mineru/render/utils/markdown_table.py
index 372ec132..b5577144 100644
--- a/mineru/render/utils/markdown_table.py
+++ b/mineru/render/utils/markdown_table.py
@@ -13,6 +13,7 @@ from mineru.config import LatexDelimitersConfig
from mineru.render.utils.assets import prefix_html_image_sources
_INLINE_EQ_RE = re.compile(r"<eq>(?P<latex>.*?)</eq>", re.IGNORECASE | re.DOTALL)
+_GFM_FORMULA_PIPE_RE = re.compile(r"(?P<slashes>\\*)\|")
_COMPLEX_CELL_TAGS = {
"blockquote",
"div",
@@ -178,7 +179,12 @@ def _render_inline_children(node: Tag, delimiters: LatexDelimitersConfig) -> str
parts.append(_render_inline_code(child.get_text()))
elif name == "eq":
latex = html.unescape(child.get_text()).strip()
- parts.append(f"{delimiters.inline.left}{latex}{delimiters.inline.right}" if latex else "")
+ escaped_latex = _escape_gfm_formula_pipes(latex)
+ parts.append(
+ f"{delimiters.inline.left}{escaped_latex}{delimiters.inline.right}"
+ if escaped_latex
+ else ""
+ )
elif name == "a":
href = str(child.get("href", "")).strip()
parts.append(f"[{rendered}]({_escape_link_url(href)})" if href else rendered)
@@ -202,6 +208,17 @@ def _render_inline_code(content: str) -> str:
return f"{fence}{_escape_cell_text(content)}{fence}"
+def _escape_gfm_formula_pipes(latex: str) -> str:
+ """转义公式竖线,并保证 GFM 解析后恢复原始反斜杠数量。"""
+
+ def _replace(match: re.Match[str]) -> str:
+ """把竖线前 n 个反斜杠扩展为 2n+1 个 Markdown 反斜杠。"""
+ slash_count = len(match.group("slashes"))
+ return "\\" * (2 * slash_count + 1) + "|"
+
+ return _GFM_FORMULA_PIPE_RE.sub(_replace, latex)
+
+
def _escape_link_url(url: str) -> str:
"""转义 GFM 表格链接目标中的空格、反斜杠和括号。"""
return (
diff --git a/mineru/utils/text_utils.py b/mineru/utils/text_utils.py
index f83e8961..04bb01a9 100644
--- a/mineru/utils/text_utils.py
+++ b/mineru/utils/text_utils.py
@@ -11,6 +11,14 @@ CJK_LANGS = frozenset({"zh", "ja", "ko"})
LINE_END_HYPHEN_CHARS = "-\u00ad\u2010\u2011\u2043"
LINE_END_HYPHEN_RE = re.compile(rf"[A-Za-z]+[{re.escape(LINE_END_HYPHEN_CHARS)}]\s*$")
+# 仅识别带协议或 www 前缀、且一直延伸到行末的 URL token,避免普通西文误判为链接。
+_URL_TOKEN_AT_LINE_END_RE = re.compile(
+ r"(?<![A-Za-z0-9])(?:(?:https?|ftp)://|www\.)[^\s<>]+$",
+ re.IGNORECASE,
+)
+# 这些结构字符出现在下一物理行行首时,可以保守地判定为上一行 URL 的延续。
+_URL_CONTINUATION_PREFIX_CHARS = frozenset("/?#&=")
+
def is_hyphen_at_line_end(line: str) -> bool:
"""判断文本行是否以英文单词的跨行断词符结尾。
@@ -20,25 +28,39 @@ def is_hyphen_at_line_end(line: str) -> bool:
return bool(LINE_END_HYPHEN_RE.search(line))
+def _is_url_line_continuation(previous_content: str, next_content: str) -> bool:
+ """判断下一物理行是否以明确的 URL 结构字符延续上一行末尾链接。"""
+ stripped_next = next_content.lstrip()
+ return bool(
+ stripped_next
+ and stripped_next[0] in _URL_CONTINUATION_PREFIX_CHARS
+ and _URL_TOKEN_AT_LINE_END_RE.search(previous_content)
+ )
+
+
def resolve_text_line_boundary(
previous_content: str,
*,
block_language: str,
- next_starts_with_lowercase: bool,
+ next_content: str,
) -> tuple[str, str]:
"""返回处理后的上一行内容和本次物理行边界分隔符。
- CJK 文本直接连接物理行;普通西文行插入一个空格。西文行末如果是合法的
- hyphen,则始终直接连接下一行,并仅在下一行以小写字母开头时删除 hyphen。
+ CJK 文本直接连接物理行;明确的 URL 结构延续也直接连接;普通西文行插入
+ 一个空格。西文行末如果是合法的 hyphen,则始终直接连接下一行,并仅在
+ 下一行以小写字母开头时删除 hyphen。
"""
processed_content = previous_content.rstrip()
if not processed_content:
return "", ""
if block_language in CJK_LANGS:
return processed_content, ""
+ if _is_url_line_continuation(processed_content, next_content):
+ return processed_content, ""
if not is_hyphen_at_line_end(processed_content):
return processed_content, " "
- if next_starts_with_lowercase:
+ stripped_next = next_content.lstrip()
+ if stripped_next and stripped_next[0].islower():
return processed_content[:-1], ""
return processed_content, ""
diff --git a/tests/unittest/test_flash_pdf_samples.py b/tests/unittest/test_flash_pdf_samples.py
index 6db75ba2..d7649296 100644
--- a/tests/unittest/test_flash_pdf_samples.py
+++ b/tests/unittest/test_flash_pdf_samples.py
@@ -343,8 +343,8 @@ def test_demo2_pages2_to6_restore_paragraphs_formulas_and_reading_order() -> Non
assert "Fp =" in formula7
assert "otherwise" in formula7
assert not [content for content in page3_contents if content.strip() in {"2", "p", "otherwise", "(7)"}]
- assert "available at http://mc2.unl.edu/current-research" in page3_contents[-1]
- assert "/image-processing/. Figure 2" in page3_contents[-1]
+ assert "available at http://mc2.unl.edu/current-research/image-processing/. Figure 2" in page3_contents[-1]
+ assert "current-research /image-processing" not in page3_contents[-1]
page4_contents = [block["content"] for block in model_list[3]]
figure2 = next(content for content in page4_contents if content.startswith("Figure 2:"))
diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.py
index adf0185c..32c714fa 100644
--- a/tests/unittest/test_markdown_render.py
+++ b/tests/unittest/test_markdown_render.py
@@ -408,8 +408,8 @@ def test_code_uses_language_and_dynamic_fence() -> None:
assert rendered.endswith("```txt\nx\n```")
-def test_algorithm_preserves_whitespace_escapes_html_and_renders_formula() -> None:
- """验证算法 HTML 同时保留缩进、转义文本并支持相邻公式。"""
+def test_algorithm_preserves_whitespace_comparisons_scripts_and_formula() -> None:
+ """验证算法 HTML 原样保留缩进、比较符、上下标并支持相邻公式。"""
algorithm = CodeBlock(
type="code",
index=0,
@@ -418,7 +418,10 @@ def test_algorithm_preserves_whitespace_escapes_html_and_renders_formula() -> No
CodeBodyBlock(
type="code_body",
index=0,
- content="if <x>:\n T<sub>queue</sub><sup>2</sup> = <eq>a < b</eq><eq>c</eq>",
+ content=(
+ "if a < b and c > d:\n T<sub>queue</sub><sup>2</sup> = "
+ "<eq>a < b</eq><eq>c > d</eq>"
+ ),
)
],
)
@@ -426,7 +429,9 @@ def test_algorithm_preserves_whitespace_escapes_html_and_renders_formula() -> No
rendered = render_markdown(_middle(_page(0, algorithm)))
assert 'class="mineru-algorithm"' in rendered
- assert "if &lt;x&gt;:\n T<sub>queue</sub><sup>2</sup> = $a &lt; b$ $c$" in rendered
+ assert "if a < b and c > d:\n T<sub>queue</sub><sup>2</sup> = $a < b$ $c > d$" in rendered
+ assert "&lt;" not in rendered
+ assert "&gt;" not in rendered
def test_image_path_precedes_base64_and_visual_child_order_is_preserved() -> None:
diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.py
index 0b3d8014..7b1506e4 100644
--- a/tests/unittest/test_pdf_analyze_block_content.py
+++ b/tests/unittest/test_pdf_analyze_block_content.py
@@ -490,6 +490,19 @@ def test_text_content_keeps_natural_paragraph_joining() -> None:
assert content == "第一行第二行"
+def test_text_content_joins_structural_url_continuation_without_space() -> None:
+ """验证 PDF 内容重建不会在明确的跨行 URL 路径前插入空格。"""
+ content = text_content._lines_to_block_content(
+ _build_text_lines(
+ "Available at https://example.test/current-research",
+ "/image-processing/ for details.",
+ ),
+ BlockType.TEXT,
+ )
+
+ assert content == "Available at https://example.test/current-research/image-processing/ for details."
+
+
@pytest.mark.parametrize("block_type", [BlockType.CODE, RAW_ALGORITHM])
def test_code_content_keeps_existing_line_breaks(block_type: str) -> None:
"""验证 code/algorithm 原有的逐行拼接语义保持不变。"""
diff --git a/tests/unittest/test_render_html_table.py b/tests/unittest/test_render_html_table.py
index 2936e6d3..86d57109 100644
--- a/tests/unittest/test_render_html_table.py
+++ b/tests/unittest/test_render_html_table.py
@@ -1,3 +1,6 @@
+import markdown
+from bs4 import BeautifulSoup
+
from mineru.config import LatexDelimitersConfig
from mineru.render.utils.markdown_table import format_embedded_html, render_html_table
@@ -32,6 +35,29 @@ def test_render_html_table_preserves_supported_inline_markup() -> None:
)
+def test_render_html_table_escapes_formula_pipes_without_changing_latex() -> None:
+ """验证 GFM 源码转义公式竖线,Markdown 解析后恢复原始 LaTeX。"""
+ formulas = [
+ r"\left|x\right|",
+ r"\|x\|",
+ r"\begin{array}{c|c}x\end{array}",
+ ]
+ rows = "".join(
+ f"<tr><td>F{index}</td><td><eq>{formula}</eq></td><td>ok</td></tr>"
+ for index, formula in enumerate(formulas, start=1)
+ )
+ html = f"<table><tr><th>Name</th><th>Formula</th><th>Note</th></tr>{rows}</table>"
+
+ rendered = render_html_table(html, asset_base_url="", delimiters=DELIMITERS)
+ assert rendered is not None
+ parsed = BeautifulSoup(markdown.markdown(rendered, extensions=["tables"]), "html.parser")
+ parsed_rows = parsed.find_all("tr")
+
+ assert [len(row.find_all(["th", "td"], recursive=False)) for row in parsed_rows] == [3, 3, 3, 3]
+ assert [row.find_all("td", recursive=False)[1].get_text() for row in parsed_rows[1:]] == [
+ f"${formula}$" for formula in formulas
+ ]
+
def test_render_html_table_falls_back_for_span_attribute_even_when_value_is_one() -> None:
"""验证只要显式出现 rowspan/colspan 就按复杂 HTML 输出。"""
html = '<table><tr><td colspan="1">A</td></tr></table>'
diff --git a/tests/unittest/test_text_utils.py b/tests/unittest/test_text_utils.py
new file mode 100644
index 00000000..12002f0b
--- /dev/null
+++ b/tests/unittest/test_text_utils.py
@@ -0,0 +1,70 @@
+import pytest
+
+from mineru.utils.text_utils import resolve_text_line_boundary
+
+
+ ("previous_content", "next_content", "block_language", "expected"),
+ [
+ pytest.param(
+ "See https://example.test/current-research",
+ "/image-processing/",
+ "en",
+ "See https://example.test/current-research/image-processing/",
+ id="url-path-continuation",
+ ),
+ pytest.param(
+ "Download from ftp://example.test/archive",
+ "?format=zip",
+ "en",
+ "Download from ftp://example.test/archive?format=zip",
+ id="url-query-continuation",
+ ),
+ pytest.param(
+ "Visit www.example.test/docs",
+ "#install",
+ "en",
+ "Visit www.example.test/docs#install",
+ id="url-fragment-continuation",
+ ),
+ pytest.param(
+ "Use https://example.test/search?key=one",
+ "&page=2",
+ "en",
+ "Use https://example.test/search?key=one&page=2",
+ id="url-query-parameter-continuation",
+ ),
+ pytest.param(
+ "Use https://example.test/search?key",
+ "=value",
+ "en",
+ "Use https://example.test/search?key=value",
+ id="url-query-value-continuation",
+ ),
+ pytest.param("input", "/ output", "en", "input / output", id="ordinary-slash-text"),
+ pytest.param(
+ "See https://example.test/complete",
+ "Figure 2 follows.",
+ "en",
+ "See https://example.test/complete Figure 2 follows.",
+ id="url-followed-by-prose",
+ ),
+ pytest.param("inter-", "national", "en", "international", id="western-hyphen"),
+ pytest.param("first line", "second line", "en", "first line second line", id="western-space"),
+ pytest.param("中文", "继续", "zh", "中文继续", id="cjk-direct-join"),
+ ],
+)
+def test_resolve_text_line_boundary_keeps_conservative_joining_rules(
+ previous_content: str,
+ next_content: str,
+ block_language: str,
+ expected: str,
+) -> None:
+ """验证 URL、普通西文、断词和 CJK 的物理行边界规则互不干扰。"""
+ processed_previous, separator = resolve_text_line_boundary(
+ previous_content,
+ block_language=block_language,
+ next_content=next_content,
+ )
+
+ assert f"{processed_previous}{separator}{next_content}" == expected