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 handling of inline formulas and empty content in index and code blocks
myhloli74571982244c
diff --git a/mineru/backend/hybrid/hybrid_analyze.py b/mineru/backend/hybrid/hybrid_analyze.pyindex dc373f6f..807356df 100644--- a/mineru/backend/hybrid/hybrid_analyze.py+++ b/mineru/backend/hybrid/hybrid_analyze.py@@ -177,6 +177,8 @@ def _is_hybrid_medium_ocr_det_candidate(block: dict[str, Any]) -> bool:item_type = block.get("type") or block.get("label")return item_type in {*NOT_EXTRACT_TYPES,+ MineruBlockType.ALGORITHM,+ MineruBlockType.CODE,MineruBlockType.DOC_TITLE,MineruBlockType.PARAGRAPH_TITLE,MineruBlockType.INDEX,diff --git a/mineru/backend/hybrid/hybrid_magic_model.py b/mineru/backend/hybrid/hybrid_magic_model.pyindex 302303e0..9748cb29 100644--- a/mineru/backend/hybrid/hybrid_magic_model.py+++ b/mineru/backend/hybrid/hybrid_magic_model.py@@ -49,37 +49,98 @@ OCR_DET_LINE_BLOCK_TYPES = {}-def _should_fill_empty_index_from_spans(block_type: str, block_content: str | None, use_vlm_text_content: bool) -> bool:- """判断空目录块是否应复用 OCR/PDF span 回填,避免生成空文本目录项。"""- return block_type == BlockType.INDEX and not use_vlm_text_content and not (block_content or "").strip()+EMPTY_CONTENT_INLINE_FILL_BLOCK_TYPES = {+ BlockType.INDEX,+ BlockType.CODE_BODY,+}+++def _has_inline_formula_content(content: str | None) -> bool:+ """判断 content 是否包含可安全拆分的成对行内公式标记。"""+ return bool(content) and content.count("\\(") == content.count("\\)") and content.count("\\(") > 0+++def _split_inline_formula_content_to_spans(content: str | None, bbox: BBox) -> list[Span]:+ """按 \\(...\\) 将文本拆成普通文本 span 和行内公式 span。"""+ if not content:+ return []++ spans: list[Span] = []+ last_end = 0+ for match in re.finditer(r"\\\((.+?)\\\)", content):+ start, end = match.span()+ if start > last_end:+ text_before = content[last_end:start]+ if text_before.strip():+ spans.append(Span(type=ContentType.TEXT, bbox=bbox, content=text_before))++ formula = match.group(1).strip()+ if formula:+ spans.append(Span(type=ContentType.INLINE_EQUATION, bbox=bbox, content=formula))++ last_end = end++ if last_end < len(content):+ text_after = content[last_end:]+ if text_after.strip():+ spans.append(Span(type=ContentType.TEXT, bbox=bbox, content=text_after))++ return spans-def _collapse_index_lines_to_single_content_span(block: Block) -> None:- """将回填出的目录多行折叠为单个文本 span,避免后续逐行拼接时丢失换行。"""- line_texts = []+def _should_fill_empty_content_from_spans(+ block_type: str,+ block_content: str | None,+ use_vlm_text_content: bool,+) -> bool:+ """判断空内容块是否需要复用 OCR/PDF span 回填,避免生成空目录或空代码块。"""+ return (+ block_type in EMPTY_CONTENT_INLINE_FILL_BLOCK_TYPES+ and not use_vlm_text_content+ and not (block_content or "").strip()+ )+++def _line_to_inline_formula_content(line: Line) -> str:+ """将一行中的文本和行内公式 span 拼回统一 content 字符串。"""+ parts: list[str] = []+ for span in line.spans:+ if span.type == ContentType.TEXT:+ parts.append(span.content or "")+ elif span.type == ContentType.INLINE_EQUATION and span.content:+ parts.append(f"\\({span.content}\\)")+ return "".join(parts)+++def _collapse_lines_to_inline_content_spans(block: Block) -> None:+ """将多行回填结果折叠为一个 line,并复用统一规则拆分文本和行内公式 span。"""+ line_texts: list[str] = []for line in block.lines:- line_text = "".join(span.content or "" for span in line.spans).strip()- if line_text:+ line_text = _line_to_inline_formula_content(line)+ if line_text.strip():line_texts.append(line_text)if not line_texts:block.lines = []returncontent = "\n".join(line_texts)+ spans = _split_inline_formula_content_to_spans(content, block.bbox)block.lines = [Line(bbox=block.bbox,- spans=[- Span(- type=ContentType.TEXT,- bbox=block.bbox,- content=content,- )- ],+ spans=spans,)]+def _ensure_code_body_metadata_line(block: Block, code_type: str | None, guess_lang: str | None) -> None:+ """为空代码块补一行元数据,确保父 code block 能保留 code/algorithm 子类型。"""+ if not block.lines:+ block.lines = [Line(spans=[Span(type=ContentType.TEXT, bbox=block.bbox, content="")], bbox=block.bbox)]+ block.lines[0]._code_type = code_type+ block.lines[0]._code_guess_lang = guess_lang++def _copy_raw_text_block_metadata(draft: VlmContentBlockDraft, block: Block) -> None:if draft.raw_type != BlockType.TEXT:return@@ -217,7 +278,7 @@ class MagicModel:if span_type == ContentType.TEXT and block_content is None:# 文本类块缺失 content 时按空文本处理,避免 VLM 渲染阶段遇到 None。block_content = ""- fill_empty_index_from_spans = _should_fill_empty_index_from_spans(+ fill_empty_content_from_spans = _should_fill_empty_content_from_spans(block_type,block_content,use_vlm_text_content,@@ -239,7 +300,7 @@ class MagicModel:bbox=block_bbox,content=isolated_formula_clean(block_content or ""),)- elif not fill_empty_index_from_spans and (use_vlm_text_content or block_type not in not_extract_list):+ elif not fill_empty_content_from_spans and (use_vlm_text_content or block_type not in not_extract_list):# 使用 VLM 文本内容时,所有文本块都直接消费 block content。# 非 VLM 文本路径下,非提取块仍沿用直接内容模式。if block_content:@@ -248,52 +309,10 @@ class MagicModel:if block_type in [BlockType.TITLE, BlockType.DOC_TITLE, BlockType.PARAGRAPH_TITLE] and block_content:block_content = re.sub(r"\n\s*", " ", block_content).strip()- if (- block_content- and block_content.count("\\(") == block_content.count("\\)")- and block_content.count("\\(") > 0- ):- switch_code_to_algorithm = True-- spans = []- last_end = 0- for match in re.finditer(r"\\\((.+?)\\\)", block_content):- start, end = match.span()-- if start > last_end:- text_before = block_content[last_end:start]- if text_before.strip():- spans.append(- Span(- type=ContentType.TEXT,- bbox=block_bbox,- content=text_before,- )- )-- formula = match.group(1)- spans.append(- Span(- type=ContentType.INLINE_EQUATION,- bbox=block_bbox,- content=formula.strip(),- )- )-- last_end = end-- if last_end < len(block_content):- text_after = block_content[last_end:]- if text_after.strip():- spans.append(- Span(- type=ContentType.TEXT,- bbox=block_bbox,- content=text_after,- )- )-- span = spans+ if _has_inline_formula_content(block_content):+ if block_type == BlockType.CODE_BODY and code_block_sub_type == "code":+ switch_code_to_algorithm = True+ span = _split_inline_formula_content_to_spans(block_content, block_bbox)else:span = Span(type=span_type,@@ -306,7 +325,7 @@ class MagicModel:ContentType.TABLE,ContentType.CHART,ContentType.INTERLINE_EQUATION,- ] or (not fill_empty_index_from_spans and (use_vlm_text_content or block_type not in not_extract_list)):+ ] or (not fill_empty_content_from_spans and (use_vlm_text_content or block_type not in not_extract_list)):if span is None:continueif isinstance(span, Span):@@ -338,8 +357,10 @@ class MagicModel:block = Block(index=index, type=block_type, bbox=block_bbox, angle=block_angle)block._fix_spans = block_spansblock = fix_text_block(block)- if fill_empty_index_from_spans:- _collapse_index_lines_to_single_content_span(block)+ if fill_empty_content_from_spans:+ _collapse_lines_to_inline_content_spans(block)+ if block_type == BlockType.CODE_BODY:+ _ensure_code_body_metadata_line(block, code_block_sub_type, guess_lang)_copy_raw_text_block_metadata(draft, block)if block.type == BlockType.INDEX: