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
fix(server): log directly accessible API documentation URLs
myhlolia81937846ebe
diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 4546618c..f9429668 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -23,6 +23,7 @@ from ..config import Config, ConfigSource, LogConfig, LogLevel, _mineru_home, gefrom ..errors import MineruError, error_response, http_status_forfrom ..utils.async_utils import drain_futurefrom ..utils.logger import configure_global_log_level+from ..utils.server import ServerWithDocsfrom ..utils.stdio import configure_standard_streamsfrom .endpoint import EndpointTransport, read_endpoint_file, remove_endpoint_file, uds_available, write_endpoint_filefrom .instance_lock import DoclibLockUnavailable, build_doclib_home_owned_message, doclib_home_lock@@ -566,7 +567,7 @@ def _run_server(cfg: Config, *, log_source: ConfigSource | Literal["provided"] =lifespan="on",timeout_keep_alive=cfg.doclib.tcp.timeout,)- server = uvicorn.Server(uv_config)+ server = ServerWithDocs(uv_config, docs_path="/api/docs", docs_require_auth=True)def request_shutdown() -> None:"""通过 Uvicorn 正常退出,确保 Windows 也会执行生命周期清理。"""diff --git a/mineru/kit/commands/file_parse_server.py b/mineru/kit/commands/file_parse_server.pyindex 78fcce8f..bd20d3b1 100644--- a/mineru/kit/commands/file_parse_server.py+++ b/mineru/kit/commands/file_parse_server.py@@ -7,6 +7,7 @@ from pathlib import Pathimport typerfrom ...utils.i18n import t+from ...utils.server import run_serverfrom ..errors import exit_with_message@@ -21,7 +22,6 @@ def file_parse_server_cmd(),) -> None:"""惰性加载包装应用,不启动本地解析模型或继承调用者的认证头。"""- import uvicornfrom filelock import Timeoutfrom ..file_parse import FileParseSettings, create_app@@ -31,7 +31,7 @@ def file_parse_server_cmd(except ValueError as exc:exit_with_message("invalid_request", str(exc))try:- uvicorn.run(create_app(settings), host=host, port=port)+ run_server(create_app(settings), host=host, port=port)except Timeout:exit_with_message("invalid_request", "Another file-parse-server is using this state directory")diff --git a/mineru/kit/router/cli.py b/mineru/kit/router/cli.pyindex eaa29a3f..88eb2cc3 100644--- a/mineru/kit/router/cli.py+++ b/mineru/kit/router/cli.py@@ -6,11 +6,11 @@ from __future__ import annotationsfrom typing import castimport typer-import uvicornfrom ...types import SERVER_TIERS, ServerTierfrom ...utils.i18n import tfrom ...utils.logger import configure_global_log_level+from ...utils.server import run_serverfrom ...utils.stdio import configure_standard_streamsfrom ..errors import exit_with_messagefrom .app import create_app@@ -73,7 +73,7 @@ def router_cmd(exit_with_message("invalid_request", str(exc))settings.apply_to_env()if reload:- uvicorn.run(+ run_server("mineru.kit.router.app:create_app_from_env",host=host,port=port,@@ -81,7 +81,7 @@ def router_cmd(factory=True,)return- uvicorn.run(create_app(settings), host=host, port=port, reload=False)+ run_server(create_app(settings), host=host, port=port, reload=False)def main() -> None:diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 725531e2..115ad7b0 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -56,6 +56,7 @@ from ..utils.async_utils import drain_future, run_syncfrom ..model.runtime.ownership import RuntimeOwner, runtime_ownerfrom ..model.vlm.errors import is_fatal_engine_errorfrom ..utils.logger import configure_global_log_level+from ..utils.server import ServerWithDocsfrom ..utils.stdio import configure_standard_streamsfrom ..version import __version__from . import parse_async@@ -2245,7 +2246,7 @@ def main(log_level=server_log_level,log_config=_build_server_log_config(server_log_level),)- server = uvicorn.Server(config)+ server = ServerWithDocs(config, docs_path="/docs" if application.openapi_url is not None else None)server_ref[0] = serverif shutdown_requested.is_set():server.should_exit = Truediff --git a/mineru/utils/server.py b/mineru/utils/server.pynew file mode 100644index 00000000..85db4cd1--- /dev/null+++ b/mineru/utils/server.py@@ -0,0 +1,75 @@+"""在 Uvicorn 成功监听后展示可直接访问的 API 文档地址。"""++from __future__ import annotations++import logging+import socket++import uvicorn+from starlette.types import ASGIApp+from uvicorn.main import STARTUP_FAILURE+from uvicorn.supervisors import ChangeReload, Multiprocess++logger = logging.getLogger("uvicorn.error")+++class ServerWithDocs(uvicorn.Server):+ """沿用 Uvicorn 生命周期,从实际监听端口生成浏览器文档链接。"""++ def __init__(self, config: uvicorn.Config, *, docs_path: str | None = "/docs", docs_require_auth: bool = False) -> None:+ """接收实际文档路径与认证要求,关闭文档时传入 None。"""+ super().__init__(config)+ self.docs_path = docs_path+ self.docs_require_auth = docs_require_auth++ async def startup(self, sockets: list[socket.socket] | None = None) -> None:+ """成功绑定后输出文档链接,通配监听地址转换为本机可访问地址。"""+ await super().startup(sockets=sockets)+ if not self.started or self.should_exit or self.docs_path is None:+ return+ scheme = "https" if self.config.is_ssl else "http"+ auth_note = " (requires Bearer authentication)" if self.docs_require_auth else ""+ for server in self.servers:+ for listener in server.sockets or ():+ if listener.family not in {socket.AF_INET, socket.AF_INET6}:+ continue+ host, port = listener.getsockname()[:2]+ host = {"0.0.0.0": "127.0.0.1", "::": "::1"}.get(host, host)+ authority = f"[{host}]" if ":" in host else host+ logger.info("API documentation available at %s://%s:%d%s%s", scheme, authority, port, self.docs_path, auth_note)+++def run_server(+ app: ASGIApp | str,+ *,+ host: str,+ port: int,+ reload: bool = False,+ factory: bool = False,+) -> None:+ """统一启动带文档提示的 API,保留 Uvicorn 的重载、多进程和正常中断处理。"""+ config = uvicorn.Config(app, host=host, port=port, reload=reload, factory=factory)+ if (config.reload or config.workers > 1) and not isinstance(app, str):+ logger.warning("You must pass the application as an import string to enable 'reload' or 'workers'.")+ raise SystemExit(1)+ server = ServerWithDocs(config)+ bound_socket: socket.socket | None = None+ try:+ if config.should_reload:+ bound_socket = config.bind_socket()+ ChangeReload(config, target=server.run, sockets=[bound_socket]).run()+ elif config.workers > 1:+ bound_socket = config.bind_socket()+ Multiprocess(config, target=server.run, sockets=[bound_socket]).run()+ else:+ server.run()+ except KeyboardInterrupt:+ pass+ finally:+ if bound_socket is not None:+ bound_socket.close()+ if not server.started and not config.should_reload and config.workers == 1:+ raise SystemExit(STARTUP_FAILURE)+++__all__ = ["ServerWithDocs", "run_server"]diff --git a/tests/unittest/test_api_server_logging.py b/tests/unittest/test_api_server_logging.pyindex 057ba6ae..26f073b2 100644--- a/tests/unittest/test_api_server_logging.py+++ b/tests/unittest/test_api_server_logging.py@@ -34,7 +34,7 @@ def _invoke_entrypoint(monkeypatch: pytest.MonkeyPatch, entrypoint: str, args: l@pytest.mark.parametrize("level", [None, "critical", "ERROR", "Warning", "info", "debug", "TRACE"])def test_log_level_reaches_server(monkeypatch: pytest.MonkeyPatch, entrypoint: str, level: str | None) -> None:"""显式 --log-level 只作用于服务配置,loguru 全局级别始终取全局配置,且不进入应用业务参数。"""- application = object()+ application = SimpleNamespace(openapi_url="/openapi.json")create_app = MagicMock(return_value=application)config = MagicMock(return_value=object())expected_server_level = (level or "debug").lower()@@ -45,7 +45,7 @@ def test_log_level_reaches_server(monkeypatch: pytest.MonkeyPatch, entrypoint: smonkeypatch.setattr(api_server, "configure_global_log_level", configure_global)monkeypatch.setattr(kit_api, "configure_global_log_level", MagicMock(return_value="debug"))monkeypatch.setattr(api_server.uvicorn, "Config", config)- monkeypatch.setattr(api_server.uvicorn, "Server", MagicMock(return_value=server))+ monkeypatch.setattr(api_server, "ServerWithDocs", MagicMock(return_value=server))monkeypatch.setattr(api_server.ManagedProcessControlWatcher, "from_environment", lambda callback: None)assert _invoke_entrypoint(monkeypatch, entrypoint, [] if level is None else ["--log-level", level]) == 0diff --git a/tests/unittest/test_api_server_shutdown.py b/tests/unittest/test_api_server_shutdown.pyindex 9ba068cf..4f498a16 100644--- a/tests/unittest/test_api_server_shutdown.py+++ b/tests/unittest/test_api_server_shutdown.py@@ -3,6 +3,7 @@from __future__ import annotationsimport os+import reimport signalimport subprocessimport sys@@ -12,6 +13,7 @@ from types import SimpleNamespacefrom unittest.mock import MagicMockimport pytest+import httpxfrom click.testing import CliRunnerfrom mineru.parser import api_server@@ -23,9 +25,9 @@ def test_server_run_closes_control_watcher(monkeypatch: pytest.MonkeyPatch, erro"""正常中断应成功退出,真实服务异常继续传播,所有路径均关闭托管控制通道。"""watcher = MagicMock()server = SimpleNamespace(run=MagicMock(side_effect=error), should_exit=False)- monkeypatch.setattr(api_server, "create_app", MagicMock(return_value=object()))+ monkeypatch.setattr(api_server, "create_app", MagicMock(return_value=SimpleNamespace(openapi_url="/openapi.json")))monkeypatch.setattr(api_server.uvicorn, "Config", MagicMock())- monkeypatch.setattr(api_server.uvicorn, "Server", MagicMock(return_value=server))+ monkeypatch.setattr(api_server, "ServerWithDocs", MagicMock(return_value=server))monkeypatch.setattr(api_server.ManagedProcessControlWatcher, "from_environment", lambda callback: watcher)result = CliRunner().invoke(api_server.main, ["--tier", "flash"])@@ -42,6 +44,7 @@ def test_server_run_closes_control_watcher(monkeypatch: pytest.MonkeyPatch, erro@pytest.mark.skipif(sys.platform == "win32", reason="Windows 不支持通过 send_signal 模拟终端 Ctrl+C")[email protected]("docs_enabled", [True, False])@pytest.mark.parametrize("entrypoint",[@@ -51,13 +54,18 @@ def test_server_run_closes_control_watcher(monkeypatch: pytest.MonkeyPatch, erro],ids=["module", "kit", "alias"],)-def test_api_server_sigint_exits_cleanly(tmp_path: Path, entrypoint: list[str]) -> None:- """启动真实服务并发送 SIGINT,确保 lifespan 完整关闭且不出现退出异常堆栈。"""+def test_api_server_sigint_exits_cleanly(tmp_path: Path, entrypoint: list[str], docs_enabled: bool) -> None:+ """验证文档日志中的链接可访问、关闭文档时隐藏链接,以及真实 SIGINT 正常退出。"""config_path = tmp_path / "config.yaml"config_path.write_text("{}\n", encoding="utf-8")env = os.environ.copy()env.pop(CONTROL_ENV, None)- env.update(MINERU_CONFIG=str(config_path), PYTHONUNBUFFERED="1", CI="1")+ env.update(+ MINERU_CONFIG=str(config_path),+ PYTHONUNBUFFERED="1",+ CI="1",+ MINERU_API_ENABLE_FASTAPI_DOCS=str(docs_enabled).lower(),+ )log_path = tmp_path / "server.log"with log_path.open("w", encoding="utf-8") as log:process = subprocess.Popen(@@ -82,13 +90,18 @@ def test_api_server_sigint_exits_cleanly(tmp_path: Path, entrypoint: list[str])deadline = time.monotonic() + 30while time.monotonic() < deadline:output = log_path.read_text(encoding="utf-8")- if "Uvicorn running on" in output:+ if ("API documentation available at" if docs_enabled else "Uvicorn running on") in output:breakassert process.poll() is None, outputtime.sleep(0.05)else:pytest.fail(f"API 服务未在预期时间内启动:\n{output}")+ if docs_enabled:+ match = re.search(r"API documentation available at (http://127\.0\.0\.1:\d+/docs)", output)+ assert match is not None, output+ assert httpx.get(match[1], timeout=5, trust_env=False).status_code == 200+process.send_signal(signal.SIGINT)process.wait(timeout=15)finally:@@ -100,5 +113,6 @@ def test_api_server_sigint_exits_cleanly(tmp_path: Path, entrypoint: list[str])assert "Application shutdown complete." in outputassert "Finished server process" in outputassert process.returncode == 0, output+ assert ("API documentation available at" in output) is docs_enabledfor marker in ("Traceback", "CancelledError", "KeyboardInterrupt", "Abort"):assert marker not in output, outputdiff --git a/tests/unittest/test_doclib_instance_lock.py b/tests/unittest/test_doclib_instance_lock.pyindex 4c1a074d..81b5e586 100644--- a/tests/unittest/test_doclib_instance_lock.py+++ b/tests/unittest/test_doclib_instance_lock.py@@ -110,7 +110,7 @@ def test_run_server_writes_owner_endpoint_before_binding_transport(monkeypatch:monkeypatch.setattr(doclib_app, "create_app", lambda cfg: app)monkeypatch.setattr(doclib_app.uvicorn, "Config", lambda *args, **kwargs: object())- monkeypatch.setattr(doclib_app.uvicorn, "Server", lambda cfg: object())+ monkeypatch.setattr(doclib_app, "ServerWithDocs", lambda cfg, **kwargs: object())def _write_endpoint(path: str, *, pid: int, server_id: str, transports: list[object]) -> None:writes.append({"path": path, "pid": pid, "server_id": server_id, "transports": transports})diff --git a/tests/unittest/test_doclib_lifespan.py b/tests/unittest/test_doclib_lifespan.pyindex f75e59ad..6f6d2cc1 100644--- a/tests/unittest/test_doclib_lifespan.py+++ b/tests/unittest/test_doclib_lifespan.py@@ -271,8 +271,10 @@ def test_host_shutdown_after_tier_change_cleans_managed_process(class Server:"""保留宿主与真实应用的组装路径,用受控循环替代网络服务等待。"""- def __init__(self, config: Any) -> None:+ def __init__(self, config: Any, *, docs_path: str, docs_require_auth: bool) -> None:"""保存标准入口传入的 ASGI 应用,等待停机回调设置退出标志。"""+ assert docs_path == "/api/docs"+ assert docs_require_authself.app = config.appself.should_exit = False@@ -294,7 +296,7 @@ def test_host_shutdown_after_tier_change_cleans_managed_process(assert state.health.managed_proc is Noneassert state.health.managed_control is None- monkeypatch.setattr(doclib_app.uvicorn, "Server", Server)+ monkeypatch.setattr(doclib_app, "ServerWithDocs", Server)doclib_app._run_server(cfg)assert start.call_count == (2 if complete_tier_restart else 1)assert [call.args[0] for call in stop.call_args_list if call.args[0] is not None] == processes[: start.call_count]diff --git a/tests/unittest/test_file_parse.py b/tests/unittest/test_file_parse.pyindex d5acae7b..e33c2914 100644--- a/tests/unittest/test_file_parse.py+++ b/tests/unittest/test_file_parse.py@@ -888,7 +888,7 @@ def test_cli_configuration_and_environment(tmp_path: Path, monkeypatch: pytest.Massert application.state.service.settings.api_url == "https://explicit.test/api"assert application.state.service.settings.api_key == "environment-key"- monkeypatch.setattr("uvicorn.run", run)+ monkeypatch.setattr("mineru.kit.commands.file_parse_server.run_server", run)monkeypatch.setenv("MINERU_API_URL", "https://environment.test")monkeypatch.setenv("MINERU_API_KEY", "environment-key")result = CliRunner().invoke(diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 52a1ba0f..1548c8a8 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -870,7 +870,7 @@ def test_router_uses_explicit_v1_worker_options_and_rejects_legacy_args(monkeypaseen["port"] = portseen["reload"] = reload- monkeypatch.setattr(router_cli.uvicorn, "run", _fake_run)+ monkeypatch.setattr(router_cli, "run_server", _fake_run)result = runner.invoke(app,@@ -921,7 +921,7 @@ def test_router_reload_uses_environment_factory(monkeypatch: pytest.MonkeyPatch)seen["target"] = targetseen.update(kwargs)- monkeypatch.setattr(router_cli.uvicorn, "run", _fake_run)+ monkeypatch.setattr(router_cli, "run_server", _fake_run)result = runner.invoke(app, ["router", "--reload", "--local-gpus", "none"])diff --git a/tests/unittest/test_router_admin.py b/tests/unittest/test_router_admin.pyindex d29326dd..4f90a37c 100644--- a/tests/unittest/test_router_admin.py+++ b/tests/unittest/test_router_admin.py@@ -616,7 +616,7 @@ def test_cli_admin_key_precedence_and_reload(monkeypatch: pytest.MonkeyPatch) ->seen.append(settings)assert kwargs["reload"] is True- monkeypatch.setattr(cli.uvicorn, "run", run)+ monkeypatch.setattr(cli, "run_server", run)runner = CliRunner()result = runner.invoke(cli_app, ["router", "--reload", "--local-gpus", "none"])assert result.exit_code == 0, result.outputdiff --git a/tests/unittest/test_server_docs_logging.py b/tests/unittest/test_server_docs_logging.pynew file mode 100644index 00000000..3b87aff1--- /dev/null+++ b/tests/unittest/test_server_docs_logging.py@@ -0,0 +1,96 @@+"""验证文档提示使用真实监听地址,并遵守启动结果和文档开关。"""++from __future__ import annotations++import asyncio+import logging+import socket++import httpx+import pytest+import uvicorn+from fastapi import FastAPI++from mineru.utils import server as server_utils+++ ("host", "expected_host"),+ [+ ("127.0.0.1", "127.0.0.1"),+ ("0.0.0.0", "127.0.0.1"),+ pytest.param("::1", "[::1]", marks=pytest.mark.skipif(not socket.has_ipv6, reason="系统未启用 IPv6")),+ pytest.param("::", "[::1]", marks=pytest.mark.skipif(not socket.has_ipv6, reason="系统未启用 IPv6")),+ ],+)[email protected](("docs_path", "requires_auth"), [("/docs", False), ("/api/docs", True)])+def test_docs_url_uses_bound_port_and_connectable_host(+ caplog: pytest.LogCaptureFixture,+ monkeypatch: pytest.MonkeyPatch,+ host: str,+ expected_host: str,+ docs_path: str,+ requires_auth: bool,+) -> None:+ """真实绑定随机端口,验证通配地址、IPv6、自定义文档路径和 HTTP 可达性。"""+ monkeypatch.setattr(server_utils, "logger", logging.getLogger("test_server_docs"))++ async def scenario() -> None:+ """启动实际 HTTP 监听并访问日志中的文档链接,最后执行完整关闭。"""+ config = uvicorn.Config(FastAPI(docs_url=docs_path), host=host, port=0, log_config=None)+ config.load()+ server = server_utils.ServerWithDocs(config, docs_path=docs_path, docs_require_auth=requires_auth)+ server.lifespan = config.lifespan_class(config)+ await server.startup()+ try:+ port = server.servers[0].sockets[0].getsockname()[1]+ docs_url = f"http://{expected_host}:{port}{docs_path}"+ assert f"API documentation available at {docs_url}" in caplog.text+ assert ("requires Bearer authentication" in caplog.text) is requires_auth+ async with httpx.AsyncClient(trust_env=False) as client:+ response = await client.get(docs_url)+ assert response.status_code == 200+ finally:+ await server.shutdown()++ with caplog.at_level(logging.INFO, logger="test_server_docs"):+ asyncio.run(scenario())+++def test_disabled_docs_have_no_startup_link(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch) -> None:+ """文档关闭后,成功监听也不打印无法访问的链接。"""+ monkeypatch.setattr(server_utils, "logger", logging.getLogger("test_server_docs"))++ async def scenario() -> None:+ """为关闭文档的应用建立真实监听,核对日志并回收资源。"""+ config = uvicorn.Config(FastAPI(docs_url=None, openapi_url=None), port=0, log_config=None)+ config.load()+ server = server_utils.ServerWithDocs(config, docs_path=None)+ server.lifespan = config.lifespan_class(config)+ await server.startup()+ await server.shutdown()++ with caplog.at_level(logging.INFO, logger="test_server_docs"):+ asyncio.run(scenario())+ assert "API documentation available at" not in caplog.text+++def test_failed_bind_has_no_docs_link(caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch) -> None:+ """端口被占用导致启动失败时,禁止提前打印成功访问提示。"""+ monkeypatch.setattr(server_utils, "logger", logging.getLogger("test_server_docs"))+ with socket.socket() as occupied:+ occupied.bind(("127.0.0.1", 0))+ occupied.listen()++ async def scenario() -> None:+ """让服务绑定已占用的端口,保留 Uvicorn 原有失败退出行为。"""+ config = uvicorn.Config(FastAPI(), port=occupied.getsockname()[1], log_config=None)+ config.load()+ server = server_utils.ServerWithDocs(config)+ server.lifespan = config.lifespan_class(config)+ with pytest.raises(SystemExit):+ await server.startup()++ with caplog.at_level(logging.INFO, logger="test_server_docs"):+ asyncio.run(scenario())+ assert "API documentation available at" not in caplog.text