pgx-docling-parser-serve 0.0.0.dev0__py3-none-any.whl

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.

@@ -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__"]
docling_serve/serve.py ADDED
@@ -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
+
@@ -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,5 @@
1
+ docling_serve/__init__.py,sha256=HBZQZOANCa2UZuZqOIc2QAOMhX5Hqv0jNPO01M6UG40,306
2
+ docling_serve/serve.py,sha256=jOP-ldDjowyX04B0V5TJmw5RUtkVpyZoVrmFLkiAv4g,8605
3
+ pgx_docling_parser_serve-0.0.0.dev0.dist-info/METADATA,sha256=fVIg0jHC-YbFFvDxPuWzuEf4HCD7_po3CTxOqoEh_eM,1779
4
+ pgx_docling_parser_serve-0.0.0.dev0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
5
+ pgx_docling_parser_serve-0.0.0.dev0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any