Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: add TeX Live LaTeX renderer

myhlolibbec867b12cb
diff --git a/docs/next/middle-json.md b/docs/next/middle-json.md
index 5d3ae1c8..4efd9a69 100644
--- a/docs/next/middle-json.md
+++ b/docs/next/middle-json.md
@@ -19,7 +19,7 @@ Middle JSON 已经收敛为 schema 2.0 的严格 Pydantic 模型:`mineru/types
5. [Canonical Envelope](middle-json/envelope.md): 顶层结构、`_meta`、版本和兼容输入。
6. [当前 Content List v2 结构盘点](middle-json/structured-content-current.md): 当前 Structured Content 起点的事实结构。
7. [Structured Content Schema](middle-json/structured-content-schema.md): NEXT 版结构化内容 JSON 的目标 schema 草案。
-8. [Rendering Contract](middle-json/rendering.md): Markdown / HTML / DOCX / Structured Content 如何通过 `render/api.py` 消费 middle structure。
+8. [Rendering Contract](middle-json/rendering.md): Markdown / HTML / LaTeX / DOCX / Structured Content 如何通过 `render/api.py` 消费 middle structure。
9. [迁移计划](middle-json/migration.md): 可执行阶段、任务清单和验收标准。
## 整理原则
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.md
index 8dddd036..1ba45132 100644
--- a/docs/next/middle-json/rendering.md
+++ b/docs/next/middle-json/rendering.md
@@ -1,8 +1,8 @@
# Rendering Contract
-状态: 统一入口 / Markdown / Content List V1/V2 / Structured Content / DOCX / EPUB 3.3 / PDF / HTML v1
+状态: 统一入口 / Markdown / LaTeX / Content List V1/V2 / Structured Content / DOCX / EPUB 3.3 / PDF / HTML v1
读者: render 开发者、backend 开发者、SDK 开发者
-范围: 严格 MiddleJson 到 Markdown、Content List V1/V2、Structured Content、DOCX、EPUB、PDF 和 HTML 的统一消费契约
+范围: 严格 MiddleJson 到 Markdown、LaTeX、Content List V1/V2、Structured Content、DOCX、EPUB、PDF 和 HTML 的统一消费契约
## 统一入口
@@ -30,6 +30,7 @@ markdown = render(
| --- | --- | --- |
| `MARKDOWN` | `MarkdownRenderOptions(mode, asset_base_url, image_renderer)` | `str` |
| `HTML` | `HtmlRenderOptions(mode, asset_base_url, standalone, document_title)` | `str` |
+| `LATEX` | `LatexRenderOptions(asset_base_path, document_title)` | `str` |
| `DOCX` | `DocxRenderOptions(asset_resolver)` | `bytes` |
| `EPUB` | `EpubRenderOptions(title, authors, language, identifier, modified_at, asset_resolver)` | `bytes` |
| `PDF` | `PdfRenderOptions(asset_resolver, document_title)` | `bytes` |
@@ -43,12 +44,13 @@ markdown = render(
只有 Markdown 与 HTML 的专用函数和 Options 暴露 `mode`;其它格式传入 `mode` 会按严格签名
直接抛出 `TypeError`,不会兼容或静默忽略。
-所有入口均不修改传入的 `MiddleJson`。renderer 不负责把结果或图片写到文件系统;DOCX、
-EPUB 与 PDF 需要读取相对图片 sidecar 时,只能通过显式 `asset_resolver` 获取字节。
+所有入口均不修改传入的 `MiddleJson`。renderer 不负责把结果或图片写到文件系统;LaTeX 只在
+源码中引用现有 sidecar,DOCX、EPUB 与 PDF 需要读取相对图片 sidecar 时只能通过显式
+`asset_resolver` 获取字节。
### 内部依赖边界
-`markdown.py`、`html.py`、`docx.py`、`epub.py`、`pdf.py`、`content_list.py`、`content_list_v2.py` 和
+`markdown.py`、`html.py`、`latex.py`、`docx.py`、`epub.py`、`pdf.py`、`content_list.py`、`content_list_v2.py` 和
`structured_content.py` 是稳定公共门面;实现代码位于非公共
`mineru.render._internal`。`common` 只保存跨格式 AST、解析、列表/目录语义和 render planner,
不得依赖任一格式实现。各格式私有子包只能依赖 `common`、基础层与自身模块,彼此
@@ -78,6 +80,45 @@ image block 及无结构内容的 table/chart/equation 可以改用调用方提
仍保留文本或表格内容,但会移除由自定义 renderer 接管的内嵌 `<img>`。清理后只剩图片的
table 会回退到自定义 renderer。
+## TeX Live LaTeX
+
+```python
+from pathlib import Path
+
+from mineru.render import render_latex
+
+latex_source = render_latex(
+ middle_json,
+ asset_base_path=".",
+ document_title=None,
+)
+Path("main.tex").write_text(latex_source, encoding="utf-8")
+```
+
+`render_latex()` 返回完整 UTF-8 `.tex` 字符串,不写文件、不读取 cwd、不访问网络。标准编译命令为:
+
+```bash
+latexmk -xelatex main.tex
+```
+
+编译环境合同是 TeX Live 官方安装器的默认 `scheme-full`,不是 Linux 发行版可能裁剪过的同名
+系统包。文档固定使用 `ctexart` 与 TeX Live 自带 Fandol 字体,因此 Windows、macOS 和 Linux
+都不依赖系统中文字体,也不需要 `.latexmkrc`、Shell Escape 或额外下载宏包。
+
+LaTeX 固定使用共享 planner 的 DEFAULT 连续语义:隐藏页面辅助块、合并跨页续段、续列表和续表,
+不保留空源页或源页面硬分页,`page_footnote` 继续输出。标题、正文和页面脚注 anchor 使用稳定安全的
+document-wide target;Index 与 fragment 链接只跳转到真实目标。普通文字、样式、代码、metadata、
+链接和路径均执行 TeX 转义;MiddleJson 中不含外层定界符的行内/行间 LaTeX 公式按原始内容输出。
+
+图片只引用 `png`、`jpg/jpeg` 或 `pdf` 的安全 `image_path`。`asset_base_path` 相对于实际编译目录
+拼接 sidecar;renderer 不复制图片。data URI、远程 URL、缺失路径和 XeLaTeX 不支持的格式会输出
+可见替代信息,远程 URL 保留为链接。HTML table 使用 `longtable`,支持 `rowspan/colspan`、嵌套表、
+富文本、公式、链接和相对图片;结构无效时依次回退表格图片、可见文本与占位。
+
+renderer 不执行生成的源码。裸公式属于保真通道,可能包含任意 TeX 指令;来自不可信文档的 `.tex`
+必须在隔离环境中以禁用 Shell Escape 的方式编译。该能力只属于严格 `mineru.render` 公共面,不新增
+ParseResult 方法,也不迁移 CLI、API、doclib 或 parse-job `output_formats`。
+
## 可编辑 DOCX
```python
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index 0209b977..2eb6a7a1 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -9,6 +9,7 @@ from .contracts import (
EpubRenderOptions,
HtmlRenderOptions,
ImageRenderer,
+ LatexRenderOptions,
MarkdownRenderOptions,
PdfRenderOptions,
RenderFormat,
@@ -22,6 +23,7 @@ from .content_list_v2 import render_content_list_v2
from .docx import DocxRenderError, render_docx
from .epub import render_epub
from .html import render_html
+from .latex import render_latex
from .markdown import render_markdown
from .pdf import render_pdf
from .structured_content import render_structured_content
@@ -35,6 +37,7 @@ __all__ = [
"EpubRenderOptions",
"HtmlRenderOptions",
"ImageRenderer",
+ "LatexRenderOptions",
"MarkdownRenderOptions",
"PdfRenderOptions",
"RenderFormat",
@@ -48,6 +51,7 @@ __all__ = [
"render_docx",
"render_epub",
"render_html",
+ "render_latex",
"render_markdown",
"render_pdf",
"render_structured_content",
diff --git a/mineru/render/_internal/common/html_table.py b/mineru/render/_internal/common/html_table.py
new file mode 100644
index 00000000..b0086c99
--- /dev/null
+++ b/mineru/render/_internal/common/html_table.py
@@ -0,0 +1,179 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""多格式 renderer 共用的有界 HTML table 占位网格解析。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import TypeAlias
+
+from bs4 import BeautifulSoup, Tag
+
+MAX_NESTED_TABLE_DEPTH = 4
+MAX_TABLE_ROWS = 500
+MAX_TABLE_COLUMNS = 100
+MAX_TABLE_SLOTS = 10_000
+_POSITIVE_INTEGER_RE = re.compile(r"[0-9]+")
+
+HtmlTableSource: TypeAlias = str | BeautifulSoup | Tag
+
+
+class HtmlTableError(ValueError):
+ """表示 HTML table 无法安全解析为严格矩形网格。"""
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlTableCell:
+ """保存原始 HTML 单元格在逻辑占位网格中的位置。"""
+
+ tag: Tag
+ row: int
+ column: int
+ rowspan: int
+ colspan: int
+ is_header: bool
+
+ @property
+ def end_row(self) -> int:
+ """返回单元格占用的末行下标。"""
+ return self.row + self.rowspan - 1
+
+ @property
+ def end_column(self) -> int:
+ """返回单元格占用的末列下标。"""
+ return self.column + self.colspan - 1
+
+
+@dataclass(frozen=True, slots=True)
+class HtmlTableGrid:
+ """保存经过重叠、边界、规模与矩形校验的 HTML 表格网格。"""
+
+ tag: Tag
+ row_count: int
+ column_count: int
+ cells: tuple[HtmlTableCell, ...]
+ header_rows: tuple[int, ...]
+
+
+def parse_html_tables(source: HtmlTableSource) -> tuple[HtmlTableGrid, ...]:
+ """解析 source 中相对当前上下文的一个或多个顶层 table。"""
+ root = BeautifulSoup(source, "html.parser") if isinstance(source, str) else source
+ if not isinstance(root, (BeautifulSoup, Tag)):
+ raise HtmlTableError("HTML table source must be a string or BeautifulSoup Tag")
+ if isinstance(root, Tag) and root.name == "table":
+ table_tags = (root,)
+ else:
+ parent_table = root.find_parent("table") if isinstance(root, Tag) else None
+ table_tags = tuple(table for table in root.find_all("table") if table.find_parent("table") is parent_table)
+ if not table_tags:
+ raise HtmlTableError("HTML does not contain a top-level table")
+ return tuple(_parse_html_table(table) for table in table_tags)
+
+
+def _parse_html_table(table: Tag) -> HtmlTableGrid:
+ """把单个 table 标签解析为严格矩形占位网格。"""
+ if table.name != "table":
+ raise HtmlTableError("Expected a <table> tag")
+ rows = tuple(row for row in table.find_all("tr") if row.find_parent("table") is table)
+ if not rows or len(rows) > MAX_TABLE_ROWS:
+ raise HtmlTableError(f"Table row count must be between 1 and {MAX_TABLE_ROWS}")
+
+ occupied: dict[tuple[int, int], HtmlTableCell] = {}
+ cells: list[HtmlTableCell] = []
+ for row_index, row in enumerate(rows):
+ column_index = 0
+ for source_cell in row.find_all(("td", "th"), recursive=False):
+ while (row_index, column_index) in occupied:
+ column_index += 1
+ rowspan = _parse_span(source_cell, "rowspan")
+ colspan = _parse_span(source_cell, "colspan")
+ if row_index + rowspan > len(rows):
+ raise HtmlTableError(f"rowspan exceeds table bounds at row={row_index}, column={column_index}")
+ if column_index + colspan > MAX_TABLE_COLUMNS:
+ raise HtmlTableError(f"Table column count exceeds {MAX_TABLE_COLUMNS}")
+ coordinates = tuple(
+ (target_row, target_column)
+ for target_row in range(row_index, row_index + rowspan)
+ for target_column in range(column_index, column_index + colspan)
+ )
+ overlap = next((coordinate for coordinate in coordinates if coordinate in occupied), None)
+ if overlap is not None:
+ raise HtmlTableError(f"Cell span overlaps row={overlap[0]}, column={overlap[1]}")
+ placement = HtmlTableCell(
+ tag=source_cell,
+ row=row_index,
+ column=column_index,
+ rowspan=rowspan,
+ colspan=colspan,
+ is_header=source_cell.name == "th",
+ )
+ cells.append(placement)
+ occupied.update(dict.fromkeys(coordinates, placement))
+ if len(occupied) > MAX_TABLE_SLOTS:
+ raise HtmlTableError(f"Table occupancy exceeds {MAX_TABLE_SLOTS} slots")
+ column_index += colspan
+
+ if not occupied:
+ raise HtmlTableError("Table must contain at least one cell")
+ column_count = max(column for _, column in occupied) + 1
+ missing = next(
+ (
+ (row_index, column_index)
+ for row_index in range(len(rows))
+ for column_index in range(column_count)
+ if (row_index, column_index) not in occupied
+ ),
+ None,
+ )
+ if missing is not None:
+ raise HtmlTableError(f"Table occupancy is not rectangular at row={missing[0]}, column={missing[1]}")
+ header_rows = tuple(
+ row_index
+ for row_index, row in enumerate(rows)
+ if _row_belongs_to_thead(row, table)
+ or all(occupied[(row_index, column_index)].is_header for column_index in range(column_count))
+ )
+ return HtmlTableGrid(
+ tag=table,
+ row_count=len(rows),
+ column_count=column_count,
+ cells=tuple(cells),
+ header_rows=header_rows,
+ )
+
+
+def _parse_span(cell: Tag, attribute: str) -> int:
+ """读取严格正整数 rowspan/colspan,缺失时返回一。"""
+ raw_value = cell.get(attribute, "1")
+ if isinstance(raw_value, list):
+ raise HtmlTableError(f"Invalid {attribute}: {raw_value!r}")
+ value = str(raw_value).strip()
+ if _POSITIVE_INTEGER_RE.fullmatch(value) is None:
+ raise HtmlTableError(f"Invalid {attribute}: {raw_value!r}")
+ span = int(value)
+ if span < 1 or span > MAX_TABLE_SLOTS:
+ raise HtmlTableError(f"Invalid {attribute}: {raw_value!r}")
+ return span
+
+
+def _row_belongs_to_thead(row: Tag, table: Tag) -> bool:
+ """判断 tr 是否位于当前 table 的 thead 内。"""
+ parent = row.parent
+ while isinstance(parent, Tag) and parent is not table:
+ if parent.name == "thead":
+ return True
+ parent = parent.parent
+ return False
+
+
+__all__ = [
+ "HtmlTableCell",
+ "HtmlTableError",
+ "HtmlTableGrid",
+ "HtmlTableSource",
+ "MAX_NESTED_TABLE_DEPTH",
+ "MAX_TABLE_COLUMNS",
+ "MAX_TABLE_ROWS",
+ "MAX_TABLE_SLOTS",
+ "parse_html_tables",
+]
diff --git a/mineru/render/_internal/latex/__init__.py b/mineru/render/_internal/latex/__init__.py
new file mode 100644
index 00000000..818730ae
--- /dev/null
+++ b/mineru/render/_internal/latex/__init__.py
@@ -0,0 +1,3 @@
+# Copyright (c) Opendatalab. All rights reserved.
+
+__all__: list[str] = []
diff --git a/mineru/render/_internal/latex/assets.py b/mineru/render/_internal/latex/assets.py
new file mode 100644
index 00000000..6a7061ee
--- /dev/null
+++ b/mineru/render/_internal/latex/assets.py
@@ -0,0 +1,86 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""LaTeX renderer 的纯路径 sidecar 图片解析。"""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+from urllib.parse import urlsplit
+
+from ....types import ImagePayloadBlock
+from ....utils.image_payload import validate_image_sidecar_path
+
+_SUPPORTED_IMAGE_EXTENSIONS = {".jpeg", ".jpg", ".pdf", ".png"}
+_FORBIDDEN_TEX_PATH_CHARACTERS = {"%", "{", "}"}
+
+
+def normalize_asset_base_path(asset_base_path: str) -> str:
+ """把调用方路径前缀规范化为 TeX 可跨平台读取的正斜杠形式。"""
+ if not isinstance(asset_base_path, str):
+ raise TypeError("asset_base_path must be a string")
+ if any(character == "\x00" or character in "\r\n" for character in asset_base_path):
+ raise ValueError("asset_base_path must not contain control characters")
+ normalized = asset_base_path.replace("\\", "/")
+ if normalized == "/" or (len(normalized) == 3 and normalized[1:] == ":/"):
+ return normalized
+ return normalized.rstrip("/")
+
+
+def resolve_block_image_path(block: ImagePayloadBlock, asset_base_path: str) -> str | None:
+ """只从 block 的安全 sidecar 路径解析 XeLaTeX 可直接读取的图片。"""
+ if block.image_path is None:
+ return None
+ return resolve_relative_image_path(block.image_path, asset_base_path)
+
+
+def resolve_html_image_path(source: str, asset_base_path: str) -> str | None:
+ """解析 HTML img 的安全相对路径,拒绝 data URI 与远程地址。"""
+ if not isinstance(source, str):
+ return None
+ normalized = source.strip()
+ if not normalized:
+ return None
+ parsed = urlsplit(normalized)
+ if parsed.scheme or parsed.netloc or normalized.startswith(("/", "#")):
+ return None
+ try:
+ return resolve_relative_image_path(normalized, asset_base_path)
+ except ValueError:
+ return None
+
+
+def resolve_relative_image_path(relative_path: str, asset_base_path: str) -> str | None:
+ """拼接安全相对路径,并限制为 XeLaTeX 原生支持的图片扩展名。"""
+ safe_path = validate_image_sidecar_path(relative_path)
+ if PurePosixPath(safe_path).suffix.casefold() not in _SUPPORTED_IMAGE_EXTENSIONS:
+ return None
+ if not asset_base_path:
+ resolved = safe_path
+ elif asset_base_path.endswith("/"):
+ resolved = f"{asset_base_path}{safe_path}"
+ else:
+ resolved = f"{asset_base_path}/{safe_path}"
+ if any(character in _FORBIDDEN_TEX_PATH_CHARACTERS for character in resolved):
+ return None
+ if any(ord(character) < 0x20 or ord(character) == 0x7F for character in resolved):
+ return None
+ return resolved
+
+
+def remote_block_image_url(block: ImagePayloadBlock) -> str | None:
+ """返回 block 已由严格模型校验过的远程图片 URL。"""
+ return block.image_url
+
+
+def tex_image_path(path: str) -> str:
+ """使用 detokenize 包装已校验路径,保留空格及 TeX 保留字符。"""
+ return rf"\detokenize{{{path}}}"
+
+
+__all__ = [
+ "normalize_asset_base_path",
+ "remote_block_image_url",
+ "resolve_block_image_path",
+ "resolve_html_image_path",
+ "resolve_relative_image_path",
+ "tex_image_path",
+]
diff --git a/mineru/render/_internal/latex/inline.py b/mineru/render/_internal/latex/inline.py
new file mode 100644
index 00000000..6c209a2b
--- /dev/null
+++ b/mineru/render/_internal/latex/inline.py
@@ -0,0 +1,146 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 InlineSpan 到安全 LaTeX 行内源码的转换。"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from hashlib import sha256
+import re
+from typing import Iterable
+
+from ....backend.postprocess.inline import join_inline_spans
+from ....types import CodeInlineSpan, EquationInlineSpan, HyperlinkSpan, InlineSpan, InlineStyle, TextSpan
+
+_INVALID_TEXT_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
+_TEXT_ESCAPES = {
+ "\\": r"\textbackslash{}",
+ "{": r"\{",
+ "}": r"\}",
+ "$": r"\$",
+ "&": r"\&",
+ "#": r"\#",
+ "_": r"\_",
+ "%": r"\%",
+ "~": r"\textasciitilde{}",
+ "^": r"\textasciicircum{}",
+}
+_URL_ESCAPES = {
+ "\\": "/",
+ "{": r"\{",
+ "}": r"\}",
+ "$": r"\$",
+ "&": r"\&",
+ "#": r"\#",
+ "_": r"\_",
+ "%": r"\%",
+ "~": r"\string~",
+ "^": r"\string^",
+}
+
+
+@dataclass(slots=True)
+class LatexAnchorRegistry:
+ """把原始 anchor 映射为安全稳定 target,并只发射首次定义。"""
+
+ source_targets: set[str]
+ emitted: set[str] = field(default_factory=set)
+
+ def target_for(self, anchor: str | None) -> str | None:
+ """仅为真实可见目标返回稳定的 TeX target 名。"""
+ normalized = (anchor or "").strip()
+ if not normalized or normalized not in self.source_targets:
+ return None
+ digest = sha256(normalized.encode("utf-8")).hexdigest()[:24]
+ return f"mineru-{digest}"
+
+ def emit_target(self, anchor: str | None) -> str:
+ """首次出现时输出 hypertarget,重复 anchor 不再重复定义。"""
+ target = self.target_for(anchor)
+ if target is None or target in self.emitted:
+ return ""
+ self.emitted.add(target)
+ return rf"\hypertarget{{{target}}}{{}}"
+
+
+def escape_latex_text(content: str, *, preserve_newlines: bool = True) -> str:
+ """转义普通文本中的全部 TeX 控制字符并保留 Unicode。"""
+ normalized = _INVALID_TEXT_CONTROL_RE.sub("\ufffd", content).replace("\r\n", "\n").replace("\r", "\n")
+ parts: list[str] = []
+ for character in normalized:
+ if character == "\n":
+ parts.append(r"\MinerULineBreak{}" if preserve_newlines else " ")
+ else:
+ parts.append(_TEXT_ESCAPES.get(character, character))
+ return "".join(parts)
+
+
+def escape_latex_url(target: str) -> str:
+ """转义 hyperref URL 参数,同时保留 URL 的可解析结构。"""
+ normalized = _INVALID_TEXT_CONTROL_RE.sub("", target).replace("\r", "").replace("\n", "")
+ return "".join(_URL_ESCAPES.get(character, character) for character in normalized)
+
+
+def render_inline_spans(spans: Iterable[InlineSpan], anchors: LatexAnchorRegistry) -> str:
+ """按 span discriminator 渲染完整行内语义。"""
+ parts: list[str] = []
+ for span in spans:
+ if isinstance(span, TextSpan):
+ rendered = escape_latex_text(span.content)
+ parts.append(_apply_text_styles(rendered, span.styles))
+ elif isinstance(span, EquationInlineSpan):
+ parts.append(rf"\({span.content}\)")
+ elif isinstance(span, CodeInlineSpan):
+ parts.append(rf"\texttt{{{_escape_inline_code(span.content)}}}")
+ elif isinstance(span, HyperlinkSpan):
+ label = render_inline_spans(span.content, anchors)
+ if span.url.startswith("#"):
+ target = anchors.target_for(span.url[1:])
+ parts.append(rf"\hyperlink{{{target}}}{{{label}}}" if target else label)
+ else:
+ parts.append(rf"\href{{{escape_latex_url(span.url)}}}{{{label}}}")
+ else:
+ raise TypeError(f"Unsupported InlineSpan type: {type(span).__name__}")
+ return "".join(parts)
+
+
+def render_joined_inline_contents(
+ contents: Iterable[Iterable[InlineSpan]],
+ anchors: LatexAnchorRegistry,
+) -> str:
+ """按共享物理段落边界规则合并并渲染多段 InlineSpan。"""
+ return render_inline_spans(join_inline_spans(contents), anchors)
+
+
+def _apply_text_styles(content: str, styles: list[InlineStyle]) -> str:
+ """按公开固定顺序嵌套 LaTeX 文字样式。"""
+ wrappers = {
+ "bold": r"\textbf{%s}",
+ "italic": r"\textit{%s}",
+ "underline": r"\uline{%s}",
+ "emphasis": r"\CJKunderdot[format=\normalcolor]{%s}",
+ "strikethrough": r"\sout{%s}",
+ "superscript": r"\textsuperscript{%s}",
+ "subscript": r"\textsubscript{%s}",
+ }
+ rendered = content
+ for style in reversed(styles):
+ wrapper = wrappers.get(style)
+ if wrapper is None:
+ raise TypeError(f"Unsupported inline style: {style}")
+ rendered = wrapper % rendered
+ return rendered
+
+
+def _escape_inline_code(content: str) -> str:
+ """转义行内代码,并把连续空格与 Tab 转为等宽可见空格。"""
+ expanded = content.replace("\t", " ")
+ return escape_latex_text(expanded).replace(" ", r"\ ")
+
+
+__all__ = [
+ "LatexAnchorRegistry",
+ "escape_latex_text",
+ "escape_latex_url",
+ "render_inline_spans",
+ "render_joined_inline_contents",
+]
diff --git a/mineru/render/_internal/latex/renderer.py b/mineru/render/_internal/latex/renderer.py
new file mode 100644
index 00000000..6859673b
--- /dev/null
+++ b/mineru/render/_internal/latex/renderer.py
@@ -0,0 +1,518 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到 TeX Live XeLaTeX 完整文档的渲染实现。"""
+
+from __future__ import annotations
+
+import re
+
+from bs4 import BeautifulSoup
+from loguru import logger
+
+from ....backend.postprocess.inline import inline_plain_text
+from ....types import (
+ PAGE_AUXILIARY_BLOCK_TYPES,
+ RAW_ALGORITHM,
+ AlgorithmBodyBlock,
+ BlockType,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ ImagePayloadBlock,
+ IndexBlock,
+ InlineSpan,
+ ListBlock,
+ MiddleJson,
+ PageFootnoteBlock,
+ ParagraphTitleBlock,
+ RefTextBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+ TitleBlockBase,
+)
+from ..common.index import strip_index_page_tail
+from ..common.list_items import ListItem, parse_list_item_marker, reference_list_needs_bullets
+from ..common.planner import PlannedBlock, build_render_plan
+from .assets import (
+ normalize_asset_base_path,
+ remote_block_image_url,
+ resolve_block_image_path,
+ tex_image_path,
+)
+from .inline import (
+ LatexAnchorRegistry,
+ escape_latex_text,
+ escape_latex_url,
+ render_inline_spans,
+ render_joined_inline_contents,
+)
+from .table import LatexTableError, LatexTableRenderer
+
+_HTML_TABLE_RE = re.compile(r"<\s*table\b", re.IGNORECASE)
+_TOP_LEVEL_DISPLAY_ENV_RE = re.compile(
+ r"^\s*\\begin\{(?P<name>align\*?|equation\*?|gather\*?|multline\*?)\}",
+ re.DOTALL,
+)
+_PREAMBLE_LINES = (
+ "% !TeX program = xelatex",
+ "% Generated by MinerU. Compile with: latexmk -xelatex <file>.tex",
+ r"\documentclass[UTF8,fontset=fandol,11pt]{ctexart}",
+ r"\usepackage[a4paper,margin=20mm]{geometry}",
+ r"\usepackage{amsmath,amssymb}",
+ r"\usepackage{graphicx}",
+ r"\usepackage{longtable}",
+ r"\usepackage{array}",
+ r"\usepackage{booktabs}",
+ r"\usepackage{multirow}",
+ r"\usepackage{enumitem}",
+ r"\usepackage[table]{xcolor}",
+ r"\usepackage[normalem]{ulem}",
+ r"\usepackage{xeCJKfntef}",
+ r"\usepackage{fvextra}",
+ r"\usepackage[unicode,hidelinks]{hyperref}",
+ r"\definecolor{MinerUGray}{HTML}{6B7280}",
+ r"\definecolor{MinerUSurface}{HTML}{F3F4F6}",
+ r"\definecolor{MinerUTableHeader}{HTML}{E5E7EB}",
+ r"\setlength{\parindent}{2em}",
+ r"\setlength{\parskip}{0.4em}",
+ r"\setlist{leftmargin=*,nosep}",
+ r"\setlength{\LTpre}{0.4em}",
+ r"\setlength{\LTpost}{0.6em}",
+ r"\newcommand{\MinerULineBreak}{\leavevmode\hfill\break}",
+ r"\newcommand{\MinerUPlaceholder}[1]{\fcolorbox{MinerUGray}{MinerUSurface}{\textit{#1}}}",
+)
+
+
+class _LatexRenderer:
+ """保存一次完整 LaTeX 文档渲染所需的确定性状态。"""
+
+ def __init__(
+ self,
+ middle_json: MiddleJson,
+ *,
+ asset_base_path: str,
+ document_title: str | None,
+ ) -> None:
+ """初始化共享 planner、anchor、表格与代码环境上下文。"""
+ self.middle_json = middle_json
+ self.asset_base_path = normalize_asset_base_path(asset_base_path)
+ self.document_title = _resolve_document_title(middle_json, document_title)
+ self.anchors = LatexAnchorRegistry(_collect_anchor_targets(middle_json))
+ self.tables = LatexTableRenderer(asset_base_path=self.asset_base_path, anchors=self.anchors)
+ self.verbatim_counter = 0
+
+ def render(self) -> str:
+ """生成包含固定 TeX Live 导言区与正文环境的完整源码。"""
+ rendered_blocks: list[str] = []
+ for page in build_render_plan(self.middle_json):
+ for planned in page:
+ if planned.removed or planned.block.type in PAGE_AUXILIARY_BLOCK_TYPES:
+ continue
+ rendered = self._render_planned_block(planned)
+ if rendered.strip():
+ rendered_blocks.append(rendered.strip("\n"))
+ title = escape_latex_text(self.document_title, preserve_newlines=False)
+ lines = [*_PREAMBLE_LINES, rf"\hypersetup{{pdftitle={{{title}}}}}", r"\begin{document}"]
+ if rendered_blocks:
+ lines.extend(("", "\n\n".join(rendered_blocks), ""))
+ lines.append(r"\end{document}")
+ return "\n".join(lines) + "\n"
+
+ def _render_planned_block(self, planned: PlannedBlock) -> str:
+ """按严格 PageBlock 具体类型分发 LaTeX 渲染。"""
+ block = planned.block
+ if isinstance(block, TextBlock):
+ content = render_joined_inline_contents(planned.text_contents or [block.content], self.anchors)
+ return self._anchored_paragraph(content, block.anchor)
+ if isinstance(block, RefTextBlock):
+ content = render_joined_inline_contents(planned.text_contents or [block.content], self.anchors)
+ return _paragraph(content)
+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):
+ return self._render_title(block)
+ if isinstance(block, PageFootnoteBlock):
+ return self._render_page_footnote(block)
+ if isinstance(block, EquationBlock):
+ return self._render_equation(block)
+ if isinstance(block, ListBlock):
+ return self._render_list(block)
+ if isinstance(block, IndexBlock):
+ return self._render_index(block)
+ if isinstance(block, ImageBlock):
+ return self._render_image_block(block)
+ if isinstance(block, TableBlock):
+ return self._render_table_block(block)
+ if isinstance(block, ChartBlock):
+ return self._render_chart_block(block)
+ if isinstance(block, CodeBlock):
+ return self._render_code_block(block)
+ raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")
+
+ def _anchored_paragraph(self, content: str, anchor: str | None) -> str:
+ """给可见正文添加首次出现的文档级 hypertarget。"""
+ if not content.strip():
+ return ""
+ target = self.anchors.emit_target(anchor)
+ return "\n".join(part for part in (target, _paragraph(content)) if part)
+
+ def _render_title(self, block: DocTitleBlock | ParagraphTitleBlock) -> str:
+ """把全局标题层级映射为无编号 LaTeX 标题命令。"""
+ content = render_inline_spans(block.content, self.anchors)
+ if not content.strip():
+ return ""
+ target = self.anchors.emit_target(block.anchor)
+ command = {
+ 1: "section",
+ 2: "subsection",
+ 3: "subsubsection",
+ 4: "paragraph",
+ 5: "subparagraph",
+ }.get(block.level)
+ heading = rf"\{command}*{{{content}}}" if command is not None else rf"\par\noindent{{\small\bfseries {content}}}\par"
+ return "\n".join(part for part in (target, heading) if part)
+
+ def _render_page_footnote(self, block: PageFootnoteBlock) -> str:
+ """把页面脚注保留为可寻址的小字号灰色正文块。"""
+ content = render_inline_spans(block.content, self.anchors)
+ if not content.strip():
+ return ""
+ target = self.anchors.emit_target(block.anchor)
+ footnote = rf"{{\footnotesize\color{{MinerUGray}} {content}\par}}"
+ return "\n".join(part for part in (target, footnote) if part)
+
+ def _render_equation(self, block: EquationBlock) -> str:
+ """原样输出块级 LaTeX;空公式按 sidecar 与占位顺序回退。"""
+ content = block.content.strip()
+ if content:
+ return _wrap_display_formula(content)
+ if not _has_image_payload(block):
+ return self._placeholder("formula unavailable") + r"\par"
+ return self._render_image_payload(block, alt_text="formula")
+
+ def _render_list(self, block: ListBlock) -> str:
+ """按共享 marker 分类递归输出原生或显式标记列表。"""
+ parsed_leaves = [
+ parse_list_item_marker(child.content)
+ for child in block.content
+ if not isinstance(child, ListBlock) and inline_plain_text(child.content).strip()
+ ]
+ add_reference_bullets = reference_list_needs_bullets(block)
+ environment, kind = _classify_list(parsed_leaves, add_reference_bullets)
+ options = "[leftmargin=*,nosep]"
+ if environment == "description":
+ options = "[style=nextline,leftmargin=3em,nosep]"
+ lines = [rf"\begin{{{environment}}}{options}"]
+ has_item = False
+ for child in block.content:
+ if isinstance(child, ListBlock):
+ nested = self._render_list(child)
+ if nested:
+ if not has_item:
+ lines.append(r"\item[]")
+ has_item = True
+ lines.append(nested)
+ continue
+ parsed = parse_list_item_marker(child.content)
+ item_spans, label = _list_item_content(parsed, child.content, kind, add_reference_bullets)
+ content = render_inline_spans(item_spans, self.anchors) or "~"
+ if environment == "description" or label is not None:
+ rendered_label = escape_latex_text(label or "", preserve_newlines=False)
+ lines.append(rf"\item[{{{rendered_label}}}] {content}")
+ else:
+ lines.append(rf"\item {content}")
+ has_item = True
+ lines.append(rf"\end{{{environment}}}")
+ return "\n".join(lines) if has_item else ""
+
+ def _render_index(self, block: IndexBlock) -> str:
+ """递归输出正文内目录,并仅链接真实 anchor target。"""
+ lines = [r"\begin{itemize}[leftmargin=*,nosep]"]
+ has_item = False
+ for child in block.content:
+ if isinstance(child, IndexBlock):
+ nested = self._render_index(child)
+ if nested:
+ if not has_item:
+ lines.append(r"\item[]")
+ has_item = True
+ lines.append(nested)
+ continue
+ content = strip_index_page_tail(child.content)
+ label = render_inline_spans(content, self.anchors).strip()
+ if not label:
+ continue
+ target = self.anchors.target_for(child.anchor)
+ if target is not None:
+ label = rf"\hyperlink{{{target}}}{{{label}}}"
+ lines.append(rf"\item {label}")
+ has_item = True
+ lines.append(r"\end{itemize}")
+ return "\n".join(lines) if has_item else ""
+
+ def _render_image_block(self, block: ImageBlock) -> str:
+ """按原始子块顺序输出图片主体及说明文本。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, ImageBodyBlock):
+ alt = _plain_html_text(child.content) or block.sub_type or "image"
+ parts.append(self._render_image_payload(child, alt_text=alt))
+ elif isinstance(child, ImageAnnotationBlock):
+ parts.append(self._render_annotation(child))
+ else:
+ raise TypeError(f"Unsupported image child: {type(child).__name__}")
+ return _join_parts(parts)
+
+ def _render_table_block(self, block: TableBlock) -> str:
+ """优先输出原生 longtable,再回退图片、可见文本或占位。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, TableBodyBlock):
+ parts.append(self._render_table_body(child))
+ elif isinstance(child, TableAnnotationBlock):
+ parts.append(self._render_annotation(child))
+ else:
+ raise TypeError(f"Unsupported table child: {type(child).__name__}")
+ return _join_parts(parts)
+
+ def _render_table_body(self, block: TableBodyBlock) -> str:
+ """执行结构化表格到 sidecar、文本、占位的固定回退链。"""
+ content = block.content.strip()
+ if content and _HTML_TABLE_RE.search(content):
+ try:
+ return self.tables.render(content)
+ except LatexTableError as exc:
+ logger.warning("LaTeX HTML table fallback: {}", exc)
+ image = self._render_local_image(block)
+ if image:
+ return image
+ plain = _plain_html_text(content)
+ if plain:
+ return self._render_verbatim(plain)
+ return self._placeholder("table unavailable")
+ if content:
+ return self._render_verbatim(block.content)
+ if not _has_image_payload(block):
+ return self._placeholder("table unavailable") + r"\par"
+ return self._render_image_payload(block, alt_text="table")
+
+ def _render_chart_block(self, block: ChartBlock) -> str:
+ """保留 chart 图片,并继续输出可物化的结构化表格。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, ChartBodyBlock):
+ body_parts: list[str] = []
+ has_image_payload = bool(child.image_path or child.image_base64 or child.image_url)
+ local_image = self._render_local_image(child)
+ if local_image:
+ body_parts.append(local_image)
+ elif has_image_payload:
+ body_parts.append(self._render_image_payload(child, alt_text=block.sub_type or "chart"))
+ content = child.content.strip()
+ if content and _HTML_TABLE_RE.search(content):
+ try:
+ body_parts.append(self.tables.render(content))
+ except LatexTableError as exc:
+ logger.warning("LaTeX chart table fallback: {}", exc)
+ plain = _plain_html_text(content)
+ if plain:
+ body_parts.append(_paragraph(escape_latex_text(plain)))
+ elif content and not local_image:
+ body_parts.append(_paragraph(escape_latex_text(_plain_html_text(content))))
+ elif not has_image_payload and not content:
+ body_parts.append(self._placeholder("chart unavailable"))
+ parts.append(_join_parts(body_parts))
+ elif isinstance(child, ChartAnnotationBlock):
+ parts.append(self._render_annotation(child))
+ else:
+ raise TypeError(f"Unsupported chart child: {type(child).__name__}")
+ return _join_parts(parts)
+
+ def _render_code_block(self, block: CodeBlock) -> str:
+ """输出保留空白的代码或包含公式的算法正文及说明。"""
+ parts: list[str] = []
+ for child in block.content:
+ if isinstance(child, CodeBodyBlock):
+ if block.sub_type != BlockType.CODE:
+ raise TypeError("code_body requires code subtype")
+ parts.append(self._render_verbatim(child.content))
+ elif isinstance(child, AlgorithmBodyBlock):
+ if block.sub_type != RAW_ALGORITHM:
+ raise TypeError("algorithm_body requires algorithm subtype")
+ content = render_inline_spans(child.content, self.anchors)
+ parts.append("\n".join((r"\begin{quote}", rf"{{\small\ttfamily {content}\par}}", r"\end{quote}")))
+ elif isinstance(child, CodeAnnotationBlock):
+ parts.append(self._render_annotation(child))
+ else:
+ raise TypeError(f"Unsupported code child: {type(child).__name__}")
+ return _join_parts(parts)
+
+ def _render_annotation(
+ self,
+ block: ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock,
+ ) -> str:
+ """按 caption/footnote discriminator 输出弱化说明样式。"""
+ content = render_inline_spans(block.content, self.anchors)
+ if not content.strip():
+ return ""
+ if str(block.type).endswith("caption"):
+ return rf"{{\small\itshape {content}\par}}"
+ return rf"{{\footnotesize\color{{MinerUGray}} {content}\par}}"
+
+ def _render_image_payload(self, block: ImagePayloadBlock, *, alt_text: str) -> str:
+ """输出本地 sidecar;其它来源降级为链接或可见占位。"""
+ local = self._render_local_image(block)
+ if local:
+ return local
+ label = self._placeholder(f"image unavailable: {alt_text}")
+ remote_url = remote_block_image_url(block)
+ if remote_url:
+ return rf"\href{{{escape_latex_url(remote_url)}}}{{{label}}}\par"
+ return label + r"\par"
+
+ def _render_local_image(self, block: ImagePayloadBlock) -> str:
+ """若存在 XeLaTeX 支持的安全 sidecar,则生成有界 includegraphics。"""
+ path = resolve_block_image_path(block, self.asset_base_path)
+ if path is None:
+ return ""
+ return (
+ rf"\noindent\includegraphics[width=\linewidth,height=.8\textheight,keepaspectratio]"
+ rf"{{{tex_image_path(path)}}}\par"
+ )
+
+ def _placeholder(self, message: str) -> str:
+ """生成不暴露二进制载荷的稳定可见占位。"""
+ return rf"\MinerUPlaceholder{{{escape_latex_text(message, preserve_newlines=False)}}}"
+
+ def _render_verbatim(self, content: str) -> str:
+ """为每个预格式块选择正文无法提前闭合的唯一 fvextra 环境。"""
+ normalized = content.replace("\r\n", "\n").replace("\r", "\n")
+ while True:
+ self.verbatim_counter += 1
+ environment = f"MinerUVerbatim{self.verbatim_counter}"
+ if rf"\end{{{environment}}}" not in normalized:
+ break
+ definition = (
+ rf"\DefineVerbatimEnvironment{{{environment}}}{{Verbatim}}"
+ r"{breaklines=true,breakanywhere=true,fontsize=\small}"
+ )
+ return "\n".join((definition, rf"\begin{{{environment}}}", normalized, rf"\end{{{environment}}}"))
+
+
+def render_latex(
+ middle_json: MiddleJson,
+ *,
+ asset_base_path: str = "",
+ document_title: str | None = None,
+) -> str:
+ """把严格 MiddleJson 纯函数式渲染为 TeX Live XeLaTeX 完整源码。"""
+ if not isinstance(middle_json, MiddleJson):
+ raise TypeError("render_latex expects a MiddleJson instance")
+ if not isinstance(asset_base_path, str):
+ raise TypeError("asset_base_path must be a string")
+ if document_title is not None and not isinstance(document_title, str):
+ raise TypeError("document_title must be a string or None")
+ return _LatexRenderer(
+ middle_json,
+ asset_base_path=asset_base_path,
+ document_title=document_title,
+ ).render()
+
+
+def _resolve_document_title(middle_json: MiddleJson, explicit: str | None) -> str:
+ """按显式标题、首个文档标题和固定回退值解析 metadata title。"""
+ if explicit is not None and explicit.strip():
+ return explicit.strip()
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if isinstance(block, DocTitleBlock):
+ title = inline_plain_text(block.content).strip()
+ if title:
+ return title
+ return "MinerU Document"
+
+
+def _collect_anchor_targets(middle_json: MiddleJson) -> set[str]:
+ """收集真实可见的正文、标题和页面脚注 anchor。"""
+ targets: set[str] = set()
+ for page in middle_json.pages:
+ for block in page.blocks:
+ if not isinstance(block, (TextBlock, TitleBlockBase, PageFootnoteBlock)):
+ continue
+ anchor = (block.anchor or "").strip()
+ if anchor and inline_plain_text(block.content).strip():
+ targets.add(anchor)
+ return targets
+
+
+def _classify_list(items: list[ListItem], add_reference_bullets: bool) -> tuple[str, str]:
+ """根据直属 marker 选择 LaTeX 列表环境和内容策略。"""
+ if add_reference_bullets:
+ return "itemize", "reference"
+ if items and all(item.kind == "unordered" for item in items):
+ return "itemize", "unordered"
+ if items and all(item.kind == "ordered" for item in items):
+ styles = {item.ordered_style for item in items}
+ if len(styles) == 1:
+ return "enumerate", "ordered"
+ if items and all(item.kind == "none" for item in items):
+ return "itemize", "unmarked"
+ return "description", "explicit"
+
+
+def _list_item_content(
+ item: ListItem,
+ original: list[InlineSpan],
+ kind: str,
+ add_reference_bullets: bool,
+) -> tuple[list[InlineSpan], str | None]:
+ """决定列表项应剥离、保留还是显式显示源 marker。"""
+ if add_reference_bullets:
+ return (item.body, None) if item.kind == "unordered" else (original, None)
+ if kind == "unordered":
+ return item.body, None
+ if kind == "ordered":
+ return item.body, item.marker
+ if kind == "unmarked":
+ return item.body, None
+ return item.body, item.marker
+
+
+def _paragraph(content: str) -> str:
+ """把非空行内源码收束为一个普通 LaTeX 段落。"""
+ return f"{content}\\par" if content.strip() else ""
+
+
+def _wrap_display_formula(content: str) -> str:
+ """保留完整 AMS display 环境,其它裸公式统一放入 equation*。"""
+ match = _TOP_LEVEL_DISPLAY_ENV_RE.match(content)
+ if match is not None and content.rstrip().endswith(rf"\end{{{match.group('name')}}}"):
+ return content
+ return "\n".join((r"\begin{equation*}", content, r"\end{equation*}"))
+
+
+def _join_parts(parts: list[str]) -> str:
+ """按子块源顺序连接全部非空 LaTeX 片段。"""
+ return "\n\n".join(part for part in parts if part and part.strip())
+
+
+def _plain_html_text(content: str) -> str:
+ """从 HTML 或普通字符串提取可见文本供替代信息使用。"""
+ if not content:
+ return ""
+ return BeautifulSoup(content, "html.parser").get_text("\n", strip=True)
+
+
+def _has_image_payload(block: ImagePayloadBlock) -> bool:
+ """判断 block 是否声明任一种图片来源。"""
+ return bool(block.image_path or block.image_base64 or block.image_url)
+
+
+__all__ = ["render_latex"]
diff --git a/mineru/render/_internal/latex/table.py b/mineru/render/_internal/latex/table.py
new file mode 100644
index 00000000..4dd0deaf
--- /dev/null
+++ b/mineru/render/_internal/latex/table.py
@@ -0,0 +1,258 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""HTML table 到 TeX Live longtable/tabular 源码的安全物化。"""
+
+from __future__ import annotations
+
+from bs4 import NavigableString, Tag
+from pydantic import ValidationError
+
+from ....types import CodeInlineSpan, EquationInlineSpan, HyperlinkSpan, InlineSpan, InlineStyle, TextSpan, parse_inline_spans
+from ....utils.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
+from ..common.html_table import (
+ HtmlTableCell,
+ HtmlTableError,
+ HtmlTableGrid,
+ HtmlTableSource,
+ MAX_NESTED_TABLE_DEPTH,
+ parse_html_tables,
+)
+from .assets import resolve_html_image_path, tex_image_path
+from .inline import LatexAnchorRegistry, escape_latex_text, escape_latex_url, render_inline_spans
+
+_BLOCK_TAGS = {"address", "article", "blockquote", "div", "figcaption", "footer", "header", "li", "p", "section"}
+_SKIPPED_TAGS = {"script", "style", "template", "noscript"}
+
+
+class LatexTableError(HtmlTableError):
+ """表示 HTML table 无法安全物化为 LaTeX 表格。"""
+
+
+class LatexTableRenderer:
+ """持有图片路径和 anchor 上下文的递归 LaTeX 表格 renderer。"""
+
+ def __init__(self, *, asset_base_path: str, anchors: LatexAnchorRegistry) -> None:
+ """保存表格单元格渲染所需的文档级上下文。"""
+ self.asset_base_path = asset_base_path
+ self.anchors = anchors
+
+ def render(self, source: HtmlTableSource) -> str:
+ """把一个或多个顶层 HTML table 转换为可分页 LaTeX 表格。"""
+ return self._render_source(source, depth=1)
+
+ def _render_source(self, source: HtmlTableSource, *, depth: int) -> str:
+ """递归解析当前层级的 table,并执行深度上限校验。"""
+ if depth > MAX_NESTED_TABLE_DEPTH:
+ raise LatexTableError(f"Nested table depth exceeds {MAX_NESTED_TABLE_DEPTH}")
+ try:
+ grids = parse_html_tables(source)
+ except HtmlTableError as exc:
+ raise LatexTableError(str(exc)) from exc
+ return "\n\n".join(self._render_grid(grid, depth=depth) for grid in grids)
+
+ def _render_grid(self, grid: HtmlTableGrid, *, depth: int) -> str:
+ """把严格占位网格转换为 longtable 或嵌套 tabular。"""
+ environment = "longtable" if depth == 1 else "tabular"
+ column_spec = self._column_spec(grid.column_count)
+ occupied = {
+ (row, column): placement
+ for placement in grid.cells
+ for row in range(placement.row, placement.end_row + 1)
+ for column in range(placement.column, placement.end_column + 1)
+ }
+ lines = [rf"\begin{{{environment}}}{{{column_spec}}}", r"\hline"]
+ for row_index in range(grid.row_count):
+ segments: list[str] = []
+ column_index = 0
+ while column_index < grid.column_count:
+ placement = occupied[(row_index, column_index)]
+ if placement.column != column_index:
+ column_index += 1
+ continue
+ if placement.row == row_index:
+ segment = self._render_cell(
+ placement.tag,
+ is_header=placement.is_header,
+ rowspan=placement.rowspan,
+ colspan=placement.colspan,
+ column_count=grid.column_count,
+ depth=depth,
+ )
+ else:
+ segment = self._continued_rowspan_placeholder(placement.colspan)
+ segments.append(segment)
+ column_index += placement.colspan
+ lines.append(" & ".join(segments) + r" \\")
+ lines.extend(_row_rules(occupied, row_index=row_index, column_count=grid.column_count))
+ lines.append(rf"\end{{{environment}}}")
+ return "\n".join(lines)
+
+ def _render_cell(
+ self,
+ cell: Tag,
+ *,
+ is_header: bool,
+ rowspan: int,
+ colspan: int,
+ column_count: int,
+ depth: int,
+ ) -> str:
+ """渲染一个 origin cell,并组合 rowspan/colspan 声明。"""
+ parts: list[str] = []
+ spans = _html_cell_spans(cell)
+ if spans:
+ parts.append(render_inline_spans(spans, self.anchors))
+ for image in cell.find_all("img"):
+ if image.find_parent("table") is not cell.find_parent("table"):
+ continue
+ source = image.get("src", "")
+ if isinstance(source, list):
+ source = ""
+ alt = image.get("alt", "image")
+ if isinstance(alt, list):
+ alt = " ".join(str(item) for item in alt)
+ parts.append(self._render_image(str(source), str(alt)))
+ for nested in cell.find_all("table"):
+ if nested.find_parent(("td", "th")) is not cell:
+ continue
+ parts.append(self._render_source(nested, depth=depth + 1))
+ content = r"\par ".join(part for part in parts if part) or "~"
+ if is_header:
+ content = rf"\cellcolor{{MinerUTableHeader}}\textbf{{{content}}}"
+ width = _cell_width(colspan, column_count)
+ if rowspan > 1:
+ content = rf"\multirow{{{rowspan}}}{{*}}{{\parbox[t]{{{width}}}{{{content}}}}}"
+ if colspan > 1:
+ content = rf"\multicolumn{{{colspan}}}{{|p{{{width}}}|}}{{{content}}}"
+ return content
+
+ def _render_image(self, source: str, alt_text: str) -> str:
+ """渲染单元格图片;非本地 sidecar 退化为可见链接或占位。"""
+ path = resolve_html_image_path(source, self.asset_base_path)
+ if path is not None:
+ return rf"\includegraphics[width=.85\linewidth,height=.25\textheight,keepaspectratio]{{{tex_image_path(path)}}}"
+ label = rf"\textit{{{escape_latex_text(f'image unavailable: {alt_text}')}}}"
+ normalized = source.strip()
+ if normalized.startswith(("http://", "https://")):
+ return rf"\href{{{escape_latex_url(normalized)}}}{{{label}}}"
+ return label
+
+ @staticmethod
+ def _column_spec(column_count: int) -> str:
+ """按逻辑列数生成确定性的等宽段落列声明。"""
+ if column_count <= 0:
+ raise LatexTableError("Table must contain at least one column")
+ width = _cell_width(1, column_count)
+ column = rf">{{\raggedright\arraybackslash}}p{{{width}}}"
+ return "|" + "|".join(column for _ in range(column_count)) + "|"
+
+ @staticmethod
+ def _continued_rowspan_placeholder(colspan: int) -> str:
+ """为前序行延续下来的 rowspan 写入等列宽空占位。"""
+ return rf"\multicolumn{{{colspan}}}{{|l|}}{{}}" if colspan > 1 else ""
+
+
+def _cell_width(colspan: int, column_count: int) -> str:
+ """按表格总列数计算当前单元格占用的 linewidth 比例。"""
+ ratio = 0.94 * colspan / column_count
+ return f"{ratio:.6f}\\linewidth"
+
+
+def _row_rules(
+ occupied: dict[tuple[int, int], HtmlTableCell],
+ *,
+ row_index: int,
+ column_count: int,
+) -> list[str]:
+ """只在当前行结束的单元格列下画线,避免横线切穿 rowspan。"""
+ ending_columns = [column for column in range(column_count) if occupied[(row_index, column)].end_row == row_index]
+ if len(ending_columns) == column_count:
+ return [r"\hline"]
+ rules: list[str] = []
+ range_start: int | None = None
+ previous: int | None = None
+ for column in ending_columns:
+ if range_start is None:
+ range_start = column
+ elif previous is not None and column != previous + 1:
+ rules.append(rf"\cline{{{range_start + 1}-{previous + 1}}}")
+ range_start = column
+ previous = column
+ if range_start is not None and previous is not None:
+ rules.append(rf"\cline{{{range_start + 1}-{previous + 1}}}")
+ return rules
+
+
+def _html_cell_spans(cell: Tag) -> list[InlineSpan]:
+ """把单元格中非图片、非嵌套表内容转换为严格 InlineSpan。"""
+ spans: list[InlineSpan] = []
+ for child in cell.children:
+ spans.extend(_html_node_spans(child, styles=(), allow_links=True))
+ if not spans:
+ return []
+ try:
+ return parse_inline_spans(spans)
+ except (TypeError, ValidationError, ValueError) as exc:
+ raise LatexTableError("HTML table cell inline content is invalid") from exc
+
+
+def _html_node_spans(node: object, *, styles: tuple[InlineStyle, ...], allow_links: bool) -> list[InlineSpan]:
+ """递归解析表格单元格中的安全富文本标签。"""
+ if isinstance(node, NavigableString):
+ text = str(node)
+ return [TextSpan(type="text", content=text, styles=list(styles))] if text else []
+ if not isinstance(node, Tag):
+ return []
+ name = (node.name or "").lower()
+ if name in _SKIPPED_TAGS or name in {"img", "table"}:
+ return []
+ if name == "br":
+ return [TextSpan(type="text", content="\n", styles=list(styles))]
+ if name == "eq":
+ content = node.get_text()
+ return [EquationInlineSpan(type="equation_inline", content=content)] if content.strip() else []
+ if name == "code":
+ content = node.get_text()
+ return [CodeInlineSpan(type="code_inline", content=content)] if content else []
+ style_name: InlineStyle | None = {
+ "b": "bold",
+ "strong": "bold",
+ "i": "italic",
+ "em": "italic",
+ "u": "underline",
+ "s": "strikethrough",
+ "del": "strikethrough",
+ "sup": "superscript",
+ "sub": "subscript",
+ }.get(name)
+ child_styles = tuple(dict.fromkeys((*styles, style_name))) if style_name is not None else styles
+ if name == "a" and allow_links:
+ children = [
+ span
+ for child in node.children
+ for span in _html_node_spans(child, styles=child_styles, allow_links=False)
+ if not isinstance(span, HyperlinkSpan)
+ ]
+ target = sanitize_hyperlink_target(
+ node.get("href"),
+ allowed_schemes=OFFICE_EXTERNAL_HYPERLINK_SCHEMES,
+ allow_relative=True,
+ allow_fragment=True,
+ )
+ if target is not None and children:
+ try:
+ return [HyperlinkSpan(type="hyperlink", url=target, content=children)] # type: ignore[arg-type]
+ except ValidationError:
+ pass
+ return children
+ spans = [span for child in node.children for span in _html_node_spans(child, styles=child_styles, allow_links=allow_links)]
+ if name in _BLOCK_TAGS and spans and not _spans_end_with_newline(spans):
+ spans.append(TextSpan(type="text", content="\n"))
+ return spans
+
+
+def _spans_end_with_newline(spans: list[InlineSpan]) -> bool:
+ """判断当前 span 序列是否已经以普通文本换行结束。"""
+ return bool(spans and isinstance(spans[-1], TextSpan) and spans[-1].content.endswith("\n"))
+
+
+__all__ = ["LatexTableError", "LatexTableRenderer"]
diff --git a/mineru/render/_internal/pdf/table.py b/mineru/render/_internal/pdf/table.py
index 0aca5185..1a33b551 100644
--- a/mineru/render/_internal/pdf/table.py
+++ b/mineru/render/_internal/pdf/table.py
@@ -3,66 +3,32 @@
from __future__ import annotations
-from dataclasses import dataclass
-import re
-from typing import Protocol, TypeAlias
+from typing import Protocol
-from bs4 import BeautifulSoup, NavigableString, Tag
+from bs4 import NavigableString, Tag
from pydantic import ValidationError
from reportlab.platypus import Flowable, LongTable, Paragraph, Table, TableStyle
from ....types import CodeInlineSpan, EquationInlineSpan, HyperlinkSpan, InlineSpan, InlineStyle, TextSpan, parse_inline_spans
from ....utils.hyperlink import OFFICE_EXTERNAL_HYPERLINK_SCHEMES, sanitize_hyperlink_target
+from ..common.html_table import (
+ HtmlTableCell,
+ HtmlTableError,
+ HtmlTableGrid,
+ HtmlTableSource,
+ MAX_NESTED_TABLE_DEPTH,
+ parse_html_tables as _parse_common_html_tables,
+)
from .styles import BORDER_COLOR, SURFACE_COLOR, PdfStyleSet
-MAX_NESTED_TABLE_DEPTH = 4
-MAX_TABLE_ROWS = 500
-MAX_TABLE_COLUMNS = 100
-MAX_TABLE_SLOTS = 10_000
-_POSITIVE_INTEGER_RE = re.compile(r"[0-9]+")
_BLOCK_TAGS = {"address", "article", "blockquote", "div", "figcaption", "footer", "header", "li", "p", "section"}
_SKIPPED_TAGS = {"script", "style", "template", "noscript"}
-HtmlTableSource: TypeAlias = str | BeautifulSoup | Tag
-
-class PdfTableError(ValueError):
+class PdfTableError(HtmlTableError):
"""表示 HTML 表格结构或 PDF 表格几何无法安全物化。"""
-@dataclass(frozen=True, slots=True)
-class HtmlTableCell:
- """保存原始 HTML 单元格在逻辑占位网格中的位置。"""
-
- tag: Tag
- row: int
- column: int
- rowspan: int
- colspan: int
- is_header: bool
-
- @property
- def end_row(self) -> int:
- """返回单元格占用的末行下标。"""
- return self.row + self.rowspan - 1
-
- @property
- def end_column(self) -> int:
- """返回单元格占用的末列下标。"""
- return self.column + self.colspan - 1
-
-
-@dataclass(frozen=True, slots=True)
-class HtmlTableGrid:
- """保存经过重叠、边界、规模与矩形校验的 HTML 表格网格。"""
-
- tag: Tag
- row_count: int
- column_count: int
- cells: tuple[HtmlTableCell, ...]
- header_rows: tuple[int, ...]
-
-
class ParagraphBuilder(Protocol):
"""定义表格单元格创建富文本 Paragraph 的回调。"""
@@ -80,18 +46,11 @@ class HtmlImageBuilder(Protocol):
def parse_html_tables(source: HtmlTableSource) -> tuple[HtmlTableGrid, ...]:
- """解析 source 中相对当前上下文的一个或多个顶层 table。"""
- root = BeautifulSoup(source, "html.parser") if isinstance(source, str) else source
- if not isinstance(root, (BeautifulSoup, Tag)):
- raise PdfTableError("HTML table source must be a string or BeautifulSoup Tag")
- if isinstance(root, Tag) and root.name == "table":
- table_tags = (root,)
- else:
- parent_table = root.find_parent("table") if isinstance(root, Tag) else None
- table_tags = tuple(table for table in root.find_all("table") if table.find_parent("table") is parent_table)
- if not table_tags:
- raise PdfTableError("HTML does not contain a top-level table")
- return tuple(_parse_html_table(table) for table in table_tags)
+ """复用共用网格解析,并保持 PDF 私有异常类型不变。"""
+ try:
+ return _parse_common_html_tables(source)
+ except HtmlTableError as exc:
+ raise PdfTableError(str(exc)) from exc
def build_pdf_tables(
@@ -122,76 +81,6 @@ def build_pdf_tables(
)
-def _parse_html_table(table: Tag) -> HtmlTableGrid:
- """把单个 table 标签解析为严格矩形占位网格。"""
- if table.name != "table":
- raise PdfTableError("Expected a <table> tag")
- rows = tuple(row for row in table.find_all("tr") if row.find_parent("table") is table)
- if not rows or len(rows) > MAX_TABLE_ROWS:
- raise PdfTableError(f"Table row count must be between 1 and {MAX_TABLE_ROWS}")
- occupied: dict[tuple[int, int], HtmlTableCell] = {}
- cells: list[HtmlTableCell] = []
- for row_index, row in enumerate(rows):
- column_index = 0
- for source_cell in row.find_all(("td", "th"), recursive=False):
- while (row_index, column_index) in occupied:
- column_index += 1
- rowspan = _parse_span(source_cell, "rowspan")
- colspan = _parse_span(source_cell, "colspan")
- if row_index + rowspan > len(rows):
- raise PdfTableError(f"rowspan exceeds table bounds at row={row_index}, column={column_index}")
- if column_index + colspan > MAX_TABLE_COLUMNS:
- raise PdfTableError(f"Table column count exceeds {MAX_TABLE_COLUMNS}")
- coordinates = tuple(
- (target_row, target_column)
- for target_row in range(row_index, row_index + rowspan)
- for target_column in range(column_index, column_index + colspan)
- )
- overlap = next((coordinate for coordinate in coordinates if coordinate in occupied), None)
- if overlap is not None:
- raise PdfTableError(f"Cell span overlaps row={overlap[0]}, column={overlap[1]}")
- placement = HtmlTableCell(
- tag=source_cell,
- row=row_index,
- column=column_index,
- rowspan=rowspan,
- colspan=colspan,
- is_header=source_cell.name == "th",
- )
- cells.append(placement)
- occupied.update(dict.fromkeys(coordinates, placement))
- if len(occupied) > MAX_TABLE_SLOTS:
- raise PdfTableError(f"Table occupancy exceeds {MAX_TABLE_SLOTS} slots")
- column_index += colspan
- if not occupied:
- raise PdfTableError("Table must contain at least one cell")
- column_count = max(column for _, column in occupied) + 1
- missing = next(
- (
- (row_index, column_index)
- for row_index in range(len(rows))
- for column_index in range(column_count)
- if (row_index, column_index) not in occupied
- ),
- None,
- )
- if missing is not None:
- raise PdfTableError(f"Table occupancy is not rectangular at row={missing[0]}, column={missing[1]}")
- header_rows = tuple(
- row_index
- for row_index, row in enumerate(rows)
- if _row_belongs_to_thead(row, table)
- or all(occupied[(row_index, column_index)].is_header for column_index in range(column_count))
- )
- return HtmlTableGrid(
- tag=table,
- row_count=len(rows),
- column_count=column_count,
- cells=tuple(cells),
- header_rows=header_rows,
- )
-
-
def _build_pdf_table(
grid: HtmlTableGrid,
*,
@@ -366,30 +255,6 @@ def _spans_end_with_newline(spans: list[InlineSpan]) -> bool:
return bool(spans and isinstance(spans[-1], TextSpan) and spans[-1].content.endswith("\n"))
-def _parse_span(cell: Tag, attribute: str) -> int:
- """读取严格正整数 rowspan/colspan,缺失时返回一。"""
- raw_value = cell.get(attribute, "1")
- if isinstance(raw_value, list):
- raise PdfTableError(f"Invalid {attribute}: {raw_value!r}")
- value = str(raw_value).strip()
- if _POSITIVE_INTEGER_RE.fullmatch(value) is None:
- raise PdfTableError(f"Invalid {attribute}: {raw_value!r}")
- span = int(value)
- if span < 1 or span > MAX_TABLE_SLOTS:
- raise PdfTableError(f"Invalid {attribute}: {raw_value!r}")
- return span
-
-
-def _row_belongs_to_thead(row: Tag, table: Tag) -> bool:
- """判断 tr 是否位于当前 table 的 thead 内。"""
- parent = row.parent
- while isinstance(parent, Tag) and parent is not table:
- if parent.name == "thead":
- return True
- parent = parent.parent
- return False
-
-
def _column_widths(total_width: float, column_count: int) -> list[float]:
"""把可用宽度确定性地均分到全部逻辑列。"""
if column_count <= 0:
diff --git a/mineru/render/api.py b/mineru/render/api.py
index 7bbb2fd3..356026ca 100644
--- a/mineru/render/api.py
+++ b/mineru/render/api.py
@@ -13,6 +13,7 @@ from .contracts import (
DocxRenderOptions,
EpubRenderOptions,
HtmlRenderOptions,
+ LatexRenderOptions,
MarkdownRenderOptions,
PdfRenderOptions,
RenderFormat,
@@ -25,6 +26,7 @@ from .content_list_v2 import render_content_list_v2
from .docx import render_docx
from .epub import render_epub
from .html import render_html
+from .latex import render_latex
from .markdown import render_markdown
from .pdf import render_pdf
from .structured_content import render_structured_content
@@ -52,6 +54,17 @@ def render(
...
+@overload
+def render(
+ middle_json: MiddleJson,
+ output_format: Literal[RenderFormat.LATEX],
+ *,
+ options: LatexRenderOptions | None = None,
+) -> str:
+ """声明 LaTeX 目标对应的字符串返回类型。"""
+ ...
+
+
@overload
def render(
middle_json: MiddleJson,
@@ -153,6 +166,16 @@ def render(
document_title=resolved_options.document_title,
)
+ if output_format is RenderFormat.LATEX:
+ resolved_options = options if options is not None else LatexRenderOptions()
+ if not isinstance(resolved_options, LatexRenderOptions):
+ raise TypeError("LATEX output requires LatexRenderOptions")
+ return render_latex(
+ middle_json,
+ asset_base_path=resolved_options.asset_base_path,
+ document_title=resolved_options.document_title,
+ )
+
if output_format is RenderFormat.DOCX:
resolved_options = options if options is not None else DocxRenderOptions()
if not isinstance(resolved_options, DocxRenderOptions):
diff --git a/mineru/render/contracts.py b/mineru/render/contracts.py
index 386c2bfd..59d3c7ce 100644
--- a/mineru/render/contracts.py
+++ b/mineru/render/contracts.py
@@ -17,6 +17,7 @@ class RenderFormat(str, Enum):
MARKDOWN = "markdown"
HTML = "html"
+ LATEX = "latex"
DOCX = "docx"
EPUB = "epub"
STRUCTURED_CONTENT = "structured_content"
@@ -83,6 +84,21 @@ class HtmlRenderOptions:
raise TypeError("document_title must be a string or None")
+@dataclass(frozen=True, slots=True)
+class LatexRenderOptions:
+ """LaTeX renderer 的统一入口选项。"""
+
+ asset_base_path: str = ""
+ document_title: str | None = None
+
+ def __post_init__(self) -> None:
+ """在构造时校验 LaTeX 素材路径前缀与文档标题。"""
+ if not isinstance(self.asset_base_path, str):
+ raise TypeError("asset_base_path must be a string")
+ if self.document_title is not None and not isinstance(self.document_title, str):
+ raise TypeError("document_title must be a string or None")
+
+
@dataclass(frozen=True, slots=True)
class DocxRenderOptions:
"""DOCX renderer 的统一入口选项。"""
@@ -183,6 +199,7 @@ class ContentListV2RenderOptions:
RenderOptions: TypeAlias = (
MarkdownRenderOptions
| HtmlRenderOptions
+ | LatexRenderOptions
| DocxRenderOptions
| EpubRenderOptions
| PdfRenderOptions
@@ -201,6 +218,7 @@ __all__ = [
"EpubRenderOptions",
"HtmlRenderOptions",
"ImageRenderer",
+ "LatexRenderOptions",
"MarkdownRenderOptions",
"PdfRenderOptions",
"RenderFormat",
diff --git a/mineru/render/latex.py b/mineru/render/latex.py
new file mode 100644
index 00000000..5489c79c
--- /dev/null
+++ b/mineru/render/latex.py
@@ -0,0 +1,25 @@
+# Copyright (c) Opendatalab. All rights reserved.
+"""严格 MiddleJson 到 TeX Live LaTeX 源码的轻量公共门面。"""
+
+from __future__ import annotations
+
+from ..types import MiddleJson
+
+
+def render_latex(
+ middle_json: MiddleJson,
+ *,
+ asset_base_path: str = "",
+ document_title: str | None = None,
+) -> str:
+ """惰性加载 LaTeX 实现并返回完整 UTF-8 文档源码。"""
+ from ._internal.latex.renderer import render_latex as _render_latex
+
+ return _render_latex(
+ middle_json,
+ asset_base_path=asset_base_path,
+ document_title=document_title,
+ )
+
+
+__all__ = ["render_latex"]
diff --git a/tests/unittest/test_backend_architecture.py b/tests/unittest/test_backend_architecture.py
index 19a2de5e..0b5ac169 100644
--- a/tests/unittest/test_backend_architecture.py
+++ b/tests/unittest/test_backend_architecture.py
@@ -43,10 +43,13 @@ _CHINESE_DOCSTRING_PATHS = (
_PROJECT_ROOT / "mineru/model/ocr/results.py",
_PROJECT_ROOT / "mineru/render/markdown.py",
_PROJECT_ROOT / "mineru/render/html.py",
+ _PROJECT_ROOT / "mineru/render/latex.py",
_PROJECT_ROOT / "mineru/render/docx.py",
_PROJECT_ROOT / "mineru/render/epub.py",
_PROJECT_ROOT / "mineru/render/pdf.py",
_PROJECT_ROOT / "mineru/render/structured_content.py",
+ _PROJECT_ROOT / "mineru/render/_internal/common/html_table.py",
+ _PROJECT_ROOT / "mineru/render/_internal/latex",
_PROJECT_ROOT / "mineru/utils/image.py",
)
_REMOVED_INTERNAL_MODULES = (
@@ -217,6 +220,29 @@ def test_layer_dependencies_are_one_way() -> None:
assert not offenders
+def test_latex_and_render_common_keep_private_dependencies_one_way() -> None:
+ """守卫 LaTeX 不跨入其它格式私有实现,common 也不反向依赖格式包。"""
+ format_names = ("content_list", "docx", "epub", "html", "markdown", "pdf", "structured_content")
+ latex_offenders = {
+ str(path.relative_to(_PROJECT_ROOT)): sorted(
+ module
+ for module in _resolved_imports(path)
+ if module.startswith(tuple(f"mineru.render._internal.{name}" for name in format_names))
+ )
+ for path in (_PROJECT_ROOT / "mineru/render/_internal/latex").rglob("*.py")
+ }
+ common_offenders = {
+ str(path.relative_to(_PROJECT_ROOT)): sorted(
+ module
+ for module in _resolved_imports(path)
+ if module.startswith(tuple(f"mineru.render._internal.{name}" for name in (*format_names, "latex")))
+ )
+ for path in (_PROJECT_ROOT / "mineru/render/_internal/common").rglob("*.py")
+ }
+ assert not {path: imports for path, imports in latex_offenders.items() if imports}
+ assert not {path: imports for path, imports in common_offenders.items() if imports}
+
+
def test_flash_office_does_not_depend_on_pdf_implementation() -> None:
"""守卫 Office 格式只复用中立能力,不反向依赖 Flash PDF 实现。"""
offenders = {
diff --git a/tests/unittest/test_latex_render.py b/tests/unittest/test_latex_render.py
new file mode 100644
index 00000000..f8a6ad75
--- /dev/null
+++ b/tests/unittest/test_latex_render.py
@@ -0,0 +1,436 @@
+from __future__ import annotations
+
+from _span_test_utils import inline as _inline
+
+from copy import deepcopy
+from pathlib import Path
+import os
+import shutil
+import subprocess
+
+from PIL import Image
+import pytest
+
+from mineru.render import render_latex
+from mineru.types import (
+ AlgorithmBodyBlock,
+ ChartAnnotationBlock,
+ ChartBlock,
+ ChartBodyBlock,
+ CodeAnnotationBlock,
+ CodeBlock,
+ CodeBodyBlock,
+ DocTitleBlock,
+ EquationBlock,
+ ImageAnnotationBlock,
+ ImageBlock,
+ ImageBodyBlock,
+ IndexBlock,
+ ListBlock,
+ MiddleJson,
+ PageAuxTextBlock,
+ PageBlock,
+ PageFootnoteBlock,
+ PageInfo,
+ ParagraphTitleBlock,
+ TableAnnotationBlock,
+ TableBlock,
+ TableBodyBlock,
+ TextBlock,
+)
+
+_TEX_LIVE_FILES = (
+ "ctexart.cls",
+ "geometry.sty",
+ "amsmath.sty",
+ "amssymb.sty",
+ "graphicx.sty",
+ "longtable.sty",
+ "array.sty",
+ "booktabs.sty",
+ "multirow.sty",
+ "enumitem.sty",
+ "xcolor.sty",
+ "ulem.sty",
+ "xeCJKfntef.sty",
+ "fvextra.sty",
+ "hyperref.sty",
+ "FandolSong-Regular.otf",
+ "FandolSong-Bold.otf",
+ "FandolHei-Regular.otf",
+ "FandolHei-Bold.otf",
+ "FandolKai-Regular.otf",
+ "FandolFang-Regular.otf",
+)
+
+
+def _middle(*pages: PageInfo) -> MiddleJson:
+ """构造无需源坐标布局的严格测试 MiddleJson。"""
+ return MiddleJson(
+ pages=list(pages),
+ is_full_document=True,
+ file_suffix="docx",
+ effort="flash",
+ parse_mode="txt",
+ mineru_version="test",
+ )
+
+
+def _page(page_idx: int, *blocks: PageBlock) -> PageInfo:
+ """按调用方顺序构造一页测试内容。"""
+ return PageInfo(page_idx=page_idx, blocks=list(blocks))
+
+
+def test_latex_document_uses_tex_live_preamble_default_planner_and_escaping() -> None:
+ """验证固定 TeX Live 模板、续段合并、辅助块过滤、标题和普通文本转义。"""
+ middle = _middle(
+ _page(
+ 0,
+ PageAuxTextBlock(type="header", index=0, content=_inline("HEADER")),
+ DocTitleBlock(type="doc_title", index=1, level=1, content=_inline("中文标题")),
+ TextBlock(type="text", index=2, content=_inline("first\ninter-"), anchor="body-target"),
+ ),
+ _page(
+ 3,
+ TextBlock(type="text", index=0, content=_inline("national 50% & x_y {#} \\path"), continues_prev=True),
+ PageFootnoteBlock(type="page_footnote", index=1, anchor="note", content=_inline("页面脚注")),
+ ),
+ )
+ original = deepcopy(middle)
+
+ rendered = render_latex(middle, document_title="Title & Metadata")
+
+ assert rendered.startswith("% !TeX program = xelatex\n")
+ assert r"\documentclass[UTF8,fontset=fandol,11pt]{ctexart}" in rendered
+ assert "unicode-math" not in rendered and r"\setCJKmainfont" not in rendered
+ assert r"\hypersetup{pdftitle={Title \& Metadata}}" in rendered
+ assert r"first\MinerULineBreak{}international 50\% \& x\_y \{\#\} \textbackslash{}path\par" in rendered
+ assert "HEADER" not in rendered
+ assert "页面脚注" in rendered and r"\footnotesize\color{MinerUGray}" in rendered
+ assert r"\write18" not in rendered and "minted" not in rendered and "shellesc" not in rendered.casefold()
+ assert rendered.endswith("\\end{document}\n")
+ assert rendered == render_latex(middle, document_title="Title & Metadata")
+ assert middle == original
+
+
+def test_latex_renders_inline_styles_formulas_links_and_safe_anchors() -> None:
+ """验证全部 InlineSpan 样式、原始公式、内外部链接及哈希 anchor。"""
+ title = ParagraphTitleBlock(
+ type="paragraph_title",
+ index=0,
+ level=2,
+ anchor="章节 1/#",
+ content=_inline("章节一"),
+ )
+ text = TextBlock(
+ type="text",
+ index=1,
+ content=[
+ {"type": "text", "content": "Styled", "styles": ["bold", "italic", "underline"]},
+ {"type": "text", "content": " dot", "styles": ["emphasis"]},
+ {"type": "text", "content": " strike", "styles": ["strikethrough"]},
+ {"type": "text", "content": "2", "styles": ["superscript"]},
+ {"type": "text", "content": "i", "styles": ["subscript"]},
+ {"type": "code_inline", "content": "a_b% c"},
+ {"type": "equation_inline", "content": r"x_1^2"},
+ {"type": "hyperlink", "url": "#章节 1/#", "content": _inline("jump")},
+ {"type": "hyperlink", "url": "https://example.com/a_b?q=1&x=2", "content": _inline("external")},
+ ],
+ )
+ equation = EquationBlock(type="equation", index=2, content=r"\frac{1}{1-x^2}\tag{7}")
+ aligned = EquationBlock(type="equation", index=3, content=r"\begin{align}a&=b\\c&=d\end{align}")
+
+ rendered = render_latex(_middle(_page(0, title, text, equation, aligned)))
+
+ assert r"\textbf{\textit{\uline{Styled}}}" in rendered
+ assert r"\CJKunderdot[format=\normalcolor]{ dot}" in rendered
+ assert r"\sout{ strike}" in rendered
+ assert r"\textsuperscript{2}" in rendered and r"\textsubscript{i}" in rendered
+ assert r"\texttt{a\_b\%\ \ c}" in rendered and r"\(x_1^2\)" in rendered
+ assert r"\hypertarget{mineru-" in rendered and r"\hyperlink{mineru-" in rendered
+ assert r"\href{https://example.com/a\_b?q=1\&x=2}{external}" in rendered
+ assert "\\begin{equation*}\n\\frac{1}{1-x^2}\\tag{7}\n\\end{equation*}" in rendered
+ assert rendered.count(r"\begin{align}") == 1 and r"\begin{equation*}\begin{align}" not in rendered
+
+
+def test_latex_renders_native_lists_and_linked_index() -> None:
+ """验证有序、显式、嵌套列表和目录链接保持来源语义。"""
+ target = ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="target", content=_inline("Target"))
+ ordered = ListBlock(
+ type="list",
+ index=1,
+ sub_type="text",
+ content=[
+ TextBlock(type="text", content=_inline("2. Second")),
+ TextBlock(type="text", content=_inline("4. Fourth")),
+ ListBlock(type="list", sub_type="text", content=[TextBlock(type="text", content=_inline("- Nested"))]),
+ ],
+ )
+ explicit = ListBlock(
+ type="list",
+ index=2,
+ sub_type="text",
+ content=[
+ TextBlock(type="text", content=_inline("[A] Alpha")),
+ TextBlock(type="text", content=_inline("plain")),
+ ],
+ )
+ index = IndexBlock(
+ type="index",
+ index=3,
+ content=[ParagraphTitleBlock(type="paragraph_title", level=2, anchor="target", content=_inline("Target\t12"))],
+ )
+
+ rendered = render_latex(_middle(_page(0, target, ordered, explicit, index)))
+
+ assert r"\begin{enumerate}[leftmargin=*,nosep]" in rendered
+ assert r"\item[{2.}] Second" in rendered and r"\item[{4.}] Fourth" in rendered
+ assert r"\item Nested" in rendered
+ assert r"\begin{description}[style=nextline,leftmargin=3em,nosep]" in rendered
+ assert r"\item[{[A]}] Alpha" in rendered and r"\item[{}] plain" in rendered
+ assert "Target 12" not in rendered
+ assert r"\hyperlink{mineru-" in rendered and "{Target}" in rendered
+
+
+def test_latex_renders_visual_blocks_complex_tables_and_code_in_source_order() -> None:
+ """验证图片、复杂表格、图表、代码和视觉说明按子块来源顺序输出。"""
+ image = ImageBlock(
+ type="image",
+ index=0,
+ content=[
+ ImageAnnotationBlock(type="image_caption", content=_inline("Before image")),
+ ImageBodyBlock(type="image_body", index=0, content="Alt", image_path="images/a b.png"),
+ ImageAnnotationBlock(type="image_footnote", content=_inline("After image")),
+ ],
+ )
+ table_html = (
+ "<table><thead><tr><th rowspan='2'>H</th><th colspan='2'><b>Group</b></th></tr></thead>"
+ "<tbody><tr><td><eq>x^2</eq></td><td>before<table><tr><td>Nested</td></tr></table></td></tr></tbody></table>"
+ )
+ table = TableBlock(
+ type="table",
+ index=1,
+ content=[
+ TableBodyBlock(type="table_body", index=1, content=table_html),
+ TableAnnotationBlock(type="table_caption", content=_inline("Table caption")),
+ ],
+ )
+ chart = ChartBlock(
+ type="chart",
+ index=2,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=2,
+ content="<table><tr><td>Data</td></tr></table>",
+ image_path="images/chart.png",
+ ),
+ ChartAnnotationBlock(type="chart_footnote", content=_inline("Chart note")),
+ ],
+ )
+ code = CodeBlock(
+ type="code",
+ index=3,
+ sub_type="code",
+ guess_lang="python",
+ content=[
+ CodeBodyBlock(type="code_body", index=3, content="print('x_y%')\n\\end{MinerUVerbatim1}"),
+ CodeAnnotationBlock(type="code_caption", content=_inline("Code caption")),
+ ],
+ )
+ algorithm = CodeBlock(
+ type="code",
+ index=4,
+ sub_type="algorithm",
+ content=[
+ AlgorithmBodyBlock(
+ type="algorithm_body",
+ index=4,
+ content=[{"type": "text", "content": "Step "}, {"type": "equation_inline", "content": "x^2"}],
+ )
+ ],
+ )
+
+ rendered = render_latex(
+ _middle(_page(0, image, table, chart, code, algorithm)),
+ asset_base_path="document assets",
+ )
+
+ assert rendered.index("Before image") < rendered.index(r"\detokenize{document assets/images/a b.png}")
+ assert rendered.index(r"\detokenize{document assets/images/a b.png}") < rendered.index("After image")
+ assert r"\begin{longtable}" in rendered and r"\multirow{2}" in rendered and r"\multicolumn{2}" in rendered
+ assert r"\cline{2-3}" in rendered
+ assert r"\begin{tabular}" in rendered and "Nested" in rendered and r"\(x^2\)" in rendered
+ assert r"\detokenize{document assets/images/chart.png}" in rendered and "Data" in rendered
+ assert "Table caption" in rendered and "Chart note" in rendered
+ assert r"\DefineVerbatimEnvironment{MinerUVerbatim2}" in rendered
+ assert "print('x_y%')" in rendered and "Code caption" in rendered
+ assert r"{\small\ttfamily Step \(x^2\)\par}" in rendered
+
+
+def test_latex_image_and_table_fallbacks_remain_visible_without_io() -> None:
+ """验证远程、data URI、不支持格式和畸形表格均退化为可见内容。"""
+ remote = ImageBlock(
+ type="image",
+ index=0,
+ content=[
+ ImageBodyBlock(
+ type="image_body",
+ index=0,
+ content="Remote diagram",
+ image_url="https://example.com/a.png",
+ )
+ ],
+ )
+ unsupported = ImageBlock(
+ type="image",
+ index=1,
+ content=[ImageBodyBlock(type="image_body", index=1, content="SVG diagram", image_path="images/a.svg")],
+ )
+ malformed = TableBlock(
+ type="table",
+ index=2,
+ content=[TableBodyBlock(type="table_body", index=2, content="<table><tr><td rowspan='2'>A</td></tr></table>")],
+ )
+ spatial = TableBlock(
+ type="table",
+ index=3,
+ content=[TableBodyBlock(type="table_body", index=3, content="A B\n1 2")],
+ )
+ inline_chart = ChartBlock(
+ type="chart",
+ index=4,
+ content=[
+ ChartBodyBlock(
+ type="chart_body",
+ index=4,
+ content="",
+ image_base64="data:image/png;base64,AAAA",
+ )
+ ],
+ )
+ empty_formula = EquationBlock(type="equation", index=5, content="")
+ empty_table = TableBlock(
+ type="table",
+ index=6,
+ content=[TableBodyBlock(type="table_body", index=6, content="")],
+ )
+
+ rendered = render_latex(
+ _middle(_page(0, remote, unsupported, malformed, spatial, inline_chart, empty_formula, empty_table))
+ )
+
+ assert r"\href{https://example.com/a.png}" in rendered and "Remote diagram" in rendered
+ assert "SVG diagram" in rendered and "images/a.svg" not in rendered
+ assert "A" in rendered and rendered.count("table unavailable") == 1
+ assert "A B\n1 2" in rendered
+ assert rendered.count(r"\DefineVerbatimEnvironment") == 2
+ assert "image unavailable: chart" in rendered
+ assert "formula unavailable" in rendered and "table unavailable" in rendered
+
+
+def test_latex_normalizes_windows_asset_prefix_without_system_font_or_io_dependencies() -> None:
+ """验证 Windows 路径前缀使用 XeLaTeX 跨平台可读的正斜杠。"""
+ image = ImageBlock(
+ type="image",
+ index=0,
+ content=[ImageBodyBlock(type="image_body", index=0, content="image", image_path="images/a.png")],
+ )
+
+ rendered = render_latex(_middle(_page(0, image)), asset_base_path=r"C:\documents\output")
+
+ assert r"\detokenize{C:/documents/output/images/a.png}" in rendered
+
+
+def test_latex_public_entry_rejects_invalid_contract_values() -> None:
+ """验证专用入口拒绝旧字典、错误选项类型和控制字符路径。"""
+ middle = _middle(_page(0))
+
+ with pytest.raises(TypeError, match="MiddleJson"):
+ render_latex(middle.to_dict()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="asset_base_path"):
+ render_latex(middle, asset_base_path=1) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="document_title"):
+ render_latex(middle, document_title=1) # type: ignore[arg-type]
+ with pytest.raises(ValueError, match="control"):
+ render_latex(middle, asset_base_path="images\nunsafe")
+
+
+def test_latex_compiles_with_default_tex_live_full(tmp_path: Path) -> None:
+ """在可用或强制要求的 TeX Live full 环境中真实编译代表文档。"""
+ required = os.environ.get("MINERU_REQUIRE_TEXLIVE") == "1"
+ latexmk = shutil.which("latexmk")
+ xelatex = shutil.which("xelatex")
+ kpsewhich = shutil.which("kpsewhich")
+ missing_tools = [
+ name for name, path in (("latexmk", latexmk), ("xelatex", xelatex), ("kpsewhich", kpsewhich)) if path is None
+ ]
+ if missing_tools:
+ message = f"TeX Live tools are unavailable: {', '.join(missing_tools)}"
+ pytest.fail(message) if required else pytest.skip(message)
+ assert latexmk is not None and xelatex is not None and kpsewhich is not None
+
+ missing_files = [
+ filename
+ for filename in _TEX_LIVE_FILES
+ if subprocess.run([kpsewhich, filename], capture_output=True, text=True, check=False).returncode != 0
+ ]
+ if missing_files:
+ message = f"TeX Live scheme-full files are unavailable: {', '.join(missing_files)}"
+ pytest.fail(message) if required else pytest.skip(message)
+
+ image_dir = tmp_path / "images"
+ image_dir.mkdir()
+ Image.new("RGB", (16, 8), (40, 80, 120)).save(image_dir / "sample image.png")
+ middle = _middle(
+ _page(
+ 0,
+ DocTitleBlock(type="doc_title", index=0, level=1, content=_inline("中文 TeX Live")),
+ TextBlock(
+ type="text",
+ index=1,
+ content=[
+ {"type": "text", "content": "正文 "},
+ {"type": "equation_inline", "content": r"x_1^2"},
+ ],
+ ),
+ EquationBlock(type="equation", index=2, content=r"\frac{a}{b}\tag{1}"),
+ ImageBlock(
+ type="image",
+ index=3,
+ content=[ImageBodyBlock(type="image_body", index=3, content="sample", image_path="images/sample image.png")],
+ ),
+ TableBlock(
+ type="table",
+ index=4,
+ content=[
+ TableBodyBlock(
+ type="table_body",
+ index=4,
+ content="<table><tr><th colspan='2'>Header</th></tr><tr><td>A</td><td><eq>x</eq></td></tr></table>",
+ )
+ ],
+ ),
+ CodeBlock(
+ type="code",
+ index=5,
+ sub_type="code",
+ guess_lang="python",
+ content=[CodeBodyBlock(type="code_body", index=5, content="print('TeX Live')")],
+ ),
+ )
+ )
+ tex_path = tmp_path / "main.tex"
+ tex_path.write_text(render_latex(middle), encoding="utf-8")
+
+ result = subprocess.run(
+ [latexmk, "-xelatex", "-interaction=nonstopmode", "-halt-on-error", tex_path.name],
+ cwd=tmp_path,
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=120,
+ )
+
+ assert result.returncode == 0, f"{result.stdout}\n{result.stderr}"
+ assert (tmp_path / "main.pdf").read_bytes().startswith(b"%PDF-")
diff --git a/tests/unittest/test_render_api.py b/tests/unittest/test_render_api.py
index 2867d837..81d8db29 100644
--- a/tests/unittest/test_render_api.py
+++ b/tests/unittest/test_render_api.py
@@ -18,6 +18,7 @@ from mineru.render import (
DocxRenderOptions,
EpubRenderOptions,
HtmlRenderOptions,
+ LatexRenderOptions,
MarkdownRenderOptions,
PdfRenderOptions,
RenderFormat,
@@ -59,6 +60,7 @@ def test_unified_render_dispatches_all_native_output_types_without_mutation() ->
markdown = render(middle, RenderFormat.MARKDOWN)
html = render(middle, RenderFormat.HTML)
+ latex = render(middle, RenderFormat.LATEX)
docx = render(middle, RenderFormat.DOCX)
epub = render(
middle,
@@ -72,6 +74,7 @@ def test_unified_render_dispatches_all_native_output_types_without_mutation() ->
assert markdown == "hello"
assert isinstance(html, str) and "<html" in html and "hello" in html
+ assert latex.startswith("% !TeX program = xelatex") and "hello\\par" in latex
assert isinstance(docx, bytes) and docx.startswith(b"PK\x03\x04")
assert isinstance(epub, bytes) and epub.startswith(b"PK\x03\x04")
assert isinstance(pdf, bytes) and pdf.startswith(b"%PDF-")
@@ -146,6 +149,14 @@ def test_unified_render_forwards_format_specific_options() -> None:
document_title="Unified Render",
),
)
+ latex_document = render(
+ image_middle,
+ RenderFormat.LATEX,
+ options=LatexRenderOptions(
+ asset_base_path="document assets",
+ document_title="Unified Render",
+ ),
+ )
pdf = render(
middle,
RenderFormat.PDF,
@@ -165,6 +176,13 @@ def test_unified_render_forwards_format_specific_options() -> None:
assert "https://cdn.example/doc/images/a%20b.png" in image_markdown
assert "<title>Unified Render</title>" in html_document
assert 'src="https://cdn.example/doc/images/a%20b.png"' in html_document
+ assert r"\hypersetup{pdftitle={Unified Render}}" in latex_document
+ assert r"\detokenize{document assets/images/a b.png}" in latex_document
+ assert latex_document == render_module.render_latex(
+ image_middle,
+ asset_base_path="document assets",
+ document_title="Unified Render",
+ )
assert pdf == render_module.render_pdf(middle, document_title="Unified Render")
assert [page["blocks"][0]["content"] for page in original_tree["pages"]] == ["first-", "second"]
assert original_tree["pages"][1]["blocks"][0]["continues_prev"] is True
@@ -227,6 +245,8 @@ def test_unified_render_rejects_legacy_format_and_mismatched_options() -> None:
render(middle, RenderFormat.MARKDOWN, options=HtmlRenderOptions()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="StructuredContentRenderOptions"):
render(middle, RenderFormat.STRUCTURED_CONTENT, options=DocxRenderOptions()) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="LatexRenderOptions"):
+ render(middle, RenderFormat.LATEX, options=HtmlRenderOptions()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="EpubRenderOptions"):
render(middle, RenderFormat.EPUB, options=DocxRenderOptions()) # type: ignore[arg-type]
with pytest.raises(TypeError, match="PdfRenderOptions"):
@@ -242,6 +262,7 @@ def test_public_options_validate_fields() -> None:
assert [item.value for item in RenderFormat] == [
"markdown",
"html",
+ "latex",
"docx",
"epub",
"structured_content",
@@ -257,6 +278,7 @@ def test_public_options_validate_fields() -> None:
for options_type in (
DocxRenderOptions,
EpubRenderOptions,
+ LatexRenderOptions,
PdfRenderOptions,
StructuredContentRenderOptions,
ContentListRenderOptions,
@@ -291,6 +313,10 @@ def test_public_options_validate_fields() -> None:
PdfRenderOptions(asset_resolver="images") # type: ignore[arg-type]
with pytest.raises(TypeError, match="document_title"):
PdfRenderOptions(document_title=1) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="asset_base_path"):
+ LatexRenderOptions(asset_base_path=1) # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="document_title"):
+ LatexRenderOptions(document_title=1) # type: ignore[arg-type]
def test_public_render_exposes_all_three_structured_output_names() -> None:
@@ -300,8 +326,11 @@ def test_public_render_exposes_all_three_structured_output_names() -> None:
assert callable(render_module.render_content_list_v2)
assert callable(render_module.render_epub)
assert callable(render_module.render_pdf)
+ assert callable(render_module.render_latex)
assert not hasattr(render_module, "MarkdownRenderMode")
assert ContentListRenderOptions is render_module.ContentListRenderOptions
assert ContentListV2RenderOptions is render_module.ContentListV2RenderOptions
+ assert LatexRenderOptions is render_module.LatexRenderOptions
+ assert "LATEX" in RenderFormat.__members__
assert "CONTENT_LIST" in RenderFormat.__members__
assert "CONTENT_LIST_V2" in RenderFormat.__members__