datalab-python-sdk 0.8.0__tar.gz → 0.9.1__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.
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/CHANGELOG.md +30 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/PKG-INFO +30 -3
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/README.md +29 -2
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/__init__.py +4 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/client.py +236 -22
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/models.py +56 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/pyproject.toml +4 -1
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_api_consistency.py +10 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_client_methods.py +54 -0
- datalab_python_sdk-0.9.1/tests/test_transport_audit.py +346 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/uv.lock +8 -4
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/.github/workflows/ci.yml +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/.gitignore +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/.pre-commit-config.yaml +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/.python-version +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/LICENSE +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/08-Lambda-Calculus.pptx +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/adversarial.pdf +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/bid_evaluation.docx +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/book_review.ppt +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/book_store.xls +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/chi_hind.png +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/how_to_read.doc +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/normandy.epub +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/sample-1-sheet.xlsx +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/thinkpython.pdf +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/data/vibe.html +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/auth.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/cli.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/exceptions.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/mimetypes.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/datalab_sdk/settings.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/integration/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/integration/__init__.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/integration/test_live_api.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/integration/test_readme_examples.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/pytest.ini +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/end_to_end_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_api_tutorial/1_get_step_types.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_api_tutorial/2_get_workflows.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_api_tutorial/3_create_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_api_tutorial/4_execute_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_api_tutorial/5_poll_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_api_tutorial/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_definitions/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_definitions/eval_segmentation.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_definitions/parse_segment.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_definitions/segment_parallel_extract.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/recipes/workflows/workflow_definitions/slack_alert.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/__init__.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/conftest.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_cli_options.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_cli_simple.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_device_login.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_errors.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_new_endpoints.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_progress.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_results.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.1}/tests/test_workflows.py +0 -0
|
@@ -3,6 +3,36 @@
|
|
|
3
3
|
The newest release is at the top. Each export to this repository uses the
|
|
4
4
|
top section as its commit message.
|
|
5
5
|
|
|
6
|
+
## 0.9.1
|
|
7
|
+
|
|
8
|
+
Changed:
|
|
9
|
+
|
|
10
|
+
- Result polls check every 0.3 seconds for the first 8 seconds of a request,
|
|
11
|
+
then every `poll_interval`. Most single-page results are ready within a few
|
|
12
|
+
seconds, so they arrive sooner. The polling budget is unchanged: the waits
|
|
13
|
+
between polls add up to `max_polls * poll_interval` seconds. A
|
|
14
|
+
`poll_interval` above 1 second turns the fast phase off.
|
|
15
|
+
|
|
16
|
+
## 0.9.0
|
|
17
|
+
|
|
18
|
+
New:
|
|
19
|
+
|
|
20
|
+
- **Open beta:** `redact()` and `get_redaction_presets()` on both clients,
|
|
21
|
+
with `RedactOptions` and `RedactResult`. Results preserve the verification
|
|
22
|
+
verdict and failed checks, including when a completed run returns an
|
|
23
|
+
available PDF with failed verification. Regional signed results use the same
|
|
24
|
+
verified result contract. Use save_output to save the PDF; streaming redaction
|
|
25
|
+
results is not supported. The redaction API may change.
|
|
26
|
+
- `upload_files(..., max_concurrency=5)` bounds active uploads, streams
|
|
27
|
+
files from disk, and reuses storage connections within a batch. Results
|
|
28
|
+
retain input order. Uploads respect the configured request timeout.
|
|
29
|
+
|
|
30
|
+
Fixed:
|
|
31
|
+
|
|
32
|
+
- Synchronous calls propagate an operation's `RuntimeError` without attempting
|
|
33
|
+
to rerun its coroutine. Calling the synchronous client inside an active event
|
|
34
|
+
loop now directs callers to `AsyncDatalabClient`.
|
|
35
|
+
|
|
6
36
|
## 0.8.0
|
|
7
37
|
|
|
8
38
|
New:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: datalab-python-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.1
|
|
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
|
|
@@ -125,6 +125,30 @@ print(result.extraction_schema_json, result.extraction_score_average)
|
|
|
125
125
|
|
|
126
126
|
When you do not set the parse `mode`, the API picks the parse mode that matches `extraction_mode`.
|
|
127
127
|
|
|
128
|
+
## Redaction
|
|
129
|
+
|
|
130
|
+
**Open beta (SDK 0.9.0):** the redaction API may change.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from datalab_sdk import RedactOptions
|
|
134
|
+
|
|
135
|
+
result = client.redact(
|
|
136
|
+
"document.pdf",
|
|
137
|
+
options=RedactOptions(preset="personal_information"),
|
|
138
|
+
)
|
|
139
|
+
# A PDF can be returned even when verification fails. Review these first.
|
|
140
|
+
print(result.verdict, result.failing_checks)
|
|
141
|
+
if result.success and result.verdict == "PASS" and not result.withheld and result.output_base64:
|
|
142
|
+
result.save_output("redacted.pdf")
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
`get_redaction_presets()` returns the built-in preset IDs and specifications.
|
|
146
|
+
Use `redaction_spec` to supply a custom spec. Redaction processes the whole
|
|
147
|
+
PDF or image; page subsets are not supported. Completed requests are charged
|
|
148
|
+
even if verification fails. `save_output` on `redact()` saves any available
|
|
149
|
+
PDF, including one with failed verification. Redaction returns a typed result;
|
|
150
|
+
`stream_response_to` is not supported for this helper.
|
|
151
|
+
|
|
128
152
|
## Other endpoints
|
|
129
153
|
|
|
130
154
|
| Method | Endpoint |
|
|
@@ -135,7 +159,6 @@ When you do not set the parse `mode`, the API picks the parse mode that matches
|
|
|
135
159
|
| `form_fields()` | Find the fillable fields in a PDF or image |
|
|
136
160
|
| `track_changes()` | Read tracked changes and comments from DOCX or PDF |
|
|
137
161
|
| `create_document()` | Make a DOCX from markdown with track changes markup |
|
|
138
|
-
| `generate_extraction_schemas()` | Suggest extraction schemas for a saved checkpoint |
|
|
139
162
|
| `delete_result()` | Result deletion, by `result.request_id` |
|
|
140
163
|
| `upload_files()`, `list_files()`, ... | File storage. Pass the returned `datalab://file-...` reference as `file_url` |
|
|
141
164
|
| `create_extraction_schema()`, ... | Saved extraction schemas |
|
|
@@ -148,10 +171,14 @@ Published-agent execution is in open beta; the API may change. Processor design
|
|
|
148
171
|
## Inputs, polling and errors
|
|
149
172
|
|
|
150
173
|
- Send a local file with `file_path`, or a URL or a `datalab://file-...` reference with `file_url`. When you set `processing_location`, send the document as `file_url`.
|
|
151
|
-
- Processing methods poll until the result is ready. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk.
|
|
174
|
+
- Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk.
|
|
152
175
|
- The SDK retries a submission that gets HTTP 429 or 503, and polls that get 408, 429, 5xx or a connection error. It waits for the `Retry-After` header when the API sends one.
|
|
153
176
|
- 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`.
|
|
154
177
|
|
|
178
|
+
With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
|
|
179
|
+
files from disk and limits the number of active uploads. Results retain the
|
|
180
|
+
input order. Use `AsyncDatalabClient` inside an existing async event loop.
|
|
181
|
+
|
|
155
182
|
## Workflows
|
|
156
183
|
|
|
157
184
|
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.
|
|
@@ -104,6 +104,30 @@ print(result.extraction_schema_json, result.extraction_score_average)
|
|
|
104
104
|
|
|
105
105
|
When you do not set the parse `mode`, the API picks the parse mode that matches `extraction_mode`.
|
|
106
106
|
|
|
107
|
+
## Redaction
|
|
108
|
+
|
|
109
|
+
**Open beta (SDK 0.9.0):** the redaction API may change.
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from datalab_sdk import RedactOptions
|
|
113
|
+
|
|
114
|
+
result = client.redact(
|
|
115
|
+
"document.pdf",
|
|
116
|
+
options=RedactOptions(preset="personal_information"),
|
|
117
|
+
)
|
|
118
|
+
# A PDF can be returned even when verification fails. Review these first.
|
|
119
|
+
print(result.verdict, result.failing_checks)
|
|
120
|
+
if result.success and result.verdict == "PASS" and not result.withheld and result.output_base64:
|
|
121
|
+
result.save_output("redacted.pdf")
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`get_redaction_presets()` returns the built-in preset IDs and specifications.
|
|
125
|
+
Use `redaction_spec` to supply a custom spec. Redaction processes the whole
|
|
126
|
+
PDF or image; page subsets are not supported. Completed requests are charged
|
|
127
|
+
even if verification fails. `save_output` on `redact()` saves any available
|
|
128
|
+
PDF, including one with failed verification. Redaction returns a typed result;
|
|
129
|
+
`stream_response_to` is not supported for this helper.
|
|
130
|
+
|
|
107
131
|
## Other endpoints
|
|
108
132
|
|
|
109
133
|
| Method | Endpoint |
|
|
@@ -114,7 +138,6 @@ When you do not set the parse `mode`, the API picks the parse mode that matches
|
|
|
114
138
|
| `form_fields()` | Find the fillable fields in a PDF or image |
|
|
115
139
|
| `track_changes()` | Read tracked changes and comments from DOCX or PDF |
|
|
116
140
|
| `create_document()` | Make a DOCX from markdown with track changes markup |
|
|
117
|
-
| `generate_extraction_schemas()` | Suggest extraction schemas for a saved checkpoint |
|
|
118
141
|
| `delete_result()` | Result deletion, by `result.request_id` |
|
|
119
142
|
| `upload_files()`, `list_files()`, ... | File storage. Pass the returned `datalab://file-...` reference as `file_url` |
|
|
120
143
|
| `create_extraction_schema()`, ... | Saved extraction schemas |
|
|
@@ -127,10 +150,14 @@ Published-agent execution is in open beta; the API may change. Processor design
|
|
|
127
150
|
## Inputs, polling and errors
|
|
128
151
|
|
|
129
152
|
- Send a local file with `file_path`, or a URL or a `datalab://file-...` reference with `file_url`. When you set `processing_location`, send the document as `file_url`.
|
|
130
|
-
- Processing methods poll until the result is ready. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk.
|
|
153
|
+
- Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk.
|
|
131
154
|
- The SDK retries a submission that gets HTTP 429 or 503, and polls that get 408, 429, 5xx or a connection error. It waits for the `Retry-After` header when the API sends one.
|
|
132
155
|
- 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`.
|
|
133
156
|
|
|
157
|
+
With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
|
|
158
|
+
files from disk and limits the number of active uploads. Results retain the
|
|
159
|
+
input order. Use `AsyncDatalabClient` inside an existing async event loop.
|
|
160
|
+
|
|
134
161
|
## Workflows
|
|
135
162
|
|
|
136
163
|
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.
|
|
@@ -30,6 +30,8 @@ from .models import (
|
|
|
30
30
|
CustomPipelineOptions,
|
|
31
31
|
TrackChangesOptions,
|
|
32
32
|
OCROptions,
|
|
33
|
+
RedactOptions,
|
|
34
|
+
RedactResult,
|
|
33
35
|
FormFillingOptions,
|
|
34
36
|
FormFillingResult,
|
|
35
37
|
FormFieldsOptions,
|
|
@@ -78,6 +80,8 @@ __all__ = [
|
|
|
78
80
|
"CustomPipelineOptions",
|
|
79
81
|
"TrackChangesOptions",
|
|
80
82
|
"OCROptions",
|
|
83
|
+
"RedactOptions",
|
|
84
|
+
"RedactResult",
|
|
81
85
|
"FormFillingOptions",
|
|
82
86
|
"FormFillingResult",
|
|
83
87
|
"FormFieldsOptions",
|
|
@@ -43,6 +43,8 @@ from datalab_sdk.models import (
|
|
|
43
43
|
CustomProcessorOptions,
|
|
44
44
|
TrackChangesOptions,
|
|
45
45
|
OCROptions,
|
|
46
|
+
RedactOptions,
|
|
47
|
+
RedactResult,
|
|
46
48
|
FormFillingOptions,
|
|
47
49
|
FormFillingResult,
|
|
48
50
|
FormFieldsOptions,
|
|
@@ -95,6 +97,12 @@ class _ProgressReporter:
|
|
|
95
97
|
_SUBMIT_RETRY_STATUSES = (429, 503)
|
|
96
98
|
_BACKOFF = wait_exponential_jitter(initial=5, max=120)
|
|
97
99
|
_MAX_RETRY_AFTER_SECONDS = 120.0
|
|
100
|
+
# The first FAST_POLL_SECONDS of a result poll check every FAST_POLL_INTERVAL
|
|
101
|
+
# seconds, then every poll_interval.
|
|
102
|
+
FAST_POLL_INTERVAL = 0.3
|
|
103
|
+
FAST_POLL_SECONDS = 8.0
|
|
104
|
+
# Hard stop on poll requests, in case the time budget never runs out.
|
|
105
|
+
_MAX_POLL_REQUESTS = 100_000
|
|
98
106
|
|
|
99
107
|
|
|
100
108
|
def _wait_retry_after_or_backoff(retry_state) -> float:
|
|
@@ -318,6 +326,7 @@ class AsyncDatalabClient:
|
|
|
318
326
|
poll_interval: int = 1,
|
|
319
327
|
stream_response_to: Optional[Path] = None,
|
|
320
328
|
on_progress: Optional[ProgressCallback] = None,
|
|
329
|
+
result_transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
|
|
321
330
|
) -> Union[Dict[str, Any], FileResult]:
|
|
322
331
|
"""Poll for result completion"""
|
|
323
332
|
full_url = (
|
|
@@ -327,7 +336,16 @@ class AsyncDatalabClient:
|
|
|
327
336
|
)
|
|
328
337
|
|
|
329
338
|
progress = _ProgressReporter(on_progress)
|
|
330
|
-
|
|
339
|
+
# Most single-page results are ready within a few seconds, so the first
|
|
340
|
+
# FAST_POLL_SECONDS poll every FAST_POLL_INTERVAL. After that the loop
|
|
341
|
+
# polls every poll_interval. The budget is unchanged: the sleeps add up
|
|
342
|
+
# to max_polls * poll_interval seconds, as in the plain loop. A caller
|
|
343
|
+
# that asks for a poll_interval above 1 second gets no fast phase.
|
|
344
|
+
loop = asyncio.get_running_loop()
|
|
345
|
+
fast_until = loop.time() + FAST_POLL_SECONDS if 0 < poll_interval <= 1 else 0.0
|
|
346
|
+
budget = max_polls * poll_interval
|
|
347
|
+
slept = 0.0
|
|
348
|
+
for i in range(max_polls if poll_interval <= 0 else _MAX_POLL_REQUESTS):
|
|
331
349
|
if stream_response_to:
|
|
332
350
|
result = await self._poll_get_streaming(full_url, stream_response_to)
|
|
333
351
|
status, success, error = result.status, result.success, result.error
|
|
@@ -342,6 +360,10 @@ class AsyncDatalabClient:
|
|
|
342
360
|
if status == "complete":
|
|
343
361
|
if not stream_response_to:
|
|
344
362
|
result = await self._resolve_signed_result(data)
|
|
363
|
+
if result_transform is not None:
|
|
364
|
+
result = result_transform(result)
|
|
365
|
+
success = result.get("success", False)
|
|
366
|
+
percent = result.get("progress_percent")
|
|
345
367
|
await progress.report(percent, complete=bool(success))
|
|
346
368
|
return result
|
|
347
369
|
|
|
@@ -350,7 +372,15 @@ class AsyncDatalabClient:
|
|
|
350
372
|
if not success and status != "processing":
|
|
351
373
|
raise DatalabAPIError(f"Processing failed: {error or 'Unknown error'}")
|
|
352
374
|
|
|
353
|
-
|
|
375
|
+
if poll_interval <= 0:
|
|
376
|
+
await asyncio.sleep(poll_interval)
|
|
377
|
+
continue
|
|
378
|
+
if slept >= budget:
|
|
379
|
+
break
|
|
380
|
+
delay = FAST_POLL_INTERVAL if loop.time() < fast_until else poll_interval
|
|
381
|
+
delay = min(delay, budget - slept)
|
|
382
|
+
await asyncio.sleep(delay)
|
|
383
|
+
slept += delay
|
|
354
384
|
|
|
355
385
|
raise DatalabTimeoutError(
|
|
356
386
|
f"Polling timed out after {max_polls * poll_interval} seconds"
|
|
@@ -645,6 +675,7 @@ class AsyncDatalabClient:
|
|
|
645
675
|
stream_response_to: Optional[Path] = None,
|
|
646
676
|
json: Optional[Dict[str, Any]] = None,
|
|
647
677
|
on_progress: Optional[ProgressCallback] = None,
|
|
678
|
+
result_transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
|
|
648
679
|
) -> Union[Dict[str, Any], FileResult]:
|
|
649
680
|
"""Submit a request and poll for the result.
|
|
650
681
|
|
|
@@ -664,6 +695,11 @@ class AsyncDatalabClient:
|
|
|
664
695
|
poll_interval=poll_interval,
|
|
665
696
|
on_progress=on_progress,
|
|
666
697
|
stream_response_to=stream_response_to,
|
|
698
|
+
**(
|
|
699
|
+
{"result_transform": result_transform}
|
|
700
|
+
if result_transform is not None
|
|
701
|
+
else {}
|
|
702
|
+
),
|
|
667
703
|
)
|
|
668
704
|
if isinstance(result, dict):
|
|
669
705
|
result = dict(result)
|
|
@@ -1265,6 +1301,104 @@ class AsyncDatalabClient:
|
|
|
1265
1301
|
self._save_if_requested(result, save_output)
|
|
1266
1302
|
return result
|
|
1267
1303
|
|
|
1304
|
+
@staticmethod
|
|
1305
|
+
def _normalize_redaction_result(data: Dict[str, Any]) -> Dict[str, Any]:
|
|
1306
|
+
"""Project inline and signed worker results onto the public redaction contract."""
|
|
1307
|
+
result = {
|
|
1308
|
+
key: value
|
|
1309
|
+
for key, value in data.items()
|
|
1310
|
+
if key in RedactResult.__dataclass_fields__
|
|
1311
|
+
}
|
|
1312
|
+
document = (
|
|
1313
|
+
data.get("redacted_document")
|
|
1314
|
+
if "redacted_document" in data
|
|
1315
|
+
else data.get("output_base64")
|
|
1316
|
+
)
|
|
1317
|
+
result["output_base64"] = document or None
|
|
1318
|
+
result["withheld"] = not bool(document)
|
|
1319
|
+
if "redacted_document" in data:
|
|
1320
|
+
checks = [
|
|
1321
|
+
metric
|
|
1322
|
+
for metric in (data.get("verifier_metrics") or [])
|
|
1323
|
+
if isinstance(metric, dict)
|
|
1324
|
+
and metric.get("status") != "pass"
|
|
1325
|
+
and metric.get("severity", "blocking") != "advisory"
|
|
1326
|
+
]
|
|
1327
|
+
else:
|
|
1328
|
+
checks = data.get("failing_checks") or []
|
|
1329
|
+
result["failing_checks"] = [
|
|
1330
|
+
{"id": check["id"]}
|
|
1331
|
+
for check in checks
|
|
1332
|
+
if isinstance(check, dict) and isinstance(check.get("id"), str)
|
|
1333
|
+
]
|
|
1334
|
+
for field in ("targets_removed", "targets_not_found"):
|
|
1335
|
+
if result.get(f"{field}_count") is None and isinstance(
|
|
1336
|
+
data.get(field), list
|
|
1337
|
+
):
|
|
1338
|
+
result[f"{field}_count"] = len(data[field])
|
|
1339
|
+
result["success"] = (
|
|
1340
|
+
bool(document)
|
|
1341
|
+
and data.get("verdict") == "PASS"
|
|
1342
|
+
and not checks
|
|
1343
|
+
and data.get("success") is not False
|
|
1344
|
+
)
|
|
1345
|
+
if result["success"]:
|
|
1346
|
+
result["error"] = None
|
|
1347
|
+
else:
|
|
1348
|
+
result["error"] = (
|
|
1349
|
+
"The PDF is available but did not pass all verification checks. Review failing_checks before using it."
|
|
1350
|
+
if document
|
|
1351
|
+
else "No redacted PDF is available. See failing_checks for verification results."
|
|
1352
|
+
)
|
|
1353
|
+
if result.get("progress_percent") == 100:
|
|
1354
|
+
result["progress_percent"] = None
|
|
1355
|
+
return result
|
|
1356
|
+
|
|
1357
|
+
async def redact(
|
|
1358
|
+
self,
|
|
1359
|
+
file_path: Optional[Union[str, Path]] = None,
|
|
1360
|
+
file_url: Optional[str] = None,
|
|
1361
|
+
options: Optional[RedactOptions] = None,
|
|
1362
|
+
save_output: Optional[Union[str, Path]] = None,
|
|
1363
|
+
max_polls: int = 300,
|
|
1364
|
+
poll_interval: int = 1,
|
|
1365
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
1366
|
+
) -> RedactResult:
|
|
1367
|
+
"""Redact a PDF or image. Inspect verdict/failing_checks before use.
|
|
1368
|
+
|
|
1369
|
+
A completed request can return success=False and an available PDF.
|
|
1370
|
+
save_output saves that PDF too. Completed runs are charged even when
|
|
1371
|
+
verification fails. Redaction reviews the whole document.
|
|
1372
|
+
"""
|
|
1373
|
+
result_data = await self._submit_and_poll(
|
|
1374
|
+
"/api/v1/redact",
|
|
1375
|
+
data=self.get_form_params(
|
|
1376
|
+
file_path=file_path,
|
|
1377
|
+
file_url=file_url,
|
|
1378
|
+
options=options if options is not None else RedactOptions(),
|
|
1379
|
+
),
|
|
1380
|
+
max_polls=max_polls,
|
|
1381
|
+
poll_interval=poll_interval,
|
|
1382
|
+
result_transform=self._normalize_redaction_result,
|
|
1383
|
+
on_progress=on_progress,
|
|
1384
|
+
)
|
|
1385
|
+
result = RedactResult(
|
|
1386
|
+
**{
|
|
1387
|
+
key: value
|
|
1388
|
+
for key, value in result_data.items()
|
|
1389
|
+
if key in RedactResult.__dataclass_fields__
|
|
1390
|
+
}
|
|
1391
|
+
)
|
|
1392
|
+
if save_output and result.output_base64:
|
|
1393
|
+
output_path = Path(save_output)
|
|
1394
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
1395
|
+
result.save_output(output_path)
|
|
1396
|
+
return result
|
|
1397
|
+
|
|
1398
|
+
async def get_redaction_presets(self) -> Dict[str, Any]:
|
|
1399
|
+
"""Get built-in redaction preset IDs, labels, and specifications."""
|
|
1400
|
+
return await self._make_request("GET", "/api/v1/redact/presets")
|
|
1401
|
+
|
|
1268
1402
|
async def fill(
|
|
1269
1403
|
self,
|
|
1270
1404
|
file_path: Optional[Union[str, Path]] = None,
|
|
@@ -1824,6 +1958,7 @@ class AsyncDatalabClient:
|
|
|
1824
1958
|
self,
|
|
1825
1959
|
file_path: Union[str, Path],
|
|
1826
1960
|
processing_location: Optional[str] = None,
|
|
1961
|
+
upload_session: Optional[aiohttp.ClientSession] = None,
|
|
1827
1962
|
) -> UploadedFileMetadata:
|
|
1828
1963
|
"""
|
|
1829
1964
|
Internal method to upload a single file to Datalab storage
|
|
@@ -1871,14 +2006,23 @@ class AsyncDatalabClient:
|
|
|
1871
2006
|
|
|
1872
2007
|
# Step 2: Upload file to presigned URL
|
|
1873
2008
|
try:
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
2009
|
+
if upload_session is None:
|
|
2010
|
+
async with self._signed_url_session() as session:
|
|
2011
|
+
with file_path.open("rb") as file_data:
|
|
2012
|
+
async with session.put(
|
|
2013
|
+
upload_url,
|
|
2014
|
+
data=file_data,
|
|
2015
|
+
headers={"Content-Type": mime_type},
|
|
2016
|
+
) as upload_response:
|
|
2017
|
+
upload_response.raise_for_status()
|
|
2018
|
+
else:
|
|
2019
|
+
with file_path.open("rb") as file_data:
|
|
2020
|
+
async with upload_session.put(
|
|
2021
|
+
upload_url,
|
|
2022
|
+
data=file_data,
|
|
2023
|
+
headers={"Content-Type": mime_type},
|
|
2024
|
+
) as upload_response:
|
|
2025
|
+
upload_response.raise_for_status()
|
|
1882
2026
|
except Exception as e:
|
|
1883
2027
|
raise DatalabFileError(f"Failed to upload file to storage: {str(e)}")
|
|
1884
2028
|
|
|
@@ -1906,6 +2050,8 @@ class AsyncDatalabClient:
|
|
|
1906
2050
|
self,
|
|
1907
2051
|
file_paths: Union[str, Path, list[Union[str, Path]]],
|
|
1908
2052
|
processing_location: Optional[str] = None,
|
|
2053
|
+
*,
|
|
2054
|
+
max_concurrency: int = 5,
|
|
1909
2055
|
) -> Union[UploadedFileMetadata, list[UploadedFileMetadata]]:
|
|
1910
2056
|
"""
|
|
1911
2057
|
Upload one or more files to Datalab storage
|
|
@@ -1915,10 +2061,12 @@ class AsyncDatalabClient:
|
|
|
1915
2061
|
2. Upload the file to the presigned URL
|
|
1916
2062
|
3. Confirm the upload with the API
|
|
1917
2063
|
|
|
1918
|
-
|
|
2064
|
+
Files stream from disk, with at most max_concurrency uploads in flight.
|
|
2065
|
+
Results preserve the input order.
|
|
1919
2066
|
|
|
1920
2067
|
Args:
|
|
1921
2068
|
file_paths: Single file path or list of file paths to upload
|
|
2069
|
+
max_concurrency: Maximum concurrent uploads (default: 5, minimum: 1)
|
|
1922
2070
|
processing_location: Optional residency region (e.g. "eu") for
|
|
1923
2071
|
the stored file. Use the returned reference as file_url in a
|
|
1924
2072
|
request with the same processing_location.
|
|
@@ -1934,16 +2082,36 @@ class AsyncDatalabClient:
|
|
|
1934
2082
|
# Upload multiple files
|
|
1935
2083
|
metadatas = client.upload_files(["doc1.pdf", "doc2.pdf"])
|
|
1936
2084
|
"""
|
|
1937
|
-
|
|
2085
|
+
if type(max_concurrency) is not int or max_concurrency < 1:
|
|
2086
|
+
raise DatalabValidationError("max_concurrency must be a positive integer")
|
|
2087
|
+
|
|
1938
2088
|
if isinstance(file_paths, (str, Path)):
|
|
1939
2089
|
return await self._upload_single_file(file_paths, processing_location)
|
|
2090
|
+
if not file_paths:
|
|
2091
|
+
return []
|
|
1940
2092
|
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
2093
|
+
results = [None] * len(file_paths)
|
|
2094
|
+
pending = iter(enumerate(file_paths))
|
|
2095
|
+
async with self._signed_url_session() as session:
|
|
2096
|
+
|
|
2097
|
+
async def upload_worker():
|
|
2098
|
+
for index, file_path in pending:
|
|
2099
|
+
results[index] = await self._upload_single_file(
|
|
2100
|
+
file_path, processing_location, upload_session=session
|
|
2101
|
+
)
|
|
2102
|
+
|
|
2103
|
+
workers = [
|
|
2104
|
+
asyncio.create_task(upload_worker())
|
|
2105
|
+
for _ in range(min(max_concurrency, len(file_paths)))
|
|
2106
|
+
]
|
|
2107
|
+
try:
|
|
2108
|
+
await asyncio.gather(*workers)
|
|
2109
|
+
finally:
|
|
2110
|
+
# Do not leave uploads running after a failure or cancellation.
|
|
2111
|
+
for worker in workers:
|
|
2112
|
+
worker.cancel()
|
|
2113
|
+
await asyncio.gather(*workers, return_exceptions=True)
|
|
2114
|
+
return results
|
|
1947
2115
|
|
|
1948
2116
|
async def list_files(
|
|
1949
2117
|
self,
|
|
@@ -2716,10 +2884,19 @@ class DatalabClient:
|
|
|
2716
2884
|
"""Run async coroutine in sync context"""
|
|
2717
2885
|
try:
|
|
2718
2886
|
loop = asyncio.get_event_loop()
|
|
2719
|
-
return loop.run_until_complete(self._async_wrapper(coro))
|
|
2720
2887
|
except RuntimeError:
|
|
2721
|
-
#
|
|
2888
|
+
# Only a missing loop should select asyncio.run. RuntimeError from
|
|
2889
|
+
# the operation itself must propagate without rerunning it.
|
|
2890
|
+
return asyncio.run(self._async_wrapper(coro))
|
|
2891
|
+
if loop.is_running():
|
|
2892
|
+
coro.close()
|
|
2893
|
+
raise RuntimeError(
|
|
2894
|
+
"DatalabClient cannot run inside an active event loop; "
|
|
2895
|
+
"use AsyncDatalabClient instead."
|
|
2896
|
+
)
|
|
2897
|
+
if loop.is_closed():
|
|
2722
2898
|
return asyncio.run(self._async_wrapper(coro))
|
|
2899
|
+
return loop.run_until_complete(self._async_wrapper(coro))
|
|
2723
2900
|
|
|
2724
2901
|
async def _async_wrapper(self, coro):
|
|
2725
2902
|
"""Wrapper to ensure session management"""
|
|
@@ -3021,6 +3198,37 @@ class DatalabClient:
|
|
|
3021
3198
|
)
|
|
3022
3199
|
)
|
|
3023
3200
|
|
|
3201
|
+
def redact(
|
|
3202
|
+
self,
|
|
3203
|
+
file_path: Optional[Union[str, Path]] = None,
|
|
3204
|
+
file_url: Optional[str] = None,
|
|
3205
|
+
options: Optional[RedactOptions] = None,
|
|
3206
|
+
save_output: Optional[Union[str, Path]] = None,
|
|
3207
|
+
max_polls: int = 300,
|
|
3208
|
+
poll_interval: int = 1,
|
|
3209
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
3210
|
+
) -> RedactResult:
|
|
3211
|
+
"""Redact a PDF or image. Inspect verdict/failing_checks before use.
|
|
3212
|
+
|
|
3213
|
+
A failed verification can still return a PDF and incur a charge.
|
|
3214
|
+
save_output saves any available PDF, including failed verification.
|
|
3215
|
+
"""
|
|
3216
|
+
return self._run_async(
|
|
3217
|
+
self._async_client.redact(
|
|
3218
|
+
file_path=file_path,
|
|
3219
|
+
file_url=file_url,
|
|
3220
|
+
options=options,
|
|
3221
|
+
save_output=save_output,
|
|
3222
|
+
max_polls=max_polls,
|
|
3223
|
+
poll_interval=poll_interval,
|
|
3224
|
+
on_progress=on_progress,
|
|
3225
|
+
)
|
|
3226
|
+
)
|
|
3227
|
+
|
|
3228
|
+
def get_redaction_presets(self) -> Dict[str, Any]:
|
|
3229
|
+
"""Get built-in redaction preset IDs, labels, and specifications."""
|
|
3230
|
+
return self._run_async(self._async_client.get_redaction_presets())
|
|
3231
|
+
|
|
3024
3232
|
def fill(
|
|
3025
3233
|
self,
|
|
3026
3234
|
file_path: Optional[Union[str, Path]] = None,
|
|
@@ -3194,6 +3402,8 @@ class DatalabClient:
|
|
|
3194
3402
|
self,
|
|
3195
3403
|
file_paths: Union[str, Path, list[Union[str, Path]]],
|
|
3196
3404
|
processing_location: Optional[str] = None,
|
|
3405
|
+
*,
|
|
3406
|
+
max_concurrency: int = 5,
|
|
3197
3407
|
) -> Union[UploadedFileMetadata, list[UploadedFileMetadata]]:
|
|
3198
3408
|
"""
|
|
3199
3409
|
Upload one or more files to Datalab storage (sync version)
|
|
@@ -3203,10 +3413,12 @@ class DatalabClient:
|
|
|
3203
3413
|
2. Upload the file to the presigned URL
|
|
3204
3414
|
3. Confirm the upload with the API
|
|
3205
3415
|
|
|
3206
|
-
|
|
3416
|
+
Files stream from disk, with at most max_concurrency uploads in flight.
|
|
3417
|
+
Results preserve the input order.
|
|
3207
3418
|
|
|
3208
3419
|
Args:
|
|
3209
3420
|
file_paths: Single file path or list of file paths to upload
|
|
3421
|
+
max_concurrency: Maximum concurrent uploads (default: 5, minimum: 1)
|
|
3210
3422
|
processing_location: Optional residency region, e.g. "eu"
|
|
3211
3423
|
|
|
3212
3424
|
Returns:
|
|
@@ -3222,7 +3434,9 @@ class DatalabClient:
|
|
|
3222
3434
|
"""
|
|
3223
3435
|
return self._run_async(
|
|
3224
3436
|
self._async_client.upload_files(
|
|
3225
|
-
file_paths=file_paths,
|
|
3437
|
+
file_paths=file_paths,
|
|
3438
|
+
processing_location=processing_location,
|
|
3439
|
+
max_concurrency=max_concurrency,
|
|
3226
3440
|
)
|
|
3227
3441
|
)
|
|
3228
3442
|
|
|
@@ -231,6 +231,24 @@ class OCROptions(ProcessingOptions):
|
|
|
231
231
|
processing_location: Optional[str] = None # residency region, e.g. "eu"
|
|
232
232
|
|
|
233
233
|
|
|
234
|
+
@dataclass
|
|
235
|
+
class RedactOptions:
|
|
236
|
+
"""Options for whole-document redaction via /redact.
|
|
237
|
+
|
|
238
|
+
A custom spec replaces matching fields of the preset. Provide goal, rules,
|
|
239
|
+
and keep to override all three fields. Redaction does not support
|
|
240
|
+
page_range/max_pages.
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
preset: Optional[str] = "personal_information"
|
|
244
|
+
redaction_spec: Optional[Union[Dict[str, Any], str]] = None
|
|
245
|
+
skip_cache: bool = False
|
|
246
|
+
processing_location: Optional[str] = None
|
|
247
|
+
|
|
248
|
+
def to_form_data(self) -> Dict[str, Any]:
|
|
249
|
+
return ProcessingOptions.to_form_data(self)
|
|
250
|
+
|
|
251
|
+
|
|
234
252
|
@dataclass
|
|
235
253
|
class FormFillingOptions(ProcessingOptions):
|
|
236
254
|
"""Options for form filling via the /fill endpoint.
|
|
@@ -582,6 +600,44 @@ class OCRResult:
|
|
|
582
600
|
)
|
|
583
601
|
|
|
584
602
|
|
|
603
|
+
@dataclass
|
|
604
|
+
class RedactResult:
|
|
605
|
+
"""Redacted PDF and verification report.
|
|
606
|
+
|
|
607
|
+
A completed request can return success=False and an available PDF.
|
|
608
|
+
Inspect verdict and failing_checks before using or sharing the PDF.
|
|
609
|
+
"""
|
|
610
|
+
|
|
611
|
+
status: str
|
|
612
|
+
success: Optional[bool] = None
|
|
613
|
+
error: Optional[str] = None
|
|
614
|
+
verdict: Optional[str] = None
|
|
615
|
+
withheld: Optional[bool] = None
|
|
616
|
+
output_base64: Optional[str] = None
|
|
617
|
+
targets_removed_count: Optional[int] = None
|
|
618
|
+
targets_not_found_count: Optional[int] = None
|
|
619
|
+
failing_checks: Optional[List[Dict[str, Any]]] = None
|
|
620
|
+
boxes_applied: Optional[int] = None
|
|
621
|
+
pages_rewritten: Optional[List[int]] = None
|
|
622
|
+
text_layer_skipped: Optional[List[int]] = None
|
|
623
|
+
runtime: Optional[float] = None
|
|
624
|
+
page_count: Optional[int] = None
|
|
625
|
+
cost_breakdown: Optional[Dict[str, Any]] = None
|
|
626
|
+
versions: Optional[Union[Dict[str, Any], str]] = None
|
|
627
|
+
request_id: Optional[str] = None
|
|
628
|
+
result_url: Optional[str] = None
|
|
629
|
+
expires_in: Optional[int] = None
|
|
630
|
+
progress_percent: Optional[int] = None
|
|
631
|
+
|
|
632
|
+
def save_output(self, output_path: Union[str, Path]) -> None:
|
|
633
|
+
"""Save the available PDF, including one that failed verification."""
|
|
634
|
+
if not self.output_base64:
|
|
635
|
+
raise ValueError("No output data available to save")
|
|
636
|
+
Path(output_path).with_suffix(".pdf").write_bytes(
|
|
637
|
+
base64.b64decode(self.output_base64)
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
|
|
585
641
|
@dataclass
|
|
586
642
|
class FormFillingResult:
|
|
587
643
|
"""Result from form filling"""
|
|
@@ -7,7 +7,7 @@ readme = "README.md"
|
|
|
7
7
|
license = "MIT"
|
|
8
8
|
repository = "https://github.com/datalab-to/sdk"
|
|
9
9
|
keywords = ["datalab", "sdk", "document-intelligence", "api"]
|
|
10
|
-
version = "0.
|
|
10
|
+
version = "0.9.1"
|
|
11
11
|
description = "SDK for the Datalab document intelligence API"
|
|
12
12
|
requires-python = ">=3.11"
|
|
13
13
|
dependencies = [
|
|
@@ -64,3 +64,6 @@ include = ["*.py", "*.pyi"]
|
|
|
64
64
|
|
|
65
65
|
[tool.ruff.lint]
|
|
66
66
|
select = ["E4", "E7", "E9", "F"]
|
|
67
|
+
|
|
68
|
+
[tool.uv]
|
|
69
|
+
exclude-newer = "7 days"
|