Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance URL handling to support continuation across lines and preserve independent URLs
myhlolib03ef822fe15
diff --git a/mineru/utils/text_utils.py b/mineru/utils/text_utils.pyindex 04bb01a9..9ab8baa2 100644--- a/mineru/utils/text_utils.py+++ b/mineru/utils/text_utils.py@@ -11,13 +11,16 @@ 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 候选仅允许 RFC 3986 常见 ASCII 字符,避免把中文正文吞入链接。+_URL_CANDIDATE_RE = re.compile(+ r"(?<![A-Za-z0-9])(?:(?:https?|ftp)://|www\.)[A-Za-z0-9._~:/?#\[\]@!$&'()*+,;=%-]+",+ re.ASCII | re.IGNORECASE,+)+# 下一行自身以完整 URL 开头时,必须保留边界,避免两条独立链接相连。+_URL_AT_LINE_START_RE = re.compile(+ r"(?:(?:https?|ftp)://|www\.)",+ re.ASCII | re.IGNORECASE,)-# 这些结构字符出现在下一物理行行首时,可以保守地判定为上一行 URL 的延续。-_URL_CONTINUATION_PREFIX_CHARS = frozenset("/?#&=")def is_hyphen_at_line_end(line: str) -> bool:@@ -28,14 +31,15 @@ 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 结构字符延续上一行末尾链接。"""+def _url_spans_line_boundary(previous_content: str, next_content: str) -> bool:+ """判断无空格候选中是否存在严格横跨当前物理行边界的 URL。"""+ stripped_previous = previous_content.rstrip()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)- )+ if not stripped_previous or not stripped_next:+ return False+ candidate = f"{stripped_previous}{stripped_next}"+ boundary = len(stripped_previous)+ return any(match.start() < boundary < match.end() for match in _URL_CANDIDATE_RE.finditer(candidate))def resolve_text_line_boundary(@@ -46,20 +50,23 @@ def resolve_text_line_boundary() -> tuple[str, str]:"""返回处理后的上一行内容和本次物理行边界分隔符。- CJK 文本直接连接物理行;明确的 URL 结构延续也直接连接;普通西文行插入- 一个空格。西文行末如果是合法的 hyphen,则始终直接连接下一行,并仅在- 下一行以小写字母开头时删除 hyphen。+ 严格横跨边界的 URL 候选直接连接,但下一行自身为完整 URL 时保留空格。+ 其余 CJK 文本直接连接物理行,普通西文行插入一个空格。西文行末如果是+ 合法的 hyphen,则始终直接连接下一行,并仅在下一行以小写字母开头时删除+ hyphen。"""processed_content = previous_content.rstrip()if not processed_content:return "", ""- if block_language in CJK_LANGS:+ stripped_next = next_content.lstrip()+ if _url_spans_line_boundary(processed_content, stripped_next):+ if _URL_AT_LINE_START_RE.match(stripped_next):+ return processed_content, " "return processed_content, ""- if _is_url_line_continuation(processed_content, next_content):+ if block_language in CJK_LANGS:return processed_content, ""if not is_hyphen_at_line_end(processed_content):return processed_content, " "- 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.pyindex d7649296..31d30a2d 100644--- a/tests/unittest/test_flash_pdf_samples.py+++ b/tests/unittest/test_flash_pdf_samples.py@@ -22,6 +22,51 @@ from mineru.model.flash.native_pdf import (from mineru.utils.pdf_document import PDFDocument, get_lines_from_chars+# demo4 第 9 至 11 页中实际跨物理行显示的 URL,用于确保纯正则拼接覆盖全部形态。+_DEMO4_WRAPPED_URLS = (+ "https://doi.org/10.1007/s00259-025-07388-8",+ "https://doi.org/10.37921/690910twdfoo",+ "https://www.cancerimagingarchive.net/collection/acrin-nsclc-fdg-pet/",+ "http://creativecommons.org/licenses/by/4.0/",+ "https://doi.org/10.3322/caac.21660",+ "https://doi.org/10.1016/j.mayocp.2019.01.013",+ "https://doi.org/10.1016/j.jiph.2012.09.003",+ "https://doi.org/10.1016/s0140-6736(02)08352-6",+ "https://doi.org/10.1016/s0140-6736(02)08388-5",+ "https://doi.org/10.1378/chest.123.1_suppl.137s",+ "https://doi.org/10.1016/j.ejrad.2009.01.036",+ "https://doi.org/10.2214/ajr.16.16532",+ "https://doi.org/10.1200/jco.2012.47.5947",+ "https://doi.org/10.1007/s00259-022-05832-7",+ "https://doi.org/10.1016/j.radonc.2022.04.003",+ "https://doi.org/10.1016/j.crad.2015.03.010",+ "https://doi.org/10.3390/ijms22084120",+ "https://doi.org/10.1016/j.bone.2015.05.046",+ "https://doi.org/10.1016/j.cell.2007.05.047",+ "https://doi.org/10.1016/j.cell.2010.06.003",+ "https://doi.org/10.1038/s41577-019-0178-8",+ "https://doi.org/10.3389/fmed.2021.740615",+ "https://doi.org/10.1038/s41467-020-16878-2",+ "https://doi.org/10.1186/s12957-018-1439-x",+ "https://doi.org/10.1097/mnm.0000000000000483",+ "https://doi.org/10.1080/00031305.1992.10475879",+ "https://doi.org/10.3389/fmed.2025.1597844",+ "https://doi.org/10.1109/tpami.2024.3400281",+ "https://doi.org/10.3389/fonc.2022.922465",+ "https://doi.org/10.1002/acn3.121",+ "https://doi.org/10.36660/abc.20210463",+ "https://doi.org/10.18632/oncotarget.11816",+ "https://doi.org/10.1007/s00259-023-06192-6",+ "https://doi.org/10.2215/cjn.04151206",+ "https://doi.org/10.1038/s41593-018-0213-2",+ "https://doi.org/10.1038/s41698-022-00286-4",+ "https://doi.org/10.1016/j.bone.2022.116540",+ "https://doi.org/10.3389/fimmu.2023.1222129",+ "https://doi.org/10.5483/bmbrep.2008.41.7.495",+ "https://doi.org/10.1016/j.xjon.2022.09.001",+)++def _native_model_list(pdf_name: str) -> list[list[dict[str, Any]]]:"""运行仓库内数字 PDF 样例并返回 Flash 原生模型输出。"""@@ -822,6 +867,9 @@ def test_demo4_nct00083083_targeted_flash_regressions() -> None:"""验证 demo4 的跨栏图注、页眉脚注、续行、公式否决和参考文献分组。"""model_list = _native_model_list("demo4.pdf")+ all_content = "\n".join(str(block.get("content", "")) for page in model_list for block in page)+ assert len(_DEMO4_WRAPPED_URLS) == 40+ assert not [url for url in _DEMO4_WRAPPED_URLS if url not in all_content]page1 = model_list[0]assert any(block["type"] == "header" and "07388-8" in str(block["content"]) for block in page1)@@ -1425,7 +1473,7 @@ def test_iebm_left_indented_compact_formula_is_equation() -> None:def test_npu_numbered_figure_captions_are_independent_annotations() -> None:- """验证 NPU 指南十四个编号图注独立输出,且不产生视觉脚注误报。"""+ """验证 NPU 图注稳定、跨行 URL 连续,且多条独立 URL 不会相连。"""model_list = _txt_model_list("NPU_开发环境部署_参考指南.pdf")expected_counts = {6: 1, 7: 1, 14: 2, 15: 2, 16: 2, 17: 1, 18: 1, 19: 2, 20: 2}@@ -1437,6 +1485,22 @@ def test_npu_numbered_figure_captions_are_independent_annotations() -> None:assert all(str(block["content"]).startswith("图 ") for page in model_list for block in page if block["type"] == "caption")assert not [block for page in model_list for block in page if block["type"] == "footnote"]+ docker_url = "https://download.docker.com/linux/ubuntu/dists/"+ assert any(docker_url in str(block.get("content", "")) for block in model_list[8])++ reference_urls = [+ "https://blog.csdn.net/hzgnet2021/article/details/134925349",+ "https://blog.csdn.net/NuOne_plus/article/details/120330419",+ "https://blog.csdn.net/qq_38567039/article/details/124848621",+ ]+ reference_block = next(+ str(block.get("content", ""))+ for block in model_list[21]+ if reference_urls[0] in str(block.get("content", ""))+ )+ assert " ".join(reference_urls) in reference_block+ assert not any(first + second in reference_block for first, second in zip(reference_urls, reference_urls[1:]))+def test_frozen_soil_page3_formula3_remains_one_equation() -> None:"""验证中文论文第三页公式编号完整转为 tag 并归入单个公式块。"""diff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.pyindex 32c714fa..cf4cebaa 100644--- a/tests/unittest/test_markdown_render.py+++ b/tests/unittest/test_markdown_render.py@@ -140,6 +140,27 @@ def test_text_continuation_handles_hyphen_and_cjk_boundaries() -> None:assert render_markdown(cjk) == "中文继续"+def test_text_continuation_joins_url_candidates_but_separates_independent_urls() -> None:+ """验证 Markdown 续写连接跨块 URL,同时保留两条独立 URL 的分隔。"""+ continued_url = _middle(+ _page(+ 0,+ TextBlock(type="text", index=0, content="See https://doi.o"),+ TextBlock(type="text", index=1, content="rg/10.1016/example", continues_prev=True),+ )+ )+ independent_urls = _middle(+ _page(+ 0,+ TextBlock(type="text", index=0, content="https://example.test/first"),+ TextBlock(type="text", index=1, content="https://example.test/second", continues_prev=True),+ )+ )++ assert render_markdown(continued_url) == "See https://doi.org/10.1016/example"+ assert render_markdown(independent_urls) == "https://example.test/first https://example.test/second"++def test_text_continuation_does_not_rewrite_formula_or_style_wrappers() -> None:"""验证续写边界不会越过末尾公式或破坏样式节点。"""formula = _middle(diff --git a/tests/unittest/test_pdf_analyze_block_content.py b/tests/unittest/test_pdf_analyze_block_content.pyindex 7b1506e4..f74ebb26 100644--- a/tests/unittest/test_pdf_analyze_block_content.py+++ b/tests/unittest/test_pdf_analyze_block_content.py@@ -490,17 +490,17 @@ def test_text_content_keeps_natural_paragraph_joining() -> None:assert content == "第一行第二行"-def test_text_content_joins_structural_url_continuation_without_space() -> None:- """验证 PDF 内容重建不会在明确的跨行 URL 路径前插入空格。"""+def test_text_content_joins_cross_line_url_candidate_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.",+ "Available at https://doi.o",+ "rg/10.1016/example for details.",),BlockType.TEXT,)- assert content == "Available at https://example.test/current-research/image-processing/ for details."+ assert content == "Available at https://doi.org/10.1016/example for details."@pytest.mark.parametrize("block_type", [BlockType.CODE, RAW_ALGORITHM])diff --git a/tests/unittest/test_text_utils.py b/tests/unittest/test_text_utils.pyindex 12002f0b..f12f8d7b 100644--- a/tests/unittest/test_text_utils.py+++ b/tests/unittest/test_text_utils.py@@ -43,11 +43,46 @@ from mineru.utils.text_utils import resolve_text_line_boundary),pytest.param("input", "/ output", "en", "input / output", id="ordinary-slash-text"),pytest.param(- "See https://example.test/complete",- "Figure 2 follows.",+ "https://blog.example.test/first",+ "https://blog.example.test/second","en",- "See https://example.test/complete Figure 2 follows.",- id="url-followed-by-prose",+ "https://blog.example.test/first https://blog.example.test/second",+ id="independent-urls",+ ),+ pytest.param(+ "DOI https",+ "://doi.org/10.37921/example",+ "en",+ "DOI https://doi.org/10.37921/example",+ id="url-scheme-continuation",+ ),+ pytest.param(+ "See https://doi.o",+ "rg/10.3322/example",+ "en",+ "See https://doi.org/10.3322/example",+ id="url-host-continuation",+ ),+ pytest.param(+ "See https://doi.org/10.101",+ "6/example",+ "en",+ "See https://doi.org/10.1016/example",+ id="url-numeric-path-continuation",+ ),+ pytest.param(+ "See https://doi.org/10.1038/example-019",+ "-0178-8",+ "en",+ "See https://doi.org/10.1038/example-019-0178-8",+ id="url-hyphen-continuation",+ ),+ pytest.param(+ "Download from https://download.docker.com/linux/",+ "ubuntu/dists/",+ "en",+ "Download from https://download.docker.com/linux/ubuntu/dists/",+ id="url-alpha-path-continuation",),pytest.param("inter-", "national", "en", "international", id="western-hyphen"),pytest.param("first line", "second line", "en", "first line second line", id="western-space"),