RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
feat(deepdoc): verify PaddleOCR service connectivity in check_installation (#17669)
幻028b851b2272
diff --git a/deepdoc/parser/paddleocr_parser.py b/deepdoc/parser/paddleocr_parser.pyindex 4d94b4d508..dd61bfbe86 100644--- a/deepdoc/parser/paddleocr_parser.py+++ b/deepdoc/parser/paddleocr_parser.py@@ -270,7 +270,17 @@ class PaddleOCRParser(RAGFlowPdfParser):# Public methodsdef check_installation(self) -> tuple[bool, str]:- """Check if the parser is properly installed and configured."""+ """Check that the parser is configured and the OCR service is reachable.++ The hosted service is validated with a minimal POST to the jobs+ endpoint (model only, no file). It authenticates the token before+ accepting a job, so an invalid token yields HTTP 401/403 without+ creating a job or consuming page quota, while a valid token yields a+ different error (e.g. 422 for a missing file). A self-hosted PaddleX+ deployment only serves the synchronous layout-parsing endpoint, so+ reachability there is probed with a plain GET; any HTTP response+ counts as reachable.+ """if not self.base_url:return False, "[PaddleOCR] Base URL not configured"@@ -279,6 +289,37 @@ class PaddleOCRParser(RAGFlowPdfParser):if not self.local and not self.access_token:return False, "[PaddleOCR] Access token not configured"+ # The hosted service is only reachable over HTTPS; a plaintext hosted+ # address is a misconfiguration, not an unauthenticated deployment.+ if not self.local and not self.base_url.strip().lower().startswith("https://"):+ reason = "[PaddleOCR] Hosted service requires an HTTPS base URL"+ self.logger.warning(reason)+ return False, reason++ headers: dict[str, str] = {"Client-Platform": "ragflow"}+ if self.access_token:+ if self.base_url.strip().lower().startswith("https://"):+ headers["Authorization"] = f"Bearer {self.access_token}"+ else:+ self.logger.warning("[PaddleOCR] access token not sent: the endpoint is not HTTPS")++ try:+ if self.local:+ resp = requests.get(self._local_endpoint(self.base_url), headers=headers, timeout=10)+ else:+ jobs_url = f"{self.base_url.rstrip('/')}/api/v2/ocr/jobs"+ resp = requests.post(jobs_url, data={"model": self.algorithm}, headers=headers, timeout=10)+ except Exception as exc: # noqa: BLE001 - connectivity failures are expected here+ reason = f"[PaddleOCR] service unreachable at {self.base_url}: {exc}"+ self.logger.warning(reason)+ return False, reason++ if not self.local and resp.status_code in (401, 403):+ reason = f"[PaddleOCR] access token rejected by {self.base_url} (HTTP {resp.status_code})"+ self.logger.warning(reason)+ return False, reason++ self.logger.info(f"[PaddleOCR] service reachable at {self.base_url} (HTTP {resp.status_code})")return True, ""def parse_pdf(diff --git a/test/unit_test/deepdoc/parser/test_paddleocr_parser.py b/test/unit_test/deepdoc/parser/test_paddleocr_parser.pyindex aa928b88d1..8ad0cd5b53 100644--- a/test/unit_test/deepdoc/parser/test_paddleocr_parser.py+++ b/test/unit_test/deepdoc/parser/test_paddleocr_parser.py@@ -103,6 +103,12 @@ def test_self_hosted_needs_base_url_not_token(monkeypatch):_clear_env(monkeypatch)module = _load_paddleocr_parser(monkeypatch)+ # The connectivity probe must not depend on something actually listening:+ # any HTTP response (a stubbed 404 here) already counts as reachable.+ probe = Mock()+ probe.status_code = 404+ monkeypatch.setattr(module.requests, "get", Mock(return_value=probe))+# A self-hosted deployment usually runs unauthenticated, so the token must# not be required; its address must be.ok, reason = module.PaddleOCRParser(base_url="http://127.0.0.1:8080").check_installation()@@ -124,6 +130,12 @@ def test_hosted_still_requires_token(monkeypatch):assert ok is Falseassert "Access token" in reason+ # The token check probes the jobs endpoint; stub it so the suite never+ # reaches the real hosted service (a valid token yields a non-401/403).+ probe = Mock()+ probe.status_code = 422+ monkeypatch.setattr(module.requests, "post", Mock(return_value=probe))+ok, _ = module.PaddleOCRParser(access_token="tok").check_installation()assert ok is Truediff --git a/test/unit_test/deepdoc/parser/test_paddleocr_parser_check_installation.py b/test/unit_test/deepdoc/parser/test_paddleocr_parser_check_installation.pynew file mode 100644index 0000000000..4d3feb9cda--- /dev/null+++ b/test/unit_test/deepdoc/parser/test_paddleocr_parser_check_installation.py@@ -0,0 +1,238 @@+#+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+"""Unit tests for PaddleOCRParser.check_installation().++The check verifies real service reachability on top of the configuration+checks, mirroring the Mistral/MinerU parser checks. The probe follows the+wire protocol of the configured deployment: the hosted service gets a+minimal model-only POST to the jobs endpoint (which also validates the+token via 401/403), while a self-hosted PaddleX deployment only serves the+synchronous layout-parsing endpoint and is probed with a plain GET. No+live service or heavy deepdoc dependency chain is required.+"""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path+from types import ModuleType+from unittest import mock++import requests++_REPO = Path(__file__).resolve().parents[4]++# The hosted address recognized by _is_hosted_service (matches the module's+# _DEFAULT_BASE_URL); any other hostname counts as a self-hosted deployment.+_HOSTED_BASE = "https://paddleocr.aistudio-app.com"+++def _load_paddleocr_parser(monkeypatch) -> ModuleType:+ """Load paddleocr_parser.py directly, stubbing heavy dependencies."""+ # Heavy / optional third-party imports used by the parser at runtime.+ for name in ("numpy", "pdfplumber", "PIL", "PIL.Image"):+ monkeypatch.setitem(sys.modules, name, mock.MagicMock())++ # deepdoc package tree: provide real modules so class inheritance works.+ deepdoc_mod = ModuleType("deepdoc")+ deepdoc_mod.__path__ = [str(_REPO / "deepdoc")]+ monkeypatch.setitem(sys.modules, "deepdoc", deepdoc_mod)++ parser_mod = ModuleType("deepdoc.parser")+ parser_mod.__path__ = [str(_REPO / "deepdoc" / "parser")]+ monkeypatch.setitem(sys.modules, "deepdoc.parser", parser_mod)++ pdf_parser_mod = ModuleType("deepdoc.parser.pdf_parser")++ class _RAGFlowPdfParser:+ pass++ pdf_parser_mod.RAGFlowPdfParser = _RAGFlowPdfParser+ monkeypatch.setitem(sys.modules, "deepdoc.parser.pdf_parser", pdf_parser_mod)++ utils_mod = ModuleType("deepdoc.parser.utils")+ utils_mod.extract_pdf_outlines = mock.MagicMock(return_value=[])+ monkeypatch.setitem(sys.modules, "deepdoc.parser.utils", utils_mod)++ constants_mod = ModuleType("common.constants")+ constants_mod.MAXIMUM_PAGE_NUMBER = 100000+ monkeypatch.setitem(sys.modules, "common.constants", constants_mod)++ module_name = "test_paddleocr_parser_unit_module"+ spec = importlib.util.spec_from_file_location(module_name, _REPO / "deepdoc" / "parser" / "paddleocr_parser.py")+ module = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, module_name, module)+ spec.loader.exec_module(module)+ return module+++class _Resp:+ def __init__(self, status_code: int, text: str = ""):+ self.status_code = status_code+ self.text = text+++def test_missing_access_token_returns_false_without_request(monkeypatch):+ """The hosted service requires a token; the check fails before any HTTP+ call."""+ m = _load_paddleocr_parser(monkeypatch)+ monkeypatch.delenv("PADDLEOCR_ACCESS_TOKEN", raising=False)+ p = m.PaddleOCRParser(base_url=_HOSTED_BASE, access_token=None)+ with (+ mock.patch.object(m.requests, "post") as post,+ mock.patch.object(m.requests, "get") as get,+ ):+ ok, reason = p.check_installation()+ assert ok is False+ assert "token" in reason.lower()+ post.assert_not_called()+ get.assert_not_called()+++def test_missing_base_url_returns_false_without_request(monkeypatch):+ m = _load_paddleocr_parser(monkeypatch)+ monkeypatch.setenv("PADDLEOCR_BASE_URL", "")+ p = m.PaddleOCRParser(base_url=None, access_token="tok")+ with (+ mock.patch.object(m.requests, "post") as post,+ mock.patch.object(m.requests, "get") as get,+ ):+ ok, reason = p.check_installation()+ assert ok is False+ assert "base url" in reason.lower()+ post.assert_not_called()+ get.assert_not_called()+++def test_access_token_rejected_returns_false(monkeypatch):+ m = _load_paddleocr_parser(monkeypatch)+ p = m.PaddleOCRParser(base_url=_HOSTED_BASE + "/", access_token="bad-token")+ with mock.patch.object(m.requests, "post", return_value=_Resp(401, '{"code": 401, "msg": "Unauthorized"}')) as post:+ ok, reason = p.check_installation()+ assert ok is False+ assert "rejected" in reason.lower()+ post.assert_called_once()+ args, kwargs = post.call_args+ assert args[0] == _HOSTED_BASE + "/api/v2/ocr/jobs"+ assert kwargs["headers"]["Authorization"] == "Bearer bad-token"+ assert kwargs["data"] == {"model": "PaddleOCR-VL"}+++def test_access_token_rejected_403_returns_false(monkeypatch):+ m = _load_paddleocr_parser(monkeypatch)+ p = m.PaddleOCRParser(base_url=_HOSTED_BASE, access_token="bad-token")+ with mock.patch.object(m.requests, "post", return_value=_Resp(403)):+ ok, reason = p.check_installation()+ assert ok is False+ assert "403" in reason+++def test_validation_error_means_token_and_service_ok(monkeypatch):+ """A 4xx other than 401/403 proves the token is accepted (e.g. 422 for a+ missing file), so connectivity is confirmed."""+ m = _load_paddleocr_parser(monkeypatch)+ p = m.PaddleOCRParser(base_url=_HOSTED_BASE, access_token="valid-token")+ with mock.patch.object(m.requests, "post", return_value=_Resp(422, "missing file")):+ ok, reason = p.check_installation()+ assert ok is True+ assert reason == ""+++def test_http_error_other_than_auth_confirms_reachability(monkeypatch):+ """405/404/500 responses still prove the service is reachable."""+ m = _load_paddleocr_parser(monkeypatch)+ p = m.PaddleOCRParser(base_url=_HOSTED_BASE, access_token="tok")+ with mock.patch.object(m.requests, "post", return_value=_Resp(405)):+ ok, _ = p.check_installation()+ assert ok is True+++def test_network_error_returns_false(monkeypatch):+ m = _load_paddleocr_parser(monkeypatch)+ p = m.PaddleOCRParser(base_url=_HOSTED_BASE, access_token="tok")+ with mock.patch.object(+ m.requests,+ "post",+ side_effect=requests.ConnectionError("connection refused"),+ ):+ ok, reason = p.check_installation()+ assert ok is False+ assert "unreachable" in reason.lower()+++def test_hosted_non_https_base_url_rejected_before_probe(monkeypatch):+ """A hosted hostname over plain HTTP is a misconfiguration: fail with a+ configuration reason instead of probing without authentication."""+ m = _load_paddleocr_parser(monkeypatch)+ p = m.PaddleOCRParser(base_url="http://paddleocr.aistudio-app.com", access_token="tok")+ with (+ mock.patch.object(m.requests, "post") as post,+ mock.patch.object(m.requests, "get") as get,+ ):+ ok, reason = p.check_installation()+ assert ok is False+ assert "https" in reason.lower()+ post.assert_not_called()+ get.assert_not_called()+++def test_self_hosted_probe_uses_layout_parsing_get(monkeypatch):+ """A self-hosted PaddleX deployment only serves the synchronous+ layout-parsing endpoint, so the probe is a GET there — no token is+ required and any HTTP response counts as reachable."""+ m = _load_paddleocr_parser(monkeypatch)+ monkeypatch.delenv("PADDLEOCR_ACCESS_TOKEN", raising=False)+ p = m.PaddleOCRParser(base_url="http://127.0.0.1:8080", access_token=None)+ with (+ mock.patch.object(m.requests, "get", return_value=_Resp(404)) as get,+ mock.patch.object(m.requests, "post") as post,+ ):+ ok, reason = p.check_installation()+ assert ok is True+ assert reason == ""+ get.assert_called_once()+ args, kwargs = get.call_args+ assert args[0] == "http://127.0.0.1:8080/layout-parsing"+ assert "Authorization" not in kwargs["headers"]+ post.assert_not_called()+++def test_self_hosted_token_not_sent_over_http(monkeypatch):+ """Mirroring the parse path, the token is not sent to a non-HTTPS+ endpoint."""+ m = _load_paddleocr_parser(monkeypatch)+ monkeypatch.delenv("PADDLEOCR_ACCESS_TOKEN", raising=False)+ p = m.PaddleOCRParser(base_url="http://127.0.0.1:8080", access_token="tok")+ with mock.patch.object(m.requests, "get", return_value=_Resp(200)) as get:+ ok, _ = p.check_installation()+ assert ok is True+ _, kwargs = get.call_args+ assert "Authorization" not in kwargs["headers"]+++def test_self_hosted_base_url_carrying_endpoint_path_not_duplicated(monkeypatch):+ """Pasting the full pipeline URL as the base URL is the likelier user+ mistake; the probe must reuse the address as-is instead of appending the+ endpoint path a second time."""+ m = _load_paddleocr_parser(monkeypatch)+ monkeypatch.delenv("PADDLEOCR_ACCESS_TOKEN", raising=False)+ p = m.PaddleOCRParser(base_url="http://127.0.0.1:8080/layout-parsing", access_token=None)+ with mock.patch.object(m.requests, "get", return_value=_Resp(200)) as get:+ ok, _ = p.check_installation()+ assert ok is True+ args, _ = get.call_args+ assert args[0] == "http://127.0.0.1:8080/layout-parsing"