Skip to content

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

fix(parsing): fall back to a text-capable engine when the global default can't take a file (#1502)

ZQR1101182acb8ad7b3
diff --git a/deeptutor/services/parsing/service.py b/deeptutor/services/parsing/service.py
index a8fdd9c93..0daa05811 100644
--- a/deeptutor/services/parsing/service.py
+++ b/deeptutor/services/parsing/service.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import logging
from pathlib import Path
-from typing import Callable, Optional
+from typing import Any, Callable, Optional
from deeptutor.services.config.runtime_settings import (
_DEFAULT_DOCUMENT_PARSING_ENGINE,
@@ -40,6 +40,37 @@ def _display_extension(source_path: str | Path, supported: frozenset[str]) -> st
return Path(source_path).suffix.lower() or "this"
+# Engines tried, in order, when the *implicitly* selected engine (the global
+# default) does not advertise support for a file's suffix. The global
+# single-select is a default, not a per-file command: a mixed KB (MinerU PDFs
+# plus .txt/.md notes) must not hard-fail the whole ingest batch on the files
+# the chosen engine was never built for (#1502). ``text_only`` leads because
+# it is lossless for text files and needs no model.
+_FALLBACK_ENGINE_PREFERENCE = ("text_only", "markitdown", "tika")
+
+
+def _find_fallback_engine(
+ source_path: str | Path, primary_engine: str
+) -> Optional[tuple[str, Any, Any]]:
+ """First installed engine other than ``primary`` that supports the file.
+
+ Returns ``(engine_name, parser, config)`` or ``None``. Engines that are
+ not installed are skipped — the fallback must never turn a routing
+ decision into an import-time failure.
+ """
+ for name in _FALLBACK_ENGINE_PREFERENCE:
+ if name == primary_engine:
+ continue
+ try:
+ parser = get_parser(name)
+ except Exception:
+ continue
+ supported = parser.supported_formats()
+ if not supported or _matches_supported_format(source_path, supported):
+ return name, parser, parser.resolve_config()
+ return None
+
+
class ParseService:
"""Cache-aware, engine-pluggable document parsing."""
@@ -94,10 +125,28 @@ class ParseService:
supported = parser.supported_formats()
if supported and not _matches_supported_format(source_path, supported):
- suffix = _display_extension(source_path, supported)
- raise ParserError(
- f"The '{engine_name}' parsing engine doesn't support {suffix} "
- f"files. Choose a different engine in Settings → Document Parsing."
+ if engine is not None:
+ # The caller pinned this engine by name — keep the loud error.
+ suffix = _display_extension(source_path, supported)
+ raise ParserError(
+ f"The '{engine_name}' parsing engine doesn't support {suffix} "
+ f"files. Choose a different engine in Settings → Document Parsing."
+ )
+ fallback = _find_fallback_engine(source_path, engine_name)
+ if fallback is None:
+ suffix = _display_extension(source_path, supported)
+ raise ParserError(
+ f"The '{engine_name}' parsing engine doesn't support {suffix} "
+ f"files. Choose a different engine in Settings → Document Parsing."
+ )
+ primary_engine = engine_name
+ engine_name, parser, config = fallback
+ supported = parser.supported_formats()
+ logger.warning(
+ "The '%s' parsing engine doesn't support %s files; using '%s' for this file.",
+ primary_engine,
+ _display_extension(source_path, supported),
+ engine_name,
)
sig = parser.signature(config).hash()
diff --git a/tests/services/parsing/test_parse_service.py b/tests/services/parsing/test_parse_service.py
index 10ff33d1a..91c9a603a 100644
--- a/tests/services/parsing/test_parse_service.py
+++ b/tests/services/parsing/test_parse_service.py
@@ -148,3 +148,114 @@ def test_missing_file_raises(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ->
service = ParseService(cache_root=tmp_path / "cache")
with pytest.raises(ParserError):
service.parse(tmp_path / "ghost.pdf", engine="fake")
+
+
+# ---------------------------------------------------------------------------
+# Implicit-engine fallback for unsupported suffixes (#1502)
+# ---------------------------------------------------------------------------
+
+
+class _NamedFakeParser(_FakeParser):
+ def __init__(self, *, name: str, formats: frozenset[str], **kwargs) -> None:
+ super().__init__(**kwargs)
+ self.name = name
+ self._formats = formats
+
+ def supported_formats(self):
+ return self._formats
+
+
+def _use_map(monkeypatch: pytest.MonkeyPatch, parsers: dict) -> None:
+ def _get(name: str):
+ if name not in parsers:
+ raise KeyError(name)
+ return parsers[name]
+
+ monkeypatch.setattr(svc_mod, "get_parser", _get)
+
+
+def _txt(tmp_path: Path, name: str = "notes.txt") -> Path:
+ path = tmp_path / name
+ path.write_text("plain text", encoding="utf-8")
+ return path
+
+
+def test_implicit_engine_falls_back_for_unsupported_suffix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """MinerU-style engine selected globally + a .txt file → the text-capable
+ engine parses it instead of failing the whole ingest batch (#1502)."""
+ primary = _NamedFakeParser(name="mineru", formats=frozenset({".pdf", ".docx"}))
+ text_engine = _NamedFakeParser(name="text_only", formats=frozenset(), sig="text-v1")
+ _use_map(monkeypatch, {"mineru": primary, "text_only": text_engine})
+ monkeypatch.setattr(svc_mod, "load_document_parsing_settings", lambda: {"engine": "mineru"})
+ txt = _txt(tmp_path)
+ service = ParseService(cache_root=tmp_path / "cache")
+
+ result = service.parse(txt)
+
+ assert result.engine == "text_only"
+ assert primary.calls == []
+
+
+def test_explicit_engine_keeps_the_loud_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A caller that pinned the engine by name gets the current hard error."""
+ primary = _NamedFakeParser(name="mineru", formats=frozenset({".pdf", ".docx"}))
+ text_engine = _NamedFakeParser(name="text_only", formats=frozenset())
+ _use_map(monkeypatch, {"mineru": primary, "text_only": text_engine})
+ txt = _txt(tmp_path)
+ service = ParseService(cache_root=tmp_path / "cache")
+
+ with pytest.raises(ParserError, match="doesn't support"):
+ service.parse(txt, engine="mineru")
+ assert text_engine.calls == []
+
+
+def test_fallback_prefers_the_documented_order(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """text_only wins over markitdown/tika when all are installed."""
+ primary = _NamedFakeParser(name="mineru", formats=frozenset({".pdf"}))
+ markitdown = _NamedFakeParser(name="markitdown", formats=frozenset({".txt"}))
+ text_engine = _NamedFakeParser(name="text_only", formats=frozenset({".txt"}))
+ _use_map(
+ monkeypatch,
+ {"mineru": primary, "text_only": text_engine, "markitdown": markitdown},
+ )
+ monkeypatch.setattr(svc_mod, "load_document_parsing_settings", lambda: {"engine": "mineru"})
+ service = ParseService(cache_root=tmp_path / "cache")
+
+ result = service.parse(_txt(tmp_path))
+
+ assert result.engine == "text_only"
+ assert markitdown.calls == []
+
+
+def test_no_fallback_engine_raises_the_original_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Nothing installed can take the file → the loud error is unchanged."""
+ primary = _NamedFakeParser(name="mineru", formats=frozenset({".pdf"}))
+ _use_map(monkeypatch, {"mineru": primary})
+ monkeypatch.setattr(svc_mod, "load_document_parsing_settings", lambda: {"engine": "mineru"})
+ service = ParseService(cache_root=tmp_path / "cache")
+
+ with pytest.raises(ParserError, match="doesn't support"):
+ service.parse(_txt(tmp_path))
+
+
+def test_fallback_skips_uninstalled_engines(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """text_only missing → markitdown is tried next without failing."""
+ primary = _NamedFakeParser(name="mineru", formats=frozenset({".pdf"}))
+ markitdown = _NamedFakeParser(name="markitdown", formats=frozenset({".txt"}))
+ _use_map(monkeypatch, {"mineru": primary, "markitdown": markitdown})
+ monkeypatch.setattr(svc_mod, "load_document_parsing_settings", lambda: {"engine": "mineru"})
+ service = ParseService(cache_root=tmp_path / "cache")
+
+ result = service.parse(_txt(tmp_path))
+
+ assert result.engine == "markitdown"