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

212 statements  

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

1""" 

2Docling document parsing client. 

3 

4Sends documents to the docling-serve HTTP API for parsing, then returns 

5text chunks enriched with page-level provenance metadata. 

6 

7For plain-text file types (txt, md, csv, json, yaml, xml, html, rst) the 

8document is chunked locally without a network round-trip. 

9 

10Chunking uses tiktoken (cl100k_base, the encoding for text-embedding-3-small) 

11so chunk boundaries align with the token budget of the embedding model. 

12Target: 512 tokens per chunk, 64-token overlap. 

13""" 

14 

15import logging 

16import os 

17from dataclasses import dataclass, field 

18 

19import httpx 

20import tiktoken 

21 

22logger = logging.getLogger(__name__) 

23 

24DOCLING_URL = os.environ.get("DOCLING_URL", "http://docling:5001") 

25 

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

27#: It answers ``{"document": {"json_content", "md_content", …}, "status", 

28#: "errors", …}`` — the content is under ``document``, never at the top. 

29CONVERT_PATH = "/v1/convert/file" 

30#: What is asked for, as repeated form fields: the DoclingDocument (its texts 

31#: carry their pages) and markdown as the fallback. Pictures become a 

32#: placeholder; by default each is embedded as base64 in the markdown, which 

33#: would be chunked and embedded as text. 

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

35 "to_formats": ["json", "md"], 

36 "image_export_mode": "placeholder", 

37} 

38#: How long one conversion may take. A long PDF on a CPU host takes minutes; 

39#: docling-serve's own wait matches it (``DOCLING_SERVE_MAX_SYNC_WAIT`` in 

40#: docker-compose.yml), or it gives up at its default of 120 s. 

41DOCLING_TIMEOUT_S = 300.0 

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

43#: (the others are ``success`` and ``partial_success``). 

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

45 

46# Token-aware chunk tuning — matches the embedding model's token space. 

47# text-embedding-3-small supports up to 8,191 tokens; 512 is a practical 

48# retrieval sweet spot (granular enough for precision, large enough for context). 

49CHUNK_SIZE_TOKENS = 512 

50CHUNK_OVERLAP_TOKENS = 64 

51 

52_tokenizer = tiktoken.get_encoding("cl100k_base") 

53 

54# MIME types that can be split locally (no need for docling) 

55_PLAIN_TEXT_MIMES = { 

56 "text/plain", 

57 "text/csv", 

58 "text/markdown", 

59 "text/x-markdown", 

60 "text/html", 

61 "text/xml", 

62 "text/x-rst", 

63 "application/json", 

64 "application/xml", 

65 "application/x-yaml", 

66 "application/yaml", 

67} 

68 

69 

70#: Extensions whose content is text, chunked locally whatever MIME type the 

71#: browser (or a server) labelled it with. 

72TEXT_EXTENSIONS = frozenset( 

73 {".txt", ".md", ".csv", ".json", ".xml", ".html", ".htm", ".rst", ".yaml", ".yml"} 

74) 

75 

76#: What a document docling cannot read is recorded with — never the 

77#: exception's text. 

78UNREADABLE_MESSAGE = ( 

79 "The document could not be read: the document parser is unavailable or " 

80 "could not convert it. Try reindexing it later." 

81) 

82 

83 

84class DocumentUnreadable(RuntimeError): 

85 """A binary document docling could not convert. Its bytes are not text, 

86 so splitting them as text — what the fallback used to do — indexed a PDF 

87 as junk and marked it indexed.""" 

88 

89 

90def looks_textual(content: bytes, filename: str = "") -> bool: 

91 """Whether ``content`` is text: a text extension, or a head with no NUL 

92 bytes that decodes as UTF-8 (a multi-byte character cut at the end of the 

93 sample is allowed).""" 

94 _, dot, ext = (filename or "").lower().rpartition(".") 

95 if dot and f".{ext}" in TEXT_EXTENSIONS: 

96 return True 

97 head = content[:8192] 

98 if b"\x00" in head: 

99 return False 

100 try: 

101 head.decode("utf-8") 

102 except UnicodeDecodeError as exc: 

103 return exc.start >= len(head) - 3 

104 return True 

105 

106 

107@dataclass 

108class DocChunk: 

109 text: str 

110 page_number: int | None 

111 chunk_index: int 

112 extra: dict = field(default_factory=dict) 

113 

114 

115# ─── Token-aware splitter ────────────────────────────────────────────────────── 

116 

117 

118def _split_tokens(text: str) -> list[str]: 

119 """Split *text* into token-bounded pieces with overlap.""" 

120 text = text.strip() 

121 if not text: 

122 return [] 

123 ids = _tokenizer.encode(text) 

124 if len(ids) <= CHUNK_SIZE_TOKENS: 

125 return [text] 

126 parts: list[str] = [] 

127 start = 0 

128 while start < len(ids): 

129 end = min(start + CHUNK_SIZE_TOKENS, len(ids)) 

130 parts.append(_tokenizer.decode(ids[start:end])) 

131 start += CHUNK_SIZE_TOKENS - CHUNK_OVERLAP_TOKENS 

132 return parts 

133 

134 

135def _chunks_from_text( 

136 text: str, page_number: int | None, base_index: int 

137) -> list[DocChunk]: 

138 return [ 

139 DocChunk(text=part, page_number=page_number, chunk_index=base_index + i) 

140 for i, part in enumerate(_split_tokens(text)) 

141 ] 

142 

143 

144def chunk_markdown(markdown: str) -> list[DocChunk]: 

145 """Chunk already-extracted text — a website page's markdown — without a 

146 round trip to docling-serve, which has nothing left to parse.""" 

147 return _plain_text_chunks(markdown.encode("utf-8"), "text/markdown") 

148 

149 

150def _plain_text_chunks(content: bytes, mime_type: str) -> list[DocChunk]: 

151 """Chunk plain-text content locally, respecting paragraph boundaries.""" 

152 try: 

153 text = content.decode("utf-8", errors="replace") 

154 except Exception: 

155 text = content.decode("latin-1", errors="replace") 

156 # Accumulate paragraphs into token-bounded chunks preserving semantic units. 

157 paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()] 

158 chunks: list[DocChunk] = [] 

159 current = "" 

160 for para in paragraphs: 

161 candidate = (current + "\n\n" + para).lstrip() if current else para 

162 if len(_tokenizer.encode(candidate)) > CHUNK_SIZE_TOKENS and current: 

163 chunks.extend(_chunks_from_text(current, None, len(chunks))) 

164 # Carry overlap: last CHUNK_OVERLAP_TOKENS tokens of current chunk 

165 overlap_ids = _tokenizer.encode(current)[-CHUNK_OVERLAP_TOKENS:] 

166 current = _tokenizer.decode(overlap_ids) + "\n\n" + para 

167 else: 

168 current = candidate 

169 if current.strip(): 

170 chunks.extend(_chunks_from_text(current, None, len(chunks))) 

171 return chunks 

172 

173 

174# ─── Docling JSON parsers ───────────────────────────────────────────────────── 

175 

176 

177#: The DoclingDocument (v2) collections a body's ``$ref`` can name. 

178_BODY_COLLECTIONS = ("texts", "tables", "groups") 

179 

180 

181def _in_reading_order(json_doc: dict) -> list[dict]: 

182 """A DoclingDocument v2's items as its body orders them — each text, and 

183 each table as a ``{"text", "prov"}`` of its rows — through groups (a 

184 list, a section) to any depth. 

185 

186 ``texts`` alone holds no table: a table is under ``tables``, named by the 

187 body where it stands, so reading ``texts`` indexed none of a policy's 

188 figures. Page headers and footers are not in the body (``furniture``), 

189 so they stay out too.""" 

190 collections = {name: json_doc.get(name) or [] for name in _BODY_COLLECTIONS} 

191 items: list[dict] = [] 

192 seen: set[str] = set() 

193 

194 def visit(node: dict) -> None: 

195 for child in node.get("children") or []: 

196 ref = str((child or {}).get("$ref") or "") 

197 kind, _, index = ref.removeprefix("#/").partition("/") 

198 if ref in seen or kind not in collections or not index.isdigit(): 

199 continue 

200 seen.add(ref) 

201 if int(index) >= len(collections[kind]): 

202 continue 

203 item = collections[kind][int(index)] 

204 if kind == "texts": 

205 items.append(item) 

206 elif kind == "tables": 

207 items.append({"text": _table_text(item), "prov": item.get("prov")}) 

208 visit(item) 

209 

210 visit(json_doc.get("body") or {}) 

211 return items 

212 

213 

214def _table_text(table: dict) -> str: 

215 """A table's rows, one a line, its cells ``|``-separated.""" 

216 rows = ( 

217 " | ".join(str(cell.get("text") or "").strip() for cell in row) 

218 for row in (table.get("data") or {}).get("grid") or [] 

219 ) 

220 return "\n".join(row for row in rows if row.strip(" |")) 

221 

222 

223def _chunks_from_docling_json(json_doc: dict) -> list[DocChunk]: 

224 """ 

225 Extract ordered text chunks from a DoclingDocument JSON payload. 

226 

227 Handles both docling v1 (texts as dict keyed by numeric string) and 

228 docling v2 (texts as list). Falls back to an empty list on parse 

229 errors so the caller can fall back to markdown. 

230 """ 

231 chunks: list[DocChunk] = [] 

232 

233 try: 

234 raw_texts = json_doc.get("texts", {}) 

235 

236 # v2: the body's items in reading order, tables included; the bare 

237 # texts list when the body names none 

238 if isinstance(raw_texts, list): 

239 text_items = _in_reading_order(json_doc) or raw_texts 

240 else: 

241 # v1: dict keyed by ref index; restore reading order via body refs 

242 body = json_doc.get("body", {}) 

243 ordered_refs: list[str] = [] 

244 for child in body.get("children", []): 

245 ref = child.get("$ref", "") 

246 if "/texts/" in ref: 

247 ordered_refs.append(ref.split("/texts/")[-1]) 

248 

249 if ordered_refs: 

250 text_items = [raw_texts[r] for r in ordered_refs if r in raw_texts] 

251 else: 

252 text_items = list(raw_texts.values()) 

253 

254 # Accumulate items into token-bounded chunks 

255 current_text = "" 

256 current_page: int | None = None 

257 

258 for item in text_items: 

259 text = (item.get("text") or "").strip() 

260 if not text: 

261 continue 

262 

263 prov = item.get("prov") or [] 

264 page_no: int | None = prov[0].get("page_no") if prov else None 

265 

266 candidate = (current_text + "\n" + text).lstrip() if current_text else text 

267 if current_text and len(_tokenizer.encode(candidate)) > CHUNK_SIZE_TOKENS: 

268 chunks.extend( 

269 _chunks_from_text(current_text, current_page, len(chunks)) 

270 ) 

271 overlap_ids = _tokenizer.encode(current_text)[-CHUNK_OVERLAP_TOKENS:] 

272 current_text = _tokenizer.decode(overlap_ids) + "\n" + text 

273 current_page = page_no if page_no is not None else current_page 

274 else: 

275 if not current_text: 

276 current_page = page_no 

277 current_text = candidate 

278 

279 if current_text.strip(): 

280 chunks.extend(_chunks_from_text(current_text, current_page, len(chunks))) 

281 

282 except Exception as exc: 

283 logger.warning("Failed to parse docling JSON structure: %s", exc) 

284 return [] 

285 

286 return chunks 

287 

288 

289def _chunks_from_markdown(md: str) -> list[DocChunk]: 

290 """Chunk a markdown string by paragraph boundaries (no page numbers).""" 

291 paragraphs = [p.strip() for p in md.split("\n\n") if p.strip()] 

292 chunks: list[DocChunk] = [] 

293 current = "" 

294 for para in paragraphs: 

295 candidate = (current + "\n\n" + para).lstrip() if current else para 

296 if current and len(_tokenizer.encode(candidate)) > CHUNK_SIZE_TOKENS: 

297 chunks.extend(_chunks_from_text(current, None, len(chunks))) 

298 overlap_ids = _tokenizer.encode(current)[-CHUNK_OVERLAP_TOKENS:] 

299 current = _tokenizer.decode(overlap_ids) + "\n\n" + para 

300 else: 

301 current = candidate 

302 if current.strip(): 

303 chunks.extend(_chunks_from_text(current, None, len(chunks))) 

304 return chunks 

305 

306 

307def _docling_errors(data: dict) -> str: 

308 """docling-serve's ``errors``, as ``component/module: message`` — what it 

309 says went wrong, for the log.""" 

310 described = [] 

311 for error in data.get("errors") or []: 

312 if not isinstance(error, dict): 

313 continue 

314 where = "/".join( 

315 str(error[k]) for k in ("component_type", "module_name") if error.get(k) 

316 ) 

317 message = str(error.get("error_message") or "")[:200] 

318 described.append(f"{where}: {message}" if where else message) 

319 return "; ".join(described) or "none given" 

320 

321 

322def _parse_docling_response( 

323 data: dict, fallback_content: bytes, fallback_mime: str, filename: str = "" 

324) -> list[DocChunk]: 

325 """ 

326 Chunks from docling-serve's answer to one file (``CONVERT_PATH``). 

327 

328 Tries the DoclingDocument first (page numbers available), then markdown, 

329 then its text, then — only for content that is text — a plain-text split. 

330 A binary document with nothing usable yields no chunks, which the caller 

331 records. 

332 """ 

333 status = str(data.get("status") or "").lower() 

334 document = data.get("document") 

335 if not isinstance(document, dict) or status in _NOT_CONVERTED: 

336 logger.warning( 

337 "docling did not convert a %s document (status=%s, errors: %s)", 

338 _extension(filename) or fallback_mime, 

339 status or "missing", 

340 _docling_errors(data), 

341 ) 

342 document = {} 

343 

344 json_doc = document.get("json_content") 

345 if json_doc and isinstance(json_doc, dict): 

346 chunks = _chunks_from_docling_json(json_doc) 

347 if chunks: 

348 return chunks 

349 

350 md = document.get("md_content") 

351 if md and isinstance(md, str): 

352 chunks = _chunks_from_markdown(md) 

353 if chunks: 

354 return chunks 

355 

356 txt = document.get("text_content") 

357 if txt and isinstance(txt, str): 

358 chunks = _chunks_from_text(txt.strip(), None, 0) 

359 if chunks: 

360 return chunks 

361 

362 if not looks_textual(fallback_content, filename): 

363 logger.warning("docling response contained no usable content") 

364 return [] 

365 logger.warning( 

366 "docling response contained no usable content; falling back to plain-text" 

367 ) 

368 return _plain_text_chunks(fallback_content, fallback_mime) 

369 

370 

371def _extension(filename: str) -> str: 

372 _, dot, ext = (filename or "").lower().rpartition(".") 

373 return f".{ext}" if dot and ext else "" 

374 

375 

376def _named_for_docling(filename: str, mime_type: str) -> str: 

377 """``filename`` with the extension of its type when it has none. 

378 

379 A document imported from a link is named by the URL's last segment — 

380 often ``download`` or ``view`` — and docling-serve reads a file's format 

381 from its name as well as its bytes.""" 

382 if _extension(filename): 

383 return filename 

384 from app.services.knowledge.file_types import extension_for 

385 

386 ext = extension_for(mime_type) or "" 

387 return f"{filename or 'document'}{ext}" 

388 

389 

390# ─── Public API ─────────────────────────────────────────────────────────────── 

391 

392 

393async def parse_document( 

394 content: bytes, filename: str, mime_type: str 

395) -> list[DocChunk]: 

396 """ 

397 Parse *content* into text chunks enriched with page metadata. 

398 

399 Plain-text types are chunked locally, as is text labelled as something 

400 else (``application/octet-stream``). Every other type is sent to 

401 docling-serve; when that fails, text still falls back to a plain-text 

402 split, and a binary document raises :class:`DocumentUnreadable`. 

403 """ 

404 if ( 

405 mime_type in _PLAIN_TEXT_MIMES 

406 or mime_type.startswith("text/") 

407 or ( 

408 mime_type == "application/octet-stream" and looks_textual(content, filename) 

409 ) 

410 ): 

411 return _plain_text_chunks(content, mime_type) 

412 

413 try: 

414 async with httpx.AsyncClient(timeout=DOCLING_TIMEOUT_S) as client: 

415 resp = await client.post( 

416 f"{DOCLING_URL}{CONVERT_PATH}", 

417 files={ 

418 "files": ( 

419 _named_for_docling(filename, mime_type), 

420 content, 

421 mime_type, 

422 ) 

423 }, 

424 data=CONVERT_OPTIONS, 

425 ) 

426 resp.raise_for_status() 

427 data = resp.json() 

428 if not isinstance(data, dict): 

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

430 except Exception as exc: 

431 status = getattr(getattr(exc, "response", None), "status_code", None) 

432 failure = f"{type(exc).__name__}{f' {status}' if status else ''}" 

433 if not looks_textual(content, filename): 

434 logger.warning( 

435 "docling request failed for a %s document (%s)", 

436 _extension(filename) or mime_type, 

437 failure, 

438 ) 

439 raise DocumentUnreadable(UNREADABLE_MESSAGE) from exc 

440 logger.warning( 

441 "docling request failed (%s) — using plain-text fallback", failure 

442 ) 

443 return _plain_text_chunks(content, mime_type) 

444 

445 return _parse_docling_response(data, content, mime_type, filename)