From e96cba219c55cbf2da454c47f35fbbbe65fd4028 Mon Sep 17 00:00:00 2001 From: "Bingxi Zhao (Frank)" <13051345080@163.com> Date: Sun, 15 Nov 2026 01:20:52 +0800 Subject: [PATCH] feat(docling): expose optional enrichments and version remote cache Fixes #2518 --- .../modules/manifests/parser-docling.json | 4 +- deeptutor/services/config/runtime_settings.py | 8 +++ .../parsing/engines/docling/config.py | 6 ++ .../parsing/engines/docling/engine.py | 7 ++- .../parsing/engines/docling/formats.py | 26 ++++++-- .../parsing/engines/docling/local_worker.py | 38 ++++++++++- .../parsing/engines/docling/remote.py | 31 +++++++++ requirements/modules/parser-docling.txt | 4 +- .../parsing/test_docling_content_list.py | 3 + .../parsing/test_docling_local_worker.py | 46 +++++++++----- tests/services/parsing/test_engines.py | 63 +++++++++++++++---- tests/test_packaging_metadata.py | 4 +- .../DocumentParsingSettingsSection.tsx | 11 +++- 13 files changed, 208 insertions(+), 43 deletions(-) diff --git a/deeptutor/modules/manifests/parser-docling.json b/deeptutor/modules/manifests/parser-docling.json index 338f3f39f..80ca8a22e 100644 --- a/deeptutor/modules/manifests/parser-docling.json +++ b/deeptutor/modules/manifests/parser-docling.json @@ -15,8 +15,8 @@ "navigation": [], "services": [], "requirements": [ - "docling[xbrl]>=2.123.1", - "docling-slim[format-iwork,format-opendocument]>=2.123.1" + "docling[xbrl]>=2.148.0", + "docling-slim[format-iwork,format-opendocument]>=2.148.0" ], "executables": [], "parser_engine": "docling" diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py index 890e8db68..268354325 100644 --- a/deeptutor/services/config/runtime_settings.py +++ b/deeptutor/services/config/runtime_settings.py @@ -231,6 +231,9 @@ _DEFAULT_DOCLING_ENGINE: dict[str, Any] = { "do_ocr": False, "do_table_structure": True, "allow_local_model_download": False, + "do_formula_enrichment": False, + "do_picture_classification": False, + "do_picture_description": False, } # markitdown engine slice. Pure-Python, no model downloads. Optionally uses @@ -1322,6 +1325,11 @@ class RuntimeSettingsService: "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), + "do_formula_enrichment": _coerce_bool(settings.get("do_formula_enrichment"), False), + "do_picture_classification": _coerce_bool( + settings.get("do_picture_classification"), False + ), + "do_picture_description": _coerce_bool(settings.get("do_picture_description"), False), "allow_local_model_download": _coerce_bool( settings.get("allow_local_model_download"), False ), diff --git a/deeptutor/services/parsing/engines/docling/config.py b/deeptutor/services/parsing/engines/docling/config.py index 97b344460..49719ab26 100644 --- a/deeptutor/services/parsing/engines/docling/config.py +++ b/deeptutor/services/parsing/engines/docling/config.py @@ -30,6 +30,9 @@ class DoclingConfig: api_token: str = "" do_ocr: bool = False do_table_structure: bool = True + do_formula_enrichment: bool = False + do_picture_classification: bool = False + do_picture_description: bool = False allow_local_model_download: bool = False @property @@ -52,6 +55,9 @@ def resolve_docling_config() -> DoclingConfig: 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)), + do_formula_enrichment=bool(slice_.get("do_formula_enrichment", False)), + do_picture_classification=bool(slice_.get("do_picture_classification", False)), + do_picture_description=bool(slice_.get("do_picture_description", False)), 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 d03196668..cf792b0b5 100644 --- a/deeptutor/services/parsing/engines/docling/engine.py +++ b/deeptutor/services/parsing/engines/docling/engine.py @@ -95,10 +95,15 @@ class DoclingParser: def signature(self, config: DoclingConfig) -> ParserSignature: version = package_version("docling") if config.is_remote: - version = f"remote-{MIN_DOCLING_VERSION}:{config.api_base_url}" + from .remote import remote_version + + version = f"remote-{remote_version(config)}:{config.api_base_url}" params: dict[str, object] = { "do_ocr": config.do_ocr, "do_table_structure": config.do_table_structure, + "do_formula_enrichment": config.do_formula_enrichment, + "do_picture_classification": config.do_picture_classification, + "do_picture_description": config.do_picture_description, } if config.is_local: # The local worker emits content_list blocks; the schema version diff --git a/deeptutor/services/parsing/engines/docling/formats.py b/deeptutor/services/parsing/engines/docling/formats.py index 4b5af0560..833136a3c 100644 --- a/deeptutor/services/parsing/engines/docling/formats.py +++ b/deeptutor/services/parsing/engines/docling/formats.py @@ -1,6 +1,6 @@ """Docling version and input-format compatibility helpers. -The fallback mirrors Docling 2.123.1, the minimum version DeepTutor installs. +The fallback mirrors Docling 2.148.0, the minimum version DeepTutor installs. The list stays static on purpose. Importing even Docling's format-model module loads Transformers and PyTorch in current Docling releases. On macOS the PyTorch and FAISS wheels bundle different OpenMP runtimes, and putting both in @@ -15,13 +15,27 @@ import re from .._versions import package_version -MIN_DOCLING_VERSION = "2.123.1" +MIN_DOCLING_VERSION = "2.148.0" -# Source: docling.datamodel.base_models.FormatToExtensions in Docling 2.123.1. +# Source: docling.datamodel.base_models.FormatToExtensions in Docling 2.148.0. # Extensions are normalized to lower case and include the leading dot. This # deliberately includes compound suffixes such as .dclg.xml and .tar.gz. -DOCLING_2_123_1_FORMATS = frozenset( +DOCLING_2_148_0_FORMATS = frozenset( { + ".afp", + ".gif", + ".ical", + ".icalendar", + ".ics", + ".ifb", + ".key", + ".markdown", + ".mht", + ".mhtml", + ".numbers", + ".rtf", + ".xltm", + ".xltx", ".aac", ".adoc", ".asc", @@ -106,7 +120,7 @@ def docling_supported_formats() -> frozenset[str]: Do not import ``docling`` here. This helper is called by upload-policy and file-routing paths that must stay independent of Docling's ML runtime. """ - return DOCLING_2_123_1_FORMATS + return DOCLING_2_148_0_FORMATS def installed_docling_version() -> str: @@ -129,7 +143,7 @@ def docling_version_is_current(version: str | None = None) -> bool: __all__ = [ - "DOCLING_2_123_1_FORMATS", + "DOCLING_2_148_0_FORMATS", "MIN_DOCLING_VERSION", "docling_supported_formats", "docling_version_is_current", diff --git a/deeptutor/services/parsing/engines/docling/local_worker.py b/deeptutor/services/parsing/engines/docling/local_worker.py index d8adb9f6e..03a7e03c3 100644 --- a/deeptutor/services/parsing/engines/docling/local_worker.py +++ b/deeptutor/services/parsing/engines/docling/local_worker.py @@ -47,7 +47,13 @@ def parse_local( if config.do_table_structure: command.append("--do-table-structure") + for name in ("do_formula_enrichment", "do_picture_classification", "do_picture_description"): + if getattr(config, name): + command.append("--" + name.replace("_", "-")) env = os.environ.copy() + if not config.allow_local_model_download: + env["HF_HUB_OFFLINE"] = "1" + env["TRANSFORMERS_OFFLINE"] = "1" env["PYTHONUNBUFFERED"] = "1" try: process = subprocess.Popen( # noqa: S603 - argv is fixed and shell=False @@ -94,7 +100,14 @@ def _stop_worker(process: subprocess.Popen) -> None: process.wait() -def _build_converter(*, do_ocr: bool, do_table_structure: bool): +def _build_converter( + *, + do_ocr: bool, + do_table_structure: bool, + do_formula_enrichment: bool = False, + do_picture_classification: bool = False, + do_picture_description: bool = False, +): """Import and configure Docling inside the isolated worker only. Docling's option API moves between compatible releases, so a configuration @@ -114,6 +127,9 @@ def _build_converter(*, do_ocr: bool, do_table_structure: bool): pipeline_options = PdfPipelineOptions() pipeline_options.do_ocr = do_ocr pipeline_options.do_table_structure = do_table_structure + pipeline_options.do_formula_enrichment = do_formula_enrichment + pipeline_options.do_picture_classification = do_picture_classification + pipeline_options.do_picture_description = do_picture_description # Picture crops feed the image blocks of the content_list IR. Guarded # attribute-by-attribute so a Docling release that renames an option # keeps converting (same contract as the fallback below). @@ -124,7 +140,13 @@ def _build_converter(*, do_ocr: bool, do_table_structure: bool): return DocumentConverter( format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)} ) - except Exception as exc: # noqa: BLE001 - degrade to upstream defaults, loudly + except ImportError: + raise + except (AttributeError, TypeError, ValueError, RuntimeError) as exc: + if do_formula_enrichment or do_picture_classification or do_picture_description: + raise ParserError( + "Docling cannot apply the requested enrichments; upgrade the parser or disable those options." + ) from exc # The worker runs under ``python -m`` and the parent relays stderr through # ``on_output``, so a single line here reaches the parse log. print( @@ -144,10 +166,16 @@ def _convert( *, do_ocr: bool, do_table_structure: bool, + do_formula_enrichment: bool = False, + do_picture_classification: bool = False, + do_picture_description: bool = False, ) -> None: converter = _build_converter( do_ocr=do_ocr, do_table_structure=do_table_structure, + do_formula_enrichment=do_formula_enrichment, + do_picture_classification=do_picture_classification, + do_picture_description=do_picture_description, ) result = converter.convert(str(source_path)) document = result.document @@ -169,6 +197,9 @@ def _parser() -> argparse.ArgumentParser: parser.add_argument("--workdir", required=True, type=Path) parser.add_argument("--do-ocr", action="store_true") parser.add_argument("--do-table-structure", action="store_true") + parser.add_argument("--do-formula-enrichment", action="store_true") + parser.add_argument("--do-picture-classification", action="store_true") + parser.add_argument("--do-picture-description", action="store_true") return parser @@ -180,6 +211,9 @@ def main(argv: Optional[Sequence[str]] = None) -> int: args.workdir, do_ocr=args.do_ocr, do_table_structure=args.do_table_structure, + do_formula_enrichment=args.do_formula_enrichment, + do_picture_classification=args.do_picture_classification, + do_picture_description=args.do_picture_description, ) except Exception as exc: # noqa: BLE001 - forwarded to the parent process print(f"{type(exc).__name__}: {exc}", file=sys.stderr, flush=True) diff --git a/deeptutor/services/parsing/engines/docling/remote.py b/deeptutor/services/parsing/engines/docling/remote.py index f48ecf950..77c997d43 100644 --- a/deeptutor/services/parsing/engines/docling/remote.py +++ b/deeptutor/services/parsing/engines/docling/remote.py @@ -69,6 +69,34 @@ def parse_remote( report(f"Docling server: wrote {stem}.md") +def remote_version(config: DoclingConfig) -> str: + """Bind cache reuse to the actual server build, not the local package floor.""" + try: + with httpx.Client(timeout=_HEALTH_TIMEOUT_SECONDS) as client: + response = client.get( + config.api_base_url.rstrip("/") + _VERSION_ENDPOINT, headers=_auth_headers(config) + ) + response.raise_for_status() + value = response.json() + if not isinstance(value, dict) or not any( + value.get(key) for key in ("docling", "docling-serve", "version") + ): + raise ValueError("missing server version") + # Docling Serve and its converter can be upgraded independently. + return json.dumps( + { + key: str(value[key]) + for key in ("docling", "docling-serve", "docling-core", "version") + if value.get(key) + }, + sort_keys=True, + ) + except (httpx.HTTPError, ValueError) as exc: + raise ParserError( + "Cannot verify Docling server version; check its /version endpoint before reusing cached parses." + ) from exc + + def verify_remote( config: DoclingConfig, timeout: float = _HEALTH_TIMEOUT_SECONDS ) -> tuple[bool, str]: @@ -99,6 +127,9 @@ def _convert_file(source_path: Path, base_url: str, config: DoclingConfig) -> st "to_formats": "md", "do_ocr": "true" if config.do_ocr else "false", "do_table_structure": "true" if config.do_table_structure else "false", + "do_formula_enrichment": "true" if config.do_formula_enrichment else "false", + "do_picture_classification": "true" if config.do_picture_classification else "false", + "do_picture_description": "true" if config.do_picture_description else "false", } with source_path.open("rb") as source: files = {"files": (source_path.name, source, "application/octet-stream")} diff --git a/requirements/modules/parser-docling.txt b/requirements/modules/parser-docling.txt index 253ba74fc..7651ec0ac 100644 --- a/requirements/modules/parser-docling.txt +++ b/requirements/modules/parser-docling.txt @@ -1,5 +1,5 @@ # Generated by scripts/sync_module_requirements.py; edit module manifests. -r ../core.txt -r parsing.txt -docling[xbrl]>=2.123.1 -docling-slim[format-iwork,format-opendocument]>=2.123.1 +docling[xbrl]>=2.148.0 +docling-slim[format-iwork,format-opendocument]>=2.148.0 diff --git a/tests/services/parsing/test_docling_content_list.py b/tests/services/parsing/test_docling_content_list.py index 652a6ddcc..4ac3c9de1 100644 --- a/tests/services/parsing/test_docling_content_list.py +++ b/tests/services/parsing/test_docling_content_list.py @@ -894,6 +894,9 @@ def test_local_signature_tracks_content_list_schema(monkeypatch: pytest.MonkeyPa assert docling_engine.CONTENT_LIST_SCHEMA_VERSION == 4 local_before = parser.signature(DoclingConfig(mode="local")).hash() + monkeypatch.setattr( + "deeptutor.services.parsing.engines.docling.remote.remote_version", lambda _: "server-test" + ) remote_config = DoclingConfig(mode="remote", api_base_url="http://host:5001") remote_before = parser.signature(remote_config).hash() diff --git a/tests/services/parsing/test_docling_local_worker.py b/tests/services/parsing/test_docling_local_worker.py index c40bb1b33..0630b3fe7 100644 --- a/tests/services/parsing/test_docling_local_worker.py +++ b/tests/services/parsing/test_docling_local_worker.py @@ -143,23 +143,11 @@ def test_missing_docling_install_propagates( local_worker._build_converter(do_ocr=False, do_table_structure=False) -def test_older_docling_without_pipeline_options_still_degrades_loudly( - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """The option modules live inside the ``try``, so older releases still convert. - - This preserves the pre-#2518 behaviour; only the silence changes. - """ - +def test_missing_pipeline_options_require_a_compatible_docling_install(monkeypatch): _install_docling_stubs(monkeypatch) monkeypatch.setitem(sys.modules, "docling.datamodel.pipeline_options", None) - - converter = local_worker._build_converter(do_ocr=False, do_table_structure=False) - - assert isinstance(converter, _StubConverter) - err = capsys.readouterr().err - assert "Docling option setup failed" in err + with pytest.raises(ImportError): + local_worker._build_converter(do_ocr=False, do_table_structure=False) def test_fallback_warning_is_a_single_line( @@ -177,3 +165,31 @@ def test_fallback_warning_is_a_single_line( err = capsys.readouterr().err assert len([line for line in err.splitlines() if line.strip()]) == 1 + + +def test_requested_enrichments_reach_the_converter(monkeypatch): + _install_docling_stubs(monkeypatch) + converter = local_worker._build_converter( + do_ocr=False, + do_table_structure=True, + do_formula_enrichment=True, + do_picture_classification=True, + do_picture_description=True, + ) + options = converter.format_options["pdf"].pipeline_options + assert ( + options.do_formula_enrichment + and options.do_picture_classification + and options.do_picture_description + ) + + +def test_enrichment_setup_failure_never_silently_changes_requested_output(monkeypatch): + def broken(): + raise ValueError("unsupported option API") + + _install_docling_stubs(monkeypatch, pipeline_options_factory=broken) + with pytest.raises(local_worker.ParserError, match="requested enrichments"): + local_worker._build_converter( + do_ocr=False, do_table_structure=True, do_formula_enrichment=True + ) diff --git a/tests/services/parsing/test_engines.py b/tests/services/parsing/test_engines.py index e79eb11b1..acaa628cc 100644 --- a/tests/services/parsing/test_engines.py +++ b/tests/services/parsing/test_engines.py @@ -275,7 +275,10 @@ 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: +def test_docling_signature_distinguishes_local_and_remote(monkeypatch) -> None: + monkeypatch.setattr( + "deeptutor.services.parsing.engines.docling.remote.remote_version", lambda _: "server-test" + ) parser = factory.get_parser("docling") from deeptutor.services.parsing.engines.docling.config import DoclingConfig @@ -290,15 +293,15 @@ def test_docling_signature_distinguishes_local_and_remote() -> None: def test_docling_advertises_complete_current_upstream_formats() -> None: from deeptutor.services.parsing.engines.docling.formats import ( - DOCLING_2_123_1_FORMATS, + DOCLING_2_148_0_FORMATS, MIN_DOCLING_VERSION, docling_supported_formats, docling_version_is_current, ) - assert MIN_DOCLING_VERSION == "2.123.1" - assert len(DOCLING_2_123_1_FORMATS) == 74 - assert DOCLING_2_123_1_FORMATS <= docling_supported_formats() + assert MIN_DOCLING_VERSION == "2.148.0" + assert len(DOCLING_2_148_0_FORMATS) == 88 + assert DOCLING_2_148_0_FORMATS <= docling_supported_formats() assert { ".pdf", ".doc", @@ -311,14 +314,14 @@ def test_docling_advertises_complete_current_upstream_formats() -> None: ".dclg.xml", ".tar.gz", } <= factory.get_parser("docling").supported_formats() - assert docling_version_is_current("2.123.1") is True - assert docling_version_is_current("2.124.0") is True + assert docling_version_is_current("2.148.0") is True + assert docling_version_is_current("2.149.0") is True assert docling_version_is_current("2.122.9") is False def test_docling_format_discovery_never_imports_the_runtime(monkeypatch) -> None: from deeptutor.services.parsing.engines.docling.formats import ( - DOCLING_2_123_1_FORMATS, + DOCLING_2_148_0_FORMATS, docling_supported_formats, ) @@ -331,7 +334,7 @@ def test_docling_format_discovery_never_imports_the_runtime(monkeypatch) -> None monkeypatch.setattr(builtins, "__import__", guarded_import) - assert docling_supported_formats() == DOCLING_2_123_1_FORMATS + assert docling_supported_formats() == DOCLING_2_148_0_FORMATS def test_docling_remote_readiness_needs_no_local_package() -> None: @@ -356,7 +359,7 @@ def test_docling_local_readiness_requires_current_package(monkeypatch) -> None: assert report.ready is False assert report.reason == "update_required" - assert "2.123.1" in report.message + assert "2.148.0" in report.message def test_docling_local_parse_runs_in_isolated_worker(tmp_path, monkeypatch) -> None: @@ -1010,8 +1013,8 @@ def test_install_manager_spec_allowlist() -> None: assert ENGINE_PIP_SPECS["pymupdf4llm"] == ["pymupdf4llm>=1.28.2"] assert ENGINE_PIP_SPECS["liteparse"] == ["liteparse>=2.14.2"] assert ENGINE_PIP_SPECS["docling"] == [ - "docling[xbrl]>=2.123.1", - "docling-slim[format-iwork,format-opendocument]>=2.123.1", + "docling[xbrl]>=2.148.0", + "docling-slim[format-iwork,format-opendocument]>=2.148.0", ] assert "text_only" not in ENGINE_PIP_SPECS assert "mineru" not in ENGINE_PIP_SPECS @@ -1180,3 +1183,39 @@ def test_docling_models_dir_honors_cache_env(monkeypatch, tmp_path) -> None: models.mkdir(parents=True) (models / "model.bin").write_bytes(b"x") assert docling_engine._docling_models_ready() is True + + +def test_docling_enrichments_and_server_build_change_the_cache_key(monkeypatch): + from deeptutor.services.parsing.engines.docling import remote + from deeptutor.services.parsing.engines.docling.config import DoclingConfig + from deeptutor.services.parsing.engines.docling.engine import DoclingParser + + parser = DoclingParser() + base = parser.signature(DoclingConfig()).hash() + for key in ("do_formula_enrichment", "do_picture_classification", "do_picture_description"): + assert parser.signature(DoclingConfig(**{key: True})).hash() != base + monkeypatch.setattr(remote, "remote_version", lambda _: "server-A") + before = parser.signature(DoclingConfig(mode="remote")).hash() + monkeypatch.setattr(remote, "remote_version", lambda _: "server-B") + assert parser.signature(DoclingConfig(mode="remote")).hash() != before + + +def test_docling_remote_version_uses_both_components_and_auth(monkeypatch): + from deeptutor.services.parsing.engines.docling import remote + from deeptutor.services.parsing.engines.docling.config import DoclingConfig + + original = httpx.Client + requests = [] + + def handler(request): + requests.append(request) + return httpx.Response(200, json={"docling-serve": "1.0", "docling": "2.148.0"}) + + monkeypatch.setattr( + remote.httpx, + "Client", + lambda **kwargs: original(transport=httpx.MockTransport(handler), **kwargs), + ) + value = remote.remote_version(DoclingConfig(mode="remote", api_token="synthetic-key")) + assert "2.148.0" in value and "1.0" in value + assert requests[0].headers["X-Api-Key"] == "synthetic-key" diff --git a/tests/test_packaging_metadata.py b/tests/test_packaging_metadata.py index 75e0dc1a5..5e882e1ea 100644 --- a/tests/test_packaging_metadata.py +++ b/tests/test_packaging_metadata.py @@ -76,8 +76,8 @@ def test_docling_parser_avoids_source_only_build_dependencies(): ("parser-markitdown", "markitdown[all]>=0.1.7"), ("parser-pymupdf4llm", "pymupdf4llm>=1.28.2"), ("parser-liteparse", "liteparse>=2.14.2"), - ("parser-docling", "docling[xbrl]>=2.123.1"), - ("parser-docling", "docling-slim[format-iwork,format-opendocument]>=2.123.1"), + ("parser-docling", "docling[xbrl]>=2.148.0"), + ("parser-docling", "docling-slim[format-iwork,format-opendocument]>=2.148.0"), ], ) def test_dependency_floor_belongs_to_its_module(module, requirement): diff --git a/web/features/settings/sections/DocumentParsingSettingsSection.tsx b/web/features/settings/sections/DocumentParsingSettingsSection.tsx index 23e7775ff..97a77fd50 100644 --- a/web/features/settings/sections/DocumentParsingSettingsSection.tsx +++ b/web/features/settings/sections/DocumentParsingSettingsSection.tsx @@ -452,7 +452,7 @@ function DoclingPanel({ description={ isRemote ? t( - "Documents are sent to a Docling Serve server for conversion.", + "Docling Serve returns Markdown only here. Use local Docling for structured table, equation and image blocks.", ) : t( "Parsing runs on this machine using the installed docling package.", @@ -661,6 +661,15 @@ function DoclingPanel({ /> )} + + {([ + ["do_formula_enrichment", "Recognize formulas"], + ["do_picture_classification", "Classify pictures"], + ["do_picture_description", "Describe pictures with Docling"], + ] as const).map(([key, label]) => ( + onSave({ [key]: value })} />} /> + ))} + ); }