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: simplify list block processing to maintain independent numbering for nested ordered lists
myhloli8c5f34579320
diff --git a/mineru/backend/postprocess/lists.py b/mineru/backend/postprocess/lists.pyindex 64d3b681..e87cbe4e 100644--- a/mineru/backend/postprocess/lists.py+++ b/mineru/backend/postprocess/lists.py@@ -162,16 +162,7 @@ def _visible_text(content: str) -> str:def fix_office_list_blocks(list_blocks: list[dict[str, Any]]) -> list[dict[str, Any]]:- """将 Office 列表层级和起始序号写入文本内容,并移除原始元数据。"""-- def get_list_ilevel(list_block: dict[str, Any], parent_ilevel: int | None) -> int:- """读取列表层级,非法值按递归深度回退。"""- fallback_ilevel = 0 if parent_ilevel is None else parent_ilevel + 1- try:- ilevel = int(list_block.get("ilevel"))- except (TypeError, ValueError):- return fallback_ilevel- return ilevel if ilevel >= 0 else fallback_ilevel+ """将每层 Office 列表的局部序号写入文本内容,并移除原始元数据。"""def get_ordered_list_start(list_block: dict[str, Any]) -> int:"""读取有序列表起始编号,保留合法的零值。"""@@ -184,22 +175,8 @@ def fix_office_list_blocks(list_blocks: list[dict[str, Any]]) -> list[dict[str,return 1return start if start >= 0 else 1- def format_ordered_prefix(ordered_numbers: dict[int, int]) -> str:- """按列表层级拼接有序编号。"""- number_parts = [str(number) for _, number in sorted(ordered_numbers.items())]- if len(number_parts) == 1:- return f"{number_parts[0]}. "- return f"{'.'.join(number_parts)} "-- def fix_list_block(- list_block: dict[str, Any],- inherited_ordered_numbers: dict[int, int],- parent_ilevel: int | None,- ) -> None:- """递归处理单个列表块,并向嵌套列表传递有序编号。"""- ilevel = get_list_ilevel(list_block, parent_ilevel)- base_ordered_numbers = {level: number for level, number in inherited_ordered_numbers.items() if level < ilevel}- active_ordered_numbers = dict(base_ordered_numbers)+ def fix_list_block(list_block: dict[str, Any]) -> None:+ """递归处理列表树;每个有序列表只维护当前层的独立编号。"""is_ordered = list_block.get("attribute") == "ordered"ordered_number = get_ordered_list_start(list_block)content = list_block.get("content")@@ -213,20 +190,18 @@ def fix_office_list_blocks(list_blocks: list[dict[str, Any]]) -> list[dict[str,if not isinstance(child_content, str):continueif is_ordered:- active_ordered_numbers = dict(base_ordered_numbers)- active_ordered_numbers[ilevel] = ordered_number- prefix = format_ordered_prefix(active_ordered_numbers)+ prefix = f"{ordered_number}. "ordered_number += 1else:prefix = "- "child_block["content"] = f"{prefix}{child_content}"elif child_type == BlockType.LIST:- fix_list_block(child_block, dict(active_ordered_numbers), ilevel)+ fix_list_block(child_block)list_block.pop("attribute", None)list_block.pop("ilevel", None)list_block.pop("start", None)for list_block in list_blocks:if isinstance(list_block, dict):- fix_list_block(list_block, {}, None)+ fix_list_block(list_block)return list_blocksdiff --git a/tests/unittest/test_office_parser_regressions.py b/tests/unittest/test_office_parser_regressions.pyindex 414be080..7897bd71 100644--- a/tests/unittest/test_office_parser_regressions.py+++ b/tests/unittest/test_office_parser_regressions.py@@ -1,6 +1,13 @@+from pathlib import Path+from pytest import MonkeyPatch+from mineru.backend.analyze import doc_analyzefrom mineru.model.flash.office import image as office_image+from mineru.render.markdown import render_markdown+++_PROJECT_ROOT = Path(__file__).resolve().parents[2]def test_vector_image_part_skip_log_is_debug(monkeypatch: MonkeyPatch) -> None:@@ -36,3 +43,30 @@ def test_vector_image_part_skip_log_is_debug(monkeypatch: MonkeyPatch) -> None:assert len(fake_logger.debug_messages) == 1assert "Skipping WMF image part before Pillow load" in fake_logger.debug_messages[0]assert fake_logger.warning_messages == []+++def test_docx_nested_ordered_lists_render_with_local_markers() -> None:+ """验证真实 DOCX 的多级有序列表使用当前层编号,并由 Markdown 缩进表达层级。"""+ file_bytes = (_PROJECT_ROOT / "demo" / "office_docs" / "docx_01.docx").read_bytes()++ middle_json, _ = doc_analyze(file_bytes, file_suffix="docx")+ markdown = render_markdown(middle_json)+ start = markdown.index("1. 如有未尽事宜")+ end_marker = " - 本合同一式四份,省政府采购中心各一份"+ end = markdown.index(end_marker, start) + len(end_marker)++ assert markdown[start:end] == r"""1. 如有未尽事宜,由双方依法订立[补充合同](https://github.com/opendatalab/MinerU)。+2. 本合同双方应加盖骑缝章。+ - 本合同一式四份,自双方签章并经省政府采购中心审核编号后生效。+ - 甲方、乙方、政府采购管理部门、<u>___广东__</u>省政府采购中心各一份+3. $a^{2}+b^{2}=c^{2}$行内公式后接正文+ - 本合同一式四份,自双方签章并经省政府采购中心审核编号后生效+ 1. 本合同双方应加盖骑缝章。+ 2. 自双方签章并经省政府采购中心审核编号后生效。+ 1. 最里层列表$\left(x+a\right)^{n}=\sum_{k=0}^{n}\left(\genfrac{}{}{0pt}{}{n}{k}\right)x^{k}a^{n-k}$行内公式后接正文+ 2. 合同一式四份,自双方签章后生效+ 3. <s><strong><u>xyz</u></strong></s>省政府采购中心各一份+ 1. 最内层列表$A=\pi r^{2}$行内公式后接正文+ 2. 合同一式四份,采购管理部门各一份+ 4. 文本[超链接](https://github.com/opendatalab/MinerU)支持,由双方依法订立补充公式$x=\frac{-b\pm \sqrt{b^{2}-4ac}}{2a}$+ - 本合同一式四份,省政府采购中心各一份"""diff --git a/tests/unittest/test_postprocess_pages.py b/tests/unittest/test_postprocess_pages.pyindex 2bfa80dd..5e74f9ef 100644--- a/tests/unittest/test_postprocess_pages.py+++ b/tests/unittest/test_postprocess_pages.py@@ -2,6 +2,7 @@ from copy import deepcopyimport pytest+from mineru.backend.postprocess.lists import fix_office_list_blocksfrom mineru.backend.postprocess.pages import model_list_to_pagesfrom mineru.types import (ChartBlock,@@ -117,6 +118,103 @@ def test_model_list_to_pages_preserves_recursive_office_list_and_index() -> Noneassert "anchor" not in index_block.content[0].content[0].model_fields_set+def test_fix_office_list_blocks_uses_local_ordered_markers_at_each_depth() -> None:+ """验证多级 Office 有序列表按当前层独立编号,并保留富文本与各层起始值。"""+ rich_content = (+ '<text style="bold">root</text><eq>x</eq>'+ '<hyperlink><text>link</text><url>https://example.com</url></hyperlink>'+ )+ list_block = {+ "type": "list",+ "attribute": "ordered",+ "ilevel": 0,+ "start": 3,+ "content": [+ {"type": "text", "content": rich_content},+ {+ "type": "list",+ "attribute": "unordered",+ "ilevel": 1,+ "content": [+ {"type": "text", "content": "bullet before"},+ {+ "type": "list",+ "attribute": "ordered",+ "ilevel": 2,+ "start": 1,+ "content": [+ {"type": "text", "content": "level two first"},+ {"type": "text", "content": "level two second"},+ {+ "type": "list",+ "attribute": "ordered",+ "ilevel": 3,+ "start": 0,+ "content": [+ {"type": "text", "content": "zero"},+ {"type": "text", "content": "one"},+ ],+ },+ {"type": "text", "content": "level two third"},+ {+ "type": "list",+ "attribute": "ordered",+ "ilevel": 3,+ "start": 5,+ "content": [+ {"type": "text", "content": "five"},+ {"type": "text", "content": "six"},+ ],+ },+ {"type": "text", "content": "level two fourth"},+ ],+ },+ {"type": "text", "content": "bullet after"},+ ],+ },+ {"type": "text", "content": "root after nested"},+ ],+ }+ invalid_start_list = {+ "type": "list",+ "attribute": "ordered",+ "ilevel": 0,+ "start": "invalid",+ "content": [{"type": "text", "content": "fallback"}],+ }++ result = fix_office_list_blocks([list_block, invalid_start_list])++ assert result == [list_block, invalid_start_list]+ assert list_block["content"][0]["content"] == f"3. {rich_content}"+ assert list_block["content"][2]["content"] == "4. root after nested"+ unordered = list_block["content"][1]+ assert unordered["content"][0]["content"] == "- bullet before"+ assert unordered["content"][2]["content"] == "- bullet after"+ level_two = unordered["content"][1]+ assert [level_two["content"][index]["content"] for index in (0, 1, 3, 5)] == [+ "1. level two first",+ "2. level two second",+ "3. level two third",+ "4. level two fourth",+ ]+ zero_start = level_two["content"][2]+ assert [child["content"] for child in zero_start["content"]] == ["0. zero", "1. one"]+ five_start = level_two["content"][4]+ assert [child["content"] for child in five_start["content"]] == ["5. five", "6. six"]+ assert invalid_start_list["content"][0]["content"] == "1. fallback"++ pending_lists = list(result)+ while pending_lists:+ current = pending_lists.pop()+ assert {"attribute", "ilevel", "start"}.isdisjoint(current)+ pending_lists.extend(+ child+ for child in current.get("content", [])+ if isinstance(child, dict) and child.get("type") == "list"+ )++def test_model_list_to_pages_maps_index_anchor_to_document_title_type_and_level() -> None:"""验证 Office 目录叶子按跨页目标 anchor 继承真实标题类型与层级。"""model_list = [