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: simplify Gradio API by removing deprecated remote server options and unused components
myhloli3c765c4c736a
diff --git a/mineru/cli_old/gradio_app.py b/mineru/cli_old/gradio_app.pyindex 9253e262..4798fe3c 100644--- a/mineru/cli_old/gradio_app.py+++ b/mineru/cli_old/gradio_app.py@@ -52,13 +52,7 @@ from mineru.parser.api_client import MinerUApiParserfrom mineru.parser.base import ParseResultfrom mineru.parser.tier import ParserRuntimeOptions, runtime_options_for_tierfrom mineru.render import render_content_list, render_markdown, render_structured_content-from mineru.utils.backend_options import (- CANONICAL_HYBRID_ENGINE,- LOCAL_HYBRID_EFFORT,- MAX_HYBRID_EFFORT,-)from mineru.utils.image_payload import validate_image_sidecar_path-from mineru.utils.ocr_language import PUBLIC_OCR_LANGUAGE_CHOICES, validate_public_ocr_langfrom mineru.utils.pdf_document import PDFDocumentfrom mineru.utils.pdf_page_id import parse_page_rangefrom mineru.utils.pdfium_guard import safe_rewrite_pdf_bytes_with_pdfium_result@@ -247,7 +241,6 @@ STATUS_QUEUED_LOCALLY_PREFIX = "Queued locally:"DEFAULT_GRADIO_TIER = "pro"GRADIO_TIER_CHOICES = ("standard", "pro")-GRADIO_REMOTE_BACKEND = "hybrid-http-client"STATUS_STEP_DEFINITIONS = [("status_step_prepare", STATUS_PREPARING_REQUEST),("status_step_check", STATUS_CHECKING_SERVER),@@ -593,10 +586,9 @@ def render_client_i18n_text(i18n, key, locale=None):)-def resolve_gradio_runtime_options(tier: str | None, use_remote_server: bool = False) -> ParserRuntimeOptions:- """根据 Gradio 公开 tier 与远端开关派生内部 backend/effort,保持旧提交链路兼容。"""- backend = GRADIO_REMOTE_BACKEND if use_remote_server else CANONICAL_HYBRID_ENGINE- return runtime_options_for_tier(tier or DEFAULT_GRADIO_TIER, backend=backend)+def resolve_gradio_runtime_options(tier: str | None) -> ParserRuntimeOptions:+ """根据 Gradio 公开 tier 派生 v1 API 任务使用的运行配置。"""+ return runtime_options_for_tier(tier or DEFAULT_GRADIO_TIER)def select_tier_info_key(tier_choice: object) -> str:@@ -608,18 +600,6 @@ def select_tier_info_key(tier_choice: object) -> str:return "tier_info_default"-def select_force_ocr_info_key(tier_choice: object) -> str:- """根据 Gradio tier 选择强制 OCR 说明;当前公开 tier 均走 Hybrid 文案。"""- if tier_choice in GRADIO_TIER_CHOICES:- return "force_ocr_info_hybrid"- return "force_ocr_info"---def frontend_managed_initial_visibility(is_visible: bool):- """转换前端托管显隐控件的初始状态;hidden 会保留 DOM 挂载避免状态丢失。"""- return True if is_visible else "hidden"--def resolve_status_step_index(status_lines):"""根据现有状态日志推断步骤面板中当前应高亮的步骤索引。"""if not status_lines:@@ -1229,52 +1209,6 @@ def prepare_markdown_for_gradio_preview(markdown_text, latex_delimiters):return escape_latex_blocks_for_gradio_preview(markdown_text, latex_delimiters)-def normalize_language(language):- if '(' in language and ')' in language:- language = language.split('(')[0].strip()- return validate_public_ocr_lang(language)---def resolve_parse_method(file_path, is_ocr, tier=DEFAULT_GRADIO_TIER):- """根据文件类型和 OCR 开关解析旧 multipart parse_method,tier 只保留签名语义。"""- file_suffix = Path(file_path).suffix.lower().lstrip('.')- if file_suffix in office_suffixes:- return "auto"- return "ocr" if is_ocr else "auto"---def is_image_analysis_option_visible(tier: object) -> bool:- """判断 Gradio 图片分析开关是否应展示;当前公开 tier 不暴露 extra_high。"""- if tier not in GRADIO_TIER_CHOICES:- return False- try:- runtime = resolve_gradio_runtime_options(str(tier), use_remote_server=False)- except ValueError:- return False- return runtime.effort == MAX_HYBRID_EFFORT---def is_ocr_language_option_visible(tier: object) -> bool:- """判断 OCR 语言选项是否展示;只有 standard 对应的 Hybrid medium 暴露语言输入。"""- if tier not in GRADIO_TIER_CHOICES:- return False- try:- runtime = resolve_gradio_runtime_options(str(tier), use_remote_server=False)- except ValueError:- return False- return runtime.effort == LOCAL_HYBRID_EFFORT---def is_force_ocr_option_visible(tier: object) -> bool:- """判断强制 OCR 开关是否展示;公开 tier 均基于 Hybrid,保留强制 OCR。"""- return tier in GRADIO_TIER_CHOICES---def should_use_client_side_output_generation(client_side_output_generation):- """判断当前 Gradio 任务是否需要在客户端生成最终输出。"""- return client_side_output_generation--def create_gradio_run_paths(file_path, output_root="./output"):"""生成 Gradio 单次任务目录,统一返回绝对路径以便文件预览组件访问。"""run_id = f"{time.strftime('%y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}_{safe_stem(Path(file_path).stem)}"@@ -1299,39 +1233,6 @@ def build_gradio_allowed_paths(output_root="./output"):return allowed_paths-async def resolve_server_health(http_client, api_url):- """兼容旧调用名:当前 Gradio 健康检查统一走 v1 /tiers 探测。"""- return await resolve_v1_server_health(http_client, api_url)---async def ensure_local_api_ready_for_gradio_startup(- timeout_seconds: float = _api_client.LOCAL_API_STARTUP_TIMEOUT_SECONDS,-):- """兼容旧调用名:等待本地 v1 API server 就绪。"""- local_server, started_now = _gradio_local_api_server.ensure_started()- if started_now:- logger.info(f"Started local MinerU v1 API at {local_server.base_url}")-- async with httpx.AsyncClient(- timeout=_api_client.build_http_timeout(),- follow_redirects=True,- ) as http_client:- return await wait_for_v1_api_ready(- http_client,- local_server,- timeout_seconds=timeout_seconds,- )---def maybe_prepare_local_api_for_gradio_startup(- *,- api_url: str | None,- enable_vlm_preload: bool,-):- """保留旧函数入口;v1 server 已在构建 Dropdown 前完成探测。"""- return None--def resolve_gradio_max_concurrent_requests(api_url, server_health):if api_url is None:return server_health.max_concurrent_requests@@ -1347,31 +1248,20 @@ def resolve_gradio_max_concurrent_requests(api_url, server_health):async def _run_to_markdown_job(file_path,end_pages=10,- is_ocr=False,- formula_enable=True,- table_enable=True,- image_analysis=True,tier=DEFAULT_GRADIO_TIER,- language="ch",- use_remote_server=False,- url=None,api_url=None,- client_side_output_generation=False,status_callback: Callable[[str], None] | None = None,):if file_path is None:return "", "", "", None, None- # v1 API 当前只公开 tier 和 page_range;旧 UI 参数保留用于前端兼容,不写入未公开 payload。- del is_ocr, formula_enable, table_enable, image_analysis, language, url, client_side_output_generation-def emit_status(message: str) -> None:if status_callback is not None:status_callback(message)file_path = str(file_path)file_suffix = Path(file_path).suffix.lower().lstrip('.')- runtime = resolve_gradio_runtime_options(tier, use_remote_server=use_remote_server)+ runtime = resolve_gradio_runtime_options(tier)backend = runtime.backendeffort = runtime.effortpage_range = build_v1_gradio_page_range(end_pages)@@ -1433,16 +1323,8 @@ async def _run_to_markdown_job(async def stream_to_markdown(file_path,end_pages=10,- is_ocr=False,- formula_enable=True,- table_enable=True,- image_analysis=True,tier=DEFAULT_GRADIO_TIER,- language="ch",- use_remote_server=False,- url=None,api_url=None,- client_side_output_generation=False,):status_state = StatusPanelState()job_task: asyncio.Task | None = None@@ -1464,16 +1346,8 @@ async def stream_to_markdown(_run_to_markdown_job(file_path=file_path,end_pages=end_pages,- is_ocr=is_ocr,- formula_enable=formula_enable,- table_enable=table_enable,- image_analysis=image_analysis,tier=tier,- language=language,- use_remote_server=use_remote_server,- url=url,api_url=api_url,- client_side_output_generation=client_side_output_generation,status_callback=enqueue_status,))@@ -1610,9 +1484,6 @@ def render_header_html(i18n):)return rendered_header-all_lang = list(PUBLIC_OCR_LANGUAGE_CHOICES)--def safe_stem(file_path):stem = Path(file_path).stem# 只保留字母、数字、下划线和点,其他字符替换为下划线@@ -1767,7 +1638,7 @@ def update_doc_show(file_path):'--enable-http-client','http_client_enable',type=bool,- help="Enable http-client backend to link openai-compatible servers.",+ help="Deprecated no-op; use --api-url to bind Gradio to an external v1 API server.",default=False,)@click.option(@@ -1809,14 +1680,14 @@ def update_doc_show(file_path):'--enable-vlm-preload','enable_vlm_preload',type=bool,- help="Preload the local VLM model when gradio starts a local mineru-api service.",+ help="Deprecated no-op; Gradio v1 starts or connects to a parser API server.",default=False,)@click.option('--client-side-output-generation','client_side_output_generation',type=bool,- help="Generate markdown and content lists locally from server-returned middle json.",+ help="Deprecated no-op; Gradio v1 persists outputs from ParseResult locally.",default=False,)@click.option(@@ -1853,25 +1724,6 @@ def main(ctx,"tier_info_default": "Select the parsing tier.","tier_info_standard": "Standard tier uses fast local Hybrid parsing.","tier_info_pro": "Pro tier uses higher quality Hybrid parsing.",- "use_remote_server": "Use remote server",- "use_remote_server_info": "Send parsing requests to an OpenAI-compatible server.",- "server_url": "Server URL",- "server_url_info": "OpenAI-compatible server URL.",- "recognition_options": "**Recognition Options:**",- "advanced_options": "Advanced options",- "table_enable": "Enable table recognition",- "table_info": "If disabled, tables will be shown as images.",- "image_analysis_enable": "Enable image analysis",- "image_analysis_info": "If disabled, image/chart blocks will keep layout positions but skip VLM image/chart analysis.",- "formula_label_vlm": "Enable display formula recognition",- "formula_label_hybrid": "Enable inline formula recognition",- "formula_info_vlm": "If disabled, display formulas will be shown as images.",- "formula_info_hybrid": "If disabled, inline formulas will not be detected or parsed.",- "ocr_language": "OCR Language",- "ocr_language_info": "Select the OCR language for Hybrid medium local OCR and table OCR.",- "force_ocr": "Force enable OCR",- "force_ocr_info": "Enable only if the result is extremely poor. Hybrid medium requires correct OCR language.",- "force_ocr_info_hybrid": "Enable only if the result is extremely poor.","convert": "Convert","clear": "Clear","doc_preview": "Document preview",@@ -1916,25 +1768,6 @@ def main(ctx,"tier_info_default": "选择文档解析 tier。","tier_info_standard": "standard 使用快速本地 Hybrid 解析。","tier_info_pro": "pro 使用更高质量的 Hybrid 解析。",- "use_remote_server": "使用远端服务",- "use_remote_server_info": "将解析请求发送到 OpenAI 兼容服务。",- "server_url": "服务器地址",- "server_url_info": "OpenAI 兼容服务器地址。",- "recognition_options": "**识别选项:**",- "advanced_options": "高级选项",- "table_enable": "启用表格识别",- "table_info": "禁用后,表格将显示为图片。",- "image_analysis_enable": "启用图片分析",- "image_analysis_info": "禁用后,图片/图表块仍保留版面位置,但跳过 VLM 图片/图表分析。",- "formula_label_vlm": "启用行间公式识别",- "formula_label_hybrid": "启用行内公式识别",- "formula_info_vlm": "禁用后,行间公式将显示为图片。",- "formula_info_hybrid": "禁用后,行内公式将不会被检测或解析。",- "ocr_language": "OCR 语言",- "ocr_language_info": "为 Hybrid medium 的本地 OCR 和表格 OCR 选择语言。",- "force_ocr": "强制启用 OCR",- "force_ocr_info": "仅在识别效果极差时启用;Hybrid medium 需选择正确的 OCR 语言。",- "force_ocr_info_hybrid": "仅在识别效果极差时启用。","convert": "转换","clear": "清除","doc_preview": "文档预览",@@ -1965,47 +1798,22 @@ def main(ctx,},)- # 根据 tier 获取公式识别标签(闭包函数以支持 i18n)- def get_formula_label(tier_choice):- return i18n("formula_label_hybrid")-- def get_formula_info(tier_choice):- return i18n("formula_info_hybrid") if tier_choice in GRADIO_TIER_CHOICES else ""-def get_tier_info(tier_choice):return i18n(select_tier_info_key(tier_choice))- def get_force_ocr_info(tier_choice):- """根据 tier 返回强制 OCR 控件说明,当前公开 tier 统一使用 Hybrid 文案。"""- return i18n(select_force_ocr_info_key(tier_choice))-- # 更新界面函数- def update_interface(tier_choice, use_remote_server):- """根据 tier 和远端开关更新 Gradio 联动控件,保持前端显隐规则集中。"""- use_remote_server = bool(use_remote_server)- formula_label_update = gr.update(label=get_formula_label(tier_choice), info=get_formula_info(tier_choice))- tier_info_update = gr.update(info=get_tier_info(tier_choice))- force_ocr_update = gr.update(info=get_force_ocr_info(tier_choice))- image_analysis_update = gr.update(visible=is_image_analysis_option_visible(tier_choice))- language_update = gr.update(visible=is_ocr_language_option_visible(tier_choice))- client_options_update = gr.update(visible=use_remote_server)- ocr_options_update = gr.update(visible=is_force_ocr_option_visible(tier_choice))-- return (- client_options_update,- ocr_options_update,- force_ocr_update,- formula_label_update,- tier_info_update,- image_analysis_update,- language_update,- )-del kwargs+ if http_client_enable:+ logger.warning(+ "Ignoring --enable-http-client because Gradio v1 selects external parser services with --api-url."+ )if enable_vlm_preload:logger.warning("Ignoring --enable-vlm-preload because Gradio now launches the v1 parser API server.")+ if client_side_output_generation:+ logger.warning(+ "Ignoring --client-side-output-generation because Gradio v1 persists outputs from ParseResult locally."+ )_gradio_local_api_server.configure(ctx.args)startup_health = resolve_gradio_v1_startup_health(api_url=api_url)tier_choices = startup_health.tier_choices@@ -2023,30 +1831,15 @@ def main(ctx,async def convert_to_markdown_stream(file_path,end_pages=10,- is_ocr=False,- formula_enable=True,- table_enable=True,- image_analysis=True,tier=DEFAULT_GRADIO_TIER,- language="ch",- use_remote_server=False,- url=None,request: gr.Request = None,):request_locale = resolve_request_locale(request)async for update in stream_to_markdown(file_path=file_path,end_pages=end_pages,- is_ocr=is_ocr,- formula_enable=formula_enable,- table_enable=table_enable,- image_analysis=image_analysis,tier=tier,- language=language,- use_remote_server=use_remote_server,- url=url,api_url=api_url,- client_side_output_generation=client_side_output_generation,):update = (render_status_steps_html(update[0], i18n, locale=request_locale),@@ -2076,31 +1869,9 @@ def main(ctx,info=get_tier_info(preferred_tier),elem_classes=["mineru-tier-select"],)- use_remote_server = gr.Checkbox(- label=i18n("use_remote_server"),- value=False,- visible=http_client_enable,- info=i18n("use_remote_server_info"),- elem_classes=["mineru-remote-server-toggle"],- )- with gr.Row(- visible=frontend_managed_initial_visibility(False),- elem_classes=["mineru-client-options"],- ) as client_options:- url = gr.Textbox(- label=i18n("server_url"),- value='http://localhost:30000',- placeholder='http://localhost:30000',- info=i18n("server_url_info"),- )- # 下面这些选项在上传 office 文件时会被自动隐藏+ # 页数控件在上传 Office 文件时会被自动隐藏。with gr.Group() as options_group:max_pages = gr.Slider(1, max_convert_pages, max_convert_pages, step=1, label=i18n("max_pages"))- advanced_bu = gr.Button(- i18n("advanced_options"),- size="sm",- elem_classes=["mineru-advanced-open"],- )with gr.Row(elem_classes=["mineru-actions"]):change_bu = gr.Button(i18n("convert"), variant="primary", scale=1, min_width=0)clear_bu = gr.ClearButton(value=i18n("clear"), scale=1, min_width=0)@@ -2184,67 +1955,16 @@ def main(ctx,label=None,)- with gr.Column(elem_classes=["mineru-advanced-popover"]):- with gr.Column(elem_classes=["mineru-advanced-card"]):- with gr.Group():- table_enable = gr.Checkbox(label=i18n("table_enable"), value=True, info=i18n("table_info"))- formula_enable = gr.Checkbox(label=get_formula_label(preferred_tier), value=True, info=get_formula_info(preferred_tier))- image_analysis = gr.Checkbox(- label=i18n("image_analysis_enable"),- value=True,- visible=frontend_managed_initial_visibility(- is_image_analysis_option_visible(preferred_tier)- ),- info=i18n("image_analysis_info"),- elem_classes=["mineru-image-analysis-option"],- )- with gr.Column(elem_classes=["mineru-force-ocr-option"]) as ocr_options:- with gr.Group():- with gr.Column(elem_classes=["mineru-ocr-language-options"]):- language = gr.Dropdown(- all_lang,- label=i18n("ocr_language"),- value=all_lang[0],- info=i18n("ocr_language_info"),- visible=frontend_managed_initial_visibility(- is_ocr_language_option_visible(preferred_tier)- ),- )- is_ocr = gr.Checkbox(- label=i18n("force_ocr"),- value=False,- info=i18n(select_force_ocr_info_key(preferred_tier)),- )-# 添加事件处理_private_api_kwargs = ({"api_visibility": "private", "queue": False}if IS_GRADIO_6else {"api_name": False, "queue": False})- tier.change(- fn=update_interface,- inputs=[tier, use_remote_server],- outputs=[client_options, ocr_options, is_ocr, formula_enable, tier, image_analysis, language],- **_private_api_kwargs- )- use_remote_server.change(- fn=update_interface,- inputs=[tier, use_remote_server],- outputs=[client_options, ocr_options, is_ocr, formula_enable, tier, image_analysis, language],- **_private_api_kwargs- )- # 添加demo.load事件,在页面加载时触发一次界面更新- demo.load(- fn=update_interface,- inputs=[tier, use_remote_server],- outputs=[client_options, ocr_options, is_ocr, formula_enable, tier, image_analysis, language],- **_private_api_kwargs- )- clear_bu.add([input_file, md, doc_show, md_text, content_list_json, output_file, is_ocr, office_html, status_panel])+ clear_bu.add([input_file, md, doc_show, md_text, content_list_json, output_file, office_html, status_panel])def reset_primary_ui():- """清除主界面状态。高级气泡由前端点击外部逻辑自动收起。"""+ """清除主界面状态,并恢复文件预览与状态面板。"""return (gr.update(visible=True),gr.update(value=None, visible=True),@@ -2294,7 +2014,7 @@ def main(ctx,)change_bu.click(fn=convert_to_markdown_stream,- inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, image_analysis, tier, language, use_remote_server, url],+ inputs=[input_file, max_pages, tier],outputs=[status_panel, output_file, md, md_text, content_list_json, doc_show],**_to_md_api_kwargs)@@ -2308,10 +2028,6 @@ def main(ctx,_launch_kwargs = {"footer_links": footer_links, "css": APP_CSS, "head": APP_HEAD}else:_launch_kwargs = {"show_api": api_enable}- maybe_prepare_local_api_for_gradio_startup(- api_url=api_url,- enable_vlm_preload=enable_vlm_preload,- )demo.launch(server_name=server_name,server_port=server_port,diff --git a/mineru/resources/gradio_app.css b/mineru/resources/gradio_app.cssindex acb818b6..138e91a9 100644--- a/mineru/resources/gradio_app.css+++ b/mineru/resources/gradio_app.css@@ -8,11 +8,6 @@--mineru-status-panel-bg: rgba(255, 255, 255, 0.78);--mineru-status-latest-border: rgba(17, 24, 39, 0.13);--mineru-status-latest-text: #374151;- --mineru-popover-border: rgba(17, 24, 39, 0.12);- --mineru-popover-shell-bg: rgba(255, 255, 255, 0.88);- --mineru-popover-card-bg: rgba(255, 255, 255, 0.96);- --mineru-popover-shadow: 0 18px 42px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(17, 24, 39, 0.04) inset;- --mineru-popover-dropdown-shadow: 0 14px 30px rgba(15, 23, 42, 0.16);}@media (prefers-color-scheme: light) {.gradio-container {@@ -21,11 +16,6 @@--mineru-status-panel-bg: rgba(255, 255, 255, 0.78);--mineru-status-latest-border: rgba(17, 24, 39, 0.13);--mineru-status-latest-text: #374151;- --mineru-popover-border: rgba(17, 24, 39, 0.12);- --mineru-popover-shell-bg: rgba(255, 255, 255, 0.88);- --mineru-popover-card-bg: rgba(255, 255, 255, 0.96);- --mineru-popover-shadow: 0 18px 42px rgba(15, 23, 42, 0.18), 0 0 0 1px rgba(17, 24, 39, 0.04) inset;- --mineru-popover-dropdown-shadow: 0 14px 30px rgba(15, 23, 42, 0.16);}}body.dark .gradio-container {@@ -34,11 +24,6 @@ body.dark .gradio-container {--mineru-status-panel-bg: rgba(0, 0, 0, 0.18);--mineru-status-latest-border: var(--mineru-panel-border);--mineru-status-latest-text: var(--body-text-color-subdued);- --mineru-popover-border: rgba(255, 255, 255, 0.08);- --mineru-popover-shell-bg: linear-gradient(135deg, rgba(255, 255, 255, 0.20), rgba(255, 255, 255, 0.05) 44%, rgba(249, 115, 22, 0.16));- --mineru-popover-card-bg: linear-gradient(180deg, rgba(42, 43, 48, 0.97), rgba(32, 33, 36, 0.94));- --mineru-popover-shadow: 0 18px 42px rgba(0, 0, 0, 0.34), 0 0 0 1px rgba(255, 255, 255, 0.04) inset;- --mineru-popover-dropdown-shadow: 0 14px 30px rgba(0, 0, 0, 0.36);}.mineru-shell {display: flex;@@ -99,97 +84,6 @@ body.dark .gradio-container {padding-left: 8px !important;padding-right: 8px !important;}-.mineru-advanced-open,-.mineru-advanced-open button {- min-width: 0 !important;- width: 100% !important;-}-.mineru-advanced-popover {- position: fixed !important;- left: var(--mineru-popover-left, 316px) !important;- top: var(--mineru-popover-top, 360px) !important;- z-index: 1000 !important;- width: min(420px, calc(100vw - var(--mineru-popover-left, 316px) - 18px)) !important;- max-width: calc(100vw - 36px) !important;- padding: 1px !important;- border: 1px solid var(--mineru-popover-border) !important;- border-radius: 14px !important;- background: var(--mineru-popover-shell-bg) !important;- box-shadow: var(--mineru-popover-shadow) !important;- backdrop-filter: blur(12px);- overflow: hidden !important;- visibility: hidden !important;- opacity: 0 !important;- pointer-events: none !important;- transform: translateY(-4px) scale(0.985) !important;- transform-origin: left center !important;- transition:- opacity 140ms ease,- transform 140ms ease,- visibility 0s linear 140ms !important;-}-body.mineru-advanced-popover-open .gradio-container .contain .mineru-advanced-popover,-body.mineru-advanced-popover-open .mineru-advanced-popover {- visibility: visible !important;- opacity: 1 !important;- pointer-events: auto !important;- transform: translateY(0) scale(1) !important;- transition:- opacity 140ms ease,- transform 140ms ease,- visibility 0s linear 0s !important;-}-.mineru-advanced-popover::before {- display: none !important;-}-.mineru-advanced-card {- width: 100% !important;- max-height: min(70vh, 620px) !important;- margin: 0 !important;- padding: 14px !important;- overflow: auto !important;- border: 0 !important;- border-radius: 13px !important;- background: var(--mineru-popover-card-bg) !important;- box-shadow: 0 1px 0 rgba(255, 255, 255, 0.06) inset !important;-}-.mineru-advanced-popover .wrap,-.mineru-advanced-popover .block {- min-width: 0 !important;-}-.mineru-advanced-popover .wrap,-.mineru-advanced-popover .block,-.mineru-advanced-popover .form,-.mineru-advanced-popover .styler,-.mineru-advanced-popover .gr-group {- overflow: visible !important;-}-.mineru-advanced-popover [data-testid="status-tracker"] {- display: none !important;- visibility: hidden !important;- pointer-events: none !important;-}-.mineru-client-options,-.mineru-image-analysis-option,-.mineru-ocr-language-options {- display: none !important;-}-body.mineru-show-client-options .gradio-container .contain .mineru-client-options.mineru-client-options {- display: flex !important;-}-body.mineru-show-image-analysis .gradio-container .contain .mineru-image-analysis-option.mineru-image-analysis-option {- display: block !important;-}-body.mineru-show-ocr-language .gradio-container .contain .mineru-ocr-language-options.mineru-ocr-language-options {- display: flex !important;-}-body.mineru-hide-force-ocr .gradio-container .contain .mineru-force-ocr-option.mineru-force-ocr-option {- display: none !important;-}-.mineru-advanced-popover ul.options {- border-radius: 8px !important;- box-shadow: var(--mineru-popover-dropdown-shadow) !important;-}.mineru-result-tabs .tab-nav {border-bottom-color: var(--mineru-panel-border);}diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.jsindex e6d073ff..03a44b92 100644--- a/mineru/resources/gradio_app.js+++ b/mineru/resources/gradio_app.js@@ -1,19 +1,11 @@() => {- const POPOVER_SCRIPT_VERSION = "tier-remote-options-v1";- if (window.__mineruAdvancedPopoverInstalled === POPOVER_SCRIPT_VERSION) {+ const APP_SCRIPT_VERSION = "v1-only-options";+ if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {return;}- window.__mineruAdvancedPopoverInstalled = POPOVER_SCRIPT_VERSION;+ window.__mineruGradioAppInstalled = APP_SCRIPT_VERSION;- const POPOVER_OPEN_CLASS = "mineru-advanced-popover-open";- const CLIENT_OPTIONS_VISIBLE_CLASS = "mineru-show-client-options";- const IMAGE_ANALYSIS_VISIBLE_CLASS = "mineru-show-image-analysis";- const OCR_LANGUAGE_VISIBLE_CLASS = "mineru-show-ocr-language";- const FORCE_OCR_HIDDEN_CLASS = "mineru-hide-force-ocr";const OFFICE_PREVIEW_NOTICE_STORAGE_KEY = "mineru.officePreviewNoticeIgnored";- const OPEN_DELAY_MS = 120;- const CLOSE_DELAY_MS = 280;- const ANIMATION_DELAY_MS = 140;const CLIPBOARD_MIME_EXTENSIONS = {"image/png": "png","image/jpeg": "jpg",@@ -95,59 +87,6 @@const refreshMineruCustomHtml = () => {localizeMineruCustomText();applyOfficePreviewNoticePreference();- refreshMineruOptionVisibility();- };-- // 兼容 Gradio 将 elem_classes 挂到按钮自身或按钮外层容器的两种 DOM 结构。- const findButton = () => document.querySelector(- "button.mineru-advanced-open, .mineru-advanced-open button, .mineru-advanced-open"- );- const findPopover = () => document.querySelector(".mineru-advanced-popover");- const findTierRoot = () => document.querySelector(".mineru-tier-select");- const findRemoteServerRoot = () => document.querySelector(".mineru-remote-server-toggle");- let openTimer = null;- let closeTimer = null;- let visibilityTimer = null;- let hoverHandlersInstalled = false;-- // 读取 Gradio tier 下拉框当前值;value 属性比可见文本更稳定。- const getTierValue = () => {- const tierRoot = findTierRoot();- const tierControl = tierRoot?.querySelector('[role="listbox"]');- return (tierControl?.value || tierControl?.textContent || "").trim();- };-- // 读取远端服务开关状态,缺失时按关闭处理以保持本地默认路径。- const getUseRemoteServer = () => {- const remoteServerRoot = findRemoteServerRoot();- const remoteServerControl = remoteServerRoot?.querySelector('input[type="checkbox"]');- return Boolean(remoteServerControl?.checked);- };-- // 根据当前 tier/远端开关刷新前端状态类,避免依赖 Gradio 重新挂载隐藏组件。- const refreshMineruOptionVisibility = () => {- const tier = getTierValue();- const useRemoteServer = getUseRemoteServer();- const showClientOptions = useRemoteServer;- const showImageAnalysis = false;- const showOcrLanguage = tier === "standard";- const hideForceOcr = !["standard", "pro"].includes(tier);-- document.body.classList.toggle(CLIENT_OPTIONS_VISIBLE_CLASS, showClientOptions);- document.body.classList.toggle(IMAGE_ANALYSIS_VISIBLE_CLASS, showImageAnalysis);- document.body.classList.toggle(OCR_LANGUAGE_VISIBLE_CLASS, showOcrLanguage);- document.body.classList.toggle(FORCE_OCR_HIDDEN_CLASS, hideForceOcr);- if (document.body.classList.contains(POPOVER_OPEN_CLASS)) {- positionPopover();- }- };-- // Gradio 控件会异步写回 value,延后一帧再读可以覆盖 Dropdown option 点击和控件切换。- const queueMineruOptionVisibilityRefresh = () => {- requestAnimationFrame(() => {- refreshMineruOptionVisibility();- requestAnimationFrame(refreshMineruOptionVisibility);- });};const findUploadFileInput = () => {@@ -279,216 +218,13 @@return assignClipboardFileToUpload(uploadInput, uploadFiles);};- // 修正 Gradio Dropdown 在 fixed 浮层里按视口定位导致的下拉列表漂移。- const positionAdvancedDropdowns = () => {- const popover = findPopover();- if (!popover || !document.body.classList.contains(POPOVER_OPEN_CLASS)) {- return;- }-- popover.querySelectorAll("ul.options").forEach((options) => {- const wrap = options.closest(".wrap");- if (!wrap) {- return;- }-- popover.querySelectorAll(".wrap").forEach((item) => {- item.style.removeProperty("z-index");- });-- const wrapRect = wrap.getBoundingClientRect();- const popoverRect = popover.getBoundingClientRect();- const viewportPadding = 12;- const gap = 6;- const belowSpace = Math.max(0, popoverRect.bottom - wrapRect.bottom - viewportPadding);- const aboveSpace = Math.max(0, wrapRect.top - popoverRect.top - viewportPadding);- const naturalHeight = Math.max(36, Math.min(options.scrollHeight || 220, 240));- const openBelow = belowSpace >= Math.min(180, naturalHeight) || belowSpace >= aboveSpace;- const availableHeight = Math.max(84, openBelow ? belowSpace : aboveSpace);- const height = Math.min(naturalHeight, availableHeight);- const top = openBelow ? wrap.offsetHeight + gap : -height - gap;-- wrap.style.setProperty("z-index", "1003", "important");- options.style.setProperty("position", "absolute", "important");- options.style.setProperty("left", "0", "important");- options.style.setProperty("top", `${top}px`, "important");- options.style.setProperty("bottom", "auto", "important");- options.style.setProperty("width", `${wrapRect.width}px`, "important");- options.style.setProperty("max-height", `${height}px`, "important");- options.style.setProperty("z-index", "1004", "important");- });- };-- // 只在真正支持鼠标悬浮的桌面环境启用 hover 浮窗,触屏设备继续使用点击兜底。- const supportsHoverPopover = () => (- typeof window.matchMedia === "function"- && window.matchMedia("(hover: hover) and (pointer: fine)").matches- );-- // 取消尚未执行的打开/关闭计时,避免鼠标在按钮和气泡之间移动时闪烁。- const cancelPopoverTimers = () => {- if (openTimer !== null) {- clearTimeout(openTimer);- openTimer = null;- }- if (closeTimer !== null) {- clearTimeout(closeTimer);- closeTimer = null;- }- if (visibilityTimer !== null) {- clearTimeout(visibilityTimer);- visibilityTimer = null;- }- };-- // 清理旧版 display 开关留下的内联样式,后续统一交给 CSS 的可见性和动画状态控制。- const clearLegacyPopoverDisplay = (popover) => {- if (popover) {- popover.style.removeProperty("display");- }- };-- // 用内联 important 同步动画属性,避免 Gradio 自动 scoped CSS 抬高隐藏规则优先级。- const applyOpenPopoverStyle = (popover) => {- if (!popover) {- return;- }- popover.style.setProperty("visibility", "visible", "important");- popover.style.setProperty("opacity", "1", "important");- popover.style.setProperty("pointer-events", "auto", "important");- popover.style.setProperty("transform", "translateY(0) scale(1)", "important");- };-- // 关闭时先取消交互并播放淡出,动画结束后再隐藏可见性。- const applyClosedPopoverStyle = (popover) => {- if (!popover) {- return;- }- popover.style.setProperty("opacity", "0", "important");- popover.style.setProperty("pointer-events", "none", "important");- popover.style.setProperty("transform", "translateY(-4px) scale(0.985)", "important");- visibilityTimer = window.setTimeout(() => {- if (!document.body.classList.contains(POPOVER_OPEN_CLASS)) {- popover.style.setProperty("visibility", "hidden", "important");- }- visibilityTimer = null;- }, ANIMATION_DELAY_MS);- };-- // 等待 Gradio 完成下拉列表挂载后,再按当前输入框位置校正。- const queueDropdownPosition = () => {- requestAnimationFrame(() => {- requestAnimationFrame(positionAdvancedDropdowns);- });- };-- // 根据高级选项按钮的位置,把气泡贴在左侧控制栏右侧并限制在视口内。- const positionPopover = () => {- const button = findButton();- const popover = findPopover();- if (!button || !popover) {- return;- }-- const buttonRect = button.getBoundingClientRect();- const preferredWidth = Math.min(420, window.innerWidth - 36);- const left = Math.min(- Math.max(18, buttonRect.right + 12),- Math.max(18, window.innerWidth - preferredWidth - 18)- );- const availableHeight = Math.max(260, window.innerHeight - 36);- const measuredHeight = Math.min(- popover.scrollHeight || 520,- availableHeight,- Math.round(window.innerHeight * 0.7)- );- const centeredTop = buttonRect.top + buttonRect.height / 2 - measuredHeight / 2;- const top = Math.min(- Math.max(18, centeredTop),- Math.max(18, window.innerHeight - measuredHeight - 18)- );-- popover.style.setProperty("--mineru-popover-left", `${left}px`);- popover.style.setProperty("--mineru-popover-top", `${top}px`);- };-- // 打开气泡时保持组件 DOM 挂载,只切换 body 状态类并重新计算位置。- const openPopover = () => {- const popover = findPopover();- cancelPopoverTimers();- clearLegacyPopoverDisplay(popover);- document.body.classList.add(POPOVER_OPEN_CLASS);- applyOpenPopoverStyle(popover);- requestAnimationFrame(() => {- positionPopover();- queueDropdownPosition();- });- };-- // 收起气泡时不卸载 Gradio 控件,用户已经修改的高级配置会保留在原组件上。- const closePopover = () => {- const popover = findPopover();- cancelPopoverTimers();- clearLegacyPopoverDisplay(popover);- document.body.classList.remove(POPOVER_OPEN_CLASS);- applyClosedPopoverStyle(popover);- };-- // 鼠标进入按钮后延迟打开,防止只是路过按钮时频繁弹出。- const scheduleHoverOpen = () => {- if (!supportsHoverPopover()) {- return;- }- cancelPopoverTimers();- openTimer = window.setTimeout(() => {- openTimer = null;- openPopover();- }, OPEN_DELAY_MS);- };-- // 鼠标离开按钮或气泡后延迟关闭,给用户从按钮移动到气泡留出缓冲时间。- const scheduleHoverClose = () => {- if (!supportsHoverPopover()) {- return;- }- cancelPopoverTimers();- closeTimer = window.setTimeout(() => {- closeTimer = null;- closePopover();- }, CLOSE_DELAY_MS);- };-- // 给真实桌面指针安装 hover 事件;如果 Gradio 稍后才挂载 DOM,就通过观察器重试。- const installHoverPopoverHandlers = () => {- if (hoverHandlersInstalled || !supportsHoverPopover()) {- return;- }- const button = findButton();- const popover = findPopover();- if (!button || !popover) {- return;- }- button.addEventListener("pointerenter", scheduleHoverOpen);- button.addEventListener("pointerleave", scheduleHoverClose);- button.addEventListener("mouseenter", scheduleHoverOpen);- button.addEventListener("mouseleave", scheduleHoverClose);- popover.addEventListener("pointerenter", cancelPopoverTimers);- popover.addEventListener("pointerleave", scheduleHoverClose);- popover.addEventListener("mouseenter", cancelPopoverTimers);- popover.addEventListener("mouseleave", scheduleHoverClose);- hoverHandlersInstalled = true;- };-refreshMineruCustomHtml();- installHoverPopoverHandlers();requestAnimationFrame(() => {refreshMineruCustomHtml();- installHoverPopoverHandlers();});if (typeof MutationObserver !== "undefined") {const uiObserver = new MutationObserver(() => {refreshMineruCustomHtml();- installHoverPopoverHandlers();});uiObserver.observe(document.body, { childList: true, subtree: true });}@@ -498,7 +234,6 @@if (!(target instanceof Element)) {return;}- queueMineruOptionVisibilityRefresh();if (target.closest(".office-preview-ignore-forever")) {const notice = target.closest(".office-preview-notice");if (setOfficePreviewNoticeIgnored()) {@@ -512,50 +247,6 @@target.closest(".office-preview-notice")?.classList.add("is-dismissed");return;}- if (target.closest(".mineru-advanced-open")) {- if (document.body.classList.contains(POPOVER_OPEN_CLASS)) {- closePopover();- } else {- openPopover();- }- return;- }- if (target.closest(".mineru-advanced-popover")) {- queueDropdownPosition();- }- if (!target.closest(".mineru-advanced-popover")) {- closePopover();- }- });-- document.addEventListener("focusin", (event) => {- const target = event.target;- if (target instanceof Element && target.closest(".mineru-advanced-popover")) {- queueDropdownPosition();- }- });-- document.addEventListener("input", (event) => {- const target = event.target;- queueMineruOptionVisibilityRefresh();- if (target instanceof Element && target.closest(".mineru-advanced-popover")) {- queueDropdownPosition();- }- });-- document.addEventListener("change", () => {- queueMineruOptionVisibilityRefresh();- });-- document.addEventListener("keydown", (event) => {- if (event.key === "Escape") {- closePopover();- return;- }- const target = event.target;- if (target instanceof Element && target.closest(".mineru-advanced-popover")) {- queueDropdownPosition();- }});document.addEventListener("paste", (event) => {@@ -563,11 +254,4 @@event.preventDefault();}});-- window.addEventListener("resize", () => {- if (document.body.classList.contains(POPOVER_OPEN_CLASS)) {- positionPopover();- positionAdvancedDropdowns();- }- });}diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex a3f7faaf..390914ae 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -572,32 +572,19 @@ def test_parse_rejects_removed_ch_lite_language(tmp_path: Path) -> None:assert "Language ch_lite not supported" in result.output-def test_gradio_language_option_only_visible_for_standard_tier() -> None:+def test_gradio_tier_selection_derives_v1_runtime() -> None:from mineru.cli_old import gradio_app- assert gradio_app.is_ocr_language_option_visible("standard") is True- assert gradio_app.is_ocr_language_option_visible("pro") is False- assert gradio_app.is_ocr_language_option_visible("flash") is False---def test_gradio_tier_remote_selection_derives_backend_and_effort() -> None:- from mineru.cli_old import gradio_app-- assert gradio_app.resolve_gradio_runtime_options("standard", False).as_kwargs() == {+ assert gradio_app.resolve_gradio_runtime_options("standard").as_kwargs() == {"tier": "standard","backend": "hybrid-engine","effort": "medium",}- assert gradio_app.resolve_gradio_runtime_options("pro", False).as_kwargs() == {+ assert gradio_app.resolve_gradio_runtime_options("pro").as_kwargs() == {"tier": "pro","backend": "hybrid-engine","effort": "high",}- assert gradio_app.resolve_gradio_runtime_options("pro", True).as_kwargs() == {- "tier": "pro",- "backend": "hybrid-http-client",- "effort": "high",- }def test_gradio_extracts_supported_tiers_from_v1_tiers_payload() -> None:@@ -812,43 +799,49 @@ def test_gradio_run_paths_are_absolute(tmp_path: Path) -> None:assert archive_zip_path.parent == run_root-def test_gradio_frontend_uses_tier_and_remote_server_visibility() -> None:+def test_gradio_frontend_uses_v1_only_tier_visibility() -> None:js_text = Path("mineru/resources/gradio_app.js").read_text(encoding="utf-8")- assert ".mineru-tier-select" in js_text- assert ".mineru-remote-server-toggle" in js_text+ assert ".mineru-remote-server-toggle" not in js_text+ assert ".mineru-advanced-popover" not in js_text+ assert "getUseRemoteServer" not in js_textassert "getBackendValue" not in js_textassert "getEffortValue" not in js_textassert ".mineru-backend-select" not in js_textassert ".mineru-hybrid-effort" not in js_textassert 'input[type="radio"]' not in js_text- assert "const showClientOptions = useRemoteServer;" in js_text- assert 'const showOcrLanguage = tier === "standard";' in js_text+ assert "mineru-show-client-options" not in js_text+ assert "mineru-show-image-analysis" not in js_text+ assert "mineru-show-ocr-language" not in js_text+ assert "mineru-hide-force-ocr" not in js_text-def test_gradio_tier_and_remote_server_options_replace_backend_effort_controls() -> None:- """校验 Gradio 公开控制面只暴露 tier 和是否使用远端 server。"""+def test_gradio_submit_inputs_are_v1_only() -> None:+ """校验 Gradio 公开控制面只保留 v1 API 支持的单次任务输入。"""gradio_text = Path("mineru/cli_old/gradio_app.py").read_text(encoding="utf-8")backend_block_idx = gradio_text.index('elem_classes=["mineru-backend-options-block"]')tier_idx = gradio_text.index("tier = gr.Dropdown(")- remote_idx = gradio_text.index("use_remote_server = gr.Checkbox(")- client_options_idx = gradio_text.index('elem_classes=["mineru-client-options"]')max_pages_idx = gradio_text.index("max_pages = gr.Slider(")- advanced_popover_idx = gradio_text.index('elem_classes=["mineru-advanced-popover"]')assert "backend = gr.Dropdown(" not in gradio_textassert "effort = gr.Dropdown(" not in gradio_textassert "effort = gr.Radio(" not in gradio_textassert "Hybrid effort" not in gradio_textassert "解析强度" not in gradio_text- assert "use_remote_server=use_remote_server" in gradio_text+ assert "use_remote_server = gr.Checkbox(" not in gradio_text+ assert "url = gr.Textbox(" not in gradio_text+ assert 'elem_classes=["mineru-client-options"]' not in gradio_text+ assert 'elem_classes=["mineru-advanced-popover"]' not in gradio_text+ assert "is_ocr = gr.Checkbox(" not in gradio_text+ assert "formula_enable = gr.Checkbox(" not in gradio_text+ assert "table_enable = gr.Checkbox(" not in gradio_text+ assert "image_analysis = gr.Checkbox(" not in gradio_text+ assert "language = gr.Dropdown(" not in gradio_text+ assert "use_remote_server=use_remote_server" not in gradio_textassert "tier=tier" in gradio_text- assert (- "inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, image_analysis, "- "tier, language, use_remote_server, url]"- ) in gradio_text- assert backend_block_idx < tier_idx < remote_idx < client_options_idx < max_pages_idx < advanced_popover_idx+ assert "inputs=[input_file, max_pages, tier]" in gradio_text+ assert backend_block_idx < tier_idx < max_pages_idxdef test_parse_forwards_flash_backend(monkeypatch: Any, tmp_path: Path) -> None: