DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(parsing): add remote Apache Tika parsing engine (#875)
Alok Saboo6cb65a2a7920
diff --git a/README.md b/README.mdindex e7609f201..d8670df1c 100644--- a/README.md+++ b/README.md@@ -587,7 +587,7 @@ Knowledge bases are the document collections behind RAG — they ground Chat tur<img src="assets/figs/web-1.4.6+/knowledge/01-create%20knowledge%20base.png" alt="Create a knowledge base" width="900"></div>-Creating 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). 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, 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. The CLI mirrors the lifecycle with `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, and `delete`.+Creating 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). 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 `deeptutor kb list`, `info`, `create`, `add`, `search`, `set-default`, and `delete`.</details>diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pyindex bfea48fb7..8fc8910d4 100644--- a/deeptutor/api/routers/settings.py+++ b/deeptutor/api/routers/settings.py@@ -299,6 +299,13 @@ class DoclingRemoteTest(BaseModel):api_token: Optional[str] = None+class TikaRemoteTest(BaseModel):+ """Draft Tika server test. Tests the unsaved URL so the user can verify+ before saving."""++ server_url: str = "http://localhost:9998"++class DocumentParsingInstall(BaseModel):"""One-click pip install of an optional parser engine's package(s)."""@@ -1038,6 +1045,20 @@ async def test_docling_remote_connection(payload: DoclingRemoteTest):return {"ok": ok, "message": detail or ("Ready to parse." if ok else "Not ready.")}[email protected]("/document-parsing/tika/test")+async def test_tika_remote_connection(payload: TikaRemoteTest):+ """Live connectivity check for the Tika server draft URL. Pings ``/version``+ so the user can verify the URL before saving."""+ _require_settings_admin()+ from deeptutor.services.parsing.engines.tika.config import TikaConfig+ from deeptutor.services.parsing.engines.tika.remote import verify_remote++ server_url = payload.server_url.strip().rstrip("/") or "http://localhost:9998"+ config = TikaConfig(server_url=server_url)+ ok, detail = await asyncio.to_thread(verify_remote, config)+ return {"ok": ok, "message": detail or ("Ready to parse." if ok else "Not ready.")}++def _normalize_engine_name(name: str) -> str:return (name or "").strip().lower().replace("-", "_").replace(" ", "_")diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex b894ea620..0066469b1 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -100,6 +100,7 @@ DOCUMENT_PARSING_ENGINE_DOCLING = "docling"DOCUMENT_PARSING_ENGINE_MARKITDOWN = "markitdown"DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM = "pymupdf4llm"DOCUMENT_PARSING_ENGINE_LITEPARSE = "liteparse"+DOCUMENT_PARSING_ENGINE_TIKA = "tika"_DOCUMENT_PARSING_ENGINES = frozenset({DOCUMENT_PARSING_ENGINE_TEXT_ONLY,@@ -108,6 +109,7 @@ _DOCUMENT_PARSING_ENGINES = frozenset(DOCUMENT_PARSING_ENGINE_MARKITDOWN,DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,DOCUMENT_PARSING_ENGINE_LITEPARSE,+ DOCUMENT_PARSING_ENGINE_TIKA,})# Image formats PyMuPDF4LLM can write extracted page images as.@@ -187,6 +189,11 @@ _DEFAULT_LITEPARSE_ENGINE: dict[str, Any] = {"max_pages": 0,}+# Tika engine slice. Remote-only Apache Tika server; no local package or models.+_DEFAULT_TIKA_ENGINE: dict[str, Any] = {+ "server_url": "http://localhost:9998",+}+# Built-in text-only engine slice. It deliberately has no knobs: it reuses# DeepTutor's legacy text extractors for PDF / Office / text-like files._DEFAULT_TEXT_ONLY_ENGINE: dict[str, Any] = {}@@ -205,6 +212,7 @@ DEFAULT_DOCUMENT_PARSING_SETTINGS: dict[str, Any] = {DOCUMENT_PARSING_ENGINE_MARKITDOWN: _DEFAULT_MARKITDOWN_ENGINE,DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: _DEFAULT_PYMUPDF4LLM_ENGINE,DOCUMENT_PARSING_ENGINE_LITEPARSE: _DEFAULT_LITEPARSE_ENGINE,+ DOCUMENT_PARSING_ENGINE_TIKA: _DEFAULT_TIKA_ENGINE,},}@@ -446,6 +454,9 @@ class RuntimeSettingsService:engines[DOCUMENT_PARSING_ENGINE_DOCLING] = self._apply_docling_process_overrides(dict(engines[DOCUMENT_PARSING_ENGINE_DOCLING]))+ engines[DOCUMENT_PARSING_ENGINE_TIKA] = self._apply_tika_process_overrides(+ dict(engines[DOCUMENT_PARSING_ENGINE_TIKA])+ )payload = {**payload, "engines": engines}return payload@@ -872,6 +883,9 @@ class RuntimeSettingsService:DOCUMENT_PARSING_ENGINE_LITEPARSE: self._normalize_liteparse_engine(engines_in.get(DOCUMENT_PARSING_ENGINE_LITEPARSE) or {}),+ DOCUMENT_PARSING_ENGINE_TIKA: self._normalize_tika_engine(+ engines_in.get(DOCUMENT_PARSING_ENGINE_TIKA) or {}+ ),}engine = _string(settings.get("engine")).lower().replace("-", "_").replace(" ", "_")@@ -937,6 +951,18 @@ class RuntimeSettingsService:payload["api_token"] = valuereturn self._normalize_docling_engine(payload)+ def _normalize_tika_engine(self, settings: dict[str, Any]) -> dict[str, Any]:+ return {+ "server_url": _string(settings.get("server_url")).rstrip("/")+ or "http://localhost:9998",+ }++ def _apply_tika_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:+ payload = dict(settings)+ if value := self._process_env_value("TIKA_SERVER_URL"):+ payload["server_url"] = value+ return self._normalize_tika_engine(payload)+def _normalize_markitdown_engine(self, settings: dict[str, Any]) -> dict[str, Any]:return {"enable_llm_image_description": _coerce_bool(@@ -1182,6 +1208,7 @@ __all__ = ["DOCUMENT_PARSING_ENGINE_MINERU","DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM","DOCUMENT_PARSING_ENGINE_TEXT_ONLY",+ "DOCUMENT_PARSING_ENGINE_TIKA","DOCLING_MODE_LOCAL","DOCLING_MODE_REMOTE","LITEPARSE_IMAGE_MODES",diff --git a/deeptutor/services/parsing/engines/factory.py b/deeptutor/services/parsing/engines/factory.pyindex d85ae374a..289113735 100644--- a/deeptutor/services/parsing/engines/factory.py+++ b/deeptutor/services/parsing/engines/factory.py@@ -17,6 +17,7 @@ from deeptutor.services.config.runtime_settings import (DOCUMENT_PARSING_ENGINE_MINERU,DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM,DOCUMENT_PARSING_ENGINE_TEXT_ONLY,+ DOCUMENT_PARSING_ENGINE_TIKA,)from ..base import Parser@@ -59,6 +60,12 @@ def _pymupdf4llm_class():return PyMuPDF4LLMParser+def _tika_class():+ from .tika.engine import TikaParser++ return TikaParser++# name -> zero-arg loader returning the engine class._ENGINE_LOADERS: Dict[str, Callable[[], Any]] = {DOCUMENT_PARSING_ENGINE_TEXT_ONLY: _text_only_class,@@ -67,6 +74,7 @@ _ENGINE_LOADERS: Dict[str, Callable[[], Any]] = {DOCUMENT_PARSING_ENGINE_MARKITDOWN: _markitdown_class,DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM: _pymupdf4llm_class,DOCUMENT_PARSING_ENGINE_LITEPARSE: _liteparse_class,+ DOCUMENT_PARSING_ENGINE_TIKA: _tika_class,}KNOWN_ENGINES = frozenset(_ENGINE_LOADERS)@@ -124,6 +132,14 @@ _ENGINE_META: Dict[str, Dict[str, Any]] = {),"needs_local_models": False,},+ DOCUMENT_PARSING_ENGINE_TIKA: {+ "name": "Tika",+ "description": (+ "Remote Apache Tika server. Broad format support, no local install "+ "or model downloads. Point at an existing tika-server container."+ ),+ "needs_local_models": False,+ },}diff --git a/deeptutor/services/parsing/engines/tika/__init__.py b/deeptutor/services/parsing/engines/tika/__init__.pynew file mode 100644index 000000000..63341e163--- /dev/null+++ b/deeptutor/services/parsing/engines/tika/__init__.py@@ -0,0 +1 @@+"""Tika engine — remote Apache Tika server (no local install)."""diff --git a/deeptutor/services/parsing/engines/tika/config.py b/deeptutor/services/parsing/engines/tika/config.pynew file mode 100644index 000000000..d35d71bbb--- /dev/null+++ b/deeptutor/services/parsing/engines/tika/config.py@@ -0,0 +1,36 @@+"""Tika engine config (read-side adapter over the v2 settings slice)."""++from __future__ import annotations++from dataclasses import dataclass++from deeptutor.services.config.runtime_settings import (+ DOCUMENT_PARSING_ENGINE_TIKA,+ load_document_parsing_settings,+)++DEFAULT_TIKA_SERVER_URL = "http://localhost:9998"+++@dataclass(frozen=True)+class TikaConfig:+ """Validated Tika configuration.++ Tika is remote-only: ``server_url`` is a Tika server (``tika-server`` /+ the docker image). There is no local package or model download.+ """++ server_url: str = DEFAULT_TIKA_SERVER_URL+++def resolve_tika_config() -> TikaConfig:+ slice_ = (+ load_document_parsing_settings().get("engines", {}).get(DOCUMENT_PARSING_ENGINE_TIKA, {})+ )+ return TikaConfig(+ server_url=str(slice_.get("server_url") or DEFAULT_TIKA_SERVER_URL).rstrip("/")+ or DEFAULT_TIKA_SERVER_URL,+ )+++__all__ = ["DEFAULT_TIKA_SERVER_URL", "TikaConfig", "resolve_tika_config"]diff --git a/deeptutor/services/parsing/engines/tika/engine.py b/deeptutor/services/parsing/engines/tika/engine.pynew file mode 100644index 000000000..c8fdc9fdd--- /dev/null+++ b/deeptutor/services/parsing/engines/tika/engine.py@@ -0,0 +1,93 @@+"""Tika engine adapter implementing the ``Parser`` protocol.++Remote-only: a Tika server extracts text, which is written as Markdown for the+canonical IR. There is no local package or model download.+"""++from __future__ import annotations++from pathlib import Path+from typing import Callable, Optional++from ...base import ReadinessReport+from ...signature import ParserSignature+from .config import TikaConfig, resolve_tika_config++_SUPPORTED = frozenset(+ {+ ".pdf",+ ".docx",+ ".doc",+ ".pptx",+ ".ppt",+ ".xlsx",+ ".xls",+ ".odt",+ ".ods",+ ".odp",+ ".html",+ ".htm",+ ".csv",+ ".json",+ ".xml",+ ".txt",+ ".md",+ ".rtf",+ ".epub",+ ".png",+ ".jpg",+ ".jpeg",+ ".gif",+ ".webp",+ ".tif",+ ".tiff",+ }+)+++class TikaParser:+ name = "tika"+ needs_local_models = False++ @classmethod+ def is_available(cls) -> bool:+ return True++ def resolve_config(self) -> TikaConfig:+ return resolve_tika_config()++ def supported_formats(self) -> frozenset[str]:+ return _SUPPORTED++ def signature(self, config: TikaConfig) -> ParserSignature:+ return ParserSignature.build("tika", f"remote:{config.server_url}", {})++ def is_ready(self, config: TikaConfig) -> ReadinessReport:+ if not (config.server_url or "").strip():+ return ReadinessReport(+ ready=False,+ reason="not_configured",+ message="Tika has no server URL configured.",+ )+ return ReadinessReport(ready=True)++ def verify(self, config: TikaConfig) -> tuple[bool, str]:+ """Live connectivity check for the Settings “Test” button."""+ from .remote import verify_remote++ return verify_remote(config)++ def parse(+ self,+ source_path: Path,+ workdir: Path,+ *,+ config: TikaConfig,+ on_output: Optional[Callable[[str], None]] = None,+ ) -> None:+ from .remote import parse_remote++ parse_remote(source_path, workdir, config=config, on_output=on_output)+++__all__ = ["TikaParser"]diff --git a/deeptutor/services/parsing/engines/tika/remote.py b/deeptutor/services/parsing/engines/tika/remote.pynew file mode 100644index 000000000..42ac7aa08--- /dev/null+++ b/deeptutor/services/parsing/engines/tika/remote.py@@ -0,0 +1,137 @@+"""Apache Tika REST API backend.++Sends a local file to a Tika server via ``PUT /tika`` (``Accept: text/plain``)+and writes the extracted text into the working directory as ``<stem>.md``, so+the downstream ``ParseService`` is backend-agnostic.++Runs synchronously inside the worker thread that the parsing service invokes, so+a blocking ``httpx.Client`` is the simplest correct choice (no nested event+loop).+"""++from __future__ import annotations++from collections.abc import Callable+import logging+from pathlib import Path+from urllib.parse import quote++import httpx++from ...types import ParserError+from .config import TikaConfig++logger = logging.getLogger(__name__)++_CONVERT_ENDPOINT = "/tika"+_VERSION_ENDPOINT = "/version"++_SUBMIT_TIMEOUT_SECONDS = 300.0+_HEALTH_TIMEOUT_SECONDS = 8.0+++def parse_remote(+ source_path: Path,+ workdir: Path,+ config: TikaConfig,+ *,+ on_output: Callable[[str], None] | None = None,+) -> None:+ """Send ``source_path`` to the Tika server; write ``<stem>.md``.++ Raises :class:`ParserError` on any failure."""+ if not source_path.is_file():+ raise ParserError(f"File not found: {source_path}")+ if not (config.server_url or "").strip():+ raise ParserError(+ "Tika has no server URL configured. Set one under Settings → Document Parsing."+ )++ def report(message: str) -> None:+ if on_output:+ try:+ on_output(message)+ except Exception:+ logger.debug("on_output callback failed", exc_info=True)++ base_url = config.server_url.rstrip("/")+ report(f"Tika server: converting {source_path.name}…")+ try:+ text = _convert_file(source_path, base_url)+ except _ConnectivityError as exc:+ raise ParserError(str(exc)) from exc++ stem = source_path.stem+ (workdir / f"{stem}.md").write_text(text, encoding="utf-8")+ report(f"Tika server: wrote {stem}.md")+++def verify_remote(config: TikaConfig, timeout: float = _HEALTH_TIMEOUT_SECONDS) -> tuple[bool, str]:+ """Best-effort connectivity check for the Settings "Test connection" button.++ Pings ``/version`` — cheap and non-destructive. Never raises; returns+ ``(ok, detail)``."""+ if not (config.server_url or "").strip():+ return False, "No Tika server URL configured."+ base_url = config.server_url.rstrip("/")+ try:+ with httpx.Client(timeout=timeout) as client:+ version = _get_text(client, base_url + _VERSION_ENDPOINT)+ except _ConnectivityError as exc:+ return False, str(exc)+ return True, version+++class _ConnectivityError(Exception):+ """Wraps any network/HTTP failure so callers get one user-facing error."""+++def _convert_file(source_path: Path, base_url: str) -> str:+ headers = {+ "Accept": "text/plain",+ "Content-Type": "application/octet-stream",+ "Content-Disposition": f"attachment; filename*=UTF-8''{quote(source_path.name, safe='')}",+ }+ with source_path.open("rb") as source:+ with httpx.Client(base_url=base_url, timeout=_SUBMIT_TIMEOUT_SECONDS) as client:+ try:+ response = client.put(_CONVERT_ENDPOINT, content=source, headers=headers)+ except httpx.HTTPError as exc:+ raise _ConnectivityError(f"Tika server request failed: {exc}") from exc+ try:+ response.raise_for_status()+ except httpx.HTTPStatusError as exc:+ raise _ConnectivityError(_http_error_message(exc)) from exc+ text = response.text+ if not isinstance(text, str):+ raise _ConnectivityError(f"Tika server returned no text for {source_path.name}.")+ return text+++def _http_error_message(exc: httpx.HTTPStatusError) -> str:+ status = exc.response.status_code+ if status in (401, 403):+ return "Tika server rejected the request (401/403)."+ if status == 415:+ return "Tika server does not support this file type (415)."+ if status == 422:+ return "Tika server could not parse the document (422)."+ if status == 429:+ return "Tika server rate limit hit (429). Try again later."+ return f"Tika server returned HTTP {status}."+++def _get_text(client: httpx.Client, url: str) -> str:+ try:+ response = client.get(url)+ try:+ response.raise_for_status()+ except httpx.HTTPStatusError as exc:+ raise _ConnectivityError(_http_error_message(exc)) from exc+ except httpx.HTTPError as exc:+ raise _ConnectivityError(f"Tika server request failed: {exc}") from exc+ text = response.text.strip()+ return text or "reachable"+++__all__ = ["parse_remote", "verify_remote"]diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.pyindex 23c6cc448..04e2eb587 100644--- a/tests/services/config/test_runtime_settings.py+++ b/tests/services/config/test_runtime_settings.py@@ -369,6 +369,39 @@ def test_docling_process_env_override(tmp_path: Path) -> None:assert plain.load_document_parsing()["engines"]["docling"]["api_token"] == "file-key"+def test_tika_defaults_and_normalization(tmp_path: Path) -> None:+ service = RuntimeSettingsService(tmp_path / "settings", process_env={})++ defaults = service.load_document_parsing(include_process_overrides=False)["engines"]["tika"]+ assert defaults["server_url"] == "http://localhost:9998"++ saved = service.save_document_parsing(+ {"engines": {"tika": {"server_url": "http://192.168.2.162:9998/"}}}+ )["engines"]["tika"]+ assert saved["server_url"] == "http://192.168.2.162:9998"+ assert (+ service.save_document_parsing({"engines": {"tika": {"server_url": ""}}})["engines"]["tika"][+ "server_url"+ ]+ == "http://localhost:9998"+ )+++def test_tika_process_env_override(tmp_path: Path) -> None:+ service = RuntimeSettingsService(+ tmp_path / "settings",+ process_env={"TIKA_SERVER_URL": "http://tika:9998"},+ )+ service.save_document_parsing({"engines": {"tika": {"server_url": "http://localhost:9998"}}})++ assert service.load_document_parsing()["engines"]["tika"]["server_url"] == "http://tika:9998"+ persisted = _read_json(service.path_for("document_parsing"))["engines"]["tika"]+ assert persisted["server_url"] == "http://localhost:9998"++ plain = RuntimeSettingsService(tmp_path / "settings", process_env={})+ assert plain.load_document_parsing()["engines"]["tika"]["server_url"] == "http://localhost:9998"++def test_mineru_process_env_override(tmp_path: Path) -> None:service = RuntimeSettingsService(tmp_path / "settings",@@ -423,6 +456,7 @@ def test_document_parsing_v1_to_v2_migration(tmp_path: Path) -> None:"markitdown","pymupdf4llm","liteparse",+ "tika",}# Migration is persisted to the renamed file (v2, no top-level flat keys);# the legacy mineru.json is gone.diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.pyindex 5b0dc65f5..5999a76ed 100644--- a/tests/services/parsing/test_engines.py+++ b/tests/services/parsing/test_engines.py@@ -8,6 +8,7 @@ import pytestfrom deeptutor.services.parsing.engines import factoryfrom deeptutor.services.parsing.engines.docling.config import DoclingConfig+from deeptutor.services.parsing.engines.tika.config import TikaConfigfrom deeptutor.services.parsing.types import ParserError@@ -19,6 +20,7 @@ def test_known_engines() -> None:"markitdown","pymupdf4llm","liteparse",+ "tika",}@@ -31,6 +33,7 @@ def test_list_engines_reports_metadata_and_availability() -> None:"markitdown","pymupdf4llm","liteparse",+ "tika",}assert engines["text_only"]["available"] is Trueassert engines["text_only"]["needs_local_models"] is False@@ -41,6 +44,8 @@ def test_list_engines_reports_metadata_and_availability() -> None:assert engines["markitdown"]["needs_local_models"] is Falseassert engines["pymupdf4llm"]["needs_local_models"] is Falseassert engines["liteparse"]["needs_local_models"] is False+ assert engines["tika"]["available"] is True+ assert engines["tika"]["needs_local_models"] is Falsedef test_get_parser_unknown_raises() -> None:@@ -198,6 +203,96 @@ def test_docling_remote_business_error_raises(tmp_path, monkeypatch: pytest.Monkassert not (workdir / "doc.md").exists()+def test_tika_signature_tracks_server_url() -> None:+ parser = factory.get_parser("tika")+ a = parser.signature(TikaConfig(server_url="http://host:9998")).hash()+ b = parser.signature(TikaConfig(server_url="http://other:9998")).hash()+ assert a != b+++def test_tika_readiness_needs_url() -> None:+ parser = factory.get_parser("tika")+ assert parser.is_available() is True+ assert parser.is_ready(TikaConfig(server_url="http://host:9998")).ready+ blocked = parser.is_ready(TikaConfig(server_url=""))+ assert blocked.ready is False+ assert blocked.reason == "not_configured"+++def test_tika_parse_writes_markdown(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ src = tmp_path / "doc.pdf"+ src.write_bytes(b"%PDF-1.4 fake")+ workdir = tmp_path / "parsed"+ workdir.mkdir()++ captured: dict = {}++ class _FakeResponse:+ text = "# Extracted via Tika\n"++ def raise_for_status(self):+ return None++ class _FakeClient:+ def __init__(self, *_args, **_kwargs):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def put(self, endpoint, content=None, headers=None):+ captured["endpoint"] = endpoint+ captured["headers"] = headers+ return _FakeResponse()++ monkeypatch.setattr(httpx, "Client", _FakeClient)+ parser = factory.get_parser("tika")+ parser.parse(src, workdir, config=TikaConfig(server_url="http://host:9998"))++ assert captured["endpoint"] == "/tika"+ assert captured["headers"]["Accept"] == "text/plain"+ assert captured["headers"]["Content-Type"] == "application/octet-stream"+ assert "doc.pdf" in captured["headers"]["Content-Disposition"]+ assert (workdir / "doc.md").read_text(encoding="utf-8") == "# Extracted via Tika\n"+++def test_tika_http_error_raises(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ src = tmp_path / "doc.pdf"+ src.write_bytes(b"%PDF-1.4 fake")+ workdir = tmp_path / "parsed"+ workdir.mkdir()++ class _FailingResponse:+ status_code = 422++ def raise_for_status(self):+ request = httpx.Request("PUT", "http://host:9998/tika")+ response = httpx.Response(422, request=request)+ raise httpx.HTTPStatusError("unprocessable", request=request, response=response)++ class _FailingClient:+ def __init__(self, *_args, **_kwargs):+ pass++ def __enter__(self):+ return self++ def __exit__(self, *_args):+ return False++ def put(self, *args, **kwargs):+ return _FailingResponse()++ monkeypatch.setattr(httpx, "Client", _FailingClient)+ parser = factory.get_parser("tika")+ with pytest.raises(ParserError, match="422"):+ parser.parse(src, workdir, config=TikaConfig(server_url="http://host:9998"))+ assert not (workdir / "doc.md").exists()++def test_mineru_local_model_download_gate(monkeypatch: pytest.MonkeyPatch) -> None:from deeptutor.services.parsing.engines.mineru import backendfrom deeptutor.services.parsing.engines.mineru import readiness as rddiff --git a/web/app/(utility)/settings/document-parsing/page.tsx b/web/app/(utility)/settings/document-parsing/page.tsxindex 720e8a867..9dcc294f0 100644--- a/web/app/(utility)/settings/document-parsing/page.tsx+++ b/web/app/(utility)/settings/document-parsing/page.tsx@@ -144,7 +144,7 @@ export default function DocumentParsingSettingsPage() {</h2><p className="mt-1 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{t(- "The active engine handles all parsing. Text-only is built in and extracts plain text; markitdown is lightweight and optional; MinerU and Docling produce richer structure but may need local models or a hosted API.",+ "The active engine handles all parsing. Text-only is built in and extracts plain text; markitdown is lightweight and optional; MinerU and Docling produce richer structure, while Tika provides broad remote text extraction.",)}</p></header>@@ -256,6 +256,17 @@ export default function DocumentParsingSettingsPage() {}/>)}++ {data.engine === "tika" && (+ <TikaPanel+ slice={data.engines.tika || {}}+ readiness={data.readiness.tika}+ busy={busy}+ onSave={(patch) =>+ putDocumentParsing({ engines: { tika: patch } })+ }+ />+ )}</>)}</div>@@ -680,6 +691,157 @@ function DoclingPanel({);}+const DEFAULT_TIKA_URL = "http://localhost:9998";++function TikaPanel({+ slice,+ readiness,+ busy,+ onSave,+}: {+ slice: Record<string, unknown>;+ readiness?: Readiness;+ busy: boolean;+ onSave: (patch: Record<string, unknown>) => Promise<boolean>;+}) {+ const { t } = useTranslation();+ const [draftUrl, setDraftUrl] = useState(+ (typeof slice.server_url === "string" && slice.server_url) || "",+ );+ const [saving, setSaving] = useState(false);+ const [testing, setTesting] = useState(false);+ const [testResult, setTestResult] = useState<{+ ok: boolean;+ message: string;+ } | null>(null);++ async function save() {+ setSaving(true);+ setTestResult(null);+ try {+ await onSave({ server_url: draftUrl.trim() || DEFAULT_TIKA_URL });+ } finally {+ setSaving(false);+ }+ }++ async function testConnection() {+ setTesting(true);+ setTestResult(null);+ try {+ const response = await apiFetch(+ apiUrl("/api/v1/settings/document-parsing/tika/test"),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ server_url: draftUrl.trim() || DEFAULT_TIKA_URL,+ }),+ },+ );+ const data = (await response.json().catch(() => ({}))) as {+ ok?: boolean;+ message?: string;+ detail?: string;+ };+ if (!response.ok) {+ setTestResult({+ ok: false,+ message: data.detail || t("Connection test failed."),+ });+ return;+ }+ setTestResult({+ ok: Boolean(data.ok),+ message:+ data.message ||+ (data.ok ? t("Ready to parse.") : t("Connection test failed.")),+ });+ } catch (err) {+ setTestResult({+ ok: false,+ message: err instanceof Error ? err.message : String(err),+ });+ } finally {+ setTesting(false);+ }+ }++ return (+ <SettingSection+ title={t("Tika")}+ description={t(+ "Point at an Apache Tika server (e.g. the apache/tika docker image). No local install or models needed.",+ )}+ >+ <ReadinessNotice readiness={readiness} />+ <SettingRow+ title={t("Server base URL")}+ control={+ <input+ className={`${inputClass} w-[320px] max-w-[48vw] font-mono text-[12px]`}+ placeholder={DEFAULT_TIKA_URL}+ value={draftUrl}+ onChange={(e) => {+ setDraftUrl(e.target.value);+ setTestResult(null);+ }}+ />+ }+ />+ <SettingRow+ title={t("Test connection")}+ description={t("Pings the server /version endpoint.")}+ control={+ <div className="flex items-center gap-3">+ {testResult && (+ <span+ className={`inline-flex max-w-[40vw] items-center gap-1 text-[12px] ${+ testResult.ok+ ? "text-emerald-600 dark:text-emerald-400"+ : "text-red-600 dark:text-red-400"+ }`}+ >+ {testResult.ok ? (+ <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />+ ) : (+ <XCircle className="h-3.5 w-3.5 shrink-0" />+ )}+ {testResult.message}+ </span>+ )}+ <button+ type="button"+ onClick={testConnection}+ disabled={testing || saving || busy}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-3 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {testing && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Test")}+ </button>+ <button+ type="button"+ onClick={save}+ disabled={saving || busy}+ className="inline-flex items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {saving && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Save Tika server")}+ </button>+ </div>+ }+ />+ <div className="px-1 pb-4">+ <span className="text-[12px] text-[var(--muted-foreground)]">+ {t(+ "Settings are written to data/user/settings/document_parsing.json.",+ )}+ </span>+ </div>+ </SettingSection>+ );+}+function MarkItDownPanel({slice,available,