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
refactor: migrate markdown rendering to render/ layer (Stage 2 Layer 1)
jinzhenj051381c6945c
diff --git a/mineru/backend/hybrid/model_output_to_middle_json.py b/mineru/backend/hybrid/model_output_to_middle_json.pyindex bb0fdf71..6d97d630 100644--- a/mineru/backend/hybrid/model_output_to_middle_json.py+++ b/mineru/backend/hybrid/model_output_to_middle_json.py@@ -116,6 +116,7 @@ def blocks_to_page_info(discarded_blocks=discarded_blocks,page_size=(width, height),page_idx=page_index,+ _backend="hybrid",)return page_infodiff --git a/mineru/backend/office/mkcontent/output_builders.py b/mineru/backend/office/mkcontent/output_builders.pyindex d8ab237a..8cc6dbbb 100644--- a/mineru/backend/office/mkcontent/output_builders.py+++ b/mineru/backend/office/mkcontent/output_builders.py@@ -383,57 +383,38 @@ def mk_blocks_to_markdown(else:para_text = f"{'#' * title_level} {title_text}"elif para_type == BlockType.IMAGE:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- for span in _iter_body_spans(- para_block,- BlockType.IMAGE_BODY,- ContentType.IMAGE,- ):- if span:- para_text += f""- for caption_text in _collect_caption_texts(- para_block,- BlockType.IMAGE_CAPTION,- ):- para_text += " \n" + caption_text+ # if make_mode == MakeMode.NLP_MD:+ # continue+ # elif make_mode == MakeMode.MM_MD:+ for span in _iter_body_spans(para_block, BlockType.IMAGE_BODY, ContentType.IMAGE):+ if span:+ para_text += f""+ for caption_text in _collect_caption_texts(para_block, BlockType.IMAGE_CAPTION):+ para_text += " \n" + caption_textelif para_type == BlockType.TABLE:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- for span in _iter_body_spans(- para_block,- BlockType.TABLE_BODY,- ContentType.TABLE,- ):- para_text += f"\n{_format_embedded_html(span.html, img_bucket_path)}\n"- for caption_text in _collect_caption_texts(- para_block,- BlockType.TABLE_CAPTION,- ):- para_text += " \n" + caption_text+ # if make_mode == MakeMode.NLP_MD:+ # continue+ # elif make_mode == MakeMode.MM_MD:+ for span in _iter_body_spans(para_block, BlockType.TABLE_BODY, ContentType.TABLE):+ para_text += f"\n{_format_embedded_html(span.html, img_bucket_path)}\n"+ for caption_text in _collect_caption_texts(para_block, BlockType.TABLE_CAPTION):+ para_text += " \n" + caption_textelif para_type == BlockType.CHART:- if make_mode == MakeMode.NLP_MD:+ # if make_mode == MakeMode.NLP_MD:+ # continue+ # elif make_mode == MakeMode.MM_MD:+ image_path, chart_content = get_body_data(para_block)+ if chart_content:+ para_text += f"\n{_format_embedded_html(chart_content, img_bucket_path)}\n"+ elif image_path:+ para_text += f"})"+ else:continue- elif make_mode == MakeMode.MM_MD:- image_path, chart_content = get_body_data(para_block)- if chart_content:- para_text += f"\n{_format_embedded_html(chart_content, img_bucket_path)}\n"- elif image_path:- para_text += f"})"- else:- continue- for caption_text in _collect_caption_texts(- para_block,- BlockType.CHART_CAPTION,- ):- para_text += " \n" + caption_text- if para_text.strip() == "":- continue- else:- # page_markdown.append(para_text.strip())+ for caption_text in _collect_caption_texts(para_block, BlockType.CHART_CAPTION):+ para_text += " \n" + caption_text++ if para_text.strip() != "":page_markdown.append(para_text.strip("\r\n"))return page_markdowndiff --git a/mineru/backend/office/model_output_to_middle_json.py b/mineru/backend/office/model_output_to_middle_json.pyindex 9656e05e..e5c2c799 100644--- a/mineru/backend/office/model_output_to_middle_json.py+++ b/mineru/backend/office/model_output_to_middle_json.py@@ -67,6 +67,7 @@ def blocks_to_page_info(page_blocks: list[dict[str, Any]], image_writer: Any, papara_blocks=blocks,discarded_blocks=discarded_blocks,page_idx=page_index,+ _backend="office",)return page_infodiff --git a/mineru/backend/pipeline/model_output_to_middle_json.py b/mineru/backend/pipeline/model_output_to_middle_json.pyindex cb020ed6..80a9d368 100644--- a/mineru/backend/pipeline/model_output_to_middle_json.py+++ b/mineru/backend/pipeline/model_output_to_middle_json.py@@ -51,6 +51,7 @@ def blocks_to_page_info(page_idx=page_index,page_size=(page_w, page_h),discarded_blocks=discarded_blocks,+ _backend="pipeline",)diff --git a/mineru/backend/pipeline/pipeline_magic_model.py b/mineru/backend/pipeline/pipeline_magic_model.pyindex 258b5f9d..3adca705 100644--- a/mineru/backend/pipeline/pipeline_magic_model.py+++ b/mineru/backend/pipeline/pipeline_magic_model.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom copy import deepcopyfrom typing import TYPE_CHECKING, Any+from ...render.merge import _merge_para_textfrom ...types import EMPTY_BBOX, BBox, Block, Line, Spanfrom ...utils.enum_class import BlockType, ContentTypefrom ...utils.guess_suffix_or_lang import guess_language_by_text@@ -21,7 +22,6 @@ from ..utils.visual_magic_model_utils import (fallback_leading_table_continuation_captions,find_best_visual_parent,)-from .pipeline_middle_json_mkcontent import _merge_para_textif TYPE_CHECKING:from PIL.Image import Image as PILImage@@ -164,7 +164,7 @@ class MagicModel:for line in sort_block_lines:line._is_list_start = True_temp_block = Block(index=0, type="", bbox=EMPTY_BBOX, lines=sort_block_lines)- code_content = _merge_para_text(_temp_block, False, "\n")+ code_content = _merge_para_text(_temp_block, escape_markdown=False, list_line_break="\n")guess_lang = guess_language_by_text(code_content)if guess_lang not in ["txt", "unknown"]:block.sub_type = "code"diff --git a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.pyindex 82c47f4d..1d189c08 100644--- a/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py+++ b/mineru/backend/pipeline/pipeline_middle_json_mkcontent.py@@ -1,256 +1,24 @@# Copyright (c) Opendatalab. All rights reserved.from __future__ import annotations-import re-from copy import deepcopy-from html import unescapefrom typing import Anyfrom loguru import logger-from ...types import BBox, Block, IntBBox, Line, PageInfo, Span-from ...utils.config_reader import get_latex_delimiter_config+from ...render.markdown import _get_title_level, blocks_to_markdown+from ...render.merge import (+ CJK_LANGS,+ _collect_text_for_lang_detection,+ _next_line_starts_with_lowercase_text,+ _normalize_text_content,+ merge_para_text,+)+from ...render.merge_visual import _format_embedded_html, _inherit_parent_code_render_metadata, _normalize_visual_content+from ...types import BBox, Block, IntBBox, Line, PageInfofrom ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeModefrom ...utils.language import detect_lang-from ..utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end-from ..utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix---def make_blocks_to_markdown(paras_of_layout: list[Block], mode: str, img_bucket_path: str = "") -> list[str]:- page_markdown = []- for para_block in paras_of_layout:- para_text = ""- para_type = para_block.type- if para_type in [BlockType.TEXT, BlockType.LIST, BlockType.INDEX, BlockType.ABSTRACT, BlockType.REF_TEXT]:- para_text = merge_para_with_text(para_block)- elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)- para_text = f"{'#' * title_level} {merge_para_with_text(para_block)}"- elif para_type == BlockType.INTERLINE_EQUATION:- if len(para_block.lines) == 0 or len(para_block.lines[0].spans) == 0:- continue- if para_block.lines[0].spans[0].content:- para_text = merge_para_with_text(para_block)- else:- para_text = f""- elif para_type == BlockType.IMAGE:- if mode == MakeMode.NLP_MD:- continue- elif mode == MakeMode.MM_MD:- para_text = merge_visual_blocks_to_markdown(para_block, img_bucket_path)- elif para_type == BlockType.CHART:- if mode == MakeMode.NLP_MD:- continue- elif mode == MakeMode.MM_MD:- para_text = merge_visual_blocks_to_markdown(para_block, img_bucket_path)- elif para_type == BlockType.TABLE:- if mode == MakeMode.NLP_MD:- continue- elif mode == MakeMode.MM_MD:- para_text = merge_visual_blocks_to_markdown(para_block, img_bucket_path)- elif para_type == BlockType.CODE:- para_text = merge_visual_blocks_to_markdown(para_block)-- if para_text.strip() == "":- continue- else:- page_markdown.append(para_text.strip())-- return page_markdown---def merge_visual_blocks_to_markdown(para_block: Block, img_bucket_path: str = "") -> str:- # 将 image/table/chart/code 这类视觉块的子 block 按阅读顺序拼接成 markdown。- # 这里不再写死 caption/body/footnote 的优先级,而是先展开成 segment,- # 再根据 markdown_line / html_block 两类片段决定分隔方式。- rendered_segments = []-- for block in get_blocks_in_index_order(para_block.blocks):- render_block = _inherit_parent_code_render_metadata(block, para_block)- rendered_segments.extend(render_visual_block_segments(render_block, img_bucket_path, para_block))-- para_text = ""- prev_segment_kind = None- for segment_text, segment_kind in rendered_segments:- if para_text:- para_text += get_visual_block_separator(prev_segment_kind, segment_kind)- para_text += segment_text- prev_segment_kind = segment_kind-- return para_text---def get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:- # 按 middle json 中的 index 排序子 block;- # 如果 index 缺失,则退化为保持原始顺序。- return [- block- for _, block in sorted(- enumerate(blocks),- key=lambda item: (item[1].index, item[0]),- )- ]---def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block:- # pipeline_magic_model 会把 code_body 的 sub_type/guess_lang 提升到父 code block。- # markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。- if block.type != BlockType.CODE_BODY:- return block- if parent_block.type != BlockType.CODE:- return block-- needs_sub_type = not block.sub_type and parent_block.sub_type- needs_guess_lang = not block.guess_lang and parent_block.guess_lang- if not needs_sub_type and not needs_guess_lang:- return block-- render_block = deepcopy(block)- if needs_sub_type:- render_block.sub_type = parent_block.sub_type- if needs_guess_lang:- render_block.guess_lang = parent_block.guess_lang- return render_block---def render_visual_block_segments(- block: Block, img_bucket_path: str = "", para_block: Block | None = None-) -> list[tuple[str, str]]:- # 将单个视觉子 block 渲染成一个或多个 segment。- # 文本类子块统一输出 markdown_line;- # table 的 html 输出为 html_block,供后续决定是否需要空行隔开。- block_type = block.type-- if block_type in [- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_FOOTNOTE,- BlockType.TABLE_CAPTION,- BlockType.TABLE_FOOTNOTE,- BlockType.CODE_BODY,- BlockType.CODE_CAPTION,- BlockType.CODE_FOOTNOTE,- BlockType.CHART_CAPTION,- BlockType.CHART_FOOTNOTE,- ]:- block_text = merge_para_with_text(block)- if block_text.strip():- return [(block_text, "markdown_line")]- return []-- if block_type == BlockType.IMAGE_BODY:- rendered_segments = []- for line in block.lines:- for span in line.spans:- if span.type != ContentType.IMAGE:- continue- if span.image_path:- rendered_segments.append((f"", "markdown_line"))- details_block = _build_visual_details_block(- span.content, (para_block.sub_type if para_block else None) or "image content"- )- if details_block:- rendered_segments.append((details_block, "details_block"))- return rendered_segments-- if block_type == BlockType.CHART_BODY:- return [- (f"", "markdown_line")- for line in block.lines- for span in line.spans- if span.type == ContentType.CHART and span.image_path- ]-- if block_type == BlockType.TABLE_BODY:- rendered_segments = []- for line in block.lines:- for span in line.spans:- if span.type != ContentType.TABLE:- continue- if span.html:- rendered_segments.append((_format_embedded_html(span.html, img_bucket_path), "html_block"))- elif span.image_path:- rendered_segments.append((f"", "markdown_line"))- return rendered_segments-- return []---def get_visual_block_separator(prev_segment_kind: str | None, current_segment_kind: str) -> str:- # 根据前后 segment 类型决定分隔符:- # 1. 普通 markdown 行之间用 hard break(" \\n")- # 2. 进入 html block 前只换一行- # 3. html block 后必须留空行,否则后续文本仍会被当作 html 块内容- if prev_segment_kind == "html_block":- # Raw HTML blocks need a blank line after them, otherwise the following- # markdown text is still treated as part of the HTML block.- return "\n\n"- if prev_segment_kind == "details_block" or current_segment_kind == "details_block":- return "\n\n"- if current_segment_kind == "html_block":- return "\n"- return " \n"---latex_delimiters_config = get_latex_delimiter_config()--default_delimiters = {"display": {"left": "$$", "right": "$$"}, "inline": {"left": "$", "right": "$"}}--delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters--display_left_delimiter = delimiters["display"]["left"]-display_right_delimiter = delimiters["display"]["right"]-inline_left_delimiter = delimiters["inline"]["left"]-inline_right_delimiter = delimiters["inline"]["right"]--CJK_LANGS = {"zh", "ja", "ko"}---def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:- """Prefix non-data image sources in table HTML with img_bucket_path."""- if not html or not img_bucket_path:- return html-- return re.sub(- r'src="(?!data:)([^"]+)"',- lambda match: f'src="{img_bucket_path}/{match.group(1)}"',- html,- )---def _replace_eq_tags_in_table_html(html: str) -> str:- """Replace <eq>...</eq> tags in table HTML with inline math delimiters."""- if not html:- return html-- return re.sub(- r"<eq>(.*?)</eq>",- lambda match: f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} ",- html,- flags=re.DOTALL,- )---def _format_embedded_html(html: str, img_bucket_path: str) -> str:- """Normalize embedded table HTML for markdown/content outputs."""- return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))---def _normalize_visual_content(content: str) -> str:- """将视觉块识别内容统一成字符串,便于 markdown 和结构化输出复用。"""- if isinstance(content, list):- return "\n".join(str(item) for item in content if str(item).strip())- if isinstance(content, str):- return content.strip()- return ""---def _build_visual_details_block(content: str, summary: str) -> str:- """根据视觉块的识别文本生成 VLM 风格的折叠详情块。"""- normalized_content = _normalize_visual_content(content)- if not normalized_content:- return ""-- return f"<details>\n<summary>{summary}</summary>\n\n{normalized_content}\n</details>"+from ..utils.char_utils import is_hyphen_at_line_end+from ..utils.markdown_utils import escape_conservative_markdown_textdef _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:@@ -260,159 +28,6 @@ def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> Npara_content["sub_type"] = sub_type-def merge_para_with_text(para_block: Block) -> str:- if _is_fenced_code_block(para_block):- code_text = _merge_para_text(para_block, escape_markdown=False, list_line_break="\n")- if not code_text:- return ""- code_text = "\n".join(line.rstrip() for line in code_text.split("\n"))- guess_lang = para_block.guess_lang or "txt"- return f"```{guess_lang}\n{code_text}\n```"-- para_text = _merge_para_text(para_block)- if para_block.type == BlockType.TEXT:- para_text = escape_text_block_markdown_prefix(para_text)- return para_text---def _merge_para_text(para_block: Block, escape_markdown: bool = True, list_line_break: str = " \n") -> str:- # 将普通文本段落 block 渲染成 markdown 字符串。- # 处理流程分为三层:- # 1. 先收集文本内容做语言检测- # 2. 再把每个 span 渲染成 markdown 片段- # 3. 最后按语言和上下文决定 span 之间如何补空格/换行- block_lang = detect_lang(_collect_text_for_lang_detection(para_block))- para_parts = []-- for line_idx, line in enumerate(para_block.lines):- line_prefix = _line_prefix(line_idx, line, list_line_break)- if line_prefix:- para_parts.append(line_prefix)-- for span_idx, span in enumerate(line.spans):- rendered_span = _render_span(span, escape_markdown=escape_markdown)- if rendered_span is None:- continue-- span_type, content = rendered_span- content, suffix = _join_rendered_span(- para_block,- block_lang,- line,- line_idx,- span_idx,- span_type,- content,- )- para_parts.append(content)- if suffix:- para_parts.append(suffix)-- return "".join(para_parts).rstrip()---def _is_fenced_code_block(para_block: Block) -> bool:- return para_block.type == BlockType.CODE_BODY and para_block.sub_type == BlockType.CODE---def _collect_text_for_lang_detection(para_block: Block) -> str:- # 只收集 TEXT span 的内容,用于语言检测。- # 这里会先做全角转半角,但不会修改原始输入数据。- block_text_parts = []- for line in para_block.lines:- for span in line.spans:- if span.type == ContentType.TEXT:- block_text_parts.append(_normalize_text_content(span.content))- return "".join(block_text_parts)---def _normalize_text_content(content: str) -> str:- # 对原始文本做统一归一化,当前只负责全角转半角。- # 单独拆出来是为了让语言检测和渲染阶段复用同一套文本预处理。- return full_to_half_exclude_marks(content or "")---def _render_span(span: Span, escape_markdown: bool = True) -> tuple[str, str] | None:- # 将单个 span 渲染成 markdown 片段。- # 这里只负责“渲染成什么文本”,不决定后面是否补空格。- span_type = span.type- content = ""-- if span_type == ContentType.TEXT:- content = _normalize_text_content(span.content)- if escape_markdown:- content = escape_special_markdown_char(content)- elif span_type == ContentType.INLINE_EQUATION:- if span.content:- content = f"{inline_left_delimiter}{span.content}{inline_right_delimiter}"- elif span_type == ContentType.INTERLINE_EQUATION:- if span.content:- content = f"\n{display_left_delimiter}\n{span.content}\n{display_right_delimiter}\n"- else:- return None-- content = content.strip()- if not content:- return None-- return span_type, content---def _join_rendered_span(- para_block: Block, block_lang: str, line: Line, line_idx: int, span_idx: int, span_type: str, content: str-) -> tuple[str, str]:- # 根据语言和上下文决定当前 span 后面的分隔符。- # 这里集中处理:- # 1. CJK 与西文的空格差异- # 2. 西文行尾连字符是否需要跨行合并- # 3. 独立公式是否作为块内容直接插入- if span_type == ContentType.INTERLINE_EQUATION:- return content, ""-- is_last_span = span_idx == len(line.spans) - 1-- if block_lang in CJK_LANGS:- if is_last_span and span_type != ContentType.INLINE_EQUATION:- return content, ""- return content, " "-- if span_type not in [ContentType.TEXT, ContentType.INLINE_EQUATION]:- return content, ""-- if is_last_span and span_type == ContentType.TEXT and is_hyphen_at_line_end(content):- if _next_line_starts_with_lowercase_text(para_block, line_idx):- return content[:-1], ""- return content, ""-- return content, " "---def _line_prefix(line_idx: int, line: Line, list_line_break: str = " \n") -> str:- # 处理进入新 list item 前的 block 级换行。- # 这里保留历史语义:list 起始行前插入一个 hard break。- if line_idx >= 1 and line._is_list_start:- return list_line_break- return ""---def _next_line_starts_with_lowercase_text(para_block: Block, line_idx: int) -> bool:- # 判断下一行是否以小写英文文本开头。- # 这个条件用于决定西文行尾的连字符是否应与下一行合并。- if line_idx + 1 >= len(para_block.lines):- return False-- next_line_spans = para_block.lines[line_idx + 1].spans- if not next_line_spans:- return False-- next_span = next_line_spans[0]- if next_span.type != ContentType.TEXT:- return False-- next_content = _normalize_text_content(next_span.content)- return bool(next_content) and next_content[0].islower()--def merge_adjacent_ref_text_blocks_for_content(para_blocks: list[Block]) -> list[Block]:merged_blocks = []ref_group = []@@ -592,7 +207,7 @@ def make_blocks_to_content_list(]:para_content = {"type": ContentType.TEXT,- "text": merge_para_with_text(para_block),+ "text": merge_para_text(para_block),}elif para_type in [BlockType.HEADER,@@ -603,7 +218,7 @@ def make_blocks_to_content_list(]:para_content = {"type": para_type,- "text": merge_para_with_text(para_block),+ "text": merge_para_text(para_block),}elif para_type == BlockType.REF_TEXT:para_content = {@@ -612,15 +227,15 @@ def make_blocks_to_content_list("list_items": [],}for block in _get_ref_text_item_blocks(para_block):- item_text = merge_para_with_text(block)+ item_text = merge_para_text(block)if item_text.strip():para_content["list_items"].append(item_text)elif para_type == BlockType.TITLE:para_content = {"type": ContentType.TEXT,- "text": merge_para_with_text(para_block),+ "text": merge_para_text(para_block),}- title_level = get_title_level(para_block)+ title_level = _get_title_level(para_block)if title_level != 0:para_content["text_level"] = title_levelelif para_type == BlockType.INTERLINE_EQUATION:@@ -631,7 +246,7 @@ def make_blocks_to_content_list("img_path": f"{img_bucket_path}/{para_block.lines[0].spans[0].image_path}",}if para_block.lines[0].spans[0].content:- para_content["text"] = merge_para_with_text(para_block)+ para_content["text"] = merge_para_text(para_block)para_content["text_format"] = "latex"elif para_type == BlockType.IMAGE:para_content = {"type": ContentType.IMAGE, "img_path": "", BlockType.IMAGE_CAPTION: [], BlockType.IMAGE_FOOTNOTE: []}@@ -649,9 +264,9 @@ def make_blocks_to_content_list(if span.image_path:para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"if block.type == BlockType.IMAGE_CAPTION:- para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.IMAGE_CAPTION].append(merge_para_text(block))if block.type == BlockType.IMAGE_FOOTNOTE:- para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_text(block))elif para_type == BlockType.TABLE:para_content = {"type": ContentType.TABLE, "img_path": "", BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}for block in para_block.blocks:@@ -665,9 +280,9 @@ def make_blocks_to_content_list(para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"if block.type == BlockType.TABLE_CAPTION:- para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.TABLE_CAPTION].append(merge_para_text(block))if block.type == BlockType.TABLE_FOOTNOTE:- para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_text(block))elif para_type == BlockType.CHART:para_content = {"type": ContentType.CHART,@@ -683,9 +298,9 @@ def make_blocks_to_content_list(if span.type == ContentType.CHART and span.image_path:para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"if block.type == BlockType.CHART_CAPTION:- para_content[BlockType.CHART_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.CHART_CAPTION].append(merge_para_text(block))if block.type == BlockType.CHART_FOOTNOTE:- para_content[BlockType.CHART_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.CHART_FOOTNOTE].append(merge_para_text(block))elif para_type == BlockType.CODE:para_content = {"type": BlockType.CODE,@@ -696,11 +311,11 @@ def make_blocks_to_content_list(for block in para_block.blocks:render_block = _inherit_parent_code_render_metadata(block, para_block)if block.type == BlockType.CODE_BODY:- para_content[BlockType.CODE_BODY] = merge_para_with_text(render_block)+ para_content[BlockType.CODE_BODY] = merge_para_text(render_block)if block.type == BlockType.CODE_CAPTION:- para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.CODE_CAPTION].append(merge_para_text(block))if block.type == BlockType.CODE_FOOTNOTE:- para_content[BlockType.CODE_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.CODE_FOOTNOTE].append(merge_para_text(block))if not para_content:return None@@ -743,7 +358,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page},}elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)+ title_level = _get_title_level(para_block)if title_level != 0:para_content = {"type": ContentTypeV2.TITLE,@@ -958,7 +573,11 @@ def union_make(if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:if not paras_of_layout:continue- page_markdown = make_blocks_to_markdown(paras_of_layout, make_mode, img_bucket_path)+ page_markdown = blocks_to_markdown(+ para_blocks=paras_of_layout,+ img_bucket_path=img_bucket_path,+ no_rich_content=(make_mode == MakeMode.NLP_MD),+ )output_markdowns.extend(page_markdown)elif make_mode == MakeMode.CONTENT_LIST:para_blocks = merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))@@ -989,15 +608,6 @@ def union_make(return None-def get_title_level(block: Block) -> int:- title_level = block.level- if title_level is None:- title_level = 1- if title_level < 1:- title_level = 0- return title_level--def escape_special_markdown_char(content: str) -> str:"""转义正文里对markdown语法有特殊意义的字符diff --git a/mineru/backend/utils/markdown_utils.py b/mineru/backend/utils/markdown_utils.pyindex e29d6efe..471f2b21 100644--- a/mineru/backend/utils/markdown_utils.py+++ b/mineru/backend/utils/markdown_utils.py@@ -6,6 +6,7 @@ CONSERVATIVE_MARKDOWN_SPECIAL_CHARS = ("*", "_", "`", "~", "$")TEXT_BLOCK_MARKDOWN_PREFIX_RE = re.compile(r"^(?P<indent>[ \t]{0,3})(?P<marker>#{1,6}|[+-])(?=[ \t])")+# DONE in renderdef escape_conservative_markdown_text(content: str) -> str:"""Escape plain-text characters that carry inline Markdown semantics."""if not content:@@ -29,6 +30,7 @@ def escape_conservative_markdown_text(content: str) -> str:return "".join(escaped_chars)+# DONE in renderdef escape_text_block_markdown_prefix(content: str) -> str:"""Escape a leading Markdown block marker in an assembled text block."""if not content:diff --git a/mineru/backend/utils/middle_json_utils.py b/mineru/backend/utils/middle_json_utils.pyindex d0bf8566..5c910180 100644--- a/mineru/backend/utils/middle_json_utils.py+++ b/mineru/backend/utils/middle_json_utils.py@@ -57,6 +57,7 @@ def append_pages(page_idx=page_index,page_size=(page_w, page_h),discarded_blocks=[],+ _backend=None,)finally:close_pdfium_child(page)diff --git a/mineru/backend/utils/table_merge.py b/mineru/backend/utils/table_merge.pyindex 0ecbe5d9..7d64d806 100644--- a/mineru/backend/utils/table_merge.py+++ b/mineru/backend/utils/table_merge.py@@ -7,9 +7,9 @@ from typing import Anyfrom bs4 import BeautifulSoup, Tag+from ...render.merge import merge_para_textfrom ...types import BBox, Block, PageInfo, Spanfrom ...utils.enum_class import BlockType-from ..vlm.vlm_middle_json_mkcontent import merge_para_with_textfrom .char_utils import full_to_halffrom .table_continuation import is_table_continuation_text@@ -210,7 +210,7 @@ def _find_table_body_span(table_block: Block) -> Span | None:def _is_continuation_caption(caption_block: Block) -> bool:"""判断 caption 文本是否带有续表标记。"""- return is_table_continuation_text(merge_para_with_text(caption_block))+ return is_table_continuation_text(merge_para_text(caption_block))def _is_post_table_non_continuation_caption(table_block: Block, caption_block: Block) -> bool:diff --git a/mineru/backend/vlm/model_output_to_middle_json.py b/mineru/backend/vlm/model_output_to_middle_json.pyindex 9fcc8bbd..1d43cb99 100644--- a/mineru/backend/vlm/model_output_to_middle_json.py+++ b/mineru/backend/vlm/model_output_to_middle_json.py@@ -82,6 +82,7 @@ def blocks_to_page_info(discarded_blocks=discarded_blocks,page_size=(width, height),page_idx=page_index,+ _backend="vlm",)return page_infodiff --git a/mineru/backend/vlm/vlm_middle_json_mkcontent.py b/mineru/backend/vlm/vlm_middle_json_mkcontent.pyindex b0f17da9..25f2465c 100644--- a/mineru/backend/vlm/vlm_middle_json_mkcontent.py+++ b/mineru/backend/vlm/vlm_middle_json_mkcontent.py@@ -1,68 +1,17 @@# Copyright (c) Opendatalab. All rights reserved.import os-import re-from html import unescapefrom typing import Anyfrom loguru import logger+from ...render.markdown import _get_title_level, blocks_to_markdown+from ...render.merge import _normalize_text_content, merge_para_text+from ...render.merge_visual import _build_media_path, _format_embedded_htmlfrom ...types import Block, Line, PageInfo-from ...utils.config_reader import get_formula_enable, get_latex_delimiter_config, get_table_enable+from ...utils.config_reader import get_formula_enable, get_table_enablefrom ...utils.enum_class import BlockType, ContentType, ContentTypeV2, MakeModefrom ...utils.language import detect_lang-from ..utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end-from ..utils.markdown_utils import escape_conservative_markdown_text, escape_text_block_markdown_prefix--latex_delimiters_config = get_latex_delimiter_config()--default_delimiters = {- "display": {"left": "$$", "right": "$$"},- "inline": {"left": "$", "right": "$"},-}--delimiters = latex_delimiters_config if latex_delimiters_config else default_delimiters--display_left_delimiter = delimiters["display"]["left"]-display_right_delimiter = delimiters["display"]["right"]-inline_left_delimiter = delimiters["inline"]["left"]-inline_right_delimiter = delimiters["inline"]["right"]---def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:- """Prefix non-data image sources in table HTML with img_bucket_path."""- if not html or not img_bucket_path:- return html-- return re.sub(- r'src="(?!data:)([^"]+)"',- lambda match: f'src="{img_bucket_path}/{match.group(1)}"',- html,- )---def _replace_eq_tags_in_table_html(html: str) -> str:- """Replace <eq>...</eq> tags in table HTML with inline math delimiters."""- if not html:- return html-- return re.sub(- r"<eq>(.*?)</eq>",- lambda match: f" {inline_left_delimiter}{unescape(match.group(1))}{inline_right_delimiter} ",- html,- flags=re.DOTALL,- )---def _format_embedded_html(html: str, img_bucket_path: str) -> str:- """Normalize embedded table HTML for markdown/content outputs."""- return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))---def _normalize_text_content(content: str | None) -> str:- """将 VLM 文本 span 的空 content 规范为空字符串,再做全角转半角。"""- if content is None:- return ""- return full_to_half_exclude_marks(content)+from ..utils.char_utils import is_hyphen_at_line_enddef _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: int) -> bool:@@ -81,326 +30,12 @@ def _has_following_joinable_span(para_block: Block, line_idx: int, span_idx: intreturn False-def _build_media_path(img_bucket_path: str, image_path: str) -> str:- if not image_path:- return ""- if not img_bucket_path:- return image_path- return f"{img_bucket_path}/{image_path}"--def _apply_visual_sub_type(para_content: dict[str, Any], para_block: Block) -> None:sub_type = para_block.sub_typeif sub_type:para_content["sub_type"] = sub_type-def _build_visual_details_block(content: str, span_type: str, summary_override: str = "") -> str:- if not isinstance(content, str) or not content.strip():- return ""-- if span_type == ContentType.CHART:- summary = summary_override or "chart content"- else:- summary = summary_override or "image content"-- return f"<details>\n<summary>{summary}</summary>\n\n{content}\n</details>"---def _build_visual_body_segments(- image_path: str, content: str, img_bucket_path: str, span_type: str, summary_override: str = ""-) -> list[tuple[str, str]]:- body_segments = []- media_path = _build_media_path(img_bucket_path, image_path)- if media_path:- body_segments.append((f"", "markdown_line"))-- details_block = _build_visual_details_block(- content,- span_type,- summary_override=summary_override,- )- if details_block:- body_segments.append((details_block, "html_block"))-- return body_segments---def _get_blocks_in_index_order(blocks: list[Block]) -> list[Block]:- return [- block- for _, block in sorted(- enumerate(blocks),- key=lambda item: (item[1].index, item[0]),- )- ]---def _render_code_block_markdown(block: Block, para_block: Block) -> str:- code_text = merge_para_with_text(block)- if para_block.sub_type == BlockType.CODE:- guess_lang = para_block.guess_lang or "txt"- return f"```{guess_lang}\n{code_text}\n```"- return code_text---def _render_visual_block_segments(- block: Block, para_block: Block, img_bucket_path: str = "", table_enable: bool = True-) -> list[tuple[str, str]]:- block_type = block.type-- if block_type in [- BlockType.IMAGE_CAPTION,- BlockType.IMAGE_FOOTNOTE,- BlockType.TABLE_CAPTION,- BlockType.TABLE_FOOTNOTE,- BlockType.CODE_CAPTION,- BlockType.CODE_FOOTNOTE,- BlockType.CHART_CAPTION,- BlockType.CHART_FOOTNOTE,- ]:- block_text = merge_para_with_text(block)- if block_text.strip():- return [(block_text, "markdown_line")]- return []-- if block_type == BlockType.IMAGE_BODY:- rendered_segments = []- for line in block.lines:- for span in line.spans:- if span.type != ContentType.IMAGE:- continue- rendered_segments.extend(- _build_visual_body_segments(- span.image_path,- span.content,- img_bucket_path,- ContentType.IMAGE,- summary_override=para_block.sub_type,- )- )- return rendered_segments-- if block_type == BlockType.CHART_BODY:- rendered_segments = []- for line in block.lines:- for span in line.spans:- if span.type != ContentType.CHART:- continue- rendered_segments.extend(- _build_visual_body_segments(- span.image_path,- span.content,- img_bucket_path,- ContentType.CHART,- summary_override=para_block.sub_type,- )- )- return rendered_segments-- if block_type == BlockType.TABLE_BODY:- rendered_segments = []- for line in block.lines:- for span in line.spans:- if span.type != ContentType.TABLE:- continue- if table_enable and span.html:- rendered_segments.append(- (- _format_embedded_html(span.html, img_bucket_path),- "html_block",- )- )- elif span.image_path:- rendered_segments.append(- (- f"})",- "markdown_line",- )- )- return rendered_segments-- if block_type == BlockType.CODE_BODY:- block_text = _render_code_block_markdown(block, para_block)- if block_text.strip():- return [(block_text, "markdown_line")]- return []-- return []---def _get_visual_block_separator(prev_segment_kind: str, current_segment_kind: str) -> str:- if prev_segment_kind == "html_block" or current_segment_kind == "html_block":- return "\n\n"- return " \n"---def _merge_visual_blocks_to_markdown(para_block: Block, img_bucket_path: str = "", table_enable: bool = True) -> str:- rendered_segments = []- for block in _get_blocks_in_index_order(para_block.blocks):- rendered_segments.extend(- _render_visual_block_segments(- block,- para_block,- img_bucket_path,- table_enable=table_enable,- )- )-- para_text = ""- prev_segment_kind = ""- for segment_text, segment_kind in rendered_segments:- if para_text:- para_text += _get_visual_block_separator(prev_segment_kind, segment_kind)- para_text += segment_text- prev_segment_kind = segment_kind-- return para_text---def merge_para_with_text(- para_block: Block,- formula_enable: bool = True,- img_bucket_path: str = "",- escape_text_block_prefix: bool = True,-) -> str:- block_text = ""- for line in para_block.lines:- for span in line.spans:- if span.type in [ContentType.TEXT]:- span.content = _normalize_text_content(span.content)- block_text += span.content- block_lang = detect_lang(block_text)- escape_markdown_text = para_block.type != BlockType.CODE_BODY-- para_text = ""- for i, line in enumerate(para_block.lines):- for j, span in enumerate(line.spans):- span_type = span.type- content = ""- if span_type == ContentType.TEXT:- content = span.content- if escape_markdown_text:- content = escape_conservative_markdown_text(content)- elif span_type == ContentType.INLINE_EQUATION:- content = f"{inline_left_delimiter}{span.content}{inline_right_delimiter}"- elif span_type == ContentType.INTERLINE_EQUATION:- if formula_enable:- content = f"\n{display_left_delimiter}\n{span.content}\n{display_right_delimiter}\n"- else:- if span.image_path:- content = f""-- content = content.strip()- if content:- if span_type == ContentType.INTERLINE_EQUATION:- para_text += content- continue-- # 定义CJK语言集合(中日韩)- cjk_langs = {"zh", "ja", "ko"}- # logger.info(f'block_lang: {block_lang}, content: {content}')-- # 判断是否为行末span- is_last_span = j == len(line.spans) - 1- has_following_joinable_span = _has_following_joinable_span(para_block, i, j)-- if block_lang in cjk_langs: # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格- if has_following_joinable_span and (not is_last_span or span_type == ContentType.INLINE_EQUATION):- para_text += f"{content} "- else:- para_text += content- else:- # 西方文本语境下 每行的最后一个span判断是否要去除连字符- if span_type in [ContentType.TEXT, ContentType.INLINE_EQUATION]:- # 如果span是line的最后一个且末尾带有-连字符,那么末尾不应该加空格,同时应该把-删除- if is_last_span and span_type == ContentType.TEXT and is_hyphen_at_line_end(content):- # 如果下一行的第一个span是小写字母开头,删除连字符- if (- i + 1 < len(para_block.lines)- and para_block.lines[i + 1].spans- and para_block.lines[i + 1].spans[0].type == ContentType.TEXT- and para_block.lines[i + 1].spans[0].content- and para_block.lines[i + 1].spans[0].content[0].islower()- ):- para_text += content[:-1]- else: # 如果没有下一行,或者下一行的第一个span不是小写字母开头,则保留连字符但不加空格- para_text += content- else: # 西方文本语境下 content间需要空格分隔- if has_following_joinable_span:- para_text += f"{content} "- else:- para_text += content- if escape_text_block_prefix and para_block.type == BlockType.TEXT:- para_text = escape_text_block_markdown_prefix(para_text)- return para_text---def mk_blocks_to_markdown(- para_blocks: list[Block], make_mode: str, formula_enable: bool, table_enable: bool, img_bucket_path: str = ""-) -> list[str]:- page_markdown: list[str] = []- for para_block in para_blocks:- para_text = ""- para_type = para_block.type- if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION, BlockType.PHONETIC, BlockType.REF_TEXT]:- para_text = merge_para_with_text(para_block, formula_enable=formula_enable, img_bucket_path=img_bucket_path)- elif para_type == BlockType.LIST:- for block in para_block.blocks:- item_text = merge_para_with_text(- block,- formula_enable=formula_enable,- img_bucket_path=img_bucket_path,- escape_text_block_prefix=False,- )- para_text += f"{item_text} \n"- elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)- para_text = f"{'#' * title_level} {merge_para_with_text(para_block)}"- elif para_type == BlockType.IMAGE:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- para_text = _merge_visual_blocks_to_markdown(- para_block,- img_bucket_path,- table_enable=table_enable,- )-- elif para_type == BlockType.TABLE:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- para_text = _merge_visual_blocks_to_markdown(- para_block,- img_bucket_path,- table_enable=table_enable,- )- elif para_type == BlockType.CHART:- if make_mode == MakeMode.NLP_MD:- continue- elif make_mode == MakeMode.MM_MD:- para_text = _merge_visual_blocks_to_markdown(- para_block,- img_bucket_path,- table_enable=table_enable,- )- elif para_type == BlockType.CODE:- para_text = _merge_visual_blocks_to_markdown(- para_block,- img_bucket_path,- table_enable=table_enable,- )-- if para_text.strip() == "":- continue- else:- # page_markdown.append(para_text.strip() + ' ')- page_markdown.append(para_text.strip())-- return page_markdown--def make_blocks_to_content_list(para_block: Block, img_bucket_path: str, page_idx: int, page_size: tuple[int, int]) -> dict[str, Any]:@@ -419,30 +54,31 @@ def make_blocks_to_content_list(]:para_content = {"type": para_type,- "text": merge_para_with_text(para_block),+ "text": merge_para_text(para_block),}elif para_type == BlockType.LIST:+ # TODO: Now merge_para_text can handle LIST.para_content = {"type": para_type,"sub_type": para_block.sub_type,"list_items": [],}for block in para_block.blocks:- item_text = merge_para_with_text(block, escape_text_block_prefix=False)+ item_text = merge_para_text(block, escape_text_block_prefix=False)if item_text.strip():para_content["list_items"].append(item_text)elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)+ title_level = _get_title_level(para_block)para_content = {"type": ContentType.TEXT,- "text": merge_para_with_text(para_block),+ "text": merge_para_text(para_block),}if title_level != 0:para_content["text_level"] = title_levelelif para_type == BlockType.INTERLINE_EQUATION:para_content = {"type": ContentType.EQUATION,- "text": merge_para_with_text(para_block),+ "text": merge_para_text(para_block),"text_format": "latex",}elif para_type == BlockType.IMAGE:@@ -453,9 +89,9 @@ def make_blocks_to_content_list(_apply_visual_sub_type(para_content, para_block)for block in para_block.blocks:if block.type == BlockType.IMAGE_CAPTION:- para_content[BlockType.IMAGE_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.IMAGE_CAPTION].append(merge_para_text(block))if block.type == BlockType.IMAGE_FOOTNOTE:- para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.IMAGE_FOOTNOTE].append(merge_para_text(block))elif para_type == BlockType.TABLE:para_content = {"type": ContentType.TABLE, "img_path": "", BlockType.TABLE_CAPTION: [], BlockType.TABLE_FOOTNOTE: []}for block in para_block.blocks:@@ -469,9 +105,9 @@ def make_blocks_to_content_list(para_content["img_path"] = f"{img_bucket_path}/{span.image_path}"if block.type == BlockType.TABLE_CAPTION:- para_content[BlockType.TABLE_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.TABLE_CAPTION].append(merge_para_text(block))if block.type == BlockType.TABLE_FOOTNOTE:- para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.TABLE_FOOTNOTE].append(merge_para_text(block))elif para_type == BlockType.CHART:image_path, chart_content = get_body_data(para_block)para_content = {@@ -484,20 +120,20 @@ def make_blocks_to_content_list(_apply_visual_sub_type(para_content, para_block)for block in para_block.blocks:if block.type == BlockType.CHART_CAPTION:- para_content[BlockType.CHART_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.CHART_CAPTION].append(merge_para_text(block))if block.type == BlockType.CHART_FOOTNOTE:- para_content[BlockType.CHART_FOOTNOTE].append(merge_para_with_text(block))+ para_content[BlockType.CHART_FOOTNOTE].append(merge_para_text(block))elif para_type == BlockType.CODE:para_content = {"type": BlockType.CODE, "sub_type": para_block.sub_type, BlockType.CODE_CAPTION: []}for block in para_block.blocks:if block.type == BlockType.CODE_BODY:- code_text = merge_para_with_text(block)+ code_text = merge_para_text(block)if para_block.sub_type == BlockType.CODE:guess_lang = para_block.guess_lang or "txt"code_text = f"```{guess_lang}\n{code_text}\n```"para_content[BlockType.CODE_BODY] = code_textif block.type == BlockType.CODE_CAPTION:- para_content[BlockType.CODE_CAPTION].append(merge_para_with_text(block))+ para_content[BlockType.CODE_CAPTION].append(merge_para_text(block))page_width, page_height = page_sizepara_bbox = para_block.bbox@@ -544,7 +180,7 @@ def make_blocks_to_content_list_v2(para_block: Block, img_bucket_path: str, page},}elif para_type == BlockType.TITLE:- title_level = get_title_level(para_block)+ title_level = _get_title_level(para_block)if title_level != 0:para_content = {"type": ContentTypeV2.TITLE,@@ -867,7 +503,13 @@ def union_make(if make_mode in [MakeMode.MM_MD, MakeMode.NLP_MD]:if not paras_of_layout:continue- page_markdown = mk_blocks_to_markdown(paras_of_layout, make_mode, formula_enable, table_enable, img_bucket_path)+ page_markdown = blocks_to_markdown(+ para_blocks=paras_of_layout,+ img_bucket_path=img_bucket_path,+ table_as_image=not table_enable,+ formula_as_image=not formula_enable,+ no_rich_content=(make_mode == MakeMode.NLP_MD),+ )output_content.extend(page_markdown)elif make_mode == MakeMode.CONTENT_LIST:para_blocks = (paras_of_layout or []) + (paras_of_discarded or [])@@ -891,14 +533,3 @@ def union_make(elif make_mode in [MakeMode.CONTENT_LIST, MakeMode.CONTENT_LIST_V2]:return output_contentreturn None---def get_title_level(block: Block) -> int:- title_level = block.level- if title_level is None:- title_level = 1- if title_level > 4:- title_level = 4- elif title_level < 1:- title_level = 0- return title_leveldiff --git a/mineru/cli/client_side_output.py b/mineru/cli/client_side_output.pyindex 653d4fb0..ec690866 100644--- a/mineru/cli/client_side_output.py+++ b/mineru/cli/client_side_output.py@@ -15,22 +15,9 @@ SUPPORTED_BACKENDS = {*PDF_BACKENDS, "office"}def _select_union_make(backend: str) -> Callable[[list, str, str], Any]:"""根据 middle json 后端选择对应的 Markdown/content list 渲染函数。"""- if backend == "pipeline":- from mineru.backend.pipeline.pipeline_middle_json_mkcontent import union_make+ from mineru.render import render_markdown- return union_make- if backend in {"vlm", "hybrid"}:- from mineru.backend.vlm.vlm_middle_json_mkcontent import union_make-- return union_make- if backend == "office":- from mineru.backend.office.office_middle_json_mkcontent import union_make-- return union_make-- raise ValueError(- f"Unsupported middle json backend for client-side output generation: {backend}"- )+ return render_markdowndef _write_json(path: Path, payload: Any) -> None:diff --git a/mineru/cli/common.py b/mineru/cli/common.pyindex 05720e98..5b91b070 100644--- a/mineru/cli/common.py+++ b/mineru/cli/common.py@@ -13,12 +13,11 @@ from typing import Any, Callable, Sequencefrom loguru import loggerfrom mineru.backend.office.docx_analyze import office_docx_analyze-from mineru.backend.office.office_middle_json_mkcontent import union_make as office_union_makefrom mineru.backend.office.pptx_analyze import office_pptx_analyzefrom mineru.backend.office.xlsx_analyze import office_xlsx_analyzefrom mineru.backend.vlm.vlm_analyze import aio_doc_analyze as aio_vlm_doc_analyzefrom mineru.backend.vlm.vlm_analyze import doc_analyze as vlm_doc_analyze-from mineru.backend.vlm.vlm_middle_json_mkcontent import union_make as vlm_union_make+from mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.data.data_reader_writer import FileBasedDataWriterfrom mineru.utils.draw_bbox import draw_layout_bbox, draw_span_bboxfrom mineru.utils.engine_utils import get_vlm_engine@@ -256,16 +255,6 @@ def _process_output(process_mode: str,backend: str,) -> None:- from mineru.backend.pipeline.pipeline_middle_json_mkcontent import union_make as pipeline_union_make-- if process_mode == "pipeline":- make_func = pipeline_union_make- elif process_mode == "vlm":- make_func = vlm_union_make- elif process_mode in office_suffixes:- make_func = office_union_make- else:- raise Exception(f"Unknown process_mode: {process_mode}")"""处理输出文件"""if f_draw_layout_bbox:try:@@ -294,20 +283,20 @@ def _process_output(image_dir = str(os.path.basename(local_image_dir))if f_dump_md:- md_content_str = make_func(middle_json, f_make_md_mode, image_dir)+ md_content_str = render_markdown(middle_json, image_dir, make_mode=f_make_md_mode)md_writer.write_string(f"{pdf_file_name}.md",md_content_str,)if f_dump_content_list:- content_list = make_func(middle_json, MakeMode.CONTENT_LIST, image_dir)+ content_list = render_content_list(middle_json, image_dir)md_writer.write_string(f"{pdf_file_name}_content_list.json",json.dumps(content_list, ensure_ascii=False, indent=1),)- content_list_v2 = make_func(middle_json, MakeMode.CONTENT_LIST_V2, image_dir)+ content_list_v2 = render_content_list_v2(middle_json, image_dir)md_writer.write_string(f"{pdf_file_name}_content_list_v2.json",json.dumps(content_list_v2, ensure_ascii=False, indent=1),diff --git a/mineru/parser/parse_result.py b/mineru/parser/parse_result.pyindex 1102ac0c..e0614b1e 100644--- a/mineru/parser/parse_result.py+++ b/mineru/parser/parse_result.py@@ -8,6 +8,7 @@ import refrom dataclasses import dataclassfrom typing import Any+from mineru.render import render_content_list, render_content_list_v2, render_markdownfrom mineru.types import PageInfofrom ..utils.enum_class import MakeMode@@ -16,24 +17,8 @@ from ..utils.pdf_document import PDFDocument_INLINE_IMAGE_DATA_URI_RE = re.compile(r"data:image/([^;]+);base64,([^\"]+)", re.DOTALL)-def _load_union_make(backend: str):- if backend == "pipeline":- from ..backend.pipeline.pipeline_middle_json_mkcontent import union_make-- return union_make- if backend in ("vlm", "hybrid"):- from ..backend.vlm.vlm_middle_json_mkcontent import union_make-- return union_make- if backend == "flash":- return _flash_union_make- from ..backend.office.office_middle_json_mkcontent import union_make-- return union_make---def _flash_union_make(pages: list, mode) -> str | list:- """Minimal union_make for flash: just concatenate text from spans."""+def _render_flash_markdown(pages: list, mode) -> str | list:+ """Minimal markdown renderer for flash: just concatenate text from spans."""from ..utils.enum_class import MakeModeif mode == MakeMode.MM_MD:@@ -81,34 +66,30 @@ class ParseResult:return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)def markdown(self) -> str:- union_make = _load_union_make(self._backend)- markdown = union_make(self.pages, MakeMode.MM_MD)- assert isinstance(markdown, str)- return markdown+ if self._backend == "flash":+ return _render_flash_markdown(self.pages, MakeMode.MM_MD) # type: ignore[return-value]+ return render_markdown(self.pages)def markdown_with_markers(self, *, page_count: int | None = None) -> str:"""Generate markdown with page boundary markers (<!-- page N of M -->)."""total = page_count or len(self.pages)- union_make = _load_union_make(self._backend)parts: list[str] = []for p in self.pages:page_num = p.page_idx + 1 # 1-basedparts.append(f"<!-- page {page_num} of {total} -->")try:- page_md = union_make([p], MakeMode.MM_MD)- if isinstance(page_md, str) and page_md.strip():+ page_md = render_markdown([p])+ if page_md.strip():parts.append(page_md)except Exception:passreturn "\n\n".join(parts)def content_list(self) -> list[dict[str, Any]]:- union_make = _load_union_make(self._backend)- return union_make(self.pages, MakeMode.CONTENT_LIST) # type: ignore[return-value]+ return render_content_list(self.pages)def content_list_v2(self) -> list[dict[str, Any]]:- union_make = _load_union_make(self._backend)- return union_make(self.pages, MakeMode.CONTENT_LIST_V2) # type: ignore[return-value]+ return render_content_list_v2(self.pages)def save(self, writer: Any) -> None:prefix = self._file_namediff --git a/mineru/render/__init__.py b/mineru/render/__init__.pynew file mode 100644index 00000000..3269f36f--- /dev/null+++ b/mineru/render/__init__.py@@ -0,0 +1,7 @@+from .union_make import render_content_list, render_content_list_v2, render_markdown++__all__ = [+ "render_content_list",+ "render_content_list_v2",+ "render_markdown",+]diff --git a/mineru/render/markdown.py b/mineru/render/markdown.pynew file mode 100644index 00000000..6ed7bca6--- /dev/null+++ b/mineru/render/markdown.py@@ -0,0 +1,91 @@+from ..types import Block+from ..utils.enum_class import BlockType, ContentType+from .merge import merge_para_text+from .merge_visual import _build_media_path, merge_visual_para_text+++def blocks_to_markdown(+ para_blocks: list[Block],+ img_bucket_path: str = "",+ table_as_image: bool = False,+ formula_as_image: bool = False,+ no_rich_content: bool = False,+) -> list[str]:+ para_texts: list[str] = []+ for para_block in para_blocks:+ para_text = _block_to_markdown(+ para_block=para_block,+ img_bucket_path=img_bucket_path,+ table_as_image=table_as_image,+ formula_as_image=formula_as_image,+ no_rich_content=no_rich_content,+ )+ if para_text := (para_text or "").strip():+ para_texts.append(para_text)+ return para_texts+++def _block_to_markdown(+ para_block: Block,+ img_bucket_path: str = "",+ table_as_image: bool = False,+ formula_as_image: bool = False,+ no_rich_content: bool = False,+) -> str | None:+ para_type = para_block.type+ if para_type == BlockType.TEXT:+ return merge_para_text(para_block)+ if para_type == BlockType.TITLE:+ title_level = _get_title_level(para_block)+ return f"{'#' * title_level} {merge_para_text(para_block)}"+ if para_type == BlockType.INDEX:+ return merge_para_text(para_block)+ if para_type == BlockType.ABSTRACT:+ return merge_para_text(para_block)+ if para_type == BlockType.REF_TEXT:+ return merge_para_text(para_block)+ if para_type == BlockType.LIST:+ return merge_para_text(para_block)+ if para_type == BlockType.PHONETIC:+ return merge_para_text(para_block)+ if para_type == BlockType.CODE:+ return merge_visual_para_text(para_block)++ if para_type == BlockType.INTERLINE_EQUATION:+ if not formula_as_image:+ if (para_text := merge_para_text(para_block)).strip():+ return para_text+ return _build_image_link(para_block, ContentType.INTERLINE_EQUATION, img_bucket_path)++ if no_rich_content:+ return None+ if para_type == BlockType.IMAGE:+ return merge_visual_para_text(para_block, img_bucket_path)+ if para_type == BlockType.TABLE:+ if not table_as_image:+ return merge_visual_para_text(para_block, img_bucket_path)+ return _build_image_link(para_block, ContentType.TABLE, img_bucket_path)+ if para_type == BlockType.CHART:+ return merge_visual_para_text(para_block, img_bucket_path)+ return None+++def _get_title_level(block: Block) -> int:+ title_level = block.level+ if title_level is None:+ title_level = 1+ if title_level > 6:+ title_level = 6+ elif title_level < 1:+ title_level = 0+ return title_level+++def _build_image_link(block: Block, target_span_type: str, img_bucket_path: str) -> str | None:+ for line in block.lines:+ for span in line.spans:+ if span.type != target_span_type or not span.image_path:+ continue+ if media_path := _build_media_path(img_bucket_path, span.image_path):+ return f""+ return Nonediff --git a/mineru/render/merge.py b/mineru/render/merge.pynew file mode 100644index 00000000..5346154d--- /dev/null+++ b/mineru/render/merge.py@@ -0,0 +1,226 @@+# Copyright (c) Opendatalab. All rights reserved.+"""Unified paragraph-level text merging for Pipeline and VLM backends.++Produces a single Markdown string from a Block's line/spans, handling+language detection, CJK / western spacing, hyphen de-duplication, and+Markdown escaping.+"""++from __future__ import annotations++from ..backend.utils.char_utils import full_to_half_exclude_marks, is_hyphen_at_line_end+from ..types import Block, Line, Span+from ..utils.config_reader import get_latex_delimiter_config+from ..utils.enum_class import BlockType, ContentType+from ..utils.language import detect_lang++CJK_LANGS = frozenset({"zh", "ja", "ko"})++_latex_config = get_latex_delimiter_config()++if isinstance(_latex_config, dict):+ inline_left = _latex_config.get("inline_left", "$")+ inline_right = _latex_config.get("inline_right", "$")+ display_left = _latex_config.get("display_left", "$$")+ display_right = _latex_config.get("display_right", "$$")+else:+ inline_left = "$"+ inline_right = "$"+ display_left = "$$"+ display_right = "$$"++del _latex_config+++# ------------------------------------------------------------------ #+# Public API+# ------------------------------------------------------------------ #+++def merge_para_text(para_block: Block) -> str:+ """Convert a block's lines/spans into a single Markdown string.++ Accepted block types:+ TEXT, TITLE, INDEX, ABSTRACT, REF_TEXT, LIST, INTERLINE_EQUATION, PHONETIC+ {IMAGE/TABLE/CHART/CODE)_(CAPTION/FOOTNOTE), CODE_BODY++ Handles fenced code blocks, Markdown escaping, and TEXT-block prefix+ escape automatically.+ """+ if _is_fenced_code_block(para_block):+ code_text = _merge_para_text(para_block, escape_markdown=False, list_line_break="\n")+ if not code_text:+ return ""+ code_text = "\n".join(line.rstrip() for line in code_text.split("\n"))+ guess_lang = para_block.guess_lang or "txt"+ return f"```{guess_lang}\n{code_text}\n```"++ if para_block.type == BlockType.LIST and len(para_block.blocks):+ # (VLM) list block+ list_text = ""+ for block in para_block.blocks:+ item_text = _merge_para_text(block)+ list_text += f"{item_text} \n"+ return list_text++ para_text = _merge_para_text(para_block)+ if para_block.type == BlockType.TEXT: # (VLM) list do not escape+ para_text = _escape_text_block_markdown_prefix(para_text)+ return para_text+++# ------------------------------------------------------------------ #+# Internal helpers+# ------------------------------------------------------------------ #++import re # noqa: E402++_TEXT_BLOCK_MD_PREFIX_RE = re.compile(r"^(?P<indent>[ \t]{0,3})(?P<marker>#{1,6}|[+-])(?=[ \t])")+++def _escape_text_block_markdown_prefix(content: str) -> str:+ """Escape a leading Markdown block marker in an assembled text block."""+ if not content:+ return content+ match = _TEXT_BLOCK_MD_PREFIX_RE.match(content)+ if not match:+ return content+ marker_start = match.start("marker")+ return f"{content[:marker_start]}\\{content[marker_start:]}"+++def _is_fenced_code_block(para_block: Block) -> bool:+ return para_block.type == BlockType.CODE_BODY and para_block.sub_type == BlockType.CODE+++def _normalize_text_content(content: str) -> str:+ return full_to_half_exclude_marks(content or "")+++def _collect_text_for_lang_detection(para_block: Block) -> str:+ parts: list[str] = []+ for line in para_block.lines:+ for span in line.spans:+ if span.type == ContentType.TEXT:+ parts.append(_normalize_text_content(span.content))+ return "".join(parts)+++def _line_prefix(line_idx: int, line: Line, list_line_break: str = " \n") -> str:+ if line_idx >= 1 and line._is_list_start:+ return list_line_break+ return ""+++_MARKDOWN_SPECIAL = frozenset({"*", "_", "`", "~", "$"})+++def _escape_conservative_markdown_text(content: str) -> str:+ """Escape plain-text characters that carry inline Markdown semantics."""+ if not content:+ return content+ escaped: list[str] = []+ backslashes = 0+ for char in content:+ if char == "\\":+ escaped.append(char)+ backslashes += 1+ continue+ if char in _MARKDOWN_SPECIAL and backslashes % 2 == 0:+ escaped.append("\\")+ escaped.append(char)+ backslashes = 0+ return "".join(escaped)+++def _render_span(span: Span, *, escape_markdown: bool = True) -> tuple[str, str] | None:+ span_type = span.type+ content = ""++ if span_type == ContentType.TEXT:+ content = _normalize_text_content(span.content) # (VLM) SKIP+ if escape_markdown:+ content = _escape_conservative_markdown_text(content)+ elif span_type == ContentType.INLINE_EQUATION:+ if span.content:+ content = f"{inline_left}{span.content}{inline_right}"+ elif span_type == ContentType.INTERLINE_EQUATION:+ if span.content:+ content = f"\n{display_left}\n{span.content}\n{display_right}\n"+ # (VLM) if not(formula_enable) use image link+ else:+ return None++ content = content.strip()+ if not content:+ return None+ return span_type, content+++def _next_line_starts_with_lowercase_text(para_block: Block, line_idx: int) -> bool:+ if line_idx + 1 >= len(para_block.lines):+ return False+ next_spans = para_block.lines[line_idx + 1].spans+ if not next_spans:+ return False+ first = next_spans[0]+ if first.type != ContentType.TEXT:+ return False+ first_content = _normalize_text_content(first.content)+ return bool(first_content) and first_content[0].islower()+++def _join_rendered_span(+ para_block: Block, block_lang: str, line: Line, line_idx: int, span_idx: int, span_type: str, content: str+) -> tuple[str, str]:+ if span_type == ContentType.INTERLINE_EQUATION:+ return content, ""++ is_last_span = bool(span_idx == len(line.spans) - 1)++ # 中文/日语/韩文语境下,换行不需要空格分隔,但是如果是行内公式结尾,还是要加空格+ if block_lang in CJK_LANGS:+ if is_last_span and span_type != ContentType.INLINE_EQUATION:+ return content, ""+ # (VLM) use _has_following_joinable_span()+ return content, " "++ if span_type not in (ContentType.TEXT, ContentType.INLINE_EQUATION):+ return content, ""++ if is_last_span and span_type == ContentType.TEXT and is_hyphen_at_line_end(content):+ if _next_line_starts_with_lowercase_text(para_block, line_idx):+ return content[:-1], ""+ return content, ""+ # 西方文本语境下 content间需要空格分隔+ return content, " "+++# ------------------------------------------------------------------ #+# Core merge+# ------------------------------------------------------------------ #+++def _merge_para_text(para_block: Block, *, escape_markdown: bool = True, list_line_break: str = " \n") -> str:+ """Core paragraph rendering shared by Pipeline and VLM backends."""+ block_lang = detect_lang(_collect_text_for_lang_detection(para_block))+ para_parts: list[str] = []+ # (VLM) escape_markdown_text = para_block.type != BlockType.CODE_BODY++ for line_idx, line in enumerate(para_block.lines):+ # (PIPELINE ONLY)+ if prefix := _line_prefix(line_idx, line, list_line_break):+ para_parts.append(prefix)++ for span_idx, span in enumerate(line.spans):+ rendered = _render_span(span, escape_markdown=escape_markdown)+ if rendered is None:+ continue++ span_type, content = rendered+ content, suffix = _join_rendered_span(para_block, block_lang, line, line_idx, span_idx, span_type, content)+ para_parts.append(content)+ if suffix:+ para_parts.append(suffix)++ return "".join(para_parts).rstrip()diff --git a/mineru/render/merge_visual.py b/mineru/render/merge_visual.pynew file mode 100644index 00000000..ab7e29ae--- /dev/null+++ b/mineru/render/merge_visual.py@@ -0,0 +1,229 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++from copy import deepcopy+from html import unescape+from typing import Any++from ..types import Block+from ..utils.enum_class import BlockType, ContentType+from .merge import inline_left, inline_right, merge_para_text++# --------------------------------------------------------------------------- #+# Merge IMAGE / TABLE / CHART / CODE composite blocks into a single+# Markdown string. Shared by Pipeline and VLM backends.+# --------------------------------------------------------------------------- #+++def merge_visual_para_text(para_block: Block, img_bucket_path: str = "") -> str:+ rendered_segments: list[tuple[str, str]] = []++ for block in _blocks_in_index_order(para_block.blocks):+ render_block = _inherit_parent_code_render_metadata(block, para_block)+ rendered_segments.extend(_render_visual_block_segments(render_block, para_block, img_bucket_path))++ para_text = ""+ prev_kind: str | None = None+ for segment_text, segment_kind in rendered_segments:+ if para_text:+ para_text += _visual_block_separator(prev_kind, segment_kind)+ para_text += segment_text+ prev_kind = segment_kind++ return para_text+++# --------------------------------------------------------------------------- #+# Internal helpers — sorted by dependency order+# --------------------------------------------------------------------------- #++import re # noqa: E402+++def _blocks_in_index_order(blocks: list[Block]) -> list[Block]:+ return [b for _, b in sorted(enumerate(blocks), key=lambda item: (item[1].index, item[0]))]+++def _inherit_parent_code_render_metadata(block: Block, parent_block: Block) -> Block:+ # pipeline_magic_model 会把 code_body 的 sub_type/guess_lang 提升到父 code block。+ # markdown 渲染 code_body 时需要把这两个字段临时透传回来,但不能修改原始输入。+ if block.type != BlockType.CODE_BODY:+ return block+ if parent_block.type != BlockType.CODE:+ return block++ needs_sub_type = not block.sub_type and parent_block.sub_type+ needs_guess_lang = not block.guess_lang and parent_block.guess_lang+ if not needs_sub_type and not needs_guess_lang:+ return block++ render_block = deepcopy(block)+ if needs_sub_type:+ render_block.sub_type = parent_block.sub_type+ if needs_guess_lang:+ render_block.guess_lang = parent_block.guess_lang+ return render_block+++# -- HTML helpers ------------------------------------------------------------+++def _prefix_table_img_src(html: str, img_bucket_path: str) -> str:+ if not html or not img_bucket_path:+ return html+ return re.sub(+ r'src="(?!data:)([^"]+)"',+ lambda m: f'src="{img_bucket_path}/{m.group(1)}"',+ html,+ )+++def _replace_eq_tags_in_table_html(html: str) -> str:+ if not html:+ return html+ return re.sub(+ r"<eq>(.*?)</eq>",+ lambda m: f" {inline_left}{unescape(m.group(1))}{inline_right} ",+ html,+ flags=re.DOTALL,+ )+++def _format_embedded_html(html: str, img_bucket_path: str) -> str:+ return _replace_eq_tags_in_table_html(_prefix_table_img_src(html, img_bucket_path))+++def _build_media_path(img_bucket_path: str, image_path: str) -> str:+ if not image_path:+ return ""+ if not img_bucket_path:+ return image_path+ return f"{img_bucket_path}/{image_path}"+++# -- Visual body / details ---------------------------------------------------+++def _build_visual_details_block(content: Any, summary: str) -> str:+ normalized = _normalize_visual_content(content)+ if not normalized:+ return ""+ return f"<details>\n<summary>{summary}</summary>\n\n{normalized}\n</details>"+++def _normalize_visual_content(content: Any) -> str:+ if isinstance(content, list):+ return "\n".join(str(item) for item in content if str(item).strip())+ if isinstance(content, str):+ return content.strip()+ return ""+++def _build_visual_body_segments(+ *, image_path: str, content: str, img_bucket_path: str, details_summary: str+) -> list[tuple[str, str]]:+ segments: list[tuple[str, str]] = []+ media_path = _build_media_path(img_bucket_path, image_path)+ if media_path:+ segments.append((f"", "markdown_line"))+ details = _build_visual_details_block(content, details_summary)+ if details:+ segments.append((details, "details_block"))+ return segments+++# -- Per-block-type segment rendering ----------------------------------------+++def _render_visual_block_segments(block: Block, para_block: Block, img_bucket_path: str) -> list[tuple[str, str]]:+ # 将单个视觉子 block 渲染成一个或多个 segment。+ # 文本类子块统一输出 markdown_line;+ # table 的 html 输出为 html_block,供后续决定是否需要空行隔开。++ block_type = block.type++ # text-like sub-blocks (caption / footnote / code body)+ if block_type in (+ BlockType.IMAGE_CAPTION,+ BlockType.IMAGE_FOOTNOTE,+ BlockType.TABLE_CAPTION,+ BlockType.TABLE_FOOTNOTE,+ BlockType.CODE_BODY,+ BlockType.CODE_CAPTION,+ BlockType.CODE_FOOTNOTE,+ BlockType.CHART_CAPTION,+ BlockType.CHART_FOOTNOTE,+ ):+ text = merge_para_text(block)+ if text.strip():+ return [(text, "markdown_line")]+ return []++ # IMAGE_BODY+ if block_type == BlockType.IMAGE_BODY:+ image_segments: list[tuple[str, str]] = []+ for line in block.lines:+ for span in line.spans:+ if span.type != ContentType.IMAGE:+ continue+ image_segments.extend(+ _build_visual_body_segments(+ image_path=span.image_path,+ content=span.content,+ img_bucket_path=img_bucket_path,+ details_summary=para_block.sub_type or "image content",+ )+ )+ return image_segments++ # CHART_BODY+ if block_type == BlockType.CHART_BODY:+ chart_segments: list[tuple[str, str]] = []+ for line in block.lines:+ for span in line.spans:+ if span.type != ContentType.CHART:+ continue+ chart_segments.extend(+ _build_visual_body_segments(+ image_path=span.image_path,+ content=span.content,+ img_bucket_path=img_bucket_path,+ details_summary=para_block.sub_type or "chart content",+ )+ )+ return chart_segments++ # TABLE_BODY+ if block_type == BlockType.TABLE_BODY:+ table_segments: list[tuple[str, str]] = []+ for line in block.lines:+ for span in line.spans:+ if span.type != ContentType.TABLE:+ continue+ if span.html: # (VLM) also checks table_enable+ table_segments.append((_format_embedded_html(span.html, img_bucket_path), "html_block"))+ elif span.image_path:+ if media_path := _build_media_path(img_bucket_path, span.image_path):+ table_segments.append((f"", "markdown_line"))+ return table_segments++ return []+++# -- Segment separator -------------------------------------------------------+++def _visual_block_separator(prev_kind: str | None, current_kind: str) -> str:+ # 根据前后 segment 类型决定分隔符:+ # 1. 普通 markdown 行之间用 hard break(" \\n")+ # 2. 进入 html block 前只换一行+ # 3. html block 后必须留空行,否则后续文本仍会被当作 html 块内容+ if prev_kind == "html_block":+ # Raw HTML blocks need a blank line after them, otherwise the following+ # markdown text is still treated as part of the HTML block.+ return "\n\n"+ if prev_kind == "details_block" or current_kind == "details_block":+ return "\n\n"+ if current_kind == "html_block":+ return "\n"+ return " \n"diff --git a/mineru/render/union_make.py b/mineru/render/union_make.pynew file mode 100644index 00000000..1f82ff94--- /dev/null+++ b/mineru/render/union_make.py@@ -0,0 +1,151 @@+# Copyright (c) Opendatalab. All rights reserved.+from __future__ import annotations++from typing import Any, Literal++from ..render.markdown import blocks_to_markdown+from ..types import PageInfo+from ..utils.enum_class import MakeMode++Backend = Literal["pipeline", "vlm", "hybrid", "office"]+++def _backend_from_pages(pages: list[PageInfo]) -> Backend | None:+ """Infer backend from the first page. Returns ``None`` for empty input."""+ return pages[0]._backend if pages else None+++# ------------------------------------------------------------------ #+# Per-backend dispatch helpers for Content-List modes+# (Markdown rendering moved to ``render/markdown.py``).+# ------------------------------------------------------------------ #+++def _dispatch_make_content_list(+ backend: Backend,+ para_block: Any,+ img_bucket_path: str,+ page_idx: int,+ page_size: Any,+) -> Any: # type: ignore[return]+ if backend == "pipeline":+ from ..backend.pipeline.pipeline_middle_json_mkcontent import make_blocks_to_content_list++ return make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)+ if backend == "office":+ from ..backend.office.mkcontent.output_builders import make_blocks_to_content_list++ return make_blocks_to_content_list(para_block, img_bucket_path, page_idx)+ # vlm / hybrid+ from ..backend.vlm.vlm_middle_json_mkcontent import make_blocks_to_content_list++ return make_blocks_to_content_list(para_block, img_bucket_path, page_idx, page_size)+++def _dispatch_make_content_list_v2(+ backend: Backend,+ para_block: Any,+ img_bucket_path: str,+ page_size: Any,+) -> Any: # type: ignore[return]+ if backend == "pipeline":+ from ..backend.pipeline.pipeline_middle_json_mkcontent import make_blocks_to_content_list_v2++ return make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)+ if backend == "office":+ from ..backend.office.mkcontent.output_builders import make_blocks_to_content_list_v2++ return make_blocks_to_content_list_v2(para_block, img_bucket_path)+ # vlm / hybrid+ from ..backend.vlm.vlm_middle_json_mkcontent import make_blocks_to_content_list_v2++ return make_blocks_to_content_list_v2(para_block, img_bucket_path, page_size)+++def _get_merged_para_blocks(paras_of_layout: list, paras_of_discarded: list, backend: Backend) -> list:+ """Build the para-block list for Content-List modes.++ The pipeline backend runs ``merge_adjacent_ref_text_blocks_for_content``+ before merging layout and discarded blocks; the other backends simply+ concatenate them.+ """+ if backend == "pipeline":+ from ..backend.pipeline.pipeline_middle_json_mkcontent import merge_adjacent_ref_text_blocks_for_content++ return merge_adjacent_ref_text_blocks_for_content((paras_of_layout or []) + (paras_of_discarded or []))+ return (paras_of_layout or []) + (paras_of_discarded or [])+++# ------------------------------------------------------------------ #+# Public renderer functions+# ------------------------------------------------------------------ #+++def render_markdown(+ pdf_info: list[PageInfo],+ img_bucket_path: str = "",+ *,+ formula_enable: bool = True,+ table_enable: bool = True,+ make_mode: str = MakeMode.MM_MD,+) -> str:+ """Render pages to a single Markdown string."""+ backend = _backend_from_pages(pdf_info)+ if backend is None:+ return ""+ assert backend != "office", "temp not support"+ output_md: list[str] = []+ for page_info in pdf_info:+ paras_of_layout = page_info.para_blocks+ if not paras_of_layout:+ continue+ page_md = blocks_to_markdown(+ para_blocks=paras_of_layout,+ img_bucket_path=img_bucket_path,+ table_as_image=not table_enable,+ formula_as_image=not formula_enable,+ no_rich_content=(make_mode == MakeMode.NLP_MD),+ )+ output_md.extend(page_md)+ return "\n\n".join(output_md)+++def render_content_list(+ pdf_info: list[PageInfo],+ img_bucket_path: str = "",+) -> list[dict[str, Any]]:+ """Render pages to a flat Content List (V1)."""+ backend = _backend_from_pages(pdf_info)+ if backend is None:+ return []+ output_items: list[dict[str, Any]] = []+ for page_info in pdf_info:+ para_blocks = _get_merged_para_blocks(page_info.para_blocks, page_info.discarded_blocks, backend)+ if not para_blocks:+ continue+ for para_block in para_blocks:+ item = _dispatch_make_content_list(backend, para_block, img_bucket_path, page_info.page_idx, page_info.page_size)+ if item:+ output_items.append(item)+ return output_items+++def render_content_list_v2(+ pdf_info: list[PageInfo],+ img_bucket_path: str = "",+) -> list[list[dict[str, Any]]]:+ """Render pages to a per-page Content List (V2)."""+ backend = _backend_from_pages(pdf_info)+ if backend is None:+ return []+ output_lists: list[list[dict[str, Any]]] = []+ for page_info in pdf_info:+ para_blocks = _get_merged_para_blocks(page_info.para_blocks, page_info.discarded_blocks, backend)+ page_contents: list[dict[str, Any]] = []+ if para_blocks:+ for para_block in para_blocks:+ item = _dispatch_make_content_list_v2(backend, para_block, img_bucket_path, page_info.page_size)+ if item:+ page_contents.append(item)+ output_lists.append(page_contents)+ return output_listsdiff --git a/mineru/types.py b/mineru/types.pyindex 7f3867be..68995160 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -453,3 +453,6 @@ class PageInfo(_DocElement):preproc_blocks: list[Block] = field(default_factory=list)para_blocks: list[Block] = field(default_factory=list)discarded_blocks: list[Block] = field(default_factory=list)++ # Temporary — will be removed once the render layer converges.+ _backend: Literal["pipeline", "vlm", "hybrid", "office"] | None = Nonediff --git a/mineru/utils/enum_class.py b/mineru/utils/enum_class.pyindex d666903c..7d2eb1ae 100644--- a/mineru/utils/enum_class.py+++ b/mineru/utils/enum_class.py@@ -1,35 +1,41 @@# Copyright (c) Opendatalab. All rights reserved.from enum import Enum+class BlockType:- IMAGE = 'image'- TABLE = 'table'- CHART = 'chart'- IMAGE_BODY = 'image_body'- TABLE_BODY = 'table_body'- CHART_BODY = 'chart_body'- CAPTION = 'caption' # generic caption type (e.g., for Word documents)- IMAGE_CAPTION = 'image_caption'- TABLE_CAPTION = 'table_caption'- CHART_CAPTION = 'chart_caption'- ALGORITHM_CAPTION = 'algorithm_caption'- FOOTNOTE = 'footnote' # pp_layout中的vision_footnote- IMAGE_FOOTNOTE = 'image_footnote'- TABLE_FOOTNOTE = 'table_footnote'- CHART_FOOTNOTE = 'chart_footnote'- TEXT = 'text'- TITLE = 'title'- INTERLINE_EQUATION = 'interline_equation'- EQUATION = "equation" # 公式(独立公式)- LIST = 'list'- INDEX = 'index'- DISCARDED = 'discarded'+ IMAGE = "image"+ IMAGE_BODY = "image_body"+ IMAGE_CAPTION = "image_caption"+ IMAGE_FOOTNOTE = "image_footnote"++ TABLE = "table"+ TABLE_BODY = "table_body"+ TABLE_CAPTION = "table_caption"+ TABLE_FOOTNOTE = "table_footnote"++ CHART = "chart"+ CHART_BODY = "chart_body"+ CHART_CAPTION = "chart_caption"+ CHART_FOOTNOTE = "chart_footnote"# Added in vlm 2.5CODE = "code"CODE_BODY = "code_body"CODE_CAPTION = "code_caption"CODE_FOOTNOTE = "code_footnote"++ CAPTION = "caption" # generic caption type (e.g., for Word documents)+ ALGORITHM_CAPTION = "algorithm_caption"+ FOOTNOTE = "footnote" # pp_layout中的vision_footnote+ TEXT = "text"+ TITLE = "title"+ INTERLINE_EQUATION = "interline_equation"+ EQUATION = "equation" # 公式(独立公式)+ LIST = "list"+ INDEX = "index"+ DISCARDED = "discarded"++ # Added in vlm 2.5ALGORITHM = "algorithm"REF_TEXT = "ref_text"PHONETIC = "phonetic"@@ -48,37 +54,38 @@ class BlockType:FOOTER_IMAGE = "footer_image"FORMULA_NUMBER = "formula_number"+class ContentType:- IMAGE = 'image'- TABLE = 'table'- CHART = 'chart'- TEXT = 'text'- INTERLINE_EQUATION = 'interline_equation'- INLINE_EQUATION = 'inline_equation'- EQUATION = 'equation'- HYPERLINK = 'hyperlink'+ IMAGE = "image"+ TABLE = "table"+ CHART = "chart"+ TEXT = "text"+ INTERLINE_EQUATION = "interline_equation"+ INLINE_EQUATION = "inline_equation"+ EQUATION = "equation"+ HYPERLINK = "hyperlink"class ContentTypeV2:- CODE = 'code'+ CODE = "code"ALGORITHM = "algorithm"- EQUATION_INTERLINE = 'equation_interline'- IMAGE = 'image'- TABLE = 'table'- CHART = 'chart'- TABLE_SIMPLE = 'simple_table'- TABLE_COMPLEX = 'complex_table'- LIST = 'list'- LIST_TEXT = 'text_list'- LIST_REF = 'reference_list'- INDEX = 'index'- TITLE = 'title'- PARAGRAPH = 'paragraph'- SPAN_TEXT = 'text'- SPAN_EQUATION_INLINE = 'equation_inline'- SPAN_PHONETIC = 'phonetic'- SPAN_MD = 'md'- SPAN_CODE_INLINE = 'code_inline'+ EQUATION_INTERLINE = "equation_interline"+ IMAGE = "image"+ TABLE = "table"+ CHART = "chart"+ TABLE_SIMPLE = "simple_table"+ TABLE_COMPLEX = "complex_table"+ LIST = "list"+ LIST_TEXT = "text_list"+ LIST_REF = "reference_list"+ INDEX = "index"+ TITLE = "title"+ PARAGRAPH = "paragraph"+ SPAN_TEXT = "text"+ SPAN_EQUATION_INLINE = "equation_inline"+ SPAN_PHONETIC = "phonetic"+ SPAN_MD = "md"+ SPAN_CODE_INLINE = "code_inline"PAGE_HEADER = "page_header"PAGE_FOOTER = "page_footer"PAGE_NUMBER = "page_number"@@ -87,10 +94,10 @@ class ContentTypeV2:class MakeMode:- MM_MD = 'mm_markdown'- NLP_MD = 'nlp_markdown'- CONTENT_LIST = 'content_list'- CONTENT_LIST_V2 = 'content_list_v2'+ MM_MD = "mm_markdown"+ NLP_MD = "nlp_markdown"+ CONTENT_LIST = "content_list"+ CONTENT_LIST_V2 = "content_list_v2"class ModelPath:@@ -108,13 +115,13 @@ class ModelPath:class SplitFlag:- CROSS_PAGE = 'cross_page'- LINES_DELETED = 'lines_deleted'+ CROSS_PAGE = "cross_page"+ LINES_DELETED = "lines_deleted"class ImageType:- PIL = 'pil_img'- BASE64 = 'base64_img'+ PIL = "pil_img"+ BASE64 = "base64_img"class NotExtractType(Enum):diff --git a/mineru/utils/llm_aided.py b/mineru/utils/llm_aided.pyindex 6d505b76..e86e5a07 100644--- a/mineru/utils/llm_aided.py+++ b/mineru/utils/llm_aided.py@@ -9,7 +9,7 @@ import json_repairfrom loguru import loggerfrom openai import OpenAI-from ..backend.pipeline.pipeline_middle_json_mkcontent import merge_para_with_text+from ..render.merge import merge_para_textfrom ..types import BBox, Block, PageInfofrom .enum_class import BlockType@@ -66,7 +66,7 @@ def _build_title_dict(title_block_refs: list[tuple[PageInfo, Block]]) -> dict[stfor i, (page_info, block) in enumerate(title_block_refs):title_dict[str(i)] = [- merge_para_with_text(block),+ merge_para_text(block),_get_title_line_avg_height(block),page_info.page_idx + 1,]@@ -241,7 +241,7 @@ def _get_title_block_identity(block: Block) -> tuple[str, int] | tuple[str, BBoxif block_index is not None:return ("index", block_index)- return ("bbox_text", block.bbox, merge_para_with_text(block))+ return ("bbox_text", block.bbox, merge_para_text(block))def _sync_para_titles_to_preproc(page_info_list: list[PageInfo]) -> None: