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
fix: add index block handling and parsing for improved document structure
myhloli6f493fbb9a86
diff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex 2b1207ea..b7995173 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -49,6 +49,7 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:title_blocks = magic_model.get_title_blocks()discarded_blocks = magic_model.get_discarded_blocks()list_blocks = magic_model.get_list_blocks()+ index_blocks = magic_model.get_index_blocks()text_blocks = magic_model.get_text_blocks()interline_equation_blocks = magic_model.get_interline_equation_blocks()@@ -60,6 +61,7 @@ def blocks_to_page_info(page_blocks, image_writer, page_index) -> dict:*text_blocks,*interline_equation_blocks,*list_blocks,+ *index_blocks,])# 对page_blocks根据index的值进行排序page_blocks.sort(key=lambda x: x["index"])diff --git a/mineru/backend/office/office_magic_model.py b/mineru/backend/office/office_magic_model.pyindex 3f31f4e3..17e7e0e7 100644--- a/mineru/backend/office/office_magic_model.py+++ b/mineru/backend/office/office_magic_model.py@@ -61,6 +61,13 @@ class MagicModel:parsed_list["index"] = indexblocks.append(parsed_list)continue+ elif block_type in ["index"]:+ # 解析嵌套索引结构(目录),生成与list一致的blocks结构+ parsed_index = parse_index_block(block_info)+ if parsed_index:+ parsed_index["index"] = index+ blocks.append(parsed_index)+ continueelse:# 未知类型,跳过continue@@ -97,6 +104,7 @@ class MagicModel:self.ref_text_blocks = []self.phonetic_blocks = []self.list_blocks = []+ self.index_blocks = []for block in blocks:if block["type"] in [BlockType.IMAGE_BODY, BlockType.IMAGE_CAPTION, BlockType.IMAGE_FOOTNOTE]:self.image_blocks.append(block)@@ -118,6 +126,8 @@ class MagicModel:self.discarded_blocks.append(block)elif block["type"] == BlockType.LIST:self.list_blocks.append(block)+ elif block["type"] == BlockType.INDEX:+ self.index_blocks.append(block)else:continue@@ -132,6 +142,9 @@ class MagicModel:def get_list_blocks(self):return self.list_blocks+ def get_index_blocks(self):+ return self.index_blocks+def get_image_blocks(self):return self.image_blocks@@ -325,6 +338,48 @@ def parse_list_block(list_block: dict):return result+def parse_index_block(index_block: dict):+ """+ 递归解析嵌套索引结构(目录),生成与list一致的blocks结构。++ Args:+ index_block: 索引块字典++ Returns:+ 解析后的索引block字典,若内容为空则返回 None+ """+ content = index_block.get("content", [])+ if not content:+ return None++ blocks = []++ for item in content:+ item_type = item.get("type", "")++ if item_type == "text":+ text_content = item.get("content", "")+ spans = parse_text_block_spans(text_content)+ text_block = {+ "type": BlockType.TEXT,+ "lines": [{"spans": spans}]+ }+ blocks.append(text_block)++ elif item_type == "index":+ nested_index = parse_index_block(item)+ if nested_index:+ blocks.append(nested_index)++ result = {+ "type": BlockType.INDEX,+ "ilevel": index_block.get("ilevel", 0),+ "blocks": blocks+ }++ return result++def clean_table_html(html: str) -> str:"""清洗表格HTML,只保留对表格结构表示有用的信息。diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pyindex 5d93f2c1..8f2e23ab 100644--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ b/mineru/backend/office/office_middle_json_mkcontent.py@@ -78,7 +78,7 @@ def _flatten_list_items(list_block):ordered_counter = 1for block in list_block.get('blocks', []):- if block['type'] == BlockType.LIST:+ if block['type'] in [BlockType.LIST, BlockType.INDEX]:items.extend(_flatten_list_items(block))else:item_text = merge_para_with_text(block)@@ -100,7 +100,7 @@ def _flatten_list_items_v2(list_block):ordered_counter = 1for block in list_block.get('blocks', []):- if block['type'] == BlockType.LIST:+ if block['type'] in [BlockType.LIST, BlockType.INDEX]:items.extend(_flatten_list_items_v2(block))else:item_content = merge_para_with_text_v2(block)@@ -132,7 +132,7 @@ def mk_blocks_to_markdown(para_blocks, make_mode, img_buket_path=''):para_type = para_block['type']if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:para_text = merge_para_with_text(para_block)- elif para_type == BlockType.LIST:+ elif para_type in [BlockType.LIST, BlockType.INDEX]:para_text = merge_list_to_markdown(para_block)elif para_type == BlockType.TITLE:title_level = get_title_level(para_block)@@ -191,6 +191,11 @@ def make_blocks_to_content_list(para_block, img_buket_path, page_idx):'type': para_type,'list_items': _flatten_list_items(para_block),}+ elif para_type == BlockType.INDEX:+ para_content = {+ 'type': para_type,+ 'list_items': _flatten_list_items(para_block),+ }elif para_type == BlockType.TITLE:title_level = get_title_level(para_block)para_content = {@@ -342,6 +347,14 @@ def make_blocks_to_content_list_v2(para_block, img_buket_path):'list_items': _flatten_list_items_v2(para_block),}}+ elif para_type == BlockType.INDEX:+ para_content = {+ 'type': ContentTypeV2.INDEX,+ 'content': {+ 'list_type': ContentTypeV2.LIST_TEXT,+ 'list_items': _flatten_list_items_v2(para_block),+ }+ }return para_contentdiff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex 84d95505..acff3308 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -74,6 +74,8 @@ class DocxConverter:self.list_counters: dict[tuple[int, int], int] = ({}) # 列表计数器 (numId, ilvl) -> count+ self.index_block_stack: list = [] # 目录索引块堆栈+ self.pre_index_ilevel: int = -1 # 上一个目录项的缩进等级self.equation_bookends: str = "<eq>{EQ}</eq>" # 公式标记格式self.chart_list = [] # 图表列表self.processed_textbox_elements: list = []@@ -351,12 +353,16 @@ class DocxConverter:".//w:sdtContent", namespaces=DocxConverter._BLIP_NAMESPACES)if sdt_content is not None:- # Iterate paragraphs, runs, or text inside <w:sdtContent>.- paragraphs = sdt_content.findall(- ".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES- )- for p in paragraphs:- self._handle_text_elements(p)+ if self._is_toc_sdt(element):+ # 处理目录SDT,转换为INDEX块+ self._handle_sdt_as_index(sdt_content)+ else:+ # 其他SDT元素,按普通文本处理+ paragraphs = sdt_content.findall(+ ".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES+ )+ for p in paragraphs:+ self._handle_text_elements(p)# 检查文本段落元素elif tag_name == "p":# 处理文本元素(包括段落属性如"tcPr", "sectPr"等)@@ -1100,6 +1106,227 @@ class DocxConverter:for key in keys_to_reset:self.list_counters[key] = 0+ def _is_toc_sdt(self, element: BaseOxmlElement) -> bool:+ """+ 检测SDT元素是否为目录(Table of Contents)。++ 检测策略:+ 1. 检查 w:sdtPr 中的 docPartGallery 或 tag 元素+ 2. 回退到检查内容中的段落样式是否为 "TOC N" 格式++ Args:+ element: SDT XML元素++ Returns:+ bool: 如果是目录SDT返回 True,否则返回 False+ """+ # 方法1: 检查 w:sdtPr 中的 docPartGallery+ sdt_pr = element.find("w:sdtPr", namespaces=DocxConverter._BLIP_NAMESPACES)+ if sdt_pr is not None:+ doc_part_gallery = sdt_pr.find(+ ".//w:docPartGallery", namespaces=DocxConverter._BLIP_NAMESPACES+ )+ if doc_part_gallery is not None:+ val = doc_part_gallery.get(self.XML_KEY, "")+ if "Table of Contents" in val or "toc" in val.lower():+ return True++ # 检查 tag 元素的值+ tag_elem = sdt_pr.find("w:tag", namespaces=DocxConverter._BLIP_NAMESPACES)+ if tag_elem is not None:+ val = tag_elem.get(self.XML_KEY, "").lower().replace(" ", "")+ if "toc" in val or "contents" in val or "tableofcontents" in val:+ return True++ # 方法2: 检查内容段落的样式是否为 "TOC N" 格式+ sdt_content = element.find(+ "w:sdtContent", namespaces=DocxConverter._BLIP_NAMESPACES+ )+ if sdt_content is not None:+ paragraphs = sdt_content.findall(+ "w:p", namespaces=DocxConverter._BLIP_NAMESPACES+ )+ for p in paragraphs[:5]: # 只检查前5个段落即可判断+ try:+ p_obj = Paragraph(p, self.docx_obj)+ if p_obj.style and p_obj.style.name:+ style_name = p_obj.style.name+ if re.match(r'^TOC\s*\d+$', style_name, re.IGNORECASE) or \+ re.match(r'^目录\s*\d+$', style_name):+ return True+ except Exception:+ continue++ return False++ def _get_toc_item_level(self, paragraph: Paragraph) -> Optional[int]:+ """+ 从段落样式中获取目录项的层级(0-based)。++ "TOC 1" -> 0+ "TOC 2" -> 1+ "目录 1" -> 0++ Args:+ paragraph: 段落对象++ Returns:+ Optional[int]: 层级(0-based),如果不是目录样式则返回 None+ """+ if paragraph.style is None:+ return None+ style_name = paragraph.style.name+ if style_name:+ match = re.match(r'^(?:TOC|目录)\s*(\d+)$', style_name, re.IGNORECASE)+ if match:+ level = int(match.group(1))+ return level - 1 # 转换为 0-based+ return None++ def _add_index_item(+ self,+ *,+ ilevel: int,+ elements: list,+ text: str = "",+ equations: list = None,+ ) -> None:+ """+ 添加目录项到索引块。++ 生成的索引结构:+ {+ "type": "index",+ "ilevel": 0,+ "content": [+ {"type": "text", "content": "目录项文本"},+ {"type": "index", "ilevel": 1, "content": [...]},+ ]+ }++ Args:+ ilevel: 缩进等级(0-based)+ elements: 元素列表+ text: 处理后的文本(包含公式标记)+ equations: 公式列表+ """+ if equations is None:+ equations = []+ if not elements:+ return++ content_text = self._build_text_with_equations_and_hyperlinks(+ elements, text, equations+ )++ # 情况 1: 首个目录项,创建新的顶层索引块+ if self.pre_index_ilevel == -1:+ index_block = {+ "type": BlockType.INDEX,+ "content": [],+ "ilevel": ilevel,+ }+ self.cur_page.append(index_block)+ self.index_block_stack.append(index_block)++ index_item = {+ "type": BlockType.TEXT,+ "content": content_text,+ }+ index_block["content"].append(index_item)+ self.pre_index_ilevel = ilevel++ # 情况 2: 增加缩进,打开子索引块+ elif self.pre_index_ilevel < ilevel:+ child_index_block = {+ "type": BlockType.INDEX,+ "content": [],+ "ilevel": ilevel,+ }+ parent_index_block = self.index_block_stack[-1]+ parent_index_block["content"].append(child_index_block)+ self.index_block_stack.append(child_index_block)++ index_item = {+ "type": BlockType.TEXT,+ "content": content_text,+ }+ child_index_block["content"].append(index_item)+ self.pre_index_ilevel = ilevel++ # 情况 3: 减少缩进,关闭子索引块+ elif ilevel < self.pre_index_ilevel:+ while self.index_block_stack:+ top_block = self.index_block_stack[-1]+ if top_block["ilevel"] == ilevel:+ break+ self.index_block_stack.pop()+ if self.index_block_stack:+ index_block = self.index_block_stack[-1]+ index_item = {+ "type": BlockType.TEXT,+ "content": content_text,+ }+ index_block["content"].append(index_item)+ self.pre_index_ilevel = ilevel++ # 情况 4: 同级目录项+ else:+ if self.index_block_stack:+ index_block = self.index_block_stack[-1]+ index_item = {+ "type": BlockType.TEXT,+ "content": content_text,+ }+ index_block["content"].append(index_item)++ def _handle_sdt_as_index(self, sdt_content: BaseOxmlElement) -> None:+ """+ 处理目录SDT内容,将其转换为层级化的INDEX块。++ Args:+ sdt_content: w:sdtContent XML元素+ """+ paragraphs = sdt_content.findall(+ ".//w:p", namespaces=DocxConverter._BLIP_NAMESPACES+ )++ # 重置索引状态,开始新的目录块+ self.index_block_stack = []+ self.pre_index_ilevel = -1++ for p in paragraphs:+ try:+ p_obj = Paragraph(p, self.docx_obj)+ paragraph_elements = self._get_paragraph_elements(p_obj)+ text, equations = self._handle_equations_in_text(+ element=p, text=p_obj.text+ )+ if text is None:+ continue+ text = text.strip()+ if not text:+ continue++ # 获取目录项层级+ toc_level = self._get_toc_item_level(p_obj)+ if toc_level is None:+ toc_level = 0++ self._add_index_item(+ ilevel=toc_level,+ elements=paragraph_elements,+ text=text,+ equations=equations,+ )+ except Exception as e:+ logger.debug(f"Error processing TOC paragraph: {e}")+ continue++ # 处理完成后重置索引状态+ self.index_block_stack = []+ self.pre_index_ilevel = -1+def _get_heading_and_level(self, style_label: str) -> tuple[str, Optional[int]]:"""从样式标签获取标题和层级。diff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex ff684e57..0cb75873 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -54,6 +54,7 @@ class ContentTypeV2:LIST = 'list'LIST_TEXT = 'text_list'LIST_REF = 'reference_list'+ INDEX = 'index'TITLE = 'title'PARAGRAPH = 'paragraph'SPAN_TEXT = 'text'