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: add HTML rendering support and enhance list item parsing utilities
myhlolie56f199b65f1
diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex fa703641..f0f84f09 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -1,8 +1,8 @@# Rendering Contract-状态: Markdown / Content List / DOCX v1+状态: Markdown / Content List / DOCX / HTML v1读者: render 开发者、backend 开发者、SDK 开发者-范围: 严格 MiddleJson 到 Markdown、Content List 和 DOCX 的消费契约+范围: 严格 MiddleJson 到 Markdown、Content List、DOCX 和 HTML 的消费契约## 公共入口@@ -63,6 +63,91 @@ HTML table 使用 occupancy grid 生成原生 Word table,支持 `rowspan/colsp`MarkdownRenderMode` 是 `RenderMode` 的既有公共别名。DOCX 是语义化可编辑输出,不承诺复刻源 PDF/Office 的字体、分栏、断行和页数;CLI、doclib 与 v1 API 不在本契约范围。+## MPE/Crossnote 风格 HTML++```python+from mineru.render import RenderMode, render_html++html_document = render_html(+ middle_json,+ mode=RenderMode.DEFAULT,+ asset_base_url="",+ standalone=True,+ document_title=None,+)+```++`render_html()` 只接受严格 `MiddleJson`,返回字符串且不写文件、不读取图片 sidecar、+不访问网络。`standalone=True` 输出完整 HTML5 文档;`False` 输出单根+`article.crossnote.markdown-preview.mineru-document` fragment,不包含 CSS、脚本或+`head`。显式标题缺失时,HTML title 使用首个非空 `doc_title` 的纯文本,再回退为+`MinerU Document`。++HTML 与 DOCX/Markdown 共用 `RenderMode` 和续段/续表 planner。DEFAULT 输出无页面 wrapper+的连续阅读内容;FULL 为每个 `PageInfo` 输出一个 `section.mineru-page`,包括空页,并在+相邻页面之间输出 `hr.mineru-page-break`。每个顶层 block wrapper 保留来源 page/type/index+元数据。行内内容直接消费共享 AST:普通文本始终 HTML escape,未知标签保持可见;公式只+在 `mineru-math` carrier 内使用 `\(...\)` 或 `\[...\]`,不扫描普通正文中的美元符号。++完整文档按原字节内联 Crossnote 0.9.31 的 `github-light.css`、`github.css` Prism theme 和+`style-template.css`,并在 style 开头保留完整 NCSA notice;许可证与来源说明也随资源打包。+MinerU 自有补充 CSS 只覆盖新增结构。+有公式时按需加载固定 MathJax 4.1.2 `tex-chtml.js`,启用 `ui/safe`、禁用 `require`,并+关闭菜单和 enrichment。有可高亮代码时按需加载固定 Prism 1.30.0 core 和 Autoloader,+语言组件根固定到同版本 jsDelivr。入口脚本携带 SRI;动态 MathJax 扩展、字体和 Prism+语言组件没有逐文件 SRI。renderer 不注入 CSP,HTTP 宿主需要自行允许相应 jsDelivr+script/font/style,并评估 CDN 供应链策略。++为保持与 MPE 导出 DOM/CSS 选择器完全兼容,standalone 保留其非标准+`body[for="html-export"]` 属性;字节不变的上游 `style-template.css` 也包含 Nu validator+会报告的既有 CSS `calc()` 表达式。这两项是已知兼容偏差,MinerU 自有 HTML 结构和补充+CSS 仍按 HTML5/CSS 语义生成。++fragment 调用方必须自行加载同版本 CSS、MathJax 和 Prism;三份 Crossnote CSS 未重新+scope,会影响宿主页全局样式。MathJax 必须在初始化前复用 standalone 的 delimiter、+`ignoreHtmlClass/processHtmlClass`、`ui/safe`、禁用 `require` 及 safeOptions 配置。动态插入后调用+`MathJax.typesetPromise([root])` 与 `Prism.highlightAllUnder(root)`;替换已有公式前先调用+`MathJax.typesetClear([root])`。fragment 内的相对图片以宿主页 URL 为基准,不能通过+fragment 自带 `base` 修正。++fragment 宿主的 MathJax 配置至少必须包含以下安全边界,并在加载 `tex-chtml.js` 前赋值:++```javascript+window.MathJax = {+ loader: {load: ["ui/safe"]},+ tex: {+ inlineMath: [["\\(", "\\)"]],+ displayMath: [["\\[", "\\]"]],+ processEnvironments: false,+ processRefs: false,+ packages: {"[-]": ["require"]},+ },+ options: {+ ignoreHtmlClass: "mineru-document",+ processHtmlClass: "mineru-math",+ enableMenu: false,+ enableEnrichment: false,+ safeOptions: {+ allow: {URLs: "none", classes: "none", cssIDs: "none", styles: "none"},+ },+ },+};+```++standalone 还会通过 `startup.ready` 把 menu/enrichment 选项重新施加到 live MathDocument;+fragment 宿主如需完全相同行为,也必须复用该 hook,而不能只复制上面的静态字段。++HTML table/chart/image body 只在识别为 markup 时经过 `nh3` allowlist。活动标签、事件属性、+来源 style/class/id/data 属性和危险 URL 会被删除;链接只允许相对地址、fragment、+`http/https/mailto/tel`,图片只允许安全 sidecar、根相对路径、HTTP(S) 与签名匹配的 raster+data URI。安全 `<eq>` 在清洗后转换为公式 carrier。清洗后不可用的 table 优先回退整体+图片,否则以转义后的 `pre` 可见保留;普通 `<local_dir>` 等尖括号文本不会进入 sanitizer。+Chart 的 pipe table 只实现 GFM 列结构与反斜杠/pipe 解码,cell 内容继续消费 MiddleJson+行内标签;`**bold**`、反引号和 Markdown link 等任意 GFM inline 语法不会二次解析。++v1 只增加严格 `mineru.render` 公共面,不迁移旧 parser、CLI、API 或 doclib,也不提供+Markdown 字符串转 HTML、离线单文件、主题切换、侧边 TOC 或用户自定义 head/CSS/script。+## 树形 Markdown Content List严格 render 层还提供不合并、不丢块的树形内容输出:diff --git a/mineru/render/__init__.py b/mineru/render/__init__.pyindex 2371fe99..6a88641f 100644--- a/mineru/render/__init__.py+++ b/mineru/render/__init__.py@@ -2,6 +2,7 @@from .content_list import render_content_listfrom .docx import DocxRenderError, render_docx+from .html import render_htmlfrom .markdown import MarkdownRenderMode, render_markdownfrom .utils.logical_blocks import RenderMode@@ -11,5 +12,6 @@ __all__ = ["RenderMode","render_content_list","render_docx",+ "render_html","render_markdown",]diff --git a/mineru/render/docx.py b/mineru/render/docx.pyindex 6ebed5f3..06b93ee1 100644--- a/mineru/render/docx.py+++ b/mineru/render/docx.py@@ -34,7 +34,6 @@ from mineru.render.utils.docx_inline import (append_inline_nodes,append_internal_link,append_joined_inline_contents,- plain_inline_text,sanitize_xml_text,)from mineru.render.utils.docx_math import DocxFormulaError, latex_to_omml, split_formula_tag@@ -51,6 +50,8 @@ from mineru.render.utils.docx_styles import ()from mineru.render.utils.docx_table import DocxTableError, NestedTableWriter, materialize_docx_tablesfrom mineru.render.utils.inline import InlineEquation, InlineLink, InlineNode, InlineStyled, InlineText, parse_inline_content+from mineru.render.utils.index import strip_index_page_tail+from mineru.render.utils.list_items import parse_list_item_markerfrom mineru.render.utils.logical_blocks import PlannedBlock, RenderMode, build_render_planfrom mineru.types import (PAGE_AUXILIARY_BLOCK_TYPES,@@ -83,10 +84,6 @@ from mineru.types import (TitleBlockBase,)-_INDEX_ROMAN_RE = re.compile(r"[ivxlcdm]+", re.IGNORECASE)-_LIST_MARKER_RE = re.compile(- r"^(?P<leading>\s*)(?P<marker>[-*+]|\[[^\]\n]+\]|\(?\d+[.)]|[A-Za-z][.)]|[IVXLCDMivxlcdm]+[.)])(?P<space>\s+)"-)_HTML_TABLE_RE = re.compile(r"<table\b", re.IGNORECASE)_ANNOTATION_CAPTION_TYPES = {BlockType.IMAGE_CAPTION,@@ -300,8 +297,8 @@ class _DocxRenderer:self._render_list(child, context, depth=depth + 1)continueparagraph = self.document.add_paragraph(style=BODY_STYLE)- marker = _LIST_MARKER_RE.match(child.content)- if marker is None:+ item = parse_list_item_marker(child.content)+ if item.marker is None:paragraph.paragraph_format.left_indent = Mm(depth * 6)else:paragraph.paragraph_format.left_indent = Mm((depth + 1) * 6)@@ -320,7 +317,7 @@ class _DocxRenderer:if isinstance(child, IndexBlock):self._render_index(child, context, depth=depth + 1)continue- content = _strip_index_page_tail(child.content)+ content = strip_index_page_tail(child.content)nodes = parse_inline_content(content)if not nodes:continue@@ -770,25 +767,6 @@ def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:if isinstance(block, TitleBlockBase) and block.anchor:yield block.anchor--def _strip_index_page_tail(content: str) -> str:- """删除目录末尾可信页码,并把其余 tab 转换为普通空格。"""- if "\t" not in content:- return content- head, tail = content.rsplit("\t", 1)- tail_text = plain_inline_text(tail).strip()- if _looks_like_index_page_token(tail_text):- content = head- return content.replace("\t", " ")---def _looks_like_index_page_token(content: str) -> bool:- """判断目录 tab 后缀是否为数字、罗马数字或单字母页码。"""- if not content or len(content) > 12:- return False- return bool(content.isdigit() or _INDEX_ROMAN_RE.fullmatch(content) or re.fullmatch(r"[A-Za-z]", content))--def _plain_html_text(content: str) -> str:"""把图片或图表 body 内容收敛为适合 alt description 的纯文本。"""if not content.strip():diff --git a/mineru/render/html.py b/mineru/render/html.pynew file mode 100644index 00000000..3fa3b260--- /dev/null+++ b/mineru/render/html.py@@ -0,0 +1,830 @@+# Copyright (c) Opendatalab. All rights reserved.+"""严格 MiddleJson 到 MPE/Crossnote 风格 HTML 的公共渲染实现。"""++from __future__ import annotations++import html+import re+from functools import lru_cache+from importlib import resources+from urllib.parse import quote++from bs4 import BeautifulSoup+from loguru import logger++from mineru.render.utils.html_inline import (+ HtmlInlineResult,+ render_inline_content_html,+ render_inline_nodes_html,+ render_joined_inline_contents_html,+ render_math_html,+)+from mineru.render.utils.html_sanitizer import (+ is_supported_html_markup,+ sanitize_html_fragment,+ sanitize_image_source,+)+from mineru.render.utils.html_table import looks_like_gfm_table, render_gfm_table_html+from mineru.render.utils.index import strip_index_page_tail+from mineru.render.utils.inline import inline_plain_text, parse_inline_content+from mineru.render.utils.list_items import ListItem, parse_list_item_marker, reference_list_needs_bullets+from mineru.render.utils.logical_blocks import PlannedBlock, RenderMode, build_render_plan+from mineru.types import (+ PAGE_AUXILIARY_BLOCK_TYPES,+ RAW_ALGORITHM,+ BlockType,+ ChartAnnotationBlock,+ ChartBlock,+ ChartBodyBlock,+ CodeAnnotationBlock,+ CodeBlock,+ CodeBodyBlock,+ DocTitleBlock,+ EquationBlock,+ ImageAnnotationBlock,+ ImageBlock,+ ImageBodyBlock,+ IndexBlock,+ ListBlock,+ MiddleJson,+ PageAuxTextBlock,+ ParagraphTitleBlock,+ RefTextBlock,+ TableAnnotationBlock,+ TableBlock,+ TableBodyBlock,+ TextBlock,+ TitleBlockBase,+)++_STYLE_RESOURCE_PATHS = (+ ("crossnote", "github.css"),+ ("crossnote", "github-light.css"),+ ("crossnote", "style-template.css"),+ ("mineru.css",),+)+_MATHJAX_URL = "https://cdn.jsdelivr.net/npm/[email protected]/tex-chtml.js"+_MATHJAX_INTEGRITY = "sha384-zAhQQhdaMeHsMProNntGGg6nOUVcfuF9F22C3d1qJ9NZAVzCplXk1X85D2O5iufn"+_PRISM_CORE_URL = "https://cdn.jsdelivr.net/npm/[email protected]/components/prism-core.min.js"+_PRISM_CORE_INTEGRITY = "sha384-zLRFO4dwowZvh8kzutOb5AWhH7f39HeJp+N7PtHF1SQtTBnifRx0AtmvTYs3F4YV"+_PRISM_AUTOLOADER_URL = "https://cdn.jsdelivr.net/npm/[email protected]/plugins/autoloader/prism-autoloader.min.js"+_PRISM_AUTOLOADER_INTEGRITY = "sha384-Uq05+JLko69eOiPr39ta9bh7kld5PKZoU+fF7g0EXTAriEollhZ+DrN8Q/Oi8J2Q"+_PRISM_LANGUAGES_PATH = "https://cdn.jsdelivr.net/npm/[email protected]/components/"+_SAFE_PRISM_LANGUAGE_RE = re.compile(r"[a-z0-9][a-z0-9-]{0,31}")+_BLOCKED_PRISM_LANGUAGE_NAMES = {"constructor", "prototype"}+_PRISM_LANGUAGE_ALIASES = {+ "c#": "csharp",+ "c++": "cpp",+ "html": "markup",+ "js": "javascript",+ "py": "python",+ "sh": "bash",+ "shell": "bash",+ "none": "",+ "text": "",+ "txt": "",+ "ts": "typescript",+ "xml": "markup",+ "yml": "yaml",+}+++class _HtmlRenderer:+ """维护一次 HTML 渲染所需的 anchor、公式与代码资源状态。"""++ def __init__(+ self,+ middle_json: MiddleJson,+ *,+ mode: RenderMode,+ asset_base_url: str,+ standalone: bool,+ document_title: str | None,+ ) -> None:+ """保存严格输入和调用选项,并预收集真实正文标题 anchor。"""+ self.middle_json = middle_json+ self.mode = mode+ self.asset_base_url = asset_base_url+ self.standalone = standalone+ self.document_title = document_title+ self.anchor_targets = _collect_title_anchor_ids(middle_json)+ self.emitted_anchors: set[str] = set()+ self.has_math = False+ self.has_prism = False++ def render(self) -> str:+ """生成 fragment article,并按需包装完整 HTML 文档。"""+ planned_pages = build_render_plan(self.middle_json, self.mode)+ if self.mode is RenderMode.FULL:+ body = self._render_full_pages(planned_pages)+ else:+ body = self._render_default_pages(planned_pages)+ article = (+ f'<article class="crossnote markdown-preview mineru-document '+ f'mineru-document--{self.mode.value}">\n{body}\n</article>'+ )+ if not self.standalone:+ return article+ # 最终依赖以真实 DOM 为准,避免回退分支或普通文本中的 class 字样误触发。+ article_soup = BeautifulSoup(article, "html.parser")+ self.has_math = article_soup.select_one(".mineru-math") is not None+ self.has_prism = any(+ any(str(class_name).startswith("language-") for class_name in code.get("class", []))+ for code in article_soup.find_all("code")+ if code.get_text()+ )+ return self._render_standalone(article)++ def _render_default_pages(self, planned_pages: list[list[PlannedBlock]]) -> str:+ """把 DEFAULT 计划展平为无页面边界的连续阅读内容。"""+ rendered: list[str] = []+ for page in planned_pages:+ for planned in page:+ block = self._render_planned_block(planned)+ if block:+ rendered.append(block)+ return "\n".join(rendered)++ def _render_full_pages(self, planned_pages: list[list[PlannedBlock]]) -> str:+ """为 FULL 计划保留所有页面 section 和相邻页面分隔。"""+ sections: list[str] = []+ for page in planned_pages:+ page_idx = page[0].page_idx if page else None+ if page_idx is None:+ page_position = len(sections)+ page_idx = self.middle_json.pages[page_position].page_idx+ blocks = [rendered for planned in page if (rendered := self._render_planned_block(planned))]+ rendered_blocks = "\n".join(blocks)+ sections.append(f'<section class="mineru-page" data-page-idx="{page_idx}">\n{rendered_blocks}\n</section>')+ return '\n<hr class="mineru-page-break" aria-hidden="true">\n'.join(sections)++ def _render_planned_block(self, planned: PlannedBlock) -> str:+ """过滤计划块、分派类型 visitor,并添加稳定来源元数据。"""+ if planned.removed:+ return ""+ block = planned.block+ if self.mode is RenderMode.DEFAULT and block.type in PAGE_AUXILIARY_BLOCK_TYPES:+ return ""+ content = self._render_block_content(planned)+ if not content or not content.strip():+ return ""+ attrs = [+ 'class="mineru-block"',+ f'data-page-idx="{planned.page_idx}"',+ f'data-block-type="{html.escape(str(block.type), quote=True)}"',+ ]+ if block.index is not None:+ attrs.append(f'data-block-index="{block.index}"')+ return f"<div {' '.join(attrs)}>\n{content}\n</div>"++ def _render_block_content(self, planned: PlannedBlock) -> str:+ """按严格 PageBlock 具体类型返回对应语义 HTML。"""+ block = planned.block+ if isinstance(block, TextBlock):+ rendered = render_joined_inline_contents_html(planned.text_contents or [block.content])+ self._observe_inline(rendered)+ return f'<p class="mineru-text">{rendered.html}</p>' if rendered.html else ""+ if isinstance(block, RefTextBlock):+ rendered = render_joined_inline_contents_html(planned.text_contents or [block.content])+ self._observe_inline(rendered)+ return f'<p class="mineru-ref-text">{rendered.html}</p>' if rendered.html else ""+ if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):+ return self._render_title(block)+ if isinstance(block, PageAuxTextBlock):+ rendered = render_inline_content_html(block.content)+ self._observe_inline(rendered)+ class_name = html.escape(str(block.type).replace("_", "-"), quote=True)+ return f'<div class="mineru-page-aux mineru-page-aux--{class_name}">{rendered.html}</div>' if rendered.html else ""+ 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 _render_title(self, block: DocTitleBlock | ParagraphTitleBlock) -> str:+ """渲染标题,并保证正文 anchor 只在首次出现时生成 id。"""+ rendered = render_inline_content_html(block.content)+ self._observe_inline(rendered)+ if not rendered.html:+ return ""+ level = min(max(block.level, 1), 6)+ attrs = [f'class="mineru-heading mineru-heading--{level}"', f'data-heading-level="{block.level}"']+ anchor = _anchor_key(block.anchor)+ if anchor:+ if anchor not in self.emitted_anchors:+ anchor_id = self.anchor_targets.get(anchor)+ if anchor_id:+ attrs.append(f'id="{html.escape(anchor_id, quote=True)}"')+ self.emitted_anchors.add(anchor)+ else:+ logger.warning("Duplicate HTML title anchor omitted: {!r}", anchor)+ return f"<h{level} {' '.join(attrs)}>{rendered.html}</h{level}>"++ def _render_equation(self, block: EquationBlock) -> str:+ """优先输出行间公式,空 LaTeX 时回退到安全图片来源。"""+ if block.content.strip():+ rendered = render_math_html(block.content, display=True)+ self._observe_inline(rendered)+ return rendered.html+ source = self._safe_block_image_source(block)+ return self._render_image(source, alt="formula", class_name="mineru-equation-image") if source else ""++ 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 child.content.strip()+ ]+ add_reference_bullets = reference_list_needs_bullets(block)+ container_tag, list_type, class_name = _classify_list(parsed_leaves, add_reference_bullets)+ items: list[dict[str, object]] = []+ expected_value: int | None = None++ for child in block.content:+ if isinstance(child, ListBlock):+ nested = self._render_list(child)+ if not nested:+ continue+ if not items:+ items.append({"content": "", "attrs": ' class="mineru-list-item--orphan"', "nested": []})+ nested_items = items[-1]["nested"]+ assert isinstance(nested_items, list)+ nested_items.append(nested)+ continue++ parsed = parse_list_item_marker(child.content)+ item_content, marker = _list_item_content(+ parsed,+ add_reference_bullets,+ explicit_markers=class_name == "mineru-list--explicit",+ )+ rendered = render_inline_content_html(item_content)+ self._observe_inline(rendered)+ if not rendered.html and not marker:+ items.append({"content": "", "attrs": ' class="mineru-list-item--markerless"', "nested": []})+ continue++ attrs: list[str] = []+ if class_name == "mineru-list--explicit":+ attrs.append('class="mineru-list-item--explicit"')+ if container_tag == "ol" and parsed.kind == "ordered" and parsed.value is not None:+ if expected_value is None:+ expected_value = parsed.value+ if parsed.value != expected_value:+ attrs.append(f'value="{parsed.value}"')+ expected_value = parsed.value + 1+ marker_html = (+ f'<span class="mineru-list-marker">{html.escape(_replace_html_controls(marker), quote=False)}</span>'+ if marker+ else ""+ )+ if class_name == "mineru-list--explicit" and not marker_html:+ marker_html = '<span class="mineru-list-marker"></span>'+ items.append(+ {+ "content": f'{marker_html}<span class="mineru-list-content">{rendered.html}</span>',+ "attrs": f" {' '.join(attrs)}" if attrs else "",+ "nested": [],+ }+ )++ rendered_items: list[str] = []+ for item in items:+ nested = item["nested"]+ assert isinstance(nested, list)+ item_content = str(item["content"])+ if not item_content and not nested:+ continue+ rendered_items.append(f"<li{item['attrs']}>{item_content}{''.join(str(value) for value in nested)}</li>")+ if not rendered_items:+ return ""++ container_attrs = [f'class="mineru-list {class_name}"']+ if list_type:+ container_attrs.append(f'type="{list_type}"')+ if container_tag == "ol" and parsed_leaves and parsed_leaves[0].value not in (None, 1):+ container_attrs.append(f'start="{parsed_leaves[0].value}"')+ return f"<{container_tag} {' '.join(container_attrs)}>{''.join(rendered_items)}</{container_tag}>"++ def _render_index(self, block: IndexBlock) -> str:+ """递归渲染目录,并仅链接到真实正文标题 anchor。"""+ items: list[dict[str, object]] = []+ for child in block.content:+ if isinstance(child, IndexBlock):+ nested = self._render_index_list(child)+ if not nested:+ continue+ if not items:+ items.append({"content": "", "orphan": True, "nested": []})+ nested_items = items[-1]["nested"]+ assert isinstance(nested_items, list)+ nested_items.append(nested)+ continue+ rendered = self._render_index_leaf(child)+ items.append({"content": rendered, "orphan": False, "nested": []})+ inner = _serialize_index_items(items)+ return f'<nav class="mineru-index" aria-label="Table of contents"><ul>{inner}</ul></nav>' if inner else ""++ def _render_index_list(self, block: IndexBlock) -> str:+ """渲染一个嵌套 IndexBlock 为可挂接到父项的 ul。"""+ items: list[dict[str, object]] = []+ for child in block.content:+ if isinstance(child, IndexBlock):+ nested = self._render_index_list(child)+ if nested:+ if not items:+ items.append({"content": "", "orphan": True, "nested": []})+ nested_items = items[-1]["nested"]+ assert isinstance(nested_items, list)+ nested_items.append(nested)+ continue+ rendered = self._render_index_leaf(child)+ items.append({"content": rendered, "orphan": False, "nested": []})+ inner = _serialize_index_items(items)+ return f"<ul>{inner}</ul>" if inner else ""++ def _render_index_leaf(self, block: TextBlock | TitleBlockBase) -> str:+ """渲染目录叶子,并在 anchor 命中正文标题时生成内部链接。"""+ content = strip_index_page_tail(block.content)+ rendered = render_inline_content_html(content)+ self._observe_inline(rendered)+ if not rendered.html:+ return ""+ anchor = _anchor_key(block.anchor) if isinstance(block, TitleBlockBase) else ""+ if anchor and (anchor_id := self.anchor_targets.get(anchor)):+ href = quote(anchor_id, safe="-._~")+ return f'<a href="#{href}">{rendered.html}</a>'+ return rendered.html++ def _render_image_block(self, block: ImageBlock) -> str:+ """按原始子块顺序渲染图片主体及重复说明。"""+ parts: list[str] = []+ for child in block.content:+ if isinstance(child, ImageBodyBlock):+ body = self._render_image_body(block, child)+ elif isinstance(child, ImageAnnotationBlock):+ body = self._render_annotation(child)+ else:+ raise TypeError(f"Unsupported image child: {type(child).__name__}")+ if body:+ parts.append(body)+ return f'<figure class="mineru-figure mineru-figure--image">{"".join(parts)}</figure>' if parts else ""++ def _render_image_body(self, parent: ImageBlock, block: ImageBodyBlock) -> str:+ """渲染图片,并把并存的识别内容放入原生 details。"""+ source = self._safe_block_image_source(block)+ content = self._render_embedded_content(block.content)+ alt = _plain_content_text(block.content) or parent.sub_type or "image"+ parts = [self._render_image(source, alt=alt, class_name="mineru-image")] if source else []+ if content.html:+ if source:+ parts.append(self._render_details(content.html, parent.sub_type or "image content"))+ else:+ parts.append(content.html)+ return "".join(parts)++ def _render_table_block(self, block: TableBlock) -> str:+ """按原始子块顺序渲染表格主体、标题与脚注。"""+ parts: list[str] = []+ for child in block.content:+ if isinstance(child, TableBodyBlock):+ body = self._render_table_body(child)+ elif isinstance(child, TableAnnotationBlock):+ body = self._render_annotation(child)+ else:+ raise TypeError(f"Unsupported table child: {type(child).__name__}")+ if body:+ parts.append(body)+ return f'<figure class="mineru-figure mineru-figure--table">{"".join(parts)}</figure>' if parts else ""++ def _render_table_body(self, block: TableBodyBlock) -> str:+ """优先保留安全 HTML table,空间文本和整体图片依次回退。"""+ normalized_content = _replace_html_controls(block.content)+ content = normalized_content.strip()+ if content:+ source_soup = BeautifulSoup(content, "html.parser")+ if source_soup.find("table") is not None:+ rendered = self._render_embedded_content(content)+ if rendered.html and _contains_usable_table(rendered.html):+ return rendered.html+ source = self._safe_block_image_source(block)+ if source:+ return self._render_image(source, alt="table", class_name="mineru-table-image")+ return _render_raw_fallback(content)+ return f'<pre class="mineru-table-text">{html.escape(normalized_content, quote=False)}</pre>'+ source = self._safe_block_image_source(block)+ return self._render_image(source, alt="table", class_name="mineru-table-image") if source else ""++ def _render_chart_block(self, block: ChartBlock) -> str:+ """按原始子块顺序渲染 chart 图片、结构内容及说明。"""+ parts: list[str] = []+ for child in block.content:+ if isinstance(child, ChartBodyBlock):+ body = self._render_chart_body(block, child)+ elif isinstance(child, ChartAnnotationBlock):+ body = self._render_annotation(child)+ else:+ raise TypeError(f"Unsupported chart child: {type(child).__name__}")+ if body:+ parts.append(body)+ return f'<figure class="mineru-figure mineru-figure--chart">{"".join(parts)}</figure>' if parts else ""++ def _render_chart_body(self, parent: ChartBlock, block: ChartBodyBlock) -> str:+ """渲染 chart 图片,并将并存结构内容放入 details。"""+ source = self._safe_block_image_source(block)+ content = self._render_chart_content(block.content)+ parts = [self._render_image(source, alt=parent.sub_type or "chart", class_name="mineru-chart-image")] if source else []+ if content.html:+ if source:+ parts.append(self._render_details(content.html, parent.sub_type or "chart content"))+ else:+ parts.append(content.html)+ return "".join(parts)++ def _render_chart_content(self, content: str) -> HtmlInlineResult:+ """按 HTML、严格 GFM 表格、普通行内内容的顺序渲染 chart content。"""+ normalized = content.strip()+ if not normalized:+ return HtmlInlineResult("")+ if is_supported_html_markup(normalized):+ return self._render_embedded_content(normalized)+ if looks_like_gfm_table(normalized):+ rendered = render_gfm_table_html(normalized)+ if rendered is None:+ return HtmlInlineResult(_render_raw_fallback(content))+ self._observe_inline(rendered)+ return rendered+ rendered = render_inline_content_html(content)+ self._observe_inline(rendered)+ return rendered++ def _render_code_block(self, block: CodeBlock) -> str:+ """按原始子块顺序渲染代码或算法及其说明。"""+ parts: list[str] = []+ for child in block.content:+ if isinstance(child, CodeBodyBlock):+ body = self._render_code_body(block, child)+ elif isinstance(child, CodeAnnotationBlock):+ body = self._render_annotation(child)+ else:+ raise TypeError(f"Unsupported code child: {type(child).__name__}")+ if body:+ parts.append(body)+ return f'<figure class="mineru-figure mineru-figure--code">{"".join(parts)}</figure>' if parts else ""++ def _render_code_body(self, parent: CodeBlock, block: CodeBodyBlock) -> str:+ """代码使用 Prism class,算法使用共享 inline AST 保留空白。"""+ if parent.sub_type == BlockType.CODE:+ escaped = html.escape(_replace_html_controls(block.content), quote=False)+ if not block.content:+ return '<pre class="mineru-code"><code></code></pre>'+ language = _normalize_prism_language(parent.guess_lang)+ class_attr = f' class="language-{language}"' if language else ""+ pre_class = f"mineru-code language-{language}" if language else "mineru-code"+ self.has_prism = bool(language) or self.has_prism+ return f'<pre class="{pre_class}"><code{class_attr}>{escaped}</code></pre>'+ if parent.sub_type == RAW_ALGORITHM:+ rendered = render_inline_nodes_html(+ parse_inline_content(block.content),+ separate_adjacent_math=True,+ preserve_newlines=True,+ )+ self._observe_inline(rendered)+ return f'<div class="mineru-algorithm">{rendered.html}</div>' if rendered.html else ""+ raise ValueError(f"Unsupported code subtype: {parent.sub_type}")++ def _render_annotation(+ self,+ block: ImageAnnotationBlock | TableAnnotationBlock | ChartAnnotationBlock | CodeAnnotationBlock,+ ) -> str:+ """把视觉说明渲染为保持原类型的独立段落。"""+ rendered = render_inline_content_html(block.content)+ self._observe_inline(rendered)+ if not rendered.html:+ return ""+ is_caption = str(block.type).endswith("caption")+ role_class = "mineru-caption" if is_caption else "mineru-footnote"+ type_class = html.escape(str(block.type).replace("_", "-"), quote=True)+ return f'<p class="{role_class} {role_class}--{type_class}">{rendered.html}</p>'++ def _render_embedded_content(self, content: str) -> HtmlInlineResult:+ """安全处理 body 富 HTML;普通内容走共享 inline AST。"""+ normalized = content.strip()+ if not normalized:+ return HtmlInlineResult("")+ if not is_supported_html_markup(normalized):+ rendered = render_inline_content_html(content)+ self._observe_inline(rendered)+ return rendered+ sanitized = sanitize_html_fragment(normalized, asset_base_url=self.asset_base_url)+ rendered = self._replace_safe_equations(sanitized)+ self._observe_inline(rendered)+ return rendered++ def _replace_safe_equations(self, markup: str) -> HtmlInlineResult:+ """把 sanitizer 保留的 eq 标签替换为可信 MathJax carrier。"""+ if not markup:+ return HtmlInlineResult("")+ soup = BeautifulSoup(markup, "html.parser")+ has_math = False+ for equation in list(soup.find_all("eq")):+ rendered = render_math_html(equation.get_text(), display=False)+ if not rendered.html:+ equation.decompose()+ continue+ replacement = BeautifulSoup(rendered.html, "html.parser")+ equation.replace_with(*list(replacement.contents))+ has_math = True+ return HtmlInlineResult(str(soup), has_math)++ def _safe_block_image_source(self, block: EquationBlock | ImageBodyBlock | TableBodyBlock | ChartBodyBlock) -> str | None:+ """解析 block 图片来源,并应用 HTML renderer 的 URL 安全策略。"""+ if block.image_path:+ return sanitize_image_source(block.image_path, asset_base_url=self.asset_base_url)+ if block.image_base64:+ return sanitize_image_source(block.image_base64)+ return None++ def _render_image(self, source: str, *, alt: str, class_name: str) -> str:+ """构造属性已转义的安全 img 元素。"""+ return (+ f'<img class="{class_name}" src="{html.escape(source, quote=True)}" '+ f'alt="{html.escape(_replace_html_controls(alt), quote=True)}">'+ )++ def _render_details(self, content: str, summary: str) -> str:+ """构造浏览器原生折叠详情,不引入额外脚本。"""+ return (+ '<details class="mineru-details">'+ f"<summary>{html.escape(_replace_html_controls(summary), quote=False)}</summary>{content}</details>"+ )++ def _observe_inline(self, rendered: HtmlInlineResult) -> None:+ """累计当前文档是否需要加载 MathJax。"""+ self.has_math = rendered.has_math or self.has_math++ def _render_standalone(self, article: str) -> str:+ """用固定 CSS 和按需 CDN 资源包装完整 HTML 文档。"""+ title = html.escape(+ _replace_html_controls(_resolve_document_title(self.middle_json, self.document_title)),+ quote=False,+ )+ styles = _load_html_styles()+ dependencies = []+ if self.has_math:+ dependencies.append(_mathjax_head())+ if self.has_prism:+ dependencies.append(_prism_head())+ dependency_html = "\n".join(dependencies)+ return (+ "<!doctype html>\n"+ '<html lang="und">\n'+ "<head>\n"+ '<meta charset="utf-8">\n'+ '<meta name="viewport" content="width=device-width, initial-scale=1.0">\n'+ f"<title>{title}</title>\n"+ f"<style>\n{styles}\n</style>\n"+ f"{dependency_html}\n"+ "</head>\n"+ '<body for="html-export">\n'+ f"{article}\n"+ "</body>\n"+ "</html>"+ )+++def render_html(+ middle_json: MiddleJson,+ *,+ mode: RenderMode = RenderMode.DEFAULT,+ asset_base_url: str = "",+ standalone: bool = True,+ document_title: str | None = None,+) -> str:+ """把严格 MiddleJson 无副作用地渲染为 HTML 文档或单根 fragment。"""+ if not isinstance(middle_json, MiddleJson):+ raise TypeError("render_html expects a MiddleJson instance")+ if not isinstance(mode, RenderMode):+ raise TypeError("mode must be a RenderMode value")+ if not isinstance(asset_base_url, str):+ raise TypeError("asset_base_url must be a string")+ if not isinstance(standalone, bool):+ raise TypeError("standalone must be a bool")+ if document_title is not None and not isinstance(document_title, str):+ raise TypeError("document_title must be a string or None")+ return _HtmlRenderer(+ middle_json,+ mode=mode,+ asset_base_url=asset_base_url,+ standalone=standalone,+ document_title=document_title,+ ).render()+++def _classify_list(items: list[ListItem], add_reference_bullets: bool) -> tuple[str, str | None, str]:+ """根据直属 marker 选择原生列表类型或显式 marker 模式。"""+ if add_reference_bullets:+ return "ul", None, "mineru-list--reference"+ if items and all(item.kind == "unordered" for item in items):+ return "ul", None, "mineru-list--unordered"+ if items and all(item.kind == "ordered" for item in items):+ styles = {item.ordered_style for item in items}+ if len(styles) == 1:+ style = next(iter(styles))+ list_type = {+ "lower-alpha": "a",+ "upper-alpha": "A",+ "lower-roman": "i",+ "upper-roman": "I",+ }.get(style or "")+ return "ol", list_type, "mineru-list--ordered"+ if items and all(item.kind == "none" for item in items):+ return "ul", None, "mineru-list--unmarked"+ return "ul", None, "mineru-list--explicit"+++def _list_item_content(+ item: ListItem,+ add_reference_bullets: bool,+ *,+ explicit_markers: bool,+) -> tuple[str, str | None]:+ """决定一个列表项应剥离、保留还是显式显示源 marker。"""+ if add_reference_bullets:+ if item.kind == "unordered":+ return item.body, None+ original = f"{item.leading}{item.marker or ''}{item.separator}{item.body}"+ return original, None+ if explicit_markers:+ return item.body, item.marker+ if item.kind in {"unordered", "ordered"}:+ return item.body, None+ return item.body, item.marker+++def _serialize_index_items(items: list[dict[str, object]]) -> str:+ """把目录项及其已挂接的嵌套 ul 序列化为 li。"""+ rendered: list[str] = []+ for item in items:+ nested = item["nested"]+ assert isinstance(nested, list)+ content = str(item["content"])+ if not content and not nested:+ continue+ class_attr = ' class="mineru-list-item--orphan"' if item["orphan"] else ""+ rendered.append(f"<li{class_attr}>{content}{''.join(str(value) for value in nested)}</li>")+ return "".join(rendered)+++def _collect_title_anchor_ids(middle_json: MiddleJson) -> dict[str, str]:+ """为正文首次出现的非空 anchor 分配无空白且 document-wide 唯一的 HTML id。"""+ anchor_ids: dict[str, str] = {}+ used_ids: set[str] = set()+ for page in middle_json.pages:+ for block in page.blocks:+ if not isinstance(block, TitleBlockBase):+ continue+ anchor = _anchor_key(block.anchor)+ visible_title = inline_plain_text(parse_inline_content(block.content)).strip()+ if not anchor or not visible_title or anchor in anchor_ids:+ continue+ base_id = _html_anchor_base(anchor)+ candidate = base_id+ suffix = 2+ while candidate in used_ids:+ candidate = f"{base_id}-{suffix}"+ suffix += 1+ anchor_ids[anchor] = candidate+ used_ids.add(candidate)+ return anchor_ids+++def _plain_content_text(content: str) -> str:+ """从 body 内容提取安全 img alt 所需的可见纯文本。"""+ if not content:+ return ""+ if is_supported_html_markup(content):+ return BeautifulSoup(content, "html.parser").get_text(" ", strip=True)+ return inline_plain_text(parse_inline_content(content)).strip()+++def _contains_usable_table(markup: str) -> bool:+ """确认清洗后的 markup 至少保留一个含单元格的 table。"""+ soup = BeautifulSoup(markup, "html.parser")+ return any(table.find(("td", "th")) is not None for table in soup.find_all("table"))+++def _render_raw_fallback(content: str) -> str:+ """把无法安全结构化的原内容转义为可见 pre,避免静默丢失。"""+ return f'<pre class="mineru-raw-fallback">{html.escape(_replace_html_controls(content), quote=False)}</pre>'+++def _normalize_prism_language(language: str | None) -> str | None:+ """把模型语言名归一化为不可构造路径穿越的 Prism component 名。"""+ normalized = (language or "").strip().lower()+ normalized = _PRISM_LANGUAGE_ALIASES.get(normalized, normalized.replace("_", "-"))+ if not normalized or normalized in _BLOCKED_PRISM_LANGUAGE_NAMES:+ return None+ return normalized if _SAFE_PRISM_LANGUAGE_RE.fullmatch(normalized) else None+++def _resolve_document_title(middle_json: MiddleJson, explicit_title: str | None) -> str:+ """按显式参数、首个正文文档标题、固定回退值解析 HTML title。"""+ if explicit_title and explicit_title.strip():+ return explicit_title.strip()+ for page in middle_json.pages:+ for block in page.blocks:+ if isinstance(block, DocTitleBlock):+ title = inline_plain_text(parse_inline_content(block.content)).strip()+ if title:+ return title+ return "MinerU Document"+++def _anchor_key(anchor: str | None) -> str:+ """保留 producer anchor 身份,仅去除首尾空白供标题与目录精确匹配。"""+ return (anchor or "").strip()+++def _html_anchor_base(anchor: str) -> str:+ """把原始 anchor 转成无空白的 HTML id 基值,碰撞由 document registry 处理。"""+ return re.sub(r"\s+", "-", _replace_html_controls(anchor))+++def _replace_html_controls(content: str) -> str:+ """替换 HTML 不允许的 C0 控制字符与不可编码的孤立 surrogate。"""+ return re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]", "\ufffd", content)+++@lru_cache(maxsize=1)+def _load_html_styles() -> str:+ """从包资源读取并缓存固定 Crossnote CSS 与 MinerU 补充样式。"""+ root = resources.files("mineru").joinpath("resources", "html")+ license_text = root.joinpath("crossnote", "LICENSE.md").read_text(encoding="utf-8")+ notice = f"/*\nCrossnote 0.9.31 CSS license notice:\n{license_text}\n*/"+ styles = [root.joinpath(*path).read_text(encoding="utf-8") for path in _STYLE_RESOURCE_PATHS]+ return "\n".join([notice, *styles])+++def _mathjax_head() -> str:+ """返回固定、收紧公式输入能力的 MathJax 4.1.2 head 片段。"""+ return f"""<script>+window.MathJax = {{+ loader: {{load: ['ui/safe']}},+ tex: {{+ inlineMath: [['\\\\(', '\\\\)']],+ displayMath: [['\\\\[', '\\\\]']],+ processEscapes: true,+ processEnvironments: false,+ processRefs: false,+ packages: {{'[-]': ['require']}}+ }},+ options: {{+ ignoreHtmlClass: 'mineru-document',+ processHtmlClass: 'mineru-math',+ enableMenu: false,+ enableEnrichment: false,+ safeOptions: {{allow: {{URLs: 'none', classes: 'none', cssIDs: 'none', styles: 'none'}}}}+ }},+ startup: {{+ ready: function () {{+ window.MathJax.startup.defaultReady();+ var options = window.MathJax.startup.document.options;+ options.enableMenu = false;+ options.enableEnrichment = false;+ }}+ }}+}};+</script>+<script id="MathJax-script" defer src="{_MATHJAX_URL}"+ integrity="{_MATHJAX_INTEGRITY}" crossorigin="anonymous" referrerpolicy="no-referrer"></script>"""+++def _prism_head() -> str:+ """返回固定 Prism core、Autoloader 和当前文档局部高亮脚本。"""+ return f"""<script defer data-manual src="{_PRISM_CORE_URL}"+ integrity="{_PRISM_CORE_INTEGRITY}" crossorigin="anonymous" referrerpolicy="no-referrer"></script>+<script defer src="{_PRISM_AUTOLOADER_URL}"+ integrity="{_PRISM_AUTOLOADER_INTEGRITY}" crossorigin="anonymous" referrerpolicy="no-referrer"></script>+<script>+document.addEventListener('DOMContentLoaded', function () {{+ if (!window.Prism || !Prism.plugins || !Prism.plugins.autoloader) return;+ Prism.plugins.autoloader.languages_path = '{_PRISM_LANGUAGES_PATH}';+ var root = document.querySelector('.mineru-document');+ if (root) Prism.highlightAllUnder(root);+}});+</script>"""+++__all__ = ["render_html"]diff --git a/mineru/render/markdown.py b/mineru/render/markdown.pyindex 2e82e20b..bb140e5d 100644--- a/mineru/render/markdown.py+++ b/mineru/render/markdown.py@@ -9,12 +9,12 @@ import refrom mineru.config import LatexDelimitersConfig, configfrom mineru.render.utils.assets import build_markdown_image, resolve_image_sourcefrom mineru.render.utils.inline import (- inline_plain_text,- parse_inline_content,render_inline_content,render_internal_link,render_joined_inline_contents,)+from mineru.render.utils.index import strip_index_page_tail+from mineru.render.utils.list_items import has_markdown_unordered_marker, reference_list_needs_bulletsfrom mineru.render.utils.logical_blocks import MarkdownRenderMode, PlannedBlock, build_render_planfrom mineru.render.utils.markdown_table import format_embedded_html, render_html_tablefrom mineru.render.utils.markdown_utils import escape_standalone_marker_rule, escape_text_block_markdown_prefix@@ -58,10 +58,6 @@ _ALGORITHM_TOKEN_RE = re.compile(re.IGNORECASE | re.DOTALL,)_VALID_CODE_LANGUAGE_RE = re.compile(r"[A-Za-z0-9_.+#-]+")-_INDEX_ROMAN_RE = re.compile(r"[ivxlcdm]+", re.IGNORECASE)-# 去除首部空白后,前五个可见字符内出现 Unicode 数字即视为单项命中。-_REF_ITEM_NUMBER_PREFIX_RE = re.compile(r"^\D{0,4}\d")-_UNORDERED_LIST_ITEM_RE = re.compile(r"^[ \t]*-[ \t]+")def render_markdown(@@ -200,7 +196,7 @@ def _render_equation(def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:"""递归渲染列表,并给多数条目无数字前缀的参考文献补无序标记。"""- add_ref_bullets = _should_add_reference_list_bullets(block)+ add_ref_bullets = reference_list_needs_bullets(block)lines: list[str] = []for child in block.content:if isinstance(child, ListBlock):@@ -214,33 +210,13 @@ def _render_list(block: ListBlock, delimiters: LatexDelimitersConfig, depth: intitem = escape_standalone_marker_rule(item)indent = " " * depthitem_lines = item.splitlines() or [item]- if add_ref_bullets and not _UNORDERED_LIST_ITEM_RE.match(item):+ if add_ref_bullets and not has_markdown_unordered_marker(item):lines.append(f"{indent}- {item_lines[0]}")lines.extend(f"{indent} {line}" for line in item_lines[1:])else:lines.extend(f"{indent}{line}" for line in item_lines)return "\n".join(lines)--def _should_add_reference_list_bullets(block: ListBlock) -> bool:- """统计直属可见条目的数字前缀,未达到严格多数时给参考文献补项目符号。"""- if block.sub_type != BlockType.REF_TEXT:- return False-- item_count = 0- numbered_count = 0- for child in block.content:- if isinstance(child, ListBlock):- continue- visible_text = inline_plain_text(parse_inline_content(child.content)).lstrip()- if not visible_text:- continue- item_count += 1- if _REF_ITEM_NUMBER_PREFIX_RE.match(visible_text):- numbered_count += 1- return item_count > 0 and numbered_count * 2 <= item_count--def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: int = 0) -> str:"""递归渲染目录列表,并给标题叶子添加内部 anchor 链接。"""lines: list[str] = []@@ -250,7 +226,7 @@ def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: iif nested:lines.extend(nested.splitlines())continue- content = _strip_index_page_tail(child.content)+ content = strip_index_page_tail(child.content)label = render_inline_content(content, delimiters).strip()if not label:continue@@ -259,25 +235,6 @@ def _render_index(block: IndexBlock, delimiters: LatexDelimitersConfig, depth: ilines.append(f"{' ' * depth}- {label}")return "\n".join(lines)--def _strip_index_page_tail(content: str) -> str:- """删除目录末尾可信页码,并把其余 tab 转换为普通空格。"""- if "\t" not in content:- return content- head, tail = content.rsplit("\t", 1)- tail_text = inline_plain_text(parse_inline_content(tail)).strip()- if _looks_like_index_page_token(tail_text):- content = head- return content.replace("\t", " ")---def _looks_like_index_page_token(content: str) -> bool:- """判断目录 tab 后缀是否为数字、罗马数字或单字母页码。"""- if not content or len(content) > 12:- return False- return bool(content.isdigit() or _INDEX_ROMAN_RE.fullmatch(content) or re.fullmatch(r"[A-Za-z]", content))--def _render_image_block(block: ImageBlock,delimiters: LatexDelimitersConfig,diff --git a/mineru/render/utils/html_inline.py b/mineru/render/utils/html_inline.pynew file mode 100644index 00000000..ddf6c0e6--- /dev/null+++ b/mineru/render/utils/html_inline.py@@ -0,0 +1,163 @@+# Copyright (c) Opendatalab. All rights reserved.+"""MiddleJson 共享行内语义到安全 HTML 的序列化工具。"""++from __future__ import annotations++import html+import re+from dataclasses import dataclass++from mineru.render.utils.html_sanitizer import sanitize_link_url+from mineru.render.utils.inline import (+ InlineEquation,+ InlineLink,+ InlineNode,+ InlineStyled,+ InlineText,+ inline_plain_text,+ join_inline_contents,+ parse_inline_content,+)+++@dataclass(frozen=True, slots=True)+class HtmlInlineResult:+ """保存一段行内 HTML 及其是否包含需由 MathJax 处理的公式。"""++ html: str+ has_math: bool = False+++def render_inline_content_html(content: str) -> HtmlInlineResult:+ """把一段 MiddleJson 行内内容渲染为安全 HTML。"""+ return render_inline_nodes_html(parse_inline_content(content))+++def render_joined_inline_contents_html(contents: list[str]) -> HtmlInlineResult:+ """按共享物理段落边界规则合并多段内容后渲染 HTML。"""+ return render_inline_nodes_html(join_inline_contents(contents))+++def render_inline_nodes_html(+ nodes: list[InlineNode],+ *,+ separate_adjacent_math: bool = False,+ preserve_newlines: bool = False,+) -> HtmlInlineResult:+ """渲染行内节点,可分隔相邻公式或给 pre-wrap 容器保留原始换行。"""+ parts: list[str] = []+ has_math = False+ previous_was_math = False+ for node in nodes:+ rendered = _render_inline_node_html(node, preserve_newlines=preserve_newlines)+ if not rendered.html:+ continue+ current_is_math = isinstance(node, InlineEquation)+ if separate_adjacent_math and previous_was_math and current_is_math:+ parts.append(" ")+ parts.append(rendered.html)+ has_math = rendered.has_math or has_math+ previous_was_math = current_is_math+ return HtmlInlineResult("".join(parts), has_math)+++def render_math_html(latex: str, *, display: bool) -> HtmlInlineResult:+ """把裸 LaTeX 放入只由 MathJax 扫描的行内或行间公式载体。"""+ normalized = latex.strip()+ if not normalized:+ return HtmlInlineResult("")+ normalized = _neutralize_math_closing_delimiter(normalized, "]" if display else ")")+ escaped = _escape_text(normalized)+ if display:+ return HtmlInlineResult(+ f'<div class="mineru-math mineru-math--block">\\[\n{escaped}\n\\]</div>',+ has_math=True,+ )+ return HtmlInlineResult(+ f'<span class="mineru-math mineru-math--inline">\\({escaped}\\)</span>',+ has_math=True,+ )+++def _render_inline_node_html(node: InlineNode, *, preserve_newlines: bool) -> HtmlInlineResult:+ """把一个共享行内节点映射为 HTML。"""+ if isinstance(node, InlineText):+ escaped = _escape_text(node.content)+ return HtmlInlineResult(escaped if preserve_newlines else escaped.replace("\n", "<br>\n"))+ if isinstance(node, InlineEquation):+ return render_math_html(node.latex, display=False)+ if isinstance(node, InlineStyled):+ children = render_inline_nodes_html(node.children, preserve_newlines=preserve_newlines)+ rendered = _apply_html_styles(children.html, node.styles)+ plain_text = inline_plain_text(node.children)+ if _needs_whitespace_preservation(plain_text):+ rendered = f'<span class="mineru-preserve-whitespace">{rendered}</span>'+ return HtmlInlineResult(rendered, children.has_math)+ if isinstance(node, InlineLink):+ children = render_inline_nodes_html(node.children, preserve_newlines=preserve_newlines)+ safe_url = sanitize_link_url(node.url)+ if not safe_url or safe_url == ".":+ return children+ href = html.escape(safe_url, quote=True)+ return HtmlInlineResult(+ f'<a href="{href}" rel="noopener noreferrer">{children.html}</a>',+ children.has_math,+ )+ raise TypeError(f"Unsupported inline node: {type(node).__name__}")+++def _apply_html_styles(content: str, styles: tuple[str, ...]) -> str:+ """按 Markdown renderer 的稳定顺序应用共享富文本样式。"""+ if not content:+ return content+ if "superscript" in styles:+ content = f"<sup>{content}</sup>"+ elif "subscript" in styles:+ content = f"<sub>{content}</sub>"+ if "underline" in styles:+ content = f"<u>{content}</u>"+ if "bold" in styles:+ content = f"<strong>{content}</strong>"+ if "italic" in styles:+ content = f"<em>{content}</em>"+ if "strikethrough" in styles:+ content = f"<s>{content}</s>"+ if "emphasis" in styles:+ content = f'<span class="mineru-text-emphasis">{content}</span>'+ return content+++def _escape_text(content: str) -> str:+ """转义普通文本,并替换 HTML 不允许的 C0 控制字符。"""+ normalized = content.replace("\r\n", "\n").replace("\r", "\n")+ normalized = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]", "\ufffd", normalized)+ return html.escape(normalized, quote=False)+++def _needs_whitespace_preservation(content: str) -> bool:+ """判断富文本是否包含浏览器默认会折叠的有效空白。"""+ return bool(content and (content != content.strip(" \t\n") or " " in content or "\t" in content or "\n" in content))+++def _neutralize_math_closing_delimiter(latex: str, closing: str) -> str:+ """把公式体内奇数反斜杠引出的结束定界符改写为等价 TeX,防止提前闭合。"""+ token = re.escape(closing)++ def _replace(match: re.Match[str]) -> str:+ """保留成对反斜杠,并把最后一个定界反斜杠改为 mathclose。"""+ slashes = match.group("slashes")+ if len(slashes) % 2 == 0:+ return match.group(0)+ prefix = "\\" * (len(slashes) - 1)+ return f"{prefix}\\mathclose{{{closing}}}"++ return re.sub(rf"(?P<slashes>\\+){token}", _replace, latex)+++__all__ = [+ "HtmlInlineResult",+ "render_inline_content_html",+ "render_inline_nodes_html",+ "render_joined_inline_contents_html",+ "render_math_html",+]diff --git a/mineru/render/utils/html_sanitizer.py b/mineru/render/utils/html_sanitizer.pynew file mode 100644index 00000000..4b898c09--- /dev/null+++ b/mineru/render/utils/html_sanitizer.py@@ -0,0 +1,478 @@+# Copyright (c) Opendatalab. All rights reserved.+"""HTML renderer 使用的嵌入片段安全处理。"""++from __future__ import annotations++import html+import re+from urllib.parse import quote, unquote, urlsplit++import nh3+from bs4 import BeautifulSoup, NavigableString, Tag++from mineru.utils.image_payload import parse_image_data_uri_strict+++_ALLOWED_TAGS = {+ "a",+ "b",+ "blockquote",+ "br",+ "caption",+ "code",+ "col",+ "colgroup",+ "div",+ "em",+ "eq",+ "i",+ "img",+ "li",+ "ol",+ "p",+ "pre",+ "s",+ "span",+ "strong",+ "sub",+ "sup",+ "table",+ "tbody",+ "td",+ "tfoot",+ "th",+ "thead",+ "tr",+ "u",+ "ul",+}+_ACTIVE_CONTENT_TAGS = {+ "audio",+ "button",+ "canvas",+ "embed",+ "form",+ "iframe",+ "input",+ "math",+ "noscript",+ "object",+ "script",+ "select",+ "style",+ "svg",+ "template",+ "textarea",+ "video",+}+_ALLOWED_ATTRIBUTES = {+ "a": {"href", "title"},+ "col": {"span"},+ "colgroup": {"span"},+ "img": {"alt", "src", "title"},+ "li": {"value"},+ "ol": {"start"},+ "td": {"colspan", "rowspan"},+ "th": {"colspan", "rowspan", "scope"},+}+_ALLOWED_URL_SCHEMES = {"data", "http", "https", "mailto", "tel"}+_LINK_SCHEMES = {"http", "https", "mailto", "tel"}+_EQ_PLACEHOLDER_TAG = "mineru-eq-placeholder"+_DATA_IMAGE_RE = re.compile(+ r"\Adata:(?P<mime>image/[a-z0-9.+-]+);base64,(?P<payload>[a-z0-9+/]*={0,2})\Z",+ re.IGNORECASE,+)+_SCHEME_RE = re.compile(r"\A[a-z][a-z0-9+.-]*:", re.IGNORECASE)+_INTEGER_RE = re.compile(r"\A[+-]?\d+\Z")+_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f\ud800-\udfff]")+_INVALID_HTML_TEXT_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]")+_HTML_TAG_TOKEN_RE = re.compile(+ r"<\s*(?P<closing>/)?\s*(?P<name>[A-Za-z][A-Za-z0-9:-]*)\b(?P<attrs>[^>]*)>",+ re.DOTALL,+)+_VOID_MARKUP_TAGS = {"br"}+_SOURCE_MARKUP_TAGS = _ALLOWED_TAGS | _ACTIVE_CONTENT_TAGS+_PHRASING_CONTAINER_TAGS = {"a", "b", "code", "em", "i", "p", "s", "span", "strong", "sub", "sup", "u"}+_TABLE_STRUCTURE_TAGS = {"colgroup", "table", "tbody", "tfoot", "thead", "tr"}+++def is_supported_html_markup(content: str) -> bool:+ """判断内容是否包含需要交给安全层处理的 HTML 标签。++ 只有白名单标签或必须整体删除的活动标签才算 HTML,避免把+ ``<local_dir>`` 和数学不等式这类普通文本误判为标记。+ """+ if not isinstance(content, str):+ raise TypeError("content must be a string")+ if "<" not in content or ">" not in content:+ return False+ tokens = list(_HTML_TAG_TOKEN_RE.finditer(content))+ closing_names = {+ match.group("name").lower()+ for match in tokens+ if match.group("closing") and match.group("name").lower() in _SOURCE_MARKUP_TAGS+ }+ for match in tokens:+ if match.group("closing"):+ continue+ name = match.group("name").lower()+ if name not in _SOURCE_MARKUP_TAGS:+ continue+ if name in _VOID_MARKUP_TAGS or name in closing_names:+ return True+ if name in {"img", "embed"} and re.search(r"\bsrc\s*=", match.group("attrs"), re.IGNORECASE):+ return True+ return False+++def sanitize_link_url(url: str) -> str | None:+ """校验链接地址,仅保留安全的相对地址和显式允许的协议。"""+ normalized = _normalize_url_text(url, parameter_name="url")+ if normalized is None:+ return None+ if normalized.startswith(("//", "\\")):+ return None++ scheme_match = _SCHEME_RE.match(normalized)+ if scheme_match is None:+ return _quote_document_url(normalized)++ try:+ parsed = urlsplit(normalized)+ except ValueError:+ return None+ scheme = parsed.scheme.lower()+ if scheme not in _LINK_SCHEMES:+ return None+ if scheme in {"http", "https"}:+ try:+ if not parsed.netloc or parsed.hostname is None:+ return None+ except ValueError:+ return None+ elif not parsed.path:+ return None+ return _quote_document_url(normalized)+++def sanitize_image_source(source: str, *, asset_base_url: str = "") -> str | None:+ """校验图片来源,并为安全的相对 sidecar 路径添加资源根地址。"""+ normalized = _normalize_url_text(source, parameter_name="source")+ if normalized is None:+ return None++ data_source = _sanitize_raster_data_uri(normalized)+ if data_source is not None:+ return data_source+ if normalized.lower().startswith("data:"):+ return None++ absolute_source = _sanitize_absolute_image_url(normalized)+ if absolute_source is not None:+ return _quote_image_url(absolute_source)+ if _SCHEME_RE.match(normalized) is not None or normalized.startswith(("//", "\\", "#", "?")):+ return None+ if not _is_safe_image_path(normalized):+ return None+ if normalized.startswith("/") or not asset_base_url:+ return _quote_image_url(normalized)++ safe_base = _sanitize_asset_base_url(asset_base_url)+ if safe_base is None:+ return None+ return _quote_image_url(f"{safe_base.rstrip('/')}/{normalized.lstrip('/')}")+++def sanitize_html_fragment(markup: str, *, asset_base_url: str = "") -> str:+ """清洗嵌入 HTML,保留表格语义、安全媒体与待渲染的 ``eq`` 标签。"""+ if not isinstance(markup, str):+ raise TypeError("markup must be a string")+ if not isinstance(asset_base_url, str):+ raise TypeError("asset_base_url must be a string")++ soup = BeautifulSoup(_INVALID_HTML_TEXT_RE.sub("\ufffd", markup), "html.parser")+ _remove_active_content(soup)+ _normalize_fragment_elements(soup, asset_base_url=asset_base_url)+ _protect_equation_elements(soup)+ prepared = str(soup)+ cleaned = nh3.clean(+ prepared,+ tags=_ALLOWED_TAGS | {_EQ_PLACEHOLDER_TAG},+ clean_content_tags=_ACTIVE_CONTENT_TAGS,+ attributes=_ALLOWED_ATTRIBUTES,+ attribute_filter=_filter_sanitized_attribute,+ link_rel=None,+ url_schemes=_ALLOWED_URL_SCHEMES,+ )+ restored = cleaned.replace(f"<{_EQ_PLACEHOLDER_TAG}>", "<eq>").replace(f"</{_EQ_PLACEHOLDER_TAG}>", "</eq>")+ cleaned_soup = BeautifulSoup(restored, "html.parser")+ _normalize_cleaned_content_models(cleaned_soup)+ return str(cleaned_soup)+++def _normalize_url_text(value: str, *, parameter_name: str) -> str | None:+ """解码 HTML 实体并拒绝可用于混淆协议的控制字符。"""+ if not isinstance(value, str):+ raise TypeError(f"{parameter_name} must be a string")+ normalized = value.strip()+ for _ in range(8):+ decoded = html.unescape(normalized)+ if decoded == normalized:+ break+ normalized = decoded+ normalized = normalized.strip()+ if not normalized or _CONTROL_RE.search(normalized) is not None:+ return None+ return normalized+++def _sanitize_absolute_image_url(source: str) -> str | None:+ """只允许带有有效主机名的 HTTP(S) 图片地址。"""+ if source.startswith(("//", "\\")):+ return None+ try:+ parsed = urlsplit(source)+ except ValueError:+ return None+ if parsed.scheme.lower() not in {"http", "https"}:+ return None+ try:+ if not parsed.netloc or parsed.hostname is None:+ return None+ except ValueError:+ return None+ return source+++def _sanitize_raster_data_uri(source: str) -> str | None:+ """同时校验 MIME、base64 与文件签名,只接受受支持的栅格图。"""+ match = _DATA_IMAGE_RE.fullmatch(source)+ if match is None:+ return None+ if match.group("mime").lower() == "image/svg+xml":+ return None+ try:+ _, extension = parse_image_data_uri_strict(source)+ except ValueError:+ return None+ if extension == "svg":+ return None+ return source+++def _quote_image_url(source: str) -> str:+ """按现有 render 资源规则编码空格与括号,同时保留 URL 结构字符。"""+ return quote(source, safe="/:#?&=%@+~,;!$'*-._")+++def _quote_document_url(source: str) -> str:+ """编码链接中的空格、反斜杠与括号,同时保留 URL 结构字符。"""+ return quote(source, safe="/:#?&=%@+~,;!$'*-._")+++def _is_safe_image_path(source: str) -> bool:+ """判断相对或根相对图片路径是否不会逃逸 sidecar 根目录。"""+ if "\\" in source:+ return False+ try:+ parsed = urlsplit(source)+ except ValueError:+ return False+ if parsed.scheme or parsed.netloc or not parsed.path:+ return False++ return not _has_unsafe_path_segment(parsed.path)+++def _sanitize_asset_base_url(asset_base_url: str) -> str | None:+ """校验用于拼接 sidecar 的资源根地址。"""+ normalized = _normalize_url_text(asset_base_url, parameter_name="asset_base_url")+ if normalized is None or normalized.startswith(("//", "\\", "#", "?")):+ return None+ absolute_url = _sanitize_absolute_image_url(normalized)+ if absolute_url is not None:+ parsed = urlsplit(absolute_url)+ if parsed.query or parsed.fragment or _has_unsafe_path_segment(parsed.path):+ return None+ return absolute_url+ if _SCHEME_RE.match(normalized) is not None:+ return None+ if not _is_safe_image_path(normalized):+ return None+ parsed = urlsplit(normalized)+ return None if parsed.query or parsed.fragment else normalized+++def _has_unsafe_path_segment(path: str) -> bool:+ """递归解码 URL 路径,识别控制字符、反斜杠和父目录逃逸。"""+ decoded_path = path+ for _ in range(8):+ next_path = unquote(decoded_path)+ if next_path == decoded_path:+ break+ decoded_path = next_path+ if "\\" in decoded_path or _CONTROL_RE.search(decoded_path) is not None:+ return True+ return ".." in decoded_path.split("/")+++def _remove_active_content(soup: BeautifulSoup) -> None:+ """在通用白名单清洗前,删除活动标签及其全部内容。"""+ for tag in list(soup.find_all(_ACTIVE_CONTENT_TAGS)):+ if tag.parent is not None:+ tag.decompose()+++def _normalize_fragment_elements(soup: BeautifulSoup, *, asset_base_url: str) -> None:+ """在 nh3 前重写图片、链接和有边界的数值属性。"""+ for tag in list(soup.find_all(True)):+ if tag.parent is None:+ continue+ if tag.name == "a":+ if not _normalize_link_element(tag):+ tag.unwrap()+ continue+ if tag.name == "img":+ _normalize_image_element(tag, asset_base_url=asset_base_url)+ continue+ tag.attrs = _normalized_non_url_attributes(tag)+++def _protect_equation_elements(soup: BeautifulSoup) -> None:+ """使用临时自定义标签保护 ``eq``,规避 nh3 对该历史标签的特殊解析。"""+ for forged_placeholder in list(soup.find_all(_EQ_PLACEHOLDER_TAG)):+ forged_placeholder.unwrap()+ for equation in soup.find_all("eq"):+ latex = equation.get_text()+ equation.clear()+ equation.append(NavigableString(latex))+ equation.name = _EQ_PLACEHOLDER_TAG+++def _normalize_cleaned_content_models(soup: BeautifulSoup) -> None:+ """修复 allowlist 清洗后仍可能违反 HTML content model 的列表、colgroup 与图片。"""+ for image in soup.find_all("img"):+ if not image.has_attr("alt"):+ image["alt"] = ""++ for colgroup in soup.find_all("colgroup"):+ if colgroup.find("col", recursive=False) is not None:+ colgroup.attrs.pop("span", None)++ for list_tag in soup.find_all(("ul", "ol")):+ for child in list(list_tag.children):+ if isinstance(child, NavigableString):+ if not str(child).strip():+ continue+ item = soup.new_tag("li")+ child.replace_with(item)+ item.append(child)+ elif isinstance(child, Tag) and child.name != "li":+ item = soup.new_tag("li")+ child.replace_with(item)+ item.append(child)++ for item in list(soup.find_all("li")):+ parent = item.parent+ if isinstance(parent, Tag) and parent.name in {"ul", "ol"}:+ continue+ while isinstance(parent, Tag) and parent.name in _PHRASING_CONTAINER_TAGS:+ parent.unwrap()+ parent = item.parent+ wrapper = soup.new_tag("ul")+ if isinstance(parent, Tag) and parent.name in _TABLE_STRUCTURE_TAGS:+ boundary = parent+ while isinstance(boundary.parent, Tag) and boundary.parent.name in _TABLE_STRUCTURE_TAGS:+ boundary = boundary.parent+ boundary.insert_before(wrapper)+ item.extract()+ wrapper.append(item)+ else:+ item.replace_with(wrapper)+ wrapper.append(item)+++def _normalize_link_element(tag: Tag) -> bool:+ """清理链接属性,危险或缺失的 href 由调用方展开为普通文本。"""+ href = sanitize_link_url(_attribute_text(tag.get("href")))+ if href is None:+ return False+ attributes: dict[str, str] = {"href": href}+ title = _attribute_text(tag.get("title"))+ if title:+ attributes["title"] = title+ tag.attrs = attributes+ return True+++def _normalize_image_element(tag: Tag, *, asset_base_url: str) -> None:+ """清理图片属性,危险图片替换为可见且会被转义的 alt 文本。"""+ alt = _attribute_text(tag.get("alt"))+ source = sanitize_image_source(_attribute_text(tag.get("src")), asset_base_url=asset_base_url)+ if source is None:+ tag.replace_with(NavigableString(alt))+ return+ attributes: dict[str, str] = {"alt": alt, "src": source}+ title = _attribute_text(tag.get("title"))+ if title:+ attributes["title"] = title+ tag.attrs = attributes+++def _normalized_non_url_attributes(tag: Tag) -> dict[str, str]:+ """仅保留表格与列表语义需要的有界整数属性。"""+ attributes: dict[str, str] = {}+ if tag.name in {"td", "th"}:+ for name in ("colspan", "rowspan"):+ value = _bounded_integer(_attribute_text(tag.get(name)), minimum=1, maximum=1000)+ if value is not None:+ attributes[name] = value+ if tag.name == "th" and _attribute_text(tag.get("scope")) in {"col", "colgroup", "row", "rowgroup"}:+ attributes["scope"] = _attribute_text(tag.get("scope"))+ elif tag.name in {"col", "colgroup"}:+ value = _bounded_integer(_attribute_text(tag.get("span")), minimum=1, maximum=1000)+ if value is not None:+ attributes["span"] = value+ elif tag.name == "ol":+ value = _bounded_integer(_attribute_text(tag.get("start")), minimum=-1_000_000, maximum=1_000_000)+ if value is not None:+ attributes["start"] = value+ elif tag.name == "li":+ value = _bounded_integer(_attribute_text(tag.get("value")), minimum=-1_000_000, maximum=1_000_000)+ if value is not None:+ attributes["value"] = value+ return attributes+++def _bounded_integer(value: str, *, minimum: int, maximum: int) -> str | None:+ """解析并规范化指定闭区间内的十进制整数。"""+ if _INTEGER_RE.fullmatch(value) is None:+ return None+ number = int(value)+ return str(number) if minimum <= number <= maximum else None+++def _attribute_text(value: object) -> str:+ """将 BeautifulSoup 属性值稳定地转为字符串。"""+ if value is None:+ return ""+ if isinstance(value, list):+ return " ".join(str(item) for item in value)+ return str(value)+++def _filter_sanitized_attribute(tag: str, attribute: str, value: str) -> str | None:+ """在 nh3 重新解析后再次校验 URL,防止解析差异导致属性绕过。"""+ if tag == "a" and attribute == "href":+ return sanitize_link_url(value)+ if tag == "img" and attribute == "src":+ return sanitize_image_source(value)+ return value+++__all__ = [+ "is_supported_html_markup",+ "sanitize_html_fragment",+ "sanitize_image_source",+ "sanitize_link_url",+]diff --git a/mineru/render/utils/html_table.py b/mineru/render/utils/html_table.pynew file mode 100644index 00000000..89f6fe86--- /dev/null+++ b/mineru/render/utils/html_table.py@@ -0,0 +1,118 @@+# Copyright (c) Opendatalab. All rights reserved.+"""HTML renderer 使用的严格 GFM pipe table 转换工具。"""++from __future__ import annotations++import re++from mineru.render.utils.html_inline import HtmlInlineResult, render_inline_content_html++_SEPARATOR_CELL_RE = re.compile(r"^:?-{3,}:?$")+++def looks_like_gfm_table(content: str) -> bool:+ """判断文本是否具有 GFM pipe table 的表头与分隔行外形。"""+ lines = [line.strip() for line in content.strip().splitlines() if line.strip()]+ if len(lines) < 2:+ return False+ if not _contains_unescaped_pipe(lines[0]) or not _contains_unescaped_pipe(lines[1]):+ return False+ separator_cells = _split_pipe_row(lines[1])+ return bool(separator_cells and all(_SEPARATOR_CELL_RE.fullmatch(cell.strip()) for cell in separator_cells))+++def render_gfm_table_html(content: str) -> HtmlInlineResult | None:+ """把严格、等宽的简单 GFM pipe table 转换为语义 HTML。"""+ lines = [line.strip() for line in content.strip().splitlines() if line.strip()]+ if len(lines) < 2:+ return None+ if not _contains_unescaped_pipe(lines[0]) or not _contains_unescaped_pipe(lines[1]):+ return None+ header = _split_pipe_row(lines[0])+ separators = _split_pipe_row(lines[1])+ if not header or len(header) != len(separators):+ return None+ if not all(_SEPARATOR_CELL_RE.fullmatch(cell.strip()) for cell in separators):+ return None++ rows = [_split_pipe_row(line) for line in lines[2:]]+ if any(len(row) != len(header) for row in rows):+ return None++ alignments = [_separator_alignment(cell.strip()) for cell in separators]+ has_math = False++ def _render_row(cells: list[str], cell_tag: str) -> str:+ """渲染一行等宽单元格,并累积公式存在标记。"""+ nonlocal has_math+ rendered_cells: list[str] = []+ for index, cell in enumerate(cells):+ rendered = render_inline_content_html(_unescape_gfm_cell(cell.strip()))+ has_math = rendered.has_math or has_math+ alignment = alignments[index]+ class_attr = f' class="mineru-align-{alignment}"' if alignment else ""+ rendered_cells.append(f"<{cell_tag}{class_attr}>{rendered.html}</{cell_tag}>")+ return f"<tr>{''.join(rendered_cells)}</tr>"++ table = "".join(+ [+ '<table class="mineru-chart-table">',+ f"<thead>{_render_row(header, 'th')}</thead>",+ f"<tbody>{''.join(_render_row(row, 'td') for row in rows)}</tbody>",+ "</table>",+ ]+ )+ return HtmlInlineResult(table, has_math)+++def _split_pipe_row(line: str) -> list[str]:+ """按未被奇数个反斜杠转义的竖线切分 GFM 表格行。"""+ normalized = line.strip()+ if normalized.startswith("|"):+ normalized = normalized[1:]+ if normalized.endswith("|") and not _is_escaped(normalized, len(normalized) - 1):+ normalized = normalized[:-1]++ cells: list[str] = []+ start = 0+ for index, char in enumerate(normalized):+ if char == "|" and not _is_escaped(normalized, index):+ cells.append(normalized[start:index])+ start = index + 1+ cells.append(normalized[start:])+ return cells+++def _is_escaped(content: str, index: int) -> bool:+ """按 markdown-it table 规则判断 pipe 是否紧邻任意反斜杠。"""+ return index > 0 and content[index - 1] == "\\"+++def _contains_unescaped_pipe(content: str) -> bool:+ """判断行内是否至少包含一个真正的 GFM 列分隔符。"""+ return any(char == "|" and not _is_escaped(content, index) for index, char in enumerate(content))+++def _unescape_gfm_cell(content: str) -> str:+ """按既有 2n+1 编码逆向恢复 GFM 单元格中的原始反斜杠与竖线。"""++ def _replace(match: re.Match[str]) -> str:+ """把竖线前 2n+1 个 Markdown 反斜杠还原为 n 个。"""+ slash_count = len(match.group("slashes"))+ return "\\" * ((slash_count - 1) // 2) + "|"++ return re.sub(r"(?P<slashes>\\+)\|", _replace, content)+++def _separator_alignment(cell: str) -> str | None:+ """从 GFM 分隔单元格解析 left、center 或 right 对齐。"""+ if cell.startswith(":") and cell.endswith(":"):+ return "center"+ if cell.endswith(":"):+ return "right"+ if cell.startswith(":"):+ return "left"+ return None+++__all__ = ["looks_like_gfm_table", "render_gfm_table_html"]diff --git a/mineru/render/utils/index.py b/mineru/render/utils/index.pynew file mode 100644index 00000000..07992463--- /dev/null+++ b/mineru/render/utils/index.py@@ -0,0 +1,31 @@+# Copyright (c) Opendatalab. All rights reserved.+"""目录页码尾清理的共享工具。"""++from __future__ import annotations++import re++from mineru.render.utils.inline import inline_plain_text, parse_inline_content++_INDEX_ROMAN_RE = re.compile(r"[ivxlcdm]+", re.IGNORECASE)+++def strip_index_page_tail(content: str) -> str:+ """删除目录末尾可信页码,并把其余 tab 转换为普通空格。"""+ if "\t" not in content:+ return content+ head, tail = content.rsplit("\t", 1)+ tail_text = inline_plain_text(parse_inline_content(tail)).strip()+ if looks_like_index_page_token(tail_text):+ content = head+ return content.replace("\t", " ")+++def looks_like_index_page_token(content: str) -> bool:+ """判断目录 tab 后缀是否为数字、罗马数字或单字母页码。"""+ if not content or len(content) > 12:+ return False+ return bool(content.isdigit() or _INDEX_ROMAN_RE.fullmatch(content) or re.fullmatch(r"[A-Za-z]", content))+++__all__ = ["looks_like_index_page_token", "strip_index_page_tail"]diff --git a/mineru/render/utils/list_items.py b/mineru/render/utils/list_items.pynew file mode 100644index 00000000..ac16d09e--- /dev/null+++ b/mineru/render/utils/list_items.py@@ -0,0 +1,157 @@+# Copyright (c) Opendatalab. All rights reserved.+"""列表条目标记与参考文献列表判定的共享工具。"""++from __future__ import annotations++from dataclasses import dataclass+import re+from typing import Literal, TypeAlias++from mineru.render.utils.inline import inline_plain_text, parse_inline_content+from mineru.types import BlockType, ListBlock++ListItemKind: TypeAlias = Literal["unordered", "ordered", "explicit", "none"]+OrderedListStyle: TypeAlias = Literal["decimal", "lower-alpha", "upper-alpha", "lower-roman", "upper-roman"]++_LIST_ITEM_MARKER_RE = re.compile(+ r"^(?P<leading>\s*)(?P<marker>"+ r"(?P<unordered>[-*+])"+ r"|(?P<ordered>\d+\.|[A-Za-z]\.|[IVXLCDMivxlcdm]{2,}\.)"+ r"|(?P<explicit>\d+\)|\(\d+[.)]|[A-Za-z]\)|[IVXLCDMivxlcdm]{2,}\)|\[[^\]\n]+\])"+ r")(?P<separator>\s+)(?P<body>.*)$",+ re.DOTALL,+)+_LEADING_WHITESPACE_RE = re.compile(r"^[ \t]*")+# 去除首部空白后,前五个可见字符内出现 Unicode 数字即视为单项命中。+_REFERENCE_NUMBER_PREFIX_RE = re.compile(r"^\D{0,4}\d")+_MARKDOWN_UNORDERED_MARKER_RE = re.compile(r"^[ \t]*-[ \t]+")+_ROMAN_MARKER_RE = re.compile(r"[IVXLCDM]+", re.IGNORECASE)+_CANONICAL_ROMAN_RE = re.compile(r"M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})")+_ROMAN_VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}+_MAX_NATIVE_ORDERED_VALUE = 1_000_000+++@dataclass(frozen=True, slots=True)+class ListItem:+ """保存一个列表条目的原始标记、正文与 HTML 所需分类。"""++ marker: str | None+ body: str+ kind: ListItemKind+ value: int | None+ ordered_style: OrderedListStyle | None+ leading: str+ separator: str+++def parse_list_item_marker(content: str) -> ListItem:+ """解析列表行首 marker;无法识别时仍拆出前导水平空白。"""+ match = _LIST_ITEM_MARKER_RE.match(content)+ if match is None:+ leading_match = _LEADING_WHITESPACE_RE.match(content)+ leading = leading_match.group(0) if leading_match is not None else ""+ return ListItem(+ marker=None,+ body=content[len(leading) :],+ kind="none",+ value=None,+ ordered_style=None,+ leading=leading,+ separator="",+ )++ marker = match.group("marker")+ if match.group("unordered") is not None:+ kind: ListItemKind = "unordered"+ value = None+ ordered_style = None+ elif match.group("ordered") is not None:+ ordered = _ordered_marker_value(marker)+ if ordered is None:+ kind = "explicit"+ value = None+ ordered_style = None+ else:+ kind = "ordered"+ value, ordered_style = ordered+ else:+ kind = "explicit"+ value = None+ ordered_style = None+ return ListItem(+ marker=marker,+ body=match.group("body"),+ kind=kind,+ value=value,+ ordered_style=ordered_style,+ leading=match.group("leading"),+ separator=match.group("separator"),+ )+++def _ordered_marker_value(marker: str) -> tuple[int, OrderedListStyle] | None:+ """把有界且规范的点号 marker 转成序号;超限或畸形时返回 None。"""+ stem = marker[:-1]+ if re.fullmatch(r"(?:0|[1-9][0-9]*)", stem):+ if len(stem) > 7:+ return None+ value = int(stem)+ return (value, "decimal") if value <= _MAX_NATIVE_ORDERED_VALUE else None+ # 单字符 i/v/x/l/c/d/m 固定按罗马数字解释,消除与字母序号的歧义。+ if _ROMAN_MARKER_RE.fullmatch(stem):+ if _CANONICAL_ROMAN_RE.fullmatch(stem.upper()) is None:+ return None+ style: OrderedListStyle = "upper-roman" if stem.isupper() else "lower-roman"+ return _roman_marker_value(stem), style+ if re.fullmatch(r"[A-Za-z]", stem) is None:+ return None+ style = "upper-alpha" if stem.isupper() else "lower-alpha"+ return ord(stem.lower()) - ord("a") + 1, style+++def _roman_marker_value(marker: str) -> int:+ """按减法记数规则计算罗马 marker 的数值,兼容 producer 的宽松组合。"""+ total = 0+ previous = 0+ for character in reversed(marker.upper()):+ current = _ROMAN_VALUES[character]+ if current < previous:+ total -= current+ else:+ total += current+ previous = current+ return total+++def has_markdown_unordered_marker(content: str) -> bool:+ """判断条目是否已有 Markdown 短横线 marker,保持既有补 bullet 规则。"""+ return _MARKDOWN_UNORDERED_MARKER_RE.match(content) is not None+++def reference_list_needs_bullets(block: ListBlock) -> bool:+ """按直属非空条目的数字前缀严格多数规则判断是否补无序 marker。"""+ if block.sub_type != BlockType.REF_TEXT:+ return False++ item_count = 0+ numbered_count = 0+ for child in block.content:+ if isinstance(child, ListBlock):+ continue+ visible_text = inline_plain_text(parse_inline_content(child.content)).lstrip()+ if not visible_text:+ continue+ item_count += 1+ if _REFERENCE_NUMBER_PREFIX_RE.match(visible_text):+ numbered_count += 1+ return item_count > 0 and numbered_count * 2 <= item_count+++__all__ = [+ "ListItem",+ "ListItemKind",+ "OrderedListStyle",+ "has_markdown_unordered_marker",+ "parse_list_item_marker",+ "reference_list_needs_bullets",+]diff --git a/mineru/resources/html/crossnote/LICENSE.md b/mineru/resources/html/crossnote/LICENSE.mdnew file mode 100644index 00000000..807b6547--- /dev/null+++ b/mineru/resources/html/crossnote/LICENSE.md@@ -0,0 +1,17 @@+University of Illinois/NCSA+Open Source License++```+Copyright (c) 2017 ~ 2023 Yiyi Wang+All rights reserved.++Developed by: Yiyi Wang+ https://github.com/shd101wyy/crossnote+```++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal with the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimers.+Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimers in the documentation and/or other materials provided with the distribution.+Neither the names of Yiyi Wang, nor the names of its contributors may be used to endorse or promote products derived from this Software without specific prior written permission.+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.diff --git a/mineru/resources/html/crossnote/SOURCE.md b/mineru/resources/html/crossnote/SOURCE.mdnew file mode 100644index 00000000..826d0f2c--- /dev/null+++ b/mineru/resources/html/crossnote/SOURCE.md@@ -0,0 +1,28 @@+# Crossnote HTML styles++These files are unmodified compiled CSS resources bundled with Markdown Preview+Enhanced (MPE) 0.8.30, which declares Crossnote 0.9.31 as an exact dependency.+They are redistributed under the University of Illinois/NCSA Open Source+License in [LICENSE.md](./LICENSE.md).++The byte-for-byte source was the installed MPE 0.8.30 extension. Paths below+are relative to the extension installation root:++| Vendored file | MPE/Crossnote distribution path | SHA-256 |+| --- | --- | --- |+| `github-light.css` | `crossnote/styles/preview_theme/github-light.css` | `020bb992e41828c9ef14f687f2a71e99e2bf6f69e32de9d1ee1e292604f0d779` |+| `style-template.css` | `crossnote/styles/style-template.css` | `054061cb501481af702df4adf8d2c224d666b6fe78a84a1c3a362e6a92cfdcdf` |+| `github.css` | `crossnote/styles/prism_theme/github.css` | `885fa37a859ef386c471e7dee272e882d09c1c600b853b6f518daf40bbd1ba02` |++The upstream CSS artifacts are minified single-line files without a trailing+newline. Keep them byte-identical so the checksums remain useful.++Upstream references:++- Crossnote release: <https://github.com/shd101wyy/crossnote/releases/tag/0.9.31>+- MPE release: <https://github.com/shd101wyy/vscode-markdown-preview-enhanced/releases/tag/0.8.30>+- MPE Marketplace package: <https://marketplace.visualstudio.com/items?itemName=shd101wyy.markdown-preview-enhanced>+- `github-light` source: <https://github.com/shd101wyy/crossnote/blob/0.9.31/styles/preview_theme/github-light.less>+- `style-template` source: <https://github.com/shd101wyy/crossnote/blob/0.9.31/styles/style-template.less>+- Prism GitHub theme source: <https://github.com/shd101wyy/crossnote/blob/0.9.31/styles/prism_theme/github.css>+- Crossnote license: <https://github.com/shd101wyy/crossnote/blob/0.9.31/LICENSE.md>diff --git a/mineru/resources/html/crossnote/github-light.css b/mineru/resources/html/crossnote/github-light.cssnew file mode 100644index 00000000..b6829470--- /dev/null+++ b/mineru/resources/html/crossnote/github-light.css@@ -0,0 +1 @@+html body{font-family:'Helvetica Neue',Helvetica,'Segoe UI',Arial,freesans,sans-serif;font-size:16px;line-height:1.6;color:#333;background-color:#fff;overflow:initial;box-sizing:border-box;word-wrap:break-word}html body>:first-child{margin-top:0}html body h1,html body h2,html body h3,html body h4,html body h5,html body h6{line-height:1.2;margin-top:1em;margin-bottom:16px;color:#000}html body h1{font-size:2.25em;font-weight:300;padding-bottom:.3em}html body h2{font-size:1.75em;font-weight:400;padding-bottom:.3em}html body h3{font-size:1.5em;font-weight:500}html body h4{font-size:1.25em;font-weight:600}html body h5{font-size:1.1em;font-weight:600}html body h6{font-size:1em;font-weight:600}html body h1,html body h2,html body h3,html body h4,html body h5{font-weight:600}html body h5{font-size:1em}html body h6{color:#5c5c5c}html body strong{color:#000}html body del{color:#5c5c5c}html body a:not([href]){color:inherit;text-decoration:none}html body a{color:#08c;text-decoration:none}html body a:hover{color:#00a3f5;text-decoration:none}html body img{max-width:100%}html body>p{margin-top:0;margin-bottom:16px;word-wrap:break-word}html body>ol,html body>ul{margin-bottom:16px}html body ol,html body ul{padding-left:2em}html body ol.no-list,html body ul.no-list{padding:0;list-style-type:none}html body ol ol,html body ol ul,html body ul ol,html body ul ul{margin-top:0;margin-bottom:0}html body li{margin-bottom:0}html body li.task-list-item{list-style:none}html body li>p{margin-top:0;margin-bottom:0}html body .task-list-item-checkbox{margin:0 .2em .25em -1.8em;vertical-align:middle}html body .task-list-item-checkbox:hover{cursor:pointer}html body blockquote{margin:16px 0;font-size:inherit;padding:0 15px;color:#5c5c5c;background-color:#f0f0f0;border-left:4px solid #d6d6d6}html body blockquote>:first-child{margin-top:0}html body blockquote>:last-child{margin-bottom:0}html body hr{height:4px;margin:32px 0;background-color:#d6d6d6;border:0 none}html body table{margin:10px 0 15px 0;border-collapse:collapse;border-spacing:0;display:block;width:100%;overflow:auto;word-break:normal;word-break:keep-all}html body table th{font-weight:700;color:#000}html body table td,html body table th{border:1px solid #d6d6d6;padding:6px 13px}html body dl{padding:0}html body dl dt{padding:0;margin-top:16px;font-size:1em;font-style:italic;font-weight:700}html body dl dd{padding:0 16px;margin-bottom:16px}html body code{font-family:Menlo,Monaco,Consolas,'Courier New',monospace;font-size:.85em;color:#000;background-color:#f0f0f0;border-radius:3px;padding:.2em 0}html body code::after,html body code::before{letter-spacing:-.2em;content:'\00a0'}html body pre>code{padding:0;margin:0;word-break:normal;white-space:pre;background:0 0;border:0}html body .highlight{margin-bottom:16px}html body .highlight pre,html body pre{padding:1em;overflow:auto;line-height:1.45;border:#d6d6d6;border-radius:3px}html body .highlight pre{margin-bottom:0;word-break:normal}html body pre code,html body pre tt{display:inline;max-width:initial;padding:0;margin:0;overflow:initial;line-height:inherit;word-wrap:normal;background-color:transparent;border:0}html body pre code:after,html body pre code:before,html body pre tt:after,html body pre tt:before{content:normal}html body blockquote,html body dl,html body ol,html body p,html body pre,html body ul{margin-top:0;margin-bottom:16px}html body kbd{color:#000;border:1px solid #d6d6d6;border-bottom:2px solid #c7c7c7;padding:2px 4px;background-color:#f0f0f0;border-radius:3px}@media print{html body{background-color:#fff}html body h1,html body h2,html body h3,html body h4,html body h5,html body h6{color:#000;page-break-after:avoid}html body blockquote{color:#5c5c5c}html body pre{page-break-inside:avoid}html body table{display:table}html body img{display:block;max-width:100%;max-height:100%}html body code,html body pre{word-wrap:break-word;white-space:pre}}\ No newline at end of filediff --git a/mineru/resources/html/crossnote/github.css b/mineru/resources/html/crossnote/github.cssnew file mode 100644index 00000000..c16c50d5--- /dev/null+++ b/mineru/resources/html/crossnote/github.css@@ -0,0 +1 @@+code[class*=language-],pre[class*=language-]{color:#333;background:0 0;font-family:Consolas,"Liberation Mono",Menlo,Courier,monospace;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.4;-moz-tab-size:8;-o-tab-size:8;tab-size:8;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]{padding:.8em;overflow:auto;border-radius:3px;background:#f5f5f5}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal;background:#f5f5f5}.token.blockquote,.token.comment{color:#969896}.token.cdata{color:#183691}.token.doctype,.token.macro.property,.token.punctuation,.token.variable{color:#333}.token.builtin,.token.important,.token.keyword,.token.operator,.token.rule{color:#a71d5d}.token.attr-value,.token.regex,.token.string,.token.url{color:#183691}.token.atrule,.token.boolean,.token.code,.token.command,.token.constant,.token.entity,.token.number,.token.property,.token.symbol{color:#0086b3}.token.prolog,.token.selector,.token.tag{color:#63a35c}.token.attr-name,.token.class,.token.class-name,.token.function,.token.id,.token.namespace,.token.pseudo-class,.token.pseudo-element,.token.url-reference .token.variable{color:#795da3}.token.entity{cursor:help}.token.title,.token.title .token.punctuation{font-weight:700;color:#1d3e81}.token.list{color:#ed6a43}.token.inserted{background-color:#eaffea;color:#55a532}.token.deleted{background-color:#ffecec;color:#bd2c00}.token.bold{font-weight:700}.token.italic{font-style:italic}.language-json .token.property{color:#183691}.language-markup .token.tag .token.punctuation{color:#333}.language-css .token.function,code.language-css{color:#0086b3}.language-yaml .token.atrule{color:#63a35c}code.language-yaml{color:#183691}.language-ruby .token.function{color:#333}.language-markdown .token.url{color:#795da3}.language-makefile .token.symbol{color:#795da3}.language-makefile .token.variable{color:#183691}.language-makefile .token.builtin{color:#0086b3}.language-bash .token.keyword{color:#0086b3}pre[data-line]{position:relative;padding:1em 0 1em 3em}pre[data-line] .line-highlight-wrapper{position:absolute;top:0;left:0;background-color:transparent;display:block;width:100%}pre[data-line] .line-highlight{position:absolute;left:0;right:0;padding:inherit 0;margin-top:1em;background:hsla(24,20%,50%,.08);background:linear-gradient(to right,hsla(24,20%,50%,.1) 70%,hsla(24,20%,50%,0));pointer-events:none;line-height:inherit;white-space:pre}pre[data-line] .line-highlight:before,pre[data-line] .line-highlight[data-end]:after{content:attr(data-start);position:absolute;top:.4em;left:.6em;min-width:1em;padding:0 .5em;background-color:hsla(24,20%,50%,.4);color:#f4f1ef;font:bold 65%/1.5 sans-serif;text-align:center;vertical-align:.3em;border-radius:999px;text-shadow:none;box-shadow:0 1px #fff}pre[data-line] .line-highlight[data-end]:after{content:attr(data-end);top:auto;bottom:.4em}\ No newline at end of filediff --git a/mineru/resources/html/crossnote/style-template.css b/mineru/resources/html/crossnote/style-template.cssnew file mode 100644index 00000000..6087c80a--- /dev/null+++ b/mineru/resources/html/crossnote/style-template.css@@ -0,0 +1 @@+.markdown-preview{width:100%;height:100%;box-sizing:border-box}.markdown-preview ul{list-style:disc}.markdown-preview ul ul{list-style:circle}.markdown-preview ul ul ul{list-style:square}.markdown-preview ol{list-style:decimal}.markdown-preview ol ol,.markdown-preview ul ol{list-style-type:lower-roman}.markdown-preview ol ol ol,.markdown-preview ol ul ol,.markdown-preview ul ol ol,.markdown-preview ul ul ol{list-style-type:lower-alpha}.markdown-preview .newpage,.markdown-preview .pagebreak{page-break-before:always}.markdown-preview pre.line-numbers{position:relative;padding-left:3.8em;counter-reset:linenumber}.markdown-preview pre.line-numbers>code{position:relative}.markdown-preview pre.line-numbers .line-numbers-rows{position:absolute;pointer-events:none;top:1em;font-size:100%;left:0;width:3em;letter-spacing:-1px;border-right:1px solid #999;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.markdown-preview pre.line-numbers .line-numbers-rows>span{pointer-events:none;display:block;counter-increment:linenumber}.markdown-preview pre.line-numbers .line-numbers-rows>span:before{content:counter(linenumber);color:#999;display:block;padding-right:.8em;text-align:right}.markdown-preview .mathjax-exps .MathJax_Display{text-align:center!important}.markdown-preview:not([data-for=preview]) .code-chunk .code-chunk-btn-group{display:none}.markdown-preview:not([data-for=preview]) .code-chunk .status{display:none}.markdown-preview:not([data-for=preview]) .code-chunk .output-div{margin-bottom:16px}.markdown-preview .md-toc{padding:0}.markdown-preview .md-toc .md-toc-details{margin:0;padding:0;border:none}.markdown-preview .md-toc summary.md-toc-link-wrapper{cursor:pointer;list-style-position:outside}.markdown-preview .md-toc summary.md-toc-link-wrapper::marker{font-size:.85em}.markdown-preview .md-toc .md-toc-link-wrapper .md-toc-link{display:inline;padding:.25rem 0}.markdown-preview .md-toc .md-toc-link-wrapper .md-toc-link div,.markdown-preview .md-toc .md-toc-link-wrapper .md-toc-link p{display:inline}.markdown-preview .md-toc .md-toc-link-wrapper.highlighted .md-toc-link{font-weight:800}.markdown-preview .md-toc .md-toc-link-wrapper[data-level='0']{margin-left:12px}.markdown-preview .md-toc .md-toc-link-wrapper[data-level='1']{margin-left:28px}.markdown-preview .md-toc .md-toc-link-wrapper[data-level='2']{margin-left:44px}.markdown-preview .md-toc .md-toc-link-wrapper[data-level='3']{margin-left:60px}.markdown-preview .md-toc .md-toc-link-wrapper[data-level='4']{margin-left:76px}.markdown-preview .md-toc .md-toc-link-wrapper[data-level='5']{margin-left:80px}.markdown-preview a.tag,.markdown-preview a.tag:active,.markdown-preview a.tag:link,.markdown-preview a.tag:visited,.markdown-preview span.tag:not(.token){display:inline-block;background-color:var(--vscode-badge-background,rgba(127,127,127,.18));color:var(--vscode-badge-foreground,currentColor);border-radius:2em;font-size:.85em;font-weight:500;padding:.05em .55em;line-height:1.5;white-space:nowrap;text-decoration:none;text-shadow:none;box-shadow:none;transition:background-color .12s ease,opacity .12s ease}.markdown-preview a.tag{cursor:pointer}.markdown-preview a.tag:focus,.markdown-preview a.tag:hover{background-color:var(--vscode-badge-background,rgba(127,127,127,.32));color:var(--vscode-badge-foreground,currentColor);opacity:.85;text-decoration:none;outline:0}.markdown-preview .wikilink-embed-content{border-left:3px solid var(--vscode-textBlockQuote-border,rgba(128,128,128,.3));background:var(--vscode-textBlockQuote-background,rgba(128,128,128,.05));margin:.5em 0;padding:.5em .75em;border-radius:0 3px 3px 0}.markdown-preview .wikilink-embed-content.wikilink-embed-error{border-left-color:var(--vscode-errorForeground,#cf222e);color:var(--vscode-errorForeground,#cf222e);font-style:italic;opacity:.8}.markdown-preview .wikilink-embed-content h1:first-child,.markdown-preview .wikilink-embed-content h2:first-child,.markdown-preview .wikilink-embed-content h3:first-child,.markdown-preview .wikilink-embed-content h4:first-child,.markdown-preview .wikilink-embed-content h5:first-child,.markdown-preview .wikilink-embed-content h6:first-child{margin-top:.25em}.markdown-preview .wikilink-embed-content .wikilink-embed-content{margin:.25em 0;padding:.25em .5em}.markdown-preview .block-id{display:none}.scrollbar-style::-webkit-scrollbar{width:8px}.scrollbar-style::-webkit-scrollbar-track{border-radius:10px;background-color:transparent}.scrollbar-style::-webkit-scrollbar-thumb{border-radius:5px;background-color:var(--vscode-scrollbarSlider-background,rgba(150,150,150,.66));border:4px solid var(--vscode-scrollbarSlider-background,rgba(150,150,150,.66));background-clip:content-box}.scrollbar-style::-webkit-scrollbar-thumb:hover{background-color:var(--vscode-scrollbarSlider-hoverBackground,rgba(120,120,120,.66))}html body[for=html-export]:not([data-presentation-mode]){position:relative;width:100%;height:100%;top:0;left:0;margin:0;padding:0;overflow:auto}html body[for=html-export]:not([data-presentation-mode]) .markdown-preview{position:relative;top:0;min-height:100vh}@media screen and (min-width:914px){html body[for=html-export]:not([data-presentation-mode]) .markdown-preview{padding:2em calc(50% - 457px + 2em)}}@media screen and (max-width:914px){html body[for=html-export]:not([data-presentation-mode]) .markdown-preview{padding:2em}}@media screen and (max-width:450px){html body[for=html-export]:not([data-presentation-mode]) .markdown-preview{font-size:14px!important;padding:1em}}@media print{html body[for=html-export]:not([data-presentation-mode]) #sidebar-toc-btn{display:none}}html body[for=html-export]:not([data-presentation-mode]) #sidebar-toc-btn{position:fixed;bottom:8px;left:8px;font-size:28px;cursor:pointer;color:inherit;z-index:99;width:32px;text-align:center;opacity:.4}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] #sidebar-toc-btn{opacity:1}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc{position:fixed;top:0;left:0;width:300px;height:100%;padding:32px 0 48px 0;font-size:14px;box-shadow:0 0 4px rgba(150,150,150,.33);box-sizing:border-box;overflow:auto;background-color:inherit}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar{width:8px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar-track{border-radius:10px;background-color:transparent}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar-thumb{border-radius:5px;background-color:var(--vscode-scrollbarSlider-background,rgba(150,150,150,.66));border:4px solid var(--vscode-scrollbarSlider-background,rgba(150,150,150,.66));background-clip:content-box}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc::-webkit-scrollbar-thumb:hover{background-color:var(--vscode-scrollbarSlider-hoverBackground,rgba(120,120,120,.66))}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc a{text-decoration:none}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc{padding:0 16px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-details{margin:0;padding:0;border:none}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper .md-toc-link{display:inline;padding:.25rem 0}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper .md-toc-link div,html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper .md-toc-link p{display:inline}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper.highlighted .md-toc-link{font-weight:800}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper[data-level='0']{padding-left:0}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper[data-level='1']{padding-left:16px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper[data-level='2']{padding-left:32px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper[data-level='3']{padding-left:48px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper[data-level='4']{padding-left:64px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .md-sidebar-toc .md-toc .md-toc-link-wrapper[data-level='5']{padding-left:80px}html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview{left:300px;width:calc(100% - 300px);padding:2em calc(50% - 457px - 300px / 2);margin:0;box-sizing:border-box}@media screen and (max-width:1274px){html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview{padding:2em}}@media screen and (max-width:450px){html body[for=html-export]:not([data-presentation-mode])[html-show-sidebar-toc] .markdown-preview{width:100%}}html body[for=html-export]:not([data-presentation-mode]):not([html-show-sidebar-toc]) .markdown-preview{left:50%;transform:translateX(-50%)}html body[for=html-export]:not([data-presentation-mode]):not([html-show-sidebar-toc]) .md-sidebar-toc{display:none}\ No newline at end of filediff --git a/mineru/resources/html/mineru.css b/mineru/resources/html/mineru.cssnew file mode 100644index 00000000..248ea7ab--- /dev/null+++ b/mineru/resources/html/mineru.css@@ -0,0 +1,246 @@+/* MinerU HTML 渲染器补充样式;除打印页边距外均限定在文档根节点内。 */+.mineru-document {+ box-sizing: border-box;+}++.mineru-document *,+.mineru-document *::before,+.mineru-document *::after {+ box-sizing: inherit;+}++/* FULL 模式保留页面边界,空页也应维持可见的页面容器。 */+.mineru-document .mineru-page {+ min-width: 0;+ position: relative;+}++.mineru-document--full .mineru-page {+ min-height: 1.5rem;+}++.mineru-document .mineru-page-break {+ background: transparent;+ border: 0;+ border-top: 1px dashed #d0d7de;+ height: 0;+ margin: 2rem 0;+}++/* 图片、表格、图表及其说明沿用同一视觉容器。 */+.mineru-document .mineru-figure,+.mineru-document figure[data-block-type] {+ margin: 1.5rem 0;+ max-width: 100%;+}++.mineru-document .mineru-figure > img,+.mineru-document figure[data-block-type] > img {+ display: block;+ height: auto;+ margin-inline: auto;+ max-width: 100%;+}++.mineru-document .mineru-caption,+.mineru-document figcaption {+ color: #57606a;+ font-size: 0.9em;+ margin-top: 0.5rem;+ text-align: center;+}++.mineru-document .mineru-footnote {+ color: #57606a;+ font-size: 0.875em;+ margin-top: 0.4rem;+}++.mineru-document .mineru-details,+.mineru-document details[data-block-type] {+ border: 1px solid #d0d7de;+ border-radius: 6px;+ margin: 1rem 0;+ padding: 0.65rem 0.85rem;+}++.mineru-document .mineru-details > summary,+.mineru-document details[data-block-type] > summary {+ cursor: pointer;+ font-weight: 600;+}++/* 非标准或混合列表标记由渲染器显式输出,避免浏览器重新编号。 */+.mineru-document .mineru-list--explicit {+ list-style: none;+ padding-left: 1.5rem;+}++.mineru-document .mineru-list--unmarked {+ list-style: none;+}++.mineru-document .mineru-list-item--explicit {+ align-items: start;+ display: grid;+ gap: 0.5em;+ grid-template-columns: max-content minmax(0, 1fr);+}++.mineru-document .mineru-list-marker {+ font-variant-numeric: tabular-nums;+ text-align: right;+ user-select: none;+ white-space: pre;+}++.mineru-document .mineru-list-item--orphan {+ list-style: none;+}++.mineru-document .mineru-list-item--markerless {+ list-style: none;+}++.mineru-document .mineru-list-item--orphan > .mineru-list-marker {+ visibility: hidden;+}++.mineru-document .mineru-list-item--orphan > :is(ol, ul),+.mineru-document .mineru-list-item--explicit > :is(ol, ul) {+ grid-column: 2;+ margin-bottom: 0;+}++/* 目录不显示普通列表项目符号,并为长标题保留可换行空间。 */+.mineru-document .mineru-index,+.mineru-document .mineru-index ul {+ list-style: none;+ padding-left: 0;+}++.mineru-document .mineru-index ul ul {+ padding-left: 1.5rem;+}++.mineru-document .mineru-index a {+ overflow-wrap: anywhere;+}++/* MathJax 接管前保留可见 TeX;块公式允许横向滚动。 */+.mineru-document .mineru-math {+ overflow-wrap: anywhere;+}++.mineru-document .mineru-math--block {+ display: block;+ margin: 1rem 0;+ max-width: 100%;+ overflow-x: auto;+ overflow-y: hidden;+ text-align: center;+}++.mineru-document .mineru-preserve-whitespace {+ white-space: pre-wrap;+}++.mineru-document .mineru-text-emphasis {+ -webkit-text-emphasis: dot;+ -webkit-text-emphasis-position: under right;+ text-emphasis: dot;+ text-emphasis-position: under right;+}++.mineru-document :is(th, td).mineru-align-left {+ text-align: left;+}++.mineru-document :is(th, td).mineru-align-center {+ text-align: center;+}++.mineru-document :is(th, td).mineru-align-right {+ text-align: right;+}++.mineru-document mjx-container[display="true"] {+ max-width: 100%;+ overflow-x: auto;+ overflow-y: hidden;+}++/* 空间投影表格和不可解析原文必须保持空白与换行。 */+.mineru-document .mineru-table-text,+.mineru-document .mineru-raw-fallback {+ overflow: auto;+ tab-size: 4;+ white-space: pre-wrap;+ word-break: break-word;+}++.mineru-document .mineru-table-text {+ white-space: pre;+}++.mineru-document .mineru-raw-fallback {+ border-left: 3px solid #d0d7de;+ color: #57606a;+}++/* 算法文本保留缩进,同时允许行内公式和上下标参与排版。 */+.mineru-document .mineru-algorithm {+ font-family: Menlo, Monaco, Consolas, "Courier New", monospace;+ max-width: 100%;+ overflow-x: auto;+ tab-size: 4;+ white-space: pre-wrap;+ word-break: normal;+}++/* Prism 异步加载语言组件时,补充少量通用 token 表现。 */+.mineru-document pre[class*="language-"] {+ max-width: 100%;+}++.mineru-document pre[class*="language-"] > code {+ text-shadow: none;+}++.mineru-document .token.namespace {+ opacity: 0.75;+}++.mineru-document .token.important {+ font-weight: 700;+}++@media print {+ body[for="html-export"] {+ margin: 0;+ }++ .mineru-document {+ max-width: none;+ }++ .mineru-document .mineru-page-break {+ display: none;+ }++ .mineru-document--full .mineru-page {+ break-after: page;+ page-break-after: always;+ }++ .mineru-document--full .mineru-page:last-child {+ break-after: auto;+ page-break-after: auto;+ }++ .mineru-document .mineru-figure,+ .mineru-document figure[data-block-type] {+ break-inside: avoid;+ page-break-inside: avoid;+ }+}diff --git a/pyproject.toml b/pyproject.tomlindex c91710fd..605366b8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -52,6 +52,7 @@ dependencies = ["fast-langdetect>=0.2.3,<0.3.0","openai>=1.70.0,<3","beautifulsoup4>=4.13.5,<5",+ "nh3>=0.3.6,<0.4","magika>=0.6.2,<1.1.0","mineru-vl-utils>=1.2.1,<2","python-docx>=1.2.0,<2",diff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.pynew file mode 100644index 00000000..ff12122d--- /dev/null+++ b/tests/unittest/test_html_render.py@@ -0,0 +1,609 @@+from __future__ import annotations++from copy import deepcopy+from hashlib import sha256+from importlib import resources++from bs4 import BeautifulSoup+import pytest++from mineru.render import RenderMode, render_html+from mineru.types import (+ ChartAnnotationBlock,+ ChartBlock,+ ChartBodyBlock,+ CodeAnnotationBlock,+ CodeBlock,+ CodeBodyBlock,+ DocTitleBlock,+ EquationBlock,+ ImageBlock,+ IndexBlock,+ ListBlock,+ MiddleJson,+ PageAuxTextBlock,+ PageBlock,+ PageInfo,+ ParagraphTitleBlock,+ RefTextBlock,+ TableBlock,+ TableBodyBlock,+ TextBlock,+)++_PNG_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl2l9sAAAAASUVORK5CYII="+++def _middle(*pages: PageInfo) -> MiddleJson:+ """构造无需 PDF bbox 的严格 Office MiddleJson。"""+ return MiddleJson(+ pages=list(pages),+ 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 _list(index: int, *items: str, sub_type: str | None = None) -> ListBlock:+ """构造普通或参考文献列表。"""+ child_class = RefTextBlock if sub_type == "ref_text" else TextBlock+ return ListBlock(+ type="list",+ index=index,+ sub_type=sub_type,+ content=[child_class(type=sub_type or "text", content=item) for item in items],+ )+++def test_public_contract_fragment_standalone_title_and_input_immutability() -> None:+ """验证严格公共参数、双输出形态、标题回退和输入无副作用。"""+ middle = _middle(+ _page(+ 0,+ DocTitleBlock(+ type="doc_title",+ index=0,+ level=1,+ content='<text style="bold">Demo</text> <unsafe>',+ ),+ TextBlock(type="text", index=1, content="body"),+ )+ )+ original = deepcopy(middle)++ fragment = render_html(middle, standalone=False)+ standalone = render_html(middle)++ assert fragment.startswith('<article class="crossnote markdown-preview mineru-document')+ assert fragment in standalone+ assert '<html lang="und">' in standalone+ assert "<title>Demo <unsafe></title>" in standalone+ assert '<body for="html-export">' in standalone+ assert "<style>" in standalone+ assert "Crossnote 0.9.31 CSS license notice" in standalone+ assert "mathjax@" not in standalone+ assert "prismjs@" not in standalone+ assert middle == original++ explicit = render_html(middle, document_title="A </title><script>x</script>")+ assert "<title>A </title><script>x</script></title>" in explicit++ with pytest.raises(TypeError, match="MiddleJson"):+ render_html({}) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="RenderMode"):+ render_html(middle, mode="default") # type: ignore[arg-type]+ with pytest.raises(TypeError, match="standalone"):+ render_html(middle, standalone=1) # type: ignore[arg-type]+++def test_default_and_full_modes_preserve_their_page_contracts() -> None:+ """验证 DEFAULT 连续阅读与 FULL 空页、辅助块和页面分隔。"""+ middle = _middle(+ _page(+ 0,+ PageAuxTextBlock(type="header", index=0, content="HEADER"),+ TextBlock(type="text", index=1, content="inter-"),+ ),+ _page(5),+ _page(+ 9,+ TextBlock(type="text", index=0, content="national", continues_prev=True),+ PageAuxTextBlock(type="footer", index=1, content="FOOTER"),+ ),+ )++ default = BeautifulSoup(render_html(middle, standalone=False), "html.parser")+ full = BeautifulSoup(render_html(middle, mode=RenderMode.FULL, standalone=False), "html.parser")++ assert default.select_one(".mineru-text").get_text() == "international"+ assert default.select_one('[data-block-type="text"]')["data-page-idx"] == "0"+ assert not default.select(".mineru-page")+ assert "HEADER" not in default.get_text()++ assert [section["data-page-idx"] for section in full.select(".mineru-page")] == ["0", "5", "9"]+ assert len(full.select(".mineru-page-break")) == 2+ assert [item.get_text() for item in full.select(".mineru-text")] == ["inter-", "national"]+ assert "HEADER" in full.get_text() and "FOOTER" in full.get_text()+++def test_inline_html_escapes_plain_text_and_renders_styles_links_and_math() -> None:+ """验证普通尖括号、富样式、安全链接及 MathJax carrier。"""+ content = (+ 'p <0.05 <local_dir> <text style="bold,italic,underline"> styled </text> '+ "<hyperlink>safe<url>https://example.test/a b</url></hyperlink> "+ "<hyperlink>bad<url>javascript:alert(1)</url></hyperlink> "+ "<eq>x < y & z</eq>"+ )+ result = render_html(_middle(_page(0, TextBlock(type="text", index=0, content=content))))+ soup = BeautifulSoup(result, "html.parser")++ paragraph = soup.select_one(".mineru-text")+ assert "p <0.05 <local_dir>" in paragraph.get_text()+ assert paragraph.select_one("em strong u") is not None+ assert paragraph.select_one(".mineru-preserve-whitespace") is not None+ assert paragraph.select_one('a[href="https://example.test/a%20b"]') is not None+ assert "bad" in paragraph.get_text()+ assert "javascript:" not in result+ assert paragraph.select_one(".mineru-math").get_text() == r"\(x < y & z\)"+ assert "[email protected]/tex-chtml.js" in result+ assert "loader: {load: ['ui/safe']}" in result+ assert "ignoreHtmlClass: 'mineru-document'" in result+ assert "packages: {'[-]': ['require']}" in result+++def test_formula_body_closing_delimiters_are_neutralized_before_mathjax_scanning() -> None:+ """验证公式体内的结束定界符改写为等价 TeX,不会提前闭合 carrier。"""+ middle = _middle(+ _page(+ 0,+ TextBlock(type="text", index=0, content=r"inline <eq>x\)y</eq>"),+ EquationBlock(type="equation", index=1, content=r"x\]y"),+ )+ )+ soup = BeautifulSoup(render_html(middle, standalone=False), "html.parser")++ assert soup.select_one(".mineru-math--inline").get_text() == r"\(x\mathclose{)}y\)"+ assert soup.select_one(".mineru-math--block").get_text().replace("\n", "") == r"\[x\mathclose{]}y\]"+++def test_lists_cover_native_explicit_reference_nested_and_orphan_shapes() -> None:+ """验证列表分类、非连续编号、显式 marker、参考文献和嵌套归属。"""+ ordered = _list(0, "1. first", "3. third")+ alpha = _list(1, "a. alpha", "b. beta")+ explicit = _list(2, "(1) one", "[x] done", "plain")+ mixed = _list(6, "1. one", "- two", "plain")+ reference = _list(3, "[1] first", "Author A", sub_type="ref_text")+ nested = ListBlock(+ type="list",+ index=4,+ content=[+ TextBlock(type="text", content="- parent"),+ ListBlock(type="list", content=[TextBlock(type="text", content="- child")]),+ ],+ )+ orphan = ListBlock(+ type="list",+ index=5,+ content=[ListBlock(type="list", content=[TextBlock(type="text", content="- orphan")])],+ )+ markerless_owner = ListBlock(+ type="list",+ index=7,+ content=[+ TextBlock(type="text", content="1. visible"),+ TextBlock(type="text", content=""),+ ListBlock(type="list", content=[TextBlock(type="text", content="- nested owner")]),+ ],+ )+ soup = BeautifulSoup(+ render_html(+ _middle(_page(0, ordered, alpha, explicit, reference, nested, orphan, mixed, markerless_owner)),+ standalone=False,+ ),+ "html.parser",+ )++ ordered_html = soup.select('[data-block-index="0"] ol')[0]+ assert ordered_html.find_all("li", recursive=False)[1]["value"] == "3"+ assert ordered_html.get_text(" ", strip=True) == "first third"+ assert soup.select_one('[data-block-index="1"] ol')["type"] == "a"+ assert [marker.get_text() for marker in soup.select('[data-block-index="2"] .mineru-list-marker')] == [+ "(1)",+ "[x]",+ "",+ ]+ assert "[1] first" in soup.select_one('[data-block-index="3"] li').get_text()+ parent_item = soup.select_one('[data-block-index="4"] > .mineru-list > li')+ assert parent_item.find("ul", recursive=False) is not None+ assert soup.select_one('[data-block-index="5"] .mineru-list-item--orphan') is not None+ assert [marker.get_text() for marker in soup.select('[data-block-index="6"] .mineru-list-marker')] == [+ "1.",+ "-",+ "",+ ]+ assert soup.select_one('[data-block-index="7"] .mineru-list-item--markerless > ul') is not None+++def test_index_uses_real_forward_anchor_and_omits_duplicate_ids() -> None:+ """验证目录前向链接、页码尾清理、嵌套目录及重复 anchor 首项生效。"""+ index = IndexBlock(+ type="index",+ index=0,+ content=[+ ParagraphTitleBlock(type="paragraph_title", level=2, anchor="sec 1", content="Section\t3"),+ IndexBlock(+ type="index",+ content=[ParagraphTitleBlock(type="paragraph_title", level=3, anchor="missing", content="Missing\tiv")],+ ),+ ],+ )+ first = ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="sec 1", content="Section")+ duplicate = ParagraphTitleBlock(type="paragraph_title", index=2, level=9, anchor="sec 1", content="Duplicate")+ soup = BeautifulSoup(render_html(_middle(_page(0, index, first, duplicate)), standalone=False), "html.parser")++ assert soup.select_one('.mineru-index a[href="#sec-1"]').get_text() == "Section"+ assert "3" not in soup.select_one(".mineru-index").get_text()+ assert soup.select_one(".mineru-index li ul") is not None+ assert soup.select_one(".mineru-index li ul a") is None+ assert len(soup.select('[id="sec-1"]')) == 1+ assert soup.find("h6", attrs={"data-heading-level": "9"}).get_text() == "Duplicate"+++def test_empty_title_does_not_create_a_broken_index_target_and_anchor_controls_are_normalized() -> None:+ """验证空正文标题不成为链接目标,控制字符在 id/href 两侧一致归一化。"""+ index = IndexBlock(+ type="index",+ index=0,+ content=[+ ParagraphTitleBlock(type="paragraph_title", level=2, anchor="empty", content="Empty"),+ ParagraphTitleBlock(type="paragraph_title", level=2, anchor="bad\x00id", content="Good"),+ ParagraphTitleBlock(type="paragraph_title", level=2, anchor="bad\ufffdid", content="Collision"),+ ],+ )+ empty = ParagraphTitleBlock(type="paragraph_title", index=1, level=2, anchor="empty", content="")+ good = ParagraphTitleBlock(type="paragraph_title", index=2, level=2, anchor="bad\x00id", content="Good")+ collision = ParagraphTitleBlock(+ type="paragraph_title",+ index=3,+ level=2,+ anchor="bad\ufffdid",+ content="Collision",+ )+ soup = BeautifulSoup(+ render_html(_middle(_page(0, index, empty, good, collision)), standalone=False),+ "html.parser",+ )++ links = soup.select(".mineru-index a")+ assert len(links) == 2+ assert links[0]["href"] == "#bad%EF%BF%BDid"+ assert links[1]["href"] == "#bad%EF%BF%BDid-2"+ assert soup.find(id="bad\ufffdid") is not None+ assert soup.find(id="bad\ufffdid-2") is not None+++def test_empty_index_leaf_owns_its_following_nested_index() -> None:+ """验证空目录叶子的 nested ul 不会错误挂到更早的可见目录项。"""+ index = IndexBlock(+ type="index",+ index=0,+ content=[+ TextBlock(type="text", content="visible"),+ TextBlock(type="text", content=""),+ IndexBlock(type="index", content=[TextBlock(type="text", content="nested")]),+ ],+ )+ soup = BeautifulSoup(render_html(_middle(_page(0, index)), standalone=False), "html.parser")+ top_items = soup.select(".mineru-index > ul > li")++ assert len(top_items) == 2+ assert top_items[0].find("ul", recursive=False) is None+ assert top_items[1].find("ul", recursive=False).get_text(strip=True) == "nested"+++def test_visual_child_order_image_details_and_asset_precedence() -> None:+ """验证视觉说明顺序、图片路径优先级、URL 编码与识别内容 details。"""+ image = ImageBlock.model_validate(+ {+ "type": "image",+ "index": 0,+ "sub_type": "diagram",+ "content": [+ {"type": "image_caption", "content": "before"},+ {+ "type": "image_body",+ "index": 0,+ "content": "description <eq>x</eq>",+ "image_path": "images/a b.png",+ "image_base64": _PNG_URI,+ },+ {"type": "image_footnote", "content": "after"},+ {"type": "image_caption", "content": "again"},+ ],+ }+ )+ rendered = render_html(+ _middle(_page(0, image)),+ asset_base_url="https://cdn.example/doc",+ standalone=False,+ )+ soup = BeautifulSoup(rendered, "html.parser")++ assert rendered.index("before") < rendered.index("images/a%20b.png") < rendered.index("after") < rendered.index("again")+ assert soup.select_one("img")["src"] == "https://cdn.example/doc/images/a%20b.png"+ assert "data:image" not in rendered+ assert soup.select_one("details .mineru-math") is not None+ assert len(soup.select(".mineru-caption")) == 2+++def test_table_keeps_safe_html_and_spatial_or_image_fallbacks() -> None:+ """验证原生表格、公式、危险属性清理、空间文本和不可用表格图片回退。"""+ html_table = TableBlock(+ type="table",+ index=0,+ content=[+ TableBodyBlock(+ type="table_body",+ index=0,+ content=(+ '<table border="1"><tr><td rowspan="2" onclick="bad()">'+ "<eq>x<y</eq><table><tr><td>N</td></tr></table></td></tr></table>"+ ),+ )+ ],+ )+ spatial = TableBlock(+ type="table",+ index=1,+ content=[TableBodyBlock(type="table_body", index=1, content="A < B\nC D")],+ )+ invalid = TableBlock(+ type="table",+ index=2,+ content=[TableBodyBlock(type="table_body", index=2, content="<table></table>", image_base64=_PNG_URI)],+ )+ soup = BeautifulSoup(render_html(_middle(_page(0, html_table, spatial, invalid)), standalone=False), "html.parser")++ assert len(soup.select('[data-block-index="0"] table')) == 2+ cell = soup.select_one('[data-block-index="0"] td')+ assert cell["rowspan"] == "2"+ assert "onclick" not in cell.attrs and "border" not in soup.select_one("table").attrs+ assert cell.select_one(".mineru-math") is not None+ assert soup.select_one('[data-block-index="1"] .mineru-table-text').get_text() == "A < B\nC D"+ assert soup.select_one('[data-block-index="2"] img')["src"].startswith("data:image/png")+++def test_discarded_invalid_table_math_does_not_load_mathjax() -> None:+ """验证无单元格表格回退图片后,已丢弃的 eq 不会误触发 MathJax。"""+ table = TableBlock(+ type="table",+ index=0,+ content=[+ TableBodyBlock(+ type="table_body",+ index=0,+ content="<table><eq>x</eq></table>",+ image_base64=_PNG_URI,+ )+ ],+ )+ rendered = render_html(_middle(_page(0, table)))++ assert BeautifulSoup(rendered, "html.parser").select_one("article .mineru-math") is None+ assert "mathjax@" not in rendered+ assert "data:image/png" in rendered+++def test_chart_gfm_details_code_prism_and_algorithm_html() -> None:+ """验证严格 chart GFM、图片 details、Prism Autoloader 和算法转义。"""+ chart = ChartBlock(+ type="chart",+ index=0,+ sub_type="line chart",+ content=[+ ChartAnnotationBlock(type="chart_caption", content="chart before"),+ ChartBodyBlock(+ type="chart_body",+ index=0,+ image_path="images/chart.png",+ content="| A | B |\n| :--- | ---: |\n| 1 | 2 |",+ ),+ ],+ )+ code = CodeBlock(+ type="code",+ index=1,+ sub_type="code",+ guess_lang="shell",+ content=[+ CodeBodyBlock(type="code_body", index=1, content='echo "<x>"\n'),+ CodeAnnotationBlock(type="code_footnote", content="code after"),+ ],+ )+ algorithm = CodeBlock(+ type="code",+ index=2,+ sub_type="algorithm",+ content=[+ CodeBodyBlock(+ type="code_body",+ index=2,+ content="if a < b:\n T<sub>q</sub> = <eq>x</eq><eq>y</eq>",+ )+ ],+ )+ result = render_html(_middle(_page(0, chart, code, algorithm)))+ soup = BeautifulSoup(result, "html.parser")++ assert soup.select_one("details .mineru-chart-table") is not None+ assert soup.select_one("th.mineru-align-left") is not None+ assert soup.select_one("th.mineru-align-right") is not None+ assert soup.select_one("pre.language-bash code.language-bash").get_text() == 'echo "<x>"\n'+ assert "[email protected]/components/prism-core.min.js" in result+ assert "[email protected]/plugins/autoloader/prism-autoloader.min.js" in result+ assert "Prism.highlightAllUnder(root)" in result+ assert "sha384-zLRFO4dw" in result and "sha384-Uq05+JLk" in result+ algorithm_html = soup.select_one(".mineru-algorithm")+ assert "if a < b:" in algorithm_html.get_text()+ assert algorithm_html.select_one("sub").get_text() == "q"+ assert len(algorithm_html.select(".mineru-math")) == 2+ assert r"\(x\) \(y\)" in algorithm_html.get_text()+ assert "<br" not in str(algorithm_html)+ assert "if a < b:\n " in str(algorithm_html)++[email protected]("guess_lang", ["python bad/../../x", "constructor", "prototype", "__proto__"])+def test_invalid_code_language_remains_visible_without_loading_prism(guess_lang: str) -> None:+ """验证非法语言名不会进入 class 或 CDN 组件路径。"""+ code = CodeBlock(+ type="code",+ index=0,+ sub_type="code",+ guess_lang=guess_lang,+ content=[CodeBodyBlock(type="code_body", index=0, content="<script>x</script>")],+ )+ result = render_html(_middle(_page(0, code)))+ soup = BeautifulSoup(result, "html.parser")++ assert soup.select_one("code").get_text() == "<script>x</script>"+ assert not soup.select_one("code").get("class")+ assert "prismjs@" not in result+ assert "<script>x</script>" not in result+++def test_empty_code_and_literal_class_text_do_not_load_external_runtimes() -> None:+ """验证空代码和普通文本中的 class 字样不会误触发 Prism 或 MathJax。"""+ middle = _middle(+ _page(+ 0,+ TextBlock(type="text", index=0, content='class="mineru-math fake" class="language-python"'),+ CodeBlock(+ type="code",+ index=1,+ sub_type="code",+ guess_lang="python",+ content=[CodeBodyBlock(type="code_body", index=1, content="")],+ ),+ )+ )+ rendered = render_html(middle)++ assert "mathjax@" not in rendered+ assert "prismjs@" not in rendered+ assert '<pre class="mineru-code"><code></code></pre>' in rendered+++def test_crlf_and_cr_are_normalized_to_visible_line_breaks() -> None:+ """验证 CRLF 与 CR 统一为两个可见 HTML 换行。"""+ rendered = render_html(+ _middle(_page(0, TextBlock(type="text", index=0, content="one\r\ntwo\rthree"))),+ standalone=False,+ )+ paragraph = BeautifulSoup(rendered, "html.parser").select_one(".mineru-text")++ assert len(paragraph.find_all("br")) == 2+ assert paragraph.get_text("|", strip=True) == "one|two|three"+++def test_invalid_html_characters_are_replaced_and_output_remains_utf8_encodable() -> None:+ """验证普通文本、代码、anchor 和富 HTML 中的控制字符与 surrogate 可见降级。"""+ middle = _middle(+ _page(+ 0,+ ParagraphTitleBlock(type="paragraph_title", index=0, level=2, anchor="a\ud800", content="T\x01"),+ TextBlock(type="text", index=1, content="body\udfff"),+ CodeBlock(+ type="code",+ index=2,+ sub_type="code",+ guess_lang="txt",+ content=[CodeBodyBlock(type="code_body", index=2, content="code\ud800\x02")],+ ),+ ChartBlock(+ type="chart",+ index=3,+ content=[ChartBodyBlock(type="chart_body", index=3, content="<p>chart\udfff\x03</p>")],+ ),+ TableBlock(+ type="table",+ index=4,+ content=[TableBodyBlock(type="table_body", index=4, content="table\ud800\x04")],+ ),+ )+ )+ rendered = render_html(middle)++ rendered.encode("utf-8")+ assert "\ud800" not in rendered and "\udfff" not in rendered+ assert rendered.count("\ufffd") >= 6+++def test_setext_heading_shape_is_not_misclassified_as_a_gfm_chart_table() -> None:+ """验证缺少 pipe 的 Setext 标题形态按普通 chart 文本输出。"""+ chart = ChartBlock(+ type="chart",+ index=0,+ content=[ChartBodyBlock(type="chart_body", index=0, content="Title\n---\nbody")],+ )+ soup = BeautifulSoup(render_html(_middle(_page(0, chart)), standalone=False), "html.parser")++ assert soup.select_one(".mineru-chart-table") is None+ assert soup.select_one(".mineru-figure--chart").get_text(" ", strip=True) == "Title --- body"+++ ("slash_count", "expected"),+ [(1, "|"), (2, "|"), (3, r"\|"), (4, r"\|"), (5, r"\\|")],+)+def test_chart_gfm_pipe_matches_markdown_it_backslash_decoding(slash_count: int, expected: str) -> None:+ """验证任意相邻反斜杠都保护列内 pipe,并与 markdown-it 解码结果一致。"""+ chart = ChartBlock(+ type="chart",+ index=0,+ content=[+ ChartBodyBlock(+ type="chart_body",+ index=0,+ content="| Formula |\n| --- |\n| " + "\\" * slash_count + "| |",+ )+ ],+ )+ soup = BeautifulSoup(render_html(_middle(_page(0, chart)), standalone=False), "html.parser")++ assert soup.select_one(".mineru-chart-table td").get_text() == expected+++def test_crossnote_resources_are_byte_exact_and_packaged_with_license() -> None:+ """验证三份上游 CSS 字节、来源声明及 NCSA 许可证随包存在。"""+ root = resources.files("mineru").joinpath("resources", "html", "crossnote")+ expected = {+ "github-light.css": "020bb992e41828c9ef14f687f2a71e99e2bf6f69e32de9d1ee1e292604f0d779",+ "style-template.css": "054061cb501481af702df4adf8d2c224d666b6fe78a84a1c3a362e6a92cfdcdf",+ "github.css": "885fa37a859ef386c471e7dee272e882d09c1c600b853b6f518daf40bbd1ba02",+ }++ for name, digest in expected.items():+ assert sha256(root.joinpath(name).read_bytes()).hexdigest() == digest+ assert "University of Illinois/NCSA" in root.joinpath("LICENSE.md").read_text(encoding="utf-8")+ assert sha256(root.joinpath("LICENSE.md").read_bytes()).hexdigest() == (+ "a0459e70cef4048eba8c05562387fb05913ad8bbc67904ac866edded85e9d073"+ )+ source = root.joinpath("SOURCE.md").read_text(encoding="utf-8")+ assert "Crossnote 0.9.31" in source and "MPE 0.8.30" in source+++def test_empty_document_and_equation_image_do_not_load_external_scripts() -> None:+ """验证空文档和纯公式图片不会无谓加载 MathJax 或 Prism。"""+ empty = render_html(_middle())+ image_equation = render_html(_middle(_page(0, EquationBlock(type="equation", index=0, content="", image_base64=_PNG_URI))))++ assert '<article class="crossnote markdown-preview mineru-document mineru-document--default">\n\n</article>' in empty+ assert "mathjax@" not in empty and "prismjs@" not in empty+ assert "mathjax@" not in image_equation and "prismjs@" not in image_equation+ assert "data:image/png" in image_equationdiff --git a/tests/unittest/test_html_security.py b/tests/unittest/test_html_security.pynew file mode 100644index 00000000..f24829cb--- /dev/null+++ b/tests/unittest/test_html_security.py@@ -0,0 +1,338 @@+from __future__ import annotations++import pytest+from bs4 import BeautifulSoup, Tag++from mineru.render.utils.html_sanitizer import (+ is_supported_html_markup,+ sanitize_html_fragment,+ sanitize_image_source,+ sanitize_link_url,+)+++ "content",+ [+ "<table><tr><td>A</td></tr></table>",+ "<eq>x</eq>",+ "<script>alert(1)</script>",+ '<img src="images/a.png">',+ ],+)+def test_supported_html_markup_detects_renderable_and_active_tags(content: str) -> None:+ """验证可渲染标签和需整体删除的活动标签会进入安全层。"""+ assert is_supported_html_markup(content)+++ "content",+ [+ "plain text",+ "<local_dir> p <0.05 and x > 0",+ "<custom-wrapper>visible</custom-wrapper>",+ "literal <b> token",+ "Use <img> tag",+ "Example <script> tag",+ "<table>not markup</table>",+ ],+)+def test_supported_html_markup_keeps_ordinary_angle_brackets_as_text(content: str) -> None:+ """验证未知尖括号文本不会被误判为 HTML。"""+ assert not is_supported_html_markup(content)+++ ("url", "expected"),+ [+ ("docs/page.html", "docs/page.html"),+ ("/docs/page.html", "/docs/page.html"),+ ("#section", "#section"),+ ("?page=2", "?page=2"),+ ("https://example.com/a b", "https://example.com/a%20b"),+ ("http://example.com", "http://example.com"),+ ("mailto:[email protected]", "mailto:[email protected]"),+ ("tel:+8610000", "tel:+8610000"),+ ],+)+def test_sanitize_link_url_allows_document_links(url: str, expected: str) -> None:+ """验证文档内链接和明确允许的外部协议被保留。"""+ assert sanitize_link_url(url) == expected+++ "url",+ [+ "javascript:alert(1)",+ "javascript:alert(1)",+ "java\nscript:alert(1)",+ "data:text/html,<script>alert(1)</script>",+ "vbscript:msgbox(1)",+ "file:///etc/passwd",+ "blob:https://example.com/id",+ "//evil.example/path",+ "\\evil.example\\path",+ "http:relative",+ "https://",+ "mailto:",+ "https://example.com/\ud800",+ "",+ ],+)+def test_sanitize_link_url_rejects_dangerous_or_invalid_urls(url: str) -> None:+ """验证可执行、本地文件、协议相对及无效 URL 被拒绝。"""+ assert sanitize_link_url(url) is None+++def test_sanitize_image_source_rewrites_only_safe_relative_sidecars() -> None:+ """验证仅安全相对 sidecar 路径应用资源根地址。"""+ base = "https://cdn.example/doc"++ assert sanitize_image_source("images/a b.png", asset_base_url=base) == ("https://cdn.example/doc/images/a%20b.png")+ assert sanitize_image_source("/shared/a.png", asset_base_url=base) == "/shared/a.png"+ assert sanitize_image_source("https://images.example/a.png", asset_base_url=base) == ("https://images.example/a.png")+++ "source",+ [+ "../secret.png",+ "images/../secret.png",+ "images/%2e%2e/secret.png",+ "images/%252e%252e/secret.png",+ r"images\..\secret.png",+ "file:///tmp/a.png",+ "blob:https://example.com/id",+ "//evil.example/a.png",+ "javascript:alert(1)",+ "data:text/html;base64,PHNjcmlwdD4=",+ "data:image/svg+xml;base64,PHN2Zz4=",+ "data:image/png;base64,AAAA",+ "data:image/png;base64,not-base64!",+ "#image",+ "?image=1",+ "",+ ],+)+def test_sanitize_image_source_rejects_unsafe_sources(source: str) -> None:+ """验证路径逃逸、活动内容和非栅格 data URI 被拒绝。"""+ assert sanitize_image_source(source, asset_base_url="assets") is None+++ "source",+ [+ "data:image/png;base64,iVBORw0KGgo=",+ "data:image/jpeg;base64,/9j/",+ "data:image/gif;base64,R0lGODlh",+ "data:image/webp;base64,UklGRgAAAABXRUJQ",+ ],+)+def test_sanitize_image_source_allows_strict_raster_data_uris(source: str) -> None:+ """验证语法正确的常见栅格图 base64 data URI 被保留。"""+ assert sanitize_image_source(source, asset_base_url="https://cdn.example/doc") == source+++ "asset_base_url",+ [+ "javascript:alert(1)",+ "data:text/html,boom",+ "../escape",+ "//evil.example/assets",+ r"\evil.example\assets",+ "https://cdn.example/%252e%252e/escape",+ "https://cdn.example/assets?redirect=evil",+ ],+)+def test_sanitize_image_source_rejects_malicious_asset_bases(asset_base_url: str) -> None:+ """验证恶意资源根地址不会被拼接到安全 sidecar 路径。"""+ assert sanitize_image_source("images/a.png", asset_base_url=asset_base_url) is None+++def test_sanitize_html_fragment_keeps_structure_and_bounded_attributes() -> None:+ """验证表格、列表、富文本与合法数值属性被保留。"""+ markup = (+ "<div><blockquote><p><b>B</b><strong>S</strong><i>I</i><em>E</em><u>U</u>"+ "<s>D</s><sub>1</sub><sup>2</sup><code>C</code><br><span>T</span></p></blockquote>"+ '<table><colgroup span="1000"><col span="0"></colgroup><thead><tr>'+ '<th colspan="2" rowspan="1001">H</th></tr></thead><tbody><tr><td rowspan="1">A</td>'+ "</tr></tbody><tfoot><tr><td>B</td></tr></tfoot></table>"+ '<ol start="-1000000"><li value="+0002">two</li><li value="1000001">bad</li></ol>'+ "<ul><li>bullet</li></ul></div>"+ )++ soup = BeautifulSoup(sanitize_html_fragment(markup), "html.parser")++ assert soup.find("table") is not None+ assert soup.find("blockquote") is not None+ assert not soup.find("colgroup").has_attr("span")+ assert not soup.find("col").has_attr("span")+ assert soup.find("th")["colspan"] == "2"+ assert not soup.find("th").has_attr("rowspan")+ assert soup.find("td")["rowspan"] == "1"+ assert soup.find("ol")["start"] == "-1000000"+ assert soup.find_all("ol")[0].find_all("li")[0]["value"] == "2"+ assert not soup.find_all("ol")[0].find_all("li")[1].has_attr("value")+++def test_sanitize_html_fragment_strips_source_presentation_and_clobbering_attributes() -> None:+ """验证来源样式、事件、DOM clobbering 和 data 属性全部删除。"""+ markup = (+ '<table id="location" name="cookie" class="evil" style="position:fixed" data-x="1">'+ '<tr><td onclick="alert(1)"><span id="forms" class="x" style="color:red">safe</span></td></tr>'+ '</table><a href="/docs" target="_blank" onclick="alert(1)" id="x">docs</a>'+ '<img src="images/a.png" alt="preview" class="x" style="x" onerror="alert(1)" width="999">'+ )++ rendered = sanitize_html_fragment(markup, asset_base_url="assets")+ soup = BeautifulSoup(rendered, "html.parser")++ assert soup.find("a").attrs == {"href": "/docs"}+ assert soup.find("img").attrs == {"alt": "preview", "src": "assets/images/a.png"}+ for tag in soup.find_all(True):+ assert not ({"class", "id", "name", "style"} & tag.attrs.keys())+ assert not any(name.startswith("data-") or name.startswith("on") for name in tag.attrs)+++def test_sanitize_html_fragment_removes_active_elements_with_contents() -> None:+ """验证活动、表单和媒体标签连同内容删除。"""+ paired_tags = [+ "audio",+ "button",+ "canvas",+ "form",+ "iframe",+ "math",+ "noscript",+ "object",+ "script",+ "select",+ "style",+ "svg",+ "template",+ "textarea",+ "video",+ ]+ markup = "".join(f"<{tag}>payload-{tag}</{tag}>" for tag in paired_tags)+ markup += '<embed src="x"><input value="payload-input"><p>safe</p>'++ rendered = sanitize_html_fragment(markup)++ assert rendered == "<p>safe</p>"+++def test_sanitize_html_fragment_unwraps_unknown_safe_elements() -> None:+ """验证未知非活动 wrapper 只去除标签,不丢失可见内容。"""+ markup = '<custom-wrapper onclick="alert(1)">before<strong>safe</strong>after</custom-wrapper>'++ assert sanitize_html_fragment(markup) == "before<strong>safe</strong>after"+++def test_sanitize_html_fragment_repairs_list_colgroup_and_image_content_models() -> None:+ """验证孤立列表项、非法直接子项、colgroup span 与缺失 alt 被规范化。"""+ markup = (+ "<li>orphan</li><ol>text<div>block</div><li>ok</li></ol>"+ "<span>before<li>phrasing orphan</li>after</span>"+ '<table><colgroup span="2"><col></colgroup><tr><td><img src="images/a.png"></td></tr></table>'+ )+ soup = BeautifulSoup(sanitize_html_fragment(markup), "html.parser")++ orphan = soup.find("li", string="orphan")+ assert orphan.parent.name == "ul"+ phrasing_orphan = soup.find("li", string="phrasing orphan")+ assert phrasing_orphan.parent.name == "ul"+ assert phrasing_orphan.find_parent("span") is None+ assert all(isinstance(child, Tag) and child.name == "li" for child in soup.find("ol").children)+ assert not soup.find("colgroup").has_attr("span")+ assert soup.find("img").attrs == {"alt": "", "src": "images/a.png"}+++def test_svg_data_uri_is_rejected_before_strict_xml_parsing(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证明确拒绝的 SVG 不进入通用图片 XML 解析器。"""++ def _unexpected_parse(_source: str) -> tuple[bytes, str]:+ """若被调用即证明 SVG 快速拒绝失效。"""+ raise AssertionError("SVG parser must not run")++ monkeypatch.setattr("mineru.render.utils.html_sanitizer.parse_image_data_uri_strict", _unexpected_parse)++ assert sanitize_image_source("data:image/svg+xml;base64,PHN2Zz4=") is None+++def test_sanitize_html_fragment_preserves_safe_equation_as_plain_text() -> None:+ """验证 eq 保留为后续公式载体,其中的标签仅作纯文本处理。"""+ markup = "<p>before <eq>x<y </script><b>z</b></eq> after</p>"++ rendered = sanitize_html_fragment(markup)+ soup = BeautifulSoup(rendered, "html.parser")++ assert soup.find("eq") is not None+ assert soup.find("eq").get_text() == "x<y </script>z"+ assert "</script>" in rendered+ assert soup.find("eq").find(True) is None+++def test_sanitize_html_fragment_degrades_dangerous_links_and_images_visibly() -> None:+ """验证危险链接留下 label,危险图片留下已转义的 alt。"""+ markup = (+ '<a href="javascript:alert(1)"><strong>label</strong></a>'+ '<img src="data:image/svg+xml;base64,PHN2Zz4=" alt="<unsafe>">'+ )++ rendered = sanitize_html_fragment(markup)++ assert rendered == "<strong>label</strong><unsafe>"+ assert "javascript" not in rendered+ assert "<img" not in rendered+++def test_sanitize_html_fragment_handles_malformed_mutation_xss() -> None:+ """验证畸形 SVG/MathML/脚本与属性组合不会绕过二次解析。"""+ markup = (+ '<svg><style><img src="x" onerror="alert(1)"></style></svg>'+ '<math><mtext><img src="x" onerror="alert(2)"></mtext></math>'+ '<table><tr><td><a href="java
script:alert(3)">link</a>'+ '<img src="images/a.png" onerror="alert(4)"></td></tr></table>'+ '<iframe srcdoc="<script>alert(5)</script>">frame</iframe>'+ "<!-- <script>alert(6)</script> -->"+ )++ rendered = sanitize_html_fragment(markup, asset_base_url="assets")+ reparsed = BeautifulSoup(rendered, "html.parser")++ assert reparsed.get_text(strip=True) == "link"+ assert reparsed.find("a") is None+ assert reparsed.find("img")["src"] == "assets/images/a.png"+ lowered = rendered.lower()+ for forbidden in ("<script", "<style", "<svg", "<math", "<iframe", "onerror", "javascript"):+ assert forbidden not in lowered+++def test_sanitize_html_fragment_escapes_malicious_titles_and_alt_text() -> None:+ """验证 title/alt 中的引号与标签只作属性或可见文本。"""+ markup = (+ '<a href="https://example.com" title="" onmouseover="alert(1)">safe</a>'+ '<img src="javascript:alert(2)" alt="<img src=x onerror=alert(3)>">'+ )++ rendered = sanitize_html_fragment(markup)+ soup = BeautifulSoup(rendered, "html.parser")++ assert soup.find("a")["title"] == '" onmouseover="alert(1)'+ assert not soup.find("a").has_attr("onmouseover")+ assert soup.find("img") is None+ assert soup.get_text().endswith("<img src=x onerror=alert(3)>")+ assert "<img src=x onerror=alert(3)>" in rendered+++def test_sanitize_html_fragment_rejects_invalid_argument_types() -> None:+ """验证安全层不隐式接受非字符串输入。"""+ with pytest.raises(TypeError, match="markup"):+ sanitize_html_fragment(None) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="asset_base_url"):+ sanitize_html_fragment("<p>x</p>", asset_base_url=None) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="url"):+ sanitize_link_url(None) # type: ignore[arg-type]+ with pytest.raises(TypeError, match="source"):+ sanitize_image_source(None) # type: ignore[arg-type]diff --git a/tests/unittest/test_render_list_index_utils.py b/tests/unittest/test_render_list_index_utils.pynew file mode 100644index 00000000..5e1598ef--- /dev/null+++ b/tests/unittest/test_render_list_index_utils.py@@ -0,0 +1,158 @@+from __future__ import annotations++import pytest++from mineru.render.utils.index import looks_like_index_page_token, strip_index_page_tail+from mineru.render.utils.list_items import (+ has_markdown_unordered_marker,+ parse_list_item_marker,+ reference_list_needs_bullets,+)+from mineru.types import ListBlock, RefTextBlock, TextBlock+++ ("content", "marker", "body", "kind", "value", "ordered_style"),+ [+ ("- item", "-", "item", "unordered", None, None),+ ("* item", "*", "item", "unordered", None, None),+ ("+ item", "+", "item", "unordered", None, None),+ ("12. item", "12.", "item", "ordered", 12, "decimal"),+ ("a. item", "a.", "item", "ordered", 1, "lower-alpha"),+ ("A. item", "A.", "item", "ordered", 1, "upper-alpha"),+ ("i. item", "i.", "item", "ordered", 1, "lower-roman"),+ ("I. item", "I.", "item", "ordered", 1, "upper-roman"),+ ("iv. item", "iv.", "item", "ordered", 4, "lower-roman"),+ ("XII. item", "XII.", "item", "ordered", 12, "upper-roman"),+ ("12) item", "12)", "item", "explicit", None, None),+ ("(12) item", "(12)", "item", "explicit", None, None),+ ("(12. item", "(12.", "item", "explicit", None, None),+ ("a) item", "a)", "item", "explicit", None, None),+ ("[12] item", "[12]", "item", "explicit", None, None),+ ("[x] done", "[x]", "done", "explicit", None, None),+ ("[ ] pending", "[ ]", "pending", "explicit", None, None),+ ("plain item", None, "plain item", "none", None, None),+ ("-without-space", None, "-without-space", "none", None, None),+ ],+)+def test_parse_list_item_marker_classifies_supported_styles(+ content: str,+ marker: str | None,+ body: str,+ kind: str,+ value: int | None,+ ordered_style: str | None,+) -> None:+ """验证共享 parser 区分原生列表与需要显式 marker 的编号风格。"""+ item = parse_list_item_marker(content)++ assert item.marker == marker+ assert item.body == body+ assert item.kind == kind+ assert item.value == value+ assert item.ordered_style == ordered_style++[email protected]("content", [" 2. item", "\t- item", "- \ncontinued", " plain item"])+def test_parse_list_item_marker_preserves_reconstructable_whitespace(content: str) -> None:+ """验证 parser 单独保存前导与分隔空白,并可无损重建原内容。"""+ item = parse_list_item_marker(content)+ reconstructed = item.leading+ if item.marker is not None:+ reconstructed += item.marker + item.separator+ reconstructed += item.body++ assert reconstructed == content+++def test_single_roman_letters_use_stable_roman_precedence() -> None:+ """验证与字母编号同形的罗马字符固定优先解释为罗马数字。"""+ assert parse_list_item_marker("v. item").ordered_style == "lower-roman"+ assert parse_list_item_marker("v. item").value == 5+ assert parse_list_item_marker("c. item").ordered_style == "lower-roman"+ assert parse_list_item_marker("c. item").value == 100+ assert parse_list_item_marker("z. item").ordered_style == "lower-alpha"+ assert parse_list_item_marker("z. item").value == 26+++ "content",+ [+ f"{'9' * 5000}. item",+ "1000001. item",+ "01. item",+ "001. item",+ "IIII. item",+ f"{'M' * 5000}. item",+ ],+)+def test_unbounded_or_invalid_ordered_markers_degrade_to_explicit(content: str) -> None:+ """验证超长、超界或非规范编号不会触发大整数异常,并原样保留 marker。"""+ item = parse_list_item_marker(content)++ assert item.kind == "explicit"+ assert item.marker is not None+ assert item.value is None+ assert item.ordered_style is None+++def test_markdown_existing_bullet_detection_remains_hyphen_only() -> None:+ """验证参考文献补 bullet 只避开既有短横线,保持 Markdown 历史输出。"""+ assert has_markdown_unordered_marker(" - existing")+ assert not has_markdown_unordered_marker("* existing")+ assert not has_markdown_unordered_marker("+ existing")+ assert not has_markdown_unordered_marker("-without-space")+ assert not has_markdown_unordered_marker("-\ncontinued")+++def _reference_list(*children: TextBlock | RefTextBlock | ListBlock) -> ListBlock:+ """构造用于严格多数判定的参考文献列表。"""+ return ListBlock(type="list", sub_type="ref_text", content=list(children))+++def test_reference_list_bullet_rule_uses_visible_direct_item_strict_majority() -> None:+ """验证富文本可见数字、空项和嵌套列表遵守既有严格多数规则。"""+ nested = _reference_list(RefTextBlock(type="ref_text", content="Author nested"))+ numbered_majority = _reference_list(+ RefTextBlock(type="ref_text", content='<text style="bold">[1]</text> first'),+ RefTextBlock(type="ref_text", content="missing marker"),+ TextBlock(type="text", content="3) third"),+ RefTextBlock(type="ref_text", content=""),+ nested,+ )+ tied = _reference_list(+ RefTextBlock(type="ref_text", content="[1] first"),+ RefTextBlock(type="ref_text", content="Author A"),+ )++ assert not reference_list_needs_bullets(numbered_majority)+ assert reference_list_needs_bullets(tied)+ assert not reference_list_needs_bullets(ListBlock(type="list", sub_type="text", content=tied.content))+++ ("content", "expected"),+ [+ ("Title", "Title"),+ ("Title\t12", "Title"),+ ('Title\t<text style="bold">IV</text>', "Title"),+ ("Part\tSection\tA", "Part Section"),+ ("Title\tAppendix", "Title Appendix"),+ ("Title\tA2", "Title A2"),+ ],+)+def test_strip_index_page_tail_uses_visible_tail_token(content: str, expected: str) -> None:+ """验证目录仅删除可信的末尾页码,并把保留 tab 转为空格。"""+ assert strip_index_page_tail(content) == expected++[email protected]("content", ["1", "12", "iv", "XII", "a", "Z"])+def test_index_page_token_accepts_supported_forms(content: str) -> None:+ """验证数字、罗马数字与单字母可作为目录页码 token。"""+ assert looks_like_index_page_token(content)++[email protected]("content", ["", "AB", "A2", "appendix", "1234567890123"])+def test_index_page_token_rejects_ambiguous_forms(content: str) -> None:+ """验证空值、长值和普通词不会被误删为目录页码。"""+ assert not looks_like_index_page_token(content)