DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(knowledge): add local OCR fallback for scanned PDFs
XZH3cb8177a68f4
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.pyindex 1cb7d247c..94e4331e6 100644--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py@@ -22,6 +22,7 @@ from typing import Any, Callable, Iterablefrom llama_index.core import Documentfrom llama_index.core.schema import ImageNode+from deeptutor.services.config.runtime_settings import DOCUMENT_PARSING_ENGINE_LITEPARSEfrom deeptutor.services.embedding import get_embedding_clientfrom deeptutor.services.llm.client import get_llm_clientfrom deeptutor.services.rag.file_routing import FileTypeRouter@@ -41,6 +42,10 @@ IMAGE_DESCRIPTION_PROMPT = ("and any educational or technical meaning. Keep the answer under 180 words.")+# LiteParse is the only automatic fallback candidate: it performs local OCR,+# has no model download, and can run without changing the user's global parser.+_PDF_OCR_FALLBACK_ENGINE = DOCUMENT_PARSING_ENGINE_LITEPARSE+@dataclass(frozen=True)class _ImageSource:@@ -82,14 +87,37 @@ class LlamaIndexDocumentLoader:text, extracted_images, parse_engine = await asyncio.to_thread(self._parse_document, file_path)- self._append_if_nonempty(- documents,- file_path,- text,- parse_engine=parse_engine,- extracted_image_count=len(extracted_images),+ scanned_pdf_needs_ocr = (+ file_path.suffix.lower() == ".pdf"+ and not text.strip()+ and bool(extracted_images)+ and parse_engine != _PDF_OCR_FALLBACK_ENGINE)- image_sources.extend(extracted_images)+ if scanned_pdf_needs_ocr:+ fallback = await asyncio.to_thread(+ self._parse_document,+ file_path,+ None,+ _PDF_OCR_FALLBACK_ENGINE,+ )+ if fallback[0].strip() or fallback[1]:+ text, extracted_images, parse_engine = fallback+ scanned_pdf_needs_ocr = False+ else:+ self._log_scanned_pdf_without_ocr(+ file_path,+ parse_engine,+ len(extracted_images),+ )+ if not scanned_pdf_needs_ocr:+ self._append_if_nonempty(+ documents,+ file_path,+ text,+ parse_engine=parse_engine,+ extracted_image_count=len(extracted_images),+ )+ image_sources.extend(extracted_images)for file_path_str in classification.text_files:file_path = Path(file_path_str)@@ -140,6 +168,7 @@ class LlamaIndexDocumentLoader:self,file_path: Path,parse_service=None, # noqa: ANN001+ engine: str | None = None,) -> tuple[str, list[_ImageSource], str]:"""Parse a document through the shared, engine-pluggable parse layer.@@ -151,18 +180,42 @@ class LlamaIndexDocumentLoader:from deeptutor.services.parsing import ParserError, get_parse_servicetry:- parsed = (parse_service or get_parse_service()).parse(file_path)+ parsed = (parse_service or get_parse_service()).parse(file_path, engine=engine)except ParserError as exc:- self.logger.warning(- f"Skipped {file_path.name}: the active document-parsing engine could "- f"not handle it ({exc}). Change the engine in Settings → Document Parsing."- )+ if engine:+ self.logger.warning(+ "Automatic OCR fallback failed for %s with the %s engine: %s",+ file_path.name,+ engine,+ exc,+ )+ else:+ self.logger.warning(+ f"Skipped {file_path.name}: the active document-parsing engine could "+ f"not handle it ({exc}). Change the engine in Settings → Document Parsing."+ )return "", [], ""text = parsed.markdown.strip() or self._text_from_blocks(parsed.blocks)images = self._collect_asset_images(parsed.asset_dir, origin=file_path)return text, images, str(parsed.engine or "")+ def _log_scanned_pdf_without_ocr(+ self,+ file_path: Path,+ parse_engine: str,+ extracted_image_count: int,+ ) -> None:+ engine_label = parse_engine or "the active parser"+ self.logger.warning(+ "Skipped scanned PDF: %s. The %s engine extracted %d image(s) but no text, "+ "and no usable local OCR fallback was available. Install LiteParse under "+ "Settings, Document Parsing, or switch to an OCR-capable engine with OCR enabled.",+ file_path.name,+ engine_label,+ extracted_image_count,+ )+@staticmethoddef _text_from_blocks(blocks: list[dict] | None) -> str:"""Fall back to concatenating block text when an engine emits no markdown."""diff --git a/tests/services/rag/test_llamaindex_document_loader.py b/tests/services/rag/test_llamaindex_document_loader.pyindex 003779151..f324163a2 100644--- a/tests/services/rag/test_llamaindex_document_loader.py+++ b/tests/services/rag/test_llamaindex_document_loader.py@@ -35,6 +35,27 @@ def _install_stub_parse_service(monkeypatch, results: dict[str, "object"]) -> Nomonkeypatch.setattr(parsing, "get_parse_service", lambda: _StubService())+def _install_sequential_parse_service(+ monkeypatch: pytest.MonkeyPatch,+ outcomes: list["object"],+) -> list[tuple[str, str | None]]:+ """Record ``(file_name, engine)`` calls and return one outcome per call."""+ import deeptutor.services.parsing as parsing++ calls: list[tuple[str, str | None]] = []++ class _SequentialStubService:+ def parse(self, source_path, engine=None, **_kwargs): # noqa: ANN001+ calls.append((Path(source_path).name, engine))+ outcome = outcomes[len(calls) - 1]+ if isinstance(outcome, Exception):+ raise outcome+ return outcome++ monkeypatch.setattr(parsing, "get_parse_service", lambda: _SequentialStubService())+ return calls++def test_loader_routes_parser_files_through_active_parse_engine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -211,6 +232,126 @@ def test_loader_explains_scanned_pdf_when_parser_yields_images_only(assert "Settings, Document Parsing" in caplog.text+def _text_only_embedding_client():+ class _TextOnlyClient:+ config = type("Config", (), {"binding": "openai", "model": "text-embedding"})()++ def supports_multimodal_contents(self) -> bool:+ return False++ return _TextOnlyClient()+++def test_loader_falls_back_to_installed_liteparse_for_scanned_pdf(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pytest.importorskip("llama_index.core")+ from deeptutor.services.parsing.types import ParsedDocument+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module+ from deeptutor.services.rag.pipelines.llamaindex.document_loader import (+ LlamaIndexDocumentLoader,+ )++ pdf_path = tmp_path / "scan.pdf"+ pdf_path.write_bytes(b"stub")+ asset_dir = tmp_path / "assets"+ asset_dir.mkdir()+ (asset_dir / "page-1.png").write_bytes(b"\x89PNG\r\n")++ calls = _install_sequential_parse_service(+ monkeypatch,+ [+ ParsedDocument(markdown="", engine="pymupdf4llm", asset_dir=asset_dir),+ ParsedDocument(markdown="Recovered scanned text", engine="liteparse"),+ ],+ )+ monkeypatch.setattr(+ loader_module,+ "get_embedding_client",+ lambda: _text_only_embedding_client(),+ )++ documents = asyncio.run(LlamaIndexDocumentLoader().load([str(pdf_path)]))++ assert calls == [("scan.pdf", None), ("scan.pdf", "liteparse")]+ assert [document.text for document in documents] == ["Recovered scanned text"]+++def test_loader_reports_scanned_pdf_when_ocr_fallback_is_unavailable(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+) -> None:+ pytest.importorskip("llama_index.core")+ from deeptutor.services.parsing.types import ParsedDocument, ParserError+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module+ from deeptutor.services.rag.pipelines.llamaindex.document_loader import (+ LlamaIndexDocumentLoader,+ )++ pdf_path = tmp_path / "scan.pdf"+ pdf_path.write_bytes(b"stub")+ asset_dir = tmp_path / "assets"+ asset_dir.mkdir()+ (asset_dir / "page-1.png").write_bytes(b"\x89PNG\r\n")++ calls = _install_sequential_parse_service(+ monkeypatch,+ [+ ParsedDocument(markdown="", engine="pymupdf4llm", asset_dir=asset_dir),+ ParserError("liteparse isn't installed"),+ ],+ )+ monkeypatch.setattr(+ loader_module,+ "get_embedding_client",+ lambda: _text_only_embedding_client(),+ )++ with caplog.at_level("WARNING"):+ documents = asyncio.run(LlamaIndexDocumentLoader().load([str(pdf_path)]))++ assert calls == [("scan.pdf", None), ("scan.pdf", "liteparse")]+ assert documents == []+ assert "Automatic OCR fallback failed for scan.pdf" in caplog.text+ assert "Skipped scanned PDF: scan.pdf" in caplog.text+ assert "Install LiteParse" in caplog.text+++def test_loader_does_not_fallback_when_liteparse_already_ran(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pytest.importorskip("llama_index.core")+ from deeptutor.services.parsing.types import ParsedDocument+ from deeptutor.services.rag.pipelines.llamaindex import document_loader as loader_module+ from deeptutor.services.rag.pipelines.llamaindex.document_loader import (+ LlamaIndexDocumentLoader,+ )++ pdf_path = tmp_path / "scan.pdf"+ pdf_path.write_bytes(b"stub")+ asset_dir = tmp_path / "assets"+ asset_dir.mkdir()+ (asset_dir / "page-1.png").write_bytes(b"\x89PNG\r\n")++ calls = _install_sequential_parse_service(+ monkeypatch,+ [ParsedDocument(markdown="", engine="liteparse", asset_dir=asset_dir)],+ )+ monkeypatch.setattr(+ loader_module,+ "get_embedding_client",+ lambda: _text_only_embedding_client(),+ )++ documents = asyncio.run(LlamaIndexDocumentLoader().load([str(pdf_path)]))++ assert calls == [("scan.pdf", None)]+ assert documents == []++def test_loader_keeps_generic_empty_warning_for_non_pdf(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None: