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 tier selection for Flash-only formats and update related UI behavior
myhloli814275ab9db1
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.mdindex cd2e3984..355ca34c 100644--- a/docs/next/cli/mineru-kit-gradio.md+++ b/docs/next/cli/mineru-kit-gradio.md@@ -55,7 +55,11 @@ mineru-kit gradio \界面一次提交一个文件,支持 `filetypes.PARSEABLE_EXTENSIONS` 中的 PDF、图片、Office/ODF、RTF、HTML、CSV/TSV、EPUB 和 OFD。-解析 tier 使用原生离散滑块选择,上方即时显示当前档位。滑块按 `flash → basic → standard → advanced` 排列,仅包含服务实际支持的档位。默认优先选择 `standard`,否则选择最高可用档位;仅有一个档位时禁用滑块。上传新文件或清除结果会保留当前选择。+解析 tier 使用原生离散滑块选择,上方即时显示当前档位。滑块按 `flash → basic → standard → advanced` 排列,仅包含服务实际支持的档位。默认优先选择 `standard`,否则选择最高可用档位;仅有一个档位时禁用滑块。++上传 Office/ODF、RTF、HTML、CSV/TSV、EPUB、OFD 时,tier 自动切到 `flash` 并锁定滑块。界面记住本会话最后一次未锁定的档位,连续更换这类文件不会覆盖记忆;切回 PDF/图片或清除文件时恢复此前选择。PDF/图片之间切换继续保留当前档位。锁定与恢复同时更新档位标签、页码控件和转换按钮,无需向 Python 发送滑块拖动请求。++如果服务未提供 Flash,上传上述格式会禁用滑块和转换按钮,并提示“该格式仅支持 Flash,当前服务不可用”,不增加服务未声明的档位。转换事件仍校验 `tier_position` 的合法性;合法位置对这类文件始终使用 `flash`,服务缺少 Flash 时返回 `tier_unavailable`,不提交解析请求。上传原始 PDF 时,tier 下方显示“强制 OCR”开关,所有档位(包括 Flash)均可使用。默认关闭,提交 `ocr_mode:"auto"` 自动判断;开启时提交 `ocr_mode:"ocr"`,忽略 PDF 文本层并进行 OCR。更换或清除文件会重置开关,同一文件切换 tier 保留选择。图片与其他格式隐藏开关,提交时固定使用 `auto`。diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.pyindex 4c34b588..e275fcaf 100644--- a/mineru/kit/gradio/app.py+++ b/mineru/kit/gradio/app.py@@ -14,7 +14,7 @@ from typing import Any, Literalfrom urllib.parse import quotefrom ...errors import MineruError-from ...filetypes import IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PARSEABLE_EXTENSIONS, PDF_EXTENSIONS+from ...filetypes import FLASH_ONLY_PARSE_EXTENSIONS, IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PARSEABLE_EXTENSIONS, PDF_EXTENSIONSfrom ...types import TIERS, Tierfrom ...utils.stdio import configure_standard_streamsfrom .artifacts import RunArtifacts, markdown_for_gradio, persist_parse_result, render_download@@ -270,6 +270,8 @@ def build_gradio_app(show_label=False,elem_classes=["mineru-tier-slider"],)+ # 独立保存会话的未锁定档位,不随文件和页码选区一起重置。+ tier_selection = gr.Textbox(value=json.dumps({"tier": preferred_tier, "locked": False}), visible=False)force_ocr = gr.Checkbox(value=False,label="强制 OCR",@@ -486,18 +488,6 @@ def build_gradio_app(cancel_session_conversion.__annotations__["request"] = gr.Request# 显式注册加载事件,确保两个主版本都会执行前端初始化函数而不只加载其文本。demo.load(fn=None, js=app_js, **private_event_kwargs)- tier.input(- fn=None,- inputs=tier,- outputs=tier_label,- js="""(position) => {- // 在浏览器端即时显示当前档位;实际解析独立读取滑块位置。- const tiers = %s;- return ["解析 tier:" + tiers[position]];- }"""- % json.dumps(tier_choices),- **private_event_kwargs,- )preview_outputs = [pdf_preview,image_preview,@@ -512,7 +502,7 @@ def build_gradio_app(]# 文件页数只在上传后读取;前端缓存元数据,tier 切换和拖动不发起 Python 请求。- range_inputs = [input_file, tier, page_metadata, page_selection, page_handle_a, page_handle_b]+ range_inputs = [input_file, tier, page_metadata, page_selection, page_handle_a, page_handle_b, tier_selection]range_outputs = [page_handle_a,page_handle_b,@@ -521,6 +511,9 @@ def build_gradio_app(page_selection,convert_button,page_notice,+ tier,+ tier_label,+ tier_selection,]range_script = _resource_text("gradio_page_range.js")# 共用一个 always_last 事件流,避免文件、元数据、清除与拖动的并行回调互相覆盖。@@ -529,7 +522,10 @@ def build_gradio_app(fn=None,inputs=range_inputs,outputs=range_outputs,- js=f"(...args) => ({range_script})({json.dumps(tier_choices)}, {json.dumps(max_pages)}, ...args)",+ js=(+ f"(...args) => ({range_script})({json.dumps(tier_choices)}, "+ f"{json.dumps(sorted(FLASH_ONLY_PARSE_EXTENSIONS))}, {json.dumps(max_pages)}, ...args)"+ ),trigger_mode="always_last",**private_event_kwargs,)@@ -583,6 +579,13 @@ def build_gradio_app(except ValueError as exc:yield (_status_html(f"Failed: {exc}"), "", "", "", *empty_result[4:])return+ if suffix in FLASH_ONLY_PARSE_EXTENSIONS:+ # 提交端独立约束有效档位,避免事件 API 或前端残留值绕过 Flash 锁定。+ if "flash" not in tier_choices:+ message = "Failed: tier_unavailable: 该格式仅支持 Flash,当前服务不可用"+ yield (_status_html(message), "", "", "", *empty_result[4:])+ return+ selected_tier = "flash"try:page_text = await asyncio.to_thread(_effective_page_range, source_path, raw_page_range, tier=selected_tier, max_pages=max_pagesdiff --git a/mineru/resources/gradio_page_range.js b/mineru/resources/gradio_page_range.jsindex c8242e80..4d5de67a 100644--- a/mineru/resources/gradio_page_range.js+++ b/mineru/resources/gradio_page_range.js@@ -1,8 +1,9 @@-(tiers, maxPages, file, position, metadata, previous, handleAValue, handleBValue) => {+(tiers, flashOnlyExtensions, maxPages, file, position, metadata, previous, handleAValue, handleBValue, tierSelection) => {// 纯前端状态转换:经原生组件事件读写值,不逐次向 Python 发送拖动请求。// 内部元数据使用 JSON 文本,避免不同 Gradio 版本的 JSON 组件封装差异。metadata = JSON.parse(metadata || "{}");previous = JSON.parse(previous || "{}");+ tierSelection = JSON.parse(tierSelection);// 统一构造原生组件的局部更新,未指定属性保持不变。const update = (props = {}) => ({ __type__: "update", ...props });// 页数读取错误只作为普通文本显示,禁止把异常内容解释为 HTML。@@ -10,8 +11,16 @@"&": "&", "<": "<", ">": ">", '"': """, "'": "'",})[char]);const path = (typeof file === "string" ? file : file?.path) || "";+ const flashOnly = flashOnlyExtensions.some((extension) => path.toLowerCase().endsWith(`.${extension}`));+ const flashPosition = tiers.indexOf("flash");+ const flashUnavailable = flashOnly && flashPosition < 0;+ // 只记住未锁定时的用户选择;文件切换和晚到元数据不能把临时 Flash 写回偏好。+ if (!tierSelection.locked) tierSelection.tier = tiers[position];+ const effectivePosition = flashOnly && !flashUnavailable ? flashPosition : tiers.indexOf(tierSelection.tier);+ const selectedTier = flashOnly ? "flash" : tiers[effectivePosition];+ tierSelection.locked = flashOnly;const isPdf = path.toLowerCase().endsWith(".pdf");- const needsRange = isPdf && tiers[position] !== "flash";+ const needsRange = isPdf && selectedTier !== "flash";const fileChanged = previous?.path !== path;const state = !fileChanged ? { ...previous } : {path, page_count: 0, handle_a: 1, handle_b: 1, start_handle: "a", error: "",@@ -62,7 +71,8 @@+ `<span class="mineru-page-selection">[${start}-${end}] · ${selected} 页</span>`+ `<span>结束页 <strong>${end}</strong></span></div>`+ `<div class="mineru-page-axis"><span>1</span><span>${limitText}</span><span>${count}</span></div>`;- const notice = needsRange && !count ? (state.error || "正在读取 PDF 页数…") : "";+ const notice = flashUnavailable ? "该格式仅支持 Flash,当前服务不可用"+ : needsRange && !count ? (state.error || "正在读取 PDF 页数…") : "";const range = visible ? (start === end ? String(start) : `${start}-${end}`) : "";// 两个端点始终保留完整文档跨度,不能把轨道范围截短为页数上限。const slider = (value, label) => update({ minimum: 1, maximum: Math.max(1, count), value, interactive, label });@@ -70,7 +80,11 @@slider(state.handle_a, state.start_handle === "a" ? "起始页" : "结束页"),slider(state.handle_b, state.start_handle === "b" ? "起始页" : "结束页"),summary, range, JSON.stringify(state),- update({ interactive: Boolean(path) && (!needsRange || count > 0) }),+ update({ interactive: Boolean(path) && !flashUnavailable && (!needsRange || count > 0) }),update({ value: escapeHtml(notice), visible: Boolean(notice) }),+ // 同一事件同时更新值、标签和页码,程序赋值无需再触发 tier.input。+ update({ value: effectivePosition, interactive: !flashOnly && tiers.length > 1 }),+ `解析 tier:${selectedTier}${flashUnavailable ? "(当前服务不可用)" : ""}`,+ JSON.stringify(tierSelection),];}diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.pyindex 023456a4..927dc2e9 100644--- a/tests/unittest/test_kit_gradio.py+++ b/tests/unittest/test_kit_gradio.py@@ -18,7 +18,7 @@ from PIL import Image, ImageStatfrom pypdf import PdfReader, PdfWriterfrom reportlab.pdfgen import canvas-from mineru.filetypes import PARSEABLE_EXTENSIONS+from mineru.filetypes import FLASH_ONLY_PARSE_EXTENSIONS, IMAGE_EXTENSIONS, PARSEABLE_EXTENSIONSfrom mineru.kit.commands import gradio as gradio_commandfrom mineru.kit.gradio import app as gradio_appfrom mineru.kit.gradio import client as gradio_client@@ -910,10 +910,18 @@ def test_gradio_tier_slider_uses_available_tiers_and_preserves_selection(assert slider.interactive is (len(tiers) > 1)assert label.value == f"解析 tier:{default_tier}"assert not any(block.__class__.__name__ == "Dropdown" for block in demo.blocks.values())- label_event = next(event for event in demo.config["dependencies"] if event["targets"] == [(slider._id, "input")])+ label_events = [event for event in demo.config["dependencies"] if (slider._id, "input") in event["targets"]]+ assert len(label_events) == 1+ label_event = label_events[0]assert label_event["backend_fn"] is Falseassert label_event["queue"] is False- assert label_event["outputs"] == [label._id]+ assert label_event["trigger_mode"] == "always_last"+ assert label_event["outputs"][7:9] == [slider._id, label._id]+ preference = demo.blocks[label_event["outputs"][9]]+ assert preference.visible is False+ assert json.loads(preference.value) == {"tier": default_tier, "locked": False}+ assert preference._id in label_event["inputs"]+ assert json.dumps(sorted(FLASH_ONLY_PARSE_EXTENSIONS)) in label_event["js"]for fn in demo.fns.values():if fn.name in {"update_file_preview", "reset_ui"}:assert slider not in fn.outputs and label not in fn.outputs@@ -922,6 +930,51 @@ def test_gradio_tier_slider_uses_available_tiers_and_preserves_selection(assert slider.api_info()["type"] == "integer"[email protected]("extension", sorted(FLASH_ONLY_PARSE_EXTENSIONS | IMAGE_EXTENSIONS))[email protected]("uppercase", [False, True])+def test_gradio_conversion_enforces_file_type_tier(tmp_path: Path, extension: str, uppercase: bool) -> None:+ """高档位残留值对所有轻量格式固定为 Flash,图片则保留用户选择,后缀不区分大小写。"""+ source = tmp_path / f"source.{extension.upper() if uppercase else extension}"+ source.write_bytes(b"placeholder")+ client = SimpleNamespace(parse_file=AsyncMock(side_effect=V1ArtifactError("stop after request")))+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("standard", "flash"), ("zip",), ("file_id",))+ demo = build_gradio_app(client, capabilities, output_root=tmp_path / "output", enable_example=False)+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")++ async def convert() -> None:+ """模拟直接调用事件,并携带不应影响非 PDF 的选页与 OCR 残留值。"""+ updates = [update async for update in handler(str(source), 1, "bad range", True)]+ assert "stop after request" in updates[-1][0]++ asyncio.run(convert())+ client.parse_file.assert_awaited_once()+ kwargs = client.parse_file.call_args.kwargs+ assert kwargs["tier"] == ("flash" if extension in FLASH_ONLY_PARSE_EXTENSIONS else "standard")+ assert kwargs["page_range"] == "" and kwargs["ocr_mode"] == "auto"++[email protected]("tiers", [("standard",), ("advanced", "basic"), ("basic", "standard", "advanced")])+def test_gradio_flash_only_input_requires_available_flash(tmp_path: Path, tiers: tuple[str, ...]) -> None:+ """服务缺少 Flash 时在事件入口报错,不发起解析请求,也不保留旧下载。"""+ source = tmp_path / "source.csv"+ source.write_text("name,value\na,1\n", encoding="utf-8")+ client = SimpleNamespace(parse_file=AsyncMock())+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", tiers, ("zip",), ("file_id",))+ demo = build_gradio_app(client, capabilities, output_root=tmp_path / "output", enable_example=False)+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")++ async def convert() -> list[tuple[Any, ...]]:+ """收集合法位置的错误响应,验证不是滑杆越界触发的拒绝。"""+ return [update async for update in handler(str(source), 0, "")]++ updates = asyncio.run(convert())+ assert "tier_unavailable" in updates[-1][0]+ assert "该格式仅支持 Flash,当前服务不可用" in updates[-1][0]+ assert updates[-1][8] is None+ assert all(item["interactive"] is False and item["value"] is None for item in updates[-1][-6:])+ client.parse_file.assert_not_called()++@pytest.mark.parametrize(("tiers", "position", "expected_tier"),[diff --git a/tests/unittest/test_kit_gradio_page_range.cjs b/tests/unittest/test_kit_gradio_page_range.cjsindex 911c42e5..ebae3ba0 100644--- a/tests/unittest/test_kit_gradio_page_range.cjs+++ b/tests/unittest/test_kit_gradio_page_range.cjs@@ -4,10 +4,17 @@ const path = require("node:path");const vm = require("node:vm");const reduce = vm.runInThisContext(fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_page_range.js"), "utf8"));const tiers = ["flash", "basic", "standard", "advanced"];+// 使用 Python 测试传入的统一格式集合,测试和产品代码均不维护另一份后缀清单。+const flashOnlyExtensions = JSON.parse(process.argv[2]);+const tieredExtensions = JSON.parse(process.argv[3]);// 模拟原生 Gradio 组件值与纯前端输出更新,不复制实际联动算法。-function createUi(limit = 20) {- const state = { file: null, position: 2, metadata: {}, previous: {}, a: 1, b: 1 };+function createUi(limit = 20, availableTiers = tiers) {+ const defaultTier = availableTiers.includes("standard") ? "standard" : availableTiers.at(-1);+ const state = {+ file: null, position: availableTiers.indexOf(defaultTier), metadata: {}, previous: {}, a: 1, b: 1,+ tierSelection: { tier: defaultTier, locked: false },+ };return {state,step(action, patch = {}) {@@ -15,12 +22,15 @@ function createUi(limit = 20) {Object.assign(state, patch);if (action === "clear") state.file = null;const result = reduce(- tiers, limit, state.file, state.position,- JSON.stringify(state.metadata), JSON.stringify(state.previous), state.a, state.b+ availableTiers, flashOnlyExtensions, limit, state.file, state.position,+ JSON.stringify(state.metadata), JSON.stringify(state.previous), state.a, state.b,+ JSON.stringify(state.tierSelection));if ("value" in result[0]) state.a = result[0].value;if ("value" in result[1]) state.b = result[1].value;if (result[4].__type__ !== "update") state.previous = JSON.parse(result[4]);+ if ("value" in result[7]) state.position = result[7].value;+ state.tierSelection = JSON.parse(result[9]);return result;},upload(count, filename = "/report.pdf") {@@ -31,6 +41,87 @@ function createUi(limit = 20) {};}+// 所有轻量格式(含大写后缀)锁定 Flash;连续上传和残留输入不能覆盖原先选择。+for (const extension of flashOnlyExtensions.flatMap((extension) => [extension, extension.toUpperCase()])) {+ const ui = createUi();+ ui.step("tier", { position: 3 });+ const out = ui.step("file", { file: { path: `/source.${extension}` } });+ assert.equal(out[7].value, 0);+ assert.equal(out[7].interactive, false);+ assert.equal(out[8], "解析 tier:flash");+ assert.equal(out[5].interactive, true);+ assert.equal(out[3], "");+ assert.match(out[2], /data-range-visible="false"/);+ assert.deepEqual(ui.state.tierSelection, { tier: "advanced", locked: true });+ // 即使模拟一个已经排队的高档位 input,也不能改变锁定值或恢复偏好。+ assert.equal(ui.step("tier", { position: 1 })[7].value, 0);+ ui.step("file", { file: `/another.${extension}` });+ assert.equal(ui.state.tierSelection.tier, "advanced");+ const cleared = ui.step("clear");+ assert.equal(cleared[7].value, 3);+ assert.equal(cleared[7].interactive, true);+ assert.equal(cleared[8], "解析 tier:advanced");+ assert.equal(cleared[5].interactive, false);+}++// 切回任意 PDF/图片后在同一次事件恢复档位,PDF 等待页数、图片可立即转换。+for (const extension of tieredExtensions.flatMap((extension) => [extension, extension.toUpperCase()])) {+ const ui = createUi();+ ui.step("file", { file: "/source.csv" });+ const out = ui.step("file", { file: { path: `/source.${extension}` } });+ assert.equal(out[7].value, 2);+ assert.equal(out[7].interactive, true);+ assert.equal(out[8], "解析 tier:standard");+ assert.equal(out[5].interactive, extension.toLowerCase() !== "pdf");+ assert.deepEqual(ui.state.tierSelection, { tier: "standard", locked: false });+}++// 缺少 Flash 不伪造滑杆位置,始终阻止提交;恢复可分档文件后沿用原先能力和选择。+for (const availableTiers of [["basic", "standard", "advanced"], ["advanced"], ["flash"], ["flash", "advanced"]]) {+ const ui = createUi(20, availableTiers);+ const originalPosition = ui.state.position;+ const available = availableTiers.includes("flash");+ const out = ui.step("file", { file: "/source.csv" });+ assert.equal(out[7].interactive, false);+ assert.equal(out[7].value, available ? availableTiers.indexOf("flash") : originalPosition);+ assert.equal(out[5].interactive, available);+ assert.equal(out[6].visible, !available);+ if (!available) {+ assert.equal(out[6].value, "该格式仅支持 Flash,当前服务不可用");+ assert.match(out[8], /flash.*当前服务不可用/);+ }+ const restored = ui.step("file", { file: "/source.png" });+ assert.equal(restored[7].value, originalPosition);+ assert.equal(restored[7].interactive, availableTiers.length > 1);+ assert.equal(restored[5].interactive, true);+ assert.equal(restored[6].visible, false);+}++// 文件连续切换与旧 PDF 元数据晚到时,锁定状态和偏好只跟随当前文件。+{+ const ui = createUi();+ ui.upload(100);+ ui.step("tier", { position: 3 });+ ui.step("file", { file: "/source.csv" });+ ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100, error: "" } });+ assert.equal(ui.state.position, 0);+ assert.equal(ui.state.tierSelection.tier, "advanced");+ let out = ui.step("file", { file: "/new.pdf" });+ assert.equal(out[7].value, 3);+ assert.equal(out[5].interactive, false);+ assert.match(out[6].value, /正在读取/);+ out = ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100, error: "" } });+ assert.equal(out[5].interactive, false);+ out = ui.step("metadata", { metadata: { path: "/new.pdf", page_count: 12, error: "" } });+ assert.equal(out[5].interactive, true);+ assert.equal(out[3], "1-12");+ ui.step("tier", { position: 1 });+ ui.step("file", { file: "/second.csv" });+ assert.equal(ui.step("clear")[7].value, 1);+ // 会话互不共享偏好。+ assert.equal(createUi().state.tierSelection.tier, "standard");+}+// 同时检查组件身份、语义角色、提交范围及无障碍标签,不能只验证排序后的数字。function assertSelection(result, a, b, startHandle) {const state = JSON.parse(result[4]);diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.pyindex e139c0ab..552ecc85 100644--- a/tests/unittest/test_kit_gradio_page_range.py+++ b/tests/unittest/test_kit_gradio_page_range.py@@ -16,6 +16,7 @@ from pypdf import PdfWriterfrom typer.testing import CliRunnerfrom mineru.errors import InvalidRequestError+from mineru.filetypes import FLASH_ONLY_PARSE_EXTENSIONS, TIERED_PARSE_EXTENSIONSfrom mineru.kit.gradio import app as gradio_appfrom mineru.kit.gradio import page_range as rangesfrom mineru.kit.gradio.client import V1ServerCapabilities@@ -238,5 +239,15 @@ def test_frontend_page_range_state_machine() -> None:node = shutil.which("node")if node is None:pytest.skip("Node.js is required for frontend state tests")- result = subprocess.run([node, str(Path(__file__).with_suffix(".cjs"))], capture_output=True, text=True, check=False)+ result = subprocess.run(+ [+ node,+ str(Path(__file__).with_suffix(".cjs")),+ json.dumps(sorted(FLASH_ONLY_PARSE_EXTENSIONS)),+ json.dumps(sorted(TIERED_PARSE_EXTENSIONS)),+ ],+ capture_output=True,+ text=True,+ check=False,+ )assert result.returncode == 0, result.stdout + result.stderr