Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: enhance EPUB parsing and rendering for page footnotes
myhlolief26b0fa317a
diff --git a/CLAUDE.md b/CLAUDE.mdindex 64069adc..c4713fe6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -175,7 +175,7 @@ pr-5415 重构后,Middle JSON 已收敛为 schema 2.0 的统一结构,不再### 2.1 ModelJson 严格容器-`doc_analyze` 返回 `tuple[MiddleJson, ModelJson]`。`ModelJson` 持有 raw model-list(`pages: list[list[dict]]`)+ `page_index_map: list[int]`(空列表表示整本文档),并提供 `is_full_document`/`resolved_page_indices` 派生属性。只有 PDF Analyze 接受非空 `page_index_map`;其它 Flash 格式只支持整本解析。EPUB 可恢复目录时第 0 页为独立 `IndexBlock`,后续页面按 OPF spine 顺序排列。`backend/postprocess/document.py:model_json_to_middle_json()` 是 ModelJson → MiddleJson 的唯一编排入口,内部调用 `model_json_to_pages()` + `apply_llm_aided_postprocess()`。+`doc_analyze` 返回 `tuple[MiddleJson, ModelJson]`。`ModelJson` 持有 raw model-list(`pages: list[list[dict]]`)+ `page_index_map: list[int]`(空列表表示整本文档),并提供 `is_full_document`/`resolved_page_indices` 派生属性。只有 PDF Analyze 接受非空 `page_index_map`;其它 Flash 格式只支持整本解析。EPUB 逻辑页严格对应 OPF spine 顺序,不再前插合成目录页;位于 spine 中的 navigation XHTML 作为普通内容页保留,spine 外的 nav/NCX 不生成页面。`backend/postprocess/document.py:model_json_to_middle_json()` 是 ModelJson → MiddleJson 的唯一编排入口,内部调用 `model_json_to_pages()` + `apply_llm_aided_postprocess()`。### 3. PageInfo 结构diff --git a/README.md b/README.mdindex 8e08b941..989a54fc 100644--- a/README.md+++ b/README.md@@ -50,7 +50,7 @@ Use MinerU for local document files such as:|---|---|| PDF | `.pdf`, including scanned PDFs and academic papers || Images | `.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp`, and similar image files |-| EPUB | `.epub`, parsed as a full document with a leading table-of-contents page when available |+| EPUB | `.epub`, parsed as a full document in OPF spine order with source internal links preserved || Word | `.docx` || PowerPoint | `.pptx` || Excel | `.xlsx` |diff --git a/README_en.md b/README_en.mdindex 71804bae..56e03d5e 100644--- a/README_en.md+++ b/README_en.md@@ -330,7 +330,7 @@ If your device does not meet the GPU acceleration requirements, you can explicitmineru parse "<input_path>" --tier flash -o <output_path>```-`mineru` currently supports local `PDF`, `EPUB`, image, `CSV`, `RTF`, `DOCX`, `PPTX`, `XLSX`, `ODT`, `ODS`, and `ODP` file or directory inputs through the CLI, API, and `mineru-router`. EPUB, RTF, and OpenDocument use local semantic Flash parsing without external office-suite conversion. Non-PDF Flash inputs are always parsed as full documents; EPUB adds a leading table-of-contents page before the spine pages when a directory can be recovered. The legacy Gradio WebUI keeps its existing advertised upload formats. For detailed instructions, please refer to the [Usage Guide](https://opendatalab.github.io/MinerU/usage/).+`mineru` currently supports local `PDF`, `EPUB`, image, `CSV`, `RTF`, `DOCX`, `PPTX`, `XLSX`, `ODT`, `ODS`, and `ODP` file or directory inputs through the CLI, API, and `mineru-router`. EPUB, RTF, and OpenDocument use local semantic Flash parsing without external office-suite conversion. Non-PDF Flash inputs are always parsed as full documents; EPUB pages follow OPF spine order and preserve resolvable internal links from authored contents, including list and table layouts. The legacy Gradio WebUI keeps its existing advertised upload formats. For detailed instructions, please refer to the [Usage Guide](https://opendatalab.github.io/MinerU/usage/).# FAQdiff --git a/README_zh.md b/README_zh.mdindex e38e25df..64d8d5d5 100644--- a/README_zh.md+++ b/README_zh.md@@ -336,7 +336,7 @@ mineru -p <input_path> -o <output_path>mineru parse "<input_path>" --tier flash -o <output_path>```-当前 `mineru` 支持本地 `PDF / EPUB / 图片 / CSV / RTF / DOCX / PPTX / XLSX / ODT / ODS / ODP` 文件或目录输入,并可通过命令行、API、`mineru-router` 进行解析。EPUB、RTF 与 OpenDocument 使用本地 Flash 语义解析,不依赖外部 Office 套件转换;所有非 PDF Flash 输入只支持整本解析,EPUB 可恢复目录时会在 spine 正文前增加独立目录页。旧 Gradio WebUI 仍保持原有对外说明。具体使用方法请参考[使用指南](https://opendatalab.github.io/MinerU/zh/usage/)。+当前 `mineru` 支持本地 `PDF / EPUB / 图片 / CSV / RTF / DOCX / PPTX / XLSX / ODT / ODS / ODP` 文件或目录输入,并可通过命令行、API、`mineru-router` 进行解析。EPUB、RTF 与 OpenDocument 使用本地 Flash 语义解析,不依赖外部 Office 套件转换;所有非 PDF Flash 输入只支持整本解析,EPUB 页面严格遵循 OPF spine 顺序,并保留作者目录中可解析的列表、表格等内部跳转。旧 Gradio WebUI 仍保持原有对外说明。具体使用方法请参考[使用指南](https://opendatalab.github.io/MinerU/zh/usage/)。# FAQdiff --git a/docs/en/quick_start/index.md b/docs/en/quick_start/index.mdindex 2a05b97a..b8a341db 100644--- a/docs/en/quick_start/index.md+++ b/docs/en/quick_start/index.md@@ -148,6 +148,6 @@ If your device does not meet the GPU acceleration requirements, you can explicitmineru parse "<input_path>" --tier flash -o <output_path>```-`mineru` currently supports local `PDF`, `EPUB`, image, `CSV`, `RTF`, `DOCX`, `PPTX`, `XLSX`, `ODT`, `ODS`, and `ODP` file or directory inputs through modern CLI and API entry points. EPUB, RTF, and OpenDocument are parsed locally with Flash semantics and do not require an external office suite. Non-PDF Flash inputs only support full-document parsing; EPUB prepends a table-of-contents page when nav, NCX, or document headings provide one.+`mineru` currently supports local `PDF`, `EPUB`, image, `CSV`, `RTF`, `DOCX`, `PPTX`, `XLSX`, `ODT`, `ODS`, and `ODP` file or directory inputs through modern CLI and API entry points. EPUB, RTF, and OpenDocument are parsed locally with Flash semantics and do not require an external office suite. Non-PDF Flash inputs only support full-document parsing; EPUB pages follow OPF spine order and preserve resolvable internal links from authored contents.The legacy Gradio WebUI keeps its existing upload formats and does not yet accept CSV. For detailed instructions, please refer to the [Usage Guide](../usage/index.md).diff --git a/docs/en/reference/output_files.md b/docs/en/reference/output_files.mdindex c974df57..665bea3a 100644--- a/docs/en/reference/output_files.md+++ b/docs/en/reference/output_files.md@@ -166,7 +166,8 @@ Leaf blocks (text, title, equation, etc.) carry `content: str` directly. Visual| `list` | List container; `content` is a list of `text`/`ref_text`/nested `list` blocks; `sub_type` is `text` or `ref_text` || `index` | Index (table of contents) container; `content` is a list of `text`/`doc_title`/`paragraph_title`/nested `index` blocks || `ref_text` | Reference / bibliography text block; EPUB notes do not use this type |-| `header` / `footer` / `page_number` / `aside_text` / `page_footnote` | Page auxiliary blocks (leaf, `content: str`); only `page_footnote` may include `anchor` |+| `header` / `footer` / `page_number` / `aside_text` | Page auxiliary blocks (leaf, `content: str`); they do not accept `anchor` |+| `page_footnote` | Independent page footnote block (leaf, `content: str`); may include a document-wide `anchor` and remains visible in DEFAULT rendering |##### Sample Data (schema 2.0)@@ -259,7 +260,8 @@ Leaf blocks (text, title, equation, etc.) carry `content: str` directly. Visual| `code` | Code block with `code_content`, `code_caption`, `code_footnote`, and `code_language` || `algorithm` | Algorithm block with `algorithm_content`, `algorithm_caption`, and `algorithm_footnote` || `list` / `index` | List and index blocks with `list_items` |-| `page_header` / `page_footer` / `page_number` / `page_aside_text` / `page_footnote` | Page auxiliary blocks |+| `page_header` / `page_footer` / `page_number` / `page_aside_text` | Page auxiliary blocks |+| `page_footnote` | Independent page footnote content |Inline fields such as `title_content`, `paragraph_content`, and captions areusually span lists. A `hyperlink` span contains `content` and `url`; when one@@ -383,7 +385,7 @@ In schema 2.0, the multimodal tier produces the same unified `MiddleJson` struct- `code` is a container block; `content` holds a `code_body` plus optional `code_caption`/`code_footnote`; `sub_type` is:* `code`* `algorithm`-- Page auxiliary blocks (`header`, `footer`, `page_number`, `aside_text`, `page_footnote`) appear as top-level leaf blocks in `blocks` with `content: str` — there is no separate `discarded_blocks` field in schema 2.0. `page_footnote` alone may carry an optional document-wide `anchor`.+- Page auxiliary blocks (`header`, `footer`, `page_number`, `aside_text`) and the independent `page_footnote` block appear as top-level leaves in `blocks` with `content: str` — there is no separate `discarded_blocks` field in schema 2.0. Only `page_footnote` may carry an optional document-wide `anchor`, and it remains visible in DEFAULT rendering.- All blocks may include an `angle` field indicating rotation (one of `0, 90, 180, 270`).##### Examplesdiff --git a/docs/en/usage/cli_tools.md b/docs/en/usage/cli_tools.mdindex 996f733a..5ecd4967 100644--- a/docs/en/usage/cli_tools.md+++ b/docs/en/usage/cli_tools.md@@ -31,7 +31,7 @@ Options:--help Show help information```> [!TIP]-> `mineru` currently supports local `PDF`, `EPUB`, image, `CSV`, `RTF`, `DOCX`, `PPTX`, `XLSX`, `ODT`, `ODS`, and `ODP` file or directory inputs. Non-PDF Flash formats only support full-document parsing; EPUB emits a leading table-of-contents page when available.+> `mineru` currently supports local `PDF`, `EPUB`, image, `CSV`, `RTF`, `DOCX`, `PPTX`, `XLSX`, `ODT`, `ODS`, and `ODP` file or directory inputs. Non-PDF Flash formats only support full-document parsing; EPUB pages follow OPF spine order and preserve resolvable authored internal links.```bashmineru-api --helpdiff --git a/docs/next/cli/mineru-kit-parse.md b/docs/next/cli/mineru-kit-parse.mdindex 7453ba05..7234aefe 100644--- a/docs/next/cli/mineru-kit-parse.md+++ b/docs/next/cli/mineru-kit-parse.md@@ -30,7 +30,7 @@ mineru-kit parse <input...> -o <output> [flags]| 多文件 | 一次提交多个文件 || 目录 | 展开目录中的可解析文件 |-当前支持的扩展名包括 PDF、EPUB、常见图片、CSV、RTF、DOC/DOCX、PPT/PPTX、XLS/XLSX、ODT/ODS/ODP、HTML/HTM。目录输入只展开一层,不递归;非 PDF Flash 输入只支持整本解析,显式 `--pages` 返回 `page_range_invalid`。EPUB 可恢复目录时会增加独立首页目录。+当前支持的扩展名包括 PDF、EPUB、常见图片、CSV、RTF、DOC/DOCX、PPT/PPTX、XLS/XLSX、ODT/ODS/ODP、HTML/HTM。目录输入只展开一层,不递归;非 PDF Flash 输入只支持整本解析,显式 `--pages` 返回 `page_range_invalid`。EPUB 页面严格遵循 OPF spine 顺序,并保留作者目录中可解析的内部跳转。当前不支持:diff --git a/docs/next/middle-json/current-medium.md b/docs/next/middle-json/current-medium.mdindex 319ee58e..98dc975a 100644--- a/docs/next/middle-json/current-medium.md+++ b/docs/next/middle-json/current-medium.md@@ -56,7 +56,7 @@ MiddleJson 并执行适用的 PDF 后处理。不再提供裸 model list 加独| `mineru_version` | 非空字符串 | 必填 |当 `file_suffix="pdf"` 时,每个页面顶层 block 必须具有有效 bbox。EPUB、CSV 与 Office-顶层 block 可以没有 bbox。EPUB 可恢复目录时 `page_idx=0` 是独立 `IndexBlock` 目录页,后续页面按 OPF spine 顺序排列。PDF 标题分级直接读取 `is_full_document`;缺少该字段的+顶层 block 可以没有 bbox。EPUB 的 `page_idx` 与 OPF spine 项一一对应,不会前插合成 `IndexBlock` 目录页。PDF 标题分级直接读取 `is_full_document`;缺少该字段的旧 Middle JSON 无法通过严格解析,需要从 ModelJson 重新生成。## `PageInfo`@@ -116,7 +116,8 @@ text| `RefTextBlock` | `str` | `continues_prev`;不允许 `anchor` || `DocTitleBlock` | `str` | `anchor`、必填 `level=1` || `ParagraphTitleBlock` | `str` | `anchor`、必填 `level>=2` |-| `PageAuxTextBlock` | `str` | 共享页眉、页脚、页码、边栏和页脚注释结构;仅 `page_footnote` 可带 `anchor` |+| `PageAuxTextBlock` | `str` | 共享页眉、页脚、页码和边栏结构;不允许 `anchor` |+| `PageFootnoteBlock` | `str` | 独立页面脚注结构;可带 document-wide `anchor`,DEFAULT 也参与输出 || `TableBlock` | 有序视觉子块列表 | `continues_prev`、`cell_merge` || `TableBodyBlock` | `str` | 图片字段 || `CodeBlock` | 有序视觉子块列表 | `sub_type`、`guess_lang` |@@ -130,8 +131,8 @@ text`ref_text` 复用正文的终止符和几何规则,但不要求续段首行或首列顶起始边界,也不因续段以数字或大写字符开头而拒绝合并。-`page_footnote.anchor` 是可选的 document-wide 跳转目标。其它-`PageAuxTextBlock` discriminator 即使显式提供 anchor 也会被严格校验拒绝。+`page_footnote.anchor` 是可选的 document-wide 跳转目标。`PageAuxTextBlock`+discriminator 显式提供 anchor 会被严格校验拒绝。`CodeBlock(sub_type="code")` 必须有非空 `guess_lang`;`sub_type="algorithm"` 禁止 `guess_lang`。`continues_prev` 只允许出现在页面diff --git a/docs/next/middle-json/rendering.md b/docs/next/middle-json/rendering.mdindex cb73bfb6..3e2dcd0b 100644--- a/docs/next/middle-json/rendering.md+++ b/docs/next/middle-json/rendering.md@@ -306,22 +306,22 @@ doclib 或历史扁平 `content_list.json` 产物。`RenderMode.DEFAULT`:-- 隐藏 `header/footer/page_number/aside_text/page_footnote`。-- 合并页内和跨页 `text/ref_text.continues_prev`;ref_text 可跨过页面辅助块查找前序 ref_text。-- 合并页内和跨页 `list.continues_prev`;ref list 可跨过页面辅助块查找前序列表。+- 隐藏 `header/footer/page_number/aside_text`,保留独立 `page_footnote`。+- 合并页内和跨页 `text/ref_text.continues_prev`;ref_text 可跨过页面脚注与辅助块查找前序 ref_text。+- 合并页内和跨页 `list.continues_prev`;ref list 可跨过页面脚注与辅助块查找前序列表。- 只合并跨页 `table.continues_prev`。- 页面之间不输出分割线。`RenderMode.FULL`:- 展示全部顶层 block。-- 带 anchor 的 `page_footnote` 在 Markdown/HTML/DOCX 中分别输出 HTML anchor、元素 id 和 Word bookmark。+- 带 anchor 的 `page_footnote` 在 DEFAULT/FULL 的 Markdown/HTML/DOCX 中分别输出 span id、元素 id 和 Word bookmark。- 只合并页内 `text/ref_text/list.continues_prev`。- 不合并跨页 text/ref_text/list/table。- 每两个相邻 `PageInfo` 之间输出 `---`,空白页边界同样保留。text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到前一个 text,-后块不再在原位置输出。ref_text 与 ref list 都只跨过页面辅助块,其他语义块+后块不再在原位置输出。ref_text 与 ref list 都只跨过页面脚注与辅助块,其他语义块仍会分别阻断文本链和列表链;两种参考文献标记互不混用。普通 list 仍要求物理相邻。table 只接受跨页合并;失败时保留两张原表。@@ -329,7 +329,7 @@ text 合并允许跨越任意其他 block,后一个 text 的内容被吸收到- `text/ref_text`: 解析行内公式、样式和超链接;普通 text 转义可能误触发的 Markdown block 前缀。- `doc_title/paragraph_title`: 使用全局 `level`,Markdown 标题最多六级;anchor 输出为 HTML id。-- `page_footnote`: 仍属于页面辅助块;可选 anchor 只在 FULL 模式随脚注正文输出。+- `page_footnote`: 独立于页面辅助块,DEFAULT/FULL 都输出;Markdown 使用无可见标签的 `<small><span class="mineru-page-footnote" data-block-type="page_footnote" style="color:#6b7280">…</span></small>`,HTML/DOCX 使用小号弱化样式。- `list`: 递归缩进;普通列表直接使用 content 已内化的前缀。`sub_type=ref_text`时统计每个直属非空 item 的前五个可见字符,数字前缀未达到严格多数则给全部 item补 `- `,已有 `- ` 不重复;嵌套列表独立判定。diff --git a/docs/next/middle-json/structured-content-current.md b/docs/next/middle-json/structured-content-current.mdindex d19b492e..7f2a55dc 100644--- a/docs/next/middle-json/structured-content-current.md+++ b/docs/next/middle-json/structured-content-current.md@@ -134,7 +134,8 @@ Structured Content 需要重新定义 unknown bbox,不应把 `[0, 0, 0, 0]`| 列表 | `list`, `text_list`, `reference_list`, `index` || 文本结构 | `title`, `paragraph` || span | `text`, `phonetic`, `md`, `code_inline` |-| 页边内容 | `page_header`, `page_footer`, `page_number`, `page_aside_text`, `page_footnote` |+| 页边内容 | `page_header`, `page_footer`, `page_number`, `page_aside_text` |+| 页面脚注 | `page_footnote`(语义上独立于低价值页边内容) |当前实现并没有使用全部类型:diff --git a/docs/next/sdk/parser.md b/docs/next/sdk/parser.mdindex 42a97546..b35b64d9 100644--- a/docs/next/sdk/parser.md+++ b/docs/next/sdk/parser.md@@ -58,12 +58,12 @@ from mineru.parser import MinerUParser支持输入:-- EPUB(目录页位于最前,随后按 OPF spine 输出逻辑页)+- EPUB(严格按 OPF spine 输出逻辑页并保留可解析的作者内部链接)- 图片(PNG/JPEG 等)- CSV、RTF、DOC/DOCX、PPT/PPTX、XLS/XLSX- ODT、ODS、ODP-EPUB 始终使用 `flash/txt` 并只支持整本解析。目录来源依次为 EPUB3 nav、EPUB2 NCX 和正文标题;目录可恢复时 `page_idx=0`,原 spine 页整体后移。单条 Footnote/Endnote 输出为带可选 canonical anchor 的 `page_footnote`,正文 `noteref` 可跨 spine 正向链接到该 anchor;脚注集合容器不会整体改型。fixed-layout/SVG 仅尽力保留 DOM 文本与包内静态图片,不执行 OCR、脚本、外部资源下载或 DRM 解密。所有非 PDF Flash 格式显式传入 `page_range` 都会返回 `page_range_invalid`。+EPUB 始终使用 `flash/txt` 并只支持整本解析。每个 `page_idx` 与 OPF spine 项一一对应;位于 spine 中的 navigation XHTML 按普通内容页解析,spine 外的 nav/NCX 不生成合成目录页。正文、列表和表格中的安全内部链接统一映射到实际标题 anchor;严格匹配单一标题的目录表格行会让相邻标题单元格继承同一跳转。单条 Footnote/Endnote 输出为带可选 canonical anchor 的 `page_footnote`,正文 `noteref` 可跨 spine 正向链接到该 anchor;脚注集合容器不会整体改型。fixed-layout/SVG 仅尽力保留 DOM 文本与包内静态图片,不执行 OCR、脚本、外部资源下载或 DRM 解密。所有非 PDF Flash 格式显式传入 `page_range` 都会返回 `page_range_invalid`。## `parse()` / `parse_async()` 入口diff --git a/docs/zh/quick_start/index.md b/docs/zh/quick_start/index.mdindex 3c4dfb17..31906216 100644--- a/docs/zh/quick_start/index.md+++ b/docs/zh/quick_start/index.md@@ -159,6 +159,6 @@ mineru -p <input_path> -o <output_path>mineru parse "<input_path>" --tier flash -o <output_path>```-当前 `mineru` 的现代 CLI 和 API 入口支持本地 `PDF / EPUB / 图片 / CSV / RTF / DOCX / PPTX / XLSX / ODT / ODS / ODP` 文件或目录输入。EPUB、RTF 与 OpenDocument 采用本地 Flash 语义解析,不依赖外部 Office 套件。非 PDF Flash 输入只支持整本解析;EPUB 可从 nav、NCX 或正文标题恢复目录时会增加独立首页目录。+当前 `mineru` 的现代 CLI 和 API 入口支持本地 `PDF / EPUB / 图片 / CSV / RTF / DOCX / PPTX / XLSX / ODT / ODS / ODP` 文件或目录输入。EPUB、RTF 与 OpenDocument 采用本地 Flash 语义解析,不依赖外部 Office 套件。非 PDF Flash 输入只支持整本解析;EPUB 页面严格遵循 OPF spine 顺序,并保留作者目录中可解析的内部跳转。旧 Gradio WebUI 保持原有上传格式,暂不接收 CSV。具体使用方法请参考[使用指南](../usage/index.md)。diff --git a/docs/zh/reference/output_files.md b/docs/zh/reference/output_files.mdindex fca55bea..783ee5ee 100644--- a/docs/zh/reference/output_files.md+++ b/docs/zh/reference/output_files.md@@ -166,7 +166,8 @@ schema 2.0 已移除旧字段 `preproc_blocks`/`para_blocks`/`page_size`/`images| `list` | 列表容器;`content` 为 `text`/`ref_text`/嵌套 `list` 块列表;`sub_type` 为 `text` 或 `ref_text` || `index` | 目录容器;`content` 为 `text`/`doc_title`/`paragraph_title`/嵌套 `index` 块列表 || `ref_text` | 参考文献文本块;EPUB 脚注不使用该类型 |-| `header` / `footer` / `page_number` / `aside_text` / `page_footnote` | 页面辅助块(叶子块,`content: str`);仅 `page_footnote` 可带 `anchor` |+| `header` / `footer` / `page_number` / `aside_text` | 页面辅助块(叶子块,`content: str`);不接受 `anchor` |+| `page_footnote` | 独立页面脚注块(叶子块,`content: str`);可带 document-wide `anchor`,DEFAULT 渲染也保留 |##### 示例数据(schema 2.0)@@ -259,7 +260,8 @@ schema 2.0 已移除旧字段 `preproc_blocks`/`para_blocks`/`page_size`/`images| `code` | 代码块,包含 `code_content`、`code_caption`、`code_footnote`、`code_language` || `algorithm` | 算法块,包含 `algorithm_content`、`algorithm_caption`、`algorithm_footnote` || `list` / `index` | 列表与索引,包含 `list_items` |-| `page_header` / `page_footer` / `page_number` / `page_aside_text` / `page_footnote` | 页面辅助块 |+| `page_header` / `page_footer` / `page_number` / `page_aside_text` | 页面辅助块 |+| `page_footnote` | 独立页面脚注内容 |`title_content`、`paragraph_content`、说明文字等行内内容通常由 span 列表组成。`hyperlink` span 包含 `content`、`url`,当同一个链接内存在多段不同样式文本时,@@ -412,7 +414,7 @@ schema 2.0 已移除旧字段 `preproc_blocks`/`para_blocks`/`page_size`/`images* `code`* `algorithm`-- 页面辅助块(`header`、`footer`、`page_number`、`aside_text`、`page_footnote`)作为顶层叶子块出现在 `blocks` 中,`content: str`——schema 2.0 不再有独立的 `discarded_blocks` 字段;只有 `page_footnote` 可以额外携带 document-wide `anchor`。+- 页面辅助块(`header`、`footer`、`page_number`、`aside_text`)和独立的 `page_footnote` 块都作为顶层叶子出现在 `blocks` 中,`content: str`——schema 2.0 不再有独立的 `discarded_blocks` 字段;只有 `page_footnote` 可以额外携带 document-wide `anchor`,且 DEFAULT 渲染也会保留。- 所有 block 可能包含 `angle` 字段,用来表示旋转角度,0,90,180,270diff --git a/docs/zh/usage/cli_tools.md b/docs/zh/usage/cli_tools.mdindex 45a437a4..e9034547 100644--- a/docs/zh/usage/cli_tools.md+++ b/docs/zh/usage/cli_tools.md@@ -28,7 +28,7 @@ Options:--help 显示帮助信息```> [!TIP]-> `mineru` 当前支持本地 `PDF`、`EPUB`、图片、`CSV`、`RTF`、`DOCX`、`PPTX`、`XLSX`、`ODT`、`ODS`、`ODP` 文件或目录输入。非 PDF Flash 格式只支持整本解析;EPUB 有可用目录时会输出独立首页目录。+> `mineru` 当前支持本地 `PDF`、`EPUB`、图片、`CSV`、`RTF`、`DOCX`、`PPTX`、`XLSX`、`ODT`、`ODS`、`ODP` 文件或目录输入。非 PDF Flash 格式只支持整本解析;EPUB 页面严格遵循 OPF spine 顺序,并保留作者目录中可解析的内部跳转。```bashmineru-api --helpdiff --git a/mineru/backend/postprocess/paragraphs.py b/mineru/backend/postprocess/paragraphs.pyindex 4ab0834a..023ef87c 100644--- a/mineru/backend/postprocess/paragraphs.py+++ b/mineru/backend/postprocess/paragraphs.py@@ -6,7 +6,7 @@ import mathimport refrom typing import Any, TypeAlias-from ...types import PAGE_AUXILIARY_BLOCK_TYPES, BlockType+from ...types import MERGE_TRANSPARENT_BLOCK_TYPES, BlockTypeLINE_STOP_FLAG = (".", "!", "?", "。", "!", "?", ")", ")", '"', "”", ":", ":", ";", ";")SECTION_MERGE_BARRIER_TYPES = {@@ -18,13 +18,13 @@ TEXT_MERGE_BARRIER_TYPES = {*SECTION_MERGE_BARRIER_TYPES,BlockType.LIST,}-# 文本段落合并允许跨过视觉根块和页面装饰块,其他语义块仍会阻断候选查找。+# 文本段落合并允许跨过视觉根块、页面脚注和页面装饰块,其他语义块仍会阻断候选查找。TEXT_MERGE_TRANSPARENT_TYPES = {BlockType.IMAGE,BlockType.TABLE,BlockType.CHART,BlockType.CODE,- *PAGE_AUXILIARY_BLOCK_TYPES,+ *MERGE_TRANSPARENT_BLOCK_TYPES,}CONTINUABLE_TEXT_BLOCK_TYPES = {BlockType.TEXT, BlockType.REF_TEXT}VERTICAL_LINE_HEIGHT_TO_WIDTH_RATIO_THRESHOLD = 2@@ -201,7 +201,7 @@ def _find_previous_text_block(ordered_blocks: list[OrderedBlock],current_index: int,) -> OrderedBlock | None:- """向前查找 text,视觉根块和页面装饰块可跨过,其他语义块会阻断查找。"""+ """向前查找 text,视觉根块和合并透明块可跨过,其他语义块会阻断查找。"""for previous_index in range(current_index - 1, -1, -1):previous_block = ordered_blocks[previous_index][2]previous_type = previous_block.get("type")@@ -219,11 +219,11 @@ def _find_previous_ref_text_block(ordered_blocks: list[OrderedBlock],current_index: int,) -> OrderedBlock | None:- """跳过页面辅助块查找前一个 ref_text,其他语义块保持阻断。"""+ """跳过页面脚注与辅助块查找前一个 ref_text,其他语义块保持阻断。"""for previous_index in range(current_index - 1, -1, -1):previous_block = ordered_blocks[previous_index][2]previous_type = previous_block.get("type")- if previous_type in PAGE_AUXILIARY_BLOCK_TYPES:+ if previous_type in MERGE_TRANSPARENT_BLOCK_TYPES:continueif previous_type == BlockType.REF_TEXT:return ordered_blocks[previous_index]@@ -236,12 +236,12 @@ def _find_previous_ref_text_list_block(current_index: int,current_block: BlockDict,) -> OrderedBlock | None:- """跳过页面辅助块查找前一个 ref_text list,其他语义块保持阻断。"""+ """跳过页面脚注与辅助块查找前一个 ref_text list,其他语义块保持阻断。"""if not _is_ref_text_list_block(current_block):return Nonefor previous_index in range(current_index - 1, -1, -1):previous_block = ordered_blocks[previous_index][2]- if previous_block.get("type") in PAGE_AUXILIARY_BLOCK_TYPES:+ if previous_block.get("type") in MERGE_TRANSPARENT_BLOCK_TYPES:continueif _is_ref_text_list_block(previous_block):return ordered_blocks[previous_index]@@ -365,9 +365,7 @@ def _collect_following_same_orientation_lines() -> list[CalculationBBox]:"""在当前页向后读取至多五条同类型同方向行,语义屏障或非法文本会终止读取。"""following_lines: list[CalculationBBox] = []- transparent_types = (- TEXT_MERGE_TRANSPARENT_TYPES if current_type == BlockType.TEXT else PAGE_AUXILIARY_BLOCK_TYPES- )+ transparent_types = TEXT_MERGE_TRANSPARENT_TYPES if current_type == BlockType.TEXT else MERGE_TRANSPARENT_BLOCK_TYPESfor page_idx, _, block in ordered_blocks[current_index + 1 :]:if page_idx != current_page_idx:breakdiff --git a/mineru/backend/postprocess/table_merge/document.py b/mineru/backend/postprocess/table_merge/document.pyindex 05c64945..9161d929 100644--- a/mineru/backend/postprocess/table_merge/document.py+++ b/mineru/backend/postprocess/table_merge/document.py@@ -5,19 +5,13 @@ from __future__ import annotationsfrom typing import Any-from ....types import BlockType+from ....types import MERGE_TRANSPARENT_BLOCK_TYPES, BlockTypefrom .blocks import _get_or_create_table_statefrom .models import BlockDict, PageInfoDict, TableMergeStatefrom .structure import can_merge_tables-TABLE_BOUNDARY_IGNORED_TYPES = {- BlockType.HEADER,- BlockType.FOOTER,- BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,- BlockType.ASIDE_TEXT,-}+TABLE_BOUNDARY_IGNORED_TYPES = set(MERGE_TRANSPARENT_BLOCK_TYPES)def _clear_table_continuation_marker(table_block: BlockDict) -> None:diff --git a/mineru/model/flash/csv.py b/mineru/model/flash/csv.pyindex f98dd9c0..11446fc5 100644--- a/mineru/model/flash/csv.py+++ b/mineru/model/flash/csv.py@@ -28,9 +28,7 @@ _HEADER_KIND_DOMINANCE_DEN: Final = 10_MAX_HEADER_LABEL_CHARS: Final = 64_SEP_DIRECTIVE_RE = re.compile(r"\Asep=(?P<delimiter>[,;\t|])(?:\r\n|\n|\r|$)", re.IGNORECASE)_DISALLOWED_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]")-_DATE_RE = re.compile(- r"^\d{1,4}[-/.]\d{1,2}[-/.]\d{1,4}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?Z?)?$"-)+_DATE_RE = re.compile(r"^\d{1,4}[-/.]\d{1,2}[-/.]\d{1,4}(?:[ T]\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?Z?)?$")_TIME_RE = re.compile(r"^\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?Z?$")CsvValueKind: TypeAlias = Literal["number", "boolean", "date", "text"]@@ -135,18 +133,18 @@ def _read_csv_rows(text: str, delimiter: str) -> list[list[str]]:try:for record in reader:row = list(record) or [""]- rows.append(row)- if len(rows) > MAX_CSV_ROWS:+ next_row_count = len(rows) + 1+ if next_row_count > MAX_CSV_ROWS:raise ValueError(f"CSV exceeds max_rows={MAX_CSV_ROWS}")- max_columns = max(max_columns, len(row))- if max_columns > MAX_CSV_COLUMNS:+ next_max_columns = max(max_columns, len(row))+ if next_max_columns > MAX_CSV_COLUMNS:raise ValueError(f"CSV exceeds max_columns={MAX_CSV_COLUMNS}")+ if next_row_count * next_max_columns > MAX_CSV_GRID_SLOTS:+ raise ValueError(f"CSV exceeds max_grid_slots={MAX_CSV_GRID_SLOTS}")+ rows.append(row)+ max_columns = next_max_columnsexcept csv_module.Error as exc:raise ValueError(f"Malformed CSV near physical line {reader.line_num}: {exc}") from exc-- grid_slots = len(rows) * max_columns- if grid_slots > MAX_CSV_GRID_SLOTS:- raise ValueError(f"CSV exceeds max_grid_slots={MAX_CSV_GRID_SLOTS}")return rowsdiff --git a/mineru/model/flash/epub/converter.py b/mineru/model/flash/epub/converter.pyindex cb5b7924..eebe3f4f 100644--- a/mineru/model/flash/epub/converter.py+++ b/mineru/model/flash/epub/converter.py@@ -11,7 +11,6 @@ from lxml import etree # type: ignore[reportMissingImports]from .constants import SVG_MEDIA_TYPE, XHTML_MEDIA_TYPESfrom .errors import EpubEncryptedError, EpubParseError, EpubResourceLimitErrorfrom .package import EpubPackage-from .toc import build_epub_toc_indexfrom .xhtml import EpubChapterConverter, build_anchor_registry, convert_svg_spine@@ -28,7 +27,7 @@ class EpubConverter:try:parsed: list[tuple[int, str, str, etree._Element | None]] = []readable_count = 0- for index, spine_item in enumerate(package.content_spine_items()):+ for index, spine_item in enumerate(package.spine):if spine_item.path is None or spine_item.media_type is None:parsed.append((index, "", "", None))logger.warning("Skipping unsupported EPUB spine item index={} idref={!r}", index, spine_item.idref)@@ -50,13 +49,10 @@ class EpubConverter:raise EpubParseError("Malformed EPUB package: no selected spine content could be read")xhtml_chapters = [- (path, root)- for _, path, media_type, root in parsed- if root is not None and media_type in XHTML_MEDIA_TYPES+ (path, root) for _, path, media_type, root in parsed if root is not None and media_type in XHTML_MEDIA_TYPES]anchors = build_anchor_registry(xhtml_chapters, package)- toc_index = build_epub_toc_index(package, anchors)- pages: list[list[dict[str, Any]]] = [[toc_index]] if toc_index is not None else []+ pages: list[list[dict[str, Any]]] = []for index, path, media_type, root in parsed:if root is None:pages.append([])diff --git a/mineru/model/flash/epub/metadata.py b/mineru/model/flash/epub/metadata.pyindex 2b272f19..a240a3e5 100644--- a/mineru/model/flash/epub/metadata.py+++ b/mineru/model/flash/epub/metadata.py@@ -5,24 +5,12 @@ from __future__ import annotationsfrom typing import BinaryIO-from .constants import XHTML_MEDIA_TYPESfrom .package import EpubPackage-from .toc import build_epub_toc_index-from .xhtml import build_anchor_registrydef _epub_output_page_count(package: EpubPackage) -> int:- """按去重后的正文 spine 和可生成目录页计算最终输出页数。"""- chapters = []- for item in package.content_spine_items():- if item.path is None or item.media_type not in XHTML_MEDIA_TYPES:- continue- root = package.xml_part(item.path, allow_external_doctype=True)- if root is not None:- chapters.append((item.path, root))- anchors = build_anchor_registry(chapters, package)- toc_page_count = 1 if build_epub_toc_index(package, anchors) is not None else 0- return len(package.content_spine_items()) + toc_page_count+ """按 OPF spine 项数量返回稳定的逻辑页数。"""+ return len(package.spine)def extract_epub_metadata(file_binary: BinaryIO) -> dict[str, object | None]:diff --git a/mineru/model/flash/epub/package.py b/mineru/model/flash/epub/package.pyindex 5ea52dce..3a4a80cf 100644--- a/mineru/model/flash/epub/package.py+++ b/mineru/model/flash/epub/package.py@@ -226,9 +226,7 @@ class EpubPackage:self._asset_parts.add(part_name)self._asset_bytes += byte_countif self._asset_bytes > MAX_ASSET_TOTAL_BYTES:- raise EpubResourceLimitError(- f"EPUB resource limit exceeded: max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}"- )+ raise EpubResourceLimitError(f"EPUB resource limit exceeded: max_asset_total_bytes={MAX_ASSET_TOTAL_BYTES}")def xml_part(self,@@ -468,12 +466,6 @@ class EpubPackage:item = self.manifest.get(toc_id)return item.path if item is not None and item.path else None- def content_spine_items(self) -> list[EpubSpineItem]:- """返回去除 navigation document occurrence 后的正文 spine 项。"""- if self.navigation_path is None:- return list(self.spine)- return [item for item in self.spine if item.path != self.navigation_path]-def _read_metadata(self) -> EpubMetadata:"""提取 OPF 的首个标题、作者、主题、关键词和布局模式。"""title = author = subject = Nonediff --git a/mineru/model/flash/epub/toc.py b/mineru/model/flash/epub/toc.pydeleted file mode 100644index a4d8d8bd..00000000--- a/mineru/model/flash/epub/toc.py+++ /dev/null@@ -1,323 +0,0 @@-# Copyright (c) Opendatalab. All rights reserved.-"""把 EPUB3 navigation、EPUB2 NCX 或正文标题转换为 raw IndexBlock。"""--from __future__ import annotations--import html-import re-from dataclasses import dataclass--from loguru import logger-from lxml import etree # type: ignore[reportMissingImports]--from ....types import BlockType-from .errors import EpubEncryptedError, EpubParseError, EpubResourceLimitError-from .package import EpubPackage-from .xhtml import EpubAnchorRegistry, EpubHeadingEntry---_WHITESPACE_RE = re.compile(r"\s+")---@dataclass(frozen=True, slots=True)-class TocEntry:- """保存一个目录标签、可选正文 anchor 和嵌套子项。"""-- label: str- anchor: str | None- children: tuple[TocEntry, ...] = ()---@dataclass(slots=True)-class _MutableTocEntry:- """供 heading level stack 构造目录树使用的可变节点。"""-- label: str- anchor: str | None- children: list[_MutableTocEntry]---def _local_name(element: etree._Element) -> str:- """返回 navigation/NCX 元素不含命名空间的小写本地名。"""- return etree.QName(element).localname.casefold()---def _epub_types(element: etree._Element) -> frozenset[str]:- """读取 EPUB 命名空间或未命名 type 属性中的结构语义 token。"""- values: list[str] = []- for name, value in element.attrib.items():- local_name = etree.QName(name).localname if name.startswith("{") else name.split(":", 1)[-1]- if local_name == "type":- values.extend(value.casefold().split())- return frozenset(values)---def _normalized_text(value: str) -> str:- """折叠目录标签空白并返回可见文本。"""- return _WHITESPACE_RE.sub(" ", html.unescape(value)).strip()---def _label_text(element: etree._Element) -> str:- """提取目录标签文本,并用图片 alt/title 代替非文本内容。"""- parts: list[str] = []-- def walk(node: etree._Element) -> None:- """按 DOM 顺序收集文本和图片替代文本。"""- if node.text:- parts.append(node.text)- for child in node:- if not isinstance(child.tag, str):- entity_name = getattr(child, "name", "")- if entity_name:- parts.append(html.unescape(f"&{entity_name};"))- if child.tail:- parts.append(child.tail)- continue- name = _local_name(child)- if name in {"img", "image"}:- alternative = child.get("alt") or child.get("title") or ""- if alternative:- parts.append(alternative)- elif name not in {"ol", "ul"}:- walk(child)- if child.tail:- parts.append(child.tail)-- walk(element)- return _normalized_text("".join(parts))---def _direct_children(element: etree._Element, name: str) -> list[etree._Element]:- """返回指定本地名的直接普通子元素。"""- return [- child- for child in element- if isinstance(child.tag, str) and _local_name(child) == name- ]---def _parse_nav_list(- list_element: etree._Element,- *,- base_part: str,- anchors: EpubAnchorRegistry,-) -> tuple[TocEntry, ...]:- """递归解析 EPUB3 toc nav 的 ol/li 层级。"""- entries: list[TocEntry] = []- for item in _direct_children(list_element, "li"):- label_element = next(- (- child- for child in item- if isinstance(child.tag, str) and _local_name(child) in {"a", "span"}- ),- None,- )- nested_lists = [- child- for child in item- if isinstance(child.tag, str) and _local_name(child) in {"ol", "ul"}- ]- children = tuple(- child_entry- for nested in nested_lists- for child_entry in _parse_nav_list(nested, base_part=base_part, anchors=anchors)- )- if label_element is None:- entries.extend(children)- continue- label = _label_text(label_element)- if not label:- entries.extend(children)- continue- href = label_element.get("href") or ""- anchor = anchors.resolve_anchor(href, base_part=base_part) if href else None- entries.append(TocEntry(label, anchor, children))- return tuple(entries)---def _parse_epub3_navigation(- package: EpubPackage,- anchors: EpubAnchorRegistry,-) -> tuple[TocEntry, ...]:- """读取 EPUB3 navigation document 中唯一需要的主 toc nav。"""- if package.navigation_path is None:- return ()- try:- root = package.xml_part(package.navigation_path, allow_external_doctype=True)- except EpubResourceLimitError:- raise- except (EpubEncryptedError, EpubParseError) as exc:- logger.warning("Skipping unusable EPUB navigation document {!r}: {}", package.navigation_path, exc)- return ()- if root is None:- return ()- toc_nav = next(- (- element- for element in root.iter()- if isinstance(element.tag, str)- and _local_name(element) == "nav"- and (- "toc" in _epub_types(element)- or "doc-toc" in (element.get("role") or "").casefold().split()- )- ),- None,- )- if toc_nav is None:- return ()- root_list = next(- (- element- for element in toc_nav- if isinstance(element.tag, str) and _local_name(element) in {"ol", "ul"}- ),- None,- )- return _parse_nav_list(root_list, base_part=package.navigation_path, anchors=anchors) if root_list is not None else ()---def _parse_ncx_point(- point: etree._Element,- *,- base_part: str,- anchors: EpubAnchorRegistry,-) -> TocEntry | None:- """递归解析一个 NCX navPoint。"""- label_container = next(iter(_direct_children(point, "navlabel")), None)- label_element = (- next(- (- element- for element in label_container.iter()- if isinstance(element.tag, str) and _local_name(element) == "text"- ),- None,- )- if label_container is not None- else None- )- label = _label_text(label_element) if label_element is not None else ""- children = tuple(- child_entry- for child in _direct_children(point, "navpoint")- if (child_entry := _parse_ncx_point(child, base_part=base_part, anchors=anchors)) is not None- )- if not label:- return TocEntry("", None, children) if children else None- content = next(iter(_direct_children(point, "content")), None)- src = content.get("src") if content is not None else ""- anchor = anchors.resolve_anchor(src or "", base_part=base_part) if src else None- return TocEntry(label, anchor, children)---def _flatten_empty_ncx_entries(entries: tuple[TocEntry, ...]) -> tuple[TocEntry, ...]:- """移除 NCX 无标签容器,同时保留其有效子项。"""- result: list[TocEntry] = []- for entry in entries:- children = _flatten_empty_ncx_entries(entry.children)- if entry.label:- result.append(TocEntry(entry.label, entry.anchor, children))- else:- result.extend(children)- return tuple(result)---def _parse_epub2_ncx(- package: EpubPackage,- anchors: EpubAnchorRegistry,-) -> tuple[TocEntry, ...]:- """读取 EPUB2 NCX navMap,并保留嵌套 navPoint。"""- if package.ncx_path is None:- return ()- try:- root = package.xml_part(package.ncx_path, allow_external_doctype=True)- except EpubResourceLimitError:- raise- except (EpubEncryptedError, EpubParseError) as exc:- logger.warning("Skipping unusable EPUB NCX {!r}: {}", package.ncx_path, exc)- return ()- if root is None:- return ()- nav_map = next(- (- element- for element in root.iter()- if isinstance(element.tag, str) and _local_name(element) == "navmap"- ),- None,- )- if nav_map is None:- return ()- parsed = tuple(- entry- for point in _direct_children(nav_map, "navpoint")- if (entry := _parse_ncx_point(point, base_part=package.ncx_path, anchors=anchors)) is not None- )- return _flatten_empty_ncx_entries(parsed)---def _freeze_heading_entry(entry: _MutableTocEntry) -> TocEntry:- """把可变 heading 节点递归冻结为 TocEntry。"""- return TocEntry(entry.label, entry.anchor, tuple(_freeze_heading_entry(child) for child in entry.children))---def _toc_from_headings(headings: tuple[EpubHeadingEntry, ...]) -> tuple[TocEntry, ...]:- """按 heading level stack 构造目录树,跨级时不生成空节点。"""- roots: list[_MutableTocEntry] = []- stack: list[tuple[int, _MutableTocEntry]] = []- for heading in headings:- entry = _MutableTocEntry(heading.label, heading.anchor, [])- while stack and heading.level <= stack[-1][0]:- stack.pop()- if stack:- stack[-1][1].children.append(entry)- else:- roots.append(entry)- stack.append((heading.level, entry))- return tuple(_freeze_heading_entry(entry) for entry in roots)---def _raw_index_content(entries: tuple[TocEntry, ...], *, depth: int) -> list[dict[str, object]]:- """把 TocEntry 树转换为现有 raw IndexBlock 叶子与嵌套结构。"""- content: list[dict[str, object]] = []- for entry in entries:- leaf: dict[str, object] = {- "type": BlockType.TEXT,- "content": html.escape(entry.label, quote=False),- }- if entry.anchor:- leaf["anchor"] = entry.anchor- content.append(leaf)- if entry.children:- content.append(- {- "type": BlockType.INDEX,- "ilevel": depth + 1,- "content": _raw_index_content(entry.children, depth=depth + 1),- }- )- return content---def build_epub_toc_index(- package: EpubPackage,- anchors: EpubAnchorRegistry,-) -> dict[str, object] | None:- """按 EPUB3 nav、EPUB2 NCX、正文标题优先级构造顶层 raw IndexBlock。"""- entries = _parse_epub3_navigation(package, anchors)- if not entries:- entries = _parse_epub2_ncx(package, anchors)- if not entries:- entries = _toc_from_headings(anchors.heading_entries())- if not entries:- return None- return {- "type": BlockType.INDEX,- "ilevel": 0,- "content": _raw_index_content(entries, depth=0),- }---__all__ = ["TocEntry", "build_epub_toc_index"]diff --git a/mineru/model/flash/epub/xhtml.py b/mineru/model/flash/epub/xhtml.pyindex c75ffed2..5c012d56 100644--- a/mineru/model/flash/epub/xhtml.py+++ b/mineru/model/flash/epub/xhtml.py@@ -118,6 +118,11 @@ def _visible_text(element: etree._Element) -> str:return _WHITESPACE_RE.sub(" ", html.unescape("".join(element.itertext()))).strip()+def _normalized_toc_label(value: str) -> str:+ """规范目录标签的实体、空白和大小写,供严格标题匹配使用。"""+ return _WHITESPACE_RE.sub(" ", html.unescape(value)).strip().casefold()++def _entity_text(element: etree._Element) -> str:"""把未解析的安全 HTML 命名实体转换为可见文本。"""name = getattr(element, "name", "")@@ -198,15 +203,6 @@ class _ChapterTree:root: etree._Element-@dataclass(frozen=True, slots=True)-class EpubHeadingEntry:- """保存 heading fallback 目录使用的标题文本、层级和 anchor。"""-- label: str- level: int- anchor: str--class EpubAnchorRegistry:"""建立章节路径、标题与 note fragment 到实际 canonical anchor 的别名表。"""@@ -216,12 +212,13 @@ class EpubAnchorRegistry:self._heading_anchors: dict[etree._Element, str] = {}self._note_anchors: dict[etree._Element, str] = {}self._targets: dict[tuple[str, str | None], str] = {}- self._heading_entries: list[EpubHeadingEntry] = []+ self._heading_labels: dict[str, str] = {}for chapter in chapters:headings = [elementfor element in chapter.root.iter()- if isinstance(element.tag, str) and _local_name(element) in {"h1", "h2", "h3", "h4", "h5", "h6"}+ if isinstance(element.tag, str)+ and _local_name(element) in {"h1", "h2", "h3", "h4", "h5", "h6"}and _visible_text(element)]for ordinal, heading in enumerate(headings):@@ -229,13 +226,7 @@ class EpubAnchorRegistry:identity = f"{source_id or 'heading'}-{ordinal}"anchor = _canonical_anchor(chapter.path, identity)self._heading_anchors[heading] = anchor- self._heading_entries.append(- EpubHeadingEntry(- label=_visible_text(heading),- level=int(_local_name(heading)[1:]),- anchor=anchor,- )- )+ self._heading_labels[anchor] = _visible_text(heading)notes = [elementfor element in chapter.root.iter()@@ -255,28 +246,40 @@ class EpubAnchorRegistry:continueif (chapter.path, fragment) in self._targets:continue- target_anchor = self._heading_anchors.get(element) or self._note_anchors.get(element)- if target_anchor is None:- descendant = next(- (- child- for child in element.iterdescendants()- if isinstance(child.tag, str) and child in self._heading_anchors- ),- None,- )- if descendant is not None:- target_anchor = self._heading_anchors[descendant]+ target_anchor = self._target_anchor_for_element(element)if target_anchor is not None:self._targets[(chapter.path, fragment)] = target_anchor+ def _target_anchor_for_element(self, element: etree._Element) -> str | None:+ """把任意 fragment 元素映射到自身、祖先或后代的可输出标题与脚注。"""+ direct = self._heading_anchors.get(element) or self._note_anchors.get(element)+ if direct is not None:+ return direct+ ancestor = next(+ (parent for parent in element.iterancestors() if parent in self._heading_anchors or parent in self._note_anchors),+ None,+ )+ if ancestor is not None:+ return self._heading_anchors.get(ancestor) or self._note_anchors.get(ancestor)+ descendant = next(+ (+ child+ for child in element.iterdescendants()+ if isinstance(child.tag, str) and (child in self._heading_anchors or child in self._note_anchors)+ ),+ None,+ )+ if descendant is None:+ return None+ return self._heading_anchors.get(descendant) or self._note_anchors.get(descendant)+def heading_anchor(self, heading: etree._Element) -> str | None:"""返回一个已预扫描标题的规范 anchor。"""return self._heading_anchors.get(heading)- def heading_entries(self) -> tuple[EpubHeadingEntry, ...]:- """按 spine 和文档顺序返回全部可见标题记录。"""- return tuple(self._heading_entries)+ def heading_label(self, anchor: str) -> str | None:+ """返回 canonical 标题 anchor 对应的可见标题文本。"""+ return self._heading_labels.get(anchor)def note_anchor(self, note: etree._Element) -> str | None:"""返回一个已预扫描 Footnote/Endnote 的 canonical anchor。"""@@ -358,11 +361,7 @@ class EpubChapterConverter:def convert(self) -> list[dict[str, object]]:"""解析 XHTML body 并返回按 DOM 顺序排列的 raw blocks。"""body = next(- (- element- for element in self.root.iter()- if isinstance(element.tag, str) and _local_name(element) == "body"- ),+ (element for element in self.root.iter() if isinstance(element.tag, str) and _local_name(element) == "body"),None,)if body is None:@@ -529,9 +528,7 @@ class EpubChapterConverter:alt = (caption or element.get("alt") or element.get("title") or "").strip()if data_uri is None:return [{"type": BlockType.TEXT, "content": html.escape(alt, quote=False)}] if alt else []- blocks: list[dict[str, object]] = [- {"type": BlockType.IMAGE, "content": "", "image_base64": data_uri}- ]+ blocks: list[dict[str, object]] = [{"type": BlockType.IMAGE, "content": "", "image_base64": data_uri}]if alt:blocks.append({"type": BlockType.IMAGE_CAPTION, "content": html.escape(alt, quote=False)})return blocks@@ -559,11 +556,7 @@ class EpubChapterConverter:def _parse_figure(self, element: etree._Element, style: TextStyle) -> list[dict[str, object]]:"""解析 figure 中的图片和 figcaption,其余内容按普通容器处理。"""caption_element = next(- (- child- for child in element- if isinstance(child.tag, str) and _local_name(child) == "figcaption"- ),+ (child for child in element if isinstance(child.tag, str) and _local_name(child) == "figcaption"),None,)caption = _visible_text(caption_element) if caption_element is not None else ""@@ -576,9 +569,7 @@ class EpubChapterConverter:blocks.extend(self._image_blocks(child, caption=caption))elif name != "figcaption":child_blocks = (- self._parse_block(child, style)- if name in _BLOCK_TAGS- else self._render_inline_element(child, style)[1]+ self._parse_block(child, style) if name in _BLOCK_TAGS else self._render_inline_element(child, style)[1])blocks.extend(child_blocks)if not blocks and caption:@@ -610,18 +601,20 @@ class EpubChapterConverter:return []blocks: list[dict[str, object]] = [{"type": BlockType.TABLE, "content": markup}]caption_element = next(- (- child- for child in table- if isinstance(child.tag, str) and _local_name(child) == "caption"- ),+ (child for child in table if isinstance(child.tag, str) and _local_name(child) == "caption"),None,)if caption_element is not None and (caption := _visible_text(caption_element)):blocks.append({"type": BlockType.TABLE_CAPTION, "content": html.escape(caption, quote=False)})return blocks- def _serialize_table_node(self, element: etree._Element, inherited: TextStyle) -> str:+ def _serialize_table_node(+ self,+ element: etree._Element,+ inherited: TextStyle,+ *,+ row_link_target: str | None = None,+ ) -> str:"""递归序列化安全表格结构、行内样式、链接、公式和包内图片。"""resolved = self.stylesheet.resolve(element, inherited)if resolved.hidden:@@ -656,7 +649,7 @@ class EpubChapterConverter:"u",}if name not in allowed:- return self._serialize_table_children(element, resolved.text)+ return self._serialize_table_children(element, resolved.text, row_link_target=row_link_target)if name == "br":return "<br>"if name == "math":@@ -667,6 +660,8 @@ class EpubChapterConverter:data_uri = self._image_data_uri(src)alt = html.escape(element.get("alt") or "", quote=True)return f'<img src="{html.escape(data_uri, quote=True)}" alt="{alt}">' if data_uri else alt+ if name == "tr":+ row_link_target = self._toc_table_row_target(element)attributes: list[str] = []if name in {"td", "th"}:for attribute in ("colspan", "rowspan", "scope"):@@ -681,21 +676,64 @@ class EpubChapterConverter:target = self.anchors.resolve_link(element.get("href") or "", base_part=self.chapter_path)if target:attributes.append(f'href="{html.escape(target, quote=True)}"')- inner = self._serialize_table_children(element, resolved.text)+ inner = self._serialize_table_children(element, resolved.text, row_link_target=row_link_target)+ if name in {"td", "th"} and row_link_target and self._table_cell_can_inherit_toc_link(element):+ inner = f'<a href="{html.escape(row_link_target, quote=True)}">{inner}</a>'attrs = f" {' '.join(attributes)}" if attributes else ""return f"<{name}{attrs}>{inner}</{name}>"- def _serialize_table_children(self, element: etree._Element, style: TextStyle) -> str:+ def _serialize_table_children(+ self,+ element: etree._Element,+ style: TextStyle,+ *,+ row_link_target: str | None = None,+ ) -> str:"""序列化表格节点的文本、子元素和 tail。"""parts = [self._render_table_text(element.text, style)]for child in element:if isinstance(child.tag, str):- parts.append(self._serialize_table_node(child, style))+ parts.append(self._serialize_table_node(child, style, row_link_target=row_link_target))else:parts.append(self._render_table_text(_entity_text(child), style))parts.append(self._render_table_text(child.tail, style))return "".join(parts)+ def _toc_table_row_target(self, row: etree._Element) -> str | None:+ """为严格匹配单一目标标题的目录表格行返回内部链接。"""+ links = [+ element+ for element in row.iter()+ if isinstance(element.tag, str) and _local_name(element) == "a" and (element.get("href") or "").strip()+ ]+ if not links:+ return None+ resolved_targets: list[str] = []+ for link in links:+ target = self.anchors.resolve_link(link.get("href") or "", base_part=self.chapter_path)+ if target is None or not target.startswith("#"):+ return None+ resolved_targets.append(target)+ if len(set(resolved_targets)) != 1:+ return None+ target = resolved_targets[0]+ title = self.anchors.heading_label(target[1:])+ if title is None:+ return None+ cells = [child for child in row if isinstance(child.tag, str) and _local_name(child) in {"td", "th"}]+ row_label = " ".join(value for cell in cells if (value := _visible_text(cell)))+ if not row_label or _normalized_toc_label(row_label) != _normalized_toc_label(title):+ return None+ return target++ @staticmethod+ def _table_cell_can_inherit_toc_link(cell: etree._Element) -> bool:+ """只允许纯文本与行内样式单元格继承目录行的唯一内部链接。"""+ if not _visible_text(cell):+ return False+ allowed_inline = {"b", "br", "code", "em", "i", "s", "span", "strong", "sub", "sup", "u"}+ return all(isinstance(child.tag, str) and _local_name(child) in allowed_inline for child in cell.iterdescendants())+@staticmethoddef _render_table_text(value: str | None, style: TextStyle) -> str:"""把表格文字转义后包装为 renderer 支持的安全 HTML 样式标签。"""@@ -866,7 +904,6 @@ def convert_svg_spine(__all__ = ["EpubAnchorRegistry","EpubChapterConverter",- "EpubHeadingEntry","build_anchor_registry","convert_svg_spine",]diff --git a/mineru/render/_internal/common/planner.py b/mineru/render/_internal/common/planner.pyindex 9968b0ab..e940812c 100644--- a/mineru/render/_internal/common/planner.py+++ b/mineru/render/_internal/common/planner.py@@ -8,7 +8,7 @@ from dataclasses import dataclass, fieldfrom ....backend.postprocess.table_merge import merge_table_contentfrom ...contracts import RenderModefrom ....types import (- PAGE_AUXILIARY_BLOCK_TYPES,+ MERGE_TRANSPARENT_BLOCK_TYPES,BlockType,ContinuableTextBlockBase,ListBlock,@@ -78,7 +78,7 @@ def _find_previous_planned_text(blocks: list[PlannedBlock], current_index: int)previous_index = current_index - 1while previous_index >= 0:candidate = blocks[previous_index]- if candidate.block.type in PAGE_AUXILIARY_BLOCK_TYPES:+ if candidate.block.type in MERGE_TRANSPARENT_BLOCK_TYPES:previous_index -= 1continueif not isinstance(candidate.block, RefTextBlock):@@ -96,7 +96,7 @@ def _find_previous_planned_text(blocks: list[PlannedBlock], current_index: int)def _merge_continued_list_blocks(blocks: list[PlannedBlock], mode: RenderMode) -> None:- """把续接列表吸收到子类型一致的前序列表,参考文献可跨过页面辅助块。"""+ """把续接列表吸收到子类型一致的前序列表,参考文献可跨过合并透明块。"""for current_index, current in enumerate(blocks):if current.removed or not isinstance(current.block, ListBlock) or current.block.continues_prev is not True:continue@@ -116,7 +116,7 @@ def _find_previous_planned_list(blocks: list[PlannedBlock],current_index: int,) -> PlannedBlock | None:- """查找前序有效列表,仅允许参考文献跳过页面辅助块。"""+ """查找前序有效列表,仅允许参考文献跳过合并透明块。"""current = blocks[current_index]if not isinstance(current.block, ListBlock):return None@@ -124,7 +124,7 @@ def _find_previous_planned_list(previous_index = current_index - 1while previous_index >= 0:candidate = blocks[previous_index]- if can_skip_page_auxiliary and candidate.block.type in PAGE_AUXILIARY_BLOCK_TYPES:+ if can_skip_page_auxiliary and candidate.block.type in MERGE_TRANSPARENT_BLOCK_TYPES:previous_index -= 1continueif not isinstance(candidate.block, ListBlock):diff --git a/mineru/render/_internal/docx/renderer.py b/mineru/render/_internal/docx/renderer.pyindex 42a5ad80..9e83c713 100644--- a/mineru/render/_internal/docx/renderer.py+++ b/mineru/render/_internal/docx/renderer.py@@ -84,6 +84,7 @@ from ....types import (ListBlock,MiddleJson,PageAuxTextBlock,+ PageFootnoteBlock,ParagraphTitleBlock,RefTextBlock,TableAnnotationBlock,@@ -118,18 +119,13 @@ class _DocxRenderer:mode: RenderMode,asset_resolver: AssetResolver | None,) -> None:- """初始化 renderer,并按展示模式预注册标题与页面脚注 anchor。"""+ """初始化 renderer,并预注册标题与默认可见页面脚注 anchor。"""self.middle_json = middle_jsonself.mode = modeself.asset_resolver = asset_resolverself.document = Document()configure_document(self.document)- self.bookmarks = BookmarkRegistry(- _iter_document_anchors(- middle_json,- include_page_footnotes=mode is RenderMode.FULL,- )- )+ self.bookmarks = BookmarkRegistry(_iter_document_anchors(middle_json))self.usable_width_emu = usable_width_emu(self.document)self.usable_width_twips = usable_width_twips(self.document)@@ -165,11 +161,14 @@ class _DocxRenderer:if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):self._render_title(block, context)return+ if isinstance(block, PageFootnoteBlock):+ paragraph = self.document.add_paragraph(style=FOOTNOTE_STYLE)+ append_inline_content(paragraph, block.content, context=context)+ self.bookmarks.attach(paragraph, block.anchor)+ returnif isinstance(block, PageAuxTextBlock):paragraph = self.document.add_paragraph(style=AUXILIARY_STYLE)append_inline_content(paragraph, block.content, context=context)- if block.type == BlockType.PAGE_FOOTNOTE:- self.bookmarks.attach(paragraph, block.anchor)returnif isinstance(block, EquationBlock):self._render_equation(block, context)@@ -767,22 +766,13 @@ def render_docx().render()-def _iter_document_anchors(- middle_json: MiddleJson,- *,- include_page_footnotes: bool,-) -> Iterable[str]:- """按当前展示模式遍历实际会写入 bookmark 的标题和页面脚注 anchor。"""+def _iter_document_anchors(middle_json: MiddleJson) -> Iterable[str]:+ """遍历标题和默认可见页面脚注实际会写入的 bookmark anchor。"""for page in middle_json.pages:for block in page.blocks:if isinstance(block, TitleBlockBase) and block.anchor:yield block.anchor- elif (- include_page_footnotes- and isinstance(block, PageAuxTextBlock)- and block.type == BlockType.PAGE_FOOTNOTE- and block.anchor- ):+ elif isinstance(block, PageFootnoteBlock) and block.anchor:yield block.anchordiff --git a/mineru/render/_internal/html/renderer.py b/mineru/render/_internal/html/renderer.pyindex 0cf9414a..977463e2 100644--- a/mineru/render/_internal/html/renderer.py+++ b/mineru/render/_internal/html/renderer.py@@ -49,6 +49,7 @@ from ....types import (ListBlock,MiddleJson,PageAuxTextBlock,+ PageFootnoteBlock,ParagraphTitleBlock,RefTextBlock,TableAnnotationBlock,@@ -192,6 +193,14 @@ class _HtmlRenderer: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, PageFootnoteBlock):+ rendered = render_inline_content_html(block.content)+ self._observe_inline(rendered)+ if not rendered.html:+ return ""+ attrs = ['class="mineru-page-footnote"', 'data-block-type="page_footnote"']+ self._append_anchor_attribute(attrs, block.anchor, block_type=str(block.type))+ return f"<div {' '.join(attrs)}>{rendered.html}</div>"if isinstance(block, PageAuxTextBlock):rendered = render_inline_content_html(block.content)self._observe_inline(rendered)@@ -199,8 +208,6 @@ class _HtmlRenderer:return ""class_name = html.escape(str(block.type).replace("_", "-"), quote=True)attrs = [f'class="mineru-page-aux mineru-page-aux--{class_name}"']- if block.type == BlockType.PAGE_FOOTNOTE:- self._append_anchor_attribute(attrs, block.anchor, block_type=str(block.type))return f"<div {' '.join(attrs)}>{rendered.html}</div>"if isinstance(block, EquationBlock):return self._render_equation(block)@@ -737,7 +744,7 @@ def _collect_document_anchor_ids(middle_json: MiddleJson) -> dict[str, str]:for block in page.blocks:if isinstance(block, TitleBlockBase):visible_content = inline_plain_text(parse_inline_content(block.content)).strip()- elif isinstance(block, PageAuxTextBlock) and block.type == BlockType.PAGE_FOOTNOTE:+ elif isinstance(block, PageFootnoteBlock):visible_content = inline_plain_text(parse_inline_content(block.content)).strip()else:continuediff --git a/mineru/render/_internal/markdown/blocks.py b/mineru/render/_internal/markdown/blocks.pyindex 7522b256..6e975613 100644--- a/mineru/render/_internal/markdown/blocks.py+++ b/mineru/render/_internal/markdown/blocks.py@@ -40,6 +40,7 @@ from ....types import (IndexBlock,ListBlock,PageAuxTextBlock,+ PageFootnoteBlock,PageBlock,ParagraphTitleBlock,RefTextBlock,@@ -73,14 +74,11 @@ def render_planned_block(return escape_standalone_marker_rule(content)if isinstance(block, (DocTitleBlock, ParagraphTitleBlock)):return _render_title(block, delimiters)+ if isinstance(block, PageFootnoteBlock):+ return _render_page_footnote(block, delimiters)if isinstance(block, PageAuxTextBlock):content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))- rendered = escape_standalone_marker_rule(content)- if block.type == BlockType.PAGE_FOOTNOTE and block.anchor:- anchor = html.escape(block.anchor.strip(), quote=True)- if anchor:- return f'<a id="{anchor}"></a>\n{rendered}'- return rendered+ return escape_standalone_marker_rule(content)if isinstance(block, EquationBlock):return _render_equation(block, delimiters, asset_base_url, image_renderer)if isinstance(block, ListBlock):@@ -98,6 +96,24 @@ def render_planned_block(raise TypeError(f"Unsupported PageBlock type: {type(block).__name__}")+def _render_page_footnote(block: PageFootnoteBlock, delimiters: LatexDelimitersConfig) -> str:+ """用非折叠的小字号浅色 HTML 标识输出页面脚注。"""+ content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))+ rendered = escape_standalone_marker_rule(content)+ if not rendered.strip():+ return ""+ rendered = rendered.replace("\r\n", "\n").replace("\r", "\n").replace("\n", "<br>")+ attrs = [+ 'class="mineru-page-footnote"',+ 'data-block-type="page_footnote"',+ 'style="color:#6b7280"',+ ]+ anchor = (block.anchor or "").strip()+ if anchor:+ attrs.insert(0, f'id="{html.escape(anchor, quote=True)}"')+ return f"<small><span {' '.join(attrs)}>{rendered}</span></small>"++def render_single_block(block: PageBlock,*,diff --git a/mineru/render/_internal/structured_content/renderer.py b/mineru/render/_internal/structured_content/renderer.pyindex e2e95d4b..0f747d6c 100644--- a/mineru/render/_internal/structured_content/renderer.py+++ b/mineru/render/_internal/structured_content/renderer.py@@ -30,6 +30,7 @@ from ....types import (ImagePayloadBlock,MiddleJson,PageAuxTextBlock,+ PageFootnoteBlock,PageBlock,ParagraphTitleBlock,TableAnnotationBlock,@@ -109,7 +110,7 @@ def _render_content_block(if image_source is not None:payload["image_source"] = image_sourcereturn payload- if isinstance(block, PageAuxTextBlock):+ if isinstance(block, (PageAuxTextBlock, PageFootnoteBlock)):content = escape_text_block_markdown_prefix(render_inline_content(block.content, delimiters))payload["content"] = escape_standalone_marker_rule(content)return payloaddiff --git a/mineru/resources/html/mineru.css b/mineru/resources/html/mineru.cssindex 7f0c8f63..73e1cd1f 100644--- a/mineru/resources/html/mineru.css+++ b/mineru/resources/html/mineru.css@@ -326,7 +326,8 @@text-align: left;}-.mineru-document .mineru-footnote {+.mineru-document .mineru-footnote,+.mineru-document .mineru-page-footnote {color: var(--mineru-muted);font-size: 0.875em;margin-top: 0.4rem;diff --git a/mineru/resources/html/mineru.min.css b/mineru/resources/html/mineru.min.cssindex fb56ae1a..1ca75ee7 100644--- a/mineru/resources/html/mineru.min.css+++ b/mineru/resources/html/mineru.min.css@@ -1 +1 @@-.mineru-html-body{background:#ffffff;margin:0}.mineru-html-body>.mineru-document{margin:0 auto;max-width:60rem;min-height:100vh;padding:2rem}.mineru-document{--mineru-accent:#0b6fc2;--mineru-accent-hover:#075a9c;--mineru-background:#ffffff;--mineru-border:#d1d5db;--mineru-muted:#6b7280;--mineru-surface:#f8fafc;--mineru-text:#1f2937;background:var(--mineru-background);box-sizing:border-box;color:var(--mineru-text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:16px;line-height:1.65;overflow-wrap:break-word;width:100%}.mineru-document *,.mineru-document *::before,.mineru-document *::after{box-sizing:inherit}.mineru-document :is(h1,h2,h3,h4,h5,h6){color:var(--mineru-text);font-weight:600;line-height:1.3;margin:1.5em 0 0.65em}.mineru-document h1{font-size:2rem}.mineru-document h2{font-size:1.5rem}.mineru-document h3{font-size:1.25rem}.mineru-document h4{font-size:1.125rem}.mineru-document h5{font-size:1rem}.mineru-document h6{color:var(--mineru-muted);font-size:0.875rem}.mineru-document .mineru-block:first-child>:first-child,.mineru-document .mineru-page>.mineru-block:first-child>:first-child{margin-top:0}.mineru-document p{margin:0 0 1rem}.mineru-document :is(strong,b){font-weight:700}.mineru-document :is(s,del){color:var(--mineru-muted)}.mineru-document a{color:var(--mineru-accent);text-decoration:none;text-underline-offset:0.15em}.mineru-document a:hover{color:var(--mineru-accent-hover);text-decoration:underline}.mineru-document a:focus-visible{border-radius:0.15rem;outline:2px solid var(--mineru-accent);outline-offset:2px}.mineru-document blockquote{background:var(--mineru-surface);border-left:0.25rem solid var(--mineru-accent);color:var(--mineru-muted);margin:1rem 0;padding:0.75rem 1rem}.mineru-document blockquote>:first-child{margin-top:0}.mineru-document blockquote>:last-child{margin-bottom:0}.mineru-document :is(ol,ul){margin:0 0 1rem;padding-left:1.75rem}.mineru-document ul{list-style:disc}.mineru-document ul ul{list-style:circle}.mineru-document ul ul ul{list-style:square}.mineru-document ol{list-style:decimal}.mineru-document :is(ol,ul) ol{list-style-type:lower-roman}.mineru-document :is(ol,ul) :is(ol,ul) ol{list-style-type:lower-alpha}.mineru-document li + li{margin-top:0.25rem}.mineru-document li>:is(ol,ul){margin-bottom:0;margin-top:0.25rem}.mineru-document .mineru-list--explicit{list-style:none;padding-left:1.5rem}.mineru-document .mineru-list--unmarked{list-style:none;padding-left:0}.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-item--orphan{display:grid;grid-template-columns:0 minmax(0,1fr);list-style:none}.mineru-document .mineru-list-item--markerless{list-style:none}.mineru-document .mineru-list-marker{font-variant-numeric:tabular-nums;text-align:right;user-select:none;white-space:pre}.mineru-document .mineru-list-content{min-width:0}.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}.mineru-document table{border-collapse:collapse;border-spacing:0;display:block;margin:1rem 0;max-width:100%;overflow-x:auto;width:100%}.mineru-document :is(th,td){border:1px solid var(--mineru-border);padding:0.5rem 0.75rem;text-align:left;vertical-align:top}.mineru-document th{background:var(--mineru-surface);font-weight:600}.mineru-document caption{color:var(--mineru-muted);margin-bottom:0.5rem;text-align:left}.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 img{height:auto;max-width:100%}.mineru-document .mineru-figure{margin:1.5rem 0;max-width:100%}.mineru-document .mineru-figure>img{display:block;margin-inline:0}.mineru-document .mineru-flowchart{margin:1rem 0;max-width:100%;overflow-x:auto}.mineru-document .mineru-flowchart-canvas{display:none;min-width:0;text-align:left}.mineru-document .mineru-flowchart-canvas svg{display:block;height:auto;margin-inline:0;max-width:100%}.mineru-document .mineru-flowchart-fallback{display:block;margin-inline:0}.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-canvas{display:block}.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-fallback{display:none}.mineru-document .mineru-flowchart-details{max-width:100%}.mineru-document .mineru-flowchart-source{max-height:24rem;text-align:left;white-space:pre}.mineru-document .mineru-caption{color:var(--mineru-muted);font-size:0.9em;margin-top:0.5rem;text-align:left}.mineru-document .mineru-footnote{color:var(--mineru-muted);font-size:0.875em;margin-top:0.4rem;text-align:left}.mineru-document .mineru-details{border:1px solid var(--mineru-border);border-radius:0.375rem;margin:1rem 0;padding:0.65rem 0.85rem}.mineru-document .mineru-details>summary{cursor:pointer;font-weight:600}.mineru-document .mineru-page-aux{color:var(--mineru-muted);font-size:0.875rem}.mineru-document code,.mineru-document pre,.mineru-document .mineru-algorithm{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.mineru-document code{background:var(--mineru-surface);border-radius:0.25rem;font-size:0.875em;padding:0.15em 0.35em}.mineru-document pre{background:var(--mineru-surface);border:1px solid var(--mineru-border);border-radius:0.375rem;line-height:1.5;margin:1rem 0;max-width:100%;overflow:auto;padding:1rem;tab-size:4;white-space:pre}.mineru-document pre>code{background:transparent;border-radius:0;display:inline;font-size:inherit;line-height:inherit;padding:0;white-space:inherit}.mineru-document :is(code,pre)[class*="language-"]{color:#374151;text-align:left;text-shadow:none;word-break:normal;word-spacing:normal}.mineru-document .token.comment,.mineru-document .token.prolog,.mineru-document .token.doctype,.mineru-document .token.cdata{color:#6b7280}.mineru-document .token.punctuation{color:#374151}.mineru-document .token.namespace{opacity:0.75}.mineru-document .token.keyword,.mineru-document .token.operator,.mineru-document .token.important,.mineru-document .token.atrule{color:#7c3aed}.mineru-document .token.string,.mineru-document .token.attr-value,.mineru-document .token.regex,.mineru-document .token.url{color:#047857}.mineru-document .token.number,.mineru-document .token.boolean,.mineru-document .token.constant,.mineru-document .token.property,.mineru-document .token.symbol{color:#0369a1}.mineru-document .token.tag,.mineru-document .token.selector,.mineru-document .token.builtin{color:#b45309}.mineru-document .token.function,.mineru-document .token.class-name,.mineru-document .token.attr-name{color:#be123c}.mineru-document .token.important,.mineru-document .token.bold{font-weight:700}.mineru-document .token.italic{font-style:italic}.mineru-document .token.inserted{background:#ecfdf5;color:#047857}.mineru-document .token.deleted{background:#fff1f2;color:#be123c}.mineru-document .token.entity{cursor:help}.mineru-document .mineru-algorithm{max-width:100%;overflow-x:auto;tab-size:4;white-space:pre-wrap;word-break:normal}.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:0.2rem solid var(--mineru-border);color:var(--mineru-muted)}.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 mjx-container[display="true"]{max-width:100%;overflow-x:auto;overflow-y:hidden}.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 .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 var(--mineru-border);height:0;margin:2rem 0}@media screen and (max-width:40rem){.mineru-html-body>.mineru-document{padding:1rem}.mineru-document h1{font-size:1.75rem}.mineru-document :is(th,td){padding:0.4rem 0.55rem}}@media print{.mineru-html-body{background:#ffffff}.mineru-html-body>.mineru-document{max-width:none;min-height:0;padding:0}.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{break-inside:avoid;page-break-inside:avoid}.mineru-document table{display:table;overflow:visible}.mineru-document pre{overflow:visible;white-space:pre-wrap;word-break:break-word}}\ No newline at end of file+.mineru-html-body{background:#ffffff;margin:0}.mineru-html-body>.mineru-document{margin:0 auto;max-width:60rem;min-height:100vh;padding:2rem}.mineru-document{--mineru-accent:#0b6fc2;--mineru-accent-hover:#075a9c;--mineru-background:#ffffff;--mineru-border:#d1d5db;--mineru-muted:#6b7280;--mineru-surface:#f8fafc;--mineru-text:#1f2937;background:var(--mineru-background);box-sizing:border-box;color:var(--mineru-text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;font-size:16px;line-height:1.65;overflow-wrap:break-word;width:100%}.mineru-document *,.mineru-document *::before,.mineru-document *::after{box-sizing:inherit}.mineru-document :is(h1,h2,h3,h4,h5,h6){color:var(--mineru-text);font-weight:600;line-height:1.3;margin:1.5em 0 0.65em}.mineru-document h1{font-size:2rem}.mineru-document h2{font-size:1.5rem}.mineru-document h3{font-size:1.25rem}.mineru-document h4{font-size:1.125rem}.mineru-document h5{font-size:1rem}.mineru-document h6{color:var(--mineru-muted);font-size:0.875rem}.mineru-document .mineru-block:first-child>:first-child,.mineru-document .mineru-page>.mineru-block:first-child>:first-child{margin-top:0}.mineru-document p{margin:0 0 1rem}.mineru-document :is(strong,b){font-weight:700}.mineru-document :is(s,del){color:var(--mineru-muted)}.mineru-document a{color:var(--mineru-accent);text-decoration:none;text-underline-offset:0.15em}.mineru-document a:hover{color:var(--mineru-accent-hover);text-decoration:underline}.mineru-document a:focus-visible{border-radius:0.15rem;outline:2px solid var(--mineru-accent);outline-offset:2px}.mineru-document blockquote{background:var(--mineru-surface);border-left:0.25rem solid var(--mineru-accent);color:var(--mineru-muted);margin:1rem 0;padding:0.75rem 1rem}.mineru-document blockquote>:first-child{margin-top:0}.mineru-document blockquote>:last-child{margin-bottom:0}.mineru-document :is(ol,ul){margin:0 0 1rem;padding-left:1.75rem}.mineru-document ul{list-style:disc}.mineru-document ul ul{list-style:circle}.mineru-document ul ul ul{list-style:square}.mineru-document ol{list-style:decimal}.mineru-document :is(ol,ul) ol{list-style-type:lower-roman}.mineru-document :is(ol,ul) :is(ol,ul) ol{list-style-type:lower-alpha}.mineru-document li + li{margin-top:0.25rem}.mineru-document li>:is(ol,ul){margin-bottom:0;margin-top:0.25rem}.mineru-document .mineru-list--explicit{list-style:none;padding-left:1.5rem}.mineru-document .mineru-list--unmarked{list-style:none;padding-left:0}.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-item--orphan{display:grid;grid-template-columns:0 minmax(0,1fr);list-style:none}.mineru-document .mineru-list-item--markerless{list-style:none}.mineru-document .mineru-list-marker{font-variant-numeric:tabular-nums;text-align:right;user-select:none;white-space:pre}.mineru-document .mineru-list-content{min-width:0}.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}.mineru-document table{border-collapse:collapse;border-spacing:0;display:block;margin:1rem 0;max-width:100%;overflow-x:auto;width:100%}.mineru-document :is(th,td){border:1px solid var(--mineru-border);padding:0.5rem 0.75rem;text-align:left;vertical-align:top}.mineru-document th{background:var(--mineru-surface);font-weight:600}.mineru-document caption{color:var(--mineru-muted);margin-bottom:0.5rem;text-align:left}.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 img{height:auto;max-width:100%}.mineru-document .mineru-figure{margin:1.5rem 0;max-width:100%}.mineru-document .mineru-figure>img{display:block;margin-inline:0}.mineru-document .mineru-flowchart{margin:1rem 0;max-width:100%;overflow-x:auto}.mineru-document .mineru-flowchart-canvas{display:none;min-width:0;text-align:left}.mineru-document .mineru-flowchart-canvas svg{display:block;height:auto;margin-inline:0;max-width:100%}.mineru-document .mineru-flowchart-fallback{display:block;margin-inline:0}.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-canvas{display:block}.mineru-document .mineru-flowchart[data-mermaid-state="rendered"] .mineru-flowchart-fallback{display:none}.mineru-document .mineru-flowchart-details{max-width:100%}.mineru-document .mineru-flowchart-source{max-height:24rem;text-align:left;white-space:pre}.mineru-document .mineru-caption{color:var(--mineru-muted);font-size:0.9em;margin-top:0.5rem;text-align:left}.mineru-document .mineru-footnote,.mineru-document .mineru-page-footnote{color:var(--mineru-muted);font-size:0.875em;margin-top:0.4rem;text-align:left}.mineru-document .mineru-details{border:1px solid var(--mineru-border);border-radius:0.375rem;margin:1rem 0;padding:0.65rem 0.85rem}.mineru-document .mineru-details>summary{cursor:pointer;font-weight:600}.mineru-document .mineru-page-aux{color:var(--mineru-muted);font-size:0.875rem}.mineru-document code,.mineru-document pre,.mineru-document .mineru-algorithm{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace}.mineru-document code{background:var(--mineru-surface);border-radius:0.25rem;font-size:0.875em;padding:0.15em 0.35em}.mineru-document pre{background:var(--mineru-surface);border:1px solid var(--mineru-border);border-radius:0.375rem;line-height:1.5;margin:1rem 0;max-width:100%;overflow:auto;padding:1rem;tab-size:4;white-space:pre}.mineru-document pre>code{background:transparent;border-radius:0;display:inline;font-size:inherit;line-height:inherit;padding:0;white-space:inherit}.mineru-document :is(code,pre)[class*="language-"]{color:#374151;text-align:left;text-shadow:none;word-break:normal;word-spacing:normal}.mineru-document .token.comment,.mineru-document .token.prolog,.mineru-document .token.doctype,.mineru-document .token.cdata{color:#6b7280}.mineru-document .token.punctuation{color:#374151}.mineru-document .token.namespace{opacity:0.75}.mineru-document .token.keyword,.mineru-document .token.operator,.mineru-document .token.important,.mineru-document .token.atrule{color:#7c3aed}.mineru-document .token.string,.mineru-document .token.attr-value,.mineru-document .token.regex,.mineru-document .token.url{color:#047857}.mineru-document .token.number,.mineru-document .token.boolean,.mineru-document .token.constant,.mineru-document .token.property,.mineru-document .token.symbol{color:#0369a1}.mineru-document .token.tag,.mineru-document .token.selector,.mineru-document .token.builtin{color:#b45309}.mineru-document .token.function,.mineru-document .token.class-name,.mineru-document .token.attr-name{color:#be123c}.mineru-document .token.important,.mineru-document .token.bold{font-weight:700}.mineru-document .token.italic{font-style:italic}.mineru-document .token.inserted{background:#ecfdf5;color:#047857}.mineru-document .token.deleted{background:#fff1f2;color:#be123c}.mineru-document .token.entity{cursor:help}.mineru-document .mineru-algorithm{max-width:100%;overflow-x:auto;tab-size:4;white-space:pre-wrap;word-break:normal}.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:0.2rem solid var(--mineru-border);color:var(--mineru-muted)}.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 mjx-container[display="true"]{max-width:100%;overflow-x:auto;overflow-y:hidden}.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 .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 var(--mineru-border);height:0;margin:2rem 0}@media screen and (max-width:40rem){.mineru-html-body>.mineru-document{padding:1rem}.mineru-document h1{font-size:1.75rem}.mineru-document :is(th,td){padding:0.4rem 0.55rem}}@media print{.mineru-html-body{background:#ffffff}.mineru-html-body>.mineru-document{max-width:none;min-height:0;padding:0}.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{break-inside:avoid;page-break-inside:avoid}.mineru-document table{display:table;overflow:visible}.mineru-document pre{overflow:visible;white-space:pre-wrap;word-break:break-word}}\ No newline at end of filediff --git a/mineru/types.py b/mineru/types.pyindex c92660c4..f39ba8cc 100644--- a/mineru/types.py+++ b/mineru/types.py@@ -345,10 +345,14 @@ PAGE_AUXILIARY_BLOCK_TYPES = {BlockType.HEADER,BlockType.FOOTER,BlockType.PAGE_NUMBER,- BlockType.PAGE_FOOTNOTE,BlockType.ASIDE_TEXT,}-VISUAL_RELATION_IGNORED_TYPES = PAGE_AUXILIARY_BLOCK_TYPES+# 页面脚注需要参与输出,但不会阻断正文、列表、续表或视觉对象之间的关系判断。+MERGE_TRANSPARENT_BLOCK_TYPES = {+ *PAGE_AUXILIARY_BLOCK_TYPES,+ BlockType.PAGE_FOOTNOTE,+}+VISUAL_RELATION_IGNORED_TYPES = MERGE_TRANSPARENT_BLOCK_TYPESVISUAL_MAIN_TYPES = {BlockType.IMAGE_BODY: BlockType.IMAGE,BlockType.TABLE_BODY: BlockType.TABLE,@@ -503,23 +507,21 @@ class ParagraphTitleBlock(TitleBlockBase):class PageAuxTextBlock(StringContentBlock):- """页眉、页脚、页码、边栏和页脚注释的共享文本结构。"""+ """页眉、页脚、页码和边栏的共享文本结构。"""type: Literal[ # type: ignore[reportIncompatibleVariableOverride]BlockType.HEADER,BlockType.FOOTER,BlockType.PAGE_NUMBER,BlockType.ASIDE_TEXT,- BlockType.PAGE_FOOTNOTE,]- anchor: str | None = None- @model_validator(mode="after")- def _validate_page_footnote_anchor(self) -> PageAuxTextBlock:- """只允许页面脚注携带可跳转 anchor,避免扩大其它辅助块契约。"""- if self.type != BlockType.PAGE_FOOTNOTE and self.anchor is not None:- raise ValueError("anchor is only supported for page_footnote blocks")- return self++class PageFootnoteBlock(StringContentBlock):+ """保存需要参与默认输出并可被文档内链接引用的页面脚注。"""++ type: Literal[BlockType.PAGE_FOOTNOTE] # type: ignore[reportIncompatibleVariableOverride]+ anchor: str | None = Noneclass ImagePayloadBlock(BlockBase):@@ -708,6 +710,7 @@ PageBlock: TypeAlias = Annotated[DocTitleBlock,ParagraphTitleBlock,PageAuxTextBlock,+ PageFootnoteBlock,EquationBlock,ListBlock,IndexBlock,@@ -727,6 +730,7 @@ Block: TypeAlias = Annotated[DocTitleBlock,ParagraphTitleBlock,PageAuxTextBlock,+ PageFootnoteBlock,EquationBlock,ListBlock,IndexBlock,diff --git a/tests/unittest/_epub_test_utils.py b/tests/unittest/_epub_test_utils.pyindex 70d888b9..25664a9c 100644--- a/tests/unittest/_epub_test_utils.py+++ b/tests/unittest/_epub_test_utils.py@@ -1,13 +1,12 @@from __future__ import annotationsimport base64+import htmlfrom io import BytesIOfrom zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile-_PNG_BYTES = base64.b64decode(- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="-)+_PNG_BYTES = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=")def build_epub_fixture(@@ -22,6 +21,7 @@ def build_epub_fixture(include_ncx: bool = True,corrupt_nav: bool = False,nav_in_spine: bool = False,+ nav_extra_body_text: str = "",strip_headings: bool = False,) -> bytes:"""构造覆盖 XHTML、SVG、CSS、公式、表格、列表和图片的最小 EPUB 3。"""@@ -54,7 +54,7 @@ def build_epub_fixture(if include_ncx:opf = opf.replace("<spine>", '<spine toc="ncx">')if nav_in_spine:- opf = opf.replace("<itemref idref=\"c1\"/>", '<itemref idref="nav"/><itemref idref="c1"/>')+ opf = opf.replace('<itemref idref="c1"/>', '<itemref idref="nav"/><itemref idref="c1"/>')if use_foreign_fallback:opf = opf.replace('<item id="c2" href="text/ch2.xhtml" media-type="application/xhtml+xml"/>',@@ -104,6 +104,11 @@ def build_epub_fixture(</ol></nav><nav epub:type="landmarks"><ol><li><a href="text/ch1.xhtml">Landmark</a></li></ol></nav></body></html>"""+ if nav_extra_body_text:+ nav_xhtml = nav_xhtml.replace(+ "</body>",+ f"<p>{html.escape(nav_extra_body_text, quote=False)}</p></body>",+ )ncx = """<?xml version="1.0" encoding="UTF-8"?><ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1"><navMap><navPoint id="n1"><navLabel><text>NCX Chapter One</text></navLabel><content src="text/ch1.xhtml#chapter-one"/>@@ -242,4 +247,43 @@ def build_epub_notes_fixture() -> bytes:return output.getvalue()-__all__ = ["build_epub2_fixture", "build_epub_fixture", "build_epub_notes_fixture"]+def build_epub_table_toc_fixture() -> bytes:+ """构造标题内部 fragment 与保守整行目录表格扩展的最小 EPUB。"""+ container = (+ '<container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" version="1.0"><rootfiles>'+ '<rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/>'+ "</rootfiles></container>"+ )+ opf = """<?xml version="1.0" encoding="UTF-8"?>+<package xmlns="http://www.idpf.org/2007/opf" version="3.0">+ <metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Table TOC</dc:title></metadata>+ <manifest>+ <item id="contents" href="contents.xhtml" media-type="application/xhtml+xml"/>+ <item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/>+ </manifest>+ <spine><itemref idref="contents"/><itemref idref="chapter"/></spine>+</package>"""+ contents = """<?xml version="1.0" encoding="UTF-8"?>+<html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Contents</h1><table><tbody>+ <tr><td><a href="chapter.xhtml#chapter-marker">CHAPTER I.</a></td><td>Target Chapter</td></tr>+ <tr><td><a href="chapter.xhtml#other">Mismatch</a></td><td>Other text</td></tr>+ <tr><td><a href="https://example.com">External</a></td><td>Target Chapter</td></tr>+ <tr><td><a href="chapter.xhtml#chapter-marker">First</a></td><td><a href="chapter.xhtml#other">Second</a></td></tr>+</tbody></table></body></html>"""+ chapter = """<?xml version="1.0" encoding="UTF-8"?>+<html xmlns="http://www.w3.org/1999/xhtml"><body>+ <h2><a id="chapter-marker"/>CHAPTER I.<br/>+ Target Chapter</h2>+ <h2 id="other">Other Chapter</h2>+</body></html>"""+ output = BytesIO()+ with ZipFile(output, "w") as package:+ package.writestr("mimetype", "application/epub+zip", compress_type=ZIP_STORED)+ package.writestr("META-INF/container.xml", container, compress_type=ZIP_DEFLATED)+ package.writestr("EPUB/package.opf", opf, compress_type=ZIP_DEFLATED)+ package.writestr("EPUB/contents.xhtml", contents, compress_type=ZIP_DEFLATED)+ package.writestr("EPUB/chapter.xhtml", chapter, compress_type=ZIP_DEFLATED)+ return output.getvalue()+++__all__ = ["build_epub2_fixture", "build_epub_fixture", "build_epub_notes_fixture", "build_epub_table_toc_fixture"]diff --git a/tests/unittest/test_docx_render.py b/tests/unittest/test_docx_render.pyindex 7f8cd6f6..325e386e 100644--- a/tests/unittest/test_docx_render.py+++ b/tests/unittest/test_docx_render.py@@ -25,6 +25,7 @@ from mineru.types import (MiddleJson,PageAuxTextBlock,PageBlock,+ PageFootnoteBlock,PageInfo,ParagraphTitleBlock,TableAnnotationBlock,@@ -143,8 +144,8 @@ def test_heading_bookmark_forward_index_link_and_rich_inline_ooxml() -> None:assert "<m:oMath" in document_xml-def test_full_docx_uses_page_footnote_bookmark_for_inline_internal_link() -> None:- """验证页面脚注正向引用写为 Word 内部书签,未知目标不创建外部关系。"""+def test_default_and_full_docx_use_page_footnote_bookmark_and_style() -> None:+ """验证默认与完整 Word 都输出页面脚注书签、内部链接和专用样式。"""middle = _middle(_page(0,@@ -152,11 +153,10 @@ def test_full_docx_uses_page_footnote_bookmark_for_inline_internal_link() -> Nontype="text",index=0,content=(- "See <hyperlink>[1]<url>#note-one</url></hyperlink> and "- "<hyperlink>[x]<url>#missing-note</url></hyperlink>."+ "See <hyperlink>[1]<url>#note-one</url></hyperlink> and <hyperlink>[x]<url>#missing-note</url></hyperlink>."),),- PageAuxTextBlock(+ PageFootnoteBlock(type="page_footnote",index=1,content="Footnote body.",@@ -166,19 +166,19 @@ def test_full_docx_uses_page_footnote_bookmark_for_inline_internal_link() -> Non)default_result = render_docx(middle)- default_xml = _part(default_result, "word/document.xml")- result = render_docx(middle, mode=RenderMode.FULL)- document_xml = _part(result, "word/document.xml")- relationships = _part(result, "word/_rels/document.xml.rels")-- assert 'w:bookmarkStart w:id="0" w:name="note_one"' in document_xml- assert 'w:hyperlink w:anchor="note_one"' in document_xml- assert document_xml.count("<w:hyperlink") == 1- assert "missing-note" not in relationships- assert "#note-one" not in relationships- assert "w:bookmarkStart" not in default_xml- assert "w:hyperlink" not in default_xml- assert all("Footnote body." not in paragraph.text for paragraph in Document(BytesIO(default_result)).paragraphs)+ full_result = render_docx(middle, mode=RenderMode.FULL)+ for result in (default_result, full_result):+ document_xml = _part(result, "word/document.xml")+ relationships = _part(result, "word/_rels/document.xml.rels")+ document = Document(BytesIO(result))+ footnote = next(paragraph for paragraph in document.paragraphs if paragraph.text == "Footnote body.")++ assert 'w:bookmarkStart w:id="0" w:name="note_one"' in document_xml+ assert 'w:hyperlink w:anchor="note_one"' in document_xml+ assert document_xml.count("<w:hyperlink") == 1+ assert footnote.style.name == "MinerU Footnote"+ assert "missing-note" not in relationships+ assert "#note-one" not in relationshipsdef test_visible_styled_boundary_spaces_use_nbsp_without_mutating_input() -> None:diff --git a/tests/unittest/test_flash_csv.py b/tests/unittest/test_flash_csv.pyindex 7e92c031..76ebaa0d 100644--- a/tests/unittest/test_flash_csv.py+++ b/tests/unittest/test_flash_csv.py@@ -60,9 +60,7 @@ def test_csv_sep_directive_overrides_delimiter_sniffing() -> None:def test_csv_preserves_multiline_quotes_padding_ragged_rows_and_safe_text() -> None:"""验证多行字段、引号、前导零、首尾空格、短行补齐和 HTML 转义。"""payload = (- 'name,note,code,markup\n'- 'Alice,"line 1\nline 2",001,"<script>alert(1)</script>"\n'- 'Bob," say ""hi"" ",02\n'+ 'name,note,code,markup\nAlice,"line 1\nline 2",001,"<script>alert(1)</script>"\nBob," say ""hi"" ",02\n').encode()table_html = _raw_table_html(payload)@@ -140,6 +138,14 @@ def test_csv_enforces_resource_limits(CsvModel().predict(BytesIO(payload))+def test_csv_grid_limit_short_circuits_before_trailing_malformed_record(monkeypatch: pytest.MonkeyPatch) -> None:+ """验证网格超限后立即失败,不再继续读取尾部损坏记录。"""+ monkeypatch.setattr(csv_module, "MAX_CSV_GRID_SLOTS", 3)++ with pytest.raises(ValueError, match="max_grid_slots"):+ CsvModel().predict(BytesIO(b'a,b\n1,2\n"unterminated'))++def test_csv_doc_analyze_sync_async_and_render_contracts_match() -> None:"""验证同步异步 Analyze 元数据和既有表格渲染链保持一致。"""payload = "姓名,年龄\n张三,30\n".encode()diff --git a/tests/unittest/test_flash_epub.py b/tests/unittest/test_flash_epub.pyindex 51163b6d..46c75014 100644--- a/tests/unittest/test_flash_epub.py+++ b/tests/unittest/test_flash_epub.py@@ -8,6 +8,7 @@ from io import BytesIOfrom pathlib import Pathimport pytest+from bs4 import BeautifulSoupimport mineru.model.flash.epub.package as epub_package_modulefrom mineru.backend.analyze import aio_doc_analyze, doc_analyze@@ -23,9 +24,14 @@ from mineru.parser import api_serverfrom mineru.parser.api_server import CreateJobRequest, FileStorefrom mineru.parser.file_type import guess_suffix_by_bytes, guess_suffix_by_pathfrom mineru.render import RenderMode, render_docx, render_html, render_markdown, render_structured_content-from mineru.types import BlockType+from mineru.types import BlockType, PageFootnoteBlock-from _epub_test_utils import build_epub2_fixture, build_epub_fixture, build_epub_notes_fixture+from _epub_test_utils import (+ build_epub2_fixture,+ build_epub_fixture,+ build_epub_notes_fixture,+ build_epub_table_toc_fixture,+)def test_epub_model_analyze_and_renderers_preserve_structured_content() -> None:@@ -34,13 +40,11 @@ def test_epub_model_analyze_and_renderers_preserve_structured_content() -> None:stream = BytesIO(payload)model_pages = EpubModel().predict(stream)assert not stream.closed- assert len(model_pages) == 4+ assert len(model_pages) == 3middle, model = doc_analyze(payload, effort="xhigh", parse_mode="ocr", file_suffix="epub")explicit_full_middle, explicit_full_model = doc_analyze(payload, page_index_map=[], file_suffix="epub")- async_middle, async_model = asyncio.run(- aio_doc_analyze(payload, effort="medium", parse_mode="auto", file_suffix="epub")- )+ async_middle, async_model = asyncio.run(aio_doc_analyze(payload, effort="medium", parse_mode="auto", file_suffix="epub"))assert model.pages == async_model.pages == model_pagesassert explicit_full_model.pages == model_pagesassert explicit_full_middle.is_full_document is True@@ -48,15 +52,13 @@ def test_epub_model_analyze_and_renderers_preserve_structured_content() -> None:assert model.file_suffix == middle.file_suffix == "epub"assert model.effort == middle.effort == "flash"assert model.parse_mode == middle.parse_mode == "txt"- assert [page.page_idx for page in middle.pages] == [0, 1, 2, 3]- assert middle.pages[0].blocks[0].type == BlockType.INDEX- assert middle.pages[1].blocks[0].type == BlockType.DOC_TITLE+ assert [page.page_idx for page in middle.pages] == [0, 1, 2]+ assert middle.pages[0].blocks[0].type == BlockType.DOC_TITLEraw_blocks = [block for page in model.pages for block in page]raw_types = [block["type"] for block in raw_blocks]for expected_type in (BlockType.DOC_TITLE,- BlockType.INDEX,BlockType.PARAGRAPH_TITLE,BlockType.TEXT,BlockType.LIST,@@ -90,6 +92,7 @@ def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:middle, model = doc_analyze(build_epub_notes_fixture(), file_suffix="epub")blocks = [block for page in middle.pages for block in page.blocks]footnotes = [block for block in blocks if block.type == BlockType.PAGE_FOOTNOTE]+ assert all(isinstance(block, PageFootnoteBlock) for block in footnotes)footnote_by_text = {block.content: block for block in footnotes} # type: ignore[union-attr]first = footnote_by_text["First footnote paragraph back."]@@ -107,7 +110,7 @@ def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:body_text = next(block- for block in middle.pages[1].blocks+ for block in middle.pages[0].blocksif block.type == BlockType.TEXT and "Same-page" in block.content # type: ignore[union-attr])assert f"<url>#{first.anchor}</url>" in body_text.content # type: ignore[union-attr]@@ -129,13 +132,19 @@ def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:default_markdown = render_markdown(middle)full_markdown = render_markdown(middle, mode=RenderMode.FULL)- assert "First footnote paragraph" not in default_markdown+ assert "First footnote paragraph" in default_markdownassert f"](#{first.anchor})" in default_markdown- assert f'<a id="{first.anchor}"></a>' in full_markdown+ assert f'id="{first.anchor}" class="mineru-page-footnote"' in default_markdown+ assert f'id="{first.anchor}" class="mineru-page-footnote"' in full_markdown+ assert "Page footnote:" not in default_markdown- full_html = render_html(middle, mode=RenderMode.FULL, standalone=False)- assert f'href="#{first.anchor}"' in full_html- assert f'id="{first.anchor}"' in full_html+ for html_output in (+ render_html(middle, standalone=False),+ render_html(middle, mode=RenderMode.FULL, standalone=False),+ ):+ assert f'href="#{first.anchor}"' in html_output+ assert f'id="{first.anchor}"' in html_output+ assert 'class="mineru-page-footnote"' in html_outputstructured = render_structured_content(middle)structured_blocks = [block for page in structured["pages"] for block in page["blocks"]]@@ -146,20 +155,16 @@ def test_epub_notes_use_page_footnote_and_document_wide_anchors() -> None:def test_epub_internal_heading_links_and_exact_list_labels_survive() -> None:- """验证章节/section 别名映射到真实标题 anchor,列表标签保留源编号。"""+ """验证 spine 正文内部标题链接和列表标签保留,不注入 nav/NCX 目录页。"""middle, _ = doc_analyze(build_epub_fixture(), file_suffix="epub")- toc = middle.pages[0].blocks[0]- first_page = middle.pages[1]- second_page = middle.pages[2]+ first_page = middle.pages[0]+ second_page = middle.pages[1]first_title = first_page.blocks[0]second_title = second_page.blocks[0]assert first_title.anchor and second_title.anchor # type: ignore[union-attr]- assert toc.content[0].content == "NAV Chapter One" # type: ignore[union-attr]- assert toc.content[1].content[0].content == "NAV Section Two" # type: ignore[union-attr]- assert toc.content[2].content == "NAV Missing Appendix" # type: ignore[union-attr]markdown = render_markdown(middle)- assert markdown.startswith(f"- [NAV Chapter One](#{first_title.anchor})") # type: ignore[union-attr]- assert f" - [NAV Section Two](#{second_title.anchor})" in markdown # type: ignore[union-attr]+ assert markdown.startswith(f'<a id="{first_title.anchor}"></a>\n# Chapter One') # type: ignore[union-attr]+ assert "NAV Chapter One" not in markdownassert "NCX Chapter One" not in markdownassert "Landmark" not in markdownassert f"](#{second_title.anchor})" in markdown # type: ignore[union-attr]@@ -168,6 +173,31 @@ def test_epub_internal_heading_links_and_exact_list_labels_survive() -> None:assert "B. Two" in markdown+def test_epub_table_contents_resolve_title_marker_and_expand_only_exact_single_target_rows() -> None:+ """验证标题内部 marker 可跳转,且目录表格只扩展严格匹配的单目标行。"""+ middle, model = doc_analyze(build_epub_table_toc_fixture(), file_suffix="epub")+ assert len(middle.pages) == 2+ assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)+ table = next(block for block in model.pages[0] if block["type"] == BlockType.TABLE)+ soup = BeautifulSoup(str(table["content"]), "html.parser")+ rows = soup.find_all("tr")++ positive_links = rows[0].find_all("a", href=True)+ assert [link.get_text(strip=True) for link in positive_links] == ["CHAPTER I.", "Target Chapter"]+ assert len({link["href"] for link in positive_links}) == 1+ assert rows[1].find_all("a", href=True)[0].get_text(strip=True) == "Mismatch"+ assert len(rows[1].find_all("a", href=True)) == 1+ assert rows[2].find("a", href=True)["href"] == "https://example.com" # type: ignore[index]+ assert len(rows[2].find_all("a", href=True)) == 1+ assert len(rows[3].find_all("a", href=True)) == 2++ rendered = BeautifulSoup(render_html(middle, standalone=False), "html.parser")+ chapter_link = rendered.find("a", string="Target Chapter")+ chapter_title = rendered.find(id=positive_links[0]["href"].removeprefix("#"))+ assert chapter_link is not None and chapter_title is not None+ assert chapter_link["href"] == f"#{chapter_title['id']}"++def test_public_parser_rejects_epub_page_range(tmp_path: Path) -> None:"""验证 EPUB 公共 Parser 只接受整本解析。"""source = tmp_path / "book.epub"@@ -217,38 +247,37 @@ def test_epub2_and_mimetype_less_compatibility_packages_parse() -> None:assert detect_epub(epub2)assert detect_epub(compatibility)epub2_middle = doc_analyze(epub2, file_suffix="epub")[0]- assert epub2_middle.pages[0].blocks[0].content[0].content == "EPUB 2 Entry" # type: ignore[union-attr]- assert epub2_middle.pages[1].blocks[0].content == "EPUB Two Chapter" # type: ignore[union-attr]- assert epub2_middle.pages[1].blocks[1].content == "Legacy\u00a0body" # type: ignore[union-attr]- assert len(doc_analyze(compatibility, file_suffix="epub")[0].pages) == 4+ assert epub2_middle.pages[0].blocks[0].content == "EPUB Two Chapter" # type: ignore[union-attr]+ assert epub2_middle.pages[0].blocks[1].content == "Legacy\u00a0body" # type: ignore[union-attr]+ assert len(doc_analyze(compatibility, file_suffix="epub")[0].pages) == 3def test_epub_spine_foreign_resource_uses_xhtml_fallback_chain() -> None:"""验证 foreign spine item 缺失时仍沿 manifest fallback 到 XHTML。"""middle, _ = doc_analyze(build_epub_fixture(use_foreign_fallback=True), file_suffix="epub")- assert middle.pages[2].blocks[0].content == "Section Two" # type: ignore[union-attr]+ assert middle.pages[1].blocks[0].content == "Section Two" # type: ignore[union-attr]-def test_epub_corrupt_nav_falls_back_to_ncx() -> None:- """验证 EPUB3 nav 损坏时使用 EPUB2 NCX,而不是合并两个来源。"""+def test_epub_nav_and_ncx_outside_spine_do_not_create_synthetic_page() -> None:+ """验证 spine 外的损坏 nav 与有效 NCX 都不会生成合成目录页。"""middle, _ = doc_analyze(build_epub_fixture(corrupt_nav=True), file_suffix="epub")markdown = render_markdown(middle)- assert markdown.startswith("- [NCX Chapter One]")- assert " - [NCX Section Two]" in markdown+ assert len(middle.pages) == 3+ assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)+ assert "NCX Chapter One" not in markdownassert "NAV Chapter One" not in markdown-def test_epub_without_authored_toc_builds_nested_index_from_headings() -> None:- """验证缺失 nav/NCX 时按跨 spine 标题层级生成目录。"""+def test_epub_without_authored_toc_keeps_only_spine_pages_and_titles() -> None:+ """验证缺失 nav/NCX 时不从正文标题生成额外目录页。"""middle, _ = doc_analyze(build_epub_fixture(include_nav=False, include_ncx=False),file_suffix="epub",)- index = middle.pages[0].blocks[0]- assert index.type == BlockType.INDEX- assert index.content[0].content == "Chapter One" # type: ignore[union-attr]- assert index.content[1].content[0].content == "Section Two" # type: ignore[union-attr]- assert len(middle.pages) == 4+ assert len(middle.pages) == 3+ assert middle.pages[0].blocks[0].type == BlockType.DOC_TITLE+ assert middle.pages[1].blocks[0].type == BlockType.PARAGRAPH_TITLE+ assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)def test_epub_without_toc_or_headings_does_not_add_empty_page() -> None:@@ -265,11 +294,16 @@ def test_epub_without_toc_or_headings_does_not_add_empty_page() -> None:assert middle.pages[0].blocks[0].type != BlockType.INDEX-def test_epub_navigation_in_spine_is_replaced_by_single_front_index() -> None:- """验证 spine 中的 nav occurrence 被首页目录替代,不重复输出正文页。"""- middle, _ = doc_analyze(build_epub_fixture(nav_in_spine=True), file_suffix="epub")+def test_epub_navigation_in_spine_preserves_page_order_and_extra_body_content() -> None:+ """验证 spine 中的 nav 作为普通 XHTML 页保留目录和额外正文。"""+ middle, _ = doc_analyze(+ build_epub_fixture(nav_in_spine=True, nav_extra_body_text="Publisher front matter"),+ file_suffix="epub",+ )assert len(middle.pages) == 4- assert sum(block.type == BlockType.INDEX for page in middle.pages for block in page.blocks) == 1+ assert all(block.type != BlockType.INDEX for page in middle.pages for block in page.blocks)+ assert any(getattr(block, "content", None) == "Publisher front matter" for block in middle.pages[0].blocks)+ assert middle.pages[1].blocks[0].content == "Chapter One" # type: ignore[union-attr]def test_epub_content_detection_precedes_extension_and_rejects_fake_packages(tmp_path: Path) -> None:@@ -290,11 +324,11 @@ def test_epub_content_detection_precedes_extension_and_rejects_fake_packages(tmpdef test_epub_corrupt_chapter_keeps_empty_spine_placeholder() -> None:"""验证局部 XHTML 损坏不移动后续 spine 页号。"""middle, model = doc_analyze(build_epub_fixture(corrupt_second_chapter=True), file_suffix="epub")- assert len(model.pages) == 4- assert model.pages[2] == []- assert [page.page_idx for page in middle.pages] == [0, 1, 2, 3]- assert middle.pages[2].blocks == []- assert "SVG text" in middle.pages[3].blocks[0].content # type: ignore[union-attr]+ assert len(model.pages) == 3+ assert model.pages[1] == []+ assert [page.page_idx for page in middle.pages] == [0, 1, 2]+ assert middle.pages[1].blocks == []+ assert "SVG text" in middle.pages[2].blocks[0].content # type: ignore[union-attr]def test_epub_rejects_encrypted_unsafe_and_dtd_inputs() -> None:@@ -334,7 +368,7 @@ def test_doclib_extracts_epub_metadata(tmp_path: Path) -> None:source.write_bytes(build_epub_fixture())metadata = asyncio.run(extract_metadata(str(source)))assert metadata == {- "page_count": 4,+ "page_count": 3,"title": "EPUB Fixture","author": "Alice","subject": "Testing",@@ -343,8 +377,8 @@ def test_doclib_extracts_epub_metadata(tmp_path: Path) -> None:}-def test_epub_local_parse_job_emits_full_flash_outputs(tmp_path: Path) -> None:- """验证本地 Parse Jobs 接受 EPUB,并输出目录和全部正文。"""+def test_epub_local_parse_job_emits_spine_aligned_flash_outputs(tmp_path: Path) -> None:+ """验证本地 Parse Jobs 接受 EPUB,并按 spine 输出全部正文。"""source = tmp_path / "book.epub"source.write_bytes(build_epub_fixture())file_store = FileStore(tmp_path / "api-files")@@ -376,8 +410,8 @@ def test_epub_local_parse_job_emits_full_flash_outputs(tmp_path: Path) -> None:assert payload["file_suffix"] == "epub"assert payload["effort"] == "flash"assert payload["parse_mode"] == "txt"- assert [page["page_idx"] for page in payload["pages"]] == [0, 1, 2, 3]- assert payload["pages"][0]["blocks"][0]["type"] == "index"+ assert [page["page_idx"] for page in payload["pages"]] == [0, 1, 2]+ assert payload["pages"][0]["blocks"][0]["type"] == "doc_title"def test_epub_local_parse_job_preserves_page_range_error_code(tmp_path: Path) -> None:@@ -408,8 +442,8 @@ def test_epub_local_parse_job_preserves_page_range_error_code(tmp_path: Path) ->assert record.files[0].error.code == "page_range_invalid"-def test_doclib_ingests_epub_as_local_flash_with_output_page_count(tmp_path: Path) -> None:- """验证 doclib 为 EPUB 建立整本 flash row,并记录目录加正文页数。"""+def test_doclib_ingests_epub_as_local_flash_with_spine_page_count(tmp_path: Path) -> None:+ """验证 doclib 为 EPUB 建立整本 flash row,并记录 spine 页数。"""class _NoRulesConfig:async def match_rules(self, path: str, rule_type: str) -> list[dict[str, object]]:@@ -439,8 +473,8 @@ def test_doclib_ingests_epub_as_local_flash_with_output_page_count(tmp_path: Pat(response.sha256,),)assert response.tier == "flash"- assert doc == {"file_type": "epub", "page_count": 4}- assert parses == [{"tier": "flash", "status": "pending", "privacy": "local", "page_range": "1~4"}]+ assert doc == {"file_type": "epub", "page_count": 3}+ assert parses == [{"tier": "flash", "status": "pending", "privacy": "local", "page_range": "1~3"}]with pytest.raises(InvalidRequestError) as range_exc:await service.request_parse(str(source), tier="flash", page_range="2")@@ -469,7 +503,7 @@ def test_doclib_local_epub_task_clears_persisted_full_page_range(monkeypatch: pyservice._parse_via_local( # type: ignore[arg-type]{"path": "/tmp/book.epub", "ext": "epub"},"flash",- "1~4",+ "1~3",))assert result is expecteddiff --git a/tests/unittest/test_html_css_build.py b/tests/unittest/test_html_css_build.pyindex 144081c7..8a312a31 100644--- a/tests/unittest/test_html_css_build.py+++ b/tests/unittest/test_html_css_build.py@@ -36,7 +36,8 @@ def test_visual_bodies_captions_and_footnotes_align_left() -> None:"}") in sourceassert (- ".mineru-document .mineru-footnote {\n"+ ".mineru-document .mineru-footnote,\n"+ ".mineru-document .mineru-page-footnote {\n"" color: var(--mineru-muted);\n"" font-size: 0.875em;\n"" margin-top: 0.4rem;\n"@@ -73,16 +74,14 @@ def test_minify_css_preserves_descendant_combinator_before_pseudo_class() -> Non"""验证伪类前的后代空格不会被误当作声明冒号旁的冗余空白。"""source = ".root :is(h1, h2) { color: red; } .root:hover { color: blue; }"- assert build_html_css.minify_css(source) == (- ".root :is(h1,h2){color:red}.root:hover{color:blue}"- )+ assert build_html_css.minify_css(source) == (".root :is(h1,h2){color:red}.root:hover{color:blue}")@pytest.mark.parametrize("source",["a { color: red;",- "a { content: \"unterminated; }",+ 'a { content: "unterminated; }',"a { color: red; /* unterminated","a { color: red; }}","a { content: \\",diff --git a/tests/unittest/test_html_render.py b/tests/unittest/test_html_render.pyindex 8b25f4e8..a03e1d1b 100644--- a/tests/unittest/test_html_render.py+++ b/tests/unittest/test_html_render.py@@ -22,6 +22,7 @@ from mineru.types import (MiddleJson,PageAuxTextBlock,PageBlock,+ PageFootnoteBlock,PageInfo,ParagraphTitleBlock,RefTextBlock,@@ -159,8 +160,8 @@ def test_default_and_full_modes_preserve_their_page_contracts() -> None:assert "HEADER" in full.get_text() and "FOOTER" in full.get_text()-def test_full_html_links_to_page_footnote_anchor() -> None:- """验证 FULL HTML 为页面脚注生成唯一 id,默认模式仍过滤脚注正文。"""+def test_default_and_full_html_link_to_visible_page_footnote_anchor() -> None:+ """验证默认与完整 HTML 都输出页面脚注目标及弱化样式类。"""middle = _middle(_page(0,@@ -169,7 +170,7 @@ def test_full_html_links_to_page_footnote_anchor() -> None:index=0,content="See <hyperlink>[1]<url>#note-one</url></hyperlink>.",),- PageAuxTextBlock(+ PageFootnoteBlock(type="page_footnote",index=1,content="Footnote body.",@@ -182,10 +183,11 @@ def test_full_html_links_to_page_footnote_anchor() -> None:full = BeautifulSoup(render_html(middle, mode=RenderMode.FULL, standalone=False), "html.parser")assert default.select_one('a[href="#note-one"]') is not None- assert default.select_one("#note-one") is None- target = full.select_one("#note-one")- assert target is not None- assert target.get_text() == "Footnote body."+ for output in (default, full):+ target = output.select_one("#note-one.mineru-page-footnote")+ assert target is not None+ assert target["data-block-type"] == "page_footnote"+ assert target.get_text() == "Footnote body."assert full.select_one('a[href="#note-one"]') is not Nonediff --git a/tests/unittest/test_markdown_render.py b/tests/unittest/test_markdown_render.pyindex 749c412e..d6c37c2a 100644--- a/tests/unittest/test_markdown_render.py+++ b/tests/unittest/test_markdown_render.py@@ -20,6 +20,7 @@ from mineru.types import (MiddleJson,PageAuxTextBlock,PageBlock,+ PageFootnoteBlock,PageInfo,ParagraphTitleBlock,RefTextBlock,@@ -126,7 +127,7 @@ def test_render_modes_filter_merge_and_preserve_input() -> None:1,PageAuxTextBlock(type="page_number", index=0, content="2"),TextBlock(type="text", index=1, content="again", continues_prev=True),- PageAuxTextBlock(type="page_footnote", index=2, content="NOTE"),+ PageFootnoteBlock(type="page_footnote", index=2, content="NOTE"),),)before = middle.to_json(skip_defaults=False)@@ -134,18 +135,19 @@ def test_render_modes_filter_merge_and_preserve_input() -> None:default = render_markdown(middle)full = render_markdown(middle, mode=RenderMode.FULL)- assert default == "Hello world again\n\n"+ note = '<small><span class="mineru-page-footnote" data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'+ assert default == f"Hello world again\n\n\n\n{note}"assert full == "\n\n---\n\n".join(["HEADER\n\nHello world\n\n\n\nFOOTER",- "2\n\nagain\n\nNOTE",+ f"2\n\nagain\n\n{note}",])assert middle.to_json(skip_defaults=False) == before-def test_page_footnote_anchor_is_emitted_only_in_full_mode() -> None:- """验证默认模式隐藏脚注正文,FULL 输出可供正向引用跳转的 anchor。"""+def test_page_footnote_is_styled_and_linkable_in_default_and_full_modes() -> None:+ """验证默认与完整模式都输出非折叠的小字号页面脚注及 anchor。"""middle = _middle(_page(0,@@ -154,7 +156,7 @@ def test_page_footnote_anchor_is_emitted_only_in_full_mode() -> None:index=0,content="See <hyperlink>[1]<url>#note-one</url></hyperlink>.",),- PageAuxTextBlock(+ PageFootnoteBlock(type="page_footnote",index=1,content="Footnote body.",@@ -163,9 +165,29 @@ def test_page_footnote_anchor_is_emitted_only_in_full_mode() -> None:))- assert render_markdown(middle) == "See [\\[1\\]](#note-one)."- assert render_markdown(middle, mode=RenderMode.FULL) == (- 'See [\\[1\\]](#note-one).\n\n<a id="note-one"></a>\nFootnote body.'+ expected = (+ 'See [\\[1\\]](#note-one).\n\n<small><span id="note-one" class="mineru-page-footnote" '+ 'data-block-type="page_footnote" style="color:#6b7280">Footnote body.</span></small>'+ )+ assert render_markdown(middle) == expected+ assert render_markdown(middle, mode=RenderMode.FULL) == expected+ assert "Page footnote:" not in expected+++def test_page_footnote_does_not_interrupt_continued_text_rendering() -> None:+ """验证页面脚注保持独立输出,但不会阻断前后正文续接。"""+ middle = _middle(+ _page(+ 0,+ TextBlock(type="text", index=0, content="inter-"),+ PageFootnoteBlock(type="page_footnote", index=1, content="NOTE"),+ TextBlock(type="text", index=2, content="national", continues_prev=True),+ )+ )++ assert render_markdown(middle) == (+ 'international\n\n<small><span class="mineru-page-footnote" '+ 'data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>')@@ -198,13 +220,13 @@ def test_text_continuation_handles_hyphen_and_cjk_boundaries() -> None:assert render_markdown(cjk) == "中文继续"-def test_ref_text_continuation_skips_page_auxiliary_blocks_by_mode() -> None:- """验证 ref_text 默认跨页合并,FULL 只合并页内链且不修改输入。"""+def test_ref_text_continuation_skips_merge_transparent_blocks_by_mode() -> None:+ """验证 ref_text 可跨页面脚注与辅助块查找,FULL 仍保留页界。"""middle = _middle(_page(0,_ref_text(0, "inter-"),- PageAuxTextBlock(type="page_footnote", index=1, content="NOTE"),+ PageFootnoteBlock(type="page_footnote", index=1, content="NOTE"),),_page(1,@@ -215,10 +237,9 @@ def test_ref_text_continuation_skips_page_auxiliary_blocks_by_mode() -> None:)original = deepcopy(middle)- assert render_markdown(middle) == "international continuation"- assert render_markdown(middle, mode=RenderMode.FULL) == (- "inter-\n\nNOTE\n\n---\n\nHEADER\n\nnational continuation"- )+ note = '<small><span class="mineru-page-footnote" data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'+ assert render_markdown(middle) == f"international continuation\n\n{note}"+ assert render_markdown(middle, mode=RenderMode.FULL) == (f"inter-\n\n{note}\n\n---\n\nHEADER\n\nnational continuation")assert middle == original@@ -279,18 +300,16 @@ def test_list_continuation_merges_cross_page_chain_only_in_default_mode() -> Non)assert render_markdown(middle) == "[1] first\n[2] second\n[3] third"- assert render_markdown(middle, mode=RenderMode.FULL) == (- "[1] first\n\n---\n\n[2] second\n[3] third"- )+ assert render_markdown(middle, mode=RenderMode.FULL) == ("[1] first\n\n---\n\n[2] second\n[3] third")-def test_ref_list_continuation_skips_page_auxiliary_blocks_without_mutating_input() -> None:- """验证默认模式跨页面辅助块合并参考文献,完整模式仍保留原始页界和顺序。"""+def test_ref_list_continuation_skips_merge_transparent_blocks_without_mutating_input() -> None:+ """验证默认模式跨页面脚注与辅助块合并参考文献,FULL 仍保留页界。"""middle = _middle(_page(0,_list(0, "[1] first", sub_type="ref_text"),- PageAuxTextBlock(type="page_footnote", index=1, content="NOTE"),+ PageFootnoteBlock(type="page_footnote", index=1, content="NOTE"),),_page(1,@@ -301,20 +320,19 @@ def test_ref_list_continuation_skips_page_auxiliary_blocks_without_mutating_inpu)original = deepcopy(middle)- assert render_markdown(middle) == "[1] first\n[2] second"- assert render_markdown(middle, mode=RenderMode.FULL) == (- "[1] first\n\nNOTE\n\n---\n\nHEADER\n\n2\n\n[2] second"- )+ note = '<small><span class="mineru-page-footnote" data-block-type="page_footnote" style="color:#6b7280">NOTE</span></small>'+ assert render_markdown(middle) == f"[1] first\n[2] second\n\n{note}"+ assert render_markdown(middle, mode=RenderMode.FULL) == (f"[1] first\n\n{note}\n\n---\n\nHEADER\n\n2\n\n[2] second")assert middle == original-def test_ordinary_list_continuation_does_not_skip_page_auxiliary_blocks() -> None:- """验证页面辅助块透明规则只作用于参考文献,普通列表仍要求物理相邻。"""+def test_ordinary_list_continuation_does_not_skip_page_footnote() -> None:+ """验证页面脚注透明规则只作用于参考文献,普通列表仍要求物理相邻。"""middle = _middle(_page(0,_list(0, "- first"),- PageAuxTextBlock(type="page_footnote", index=1, content="NOTE"),+ PageFootnoteBlock(type="page_footnote", index=1, content="NOTE"),),_page(1,@@ -323,7 +341,10 @@ def test_ordinary_list_continuation_does_not_skip_page_auxiliary_blocks() -> Non),)- assert render_markdown(middle) == "- first\n\n- second"+ assert render_markdown(middle) == (+ '- first\n\n<small><span class="mineru-page-footnote" data-block-type="page_footnote" '+ 'style="color:#6b7280">NOTE</span></small>\n\n- second'+ )def test_list_continuation_keeps_semantic_barrier_and_matching_subtype() -> None:@@ -404,9 +425,7 @@ def test_reference_list_bullets_mixed_children_without_duplication() -> None:],)- assert render_markdown(_middle(_page(0, block), file_suffix="pdf")) == (- "- existing\n- Author A\n continued"- )+ assert render_markdown(_middle(_page(0, block), file_suffix="pdf")) == ("- existing\n- Author A\n continued")def test_nested_reference_list_decides_bullets_independently() -> None:@@ -644,10 +663,7 @@ def test_complex_html_tables_fall_back_to_html(html_table: str) -> None:def test_simple_html_table_converts_to_gfm_and_preserves_inline_formula() -> None:"""验证简单 HTML table 转 GFM,并保留单元格公式反斜杠。"""- content = (- "<table><tr><th>Name</th><th>Value</th></tr>"- "<tr><td>A|B</td><td><eq>\\frac{1}{2}</eq></td></tr></table>"- )+ content = "<table><tr><th>Name</th><th>Value</th></tr><tr><td>A|B</td><td><eq>\\frac{1}{2}</eq></td></tr></table>"assert render_markdown(_middle(_page(0, _table(0, content)))) == "\n".join([@@ -726,10 +742,7 @@ def test_algorithm_preserves_whitespace_comparisons_scripts_and_formula() -> NonCodeBodyBlock(type="code_body",index=0,- content=(- "if a < b and c > d:\n T<sub>queue</sub><sup>2</sup> = "- "<eq>a < b</eq><eq>c > d</eq>"- ),+ content=("if a < b and c > d:\n T<sub>queue</sub><sup>2</sup> = <eq>a < b</eq><eq>c > d</eq>"),)],)diff --git a/tests/unittest/test_middle_json_block_models.py b/tests/unittest/test_middle_json_block_models.pyindex fa429c1a..ab09c35b 100644--- a/tests/unittest/test_middle_json_block_models.py+++ b/tests/unittest/test_middle_json_block_models.py@@ -27,6 +27,7 @@ from mineru.types import (ModelJson,PageAuxTextBlock,PageBlockTypes,+ PageFootnoteBlock,PageInfo,RefTextBlock,TableAnnotationBlock,@@ -109,8 +110,8 @@ def test_shared_models_preserve_all_discriminator_values() -> None:assert isinstance(parse_block({"type": "code_footnote", "content": "f"}), CodeAnnotationBlock)-def test_page_aux_anchor_is_restricted_to_page_footnote() -> None:- """验证共享 PageAux 模型仅允许 page_footnote 使用可选 anchor。"""+def test_page_footnote_uses_independent_model_and_exclusive_anchor() -> None:+ """验证页面脚注使用独立模型,页面辅助块不再接受 anchor。"""footnote = parse_block({"type": "page_footnote",@@ -119,11 +120,11 @@ def test_page_aux_anchor_is_restricted_to_page_footnote() -> None:})- assert isinstance(footnote, PageAuxTextBlock)+ assert isinstance(footnote, PageFootnoteBlock)assert footnote.anchor == "note-one"assert footnote.to_dict()["anchor"] == "note-one"for block_type in ("header", "footer", "page_number", "aside_text"):- with pytest.raises(ValidationError, match="only supported for page_footnote"):+ with pytest.raises(ValidationError, match="Extra inputs are not permitted"):parse_block({"type": block_type, "content": "aux", "anchor": "invalid"})@@ -250,7 +251,6 @@ def test_removed_block_classes_are_not_exposed() -> None:"HeaderBlock","FooterBlock","PageNumberBlock",- "PageFootnoteBlock","ImageCaptionBlock","ImageFootnoteBlock","TableCaptionBlock",diff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.pyindex d8539e75..e644d9d0 100644--- a/tests/unittest/test_parse_result_contract.py+++ b/tests/unittest/test_parse_result_contract.py@@ -6,7 +6,7 @@ from pydantic import ValidationErrorfrom mineru.parser.base import ParseResultfrom mineru.parser import MIDDLE_JSON_SCHEMA_VERSION-from mineru.types import BlockType, MiddleJson, PageAuxTextBlock, PageInfo, TableBlock, TableBodyBlock, TextBlock+from mineru.types import BlockType, MiddleJson, PageFootnoteBlock, PageInfo, TableBlock, TableBodyBlock, TextBlockfrom mineru.utils.image_payload import ImagePayloadCachefrom mineru.version import __version__@@ -28,22 +28,25 @@ def test_parse_result_from_dict_restores_pages() -> None:result = ParseResult(middle_json=MiddleJson(pages=[- PageInfo(- page_idx=3,- blocks=[- TextBlock(- type=BlockType.TEXT,- index=0,- bbox=(0.0, 0.0, 0.1, 0.1),- content="hello",- )- ],- )- ],+ PageInfo(+ page_idx=3,+ blocks=[+ TextBlock(+ type=BlockType.TEXT,+ index=0,+ bbox=(0.0, 0.0, 0.1, 0.1),+ content="hello",+ )+ ],+ )+ ],is_full_document=True,- file_suffix="pdf", effort="medium", parse_mode="txt", mineru_version=__version__,- )+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version=__version__,)+ )restored = ParseResult.from_dict(result.to_dict())@@ -80,7 +83,7 @@ def test_parse_result_roundtrip_preserves_page_footnote_anchor() -> None:PageInfo(page_idx=0,blocks=[- PageAuxTextBlock(+ PageFootnoteBlock(type=BlockType.PAGE_FOOTNOTE,index=0,content="Footnote",diff --git a/tests/unittest/test_structured_content_render.py b/tests/unittest/test_structured_content_render.pyindex 6bc34eb8..a463744c 100644--- a/tests/unittest/test_structured_content_render.py+++ b/tests/unittest/test_structured_content_render.py@@ -19,6 +19,7 @@ from mineru.types import (MiddleJson,PageAuxTextBlock,PageBlock,+ PageFootnoteBlock,PageInfo,ParagraphTitleBlock,TableBlock,@@ -73,6 +74,13 @@ def test_structured_content_preserves_document_tree_without_merging_or_mutation(),TextBlock(type="text", index=1, content="first-"),PageAuxTextBlock(type="header", index=2, content="HEADER"),+ PageFootnoteBlock(+ type="page_footnote",+ index=3,+ bbox=(0.1, 0.8, 0.9, 0.9),+ anchor="note-one",+ content="Foot <eq>x</eq>",+ ),),_page(1,@@ -91,6 +99,7 @@ def test_structured_content_preserves_document_tree_without_merging_or_mutation("paragraph_title","text","header",+ "page_footnote",]assert result["pages"][0]["blocks"][0] == {"type": "paragraph_title",@@ -101,6 +110,12 @@ def test_structured_content_preserves_document_tree_without_merging_or_mutation(assert render_markdown(middle).startswith('<a id="section-a"></a>\n###### # **Section** $x$')assert result["pages"][0]["blocks"][1]["content"] == "first-"assert result["pages"][0]["blocks"][2]["content"] == "HEADER"+ assert result["pages"][0]["blocks"][3] == {+ "type": "page_footnote",+ "bbox": [0.1, 0.8, 0.9, 0.9],+ "anchor": "note-one",+ "content": "Foot $x$",+ }assert result["pages"][1]["blocks"][0]["content"] == "continued"assert result["pages"][1]["blocks"][0]["continues_prev"] is True_assert_output_field_contract(result)