pgx-docling-parser-serve 0.0.0.dev0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of pgx-docling-parser-serve might be problematic. Click here for more details.
- pgx_docling_parser_serve-0.0.0.dev0/.gitignore +218 -0
- pgx_docling_parser_serve-0.0.0.dev0/PKG-INFO +45 -0
- pgx_docling_parser_serve-0.0.0.dev0/README.md +33 -0
- pgx_docling_parser_serve-0.0.0.dev0/pyproject.toml +37 -0
- pgx_docling_parser_serve-0.0.0.dev0/src/docling_serve/__init__.py +9 -0
- pgx_docling_parser_serve-0.0.0.dev0/src/docling_serve/serve.py +219 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
.hypothesis/
|
|
51
|
+
.pytest_cache/
|
|
52
|
+
cover/
|
|
53
|
+
|
|
54
|
+
# Translations
|
|
55
|
+
*.mo
|
|
56
|
+
*.pot
|
|
57
|
+
|
|
58
|
+
# Django stuff:
|
|
59
|
+
*.log
|
|
60
|
+
local_settings.py
|
|
61
|
+
db.sqlite3
|
|
62
|
+
db.sqlite3-journal
|
|
63
|
+
|
|
64
|
+
# Flask stuff:
|
|
65
|
+
instance/
|
|
66
|
+
.webassets-cache
|
|
67
|
+
|
|
68
|
+
# Scrapy stuff:
|
|
69
|
+
.scrapy
|
|
70
|
+
|
|
71
|
+
# Sphinx documentation
|
|
72
|
+
docs/_build/
|
|
73
|
+
|
|
74
|
+
# PyBuilder
|
|
75
|
+
.pybuilder/
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
87
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
88
|
+
# .python-version
|
|
89
|
+
|
|
90
|
+
# pipenv
|
|
91
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
92
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
93
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
94
|
+
# install all needed dependencies.
|
|
95
|
+
# Pipfile.lock
|
|
96
|
+
|
|
97
|
+
# UV
|
|
98
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
99
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
100
|
+
# commonly ignored for libraries.
|
|
101
|
+
# uv.lock
|
|
102
|
+
|
|
103
|
+
# poetry
|
|
104
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
105
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
106
|
+
# commonly ignored for libraries.
|
|
107
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
108
|
+
# poetry.lock
|
|
109
|
+
# poetry.toml
|
|
110
|
+
|
|
111
|
+
# pdm
|
|
112
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
113
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
114
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
115
|
+
# pdm.lock
|
|
116
|
+
# pdm.toml
|
|
117
|
+
.pdm-python
|
|
118
|
+
.pdm-build/
|
|
119
|
+
|
|
120
|
+
# pixi
|
|
121
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
122
|
+
# pixi.lock
|
|
123
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
124
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
125
|
+
.pixi
|
|
126
|
+
|
|
127
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
128
|
+
__pypackages__/
|
|
129
|
+
|
|
130
|
+
# Celery stuff
|
|
131
|
+
celerybeat-schedule
|
|
132
|
+
celerybeat.pid
|
|
133
|
+
|
|
134
|
+
# Redis
|
|
135
|
+
*.rdb
|
|
136
|
+
*.aof
|
|
137
|
+
*.pid
|
|
138
|
+
|
|
139
|
+
# RabbitMQ
|
|
140
|
+
mnesia/
|
|
141
|
+
rabbitmq/
|
|
142
|
+
rabbitmq-data/
|
|
143
|
+
|
|
144
|
+
# ActiveMQ
|
|
145
|
+
activemq-data/
|
|
146
|
+
|
|
147
|
+
# SageMath parsed files
|
|
148
|
+
*.sage.py
|
|
149
|
+
|
|
150
|
+
# Environments
|
|
151
|
+
.env
|
|
152
|
+
.envrc
|
|
153
|
+
.venv
|
|
154
|
+
env/
|
|
155
|
+
venv/
|
|
156
|
+
ENV/
|
|
157
|
+
env.bak/
|
|
158
|
+
venv.bak/
|
|
159
|
+
|
|
160
|
+
# Spyder project settings
|
|
161
|
+
.spyderproject
|
|
162
|
+
.spyproject
|
|
163
|
+
|
|
164
|
+
# Rope project settings
|
|
165
|
+
.ropeproject
|
|
166
|
+
|
|
167
|
+
# mkdocs documentation
|
|
168
|
+
/site
|
|
169
|
+
|
|
170
|
+
# mypy
|
|
171
|
+
.mypy_cache/
|
|
172
|
+
.dmypy.json
|
|
173
|
+
dmypy.json
|
|
174
|
+
|
|
175
|
+
# Pyre type checker
|
|
176
|
+
.pyre/
|
|
177
|
+
|
|
178
|
+
# pytype static type analyzer
|
|
179
|
+
.pytype/
|
|
180
|
+
|
|
181
|
+
# Cython debug symbols
|
|
182
|
+
cython_debug/
|
|
183
|
+
|
|
184
|
+
# PyCharm
|
|
185
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
186
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
187
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
188
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
189
|
+
# .idea/
|
|
190
|
+
|
|
191
|
+
# Abstra
|
|
192
|
+
# Abstra is an AI-powered process automation framework.
|
|
193
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
194
|
+
# Learn more at https://abstra.io/docs
|
|
195
|
+
.abstra/
|
|
196
|
+
|
|
197
|
+
# Visual Studio Code
|
|
198
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
199
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
200
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
201
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
202
|
+
# .vscode/
|
|
203
|
+
# Temporary file for partial code execution
|
|
204
|
+
tempCodeRunnerFile.py
|
|
205
|
+
|
|
206
|
+
# Ruff stuff:
|
|
207
|
+
.ruff_cache/
|
|
208
|
+
|
|
209
|
+
# PyPI configuration file
|
|
210
|
+
.pypirc
|
|
211
|
+
|
|
212
|
+
# Marimo
|
|
213
|
+
marimo/_static/
|
|
214
|
+
marimo/_lsp/
|
|
215
|
+
__marimo__/
|
|
216
|
+
|
|
217
|
+
# Streamlit
|
|
218
|
+
.streamlit/secrets.toml
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pgx-docling-parser-serve
|
|
3
|
+
Version: 0.0.0.dev0
|
|
4
|
+
Summary: Docling-serve remote converter for pgx-docling-parser
|
|
5
|
+
Author: T-Eberle
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Requires-Python: <3.14,>=3.10
|
|
8
|
+
Requires-Dist: httpx>=0.27.0
|
|
9
|
+
Requires-Dist: pgx-docling-parser-core
|
|
10
|
+
Requires-Dist: tenacity>=8.2.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# pgx-docling-parser-serve
|
|
14
|
+
|
|
15
|
+
Remote converter for pgx-docling-parser using docling-serve API.
|
|
16
|
+
|
|
17
|
+
This package provides a remote document converter that uses the docling-serve API for document processing.
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
This package is automatically installed when you install the main package with the `docling-serve` extra:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install pgx-docling-parser[docling-serve]
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Configuration
|
|
28
|
+
|
|
29
|
+
Configure the converter using environment variables:
|
|
30
|
+
|
|
31
|
+
- `PAPERLESS_DOCLING_SERVE_URL`: URL of the docling-serve instance (default: `http://docling-serve:5000`)
|
|
32
|
+
- `PAPERLESS_DOCLING_SERVE_TIMEOUT`: Request timeout in seconds (default: `300.0`)
|
|
33
|
+
- `PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS`: Maximum number of polling attempts (default: `60`)
|
|
34
|
+
- `PAPERLESS_DOCLING_POLL_INTERVAL`: Polling interval in seconds (default: `5.0`)
|
|
35
|
+
- `PAPERLESS_DOCLING_PDF_CONVERSION_MODE`: Conversion mode - `easyocr`, `tesseract`, or `granite_docling` (default: `easyocr`)
|
|
36
|
+
|
|
37
|
+
## How It Works
|
|
38
|
+
|
|
39
|
+
The converter uses a simple 3-step workflow:
|
|
40
|
+
|
|
41
|
+
1. **Create Task**: POST to `/v1/convert/file/async` to create an async conversion task
|
|
42
|
+
2. **Poll Status**: Repeatedly GET `/v1/status/poll/{task_id}` until task completes (success/failure)
|
|
43
|
+
3. **Fetch Result**: GET `/v1/result/{task_id}` to retrieve the converted document
|
|
44
|
+
|
|
45
|
+
The polling mechanism will retry up to `PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS` times with `PAPERLESS_DOCLING_POLL_INTERVAL` seconds between attempts.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# pgx-docling-parser-serve
|
|
2
|
+
|
|
3
|
+
Remote converter for pgx-docling-parser using docling-serve API.
|
|
4
|
+
|
|
5
|
+
This package provides a remote document converter that uses the docling-serve API for document processing.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
This package is automatically installed when you install the main package with the `docling-serve` extra:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install pgx-docling-parser[docling-serve]
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Configuration
|
|
16
|
+
|
|
17
|
+
Configure the converter using environment variables:
|
|
18
|
+
|
|
19
|
+
- `PAPERLESS_DOCLING_SERVE_URL`: URL of the docling-serve instance (default: `http://docling-serve:5000`)
|
|
20
|
+
- `PAPERLESS_DOCLING_SERVE_TIMEOUT`: Request timeout in seconds (default: `300.0`)
|
|
21
|
+
- `PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS`: Maximum number of polling attempts (default: `60`)
|
|
22
|
+
- `PAPERLESS_DOCLING_POLL_INTERVAL`: Polling interval in seconds (default: `5.0`)
|
|
23
|
+
- `PAPERLESS_DOCLING_PDF_CONVERSION_MODE`: Conversion mode - `easyocr`, `tesseract`, or `granite_docling` (default: `easyocr`)
|
|
24
|
+
|
|
25
|
+
## How It Works
|
|
26
|
+
|
|
27
|
+
The converter uses a simple 3-step workflow:
|
|
28
|
+
|
|
29
|
+
1. **Create Task**: POST to `/v1/convert/file/async` to create an async conversion task
|
|
30
|
+
2. **Poll Status**: Repeatedly GET `/v1/status/poll/{task_id}` until task completes (success/failure)
|
|
31
|
+
3. **Fetch Result**: GET `/v1/result/{task_id}` to retrieve the converted document
|
|
32
|
+
|
|
33
|
+
The polling mechanism will retry up to `PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS` times with `PAPERLESS_DOCLING_POLL_INTERVAL` seconds between attempts.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24", "hatch-vcs>=0.3.0"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[tool.hatch.version]
|
|
6
|
+
source = "vcs"
|
|
7
|
+
root = "../.."
|
|
8
|
+
fallback-version = "0.0.0.dev0"
|
|
9
|
+
|
|
10
|
+
[project]
|
|
11
|
+
name = "pgx-docling-parser-serve"
|
|
12
|
+
dynamic = ["version"]
|
|
13
|
+
description = "Docling-serve remote converter for pgx-docling-parser"
|
|
14
|
+
readme = "README.md"
|
|
15
|
+
requires-python = ">=3.10,<3.14"
|
|
16
|
+
license = "MIT"
|
|
17
|
+
authors = [
|
|
18
|
+
{ name = "T-Eberle" },
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
# Dependencies specific to docling_serve (remote API client)
|
|
22
|
+
dependencies = [
|
|
23
|
+
"pgx-docling-parser-core",
|
|
24
|
+
"httpx>=0.27.0",
|
|
25
|
+
"tenacity>=8.2.0",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[tool.uv.sources]
|
|
29
|
+
pgx-docling-parser-core = { path = "../core", editable = true }
|
|
30
|
+
|
|
31
|
+
[tool.hatch.build.targets.wheel]
|
|
32
|
+
packages = ["src/docling_serve"]
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.sdist]
|
|
35
|
+
include = [
|
|
36
|
+
"src/",
|
|
37
|
+
]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
# Read version from VERSION file at repository root
|
|
6
|
+
_version_file = Path(__file__).parent.parent.parent.parent.parent / "VERSION"
|
|
7
|
+
__version__ = _version_file.read_text().strip() if _version_file.exists() else "0.0.0"
|
|
8
|
+
|
|
9
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import asyncio
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict, Any
|
|
6
|
+
import httpx
|
|
7
|
+
from docling_core.types.doc.document import DoclingDocument
|
|
8
|
+
|
|
9
|
+
from core import BaseDoclingConverter, get_pdf_conversion_mode
|
|
10
|
+
|
|
11
|
+
# Configure logging
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
# Reduce httpx logging verbosity
|
|
15
|
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
|
16
|
+
|
|
17
|
+
# Try to import ParseError from paperless-ngx, otherwise define our own
|
|
18
|
+
try:
|
|
19
|
+
from documents.parsers import ParseError
|
|
20
|
+
except ImportError:
|
|
21
|
+
class ParseError(Exception):
|
|
22
|
+
"""Exception raised when document parsing fails."""
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# Environment variable names
|
|
27
|
+
PAPERLESS_DOCLING_SERVE_URL = "PAPERLESS_DOCLING_SERVE_URL"
|
|
28
|
+
PAPERLESS_DOCLING_SERVE_TIMEOUT = "PAPERLESS_DOCLING_SERVE_TIMEOUT"
|
|
29
|
+
PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS = "PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS"
|
|
30
|
+
PAPERLESS_DOCLING_POLL_INTERVAL = "PAPERLESS_DOCLING_POLL_INTERVAL"
|
|
31
|
+
|
|
32
|
+
# Default conversion options
|
|
33
|
+
DEFAULT_OPTIONS = {
|
|
34
|
+
"to_formats": "json", # We need JSON format to get DoclingDocument
|
|
35
|
+
"image_export_mode": "placeholder",
|
|
36
|
+
"force_ocr": True
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def get_docling_serve_url() -> str:
|
|
41
|
+
"""Get the docling-serve URL from environment variable."""
|
|
42
|
+
return os.environ.get(PAPERLESS_DOCLING_SERVE_URL, "http://docling-serve:5000")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_docling_serve_timeout() -> float:
|
|
46
|
+
"""Get the docling-serve timeout from environment variable."""
|
|
47
|
+
try:
|
|
48
|
+
return float(os.environ.get(PAPERLESS_DOCLING_SERVE_TIMEOUT, "300.0"))
|
|
49
|
+
except ValueError:
|
|
50
|
+
return 300.0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_poll_max_attempts() -> int:
|
|
54
|
+
"""Get the maximum number of polling attempts from environment variable."""
|
|
55
|
+
try:
|
|
56
|
+
return int(os.environ.get(PAPERLESS_DOCLING_POLL_MAX_ATTEMPTS, "60"))
|
|
57
|
+
except ValueError:
|
|
58
|
+
return 60
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def get_poll_interval() -> float:
|
|
62
|
+
"""Get the polling interval in seconds from environment variable."""
|
|
63
|
+
try:
|
|
64
|
+
return float(os.environ.get(PAPERLESS_DOCLING_POLL_INTERVAL, "5.0"))
|
|
65
|
+
except ValueError:
|
|
66
|
+
return 5.0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class DoclingRemoteConverter(BaseDoclingConverter):
|
|
70
|
+
"""Converter that uses docling-serve API for document conversion."""
|
|
71
|
+
|
|
72
|
+
def __init__(self, **kwargs):
|
|
73
|
+
"""Initialize the converter with configuration from environment variables."""
|
|
74
|
+
self.pdf_conversion_mode = get_pdf_conversion_mode()
|
|
75
|
+
self.base_url = get_docling_serve_url()
|
|
76
|
+
self.timeout = get_docling_serve_timeout()
|
|
77
|
+
self.poll_max_attempts = get_poll_max_attempts()
|
|
78
|
+
self.poll_interval = get_poll_interval()
|
|
79
|
+
|
|
80
|
+
logger.info(
|
|
81
|
+
f"DoclingConverter initialized: mode={self.pdf_conversion_mode.value}, "
|
|
82
|
+
f"url={self.base_url}, timeout={self.timeout}s"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def _extract_docling_document(self, result: Dict[str, Any]) -> DoclingDocument:
|
|
86
|
+
"""
|
|
87
|
+
Extract and validate DoclingDocument from API result.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
result: API response containing the document
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
DoclingDocument: The validated document object
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
ParseError: If the response structure is invalid
|
|
97
|
+
"""
|
|
98
|
+
if "document" not in result or "json_content" not in result["document"]:
|
|
99
|
+
raise ParseError("Invalid response structure from docling-serve: missing json_content")
|
|
100
|
+
|
|
101
|
+
json_content = result["document"]["json_content"]
|
|
102
|
+
return DoclingDocument.model_validate(json_content)
|
|
103
|
+
|
|
104
|
+
async def convert_async(self, document_path: Path, options: Dict[str, Any]) -> DoclingDocument:
|
|
105
|
+
"""
|
|
106
|
+
Convert a document using docling-serve API.
|
|
107
|
+
|
|
108
|
+
Workflow:
|
|
109
|
+
1. POST to /v1/convert/file/async to create conversion task
|
|
110
|
+
2. Poll /v1/status/poll/{task_id} until task completes
|
|
111
|
+
3. GET /v1/result/{task_id} to fetch the result
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
document_path: Path to the document to convert
|
|
115
|
+
options: Conversion options (ocr_preset, ocr_lang, pipeline, etc.)
|
|
116
|
+
|
|
117
|
+
Returns:
|
|
118
|
+
DoclingDocument: The converted document
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
ParseError: If conversion fails
|
|
122
|
+
"""
|
|
123
|
+
logger.info(f"Starting conversion for document: {document_path}")
|
|
124
|
+
|
|
125
|
+
try:
|
|
126
|
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
|
127
|
+
# Step 1: Create conversion task
|
|
128
|
+
with open(document_path, "rb") as f:
|
|
129
|
+
files = {"files": (document_path.name, f, "application/pdf")}
|
|
130
|
+
data = {**DEFAULT_OPTIONS, **options}
|
|
131
|
+
|
|
132
|
+
logger.debug(f"Posting to {self.base_url}/v1/convert/file/async with options: {data}")
|
|
133
|
+
response = await client.post(
|
|
134
|
+
f"{self.base_url}/v1/convert/file/async",
|
|
135
|
+
files=files,
|
|
136
|
+
data=data,
|
|
137
|
+
)
|
|
138
|
+
response.raise_for_status()
|
|
139
|
+
|
|
140
|
+
task_id = response.json().get("task_id")
|
|
141
|
+
if not task_id:
|
|
142
|
+
raise ParseError("No task_id returned from async conversion endpoint")
|
|
143
|
+
|
|
144
|
+
logger.info(f"Conversion task created with ID: {task_id}")
|
|
145
|
+
|
|
146
|
+
# Step 2: Poll for completion
|
|
147
|
+
for attempt in range(self.poll_max_attempts):
|
|
148
|
+
response = await client.get(f"{self.base_url}/v1/status/poll/{task_id}")
|
|
149
|
+
response.raise_for_status()
|
|
150
|
+
|
|
151
|
+
status_data = response.json()
|
|
152
|
+
task_status = status_data.get("task_status")
|
|
153
|
+
|
|
154
|
+
logger.debug(f"Poll {attempt + 1}/{self.poll_max_attempts} - Task {task_id} status: {task_status}")
|
|
155
|
+
|
|
156
|
+
if task_status == "success":
|
|
157
|
+
logger.info(f"Task {task_id} completed successfully")
|
|
158
|
+
break
|
|
159
|
+
elif task_status == "failure":
|
|
160
|
+
error_msg = str(status_data.get("task_meta", "Unknown error"))
|
|
161
|
+
logger.error(f"Task {task_id} failed: {error_msg}")
|
|
162
|
+
raise ParseError(f"Conversion failed: {error_msg}")
|
|
163
|
+
|
|
164
|
+
# Still processing, wait before next poll
|
|
165
|
+
await asyncio.sleep(self.poll_interval)
|
|
166
|
+
else:
|
|
167
|
+
# Loop completed without break (timeout)
|
|
168
|
+
raise TimeoutError(f"Conversion timed out after {self.poll_max_attempts} polling attempts")
|
|
169
|
+
|
|
170
|
+
# Step 3: Fetch result
|
|
171
|
+
logger.debug(f"Fetching result for task: {task_id}")
|
|
172
|
+
response = await client.get(f"{self.base_url}/v1/result/{task_id}")
|
|
173
|
+
response.raise_for_status()
|
|
174
|
+
result = response.json()
|
|
175
|
+
|
|
176
|
+
# Extract and validate DoclingDocument
|
|
177
|
+
doc = self._extract_docling_document(result)
|
|
178
|
+
logger.info(f"Successfully converted document: {document_path}")
|
|
179
|
+
return doc
|
|
180
|
+
|
|
181
|
+
except ParseError:
|
|
182
|
+
raise
|
|
183
|
+
except Exception as e:
|
|
184
|
+
logger.error(f"Failed to parse {document_path}: {e}", exc_info=True)
|
|
185
|
+
raise ParseError(f"Failed to parse {document_path}") from e
|
|
186
|
+
|
|
187
|
+
def convert_easyocr(self, document_path: Path) -> DoclingDocument:
|
|
188
|
+
"""Convert using EasyOCR preset."""
|
|
189
|
+
return self._convert(document_path, {
|
|
190
|
+
"ocr_preset": "easyocr",
|
|
191
|
+
"ocr_lang": ["en", "de"]
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
def convert_tesseract(self, document_path: Path) -> DoclingDocument:
|
|
195
|
+
"""Convert using Tesseract OCR preset."""
|
|
196
|
+
return self._convert(document_path, {
|
|
197
|
+
"ocr_preset": "tesseract",
|
|
198
|
+
"ocr_lang": ["eng", "deu"]
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
def convert_granite_docling(self, document_path: Path) -> DoclingDocument:
|
|
202
|
+
"""Convert using Granite Docling VLM pipeline."""
|
|
203
|
+
return self._convert(document_path, {
|
|
204
|
+
"pipeline": "vlm"
|
|
205
|
+
})
|
|
206
|
+
|
|
207
|
+
def _convert(self, document_path: Path, options: Dict[str, Any]) -> DoclingDocument:
|
|
208
|
+
"""
|
|
209
|
+
Synchronous wrapper for async conversion.
|
|
210
|
+
|
|
211
|
+
Args:
|
|
212
|
+
document_path: Path to the document to convert
|
|
213
|
+
options: Conversion options
|
|
214
|
+
|
|
215
|
+
Returns:
|
|
216
|
+
DoclingDocument: The converted document
|
|
217
|
+
"""
|
|
218
|
+
return asyncio.run(self.convert_async(document_path, options))
|
|
219
|
+
|