Skip to content

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

feat: refactor local API server initialization and enhance CLI argument parsing

myhlolia82ec6deacb0
diff --git a/mineru/cli/api_client.py b/mineru/cli/api_client.py
index cd2621d4..dfb68317 100644
--- a/mineru/cli/api_client.py
+++ b/mineru/cli/api_client.py
@@ -78,8 +78,9 @@ class LocalAPIServer:
if self.process is not None:
raise RuntimeError("Local API server is already running")
- port = find_free_port()
- self.base_url = f"http://127.0.0.1:{port}"
+ resolved_port = find_free_port()
+ remaining_cli_args = strip_local_api_network_args(self.extra_cli_args)
+ self.base_url = f"http://127.0.0.1:{resolved_port}"
env = os.environ.copy()
env["MINERU_API_OUTPUT_ROOT"] = str(self.output_root)
env["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(
@@ -95,8 +96,8 @@ class LocalAPIServer:
"--host",
"127.0.0.1",
"--port",
- str(port),
- *self.extra_cli_args,
+ str(resolved_port),
+ *remaining_cli_args,
]
self.process = subprocess.Popen(
command,
@@ -200,6 +201,42 @@ def find_free_port() -> int:
return int(sock.getsockname()[1])
+def strip_local_api_network_args(extra_cli_args: Sequence[str]) -> tuple[str, ...]:
+ remaining_args: list[str] = []
+ i = 0
+
+ while i < len(extra_cli_args):
+ arg = extra_cli_args[i]
+ if arg == "--host":
+ next_index = i + 1
+ if next_index < len(extra_cli_args) and not extra_cli_args[next_index].startswith("--"):
+ i += 2
+ else:
+ i += 1
+ continue
+
+ if arg == "--port":
+ next_index = i + 1
+ if next_index < len(extra_cli_args) and not extra_cli_args[next_index].startswith("--"):
+ i += 2
+ else:
+ i += 1
+ continue
+
+ if arg.startswith("--host="):
+ i += 1
+ continue
+
+ if arg.startswith("--port="):
+ i += 1
+ continue
+
+ remaining_args.append(arg)
+ i += 1
+
+ return tuple(remaining_args)
+
+
def normalize_base_url(url: str) -> str:
return url.rstrip("/")
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index 69e83529..0127c998 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -841,6 +841,7 @@ async def run_orchestrated_cli(
end_page_id: Optional[int],
formula_enable: bool,
table_enable: bool,
+ extra_cli_args: tuple[str, ...] = (),
) -> None:
if start_page_id < 0:
raise click.ClickException("--start must be greater than or equal to 0")
@@ -861,7 +862,7 @@ async def run_orchestrated_cli(
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as http_client:
try:
if api_url is None:
- local_server = LocalAPIServer()
+ local_server = LocalAPIServer(extra_cli_args=extra_cli_args)
base_url = local_server.start()
logger.info(f"Started local mineru-api at {base_url}")
server_health = await wait_for_local_api_ready(http_client, local_server)
@@ -943,7 +944,8 @@ async def run_orchestrated_cli(
_stderr_sink.set_renderer(None)
[email protected](context_settings=dict(ignore_unknown_options=True, allow_extra_args=True))
@click.version_option(__version__, "--version", "-v", help="display the version and exit")
@click.option(
"-p",
@@ -1080,6 +1082,7 @@ async def run_orchestrated_cli(
help="Enable table parsing. Default is True. ",
)
def main(
+ ctx: click.Context,
input_path: Path,
output_dir: Path,
api_url: Optional[str],
@@ -1105,6 +1108,7 @@ def main(
end_page_id=end_page_id,
formula_enable=formula_enable,
table_enable=table_enable,
+ extra_cli_args=tuple(ctx.args),
)
)
diff --git a/mineru/cli/router.py b/mineru/cli/router.py
index fa908b3e..869f3db3 100644
--- a/mineru/cli/router.py
+++ b/mineru/cli/router.py
@@ -32,6 +32,7 @@ from mineru.cli.api_client import (
build_http_timeout,
find_free_port,
normalize_base_url,
+ strip_local_api_network_args,
response_detail,
)
from mineru.cli.api_protocol import API_PROTOCOL_VERSION
@@ -309,8 +310,9 @@ class ManagedLocalServer:
output_root = Path(self.temp_dir.name) / "output"
output_root.mkdir(parents=True, exist_ok=True)
- port = find_free_port()
- self.base_url = f"http://{self.connect_host}:{port}"
+ resolved_port = find_free_port()
+ remaining_cli_args = strip_local_api_network_args(self.extra_cli_args)
+ self.base_url = f"http://{self.connect_host}:{resolved_port}"
env = os.environ.copy()
env["MINERU_API_OUTPUT_ROOT"] = str(output_root)
env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"
@@ -324,8 +326,8 @@ class ManagedLocalServer:
"--host",
self.worker_host,
"--port",
- str(port),
- *self.extra_cli_args,
+ str(resolved_port),
+ *remaining_cli_args,
]
self.process = subprocess.Popen(command, cwd=os.getcwd(), env=env)
diff --git a/mineru/utils/cli_parser.py b/mineru/utils/cli_parser.py
index d1b98166..7382b983 100644
--- a/mineru/utils/cli_parser.py
+++ b/mineru/utils/cli_parser.py
@@ -1,38 +1,55 @@
+from collections.abc import Sequence
+
import click
-def arg_parse(ctx: 'click.Context') -> dict:
- # 解析额外参数
+def _coerce_cli_value(raw_value: str) -> bool | float | int | str:
+ lowered = raw_value.lower()
+ if lowered == "true":
+ return True
+ if lowered == "false":
+ return False
+
+ try:
+ return int(raw_value)
+ except ValueError:
+ pass
+
+ try:
+ return float(raw_value)
+ except ValueError:
+ return raw_value
+
+
+def parse_unknown_args(args: Sequence[str]) -> dict:
+ """Parse unknown click args into keyword arguments."""
extra_kwargs = {}
i = 0
- while i < len(ctx.args):
- arg = ctx.args[i]
- if arg.startswith('--'):
- param_name = arg[2:].replace('-', '_') # 转换参数名格式
+ while i < len(args):
+ arg = args[i]
+ if not arg.startswith("--"):
+ i += 1
+ continue
+
+ raw_option = arg[2:]
+ if "=" in raw_option:
+ param_name, raw_value = raw_option.split("=", 1)
+ extra_kwargs[param_name.replace("-", "_")] = _coerce_cli_value(raw_value)
i += 1
- if i < len(ctx.args) and not ctx.args[i].startswith('--'):
- # 参数有值
- try:
- # 尝试转换为适当的类型
- if ctx.args[i].lower() == 'true':
- extra_kwargs[param_name] = True
- elif ctx.args[i].lower() == 'false':
- extra_kwargs[param_name] = False
- elif '.' in ctx.args[i]:
- try:
- extra_kwargs[param_name] = float(ctx.args[i])
- except ValueError:
- extra_kwargs[param_name] = ctx.args[i]
- else:
- try:
- extra_kwargs[param_name] = int(ctx.args[i])
- except ValueError:
- extra_kwargs[param_name] = ctx.args[i]
- except:
- extra_kwargs[param_name] = ctx.args[i]
- else:
- # 布尔型标志参数
- extra_kwargs[param_name] = True
- i -= 1
+ continue
+
+ param_name = raw_option.replace("-", "_")
+ next_index = i + 1
+ if next_index < len(args) and not args[next_index].startswith("--"):
+ extra_kwargs[param_name] = _coerce_cli_value(args[next_index])
+ i += 2
+ continue
+
+ extra_kwargs[param_name] = True
i += 1
- return extra_kwargs
\ No newline at end of file
+
+ return extra_kwargs
+
+
+def arg_parse(ctx: "click.Context") -> dict:
+ return parse_unknown_args(ctx.args)