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: split paragraph elements at equation boundaries to preserve formatting
myhlolib8f0e28b333e
diff --git a/mineru/backend/office/office_middle_json_mkcontent.py b/mineru/backend/office/office_middle_json_mkcontent.pyindex 2c7d14b6..10d6f36c 100644--- a/mineru/backend/office/office_middle_json_mkcontent.py+++ b/mineru/backend/office/office_middle_json_mkcontent.py@@ -216,6 +216,15 @@ def _flatten_index_items(index_block):Strips the trailing tab+page-number from span content and, when targetlocation fields are present on a span, wraps the text in a markdownhyperlink pointing to the body-block anchor.++ Styling (bold, italic, underline, strikethrough) is applied via+ _apply_markdown_style. HYPERLINK spans are rendered as plain styled+ text (without the URL) because TOC entries use document-internal+ bookmark links, not external URLs.++ The tab+page-number is stripped from the raw content BEFORE markdown+ style markers are applied, so that closing markers (e.g. ``**``) are+ never inadvertently removed by the tab-stripping step."""items = []ilevel = index_block.get('ilevel', 0)@@ -225,32 +234,81 @@ def _flatten_index_items(index_block):if child.get('type') == BlockType.INDEX:items.extend(_flatten_index_items(child))elif child.get('type') == BlockType.TEXT:- raw_parts = []+ span_items = [] # list of (content, span_type, span_style)target_anchor = None+for line in child.get('lines', []):for span in line.get('spans', []):content = span.get('content', '')- if content:- # Wrap inline equations with configured delimiters- if span.get('type') == ContentType.INLINE_EQUATION:- raw_parts.append(- f'{inline_left_delimiter}{content}{inline_right_delimiter}'- )- else:- raw_parts.append(content)+ span_style = span.get('style', [])+ span_type = span.get('type')+ span_items.append((content, span_type, span_style))if 'target_anchor' in span and target_anchor is None:pid, bidx = span['target_anchor']target_anchor = f"block-p{pid}-b{bidx}"- # Combine all span content into one string, then strip the trailing- # tab + page-number in a single pass (e.g. "2.\t标题\t5" → "2. 标题").- # Applying rsplit once ensures that an internal tab between section- # number and title text (e.g. "1.1\t研究对象") becomes a space while- # only the rightmost tab separator (before the page count) is removed.- combined = ''.join(raw_parts)- if '\t' in combined:- combined = combined.rsplit('\t', 1)[0].replace('\t', ' ')- item_text = combined.strip()+ if not span_items:+ continue++ # ----------------------------------------------------------+ # Step 1: Strip the trailing tab+page-number from the raw+ # (unstyled) content BEFORE applying markdown markers.+ #+ # Find the last non-equation span that contains a tab; strip+ # everything after its last tab (the page-number separator).+ # Then replace any remaining internal tabs with spaces so that+ # "1.1\t研究对象" → "1.1 研究对象".+ # ----------------------------------------------------------+ last_tab_span_idx = -1+ for i, (content, span_type, _) in enumerate(span_items):+ if span_type != ContentType.INLINE_EQUATION and '\t' in content:+ last_tab_span_idx = i++ # Build stripped span_items+ stripped_span_items = []+ for i, (content, span_type, span_style) in enumerate(span_items):+ if span_type != ContentType.INLINE_EQUATION:+ if i == last_tab_span_idx:+ # Strip from last tab onwards (removes tab + page number)+ content = content.rsplit('\t', 1)[0]+ # Replace remaining internal tabs with spaces+ content = content.replace('\t', ' ')+ stripped_span_items.append((content, span_type, span_style))++ # ----------------------------------------------------------+ # Step 2: Apply markdown styles and build the final text.+ # ----------------------------------------------------------+ raw_parts = []+ for content, span_type, span_style in stripped_span_items:+ if not content:+ continue+ if span_type == ContentType.INLINE_EQUATION:+ # Wrap inline equations with configured delimiters+ raw_parts.append(+ f'{inline_left_delimiter}{content}{inline_right_delimiter}'+ )+ elif span_type == ContentType.HYPERLINK:+ # TOC hyperlinks use document-internal bookmark refs; output+ # only the styled display text without the URL.+ link_text = content.strip()+ if link_text:+ link_text = _apply_markdown_style(link_text, span_style)+ leading = content[:len(content) - len(content.lstrip())]+ trailing = content[len(content.rstrip()):]+ raw_parts.append(leading + link_text + trailing)+ else:+ # TEXT span: apply markdown style while preserving+ # surrounding whitespace (e.g. leading space after section #).+ stripped = content.strip()+ if stripped:+ styled = _apply_markdown_style(stripped, span_style)+ leading = content[:len(content) - len(content.lstrip())]+ trailing = content[len(content.rstrip()):]+ raw_parts.append(leading + styled + trailing)+ elif content:+ raw_parts.append(content)++ item_text = ''.join(raw_parts).strip()if not item_text:continuediff --git a/mineru/model/docx/docx_converter.py b/mineru/model/docx/docx_converter.pyindex 7081de3c..27548216 100644--- a/mineru/model/docx/docx_converter.py+++ b/mineru/model/docx/docx_converter.py@@ -246,6 +246,83 @@ class DocxConverter:result_parts.append(formatted_text)return "".join(result_parts) if result_parts else ""+ @staticmethod+ def _split_paragraph_elements_at_eq_boundaries(+ paragraph_elements: list,+ non_eq_segments: list,+ ) -> list:+ """+ 在公式边界处拆分段落元素,解决格式标注跨公式边界失效的问题。++ 当 _get_paragraph_elements 处理含公式(oMath)的段落时,python-docx 的+ iter_inner_content() 不会遍历 oMath 元素。如果公式前后的文本格式相同,+ 它们会被合并为单个元素,导致文本跨越 <eq> 标签两侧。+ _replace_text_outside_equations 只在单个非公式片段中搜索,无法找到跨片段的文本,+ 从而导致样式替换失败。++ 本方法通过将这些跨边界的合并元素重新拆分为多个片段来修复此问题,+ 使每个元素都对应 text_with_equations 中唯一的非公式片段。++ Args:+ paragraph_elements: (text, format, hyperlink) 元组的列表+ non_eq_segments: 从 text_with_equations 中提取的非公式文本片段列表++ Returns:+ 重新拆分后的 (text, format, hyperlink) 列表,每个元素均位于单个公式片段内+ """+ if len(non_eq_segments) <= 1:+ return paragraph_elements++ # 计算各非公式片段的累积结束位置,作为分割边界+ boundaries: set[int] = set()+ pos = 0+ for seg in non_eq_segments[:-1]: # 最后一个片段后无需分割+ pos += len(seg)+ boundaries.add(pos)++ if not boundaries:+ return paragraph_elements++ # 验证段落元素的拼接文本与非公式片段的拼接文本一致+ concat_elem_text = "".join(text for text, _, _ in paragraph_elements)+ concat_seg_text = "".join(non_eq_segments)+ if concat_elem_text != concat_seg_text:+ # 文本不匹配时安全降级:原样返回+ return paragraph_elements++ # 在边界处分割元素+ result = []+ text_pos = 0+ for (text, fmt, hyperlink) in paragraph_elements:+ if not text:+ result.append((text, fmt, hyperlink))+ text_pos += len(text)+ continue++ elem_start = text_pos+ elem_end = elem_start + len(text)+ text_pos = elem_end++ # 找到落在该元素内部的分割点+ splits_in_elem = sorted(+ b - elem_start for b in boundaries if elem_start < b < elem_end+ )++ if not splits_in_elem:+ result.append((text, fmt, hyperlink))+ else:+ prev = 0+ for split_pos in splits_in_elem:+ fragment = text[prev:split_pos]+ if fragment:+ result.append((fragment, fmt, hyperlink))+ prev = split_pos+ fragment = text[prev:]+ if fragment:+ result.append((fragment, fmt, hyperlink))++ return result+def _build_text_with_equations_and_hyperlinks(self,paragraph_elements: list[@@ -288,6 +365,15 @@ class DocxConverter:# 同时有公式和超链接/样式,需要合并处理# 策略:在带公式的文本基础上,将样式/超链接标记插入到正确的位置+ # 0. 拆分 text_with_equations,获取各非公式片段,用于解决跨公式边界的元素合并问题+ eq_split_pattern = re.compile(r'<eq>.*?</eq>', re.DOTALL)+ non_eq_segments = eq_split_pattern.split(text_with_equations)++ # 在公式边界处重新拆分段落元素,避免单个元素跨越多个非公式片段+ paragraph_elements = self._split_paragraph_elements_at_eq_boundaries(+ paragraph_elements, non_eq_segments+ )+# 1. 记录每个元素的原始文本和对应的格式化结果element_mappings = []for text, format_obj, hyperlink in paragraph_elements: