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(pdf): add PDF CPU gap measurement tool and documentation
myhloli99a012b1463d
diff --git a/docs/next/cli/mineru-kit-webui.md b/docs/next/cli/mineru-kit-webui.mdindex ec80f116..e4f84b7a 100644--- a/docs/next/cli/mineru-kit-webui.md+++ b/docs/next/cli/mineru-kit-webui.md@@ -59,7 +59,7 @@ mineru-kit webui \| `--api-key` | Bearer API Key;省略时读取 `MINERU_API_KEY`。 || `--server-name` / `--server-port` | Gradio UI 的监听地址和端口;省略端口时自动寻找空闲端口。 || `--output-dir` | 本地 UI 产物根目录,默认 `./output`。 |-| `--max-pages` | 单次非 Flash PDF 解析的最多页数,必须为正整数;省略则不限制。不限制 Flash 或非 PDF。 |+| `--max-pages` | 单次 PDF 解析的最多页数,必须为正整数;省略则不限制。不限制非 PDF。 || `--api-server-tier` | 自动启动 server 的能力档位:`flash`、`basic`、`standard`。 || `--api-server-concurrency` | 自动启动 server 的最大并发任务数。 || `--api-server-preload-models` | 在自动启动阶段预加载模型。 |@@ -91,13 +91,13 @@ OCR 模式由每次 V1 解析任务决定;API Server 不再提供启动时的启用 Gradio 事件 API 时,转换事件的 `tier_position` 参数为从 `0` 开始的整数位置,替代原来的 tier 字符串。例如四档齐全时 `3` 对应 `advanced`;远程仅支持 `basic/standard` 时,本地补充 Flash 后 `0` 对应 `flash`,`2` 对应 `standard`。位置始终按照上述顺序对实际可用档位编号,越界位置会报错。V1 API 的 `tier` 参数仍使用字符串。-仅在已上传原始 PDF 且 tier 不是 `flash` 时显示页码双滑块。轨道范围由 `pypdfium2` 读取的实际页数确定,为 `1~n`,两端对应包含首尾页的连续选区。Flash 和其他文件格式隐藏控件,并始终全部解析。+仅在已上传原始 PDF 时显示页码双滑块,所有档位(包括 Flash)一致。轨道范围由 `pypdfium2` 读取的实际页数确定,为 `1~n`,两端对应包含首尾页的连续选区。其他文件格式隐藏控件,并始终全部解析。默认选择全部页;配置 `mineru-kit webui --max-pages 20` 后,100 页 PDF 的初始选区为 `[1-20]`,轨道仍为 `1~100`。选区最多 20 页,允许缩小;只有超限时才联动另一端。例如将右端拖到 40 得到 `[21-40]`,再把左端拖到 15 得到 `[15-34]`,随后把左端拖到 20 得到 `[20-34]`。两个滑块可以互相越过并实时交换起止角色,拖动过程中始终抓住同一个滑块,不需要松手。显示和提交的范围始终从小到大排列。例如从 `[20-35]` 把原左滑块拖到 40,得到 `[35-40]`;同一滑块继续到 60,按上限联动为 `[41-60]`;不松手退到 30,则得到 `[30-41]`。两端重合表示单页,此时保留原来的角色,直到严格越过才交换;键盘操作遵循相同规则。-更换或清除文件会重置选区与角色;同一 PDF 切换 tier 保留两个滑块的位置和角色,包括切到 Flash 后再切回。读取页数期间,非 Flash PDF 暂不可提交;文件损坏或需要密码时显示错误,不降级为全部解析。+更换或清除文件会重置选区与角色;同一 PDF 切换 tier 保留两个滑块的位置和角色,包括切到 Flash 后再切回。读取页数期间,PDF 暂不可提交;文件损坏或需要密码时显示错误,不降级为全部解析。Gradio 转换事件保留 `raw_page_range` 字符串接口,仍接受 V1 `page_range` 语法,例如 `1-5,8,r1`。未指定时按当前上限选择前若干页,无上限则全部;显式选区(包括 `all`)超限会返回 `page_range_invalid`,不会截断。提交端按真实页数复核,直接调用事件也不能绕过上限。该限制不改变通用 Python、V1 API 或 Doclib 的选页规则。diff --git a/docs/next/page-ranges.md b/docs/next/page-ranges.mdindex 4e5cd871..2a99e37d 100644--- a/docs/next/page-ranges.md+++ b/docs/next/page-ranges.md@@ -44,12 +44,11 @@ CLI 的 `--pages`、Python/Doclib/API 的 `page_range` 和 Gradio 转换事件| Python `parse` / `parse_async` | 全部 || V1 Parse Jobs / `MinerUApiParser` | 全部 || `mineru-kit parse` | 全部 |-| Gradio 非 Flash PDF | 默认全部;配置 `--max-pages M` 后选择前 M 页,不足则全部 |-| Gradio Flash | 始终全部,忽略页码参数 |+| Gradio PDF | 默认全部;配置 `--max-pages M` 后选择前 M 页,不足则全部 |显式 `all` 选择全部 PDF 页面;内容读取/导出仍受实际缓存可用性约束。非 PDF 的解析限制不变:不能显式设置页码(包括 `all`);Gradio 对非 PDF 自动清空并隐藏此控件。-Gradio 仅对已上传的非 Flash PDF 显示选页控件;配置的页数上限也适用于直接调用 Gradio 转换事件,显式超限选区报 `page_range_invalid`。+Gradio 仅对已上传的 PDF 显示选页控件,所有档位(包括 Flash)一致;配置的页数上限也适用于直接调用 Gradio 转换事件,显式超限选区报 `page_range_invalid`。## 输入与输出diff --git a/mineru/kit/commands/webui.py b/mineru/kit/commands/webui.pyindex 8f790669..31466e80 100644--- a/mineru/kit/commands/webui.py+++ b/mineru/kit/commands/webui.py@@ -67,9 +67,7 @@ def webui_cmd(None, "--server-port", help=t("Web UI bind port; omitted: auto-select from 7860 or GRADIO_SERVER_PORT")),output_dir: str = typer.Option("./output", "--output-dir", help=t("Directory for Web UI artifacts")),- max_pages: int | None = typer.Option(- None, "--max-pages", help=t("Maximum pages per non-Flash PDF conversion; omitted: unlimited")- ),+ max_pages: int | None = typer.Option(None, "--max-pages", help=t("Maximum pages per PDF conversion; omitted: unlimited")),enable_example: bool = typer.Option(True, "--enable-example/--no-enable-example", help=t("Show local examples")),enable_api: bool = typer.Option(True, "--enable-api/--no-enable-api", help=t("Expose the Gradio event API")),api_server_tier: str = typer.Option(diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex d337f78a..79460bb2 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -779,9 +779,7 @@ def build_gradio_app(returnselected_tier = "flash"try:- page_text = await asyncio.to_thread(- _effective_page_range, source_path, raw_page_range, tier=selected_tier, max_pages=max_pages- )+ page_text = await asyncio.to_thread(_effective_page_range, source_path, raw_page_range, max_pages=max_pages)except MineruError as exc:yield (_status_html(f"Failed: {exc.code}: {exc}"), *reset_result[1:])returndiff --git a/mineru/kit/gradio/page_range.py b/mineru/kit/gradio/page_range.pyindex 667bb613..75f4b783 100644--- a/mineru/kit/gradio/page_range.py+++ b/mineru/kit/gradio/page_range.py@@ -7,7 +7,6 @@ from typing import TypedDictfrom ...errors import InvalidRequestErrorfrom ...parser.page_range import count_pages_in_range, expand_page_range, normalize_page_range_input-from ...types import Tierclass PdfPageMetadata(TypedDict):@@ -63,12 +62,11 @@ def effective_page_range(path: str | Path | None,raw_page_range: str | None,*,- tier: Tier,max_pages: int | None = None,) -> str:- """按真实 PDF 页数校验 Gradio 请求,防止绕过前端提交超限范围。"""+ """按真实 PDF 页数校验 Gradio 请求,防止绕过前端提交超限范围;所有档位(含 Flash)一致。"""validate_max_pages(max_pages)- if tier == "flash" or not path or Path(path).suffix.lower() != ".pdf":+ if not path or Path(path).suffix.lower() != ".pdf":return ""normalized = normalize_page_range_input(raw_page_range)page_count = read_pdf_page_count(path)diff --git a/mineru/resources/gradio_page_range.js b/mineru/resources/gradio_page_range.jsindex f100aad2..f8bbb143 100644--- a/mineru/resources/gradio_page_range.js+++ b/mineru/resources/gradio_page_range.js@@ -21,7 +21,7 @@const selectedTier = flashOnly ? "flash" : tiers[effectivePosition];tierSelection.locked = flashOnly;const isPdf = path.toLowerCase().endsWith(".pdf");- const needsRange = isPdf && selectedTier !== "flash";+ const needsRange = isPdf;const fileChanged = previous?.path !== path;const state = !fileChanged ? { ...previous } : {path, page_count: 0, handle_a: 1, handle_b: 1, start_handle: "a", error: "",diff --git a/mineru/utils/translations.py b/mineru/utils/translations.pyindex 5f89310e..a68bc8ad 100644--- a/mineru/utils/translations.py+++ b/mineru/utils/translations.py@@ -474,7 +474,7 @@ ZH_MESSAGES: dict[str, str] = {"Web UI 绑定端口;省略时从 7860 或 GRADIO_SERVER_PORT 自动选择"),"Directory for Web UI artifacts": "Web UI 产物目录",- "Maximum pages per non-Flash PDF conversion; omitted: unlimited": "非 Flash PDF 单次转换的最大页数;省略时不限制",+ "Maximum pages per PDF conversion; omitted: unlimited": "PDF 单次转换的最大页数;省略时不限制","Show local examples": "显示本地示例","Expose the Gradio event API": "开放 Gradio 事件 API","Managed API server capability tier": "托管 API server 的能力档位",diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex a7d6dcb0..cdffbdc5 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -1007,9 +1007,8 @@ def test_gradio_file_types_page_range_and_header_follow_new_contract(tmp_path: Passert set(gradio_app._supported_file_types()) == {f".{extension}" for extension in PARSEABLE_EXTENSIONS}source = tmp_path / "report.PDF"source.write_bytes(_pdf_bytes(5))- assert gradio_app._effective_page_range(source, " 1-3,r1 ", tier="standard") == "1-3,r1"- assert gradio_app._effective_page_range(source, " 1-3,r1 ", tier="flash") == ""- assert gradio_app._effective_page_range("report.docx", "1-3", tier="standard") == ""+ assert gradio_app._effective_page_range(source, " 1-3,r1 ") == "1-3,r1"+ assert gradio_app._effective_page_range("report.docx", "1-3") == ""header = gradio_app._render_header()assert "mineru-demo-header" in headerassert "mineru-header-popover mineru-model-popover" in header@@ -1293,7 +1292,7 @@ def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(convert_handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")updates = asyncio.run(collect_updates(convert_handler))- assert client.calls == [(source.resolve(), expected_tier, "" if expected_tier == "flash" else "1")]+ assert client.calls == [(source.resolve(), expected_tier, "1")]assert len(updates[-1]) == 16assert updates[-1][7] == Path(updates[-1][6]["root"]).nameassert updates[-1][6] is not Nonediff --git a/tests/unittest/test_kit_gradio_page_range.cjs b/tests/unittest/test_kit_gradio_page_range.cjsindex 2ee01654..356d9639 100644--- a/tests/unittest/test_kit_gradio_page_range.cjs+++ b/tests/unittest/test_kit_gradio_page_range.cjs@@ -163,8 +163,9 @@ for (const [action, value, expected] of [assertSelection(ui.step("a", { a: 40 }), 40, 35, "b");assertSelection(ui.step("a", { a: 60 }), 60, 41, "b");const crossedState = { ...ui.state.previous };-assert.equal(ui.step("tier", { position: 0 })[3], "");-assert.match(ui.step("tier", { position: 0 })[2], /data-range-visible="false"/);+// Flash 同样显示滑块,选区与角色原样保留,切回高档位不重置。+assertSelection(ui.step("tier", { position: 0 }), 60, 41, "b");+assert.match(ui.step("tier", { position: 0 })[2], /data-range-visible="true"/);assert.deepEqual(ui.state.previous, crossedState);assertSelection(ui.step("tier", { position: 3 }), 60, 41, "b");assertSelection(ui.step("a", { a: 30 }), 30, 41, "a");@@ -218,15 +219,16 @@ assertSelection(ui.upload(100), 1, 1, "a");assertSelection(ui.step("a", { a: 50 }), 50, 50, "a");assertSelection(ui.step("b", { b: 10 }), 10, 10, "a");-// 文件错误只阻止非 Flash;错误消息须转义,不能成为 HTML 注入入口。+// 文件错误阻止所有档位提交;错误消息须转义,不能成为 HTML 注入入口。ui = createUi();ui.step("file", { file: { path: "/bad.pdf" } });out = ui.step("metadata", { metadata: { path: "/bad.pdf", page_count: 0, error: "<bad>" } });assert.equal(out[5].interactive, false);assert.equal(out[6].value, "<bad>");out = ui.step("tier", { position: 0 });-assert.equal(out[5].interactive, true);-assert.equal(out[6].visible, false);+assert.equal(out[5].interactive, false);+assert.equal(out[6].visible, true);+assert.equal(out[6].value, "<bad>");// 确定性遍历总页数和上限:物理值允许倒序,排序后的范围、角色与上限必须一致。for (const count of [1, 12, 20, 100]) {diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.pyindex 78742af8..4359c01b 100644--- a/tests/unittest/test_kit_gradio_page_range.py+++ b/tests/unittest/test_kit_gradio_page_range.py@@ -244,9 +244,9 @@ def test_pdf_metadata_and_default_range(tmp_path: Path, count: int) -> None:source = _pdf(tmp_path, count)assert ranges.pdf_page_metadata(str(source)) == {"path": str(source), "page_count": count, "error": ""}expected = "1" if count == 1 else f"1-{min(count, 20)}"- assert ranges.effective_page_range(source, "", tier="standard", max_pages=20) == expected- assert ranges.effective_page_range(source, "", tier="standard") == ""- assert ranges.effective_page_range(source, "all", tier="standard") == "all"+ assert ranges.effective_page_range(source, "", max_pages=20) == expected+ assert ranges.effective_page_range(source, "") == ""+ assert ranges.effective_page_range(source, "all") == "all"@pytest.mark.parametrize(@@ -255,7 +255,7 @@ def test_pdf_metadata_and_default_range(tmp_path: Path, count: int) -> None:def test_existing_range_syntax_and_unique_page_count(tmp_path: Path, raw: str, expected: str) -> None:"""保留既有语法,按求值后的去重页数限制,不按字符串跨度计数。"""source = _pdf(tmp_path)- assert ranges.effective_page_range(source, raw, tier="standard", max_pages=20) == expected+ assert ranges.effective_page_range(source, raw, max_pages=20) == expected@pytest.mark.parametrize("raw", ["all", "1-21", "r30-r1", "1-10,90-100", "999", "20-1", "~", "0"])@@ -277,14 +277,12 @@ def test_invalid_or_oversized_range_is_rejected_before_submission(tmp_path: Pathclient.parse_file.assert_not_called()- ("path", "tier"), [("missing.pdf", "flash"), ("report.docx", "standard"), ("image.png", "advanced"), (None, "basic")]-)-def test_whole_document_modes_never_read_pdf_metadata(monkeypatch: pytest.MonkeyPatch, path: str | None, tier: str) -> None:- """Flash、非 PDF 和空输入直接清空范围,不因残留的坏页码而失败。"""[email protected]("path", ["report.docx", "image.png", None])+def test_whole_document_modes_never_read_pdf_metadata(monkeypatch: pytest.MonkeyPatch, path: str | None) -> None:+ """非 PDF 和空输入直接清空范围,不因残留的坏页码而失败。"""read_count = Mock(side_effect=AssertionError("unexpected PDF access"))monkeypatch.setattr(ranges, "read_pdf_page_count", read_count)- assert ranges.effective_page_range(path, "bad range", tier=tier, max_pages=1) == "" # type: ignore[arg-type]+ assert ranges.effective_page_range(path, "bad range", max_pages=1) == ""read_count.assert_not_called()@@ -301,7 +299,7 @@ def test_unreadable_pdf_is_not_treated_as_all_pages(tmp_path: Path, kind: str) -assert metadata["page_count"] == 0assert "无法读取 PDF 页数" in metadata["error"]with pytest.raises(InvalidRequestError, match="无法读取 PDF 页数"):- ranges.effective_page_range(source, "", tier="standard", max_pages=20)+ ranges.effective_page_range(source, "", max_pages=20)@pytest.mark.parametrize("fail", [False, True])diff --git a/tests/unittest/test_pdf_page_id.py b/tests/unittest/test_pdf_page_id.pyindex bfd7509b..0f85148f 100644--- a/tests/unittest/test_pdf_page_id.py+++ b/tests/unittest/test_pdf_page_id.py@@ -86,7 +86,7 @@ def test_page_selection_contract_across_entrypoints(assert parse_page_range(raw, 10) == [page - 1 for page in page_numbers]assert expand_page_range(raw, 10) == canonicalassert _normalize_content_page_range(raw, None, {"page_count": 10}) == canonical- assert expand_page_range(_effective_page_range("demo.pdf", raw, tier="standard"), 10) == canonical+ assert expand_page_range(_effective_page_range("demo.pdf", raw), 10) == canonicalassert parse_page_range_set(canonical) == set(page_numbers)assert count_pages_in_range(canonical) == len(page_numbers)assert format_page_range(reversed(page_numbers)) == canonical@@ -100,7 +100,7 @@ def test_invalid_and_retired_syntax_is_rejected_everywhere(raw: str) -> None:lambda: parse_page_range(raw, 10),lambda: expand_page_range(raw, 10),lambda: _normalize_content_page_range(raw, None, {"page_count": 10}),- lambda: _effective_page_range("demo.pdf", raw, tier="standard"),+ lambda: _effective_page_range("demo.pdf", raw),lambda: _validate_page_range_input(raw),):with pytest.raises(MineruError) as error: