bettersight-statement-extra.../backend/repositories/docling_repository.py

44 lines
1.9 KiB
Python

# All data access to the self-hosted Docling service - the one real
# external-API boundary this app has. No business logic here: this
# function only builds and sends the request and returns Docling's raw
# response; parsing/interpreting that response is
# services/extraction/docling_parser.py's job, not this file's.
import mimetypes
import requests
CONVERT_TIMEOUT = 300
def convert(file_path, docling_url):
"""
POST a file to Docling's /v1/convert/file, requesting both Markdown and
structured JSON. do_table_structure is left at Docling's own default
(true) - confirmed via its /openapi.json schema. The content-type is
guessed from the file's own extension rather than hardcoded to
"application/pdf" - this also handles raw image uploads (a scanned/
photographed statement with no PDF container at all) via Docling's own
OCR, confirmed for real to work when sent with its correct image/*
content-type.
Data flow:
file_path (str) - local path to the PDF or image to convert
docling_url (str) - base URL of the self-hosted Docling container
returns (dict) - Docling's raw response: {"document":
{"md_content", "json_content", ...}, "status",
"errors", "confidence", ...}
Raises on a non-2xx response or network/timeout error - callers decide
how to surface that (this module doesn't know about Flask error
responses).
"""
content_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"
with open(file_path, "rb") as f:
response = requests.post(
f"{docling_url}/v1/convert/file",
files={"files": (file_path.split("/")[-1], f, content_type)},
data={"to_formats": ["md", "json"]},
timeout=CONVERT_TIMEOUT,
)
response.raise_for_status()
return response.json()