Skip to content

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

feat(doclib): add visual block locators

jinzhenj0f7572574116
diff --git a/docs/next/architecture.md b/docs/next/architecture.md
index ce7c6b1a..4d76f642 100644
--- a/docs/next/architecture.md
+++ b/docs/next/architecture.md
@@ -314,16 +314,16 @@ ParseWorker 按 `tier`、`privacy` 和 parse-server 健康状态路由:
medium/
1~10_1710001234000.json
11~20_1710002234000.json
+ images/ # 仅在解析结果包含必要 sidecar 时存在
high/
1~20_1710003234000.json
xhigh/
1~20_1710004234000.json
- images/
```
每个 JSON 文件表示一次解析批次,文件名由页码范围和完成时间组成。每个 tier 独立目录,互不覆盖。remote 解析完成后也写入同一结构,供 CLI、SDK、搜索和缓存统一读取。
-doclib 不在 `parsed/` 中保存 Markdown、Content List 或 HTML。它们都从 Middle JSON 读取时转换得到;搜索索引可以使用临时渲染出的 Markdown 文本,但不把这份 Markdown 保存为产物文件。
+doclib 不在 `parsed/` 中保存 Markdown、Content List 或 HTML。它们都从 Middle JSON 读取时转换得到;搜索索引可以使用临时渲染出的 Markdown 文本,但不把这份 Markdown 保存为产物文件。PDF 和 image 通常不保存 block 图片,读取时从源页面按 bbox 裁剪;Office 等后端只有在解析结果包含图片时才保存 `images/` sidecar。
搜索策略:
diff --git a/docs/next/cli/mineru-parse.md b/docs/next/cli/mineru-parse.md
index 78ed6a29..a9f6ff1a 100644
--- a/docs/next/cli/mineru-parse.md
+++ b/docs/next/cli/mineru-parse.md
@@ -119,6 +119,8 @@ marker 是 Agent 的控制协议,不应依赖自然语言猜测。
默认输出到 STDOUT,便于 Agent 直接消费。指定 `--output` 时写入文件。
+Markdown 中的可视图片使用 `mineru read` 可读取的 block locator,不暴露 doclib 内部 `image_path`。`--output` 保留 locator 引用,只写 Markdown 文件,不额外创建 `images/` 目录。
+
`--json` 时,`mineru parse` 的顶层返回命令级 envelope:
```json
diff --git a/docs/next/cli/mineru-read.md b/docs/next/cli/mineru-read.md
index 6c9781a0..0615541a 100644
--- a/docs/next/cli/mineru-read.md
+++ b/docs/next/cli/mineru-read.md
@@ -84,6 +84,17 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
`--limit` 是软截断,尽量在页、block、段落、句子、换行或空白边界停止。
+### 可视 block 引用
+
+Markdown 继续优先输出 table、chart 和 formula 的结构化内容。需要输出图片时,doclib 使用可读取的 block locator,不暴露 Middle JSON 内部的 `image_path`:
+
+```markdown
+![Image block](doc:ab12cd3/tier:high/page:1/block:4)
+![Table block]()
+```
+
+非空 locator 表示该 block 当前可通过 `mineru read <locator> --format image` 读取;空 locator 表示没有可用图片。`--output` 只写 Markdown 文件,保留这些虚拟引用,不创建 `images/` 目录。
+
### `--context`
`--context N` 的含义随 locator 粒度变化:
@@ -104,15 +115,15 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
| 文档类型 | doc locator | doc/tier locator | page locator | block locator |
|----------|:-----------:|:----------------:|:------------:|:-------------:|
-| PDF | 不支持 | 不支持 | 支持 | 有 bbox 且 bbox 非 empty 时支持 |
-| Office | 不支持 | 不支持 | 不支持 | 仅 image block 支持 |
-| 其它 | 不支持 | 不支持 | 不支持 | 暂不支持 |
+| PDF / image | 不支持 | 不支持 | 支持 | 有有效 bbox 时支持;否则可回退到 sidecar |
+| Office / HTML | 不支持 | 不支持 | 不支持 | visual block 有可访问 image sidecar 时支持 |
实现语义:
-- PDF page image:从原 PDF page 渲染。
-- PDF block image:从原 PDF page 渲染后按 bbox 裁剪。
-- Office image block:从 Middle JSON 中的 image 数据生成临时 asset。
+- PDF / image page image:从源文件重新渲染页面。
+- 有有效 bbox 的 block image:从源页面渲染后按 bbox 裁剪。
+- 无有效 bbox 的 visual block:读取 doclib parsed 目录中的 image sidecar,并按请求格式生成临时 asset。
+- Markdown 中出现的非空 visual block locator 即表示该 block 支持 image 读取;源文件或 sidecar 在读取前被外部删除时,读取仍可能失败。
- `read --output` 是 CLI 本地写文件行为,不是 doclib HTTP API 写文件行为。
如果不带 `--output`,image 模式默认输出 server 返回的临时 asset path。
diff --git a/docs/next/decisions/0014-mineru-read-command.md b/docs/next/decisions/0014-mineru-read-command.md
index afe5cde1..83fd484f 100644
--- a/docs/next/decisions/0014-mineru-read-command.md
+++ b/docs/next/decisions/0014-mineru-read-command.md
@@ -62,6 +62,8 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
## Markdown 读取语义
+> visual block 的 Markdown 引用与 image 可用性规则已由 [ADR-0027](0027-doclib-visual-block-locators.md) 补充;`image_path` 不再作为 doclib 用户接口暴露。
+
`--format markdown` 是默认格式。
| Locator | 默认读取范围 |
@@ -94,25 +96,21 @@ doc:{short_id}/tier:{tier}/page:{page_no}/block:{block_no}/char:{offset}
| 文档类型 | doc locator | doc/tier locator | page locator | block locator |
|----------|:-----------:|:----------------:|:------------:|:-------------:|
-| PDF | 不支持 | 不支持 | 支持 | 有 bbox 且 bbox 非 empty 时支持 |
-| Office | 不支持 | 不支持 | 不支持 | 仅 image block 支持 |
-| 其它 | 不支持 | 不支持 | 不支持 | 暂不支持 |
+| PDF / image | 不支持 | 不支持 | 支持 | 有有效 bbox 时支持;否则可回退到 sidecar |
+| Office / HTML | 不支持 | 不支持 | 不支持 | visual block 有可访问 image sidecar 时支持 |
-PDF 的 image 输出规则:
+PDF / image 的 image 输出规则:
-- page image 从原 PDF page 渲染得到。
-- block image 从原 PDF page 渲染后按 bbox 裁剪得到。
+- page image 从源文件重新渲染得到。
+- block image 从源页面渲染后按 bbox 裁剪得到。
- block image 不按 block type 判断;只要 bbox 存在且非 empty,就可以输出 image。
-- 实现时复用 `PDFDocument.render_page()` / `PDFDocument.crop_image()`,并从 `files` 表按 `sha256` 查找 active source path 读取原 PDF bytes。
+- PDF 直接构造 `PDFDocument`;image 使用 `PDFDocument.from_image()` 重建解析时使用的单页 PDF。两者复用 `render_page()` / `crop_image()`。
-Office 的 image 输出规则:
+Office / HTML 的 image 输出规则:
-- Office 不支持 doc、doc/tier、page locator 输出 image。
-- Office 只有 image block 支持输出 image。
-- Office image block 只能从 Middle JSON 中读取 image asset。
-- 实现时优先使用 image block 内的 `span.image_base64` 解码生成临时 asset。
-- 如果 Middle JSON 中只有 `span.image_path`,仅在该 path 可访问时作为 fallback。
-- 当前 doclib parsed 目录只持久化 JSON,不保证已额外持久化 Office image 文件;因此不能依赖 `ParseResult.save()` 产物存在。
+- Office / HTML 不支持 doc、doc/tier、page locator 输出 image。
+- image、table、chart、formula 等 visual block 仅在 doclib parsed 目录中存在对应 image sidecar 时支持 image 输出。
+- `image_path` 只用于 doclib 内部安全解析 sidecar,不向 Markdown 读取者暴露。
默认情况下,image 输出打印 asset path。传入 `--output` 时,CLI 先根据输出路径后缀选择 `image_format`,由 server 生成匹配编码的临时 asset,再由 CLI 在 client 侧 copy 到指定路径。传入 `--json` 时输出完整 `DocContentResponse`。
@@ -373,7 +371,7 @@ def execute_read_plan(plan: ReadPlan) -> DocContentResponse: ...
- select page/block/char/context。
- render markdown。
- render page/block image。
-- PDF image 使用原 PDF 渲染/crop;Office image 使用 Middle JSON 中的 `span.image_base64` 或可访问的 `span.image_path`。
+- 有有效 bbox 的 block 使用 PDF/image 源页面渲染和裁剪;其他 visual block 使用 doclib parsed 目录中可访问的 sidecar。
- apply soft limit。
- build `content_ranges`。
- build `next_request`。
@@ -442,7 +440,7 @@ P0 不为 locator-first content API 提供 POST export。`GET /api/v1/content`
| `context_not_applicable` | doc 或 doc/tier locator 使用了 context。 |
| `format_not_supported` | 当前 locator 或文档类型不支持该 format。 |
| `multi_page_image_not_supported` | 请求范围覆盖多页 image。 |
-| `bbox_not_available` | PDF block 没有 bbox 或 bbox empty。 |
+| `bbox_not_available` | block 没有有效 bbox。 |
| `asset_not_available` | Office image block 没有可读取 asset。 |
## P0 范围
diff --git a/docs/next/decisions/0027-doclib-visual-block-locators.md b/docs/next/decisions/0027-doclib-visual-block-locators.md
index 04e2394c..0a77fc6d 100644
--- a/docs/next/decisions/0027-doclib-visual-block-locators.md
+++ b/docs/next/decisions/0027-doclib-visual-block-locators.md
@@ -4,11 +4,11 @@
日期: 2026-07-17
相关文档: 0012-doclib-block-locator.md, 0014-mineru-read-command.md, 0015-cli-output-json-composition.md, ../architecture.md, ../cli/mineru-read.md
-本 ADR 补充 ADR-0014 的 Markdown 图片引用和 Office block image 读取语义。ADR-0014 中 locator-first、PDF bbox 裁图、`DocContentResponse` 与 CLI `--output` 的其他决策保持不变。
+本 ADR 补充 ADR-0014 的 Markdown 图片引用和 block image 读取语义。ADR-0014 中 locator-first、源页面 bbox 裁图、`DocContentResponse` 与 CLI `--output` 的其他决策保持不变。
## 背景
-doclib 的目标是保存可渐进读取的 Middle JSON,而不是为大量 PDF 长期保存所有裁图。当前默认解析路径中,PDF 通常只保存 Middle JSON;Office 因缺少可靠 bbox,会保存解析得到的图片 sidecar。
+doclib 的目标是保存可渐进读取的 Middle JSON,而不是为大量 PDF 或 image 长期保存所有裁图。当前 PDF 和 image block 使用可映射回源页面的 bbox;Office 因缺少可靠 bbox,会保存解析得到的图片 sidecar。
PDF Middle JSON 仍可能包含解析阶段生成的 `image_path`。通用 Markdown renderer 会把它渲染为:
@@ -52,7 +52,7 @@ mineru read "doc:ab12cd3/tier:high/page:1/block:4" --format image --output image
视觉 block 按以下顺序判定是否输出非空 locator:
-1. PDF block 有有效 bbox 时,输出 canonical block locator。渲染 Markdown 时不检查源 PDF 是否存在。
+1. block 有有效 bbox 时,输出 canonical block locator。当前只有 PDF 和 image block 会产生这种 bbox,且两者都能重新渲染源页面;渲染 Markdown 时不检查源文件是否存在。
2. 否则,递归检查 block 中的视觉 span。如果存在安全的 `image_path`,并且它在当前文档和 tier 的 doclib sidecar 目录中对应实际文件,则输出 canonical block locator。
3. 其他情况输出对应类型的空 locator。
@@ -72,7 +72,7 @@ sidecar 只能从以下目录解析:
`mineru read <block-locator> --format image` 使用与 Markdown 相同的解析顺序:
-1. PDF block 有有效 bbox 时,从当前可访问的源 PDF 即时裁剪。
+1. block 有有效 bbox 时,从当前可访问的 PDF 或 image 源页面即时裁剪。
2. 否则,读取 resolver 选中的 doclib sidecar。
3. 两种方式都不可用时,返回现有结构化错误。
@@ -80,7 +80,7 @@ sidecar 只能从以下目录解析:
运行时错误沿用现有语义:
-- PDF 源文件不可访问: `no_accessible_file`。
+- PDF 或 image 源文件不可访问: `no_accessible_file`。
- bbox 在实际读取时不可用: `bbox_not_available`。
- sidecar 不存在或不可读取: `asset_not_available`。
- locator 指向不存在的 block: `block_not_found`。
@@ -96,7 +96,24 @@ Doclib renderer 只替换原本会产生图片引用的部分:
- table、chart 或公式已有 Markdown、HTML、文本或 LaTeX 内容时,继续输出结构化内容,不额外增加图片占位。
- caption、footnote 和其他文本内容保持原有顺序。
-Doclib 使用专门的 block renderer 生成这些引用。通用 renderer 不改变,避免影响 Parse SDK、Parse API、`mineru-kit` 和其他直接消费 ParseResult/Middle JSON 的调用方。
+通用 Markdown renderer 增加可选的 block-level 图片扩展点:
+
+```python
+ImageRenderer = Callable[[Block], str]
+
+def blocks_to_markdown(
+ blocks: list[Block],
+ ...,
+ image_renderer: ImageRenderer | None = None,
+) -> list[str]:
+ ...
+```
+
+未传 `image_renderer` 时,继续使用既有 image path 渲染逻辑,按 `image_path` 和 `img_bucket_path` 生成普通 Markdown 图片引用。doclib 传入绑定当前文档上下文的 closure 或 partial,返回完整的类型化虚拟图片引用。
+
+`Block` 不包含 doclib 的 `data_dir`、`sha256`、`short_id`、`tier` 和 `page_no`。doclib 因此通过 factory 创建 `Callable[[Block], str]`,在 callable 中绑定这些上下文。通用 render 模块保持纯函数,不访问 doclib 数据库或磁盘。
+
+renderer 只在原本需要输出图片的位置调用 `image_renderer`。caption、footnote、结构化 table/chart/formula 内容继续复用现有逻辑。默认实现的输出行为保持不变,避免影响 Parse SDK、Parse API、`mineru-kit` 和其他直接消费 ParseResult/Middle JSON 的调用方。
### 5. `image_path` 是 Doclib 内部实现细节
@@ -138,15 +155,15 @@ Doclib 使用专门的 block renderer 生成这些引用。通用 renderer 不
- Doclib Markdown 不再是普通 Markdown reader 可直接加载图片的自包含文档;`doc:` 是 MinerU-aware client 和 Agent 使用的虚拟引用。
- 视觉 block 是否具有非空 locator,明确表达其当前 image 读取能力。
-- PDF 继续避免长期保存大量裁图,只在显式 image read 时按 bbox 生成。
+- PDF 和 image 继续避免长期保存大量裁图,只在显式 image read 时按 bbox 生成。
- Office 和 HTML 可以通过现有 sidecar 支持 block image read。
- 内部图片命名和存储策略可以演进,不影响 doclib 的公共 Markdown 契约。
- 现有依赖 `images/<hash>` 的 doclib Markdown 消费方需要改为识别 block locator。
## 测试要求
-- PDF block 有有效 bbox 时输出非空 locator,并可通过同一 locator 裁图。
-- PDF block 无有效 bbox,但存在 sidecar 时使用 sidecar。
+- block 有有效 bbox 时输出非空 locator,并可通过同一 locator 从 PDF 或 image 源页面裁图。
+- block 无有效 bbox,但存在 sidecar 时使用 sidecar。
- 无有效 bbox且 sidecar 不存在时输出类型化空 locator。
- Office/HTML 的 image、table、chart sidecar locator 可以通过 `--format image` 读取。
- image、table、chart、formula 使用对应 alt text。
@@ -159,7 +176,8 @@ Doclib 使用专门的 block renderer 生成这些引用。通用 renderer 不
## 后续动作
- 在 doclib server 中增加共享的 block image resolver。
-- 让 doclib Markdown renderer 使用类型化虚拟 block 图片引用。
+- 为通用 Markdown renderer 增加默认兼容的 `image_renderer` 扩展点。
+- 让 doclib 通过绑定文档上下文的 `image_renderer` 生成类型化虚拟 block 图片引用。
- 扩展 block image read,使无 bbox block 可以读取已有 sidecar。
- 更新 ADR-0014、CLI、API、SDK 和 workflow 文档中的 doclib 图片引用说明。
- 在 issue #5274 中说明最终行为和兼容边界。
diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.md
index e283ba54..b30ca1c4 100644
--- a/docs/next/sdk/doclib-client.md
+++ b/docs/next/sdk/doclib-client.md
@@ -122,6 +122,8 @@ class ParseResponse:
`force=True` 与 `invalidate()` 不等价。`force=True` 跳过 done cache,并通过 `wait_parse_ids` 等待复用或新建的 active parse;旧结果仍然有效。`invalidate()` 会让旧结果退出缓存命中、读取合并、搜索刷新和 compaction 选择。
+Markdown 响应中的 visual block 图片使用 `doc:.../page:.../block:...` locator。非空图片 locator 可以原样传给 `read_content(..., format="image")`;空 locator 表示该 block 没有可用图片。SDK 调用方不应依赖或拼接 Middle JSON 内部的 `image_path`。
+
## Search 与 Info
```python
diff --git a/docs/next/workflows.md b/docs/next/workflows.md
index 823e8b44..142a0822 100644
--- a/docs/next/workflows.md
+++ b/docs/next/workflows.md
@@ -333,7 +333,7 @@ client.parse("report.pdf")
| Markdown | 默认阅读输出;读取时从 Middle JSON 转换 |
| Content List / HTML | 读取时从 Middle JSON 转换 |
-doclib 不持久化 Markdown、Content List 或 HTML。它们都是 CPU-only 的派生格式,转换成本低,按需生成即可。
+doclib 不持久化 Markdown、Content List 或 HTML。它们都是 CPU-only 的派生格式,转换成本低,按需生成即可。Markdown 中的图片使用 visual block locator;`image_path` 是 doclib 内部 sidecar 定位信息,不向读取者暴露。
### 6.7 约束
@@ -486,11 +486,11 @@ doclib 解析产物按内容和实际使用的 tier 隔离。`parsed/` 目录下
medium/
1~10_1710001234000.json
11~20_1710002234000.json
+ images/ # 可选,仅保存解析产生的必要 sidecar
high/
1~20_1710003234000.json
xhigh/
1~20_1710004234000.json
- images/
```
单个 JSON 文件表示一次解析批次,基本形态:
@@ -508,6 +508,8 @@ doclib 不在 `parsed/` 中保存:
- `output.md`
- `content_list.json`
- `structured_content.json`
+
+PDF 和 image block 图片通常在读取时从源页面按 bbox 裁剪,不写入 `images/`。无 bbox 的 visual block 只有在对应 sidecar 文件存在时才输出非空图片 locator。
- `output.html`
这些格式都由 Middle JSON 读取时转换得到。
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 8f051795..fe425ee7 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -3,11 +3,13 @@
from __future__ import annotations
import asyncio
+import math
import os
import re
import signal
import sys
import time
+from collections.abc import Callable
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
@@ -21,12 +23,11 @@ from pydantic import ValidationError
from ..config import config
from ..errors import InvalidRequestError, MineruError, NotFoundError, error_response, http_status_for
-from ..filetypes import TEXT_EXTENSIONS, TEXT_FILE_TYPES
+from ..filetypes import IMAGE_EXTENSIONS, TEXT_EXTENSIONS, TEXT_FILE_TYPES
from ..parser.tier import TierDependencyError, ensure_tier_runtime_dependencies
-from ..render import render_markdown
from ..render.markdown import blocks_to_markdown
from ..render.office.output import blocks_to_markdown as office_blocks_to_markdown
-from ..types import EMPTY_BBOX, TIERS, Block, PageInfo, Span, Tier, select_highest_cached_tier
+from ..types import EMPTY_BBOX, TIERS, Block, BlockType, PageInfo, Span, Tier, select_highest_cached_tier
from ..utils.model_registry import ModelRepo, model_repos_for_tier
from ..utils.models_download_utils import verify_model_repo
from ..utils.pdf_document import PDFDocument
@@ -125,10 +126,10 @@ from .types import (
ParsingRuleListResponse,
ParsingRuleRequest,
RemoteParseServerStatus,
+ RemoteUsageResponse,
RemoveExcludeRuleResponse,
RemoveParsingRuleResponse,
RemoveWatchResponse,
- RemoteUsageResponse,
ScanInfo,
ScanKind,
ScanListResponse,
@@ -184,9 +185,21 @@ class _ReadPlan:
next_mode: str = "parse"
-_PUBLIC_IMAGE_BUCKET_PATH = "images"
_NO_MATCHING_DOC_SHA256 = "__mineru_no_matching_doc__"
+_VISUAL_BLOCK_LABELS = {
+ BlockType.IMAGE: "Image block",
+ BlockType.TABLE: "Table block",
+ BlockType.CHART: "Chart block",
+ BlockType.INTERLINE_EQUATION: "Formula block",
+}
+
+
+@dataclass(frozen=True)
+class _BlockImageSource:
+ kind: str
+ sidecar_path: Path | None = None
+
@dataclass(frozen=True)
class _LocatorParts:
@@ -1190,12 +1203,25 @@ class DoclibServer(AsyncDoclibInterface):
loaded_pages = filter_pages_by_user_range(loaded_pages, page_range)
if not loaded_pages:
raise NotFoundError("not_cached", "Requested parsed content is not cached.", "page_range")
- return render_markdown(
- loaded_pages,
- img_bucket_path=_PUBLIC_IMAGE_BUCKET_PATH,
- add_markers=not no_marker,
- prefer_markdown_table=True,
- )
+ doc = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha256,)))
+ if doc is None:
+ raise NotFoundError("doc_not_found", f"Document {sha256} not found.", "doc_ref")
+ output: list[str] = []
+ page_count = doc["page_count"]
+ for page in loaded_pages:
+ if not no_marker:
+ output.append(_page_marker(page.page_idx + 1, page_count))
+ output.extend(
+ text
+ for _, text in _page_markdown_blocks(
+ page,
+ data_dir=data_dir,
+ sha256=sha256,
+ short_id=doc["short_id"],
+ tier=tier,
+ )
+ )
+ return "\n\n".join(output)
async def _execute_read_plan(self, plan: _ReadPlan) -> DocContentResponse:
data_dir = _effective_data_dir(self.state)
@@ -1209,12 +1235,15 @@ class DoclibServer(AsyncDoclibInterface):
if not loaded_pages:
raise NotFoundError("not_cached", "Requested parsed content is not cached.", "page_range")
+ doc = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (plan.sha256,)))
if plan.format == "image":
return await self._render_image_response(plan, loaded_pages)
pages_for_render = _select_context_pages(loaded_pages, plan.target, plan.context)
rendered = _render_progressive_markdown(
pages_for_render,
+ data_dir=data_dir,
+ sha256=plan.sha256,
short_id=plan.short_id,
tier=plan.tier,
after=_parse_after_cursor(plan.after),
@@ -1222,12 +1251,11 @@ class DoclibServer(AsyncDoclibInterface):
add_markers=not plan.no_marker,
target=plan.target,
context=plan.context,
- img_bucket_path=_PUBLIC_IMAGE_BUCKET_PATH,
+ page_count=doc["page_count"] if doc else None,
)
if not rendered.content_ranges:
raise NotFoundError("not_cached", "Requested parsed content is not cached after cursor.", "after")
- doc = cast(DocRow | None, await self.state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (plan.sha256,)))
page_count = doc["page_count"] if doc else None
paginated = _is_paginated_doc(doc) if doc else True
next_request = (
@@ -1259,7 +1287,11 @@ class DoclibServer(AsyncDoclibInterface):
next_request=next_request,
)
- async def _render_image_response(self, plan: _ReadPlan, loaded_pages: list[PageInfo]) -> DocContentResponse:
+ async def _render_image_response(
+ self,
+ plan: _ReadPlan,
+ loaded_pages: list[PageInfo],
+ ) -> DocContentResponse:
if plan.target is None or plan.target.page_no is None:
raise InvalidRequestError("format_not_supported", "image format requires a page or block locator.", "format")
if plan.page_range and len(parse_page_range_set(plan.page_range)) != 1:
@@ -1268,10 +1300,21 @@ class DoclibServer(AsyncDoclibInterface):
if page is None:
raise NotFoundError("page_not_cached", f"Page {plan.target.page_no} is not cached.", "locator")
- if _is_office_page(page):
- asset = await self._render_office_image_asset(plan, page)
+ if plan.target.block_no is None:
+ asset = await self._render_source_image_asset(plan, page)
else:
- asset = await self._render_pdf_image_asset(plan, page)
+ block = _find_block_by_no(page, plan.target.block_no)
+ if block is None:
+ raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")
+ image_dir = parse_image_sidecar_dir(_effective_data_dir(self.state), plan.sha256, plan.tier)
+ source = _resolve_block_image_source(block, image_dir=image_dir)
+ if source is None:
+ raise NotFoundError("asset_not_available", "Block image asset is not available.", "locator")
+ if source.kind == "source_bbox":
+ asset = await self._render_source_image_asset(plan, page)
+ else:
+ assert source.sidecar_path is not None
+ asset = self._render_sidecar_image_asset(plan, source.sidecar_path)
target_ref = plan.locator or page_ref(plan.short_id, plan.tier, plan.target.page_no)
return DocContentResponse(
@@ -1355,7 +1398,7 @@ class DoclibServer(AsyncDoclibInterface):
return None
return select_highest_cached_tier(tiers)
- async def _render_pdf_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:
+ async def _render_source_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:
if plan.target is None:
raise InvalidRequestError("format_not_supported", "image format requires a page or block locator.", "format")
file_row = cast(
@@ -1368,16 +1411,26 @@ class DoclibServer(AsyncDoclibInterface):
if file_row is None:
raise NotFoundError("no_accessible_file", "No active source file found for this document.", "locator")
source_path = file_row["path"]
- if not source_path.lower().endswith(".pdf"):
+ source_ext = str(file_row.get("ext") or Path(source_path).suffix).lower().lstrip(".")
+ source_bytes = Path(source_path).read_bytes()
+ if source_ext == "pdf":
+ doc = PDFDocument(source_bytes)
+ elif source_ext in IMAGE_EXTENSIONS:
+ doc = PDFDocument.from_image(source_bytes)
+ else:
raise InvalidRequestError(
- "format_not_supported", "image format for page/block is only supported for PDF sources.", "format"
+ "format_not_supported",
+ "Page and bbox image output is only supported for PDF and image sources.",
+ "format",
)
- pdf_bytes = Path(source_path).read_bytes()
- with PDFDocument(pdf_bytes) as doc:
+ with doc:
if plan.target.block_no is None:
- image = doc.render_page(plan.target.page_no - 1, scale=2).pil_image
- image_bytes = _pil_image_to_bytes(image, plan.image_format)
- width, height = image.size
+ image = doc.render_page(plan.target.page_no - 1).pil_image
+ try:
+ image_bytes = _pil_image_to_bytes(image, plan.image_format)
+ width, height = image.size
+ finally:
+ image.close()
else:
block = _find_block_by_no(page, plan.target.block_no)
if block is None:
@@ -1385,7 +1438,8 @@ class DoclibServer(AsyncDoclibInterface):
if _is_empty_bbox(block.bbox):
raise InvalidRequestError("bbox_not_available", "Block bbox is not available for image output.", "locator")
image_bytes = _transcode_image_bytes(
- doc.crop_image(block.bbox, plan.target.page_no - 1, scale=2), plan.image_format
+ doc.crop_image(block.bbox, plan.target.page_no - 1, scale=doc.render_scale),
+ plan.image_format,
)
width, height = _image_size_from_bytes(image_bytes)
return _write_temp_asset(
@@ -1398,25 +1452,8 @@ class DoclibServer(AsyncDoclibInterface):
height=height,
)
- async def _render_office_image_asset(self, plan: _ReadPlan, page: PageInfo) -> ContentAsset:
- if plan.target is None or plan.target.block_no is None:
- raise InvalidRequestError("format_not_supported", "Office image output requires an image block locator.", "format")
- block = _find_block_by_no(page, plan.target.block_no)
- if block is None:
- raise NotFoundError("block_not_found", f"Block {plan.target.block_no} not found.", "locator")
- image_span = _first_image_span(block)
- if image_span is None:
- raise InvalidRequestError(
- "format_not_supported", "Office image output is only supported for image blocks.", "format"
- )
- image_bytes = None
- if image_span.image_path:
- image_dir = parse_image_sidecar_dir(self.state.data_dir, plan.sha256, plan.tier)
- candidate = resolve_image_sidecar_path(image_dir, image_span.image_path)
- if candidate is not None and candidate.is_file():
- image_bytes = candidate.read_bytes()
- if image_bytes is None:
- raise NotFoundError("asset_not_available", "Office image asset is not available.", "locator")
+ def _render_sidecar_image_asset(self, plan: _ReadPlan, sidecar_path: Path) -> ContentAsset:
+ image_bytes = sidecar_path.read_bytes()
image_bytes = _transcode_image_bytes(image_bytes, plan.image_format)
width, height = _image_size_from_bytes(image_bytes)
return _write_temp_asset(
@@ -1743,29 +1780,7 @@ def _find_page(pages: list[PageInfo], page_no: int) -> PageInfo | None:
def _find_block_by_no(page: PageInfo, block_no: int) -> Block | None:
target_index = block_no - 1
- for block in page.para_blocks:
- found = _find_block_by_index(block, target_index)
- if found is not None:
- return found
- for block in page.discarded_blocks:
- found = _find_block_by_index(block, target_index)
- if found is not None:
- return found
- return None
-
-
-def _find_block_by_index(block: Block, index: int) -> Block | None:
- if block.index == index:
- return block
- for child in block.blocks:
- found = _find_block_by_index(child, index)
- if found is not None:
- return found
- return None
-
-
-def _is_office_page(page: PageInfo) -> bool:
- return page._backend == "office"
+ return next((block for block in page.para_blocks if block.index == target_index), None)
def _is_empty_bbox(bbox: object) -> bool:
@@ -1775,16 +1790,42 @@ def _is_empty_bbox(bbox: object) -> bool:
values = [float(v) for v in bbox]
except (TypeError, ValueError):
return True
+ if not all(math.isfinite(value) for value in values):
+ return True
return tuple(values) == tuple(float(v) for v in EMPTY_BBOX) or values[0] >= values[2] or values[1] >= values[3]
-def _first_image_span(block: Block) -> Span | None:
+def _resolve_block_image_source(block: Block, *, image_dir: str) -> _BlockImageSource | None:
+ if not _is_empty_bbox(block.bbox):
+ return _BlockImageSource(kind="source_bbox")
for span in _iter_block_spans(block):
- if span.type == "image":
- return span
+ if not span.image_path:
+ continue
+ candidate = resolve_image_sidecar_path(image_dir, span.image_path)
+ if candidate is not None and candidate.is_file():
+ return _BlockImageSource(kind="sidecar", sidecar_path=candidate)
return None
+def _make_doclib_image_renderer(
+ *,
+ data_dir: str,
+ sha256: str,
+ short_id: str,
+ tier: Tier,
+ page_no: int,
+) -> Callable[[Block], str]:
+ image_dir = parse_image_sidecar_dir(data_dir, sha256, tier)
+
+ def _render(block: Block) -> str:
+ label = _VISUAL_BLOCK_LABELS.get(block.type, "Image block")
+ source = _resolve_block_image_source(block, image_dir=image_dir)
+ locator = block_ref(short_id, tier, page_no, block.index + 1) if source is not None else ""
+ return f"![{label}]({locator})"
+
+ return _render
+
+
def _iter_block_spans(block: Block) -> Iterator[Span]:
for line in block.lines:
yield from line.spans
@@ -1875,7 +1916,9 @@ def _render_progressive_markdown(
add_markers: bool,
target: ContentCursor | None = None,
context: int = 0,
- img_bucket_path: str = "",
+ data_dir: str = "",
+ sha256: str = "",
+ page_count: int | None = None,
) -> _RenderedContent:
output: list[str] = []
ranges: list[ContentRange] = []
@@ -1888,7 +1931,13 @@ def _render_progressive_markdown(
page_no = page.page_idx + 1
if after and page_no < after.page_no:
continue
- page_blocks = _page_markdown_blocks(page, img_bucket_path=img_bucket_path)
+ page_blocks = _page_markdown_blocks(
+ page,
+ data_dir=data_dir,
+ sha256=sha256,
+ short_id=short_id,
+ tier=tier,
+ )
if target and target.block_no is not None and page_no == target.page_no:
start_block_no = max(1, target.block_no - context)
end_block_no = target.block_no + context
@@ -1960,12 +2009,12 @@ def _render_progressive_markdown(
started = True
empty_page_selected = True
if add_markers:
- page_output.append(f"<!-- page {page_no} -->")
+ page_output.append(_page_marker(page_no, page_count))
if not started or (not page_output and not empty_page_selected):
continue
if add_markers:
- marker = f"<!-- page {page_no} -->"
+ marker = _page_marker(page_no, page_count)
if not page_output or page_output[0] != marker:
page_output.insert(0, marker)
if page_output:
@@ -2004,14 +2053,42 @@ def _render_progressive_markdown(
)
-def _page_markdown_blocks(page: PageInfo, *, img_bucket_path: str = "") -> list[tuple[int, str]]:
+def _page_marker(page_no: int, page_count: int | None) -> str:
+ if page_count is None:
+ return f"<!-- page {page_no} -->"
+ return f"<!-- page {page_no} of {page_count} -->"
+
+
+def _page_markdown_blocks(
+ page: PageInfo,
+ *,
+ data_dir: str = "",
+ sha256: str = "",
+ short_id: str = "",
+ tier: Tier = "high",
+) -> list[tuple[int, str]]:
backend = page._backend
result: list[tuple[int, str]] = []
+ image_renderer = _make_doclib_image_renderer(
+ data_dir=data_dir,
+ sha256=sha256,
+ short_id=short_id,
+ tier=tier,
+ page_no=page.page_idx + 1,
+ )
for block in page.para_blocks:
if backend == "office":
- rendered = office_blocks_to_markdown([block], img_bucket_path=img_bucket_path, prefer_markdown_table=True)
+ rendered = office_blocks_to_markdown(
+ [block],
+ prefer_markdown_table=True,
+ image_renderer=image_renderer,
+ )
else:
- rendered = blocks_to_markdown([block], img_bucket_path=img_bucket_path, prefer_markdown_table=True)
+ rendered = blocks_to_markdown(
+ [block],
+ prefer_markdown_table=True,
+ image_renderer=image_renderer,
+ )
text = _join_markdown([item for item in rendered if item.strip()])
if text.strip():
result.append((block.index, text))
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index 733c3999..d8c2cf3b 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -1385,7 +1385,7 @@ class ParseService:
from ...render import render_markdown
- text = truncate_head_tail(render_markdown(pages, add_markers=False))
+ text = truncate_head_tail(render_markdown(pages, add_markers=False, image_renderer=lambda _block: ""))
await self.fts.replace(
sha256=sha256,
tier=tier,
diff --git a/mineru/render/__init__.py b/mineru/render/__init__.py
index f60c1efd..df5aa296 100644
--- a/mineru/render/__init__.py
+++ b/mineru/render/__init__.py
@@ -1,8 +1,11 @@
+from .image import ImageRenderer, image_path_renderer
from .markdown_table import to_markdown_table
from .union_make import render_content_list, render_markdown, render_structured_content
__all__ = [
"to_markdown_table",
+ "ImageRenderer",
+ "image_path_renderer",
"render_content_list",
"render_markdown",
"render_structured_content",
diff --git a/mineru/render/image.py b/mineru/render/image.py
new file mode 100644
index 00000000..729d1b43
--- /dev/null
+++ b/mineru/render/image.py
@@ -0,0 +1,37 @@
+from __future__ import annotations
+
+import re
+from collections.abc import Callable
+
+from ..types import Block, BlockType, ContentType
+
+ImageRenderer = Callable[[Block], str]
+
+_VISUAL_SPAN_TYPES: dict[str, str] = {
+ BlockType.IMAGE: ContentType.IMAGE,
+ BlockType.TABLE: ContentType.TABLE,
+ BlockType.CHART: ContentType.CHART,
+ BlockType.INTERLINE_EQUATION: ContentType.INTERLINE_EQUATION,
+}
+
+
+def image_path_renderer(block: Block, *, img_bucket_path: str = "") -> str:
+ """Render the image paths belonging to one top-level visual block."""
+ span_type = _VISUAL_SPAN_TYPES.get(block.type)
+ if span_type is None:
+ return ""
+ references: list[str] = []
+ for span in block.all_spans():
+ if span.type != span_type or not span.image_path:
+ continue
+ media_path = f"{img_bucket_path}/{span.image_path}" if img_bucket_path else span.image_path
+ references.append(f"![]({media_path})")
+ return " \n".join(references)
+
+
+def strip_embedded_image_tags(content: str) -> str:
+ """Remove embedded HTML images when a custom renderer owns image output."""
+ return re.sub(r"<img\b[^>]*>", "", content, flags=re.IGNORECASE)
+
+
+__all__ = ["ImageRenderer", "image_path_renderer"]
diff --git a/mineru/render/markdown.py b/mineru/render/markdown.py
index 9c8a9b69..7936d095 100644
--- a/mineru/render/markdown.py
+++ b/mineru/render/markdown.py
@@ -1,4 +1,5 @@
from ..types import Block, BlockType, ContentType
+from .image import ImageRenderer, strip_embedded_image_tags
from .markdown_table import to_markdown_table
from .merge import merge_para_text
from .merge_visual import _build_media_path, merge_visual_para_text
@@ -11,6 +12,7 @@ def blocks_to_markdown(
formula_as_image: bool = False,
no_rich_content: bool = False,
prefer_markdown_table: bool = False,
+ image_renderer: ImageRenderer | None = None,
) -> list[str]:
para_texts: list[str] = []
for para_block in para_blocks:
@@ -21,6 +23,7 @@ def blocks_to_markdown(
formula_as_image=formula_as_image,
no_rich_content=no_rich_content,
prefer_markdown_table=prefer_markdown_table,
+ image_renderer=image_renderer,
)
if para_text := (para_text or "").strip():
para_texts.append(para_text)
@@ -34,6 +37,7 @@ def _block_to_markdown(
formula_as_image: bool = False,
no_rich_content: bool = False,
prefer_markdown_table: bool = False,
+ image_renderer: ImageRenderer | None = None,
) -> str | None:
para_type = para_block.type
if para_type == BlockType.TEXT:
@@ -58,20 +62,28 @@ def _block_to_markdown(
if not formula_as_image:
if (para_text := merge_para_text(para_block)).strip():
return para_text
+ if image_renderer is not None:
+ return image_renderer(para_block)
return _build_image_link(para_block, ContentType.INTERLINE_EQUATION, img_bucket_path)
if no_rich_content:
return None
if para_type == BlockType.IMAGE:
- return merge_visual_para_text(para_block, img_bucket_path)
+ return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)
if para_type == BlockType.TABLE:
if not table_as_image:
if prefer_markdown_table:
- return _render_table_block_as_markdown_table(para_block, img_bucket_path)
- return merge_visual_para_text(para_block, img_bucket_path)
+ return _render_table_block_as_markdown_table(
+ para_block,
+ img_bucket_path,
+ image_renderer=image_renderer,
+ )
+ return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)
+ if image_renderer is not None:
+ return image_renderer(para_block)
return _build_image_link(para_block, ContentType.TABLE, img_bucket_path)
if para_type == BlockType.CHART:
- return merge_visual_para_text(para_block, img_bucket_path)
+ return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)
return None
@@ -96,9 +108,16 @@ def _build_image_link(block: Block, target_span_type: str, img_bucket_path: str)
return None
-def _render_table_block_as_markdown_table(para_block: Block, img_bucket_path: str) -> str:
+def _render_table_block_as_markdown_table(
+ para_block: Block,
+ img_bucket_path: str,
+ image_renderer: ImageRenderer | None = None,
+) -> str:
for span in para_block.all_spans():
if span.type != ContentType.TABLE or not span.content:
continue
- return to_markdown_table(span.content)
- return merge_visual_para_text(para_block, img_bucket_path)
+ table_html = span.content
+ if image_renderer is not None:
+ table_html = strip_embedded_image_tags(table_html)
+ return to_markdown_table(table_html)
+ return merge_visual_para_text(para_block, img_bucket_path, image_renderer=image_renderer)
diff --git a/mineru/render/merge_visual.py b/mineru/render/merge_visual.py
index b0f4e3bb..cc7804a2 100644
--- a/mineru/render/merge_visual.py
+++ b/mineru/render/merge_visual.py
@@ -6,6 +6,7 @@ from html import escape, unescape
from typing import Any
from ..types import Block, BlockType, ContentType
+from .image import ImageRenderer, strip_embedded_image_tags
from .merge import inline_left, inline_right, merge_para_text
# --------------------------------------------------------------------------- #
@@ -14,12 +15,32 @@ from .merge import inline_left, inline_right, merge_para_text
# --------------------------------------------------------------------------- #
-def merge_visual_para_text(para_block: Block, img_bucket_path: str = "") -> str:
+def merge_visual_para_text(
+ para_block: Block,
+ img_bucket_path: str = "",
+ image_renderer: ImageRenderer | None = None,
+) -> str:
rendered_segments: list[tuple[str, str]] = []
+ image_reference_pending = image_renderer is not None
for block in _blocks_in_index_order(para_block.blocks):
render_block = _inherit_parent_code_render_metadata(block, para_block)
- rendered_segments.extend(_render_visual_block_segments(render_block, para_block, img_bucket_path))
+ render_image_reference = image_reference_pending and render_block.type in {
+ BlockType.IMAGE_BODY,
+ BlockType.TABLE_BODY,
+ BlockType.CHART_BODY,
+ }
+ rendered_segments.extend(
+ _render_visual_block_segments(
+ render_block,
+ para_block,
+ img_bucket_path,
+ image_renderer=image_renderer,
+ render_image_reference=render_image_reference,
+ )
+ )
+ if render_image_reference:
+ image_reference_pending = False
para_text = ""
prev_kind: str | None = None
@@ -103,8 +124,10 @@ def _build_media_path(img_bucket_path: str, image_path: str) -> str:
# -- Visual body / details ---------------------------------------------------
-def _build_visual_details_block(content: Any, summary: str) -> str:
+def _build_visual_details_block(content: Any, summary: str, *, strip_images: bool = False) -> str:
normalized = _normalize_visual_content(content)
+ if strip_images:
+ normalized = strip_embedded_image_tags(normalized)
if not normalized:
return ""
return f"<details>\n<summary>{summary}</summary>\n\n{normalized}\n</details>"
@@ -156,17 +179,19 @@ def _render_algorithm_code_html(block: Block) -> str:
content = "\n".join(rendered_lines).strip("\n")
if not content.strip():
return ""
- return (
- '<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n'
- f"{content}\n"
- "</div>"
- )
+ return f'<div class="mineru-algorithm" style="white-space: pre-wrap; font-family:monospace;">\n{content}\n</div>'
# -- Per-block-type segment rendering ----------------------------------------
-def _render_visual_block_segments(block: Block, para_block: Block, img_bucket_path: str) -> list[tuple[str, str]]:
+def _render_visual_block_segments(
+ block: Block,
+ para_block: Block,
+ img_bucket_path: str,
+ image_renderer: ImageRenderer | None,
+ render_image_reference: bool,
+) -> list[tuple[str, str]]:
# 将单个视觉子 block 渲染成一个或多个 segment。
# 文本类子块统一输出 markdown_line;
# table 的 html 输出为 html_block,供后续决定是否需要空行隔开。
@@ -199,47 +224,87 @@ def _render_visual_block_segments(block: Block, para_block: Block, img_bucket_pa
# IMAGE_BODY
if block_type == BlockType.IMAGE_BODY:
image_segments: list[tuple[str, str]] = []
+ if image_renderer is not None and render_image_reference:
+ image_reference = image_renderer(para_block)
+ if image_reference:
+ image_segments.append((image_reference, "markdown_line"))
for line in block.lines:
for span in line.spans:
if span.type != ContentType.IMAGE:
continue
- image_segments.extend(
- _build_visual_body_segments(
- image_path=span.image_path,
- content=span.content,
- img_bucket_path=img_bucket_path,
- details_summary=para_block.sub_type or "image content",
+ if image_renderer is None:
+ image_segments.extend(
+ _build_visual_body_segments(
+ image_path=span.image_path,
+ content=span.content,
+ img_bucket_path=img_bucket_path,
+ details_summary=para_block.sub_type or "image content",
+ )
)
- )
+ else:
+ details = _build_visual_details_block(
+ span.content,
+ para_block.sub_type or "image content",
+ strip_images=True,
+ )
+ if details:
+ image_segments.append((details, "details_block"))
return image_segments
# CHART_BODY
if block_type == BlockType.CHART_BODY:
chart_segments: list[tuple[str, str]] = []
+ has_content = any(
+ _normalize_visual_content(span.content)
+ for line in block.lines
+ for span in line.spans
+ if span.type == ContentType.CHART
+ )
+ if image_renderer is not None and render_image_reference and not has_content:
+ image_reference = image_renderer(para_block)
+ if image_reference:
+ chart_segments.append((image_reference, "markdown_line"))
for line in block.lines:
for span in line.spans:
if span.type != ContentType.CHART:
continue
- chart_segments.extend(
- _build_visual_body_segments(
- image_path=span.image_path,
- content=span.content,
- img_bucket_path=img_bucket_path,
- details_summary=para_block.sub_type or "chart content",
+ if image_renderer is None:
+ chart_segments.extend(
+ _build_visual_body_segments(
+ image_path=span.image_path,
+ content=span.content,
+ img_bucket_path=img_bucket_path,
+ details_summary=para_block.sub_type or "chart content",
+ )
+ )
+ else:
+ details = _build_visual_details_block(
+ span.content,
+ para_block.sub_type or "chart content",
+ strip_images=True,
)
- )
+ if details:
+ chart_segments.append((details, "details_block"))
return chart_segments
# TABLE_BODY
if block_type == BlockType.TABLE_BODY:
table_segments: list[tuple[str, str]] = []
+ has_content = any(bool(span.content) for line in block.lines for span in line.spans if span.type == ContentType.TABLE)
+ if image_renderer is not None and render_image_reference and not has_content:
+ image_reference = image_renderer(para_block)
+ if image_reference:
+ table_segments.append((image_reference, "markdown_line"))
for line in block.lines:
for span in line.spans:
if span.type != ContentType.TABLE:
continue
if span.content: # (VLM) also checks table_enable
- table_segments.append((_format_embedded_html(span.content, img_bucket_path), "html_block"))
- elif span.image_path:
+ table_html = _format_embedded_html(span.content, img_bucket_path)
+ if image_renderer is not None:
+ table_html = strip_embedded_image_tags(table_html)
+ table_segments.append((table_html, "html_block"))
+ elif image_renderer is None and span.image_path:
if media_path := _build_media_path(img_bucket_path, span.image_path):
table_segments.append((f"![]({media_path})", "markdown_line"))
return table_segments
diff --git a/mineru/render/office/output.py b/mineru/render/office/output.py
index 929615cd..5222cb1c 100644
--- a/mineru/render/office/output.py
+++ b/mineru/render/office/output.py
@@ -6,6 +6,7 @@ from collections.abc import Generator
from typing import Any
from ...types import Block, BlockType, ContentType, ContentTypeV2, Line, Span
+from ..image import ImageRenderer, strip_embedded_image_tags
from ..markdown_table import to_markdown_table
from .merge import (
_append_hyperlink_part,
@@ -361,6 +362,7 @@ def blocks_to_markdown(
img_bucket_path: str = "",
no_rich_content: bool = False,
prefer_markdown_table: bool = False,
+ image_renderer: ImageRenderer | None = None,
) -> list[str]:
page_markdown = []
for para_block in para_blocks:
@@ -368,6 +370,8 @@ def blocks_to_markdown(
para_type = para_block.type
if para_type in [BlockType.TEXT, BlockType.INTERLINE_EQUATION]:
para_text = merge_para_with_text(para_block)
+ if para_type == BlockType.INTERLINE_EQUATION and not para_text and image_renderer is not None:
+ para_text = image_renderer(para_block)
if para_type == BlockType.TEXT:
bookmark_anchor = para_block.anchor
if isinstance(bookmark_anchor, str) and bookmark_anchor.strip() and bookmark_anchor.strip().startswith("_Toc"):
@@ -387,21 +391,32 @@ def blocks_to_markdown(
elif para_type == BlockType.IMAGE:
if no_rich_content:
continue
- for span in _iter_body_spans(para_block, BlockType.IMAGE_BODY, ContentType.IMAGE):
- if span:
- para_text += f"![]({img_bucket_path}/{span.image_path})"
+ if image_renderer is not None:
+ para_text += image_renderer(para_block)
+ else:
+ for span in _iter_body_spans(para_block, BlockType.IMAGE_BODY, ContentType.IMAGE):
+ if span:
+ para_text += f"![]({img_bucket_path}/{span.image_path})"
for caption_text in _collect_caption_texts(para_block, BlockType.IMAGE_CAPTION):
para_text += " \n" + caption_text
elif para_type == BlockType.TABLE:
if no_rich_content:
continue
+ rendered_table = False
for span in _iter_body_spans(para_block, BlockType.TABLE_BODY, ContentType.TABLE):
table_html = _format_embedded_html(span.content, img_bucket_path)
+ if image_renderer is not None:
+ table_html = strip_embedded_image_tags(table_html)
+ if not table_html:
+ continue
+ rendered_table = True
if prefer_markdown_table:
para_text += f"\n{to_markdown_table(table_html)}\n"
else:
para_text += f"\n{table_html}\n"
+ if not rendered_table and image_renderer is not None:
+ para_text += image_renderer(para_block)
for caption_text in _collect_caption_texts(para_block, BlockType.TABLE_CAPTION):
para_text += " \n" + caption_text
elif para_type == BlockType.CHART:
@@ -409,7 +424,12 @@ def blocks_to_markdown(
continue
image_path, chart_content = get_body_data(para_block)
if chart_content:
- para_text += f"\n{_format_embedded_html(chart_content, img_bucket_path)}\n"
+ chart_html = _format_embedded_html(chart_content, img_bucket_path)
+ if image_renderer is not None:
+ chart_html = strip_embedded_image_tags(chart_html)
+ para_text += f"\n{chart_html}\n"
+ elif image_renderer is not None:
+ para_text += image_renderer(para_block)
elif image_path:
para_text += f"![]({_build_media_path(img_bucket_path, image_path)})"
else:
diff --git a/mineru/render/union_make.py b/mineru/render/union_make.py
index 2f1e24f8..efc89264 100644
--- a/mineru/render/union_make.py
+++ b/mineru/render/union_make.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from typing import Any, Literal
from ..types import PageInfo
+from .image import ImageRenderer
from .markdown import blocks_to_markdown
from .office.output import blocks_to_markdown as office_blocks_to_markdown
from .structured_content import block_to_structured_content, merge_adjacent_ref_text_blocks_for_content
@@ -81,6 +82,7 @@ def render_markdown(
prefer_markdown_table: bool = False,
no_rich_content: bool = False,
add_markers: bool = False,
+ image_renderer: ImageRenderer | None = None,
) -> str:
"""Render pages to a single Markdown string.
@@ -96,6 +98,7 @@ def render_markdown(
img_bucket_path=img_bucket_path,
no_rich_content=no_rich_content,
prefer_markdown_table=prefer_markdown_table,
+ image_renderer=image_renderer,
)
if add_markers:
page_num = page_info.page_idx + 1
@@ -110,6 +113,7 @@ def render_markdown(
formula_as_image=not formula_enable,
no_rich_content=no_rich_content,
prefer_markdown_table=prefer_markdown_table,
+ image_renderer=image_renderer,
)
if add_markers:
page_num = page_info.page_idx + 1
diff --git a/mineru/utils/pdf_document.py b/mineru/utils/pdf_document.py
index c453f484..d8db7d94 100644
--- a/mineru/utils/pdf_document.py
+++ b/mineru/utils/pdf_document.py
@@ -105,8 +105,37 @@ class PDFDocument:
# ------------------------------------------------------------------ #
@staticmethod
- def from_image(image_bytes: bytes) -> "PDFDocument":
- return PDFDocument(images_bytes_to_pdf_bytes(image_bytes))
+ def from_image(
+ image_bytes: bytes,
+ render_scale: float = DEFAULT_RENDER_SCALE,
+ render_max_edge: int = DEFAULT_RENDER_MAX_EDGE,
+ ) -> "PDFDocument":
+ image = Image.open(BytesIO(image_bytes))
+ # 根据 EXIF 信息自动转正(处理手机拍摄的带 Orientation 标记的图片)
+ image = ImageOps.exif_transpose(image) or image
+
+ # 只在必要时转换
+ if image.mode != "RGB":
+ image = image.convert("RGB")
+
+ render_dpi = max(1, int(round(render_scale * POINTS_PER_INCH)))
+
+ with BytesIO() as pdf_buffer:
+ # 第一张图保存为 PDF,其余追加
+ image.save(
+ pdf_buffer,
+ format="PDF",
+ resolution=render_dpi,
+ quality=95,
+ subsampling=0,
+ )
+ pdf_bytes = pdf_buffer.getvalue()
+
+ return PDFDocument(
+ pdf_bytes,
+ render_scale=render_scale,
+ render_max_edge=render_max_edge,
+ )
# ------------------------------------------------------------------ #
# Lifecycle
@@ -199,7 +228,7 @@ class PDFDocument:
return await asyncio.to_thread(self.render_pages, start, end, scale=scale)
# TODO: move
- def crop_image(self, bbox: BBox, page_idx: int, *, scale: int = 2) -> bytes:
+ def crop_image(self, bbox: BBox, page_idx: int, *, scale: float = 2) -> bytes:
image = self.render_page(page_idx, scale=scale)
crop = None
try:
@@ -354,9 +383,7 @@ def _deduplicate_near_identical_chars(chars: list[Char]) -> list[Char]:
unique_chars.append(char)
continue
- rounded_bbox = tuple(
- int(round(float(value) / NEAR_DUPLICATE_CHAR_BBOX_TOLERANCE)) for value in bbox_values
- )
+ rounded_bbox = tuple(int(round(float(value) / NEAR_DUPLICATE_CHAR_BBOX_TOLERANCE)) for value in bbox_values)
key = (
text,
*rounded_bbox,
@@ -429,7 +456,7 @@ def _get_single_char_text(char: Char) -> str:
text = str(char.get("char", ""))
if len(text) == 1:
return text
- return text[:1] or "\uFFFD"
+ return text[:1] or "\ufffd"
def _get_char_font_id(
@@ -526,28 +553,6 @@ def get_lines_from_chars(
return lines
-def images_bytes_to_pdf_bytes(image_bytes: bytes) -> bytes:
- # 载入并转换所有图像为 RGB 模式
- image = Image.open(BytesIO(image_bytes))
- # 根据 EXIF 信息自动转正(处理手机拍摄的带 Orientation 标记的图片)
- image = ImageOps.exif_transpose(image) or image
-
- # 只在必要时转换
- if image.mode != "RGB":
- image = image.convert("RGB")
-
- with BytesIO() as pdf_buffer:
- # 第一张图保存为 PDF,其余追加
- image.save(
- pdf_buffer,
- format="PDF",
- resolution=DEFAULT_RENDER_DPI,
- quality=95,
- subsampling=0,
- )
- return pdf_buffer.getvalue()
-
-
def _page_to_image(page: pdfium.PdfPage, scale: float, max_edge: int) -> PDFPageImage:
long_edge_length = max(*page.get_size())
if (long_edge_length * scale) > max_edge:
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index a213acef..6ade6f87 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -34,7 +34,14 @@ from mineru.doclib.core.db import DatabaseManager
from mineru.doclib.core.file_io import FileStat, get_file_stat
from mineru.doclib.core.fts import FTSManager
from mineru.doclib.locators import ContentCursor
-from mineru.doclib.server import DoclibServer, _LocatorParts, _ReadPlan, _locator_after
+from mineru.doclib.server import (
+ DoclibServer,
+ _find_block_by_no,
+ _LocatorParts,
+ _make_doclib_image_renderer,
+ _ReadPlan,
+ _locator_after,
+)
from mineru.doclib.services import parse_svc as parse_svc_module
from mineru.doclib.services.cleanup_svc import CleanupService
from mineru.doclib.services.config_svc import ConfigService
@@ -4238,12 +4245,11 @@ def test_locator_after_uses_resolved_tier_when_locator_tier_is_absent() -> None:
assert _locator_after(locator, "xhigh") == "doc:eeeeeee/tier:xhigh/page:1/block:2/char:8"
-def test_progressive_markdown_uses_public_image_sidecar_prefix(tmp_path: Path) -> None:
+def test_progressive_markdown_uses_readable_pdf_block_locator(tmp_path: Path) -> None:
sha256 = "e" * 64
tier = "high"
page = _image_page("figures/rendered.jpg")
_write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
- image_dir = tmp_path / "parsed" / sha256[:2] / sha256 / tier / "images"
db = _FakeDB(
parses=[
{
@@ -4255,6 +4261,7 @@ def test_progressive_markdown_uses_public_image_sidecar_prefix(tmp_path: Path) -
}
],
file_row=None,
+ doc_row={"sha256": sha256, "short_id": "eeeeeee", "file_type": "pdf", "page_count": 1},
)
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=db))
plan = _ReadPlan(
@@ -4272,8 +4279,139 @@ def test_progressive_markdown_uses_public_image_sidecar_prefix(tmp_path: Path) -
response = asyncio.run(server._execute_read_plan(plan))
- assert str(image_dir) not in response.content
- assert "![](images/figures/rendered.jpg)" in response.content
+ assert "![Image block](doc:eeeeeee/tier:high/page:1/block:1)" in response.content
+ assert "figures/rendered.jpg" not in response.content
+
+
+ ("page_count", "expected_marker"),
+ [(100, "<!-- page 5 of 100 -->"), (None, "<!-- page 5 -->")],
+)
+def test_doc_content_marker_uses_document_page_count_only(
+ tmp_path: Path,
+ page_count: int | None,
+ expected_marker: str,
+) -> None:
+ sha256 = "e" * 64
+ tier = "high"
+ page = _text_page("selected page")
+ page.page_idx = 4
+ _write_batch(tmp_path, sha256, tier, "5", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
+ db = _FakeDB(
+ parses=[{"sha256": sha256, "tier": tier, "status": "done", "page_range": "5", "done_at": 1000}],
+ file_row=None,
+ doc_row={"sha256": sha256, "short_id": "eeeeeee", "file_type": "pdf", "page_count": page_count},
+ )
+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=db))
+
+ content = asyncio.run(
+ server._render_doc_content(
+ sha256,
+ tier=tier,
+ page_range="5",
+ format="markdown",
+ no_marker=False,
+ )
+ )
+
+ assert expected_marker in content
+ assert "<!-- page 5 of 1 -->" not in content
+
+
+ ("block_type", "label"),
+ [
+ (BlockType.IMAGE, "Image block"),
+ (BlockType.TABLE, "Table block"),
+ (BlockType.CHART, "Chart block"),
+ (BlockType.INTERLINE_EQUATION, "Formula block"),
+ ],
+)
+def test_doclib_image_renderer_uses_type_label_and_canonical_locator(
+ tmp_path: Path,
+ block_type: str,
+ label: str,
+) -> None:
+ renderer = _make_doclib_image_renderer(
+ data_dir=str(tmp_path),
+ sha256="e" * 64,
+ short_id="eeeeeee",
+ tier="high",
+ page_no=2,
+ )
+ block = Block(index=3, type=block_type, bbox=(1, 2, 30, 40))
+
+ assert renderer(block) == f"![{label}](doc:eeeeeee/tier:high/page:2/block:4)"
+
+
+def test_doclib_image_renderer_rejects_non_finite_bbox(tmp_path: Path) -> None:
+ renderer = _make_doclib_image_renderer(
+ data_dir=str(tmp_path),
+ sha256="e" * 64,
+ short_id="eeeeeee",
+ tier="high",
+ page_no=1,
+ )
+ block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, float("nan"), 10))
+
+ assert renderer(block) == "![Image block]()"
+
+
+def test_find_block_by_no_ignores_conflicting_child_indexes() -> None:
+ first = Block(
+ index=0,
+ type=BlockType.IMAGE,
+ bbox=(0, 0, 5, 5),
+ blocks=[Block(index=1, type=BlockType.IMAGE_CAPTION, bbox=(1, 1, 2, 2))],
+ )
+ second = Block(index=1, type=BlockType.IMAGE, bbox=(10, 10, 20, 20))
+ page = PageInfo(page_idx=0, para_blocks=[first, second])
+
+ assert _find_block_by_no(page, 2) is second
+
+
+ ("sidecar_exists", "expected_target"),
+ [(True, "doc:eeeeeee/tier:high/page:1/block:1"), (False, "")],
+)
+def test_progressive_markdown_uses_sidecar_availability_for_bboxless_blocks(
+ tmp_path: Path,
+ sidecar_exists: bool,
+ expected_target: str,
+) -> None:
+ sha256 = "e" * 64
+ tier = "high"
+ page = _image_page("figures/rendered.jpg")
+ page._backend = "office"
+ page.para_blocks[0].bbox = (0, 0, 0, 0)
+ _write_batch(tmp_path, sha256, tier, "1", 1000, ParseResult([page]).to_dict(skip_defaults=True)["pages"])
+ if sidecar_exists:
+ sidecar = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier)) / "figures/rendered.jpg"
+ sidecar.parent.mkdir(parents=True)
+ sidecar.write_bytes(b"image")
+ db = _FakeDB(
+ parses=[{"sha256": sha256, "tier": tier, "status": "done", "page_range": "1", "done_at": 1000}],
+ file_row=None,
+ doc_row={"sha256": sha256, "short_id": "eeeeeee", "file_type": "docx", "page_count": 1},
+ )
+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=db))
+ plan = _ReadPlan(
+ sha256=sha256,
+ short_id="eeeeeee",
+ tier=tier,
+ page_range=None,
+ after=None,
+ locator=None,
+ context=0,
+ limit=30000,
+ format="markdown",
+ no_marker=False,
+ )
+
+ response = asyncio.run(server._execute_read_plan(plan))
+
+ assert f"![Image block]({expected_target})" in response.content
+ assert "figures/rendered.jpg" not in response.content
def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
@@ -4294,7 +4432,7 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
bbox=(1, 1, 20, 20),
lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
)
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 20), blocks=[body])
+ image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 0, 0), blocks=[body])
page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
@@ -4312,14 +4450,143 @@ def test_doclib_office_image_asset_reads_cached_sidecar(tmp_path: Path) -> None:
target=ContentCursor(short_id="fffffff", tier=tier, page_no=1, block_no=1),
)
- asset = asyncio.run(server._render_office_image_asset(plan, page))
+ asset = asyncio.run(server._render_image_response(plan, [page])).asset
+ assert asset is not None
assert asset.mime_type == "image/png"
assert Path(asset.path).suffix == ".png"
with Image.open(asset.path) as image:
assert image.format == "PNG"
+ ("block_type", "body_type", "content_type"),
+ [
+ (BlockType.TABLE, BlockType.TABLE_BODY, ContentType.TABLE),
+ (BlockType.CHART, BlockType.CHART_BODY, ContentType.CHART),
+ (BlockType.INTERLINE_EQUATION, None, ContentType.INTERLINE_EQUATION),
+ ],
+)
+def test_doclib_visual_block_asset_reads_cached_sidecar(
+ tmp_path: Path,
+ block_type: str,
+ body_type: str | None,
+ content_type: str,
+) -> None:
+ sha256 = "f" * 64
+ tier = "high"
+ image_path = f"figures/{block_type}.png"
+ sidecar = Path(parse_image_sidecar_dir(str(tmp_path), sha256, tier)) / image_path
+ sidecar.parent.mkdir(parents=True)
+ sidecar.write_bytes(
+ base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
+ )
+ span = Span(type=content_type, bbox=(0, 0, 0, 0), image_path=image_path)
+ line = Line(bbox=(0, 0, 0, 0), spans=[span])
+ if body_type is None:
+ visual_block = Block(index=0, type=block_type, bbox=(0, 0, 0, 0), lines=[line])
+ else:
+ body = Block(index=0, type=body_type, bbox=(0, 0, 0, 0), lines=[line])
+ visual_block = Block(index=0, type=block_type, bbox=(0, 0, 0, 0), blocks=[body])
+ page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[visual_block], _backend="office")
+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
+ plan = _ReadPlan(
+ sha256=sha256,
+ short_id="fffffff",
+ tier=tier,
+ page_range=None,
+ after=None,
+ locator="doc:fffffff/tier:high/page:1/block:1",
+ context=0,
+ limit=30000,
+ format="image",
+ no_marker=False,
+ image_format="png",
+ target=ContentCursor(short_id="fffffff", tier=tier, page_no=1, block_no=1),
+ )
+
+ asset = asyncio.run(server._render_image_response(plan, [page])).asset
+
+ assert asset is not None
+ assert asset.mime_type == "image/png"
+ with Image.open(asset.path) as image:
+ assert image.format == "PNG"
+
+
+def test_doclib_pdf_block_locator_crops_source_pdf(tmp_path: Path) -> None:
+ sha256 = "a" * 64
+ tier = "high"
+ source_path = tmp_path / "source.pdf"
+ Image.new("RGB", (100, 100), color="white").save(source_path, "PDF")
+ page = _image_page("internal/not-persisted.png")
+ db = _FakeDB(
+ parses=[],
+ file_row={"path": str(source_path), "ext": "pdf", "sha256": sha256, "status": "active"},
+ doc_row={"sha256": sha256, "short_id": "aaaaaaa", "file_type": "pdf", "page_count": 1},
+ )
+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=db))
+ plan = _ReadPlan(
+ sha256=sha256,
+ short_id="aaaaaaa",
+ tier=tier,
+ page_range=None,
+ after=None,
+ locator="doc:aaaaaaa/tier:high/page:1/block:1",
+ context=0,
+ limit=30000,
+ format="image",
+ no_marker=False,
+ image_format="png",
+ target=ContentCursor(short_id="aaaaaaa", tier=tier, page_no=1, block_no=1),
+ )
+
+ asset = asyncio.run(server._render_image_response(plan, [page])).asset
+
+ assert asset is not None
+ assert asset.mime_type == "image/png"
+ with Image.open(asset.path) as image:
+ assert image.format == "PNG"
+ assert image.width > 0
+ assert image.height > 0
+
+
+def test_doclib_image_block_locator_crops_source_image_at_original_resolution(tmp_path: Path) -> None:
+ sha256 = "b" * 64
+ tier = "high"
+ source_path = tmp_path / "source.png"
+ Image.new("RGB", (1000, 500), color="white").save(source_path)
+ page = _image_page("internal/not-persisted.png")
+ page.page_size = (360, 180)
+ page.para_blocks[0].bbox = (0, 0, 360, 180)
+ db = _FakeDB(
+ parses=[],
+ file_row={"path": str(source_path), "ext": "png", "sha256": sha256, "status": "active"},
+ doc_row={"sha256": sha256, "short_id": "bbbbbbb", "file_type": "image", "page_count": 1},
+ )
+ server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=db))
+ plan = _ReadPlan(
+ sha256=sha256,
+ short_id="bbbbbbb",
+ tier=tier,
+ page_range=None,
+ after=None,
+ locator="doc:bbbbbbb/tier:high/page:1/block:1",
+ context=0,
+ limit=30000,
+ format="image",
+ no_marker=False,
+ image_format="png",
+ target=ContentCursor(short_id="bbbbbbb", tier=tier, page_no=1, block_no=1),
+ )
+
+ asset = asyncio.run(server._render_image_response(plan, [page])).asset
+
+ assert asset is not None
+ assert asset.mime_type == "image/png"
+ with Image.open(asset.path) as image:
+ assert image.size == (1000, 500)
+
+
def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path) -> None:
sha256 = "f" * 64
tier = "high"
@@ -4338,7 +4605,7 @@ def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path
bbox=(1, 1, 20, 20),
lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
)
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 20), blocks=[body])
+ image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 0, 0), blocks=[body])
page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
@@ -4356,8 +4623,9 @@ def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path
target=ContentCursor(short_id="fffffff", tier=tier, page_no=1, block_no=1),
)
- asset = asyncio.run(server._render_office_image_asset(plan, page))
+ asset = asyncio.run(server._render_image_response(plan, [page])).asset
+ assert asset is not None
assert asset.mime_type == "image/jpeg"
assert Path(asset.path).suffix == ".jpg"
with Image.open(asset.path) as image:
@@ -4375,7 +4643,7 @@ def test_doclib_office_image_asset_missing_sidecar_reports_asset_not_available(t
bbox=(1, 1, 20, 20),
lines=[Line(bbox=(1, 1, 20, 20), spans=[image_span])],
)
- image_block = Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 20), blocks=[body])
+ image_block = Block(index=0, type=BlockType.IMAGE, bbox=(0, 0, 0, 0), blocks=[body])
page = PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[image_block], _backend="office")
server = DoclibServer(SimpleNamespace(data_dir=str(tmp_path), db=None))
plan = _ReadPlan(
@@ -4394,7 +4662,7 @@ def test_doclib_office_image_asset_missing_sidecar_reports_asset_not_available(t
)
with pytest.raises(NotFoundError) as exc_info:
- asyncio.run(server._render_office_image_asset(plan, page))
+ asyncio.run(server._render_image_response(plan, [page]))
assert exc_info.value.code == "asset_not_available"
assert exc_info.value.param == "locator"
diff --git a/tests/unittest/test_doclib_progressive_reading.py b/tests/unittest/test_doclib_progressive_reading.py
index 01bc321e..88bf8559 100644
--- a/tests/unittest/test_doclib_progressive_reading.py
+++ b/tests/unittest/test_doclib_progressive_reading.py
@@ -1,6 +1,11 @@
import pytest
-from mineru.doclib.server import _next_content_request, _normalize_content_page_range, _page_markdown_blocks, _render_progressive_markdown
+from mineru.doclib.server import (
+ _next_content_request,
+ _normalize_content_page_range,
+ _page_markdown_blocks,
+ _render_progressive_markdown,
+)
from mineru.doclib.types import ContentRange
from mineru.errors import InvalidRequestError
from mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span
@@ -174,7 +179,14 @@ def test_paginated_next_request_is_never_after_only() -> None:
assert next_request.after is not None
-def test_paginated_empty_page_renders_page_marker_and_content_range() -> None:
+ ("page_count", "expected_marker"),
+ [(None, "<!-- page 1 -->"), (38, "<!-- page 1 of 38 -->")],
+)
+def test_paginated_empty_page_renders_page_marker_and_content_range(
+ page_count: int | None,
+ expected_marker: str,
+) -> None:
rendered = _render_progressive_markdown(
[PageInfo(page_idx=0, page_size=(100, 100), para_blocks=[], _backend="flash")],
short_id="ab12cd3",
@@ -182,9 +194,10 @@ def test_paginated_empty_page_renders_page_marker_and_content_range() -> None:
after=None,
limit=30000,
add_markers=True,
+ page_count=page_count,
)
- assert rendered.content == "<!-- page 1 -->"
+ assert rendered.content == expected_marker
assert rendered.content_ranges == [
ContentRange(page_range="1", start="doc:ab12cd3/tier:flash/page:1", end="doc:ab12cd3/tier:flash/page:1")
]
diff --git a/tests/unittest/test_render_image_renderer.py b/tests/unittest/test_render_image_renderer.py
new file mode 100644
index 00000000..6cff316c
--- /dev/null
+++ b/tests/unittest/test_render_image_renderer.py
@@ -0,0 +1,152 @@
+from __future__ import annotations
+
+import pytest
+
+from mineru.render.image import image_path_renderer
+from mineru.render.markdown import blocks_to_markdown
+from mineru.render.office.output import blocks_to_markdown as office_blocks_to_markdown
+from mineru.types import Block, BlockType, ContentType, Line, Span
+
+
+def _image_block(*, image_path: str = "internal/hash.jpg") -> Block:
+ body = Block(
+ index=0,
+ type=BlockType.IMAGE_BODY,
+ bbox=(1, 1, 20, 20),
+ lines=[
+ Line(
+ bbox=(1, 1, 20, 20),
+ spans=[Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)],
+ )
+ ],
+ )
+ caption = Block(
+ index=1,
+ type=BlockType.IMAGE_CAPTION,
+ bbox=(1, 21, 20, 25),
+ lines=[
+ Line(
+ bbox=(1, 21, 20, 25),
+ spans=[Span(type=ContentType.TEXT, bbox=(1, 21, 20, 25), content="Figure caption")],
+ )
+ ],
+ )
+ return Block(index=0, type=BlockType.IMAGE, bbox=(1, 1, 20, 25), blocks=[body, caption])
+
+
+def test_image_path_renderer_preserves_existing_relative_path_behavior() -> None:
+ block = _image_block()
+
+ assert image_path_renderer(block, img_bucket_path="images") == "![](images/internal/hash.jpg)"
+
+
+def test_pipeline_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:
+ block = _image_block()
+
+ rendered = blocks_to_markdown(
+ [block],
+ image_renderer=lambda _block: "![Image block](doc:aaaaaaa/tier:high/page:1/block:1)",
+ )
+
+ assert len(rendered) == 1
+ assert "![Image block](doc:aaaaaaa/tier:high/page:1/block:1)" in rendered[0]
+ assert "Figure caption" in rendered[0]
+ assert "internal/hash.jpg" not in rendered[0]
+
+
+def test_office_markdown_uses_custom_block_image_renderer_and_keeps_caption() -> None:
+ block = _image_block()
+
+ rendered = office_blocks_to_markdown(
+ [block],
+ image_renderer=lambda _block: "![Image block]()",
+ )
+
+ assert len(rendered) == 1
+ assert "![Image block]()" in rendered[0]
+ assert "Figure caption" in rendered[0]
+ assert "internal/hash.jpg" not in rendered[0]
+
+
+ ("block_type", "body_type", "span_type"),
+ [
+ (BlockType.TABLE, BlockType.TABLE_BODY, ContentType.TABLE),
+ (BlockType.CHART, BlockType.CHART_BODY, ContentType.CHART),
+ ],
+)
+def test_pipeline_markdown_uses_custom_renderer_for_image_only_visual_blocks(
+ block_type: str,
+ body_type: str,
+ span_type: str,
+) -> None:
+ body = Block(
+ index=0,
+ type=body_type,
+ bbox=(1, 1, 20, 20),
+ lines=[
+ Line(
+ bbox=(1, 1, 20, 20),
+ spans=[Span(type=span_type, bbox=(1, 1, 20, 20), image_path="internal/hash.jpg")],
+ )
+ ],
+ )
+ block = Block(index=0, type=block_type, bbox=(1, 1, 20, 20), blocks=[body])
+
+ rendered = blocks_to_markdown([block], image_renderer=lambda _block: "![Visual block](doc:locator)")
+
+ assert rendered == ["![Visual block](doc:locator)"]
+
+
+def test_pipeline_markdown_uses_custom_renderer_for_image_only_formula() -> None:
+ block = Block(
+ index=0,
+ type=BlockType.INTERLINE_EQUATION,
+ bbox=(1, 1, 20, 20),
+ lines=[
+ Line(
+ bbox=(1, 1, 20, 20),
+ spans=[
+ Span(
+ type=ContentType.INTERLINE_EQUATION,
+ bbox=(1, 1, 20, 20),
+ image_path="internal/hash.jpg",
+ )
+ ],
+ )
+ ],
+ )
+
+ rendered = blocks_to_markdown([block], image_renderer=lambda _block: "![Formula block](doc:locator)")
+
+ assert rendered == ["![Formula block](doc:locator)"]
+
+
[email protected]("backend", ["pipeline", "office"])
+def test_custom_renderer_removes_internal_images_from_structured_table_html(backend: str) -> None:
+ internal_path = "internal/cell-image.png"
+ html = f'<table><tr><td>Text<img src="{internal_path}"></td></tr></table>'
+ body = Block(
+ index=0,
+ type=BlockType.TABLE_BODY,
+ bbox=(1, 1, 20, 20),
+ lines=[
+ Line(
+ bbox=(1, 1, 20, 20),
+ spans=[Span(type=ContentType.TABLE, bbox=(1, 1, 20, 20), content=html)],
+ )
+ ],
+ )
+ block = Block(index=0, type=BlockType.TABLE, bbox=(1, 1, 20, 20), blocks=[body])
+ renderer = office_blocks_to_markdown if backend == "office" else blocks_to_markdown
+
+ rendered = renderer(
+ [block],
+ prefer_markdown_table=True,
+ image_renderer=lambda _block: "![Table block](doc:locator)",
+ )
+
+ assert len(rendered) == 1
+ assert "Text" in rendered[0]
+ assert internal_path not in rendered[0]
+ assert "<img" not in rendered[0]