feat(parsing): route Office and image files through MinerU (#1087)

This commit is contained in:
1553126902
2026-08-30 18:16:01 +08:00
parent ce7c2dc2dc
commit 87b006408c
7 changed files with 100 additions and 12 deletions

View File

@@ -251,7 +251,7 @@ class ChatStarterSettingsUpdate(BaseModel):
class MinerUSettingsUpdate(BaseModel):
"""MinerU PDF-parsing backend settings.
"""MinerU parsing backend settings.
``api_token`` is tri-state: ``None`` keeps the stored token (the UI sends
None when the user didn't edit the secret field), ``""`` clears it, and a

View File

@@ -93,7 +93,8 @@ _ENGINE_META: Dict[str, Dict[str, Any]] = {
"name": "MinerU",
"description": (
"Highest-fidelity multimodal parsing (layout, tables, formulas). "
"Local CLI downloads models, or use the hosted cloud API. PDF only."
"Local CLI downloads models, or use the hosted cloud API. "
"PDF, images, and modern Office (docx/pptx/xlsx)."
),
"needs_local_models": True,
},

View File

@@ -26,6 +26,28 @@ class MinerUError(RuntimeError):
surfaces it as a stream error."""
# MinerU's documented input contract (github.com/opendatalab/MinerU): PDF,
# images, and the modern Office formats. Shared by the engine's
# ``supported_formats`` routing gate and the local CLI's suffix check so the
# two never drift apart. Legacy .doc/.ppt/.xls stay off the routing path —
# the local CLI does not accept them (the cloud API does).
MINERU_SUPPORTED_SUFFIXES = frozenset(
{
".pdf",
".png",
".jpg",
".jpeg",
".jp2",
".webp",
".gif",
".bmp",
".docx",
".pptx",
".xlsx",
}
)
@dataclass(frozen=True)
class MinerUConfig:
"""Validated MinerU parsing configuration.

View File

@@ -13,12 +13,13 @@ from typing import Callable, Optional
from ...base import ReadinessReport
from ...signature import ParserSignature
from .._versions import package_version
from .config import MinerUConfig, resolve_mineru_config
from .config import MINERU_SUPPORTED_SUFFIXES, MinerUConfig, resolve_mineru_config
from .readiness import mineru_readiness
class MinerUParser:
"""PDF → multimodal ``content_list`` via the MinerU CLI or cloud API."""
"""PDF/Office/image → multimodal ``content_list`` via the MinerU CLI or
cloud API."""
name = "mineru"
needs_local_models = True
@@ -34,7 +35,7 @@ class MinerUParser:
return resolve_mineru_config()
def supported_formats(self) -> frozenset[str]:
return frozenset({".pdf"})
return MINERU_SUPPORTED_SUFFIXES
def signature(self, config: MinerUConfig) -> ParserSignature:
version = f"cloud:{config.api_base_url}" if config.is_cloud else package_version("mineru")

View File

@@ -1,6 +1,7 @@
#!/usr/bin/env python
"""
Parse PDF files using MinerU and save results to reference_papers directory
Parse documents (PDF/Office/images) using MinerU and save results to
reference_papers directory
"""
import argparse
@@ -13,6 +14,8 @@ import subprocess
import sys
import time
from .config import MINERU_SUPPORTED_SUFFIXES
# Minimum seconds between on_output callbacks. MinerU's CLI emits tqdm-style
# progress that universal-newline decoding turns into many lines per second;
# without a floor the trace panel gets flooded during model downloads.
@@ -61,10 +64,10 @@ def parse_pdf_with_mineru(
extra_env: dict[str, str] | None = None,
):
"""
Parse PDF file using MinerU
Parse a document (PDF/Office/image) using MinerU
Args:
pdf_path: Path to PDF file
pdf_path: Path to the document to parse
output_base_dir: Base path for output directory, defaults to reference_papers
on_output: Optional callback invoked (rate-limited) with each line of
the CLI's combined stdout/stderr, so callers can surface live
@@ -96,11 +99,11 @@ def parse_pdf_with_mineru(
pdf_file = Path(pdf_path).resolve()
if not pdf_file.exists():
print(f"✗ Error: PDF file does not exist: {pdf_file}")
print(f"✗ Error: file does not exist: {pdf_file}")
return False
if not pdf_file.suffix.lower() == ".pdf":
print(f"✗ Error: File is not PDF format: {pdf_file}")
if pdf_file.suffix.lower() not in MINERU_SUPPORTED_SUFFIXES:
print(f"✗ Error: unsupported file type for MinerU: {pdf_file.suffix or '(no extension)'}")
return False
# Project root is 3 levels up from deeptutor/tools/question/
@@ -119,7 +122,7 @@ def parse_pdf_with_mineru(
print(f"⚠️ Directory already exists, replacing: {output_dir.name}")
shutil.rmtree(output_dir)
print(f"📄 PDF file: {pdf_file}")
print(f"📄 Input file: {pdf_file}")
print(f"📁 Output directory: {output_dir}")
print("→ Starting parsing...")

View File

@@ -93,6 +93,17 @@ def test_mineru_cloud_readiness_needs_token() -> None:
assert mineru_readiness(MinerUConfig(mode="cloud", api_token="tok")).ready is True
def test_mineru_supported_formats_include_office_and_images() -> None:
parser = factory.get_parser("mineru")
formats = parser.supported_formats()
assert ".pdf" in formats
assert {".docx", ".pptx", ".xlsx"} <= formats
assert {".png", ".jpg", ".jpeg"} <= formats
# Legacy Office stays off the routing path: the local CLI does not accept
# .doc/.ppt/.xls, so the engine must not claim them either.
assert not {".doc", ".ppt", ".xls"} & formats
def test_docling_signature_distinguishes_local_and_remote() -> None:
parser = factory.get_parser("docling")
from deeptutor.services.parsing.engines.docling.config import DoclingConfig

View File

@@ -223,6 +223,56 @@ def test_pdf_parser_streams_output_lines(tmp_path: Path, monkeypatch: pytest.Mon
assert (out / "exam" / "auto" / "exam.md").exists()
def test_pdf_parser_accepts_office_and_image_inputs(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.parsing.engines.mineru import local as pdf_parser
doc = tmp_path / "notes.docx"
doc.write_bytes(b"PK\x05\x06")
out = tmp_path / "out"
spawned: list[list[str]] = []
class FakeProcess:
def __init__(self, cmd, **kwargs): # noqa: ANN002, ANN003
spawned.append(cmd)
target = Path(cmd[cmd.index("-o") + 1]) / "notes"
(target / "auto").mkdir(parents=True, exist_ok=True)
(target / "auto" / "notes.md").write_text("# parsed", encoding="utf-8")
self.stdout = iter(["parsing page 1/2\n"])
def wait(self):
return 0
monkeypatch.setattr(pdf_parser, "check_mineru_installed", lambda: "mineru")
monkeypatch.setattr(pdf_parser.subprocess, "Popen", FakeProcess)
ok = pdf_parser.parse_pdf_with_mineru(str(doc), str(out))
assert ok is True
# The .docx reached the CLI instead of being rejected as "not PDF".
assert spawned and spawned[0][spawned[0].index("-p") + 1] == str(doc.resolve())
def test_pdf_parser_rejects_unsupported_suffixes(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from deeptutor.services.parsing.engines.mineru import local as pdf_parser
doc = tmp_path / "archive.zip"
doc.write_bytes(b"PK\x05\x06")
monkeypatch.setattr(pdf_parser, "check_mineru_installed", lambda: "mineru")
monkeypatch.setattr(
pdf_parser.subprocess, "Popen", lambda *a, **k: pytest.fail("CLI must not spawn")
)
ok = pdf_parser.parse_pdf_with_mineru(str(doc), str(tmp_path / "out"))
assert ok is False
def test_parse_cloud_reports_progress(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
pdf = tmp_path / "exam.pdf"
pdf.write_bytes(b"%PDF-1.4")