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: standardize process output encoding
jinzhenj7bc2b3069043
diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.pyindex 2c9c3530..92ca434d 100644--- a/mineru/cli/commands/server.py+++ b/mineru/cli/commands/server.py@@ -19,6 +19,7 @@ from ...config import configfrom ...doclib.instance_lock import DoclibLockUnavailable, build_doclib_home_owned_message, doclib_home_lockfrom ...doclib.types import ServerStatusResponse, TCPServerStatusfrom ...errors import MineruError+from ...utils.stdio import utf8_subprocess_envfrom ...version import __version__from ..contracts import CliContext, RenderableObjectfrom ..runtime import run_cli@@ -232,6 +233,7 @@ def _start() -> str:stdout=stdout_log_file,stderr=stderr_log_file,start_new_session=True,+ env=utf8_subprocess_env(),)if not _wait_for_started_server(proc):diff --git a/mineru/cli/main.py b/mineru/cli/main.pyindex 51cb23b9..c7180904 100644--- a/mineru/cli/main.py+++ b/mineru/cli/main.py@@ -6,6 +6,7 @@ import typerfrom click.core import Contextfrom typer.core import TyperGroup+from ..utils.stdio import configure_standard_streamsfrom .commands import cleanup, config, list_resources, server, show, telemetry, usage, watchfrom .commands.forget import forget_cmdfrom .commands.invalidate import invalidate_cmd@@ -92,6 +93,7 @@ app.command("version")(version_cmd)def main() -> None:+ configure_standard_streams()app()diff --git a/mineru/cli/output.py b/mineru/cli/output.pyindex 0eae8a14..df9624db 100644--- a/mineru/cli/output.py+++ b/mineru/cli/output.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import sysfrom dataclasses import asdict, is_dataclassfrom typing import Any@@ -21,18 +22,22 @@ def print_rich(*objects: RenderableObject) -> None:console.print(*objects)+def print_text(value: object) -> None:+ sys.stdout.write(f"{value}\n")++def print_success(msg: str) -> None:if console:console.print(msg, style="green")else:- print(msg)+ print_text(msg)def print_info(msg: str) -> None:if console:console.print(msg, style="dim")else:- print(msg)+ print_text(msg)def print_notice(msg: str) -> None:@@ -47,9 +52,9 @@ def print_error(msg: str) -> None:def print_json(data: Any) -> None:if isinstance(data, BaseModel):- print(to_json(data, indent=2).decode("utf-8"))+ print_text(to_json(data, indent=2).decode("utf-8"))returnif is_dataclass(data) and not isinstance(data, type):- print(json.dumps(asdict(data), ensure_ascii=False, indent=2))+ print_text(json.dumps(asdict(data), ensure_ascii=False, indent=2))return- print(json.dumps(data, ensure_ascii=False, indent=2))+ print_text(json.dumps(data, ensure_ascii=False, indent=2))diff --git a/mineru/cli/runtime.py b/mineru/cli/runtime.pyindex 1ab1e9e6..f2664cf6 100644--- a/mineru/cli/runtime.py+++ b/mineru/cli/runtime.py@@ -129,18 +129,18 @@ def emit_error(ctx: CliContext, exc: Exception, *, guidance: CliGuidance | Nonedef _emit_rendered_output(rendered_output: RenderableOutput) -> None:if isinstance(rendered_output, str):- print(rendered_output)+ output.print_text(rendered_output)returnif isinstance(rendered_output, RichObject):output.print_rich(rendered_output)returnfor item in rendered_output:if isinstance(item, str):- print(item)+ output.print_text(item)elif isinstance(item, RichObject):output.print_rich(item)else:- print(item)+ output.print_text(item)def to_mineru_error(exc: Exception) -> MineruError:diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 9cd2e002..3e1bf7c7 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -21,6 +21,7 @@ from loguru import logger as loguru_loggerfrom ..config import Config, LogConfig, _mineru_home, config, get_config_sourcefrom ..errors import MineruError, error_response, http_status_for+from ..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_lockfrom .server import DoclibServer@@ -437,6 +438,7 @@ def _bind_tcp_socket(host: str, port: int, *, strict_port: bool, port_probe_coundef main() -> None:"""Entry point: python -m mineru.doclib.app"""+ configure_standard_streams()try:with doclib_home_lock():_run_server(config)@@ -512,7 +514,7 @@ def _run_server(cfg: Config) -> None:port_probe_count=cfg.doclib.tcp.port_probe_count,)if cfg.doclib.tcp.port != 0 and port != cfg.doclib.tcp.port:- print(f"Port {cfg.doclib.tcp.port} in use, using {port}")+ logger.warning("Port %d in use, using %d", cfg.doclib.tcp.port, port)tcp_sock.listen(cfg.doclib.tcp.backlog)sockets.append(tcp_sock)app.state.doclib_state.tcp_port = port@@ -534,7 +536,7 @@ def _run_server(cfg: Config) -> None:len(transports),)- print("MinerU server listening on " + " and ".join(_format_transport(transport) for transport in transports))+ logger.info("MinerU server listening on %s", " and ".join(_format_transport(transport) for transport in transports))loop = asyncio.new_event_loop()@@ -698,7 +700,13 @@ def _forward_loguru_to_logging(message: LoguruMessage) -> None:def _rotating_log_handler(path: str, level: int) -> RotatingFileHandler:- handler = RotatingFileHandler(path, maxBytes=5 * 1024 * 1024, backupCount=3)+ handler = RotatingFileHandler(+ path,+ maxBytes=5 * 1024 * 1024,+ backupCount=3,+ encoding="utf-8",+ errors="backslashreplace",+ )handler.setLevel(level)handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))return handlerdiff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.pyindex 2958b5b0..9a5642a2 100644--- a/mineru/doclib/background/parse_server_health.py+++ b/mineru/doclib/background/parse_server_health.py@@ -19,6 +19,7 @@ import httpxfrom ...config import LogConfig, ManagedParseServerConfig, configfrom ...parser.api_client import should_trust_env_for_urlfrom ...types import DEPLOYMENT_TIERS, TIERS, DeploymentTier, Tier+from ...utils.stdio import utf8_subprocess_envfrom ..config_defaults import CONFIG_DEFAULTSfrom ..remote_api import resolve_remote_api_key@@ -199,7 +200,7 @@ def start_managed_parse_server("mineru.parser.api_server",*api_server_args_for_tier(tier, host=managed_cfg.host, port=port),]- env = os.environ.copy()+ env = utf8_subprocess_env()env[MANAGED_PARSE_SERVER_ENV] = "1"logger.info("Starting managed parse-server (%s): %s", marker, " ".join(cmd))with open_managed_parse_server_logs(marker=marker, log_cfg=log_cfg) as (diff --git a/mineru/kit/main.py b/mineru/kit/main.pyindex 271785a0..6efe8776 100644--- a/mineru/kit/main.py+++ b/mineru/kit/main.py@@ -7,6 +7,7 @@ from click.core import Contextfrom typer.core import TyperGroupfrom ..cli.version_command import show_version, version_cmd+from ..utils.stdio import configure_standard_streamsfrom .commands import api_server, models, parse, router, vlm_serverTOP_LEVEL_COMMAND_ORDER = [@@ -61,6 +62,7 @@ app.command("version")(version_cmd)def main() -> None:+ configure_standard_streams()app()diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex d5f4d7a0..18019446 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -51,6 +51,7 @@ from ..types import SERVER_TIERS, TIERS_BY_SERVER_TIER, DeploymentTier, PageInfofrom ..utils.backend_options import DEFAULT_HYBRID_EFFORTfrom ..utils.image_payload import validate_image_sidecar_pathfrom ..utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang+from ..utils.stdio import configure_standard_streamsfrom ..version import __version__from . import parse_asyncfrom .base import ParseResult@@ -2428,6 +2429,7 @@ def main(api_key: str | None,) -> None:"""Start the MinerU v1 REST API server."""+ configure_standard_streams()try:application = create_app(upload_dir=upload_dir,diff --git a/mineru/utils/__init__.py b/mineru/utils/__init__.pyindex 1e17167c..b055ee36 100644--- a/mineru/utils/__init__.py+++ b/mineru/utils/__init__.py@@ -1 +1,3 @@# Copyright (c) Opendatalab. All rights reserved.++__all__ = []diff --git a/mineru/utils/stdio.py b/mineru/utils/stdio.pynew file mode 100644index 00000000..8b9deec3--- /dev/null+++ b/mineru/utils/stdio.py@@ -0,0 +1,25 @@+"""Standard stream configuration helpers."""++from __future__ import annotations++import os+import sys+from collections.abc import Mapping++_STDIO_ENCODING = "utf-8"+_STDIO_ERRORS = "backslashreplace"+++def configure_standard_streams() -> None:+ """Configure the current process standard streams for UTF-8 output."""+ for stream in (sys.stdout, sys.stderr):+ reconfigure = getattr(stream, "reconfigure", None)+ if callable(reconfigure):+ reconfigure(encoding=_STDIO_ENCODING, errors=_STDIO_ERRORS)+++def utf8_subprocess_env(base: Mapping[str, str] | None = None) -> dict[str, str]:+ """Return a child-process environment with UTF-8 standard streams."""+ env = dict(os.environ if base is None else base)+ env["PYTHONIOENCODING"] = f"{_STDIO_ENCODING}:{_STDIO_ERRORS}"+ return envdiff --git a/pyproject.toml b/pyproject.tomlindex 8326b6a3..e42040a0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -125,8 +125,8 @@ issues = "https://github.com/opendatalab/MinerU/issues"License = "https://github.com/opendatalab/MinerU/blob/master/LICENSE.md"[project.scripts]-mineru = "mineru.cli.main:app"-mineru-kit = "mineru.kit.main:app"+mineru = "mineru.cli.main:main"+mineru-kit = "mineru.kit.main:main"mineru-gradio = "mineru.cli_old.gradio_app:main"[tool.setuptools.dynamic]diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex 846dceed..978b7bdb 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -2096,6 +2096,7 @@ def test_server_start_failure_points_to_log_and_does_not_discard_child_stderr(moassert kwargs["stdout"] is not server.subprocess.DEVNULLassert kwargs["stderr"] is not server.subprocess.DEVNULLassert kwargs["stdout"] is not kwargs["stderr"]+ assert kwargs["env"]["PYTHONIOENCODING"] == "utf-8:backslashreplace"kwargs["stdout"].write("child stdout\n")kwargs["stdout"].flush()kwargs["stderr"].write("child failed\n")diff --git a/tests/unittest/test_cli_runtime_contract.py b/tests/unittest/test_cli_runtime_contract.pyindex e5e6c702..6eca6f98 100644--- a/tests/unittest/test_cli_runtime_contract.py+++ b/tests/unittest/test_cli_runtime_contract.py@@ -7,6 +7,7 @@ import typesimport pytestimport typer+import mineru.cli.main as cli_mainfrom mineru.cli import outputfrom mineru.cli import contractsfrom mineru.cli.contracts import CliContext, CliGuidance@@ -26,6 +27,29 @@ def _plain_output(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(output, "print_rich", print_rich)+def test_main_configures_standard_streams_before_running_app(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []+ monkeypatch.setattr(cli_main, "configure_standard_streams", lambda: calls.append("configure"))+ monkeypatch.setattr(cli_main, "app", lambda: calls.append("app"))++ cli_main.main()++ assert calls == ["configure", "app"]+++def test_text_output_uses_output_boundary(monkeypatch: pytest.MonkeyPatch) -> None:+ written: list[object] = []+ monkeypatch.setattr(output, "print_text", written.append)++ run_cli(+ CliContext(json_mode=False),+ lambda: {"name": "demo"},+ render=lambda data: [f"name={data['name']}", 3],+ )++ assert written == ["name=demo", 3]++def test_emit_result_json_mode_writes_single_json_object(capsys: pytest.CaptureFixture[str]) -> None:result = cli_ok({"status": "done", "count": 2})diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.pyindex 87eed2c4..eeb33fd3 100644--- a/tests/unittest/test_doclib_app_startup.py+++ b/tests/unittest/test_doclib_app_startup.py@@ -309,6 +309,8 @@ def test_setup_logging_routes_application_logs_to_rotating_file_without_stderr_dassert len(mineru_rotating_handlers) == 1assert mineru_rotating_handlers[0].baseFilename == str(log_path)+ assert mineru_rotating_handlers[0].encoding == "utf-8"+ assert mineru_rotating_handlers[0].errors == "backslashreplace"assert mineru_plain_stream_handlers == []assert mineru_logger.propagate is Falseuvicorn_error_log_paths = [@@ -322,6 +324,10 @@ def test_setup_logging_routes_application_logs_to_rotating_file_without_stderr_dhandler.baseFilename for handler in uvicorn_access_logger.handlers if isinstance(handler, RotatingFileHandler)]assert uvicorn_access_log_paths == [str(access_log_path)]++ mineru_logger.info("Unicode log: \u223c \u4e2d\u6587 \u2713")+ mineru_rotating_handlers[0].flush()+ assert "Unicode log: \u223c \u4e2d\u6587 \u2713" in log_path.read_text(encoding="utf-8")finally:_clear_test_loggers()diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex 00634a18..69d7cac8 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -592,6 +592,7 @@ def test_start_managed_parse_server_selects_port_and_writes_logs(monkeypatch: pyassert kwargs["stdout"] is not kwargs["stderr"]assert kwargs["stdin"] is subprocess.PIPEassert kwargs["env"]["MINERU_MANAGED_PARSE_SERVER"] == "1"+ assert kwargs["env"]["PYTHONIOENCODING"] == "utf-8:backslashreplace"kwargs["stdout"].write("parse helper stdout\n")kwargs["stdout"].flush()kwargs["stderr"].write("parse helper stderr\n")diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 333dca5e..cb8a583b 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -19,6 +19,7 @@ from fastapi.testclient import TestClientfrom typer.main import get_commandfrom typer.testing import CliRunner+import mineru.kit.main as kit_mainfrom mineru.cli.main import app as mineru_appfrom mineru.cli.version_command import version_cmdfrom mineru.kit.commands import api_server, models, parse, router, vlm_server@@ -39,6 +40,16 @@ _REMOVED_FORMULA_ENABLE_PARAM = "formula" + "_enable"_REMOVED_INLINE_FORMULA_PARAM = "inline_" + _REMOVED_FORMULA_ENABLE_PARAM+def test_kit_main_configures_standard_streams_before_running_app(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[str] = []+ monkeypatch.setattr(kit_main, "configure_standard_streams", lambda: calls.append("configure"))+ monkeypatch.setattr(kit_main, "app", lambda: calls.append("app"))++ kit_main.main()++ assert calls == ["configure", "app"]++def _assert_unsafe_sidecar_error(output: str) -> None:"""归一化 Typer/Click 自动换行后的错误输出,再匹配 sidecar 安全错误。"""assert "Unsafe image sidecar path" in " ".join(output.split())diff --git a/tests/unittest/test_stdio.py b/tests/unittest/test_stdio.pynew file mode 100644index 00000000..36cd8644--- /dev/null+++ b/tests/unittest/test_stdio.py@@ -0,0 +1,48 @@+from __future__ import annotations++import tomllib+from pathlib import Path++import pytest++import mineru.utils.stdio as stdio+++def test_configure_standard_streams_uses_utf8(monkeypatch: pytest.MonkeyPatch) -> None:+ class _Stream:+ def __init__(self) -> None:+ self.calls: list[dict[str, str]] = []++ def reconfigure(self, **kwargs: str) -> None:+ self.calls.append(kwargs)++ stdout = _Stream()+ stderr = _Stream()+ monkeypatch.setattr(stdio.sys, "stdout", stdout)+ monkeypatch.setattr(stdio.sys, "stderr", stderr)++ stdio.configure_standard_streams()++ expected = [{"encoding": "utf-8", "errors": "backslashreplace"}]+ assert stdout.calls == expected+ assert stderr.calls == expected+++def test_utf8_subprocess_env_overrides_inherited_stdio_encoding() -> None:+ env = stdio.utf8_subprocess_env(+ {+ "PYTHONIOENCODING": "gbk",+ "MINERU_TEST_VALUE": "preserved",+ }+ )++ assert env["PYTHONIOENCODING"] == "utf-8:backslashreplace"+ assert env["MINERU_TEST_VALUE"] == "preserved"+++def test_console_scripts_use_standard_stream_configuring_entrypoints() -> None:+ pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"+ scripts = tomllib.loads(pyproject_path.read_text(encoding="utf-8"))["project"]["scripts"]++ assert scripts["mineru"] == "mineru.cli.main:main"+ assert scripts["mineru-kit"] == "mineru.kit.main:main"