Merge pull request #1670 from Mikesad/fix/mineru-local-failure-reasons

Fix/mineru local failure reasons
This commit is contained in:
Bingxi Zhao
2026-10-04 14:57:57 +08:00
committed by GitHub
5 changed files with 420 additions and 38 deletions

View File

@@ -23,6 +23,7 @@ from .config import (
resolve_mineru_config,
)
from .formats import MINERU_PDF_FORMATS, MINERU_SUPPORTED_FORMATS
from .local import LocalParseReason, parse_document_with_mineru_result
logger = logging.getLogger(__name__)
@@ -30,6 +31,41 @@ logger = logging.getLogger(__name__)
# probe reports the same command the parse subprocess will actually use.
_LOCAL_CLI_COMMANDS = ("mineru", "magic-pdf")
#: One actionable message per local-parse failure reason. The install/cloud
#: hint is deliberately limited to ``CLI_MISSING``: a runtime failure must not
#: be reported as a missing installation (issue #1612, outcome 4).
_LOCAL_FAILURE_MESSAGES: dict[LocalParseReason, str] = {
LocalParseReason.CLI_MISSING: (
"Local MinerU parsing failed. Ensure MinerU is installed "
"(`pip install -U 'mineru[all]>=3.4.5'`) or switch to cloud mode in "
"Settings → MinerU."
),
LocalParseReason.INPUT_MISSING: (
"MinerU could not read the source file ({detail}). It may have been "
"moved or deleted before parsing started."
),
LocalParseReason.UNSUPPORTED_INPUT: (
"MinerU does not support this input type ({detail}). Supported inputs "
"are PDF, common raster images, DOCX, PPTX, and XLSX."
),
LocalParseReason.LEGACY_CLI_INPUT: (
"The legacy magic-pdf CLI only accepts PDF files. Install the current "
"MinerU CLI (`pip install -U 'mineru[all]>=3.4.5'`) to parse images, "
"DOCX, PPTX, or XLSX."
),
LocalParseReason.NONZERO_EXIT: (
"Local MinerU parsing failed at runtime (the CLI is installed). Last "
"output:\n{detail}\nCheck the source file, local model files and "
"available memory, or switch to cloud mode in Settings → MinerU."
),
LocalParseReason.NO_ARTIFACTS: (
"MinerU finished but produced no output files ({detail}). Check that "
"local models are downloaded and the output directory is writable, or "
"switch to cloud mode in Settings → MinerU."
),
LocalParseReason.EXCEPTION: "Local MinerU parsing was interrupted: {detail}",
}
def parse_document_to_workdir(
source_path: str | Path,
@@ -154,7 +190,6 @@ def _parse_local(
) -> Path:
"""Local-CLI branch: delegate to the existing subprocess parser and return
the deterministic output directory it writes to (``<base>/<stem>``)."""
from .local import parse_document_with_mineru
from .models import model_env_overrides, render_env_overrides
cli_command = None
@@ -163,7 +198,8 @@ def _parse_local(
if not probe["found"]:
raise MinerUError(
f"Configured MinerU CLI path is not an executable file: {probe['path']}. "
"Fix it in Settings → MinerU (or clear it to auto-detect from PATH)."
"Fix it in Settings → MinerU (or clear it to auto-detect from PATH).",
code=str(LocalParseReason.CLI_MISSING),
)
cli_command = probe["path"]
else:
@@ -179,7 +215,8 @@ def _parse_local(
raise MinerUError(
"The legacy magic-pdf CLI only accepts PDF files. Install the current "
"MinerU CLI (`pip install -U 'mineru[all]>=3.4.5'`) to parse images, "
"DOCX, PPTX, or XLSX."
"DOCX, PPTX, or XLSX.",
code=str(LocalParseReason.LEGACY_CLI_INPUT),
)
# A lazy first-parse model download must honor the configured source and
@@ -190,18 +227,19 @@ def _parse_local(
subprocess_env = {**download_env, **render_env_overrides()}
logger.info("Parsing %s via local MinerU CLI (%s)", source_path.name, cli_command or "PATH")
ok = parse_document_with_mineru(
result = parse_document_with_mineru_result(
str(source_path),
str(output_base),
on_output=on_output,
cli_command=cli_command,
extra_env=subprocess_env,
)
if not ok:
if not result.ok:
reason = result.reason or LocalParseReason.EXCEPTION
raise MinerUError(
"Local MinerU parsing failed. Ensure MinerU is installed "
"(`pip install -U 'mineru[all]>=3.4.5'`) or switch to cloud mode in "
"Settings → MinerU."
_LOCAL_FAILURE_MESSAGES[reason].format(detail=result.detail or "no output"),
code=str(reason),
detail=result.detail,
)
working_dir = output_base / source_path.stem
if not working_dir.is_dir():

View File

@@ -25,6 +25,15 @@ class MinerUError(RuntimeError):
misconfiguration). Carries a user-facing message; the capability layer
surfaces it as a stream error."""
def __init__(self, message: str, *, code: str | None = None, detail: str = "") -> None:
super().__init__(message)
#: Machine-readable reason when one is known (``LocalParseReason``
#: values for local failures); ``None`` when the error is raised
#: without a classification.
self.code = code
#: Bounded diagnostic excerpt backing the message; ``""`` when none.
self.detail = detail
@dataclass(frozen=True)
class MinerUConfig:

View File

@@ -4,6 +4,8 @@
import argparse
from collections import deque
from collections.abc import Callable
from dataclasses import dataclass
from enum import StrEnum
import os
from pathlib import Path
import shutil
@@ -18,6 +20,57 @@ from .formats import MINERU_SUPPORTED_FORMATS
# without a floor the trace panel gets flooded during model downloads.
_ON_OUTPUT_MIN_INTERVAL = 0.5
#: Upper bound on the failure excerpt carried back to callers: long enough for
#: a useful stderr tail, short enough to fit inside an error message.
_FAILURE_DETAIL_MAX_CHARS = 400
def _bounded_detail(text: str) -> str:
"""One failure excerpt, trimmed to ``_FAILURE_DETAIL_MAX_CHARS``."""
clean = str(text or "").strip()
if len(clean) <= _FAILURE_DETAIL_MAX_CHARS:
return clean
return clean[:_FAILURE_DETAIL_MAX_CHARS].rstrip() + "…"
class LocalParseReason(StrEnum):
"""Why a local MinerU parse failed.
The values mirror ``readiness.py``'s pre-flight reasons (``cli_missing``,
``models_missing``) so the two failure vocabularies stay aligned.
"""
CLI_MISSING = "cli_missing"
INPUT_MISSING = "input_missing"
UNSUPPORTED_INPUT = "unsupported_input"
LEGACY_CLI_INPUT = "legacy_cli_input"
NONZERO_EXIT = "nonzero_exit"
NO_ARTIFACTS = "no_artifacts"
EXCEPTION = "exception"
@dataclass(frozen=True, slots=True)
class LocalParseResult:
"""Outcome of one local MinerU parse.
``detail`` is a bounded, user-safe excerpt (stderr tail or exception
text), never the whole process log.
"""
ok: bool
reason: LocalParseReason | None = None
detail: str = ""
@classmethod
def success(cls) -> "LocalParseResult":
"""A parse that wrote its artifacts."""
return cls(ok=True)
@classmethod
def failure(cls, reason: LocalParseReason, detail: str = "") -> "LocalParseResult":
"""A failed parse, with the reason and its bounded excerpt."""
return cls(ok=False, reason=reason, detail=_bounded_detail(detail))
def check_mineru_installed():
"""Check if MinerU is installed"""
@@ -53,15 +106,18 @@ def check_mineru_installed():
return None
def parse_document_with_mineru(
def parse_document_with_mineru_result(
source_path: str,
output_base_dir: str | None = None,
on_output: Callable[[str], None] | None = None,
cli_command: str | None = None,
extra_env: dict[str, str] | None = None,
):
"""
Parse a supported document or image using MinerU.
) -> LocalParseResult:
"""Parse with MinerU and report *why* a failure happened.
Same inputs as :func:`parse_document_with_mineru`, but the outcome carries
a :class:`LocalParseReason` and a bounded ``detail`` (stderr tail or
exception text) instead of a bare ``False``.
Args:
source_path: Path to a PDF, image, DOCX, PPTX, or XLSX file
@@ -77,7 +133,7 @@ def parse_document_with_mineru(
download honors the configured source and mirror).
Returns:
bool: Whether parsing was successful
LocalParseResult: Whether parsing succeeded, and why it failed.
"""
if cli_command:
mineru_cmd = cli_command
@@ -91,23 +147,32 @@ def parse_document_with_mineru(
print("or")
print(" pip install mineru")
print("or visit: https://github.com/opendatalab/MinerU")
return False
return LocalParseResult.failure(
LocalParseReason.CLI_MISSING,
"neither `mineru` nor `magic-pdf` was found on PATH",
)
print(f"✓ Detected MinerU command: {mineru_cmd}")
source_file = Path(source_path).resolve()
if not source_file.exists():
print(f"✗ Error: Input file does not exist: {source_file}")
return False
return LocalParseResult.failure(LocalParseReason.INPUT_MISSING, str(source_file))
suffix = source_file.suffix.lower()
if suffix not in MINERU_SUPPORTED_FORMATS:
print(f"✗ Error: Unsupported MinerU input format: {source_file}")
return False
return LocalParseResult.failure(
LocalParseReason.UNSUPPORTED_INPUT,
suffix or "(no file extension)",
)
if Path(mineru_cmd).name == "magic-pdf" and suffix != ".pdf":
print("✗ Error: The legacy magic-pdf CLI only accepts PDF files.")
print("Install the current CLI with `pip install mineru` for images and Office files.")
return False
return LocalParseResult.failure(
LocalParseReason.LEGACY_CLI_INPUT,
f"magic-pdf cannot parse {suffix or '(no file extension)'}",
)
# Project root is 3 levels up from deeptutor/tools/question/
project_root = Path(__file__).parent.parent.parent.parent
@@ -177,7 +242,10 @@ def parse_document_with_mineru(
print("\n".join(tail))
if temp_output.exists():
shutil.rmtree(temp_output)
return False
return LocalParseResult.failure(
LocalParseReason.NONZERO_EXIT,
f"exit code {returncode}\n" + "\n".join(tail),
)
print("✓ MinerU parsing completed!")
@@ -187,7 +255,10 @@ def parse_document_with_mineru(
print("⚠️ Warning: No generated files found in temp directory")
if temp_output.exists():
shutil.rmtree(temp_output)
return False
return LocalParseResult.failure(
LocalParseReason.NO_ARTIFACTS,
f"no files were produced in {temp_output}",
)
source_folder = generated_folders[0] if generated_folders[0].is_dir() else temp_output
@@ -221,14 +292,42 @@ def parse_document_with_mineru(
rel_path = item.relative_to(output_dir)
print(f" - {rel_path}")
return True
return LocalParseResult.success()
except Exception as e:
print(f"✗ Error occurred during parsing: {e!s}")
import traceback
traceback.print_exc()
return False
return LocalParseResult.failure(
LocalParseReason.EXCEPTION,
f"{type(e).__name__}: {e}",
)
def parse_document_with_mineru(
source_path: str,
output_base_dir: str | None = None,
on_output: Callable[[str], None] | None = None,
cli_command: str | None = None,
extra_env: dict[str, str] | None = None,
) -> bool:
"""Parse a supported document or image using MinerU.
Retained bool contract for existing callers; see
:func:`parse_document_with_mineru_result` when the failure reason and its
bounded diagnostic excerpt matter.
Returns:
bool: Whether parsing was successful
"""
return parse_document_with_mineru_result(
source_path,
output_base_dir,
on_output=on_output,
cli_command=cli_command,
extra_env=extra_env,
).ok
def parse_pdf_with_mineru(

View File

@@ -0,0 +1,239 @@
"""Local MinerU failure classification (issue #1612, outcome 4).
Covers the reason codes returned by
:func:`deeptutor.services.parsing.engines.mineru.local.parse_document_with_mineru_result`,
how ``backend`` maps them to distinct :class:`MinerUError` messages, and the
unchanged bool contract of the legacy helpers.
"""
from __future__ import annotations
from pathlib import Path
import subprocess
import pytest
from deeptutor.services.parsing.engines.mineru import backend as mineru_backend
from deeptutor.services.parsing.engines.mineru import local as mineru_local
from deeptutor.services.parsing.engines.mineru.config import MinerUConfig, MinerUError
from deeptutor.services.parsing.engines.mineru.local import (
LocalParseReason,
LocalParseResult,
parse_document_with_mineru,
parse_document_with_mineru_result,
)
REASONS = list(LocalParseReason)
@pytest.fixture()
def pdf(tmp_path: Path) -> Path:
source = tmp_path / "exam.pdf"
source.write_bytes(b"%PDF-1.4")
return source
def _install_fake_popen(
monkeypatch: pytest.MonkeyPatch,
*,
returncode: int = 0,
lines: tuple[str, ...] = (),
artifacts: tuple[str, ...] = (),
) -> None:
"""Patch the subprocess factory so the local CLI is simulated in-process."""
class FakeProcess:
def __init__(self, cmd, **_kwargs) -> None: # noqa: ANN001
target = Path(cmd[cmd.index("-o") + 1])
for name in artifacts:
path = target / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("# parsed", encoding="utf-8")
self.stdout = iter(lines)
def wait(self) -> int:
return returncode
monkeypatch.setattr(mineru_local.subprocess, "Popen", FakeProcess)
# ---------------------------------------------------------------------------
# parse_document_with_mineru_result — reason codes
# ---------------------------------------------------------------------------
def test_cli_missing_reports_reason(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(mineru_local, "check_mineru_installed", lambda: None)
result = parse_document_with_mineru_result(pdf, tmp_path / "out")
assert result.ok is False
assert result.reason is LocalParseReason.CLI_MISSING
assert result.detail
def test_input_missing_reports_reason(pdf: Path, tmp_path: Path) -> None:
missing = tmp_path / "gone.pdf"
result = parse_document_with_mineru_result(missing, tmp_path / "out", cli_command="mineru")
assert result.reason is LocalParseReason.INPUT_MISSING
assert result.detail == str(missing.resolve())
def test_unsupported_input_reports_reason(tmp_path: Path) -> None:
source = tmp_path / "notes.xyz"
source.write_text("x", encoding="utf-8")
result = parse_document_with_mineru_result(source, tmp_path / "out", cli_command="mineru")
assert result.reason is LocalParseReason.UNSUPPORTED_INPUT
assert result.detail == ".xyz"
def test_legacy_cli_input_reports_reason(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
source = tmp_path / "lesson.docx"
source.write_bytes(b"office")
monkeypatch.setattr(
mineru_local.subprocess,
"Popen",
lambda *_args, **_kwargs: pytest.fail("legacy CLI must not be invoked"),
)
result = parse_document_with_mineru_result(source, tmp_path / "out", cli_command="magic-pdf")
assert result.reason is LocalParseReason.LEGACY_CLI_INPUT
def test_nonzero_exit_keeps_bounded_stderr_tail(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_install_fake_popen(
monkeypatch,
returncode=7,
lines=("first problem", "second problem"),
)
result = parse_document_with_mineru_result(pdf, tmp_path / "out", cli_command="mineru")
assert result.reason is LocalParseReason.NONZERO_EXIT
assert "exit code 7" in result.detail
assert "first problem" in result.detail
assert "second problem" in result.detail
def test_no_artifacts_reports_reason(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
_install_fake_popen(monkeypatch, returncode=0, artifacts=())
result = parse_document_with_mineru_result(pdf, tmp_path / "out", cli_command="mineru")
assert result.reason is LocalParseReason.NO_ARTIFACTS
def test_internal_exception_reports_reason(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
def boom(*_args, **_kwargs): # noqa: ANN002, ANN003
raise subprocess.TimeoutExpired(cmd="mineru", timeout=1)
monkeypatch.setattr(mineru_local.subprocess, "Popen", boom)
result = parse_document_with_mineru_result(pdf, tmp_path / "out", cli_command="mineru")
assert result.reason is LocalParseReason.EXCEPTION
assert "TimeoutExpired" in result.detail
def test_success_reports_ok(pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
_install_fake_popen(monkeypatch, artifacts=("exam.md",))
result = parse_document_with_mineru_result(pdf, tmp_path / "out", cli_command="mineru")
assert result.ok is True
assert result.reason is None
assert (tmp_path / "out" / "exam" / "exam.md").exists()
def test_failure_detail_is_bounded() -> None:
result = LocalParseResult.failure(LocalParseReason.EXCEPTION, "x" * 1000)
assert len(result.detail) <= mineru_local._FAILURE_DETAIL_MAX_CHARS + 1
# ---------------------------------------------------------------------------
# backend mapping and legacy contract
# ---------------------------------------------------------------------------
def test_backend_maps_every_reason_to_a_distinct_error(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
exe = tmp_path / "mineru"
exe.write_text("#!/bin/sh\n", encoding="utf-8")
exe.chmod(0o755)
config = MinerUConfig(mode="local", local_cli_path=str(exe))
messages: dict[str, str] = {}
for reason in REASONS:
monkeypatch.setattr(
mineru_backend,
"parse_document_with_mineru_result",
lambda *_args, _reason=reason, **_kwargs: LocalParseResult(
ok=False, reason=_reason, detail="excerpt-here"
),
)
with pytest.raises(MinerUError) as exc:
mineru_backend.parse_document_to_workdir(pdf, tmp_path / f"out-{reason}", config=config)
assert exc.value.code == str(reason)
assert exc.value.detail == "excerpt-here"
messages[str(reason)] = str(exc.value)
assert len(set(messages.values())) == len(messages)
install_hits = [
key for key, message in messages.items() if "Ensure MinerU is installed" in message
]
assert install_hits == ["cli_missing"]
def test_backend_runtime_failure_does_not_claim_missing_install(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(
mineru_backend,
"parse_document_with_mineru_result",
lambda *_args, **_kwargs: LocalParseResult(
ok=False, reason=LocalParseReason.NONZERO_EXIT, detail="exit code 9: broken"
),
)
with pytest.raises(MinerUError) as exc:
mineru_backend.parse_document_to_workdir(
pdf, tmp_path / "out", config=MinerUConfig(mode="local")
)
assert exc.value.code == "nonzero_exit"
assert "Ensure MinerU is installed" not in str(exc.value)
assert "exit code 9" in str(exc.value)
def test_legacy_bool_helpers_keep_their_contract(
pdf: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(mineru_local, "check_mineru_installed", lambda: None)
assert parse_document_with_mineru(pdf, tmp_path / "out") is False
source = tmp_path / "lesson.docx"
source.write_bytes(b"office")
assert mineru_local.parse_pdf_with_mineru(str(source)) is False
def test_error_without_classification_keeps_old_shape() -> None:
error = MinerUError("boom")
assert error.code is None
assert error.detail == ""
assert str(error) == "boom"

View File

@@ -12,6 +12,7 @@ from deeptutor.services.parsing.engines.mineru import backend as mineru_backend
from deeptutor.services.parsing.engines.mineru import cloud as mineru_cloud
from deeptutor.services.parsing.engines.mineru import config as mineru_config
from deeptutor.services.parsing.engines.mineru.config import MinerUConfig, MinerUError
from deeptutor.services.parsing.engines.mineru.local import LocalParseReason, LocalParseResult
# ---------------------------------------------------------------------------
# Config resolution
@@ -68,17 +69,15 @@ def test_resolve_mineru_config_preserves_token_array(monkeypatch: pytest.MonkeyP
def test_parse_pdf_to_workdir_dispatches_local(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.parsing.engines.mineru import local as pdf_parser
pdf = tmp_path / "exam.pdf"
pdf.write_bytes(b"%PDF-1.4")
out = tmp_path / "out"
def fake_local(p: str, base: str, **kwargs) -> bool: # noqa: ANN003
def fake_local(p: str, base: str, **kwargs) -> LocalParseResult: # noqa: ANN003
(Path(base) / Path(p).stem).mkdir(parents=True, exist_ok=True)
return True
return LocalParseResult.success()
monkeypatch.setattr(pdf_parser, "parse_document_with_mineru", fake_local)
monkeypatch.setattr(mineru_backend, "parse_document_with_mineru_result", fake_local)
workdir = mineru_backend.parse_pdf_to_workdir(pdf, out, config=MinerUConfig(mode="local"))
assert workdir == out / "exam"
@@ -87,11 +86,13 @@ def test_parse_pdf_to_workdir_dispatches_local(
def test_parse_pdf_to_workdir_local_failure_raises(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.parsing.engines.mineru import local as pdf_parser
pdf = tmp_path / "exam.pdf"
pdf.write_bytes(b"%PDF-1.4")
monkeypatch.setattr(pdf_parser, "parse_document_with_mineru", lambda *a, **k: False)
monkeypatch.setattr(
mineru_backend,
"parse_document_with_mineru_result",
lambda *a, **k: LocalParseResult.failure(LocalParseReason.EXCEPTION, "boom"),
)
with pytest.raises(MinerUError):
mineru_backend.parse_pdf_to_workdir(
@@ -124,19 +125,17 @@ def test_parse_pdf_to_workdir_dispatches_cloud(
def test_parse_document_to_workdir_dispatches_office_local(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.parsing.engines.mineru import local as local_parser
docx = tmp_path / "lesson.docx"
docx.write_bytes(b"office")
out = tmp_path / "out"
seen: list[str] = []
def fake_local(path: str, base: str, **_kwargs) -> bool:
def fake_local(path: str, base: str, **_kwargs) -> LocalParseResult:
seen.append(Path(path).name)
(Path(base) / Path(path).stem).mkdir(parents=True, exist_ok=True)
return True
return LocalParseResult.success()
monkeypatch.setattr(local_parser, "parse_document_with_mineru", fake_local)
monkeypatch.setattr(mineru_backend, "parse_document_with_mineru_result", fake_local)
workdir = mineru_backend.parse_document_to_workdir(docx, out, config=MinerUConfig(mode="local"))
@@ -222,8 +221,6 @@ def test_parse_local_rejects_bad_configured_path(
def test_parse_local_explains_legacy_cli_limit_for_office(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.parsing.engines.mineru import local as local_parser
source = tmp_path / "lesson.docx"
source.write_bytes(b"office")
monkeypatch.setattr(
@@ -237,8 +234,8 @@ def test_parse_local_explains_legacy_cli_limit_for_office(
},
)
monkeypatch.setattr(
local_parser,
"parse_document_with_mineru",
mineru_backend,
"parse_document_with_mineru_result",
lambda *_args, **_kwargs: pytest.fail("legacy CLI must not run"),
)