Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

10.8 KB
Raw Blame
"""Unified MinerU parsing entrypoint.

Hides the local-CLI vs cloud-API split behind one function so callers never
branch on backend. Both branches converge on the
same contract: write MinerU artifacts into a working directory and return its
path. Backend selection comes from ``document_parsing.json`` via
:func:`resolve_mineru_config`.
"""

from __future__ import annotations

from collections.abc import Callable
import logging
import os
from pathlib import Path
import shutil
import subprocess
from typing import Any

from .config import (
    MinerUConfig,
    MinerUError,
    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__)

# PATH-lookup order matches ``check_mineru_installed`` in local.py so the
# 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.TIMEOUT: "Local MinerU parsing timed out: {detail}",
    LocalParseReason.CANCELLED: "Local MinerU parsing was cancelled: {detail}",
    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,
    output_base: str | Path,
    *,
    config: MinerUConfig | None = None,
    on_output: Callable[[str], None] | None = None,
) -> Path:
    """Parse a MinerU-supported document or image into ``output_base``.

    The current MinerU input set is intentionally validated here as well as in
    :class:`ParseService`, because this module is also used directly by a few
    adapters and tests.
    """
    cfg = config or resolve_mineru_config()
    source_path = Path(source_path)
    suffix = source_path.suffix.lower()
    if suffix not in MINERU_SUPPORTED_FORMATS:
        raise MinerUError(
            f"MinerU does not support {suffix or 'files without an extension'}. "
            "Supported inputs are PDF, common raster images, DOCX, PPTX, and XLSX."
        )
    output_base = Path(output_base)
    output_base.mkdir(parents=True, exist_ok=True)

    if cfg.is_cloud:
        from .cloud import parse_cloud
        from .normalization import working_copy

        logger.info("Parsing %s via MinerU cloud API", source_path.name)
        with working_copy(source_path, output_base, cfg, on_output) as upload_path:
            return parse_cloud(upload_path, output_base, cfg, on_progress=on_output)

    return _parse_local(source_path, output_base, config=cfg, on_output=on_output)


def parse_pdf_to_workdir(
    pdf_path: str | Path,
    output_base: str | Path,
    *,
    config: MinerUConfig | None = None,
    on_output: Callable[[str], None] | None = None,
) -> Path:
    """Parse ``pdf_path`` and return the directory holding MinerU artifacts.

    The returned directory contains the parsed markdown +
    ``*_content_list.json`` (+ ``images/``) in whichever layout the active
    backend produces; :func:`load_parsed_paper` locates the content
    sub-directory regardless. ``on_output`` (if given) receives short progress
    lines from whichever backend runs — raw CLI output locally, task-state
    summaries from the cloud poller. Raises :class:`MinerUError` on failure.
    """
    pdf_path = Path(pdf_path)
    if pdf_path.suffix.lower() not in MINERU_PDF_FORMATS:
        raise MinerUError(f"parse_pdf_to_workdir expects a PDF file: {pdf_path}")
    return parse_document_to_workdir(
        pdf_path,
        output_base,
        config=config,
        on_output=on_output,
    )


def local_cli_probe(configured_path: str = "") -> dict[str, Any]:
    """Fast (no-subprocess) check for a local MinerU CLI.

    ``configured_path`` (the ``local_cli_path`` setting) takes precedence over
    PATH lookup so MinerU can live in an isolated env (uv tool / pipx /
    separate conda) without PATH games. Returns ``{found, command, path,
    source}`` where ``source`` is ``"configured"`` or ``"path"``. Cheap enough
    to run on every settings GET; the slower ``--version`` confirmation lives
    in :func:`local_cli_version` and only runs behind the explicit Test button.
    """
    configured = (configured_path or "").strip()
    if configured:
        candidate = Path(configured).expanduser()
        found = candidate.is_file() and os.access(candidate, os.X_OK)
        return {
            "found": found,
            "command": candidate.name,
            "path": str(candidate),
            "source": "configured",
        }
    for command in _LOCAL_CLI_COMMANDS:
        path = shutil.which(command)
        if path:
            return {"found": True, "command": command, "path": path, "source": "path"}
    return {"found": False, "command": "", "path": "", "source": "path"}


def local_cli_version(command: str, timeout: float = 60.0) -> str:
    """Run ``<command> --version`` and return the first output line ("" on any
    failure). ``command`` must be a whitelisted name or an existing executable
    path (the validated ``local_cli_path``) — anything else is refused. Heavy
    CLIs import slowly on first run, hence kept out of the settings GET path."""
    if command not in _LOCAL_CLI_COMMANDS:
        candidate = Path(command).expanduser()
        if not (candidate.is_file() and os.access(candidate, os.X_OK)):
            return ""
        command = str(candidate)
    try:
        result = subprocess.run(  # nosec B603 — whitelisted name or validated executable
            [command, "--version"],
            capture_output=True,
            text=True,
            timeout=timeout,
            check=False,
            shell=False,
        )
    except Exception:
        return ""
    if result.returncode != 0:
        return ""
    output = (result.stdout or result.stderr or "").strip()
    return output.splitlines()[0][:120] if output else ""


def _parse_local(
    source_path: Path,
    output_base: Path,
    *,
    config: MinerUConfig,
    on_output: Callable[[str], None] | None = None,
) -> Path:
    """Local-CLI branch: delegate to the existing subprocess parser and return
    the deterministic output directory it writes to (``<base>/<stem>``)."""
    from .models import model_env_overrides, render_env_overrides

    cli_command = None
    if (config.local_cli_path or "").strip():
        probe = local_cli_probe(config.local_cli_path)
        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).",
                code=str(LocalParseReason.CLI_MISSING),
            )
        cli_command = probe["path"]
    else:
        probe = local_cli_probe()
        if probe["found"]:
            cli_command = probe["path"]

    if (
        cli_command
        and Path(cli_command).name == "magic-pdf"
        and source_path.suffix.lower() != ".pdf"
    ):
        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.",
            code=str(LocalParseReason.LEGACY_CLI_INPUT),
        )

    # A lazy first-parse model download must honor the configured source and
    # custom address, not just the explicit Download button.
    download_env = model_env_overrides(config.model_download_source, config.model_download_endpoint)
    # Only the local CLI renders pages in this process tree; cloud mode never
    # does, so the Windows render-thread guard belongs on this branch alone.
    subprocess_env = {**download_env, **render_env_overrides()}

    logger.info("Parsing %s via local MinerU CLI (%s)", source_path.name, cli_command or "PATH")
    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 result.ok:
        reason = result.reason or LocalParseReason.EXCEPTION
        message = _LOCAL_FAILURE_MESSAGES[reason].format(detail=result.detail or "no output")
        if reason in {
            LocalParseReason.NONZERO_EXIT,
            LocalParseReason.NO_ARTIFACTS,
            LocalParseReason.EXCEPTION,
        }:
            message += (
                " Retry restarts this document from the beginning; completed compatible "
                "document parses will be reused. Incomplete output is retained for diagnosis."
            )
        raise MinerUError(
            message,
            code=str(reason),
            detail=result.detail,
        )
    working_dir = output_base / source_path.stem
    if not working_dir.is_dir():
        # Defensive: the CLI names its output dir after the source stem, but fall
        # back to the newest sub-directory if that assumption ever breaks.
        subdirs = sorted(
            (d for d in output_base.iterdir() if d.is_dir()),
            key=lambda d: d.stat().st_mtime,
            reverse=True,
        )
        if not subdirs:
            raise MinerUError("MinerU produced no output directory.")
        working_dir = subdirs[0]
    return working_dir


__all__ = [
    "MinerUError",
    "local_cli_probe",
    "local_cli_version",
    "parse_document_to_workdir",
    "parse_pdf_to_workdir",
]