DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(parsing): integrate MinerU multi-format inputs (#1087)
Bingxi Zhao (Frank)da9492fbaffa
diff --git a/README.md b/README.mdindex 2f5157888..6e0b433e6 100644--- a/README.md+++ b/README.md@@ -606,7 +606,7 @@ Knowledge bases are the document collections behind RAG — they ground Chat turCreating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). A KB can also track **GitHub repositories** (repo, branch, glob) or **documentation-site URLs** (bounded crawl depth and page count); on-demand sync hash-diffs added, changed, and removed content so followed documentation stays current without re-uploading. Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, or LiteParse — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. Docling can also run in **remote** mode against a Docling Serve server (no local install or models needed), configured via **Settings → Document Parsing** (`mode=remote`, a server base URL, and an optional API key) or the `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables. Tika is remote-only and points at an Apache Tika server (`TIKA_SERVER_URL`). The CLI mirrors the lifecycle with `list/info/create/add/search/set-default/delete`, source add/remove commands, `list-sources`, and `sync`.-The built-in LightRAG engine is installed with `pip install 'deeptutor[rag-lightrag]'`. That extra contains the supported LightRAG SDK but does not install MinerU. Choose MinerU independently in Document Parsing and either configure its cloud mode or install its local CLI when structured PDF parsing is wanted; text-only and the other parsing engines do not require MinerU.+The built-in LightRAG engine is installed with `pip install 'deeptutor[rag-lightrag]'`. That extra contains the supported LightRAG SDK but does not install MinerU. Choose MinerU independently in Document Parsing and either configure its cloud mode or install its current local CLI when structured parsing is wanted. MinerU accepts PDF, common raster images, DOCX, PPTX, and XLSX; the legacy `magic-pdf` command remains PDF-only. Text-only and the other parsing engines do not require MinerU.</details>diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex b5c0f1582..95135f461 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -251,7 +251,7 @@ class ChatStarterSettingsUpdate(BaseModel):class MinerUSettingsUpdate(BaseModel):- """MinerU PDF-parsing backend settings.+ """MinerU document-parsing backend settings.``api_token`` is tri-state: ``None`` keeps the stored token (the UI sendsNone when the user didn't edit the secret field), ``""`` clears it, and adiff --git a/deeptutor/services/parsing/engines/factory.py b/deeptutor/services/parsing/engines/factory.pyindex 289113735..890533b58 100644--- a/deeptutor/services/parsing/engines/factory.py+++ b/deeptutor/services/parsing/engines/factory.py@@ -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. Supports "+ "PDF, common images, DOCX, PPTX, and XLSX."),"needs_local_models": True,},diff --git a/deeptutor/services/parsing/engines/mineru/backend.py b/deeptutor/services/parsing/engines/mineru/backend.pyindex ac3db2f09..a1c75372b 100644--- a/deeptutor/services/parsing/engines/mineru/backend.py+++ b/deeptutor/services/parsing/engines/mineru/backend.py@@ -1,7 +1,7 @@"""Unified MinerU parsing entrypoint.-Hides the local-CLI vs cloud-API split behind one function so callers (the-mimic-mode adapter) never branch on backend. Both branches converge on the+Hides the local-CLI vs cloud-API split behind one function so callers never+branch on backend. Both branches converge on thesame contract: write MinerU artifacts into a working directory and return itspath. Backend selection comes from ``document_parsing.json`` via:func:`resolve_mineru_config`.@@ -22,12 +22,46 @@ from .config import (MinerUError,resolve_mineru_config,)+from .formats import MINERU_PDF_FORMATS, MINERU_SUPPORTED_FORMATSlogger = 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 = ("magic-pdf", "mineru")+_LOCAL_CLI_COMMANDS = ("mineru", "magic-pdf")+++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++ logger.info("Parsing %s via MinerU cloud API", source_path.name)+ return parse_cloud(source_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(@@ -46,18 +80,15 @@ def parse_pdf_to_workdir(lines from whichever backend runs — raw CLI output locally, task-statesummaries from the cloud poller. Raises :class:`MinerUError` on failure."""- cfg = config or resolve_mineru_config()pdf_path = Path(pdf_path)- output_base = Path(output_base)- output_base.mkdir(parents=True, exist_ok=True)-- if cfg.is_cloud:- from .cloud import parse_cloud-- logger.info("Parsing %s via MinerU cloud API", pdf_path.name)- return parse_cloud(pdf_path, output_base, cfg, on_progress=on_output)-- return _parse_local(pdf_path, output_base, config=cfg, on_output=on_output)+ 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]:@@ -115,7 +146,7 @@ def local_cli_version(command: str, timeout: float = 60.0) -> str:def _parse_local(- pdf_path: Path,+ source_path: Path,output_base: Path,*,config: MinerUConfig,@@ -123,7 +154,7 @@ def _parse_local() -> Path:"""Local-CLI branch: delegate to the existing subprocess parser and returnthe deterministic output directory it writes to (``<base>/<stem>``)."""- from .local import parse_pdf_with_mineru+ from .local import parse_document_with_minerufrom .models import model_env_overrides, render_env_overridescli_command = None@@ -135,6 +166,20 @@ def _parse_local("Fix it in Settings → MinerU (or clear it to auto-detect from PATH).")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 mineru`) to parse images, DOCX, PPTX, or XLSX."+ )# A lazy first-parse model download must honor the configured source and# custom address, not just the explicit Download button.@@ -143,9 +188,9 @@ def _parse_local(# 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)", pdf_path.name, cli_command or "PATH")- ok = parse_pdf_with_mineru(- str(pdf_path),+ logger.info("Parsing %s via local MinerU CLI (%s)", source_path.name, cli_command or "PATH")+ ok = parse_document_with_mineru(+ str(source_path),str(output_base),on_output=on_output,cli_command=cli_command,@@ -156,9 +201,9 @@ def _parse_local("Local MinerU parsing failed. Ensure MinerU is installed ""(`pip install mineru`) or switch to cloud mode in Settings → MinerU.")- working_dir = output_base / pdf_path.stem+ working_dir = output_base / source_path.stemif not working_dir.is_dir():- # Defensive: the CLI names its output dir after the PDF stem, but fall+ # 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()),@@ -171,4 +216,10 @@ def _parse_local(return working_dir-__all__ = ["MinerUError", "local_cli_probe", "local_cli_version", "parse_pdf_to_workdir"]+__all__ = [+ "MinerUError",+ "local_cli_probe",+ "local_cli_version",+ "parse_document_to_workdir",+ "parse_pdf_to_workdir",+]diff --git a/deeptutor/services/parsing/engines/mineru/cloud.py b/deeptutor/services/parsing/engines/mineru/cloud.pyindex f25593f3c..e0eab27cd 100644--- a/deeptutor/services/parsing/engines/mineru/cloud.py+++ b/deeptutor/services/parsing/engines/mineru/cloud.py@@ -1,9 +1,9 @@"""MinerU cloud (mineru.net) v4 API backend.-Implements the token-required *Precision API* flow for a single local PDF:+Implements the token-required *Precision API* flow for one local input:1. ``POST /api/v4/file-urls/batch`` → ``{batch_id, file_urls: [signed_url]}``-2. ``PUT`` the raw PDF bytes to ``signed_url`` (no auth, no Content-Type)+2. ``PUT`` the raw file bytes to ``signed_url`` (no auth, no Content-Type)3. Poll ``GET /api/v4/extract-results/batch/{batch_id}`` until the file's``state`` reaches ``done`` / ``failed``4. Download the ``full_zip_url`` archive and extract it into a working dir@@ -31,6 +31,7 @@ import httpxfrom deeptutor.services.keypool import KeyPoolfrom .config import MinerUConfig, MinerUError+from .formats import MINERU_SUPPORTED_FORMATSlogger = logging.getLogger(__name__)@@ -51,7 +52,7 @@ _MAX_ENTRIES = 5000def parse_cloud(- pdf_path: Path,+ source_path: Path,output_base: Path,config: MinerUConfig,*,@@ -59,9 +60,9 @@ def parse_cloud(timeout: float = DEFAULT_TIMEOUT_SECONDS,on_progress: Callable[[str], None] | None = None,) -> Path:- """Parse ``pdf_path`` via the MinerU cloud API; return the working dir.+ """Parse ``source_path`` via the MinerU cloud API; return the working dir.- The working dir sits under ``output_base`` (named after the PDF stem) and+ The working dir sits under ``output_base`` (named after the input stem) andholds the unzipped MinerU artifacts. ``on_progress`` (if given) receives ashort status line whenever the polled task state / page count changes.Raises :class:`MinerUError` on any misconfiguration, API error, timeout,@@ -72,9 +73,11 @@ def parse_cloud("MinerU cloud mode is selected but no API token is configured. ""Add a token in Settings → MinerU, or switch to local mode.")- pdf_path = Path(pdf_path)- if not pdf_path.is_file():- raise MinerUError(f"PDF file not found: {pdf_path}")+ source_path = Path(source_path)+ if not source_path.is_file():+ raise MinerUError(f"Input file not found: {source_path}")+ if source_path.suffix.lower() not in MINERU_SUPPORTED_FORMATS:+ raise MinerUError(f"Unsupported MinerU cloud input format: {source_path.suffix or 'none'}")base_url = config.api_base_url.rstrip("/")key_pool = KeyPool(config.api_keys)@@ -88,15 +91,15 @@ def parse_cloud(logger.debug("on_progress callback failed", exc_info=True)with httpx.Client(base_url=base_url, headers={"Accept": "application/json"}) as client:- report(f"MinerU cloud: requesting upload slot for {pdf_path.name}")- batch_id, upload_url = _request_upload(client, pdf_path, config, key_pool)- size_mb = pdf_path.stat().st_size / (1024 * 1024)- report(f"MinerU cloud: uploading {pdf_path.name} ({size_mb:.1f} MB)")- _upload_file(pdf_path, upload_url)+ report(f"MinerU cloud: requesting upload slot for {source_path.name}")+ batch_id, upload_url = _request_upload(client, source_path, config, key_pool)+ size_mb = source_path.stat().st_size / (1024 * 1024)+ report(f"MinerU cloud: uploading {source_path.name} ({size_mb:.1f} MB)")+ _upload_file(source_path, upload_url)zip_url = _poll_for_zip(client,batch_id,- pdf_path.name,+ source_path.name,poll_interval=poll_interval,timeout=timeout,on_progress=on_progress,@@ -106,10 +109,10 @@ def parse_cloud(archive_bytes = _download(zip_url)report("MinerU cloud: extracting archive")- working_dir = output_base / pdf_path.stem+ working_dir = output_base / source_path.stem_reset_dir(working_dir)_extract_archive(archive_bytes, working_dir)- logger.info("MinerU cloud parse complete: %s → %s", pdf_path.name, working_dir)+ logger.info("MinerU cloud parse complete: %s → %s", source_path.name, working_dir)return working_dir@@ -119,10 +122,10 @@ def parse_cloud(def _request_upload(- client: httpx.Client, pdf_path: Path, config: MinerUConfig, key_pool: KeyPool+ client: httpx.Client, source_path: Path, config: MinerUConfig, key_pool: KeyPool) -> tuple[str, str]:"""POST file-urls/batch → ``(batch_id, signed_upload_url)``."""- file_entry: dict[str, object] = {"name": pdf_path.name, "is_ocr": config.is_ocr}+ file_entry: dict[str, object] = {"name": source_path.name, "is_ocr": config.is_ocr}body: dict[str, object] = {"files": [file_entry],"model_version": config.model_version,@@ -141,19 +144,19 @@ def _request_upload(return batch_id, str(file_urls[0])-def _upload_file(pdf_path: Path, upload_url: str) -> None:- """PUT the PDF bytes to the signed URL.+def _upload_file(source_path: Path, upload_url: str) -> None:+ """PUT the input bytes to the signed URL.The signed URL carries its own auth; per MinerU's docs we must NOT send an``Authorization`` or ``Content-Type`` header (a stray Content-Type breaksthe OSS signature)."""- data = pdf_path.read_bytes()+ data = source_path.read_bytes()try:response = httpx.put(upload_url, content=data, timeout=_UPLOAD_TIMEOUT_SECONDS)response.raise_for_status()except httpx.HTTPError as exc:- raise MinerUError(f"Failed to upload PDF to MinerU: {exc}") from exc+ raise MinerUError(f"Failed to upload file to MinerU: {exc}") from excdef _poll_for_zip(diff --git a/deeptutor/services/parsing/engines/mineru/engine.py b/deeptutor/services/parsing/engines/mineru/engine.pyindex 53df39250..02cc579a3 100644--- a/deeptutor/services/parsing/engines/mineru/engine.py+++ b/deeptutor/services/parsing/engines/mineru/engine.py@@ -1,8 +1,7 @@"""MinerU engine adapter implementing the ``Parser`` protocol.-Thin wrapper over the existing ``parse_pdf_to_workdir`` (local CLI / cloud-dispatch). The readiness gate (``readiness.py``) enforces "no silent model-download" before a local parse runs.+The readiness gate (``readiness.py``) enforces "no silent model download"+before a local parse runs."""from __future__ import annotations@@ -14,11 +13,12 @@ from ...base import ReadinessReportfrom ...signature import ParserSignaturefrom .._versions import package_versionfrom .config import MinerUConfig, resolve_mineru_config+from .formats import MINERU_SUPPORTED_FORMATSfrom .readiness import mineru_readinessclass MinerUParser:- """PDF → multimodal ``content_list`` via the MinerU CLI or cloud API."""+ """Documents/images → multimodal IR via the MinerU CLI or cloud API."""name = "mineru"needs_local_models = True@@ -34,7 +34,7 @@ class MinerUParser:return resolve_mineru_config()def supported_formats(self) -> frozenset[str]:- return frozenset({".pdf"})+ return MINERU_SUPPORTED_FORMATSdef signature(self, config: MinerUConfig) -> ParserSignature:version = f"cloud:{config.api_base_url}" if config.is_cloud else package_version("mineru")@@ -62,11 +62,11 @@ class MinerUParser:config: MinerUConfig,on_output: Optional[Callable[[str], None]] = None,) -> None:- from .backend import parse_pdf_to_workdir+ from .backend import parse_document_to_workdir# Writes ``<workdir>/<stem>/...`` (markdown + content_list + images);# ParseService loads the IR from ``workdir`` afterwards.- parse_pdf_to_workdir(source_path, workdir, config=config, on_output=on_output)+ parse_document_to_workdir(source_path, workdir, config=config, on_output=on_output)__all__ = ["MinerUParser"]diff --git a/deeptutor/services/parsing/engines/mineru/formats.py b/deeptutor/services/parsing/engines/mineru/formats.pynew file mode 100644index 000000000..c9646dcaf--- /dev/null+++ b/deeptutor/services/parsing/engines/mineru/formats.py@@ -0,0 +1,32 @@+"""Input formats supported by the current MinerU CLI and hosted API."""++from __future__ import annotations++# Keep this list aligned with ``mineru/cli/common.py`` in the official MinerU+# project. DeepTutor uses dotted, lower-case suffixes throughout its parser+# protocol.+MINERU_PDF_FORMATS = frozenset({".pdf"})+MINERU_IMAGE_FORMATS = frozenset(+ {+ ".bmp",+ ".gif",+ ".jp2",+ ".jpeg",+ ".jpg",+ ".png",+ ".tiff",+ ".webp",+ }+)+MINERU_OFFICE_FORMATS = frozenset({".docx", ".pptx", ".xlsx"})+MINERU_SUPPORTED_FORMATS = frozenset(+ MINERU_PDF_FORMATS | MINERU_IMAGE_FORMATS | MINERU_OFFICE_FORMATS+)+++__all__ = [+ "MINERU_IMAGE_FORMATS",+ "MINERU_OFFICE_FORMATS",+ "MINERU_PDF_FORMATS",+ "MINERU_SUPPORTED_FORMATS",+]diff --git a/deeptutor/services/parsing/engines/mineru/local.py b/deeptutor/services/parsing/engines/mineru/local.pyindex 066cd3eb5..5d1e5af0e 100644--- a/deeptutor/services/parsing/engines/mineru/local.py+++ b/deeptutor/services/parsing/engines/mineru/local.py@@ -1,7 +1,5 @@#!/usr/bin/env python-"""-Parse PDF files using MinerU and save results to reference_papers directory-"""+"""Run MinerU's local CLI for supported documents and images."""import argparsefrom collections import deque@@ -13,6 +11,8 @@ import subprocessimport sysimport time+from .formats import MINERU_SUPPORTED_FORMATS+# 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.@@ -25,46 +25,46 @@ def check_mineru_installed():# Security: Using partial path is intentional here - we need to find# the command in user's PATH. These are trusted CLI tools, not user input.result = subprocess.run(- ["magic-pdf", "--version"], # nosec B607+ ["mineru", "--version"], # nosec B607check=False,capture_output=True,text=True,shell=False,)if result.returncode == 0:- return "magic-pdf"+ return "mineru"except FileNotFoundError:passtry:# Security: Same as above - intentionally using PATH lookup for CLI tool.result = subprocess.run(- ["mineru", "--version"], # nosec B607+ ["magic-pdf", "--version"], # nosec B607check=False,capture_output=True,text=True,shell=False,)if result.returncode == 0:- return "mineru"+ return "magic-pdf"except FileNotFoundError:passreturn None-def parse_pdf_with_mineru(- pdf_path: str,+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,):"""- Parse PDF file using MinerU+ Parse a supported document or image using MinerU.Args:- pdf_path: Path to PDF file+ source_path: Path to a PDF, image, DOCX, PPTX, or XLSX fileoutput_base_dir: Base path for output directory, defaults to reference_paperson_output: Optional callback invoked (rate-limited) with each line ofthe CLI's combined stdout/stderr, so callers can surface live@@ -94,13 +94,19 @@ def parse_pdf_with_mineru(return Falseprint(f"✓ Detected MinerU command: {mineru_cmd}")- pdf_file = Path(pdf_path).resolve()- if not pdf_file.exists():- print(f"✗ Error: PDF file does not exist: {pdf_file}")+ source_file = Path(source_path).resolve()+ if not source_file.exists():+ print(f"✗ Error: Input file does not exist: {source_file}")+ return False++ suffix = source_file.suffix.lower()+ if suffix not in MINERU_SUPPORTED_FORMATS:+ print(f"✗ Error: Unsupported MinerU input format: {source_file}")return False- if not pdf_file.suffix.lower() == ".pdf":- print(f"✗ Error: File is not PDF format: {pdf_file}")+ 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# Project root is 3 levels up from deeptutor/tools/question/@@ -112,22 +118,24 @@ def parse_pdf_with_mineru(base_dir.mkdir(parents=True, exist_ok=True)- pdf_name = pdf_file.stem- output_dir = base_dir / pdf_name+ source_name = source_file.stem+ output_dir = base_dir / source_nameif output_dir.exists():print(f"⚠️ Directory already exists, replacing: {output_dir.name}")shutil.rmtree(output_dir)- print(f"📄 PDF file: {pdf_file}")+ print(f"📄 Input file: {source_file}")print(f"📁 Output directory: {output_dir}")print("→ Starting parsing...")try:temp_output = base_dir / "temp_mineru_output"+ if temp_output.exists():+ shutil.rmtree(temp_output)temp_output.mkdir(parents=True, exist_ok=True)- cmd = [mineru_cmd, "-p", str(pdf_file), "-o", str(temp_output)]+ cmd = [mineru_cmd, "-p", str(source_file), "-o", str(temp_output)]print(f"🔧 Executing command: {' '.join(cmd)}")@@ -188,7 +196,7 @@ def parse_pdf_with_mineru(# Move MinerU-generated content to target directoryif source_folder.exists() and source_folder.is_dir():- # If source_folder is the PDF-named directory, move its contents+ # If source_folder is the source-named directory, move its contentsfor item in source_folder.iterdir():dest_item = output_dir / item.nameif dest_item.exists():@@ -223,6 +231,27 @@ def parse_pdf_with_mineru(return False+def parse_pdf_with_mineru(+ pdf_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,+):+ """Backward-compatible PDF-only wrapper around the generic CLI adapter."""+ pdf_file = Path(pdf_path)+ if pdf_file.suffix.lower() != ".pdf":+ print(f"✗ Error: File is not PDF format: {pdf_file.resolve()}")+ return False+ return parse_document_with_mineru(+ pdf_path,+ output_base_dir,+ on_output=on_output,+ cli_command=cli_command,+ extra_env=extra_env,+ )++def main():"""Main function"""parser = argparse.ArgumentParser(diff --git a/deeptutor/services/parsing/service.py b/deeptutor/services/parsing/service.pyindex c86212217..f8be721fc 100644--- a/deeptutor/services/parsing/service.py+++ b/deeptutor/services/parsing/service.py@@ -45,6 +45,16 @@ class ParseService:load_document_parsing_settings().get("engine") or _DEFAULT_DOCUMENT_PARSING_ENGINE)+ def supports(self, source_path: str | Path, *, engine: Optional[str] = None) -> bool:+ """Return whether the selected engine advertises support for this path.++ This is a cheap routing check only: it does not require the file to+ exist, initialize models, or evaluate engine readiness.+ """+ engine_name = (engine or self.active_engine()).strip().lower()+ supported = get_parser(engine_name).supported_formats()+ return not supported or Path(source_path).suffix.lower() in supported+def parse(self,source_path: str | Path,diff --git a/deeptutor/services/rag/pipelines/graphrag/ingestion.py b/deeptutor/services/rag/pipelines/graphrag/ingestion.pyindex 26b3d32fd..b942fc142 100644--- a/deeptutor/services/rag/pipelines/graphrag/ingestion.py+++ b/deeptutor/services/rag/pipelines/graphrag/ingestion.py@@ -36,11 +36,11 @@ def _unique_txt_path(target_dir: Path, source: Path, used: set[str]) -> Path:return target_dir / candidate-def _extract_parser_text(path: Path) -> str:+def _extract_parser_text(path: Path, parse_service=None) -> str: # noqa: ANN001from deeptutor.services.parsing import ParserError, get_parse_servicetry:- parsed = get_parse_service().parse(path)+ parsed = (parse_service or get_parse_service()).parse(path)except ParserError as exc:logger.error("GraphRAG ingestion: failed to parse %s: %s", path.name, exc)return ""@@ -64,8 +64,9 @@ async def prepare_input(file_paths: Iterable[str], root_dir: Path) -> int:go through the shared document-parse bridge, so the active settings engine(text-only, MinerU, Docling, markitdown) owns conversion before GraphRAGsees text.- Image files are skipped in this text-first path; unsupported files are- logged and ignored.+ Images go through the active parser when it supports their suffix (for+ example MinerU); otherwise they are skipped. Unsupported files are logged+ and ignored."""target_dir = storage.input_dir(root_dir)target_dir.mkdir(parents=True, exist_ok=True)@@ -89,10 +90,19 @@ async def prepare_input(file_paths: Iterable[str], root_dir: Path) -> int:written += _write_doc(target_dir, path, text, used)for file_path_str in classification.image_files:- logger.warning(- "GraphRAG ingestion skips image file (text-only engine): %s",- Path(file_path_str).name,- )+ from deeptutor.services.parsing import get_parse_service++ path = Path(file_path_str)+ parse_service = get_parse_service()+ supports = getattr(parse_service, "supports", lambda _path: False)+ if supports(path):+ text = _extract_parser_text(path, parse_service)+ written += _write_doc(target_dir, path, text, used)+ else:+ logger.warning(+ "GraphRAG ingestion skips image unsupported by the active parser: %s",+ path.name,+ )for file_path_str in classification.unsupported:logger.warning("GraphRAG ingestion skips unsupported file: %s", Path(file_path_str).name)diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.pyindex b1bdfd196..1cb7d247c 100644--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py@@ -99,7 +99,30 @@ class LlamaIndexDocumentLoader:for file_path_str in classification.image_files:path = Path(file_path_str)- image_sources.append(_ImageSource(path=path, origin=path))+ from deeptutor.services.parsing import get_parse_service++ parse_service = get_parse_service()+ supports = getattr(parse_service, "supports", lambda _path: False)+ if supports(path):+ self.logger.info(f"Parsing image with active document parser: {path.name}")+ text, extracted_images, parse_engine = await asyncio.to_thread(+ self._parse_document, path, parse_service+ )+ if text.strip() or extracted_images:+ self._append_if_nonempty(+ documents,+ path,+ text,+ parse_engine=parse_engine,+ extracted_image_count=len(extracted_images),+ )+ image_sources.extend(extracted_images)+ else:+ # Preserve the pre-parser behavior when an image-capable+ # engine fails or yields no usable IR.+ image_sources.append(_ImageSource(path=path, origin=path))+ else:+ image_sources.append(_ImageSource(path=path, origin=path))if image_sources:documents.extend(@@ -113,7 +136,11 @@ class LlamaIndexDocumentLoader:return documents- def _parse_document(self, file_path: Path) -> tuple[str, list[_ImageSource], str]:+ def _parse_document(+ self,+ file_path: Path,+ parse_service=None, # noqa: ANN001+ ) -> tuple[str, list[_ImageSource], str]:"""Parse a document through the shared, engine-pluggable parse layer.Returns ``(text, extracted_images, engine)``. A parse failure (engine@@ -124,7 +151,7 @@ class LlamaIndexDocumentLoader:from deeptutor.services.parsing import ParserError, get_parse_servicetry:- parsed = get_parse_service().parse(file_path)+ parsed = (parse_service or get_parse_service()).parse(file_path)except ParserError as exc:self.logger.warning(f"Skipped {file_path.name}: the active document-parsing engine could "diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.pyindex 5999a76ed..0ca78850b 100644--- a/tests/services/parsing/test_engines.py+++ b/tests/services/parsing/test_engines.py@@ -85,6 +85,25 @@ def test_mineru_signature_distinguishes_local_and_cloud() -> None:assert local != cloud+def test_mineru_advertises_current_document_and_image_formats() -> None:+ parser = factory.get_parser("mineru")++ assert parser.supported_formats() == {+ ".pdf",+ ".png",+ ".jpeg",+ ".jpg",+ ".jp2",+ ".webp",+ ".gif",+ ".bmp",+ ".tiff",+ ".docx",+ ".pptx",+ ".xlsx",+ }++def test_mineru_cloud_readiness_needs_token() -> None:from deeptutor.services.parsing.engines.mineru.config import MinerUConfigfrom deeptutor.services.parsing.engines.mineru.readiness import mineru_readinessdiff --git a/tests/services/parsing/test_parse_service.py b/tests/services/parsing/test_parse_service.pyindex c3b41405e..e810417eb 100644--- a/tests/services/parsing/test_parse_service.py+++ b/tests/services/parsing/test_parse_service.py@@ -109,6 +109,18 @@ def test_unsupported_format_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatservice.parse(_pdf(tmp_path, b"data", "notes.txt"), engine="fake")+def test_supports_is_a_side_effect_free_suffix_check(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ parser = _FakeParser()+ _use(monkeypatch, parser)+ service = ParseService(cache_root=tmp_path / "cache")++ assert service.supports(tmp_path / "missing.pdf", engine="fake") is True+ assert service.supports(tmp_path / "missing.png", engine="fake") is False+ assert parser.calls == []++def test_missing_file_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:_use(monkeypatch, _FakeParser())service = ParseService(cache_root=tmp_path / "cache")diff --git a/tests/services/rag/test_graphrag_pipeline.py b/tests/services/rag/test_graphrag_pipeline.pyindex eaaea1cae..a8f9b4728 100644--- a/tests/services/rag/test_graphrag_pipeline.py+++ b/tests/services/rag/test_graphrag_pipeline.py@@ -898,6 +898,37 @@ def test_ingestion_uses_active_parse_service_for_parser_files(tmp_path, monkeypa)+def test_ingestion_parses_images_when_active_engine_supports_them(tmp_path, monkeypatch) -> None:+ from deeptutor.services import parsing++ root = tmp_path / "root"+ image = tmp_path / "diagram.png"+ image.write_bytes(b"\x89PNG\r\n")+ calls: list[Path] = []++ class _Parsed:+ markdown = "OCR text from diagram"+ blocks: list[dict] = []++ class _ParseService:+ def supports(self, path: Path) -> bool:+ return path.suffix == ".png"++ def parse(self, path: Path):+ calls.append(path)+ return _Parsed()++ monkeypatch.setattr(parsing, "get_parse_service", lambda: _ParseService())++ count = asyncio.run(ingestion.prepare_input([str(image)], root))++ assert count == 1+ assert calls == [image]+ assert (storage.input_dir(root) / "diagram.txt").read_text(encoding="utf-8") == (+ "OCR text from diagram"+ )++def test_ingestion_avoids_name_collisions(tmp_path) -> None:root = tmp_path / "root"a = tmp_path / "a" / "doc.txt"diff --git a/tests/services/rag/test_llamaindex_document_loader.py b/tests/services/rag/test_llamaindex_document_loader.pyindex 30a5fbf6f..003779151 100644--- a/tests/services/rag/test_llamaindex_document_loader.py+++ b/tests/services/rag/test_llamaindex_document_loader.py@@ -69,6 +69,38 @@ def test_loader_routes_parser_files_through_active_parse_engine(assert "Block two" in by_name["paper.pdf"]+def test_loader_routes_images_through_active_parser_when_supported(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ pytest.importorskip("llama_index.core")+ import deeptutor.services.parsing as parsing+ from deeptutor.services.parsing.types import ParsedDocument+ from deeptutor.services.rag.pipelines.llamaindex.document_loader import (+ LlamaIndexDocumentLoader,+ )++ image_path = tmp_path / "diagram.png"+ image_path.write_bytes(b"\x89PNG\r\n")+ calls: list[Path] = []++ class _StubService:+ def supports(self, path: Path) -> bool:+ return path.suffix == ".png"++ def parse(self, path: Path, **_kwargs):+ calls.append(path)+ return ParsedDocument(markdown="OCR and layout from MinerU", engine="mineru")++ service = _StubService()+ monkeypatch.setattr(parsing, "get_parse_service", lambda: service)++ documents = asyncio.run(LlamaIndexDocumentLoader().load([str(image_path)]))++ assert calls == [image_path]+ assert len(documents) == 1+ assert documents[0].text == "OCR and layout from MinerU"++def test_loader_keeps_event_loop_responsive_while_parser_blocks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/tools/test_mineru.py b/tests/tools/test_mineru.pyindex ae18ed177..982f8d28b 100644--- a/tests/tools/test_mineru.py+++ b/tests/tools/test_mineru.py@@ -78,7 +78,7 @@ def test_parse_pdf_to_workdir_dispatches_local((Path(base) / Path(p).stem).mkdir(parents=True, exist_ok=True)return True- monkeypatch.setattr(pdf_parser, "parse_pdf_with_mineru", fake_local)+ monkeypatch.setattr(pdf_parser, "parse_document_with_mineru", fake_local)workdir = mineru_backend.parse_pdf_to_workdir(pdf, out, config=MinerUConfig(mode="local"))assert workdir == out / "exam"@@ -91,7 +91,7 @@ def test_parse_pdf_to_workdir_local_failure_raises(pdf = tmp_path / "exam.pdf"pdf.write_bytes(b"%PDF-1.4")- monkeypatch.setattr(pdf_parser, "parse_pdf_with_mineru", lambda *a, **k: False)+ monkeypatch.setattr(pdf_parser, "parse_document_with_mineru", lambda *a, **k: False)with pytest.raises(MinerUError):mineru_backend.parse_pdf_to_workdir(@@ -121,6 +121,38 @@ def test_parse_pdf_to_workdir_dispatches_cloud(assert workdir.name == "clouddir"+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:+ seen.append(Path(path).name)+ (Path(base) / Path(path).stem).mkdir(parents=True, exist_ok=True)+ return True++ monkeypatch.setattr(local_parser, "parse_document_with_mineru", fake_local)++ workdir = mineru_backend.parse_document_to_workdir(docx, out, config=MinerUConfig(mode="local"))++ assert seen == ["lesson.docx"]+ assert workdir == out / "lesson"+++def test_pdf_compatibility_wrapper_rejects_non_pdf(tmp_path: Path) -> None:+ from deeptutor.services.parsing.engines.mineru import local as local_parser++ docx = tmp_path / "lesson.docx"+ docx.write_bytes(b"office")++ assert local_parser.parse_pdf_with_mineru(str(docx)) is False++# ---------------------------------------------------------------------------# Cloud client internals# ---------------------------------------------------------------------------@@ -187,6 +219,35 @@ def test_parse_local_rejects_bad_configured_path(assert "not an executable" in str(exc.value)+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(+ mineru_backend,+ "local_cli_probe",+ lambda *_args: {+ "found": True,+ "command": "magic-pdf",+ "path": "/opt/bin/magic-pdf",+ "source": "path",+ },+ )+ monkeypatch.setattr(+ local_parser,+ "parse_document_with_mineru",+ lambda *_args, **_kwargs: pytest.fail("legacy CLI must not run"),+ )++ with pytest.raises(MinerUError, match="legacy magic-pdf"):+ mineru_backend.parse_document_to_workdir(+ source, tmp_path / "out", config=MinerUConfig(mode="local")+ )++def test_local_cli_version_rejects_unknown_command() -> None:# Whitelist guard: bare names outside the whitelist (and non-executable# paths) never reach subprocess.@@ -223,6 +284,52 @@ def test_pdf_parser_streams_output_lines(tmp_path: Path, monkeypatch: pytest.Monassert (out / "exam" / "auto" / "exam.md").exists()+def test_document_parser_passes_docx_to_current_mineru_cli(+ 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")+ out = tmp_path / "out"+ captured: dict[str, list[str]] = {}++ class FakeProcess:+ def __init__(self, cmd, **_kwargs): # noqa: ANN001+ captured["cmd"] = cmd+ target = Path(cmd[cmd.index("-o") + 1]) / "lesson"+ target.mkdir(parents=True, exist_ok=True)+ (target / "lesson.md").write_text("# parsed", encoding="utf-8")+ self.stdout = iter([])++ def wait(self):+ return 0++ monkeypatch.setattr(local_parser.subprocess, "Popen", FakeProcess)++ assert local_parser.parse_document_with_mineru(str(source), str(out), cli_command="mineru")+ assert captured["cmd"][:3] == ["mineru", "-p", str(source.resolve())]+ assert (out / "lesson" / "lesson.md").exists()+++def test_document_parser_rejects_legacy_magic_pdf_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(+ local_parser.subprocess,+ "Popen",+ lambda *_args, **_kwargs: pytest.fail("legacy CLI must not be invoked"),+ )++ assert not local_parser.parse_document_with_mineru(+ str(source), str(tmp_path / "out"), cli_command="magic-pdf"+ )++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")@@ -398,6 +505,49 @@ def test_parse_cloud_happy_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch)assert (workdir / "images" / "fig.png").exists()+def test_parse_cloud_preserves_office_filename(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source = tmp_path / "lesson.docx"+ source.write_bytes(b"office")+ submitted: dict[str, object] = {}++ def submit(_path, body): # noqa: ANN001+ submitted.update(body)+ return _Resp({"code": 0, "data": {"batch_id": "B", "file_urls": ["https://up"]}})++ _install_fake_httpx(+ monkeypatch,+ submit=submit,+ poll=lambda _path: _Resp(+ {+ "code": 0,+ "data": {+ "extract_result": [+ {+ "file_name": "lesson.docx",+ "state": "done",+ "full_zip_url": "https://zip",+ }+ ]+ },+ }+ ),+ download=lambda _url: _Resp(content=_zip_bytes(), status=200),+ )++ workdir = mineru_cloud.parse_cloud(+ source,+ tmp_path / "out",+ MinerUConfig(mode="cloud", api_token="tok"),+ poll_interval=0,+ timeout=10,+ )++ assert submitted["files"][0]["name"] == "lesson.docx"+ assert workdir.name == "lesson"++def test_parse_cloud_retries_429_with_next_token(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: