Skip to content

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

feat: implement local API server and integrate API client for task submission and status management

myhloli3dc3e06324e3
diff --git a/mineru/cli/api_client.py b/mineru/cli/api_client.py
new file mode 100644
index 00000000..29b5b771
--- /dev/null
+++ b/mineru/cli/api_client.py
@@ -0,0 +1,503 @@
+import asyncio
+import atexit
+import json
+import mimetypes
+import os
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import zipfile
+from contextlib import ExitStack
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from typing import Callable, Optional, Sequence
+
+import click
+import httpx
+from loguru import logger
+
+from mineru.cli.api_protocol import (
+ API_PROTOCOL_VERSION,
+ DEFAULT_MAX_CONCURRENT_REQUESTS,
+ get_max_concurrent_requests as read_max_concurrent_requests,
+)
+
+HEALTH_ENDPOINT = "/health"
+TASKS_ENDPOINT = "/tasks"
+TASK_STATUS_POLL_INTERVAL_SECONDS = 1.0
+TASK_RESULT_TIMEOUT_SECONDS = 600
+LOCAL_API_STARTUP_TIMEOUT_SECONDS = 30
+LOCAL_API_CLEANUP_RETRIES = 8
+LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS = 0.25
+
+
+@dataclass(frozen=True)
+class UploadAsset:
+ path: Path
+ upload_name: str
+
+
+@dataclass(frozen=True)
+class ServerHealth:
+ base_url: str
+ max_concurrent_requests: int
+ processing_window_size: int
+
+
+@dataclass(frozen=True)
+class SubmitResponse:
+ task_id: str
+ status_url: str
+ result_url: str
+ file_names: tuple[str, ...] = ()
+
+
+class LocalAPIServer:
+ def __init__(self, extra_cli_args: Sequence[str] = ()):
+ self.temp_dir = tempfile.TemporaryDirectory(prefix="mineru-api-client-")
+ self.temp_root = Path(self.temp_dir.name)
+ self.output_root = self.temp_root / "output"
+ self.base_url: str | None = None
+ self.process: subprocess.Popen[bytes] | None = None
+ self._atexit_registered = False
+ self.extra_cli_args = tuple(extra_cli_args)
+
+ def start(self) -> str:
+ 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}"
+ env = os.environ.copy()
+ env["MINERU_API_OUTPUT_ROOT"] = str(self.output_root)
+ env["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(
+ read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS)
+ )
+ env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"
+ self.output_root.mkdir(parents=True, exist_ok=True)
+
+ command = [
+ sys.executable,
+ "-m",
+ "mineru.cli.fast_api",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(port),
+ *self.extra_cli_args,
+ ]
+ self.process = subprocess.Popen(
+ command,
+ cwd=os.getcwd(),
+ env=env,
+ )
+
+ if not self._atexit_registered:
+ atexit.register(self.stop)
+ self._atexit_registered = True
+ return self.base_url
+
+ def stop(self) -> None:
+ process = self.process
+ self.process = None
+ try:
+ if process is not None and process.poll() is None:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ finally:
+ if self._atexit_registered:
+ try:
+ atexit.unregister(self.stop)
+ except Exception:
+ pass
+ self._atexit_registered = False
+ self._cleanup_temp_dir()
+
+ def _cleanup_temp_dir(self) -> None:
+ last_error: Exception | None = None
+ for attempt in range(LOCAL_API_CLEANUP_RETRIES):
+ try:
+ self.temp_dir.cleanup()
+ return
+ except FileNotFoundError:
+ return
+ except Exception as exc:
+ last_error = exc
+ if attempt + 1 < LOCAL_API_CLEANUP_RETRIES:
+ time.sleep(LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS)
+
+ if last_error is not None:
+ logger.warning(
+ "Failed to clean up temporary MinerU API directory {}: {}. "
+ "You can remove it manually after processes release any open handles.",
+ self.temp_root,
+ last_error,
+ )
+
+
+class ReusableLocalAPIServer:
+ def __init__(self, extra_cli_args: Sequence[str] = ()):
+ self._lock = threading.Lock()
+ self._server: LocalAPIServer | None = None
+ self._extra_cli_args = tuple(extra_cli_args)
+
+ def configure(self, extra_cli_args: Sequence[str]) -> None:
+ with self._lock:
+ self._extra_cli_args = tuple(extra_cli_args)
+ server = self._server
+ if server is None:
+ return
+ if server.process is not None and server.process.poll() is None:
+ return
+ self._server = None
+
+ def ensure_started(self) -> tuple[LocalAPIServer, bool]:
+ with self._lock:
+ server = self._server
+ if server is not None and server.process is not None and server.process.poll() is None:
+ return server, False
+
+ if server is not None:
+ server.stop()
+
+ server = LocalAPIServer(extra_cli_args=self._extra_cli_args)
+ server.start()
+ self._server = server
+ return server, True
+
+ def stop(self) -> None:
+ with self._lock:
+ server = self._server
+ self._server = None
+ if server is not None:
+ server.stop()
+
+
+def build_http_timeout() -> httpx.Timeout:
+ return httpx.Timeout(connect=10, read=60, write=300, pool=30)
+
+
+def find_free_port() -> int:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind(("127.0.0.1", 0))
+ sock.listen(1)
+ return int(sock.getsockname()[1])
+
+
+def normalize_base_url(url: str) -> str:
+ return url.rstrip("/")
+
+
+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
+
+
+def response_detail(response: httpx.Response) -> str:
+ try:
+ payload = response.json()
+ except Exception:
+ text = response.text.strip()
+ return text or response.reason_phrase
+
+ if isinstance(payload, dict):
+ detail = payload.get("detail")
+ if isinstance(detail, str):
+ return detail
+ error = payload.get("error")
+ if isinstance(error, str):
+ return error
+ message = payload.get("message")
+ if isinstance(message, str):
+ return message
+ return json.dumps(payload, ensure_ascii=False)
+
+
+def validate_server_health_payload(payload: dict, base_url: str) -> ServerHealth:
+ status = payload.get("status")
+ if status != "healthy":
+ raise click.ClickException(
+ f"MinerU API at {base_url} is not healthy: {json.dumps(payload, ensure_ascii=False)}"
+ )
+
+ protocol_version = payload.get("protocol_version")
+ if protocol_version != API_PROTOCOL_VERSION:
+ raise click.ClickException(
+ f"MinerU API at {base_url} returned protocol_version={protocol_version}, "
+ f"expected {API_PROTOCOL_VERSION}"
+ )
+
+ max_concurrent_requests = payload.get("max_concurrent_requests")
+ processing_window_size = payload.get("processing_window_size")
+ if not isinstance(max_concurrent_requests, int):
+ raise click.ClickException(
+ f"MinerU API at {base_url} did not return a valid max_concurrent_requests"
+ )
+ if not isinstance(processing_window_size, int):
+ raise click.ClickException(
+ f"MinerU API at {base_url} did not return a valid processing_window_size"
+ )
+
+ return ServerHealth(
+ base_url=base_url,
+ max_concurrent_requests=max_concurrent_requests,
+ processing_window_size=max(1, processing_window_size),
+ )
+
+
+async def fetch_server_health(
+ client: httpx.AsyncClient,
+ base_url: str,
+) -> ServerHealth:
+ response = await client.get(f"{base_url}{HEALTH_ENDPOINT}")
+ if response.status_code != 200:
+ raise click.ClickException(
+ f"Failed to query MinerU API health from {base_url}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+ return validate_server_health_payload(response.json(), base_url)
+
+
+async def wait_for_local_api_ready(
+ client: httpx.AsyncClient,
+ local_server: LocalAPIServer,
+ timeout_seconds: float = LOCAL_API_STARTUP_TIMEOUT_SECONDS,
+) -> ServerHealth:
+ assert local_server.base_url is not None
+ deadline = asyncio.get_running_loop().time() + timeout_seconds
+ last_error: str | None = None
+
+ while asyncio.get_running_loop().time() < deadline:
+ process = local_server.process
+ if process is not None and process.poll() is not None:
+ raise click.ClickException(
+ "Local mineru-api exited before becoming healthy."
+ )
+ try:
+ return await fetch_server_health(client, local_server.base_url)
+ except click.ClickException as exc:
+ last_error = str(exc)
+ except httpx.HTTPError as exc:
+ last_error = str(exc)
+ await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
+
+ message = "Timed out waiting for local mineru-api to become healthy."
+ if last_error:
+ message = f"{message} {last_error}"
+ raise click.ClickException(message)
+
+
+def build_parse_request_form_data(
+ lang_list: Sequence[str],
+ backend: str,
+ parse_method: str,
+ formula_enable: bool,
+ table_enable: bool,
+ server_url: Optional[str],
+ start_page_id: int,
+ end_page_id: Optional[int],
+ *,
+ return_md: bool,
+ return_middle_json: bool,
+ return_model_output: bool,
+ return_content_list: bool,
+ return_images: bool,
+ response_format_zip: bool,
+ return_original_file: bool,
+) -> dict[str, str | list[str]]:
+ effective_lang_list = list(lang_list) or ["ch"]
+ data: dict[str, str | list[str]] = {
+ "lang_list": effective_lang_list,
+ "backend": backend,
+ "parse_method": parse_method,
+ "formula_enable": str(formula_enable).lower(),
+ "table_enable": str(table_enable).lower(),
+ "return_md": str(return_md).lower(),
+ "return_middle_json": str(return_middle_json).lower(),
+ "return_model_output": str(return_model_output).lower(),
+ "return_content_list": str(return_content_list).lower(),
+ "return_images": str(return_images).lower(),
+ "response_format_zip": str(response_format_zip).lower(),
+ "return_original_file": str(return_original_file).lower(),
+ "start_page_id": str(start_page_id),
+ "end_page_id": str(99999 if end_page_id is None else end_page_id),
+ }
+ if server_url:
+ data["server_url"] = server_url
+ return data
+
+
+async def submit_parse_task(
+ base_url: str,
+ upload_assets: Sequence[UploadAsset],
+ form_data: dict[str, str | list[str]],
+) -> SubmitResponse:
+ return await asyncio.to_thread(
+ submit_parse_task_sync,
+ base_url,
+ upload_assets,
+ form_data,
+ )
+
+
+def submit_parse_task_sync(
+ base_url: str,
+ upload_assets: Sequence[UploadAsset],
+ form_data: dict[str, str | list[str]],
+) -> SubmitResponse:
+ with httpx.Client(timeout=build_http_timeout(), follow_redirects=True) as sync_client:
+ with ExitStack() as stack:
+ files = []
+ for upload_asset in upload_assets:
+ mime_type = (
+ mimetypes.guess_type(upload_asset.upload_name)[0]
+ or "application/octet-stream"
+ )
+ file_handle = stack.enter_context(open(upload_asset.path, "rb"))
+ files.append(
+ (
+ "files",
+ (
+ upload_asset.upload_name,
+ file_handle,
+ mime_type,
+ ),
+ )
+ )
+
+ response = sync_client.post(
+ f"{base_url}{TASKS_ENDPOINT}",
+ data=form_data,
+ files=files,
+ )
+
+ if response.status_code != 202:
+ raise click.ClickException(
+ f"Failed to submit parsing task: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+
+ payload = response.json()
+ task_id = payload.get("task_id")
+ status_url = payload.get("status_url")
+ result_url = payload.get("result_url")
+ file_names = payload.get("file_names")
+ if (
+ not isinstance(task_id, str)
+ or not isinstance(status_url, str)
+ or not isinstance(result_url, str)
+ ):
+ raise click.ClickException("MinerU API returned an invalid task payload")
+
+ normalized_file_names: tuple[str, ...] = ()
+ if isinstance(file_names, list) and all(isinstance(name, str) for name in file_names):
+ normalized_file_names = tuple(file_names)
+
+ return SubmitResponse(
+ task_id=task_id,
+ status_url=status_url,
+ result_url=result_url,
+ file_names=normalized_file_names,
+ )
+
+
+async def wait_for_task_result(
+ client: httpx.AsyncClient,
+ submit_response: SubmitResponse,
+ task_label: str,
+ *,
+ status_callback: Optional[Callable[[str], None]] = None,
+ timeout_seconds: float = TASK_RESULT_TIMEOUT_SECONDS,
+) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout_seconds
+ while asyncio.get_running_loop().time() < deadline:
+ response = await client.get(submit_response.status_url)
+ if response.status_code != 200:
+ raise click.ClickException(
+ f"Failed to query task status for {task_label}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+
+ payload = response.json()
+ status = payload.get("status")
+ if status in {"pending", "processing"}:
+ if status_callback is not None:
+ status_callback(status)
+ await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
+ continue
+ if status == "completed":
+ return
+ raise click.ClickException(
+ f"Task {submit_response.task_id} failed for {task_label}: "
+ f"{json.dumps(payload, ensure_ascii=False)}"
+ )
+
+ raise click.ClickException(
+ f"Timed out waiting for result of task {submit_response.task_id} "
+ f"for {task_label}"
+ )
+
+
+async def download_result_zip(
+ client: httpx.AsyncClient,
+ submit_response: SubmitResponse,
+ task_label: str,
+) -> Path:
+ response = await client.get(submit_response.result_url)
+ if response.status_code != 200:
+ raise click.ClickException(
+ f"Failed to download result ZIP for task {submit_response.task_id}: "
+ f"{response.status_code} {response_detail(response)}"
+ )
+ content_type = response.headers.get("content-type", "")
+ if "application/zip" not in content_type:
+ raise click.ClickException(
+ f"Expected a ZIP result for {task_label}, "
+ f"got content-type={content_type or 'unknown'}"
+ )
+
+ zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_cli_result_")
+ os.close(zip_fd)
+ Path(zip_path).write_bytes(response.content)
+ return Path(zip_path)
+
+
+def safe_extract_zip(zip_path: Path, output_dir: Path) -> None:
+ output_dir.mkdir(parents=True, exist_ok=True)
+ output_root = output_dir.resolve()
+
+ with zipfile.ZipFile(zip_path, "r") as zip_file:
+ for member in zip_file.infolist():
+ member_path = PurePosixPath(member.filename)
+ if member_path.is_absolute() or ".." in member_path.parts:
+ raise click.ClickException(
+ f"Refusing to extract unsafe ZIP entry: {member.filename}"
+ )
+ target_path = (output_root / Path(*member_path.parts)).resolve()
+ if target_path != output_root and output_root not in target_path.parents:
+ raise click.ClickException(
+ f"Refusing to extract unsafe ZIP entry: {member.filename}"
+ )
+
+ if member.is_dir():
+ target_path.mkdir(parents=True, exist_ok=True)
+ continue
+
+ target_path.parent.mkdir(parents=True, exist_ok=True)
+ with zip_file.open(member, "r") as source, open(target_path, "wb") as handle:
+ handle.write(source.read())
diff --git a/mineru/cli/client.py b/mineru/cli/client.py
index b7fecd4d..3f5b1713 100644
--- a/mineru/cli/client.py
+++ b/mineru/cli/client.py
@@ -1,20 +1,12 @@
# Copyright (c) Opendatalab. All rights reserved.
import asyncio
-import atexit
import json
-import mimetypes
import os
-import socket
-import subprocess
import sys
-import tempfile
import threading
-import time
-import zipfile
from concurrent.futures import Future, ProcessPoolExecutor
-from contextlib import ExitStack
from dataclasses import dataclass
-from pathlib import Path, PurePosixPath
+from pathlib import Path
from typing import Awaitable, Callable, Optional, TextIO
import click
@@ -23,7 +15,6 @@ import pypdfium2 as pdfium
from loguru import logger
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,
@@ -36,15 +27,16 @@ from mineru.utils.pdfium_guard import (
open_pdfium_document,
)
-from ..version import __version__
-from .common import (
+from mineru.version import __version__
+from mineru.cli.common import (
image_suffixes,
office_suffixes,
pdf_suffixes,
uniquify_task_stems,
)
-from .output_paths import resolve_parse_dir
-from .visualization import (
+from mineru.cli import api_client as _api_client
+from mineru.cli.output_paths import resolve_parse_dir
+from mineru.cli.visualization import (
VisualizationJob,
run_visualization_job,
)
@@ -52,15 +44,6 @@ from .visualization import (
os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
-HEALTH_ENDPOINT = "/health"
-TASKS_ENDPOINT = "/tasks"
-TASK_STATUS_POLL_INTERVAL_SECONDS = 1.0
-TASK_RESULT_TIMEOUT_SECONDS = 600
-LOCAL_API_STARTUP_TIMEOUT_SECONDS = 30
-LOCAL_API_CLEANUP_RETRIES = 8
-LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS = 0.25
-
-
@dataclass(frozen=True)
class InputDocument:
path: Path
@@ -92,18 +75,9 @@ class VisualizationContext:
futures: list[Future]
-@dataclass(frozen=True)
-class ServerHealth:
- base_url: str
- max_concurrent_requests: int
- processing_window_size: int
-
-
-@dataclass(frozen=True)
-class SubmitResponse:
- task_id: str
- status_url: str
- result_url: str
+ServerHealth = _api_client.ServerHealth
+SubmitResponse = _api_client.SubmitResponse
+LocalAPIServer = _api_client.LocalAPIServer
@dataclass(frozen=True)
@@ -258,101 +232,14 @@ logger.add(_stderr_sink, level=log_level)
def build_http_timeout() -> httpx.Timeout:
- return httpx.Timeout(connect=10, read=60, write=300, pool=30)
-
-
-class LocalAPIServer:
- def __init__(self):
- self.temp_dir = tempfile.TemporaryDirectory(prefix="mineru-api-client-")
- self.temp_root = Path(self.temp_dir.name)
- self.output_root = self.temp_root / "output"
- self.base_url: str | None = None
- self.process: subprocess.Popen[bytes] | None = None
- self._atexit_registered = False
-
- def start(self) -> str:
- 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}"
- env = os.environ.copy()
- env["MINERU_API_OUTPUT_ROOT"] = str(self.output_root)
- env["MINERU_API_MAX_CONCURRENT_REQUESTS"] = str(
- read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS)
- )
- env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"
- self.output_root.mkdir(parents=True, exist_ok=True)
-
- self.process = subprocess.Popen(
- [
- sys.executable,
- "-m",
- "mineru.cli.fast_api",
- "--host",
- "127.0.0.1",
- "--port",
- str(port),
- ],
- cwd=os.getcwd(),
- env=env,
- )
-
- if not self._atexit_registered:
- atexit.register(self.stop)
- self._atexit_registered = True
- return self.base_url
-
- def stop(self) -> None:
- process = self.process
- self.process = None
- try:
- if process is not None and process.poll() is None:
- process.terminate()
- try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait(timeout=5)
- finally:
- if self._atexit_registered:
- try:
- atexit.unregister(self.stop)
- except Exception:
- pass
- self._atexit_registered = False
- self._cleanup_temp_dir()
-
- def _cleanup_temp_dir(self) -> None:
- last_error: Exception | None = None
- for attempt in range(LOCAL_API_CLEANUP_RETRIES):
- try:
- self.temp_dir.cleanup()
- return
- except FileNotFoundError:
- return
- except Exception as exc:
- last_error = exc
- if attempt + 1 < LOCAL_API_CLEANUP_RETRIES:
- time.sleep(LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS)
-
- if last_error is not None:
- logger.warning(
- "Failed to clean up temporary MinerU API directory {}: {}. "
- "You can remove it manually after processes release any open handles.",
- self.temp_root,
- last_error,
- )
+ return _api_client.build_http_timeout()
def find_free_port() -> int:
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
- sock.bind(("127.0.0.1", 0))
- sock.listen(1)
- return int(sock.getsockname()[1])
+ return _api_client.find_free_port()
def normalize_base_url(url: str) -> str:
- return url.rstrip("/")
+ return _api_client.normalize_base_url(url)
def format_task_label(task: PlannedTask) -> str:
@@ -526,97 +413,30 @@ async def wait_for_visualization_jobs(
def response_detail(response: httpx.Response) -> str:
- try:
- payload = response.json()
- except Exception:
- text = response.text.strip()
- return text or response.reason_phrase
-
- if isinstance(payload, dict):
- detail = payload.get("detail")
- if isinstance(detail, str):
- return detail
- error = payload.get("error")
- if isinstance(error, str):
- return error
- message = payload.get("message")
- if isinstance(message, str):
- return message
- return json.dumps(payload, ensure_ascii=False)
+ return _api_client.response_detail(response)
def validate_server_health_payload(payload: dict, base_url: str) -> ServerHealth:
- status = payload.get("status")
- if status != "healthy":
- raise click.ClickException(
- f"MinerU API at {base_url} is not healthy: {json.dumps(payload, ensure_ascii=False)}"
- )
-
- protocol_version = payload.get("protocol_version")
- if protocol_version != API_PROTOCOL_VERSION:
- raise click.ClickException(
- f"MinerU API at {base_url} returned protocol_version={protocol_version}, "
- f"expected {API_PROTOCOL_VERSION}"
- )
-
- max_concurrent_requests = payload.get("max_concurrent_requests")
- processing_window_size = payload.get("processing_window_size")
- if not isinstance(max_concurrent_requests, int):
- raise click.ClickException(
- f"MinerU API at {base_url} did not return a valid max_concurrent_requests"
- )
- if not isinstance(processing_window_size, int):
- raise click.ClickException(
- f"MinerU API at {base_url} did not return a valid processing_window_size"
- )
-
- return ServerHealth(
- base_url=base_url,
- max_concurrent_requests=max_concurrent_requests,
- processing_window_size=max(1, processing_window_size),
- )
+ return _api_client.validate_server_health_payload(payload, base_url)
async def fetch_server_health(
client: httpx.AsyncClient,
base_url: str,
) -> ServerHealth:
- response = await client.get(f"{base_url}{HEALTH_ENDPOINT}")
- if response.status_code != 200:
- raise click.ClickException(
- f"Failed to query MinerU API health from {base_url}: "
- f"{response.status_code} {response_detail(response)}"
- )
- return validate_server_health_payload(response.json(), base_url)
+ return await _api_client.fetch_server_health(client, base_url)
async def wait_for_local_api_ready(
client: httpx.AsyncClient,
local_server: LocalAPIServer,
- timeout_seconds: float = LOCAL_API_STARTUP_TIMEOUT_SECONDS,
+ timeout_seconds: float = _api_client.LOCAL_API_STARTUP_TIMEOUT_SECONDS,
) -> ServerHealth:
- assert local_server.base_url is not None
- deadline = asyncio.get_running_loop().time() + timeout_seconds
- last_error: str | None = None
-
- while asyncio.get_running_loop().time() < deadline:
- process = local_server.process
- if process is not None and process.poll() is not None:
- raise click.ClickException(
- "Local mineru-api exited before becoming healthy."
- )
- try:
- return await fetch_server_health(client, local_server.base_url)
- except click.ClickException as exc:
- last_error = str(exc)
- except httpx.HTTPError as exc:
- last_error = str(exc)
- await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
-
- message = "Timed out waiting for local mineru-api to become healthy."
- if last_error:
- message = f"{message} {last_error}"
- raise click.ClickException(message)
+ return await _api_client.wait_for_local_api_ready(
+ client,
+ local_server,
+ timeout_seconds=timeout_seconds,
+ )
def probe_pdf_effective_pages(
@@ -774,94 +594,68 @@ def build_request_form_data(
server_url: Optional[str],
start_page_id: int,
end_page_id: Optional[int],
-) -> dict[str, str]:
- data = {
- "lang_list": lang,
- "backend": backend,
- "parse_method": method,
- "formula_enable": str(formula_enable).lower(),
- "table_enable": str(table_enable).lower(),
- "return_md": "true",
- "return_middle_json": "true",
- "return_model_output": "true",
- "return_content_list": "true",
- "return_images": "true",
- "response_format_zip": "true",
- "return_original_file": "true",
- "start_page_id": str(start_page_id),
- "end_page_id": str(99999 if end_page_id is None else end_page_id),
- }
- if server_url:
- data["server_url"] = server_url
- return data
+) -> dict[str, str | list[str]]:
+ return _api_client.build_parse_request_form_data(
+ lang_list=[lang],
+ backend=backend,
+ parse_method=method,
+ formula_enable=formula_enable,
+ table_enable=table_enable,
+ server_url=server_url,
+ start_page_id=start_page_id,
+ end_page_id=end_page_id,
+ return_md=True,
+ return_middle_json=True,
+ return_model_output=True,
+ return_content_list=True,
+ return_images=True,
+ response_format_zip=True,
+ return_original_file=True,
+ )
async def submit_task(
client: httpx.AsyncClient,
base_url: str,
planned_task: PlannedTask,
- form_data: dict[str, str],
+ form_data: dict[str, str | list[str]],
) -> SubmitResponse:
- return await asyncio.to_thread(
- submit_task_sync,
- base_url,
- planned_task,
- form_data,
+ del client
+ upload_assets = [
+ _api_client.UploadAsset(
+ path=document.path,
+ upload_name=f"{document.stem}{document.path.suffix}",
+ )
+ for document in planned_task.documents
+ ]
+ return await _api_client.submit_parse_task(
+ base_url=base_url,
+ upload_assets=upload_assets,
+ form_data=form_data,
)
def submit_task_sync(
base_url: str,
planned_task: PlannedTask,
- form_data: dict[str, str],
+ form_data: dict[str, str | list[str]],
) -> SubmitResponse:
- with httpx.Client(timeout=build_http_timeout(), follow_redirects=True) as sync_client:
- with ExitStack() as stack:
- files = []
- for document in planned_task.documents:
- mime_type = mimetypes.guess_type(document.path.name)[0] or "application/octet-stream"
- file_handle = stack.enter_context(open(document.path, "rb"))
- upload_filename = f"{document.stem}{document.path.suffix}"
- files.append(
- (
- "files",
- (
- upload_filename,
- file_handle,
- mime_type,
- ),
- )
+ try:
+ return _api_client.submit_parse_task_sync(
+ base_url=base_url,
+ upload_assets=[
+ _api_client.UploadAsset(
+ path=document.path,
+ upload_name=f"{document.stem}{document.path.suffix}",
)
-
- response = sync_client.post(
- f"{base_url}{TASKS_ENDPOINT}",
- data=form_data,
- files=files,
- )
-
- if response.status_code != 202:
- raise click.ClickException(
- f"Failed to submit {format_task_label(planned_task)}: "
- f"{response.status_code} {response_detail(response)}"
+ for document in planned_task.documents
+ ],
+ form_data=form_data,
)
-
- payload = response.json()
- task_id = payload.get("task_id")
- status_url = payload.get("status_url")
- result_url = payload.get("result_url")
- if (
- not isinstance(task_id, str)
- or not isinstance(status_url, str)
- or not isinstance(result_url, str)
- ):
+ except click.ClickException as exc:
raise click.ClickException(
- f"MinerU API returned an invalid task payload for {format_task_label(planned_task)}"
- )
- return SubmitResponse(
- task_id=task_id,
- status_url=status_url,
- result_url=result_url,
- )
+ f"Failed to submit {format_task_label(planned_task)}: {exc}"
+ ) from exc
async def wait_for_task_result(
@@ -869,34 +663,18 @@ async def wait_for_task_result(
submit_response: SubmitResponse,
planned_task: PlannedTask,
live_renderer: Optional[LiveTaskStatusRenderer] = None,
- timeout_seconds: float = TASK_RESULT_TIMEOUT_SECONDS,
+ timeout_seconds: float = _api_client.TASK_RESULT_TIMEOUT_SECONDS,
) -> None:
- deadline = asyncio.get_running_loop().time() + timeout_seconds
- while asyncio.get_running_loop().time() < deadline:
- response = await client.get(submit_response.status_url)
- if response.status_code != 200:
- raise click.ClickException(
- f"Failed to query task status for {format_task_label(planned_task)}: "
- f"{response.status_code} {response_detail(response)}"
- )
-
- payload = response.json()
- status = payload.get("status")
- if status in {"pending", "processing"}:
- if live_renderer is not None:
- live_renderer.update_status(submit_response.task_id, status)
- await asyncio.sleep(TASK_STATUS_POLL_INTERVAL_SECONDS)
- continue
- if status == "completed":
- return
- raise click.ClickException(
- f"Task {submit_response.task_id} failed for {format_task_label(planned_task)}: "
- f"{json.dumps(payload, ensure_ascii=False)}"
- )
-
- raise click.ClickException(
- f"Timed out waiting for result of task {submit_response.task_id} "
- f"for {format_task_label(planned_task)}"
+ return await _api_client.wait_for_task_result(
+ client=client,
+ submit_response=submit_response,
+ task_label=format_task_label(planned_task),
+ status_callback=(
+ None
+ if live_renderer is None
+ else lambda status: live_renderer.update_status(submit_response.task_id, status)
+ ),
+ timeout_seconds=timeout_seconds,
)
@@ -905,49 +683,15 @@ async def download_result_zip(
submit_response: SubmitResponse,
planned_task: PlannedTask,
) -> Path:
- response = await client.get(submit_response.result_url)
- if response.status_code != 200:
- raise click.ClickException(
- f"Failed to download result ZIP for task {submit_response.task_id}: "
- f"{response.status_code} {response_detail(response)}"
- )
- content_type = response.headers.get("content-type", "")
- if "application/zip" not in content_type:
- raise click.ClickException(
- f"Expected a ZIP result for {format_task_label(planned_task)}, "
- f"got content-type={content_type or 'unknown'}"
- )
-
- zip_fd, zip_path = tempfile.mkstemp(suffix=".zip", prefix="mineru_cli_result_")
- os.close(zip_fd)
- Path(zip_path).write_bytes(response.content)
- return Path(zip_path)
+ return await _api_client.download_result_zip(
+ client=client,
+ submit_response=submit_response,
+ task_label=format_task_label(planned_task),
+ )
def safe_extract_zip(zip_path: Path, output_dir: Path) -> None:
- output_dir.mkdir(parents=True, exist_ok=True)
- output_root = output_dir.resolve()
-
- with zipfile.ZipFile(zip_path, "r") as zip_file:
- for member in zip_file.infolist():
- member_path = PurePosixPath(member.filename)
- if member_path.is_absolute() or ".." in member_path.parts:
- raise click.ClickException(
- f"Refusing to extract unsafe ZIP entry: {member.filename}"
- )
- target_path = (output_root / Path(*member_path.parts)).resolve()
- if target_path != output_root and output_root not in target_path.parents:
- raise click.ClickException(
- f"Refusing to extract unsafe ZIP entry: {member.filename}"
- )
-
- if member.is_dir():
- target_path.mkdir(parents=True, exist_ok=True)
- continue
-
- target_path.parent.mkdir(parents=True, exist_ok=True)
- with zip_file.open(member, "r") as source, open(target_path, "wb") as handle:
- handle.write(source.read())
+ _api_client.safe_extract_zip(zip_path, output_dir)
def resolve_submit_concurrency(max_concurrent_requests: int, task_count: int) -> int:
@@ -960,13 +704,10 @@ 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
+ return _api_client.resolve_effective_max_concurrent_requests(
+ local_max=local_max,
+ server_max=server_max,
+ )
async def execute_planned_tasks(
diff --git a/mineru/cli/gradio_app.py b/mineru/cli/gradio_app.py
index 7cad3bdc..1dbce0a8 100644
--- a/mineru/cli/gradio_app.py
+++ b/mineru/cli/gradio_app.py
@@ -1,11 +1,16 @@
# Copyright (c) Opendatalab. All rights reserved.
import base64
+import asyncio
+import httpx
import os
import re
import sys
+import threading
import time
+import uuid
import zipfile
+from contextlib import asynccontextmanager
from pathlib import Path
import click
@@ -22,55 +27,50 @@ log_level = os.getenv("MINERU_LOG_LEVEL", "INFO").upper()
logger.remove() # 移除默认handler
logger.add(sys.stderr, level=log_level) # 添加新handler
-from mineru.cli.common import prepare_env, read_fn, aio_do_parse, pdf_suffixes, image_suffixes, office_suffixes, docx_suffixes
-from mineru.utils.cli_parser import arg_parse
-from mineru.utils.engine_utils import get_vlm_engine
-from mineru.utils.hash_utils import str_sha256
+from mineru.cli.common import (
+ docx_suffixes,
+ image_suffixes,
+ office_suffixes,
+ pdf_suffixes,
+ read_fn,
+)
+from mineru.cli import api_client as _api_client
+from mineru.cli.output_paths import resolve_parse_dir
+from mineru.cli.visualization import VisualizationJob, run_visualization_job
+_gradio_local_api_server = _api_client.ReusableLocalAPIServer()
-async def parse_pdf(doc_path, output_dir, end_page_id, is_ocr, formula_enable, table_enable, language, backend, url):
- os.makedirs(output_dir, exist_ok=True)
- try:
- file_name = f'{safe_stem(Path(doc_path).stem)}_{time.strftime("%y%m%d_%H%M%S")}'
- pdf_data = read_fn(doc_path)
-
- # 检测 office 文件类型
- file_suffix = Path(doc_path).suffix.lower().lstrip('.')
- if file_suffix in office_suffixes:
- # office 文件使用固定的 env_name,parse_method 设为默认值(aio_do_parse 内部会处理)
- env_name = "office"
- parse_method = "auto"
- elif backend.startswith("vlm"):
- # 根据 backend 确定 parse_method
- parse_method = "vlm"
- env_name = parse_method
- else:
- parse_method = 'ocr' if is_ocr else 'auto'
- # 根据 backend 类型准备环境目录
- if backend.startswith("hybrid"):
- env_name = f"hybrid_{parse_method}"
- else:
- env_name = parse_method
-
- local_image_dir, local_md_dir = prepare_env(output_dir, file_name, env_name)
-
- await aio_do_parse(
- output_dir=output_dir,
- pdf_file_names=[file_name],
- pdf_bytes_list=[pdf_data],
- p_lang_list=[language],
- parse_method=parse_method,
- end_page_id=end_page_id,
- formula_enable=formula_enable,
- table_enable=table_enable,
- backend=backend,
- server_url=url,
- )
- return local_md_dir, file_name
- except Exception as e:
- logger.exception(e)
- return None
+class GradioRequestConcurrencyLimiter:
+ def __init__(self):
+ self._lock = threading.Lock()
+ self._semaphores: dict[int, asyncio.Semaphore] = {}
+
+ def _get_semaphore(self, limit: int):
+ if limit <= 0:
+ return None
+ with self._lock:
+ semaphore = self._semaphores.get(limit)
+ if semaphore is None:
+ semaphore = asyncio.Semaphore(limit)
+ self._semaphores[limit] = semaphore
+ return semaphore
+
+ @asynccontextmanager
+ async def acquire(self, limit: int):
+ semaphore = self._get_semaphore(limit)
+ if semaphore is None:
+ yield
+ return
+
+ await semaphore.acquire()
+ try:
+ yield
+ finally:
+ semaphore.release()
+
+
+_gradio_request_concurrency_limiter = GradioRequestConcurrencyLimiter()
def compress_directory_to_zip(directory_path, output_zip_path):
@@ -148,37 +148,211 @@ def replace_image_with_base64(markdown_text, image_dir_path):
async def to_markdown(file_path, end_pages=10, is_ocr=False, formula_enable=True, table_enable=True, language="ch", backend="pipeline", url=None):
- # 如果language包含(),则提取括号前的内容作为实际语言
+ return await _to_markdown_impl(
+ file_path=file_path,
+ end_pages=end_pages,
+ is_ocr=is_ocr,
+ formula_enable=formula_enable,
+ table_enable=table_enable,
+ language=language,
+ backend=backend,
+ url=url,
+ )
+
+
+def normalize_language(language):
if '(' in language and ')' in language:
- language = language.split('(')[0].strip()
+ return language.split('(')[0].strip()
+ return language
- # office 文件不需要转换为 PDF,直接使用原始文件路径
+
+def resolve_parse_method(file_path, is_ocr, backend):
file_suffix = Path(file_path).suffix.lower().lstrip('.')
- is_office = file_suffix in office_suffixes
- if is_office:
- parse_file_path = file_path
- else:
- parse_file_path = to_pdf(file_path)
+ if file_suffix in office_suffixes:
+ return "auto"
+ if backend.startswith("vlm"):
+ return "auto"
+ return "ocr" if is_ocr else "auto"
+
+
+def create_gradio_run_paths(file_path, output_root="./output"):
+ run_id = f"{time.strftime('%y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}_{safe_stem(Path(file_path).stem)}"
+ run_root = Path(output_root) / "gradio" / run_id
+ extract_root = run_root / "result"
+ archive_zip_path = run_root / f"{safe_stem(Path(file_path).stem)}.zip"
+ return run_root, extract_root, archive_zip_path
+
+
+def resolve_result_file_name(submit_response, extract_root, file_path):
+ if submit_response.file_names:
+ return submit_response.file_names[0]
+
+ candidate_dirs = sorted(path.name for path in Path(extract_root).iterdir() if path.is_dir())
+ if len(candidate_dirs) == 1:
+ return candidate_dirs[0]
+ return Path(file_path).stem
+
+
+async def resolve_server_health(http_client, api_url):
+ if api_url:
+ return await _api_client.fetch_server_health(
+ http_client,
+ _api_client.normalize_base_url(api_url),
+ )
+
+ local_server, started_now = _gradio_local_api_server.ensure_started()
+ if started_now:
+ logger.info(f"Started local mineru-api at {local_server.base_url}")
+ return await _api_client.wait_for_local_api_ready(http_client, local_server)
+
+
+def resolve_gradio_max_concurrent_requests(api_url, server_health):
+ if api_url is None:
+ return server_health.max_concurrent_requests
+
+ return _api_client.resolve_effective_max_concurrent_requests(
+ local_max=_api_client.read_max_concurrent_requests(
+ default=_api_client.DEFAULT_MAX_CONCURRENT_REQUESTS
+ ),
+ server_max=server_health.max_concurrent_requests,
+ )
+
+
+def maybe_generate_local_preview(extract_root, file_name, file_suffix, backend, parse_method):
+ if file_suffix in office_suffixes:
+ return None
+
+ parse_dir = resolve_parse_dir(
+ extract_root,
+ file_name,
+ backend,
+ parse_method,
+ allow_office_fallback=True,
+ )
+ visualization_job = VisualizationJob(
+ document_stem=file_name,
+ backend=backend,
+ parse_method=parse_method,
+ parse_dir=parse_dir,
+ draw_span=backend.startswith("pipeline"),
+ )
+ result = run_visualization_job(visualization_job)
+ if result.status != "finished":
+ logger.warning(
+ f"Skipping visualization for {visualization_job.document_stem}: {result.message}"
+ )
+ return resolve_preview_pdf_path(parse_dir, file_name)
+
+
+async def _to_markdown_impl(
+ file_path,
+ end_pages=10,
+ is_ocr=False,
+ formula_enable=True,
+ table_enable=True,
+ language="ch",
+ backend="pipeline",
+ url=None,
+ api_url=None,
+):
+ if file_path is None:
+ return "", "", None, None
+
+ normalized_language = normalize_language(language)
+ file_path = str(file_path)
+ file_suffix = Path(file_path).suffix.lower().lstrip('.')
+ parse_method = resolve_parse_method(file_path, is_ocr, backend)
+ run_root, extract_root, archive_zip_path = create_gradio_run_paths(file_path)
+ run_root.mkdir(parents=True, exist_ok=True)
+
+ form_data = _api_client.build_parse_request_form_data(
+ lang_list=[normalized_language],
+ backend=backend,
+ parse_method=parse_method,
+ formula_enable=formula_enable,
+ table_enable=table_enable,
+ server_url=url,
+ start_page_id=0,
+ end_page_id=end_pages - 1,
+ return_md=True,
+ return_middle_json=True,
+ return_model_output=True,
+ return_content_list=True,
+ return_images=True,
+ response_format_zip=True,
+ return_original_file=True,
+ )
+ upload_assets = [
+ _api_client.UploadAsset(
+ path=Path(file_path),
+ upload_name=Path(file_path).name,
+ )
+ ]
+
+ async with httpx.AsyncClient(
+ timeout=_api_client.build_http_timeout(),
+ follow_redirects=True,
+ ) as http_client:
+ server_health = await resolve_server_health(http_client, api_url)
+ effective_max_concurrent_requests = resolve_gradio_max_concurrent_requests(
+ api_url=api_url,
+ server_health=server_health,
+ )
+ async with _gradio_request_concurrency_limiter.acquire(
+ effective_max_concurrent_requests
+ ):
+ submit_response = await _api_client.submit_parse_task(
+ base_url=server_health.base_url,
+ upload_assets=upload_assets,
+ form_data=form_data,
+ )
+ await _api_client.wait_for_task_result(
+ client=http_client,
+ submit_response=submit_response,
+ task_label=Path(file_path).name,
+ )
+ result_zip_path = await _api_client.download_result_zip(
+ client=http_client,
+ submit_response=submit_response,
+ task_label=Path(file_path).name,
+ )
+
+ try:
+ _api_client.safe_extract_zip(result_zip_path, extract_root)
+ finally:
+ result_zip_path.unlink(missing_ok=True)
+
+ file_name = resolve_result_file_name(submit_response, extract_root, file_path)
+ local_md_dir = resolve_parse_dir(
+ extract_root,
+ file_name,
+ backend,
+ parse_method,
+ allow_office_fallback=True,
+ )
+ preview_pdf_path = maybe_generate_local_preview(
+ extract_root=extract_root,
+ file_name=file_name,
+ file_suffix=file_suffix,
+ backend=backend,
+ parse_method=parse_method,
+ )
- # 获取识别的md文件以及压缩包文件路径
- local_md_dir, file_name = await parse_pdf(parse_file_path, './output', end_pages - 1, is_ocr, formula_enable, table_enable, language, backend, url)
- archive_zip_path = os.path.join('./output', str_sha256(local_md_dir) + '.zip')
zip_archive_success = compress_directory_to_zip(local_md_dir, archive_zip_path)
if zip_archive_success == 0:
logger.info('Compression successful')
else:
logger.error('Compression failed')
- md_path = os.path.join(local_md_dir, file_name + '.md')
+
+ md_path = Path(local_md_dir) / f"{file_name}.md"
with open(md_path, 'r', encoding='utf-8') as f:
txt_content = f.read()
md_content = replace_image_with_base64(txt_content, local_md_dir)
- # office 文件没有 layout PDF,返回 None;其他格式返回转换后的 PDF 路径
- if is_office:
- new_pdf_path = None
- else:
- new_pdf_path = resolve_preview_pdf_path(local_md_dir, file_name)
- return md_content, txt_content, archive_zip_path, new_pdf_path
+ if file_suffix in office_suffixes:
+ preview_pdf_path = None
+
+ return md_content, txt_content, str(archive_zip_path), preview_pdf_path
def resolve_preview_pdf_path(local_md_dir, file_name):
@@ -376,6 +550,13 @@ def update_doc_show(file_path):
help="Set the server port for the Gradio app.",
default=None,
)
+ '--api-url',
+ 'api_url',
+ type=str,
+ help="MinerU FastAPI base URL. If omitted, gradio starts a reusable local mineru-api service.",
+ default=None,
+)
@click.option(
'--latex-delimiters-type',
'latex_delimiters_type',
@@ -388,7 +569,7 @@ def main(ctx,
example_enable,
http_client_enable,
api_enable, max_convert_pages,
- server_name, server_port, latex_delimiters_type, **kwargs
+ server_name, server_port, api_url, latex_delimiters_type, **kwargs
):
# 创建 i18n 实例,支持中英文
@@ -504,7 +685,8 @@ def main(ctx,
return client_options_update, ocr_options_update, formula_label_update, backend_info_update
- kwargs.update(arg_parse(ctx))
+ del kwargs
+ _gradio_local_api_server.configure(ctx.args)
if latex_delimiters_type == 'a':
latex_delimiters = latex_delimiters_type_a
@@ -515,23 +697,28 @@ def main(ctx,
else:
raise ValueError(f"Invalid latex delimiters type: {latex_delimiters_type}.")
- vlm_engine = get_vlm_engine("auto", is_async=True)
- if vlm_engine in ["transformers", "mlx-engine"]:
- http_client_enable = True
- else:
- try:
- logger.info(f"Start init {vlm_engine}...")
- from mineru.backend.vlm.vlm_analyze import ModelSingleton
- model_singleton = ModelSingleton()
- predictor = model_singleton.get_model(
- vlm_engine,
- None,
- None,
- **kwargs
- )
- logger.info(f"{vlm_engine} init successfully.")
- except Exception as e:
- logger.exception(e)
+
+ async def convert_to_markdown(
+ file_path,
+ end_pages=10,
+ is_ocr=False,
+ formula_enable=True,
+ table_enable=True,
+ language="ch",
+ backend="pipeline",
+ url=None,
+ ):
+ return await _to_markdown_impl(
+ file_path=file_path,
+ end_pages=end_pages,
+ is_ocr=is_ocr,
+ formula_enable=formula_enable,
+ table_enable=table_enable,
+ language=language,
+ backend=backend,
+ url=url,
+ api_url=api_url,
+ )
# suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes + office_suffixes]
suffixes = [f".{suffix}" for suffix in pdf_suffixes + image_suffixes + docx_suffixes]
@@ -598,7 +785,11 @@ def main(ctx,
)
# 添加事件处理
- _private_api_kwargs = {"api_visibility": "private"} if IS_GRADIO_6 else {"api_name": False}
+ _private_api_kwargs = (
+ {"api_visibility": "private", "queue": False}
+ if IS_GRADIO_6
+ else {"api_name": False, "queue": False}
+ )
backend.change(
fn=update_interface,
inputs=[backend],
@@ -636,9 +827,16 @@ def main(ctx,
outputs=[doc_show],
**_private_api_kwargs
)
- _to_md_api_kwargs = {"api_visibility": "public" if api_enable else "private"} if IS_GRADIO_6 else {"api_name": "to_markdown" if api_enable else False}
+ _to_md_api_kwargs = (
+ {
+ "api_visibility": "public" if api_enable else "private",
+ "queue": False,
+ }
+ if IS_GRADIO_6
+ else {"api_name": "to_markdown" if api_enable else False, "queue": False}
+ )
change_bu.click(
- fn=to_markdown,
+ fn=convert_to_markdown,
inputs=[input_file, max_pages, is_ocr, formula_enable, table_enable, language, backend, url],
outputs=[md, md_text, output_file, doc_show],
**_to_md_api_kwargs
diff --git a/mineru/utils/engine_utils.py b/mineru/utils/engine_utils.py
index 9ac704d1..c3ed386d 100644
--- a/mineru/utils/engine_utils.py
+++ b/mineru/utils/engine_utils.py
@@ -6,9 +6,6 @@ from loguru import logger
from mineru.utils.check_sys_env import is_mac_os_version_supported, is_windows_environment, is_mac_environment, \
is_linux_environment
-DISABLE_VLM_ACCELERATION_ENV = "MINERU_DISABLE_VLM_ACCELERATION"
-_TRUE_VALUES = ("1", "true", "yes", "on")
-
def get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:
"""
@@ -21,13 +18,7 @@ def get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:
Returns:
最终选择的引擎名称
"""
- if _is_vlm_acceleration_disabled():
- if inference_engine != 'transformers':
- logger.info(
- f"{DISABLE_VLM_ACCELERATION_ENV} is enabled, forcing VLM inference engine to transformers."
- )
- inference_engine = 'transformers'
- elif inference_engine == 'auto':
+ if inference_engine == 'auto':
# 根据操作系统自动选择引擎
if is_windows_environment():
inference_engine = _select_windows_engine()
@@ -44,11 +35,6 @@ def get_vlm_engine(inference_engine: str, is_async: bool = False) -> str:
return formatted_engine
-def _is_vlm_acceleration_disabled() -> bool:
- value = os.getenv(DISABLE_VLM_ACCELERATION_ENV, "0")
- return value.strip().lower() in _TRUE_VALUES
-
-
def _select_windows_engine() -> str:
"""Windows 平台引擎选择"""
try: