datalab-python-sdk 0.14.0__tar.gz → 0.16.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.
Files changed (72) hide show
  1. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/CHANGELOG.md +94 -0
  2. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/PKG-INFO +12 -7
  3. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/README.md +11 -6
  4. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/__init__.py +10 -10
  5. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/_output_layout.py +4 -2
  6. datalab_python_sdk-0.16.0/datalab_sdk/_output_names.py +31 -0
  7. datalab_python_sdk-0.16.0/datalab_sdk/_status.py +119 -0
  8. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/cli.py +18 -458
  9. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/client.py +870 -676
  10. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/exceptions.py +64 -1
  11. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/models.py +81 -145
  12. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/pyproject.toml +1 -1
  13. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_cli_exit_codes.py +28 -1
  14. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_cli_output_layout.py +13 -0
  15. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_comparisons.py +10 -0
  16. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_new_endpoints.py +63 -32
  17. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_results.py +36 -0
  18. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_streaming_retries.py +14 -2
  19. datalab_python_sdk-0.16.0/tests/test_submit_and_check.py +800 -0
  20. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/uv.lock +1 -1
  21. datalab_python_sdk-0.14.0/recipes/workflows/README.md +0 -102
  22. datalab_python_sdk-0.14.0/recipes/workflows/end_to_end_workflow.py +0 -205
  23. datalab_python_sdk-0.14.0/recipes/workflows/workflow_api_tutorial/1_get_step_types.py +0 -60
  24. datalab_python_sdk-0.14.0/recipes/workflows/workflow_api_tutorial/2_get_workflows.py +0 -47
  25. datalab_python_sdk-0.14.0/recipes/workflows/workflow_api_tutorial/3_create_workflow.py +0 -156
  26. datalab_python_sdk-0.14.0/recipes/workflows/workflow_api_tutorial/4_execute_workflow.py +0 -63
  27. datalab_python_sdk-0.14.0/recipes/workflows/workflow_api_tutorial/5_poll_workflow.py +0 -125
  28. datalab_python_sdk-0.14.0/recipes/workflows/workflow_api_tutorial/README.md +0 -143
  29. datalab_python_sdk-0.14.0/recipes/workflows/workflow_definitions/README.md +0 -190
  30. datalab_python_sdk-0.14.0/recipes/workflows/workflow_definitions/eval_segmentation.json +0 -71
  31. datalab_python_sdk-0.14.0/recipes/workflows/workflow_definitions/parse_segment.json +0 -22
  32. datalab_python_sdk-0.14.0/recipes/workflows/workflow_definitions/segment_parallel_extract.json +0 -113
  33. datalab_python_sdk-0.14.0/recipes/workflows/workflow_definitions/slack_alert.json +0 -41
  34. datalab_python_sdk-0.14.0/tests/test_workflows.py +0 -460
  35. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/.github/workflows/ci.yml +0 -0
  36. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/.gitignore +0 -0
  37. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/.pre-commit-config.yaml +0 -0
  38. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/.python-version +0 -0
  39. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/LICENSE +0 -0
  40. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/08-Lambda-Calculus.pptx +0 -0
  41. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/adversarial.pdf +0 -0
  42. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/bid_evaluation.docx +0 -0
  43. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/book_review.ppt +0 -0
  44. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/book_store.xls +0 -0
  45. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/chi_hind.png +0 -0
  46. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/how_to_read.doc +0 -0
  47. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/normandy.epub +0 -0
  48. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/sample-1-sheet.xlsx +0 -0
  49. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/thinkpython.pdf +0 -0
  50. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/data/vibe.html +0 -0
  51. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/auth.py +0 -0
  52. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/mimetypes.py +0 -0
  53. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/datalab_sdk/settings.py +0 -0
  54. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/integration/README.md +0 -0
  55. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/integration/__init__.py +0 -0
  56. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/integration/test_live_api.py +0 -0
  57. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/integration/test_readme_examples.py +0 -0
  58. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/pytest.ini +0 -0
  59. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/__init__.py +0 -0
  60. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/conftest.py +0 -0
  61. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_api_consistency.py +0 -0
  62. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_api_key_resolution.py +0 -0
  63. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_cli_options.py +0 -0
  64. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_cli_simple.py +0 -0
  65. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_client_methods.py +0 -0
  66. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_device_login.py +0 -0
  67. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_errors.py +0 -0
  68. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_import_warnings.py +0 -0
  69. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_progress.py +0 -0
  70. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_sync_client_errors.py +0 -0
  71. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_timeout_recovery.py +0 -0
  72. {datalab_python_sdk-0.14.0 → datalab_python_sdk-0.16.0}/tests/test_transport_audit.py +0 -0
@@ -3,6 +3,100 @@
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.16.0
7
+
8
+ Added:
9
+
10
+ - Submit a document request without waiting for it, then check on it
11
+ later. `submit_convert()`, `submit_extract()`, `submit_segment()`,
12
+ `submit_agent()`, `submit_track_changes()`, `submit_create_document()`,
13
+ `submit_fill()`, `submit_form_fields()` and `submit_redact()` take the
14
+ same arguments as the blocking methods, check them the same way, and
15
+ return a `SubmittedRequest` with `request_id`, `check_url` and
16
+ `checkpoint_reused`. They do not poll.
17
+ - `check_status()` checks once whether a submitted request has finished
18
+ and returns a `RequestStatus` with `done`, `success`, `error` and
19
+ `progress_percent`; `error` is None for a success. It never returns the
20
+ result: call `get_result()` once `done` is True. It asks the API to leave the result out and reads
21
+ at most about 1 MB of a response. When an API version sends a larger
22
+ finished result anyway, `success` and `error` are None; check
23
+ `result.success` after `get_result()`. Check `success` first, because most
24
+ processing failures finish with `success=False`. It makes one status
25
+ request and does not retry it; an error it raises has `request_id` and
26
+ `check_url`.
27
+ - Use these calls when something else waits between checks, such as a
28
+ scheduler or a job queue. They work like `run_pipeline()` and
29
+ `get_pipeline_execution()` do for pipelines. `submit_agent()` is open
30
+ beta and `submit_redact()` is beta, like `run_agent()` and `redact()`.
31
+ - `DatalabProcessingError` and `DatalabResponseError`, both subclasses of
32
+ `DatalabAPIError`. The first means the API reported that the request
33
+ failed before it completed, for example an expired on-prem request; the
34
+ second means `check_status()` could not read the status response. From
35
+ `check_status()` both carry the response's HTTP `status_code`, so they
36
+ are not mistaken for connection errors.
37
+ - `DatalabError.retryable`: True when making the same call again later may
38
+ succeed and is safe. For `check_status()` and `get_result()`, that is a
39
+ timeout, a dropped connection, HTTP 408 or 429, or a 5xx; the SDK's own
40
+ poll retries use the same rule. For a submission, it is only HTTP 429 or
41
+ 503: after any other error the API may have accepted the request, and
42
+ sending it again could charge for it twice. `check_status()` does not
43
+ retry, so check again when its error's `retryable` is True.
44
+
45
+ Changed:
46
+
47
+ - When a poll reports `success=False` before the request is complete, the
48
+ processing methods raise `DatalabProcessingError` instead of a plain
49
+ `DatalabAPIError`. Code that catches `DatalabAPIError` still catches it.
50
+ - A streamed poll (`stream_response_to`) whose response has no `status`
51
+ raises `DatalabResponseError` with the HTTP status, at once. It raised a
52
+ `DatalabAPIError` with no `status_code`, which the SDK retried as a
53
+ connection error.
54
+ - A poll of a request that the team's page quota rejected (HTTP 429)
55
+ raises `DatalabProcessingError` at once. The SDK retried it as a rate
56
+ limit, though the request had already failed.
57
+ - Polls no longer retry a transport error that would happen again, such
58
+ as an invalid URL, a redirect to another scheme, or a certificate
59
+ failure. Dropped connections and cut-off bodies are still retried.
60
+
61
+ ## 0.15.0
62
+
63
+ Removed:
64
+
65
+ - The workflow methods (`create_workflow`, `get_workflow`, `list_workflows`,
66
+ `delete_workflow`, `execute_workflow`, `get_execution_status`,
67
+ `get_step_types`), their models (`Workflow`, `WorkflowStep`,
68
+ `WorkflowExecution`, `InputConfig`) and the workflow CLI commands,
69
+ including `visualize-workflow`. The API removed the Workflows API, so these
70
+ methods already failed with a 404. Use pipelines.
71
+
72
+ Deprecated:
73
+
74
+ - The custom processor management methods (`list_custom_processors`,
75
+ `get_custom_processor_status`, `list_custom_processor_versions`,
76
+ `set_active_processor_version`, `archive_custom_processor`) warn. Their
77
+ `/api/v1/custom_processors` routes are deprecated, and the sunset date
78
+ (October 31, 2026) has passed, so they can stop responding without
79
+ further notice. `run_custom_processor()` and `run_custom_pipeline()`
80
+ already warned. Run processors with `run_agent()` and
81
+ `AgentOptions(processor="cp_XXXXX")`.
82
+
83
+ Fixed:
84
+
85
+ - `save_output()` keeps every dot in the name you pass, so
86
+ `save_output("output/v1.2.report")` writes `v1.2.report.md`. Before, it
87
+ wrote `v1.2.md`. A path that ends in an extension `save_output()` writes or
88
+ a document type the API reads, such as `report.md` or `scan.jpg`, still has
89
+ that one extension replaced, as before. The CLI keeps the whole stem of an
90
+ input: `v1.2.report.pdf` saves `v1.2.report.md`, and `report.json.pdf`
91
+ saves `report.json.md` (before, `v1.2.md` and `report.md`).
92
+ - `datalab compare get` and `compare run --wait` list each file's ID and
93
+ status. When a file completed, they print the `compare differences`
94
+ command that takes the ID.
95
+ - The `file_id` docstrings of `get_file_metadata()`,
96
+ `get_file_download_url()` and `delete_file()` no longer say a hashid works:
97
+ the API takes the integer `file_id`.
98
+ - The `custom-pipeline` CLI help and warning give the passed sunset date.
99
+
6
100
  ## 0.14.0
7
101
 
8
102
  Behavior changes:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datalab-python-sdk
3
- Version: 0.14.0
3
+ Version: 0.16.0
4
4
  Summary: SDK for the Datalab document intelligence API
5
5
  Project-URL: Homepage, https://www.datalab.to
6
6
  Project-URL: Documentation, https://documentation.datalab.to
@@ -35,7 +35,7 @@ pip install datalab-python-sdk
35
35
 
36
36
  ### Authentication
37
37
 
38
- [Sign up](https://www.datalab.to/?utm_source=gh-sdk), then get your API key from [https://www.datalab.to/app/keys](https://www.datalab.to/app/keys):
38
+ [Sign up](https://www.datalab.to/auth/sign_up?utm_source=gh-sdk), then get your API key from [https://www.datalab.to/app/keys](https://www.datalab.to/app/keys):
39
39
 
40
40
  ```bash
41
41
  export DATALAB_API_KEY="your_api_key_here"
@@ -195,16 +195,21 @@ Published-agent execution is in open beta; the API may change. Processor design
195
195
  except DatalabPollingTimeoutError as e:
196
196
  result = client.get_result(e.check_url, max_polls=600)
197
197
  ```
198
- - 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
202
211
  input order. Use `AsyncDatalabClient` inside an existing async event loop.
203
212
 
204
- ## Workflows
205
-
206
- The Datalab API removed the Workflows API. The workflow methods and CLI commands in this SDK are deprecated, and the API does not answer them. Use pipelines instead.
207
-
208
213
  ## CLI Usage
209
214
 
210
215
  The SDK includes a command-line interface:
@@ -14,7 +14,7 @@ pip install datalab-python-sdk
14
14
 
15
15
  ### Authentication
16
16
 
17
- [Sign up](https://www.datalab.to/?utm_source=gh-sdk), then get your API key from [https://www.datalab.to/app/keys](https://www.datalab.to/app/keys):
17
+ [Sign up](https://www.datalab.to/auth/sign_up?utm_source=gh-sdk), then get your API key from [https://www.datalab.to/app/keys](https://www.datalab.to/app/keys):
18
18
 
19
19
  ```bash
20
20
  export DATALAB_API_KEY="your_api_key_here"
@@ -174,16 +174,21 @@ Published-agent execution is in open beta; the API may change. Processor design
174
174
  except DatalabPollingTimeoutError as e:
175
175
  result = client.get_result(e.check_url, max_polls=600)
176
176
  ```
177
- - 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`.
177
+ - 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`.
178
+
179
+ ```python
180
+ submitted = client.submit_convert("big.pdf")
181
+ # ... later, from any process
182
+ status = client.check_status(submitted.check_url)
183
+ if status.done:
184
+ result = client.get_result(submitted.check_url)
185
+ ```
186
+ - 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`.
178
187
 
179
188
  With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
180
189
  files from disk and limits the number of active uploads. Results retain the
181
190
  input order. Use `AsyncDatalabClient` inside an existing async event loop.
182
191
 
183
- ## Workflows
184
-
185
- 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.
186
-
187
192
  ## CLI Usage
188
193
 
189
194
  The SDK includes a command-line interface:
@@ -14,6 +14,8 @@ from .exceptions import (
14
14
  DatalabNotFoundError,
15
15
  DatalabRateLimitError,
16
16
  DatalabServerError,
17
+ DatalabProcessingError,
18
+ DatalabResponseError,
17
19
  DatalabTimeoutError,
18
20
  DatalabTransferTimeoutError,
19
21
  DatalabPollingTimeoutError,
@@ -25,6 +27,8 @@ from .models import (
25
27
  CreateDocumentResult,
26
28
  FileResult,
27
29
  OCRResult,
30
+ RequestStatus,
31
+ SubmittedRequest,
28
32
  ConvertOptions,
29
33
  ExtractOptions,
30
34
  SegmentOptions,
@@ -40,13 +44,9 @@ from .models import (
40
44
  FormFieldsResult,
41
45
  AgentOptions,
42
46
  AgentResult,
43
- ExtractionSchemaSuggestions,
44
- Workflow,
45
- WorkflowStep,
46
- WorkflowExecution,
47
- InputConfig,
48
47
  UploadedFileMetadata,
49
48
  ExtractionSchema,
49
+ ExtractionSchemaSuggestions,
50
50
  PipelineProcessor,
51
51
  PipelineConfig,
52
52
  PipelineVersion,
@@ -87,6 +87,8 @@ __all__ = [
87
87
  "DatalabNotFoundError",
88
88
  "DatalabRateLimitError",
89
89
  "DatalabServerError",
90
+ "DatalabProcessingError",
91
+ "DatalabResponseError",
90
92
  "DatalabTimeoutError",
91
93
  "DatalabTransferTimeoutError",
92
94
  "DatalabPollingTimeoutError",
@@ -96,6 +98,8 @@ __all__ = [
96
98
  "CreateDocumentResult",
97
99
  "FileResult",
98
100
  "OCRResult",
101
+ "RequestStatus",
102
+ "SubmittedRequest",
99
103
  "ConvertOptions",
100
104
  "ExtractOptions",
101
105
  "SegmentOptions",
@@ -111,13 +115,9 @@ __all__ = [
111
115
  "FormFieldsResult",
112
116
  "AgentOptions",
113
117
  "AgentResult",
114
- "ExtractionSchemaSuggestions",
115
- "Workflow",
116
- "WorkflowStep",
117
- "WorkflowExecution",
118
- "InputConfig",
119
118
  "UploadedFileMetadata",
120
119
  "ExtractionSchema",
120
+ "ExtractionSchemaSuggestions",
121
121
  "PipelineProcessor",
122
122
  "PipelineConfig",
123
123
  "PipelineVersion",
@@ -13,6 +13,7 @@ import tempfile
13
13
  from pathlib import Path
14
14
  from typing import Dict, List, Optional
15
15
 
16
+ from datalab_sdk._output_names import exact_output_base
16
17
  from datalab_sdk.exceptions import DatalabError
17
18
 
18
19
  OUTPUT_MARKER = ".datalab-output"
@@ -137,8 +138,9 @@ class OutputLayout:
137
138
  return list(self._folders.values())
138
139
 
139
140
  def output_path(self, file_path: Path) -> Path:
140
- """The save_output path of an input: its folder plus its stem."""
141
- return self._folders[file_path] / file_path.stem
141
+ """The save_output path of an input: its folder plus its whole stem
142
+ (report.json.tif saves report.json.md, report.json.html and so on)."""
143
+ return exact_output_base(self._folders[file_path] / file_path.stem)
142
144
 
143
145
  def __enter__(self) -> "OutputLayout":
144
146
  # A with statement doesn't call __exit__ when __enter__ raises, so any
@@ -0,0 +1,31 @@
1
+ """How save_output names the files it writes from the path it's given."""
2
+
3
+ from pathlib import Path
4
+
5
+ from datalab_sdk.mimetypes import SUPPORTED_EXTENSIONS
6
+
7
+ # The extensions save_output replaces: the ones it writes, and the input types the
8
+ # API reads, so save_output("out/scan.jpg") writes out/scan.md. Any other dot belongs
9
+ # to the name (a stem such as "v1.2.report").
10
+ _REPLACED_EXTENSIONS = {
11
+ ".md",
12
+ ".txt",
13
+ ".json",
14
+ ".xml",
15
+ ".tif",
16
+ ".htm",
17
+ *SUPPORTED_EXTENSIONS,
18
+ }
19
+
20
+
21
+ def output_file(path: Path, suffix: str) -> Path:
22
+ """`path` with `suffix` added, keeping every dot in the name except one known extension."""
23
+ if path.suffix.lower() in _REPLACED_EXTENSIONS:
24
+ path = path.with_suffix("")
25
+ return path.with_name(path.name + suffix)
26
+
27
+
28
+ def exact_output_base(base: Path) -> Path:
29
+ """A path that save_output uses whole as the base name, dots and all
30
+ (report.json gives report.json.md, not report.md)."""
31
+ return base.with_name(base.name + ".md")
@@ -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)