Skip to content

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

feat: Add remote Docling Serve parsing support (#845)

Alok Saboo506292427911
diff --git a/README.md b/README.md
index 47a40c54f..4803248eb 100644
--- a/README.md
+++ b/README.md
@@ -583,7 +583,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. 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, 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`.
</details>
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 0e50dc506..057208146 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -270,6 +270,15 @@ class DocumentParsingTest(BaseModel):
engine: Optional[str] = None
+class DoclingRemoteTest(BaseModel):
+ """Draft Docling remote-server test. ``api_token`` is tri-state: ``None``
+ falls back to the stored key, ``""`` clears it, a string supplies it (so
+ the user can verify an unsaved key before saving)."""
+
+ api_base_url: str = "http://localhost:5001"
+ api_token: Optional[str] = None
+
+
class DocumentParsingInstall(BaseModel):
"""One-click pip install of an optional parser engine's package(s)."""
@@ -812,8 +821,6 @@ def _document_parsing_payload() -> dict[str, Any]:
readiness: dict[str, Any] = {}
available = list_engines()
for entry in available:
- if not entry["available"]:
- continue
try:
parser = get_parser(entry["id"])
report = parser.is_ready(parser.resolve_config())
@@ -826,6 +833,7 @@ def _document_parsing_payload() -> dict[str, Any]:
continue
mineru_slice = engines.get("mineru", {})
+ docling_slice = engines.get("docling", {})
return {
"engine": full.get("engine"),
"engines": redacted,
@@ -839,6 +847,10 @@ def _document_parsing_payload() -> dict[str, Any]:
"api_token_set": bool(mineru_slice.get("api_token")),
"local_cli": local_cli_probe(str(mineru_slice.get("local_cli_path") or "")),
},
+ # Docling UI state (token presence for remote mode).
+ "docling": {
+ "api_token_set": bool(docling_slice.get("api_token")),
+ },
}
@@ -893,8 +905,10 @@ async def update_document_parsing_settings(payload: DocumentParsingUpdate):
if name not in engines:
continue
merged = dict(update or {})
- # MinerU token tri-state: omitted / None keeps the stored token.
- if name == "mineru" and merged.get("api_token") is None:
+ # Token tri-state for engines with a secret (MinerU, Docling remote):
+ # omitted / None keeps the stored token; "" clears it; a string
+ # replaces it.
+ if "api_token" in (engines[name] or {}) and merged.get("api_token") is None:
merged.pop("api_token", None)
engines[name].update(merged)
@@ -917,7 +931,14 @@ async def test_document_parsing(payload: DocumentParsingTest):
return {"ok": False, "message": f"The '{engine}' parsing engine isn't installed."}
try:
parser = get_parser(engine)
- report = parser.is_ready(parser.resolve_config())
+ config = parser.resolve_config()
+ report = parser.is_ready(config)
+ # Remote engines get a live connectivity check (e.g. Docling Serve
+ # /health) rather than a config-only readiness gate.
+ verify = getattr(parser, "verify", None)
+ if verify is not None and report.ready and callable(verify):
+ ok, message = verify(config)
+ return {"ok": ok, "message": message or ("Ready to parse." if ok else "Not ready.")}
except Exception as exc: # noqa: BLE001 - surface as a test result
return {"ok": False, "message": str(exc)}
return {
@@ -926,6 +947,34 @@ async def test_document_parsing(payload: DocumentParsingTest):
}
[email protected]("/document-parsing/docling/test")
+async def test_docling_remote_connection(payload: DoclingRemoteTest):
+ """Live connectivity check for the Docling remote-server draft values.
+ Pings the server health + version endpoints and returns ``ok`` + a
+ human-readable detail. Tests draft form values so the user can verify the
+ URL/key before saving; falls back to the stored key when the secret field
+ is untouched."""
+ _require_settings_admin()
+ from deeptutor.services.parsing.engines.docling.config import (
+ DoclingConfig,
+ resolve_docling_config,
+ )
+ from deeptutor.services.parsing.engines.docling.remote import verify_remote
+
+ stored = resolve_docling_config()
+ base_url = payload.api_base_url.strip().rstrip("/") or "http://localhost:5001"
+ token = stored.api_token if payload.api_token is None else payload.api_token.strip()
+ config = DoclingConfig(
+ mode="remote",
+ api_base_url=base_url,
+ api_token=token,
+ do_ocr=stored.do_ocr,
+ do_table_structure=stored.do_table_structure,
+ )
+ 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.py
index 7940f4cd8..465ab517a 100644
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@ -87,6 +87,10 @@ _LEGACY_DOCUMENT_PARSING_SETTINGS_NAME = "mineru"
MINERU_MODE_LOCAL = "local"
MINERU_MODE_CLOUD = "cloud"
_MINERU_MODES = frozenset({MINERU_MODE_LOCAL, MINERU_MODE_CLOUD})
+
+DOCLING_MODE_LOCAL = "local"
+DOCLING_MODE_REMOTE = "remote"
+_DOCLING_MODES = frozenset({DOCLING_MODE_LOCAL, DOCLING_MODE_REMOTE})
_MINERU_MODEL_VERSIONS = frozenset({"pipeline", "vlm"})
_MINERU_DOWNLOAD_SOURCES = frozenset({"huggingface", "modelscope"})
@@ -143,9 +147,14 @@ _DEFAULT_MINERU_ENGINE: dict[str, Any] = {
"allow_local_model_download": False,
}
-# Docling engine slice. Downloads layout/table models on first run, hence the
-# same ``allow_local_model_download`` gate as MinerU local.
+# Docling engine slice. ``mode`` selects the in-process ``docling`` package
+# ("local") or a Docling Serve HTTP server ("remote"; needs ``api_base_url`` and
+# optionally ``api_token``). Local downloads layout/table models on first run,
+# hence the same ``allow_local_model_download`` gate as MinerU local.
_DEFAULT_DOCLING_ENGINE: dict[str, Any] = {
+ "mode": DOCLING_MODE_LOCAL,
+ "api_base_url": "http://localhost:5001",
+ "api_token": "",
"do_ocr": False,
"do_table_structure": True,
"allow_local_model_download": False,
@@ -422,6 +431,9 @@ class RuntimeSettingsService:
engines[DOCUMENT_PARSING_ENGINE_MINERU] = self._apply_mineru_process_overrides(
dict(engines[DOCUMENT_PARSING_ENGINE_MINERU])
)
+ engines[DOCUMENT_PARSING_ENGINE_DOCLING] = self._apply_docling_process_overrides(
+ dict(engines[DOCUMENT_PARSING_ENGINE_DOCLING])
+ )
payload = {**payload, "engines": engines}
return payload
@@ -861,7 +873,14 @@ class RuntimeSettingsService:
}
def _normalize_docling_engine(self, settings: dict[str, Any]) -> dict[str, Any]:
+ mode = _string(settings.get("mode")).lower()
+ if mode not in _DOCLING_MODES:
+ mode = DOCLING_MODE_LOCAL
return {
+ "mode": mode,
+ "api_base_url": _string(settings.get("api_base_url")).rstrip("/")
+ or "http://localhost:5001",
+ "api_token": _string(settings.get("api_token")),
"do_ocr": _coerce_bool(settings.get("do_ocr"), False),
"do_table_structure": _coerce_bool(settings.get("do_table_structure"), True),
"allow_local_model_download": _coerce_bool(
@@ -869,6 +888,16 @@ class RuntimeSettingsService:
),
}
+ def _apply_docling_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = dict(settings)
+ if value := self._process_env_value("DOCLING_MODE"):
+ payload["mode"] = value
+ if value := self._process_env_value("DOCLING_API_BASE_URL"):
+ payload["api_base_url"] = value
+ if value := self._process_env_value("DOCLING_API_TOKEN"):
+ payload["api_token"] = value
+ return self._normalize_docling_engine(payload)
+
def _normalize_markitdown_engine(self, settings: dict[str, Any]) -> dict[str, Any]:
return {
"enable_llm_image_description": _coerce_bool(
@@ -1113,6 +1142,8 @@ __all__ = [
"DOCUMENT_PARSING_ENGINE_MINERU",
"DOCUMENT_PARSING_ENGINE_PYMUPDF4LLM",
"DOCUMENT_PARSING_ENGINE_TEXT_ONLY",
+ "DOCLING_MODE_LOCAL",
+ "DOCLING_MODE_REMOTE",
"LITEPARSE_IMAGE_MODES",
"MINERU_MODE_CLOUD",
"MINERU_MODE_LOCAL",
diff --git a/deeptutor/services/parsing/engines/docling/config.py b/deeptutor/services/parsing/engines/docling/config.py
index 7e9a18eee..97b344460 100644
--- a/deeptutor/services/parsing/engines/docling/config.py
+++ b/deeptutor/services/parsing/engines/docling/config.py
@@ -5,25 +5,51 @@ from __future__ import annotations
from dataclasses import dataclass
from deeptutor.services.config.runtime_settings import (
+ DOCLING_MODE_LOCAL,
+ DOCLING_MODE_REMOTE,
DOCUMENT_PARSING_ENGINE_DOCLING,
load_document_parsing_settings,
)
+DEFAULT_DOCLING_SERVER_URL = "http://localhost:5001"
+
@dataclass(frozen=True)
class DoclingConfig:
+ """Validated Docling configuration.
+
+ ``mode`` is ``"local"`` (the ``docling`` package runs in-process) or
+ ``"remote"`` (a Docling Serve HTTP server does the conversion). Remote adds
+ ``api_base_url`` and an optional ``api_token`` sent as ``X-Api-Key``. The
+ remaining fields are parsing knobs the local converter ignores where it
+ doesn't support them.
+ """
+
+ mode: str = DOCLING_MODE_LOCAL
+ api_base_url: str = DEFAULT_DOCLING_SERVER_URL
+ api_token: str = ""
do_ocr: bool = False
do_table_structure: bool = True
- # See ``allow_local_model_download`` on MinerU — gates the first-run weight
- # download (default off → no silent pull).
allow_local_model_download: bool = False
+ @property
+ def is_local(self) -> bool:
+ return self.mode == DOCLING_MODE_LOCAL
+
+ @property
+ def is_remote(self) -> bool:
+ return self.mode == DOCLING_MODE_REMOTE
+
def resolve_docling_config() -> DoclingConfig:
slice_ = (
load_document_parsing_settings().get("engines", {}).get(DOCUMENT_PARSING_ENGINE_DOCLING, {})
)
return DoclingConfig(
+ mode=str(slice_.get("mode") or DOCLING_MODE_LOCAL),
+ api_base_url=str(slice_.get("api_base_url") or DEFAULT_DOCLING_SERVER_URL).rstrip("/")
+ or DEFAULT_DOCLING_SERVER_URL,
+ api_token=str(slice_.get("api_token") or ""),
do_ocr=bool(slice_.get("do_ocr", False)),
do_table_structure=bool(slice_.get("do_table_structure", True)),
allow_local_model_download=bool(slice_.get("allow_local_model_download", False)),
diff --git a/deeptutor/services/parsing/engines/docling/engine.py b/deeptutor/services/parsing/engines/docling/engine.py
index 643cf5788..a376e3512 100644
--- a/deeptutor/services/parsing/engines/docling/engine.py
+++ b/deeptutor/services/parsing/engines/docling/engine.py
@@ -88,13 +88,25 @@ class DoclingParser:
return _SUPPORTED
def signature(self, config: DoclingConfig) -> ParserSignature:
+ version = package_version("docling")
+ if config.is_remote:
+ version = f"remote:{config.api_base_url}"
return ParserSignature.build(
"docling",
- package_version("docling"),
+ version,
{"do_ocr": config.do_ocr, "do_table_structure": config.do_table_structure},
)
def is_ready(self, config: DoclingConfig) -> ReadinessReport:
+ # Remote mode needs no local package or models.
+ if config.is_remote:
+ if not (config.api_base_url or "").strip():
+ return ReadinessReport(
+ ready=False,
+ reason="not_configured",
+ message="Docling remote mode has no server URL configured.",
+ )
+ return ReadinessReport(ready=True)
if not self.is_available():
return ReadinessReport(
ready=False,
@@ -113,6 +125,15 @@ class DoclingParser:
),
)
+ def verify(self, config: DoclingConfig) -> tuple[bool, str]:
+ """Live connectivity check for the Settings “Test” button (remote only).
+ No-op for local mode."""
+ if config.is_remote:
+ from .remote import verify_remote
+
+ return verify_remote(config)
+ return self.is_ready(config).ready, ""
+
def parse(
self,
source_path: Path,
@@ -121,6 +142,11 @@ class DoclingParser:
config: DoclingConfig,
on_output: Optional[Callable[[str], None]] = None,
) -> None:
+ if config.is_remote:
+ from .remote import parse_remote
+
+ parse_remote(source_path, workdir, config=config, on_output=on_output)
+ return
if on_output:
on_output(f"Converting {Path(source_path).name} via Docling…")
try:
diff --git a/deeptutor/services/parsing/engines/docling/remote.py b/deeptutor/services/parsing/engines/docling/remote.py
new file mode 100644
index 000000000..f48ecf950
--- /dev/null
+++ b/deeptutor/services/parsing/engines/docling/remote.py
@@ -0,0 +1,192 @@
+"""Docling Serve REST API backend.
+
+Sends a local file to a Docling Serve server via ``POST /v1/convert/file`` and
+writes the returned Markdown into the working directory — matching the canonical
+IR the local ``DoclingParser`` produces (``<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 json
+import logging
+from pathlib import Path
+
+import httpx
+
+from ...types import ParserError
+from .config import DoclingConfig
+
+logger = logging.getLogger(__name__)
+
+_CONVERT_ENDPOINT = "/v1/convert/file"
+_READY_ENDPOINT = "/health"
+_VERSION_ENDPOINT = "/version"
+
+_SUBMIT_TIMEOUT_SECONDS = 300.0
+_HEALTH_TIMEOUT_SECONDS = 8.0
+
+
+def parse_remote(
+ source_path: Path,
+ workdir: Path,
+ config: DoclingConfig,
+ *,
+ on_output: Callable[[str], None] | None = None,
+) -> None:
+ """Send ``source_path`` to the Docling Serve 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.api_base_url or "").strip():
+ raise ParserError(
+ "Docling remote mode 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.api_base_url.rstrip("/")
+ report(f"Docling server: converting {source_path.name}…")
+ try:
+ markdown = _convert_file(source_path, base_url, config)
+ except _ConnectivityError as exc:
+ raise ParserError(str(exc)) from exc
+
+ stem = source_path.stem
+ (workdir / f"{stem}.md").write_text(markdown, encoding="utf-8")
+ report(f"Docling server: wrote {stem}.md")
+
+
+def verify_remote(
+ config: DoclingConfig, timeout: float = _HEALTH_TIMEOUT_SECONDS
+) -> tuple[bool, str]:
+ """Best-effort connectivity check for the Settings "Test connection" button.
+
+ Pings ``/health`` and reads ``/version`` — cheap and non-destructive. Never
+ raises; returns ``(ok, detail)``."""
+ if not (config.api_base_url or "").strip():
+ return False, "No Docling server URL configured."
+ base_url = config.api_base_url.rstrip("/")
+ headers = _auth_headers(config)
+ try:
+ with httpx.Client(timeout=timeout) as client:
+ ready = _get_text(client, base_url + _READY_ENDPOINT, headers=headers)
+ version = _get_text(client, base_url + _VERSION_ENDPOINT, headers=headers)
+ except _ConnectivityError as exc:
+ return False, str(exc)
+ return True, f"{ready} · {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, config: DoclingConfig) -> str:
+ headers = _auth_headers(config)
+ data = {
+ "to_formats": "md",
+ "do_ocr": "true" if config.do_ocr else "false",
+ "do_table_structure": "true" if config.do_table_structure else "false",
+ }
+ with source_path.open("rb") as source:
+ files = {"files": (source_path.name, source, "application/octet-stream")}
+ with httpx.Client(
+ base_url=base_url, headers=headers, timeout=_SUBMIT_TIMEOUT_SECONDS
+ ) as client:
+ try:
+ response = client.post(_CONVERT_ENDPOINT, files=files, data=data)
+ except httpx.HTTPError as exc:
+ raise _ConnectivityError(f"Docling server request failed: {exc}") from exc
+ try:
+ response.raise_for_status()
+ except httpx.HTTPStatusError as exc:
+ raise _ConnectivityError(_http_error_message(exc)) from exc
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise _ConnectivityError("Docling server returned a non-JSON response.") from exc
+ return _extract_markdown(payload, source_path.name)
+
+
+def _extract_markdown(payload: dict, file_name: str) -> str:
+ """Pull Markdown out of the sync endpoint's ``{document, status, errors}``
+ envelope, failing on business errors even when the server returns HTTP 200."""
+ if not isinstance(payload, dict):
+ raise _ConnectivityError("Docling server returned an unexpected (non-JSON) response.")
+ status = str(payload.get("status") or "").strip().lower()
+ if status == "success":
+ markdown = (payload.get("document") or {}).get("md_content")
+ if isinstance(markdown, str):
+ return markdown
+ raise _ConnectivityError(
+ f"Docling server reported success but returned no Markdown for {file_name}."
+ )
+ detail = _format_errors(payload.get("errors")) or f"status: {status or 'unknown'}"
+ raise _ConnectivityError(f"Docling failed to convert {file_name}: {detail}")
+
+
+def _format_errors(errors) -> str:
+ if not isinstance(errors, list):
+ return ""
+ parts = [
+ str(err["error"]) if isinstance(err, dict) and err.get("error") else "" for err in errors
+ ]
+ return "; ".join(p for p in parts if p)
+
+
+def _auth_headers(config: DoclingConfig) -> dict[str, str]:
+ token = (config.api_token or "").strip()
+ # Docling Serve sends auth via the ``X-Api-Key`` header.
+ return {"X-Api-Key": token} if token else {}
+
+
+def _http_error_message(exc: httpx.HTTPStatusError) -> str:
+ status = exc.response.status_code
+ if status in (401, 403):
+ return (
+ "Docling server rejected the API key (401/403). Check the key under "
+ "Settings → Document Parsing."
+ )
+ if status == 413:
+ return "Docling server refused the file — it exceeds the server size limit (413)."
+ if status == 429:
+ return "Docling server rate limit hit (429). Try again later."
+ return f"Docling server returned HTTP {status}."
+
+
+def _get_text(client: httpx.Client, url: str, headers: dict[str, str]) -> str:
+ try:
+ response = client.get(url, headers=headers)
+ 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"Docling server request failed: {exc}") from exc
+ text = response.text.strip()
+ if not text:
+ return "reachable"
+ if text.startswith("{"):
+ # /version returns JSON like {"docling-serve": "1.29.0", ...}; summarise it.
+ try:
+ obj = json.loads(text)
+ version = obj.get("docling-serve") or obj.get("version")
+ return f"Docling Serve {version or 'reachable'}"
+ except Exception:
+ return "reachable"
+ return text
+
+
+__all__ = ["parse_remote", "verify_remote"]
diff --git a/deeptutor/services/parsing/engines/factory.py b/deeptutor/services/parsing/engines/factory.py
index e5d27aa3b..d85ae374a 100644
--- a/deeptutor/services/parsing/engines/factory.py
+++ b/deeptutor/services/parsing/engines/factory.py
@@ -92,8 +92,9 @@ _ENGINE_META: Dict[str, Dict[str, Any]] = {
DOCUMENT_PARSING_ENGINE_DOCLING: {
"name": "Docling",
"description": (
- "Structured document conversion (layout/tables). Downloads local "
- "models on first run. PDF/Office/HTML/images."
+ "Structured document conversion (layout/tables). Runs the in-process "
+ "docling package (downloads models on first run) or points at a remote "
+ "Docling Serve server. PDF/Office/HTML/images."
),
"needs_local_models": True,
},
diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.py
index 97d0a4457..23c6cc448 100644
--- a/tests/services/config/test_runtime_settings.py
+++ b/tests/services/config/test_runtime_settings.py
@@ -298,6 +298,77 @@ def test_mineru_local_cli_path_roundtrip(tmp_path: Path) -> None:
assert service.save_mineru({})["local_cli_path"] == ""
+def test_docling_defaults_and_normalization(tmp_path: Path) -> None:
+ service = RuntimeSettingsService(tmp_path / "settings", process_env={})
+
+ full = service.load_document_parsing(include_process_overrides=False)
+ defaults = full["engines"]["docling"]
+ assert defaults["mode"] == "local"
+ assert defaults["api_base_url"] == "http://localhost:5001"
+ assert defaults["api_token"] == ""
+ assert defaults["do_ocr"] is False
+ assert defaults["do_table_structure"] is True
+ assert defaults["allow_local_model_download"] is False
+
+ saved = service.save_document_parsing(
+ {
+ "engines": {
+ "docling": {
+ "mode": "REMOTE", # case-insensitive
+ "api_base_url": "http://192.168.2.162:5001/", # trailing slash stripped
+ "api_token": " key-123 ", # trimmed
+ "do_ocr": "yes", # coerced to bool
+ }
+ }
+ }
+ )["engines"]["docling"]
+ assert saved["mode"] == "remote"
+ assert saved["api_base_url"] == "http://192.168.2.162:5001"
+ assert saved["api_token"] == "key-123"
+ assert saved["do_ocr"] is True
+ # Unknown mode falls back to local; invalid URL falls back to the default.
+ assert (
+ service.save_document_parsing({"engines": {"docling": {"mode": "weird"}}})["engines"][
+ "docling"
+ ]["mode"]
+ == "local"
+ )
+ assert (
+ service.save_document_parsing({"engines": {"docling": {"api_base_url": ""}}})["engines"][
+ "docling"
+ ]["api_base_url"]
+ == "http://localhost:5001"
+ )
+
+
+def test_docling_process_env_override(tmp_path: Path) -> None:
+ service = RuntimeSettingsService(
+ tmp_path / "settings",
+ process_env={
+ "DOCLING_MODE": "remote",
+ "DOCLING_API_BASE_URL": "http://docling:5001",
+ "DOCLING_API_TOKEN": "env-key",
+ },
+ )
+ service.save_document_parsing(
+ {"engines": {"docling": {"mode": "local", "api_token": "file-key"}}}
+ )
+
+ full = service.load_document_parsing()
+ docling = full["engines"]["docling"]
+ assert docling["mode"] == "remote"
+ assert docling["api_base_url"] == "http://docling:5001"
+ assert docling["api_token"] == "env-key"
+ # Persisted file keeps on-disk values, not the env overrides.
+ persisted = _read_json(service.path_for("document_parsing"))["engines"]["docling"]
+ assert persisted["mode"] == "local"
+ assert persisted["api_token"] == "file-key"
+
+ # Without env, the file value is returned.
+ plain = RuntimeSettingsService(tmp_path / "settings", process_env={})
+ assert plain.load_document_parsing()["engines"]["docling"]["api_token"] == "file-key"
+
+
def test_mineru_process_env_override(tmp_path: Path) -> None:
service = RuntimeSettingsService(
tmp_path / "settings",
diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.py
index fdb8f109b..5b0dc65f5 100644
--- a/tests/services/parsing/test_engines.py
+++ b/tests/services/parsing/test_engines.py
@@ -3,9 +3,11 @@ from __future__ import annotations
from pathlib import Path
import zipfile
+import httpx
import pytest
from deeptutor.services.parsing.engines import factory
+from deeptutor.services.parsing.engines.docling.config import DoclingConfig
from deeptutor.services.parsing.types import ParserError
@@ -86,6 +88,116 @@ def test_mineru_cloud_readiness_needs_token() -> None:
assert mineru_readiness(MinerUConfig(mode="cloud", api_token="tok")).ready is True
+def test_docling_signature_distinguishes_local_and_remote() -> None:
+ parser = factory.get_parser("docling")
+ from deeptutor.services.parsing.engines.docling.config import DoclingConfig
+
+ local = parser.signature(DoclingConfig(mode="local")).hash()
+ remote = parser.signature(DoclingConfig(mode="remote", api_base_url="http://host:5001")).hash()
+ other_host = parser.signature(
+ DoclingConfig(mode="remote", api_base_url="http://other:5001")
+ ).hash()
+ assert local != remote
+ assert remote != other_host
+
+
+def test_docling_remote_readiness_needs_no_local_package() -> None:
+ parser = factory.get_parser("docling")
+ from deeptutor.services.parsing.engines.docling.config import DoclingConfig
+
+ # Remote mode is ready with a URL set — even if the docling package is absent.
+ assert parser.is_ready(DoclingConfig(mode="remote", api_base_url="http://host:5001")).ready
+ blocked = parser.is_ready(DoclingConfig(mode="remote", api_base_url=""))
+ assert blocked.ready is False
+ assert blocked.reason == "not_configured"
+
+
+def test_docling_remote_parse_writes_markdown(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ pdf = tmp_path / "doc.pdf"
+ pdf.write_bytes(b"%PDF-1.4 fake")
+ workdir = tmp_path / "parsed"
+ workdir.mkdir()
+
+ captured: dict = {}
+
+ class _FakeClient:
+ def __init__(self, *_args, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def post(self, endpoint, files=None, data=None):
+ captured["endpoint"] = endpoint
+ captured["files"] = files
+ captured["data"] = data
+ return _FakeResponse(
+ {
+ "status": "success",
+ "document": {"md_content": "# Extracted via Docling serve\n"},
+ }
+ )
+
+ class _FakeResponse:
+ def __init__(self, payload):
+ self.payload = payload
+
+ def raise_for_status(self):
+ return None
+
+ def json(self):
+ return self.payload
+
+ monkeypatch.setattr(httpx, "Client", _FakeClient)
+ parser = factory.get_parser("docling")
+ parser.parse(pdf, workdir, config=DoclingConfig(mode="remote", api_base_url="http://host:5001"))
+
+ # Remote parse goes to /v1/convert/file with markdown output requested and
+ # the parsed markdown written to <stem>.md.
+ assert captured["endpoint"] == "/v1/convert/file"
+ assert captured["data"]["to_formats"] == "md"
+ assert captured["files"]["files"][1].closed
+ assert (workdir / "doc.md").read_text(encoding="utf-8") == "# Extracted via Docling serve\n"
+
+
+def test_docling_remote_business_error_raises(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ pdf = tmp_path / "doc.pdf"
+ pdf.write_bytes(b"%PDF-1.4 fake")
+ workdir = tmp_path / "parsed"
+ workdir.mkdir()
+
+ class _FailingResponse:
+ def raise_for_status(self):
+ return None
+
+ def json(self):
+ return {"status": "failure", "errors": [{"error": "bad file"}], "document": None}
+
+ class _FailingClient:
+ def __init__(self, *_args, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ def post(self, *args, **kwargs):
+ return _FailingResponse()
+
+ monkeypatch.setattr(httpx, "Client", _FailingClient)
+ parser = factory.get_parser("docling")
+ with pytest.raises(ParserError, match="bad file"):
+ parser.parse(
+ pdf, workdir, config=DoclingConfig(mode="remote", api_base_url="http://host:5001")
+ )
+ assert not (workdir / "doc.md").exists()
+
+
def test_mineru_local_model_download_gate(monkeypatch: pytest.MonkeyPatch) -> None:
from deeptutor.services.parsing.engines.mineru import backend
from deeptutor.services.parsing.engines.mineru import readiness as rd
diff --git a/web/app/(utility)/settings/document-parsing/page.tsx b/web/app/(utility)/settings/document-parsing/page.tsx
index 61aa408ce..f1c8e83e6 100644
--- a/web/app/(utility)/settings/document-parsing/page.tsx
+++ b/web/app/(utility)/settings/document-parsing/page.tsx
@@ -8,6 +8,7 @@ import {
SettingRow,
SettingSection,
SettingsPageHeader,
+ inputClass,
nativeSelectClass,
selectOptionClass,
} from "@/components/settings/shared";
@@ -32,6 +33,7 @@ type DocumentParsingPayload = {
readiness: Record<string, Readiness>;
installable: string[];
mineru: { api_token_set: boolean; local_cli?: unknown };
+ docling?: { api_token_set: boolean };
};
const PIP_HINT: Record<string, string> = {
@@ -55,8 +57,7 @@ export default function DocumentParsingSettingsPage() {
apiUrl("/api/v1/settings/document-parsing"),
);
const payload = (await response.json().catch(() => ({}))) as
- | DocumentParsingPayload
- | { detail?: string };
+ DocumentParsingPayload | { detail?: string };
if (!response.ok) {
throw new Error(
"detail" in payload && payload.detail
@@ -90,8 +91,7 @@ export default function DocumentParsingSettingsPage() {
},
);
const payload = (await response.json().catch(() => ({}))) as
- | DocumentParsingPayload
- | { detail?: string };
+ DocumentParsingPayload | { detail?: string };
if (!response.ok) {
throw new Error(
"detail" in payload && payload.detail
@@ -100,8 +100,10 @@ export default function DocumentParsingSettingsPage() {
);
}
setData(payload as DocumentParsingPayload);
+ return true;
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
+ return false;
} finally {
setBusy(false);
}
@@ -201,6 +203,7 @@ export default function DocumentParsingSettingsPage() {
}
busy={busy}
onInstalled={load}
+ tokenSet={data.docling?.api_token_set ?? false}
onSave={(patch) =>
putDocumentParsing({ engines: { docling: patch } })
}
@@ -324,11 +327,16 @@ function ReadinessNotice({ readiness }: { readiness?: Readiness }) {
);
}
+const DOCLING_MODES = ["local", "remote"] as const;
+const DEFAULT_DOCLING_URL = "http://localhost:5001";
+const TOKEN_MASK = "••••••••••••";
+
function DoclingPanel({
slice,
readiness,
available,
busy,
+ tokenSet,
onInstalled,
onSave,
}: {
@@ -336,74 +344,337 @@ function DoclingPanel({
readiness?: Readiness;
available: boolean;
busy: boolean;
+ tokenSet: boolean;
onInstalled: () => void;
- onSave: (patch: Record<string, unknown>) => void;
+ onSave: (patch: Record<string, unknown>) => Promise<boolean>;
}) {
const { t } = useTranslation();
+ const mode =
+ slice.mode === "remote"
+ ? "remote"
+ : slice.mode === "local"
+ ? "local"
+ : "local";
+ const isRemote = mode === "remote";
const doOcr = Boolean(slice.do_ocr);
const doTables = slice.do_table_structure !== false;
const allowDownload = Boolean(slice.allow_local_model_download);
- if (!available) {
- return (
- <NotInstalledSection
- engineId="docling"
- title={t("Docling")}
- onInstalled={onInstalled}
- />
- );
+ // Remote server URL + API key are edited as a draft and saved together so a
+ // half-typed URL is never used mid-parse. Token is write-only.
+ const [remoteDraft, setRemoteDraft] = useState({
+ url: (typeof slice.api_base_url === "string" && slice.api_base_url) || "",
+ });
+ const [tokenDraft, setTokenDraft] = useState("");
+ const [tokenTouched, setTokenTouched] = useState(false);
+ const [savingRemote, setSavingRemote] = useState(false);
+ const [testing, setTesting] = useState(false);
+ const [testResult, setTestResult] = useState<{
+ ok: boolean;
+ message: string;
+ } | null>(null);
+ const [remoteMsg, setRemoteMsg] = useState("");
+
+ async function saveRemote() {
+ setSavingRemote(true);
+ setRemoteMsg("");
+ setTestResult(null);
+ const patch: Record<string, unknown> = {
+ mode: "remote",
+ api_base_url: remoteDraft.url.trim() || DEFAULT_DOCLING_URL,
+ };
+ if (tokenTouched) patch.api_token = tokenDraft;
+ try {
+ const saved = await onSave(patch);
+ if (saved) {
+ setRemoteMsg(t("Remote Docling settings saved."));
+ setTokenDraft("");
+ setTokenTouched(false);
+ }
+ } finally {
+ setSavingRemote(false);
+ }
+ }
+
+ async function testConnection() {
+ setTesting(true);
+ setTestResult(null);
+ try {
+ const body: Record<string, unknown> = {
+ api_base_url: remoteDraft.url.trim() || DEFAULT_DOCLING_URL,
+ };
+ if (tokenTouched) body.api_token = tokenDraft;
+ const response = await apiFetch(
+ apiUrl("/api/v1/settings/document-parsing/docling/test"),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ },
+ );
+ 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);
+ }
}
+ const notInstalled = !available && !isRemote;
+
return (
- <SettingSection
- title={t("Docling")}
- description={t(
- "Structured conversion of PDF/Office/HTML/images. Downloads layout/table models on first run.",
+ <>
+ <SettingSection
+ title={t("Docling backend")}
+ description={t(
+ "Choose where parsing runs: the in-process docling package (local) or a Docling Serve server (remote).",
+ )}
+ >
+ <SettingRow
+ title={t("Mode")}
+ description={
+ isRemote
+ ? t(
+ "Documents are sent to a Docling Serve server for conversion.",
+ )
+ : t(
+ "Parsing runs on this machine using the installed docling package.",
+ )
+ }
+ control={
+ <div className="inline-flex rounded-lg border border-[var(--border)] p-0.5">
+ {DOCLING_MODES.map((m) => (
+ <button
+ key={m}
+ type="button"
+ disabled={busy}
+ onClick={() => {
+ if (m !== mode) {
+ onSave({ mode: m });
+ setTestResult(null);
+ }
+ }}
+ className={`rounded-md px-3 py-1 text-[12px] font-medium transition-colors disabled:opacity-40 ${
+ mode === m
+ ? "bg-[var(--foreground)] text-[var(--background)]"
+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"
+ }`}
+ >
+ {m === "local" ? t("Local") : t("Remote server")}
+ </button>
+ ))}
+ </div>
+ }
+ />
+ </SettingSection>
+
+ {isRemote && (
+ <SettingSection
+ title={t("Remote server")}
+ description={t(
+ "Point at a Docling Serve server (e.g. `docling serve` or the docker image). No local docling install or models needed.",
+ )}
+ >
+ <SettingRow
+ title={t("Server base URL")}
+ control={
+ <input
+ className={`${inputClass} w-[320px] max-w-[48vw] font-mono text-[12px]`}
+ placeholder={DEFAULT_DOCLING_URL}
+ value={remoteDraft.url}
+ onChange={(e) => {
+ setRemoteDraft({ url: e.target.value });
+ setTestResult(null);
+ }}
+ />
+ }
+ />
+ <SettingRow
+ title={t("API key")}
+ description={
+ tokenSet
+ ? t(
+ "A key is saved. Type to replace it; leave blank to keep it.",
+ )
+ : t(
+ "Optional. Sent as the X-Api-Key header for a secured server.",
+ )
+ }
+ control={
+ <input
+ type="password"
+ className={`${inputClass} w-[320px] max-w-[48vw]`}
+ placeholder={tokenSet ? TOKEN_MASK : t("Optional API key")}
+ value={tokenDraft}
+ onChange={(e) => {
+ setTokenDraft(e.target.value);
+ setTokenTouched(true);
+ }}
+ />
+ }
+ />
+ <SettingRow
+ title={t("Test connection")}
+ description={t("Pings the server health + version endpoints.")}
+ 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 || savingRemote || 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={saveRemote}
+ disabled={savingRemote || 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"
+ >
+ {savingRemote && <Loader2 className="h-3 w-3 animate-spin" />}
+ {t("Save remote server")}
+ </button>
+ </div>
+ }
+ />
+ <div className="px-1 pb-4">
+ <span className="text-[12px] text-[var(--muted-foreground)]">
+ {remoteMsg ||
+ t(
+ "Settings are written to data/user/settings/document_parsing.json.",
+ )}
+ </span>
+ </div>
+ </SettingSection>
)}
- >
- <ReadinessNotice readiness={readiness} />
- {readiness && !readiness.ready && (
- <ModelDownloadRow
+
+ {isRemote && (
+ <SettingSection
+ title={t("Parsing options")}
+ description={t("Forwarded to the Docling server for each document.")}
+ >
+ <SettingRow
+ title={t("Recognize tables")}
+ control={
+ <Toggle
+ checked={doTables}
+ disabled={busy}
+ onChange={(v) => onSave({ do_table_structure: v })}
+ />
+ }
+ />
+ <SettingRow
+ title={t("OCR scanned pages")}
+ description={t("Slower; enable for image-only PDFs.")}
+ control={
+ <Toggle
+ checked={doOcr}
+ disabled={busy}
+ onChange={(v) => onSave({ do_ocr: v })}
+ />
+ }
+ />
+ </SettingSection>
+ )}
+
+ {!isRemote && notInstalled && (
+ <NotInstalledSection
engineId="docling"
- title={t("Docling")}
- onDownloaded={onInstalled}
+ title={t("Docling (local)")}
+ onInstalled={onInstalled}
/>
)}
- <SettingRow
- title={t("Allow automatic model download")}
- description={t(
- "Off by default. When off, parsing fails with guidance instead of silently downloading models. Or pre-fetch with `docling-tools models download`.",
- )}
- control={
- <Toggle
- checked={allowDownload}
- disabled={busy}
- onChange={(v) => onSave({ allow_local_model_download: v })}
+
+ {!isRemote && !notInstalled && (
+ <SettingSection
+ title={t("Docling (local)")}
+ description={t(
+ "Structured conversion of PDF/Office/HTML/images. Downloads layout/table models on first run.",
+ )}
+ >
+ <ReadinessNotice readiness={readiness} />
+ {readiness && !readiness.ready && (
+ <ModelDownloadRow
+ engineId="docling"
+ title={t("Docling")}
+ onDownloaded={onInstalled}
+ />
+ )}
+ <SettingRow
+ title={t("Allow automatic model download")}
+ description={t(
+ "Off by default. When off, parsing fails with guidance instead of silently downloading models. Or pre-fetch with `docling-tools models download`.",
+ )}
+ control={
+ <Toggle
+ checked={allowDownload}
+ disabled={busy}
+ onChange={(v) => onSave({ allow_local_model_download: v })}
+ />
+ }
/>
- }
- />
- <SettingRow
- title={t("Recognize tables")}
- control={
- <Toggle
- checked={doTables}
- disabled={busy}
- onChange={(v) => onSave({ do_table_structure: v })}
+ <SettingRow
+ title={t("Recognize tables")}
+ control={
+ <Toggle
+ checked={doTables}
+ disabled={busy}
+ onChange={(v) => onSave({ do_table_structure: v })}
+ />
+ }
/>
- }
- />
- <SettingRow
- title={t("OCR scanned pages")}
- description={t("Slower; enable for image-only PDFs.")}
- control={
- <Toggle
- checked={doOcr}
- disabled={busy}
- onChange={(v) => onSave({ do_ocr: v })}
+ <SettingRow
+ title={t("OCR scanned pages")}
+ description={t("Slower; enable for image-only PDFs.")}
+ control={
+ <Toggle
+ checked={doOcr}
+ disabled={busy}
+ onChange={(v) => onSave({ do_ocr: v })}
+ />
+ }
/>
- }
- />
- </SettingSection>
+ </SettingSection>
+ )}
+ </>
);
}