datalab-python-sdk 0.15.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datalab-python-sdk
3
- Version: 0.15.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
@@ -195,7 +195,16 @@ 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
- - 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). Invalid arguments raise `DatalabValidationError`, which is also a `ValueError`.
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
@@ -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,
@@ -83,6 +87,8 @@ __all__ = [
83
87
  "DatalabNotFoundError",
84
88
  "DatalabRateLimitError",
85
89
  "DatalabServerError",
90
+ "DatalabProcessingError",
91
+ "DatalabResponseError",
86
92
  "DatalabTimeoutError",
87
93
  "DatalabTransferTimeoutError",
88
94
  "DatalabPollingTimeoutError",
@@ -92,6 +98,8 @@ __all__ = [
92
98
  "CreateDocumentResult",
93
99
  "FileResult",
94
100
  "OCRResult",
101
+ "RequestStatus",
102
+ "SubmittedRequest",
95
103
  "ConvertOptions",
96
104
  "ExtractOptions",
97
105
  "SegmentOptions",
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)