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: refactor image rendering by consolidating ImageRenderer imports and removing unused code
myhloli829fde2b6081
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex 4e8d54b3..474e5f32 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -28,7 +28,7 @@ markdown = render(| `RenderFormat` | Options | 返回类型 || --- | --- | --- |-| `MARKDOWN` | `MarkdownRenderOptions(mode, asset_base_url)` | `str` |+| `MARKDOWN` | `MarkdownRenderOptions(mode, asset_base_url, image_renderer)` | `str` || `HTML` | `HtmlRenderOptions(mode, asset_base_url, standalone, document_title)` | `str` || `DOCX` | `DocxRenderOptions(mode, asset_resolver)` | `bytes` || `STRUCTURED_CONTENT` | `StructuredContentRenderOptions(asset_base_url)` | `dict[str, Any]` |@@ -66,6 +66,11 @@ backend 参数或旧 `Line/Span` renderer。渲染过程基于深拷贝,不修图片优先使用 `image_path`,缺失时使用 `image_base64` data URI。`asset_base_url` 只给相对 `image_path` 和 HTML 内相对 `img src` 添加前缀。+`ImageRenderer` 是从 `mineru.render` 导出的 Block 级图片扩展契约。传入自定义 renderer 时,+image block 及无结构内容的 table/chart/equation 可以改用调用方提供的图片引用;结构化 table+仍保留文本或表格内容,但会移除由自定义 renderer 接管的内嵌 `<img>`。清理后只剩图片的+table 会回退到自定义 renderer。+## 可编辑 DOCX```pythondiff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 35249a0f..113ff27f 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -1329,8 +1329,6 @@ async def _run_job(req: CreateJobRequest,file_store: FileStore,*,- server_backend: str,- language: str,ocr_mode: str,image_analysis: bool,url_timeout: int = 60,@@ -1818,12 +1816,10 @@ async def create_job()rec = job_store.create(body, file_store)- backend = runtime.backendurl_timeout_val: int = request.app.state.url_timeoutallow_local_source_val: bool = request.app.state.allow_local_sourcemax_inline_bytes_val: int = request.app.state.max_inline_bytesallow_http_source_val: bool = request.app.state.allow_http_source- language_val: str = request.app.state.languageocr_mode_val: str = request.app.state.ocr_modeimage_analysis_val: bool = request.app.state.image_analysis@@ -1834,8 +1830,6 @@ async def create_job(rec,body,file_store,- server_backend=backend,- language=language_val,ocr_mode=ocr_mode_val,image_analysis=image_analysis_val,url_timeout=url_timeout_val,diff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex a095a62c..50ba091e 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -9,8 +9,7 @@ from pathlib import Pathfrom typing import Any, Literalfrom ..render import render_markdown, render_structured_content-from ..render.contracts import RenderMode-from ..render.image import ImageRenderer+from ..render.contracts import ImageRenderer, RenderModefrom ..render.writer import DataWriterfrom ..types import FileSuffix, MiddleJson, PageInfofrom ..utils.image_payload import ImagePayloadCachediff --git a/mineru/render/__init__.py b/mineru/render/__init__.pyindex 64557dd7..4cdbb6a8 100644--- a/mineru/render/__init__.py+++ b/mineru/render/__init__.py@@ -5,6 +5,7 @@ from .contracts import (AssetResolver,DocxRenderOptions,HtmlRenderOptions,+ ImageRenderer,MarkdownRenderOptions,RenderFormat,RenderMode,@@ -14,9 +15,7 @@ from .contracts import ()from .docx import DocxRenderError, render_docxfrom .html import render_html-from .image import ImageRenderer, image_path_rendererfrom .markdown import render_markdown-from .markdown_table import to_markdown_tablefrom .structured_content import render_structured_content__all__ = [@@ -24,6 +23,7 @@ __all__ = ["DocxRenderError","DocxRenderOptions","HtmlRenderOptions",+ "ImageRenderer","MarkdownRenderOptions","RenderFormat","RenderMode",@@ -33,9 +33,6 @@ __all__ = ["render","render_docx","render_html",- "to_markdown_table",- "ImageRenderer",- "image_path_renderer","render_markdown","render_structured_content",]diff --git a/mineru/render/_internal/markdown/blocks.py b/mineru/render/_internal/markdown/blocks.pyindex 4a731d90..a0c7663a 100644--- a/mineru/render/_internal/markdown/blocks.py+++ b/mineru/render/_internal/markdown/blocks.py@@ -17,8 +17,12 @@ from mineru.render._internal.markdown.inline import (render_internal_link,render_joined_inline_contents,)-from mineru.render._internal.markdown.table import format_embedded_html, render_html_table-from mineru.render.image import ImageRenderer+from .table import (+ _strip_embedded_images,+ format_embedded_html,+ render_html_table,+)+from ...contracts import ImageRendererfrom mineru.types import (RAW_ALGORITHM,BlockType,@@ -169,6 +173,7 @@ def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: intlines.extend(f"{indent}{line}" for line in item_lines)return "\n".join(lines)+def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:"""递归渲染目录列表,并给标题叶子添加内部 anchor 链接。"""lines: list[str] = []@@ -187,6 +192,7 @@ def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: ilines.append(f"{' ' * depth}- {label}")return "\n".join(lines)+def _render_image_block(block: ImageBlock,delimiters: LatexDelimitersConfig,@@ -367,7 +373,12 @@ def _render_table_body(parent_block: TableBlock,) -> str:"""按 HTML、空间投影文本、image_renderer、图片的优先级渲染表格主体。"""- rendered_content = _render_table_content(block, delimiters, asset_base_url)+ rendered_content = _render_table_content(+ block,+ delimiters,+ asset_base_url,+ strip_embedded_images=image_renderer is not None,+ )if rendered_content:return rendered_contentif image_renderer is not None:@@ -382,18 +393,21 @@ def _render_table_content(block: TableBodyBlock,delimiters: LatexDelimitersConfig,asset_base_url: str,+ *,+ strip_embedded_images: bool = False,) -> str:"""渲染表格结构内容,不执行空内容时的图片回退。"""- if not block.content:+ content = _strip_embedded_images(block.content) if strip_embedded_images else block.content+ if not content:return ""html_table = render_html_table(- block.content,+ content,asset_base_url=asset_base_url,delimiters=delimiters,)if html_table is not None:return html_table- return _render_fenced_content(block.content)+ return _render_fenced_content(content)def _render_code_block(block: CodeBlock, delimiters: LatexDelimitersConfig) -> str:diff --git a/mineru/render/_internal/markdown/table.py b/mineru/render/_internal/markdown/table.pyindex 31e016e4..4dfea9c1 100644--- a/mineru/render/_internal/markdown/table.py+++ b/mineru/render/_internal/markdown/table.py@@ -9,8 +9,8 @@ import refrom bs4 import BeautifulSoupfrom bs4.element import NavigableString, Tag-from mineru.config import LatexDelimitersConfig-from mineru.render._internal.markdown.assets import prefix_html_image_sources+from ....config import LatexDelimitersConfig+from .assets import prefix_html_image_sources_INLINE_EQ_RE = re.compile(r"<eq>(?P<latex>.*?)</eq>", re.IGNORECASE | re.DOTALL)_GFM_FORMULA_PIPE_RE = re.compile(r"(?P<slashes>\\*)\|")@@ -53,6 +53,19 @@ _ALLOWED_INLINE_TAGS = {}+def _strip_embedded_images(markup: str) -> str:+ """移除自定义图片 renderer 接管的 HTML 图片,并识别清理后的空内容。"""+ soup = BeautifulSoup(markup, "html.parser")+ images = soup.find_all("img")+ if not images:+ return markup+ for image in images:+ image.decompose()+ if not soup.get_text(strip=True):+ return ""+ return str(soup)++def render_html_table(content: str,*,@@ -85,11 +98,7 @@ def format_embedded_html(def _replace_inline_equation(match: re.Match[str]) -> str:"""把单个 HTML eq 标签替换为配置的行内公式定界符。"""- return (- f" {delimiters.inline.left}"- f"{html.unescape(match.group('latex')).strip()}"- f"{delimiters.inline.right} "- )+ return f" {delimiters.inline.left}{html.unescape(match.group('latex')).strip()}{delimiters.inline.right} "return _INLINE_EQ_RE.sub(_replace_inline_equation, prefixed)@@ -129,9 +138,7 @@ def _convert_simple_table(table: Tag, delimiters: LatexDelimitersConfig) -> strcells = row.find_all(("th", "td"), recursive=False)if not cells:return None- rendered_rows.append(- [_normalize_cell_text(_render_inline_children(cell, delimiters)) for cell in cells]- )+ rendered_rows.append([_normalize_cell_text(_render_inline_children(cell, delimiters)) for cell in cells])header_flags.append([cell.name == "th" for cell in cells])width = max(len(row) for row in rendered_rows)@@ -180,11 +187,7 @@ def _render_inline_children(node: Tag, delimiters: LatexDelimitersConfig) -> strelif name == "eq":latex = html.unescape(child.get_text()).strip()escaped_latex = _escape_gfm_formula_pipes(latex)- parts.append(- f"{delimiters.inline.left}{escaped_latex}{delimiters.inline.right}"- if escaped_latex- else ""- )+ parts.append(f"{delimiters.inline.left}{escaped_latex}{delimiters.inline.right}" if escaped_latex else "")elif name == "a":href = str(child.get("href", "")).strip()parts.append(f"[{rendered}]({_escape_link_url(href)})" if href else rendered)@@ -221,13 +224,7 @@ def _escape_gfm_formula_pipes(latex: str) -> str:def _escape_link_url(url: str) -> str:"""转义 GFM 表格链接目标中的空格、反斜杠和括号。"""- return (- url.replace("\\", "%5C")- .replace(" ", "%20")- .replace("(", "%28")- .replace(")", "%29")- .replace("|", "%7C")- )+ return url.replace("\\", "%5C").replace(" ", "%20").replace("(", "%28").replace(")", "%29").replace("|", "%7C")def _escape_cell_text(content: str) -> str:diff --git a/mineru/render/contracts.py b/mineru/render/contracts.pyindex e8289d5e..797a15b8 100644--- a/mineru/render/contracts.py+++ b/mineru/render/contracts.py@@ -7,7 +7,7 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, Callable, TypeAlias-from .image import ImageRenderer+from ..types import BlockBaseclass RenderFormat(str, Enum):@@ -27,6 +27,7 @@ class RenderMode(str, Enum):AssetResolver: TypeAlias = Callable[[str], bytes]+ImageRenderer: TypeAlias = Callable[[BlockBase], str]def _validate_mode(mode: object) -> None:@@ -101,9 +102,7 @@ class StructuredContentRenderOptions:_validate_asset_base_url(self.asset_base_url)-RenderOptions: TypeAlias = (- MarkdownRenderOptions | HtmlRenderOptions | DocxRenderOptions | StructuredContentRenderOptions-)+RenderOptions: TypeAlias = MarkdownRenderOptions | HtmlRenderOptions | DocxRenderOptions | StructuredContentRenderOptionsRenderOutput: TypeAlias = str | bytes | dict[str, Any]@@ -111,6 +110,7 @@ __all__ = ["AssetResolver","DocxRenderOptions","HtmlRenderOptions",+ "ImageRenderer","MarkdownRenderOptions","RenderFormat","RenderMode",diff --git a/mineru/render/image.py b/mineru/render/image.pydeleted file mode 100644index 1209292e..00000000--- a/mineru/render/image.py+++ /dev/null@@ -1,41 +0,0 @@-from __future__ import annotations--import re-from collections.abc import Callable--from ..types import BlockBase, BlockType, ImagePayloadBlock, _iter_child_blocks--ImageRenderer = Callable[[BlockBase], str]--_VISUAL_BLOCK_TYPES: frozenset[str] = frozenset({- BlockType.IMAGE,- BlockType.TABLE,- BlockType.CHART,- BlockType.EQUATION,-})---def image_path_renderer(block: BlockBase, *, img_bucket_path: str = "") -> str:- """Render the image paths belonging to one top-level visual block."""- if block.type not in _VISUAL_BLOCK_TYPES:- return ""- references: list[str] = []- if isinstance(block, ImagePayloadBlock) and block.image_path:- references.append(_build_image_reference(block.image_path, img_bucket_path))- for child in _iter_child_blocks(block):- if isinstance(child, ImagePayloadBlock) and child.image_path:- references.append(_build_image_reference(child.image_path, img_bucket_path))- return " \n".join(references)---def _build_image_reference(image_path: str, img_bucket_path: str) -> str:- media_path = f"{img_bucket_path}/{image_path}" if img_bucket_path else image_path- return f""---def strip_embedded_image_tags(content: str) -> str:- """Remove embedded HTML images when a custom renderer owns image output."""- return re.sub(r"<img\b[^>]*>", "", content, flags=re.IGNORECASE)---__all__ = ["ImageRenderer", "image_path_renderer", "strip_embedded_image_tags"]diff --git a/mineru/render/markdown.py b/mineru/render/markdown.pyindex 0b8e253b..073c9a26 100644--- a/mineru/render/markdown.py+++ b/mineru/render/markdown.py@@ -3,12 +3,11 @@from __future__ import annotations-from mineru.config import LatexDelimitersConfig, config-from mineru.render._internal.common.planner import PlannedBlock, build_render_plan-from mineru.render._internal.markdown.blocks import render_planned_block-from mineru.render.contracts import RenderMode-from mineru.render.image import ImageRenderer-from mineru.types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson+from ..config import LatexDelimitersConfig, config+from ..types import PAGE_AUXILIARY_BLOCK_TYPES, MiddleJson+from ._internal.common.planner import PlannedBlock, build_render_plan+from ._internal.markdown.blocks import render_planned_block+from .contracts import ImageRenderer, RenderMode_PAGE_SEPARATOR = "\n\n---\n\n"@@ -70,131 +69,3 @@ def _render_page(__all__ = ["render_markdown"]---# OLD CODE For reference only:--# from ..types import Block, BlockType, ContentType-# from .image import ImageRenderer, strip_embedded_image_tags-# from .markdown_table import to_markdown_table-# 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,-# prefer_markdown_table: bool = False,-# image_renderer: ImageRenderer | None = None,-# ) -> 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,-# prefer_markdown_table=prefer_markdown_table,-# image_renderer=image_renderer,-# )-# for page in planned_pages-# ]-# if mode is MarkdownRenderMode.FULL:-# return _PAGE_SEPARATOR.join(rendered_pages)-# return "\n\n".join(page for page in rendered_pages if page)--# 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,-# prefer_markdown_table: bool = False,-# image_renderer: ImageRenderer | None = None,-# ) -> 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-# if image_renderer is not None:-# return image_renderer(para_block)-# 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, image_renderer=image_renderer)-# if para_type == BlockType.TABLE:-# if not table_as_image:-# if prefer_markdown_table:-# return _render_table_block_as_markdown_table(-# para_block,-# img_bucket_path,-# image_renderer=image_renderer,-# )-# return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)-# if image_renderer is not None:-# return image_renderer(para_block)-# 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, image_renderer=image_renderer)-# 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 None-#-#-# def _render_table_block_as_markdown_table(-# para_block: Block,-# img_bucket_path: str,-# image_renderer: ImageRenderer | None = None,-# ) -> str:-# for span in para_block.all_spans():-# if span.type != ContentType.TABLE or not span.content:-# continue-# table_html = span.content-# if image_renderer is not None:-# table_html = strip_embedded_image_tags(table_html)-# return to_markdown_table(table_html)-# return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)diff --git a/mineru/render/markdown_table.py b/mineru/render/markdown_table.pydeleted file mode 100644index b35fd456..00000000--- a/mineru/render/markdown_table.py+++ /dev/null@@ -1,292 +0,0 @@-from __future__ import annotations--import re-from dataclasses import dataclass-from typing import TypeVar--from bs4 import BeautifulSoup-from bs4.element import NavigableString, Tag--_ALLOWED_INLINE_TAGS = {- "a",- "b",- "br",- "code",- "em",- "eq",- "i",- "s",- "span",- "strong",- "sub",- "sup",- "u",-}--_COMPLEX_BLOCK_TAGS = {- "blockquote",- "div",- "dl",- "h1",- "h2",- "h3",- "h4",- "h5",- "h6",- "img",- "li",- "ol",- "p",- "pre",- "table",- "ul",-}--_MatrixCell = TypeVar("_MatrixCell")---@dataclass(frozen=True)-class _CellPlacement:- text: str- rowspan: int- colspan: int- is_header: bool---def to_markdown_table(- html: str,- *,- max_empty_ratio: float = 0.3,- max_complex_span_count: int = 5,-) -> str:- """Convert a simple HTML table to a Markdown table.-- Falls back to the original HTML string when the table structure or cell- content is too complex to render readably as Markdown.- """- raw_html = html.strip()- if not raw_html:- return raw_html-- soup = BeautifulSoup(raw_html, "html.parser")- table = soup.find("table")- if table is None:- return raw_html- if _has_nested_table(table):- return raw_html- if _has_merged_table_cells(table):- return raw_html-- rows = table.find_all("tr")- if not rows:- return raw_html-- grid: list[list[str | None]] = []- header_flags: list[list[bool]] = []- span_count = 0- has_rowspan = False- has_colspan = False-- for row_idx, row in enumerate(rows):- _ensure_row(grid, row_idx)- _ensure_row(header_flags, row_idx)-- col_idx = 0- cells = row.find_all(("th", "td"), recursive=False)- for cell in cells:- while col_idx < len(grid[row_idx]) and grid[row_idx][col_idx] is not None:- col_idx += 1-- placement = _parse_cell(cell)- if placement is None:- return raw_html-- rowspan = placement.rowspan- colspan = placement.colspan- if rowspan > 1:- has_rowspan = True- span_count += rowspan - 1- if colspan > 1:- has_colspan = True- span_count += colspan - 1-- for offset in range(colspan):- _ensure_width(grid, row_idx, col_idx + offset + 1, fill_value=None)- _ensure_width(header_flags, row_idx, col_idx + offset + 1, fill_value=False)- grid[row_idx][col_idx + offset] = placement.text if offset == 0 else ""- header_flags[row_idx][col_idx + offset] = placement.is_header-- for row_offset in range(1, rowspan):- next_row_idx = row_idx + row_offset- _ensure_row(grid, next_row_idx)- _ensure_row(header_flags, next_row_idx)- _ensure_width(grid, next_row_idx, col_idx + colspan, fill_value=None)- _ensure_width(header_flags, next_row_idx, col_idx + colspan, fill_value=False)- for offset in range(colspan):- grid[next_row_idx][col_idx + offset] = ""- header_flags[next_row_idx][col_idx + offset] = False-- col_idx += colspan-- width = max(len(row) for row in grid)- normalized_rows: list[list[str]] = []- normalized_headers: list[list[bool]] = []- for row, flags in zip(grid, header_flags, strict=False):- normalized_row = [(cell if cell is not None else "") for cell in row]- normalized_row.extend([""] * (width - len(normalized_row)))- normalized_rows.append(normalized_row)-- normalized_flag_row = list(flags)- normalized_flag_row.extend([False] * (width - len(normalized_flag_row)))- normalized_headers.append(normalized_flag_row)-- if not normalized_rows:- return raw_html-- empty_ratio = _empty_ratio(normalized_rows)- if has_rowspan and has_colspan and (span_count > max_complex_span_count or empty_ratio > max_empty_ratio):- return raw_html-- header_index = _detect_header_row(table, normalized_headers)- header = normalized_rows[header_index]- body_rows = normalized_rows[:header_index] + normalized_rows[header_index + 1 :]-- markdown_lines = [- _format_markdown_row(header),- _format_markdown_row(["---"] * width),- *[_format_markdown_row(row) for row in body_rows],- ]- return "\n".join(markdown_lines)---def _has_nested_table(table: Tag) -> bool:- return table.find("table") is not None---def _has_merged_table_cells(table: Tag) -> bool:- """检测合并单元格,Markdown 表格无法无损表达 rowspan/colspan。"""- for cell in table.find_all(("th", "td")):- if cell.has_attr("rowspan") or cell.has_attr("colspan"):- return True- return False---def _parse_cell(cell: Tag) -> _CellPlacement | None:- if _contains_complex_content(cell):- return None- text = _render_inline_children(cell).strip()- text = _normalize_cell_text(text)- return _CellPlacement(- text=text,- rowspan=_parse_positive_int(cell.get("rowspan")),- colspan=_parse_positive_int(cell.get("colspan")),- is_header=cell.name == "th",- )---def _contains_complex_content(cell: Tag) -> bool:- for descendant in cell.descendants:- if not isinstance(descendant, Tag):- continue- if descendant is cell:- continue- if descendant.name in _COMPLEX_BLOCK_TAGS:- return True- if descendant.name not in _ALLOWED_INLINE_TAGS:- return True- return False---def _render_inline_children(node: Tag) -> str:- parts: list[str] = []- for child in node.children:- if isinstance(child, NavigableString):- parts.append(_escape_markdown_table_text(str(child)))- continue- if not isinstance(child, Tag):- continue- if child.name == "br":- parts.append("<br>")- elif child.name == "code":- parts.append(f"`{_escape_markdown_table_text(_normalize_whitespace(child.get_text()))}`")- elif child.name == "a":- href = str(child.get("href", "")).strip()- label = _escape_markdown_table_text(_normalize_whitespace(child.get_text()))- parts.append(f"[{label}]({href})" if href else label)- elif child.name in {"b", "strong"}:- parts.append(f"**{_render_inline_children(child).strip()}**")- elif child.name in {"em", "i"}:- parts.append(f"*{_render_inline_children(child).strip()}*")- elif child.name in {"s"}:- parts.append(f"~~{_render_inline_children(child).strip()}~~")- elif child.name == "u":- parts.append(_render_inline_children(child))- else:- parts.append(_render_inline_children(child))- return "".join(parts)---def _normalize_cell_text(text: str) -> str:- text = re.sub(r"[ \t\r\f\v]+", " ", text)- text = re.sub(r" *<br> *", "<br>", text)- return text.strip()---def _escape_markdown_table_text(text: str) -> str:- return text.replace("\\", "\\\\").replace("|", r"\|")---def _normalize_whitespace(text: str) -> str:- return re.sub(r"\s+", " ", text).strip()---def _parse_positive_int(value: object) -> int:- try:- parsed = int(str(value))- except (TypeError, ValueError):- return 1- return parsed if parsed > 0 else 1---def _ensure_row(matrix: list[list[_MatrixCell]], row_idx: int) -> None:- while len(matrix) <= row_idx:- matrix.append([])---def _ensure_width(- matrix: list[list[_MatrixCell]],- row_idx: int,- width: int,- *,- fill_value: _MatrixCell,-) -> None:- _ensure_row(matrix, row_idx)- while len(matrix[row_idx]) < width:- matrix[row_idx].append(fill_value)---def _empty_ratio(rows: list[list[str]]) -> float:- total = sum(len(row) for row in rows)- if total == 0:- return 0.0- empty = sum(1 for row in rows for cell in row if cell == "")- return empty / total---def _detect_header_row(table: Tag, header_flags: list[list[bool]]) -> int:- thead = table.find("thead")- if thead is not None:- thead_rows = thead.find_all("tr", recursive=False)- if thead_rows:- return 0- for idx, flags in enumerate(header_flags):- if flags and all(flags):- return idx- return 0---def _format_markdown_row(row: list[str]) -> str:- return f"| {' | '.join(row)} |"---__all__ = ["to_markdown_table"]diff --git a/tests/unittest/test_doclib_config.py b/tests/unittest/test_doclib_config.pyindex 8a9004a7..59c0439b 100644--- a/tests/unittest/test_doclib_config.py+++ b/tests/unittest/test_doclib_config.py@@ -72,7 +72,7 @@ doclib:assert data["doclib"]["sqlite"]["path"] == str(tmp_path / "data" / "doclib.db")-def test_apply_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytest.MonkeyPatch) -> None:+def test_collect_env_overrides_uses_greedy_field_path_matching(monkeypatch: pytest.MonkeyPatch) -> None:prefix = "TEST_MINERU_"monkeypatch.setenv("TEST_MINERU_DOCLIB_TCP_ENABLED", "true")monkeypatch.setenv("TEST_MINERU_DOCLIB_TCP_PORT", "15990")@@ -157,7 +157,7 @@ def test_default_parse_server_health_check_interval_is_30_seconds() -> None:assert Config().doclib.parse_server_health_check_interval_sec == 30-def test_apply_env_overrides_can_override_doclib_data_dir(monkeypatch: pytest.MonkeyPatch) -> None:+def test_collect_env_overrides_can_override_doclib_data_dir(monkeypatch: pytest.MonkeyPatch) -> None:prefix = "TEST_MINERU_"monkeypatch.setenv("MINERU_HOME", "/tmp/mineru-home")monkeypatch.setenv("TEST_MINERU_DOCLIB_DATA_DIR", "/tmp/ignored-data-dir")@@ -220,8 +220,8 @@ def test_llm_aided_config_supports_environment_overrides(monkeypatch: pytest.Monmonkeypatch.setenv(f"{prefix}LLM_AIDED_FEATURES_TITLE_LEVELING", "true")monkeypatch.setenv(f"{prefix}LLM_AIDED_FEATURES_CROSS_PAGE_TABLE_CELL_MERGE", "true")- # _apply_env_overrides is changed, should fix this test case.- cfg = _apply_env_overrides(Config(), prefix=prefix)+ overrides, _paths = _collect_env_overrides(prefix=prefix)+ cfg = Config(**overrides)assert cfg.llm_aided.api_key == "env-secret"assert cfg.llm_aided.model == "env-model"diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 0d03b0b7..87bbf74d 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -5,7 +5,6 @@ import inspectimport ioimport jsonimport logging-import osimport subprocessimport sysimport types@@ -22,7 +21,6 @@ from pydantic import ValidationErrorimport mineru.parser.api_client as api_clientimport mineru.parser.api_server as api_serverimport mineru.parser.tier as parser_tier-from mineru.parser import parse, parse_asyncfrom mineru.parser.api_client import MinerUApiParser, _pages_from_middle_json, _parse_result_from_job, should_trust_env_for_urlfrom mineru.parser.api_server import (_API_SERVER_LANGUAGES,@@ -76,8 +74,20 @@ def _stub_api_server_dependency_preflight(monkeypatch: pytest.MonkeyPatch) -> Nomonkeypatch.setattr(importlib, "import_module", lambda _module_name: object())-def test_hybrid_analyze_import_does_not_require_vlm_utils() -> None:- """校验 Hybrid basic 所需模块导入阶段不再强依赖 VLM 工具包。"""+def _full_middle_json(*pages: PageInfo) -> MiddleJson:+ """构造未抽页的严格 MiddleJson 测试对象。"""+ return MiddleJson(+ pages=list(pages),+ is_full_document=True,+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version=__version__,+ )+++def test_backend_analyze_import_does_not_require_vlm_utils() -> None:+ """校验统一 backend 入口导入阶段不强依赖 VLM 工具包。"""repo_root = Path(__file__).resolve().parents[2]code = """import importlib.abc@@ -93,7 +103,7 @@ class BlockVlmUtilsFinder(importlib.abc.MetaPathFinder):sys.meta_path.insert(0, BlockVlmUtilsFinder())-import mineru.backend.hybrid.hybrid_analyze+import mineru.backend.analyzeprint("ok")"""@@ -719,7 +729,13 @@ def test_api_client_include_images_downloads_single_zip(monkeypatch: pytest.Monkpage = PageInfo(page_idx=0, blocks=[image_block])zip_buffer = io.BytesIO()with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as archive:- archive.writestr("middle_json.json", json.dumps(ParseResult(middle_json=MiddleJson(pages=[page], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__), _image_cache=image_cache).to_dict(), ensure_ascii=False))+ archive.writestr(+ "middle_json.json",+ json.dumps(+ ParseResult(middle_json=_full_middle_json(page), _image_cache=image_cache).to_dict(),+ ensure_ascii=False,+ ),+ )archive.writestr("images/chart.png", b"chart-bytes")archive.writestr("model_output.json", json.dumps([[{"raw": "model"}]], ensure_ascii=False, indent=4))download_calls: list[dict[str, object]] = []@@ -1477,9 +1493,7 @@ def _table_body_content(blocks: list[object]) -> str:def test_legacy_pdf_info_fills_content_from_html_when_content_missing() -> None:- pages = _pages_from_middle_json(- {"pdf_info": [_legacy_page_with_spans([_legacy_span_with_html("<table></table>")])]}- )+ pages = _pages_from_middle_json({"pdf_info": [_legacy_page_with_spans([_legacy_span_with_html("<table></table>")])]})assert _table_body_content(pages[0].blocks) == "<table></table>"@@ -1496,9 +1510,7 @@ def test_legacy_pdf_info_leaves_content_untouched_when_html_missing_or_empty() -span_no_html: dict[str, Any] = {"type": "text", "bbox": [0, 0, 10, 10], "content": "keep"}span_empty_html: dict[str, Any] = {"type": "text", "bbox": [0, 0, 10, 10], "content": "keep", "html": ""}- pages = _pages_from_middle_json(- {"pdf_info": [_legacy_page_with_spans([span_no_html, span_empty_html])]}- )+ pages = _pages_from_middle_json({"pdf_info": [_legacy_page_with_spans([span_no_html, span_empty_html])]})assert _table_body_content(pages[0].blocks) == "keep\nkeep"@@ -1907,19 +1919,16 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(content=[image_body],)parse_result = ParseResult(- middle_json=MiddleJson(- pages=[+ middle_json=_full_middle_json(PageInfo(page_idx=0,blocks=[image_block],)- ],- file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,),_image_cache=image_cache,- )+ )- async def fake_parse_async(*args, **kwargs) -> ParseResult:+ async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:return parse_resultmonkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)@@ -1941,8 +1950,6 @@ def test_api_server_rendered_outputs_do_not_return_image_sidecars(rec,request,file_store,- server_backend="hybrid-engine",- language="ch",ocr_mode="auto",image_analysis=True,allow_local_source=True,@@ -1962,7 +1969,7 @@ def test_api_server_run_job_normalizes_lightweight_file_tier_to_flash(async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:calls.append({"path": args[0], **kwargs})- return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))+ return ParseResult(middle_json=_full_middle_json(PageInfo(page_idx=0)))monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)file_store = FileStore(tmp_path / "api-files")@@ -1982,15 +1989,13 @@ def test_api_server_run_job_normalizes_lightweight_file_tier_to_flash(rec,request,file_store,- server_backend="hybrid-engine",- language="ch",ocr_mode="auto",image_analysis=True,allow_local_source=True,))- assert [(call["tier"], call["backend"]) for call in calls] == [("flash", "flash")]+ assert [call["tier"] for call in calls] == ["flash"]assert rec.tier == "standard"assert rec.files[0].status == "completed"@@ -2003,7 +2008,7 @@ def test_api_server_accepts_lightweight_job_without_requested_quality_runtime(response_tier: str,) -> None:async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:- return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))+ return ParseResult(middle_json=_full_middle_json(PageInfo(page_idx=0)))monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)source = tmp_path / "demo.html"@@ -2089,12 +2094,9 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(model_output: list[object],) -> None:parse_result = ParseResult(- middle_json=MiddleJson(- pages=[PageInfo(page_idx=0)],- file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,- ),+ middle_json=_full_middle_json(PageInfo(page_idx=0)),_model_output=model_output,- )+ )async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:return parse_result@@ -2118,8 +2120,6 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(rec,request,file_store,- server_backend="hybrid-engine",- language="ch",ocr_mode="auto",image_analysis=True,allow_local_source=True,@@ -2142,12 +2142,9 @@ def test_api_server_zip_rejects_unsafe_image_sidecar_path(tmp_path: Path,) -> None:parse_result = ParseResult(- middle_json=MiddleJson(- pages=[PageInfo(page_idx=0)],- file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,- ),+ middle_json=_full_middle_json(PageInfo(page_idx=0)),_image_cache={"../escape.png": b"bad-image"},- )+ )async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:return parse_result@@ -2170,8 +2167,6 @@ def test_api_server_zip_rejects_unsafe_image_sidecar_path(rec,request,file_store,- server_backend="hybrid-engine",- language="ch",ocr_mode="auto",image_analysis=True,allow_local_source=True,@@ -2188,12 +2183,9 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(tmp_path: Path,) -> None:parse_result = ParseResult(- middle_json=MiddleJson(- pages=[PageInfo(page_idx=0)],- file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,- ),+ middle_json=_full_middle_json(PageInfo(page_idx=0)),_model_output=None,- )+ )async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:return parse_result@@ -2217,8 +2209,6 @@ def test_api_server_zip_skips_model_output_when_parse_result_has_none(rec,request,file_store,- server_backend="hybrid-engine",- language="ch",ocr_mode="auto",image_analysis=True,allow_local_source=True,@@ -2265,8 +2255,6 @@ def test_api_server_logs_traceback_when_job_file_fails(rec,request,file_store,- server_backend="hybrid-engine",- language="ch",ocr_mode="auto",image_analysis=True,allow_local_source=True,@@ -2460,15 +2448,15 @@ def test_api_server_model_preload_is_opt_in_and_ignored_for_flash(tmp_path: Pathassert calls == [("basic", "ch")]-def test_api_server_standard_jobs_use_requested_tier_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """校验 Standard server 按每个 job 的 tier 选择 backend/effort,而不是复用全局默认值。"""+def test_api_server_standard_jobs_use_requested_tier(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """校验 Standard server 把每个 job 请求的 tier 传给统一 parser。"""_stub_api_server_dependency_preflight(monkeypatch)calls: list[dict[str, object]] = []async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:"""记录 API server 传给 parser 的 runtime 参数,并返回最小解析结果。"""calls.append(dict(kwargs))- return ParseResult(middle_json=MiddleJson(pages=[PageInfo(page_idx=0)], file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__))+ return ParseResult(middle_json=_full_middle_json(PageInfo(page_idx=0)))monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)source = tmp_path / "demo.pdf"@@ -2480,14 +2468,11 @@ def test_api_server_standard_jobs_use_requested_tier_runtime(tmp_path: Path, monasync def run_request(payload: dict[str, object]) -> dict[str, object]:request = CreateJobRequest.model_validate(payload)request.tier = request.tier or app.state.default_tier- runtime = app.state.tier_runtime_options[request.tier]rec = job_store.create(request, file_store)await api_server._run_job(rec,request,file_store,- server_backend=runtime.backend,- language=app.state.language,ocr_mode=app.state.ocr_mode,image_analysis=app.state.image_analysis,allow_local_source=app.state.allow_local_source,@@ -2526,11 +2511,7 @@ def test_api_server_standard_jobs_use_requested_tier_runtime(tmp_path: Path, monassert default_response["tier"] == "standard"assert basic_response["tier"] == "basic"assert advanced_response["tier"] == "advanced"- assert [(call["tier"], call["backend"]) for call in calls] == [- ("standard", "hybrid-engine"),- ("basic", "hybrid-engine"),- ("advanced", "hybrid-engine"),- ]+ assert [call["tier"] for call in calls] == ["standard", "basic", "advanced"]def test_api_server_basic_rejects_advanced_request(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -2599,7 +2580,7 @@ def test_api_server_skips_dependency_preflight_for_flash(monkeypatch: pytest.Mondef test_api_server_preflights_basic_tier_dependencies(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:imported_modules: list[str] = []- def fake_import_module(module_name: str):+ def fake_import_module(module_name: str) -> object:imported_modules.append(module_name)return object()@@ -2613,13 +2594,14 @@ def test_api_server_preflights_basic_tier_dependencies(monkeypatch: pytest.Monke"torch","torchvision","transformers",+ "accelerate",]def test_api_server_preflights_standard_tier_dependencies_for_platform(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:imported_modules: list[str] = []- def fake_import_module(module_name: str):+ def fake_import_module(module_name: str) -> object:imported_modules.append(module_name)return object()@@ -2646,7 +2628,7 @@ def test_api_server_preflights_standard_tier_dependencies_skip_mlx_on_intel_maco) -> None:imported_modules: list[str] = []- def fake_import_module(module_name: str):+ def fake_import_module(module_name: str) -> object:imported_modules.append(module_name)return object()@@ -2667,7 +2649,7 @@ def test_api_server_preflights_standard_tier_dependencies_skip_mlx_on_intel_macodef test_api_server_preflight_rejects_missing_tier_dependency(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:- def fake_import_module(module_name: str):+ def fake_import_module(module_name: str) -> object:if module_name == "torch":raise ModuleNotFoundError("No module named 'torch'")return object()@@ -2756,7 +2738,7 @@ def test_api_server_cli_rejects_backend_and_effort_options() -> None:def test_api_server_cli_defaults_to_all_quality_tiers(monkeypatch: pytest.MonkeyPatch) -> None:seen: dict[str, object] = {}- def _fake_run(server) -> None:+ def _fake_run(server: Any) -> None:"""记录无 --tier 启动后的默认 API server 能力,不启动真实服务。"""seen["tiers"] = [tier["id"] for tier in server.config.app.state.tiers]seen["default_tier"] = server.config.app.state.default_tier@@ -2779,7 +2761,7 @@ def test_api_server_cli_defaults_to_all_quality_tiers(monkeypatch: pytest.Monkeydef test_api_server_cli_accepts_single_tier_and_no_flash(monkeypatch: pytest.MonkeyPatch) -> None:seen: dict[str, object] = {}- def _fake_run(server) -> None:+ def _fake_run(server: Any) -> None:"""记录单个 --tier 与 --no-flash 启动后的 API server 能力列表。"""seen["tiers"] = [tier["id"] for tier in server.config.app.state.tiers]seen["default_tier"] = server.config.app.state.default_tier@@ -2830,7 +2812,7 @@ def test_api_server_cli_rejects_flash_no_flash_conflict() -> None:def test_api_server_cli_normalizes_hidden_language_alias(monkeypatch: pytest.MonkeyPatch) -> None:seen: dict[str, str] = {}- def _fake_run(server) -> None:+ def _fake_run(server: Any) -> None:"""记录 Click CLI 创建出的应用语言配置,避免测试启动真实服务。"""seen["language"] = server.config.app.state.languagediff --git a/tests/unittest/test_render_config.py b/tests/unittest/test_render_config.pyindex 055c466f..9c3df513 100644--- a/tests/unittest/test_render_config.py+++ b/tests/unittest/test_render_config.py@@ -5,7 +5,7 @@ from pathlib import Pathimport pytestfrom pydantic import ValidationError-from mineru.config import Config, _load_config+from mineru.config import Config, _collect_env_overrides, _load_configdef test_render_config_defaults() -> None:@@ -47,8 +47,8 @@ def test_render_config_supports_environment_overrides(monkeypatch: pytest.Monkeymonkeypatch.setenv(f"{prefix}RENDER_LATEX_DELIMITERS_INLINE_LEFT", r"\(")monkeypatch.setenv(f"{prefix}RENDER_LATEX_DELIMITERS_INLINE_RIGHT", r"\)")- # _apply_env_overrides is changed, should fix this test case.- config = _apply_env_overrides(Config(), prefix=prefix)+ overrides, _paths = _collect_env_overrides(prefix=prefix)+ config = Config(**overrides)assert config.render.latex_delimiters.inline.left == r"\("assert config.render.latex_delimiters.inline.right == r"\)"diff --git a/tests/unittest/test_render_image_renderer.py b/tests/unittest/test_render_image_renderer.pyindex ac83cfbc..14219fcb 100644--- a/tests/unittest/test_render_image_renderer.py+++ b/tests/unittest/test_render_image_renderer.py@@ -1,10 +1,12 @@from __future__ import annotations+from unittest.mock import Mock+import pytestfrom mineru.config import LatexDelimitersConfig, config+from mineru.render import ImageRendererfrom mineru.render._internal.markdown.blocks import render_single_block-from mineru.render.image import image_path_rendererfrom mineru.types import (BlockBase,BlockType,@@ -45,25 +47,22 @@ def _image_block() -> ImageBlock:)-def test_image_path_renderer_preserves_existing_relative_path_behavior() -> None:- block = _image_block()-- assert image_path_renderer(block, img_bucket_path="images") == ""--def test_pipeline_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:block = _image_block()+ renderer_mock = Mock(return_value="")+ image_renderer: ImageRenderer = renderer_mockrendered = render_single_block(block,delimiters=_delimiters(),asset_base_url="",- image_renderer=lambda _block: "",+ image_renderer=image_renderer,)assert "" in renderedassert "Figure caption" in renderedassert "internal/hash.jpg" not in rendered+ renderer_mock.assert_called_once_with(block)def test_office_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:@@ -116,7 +115,12 @@ def test_pipeline_markdown_uses_custom_renderer_for_image_only_visual_blocks(],)- rendered = render_single_block(block, delimiters=_delimiters(), asset_base_url="", image_renderer=lambda _block: "")+ rendered = render_single_block(+ block,+ delimiters=_delimiters(),+ asset_base_url="",+ image_renderer=lambda _block: "",+ )assert rendered == ""@@ -130,7 +134,12 @@ def test_pipeline_markdown_uses_custom_renderer_for_image_only_formula() -> Noneimage_path="internal/hash.jpg",)- rendered = render_single_block(block, delimiters=_delimiters(), asset_base_url="", image_renderer=lambda _block: "")+ rendered = render_single_block(+ block,+ delimiters=_delimiters(),+ asset_base_url="",+ image_renderer=lambda _block: "",+ )assert rendered == ""@@ -152,13 +161,45 @@ def test_custom_renderer_removes_internal_images_from_structured_table_html() ->],)+ image_renderer = Mock(return_value="")rendered = render_single_block(block,delimiters=_delimiters(),asset_base_url="",- image_renderer=lambda _block: "",+ image_renderer=image_renderer,)assert "Text" in renderedassert internal_path not in renderedassert "<img" not in rendered+ assert block.content[0].content == html+ image_renderer.assert_not_called()+++def test_custom_renderer_handles_table_html_containing_only_images() -> None:+ internal_path = "internal/cell-image.png"+ block = TableBlock(+ type=BlockType.TABLE,+ index=0,+ bbox=(0.0, 0.0, 0.1, 0.1),+ content=[+ TableBodyBlock(+ type=BlockType.TABLE_BODY,+ index=0,+ bbox=(0.0, 0.0, 0.1, 0.1),+ content=f'<table><tr><td><img src="{internal_path}"></td></tr></table>',+ )+ ],+ )+ image_renderer = Mock(return_value="")++ rendered = render_single_block(+ block,+ delimiters=_delimiters(),+ asset_base_url="",+ image_renderer=image_renderer,+ )++ assert rendered == ""+ assert internal_path not in rendered+ image_renderer.assert_called_once_with(block)