Skip to content

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

feat: implement stdin shutdown watcher and enhance local API shutdown handling

myhloli62054c9528d1
diff --git a/mineru/cli/api_client.py b/mineru/cli/api_client.py
index dfb68317..0214b449 100644
--- a/mineru/cli/api_client.py
+++ b/mineru/cli/api_client.py
@@ -32,6 +32,7 @@ TASKS_ENDPOINT = "/tasks"
TASK_STATUS_POLL_INTERVAL_SECONDS = 1.0
TASK_RESULT_TIMEOUT_SECONDS = 3600
LOCAL_API_STARTUP_TIMEOUT_SECONDS = 30
+LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS = 10
LOCAL_API_CLEANUP_RETRIES = 8
LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS = 0.25
@@ -87,6 +88,7 @@ class LocalAPIServer:
read_max_concurrent_requests(default=DEFAULT_MAX_CONCURRENT_REQUESTS)
)
env["MINERU_API_DISABLE_ACCESS_LOG"] = "1"
+ env["MINERU_API_SHUTDOWN_ON_STDIN_EOF"] = "1"
self.output_root.mkdir(parents=True, exist_ok=True)
command = [
@@ -103,6 +105,7 @@ class LocalAPIServer:
command,
cwd=os.getcwd(),
env=env,
+ stdin=subprocess.PIPE,
)
if not self._atexit_registered:
@@ -115,12 +118,23 @@ class LocalAPIServer:
self.process = None
try:
if process is not None and process.poll() is None:
- process.terminate()
+ if process.stdin is not None and not process.stdin.closed:
+ process.stdin.close()
try:
- process.wait(timeout=5)
+ process.wait(timeout=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
+ logger.debug(
+ "Local mineru-api did not stop after stdin EOF within {}s. Falling back to SIGTERM.",
+ LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS,
+ )
+ process.terminate()
+ try:
+ process.wait(timeout=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS)
+ return
+ except subprocess.TimeoutExpired:
+ pass
process.kill()
- process.wait(timeout=5)
+ process.wait(timeout=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS)
finally:
if self._atexit_registered:
try:
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py
index 61768b9b..863cba21 100644
--- a/mineru/cli/fast_api.py
+++ b/mineru/cli/fast_api.py
@@ -1,5 +1,6 @@
import asyncio
import mimetypes
+import multiprocessing
import os
import shutil
import sys
@@ -90,6 +91,33 @@ def env_flag_enabled(name: str, default: bool = False) -> bool:
return value.lower() in ("1", "true", "yes", "on")
+def is_main_multiprocessing_process() -> bool:
+ try:
+ return multiprocessing.current_process().name == "MainProcess"
+ except Exception:
+ return True
+
+
+def install_stdin_shutdown_watcher(server: uvicorn.Server) -> None:
+ if not env_flag_enabled("MINERU_API_SHUTDOWN_ON_STDIN_EOF"):
+ return
+
+ def _watch_stdin_for_eof() -> None:
+ stdin_stream = getattr(sys.stdin, "buffer", sys.stdin)
+ try:
+ stdin_stream.read()
+ except Exception:
+ return
+ server.should_exit = True
+
+ watcher = threading.Thread(
+ target=_watch_stdin_for_eof,
+ name="mineru-api-stdin-shutdown",
+ daemon=True,
+ )
+ watcher.start()
+
+
@dataclass
class ParseRequestOptions:
files: list[UploadFile]
@@ -209,7 +237,8 @@ def create_app():
_configured_max_concurrent_requests = max_concurrent_requests
app.state.max_concurrent_requests = max_concurrent_requests
_request_semaphore = asyncio.Semaphore(max_concurrent_requests)
- logger.info(f"Request concurrency limited to {max_concurrent_requests}")
+ if is_main_multiprocessing_process():
+ logger.info(f"Request concurrency limited to {max_concurrent_requests}")
app.add_middleware(GZipMiddleware, minimum_size=1000)
return app
@@ -1422,7 +1451,16 @@ def main(ctx, host, port, reload, **kwargs):
access_log=access_log,
)
else:
- uvicorn.run(app, host=host, port=port, reload=False, access_log=access_log)
+ config = uvicorn.Config(
+ app,
+ host=host,
+ port=port,
+ reload=False,
+ access_log=access_log,
+ )
+ server = uvicorn.Server(config)
+ install_stdin_shutdown_watcher(server)
+ server.run()
if __name__ == "__main__":
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 00ab4fc3..76035ebd 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -142,6 +142,7 @@ def _load_images_from_pdf_bytes_range(
)
executor = ProcessPoolExecutor(max_workers=actual_threads)
+ cancel_futures = False
try:
futures = []
future_to_range = {}
@@ -159,6 +160,7 @@ def _load_images_from_pdf_bytes_range(
_, not_done = wait(futures, timeout=timeout, return_when=ALL_COMPLETED)
if not_done:
+ cancel_futures = True
_terminate_executor_processes(executor)
raise TimeoutError(
f"PDF image rendering timeout after {timeout}s "
@@ -178,11 +180,14 @@ def _load_images_from_pdf_bytes_range(
return images_list
except Exception as exc:
+ cancel_futures = True
if not isinstance(exc, TimeoutError):
_terminate_executor_processes(executor)
raise
finally:
- executor.shutdown(wait=False, cancel_futures=True)
+ # Block until worker processes are fully reaped so multiprocessing
+ # can unregister its semaphores before interpreter shutdown.
+ executor.shutdown(wait=True, cancel_futures=cancel_futures)
def _terminate_executor_processes(executor):