datalab-python-sdk 0.8.0__tar.gz → 0.9.0__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.0}/CHANGELOG.md +20 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/PKG-INFO +29 -2
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/README.md +28 -1
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/__init__.py +4 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/client.py +211 -20
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/models.py +56 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/pyproject.toml +4 -1
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_api_consistency.py +10 -0
- datalab_python_sdk-0.9.0/tests/test_transport_audit.py +346 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/uv.lock +8 -4
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/.github/workflows/ci.yml +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/.gitignore +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/.pre-commit-config.yaml +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/.python-version +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/LICENSE +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/08-Lambda-Calculus.pptx +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/adversarial.pdf +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/bid_evaluation.docx +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/book_review.ppt +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/book_store.xls +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/chi_hind.png +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/how_to_read.doc +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/normandy.epub +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/sample-1-sheet.xlsx +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/thinkpython.pdf +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/data/vibe.html +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/auth.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/cli.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/exceptions.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/mimetypes.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/datalab_sdk/settings.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/integration/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/integration/__init__.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/integration/test_live_api.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/integration/test_readme_examples.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/pytest.ini +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/end_to_end_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_api_tutorial/1_get_step_types.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_api_tutorial/2_get_workflows.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_api_tutorial/3_create_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_api_tutorial/4_execute_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_api_tutorial/5_poll_workflow.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_api_tutorial/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_definitions/README.md +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_definitions/eval_segmentation.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_definitions/parse_segment.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_definitions/segment_parallel_extract.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/workflow_definitions/slack_alert.json +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/__init__.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/conftest.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_cli_options.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_cli_simple.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_client_methods.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_device_login.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_errors.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_new_endpoints.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_progress.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_results.py +0 -0
- {datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/tests/test_workflows.py +0 -0
|
@@ -3,6 +3,26 @@
|
|
|
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.0
|
|
7
|
+
|
|
8
|
+
New:
|
|
9
|
+
|
|
10
|
+
- **Open beta:** `redact()` and `get_redaction_presets()` on both clients,
|
|
11
|
+
with `RedactOptions` and `RedactResult`. Results preserve the verification
|
|
12
|
+
verdict and failed checks, including when a completed run returns an
|
|
13
|
+
available PDF with failed verification. Regional signed results use the same
|
|
14
|
+
verified result contract. Use save_output to save the PDF; streaming redaction
|
|
15
|
+
results is not supported. The redaction API may change.
|
|
16
|
+
- `upload_files(..., max_concurrency=5)` bounds active uploads, streams
|
|
17
|
+
files from disk, and reuses storage connections within a batch. Results
|
|
18
|
+
retain input order. Uploads respect the configured request timeout.
|
|
19
|
+
|
|
20
|
+
Fixed:
|
|
21
|
+
|
|
22
|
+
- Synchronous calls propagate an operation's `RuntimeError` without attempting
|
|
23
|
+
to rerun its coroutine. Calling the synchronous client inside an active event
|
|
24
|
+
loop now directs callers to `AsyncDatalabClient`.
|
|
25
|
+
|
|
6
26
|
## 0.8.0
|
|
7
27
|
|
|
8
28
|
New:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: datalab-python-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.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
|
|
@@ -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 |
|
|
@@ -152,6 +175,10 @@ Published-agent execution is in open beta; the API may change. Processor design
|
|
|
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 |
|
|
@@ -131,6 +154,10 @@ Published-agent execution is in open beta; the API may change. Processor design
|
|
|
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,
|
|
@@ -318,6 +320,7 @@ class AsyncDatalabClient:
|
|
|
318
320
|
poll_interval: int = 1,
|
|
319
321
|
stream_response_to: Optional[Path] = None,
|
|
320
322
|
on_progress: Optional[ProgressCallback] = None,
|
|
323
|
+
result_transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
|
|
321
324
|
) -> Union[Dict[str, Any], FileResult]:
|
|
322
325
|
"""Poll for result completion"""
|
|
323
326
|
full_url = (
|
|
@@ -342,6 +345,10 @@ class AsyncDatalabClient:
|
|
|
342
345
|
if status == "complete":
|
|
343
346
|
if not stream_response_to:
|
|
344
347
|
result = await self._resolve_signed_result(data)
|
|
348
|
+
if result_transform is not None:
|
|
349
|
+
result = result_transform(result)
|
|
350
|
+
success = result.get("success", False)
|
|
351
|
+
percent = result.get("progress_percent")
|
|
345
352
|
await progress.report(percent, complete=bool(success))
|
|
346
353
|
return result
|
|
347
354
|
|
|
@@ -645,6 +652,7 @@ class AsyncDatalabClient:
|
|
|
645
652
|
stream_response_to: Optional[Path] = None,
|
|
646
653
|
json: Optional[Dict[str, Any]] = None,
|
|
647
654
|
on_progress: Optional[ProgressCallback] = None,
|
|
655
|
+
result_transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
|
|
648
656
|
) -> Union[Dict[str, Any], FileResult]:
|
|
649
657
|
"""Submit a request and poll for the result.
|
|
650
658
|
|
|
@@ -664,6 +672,11 @@ class AsyncDatalabClient:
|
|
|
664
672
|
poll_interval=poll_interval,
|
|
665
673
|
on_progress=on_progress,
|
|
666
674
|
stream_response_to=stream_response_to,
|
|
675
|
+
**(
|
|
676
|
+
{"result_transform": result_transform}
|
|
677
|
+
if result_transform is not None
|
|
678
|
+
else {}
|
|
679
|
+
),
|
|
667
680
|
)
|
|
668
681
|
if isinstance(result, dict):
|
|
669
682
|
result = dict(result)
|
|
@@ -1265,6 +1278,104 @@ class AsyncDatalabClient:
|
|
|
1265
1278
|
self._save_if_requested(result, save_output)
|
|
1266
1279
|
return result
|
|
1267
1280
|
|
|
1281
|
+
@staticmethod
|
|
1282
|
+
def _normalize_redaction_result(data: Dict[str, Any]) -> Dict[str, Any]:
|
|
1283
|
+
"""Project inline and signed worker results onto the public redaction contract."""
|
|
1284
|
+
result = {
|
|
1285
|
+
key: value
|
|
1286
|
+
for key, value in data.items()
|
|
1287
|
+
if key in RedactResult.__dataclass_fields__
|
|
1288
|
+
}
|
|
1289
|
+
document = (
|
|
1290
|
+
data.get("redacted_document")
|
|
1291
|
+
if "redacted_document" in data
|
|
1292
|
+
else data.get("output_base64")
|
|
1293
|
+
)
|
|
1294
|
+
result["output_base64"] = document or None
|
|
1295
|
+
result["withheld"] = not bool(document)
|
|
1296
|
+
if "redacted_document" in data:
|
|
1297
|
+
checks = [
|
|
1298
|
+
metric
|
|
1299
|
+
for metric in (data.get("verifier_metrics") or [])
|
|
1300
|
+
if isinstance(metric, dict)
|
|
1301
|
+
and metric.get("status") != "pass"
|
|
1302
|
+
and metric.get("severity", "blocking") != "advisory"
|
|
1303
|
+
]
|
|
1304
|
+
else:
|
|
1305
|
+
checks = data.get("failing_checks") or []
|
|
1306
|
+
result["failing_checks"] = [
|
|
1307
|
+
{"id": check["id"]}
|
|
1308
|
+
for check in checks
|
|
1309
|
+
if isinstance(check, dict) and isinstance(check.get("id"), str)
|
|
1310
|
+
]
|
|
1311
|
+
for field in ("targets_removed", "targets_not_found"):
|
|
1312
|
+
if result.get(f"{field}_count") is None and isinstance(
|
|
1313
|
+
data.get(field), list
|
|
1314
|
+
):
|
|
1315
|
+
result[f"{field}_count"] = len(data[field])
|
|
1316
|
+
result["success"] = (
|
|
1317
|
+
bool(document)
|
|
1318
|
+
and data.get("verdict") == "PASS"
|
|
1319
|
+
and not checks
|
|
1320
|
+
and data.get("success") is not False
|
|
1321
|
+
)
|
|
1322
|
+
if result["success"]:
|
|
1323
|
+
result["error"] = None
|
|
1324
|
+
else:
|
|
1325
|
+
result["error"] = (
|
|
1326
|
+
"The PDF is available but did not pass all verification checks. Review failing_checks before using it."
|
|
1327
|
+
if document
|
|
1328
|
+
else "No redacted PDF is available. See failing_checks for verification results."
|
|
1329
|
+
)
|
|
1330
|
+
if result.get("progress_percent") == 100:
|
|
1331
|
+
result["progress_percent"] = None
|
|
1332
|
+
return result
|
|
1333
|
+
|
|
1334
|
+
async def redact(
|
|
1335
|
+
self,
|
|
1336
|
+
file_path: Optional[Union[str, Path]] = None,
|
|
1337
|
+
file_url: Optional[str] = None,
|
|
1338
|
+
options: Optional[RedactOptions] = None,
|
|
1339
|
+
save_output: Optional[Union[str, Path]] = None,
|
|
1340
|
+
max_polls: int = 300,
|
|
1341
|
+
poll_interval: int = 1,
|
|
1342
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
1343
|
+
) -> RedactResult:
|
|
1344
|
+
"""Redact a PDF or image. Inspect verdict/failing_checks before use.
|
|
1345
|
+
|
|
1346
|
+
A completed request can return success=False and an available PDF.
|
|
1347
|
+
save_output saves that PDF too. Completed runs are charged even when
|
|
1348
|
+
verification fails. Redaction reviews the whole document.
|
|
1349
|
+
"""
|
|
1350
|
+
result_data = await self._submit_and_poll(
|
|
1351
|
+
"/api/v1/redact",
|
|
1352
|
+
data=self.get_form_params(
|
|
1353
|
+
file_path=file_path,
|
|
1354
|
+
file_url=file_url,
|
|
1355
|
+
options=options if options is not None else RedactOptions(),
|
|
1356
|
+
),
|
|
1357
|
+
max_polls=max_polls,
|
|
1358
|
+
poll_interval=poll_interval,
|
|
1359
|
+
result_transform=self._normalize_redaction_result,
|
|
1360
|
+
on_progress=on_progress,
|
|
1361
|
+
)
|
|
1362
|
+
result = RedactResult(
|
|
1363
|
+
**{
|
|
1364
|
+
key: value
|
|
1365
|
+
for key, value in result_data.items()
|
|
1366
|
+
if key in RedactResult.__dataclass_fields__
|
|
1367
|
+
}
|
|
1368
|
+
)
|
|
1369
|
+
if save_output and result.output_base64:
|
|
1370
|
+
output_path = Path(save_output)
|
|
1371
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
1372
|
+
result.save_output(output_path)
|
|
1373
|
+
return result
|
|
1374
|
+
|
|
1375
|
+
async def get_redaction_presets(self) -> Dict[str, Any]:
|
|
1376
|
+
"""Get built-in redaction preset IDs, labels, and specifications."""
|
|
1377
|
+
return await self._make_request("GET", "/api/v1/redact/presets")
|
|
1378
|
+
|
|
1268
1379
|
async def fill(
|
|
1269
1380
|
self,
|
|
1270
1381
|
file_path: Optional[Union[str, Path]] = None,
|
|
@@ -1824,6 +1935,7 @@ class AsyncDatalabClient:
|
|
|
1824
1935
|
self,
|
|
1825
1936
|
file_path: Union[str, Path],
|
|
1826
1937
|
processing_location: Optional[str] = None,
|
|
1938
|
+
upload_session: Optional[aiohttp.ClientSession] = None,
|
|
1827
1939
|
) -> UploadedFileMetadata:
|
|
1828
1940
|
"""
|
|
1829
1941
|
Internal method to upload a single file to Datalab storage
|
|
@@ -1871,14 +1983,23 @@ class AsyncDatalabClient:
|
|
|
1871
1983
|
|
|
1872
1984
|
# Step 2: Upload file to presigned URL
|
|
1873
1985
|
try:
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1986
|
+
if upload_session is None:
|
|
1987
|
+
async with self._signed_url_session() as session:
|
|
1988
|
+
with file_path.open("rb") as file_data:
|
|
1989
|
+
async with session.put(
|
|
1990
|
+
upload_url,
|
|
1991
|
+
data=file_data,
|
|
1992
|
+
headers={"Content-Type": mime_type},
|
|
1993
|
+
) as upload_response:
|
|
1994
|
+
upload_response.raise_for_status()
|
|
1995
|
+
else:
|
|
1996
|
+
with file_path.open("rb") as file_data:
|
|
1997
|
+
async with upload_session.put(
|
|
1998
|
+
upload_url,
|
|
1999
|
+
data=file_data,
|
|
2000
|
+
headers={"Content-Type": mime_type},
|
|
2001
|
+
) as upload_response:
|
|
2002
|
+
upload_response.raise_for_status()
|
|
1882
2003
|
except Exception as e:
|
|
1883
2004
|
raise DatalabFileError(f"Failed to upload file to storage: {str(e)}")
|
|
1884
2005
|
|
|
@@ -1906,6 +2027,8 @@ class AsyncDatalabClient:
|
|
|
1906
2027
|
self,
|
|
1907
2028
|
file_paths: Union[str, Path, list[Union[str, Path]]],
|
|
1908
2029
|
processing_location: Optional[str] = None,
|
|
2030
|
+
*,
|
|
2031
|
+
max_concurrency: int = 5,
|
|
1909
2032
|
) -> Union[UploadedFileMetadata, list[UploadedFileMetadata]]:
|
|
1910
2033
|
"""
|
|
1911
2034
|
Upload one or more files to Datalab storage
|
|
@@ -1915,10 +2038,12 @@ class AsyncDatalabClient:
|
|
|
1915
2038
|
2. Upload the file to the presigned URL
|
|
1916
2039
|
3. Confirm the upload with the API
|
|
1917
2040
|
|
|
1918
|
-
|
|
2041
|
+
Files stream from disk, with at most max_concurrency uploads in flight.
|
|
2042
|
+
Results preserve the input order.
|
|
1919
2043
|
|
|
1920
2044
|
Args:
|
|
1921
2045
|
file_paths: Single file path or list of file paths to upload
|
|
2046
|
+
max_concurrency: Maximum concurrent uploads (default: 5, minimum: 1)
|
|
1922
2047
|
processing_location: Optional residency region (e.g. "eu") for
|
|
1923
2048
|
the stored file. Use the returned reference as file_url in a
|
|
1924
2049
|
request with the same processing_location.
|
|
@@ -1934,16 +2059,36 @@ class AsyncDatalabClient:
|
|
|
1934
2059
|
# Upload multiple files
|
|
1935
2060
|
metadatas = client.upload_files(["doc1.pdf", "doc2.pdf"])
|
|
1936
2061
|
"""
|
|
1937
|
-
|
|
2062
|
+
if type(max_concurrency) is not int or max_concurrency < 1:
|
|
2063
|
+
raise DatalabValidationError("max_concurrency must be a positive integer")
|
|
2064
|
+
|
|
1938
2065
|
if isinstance(file_paths, (str, Path)):
|
|
1939
2066
|
return await self._upload_single_file(file_paths, processing_location)
|
|
2067
|
+
if not file_paths:
|
|
2068
|
+
return []
|
|
1940
2069
|
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
2070
|
+
results = [None] * len(file_paths)
|
|
2071
|
+
pending = iter(enumerate(file_paths))
|
|
2072
|
+
async with self._signed_url_session() as session:
|
|
2073
|
+
|
|
2074
|
+
async def upload_worker():
|
|
2075
|
+
for index, file_path in pending:
|
|
2076
|
+
results[index] = await self._upload_single_file(
|
|
2077
|
+
file_path, processing_location, upload_session=session
|
|
2078
|
+
)
|
|
2079
|
+
|
|
2080
|
+
workers = [
|
|
2081
|
+
asyncio.create_task(upload_worker())
|
|
2082
|
+
for _ in range(min(max_concurrency, len(file_paths)))
|
|
2083
|
+
]
|
|
2084
|
+
try:
|
|
2085
|
+
await asyncio.gather(*workers)
|
|
2086
|
+
finally:
|
|
2087
|
+
# Do not leave uploads running after a failure or cancellation.
|
|
2088
|
+
for worker in workers:
|
|
2089
|
+
worker.cancel()
|
|
2090
|
+
await asyncio.gather(*workers, return_exceptions=True)
|
|
2091
|
+
return results
|
|
1947
2092
|
|
|
1948
2093
|
async def list_files(
|
|
1949
2094
|
self,
|
|
@@ -2716,10 +2861,19 @@ class DatalabClient:
|
|
|
2716
2861
|
"""Run async coroutine in sync context"""
|
|
2717
2862
|
try:
|
|
2718
2863
|
loop = asyncio.get_event_loop()
|
|
2719
|
-
return loop.run_until_complete(self._async_wrapper(coro))
|
|
2720
2864
|
except RuntimeError:
|
|
2721
|
-
#
|
|
2865
|
+
# Only a missing loop should select asyncio.run. RuntimeError from
|
|
2866
|
+
# the operation itself must propagate without rerunning it.
|
|
2722
2867
|
return asyncio.run(self._async_wrapper(coro))
|
|
2868
|
+
if loop.is_running():
|
|
2869
|
+
coro.close()
|
|
2870
|
+
raise RuntimeError(
|
|
2871
|
+
"DatalabClient cannot run inside an active event loop; "
|
|
2872
|
+
"use AsyncDatalabClient instead."
|
|
2873
|
+
)
|
|
2874
|
+
if loop.is_closed():
|
|
2875
|
+
return asyncio.run(self._async_wrapper(coro))
|
|
2876
|
+
return loop.run_until_complete(self._async_wrapper(coro))
|
|
2723
2877
|
|
|
2724
2878
|
async def _async_wrapper(self, coro):
|
|
2725
2879
|
"""Wrapper to ensure session management"""
|
|
@@ -3021,6 +3175,37 @@ class DatalabClient:
|
|
|
3021
3175
|
)
|
|
3022
3176
|
)
|
|
3023
3177
|
|
|
3178
|
+
def redact(
|
|
3179
|
+
self,
|
|
3180
|
+
file_path: Optional[Union[str, Path]] = None,
|
|
3181
|
+
file_url: Optional[str] = None,
|
|
3182
|
+
options: Optional[RedactOptions] = None,
|
|
3183
|
+
save_output: Optional[Union[str, Path]] = None,
|
|
3184
|
+
max_polls: int = 300,
|
|
3185
|
+
poll_interval: int = 1,
|
|
3186
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
3187
|
+
) -> RedactResult:
|
|
3188
|
+
"""Redact a PDF or image. Inspect verdict/failing_checks before use.
|
|
3189
|
+
|
|
3190
|
+
A failed verification can still return a PDF and incur a charge.
|
|
3191
|
+
save_output saves any available PDF, including failed verification.
|
|
3192
|
+
"""
|
|
3193
|
+
return self._run_async(
|
|
3194
|
+
self._async_client.redact(
|
|
3195
|
+
file_path=file_path,
|
|
3196
|
+
file_url=file_url,
|
|
3197
|
+
options=options,
|
|
3198
|
+
save_output=save_output,
|
|
3199
|
+
max_polls=max_polls,
|
|
3200
|
+
poll_interval=poll_interval,
|
|
3201
|
+
on_progress=on_progress,
|
|
3202
|
+
)
|
|
3203
|
+
)
|
|
3204
|
+
|
|
3205
|
+
def get_redaction_presets(self) -> Dict[str, Any]:
|
|
3206
|
+
"""Get built-in redaction preset IDs, labels, and specifications."""
|
|
3207
|
+
return self._run_async(self._async_client.get_redaction_presets())
|
|
3208
|
+
|
|
3024
3209
|
def fill(
|
|
3025
3210
|
self,
|
|
3026
3211
|
file_path: Optional[Union[str, Path]] = None,
|
|
@@ -3194,6 +3379,8 @@ class DatalabClient:
|
|
|
3194
3379
|
self,
|
|
3195
3380
|
file_paths: Union[str, Path, list[Union[str, Path]]],
|
|
3196
3381
|
processing_location: Optional[str] = None,
|
|
3382
|
+
*,
|
|
3383
|
+
max_concurrency: int = 5,
|
|
3197
3384
|
) -> Union[UploadedFileMetadata, list[UploadedFileMetadata]]:
|
|
3198
3385
|
"""
|
|
3199
3386
|
Upload one or more files to Datalab storage (sync version)
|
|
@@ -3203,10 +3390,12 @@ class DatalabClient:
|
|
|
3203
3390
|
2. Upload the file to the presigned URL
|
|
3204
3391
|
3. Confirm the upload with the API
|
|
3205
3392
|
|
|
3206
|
-
|
|
3393
|
+
Files stream from disk, with at most max_concurrency uploads in flight.
|
|
3394
|
+
Results preserve the input order.
|
|
3207
3395
|
|
|
3208
3396
|
Args:
|
|
3209
3397
|
file_paths: Single file path or list of file paths to upload
|
|
3398
|
+
max_concurrency: Maximum concurrent uploads (default: 5, minimum: 1)
|
|
3210
3399
|
processing_location: Optional residency region, e.g. "eu"
|
|
3211
3400
|
|
|
3212
3401
|
Returns:
|
|
@@ -3222,7 +3411,9 @@ class DatalabClient:
|
|
|
3222
3411
|
"""
|
|
3223
3412
|
return self._run_async(
|
|
3224
3413
|
self._async_client.upload_files(
|
|
3225
|
-
file_paths=file_paths,
|
|
3414
|
+
file_paths=file_paths,
|
|
3415
|
+
processing_location=processing_location,
|
|
3416
|
+
max_concurrency=max_concurrency,
|
|
3226
3417
|
)
|
|
3227
3418
|
)
|
|
3228
3419
|
|
|
@@ -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.0"
|
|
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"
|
|
@@ -20,6 +20,7 @@ from datalab_sdk.models import (
|
|
|
20
20
|
ExtractOptions,
|
|
21
21
|
FormFieldsOptions,
|
|
22
22
|
FormFillingOptions,
|
|
23
|
+
RedactOptions,
|
|
23
24
|
OCROptions,
|
|
24
25
|
SegmentOptions,
|
|
25
26
|
TrackChangesOptions,
|
|
@@ -132,6 +133,14 @@ API_FIELDS = {
|
|
|
132
133
|
"skip_cache",
|
|
133
134
|
"processing_location",
|
|
134
135
|
},
|
|
136
|
+
"/api/v1/redact": {
|
|
137
|
+
"file",
|
|
138
|
+
"file_url",
|
|
139
|
+
"preset",
|
|
140
|
+
"redaction_spec",
|
|
141
|
+
"skip_cache",
|
|
142
|
+
"processing_location",
|
|
143
|
+
},
|
|
135
144
|
"/api/v1/agent": {
|
|
136
145
|
"file",
|
|
137
146
|
"file_url",
|
|
@@ -221,6 +230,7 @@ INFERENCE_CASES = [
|
|
|
221
230
|
("track_changes", "/api/v1/track-changes", TrackChangesOptions, {}, ()),
|
|
222
231
|
("form_fields", "/api/v1/form-fields", FormFieldsOptions, {}, ()),
|
|
223
232
|
("fill", "/api/v1/fill", FormFillingOptions, {}, ("max_pages",)),
|
|
233
|
+
("redact", "/api/v1/redact", RedactOptions, {}, ()),
|
|
224
234
|
("run_agent", "/api/v1/agent", AgentOptions, {"processor": "cp_1"}, ()),
|
|
225
235
|
("ocr", "/api/v1/ocr", OCROptions, {}, ()),
|
|
226
236
|
]
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""Regression checks for public redaction and bounded storage uploads."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import base64
|
|
5
|
+
import io
|
|
6
|
+
from unittest.mock import AsyncMock, patch
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
from aiohttp import web
|
|
10
|
+
from aiohttp.test_utils import TestServer
|
|
11
|
+
|
|
12
|
+
from datalab_sdk import AsyncDatalabClient, DatalabClient, RedactOptions
|
|
13
|
+
from datalab_sdk.exceptions import DatalabFileError, DatalabValidationError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.mark.asyncio
|
|
17
|
+
@pytest.mark.parametrize("failed", [False, True])
|
|
18
|
+
async def test_redaction_wire_contract_and_verification(tmp_path, failed):
|
|
19
|
+
received = {}
|
|
20
|
+
pdf = b"%PDF-1.4 redacted"
|
|
21
|
+
|
|
22
|
+
async def submit(request):
|
|
23
|
+
received.update(await request.post())
|
|
24
|
+
return web.json_response(
|
|
25
|
+
{
|
|
26
|
+
"success": True,
|
|
27
|
+
"request_id": "red_1",
|
|
28
|
+
"request_check_url": "/api/v1/redact/red_1",
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
async def result(request):
|
|
33
|
+
return web.json_response(
|
|
34
|
+
{
|
|
35
|
+
"status": "complete",
|
|
36
|
+
"success": not failed,
|
|
37
|
+
"verdict": "FAIL" if failed else "PASS",
|
|
38
|
+
"withheld": False,
|
|
39
|
+
"failing_checks": [{"id": "review"}] if failed else [],
|
|
40
|
+
"output_base64": base64.b64encode(pdf).decode(),
|
|
41
|
+
"pages_rewritten": [0],
|
|
42
|
+
"targets_removed_count": 2,
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
async def presets(request):
|
|
47
|
+
return web.json_response({"presets": [{"id": "personal_information"}]})
|
|
48
|
+
|
|
49
|
+
app = web.Application()
|
|
50
|
+
app.router.add_post("/api/v1/redact", submit)
|
|
51
|
+
app.router.add_get("/api/v1/redact/presets", presets)
|
|
52
|
+
app.router.add_get("/api/v1/redact/red_1", result)
|
|
53
|
+
async with TestServer(app) as server:
|
|
54
|
+
async with AsyncDatalabClient(
|
|
55
|
+
api_key="secret", base_url=str(server.make_url(""))
|
|
56
|
+
) as client:
|
|
57
|
+
progress = []
|
|
58
|
+
redacted = await client.redact(
|
|
59
|
+
file_url="https://example.org/input.pdf",
|
|
60
|
+
options=RedactOptions(redaction_spec={"goal": "Remove identifiers"}),
|
|
61
|
+
save_output=tmp_path / "redacted",
|
|
62
|
+
on_progress=progress.append,
|
|
63
|
+
)
|
|
64
|
+
assert await client.get_redaction_presets() == {
|
|
65
|
+
"presets": [{"id": "personal_information"}]
|
|
66
|
+
}
|
|
67
|
+
assert received["preset"] == "personal_information"
|
|
68
|
+
assert received["redaction_spec"] == '{\n "goal": "Remove identifiers"\n}'
|
|
69
|
+
assert set(received) == {"file_url", "preset", "redaction_spec", "skip_cache"}
|
|
70
|
+
assert redacted.request_id == "red_1"
|
|
71
|
+
assert redacted.success is not failed
|
|
72
|
+
assert redacted.verdict == ("FAIL" if failed else "PASS")
|
|
73
|
+
assert redacted.failing_checks == ([{"id": "review"}] if failed else [])
|
|
74
|
+
assert redacted.pages_rewritten == [0]
|
|
75
|
+
assert (tmp_path / "redacted.pdf").read_bytes() == pdf
|
|
76
|
+
assert progress == ([] if failed else [100])
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@pytest.mark.asyncio
|
|
80
|
+
async def test_upload_streams_and_bounds_concurrency_in_order(tmp_path):
|
|
81
|
+
paths = [tmp_path / f"{index}.pdf" for index in range(7)]
|
|
82
|
+
for path in paths:
|
|
83
|
+
path.write_bytes((path.name * 100).encode())
|
|
84
|
+
active = 0
|
|
85
|
+
peak = 0
|
|
86
|
+
connections = set()
|
|
87
|
+
received = {}
|
|
88
|
+
|
|
89
|
+
async def sign(request):
|
|
90
|
+
data = await request.json()
|
|
91
|
+
name = data["filename"]
|
|
92
|
+
assert data["processing_location"] == "eu"
|
|
93
|
+
return web.json_response(
|
|
94
|
+
{
|
|
95
|
+
"file_id": name,
|
|
96
|
+
"upload_url": str(server.make_url(f"/storage/{name}")),
|
|
97
|
+
"reference": f"datalab://{name}",
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
async def upload(request):
|
|
102
|
+
nonlocal active, peak
|
|
103
|
+
assert "X-Api-Key" not in request.headers
|
|
104
|
+
assert request.content_type == "application/pdf"
|
|
105
|
+
connections.add(request.transport)
|
|
106
|
+
active += 1
|
|
107
|
+
peak = max(peak, active)
|
|
108
|
+
await asyncio.sleep(0.01)
|
|
109
|
+
received[request.match_info["name"]] = await request.read()
|
|
110
|
+
active -= 1
|
|
111
|
+
return web.Response()
|
|
112
|
+
|
|
113
|
+
async def confirm(request):
|
|
114
|
+
return web.json_response({"created": None})
|
|
115
|
+
|
|
116
|
+
app = web.Application()
|
|
117
|
+
app.router.add_post("/api/v1/files/upload", sign)
|
|
118
|
+
app.router.add_put("/storage/{name}", upload)
|
|
119
|
+
app.router.add_get("/api/v1/files/{file_id}/confirm", confirm)
|
|
120
|
+
async with TestServer(app) as server:
|
|
121
|
+
async with AsyncDatalabClient(
|
|
122
|
+
api_key="secret", base_url=str(server.make_url(""))
|
|
123
|
+
) as client:
|
|
124
|
+
# File uploads must use file handles rather than copying whole files.
|
|
125
|
+
original_put = __import__("aiohttp").ClientSession.put
|
|
126
|
+
|
|
127
|
+
def check_put(session, url, **kwargs):
|
|
128
|
+
assert isinstance(kwargs["data"], io.BufferedIOBase)
|
|
129
|
+
assert session.timeout.total == client.timeout
|
|
130
|
+
return original_put(session, url, **kwargs)
|
|
131
|
+
|
|
132
|
+
with patch("aiohttp.ClientSession.put", new=check_put):
|
|
133
|
+
result = await client.upload_files(
|
|
134
|
+
paths, processing_location="eu", max_concurrency=2
|
|
135
|
+
)
|
|
136
|
+
assert [item.original_filename for item in result] == [p.name for p in paths]
|
|
137
|
+
assert received == {path.name: path.read_bytes() for path in paths}
|
|
138
|
+
assert peak == 2
|
|
139
|
+
assert len(connections) <= 2
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@pytest.mark.asyncio
|
|
143
|
+
async def test_upload_failure_cancels_other_workers(tmp_path):
|
|
144
|
+
started = asyncio.Event()
|
|
145
|
+
stopped = asyncio.Event()
|
|
146
|
+
client = AsyncDatalabClient(api_key="k")
|
|
147
|
+
|
|
148
|
+
async def upload(path, *args, **kwargs):
|
|
149
|
+
if path == "fail":
|
|
150
|
+
await started.wait()
|
|
151
|
+
raise DatalabFileError("broken upload")
|
|
152
|
+
started.set()
|
|
153
|
+
try:
|
|
154
|
+
await asyncio.Event().wait()
|
|
155
|
+
finally:
|
|
156
|
+
stopped.set()
|
|
157
|
+
|
|
158
|
+
with patch.object(client, "_upload_single_file", new=upload):
|
|
159
|
+
with pytest.raises(DatalabFileError, match="broken upload"):
|
|
160
|
+
await client.upload_files(["fail", "waiting", "never"], max_concurrency=2)
|
|
161
|
+
assert stopped.is_set()
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@pytest.mark.asyncio
|
|
165
|
+
@pytest.mark.parametrize("limit", [0, -1, True, 1.5])
|
|
166
|
+
async def test_upload_rejects_invalid_concurrency(limit):
|
|
167
|
+
client = AsyncDatalabClient(api_key="k")
|
|
168
|
+
with pytest.raises(DatalabValidationError, match="max_concurrency"):
|
|
169
|
+
await client.upload_files([], max_concurrency=limit)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def test_sync_operation_runtime_error_propagates_once():
|
|
173
|
+
client = DatalabClient(api_key="k")
|
|
174
|
+
calls = 0
|
|
175
|
+
|
|
176
|
+
async def fail():
|
|
177
|
+
nonlocal calls
|
|
178
|
+
calls += 1
|
|
179
|
+
raise RuntimeError("operation failed")
|
|
180
|
+
|
|
181
|
+
loop = asyncio.new_event_loop()
|
|
182
|
+
asyncio.set_event_loop(loop)
|
|
183
|
+
try:
|
|
184
|
+
with pytest.raises(RuntimeError, match="^operation failed$"):
|
|
185
|
+
client._run_async(fail())
|
|
186
|
+
finally:
|
|
187
|
+
loop.close()
|
|
188
|
+
asyncio.set_event_loop(None)
|
|
189
|
+
assert calls == 1
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@pytest.mark.asyncio
|
|
193
|
+
async def test_sync_client_in_async_loop_gives_actionable_error():
|
|
194
|
+
with pytest.raises(RuntimeError, match="use AsyncDatalabClient"):
|
|
195
|
+
DatalabClient(api_key="k").get_redaction_presets()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_sync_redaction_forwards_options_and_progress():
|
|
199
|
+
client = DatalabClient(api_key="k")
|
|
200
|
+
options = RedactOptions(preset="financial_details")
|
|
201
|
+
|
|
202
|
+
def progress(value):
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
with patch.object(client._async_client, "redact", new_callable=AsyncMock) as redact:
|
|
206
|
+
client.redact(
|
|
207
|
+
file_url="https://example.org/a.pdf", options=options, on_progress=progress
|
|
208
|
+
)
|
|
209
|
+
assert redact.await_args.kwargs["options"] is options
|
|
210
|
+
assert redact.await_args.kwargs["on_progress"] is progress
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@pytest.mark.asyncio
|
|
214
|
+
@pytest.mark.parametrize(
|
|
215
|
+
"verdict,has_pdf,upstream_success,expected_success",
|
|
216
|
+
[
|
|
217
|
+
("PASS", True, True, True),
|
|
218
|
+
("FAIL", True, True, False),
|
|
219
|
+
("FAIL", False, False, False),
|
|
220
|
+
("PASS", True, False, False),
|
|
221
|
+
(None, True, True, False),
|
|
222
|
+
],
|
|
223
|
+
)
|
|
224
|
+
async def test_regional_redaction_normalizes_signed_worker_result(
|
|
225
|
+
tmp_path, verdict, has_pdf, upstream_success, expected_success
|
|
226
|
+
):
|
|
227
|
+
pdf = b"%PDF-1.4 regional output"
|
|
228
|
+
received = {}
|
|
229
|
+
progress = []
|
|
230
|
+
|
|
231
|
+
async def submit(request):
|
|
232
|
+
received.update(await request.post())
|
|
233
|
+
assert request.headers["X-Api-Key"] == "secret"
|
|
234
|
+
return web.json_response(
|
|
235
|
+
{"success": True, "request_id": "regional", "request_check_url": "/check"}
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
async def check(request):
|
|
239
|
+
return web.json_response(
|
|
240
|
+
{
|
|
241
|
+
"status": "complete",
|
|
242
|
+
"success": upstream_success,
|
|
243
|
+
"result_url": str(server.make_url("/signed")),
|
|
244
|
+
"expires_in": 600,
|
|
245
|
+
"page_count": 2,
|
|
246
|
+
"progress_percent": 100,
|
|
247
|
+
}
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
async def signed(request):
|
|
251
|
+
assert "X-Api-Key" not in request.headers
|
|
252
|
+
return web.json_response(
|
|
253
|
+
{
|
|
254
|
+
"success": upstream_success,
|
|
255
|
+
"output_shape": "redact",
|
|
256
|
+
"verdict": verdict,
|
|
257
|
+
"redacted_document": base64.b64encode(pdf).decode()
|
|
258
|
+
if has_pdf
|
|
259
|
+
else None,
|
|
260
|
+
"verifier_metrics": [
|
|
261
|
+
{
|
|
262
|
+
"id": "pii",
|
|
263
|
+
"status": "fail" if verdict != "PASS" else "pass",
|
|
264
|
+
"severity": "blocking",
|
|
265
|
+
"detail": "private document text",
|
|
266
|
+
},
|
|
267
|
+
{"id": "advice", "status": "fail", "severity": "advisory"},
|
|
268
|
+
],
|
|
269
|
+
"targets_removed_count": 3,
|
|
270
|
+
"targets_not_found_count": 1,
|
|
271
|
+
"targets_removed": [{"text": "private document text"}],
|
|
272
|
+
"pages_rewritten": [0],
|
|
273
|
+
"error": "private document text",
|
|
274
|
+
}
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
app = web.Application()
|
|
278
|
+
app.router.add_post("/api/v1/redact", submit)
|
|
279
|
+
app.router.add_get("/check", check)
|
|
280
|
+
app.router.add_get("/signed", signed)
|
|
281
|
+
async with TestServer(app) as server:
|
|
282
|
+
async with AsyncDatalabClient(
|
|
283
|
+
api_key="secret", base_url=str(server.make_url(""))
|
|
284
|
+
) as client:
|
|
285
|
+
result = await client.redact(
|
|
286
|
+
file_url="https://example.org/input.pdf",
|
|
287
|
+
options=RedactOptions(processing_location="eu"),
|
|
288
|
+
save_output=tmp_path / "regional.pdf",
|
|
289
|
+
on_progress=progress.append,
|
|
290
|
+
)
|
|
291
|
+
assert received["processing_location"] == "eu"
|
|
292
|
+
assert result.request_id == "regional"
|
|
293
|
+
assert result.result_url.endswith("/signed")
|
|
294
|
+
assert result.expires_in == 600
|
|
295
|
+
assert result.page_count == 2
|
|
296
|
+
assert result.status == "complete"
|
|
297
|
+
assert result.verdict == verdict
|
|
298
|
+
assert result.success is expected_success
|
|
299
|
+
assert result.withheld is not has_pdf
|
|
300
|
+
assert result.failing_checks == ([{"id": "pii"}] if verdict != "PASS" else [])
|
|
301
|
+
assert result.targets_removed_count == 3
|
|
302
|
+
assert result.pages_rewritten == [0]
|
|
303
|
+
assert "private document text" not in repr(result)
|
|
304
|
+
assert progress == ([100] if expected_success else [])
|
|
305
|
+
assert result.progress_percent == (100 if expected_success else None)
|
|
306
|
+
if has_pdf:
|
|
307
|
+
assert (tmp_path / "regional.pdf").read_bytes() == pdf
|
|
308
|
+
else:
|
|
309
|
+
assert not (tmp_path / "regional.pdf").exists()
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def test_redaction_helpers_do_not_offer_unverified_streaming():
|
|
313
|
+
import inspect
|
|
314
|
+
|
|
315
|
+
for method in (AsyncDatalabClient.redact, DatalabClient.redact):
|
|
316
|
+
assert "stream_response_to" not in inspect.signature(method).parameters
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@pytest.mark.parametrize("worker_shape", [False, True])
|
|
320
|
+
def test_redaction_rejects_contradictory_verdict_and_counts_legacy_targets(
|
|
321
|
+
worker_shape,
|
|
322
|
+
):
|
|
323
|
+
data = {
|
|
324
|
+
"status": "complete",
|
|
325
|
+
"success": True,
|
|
326
|
+
"verdict": "PASS",
|
|
327
|
+
"progress_percent": 100,
|
|
328
|
+
"targets_removed": [{"text": "private name"}],
|
|
329
|
+
"targets_not_found": ["private address", "private number"],
|
|
330
|
+
}
|
|
331
|
+
if worker_shape:
|
|
332
|
+
data.update(
|
|
333
|
+
redacted_document="cGRm",
|
|
334
|
+
verifier_metrics=[{"id": "pii", "severity": "blocking", "status": "fail"}],
|
|
335
|
+
)
|
|
336
|
+
else:
|
|
337
|
+
data.update(output_base64="cGRm", failing_checks=[{"id": "pii"}])
|
|
338
|
+
result = AsyncDatalabClient._normalize_redaction_result(data)
|
|
339
|
+
assert result["success"] is False
|
|
340
|
+
assert result["progress_percent"] is None
|
|
341
|
+
assert result["withheld"] is False
|
|
342
|
+
assert result["failing_checks"] == [{"id": "pii"}]
|
|
343
|
+
assert result["targets_removed_count"] == 1
|
|
344
|
+
assert result["targets_not_found_count"] == 2
|
|
345
|
+
assert "private name" not in repr(result)
|
|
346
|
+
assert "private address" not in repr(result)
|
|
@@ -2,6 +2,10 @@ version = 1
|
|
|
2
2
|
revision = 5
|
|
3
3
|
requires-python = ">=3.11"
|
|
4
4
|
|
|
5
|
+
[options]
|
|
6
|
+
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
|
|
7
|
+
exclude-newer-span = "P7D"
|
|
8
|
+
|
|
5
9
|
[[package]]
|
|
6
10
|
name = "aiohappyeyeballs"
|
|
7
11
|
version = "2.6.1"
|
|
@@ -234,7 +238,7 @@ wheels = [
|
|
|
234
238
|
|
|
235
239
|
[[package]]
|
|
236
240
|
name = "datalab-python-sdk"
|
|
237
|
-
version = "0.
|
|
241
|
+
version = "0.9.0"
|
|
238
242
|
source = { editable = "." }
|
|
239
243
|
dependencies = [
|
|
240
244
|
{ name = "aiohttp" },
|
|
@@ -1234,7 +1238,7 @@ wheels = [
|
|
|
1234
1238
|
|
|
1235
1239
|
[[package]]
|
|
1236
1240
|
name = "virtualenv"
|
|
1237
|
-
version = "21.14.
|
|
1241
|
+
version = "21.14.13"
|
|
1238
1242
|
source = { registry = "https://pypi.org/simple" }
|
|
1239
1243
|
dependencies = [
|
|
1240
1244
|
{ name = "distlib" },
|
|
@@ -1243,9 +1247,9 @@ dependencies = [
|
|
|
1243
1247
|
{ name = "platformdirs" },
|
|
1244
1248
|
{ name = "python-discovery" },
|
|
1245
1249
|
]
|
|
1246
|
-
sdist = { url = "https://files.pythonhosted.org/packages/
|
|
1250
|
+
sdist = { url = "https://files.pythonhosted.org/packages/70/aa/bff50daee0488e16d611258a9b6c5a1d0c9e128f8ca424e9f4e1c0444ef2/virtualenv-21.14.13.tar.gz", hash = "sha256:de5307ba4b9a0001d9c8ea02832d38f63ca432880f416c1bface61c4323fd905", size = 5570301, upload-time = "2026-10-22T20:10:16.952Z" }
|
|
1247
1251
|
wheels = [
|
|
1248
|
-
{ url = "https://files.pythonhosted.org/packages/
|
|
1252
|
+
{ url = "https://files.pythonhosted.org/packages/bb/a9/c10d8a44a29fb94a18b43fdf11f38caca53ae7c9406f11a72b1cb8f624f1/virtualenv-21.14.13-py3-none-any.whl", hash = "sha256:5fbb04138a4861580b78ba9110d529a26bc48fcc93c8ec36bc0202eeed96a788", size = 5557094, upload-time = "2026-10-22T20:10:15.096Z" },
|
|
1249
1253
|
]
|
|
1250
1254
|
|
|
1251
1255
|
[[package]]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{datalab_python_sdk-0.8.0 → datalab_python_sdk-0.9.0}/recipes/workflows/end_to_end_workflow.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|