Skip to content

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

feat: enhance error handling for max_concurrent_requests and normalize upload filenames

myhlolidfcd9e1b3ddc
diff --git a/mineru/cli/api_client.py b/mineru/cli/api_client.py
index eda9e9ee..cd2621d4 100644
--- a/mineru/cli/api_client.py
+++ b/mineru/cli/api_client.py
@@ -22,6 +22,8 @@ from loguru import logger
from mineru.cli.api_protocol import (
API_PROTOCOL_VERSION,
DEFAULT_MAX_CONCURRENT_REQUESTS,
+)
+from mineru.utils.config_reader import (
get_max_concurrent_requests as read_max_concurrent_requests,
)
@@ -206,13 +208,11 @@ def resolve_effective_max_concurrent_requests(
local_max: int,
server_max: int,
) -> int:
- if local_max > 0 and server_max > 0:
- return min(local_max, server_max)
- if local_max > 0:
- return local_max
- if server_max > 0:
- return server_max
- return 0
+ if local_max <= 0 or server_max <= 0:
+ raise ValueError(
+ "local_max and server_max must both be positive integers"
+ )
+ return min(local_max, server_max)
def response_detail(response: httpx.Response) -> str:
@@ -251,9 +251,9 @@ def validate_server_health_payload(payload: dict, base_url: str) -> ServerHealth
max_concurrent_requests = payload.get("max_concurrent_requests")
processing_window_size = payload.get("processing_window_size")
- if not isinstance(max_concurrent_requests, int):
+ if not isinstance(max_concurrent_requests, int) or max_concurrent_requests <= 0:
raise click.ClickException(
- f"MinerU API at {base_url} did not return a valid max_concurrent_requests"
+ f"MinerU API at {base_url} did not return a valid positive max_concurrent_requests"
)
if not isinstance(processing_window_size, int):
raise click.ClickException(
diff --git a/mineru/cli/api_protocol.py b/mineru/cli/api_protocol.py
index c59b57f6..f3af97a7 100644
--- a/mineru/cli/api_protocol.py
+++ b/mineru/cli/api_protocol.py
@@ -1,8 +1,3 @@
-from mineru.utils.config_reader import (
- get_max_concurrent_requests,
- get_processing_window_size,
-)
-
API_PROTOCOL_VERSION = 1
-DEFAULT_MAX_CONCURRENT_REQUESTS = get_max_concurrent_requests(default=3)
-DEFAULT_PROCESSING_WINDOW_SIZE = get_processing_window_size(default=64)
+DEFAULT_MAX_CONCURRENT_REQUESTS = 3
+DEFAULT_PROCESSING_WINDOW_SIZE = 64
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index 813f6d08..69e83529 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -16,6 +16,8 @@ from loguru import logger
from mineru.cli.api_protocol import (
DEFAULT_MAX_CONCURRENT_REQUESTS,
DEFAULT_PROCESSING_WINDOW_SIZE,
+)
+from mineru.utils.config_reader import (
get_max_concurrent_requests as read_max_concurrent_requests,
)
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
@@ -700,7 +702,7 @@ def safe_extract_zip(zip_path: Path, output_dir: Path) -> None:
def resolve_submit_concurrency(max_concurrent_requests: int, task_count: int) -> int:
if max_concurrent_requests <= 0:
- return max(1, task_count)
+ raise ValueError("max_concurrent_requests must be a positive integer")
return max(1, min(max_concurrent_requests, task_count))
diff --git a/mineru/cli/common.py b/mineru/cli/common.py
index 683521b6..48b546b7 100644
--- a/mineru/cli/common.py
+++ b/mineru/cli/common.py
@@ -62,6 +62,13 @@ def normalize_task_stem(stem: str, max_bytes: int = MAX_TASK_STEM_BYTES) -> str:
return truncate_to_utf8_bytes(stem, max_bytes)
+def normalize_upload_filename(upload_name: str) -> str:
+ sanitized_name = Path(upload_name).name
+ sanitized_path = Path(sanitized_name)
+ normalized_stem = normalize_task_stem(sanitized_path.stem)
+ return f"{normalized_stem}{sanitized_path.suffix}"
+
+
def build_task_stem_candidate(
stem: str,
suffix: str = "",
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py
index ab17c9b0..61768b9b 100644
--- a/mineru/cli/fast_api.py
+++ b/mineru/cli/fast_api.py
@@ -35,6 +35,7 @@ from mineru.cli.common import (
aio_do_parse,
do_parse,
image_suffixes,
+ normalize_upload_filename,
office_suffixes,
pdf_suffixes,
normalize_task_stem,
@@ -46,10 +47,13 @@ from mineru.cli.api_protocol import (
API_PROTOCOL_VERSION,
DEFAULT_MAX_CONCURRENT_REQUESTS,
DEFAULT_PROCESSING_WINDOW_SIZE,
- get_max_concurrent_requests as read_max_concurrent_requests,
)
from mineru.utils.cli_parser import arg_parse
-from mineru.utils.config_reader import get_device, get_processing_window_size
+from mineru.utils.config_reader import (
+ get_device,
+ get_max_concurrent_requests as read_max_concurrent_requests,
+ get_processing_window_size,
+)
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
from mineru.version import __version__
@@ -204,11 +208,8 @@ def create_app():
_configured_max_concurrent_requests = max_concurrent_requests
app.state.max_concurrent_requests = max_concurrent_requests
- if max_concurrent_requests > 0:
- _request_semaphore = asyncio.Semaphore(max_concurrent_requests)
- logger.info(f"Request concurrency limited to {max_concurrent_requests}")
- else:
- _request_semaphore = None
+ _request_semaphore = asyncio.Semaphore(max_concurrent_requests)
+ logger.info(f"Request concurrency limited to {max_concurrent_requests}")
app.add_middleware(GZipMiddleware, minimum_size=1000)
return app
@@ -749,10 +750,8 @@ async def save_upload_files(upload_dir: str, files: list[UploadFile]) -> list[St
for upload in files:
original_name = upload.filename or f"upload-{uuid.uuid4()}"
- sanitized_name = Path(original_name).name
- sanitized_path = Path(sanitized_name)
- normalized_stem = normalize_task_stem(sanitized_path.stem)
- filename = f"{normalized_stem}{sanitized_path.suffix}"
+ filename = normalize_upload_filename(original_name)
+ normalized_stem = normalize_task_stem(Path(filename).stem)
destination = build_upload_destination(upload_dir, filename)
try:
with open(destination, "wb") as handle:
diff --git a/mineru/cli/router.py b/mineru/cli/router.py
index f686936d..f081682a 100644
--- a/mineru/cli/router.py
+++ b/mineru/cli/router.py
@@ -7,7 +7,7 @@ import subprocess
import sys
import tempfile
import uuid
-from contextlib import asynccontextmanager, suppress
+from contextlib import ExitStack, asynccontextmanager, suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -35,6 +35,7 @@ from mineru.cli.api_client import (
response_detail,
)
from mineru.cli.api_protocol import API_PROTOCOL_VERSION
+from mineru.cli.common import normalize_upload_filename
from mineru.version import __version__
TASK_PENDING = "pending"
@@ -154,6 +155,14 @@ def resolve_connect_host(host: str) -> str:
def detect_visible_cuda_devices() -> list[str]:
+ configured_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES")
+ if configured_visible_devices is not None:
+ return [
+ item.strip()
+ for item in configured_visible_devices.split(",")
+ if item.strip()
+ ]
+
try:
import torch # type: ignore
except ImportError:
@@ -488,6 +497,41 @@ class WorkerPool:
for server in self.servers:
await self._refresh_server(server)
+ def _update_server_from_health_payload(
+ self,
+ server: WorkerState,
+ payload: dict[str, Any],
+ ) -> None:
+ protocol_version = payload.get("protocol_version")
+ if protocol_version != API_PROTOCOL_VERSION:
+ raise ValueError(
+ f"Unsupported protocol_version={protocol_version}, expected {API_PROTOCOL_VERSION}"
+ )
+
+ server.queued_tasks = int(payload.get("queued_tasks", 0))
+ server.processing_tasks = int(payload.get("processing_tasks", 0))
+ server.completed_tasks = int(payload.get("completed_tasks", 0))
+ server.failed_tasks = int(payload.get("failed_tasks", 0))
+ server.max_concurrent_requests = int(payload.get("max_concurrent_requests", 0))
+ if server.max_concurrent_requests <= 0:
+ raise ValueError("max_concurrent_requests must be a positive integer")
+ server.processing_window_size = max(
+ MIN_HEALTHY_PROCESSING_WINDOW_SIZE,
+ int(
+ payload.get(
+ "processing_window_size",
+ MIN_HEALTHY_PROCESSING_WINDOW_SIZE,
+ )
+ ),
+ )
+ server.healthy = payload.get("status") == "healthy"
+ server.last_error = (
+ None if server.healthy else json.dumps(payload, ensure_ascii=False)
+ )
+ server.consecutive_health_failures = (
+ 0 if server.healthy else server.consecutive_health_failures + 1
+ )
+
async def _refresh_server(self, server: WorkerState) -> None:
if server.local_server is not None:
if not server.local_server.is_running():
@@ -531,35 +575,14 @@ class WorkerPool:
return
payload = response.json()
- protocol_version = payload.get("protocol_version")
- if protocol_version != API_PROTOCOL_VERSION:
- server.healthy = False
- server.last_error = (
- f"Unsupported protocol_version={protocol_version}, expected {API_PROTOCOL_VERSION}"
- )
- server.consecutive_health_failures += 1
- return
-
try:
- server.queued_tasks = int(payload.get("queued_tasks", 0))
- server.processing_tasks = int(payload.get("processing_tasks", 0))
- server.completed_tasks = int(payload.get("completed_tasks", 0))
- server.failed_tasks = int(payload.get("failed_tasks", 0))
- server.max_concurrent_requests = max(0, int(payload.get("max_concurrent_requests", 0)))
- server.processing_window_size = max(
- MIN_HEALTHY_PROCESSING_WINDOW_SIZE,
- int(payload.get("processing_window_size", MIN_HEALTHY_PROCESSING_WINDOW_SIZE)),
- )
+ self._update_server_from_health_payload(server, payload)
except (TypeError, ValueError) as exc:
server.healthy = False
server.last_error = f"Invalid health payload: {exc}"
server.consecutive_health_failures += 1
return
- server.healthy = payload.get("status") == "healthy"
- server.last_error = None if server.healthy else json.dumps(payload, ensure_ascii=False)
- server.consecutive_health_failures = 0 if server.healthy else server.consecutive_health_failures + 1
-
async def _restart_local_server(self, server: WorkerState) -> None:
local_server = server.local_server
if local_server is None:
@@ -570,10 +593,8 @@ class WorkerPool:
response = await self.client.get(f"{server.base_url}{HEALTH_ENDPOINT}")
if response.status_code == 200:
payload = response.json()
- server.healthy = payload.get("status") == "healthy"
- server.last_error = None if server.healthy else json.dumps(payload, ensure_ascii=False)
server.last_checked_at = utc_now_iso()
- server.consecutive_health_failures = 0 if server.healthy else 1
+ self._update_server_from_health_payload(server, payload)
except Exception as exc:
server.healthy = False
server.last_error = str(exc)
@@ -828,7 +849,7 @@ async def stage_multipart_request(request: Request) -> MultipartPayload:
for key, value in form.multi_items():
if isinstance(value, StarletteUploadFile):
original_name = value.filename or f"upload-{uuid.uuid4()}"
- filename = Path(original_name).name
+ filename = normalize_upload_filename(original_name)
destination = build_upload_destination(temp_dir, filename)
with open(destination, "wb") as handle:
while True:
@@ -880,7 +901,10 @@ def submit_payload_to_upstream_sync(
base_url: str,
payload: MultipartPayload,
) -> dict[str, Any]:
- with httpx.Client(timeout=build_http_timeout(), follow_redirects=True) as client:
+ with ExitStack() as stack, httpx.Client(
+ timeout=build_http_timeout(),
+ follow_redirects=True,
+ ) as client:
multipart = [
(
field_name,
@@ -890,15 +914,15 @@ def submit_payload_to_upstream_sync(
]
multipart.extend(
[
- (
- upload.field_name,
(
- upload.upload_name,
- Path(upload.path).read_bytes(),
- upload.content_type,
- ),
- )
- for upload in payload.uploads
+ upload.field_name,
+ (
+ upload.upload_name,
+ stack.enter_context(open(upload.path, "rb")),
+ upload.content_type,
+ ),
+ )
+ for upload in payload.uploads
]
)
try:
diff --git a/mineru/utils/config_reader.py b/mineru/utils/config_reader.py
index 63e52d04..a04d882e 100644
--- a/mineru/utils/config_reader.py
+++ b/mineru/utils/config_reader.py
@@ -140,17 +140,26 @@ def get_processing_window_size(default: int = 64) -> int:
def get_max_concurrent_requests(default: int = 3) -> int:
+ if default <= 0:
+ raise ValueError(
+ f"default max_concurrent_requests must be a positive integer, got {default}"
+ )
value = os.getenv('MINERU_API_MAX_CONCURRENT_REQUESTS')
if value is None:
return default
try:
max_concurrent_requests = int(value)
- except ValueError:
- logger.warning(
- f"Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: {value}, use default {default}"
+ except ValueError as exc:
+ raise ValueError(
+ "Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: "
+ f"{value}. Expected a positive integer."
+ ) from exc
+ if max_concurrent_requests <= 0:
+ raise ValueError(
+ "Invalid MINERU_API_MAX_CONCURRENT_REQUESTS value: "
+ f"{value}. Expected a positive integer."
)
- return default
- return max(0, max_concurrent_requests)
+ return max_concurrent_requests
def get_latex_delimiter_config():