datalab-python-sdk 0.14.0__py3-none-any.whl → 0.16.0__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.
- {datalab_python_sdk-0.14.0.dist-info → datalab_python_sdk-0.16.0.dist-info}/METADATA +12 -7
- datalab_python_sdk-0.16.0.dist-info/RECORD +16 -0
- datalab_sdk/__init__.py +10 -10
- datalab_sdk/_output_layout.py +4 -2
- datalab_sdk/_output_names.py +31 -0
- datalab_sdk/_status.py +119 -0
- datalab_sdk/cli.py +18 -458
- datalab_sdk/client.py +870 -676
- datalab_sdk/exceptions.py +64 -1
- datalab_sdk/models.py +81 -145
- datalab_python_sdk-0.14.0.dist-info/RECORD +0 -14
- {datalab_python_sdk-0.14.0.dist-info → datalab_python_sdk-0.16.0.dist-info}/WHEEL +0 -0
- {datalab_python_sdk-0.14.0.dist-info → datalab_python_sdk-0.16.0.dist-info}/entry_points.txt +0 -0
- {datalab_python_sdk-0.14.0.dist-info → datalab_python_sdk-0.16.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: datalab-python-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.16.0
|
|
4
4
|
Summary: SDK for the Datalab document intelligence API
|
|
5
5
|
Project-URL: Homepage, https://www.datalab.to
|
|
6
6
|
Project-URL: Documentation, https://documentation.datalab.to
|
|
@@ -35,7 +35,7 @@ pip install datalab-python-sdk
|
|
|
35
35
|
|
|
36
36
|
### Authentication
|
|
37
37
|
|
|
38
|
-
[Sign up](https://www.datalab.to
|
|
38
|
+
[Sign up](https://www.datalab.to/auth/sign_up?utm_source=gh-sdk), then get your API key from [https://www.datalab.to/app/keys](https://www.datalab.to/app/keys):
|
|
39
39
|
|
|
40
40
|
```bash
|
|
41
41
|
export DATALAB_API_KEY="your_api_key_here"
|
|
@@ -195,16 +195,21 @@ Published-agent execution is in open beta; the API may change. Processor design
|
|
|
195
195
|
except DatalabPollingTimeoutError as e:
|
|
196
196
|
result = client.get_result(e.check_url, max_polls=600)
|
|
197
197
|
```
|
|
198
|
-
-
|
|
198
|
+
- To wait somewhere else, for example in a scheduler, submit with `submit_convert()`, `submit_extract()`, `submit_segment()` or another `submit_*` method (SDK 0.16.0+). It returns a `SubmittedRequest` with `request_id` and `check_url` and does not poll. `check_status(check_url)` checks once whether the request has finished, without returning the result, and does not retry. When `done` is True, `get_result(check_url)` downloads the result; check `result.success`.
|
|
199
|
+
|
|
200
|
+
```python
|
|
201
|
+
submitted = client.submit_convert("big.pdf")
|
|
202
|
+
# ... later, from any process
|
|
203
|
+
status = client.check_status(submitted.check_url)
|
|
204
|
+
if status.done:
|
|
205
|
+
result = client.get_result(submitted.check_url)
|
|
206
|
+
```
|
|
207
|
+
- API errors raise `DatalabAPIError` (with `status_code` and `response_data`) or one of its subclasses: `DatalabAuthenticationError` (401, 403), `DatalabPaymentRequiredError` (402), `DatalabNotFoundError` (404), `DatalabRateLimitError` (429) and `DatalabServerError` (5xx). `DatalabProcessingError` means the API reported that the request failed before it completed, and `DatalabResponseError` means `check_status()` could not read the response. Every `DatalabError` has `retryable`, which says whether making the same call again later may succeed and is safe: a submission is retryable only after HTTP 429 or 503, because after other errors the API may already have accepted it. Invalid arguments raise `DatalabValidationError`, which is also a `ValueError`.
|
|
199
208
|
|
|
200
209
|
With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
|
|
201
210
|
files from disk and limits the number of active uploads. Results retain the
|
|
202
211
|
input order. Use `AsyncDatalabClient` inside an existing async event loop.
|
|
203
212
|
|
|
204
|
-
## Workflows
|
|
205
|
-
|
|
206
|
-
The Datalab API removed the Workflows API. The workflow methods and CLI commands in this SDK are deprecated, and the API does not answer them. Use pipelines instead.
|
|
207
|
-
|
|
208
213
|
## CLI Usage
|
|
209
214
|
|
|
210
215
|
The SDK includes a command-line interface:
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
datalab_sdk/__init__.py,sha256=B0WuBDsy0dKH2bz5KsG5CoFB_u3r1kWaJIEzXVcrrrg,3501
|
|
2
|
+
datalab_sdk/_output_layout.py,sha256=mDtg2hZQkMw_LTsrfslxwJ4BOZ2H8wKpR9w9CaT8mBs,7989
|
|
3
|
+
datalab_sdk/_output_names.py,sha256=CVbXjF--VoX61ZSOB2eUmeg0jbq4g5EMLzWcLy1a9Gw,1001
|
|
4
|
+
datalab_sdk/_status.py,sha256=5MXXchXmhwCxiiZRmonY2hCk3aWz1jpQgU-9ovgm6i8,4518
|
|
5
|
+
datalab_sdk/auth.py,sha256=i7LzAMM5wjY5-J6BUf69do6g7zuKenQZQwueqbLJSNU,7704
|
|
6
|
+
datalab_sdk/cli.py,sha256=YZObu6fihyQ3TLvFaWurpWYZGHYTzTx3m1r6mOpHOsE,47696
|
|
7
|
+
datalab_sdk/client.py,sha256=FAx36MPDWE_xLnLP0SSz5AdVCvIkP9CQoolggE5wH78,182293
|
|
8
|
+
datalab_sdk/exceptions.py,sha256=E46kSnvcw9d7psCreEKPp65BFMXg35gIBuXSAiDMe5M,6864
|
|
9
|
+
datalab_sdk/mimetypes.py,sha256=a4ULJmHxoR_RMsD0j51hx0t2Q7In_PzNm7UlWX07eEE,932
|
|
10
|
+
datalab_sdk/models.py,sha256=bIpEqnXT_ygTIzORfZ5YYvQ1x5RySkJARz9q84EZIcI,41923
|
|
11
|
+
datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
|
|
12
|
+
datalab_python_sdk-0.16.0.dist-info/METADATA,sha256=n-EEZJLvT0gTjHpuI5alJ5ju61_TrP-mt7WwaZuH9ZI,12439
|
|
13
|
+
datalab_python_sdk-0.16.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
datalab_python_sdk-0.16.0.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
|
|
15
|
+
datalab_python_sdk-0.16.0.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
|
|
16
|
+
datalab_python_sdk-0.16.0.dist-info/RECORD,,
|
datalab_sdk/__init__.py
CHANGED
|
@@ -14,6 +14,8 @@ from .exceptions import (
|
|
|
14
14
|
DatalabNotFoundError,
|
|
15
15
|
DatalabRateLimitError,
|
|
16
16
|
DatalabServerError,
|
|
17
|
+
DatalabProcessingError,
|
|
18
|
+
DatalabResponseError,
|
|
17
19
|
DatalabTimeoutError,
|
|
18
20
|
DatalabTransferTimeoutError,
|
|
19
21
|
DatalabPollingTimeoutError,
|
|
@@ -25,6 +27,8 @@ from .models import (
|
|
|
25
27
|
CreateDocumentResult,
|
|
26
28
|
FileResult,
|
|
27
29
|
OCRResult,
|
|
30
|
+
RequestStatus,
|
|
31
|
+
SubmittedRequest,
|
|
28
32
|
ConvertOptions,
|
|
29
33
|
ExtractOptions,
|
|
30
34
|
SegmentOptions,
|
|
@@ -40,13 +44,9 @@ from .models import (
|
|
|
40
44
|
FormFieldsResult,
|
|
41
45
|
AgentOptions,
|
|
42
46
|
AgentResult,
|
|
43
|
-
ExtractionSchemaSuggestions,
|
|
44
|
-
Workflow,
|
|
45
|
-
WorkflowStep,
|
|
46
|
-
WorkflowExecution,
|
|
47
|
-
InputConfig,
|
|
48
47
|
UploadedFileMetadata,
|
|
49
48
|
ExtractionSchema,
|
|
49
|
+
ExtractionSchemaSuggestions,
|
|
50
50
|
PipelineProcessor,
|
|
51
51
|
PipelineConfig,
|
|
52
52
|
PipelineVersion,
|
|
@@ -87,6 +87,8 @@ __all__ = [
|
|
|
87
87
|
"DatalabNotFoundError",
|
|
88
88
|
"DatalabRateLimitError",
|
|
89
89
|
"DatalabServerError",
|
|
90
|
+
"DatalabProcessingError",
|
|
91
|
+
"DatalabResponseError",
|
|
90
92
|
"DatalabTimeoutError",
|
|
91
93
|
"DatalabTransferTimeoutError",
|
|
92
94
|
"DatalabPollingTimeoutError",
|
|
@@ -96,6 +98,8 @@ __all__ = [
|
|
|
96
98
|
"CreateDocumentResult",
|
|
97
99
|
"FileResult",
|
|
98
100
|
"OCRResult",
|
|
101
|
+
"RequestStatus",
|
|
102
|
+
"SubmittedRequest",
|
|
99
103
|
"ConvertOptions",
|
|
100
104
|
"ExtractOptions",
|
|
101
105
|
"SegmentOptions",
|
|
@@ -111,13 +115,9 @@ __all__ = [
|
|
|
111
115
|
"FormFieldsResult",
|
|
112
116
|
"AgentOptions",
|
|
113
117
|
"AgentResult",
|
|
114
|
-
"ExtractionSchemaSuggestions",
|
|
115
|
-
"Workflow",
|
|
116
|
-
"WorkflowStep",
|
|
117
|
-
"WorkflowExecution",
|
|
118
|
-
"InputConfig",
|
|
119
118
|
"UploadedFileMetadata",
|
|
120
119
|
"ExtractionSchema",
|
|
120
|
+
"ExtractionSchemaSuggestions",
|
|
121
121
|
"PipelineProcessor",
|
|
122
122
|
"PipelineConfig",
|
|
123
123
|
"PipelineVersion",
|
datalab_sdk/_output_layout.py
CHANGED
|
@@ -13,6 +13,7 @@ import tempfile
|
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
from typing import Dict, List, Optional
|
|
15
15
|
|
|
16
|
+
from datalab_sdk._output_names import exact_output_base
|
|
16
17
|
from datalab_sdk.exceptions import DatalabError
|
|
17
18
|
|
|
18
19
|
OUTPUT_MARKER = ".datalab-output"
|
|
@@ -137,8 +138,9 @@ class OutputLayout:
|
|
|
137
138
|
return list(self._folders.values())
|
|
138
139
|
|
|
139
140
|
def output_path(self, file_path: Path) -> Path:
|
|
140
|
-
"""The save_output path of an input: its folder plus its stem
|
|
141
|
-
|
|
141
|
+
"""The save_output path of an input: its folder plus its whole stem
|
|
142
|
+
(report.json.tif saves report.json.md, report.json.html and so on)."""
|
|
143
|
+
return exact_output_base(self._folders[file_path] / file_path.stem)
|
|
142
144
|
|
|
143
145
|
def __enter__(self) -> "OutputLayout":
|
|
144
146
|
# A with statement doesn't call __exit__ when __enter__ raises, so any
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""How save_output names the files it writes from the path it's given."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from datalab_sdk.mimetypes import SUPPORTED_EXTENSIONS
|
|
6
|
+
|
|
7
|
+
# The extensions save_output replaces: the ones it writes, and the input types the
|
|
8
|
+
# API reads, so save_output("out/scan.jpg") writes out/scan.md. Any other dot belongs
|
|
9
|
+
# to the name (a stem such as "v1.2.report").
|
|
10
|
+
_REPLACED_EXTENSIONS = {
|
|
11
|
+
".md",
|
|
12
|
+
".txt",
|
|
13
|
+
".json",
|
|
14
|
+
".xml",
|
|
15
|
+
".tif",
|
|
16
|
+
".htm",
|
|
17
|
+
*SUPPORTED_EXTENSIONS,
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def output_file(path: Path, suffix: str) -> Path:
|
|
22
|
+
"""`path` with `suffix` added, keeping every dot in the name except one known extension."""
|
|
23
|
+
if path.suffix.lower() in _REPLACED_EXTENSIONS:
|
|
24
|
+
path = path.with_suffix("")
|
|
25
|
+
return path.with_name(path.name + suffix)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def exact_output_base(base: Path) -> Path:
|
|
29
|
+
"""A path that save_output uses whole as the base name, dots and all
|
|
30
|
+
(report.json gives report.json.md, not report.md)."""
|
|
31
|
+
return base.with_name(base.name + ".md")
|
datalab_sdk/_status.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""The bounded reader behind check_status().
|
|
2
|
+
|
|
3
|
+
check_status() needs four top-level fields of a status response. An API
|
|
4
|
+
that does not support include_result=false sends the whole result, which can
|
|
5
|
+
be gigabytes, before success and error. This reader never reads more than
|
|
6
|
+
READ_LIMIT bytes of a body, and the caller turns off automatic decompression,
|
|
7
|
+
so the limit counts the bytes received.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
import ijson
|
|
15
|
+
|
|
16
|
+
READ_LIMIT = 1024 * 1024
|
|
17
|
+
_CHUNK = 64 * 1024
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class StatusBodyError(Exception):
|
|
21
|
+
"""The status body was compressed, invalid JSON, had no status, or was
|
|
22
|
+
too large without a finished status."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ProcessingFailed(Exception):
|
|
26
|
+
"""The API reported success=False for a request that is not complete."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class StatusFields:
|
|
31
|
+
"""A status snapshot. read_status() returns it normalized: success and
|
|
32
|
+
error are None while the request runs, and None for a finished request
|
|
33
|
+
whose body reached READ_LIMIT before they arrived (outcome unknown)."""
|
|
34
|
+
|
|
35
|
+
status: Optional[str] = None
|
|
36
|
+
success: Optional[bool] = None
|
|
37
|
+
error: Optional[str] = None
|
|
38
|
+
progress_percent: Optional[int] = None
|
|
39
|
+
_error_seen: bool = False
|
|
40
|
+
|
|
41
|
+
def _feed(self, events) -> None:
|
|
42
|
+
for prefix, event, value in events:
|
|
43
|
+
if prefix == "status" and event == "string":
|
|
44
|
+
self.status = value
|
|
45
|
+
elif prefix == "success" and event == "boolean":
|
|
46
|
+
self.success = value
|
|
47
|
+
elif prefix == "error" and event in ("string", "null"):
|
|
48
|
+
self.error = value
|
|
49
|
+
self._error_seen = True
|
|
50
|
+
elif prefix == "progress_percent" and event == "number":
|
|
51
|
+
self.progress_percent = value if type(value) is int else None
|
|
52
|
+
|
|
53
|
+
def _normalized(self, outcome_known: bool) -> "StatusFields":
|
|
54
|
+
if self.status is None:
|
|
55
|
+
raise StatusBodyError("the response has no status")
|
|
56
|
+
if self.status != "complete" and self.success is False:
|
|
57
|
+
raise ProcessingFailed(self.error or "Unknown error")
|
|
58
|
+
if self.status != "complete" or not outcome_known:
|
|
59
|
+
self.success = self.error = None
|
|
60
|
+
elif self.success is None:
|
|
61
|
+
self.success = True
|
|
62
|
+
# Some routes send error="" for a success: report no error as None.
|
|
63
|
+
self.error = self.error or None
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
def _finished(self) -> bool:
|
|
67
|
+
return (
|
|
68
|
+
self.status == "complete"
|
|
69
|
+
and self.success is not None
|
|
70
|
+
and (self.success or self._error_seen)
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
async def read_error_body(resp: aiohttp.ClientResponse) -> bytes:
|
|
75
|
+
"""At most READ_LIMIT bytes of an error body. A cut-off body still lets
|
|
76
|
+
the caller raise the error for the status code."""
|
|
77
|
+
try:
|
|
78
|
+
return await resp.content.read(READ_LIMIT)
|
|
79
|
+
except aiohttp.ClientError:
|
|
80
|
+
return b""
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def read_status(resp: aiohttp.ClientResponse) -> StatusFields:
|
|
84
|
+
"""Read and normalize the status fields of a 2xx status response,
|
|
85
|
+
reading at most READ_LIMIT bytes."""
|
|
86
|
+
encoding = resp.headers.get("Content-Encoding", "identity").lower()
|
|
87
|
+
if encoding != "identity":
|
|
88
|
+
raise StatusBodyError(f"status response is {encoding}-encoded")
|
|
89
|
+
|
|
90
|
+
fields = StatusFields()
|
|
91
|
+
events = ijson.sendable_list()
|
|
92
|
+
parser = ijson.parse_coro(events)
|
|
93
|
+
remaining = READ_LIMIT
|
|
94
|
+
try:
|
|
95
|
+
while remaining > 0:
|
|
96
|
+
chunk = await resp.content.read(min(_CHUNK, remaining))
|
|
97
|
+
if not chunk:
|
|
98
|
+
parser.close()
|
|
99
|
+
fields._feed(events)
|
|
100
|
+
return fields._normalized(outcome_known=True)
|
|
101
|
+
remaining -= len(chunk)
|
|
102
|
+
parser.send(chunk)
|
|
103
|
+
fields._feed(events)
|
|
104
|
+
del events[:]
|
|
105
|
+
if fields._finished():
|
|
106
|
+
return fields._normalized(outcome_known=True)
|
|
107
|
+
# The budget is spent. A body of exactly READ_LIMIT bytes has ended.
|
|
108
|
+
if await resp.content.read(1) == b"":
|
|
109
|
+
parser.close()
|
|
110
|
+
fields._feed(events)
|
|
111
|
+
return fields._normalized(outcome_known=True)
|
|
112
|
+
except ijson.JSONError as e:
|
|
113
|
+
# ijson's message adds lines that point at the bad character.
|
|
114
|
+
reason = str(e).splitlines()[0] if str(e) else type(e).__name__
|
|
115
|
+
raise StatusBodyError(f"invalid JSON: {reason}") from e
|
|
116
|
+
|
|
117
|
+
if fields.status != "complete":
|
|
118
|
+
raise StatusBodyError(f"no finished status in the first {READ_LIMIT} bytes")
|
|
119
|
+
return fields._normalized(outcome_known=False)
|