Skip to content

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

feat: implement dual slider for PDF page range selection with max page limit

myhlolif4d735c318dd
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.md
index bfbb6ba1..ccc2b7fc 100644
--- a/docs/next/cli/mineru-kit-gradio.md
+++ b/docs/next/cli/mineru-kit-gradio.md
@@ -40,6 +40,7 @@ mineru-kit gradio \
| `--api-key` | Bearer API Key;省略时读取 `MINERU_API_KEY`。 |
| `--server-name` / `--server-port` | Gradio UI 的监听地址和端口;省略端口时自动寻找空闲端口。 |
| `--output-dir` | 本地 UI 产物根目录,默认 `./output`。 |
+| `--max-pages` | 单次非 Flash PDF 解析的最多页数,必须为正整数;省略则不限制。不限制 Flash 或非 PDF。 |
| `--api-server-tier` | 自动启动 server 的能力档位:`flash`、`basic`、`standard`。 |
| `--api-server-concurrency` | 自动启动 server 的最大并发任务数。 |
| `--api-server-language` | 自动启动 server 的 OCR 语言提示。 |
@@ -59,7 +60,15 @@ mineru-kit gradio \
启用 Gradio 事件 API 时,转换事件的 `tier_position` 参数为从 `0` 开始的整数位置,替代原来的 tier 字符串。例如四档齐全时 `3` 对应 `advanced`;仅支持 `basic/standard/advanced` 时 `2` 对应 `advanced`。位置始终按照上述顺序对实际可用档位编号,越界位置会报错。V1 API 的 `tier` 参数仍使用字符串,启动参数不变。
-页码输入使用 V1 `page_range` 语法,例如 `1-5,8,r1`;留空表示全部页面。只有原始 PDF 支持显式页码范围,其他格式会自动清空并禁用页码控件。
+仅在已上传原始 PDF 且 tier 不是 `flash` 时显示页码双滑块。轨道范围由 `pypdfium2` 读取的实际页数确定,为 `1~n`,两端对应包含首尾页的连续选区。Flash 和其他文件格式隐藏控件,并始终全部解析。
+
+默认选择全部页;配置 `mineru-kit gradio --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 暂不可提交;文件损坏或需要密码时显示错误,不降级为全部解析。
+
+Gradio 转换事件保留 `raw_page_range` 字符串接口,仍接受 V1 `page_range` 语法,例如 `1-5,8,r1`。未指定时按当前上限选择前若干页,无上限则全部;显式选区(包括 `all`)超限会返回 `page_range_invalid`,不会截断。提交端按真实页数复核,直接调用事件也不能绕过上限。该限制不改变通用 Python、V1 API 或 Doclib 的选页规则。
Gradio 首先发现 `/v1/health` 和 `/v1/tiers`,然后通过 `MinerUApiParser` 上传文件、创建 `/v1/parse/jobs`、轮询任务并下载 ZIP 结果。解析结果保存为严格 Middle JSON 2.0。
diff --git a/docs/next/page-ranges.md b/docs/next/page-ranges.md
index 96f48f81..4e5cd871 100644
--- a/docs/next/page-ranges.md
+++ b/docs/next/page-ranges.md
@@ -2,7 +2,7 @@
状态: Implemented
-CLI 的 `--pages`、Python/Doclib/API 的 `page_range` 和 Gradio 页码输入使用同一套语法。
+CLI 的 `--pages`、Python/Doclib/API 的 `page_range` 和 Gradio 转换事件的页码参数使用同一套语法;Gradio 界面通过双滑块生成连续选区。
页码表示 PDF 文件内的页面顺序,从 1 开始,不使用正文印刷页码或 PDF page label。
内部 `page_idx` / `page_indices` 仍从 0 开始,抽页后保留原始页索引。
@@ -43,10 +43,13 @@ CLI 的 `--pages`、Python/Doclib/API 的 `page_range` 和 Gradio 页码输入
| Doclib 内容导出 | 导出已有缓存内容 |
| Python `parse` / `parse_async` | 全部 |
| V1 Parse Jobs / `MinerUApiParser` | 全部 |
-| `mineru-kit parse` / Gradio | 全部 |
+| `mineru-kit parse` | 全部 |
+| Gradio 非 Flash PDF | 默认全部;配置 `--max-pages M` 后选择前 M 页,不足则全部 |
+| Gradio Flash | 始终全部,忽略页码参数 |
显式 `all` 选择全部 PDF 页面;内容读取/导出仍受实际缓存可用性约束。
-非 PDF 的解析限制不变:不能显式设置页码(包括 `all`);Gradio 对非 PDF 自动清空并禁用此控件。
+非 PDF 的解析限制不变:不能显式设置页码(包括 `all`);Gradio 对非 PDF 自动清空并隐藏此控件。
+Gradio 仅对已上传的非 Flash PDF 显示选页控件;配置的页数上限也适用于直接调用 Gradio 转换事件,显式超限选区报 `page_range_invalid`。
## 输入与输出
diff --git a/mineru/kit/commands/gradio.py b/mineru/kit/commands/gradio.py
index 29db668e..ae8cb1a0 100644
--- a/mineru/kit/commands/gradio.py
+++ b/mineru/kit/commands/gradio.py
@@ -57,6 +57,9 @@ def gradio_cmd(
None, "--server-port", help="Gradio bind port; omitted: auto-select from 7860 or GRADIO_SERVER_PORT"
),
output_dir: str = typer.Option("./output", "--output-dir", help="Directory for Gradio artifacts"),
+ max_pages: int | None = typer.Option(
+ None, "--max-pages", help="Maximum pages per non-Flash PDF conversion; omitted: unlimited"
+ ),
enable_example: bool = typer.Option(True, "--enable-example/--no-enable-example", help="Show local examples"),
enable_api: bool = typer.Option(True, "--enable-api/--no-enable-api", help="Expose the Gradio event API"),
latex_delimiters_type: Literal["a", "b", "all"] = typer.Option(
@@ -86,6 +89,8 @@ def gradio_cmd(
_require_gradio_dependencies()
if server_port is not None:
_validate_server_port(server_port)
+ if max_pages is not None:
+ _validate_positive_option(max_pages, name="max_pages")
_validate_positive_option(api_server_concurrency, name="api_server_concurrency")
normalized_tier = _validate_server_tier(api_server_tier)
try:
@@ -103,6 +108,7 @@ def gradio_cmd(
server_name=server_name,
server_port=server_port,
output_dir=output_dir,
+ max_pages=max_pages,
enable_example=enable_example,
enable_api=enable_api,
latex_delimiters_type=latex_delimiters_type,
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
index 3f81cc05..dcfa6b19 100644
--- a/mineru/kit/gradio/app.py
+++ b/mineru/kit/gradio/app.py
@@ -13,7 +13,6 @@ from urllib.parse import quote
from ...errors import MineruError
from ...filetypes import IMAGE_EXTENSIONS, OFFICE_EXTENSIONS, PARSEABLE_EXTENSIONS, PDF_EXTENSIONS
-from ...parser.page_range import normalize_page_range_input
from ...types import TIERS, Tier
from ...utils.stdio import configure_standard_streams
from .artifacts import RunArtifacts, markdown_for_gradio, persist_parse_result, render_download
@@ -25,6 +24,8 @@ from .client import (
V1ArtifactClient,
V1ServerCapabilities,
)
+from .page_range import effective_page_range as _effective_page_range
+from .page_range import pdf_page_metadata, validate_max_pages
_DOWNLOAD_FORMATS: tuple[tuple[str, str], ...] = (
("zip", "ZIP"),
@@ -233,13 +234,6 @@ def _file_suffix(path_value: str | Path | None) -> str:
return Path(path_value).suffix.lower().lstrip(".")
-def _effective_page_range(path_value: str | Path | None, raw_page_range: str | None) -> str:
- """仅为 PDF 保留用户输入的 V1 page_range,其它格式统一返回空字符串。"""
- if _file_suffix(path_value) not in PDF_EXTENSIONS:
- return ""
- return normalize_page_range_input(raw_page_range)
-
-
def _is_pdf_or_image(path_value: str | Path | None) -> bool:
"""判断上传文件是否可以在 PDF 预览组件中展示。"""
suffix = _file_suffix(path_value)
@@ -278,19 +272,25 @@ def build_gradio_app(
enable_example: bool = True,
enable_api: bool = True,
latex_delimiters_type: Literal["a", "b", "all"] = "all",
+ max_pages: int | None = None,
) -> Any:
"""构建不启动监听端口的 Gradio Blocks 应用,便于单元测试和外部托管。"""
import gradio as gr
from gradio_pdf import PDF
+ validate_max_pages(max_pages)
tier_choices = [tier for tier in TIERS if tier in capabilities.tiers]
if not tier_choices:
raise ValueError("V1 API server did not advertise any parsing tier")
preferred_tier = _default_tier(capabilities)
file_types = _supported_file_types()
markdown_copy_kwargs = {"buttons": ["copy"]} if _gradio_major_version(gr) >= 6 else {"show_copy_button": True}
+ app_css = _resource_text("gradio_app.css") + _KIT_MENU_CSS
+ app_js = _resource_text("gradio_app.js")
+ # Gradio 5 在 Blocks 构造时接收静态资源,6 则在 launch 时接收。
+ blocks_kwargs = {"css": app_css, "js": app_js} if _gradio_major_version(gr) < 6 else {}
- with gr.Blocks() as demo:
+ with gr.Blocks(**blocks_kwargs) as demo:
gr.HTML(
_render_header(gradio_major_version=_gradio_major_version(gr)),
elem_classes=["mineru-header-html"],
@@ -325,12 +325,40 @@ def build_gradio_app(
page_range = gr.Textbox(
value="",
label="页码范围",
- placeholder="例如 1-5,8,r1 或 all;留空表示全部",
- interactive=False,
- elem_classes=["mineru-kit-page-range"],
+ visible=False,
)
+ # 用 JSON 文本承载内部状态,避开 Gradio 5/6 JSON 组件的序列化差异。
+ page_metadata = gr.Textbox(value="{}", visible=False)
+ page_selection = gr.Textbox(value="{}", visible=False)
+ # 布局容器在两个主版本的纯 JS 属性更新行为不同;显隐由子 HTML 的明确状态控制。
+ with gr.Column(min_width=0, elem_classes=["mineru-kit-page-range"]):
+ page_summary = gr.HTML(value="", elem_classes=["mineru-page-summary"])
+ with gr.Row(elem_classes=["mineru-page-sliders"]):
+ page_handle_a = gr.Slider(
+ minimum=1,
+ maximum=1,
+ value=1,
+ step=1,
+ precision=0,
+ label="起始页",
+ interactive=False,
+ container=False,
+ elem_classes=["mineru-page-handle-a"],
+ )
+ page_handle_b = gr.Slider(
+ minimum=1,
+ maximum=1,
+ value=1,
+ step=1,
+ precision=0,
+ label="结束页",
+ interactive=False,
+ container=False,
+ elem_classes=["mineru-page-handle-b"],
+ )
+ page_notice = gr.HTML(value="", visible=False, elem_classes=["mineru-page-notice"])
with gr.Row(elem_classes=["mineru-actions"]):
- convert_button = gr.Button("转换", variant="primary", scale=1, min_width=0)
+ convert_button = gr.Button("转换", variant="primary", scale=1, min_width=0, interactive=False)
clear_button = gr.ClearButton(value="清除", scale=1, min_width=1)
status_panel = gr.HTML(_status_html(_DEFAULT_STATUS), elem_classes=["mineru-kit-status"])
@@ -432,7 +460,6 @@ def build_gradio_app(
reset_result = (_status_html(_DEFAULT_STATUS), "", "", "", None, *_download_updates(gr, interactive=False))
if not file_path:
return (
- gr.update(value="", interactive=False),
_preview_update(gr, None, visible=False),
_preview_update(gr, None, visible=False),
_preview_update(gr, "", visible=False),
@@ -440,10 +467,8 @@ def build_gradio_app(
*reset_result,
)
suffix = _file_suffix(file_path)
- page_update = gr.update(interactive=suffix in PDF_EXTENSIONS, value="")
if suffix in PDF_EXTENSIONS:
return (
- page_update,
_preview_update(gr, file_path, visible=True),
_preview_update(gr, None, visible=False),
_preview_update(gr, "", visible=False),
@@ -452,7 +477,6 @@ def build_gradio_app(
)
if suffix in IMAGE_EXTENSIONS:
return (
- page_update,
_preview_update(gr, None, visible=False),
_preview_update(gr, file_path, visible=True),
_preview_update(gr, "", visible=False),
@@ -461,7 +485,6 @@ def build_gradio_app(
)
if _is_office(file_path):
return (
- page_update,
_preview_update(gr, None, visible=False),
_preview_update(gr, None, visible=False),
_preview_update(
@@ -473,7 +496,6 @@ def build_gradio_app(
*reset_result,
)
return (
- page_update,
_preview_update(gr, None, visible=False),
_preview_update(gr, None, visible=False),
_preview_update(gr, "", visible=False),
@@ -482,6 +504,8 @@ def build_gradio_app(
)
private_event_kwargs = _private_event_kwargs(gr)
+ # 显式注册加载事件,确保两个主版本都会执行前端初始化函数而不只加载其文本。
+ demo.load(fn=None, js=app_js, **private_event_kwargs)
tier.input(
fn=None,
inputs=tier,
@@ -498,7 +522,6 @@ def build_gradio_app(
fn=update_file_preview,
inputs=input_file,
outputs=[
- page_range,
pdf_preview,
image_preview,
office_preview,
@@ -513,6 +536,42 @@ def build_gradio_app(
**private_event_kwargs,
)
+ # 文件页数只在上传后读取;前端缓存元数据,tier 切换和拖动不发起 Python 请求。
+ range_inputs = [input_file, tier, page_metadata, page_selection, page_handle_a, page_handle_b]
+ range_outputs = [
+ page_handle_a,
+ page_handle_b,
+ page_summary,
+ page_range,
+ page_selection,
+ convert_button,
+ page_notice,
+ ]
+ range_script = _resource_text("gradio_page_range.js")
+ # 共用一个 always_last 事件流,避免文件、元数据、清除与拖动的并行回调互相覆盖。
+ gr.on(
+ triggers=[input_file.change, tier.input, page_metadata.change, page_handle_a.input, page_handle_b.input],
+ fn=None,
+ inputs=range_inputs,
+ outputs=range_outputs,
+ js=f"(...args) => ({range_script})({json.dumps(tier_choices)}, {json.dumps(max_pages)}, ...args)",
+ trigger_mode="always_last",
+ **private_event_kwargs,
+ )
+
+ def read_page_metadata(file_path: str | None) -> str:
+ """把页数元数据编码为稳定的 JSON 文本,供两个 Gradio 主版本共用。"""
+ return json.dumps(pdf_page_metadata(file_path), ensure_ascii=False)
+
+ input_file.change(
+ fn=read_page_metadata,
+ inputs=input_file,
+ outputs=page_metadata,
+ trigger_mode="always_last",
+ show_progress="hidden",
+ **private_event_kwargs,
+ )
+
async def convert_handler(
file_path: str | None,
tier_position: int | float,
@@ -549,7 +608,9 @@ def build_gradio_app(
yield (_status_html(f"Failed: {exc}"), "", "", "", *empty_result[4:])
return
try:
- page_text = _effective_page_range(source_path, raw_page_range)
+ page_text = await asyncio.to_thread(
+ _effective_page_range, source_path, raw_page_range, tier=selected_tier, max_pages=max_pages
+ )
except MineruError as exc:
yield (_status_html(f"Failed: {exc.code}: {exc}"), "", "", "", *empty_result[4:])
return
@@ -677,8 +738,9 @@ def build_gradio_app(
api_name=False,
)
- demo._mineru_kit_css = _resource_text("gradio_app.css") + _KIT_MENU_CSS
- demo._mineru_kit_js = _resource_text("gradio_app.js")
+ demo._mineru_kit_css = app_css
+ demo._mineru_kit_js = app_js
+ demo._mineru_kit_launch_kwargs = {"css": app_css, "js": app_js} if _gradio_major_version(gr) >= 6 else {}
demo.queue(default_concurrency_limit=1)
return demo
@@ -700,9 +762,11 @@ def launch_gradio(
api_server_ocr_mode: Literal["auto", "txt", "ocr"],
api_server_disable_image_analysis: bool,
api_server_preload_models: bool,
+ max_pages: int | None = None,
) -> None:
"""启动 Gradio;未指定端口时自动选择,未指定外部 URL 时托管本地 V1 API server。"""
configure_standard_streams()
+ validate_max_pages(max_pages)
resolved_api_key = api_key if api_key is not None else os.environ.get("MINERU_API_KEY")
output_root = Path(output_dir).expanduser().resolve()
output_root.mkdir(parents=True, exist_ok=True)
@@ -730,13 +794,13 @@ def launch_gradio(
enable_example=enable_example,
enable_api=enable_api,
latex_delimiters_type=latex_delimiters_type,
+ max_pages=max_pages,
)
demo.launch(
server_name=server_name,
server_port=server_port,
allowed_paths=[str(output_root)],
- css=getattr(demo, "_mineru_kit_css", None),
- js=getattr(demo, "_mineru_kit_js", None),
+ **demo._mineru_kit_launch_kwargs,
)
finally:
if managed_server is not None:
diff --git a/mineru/kit/gradio/page_range.py b/mineru/kit/gradio/page_range.py
new file mode 100644
index 00000000..62a917be
--- /dev/null
+++ b/mineru/kit/gradio/page_range.py
@@ -0,0 +1,88 @@
+"""Gradio 专用的 PDF 页数预检与单次选页限制,不改变通用解析接口。"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TypedDict
+
+from ...errors import InvalidRequestError
+from ...parser.page_range import count_pages_in_range, expand_page_range, normalize_page_range_input
+from ...types import Tier
+
+
+class PdfPageMetadata(TypedDict):
+ """只传递可序列化的文件标识、页数和错误,不保留 PDFium 对象。"""
+
+ path: str
+ page_count: int
+ error: str
+
+
+def validate_max_pages(max_pages: int | None) -> None:
+ """校验启动配置,None 表示不限制,显式值只接受正整数。"""
+ if max_pages is not None and (type(max_pages) is not int or max_pages <= 0):
+ raise ValueError("max_pages must be a positive integer or None")
+
+
+def read_pdf_page_count(path: str | Path) -> int:
+ """在共享 PDFium 锁内读取页数,并在成功或异常时及时释放文档。"""
+ import pypdfium2 as pdfium
+
+ from ...model.flash.pdf.pdfium import pdfium_guard
+
+ try:
+ with pdfium_guard():
+ document = pdfium.PdfDocument(str(path))
+ try:
+ page_count = len(document)
+ finally:
+ document.close()
+ if page_count <= 0:
+ raise ValueError("document has no available pages")
+ except Exception as exc:
+ raise InvalidRequestError(
+ "page_range_invalid",
+ "无法读取 PDF 页数,请检查文件是否损坏或需要密码。",
+ "page_range",
+ ) from exc
+ return page_count
+
+
+def pdf_page_metadata(file_path: str | None) -> PdfPageMetadata:
+ """为上传事件读取 PDF 页数;保留文件标识,供前端丢弃过期响应。"""
+ metadata: PdfPageMetadata = {"path": str(file_path or ""), "page_count": 0, "error": ""}
+ if file_path and Path(file_path).suffix.lower() == ".pdf":
+ try:
+ metadata["page_count"] = read_pdf_page_count(file_path)
+ except InvalidRequestError as exc:
+ metadata["error"] = str(exc)
+ return metadata
+
+
+def effective_page_range(
+ path: str | Path | None,
+ raw_page_range: str | None,
+ *,
+ tier: Tier,
+ max_pages: int | None = None,
+) -> str:
+ """按真实 PDF 页数校验 Gradio 请求,防止绕过前端提交超限范围。"""
+ validate_max_pages(max_pages)
+ if tier == "flash" or not path or Path(path).suffix.lower() != ".pdf":
+ return ""
+ normalized = normalize_page_range_input(raw_page_range)
+ page_count = read_pdf_page_count(path)
+ if not normalized and max_pages is not None:
+ normalized = normalize_page_range_input(f"1-{min(page_count, max_pages)}")
+ resolved = expand_page_range(normalized, page_count)
+ selected_count = count_pages_in_range(resolved)
+ if max_pages is not None and selected_count > max_pages:
+ raise InvalidRequestError(
+ "page_range_invalid",
+ f"单次最多解析 {max_pages} 页,当前选择了 {selected_count} 页。",
+ "page_range",
+ )
+ return normalized
+
+
+__all__ = ["PdfPageMetadata", "effective_page_range", "pdf_page_metadata", "read_pdf_page_count", "validate_max_pages"]
diff --git a/mineru/resources/gradio_app.css b/mineru/resources/gradio_app.css
index e7a449dc..010b38d5 100644
--- a/mineru/resources/gradio_app.css
+++ b/mineru/resources/gradio_app.css
@@ -52,6 +52,50 @@ body.dark .gradio-container {
.mineru-tier-slider .max_value {
display: none;
}
+/* 两个原生 range 共用同一条轨道;仅滑块接收指针,保留原生键盘交互。 */
+.mineru-kit-page-range {
+ display: none !important; position: relative; padding: 12px 12px 32px !important; overflow: visible !important;
+ border: 1px solid var(--mineru-panel-border); border-radius: 8px;
+}
+/* 不依赖 Gradio 布局容器的 JS visible 更新,明确状态同时适用于 5/6。 */
+.mineru-kit-page-range:has([data-range-visible="true"]) { display: flex !important; }
+.mineru-page-summary, .mineru-page-summary .html-container { padding: 0 !important; }
+.mineru-page-values, .mineru-page-axis { display: flex; justify-content: space-between; align-items: center; gap: 6px; }
+.mineru-page-values { font-size: 12px; }
+.mineru-page-selection { font-weight: 600; color: var(--mineru-accent); }
+.mineru-page-axis { position: absolute; bottom: 0; left: 0; right: 0; font-size: 12px; opacity: .7; }
+.mineru-page-summary { position: static !important; }
+.mineru-kit-page-range .mineru-page-axis { bottom: 8px; left: 12px; right: 12px; }
+.mineru-page-sliders { position: relative !important; height: 32px; min-height: 32px !important; gap: 0 !important; }
+.mineru-page-sliders::before {
+ content: ""; position: absolute; left: 8px; right: 8px; top: 14px; height: 4px; border-radius: 4px;
+ background: linear-gradient(to right,
+ var(--border-color-primary, #ddd) var(--range-start, 0%),
+ var(--mineru-accent) var(--range-start, 0%), var(--mineru-accent) var(--range-end, 100%),
+ var(--border-color-primary, #ddd) var(--range-end, 100%));
+}
+.mineru-page-sliders > .form { position: static !important; }
+.mineru-page-handle-a, .mineru-page-handle-b {
+ position: absolute !important; inset: 0; width: 100% !important; min-width: 0 !important;
+ padding: 0 !important; border: 0 !important; background: transparent !important; pointer-events: none;
+}
+.mineru-page-handle-a .head, .mineru-page-handle-b .head,
+.mineru-page-sliders .min_value, .mineru-page-sliders .max_value { display: none !important; }
+.mineru-page-sliders input[type="range"] {
+ position: absolute; inset: 0; width: 100%; height: 32px; padding: 0; margin: 0;
+ pointer-events: none; background: transparent !important;
+}
+.mineru-page-sliders input[type="range"]::-webkit-slider-runnable-track { background: transparent !important; }
+.mineru-page-sliders input[type="range"]::-moz-range-track,
+.mineru-page-sliders input[type="range"]::-moz-range-progress { background: transparent !important; }
+.mineru-page-sliders input[type="range"]::-webkit-slider-thumb { pointer-events: auto; }
+.mineru-page-sliders input[type="range"]::-moz-range-thumb { pointer-events: auto; }
+.mineru-page-sliders input[type="range"]:disabled::-webkit-slider-thumb { pointer-events: none; }
+.mineru-page-sliders input[type="range"]:disabled::-moz-range-thumb { pointer-events: none; }
+.mineru-page-handle-a { z-index: 2; }
+.mineru-page-handle-b { z-index: 3; }
+.mineru-page-handle-a:focus-within, .mineru-page-handle-b:focus-within { z-index: 4; }
+.mineru-page-notice { font-size: 13px; color: var(--body-text-color-subdued); }
.mineru-upload-file label[data-testid="block-label"] {
align-items: flex-start !important;
line-height: 1.35 !important;
diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.js
index 03a44b92..1d6f22bb 100644
--- a/mineru/resources/gradio_app.js
+++ b/mineru/resources/gradio_app.js
@@ -1,5 +1,5 @@
() => {
- const APP_SCRIPT_VERSION = "v1-only-options";
+ const APP_SCRIPT_VERSION = "v1-pdf-page-range-crossing";
if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {
return;
}
@@ -83,10 +83,26 @@
});
};
+ // 原生 range 的值更新后重画共用轨道,不修改组件值或触发额外事件。
+ const refreshPageRangeTrack = () => {
+ const track = document.querySelector(".mineru-page-sliders");
+ const handleA = track?.querySelector('.mineru-page-handle-a input[type="range"]');
+ const handleB = track?.querySelector('.mineru-page-handle-b input[type="range"]');
+ if (!handleA || !handleB) {
+ return;
+ }
+ const span = Math.max(1, Number(handleA.max) - 1);
+ const start = Math.min(Number(handleA.value), Number(handleB.value));
+ const end = Math.max(Number(handleA.value), Number(handleB.value));
+ track.style.setProperty("--range-start", `${(start - 1) / span * 100}%`);
+ track.style.setProperty("--range-end", `${(end - 1) / span * 100}%`);
+ };
+
// 自定义 HTML 由 Gradio 动态重绘,统一在 DOM 变更后补本地化和忽略状态。
const refreshMineruCustomHtml = () => {
localizeMineruCustomText();
applyOfficePreviewNoticePreference();
+ refreshPageRangeTrack();
};
const findUploadFileInput = () => {
@@ -254,4 +270,37 @@
event.preventDefault();
}
});
+
+ // 拖动时下一帧读取 Gradio 已同步的值;键盘输入也走同一条路径。
+ document.addEventListener("input", (event) => {
+ if (event.target instanceof Element && event.target.closest(".mineru-page-sliders")) {
+ requestAnimationFrame(refreshPageRangeTrack);
+ }
+ });
+
+ // 优先命中离指针最近的物理滑块;重合时按当前起止角色决定左右半边的命中目标。
+ document.addEventListener("pointermove", (event) => {
+ if (event.buttons || !(event.target instanceof Element)) {
+ return;
+ }
+ const track = event.target.closest(".mineru-page-sliders");
+ const rootA = track?.querySelector(".mineru-page-handle-a");
+ const rootB = track?.querySelector(".mineru-page-handle-b");
+ const handleA = rootA?.querySelector('input[type="range"]');
+ const handleB = rootB?.querySelector('input[type="range"]');
+ if (!handleA || !handleB) {
+ return;
+ }
+ const bounds = handleA.getBoundingClientRect();
+ const span = Math.max(1, Number(handleA.max) - 1);
+ const centerA = bounds.left + 8 + (Number(handleA.value) - 1) / span * (bounds.width - 16);
+ const centerB = bounds.left + 8 + (Number(handleB.value) - 1) / span * (bounds.width - 16);
+ const startHandle = track.closest(".mineru-kit-page-range")
+ ?.querySelector("[data-start-handle]")?.getAttribute("data-start-handle") || "a";
+ const preferA = handleA.value === handleB.value
+ ? (event.clientX < centerA ? startHandle === "a" : startHandle !== "a")
+ : Math.abs(event.clientX - centerA) < Math.abs(event.clientX - centerB);
+ rootA.style.zIndex = preferA ? "5" : "2";
+ rootB.style.zIndex = preferA ? "2" : "5";
+ });
}
diff --git a/mineru/resources/gradio_page_range.js b/mineru/resources/gradio_page_range.js
new file mode 100644
index 00000000..c8242e80
--- /dev/null
+++ b/mineru/resources/gradio_page_range.js
@@ -0,0 +1,76 @@
+(tiers, maxPages, file, position, metadata, previous, handleAValue, handleBValue) => {
+ // 纯前端状态转换:经原生组件事件读写值,不逐次向 Python 发送拖动请求。
+ // 内部元数据使用 JSON 文本,避免不同 Gradio 版本的 JSON 组件封装差异。
+ metadata = JSON.parse(metadata || "{}");
+ previous = JSON.parse(previous || "{}");
+ // 统一构造原生组件的局部更新,未指定属性保持不变。
+ const update = (props = {}) => ({ __type__: "update", ...props });
+ // 页数读取错误只作为普通文本显示,禁止把异常内容解释为 HTML。
+ const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (char) => ({
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
+ })[char]);
+ const path = (typeof file === "string" ? file : file?.path) || "";
+ const isPdf = path.toLowerCase().endsWith(".pdf");
+ const needsRange = isPdf && tiers[position] !== "flash";
+ const fileChanged = previous?.path !== path;
+ const state = !fileChanged ? { ...previous } : {
+ path, page_count: 0, handle_a: 1, handle_b: 1, start_handle: "a", error: "",
+ };
+
+ // 只缓存当前文件的元数据;晚到的旧文件响应不能覆盖已经读好的新文件页数。
+ let initialized = false;
+ if (isPdf && metadata?.path === path && !state.page_count && !state.error) {
+ state.page_count = metadata.page_count || 0;
+ state.error = metadata.error || "";
+ state.handle_a = 1;
+ state.handle_b = Math.min(state.page_count || 1, maxPages ?? Infinity);
+ state.start_handle = "a";
+ initialized = true;
+ }
+
+ const count = state.page_count || 0;
+ if (count > 0 && !fileChanged && !initialized) {
+ // 物理滑块只受文档边界约束;交叉时不交换组件值,保持鼠标和焦点所在的实体。
+ const clamp = (value) => Math.min(count, Math.max(1, Math.round(value)));
+ // 超限时把另一滑块推到拖动端附近,方向由实际位置而不是起止角色决定。
+ const linkedPosition = (active, other) => maxPages !== null && Math.abs(active - other) + 1 > maxPages
+ ? active + Math.sign(other - active) * (maxPages - 1)
+ : other;
+ if (handleAValue !== state.handle_a) {
+ state.handle_a = clamp(handleAValue);
+ state.handle_b = linkedPosition(state.handle_a, state.handle_b);
+ } else if (handleBValue !== state.handle_b) {
+ state.handle_b = clamp(handleBValue);
+ state.handle_a = linkedPosition(state.handle_b, state.handle_a);
+ }
+ }
+
+ // 只有严格越过才交换角色;重合时沿用上一次角色,避免边界附近的标签抖动。
+ if (state.handle_a < state.handle_b) {
+ state.start_handle = "a";
+ } else if (state.handle_b < state.handle_a) {
+ state.start_handle = "b";
+ }
+ const visible = needsRange && count > 0;
+ const interactive = visible && count > 1;
+ const start = Math.min(state.handle_a, state.handle_b);
+ const end = Math.max(state.handle_a, state.handle_b);
+ const selected = end - start + 1;
+ const limitText = maxPages === null ? "不限页数" : `最多 ${maxPages} 页`;
+ const summary = `<div class="mineru-page-values" data-range-visible="${visible}" data-start-handle="${state.start_handle}">`
+ + `<span>起始页 <strong>${start}</strong></span>`
+ + `<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 range = visible ? (start === end ? String(start) : `${start}-${end}`) : "";
+ // 两个端点始终保留完整文档跨度,不能把轨道范围截短为页数上限。
+ const slider = (value, label) => update({ minimum: 1, maximum: Math.max(1, count), value, interactive, label });
+ return [
+ 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({ value: escapeHtml(notice), visible: Boolean(notice) }),
+ ];
+}
diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.py
index d7256acb..74461083 100644
--- a/tests/unittest/test_kit_gradio.py
+++ b/tests/unittest/test_kit_gradio.py
@@ -724,11 +724,14 @@ def test_render_download_rejects_state_outside_allowed_root(tmp_path: Path) -> N
assert not (tmp_path / "escaped.html").exists()
-def test_gradio_file_types_page_range_and_header_follow_new_contract() -> None:
+def test_gradio_file_types_page_range_and_header_follow_new_contract(tmp_path: Path) -> None:
"""验证完整扩展名、PDF-only 页码规则和复用后的 Header。"""
assert set(gradio_app._supported_file_types()) == {f".{extension}" for extension in PARSEABLE_EXTENSIONS}
- assert gradio_app._effective_page_range("report.PDF", " 1-3,r1 ") == "1-3,r1"
- assert gradio_app._effective_page_range("report.docx", "1-3") == ""
+ 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") == ""
header = gradio_app._render_header(gradio_major_version=6)
assert "mineru-gradio6-header" in header
assert "mineru-header-popover mineru-model-popover" in header
@@ -761,10 +764,11 @@ def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -
assert file_inputs[0].file_count == "single"
assert set(file_inputs[0].file_types) == {f".{extension}" for extension in PARSEABLE_EXTENSIONS}
preview_handler = next(fn.fn for fn in app.fns.values() if fn.name == "update_file_preview")
- assert preview_handler("report.pdf")[0]["interactive"] is True
- non_pdf_page_update = preview_handler("report.docx")[0]
- assert non_pdf_page_update["interactive"] is False
- assert non_pdf_page_update["value"] == ""
+ assert preview_handler("report.pdf")[0] == {"__type__": "update", "value": "report.pdf", "visible": True}
+ assert preview_handler("report.docx")[0]["visible"] is False
+ range_group = next(block for block in app.blocks.values() if "mineru-kit-page-range" in (block.elem_classes or []))
+ assert range_group.visible is True
+ assert '[data-range-visible="true"]' in app._mineru_kit_css
assert sum(1 for dependency in app.config["dependencies"] if dependency.get("queue") is True) >= 7
@@ -861,7 +865,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, "1")]
+ assert client.calls == [(source.resolve(), expected_tier, "" if expected_tier == "flash" else "1")]
assert len(updates[-1]) == 15
assert updates[-1][8] is not None
assert all(update["interactive"] is True and update["value"] is None for update in updates[-1][-6:])
diff --git a/tests/unittest/test_kit_gradio_page_range.cjs b/tests/unittest/test_kit_gradio_page_range.cjs
new file mode 100644
index 00000000..911c42e5
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_page_range.cjs
@@ -0,0 +1,163 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+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"];
+
+// 模拟原生 Gradio 组件值与纯前端输出更新,不复制实际联动算法。
+function createUi(limit = 20) {
+ const state = { file: null, position: 2, metadata: {}, previous: {}, a: 1, b: 1 };
+ return {
+ state,
+ step(action, patch = {}) {
+ // 应用本次输入事件,并保留 Gradio update 的跳过语义。
+ 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
+ );
+ 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]);
+ return result;
+ },
+ upload(count, filename = "/report.pdf") {
+ // 上传和元数据完成分两次触发,以检查未完成阶段的提交限制。
+ this.step("file", { file: { path: filename } });
+ return this.step("metadata", { metadata: { path: filename, page_count: count, error: "" } });
+ },
+ };
+}
+
+// 同时检查组件身份、语义角色、提交范围及无障碍标签,不能只验证排序后的数字。
+function assertSelection(result, a, b, startHandle) {
+ const state = JSON.parse(result[4]);
+ const start = Math.min(a, b);
+ const end = Math.max(a, b);
+ assert.equal(result[0].value, a);
+ assert.equal(result[1].value, b);
+ assert.equal(state.handle_a, a);
+ assert.equal(state.handle_b, b);
+ assert.equal(state.start_handle, startHandle);
+ assert.equal(result[0].label, startHandle === "a" ? "起始页" : "结束页");
+ assert.equal(result[1].label, startHandle === "b" ? "起始页" : "结束页");
+ assert.equal(result[3], start === end ? String(start) : `${start}-${end}`);
+ assert(result[2].includes(`[${start}-${end}] · ${end - start + 1} 页`));
+ assert(result[2].includes(`data-start-handle="${startHandle}"`));
+}
+
+let ui = createUi();
+assert.match(ui.step("file")[2], /data-range-visible="false"/);
+let out = ui.step("file", { file: { path: "/report.pdf" } });
+assert.equal(out[5].interactive, false);
+assert.match(out[6].value, /正在读取/);
+out = ui.upload(100);
+assert.equal(out[0].minimum, 1);
+assert.equal(out[1].maximum, 100);
+assert.equal(out[3], "1-20");
+for (const [action, value, expected] of [
+ ["b", 40, "21-40"], ["a", 15, "15-34"], ["a", 20, "20-34"], ["b", 35, "20-35"]
+]) {
+ assert.equal(ui.step(action, { [action]: value })[3], expected);
+}
+
+// 原左滑块保持 A 身份连续穿越:20→40→60→30,超限时推动 B 而不是交换物理值。
+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"/);
+assert.deepEqual(ui.state.previous, crossedState);
+assertSelection(ui.step("tier", { position: 3 }), 60, 41, "b");
+assertSelection(ui.step("a", { a: 30 }), 30, 41, "a");
+
+// 两侧接近相等时保留旧角色,只有严格越过才交换;反复穿越也不改变组件身份。
+assertSelection(ui.step("a", { a: 41 }), 41, 41, "a");
+assertSelection(ui.step("a", { a: 42 }), 42, 41, "b");
+assertSelection(ui.step("a", { a: 41 }), 41, 41, "b");
+assertSelection(ui.step("a", { a: 40 }), 40, 41, "a");
+assertSelection(ui.step("b", { b: 40 }), 40, 40, "a");
+assertSelection(ui.step("b", { b: 39 }), 40, 39, "b");
+assertSelection(ui.step("b", { b: 40 }), 40, 40, "b");
+
+// 原右滑块保持 B 身份连续穿越:55→30→10,左边的 B 超限时把 A 向左推。
+ui = createUi();
+ui.upload(100);
+ui.step("b", { b: 55 });
+assertSelection(ui.step("a", { a: 40 }), 40, 55, "a");
+assertSelection(ui.step("b", { b: 30 }), 40, 30, "b");
+assertSelection(ui.step("b", { b: 10 }), 29, 10, "b");
+assertSelection(ui.step("a", { a: -500 }), 1, 10, "a");
+assertSelection(ui.step("b", { b: 500 }), 81, 100, "a");
+
+// 换文件后旧页数响应不能覆盖新状态,已缓存页数不受晚到响应污染。
+ui.step("file", { file: { path: "/new.pdf" } });
+out = ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100 } });
+assert.equal(out[5].interactive, false);
+assert.equal(JSON.parse(out[4]).page_count, 0);
+out = ui.upload(12, "/new.pdf");
+assert.equal(out[3], "1-12");
+assertSelection(out, 1, 12, "a");
+ui.step("metadata", { metadata: { path: "/report.pdf", page_count: 100 } });
+assert.equal(ui.step("tier", { position: 2 })[3], "1-12");
+out = ui.step("file", { file: { path: "/sample.csv" } });
+assert.match(out[2], /data-range-visible="false"/);
+assert.equal(out[3], "");
+assert.equal(out[5].interactive, true);
+out = ui.step("clear");
+assert.equal(out[5].interactive, false);
+assert.equal(JSON.parse(out[4]).path, "");
+assert.equal(JSON.parse(out[4]).start_handle, "a");
+
+// 不限页数时跨越不能移动对端;上限为 1 时两个实体一起移动并保留重合角色。
+ui = createUi(null);
+ui.upload(100);
+ui.step("b", { b: 35 });
+assertSelection(ui.step("a", { a: 100 }), 100, 35, "b");
+assertSelection(ui.step("b", { b: 1 }), 100, 1, "b");
+ui = createUi(1);
+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 注入入口。
+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, "&lt;bad&gt;");
+out = ui.step("tier", { position: 0 });
+assert.equal(out[5].interactive, true);
+assert.equal(out[6].visible, false);
+
+// 确定性遍历总页数和上限:物理值允许倒序,排序后的范围、角色与上限必须一致。
+for (const count of [1, 12, 20, 100]) {
+ for (const limit of [null, 1, 20, 250]) {
+ ui = createUi(limit);
+ out = ui.upload(count);
+ assert.equal(ui.state.b, Math.min(count, limit ?? count));
+ assert.equal(out[1].interactive, count > 1);
+ let seed = 7;
+ for (let step = 0; step < 1000; step++) {
+ seed = (seed * 16807) % 2147483647;
+ const action = step % 2 ? "a" : "b";
+ const value = seed % (count + 40) - 20;
+ const other = action === "a" ? "b" : "a";
+ const previousOther = ui.state[other];
+ const previousRole = ui.state.previous.start_handle;
+ const wanted = Math.min(count, Math.max(1, value));
+ out = ui.step(action, { [action]: value });
+ const { a, b } = ui.state;
+ assert(a >= 1 && a <= count && b >= 1 && b <= count);
+ assert.equal(ui.state[action], wanted);
+ assert(limit === null || Math.abs(a - b) + 1 <= limit);
+ if (limit === null || Math.abs(wanted - previousOther) + 1 <= limit) {
+ assert.equal(ui.state[other], previousOther);
+ }
+ assertSelection(out, a, b, a < b ? "a" : b < a ? "b" : previousRole);
+ }
+ }
+}
+console.log("Page range frontend cases passed (including 16000 boundary transitions).");
diff --git a/tests/unittest/test_kit_gradio_page_range.py b/tests/unittest/test_kit_gradio_page_range.py
new file mode 100644
index 00000000..c7bc563f
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_page_range.py
@@ -0,0 +1,242 @@
+"""Gradio 双滑块的页数预检、请求约束和前端状态回归。"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import shutil
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pypdfium2 as pdfium
+import pytest
+from pypdf import PdfWriter
+from typer.testing import CliRunner
+
+from mineru.errors import InvalidRequestError
+from mineru.kit.gradio import app as gradio_app
+from mineru.kit.gradio import page_range as ranges
+from mineru.kit.gradio.client import V1ServerCapabilities
+from mineru.kit.main import app
+from mineru.model.flash.pdf.pdfium import _pdfium_lock
+
+
+def _pdf(tmp_path: Path, page_count: int = 100, *, encrypted: bool = False) -> Path:
+ """生成测试用 PDF,可选密码保护及空文档。"""
+ writer = PdfWriter()
+ for _ in range(page_count):
+ writer.add_blank_page(width=200, height=300)
+ if encrypted:
+ writer.encrypt("required-password")
+ path = tmp_path / "report.PDF"
+ writer.write(path)
+ return path
+
+
[email protected](("args", "expected"), [([], None), (["--max-pages", "20"], 20)])
+def test_command_forwards_max_pages(monkeypatch: pytest.MonkeyPatch, args: list[str], expected: int | None) -> None:
+ """验证省略或显式配置上限时的启动参数透传。"""
+ launch = Mock()
+ monkeypatch.setattr(gradio_app, "launch_gradio", launch)
+ result = CliRunner().invoke(app, ["gradio", *args])
+ assert result.exit_code == 0, result.output
+ assert launch.call_args.kwargs["max_pages"] == expected
+ assert "--max-pages" in CliRunner().invoke(app, ["gradio", "--help"]).output
+
+
[email protected]("value", ["0", "-1", "1.5", "invalid"])
+def test_command_rejects_invalid_max_pages(monkeypatch: pytest.MonkeyPatch, value: str) -> None:
+ """验证非正整数配置在启动任何服务前报错。"""
+ launch = Mock()
+ monkeypatch.setattr(gradio_app, "launch_gradio", launch)
+ result = CliRunner().invoke(app, ["gradio", "--max-pages", value])
+ assert result.exit_code != 0
+ launch.assert_not_called()
+
+
[email protected]("value", [0, -1, 1.5, True, "20"])
+def test_programmatic_max_pages_validation(value: object) -> None:
+ """验证直接构建或启动界面也不能绕过整数配置检查。"""
+ with pytest.raises(ValueError, match="positive integer"):
+ ranges.validate_max_pages(value) # type: ignore[arg-type]
+
+
+def test_launch_forwards_limit_and_versioned_assets(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """验证启动链路向界面传入上限,并使用构建阶段确定的版本兼容资源参数。"""
+ client = SimpleNamespace(discover=AsyncMock(return_value=Mock()))
+ demo = SimpleNamespace(launch=Mock(), _mineru_kit_launch_kwargs={"css": "test-css", "js": "test-js"})
+ build = Mock(return_value=demo)
+ monkeypatch.setattr(gradio_app, "V1ArtifactClient", Mock(return_value=client))
+ monkeypatch.setattr(gradio_app, "build_gradio_app", build)
+ gradio_app.launch_gradio(
+ api_url="http://127.0.0.1:1",
+ api_key=None,
+ server_name="127.0.0.1",
+ server_port=None,
+ output_dir=str(tmp_path),
+ enable_example=False,
+ enable_api=True,
+ latex_delimiters_type="all",
+ api_server_tier="standard",
+ api_server_no_flash=False,
+ api_server_concurrency=1,
+ api_server_language="ch",
+ api_server_ocr_mode="auto",
+ api_server_disable_image_analysis=False,
+ api_server_preload_models=False,
+ max_pages=20,
+ )
+ assert build.call_args.kwargs["max_pages"] == 20
+ assert demo.launch.call_args.kwargs["css"] == "test-css"
+ assert demo.launch.call_args.kwargs["js"] == "test-js"
+
+
[email protected]("count", [1, 12, 20, 100])
+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"
+
+
+ ("raw", "expected"), [("20-35", "20-35"), (" 1, 1-20 ", "1-20"), ("r20-r1", "r20-r1"), ("95-200", "95-200")]
+)
+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
+
+
[email protected]("raw", ["all", "1-21", "r30-r1", "1-10,90-100", "999", "20-1", "~", "0"])
+def test_invalid_or_oversized_range_is_rejected_before_submission(tmp_path: Path, raw: str) -> None:
+ """验证直接调用 Gradio 转换事件也无法提交超限或非法范围。"""
+ source = _pdf(tmp_path)
+ client = SimpleNamespace(parse_file=AsyncMock())
+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash", "standard"), ("zip",), ("file_id",))
+ demo = gradio_app.build_gradio_app(client, capabilities, output_root=tmp_path, max_pages=20, enable_example=False)
+ handler = next(fn.fn for fn in demo.fns.values() if fn.name == "convert_handler")
+
+ async def collect() -> list[tuple[object, ...]]:
+ """收集错误事件并确认没有启动实际解析。"""
+ return [update async for update in handler(str(source), 1, raw)]
+
+ updates = asyncio.run(collect())
+ assert "page_range_invalid" in str(updates[-1][0])
+ assert updates[-1][8] is None
+ client.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 和空输入直接清空范围,不因残留的坏页码而失败。"""
+ 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]
+ read_count.assert_not_called()
+
+
[email protected]("kind", ["broken", "encrypted", "empty", "missing"])
+def test_unreadable_pdf_is_not_treated_as_all_pages(tmp_path: Path, kind: str) -> None:
+ """损坏、加密、空页和丢失文件均反馈错误,不能降级为全部解析。"""
+ source = tmp_path / "report.PDF"
+ if kind == "broken":
+ source.write_bytes(b"not a PDF")
+ elif kind != "missing":
+ source = _pdf(tmp_path, 0 if kind == "empty" else 1, encrypted=kind == "encrypted")
+ metadata = ranges.pdf_page_metadata(str(source))
+ assert metadata["path"] == str(source)
+ assert metadata["page_count"] == 0
+ assert "无法读取 PDF 页数" in metadata["error"]
+ with pytest.raises(InvalidRequestError, match="无法读取 PDF 页数"):
+ ranges.effective_page_range(source, "", tier="standard", max_pages=20)
+
+
[email protected]("fail", [False, True])
+def test_pdfium_access_is_locked_and_document_is_closed(monkeypatch: pytest.MonkeyPatch, fail: bool) -> None:
+ """验证页数读取和异常路径都持有共享锁并且恰好关闭文档一次。"""
+ closed: list[bool] = []
+
+ class Document:
+ """检查文档生命周期内的锁状态。"""
+
+ def __init__(self, _path: str) -> None:
+ """确认打开时已持有共享锁。"""
+ assert _pdfium_lock._is_owned()
+
+ def __len__(self) -> int:
+ """模拟正常页数或读取页数失败。"""
+ assert _pdfium_lock._is_owned()
+ if fail:
+ raise RuntimeError("count failed")
+ return 10
+
+ def close(self) -> None:
+ """确认清理时仍然持有共享锁。"""
+ closed.append(_pdfium_lock._is_owned())
+
+ monkeypatch.setattr(pdfium, "PdfDocument", Document)
+ if fail:
+ with pytest.raises(InvalidRequestError):
+ ranges.read_pdf_page_count("report.pdf")
+ else:
+ assert ranges.read_pdf_page_count("report.pdf") == 10
+ assert closed == [True]
+
+
+def test_metadata_does_not_read_non_pdf(monkeypatch: pytest.MonkeyPatch) -> None:
+ """非 PDF 和清除文件不触发 PDFium 读取。"""
+ count = Mock()
+ monkeypatch.setattr(ranges, "read_pdf_page_count", count)
+ assert ranges.pdf_page_metadata(None) == {"path": "", "page_count": 0, "error": ""}
+ assert ranges.pdf_page_metadata("report.docx")["page_count"] == 0
+ count.assert_not_called()
+
+
+def test_native_range_components_and_frontend_only_events(tmp_path: Path) -> None:
+ """双滑块使用原生组件,联动与档位切换不请求 Python,公开转换输入仍为三项。"""
+ capabilities = V1ServerCapabilities("http://127.0.0.1:1", ("flash", "standard"), ("zip",), ("file_id",))
+ demo = gradio_app.build_gradio_app(Mock(), capabilities, output_root=tmp_path, max_pages=20, enable_example=False)
+ sliders = [block for block in demo.blocks.values() if block.__class__.__name__ == "Slider"]
+ assert len(sliders) == 3
+ assert sliders[1].elem_classes == ["mineru-page-handle-a"]
+ assert sliders[2].elem_classes == ["mineru-page-handle-b"]
+ for slider in sliders[1:]:
+ assert slider.step == 1 and slider.precision == 0
+ events = [event for event in demo.config["dependencies"] if (slider._id, "input") in event["targets"]]
+ assert len(events) == 1 and events[0]["backend_fn"] is False and events[0]["queue"] is False
+ assert events[0]["trigger_mode"] == "always_last"
+ assert len(events[0]["targets"]) == 5
+ assert events[0]["outputs"][:2] == [sliders[1]._id, sliders[2]._id]
+ handler = next(fn for fn in demo.fns.values() if fn.name == "convert_handler")
+ assert len(handler.inputs) == 3
+ assert handler.inputs[2].__class__.__name__ == "Textbox" and handler.inputs[2].visible is False
+ metadata_handler = next(fn for fn in demo.fns.values() if fn.name == "read_page_metadata")
+ assert metadata_handler.outputs[0].__class__.__name__ == "Textbox"
+ metadata = json.loads(metadata_handler.fn(str(_pdf(tmp_path, 12))))
+ assert metadata["page_count"] == 12 and metadata["error"] == ""
+ load_events = [event for event in demo.config["dependencies"] if any(target[1] == "load" for target in event["targets"])]
+ assert any(event["js"] == demo._mineru_kit_js and not event["backend_fn"] for event in load_events)
+ import gradio as gr
+
+ if gradio_app._gradio_major_version(gr) >= 6:
+ assert set(demo._mineru_kit_launch_kwargs) == {"css", "js"}
+ else:
+ assert demo._mineru_kit_launch_kwargs == {}
+ assert demo.css and demo.js
+
+
+def test_frontend_page_range_state_machine() -> None:
+ """通过 Node 执行实际前端脚本,覆盖联动、竞态、键盘等共享状态转换。"""
+ 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)
+ assert result.returncode == 0, result.stdout + result.stderr