datalab-python-sdk 0.13.0__tar.gz → 0.14.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.13.0 → datalab_python_sdk-0.14.0}/CHANGELOG.md +61 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/PKG-INFO +2 -2
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/README.md +1 -1
- datalab_python_sdk-0.14.0/datalab_sdk/_output_layout.py +194 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/auth.py +88 -4
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/cli.py +99 -124
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/client.py +27 -23
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/pyproject.toml +1 -1
- datalab_python_sdk-0.14.0/tests/test_api_key_resolution.py +295 -0
- datalab_python_sdk-0.14.0/tests/test_cli_exit_codes.py +237 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_cli_options.py +1 -0
- datalab_python_sdk-0.14.0/tests/test_cli_output_layout.py +413 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_cli_simple.py +11 -3
- datalab_python_sdk-0.14.0/tests/test_import_warnings.py +59 -0
- datalab_python_sdk-0.14.0/tests/test_sync_client_errors.py +99 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/uv.lock +1 -1
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/.github/workflows/ci.yml +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/.gitignore +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/.pre-commit-config.yaml +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/.python-version +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/LICENSE +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/08-Lambda-Calculus.pptx +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/adversarial.pdf +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/bid_evaluation.docx +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/book_review.ppt +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/book_store.xls +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/chi_hind.png +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/how_to_read.doc +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/normandy.epub +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/sample-1-sheet.xlsx +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/thinkpython.pdf +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/data/vibe.html +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/__init__.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/exceptions.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/mimetypes.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/models.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/datalab_sdk/settings.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/integration/README.md +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/integration/__init__.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/integration/test_live_api.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/integration/test_readme_examples.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/pytest.ini +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/README.md +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/end_to_end_workflow.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_api_tutorial/1_get_step_types.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_api_tutorial/2_get_workflows.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_api_tutorial/3_create_workflow.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_api_tutorial/4_execute_workflow.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_api_tutorial/5_poll_workflow.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_api_tutorial/README.md +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_definitions/README.md +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_definitions/eval_segmentation.json +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_definitions/parse_segment.json +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_definitions/segment_parallel_extract.json +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/recipes/workflows/workflow_definitions/slack_alert.json +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/__init__.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/conftest.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_api_consistency.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_client_methods.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_comparisons.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_device_login.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_errors.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_new_endpoints.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_progress.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_results.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_streaming_retries.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_timeout_recovery.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_transport_audit.py +0 -0
- {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.14.0}/tests/test_workflows.py +0 -0
|
@@ -3,6 +3,67 @@
|
|
|
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.14.0
|
|
7
|
+
|
|
8
|
+
Behavior changes:
|
|
9
|
+
|
|
10
|
+
- The CLI exits with status 1 when any file fails, and `compare run --wait`
|
|
11
|
+
exits with status 1 when the comparison or any of its files fails. Before,
|
|
12
|
+
both exited 0, so scripts and CI couldn't tell. The summary names the
|
|
13
|
+
output directory only when a file was saved, says `No output was saved.`
|
|
14
|
+
when none was, and a run that saves nothing leaves no empty output
|
|
15
|
+
directory.
|
|
16
|
+
- The key saved by `datalab login` is only sent to the host it was saved
|
|
17
|
+
for: the same scheme, host and port. A client or CLI command with another
|
|
18
|
+
`base_url`, including `https://datalab.to` for a key saved for
|
|
19
|
+
`https://www.datalab.to`, no longer uses it, and the error names the saved
|
|
20
|
+
host and `datalab login --host`. Before, the client sent the saved key to
|
|
21
|
+
any `base_url`.
|
|
22
|
+
- An empty `api_key` (or `--api_key ""`) raises an error instead of being
|
|
23
|
+
sent. An empty or blank `DATALAB_API_KEY` counts as unset, and whitespace
|
|
24
|
+
around a key, such as a newline from a `.env` file, is removed.
|
|
25
|
+
- The CLI saves results to `./output/` when `--output_dir` is not given,
|
|
26
|
+
instead of the working directory. Scripts that read results from the
|
|
27
|
+
working directory, such as `./report/report.md` after
|
|
28
|
+
`datalab convert report.pdf`, now find them at `./output/report/report.md`.
|
|
29
|
+
Pass `--output_dir .` to keep the old location. The CLI prints the full
|
|
30
|
+
output path when a run starts and in its summary.
|
|
31
|
+
- The CLI's output folders mirror the input directory: `a/report.pdf`
|
|
32
|
+
saves to `<output_dir>/a/report/report.md`. Before, every input saved to
|
|
33
|
+
`<output_dir>/<stem>/`, so `a/report.pdf` and `b/report.pdf` overwrote
|
|
34
|
+
each other. With the same `--output_dir`, a single file keeps its old
|
|
35
|
+
path.
|
|
36
|
+
|
|
37
|
+
Fixed:
|
|
38
|
+
|
|
39
|
+
- `import datalab_sdk` no longer raises a `DeprecationWarning` with
|
|
40
|
+
tenacity 9.2 or later, so it works under
|
|
41
|
+
`python -W error::DeprecationWarning`. Retries keep the same backoff.
|
|
42
|
+
- An error from the sync `DatalabClient` is no longer chained to
|
|
43
|
+
`RuntimeError: There is no current event loop`. This happened whenever no
|
|
44
|
+
event loop was set: in every script on Python 3.14, and on earlier
|
|
45
|
+
versions in a worker thread or after an earlier `asyncio.run()`.
|
|
46
|
+
- The sync `DatalabClient` works under `-W error::DeprecationWarning` on
|
|
47
|
+
Python 3.12 and 3.13. Before, every call failed with "There is no current
|
|
48
|
+
event loop".
|
|
49
|
+
- A CLI directory scan skips folders that the CLI saved results to: each
|
|
50
|
+
has a `.datalab-output` file. Before, a second run in the same folder
|
|
51
|
+
processed and billed the first run's HTML and images as new inputs.
|
|
52
|
+
Results saved by 0.13.0 and earlier have no such file, so move or delete
|
|
53
|
+
them before you scan a folder that holds them.
|
|
54
|
+
- The CLI checks every output folder before it submits anything. It stops
|
|
55
|
+
when two inputs would save to the same folder (such as `report.pdf` and
|
|
56
|
+
`report.docx` side by side, or names that differ only in case on a file
|
|
57
|
+
system that ignores case), when one input's folder would be inside
|
|
58
|
+
another's (such as `report.pdf` next to a `report/` folder of documents),
|
|
59
|
+
when a folder already exists and is not a CLI output folder, or when a
|
|
60
|
+
folder holds another input's results from an earlier run. The error for
|
|
61
|
+
inputs with the same name suggests `--extensions` to process one type.
|
|
62
|
+
- Every `datalab` CLI command uses the key saved by `datalab login`. Before,
|
|
63
|
+
`convert`, `create-document`, `compare` and the other processing commands
|
|
64
|
+
asked for `--api_key` or `DATALAB_API_KEY`. The SDK and the CLI now pick a
|
|
65
|
+
key the same way: `api_key`, then `DATALAB_API_KEY`, then the saved key.
|
|
66
|
+
|
|
6
67
|
## 0.13.0
|
|
7
68
|
|
|
8
69
|
New:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: datalab-python-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.14.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
|
|
@@ -47,7 +47,7 @@ Or sign in from a terminal, which also works for coding agents:
|
|
|
47
47
|
datalab login
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
-
It shows a code and a link. Open the link, sign in or sign up, approve the code, and type the 6-digit code that we email you. The SDK saves the key to `~/.config/datalab/config.json`, readable only by your user
|
|
50
|
+
It shows a code and a link. Open the link, sign in or sign up, approve the code, and type the 6-digit code that we email you. The SDK saves the key to `~/.config/datalab/config.json`, readable only by your user. The client and the `datalab` CLI use it when no key is passed and `DATALAB_API_KEY` is not set, and send it only to the host you signed in to. `datalab logout` deletes it.
|
|
51
51
|
|
|
52
52
|
### Basic Usage
|
|
53
53
|
|
|
@@ -26,7 +26,7 @@ Or sign in from a terminal, which also works for coding agents:
|
|
|
26
26
|
datalab login
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
It shows a code and a link. Open the link, sign in or sign up, approve the code, and type the 6-digit code that we email you. The SDK saves the key to `~/.config/datalab/config.json`, readable only by your user
|
|
29
|
+
It shows a code and a link. Open the link, sign in or sign up, approve the code, and type the 6-digit code that we email you. The SDK saves the key to `~/.config/datalab/config.json`, readable only by your user. The client and the `datalab` CLI use it when no key is passed and `DATALAB_API_KEY` is not set, and send it only to the host you signed in to. `datalab logout` deletes it.
|
|
30
30
|
|
|
31
31
|
### Basic Usage
|
|
32
32
|
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Where the CLI saves each input's results, and the folders it makes for them.
|
|
2
|
+
|
|
3
|
+
Each input saves to its own folder under the output directory, mirroring the
|
|
4
|
+
input tree: `a/report.pdf` saves to `<output_dir>/a/report/`. Each folder
|
|
5
|
+
holds OUTPUT_MARKER, a file with the input's file name, so a directory scan
|
|
6
|
+
skips the folder and a later run only reuses it for the same input.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import tempfile
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
from datalab_sdk.exceptions import DatalabError
|
|
17
|
+
|
|
18
|
+
OUTPUT_MARKER = ".datalab-output"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _nearest_existing(path: Path) -> Path:
|
|
22
|
+
path = path.absolute()
|
|
23
|
+
while not path.exists() and path != path.parent:
|
|
24
|
+
path = path.parent
|
|
25
|
+
return path
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def ignores_case(directory: Path) -> bool:
|
|
29
|
+
"""Whether the file system that holds directory (or its nearest existing
|
|
30
|
+
parent) ignores case in names. Assumes it does when it can't tell."""
|
|
31
|
+
probe_dir = _nearest_existing(directory)
|
|
32
|
+
try:
|
|
33
|
+
with tempfile.NamedTemporaryFile(prefix=".datalab-Case-", dir=probe_dir) as f:
|
|
34
|
+
name = os.path.basename(f.name)
|
|
35
|
+
return os.path.exists(os.path.join(probe_dir, name.swapcase()))
|
|
36
|
+
except OSError:
|
|
37
|
+
return True
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _extension(file_path: Path) -> str:
|
|
41
|
+
return file_path.suffix.lstrip(".").lower()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _marker_owner(marker: Path) -> str:
|
|
45
|
+
"""The name of the input whose results a marked folder holds, if recorded."""
|
|
46
|
+
try:
|
|
47
|
+
return marker.read_text(encoding="utf-8")
|
|
48
|
+
except (OSError, UnicodeDecodeError):
|
|
49
|
+
return ""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class OutputLayout:
|
|
53
|
+
"""The output folder of each input in one CLI run.
|
|
54
|
+
|
|
55
|
+
plan() checks every folder before anything is submitted. Entering the
|
|
56
|
+
layout creates the folders and their markers; leaving it, also after an
|
|
57
|
+
error or Ctrl-C, removes markers from folders that got no results and the
|
|
58
|
+
folders this run created that are left empty.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, folders: Dict[Path, Path]):
|
|
62
|
+
self._folders = folders
|
|
63
|
+
self._created: List[Path] = []
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def plan(
|
|
67
|
+
cls, files: List[Path], input_root: Optional[Path], output_dir: Path
|
|
68
|
+
) -> "OutputLayout":
|
|
69
|
+
"""Plan each input's folder: its path under input_root, without the
|
|
70
|
+
extension. Without input_root, a folder is named after the file alone.
|
|
71
|
+
|
|
72
|
+
Raises DatalabError when two inputs would share a folder, one folder
|
|
73
|
+
would be inside another, a folder exists and is not an output folder,
|
|
74
|
+
or a folder holds another input's results from an earlier run.
|
|
75
|
+
"""
|
|
76
|
+
case_blind = ignores_case(output_dir)
|
|
77
|
+
folders: Dict[Path, Path] = {}
|
|
78
|
+
seen: Dict[str, Path] = {}
|
|
79
|
+
for file_path in files:
|
|
80
|
+
try:
|
|
81
|
+
relative = file_path.relative_to(input_root) if input_root else None
|
|
82
|
+
except ValueError:
|
|
83
|
+
relative = None
|
|
84
|
+
relative = relative or Path(file_path.name)
|
|
85
|
+
folder = output_dir / relative.parent / file_path.stem
|
|
86
|
+
key = str(folder.resolve())
|
|
87
|
+
if case_blind:
|
|
88
|
+
key = key.casefold()
|
|
89
|
+
if key in seen:
|
|
90
|
+
# The folders are only the same because case is ignored when
|
|
91
|
+
# their names differ, as for Doc.png and doc.pdf.
|
|
92
|
+
only_case = folders[seen[key]] != folder
|
|
93
|
+
raise DatalabError(
|
|
94
|
+
f"{seen[key]} and {file_path} would save to the same output "
|
|
95
|
+
f"folder {folder}"
|
|
96
|
+
+ (", because this file system ignores case" if only_case else "")
|
|
97
|
+
+ f". Process one type with --extensions {_extension(file_path)}, "
|
|
98
|
+
"rename one of them, or use another --output_dir."
|
|
99
|
+
)
|
|
100
|
+
marker = folder / OUTPUT_MARKER
|
|
101
|
+
if folder.exists() and not marker.is_file():
|
|
102
|
+
raise DatalabError(
|
|
103
|
+
f"The output folder for {file_path}, {folder}, already exists "
|
|
104
|
+
"and is not a datalab output folder. Move it, or choose another "
|
|
105
|
+
"--output_dir."
|
|
106
|
+
)
|
|
107
|
+
owner = _marker_owner(marker)
|
|
108
|
+
if owner and (
|
|
109
|
+
owner.casefold() != file_path.name.casefold()
|
|
110
|
+
if case_blind
|
|
111
|
+
else owner != file_path.name
|
|
112
|
+
):
|
|
113
|
+
raise DatalabError(
|
|
114
|
+
f"The output folder for {file_path}, {folder}, holds the results "
|
|
115
|
+
f"of {owner} from an earlier run. Move them, process one type "
|
|
116
|
+
f"with --extensions {_extension(file_path)}, or use another "
|
|
117
|
+
"--output_dir."
|
|
118
|
+
)
|
|
119
|
+
seen[key] = file_path
|
|
120
|
+
folders[file_path] = folder
|
|
121
|
+
|
|
122
|
+
# One input's folder inside another's could put a folder where the other
|
|
123
|
+
# input's result file goes, for example report/report.md/.
|
|
124
|
+
for inner, inner_file in seen.items():
|
|
125
|
+
for parent in Path(inner).parents:
|
|
126
|
+
outer_file = seen.get(str(parent))
|
|
127
|
+
if outer_file is not None:
|
|
128
|
+
raise DatalabError(
|
|
129
|
+
f"The output folder for {inner_file} would be inside the "
|
|
130
|
+
f"output folder for {outer_file}. Rename one of them, or "
|
|
131
|
+
"process one with another --output_dir."
|
|
132
|
+
)
|
|
133
|
+
return cls(folders)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def folders(self) -> List[Path]:
|
|
137
|
+
return list(self._folders.values())
|
|
138
|
+
|
|
139
|
+
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
|
|
142
|
+
|
|
143
|
+
def __enter__(self) -> "OutputLayout":
|
|
144
|
+
# A with statement doesn't call __exit__ when __enter__ raises, so any
|
|
145
|
+
# error here, Ctrl-C included, cleans up what was made so far.
|
|
146
|
+
try:
|
|
147
|
+
for file_path, folder in self._folders.items():
|
|
148
|
+
missing = []
|
|
149
|
+
path = folder
|
|
150
|
+
while not path.exists() and path != path.parent:
|
|
151
|
+
missing.append(path)
|
|
152
|
+
path = path.parent
|
|
153
|
+
for path in reversed(missing):
|
|
154
|
+
path.mkdir()
|
|
155
|
+
self._created.append(path)
|
|
156
|
+
marker = folder / OUTPUT_MARKER
|
|
157
|
+
marker.write_text(file_path.name, encoding="utf-8")
|
|
158
|
+
except OSError as e:
|
|
159
|
+
self.__exit__(None, None, None)
|
|
160
|
+
raise DatalabError(f"Can't create the output folder {folder}: {e}")
|
|
161
|
+
except BaseException:
|
|
162
|
+
self.__exit__(None, None, None)
|
|
163
|
+
raise
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
def __exit__(self, *exc) -> None:
|
|
167
|
+
for folder in self._folders.values():
|
|
168
|
+
try:
|
|
169
|
+
if [p.name for p in folder.iterdir()] == [OUTPUT_MARKER]:
|
|
170
|
+
(folder / OUTPUT_MARKER).unlink()
|
|
171
|
+
folder.rmdir()
|
|
172
|
+
except OSError:
|
|
173
|
+
pass
|
|
174
|
+
for path in reversed(self._created):
|
|
175
|
+
try:
|
|
176
|
+
path.rmdir()
|
|
177
|
+
except OSError:
|
|
178
|
+
pass
|
|
179
|
+
|
|
180
|
+
def snapshot(self, file_path: Path) -> Dict[str, int]:
|
|
181
|
+
"""The names and modification times of an input's results so far."""
|
|
182
|
+
try:
|
|
183
|
+
return {
|
|
184
|
+
p.name: p.stat().st_mtime_ns
|
|
185
|
+
for p in self._folders[file_path].iterdir()
|
|
186
|
+
if p.name != OUTPUT_MARKER
|
|
187
|
+
}
|
|
188
|
+
except OSError:
|
|
189
|
+
return {}
|
|
190
|
+
|
|
191
|
+
def wrote_output(self, file_path: Path, before: Dict[str, int]) -> bool:
|
|
192
|
+
"""Whether a result was written for an input since snapshot() gave `before`."""
|
|
193
|
+
after = self.snapshot(file_path)
|
|
194
|
+
return any(before.get(name) != mtime for name, mtime in after.items())
|
|
@@ -6,7 +6,9 @@ The flow (server side: /api/auth/device/code, /app/device, /api/auth/device/toke
|
|
|
6
6
|
3. Poll until the server returns a new API key, then save it to the config file.
|
|
7
7
|
|
|
8
8
|
The key is saved to $XDG_CONFIG_HOME/datalab/config.json (default ~/.config/datalab/config.json)
|
|
9
|
-
with mode 0600
|
|
9
|
+
with mode 0600, together with the host it was issued for. resolve_api_key() picks the key that the
|
|
10
|
+
SDK and the CLI send: an explicit key, then DATALAB_API_KEY, then the saved key, and the saved key
|
|
11
|
+
only to the host it was saved for.
|
|
10
12
|
"""
|
|
11
13
|
|
|
12
14
|
from __future__ import annotations
|
|
@@ -19,7 +21,8 @@ import urllib.error
|
|
|
19
21
|
import urllib.request
|
|
20
22
|
import webbrowser
|
|
21
23
|
from pathlib import Path
|
|
22
|
-
from typing import Callable, Optional
|
|
24
|
+
from typing import Callable, NamedTuple, Optional
|
|
25
|
+
from urllib.parse import urlsplit
|
|
23
26
|
|
|
24
27
|
from datalab_sdk.exceptions import DatalabAPIError
|
|
25
28
|
from datalab_sdk.settings import settings
|
|
@@ -32,11 +35,92 @@ def config_path() -> Path:
|
|
|
32
35
|
return Path(base) / "datalab" / "config.json"
|
|
33
36
|
|
|
34
37
|
|
|
35
|
-
def
|
|
38
|
+
def _load_config() -> dict:
|
|
36
39
|
try:
|
|
37
|
-
|
|
40
|
+
config = json.loads(config_path().read_text())
|
|
38
41
|
except (OSError, ValueError):
|
|
42
|
+
return {}
|
|
43
|
+
return config if isinstance(config, dict) else {}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def load_saved_api_key() -> Optional[str]:
|
|
47
|
+
"""Return the saved key, whatever host it is for. Use resolve_api_key() to send one."""
|
|
48
|
+
return _load_config().get("api_key") or None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_DEFAULT_PORTS = {"http": 80, "https": 443}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Origin(NamedTuple):
|
|
55
|
+
"""The scheme, host and port of a URL, with the default port filled in."""
|
|
56
|
+
|
|
57
|
+
scheme: str
|
|
58
|
+
host: str
|
|
59
|
+
port: Optional[int]
|
|
60
|
+
|
|
61
|
+
def __str__(self) -> str:
|
|
62
|
+
"""A URL without any user name, password, path or query."""
|
|
63
|
+
host = f"[{self.host}]" if ":" in self.host else self.host
|
|
64
|
+
default = _DEFAULT_PORTS.get(self.scheme)
|
|
65
|
+
return f"{self.scheme}://{host}" + (
|
|
66
|
+
"" if self.port == default else f":{self.port}"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _origin(url: str) -> Optional[_Origin]:
|
|
71
|
+
try:
|
|
72
|
+
parts = urlsplit(url.strip())
|
|
73
|
+
port = parts.port
|
|
74
|
+
except (AttributeError, ValueError):
|
|
75
|
+
return None
|
|
76
|
+
scheme = parts.scheme.lower()
|
|
77
|
+
if not scheme or not parts.hostname:
|
|
39
78
|
return None
|
|
79
|
+
return _Origin(scheme, parts.hostname.lower(), port or _DEFAULT_PORTS.get(scheme))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def resolve_api_key(api_key: Optional[str], base_url: str) -> str:
|
|
83
|
+
"""Return the API key to send to base_url. Raises DatalabAPIError when there is none.
|
|
84
|
+
|
|
85
|
+
The order is an explicit key, then DATALAB_API_KEY, then the key saved by
|
|
86
|
+
`datalab login`. The saved key is used only when base_url has the same
|
|
87
|
+
origin (scheme, host and port) as the host it was saved for, so it is never
|
|
88
|
+
sent to another server. An empty or blank DATALAB_API_KEY counts as unset.
|
|
89
|
+
Whitespace around a key, such as a newline from a .env file, is removed.
|
|
90
|
+
|
|
91
|
+
This chooses the key for base_url only. Requests that base_url's server
|
|
92
|
+
sends the client on to, such as check URLs and redirects, use the same
|
|
93
|
+
key: that server already has it.
|
|
94
|
+
"""
|
|
95
|
+
if api_key is not None:
|
|
96
|
+
if not api_key.strip():
|
|
97
|
+
raise DatalabAPIError("The API key passed is empty.")
|
|
98
|
+
return api_key.strip()
|
|
99
|
+
env_key = (settings.DATALAB_API_KEY or "").strip()
|
|
100
|
+
if env_key:
|
|
101
|
+
return env_key
|
|
102
|
+
config = _load_config()
|
|
103
|
+
saved_key = config.get("api_key")
|
|
104
|
+
saved_host = config.get("host")
|
|
105
|
+
saved_origin = _origin(saved_host) if isinstance(saved_host, str) else None
|
|
106
|
+
target_origin = _origin(base_url)
|
|
107
|
+
if saved_key and saved_origin is not None and saved_origin == target_origin:
|
|
108
|
+
return saved_key
|
|
109
|
+
if saved_key:
|
|
110
|
+
target = str(target_origin) if target_origin else None
|
|
111
|
+
login = (
|
|
112
|
+
f"datalab login --host {target}" if target else "datalab login --host <url>"
|
|
113
|
+
)
|
|
114
|
+
raise DatalabAPIError(
|
|
115
|
+
f"No API key for {target or 'this base_url'}. The key saved by "
|
|
116
|
+
f"`datalab login` is for {saved_origin or 'an unknown host'}, "
|
|
117
|
+
f"and is only sent to the same scheme, host and port. Run `{login}`, "
|
|
118
|
+
"set DATALAB_API_KEY, or pass an API key."
|
|
119
|
+
)
|
|
120
|
+
raise DatalabAPIError(
|
|
121
|
+
"No API key. Run `datalab login`, set DATALAB_API_KEY, or pass an API key. "
|
|
122
|
+
f"Get a free API key at {KEYS_PAGE}"
|
|
123
|
+
)
|
|
40
124
|
|
|
41
125
|
|
|
42
126
|
def save_api_key(api_key: str, host: str, team_name: Optional[str] = None) -> Path:
|