Coverage for app / util / docling_client.py: 95%

39 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Minimal docling-serve client for svc-ai. 

3 

4svc-core owns ingestion (parse → chunk → embed → index). svc-ai only needs 

5to *read* a document that is not in the vector index yet — uploaded moments 

6ago, or whose indexing failed — so this client converts bytes to text and 

7nothing more. Plain-text formats are decoded locally; everything else is 

8sent to docling-serve (same service svc-core uses). 

9""" 

10 

11from __future__ import annotations 

12 

13import logging 

14from typing import Any 

15 

16import httpx 

17 

18from app.common.settings import get_settings 

19 

20logger = logging.getLogger(__name__) 

21 

22_PLAIN_TEXT_MIMES = frozenset( 

23 { 

24 "text/plain", 

25 "text/csv", 

26 "text/markdown", 

27 "text/x-markdown", 

28 "text/html", 

29 "text/xml", 

30 "text/x-rst", 

31 "application/json", 

32 "application/xml", 

33 "application/x-yaml", 

34 "application/yaml", 

35 } 

36) 

37 

38 

39#: docling-serve's synchronous conversion of one uploaded file (its v1 API). 

40#: It answers ``{"document": {"md_content", …}, "status", "errors", …}`` — 

41#: the content is under ``document``, never at the top. 

42CONVERT_PATH = "/v1/convert/file" 

43#: Markdown, with pictures as a placeholder: by default each is embedded as 

44#: base64, which would reach the model as text. 

45CONVERT_OPTIONS: dict[str, str | list[str]] = { 

46 "to_formats": ["md"], 

47 "image_export_mode": "placeholder", 

48} 

49#: The statuses docling-serve answers a conversion that produced nothing with. 

50_NOT_CONVERTED = frozenset({"failure", "skipped"}) 

51 

52 

53def _extract_text(data: dict[str, Any]) -> str: 

54 """The markdown (or text) of docling-serve's answer to one file; "" when 

55 it converted nothing.""" 

56 document = data.get("document") 

57 if not isinstance(document, dict): 

58 return "" 

59 if str(data.get("status") or "").lower() in _NOT_CONVERTED: 

60 return "" 

61 for key in ("md_content", "text_content"): 

62 value = document.get(key) 

63 if isinstance(value, str) and value.strip(): 

64 return value.strip() 

65 return "" 

66 

67 

68async def document_to_text(content: bytes, filename: str, mime_type: str) -> str: 

69 """Best-effort text of *content*; "" when nothing could be extracted.""" 

70 if mime_type in _PLAIN_TEXT_MIMES or mime_type.startswith("text/"): 

71 return content.decode("utf-8", errors="replace").strip() 

72 

73 url = get_settings().docling_url.rstrip("/") 

74 try: 

75 async with httpx.AsyncClient(timeout=120.0) as client: 

76 resp = await client.post( 

77 f"{url}{CONVERT_PATH}", 

78 files={"files": (filename, content, mime_type)}, 

79 data=CONVERT_OPTIONS, 

80 ) 

81 resp.raise_for_status() 

82 data = resp.json() 

83 if not isinstance(data, dict): 

84 raise ValueError("docling answered something other than an object") 

85 except Exception as exc: # noqa: BLE001 — reading is best-effort 

86 logger.warning("docling conversion failed for %s: %s", filename, exc) 

87 return "" 

88 text = _extract_text(data) 

89 if not text: 

90 logger.warning( 

91 "docling converted nothing from %s (status=%s, %d error(s))", 

92 filename, 

93 data.get("status") or "missing", 

94 len(data.get("errors") or []), 

95 ) 

96 return text