datalab-python-sdk 0.13.0__tar.gz → 0.15.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 (70) hide show
  1. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/CHANGELOG.md +100 -0
  2. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/PKG-INFO +3 -7
  3. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/README.md +2 -6
  4. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/__init__.py +2 -10
  5. datalab_python_sdk-0.15.0/datalab_sdk/_output_layout.py +196 -0
  6. datalab_python_sdk-0.15.0/datalab_sdk/_output_names.py +31 -0
  7. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/auth.py +88 -4
  8. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/cli.py +114 -579
  9. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/client.py +160 -508
  10. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/models.py +26 -145
  11. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/pyproject.toml +1 -1
  12. datalab_python_sdk-0.15.0/tests/test_api_key_resolution.py +295 -0
  13. datalab_python_sdk-0.15.0/tests/test_cli_exit_codes.py +264 -0
  14. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_cli_options.py +1 -0
  15. datalab_python_sdk-0.15.0/tests/test_cli_output_layout.py +426 -0
  16. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_cli_simple.py +11 -3
  17. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_comparisons.py +10 -0
  18. datalab_python_sdk-0.15.0/tests/test_import_warnings.py +59 -0
  19. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_new_endpoints.py +63 -32
  20. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_results.py +36 -0
  21. datalab_python_sdk-0.15.0/tests/test_sync_client_errors.py +99 -0
  22. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/uv.lock +1 -1
  23. datalab_python_sdk-0.13.0/recipes/workflows/README.md +0 -102
  24. datalab_python_sdk-0.13.0/recipes/workflows/end_to_end_workflow.py +0 -205
  25. datalab_python_sdk-0.13.0/recipes/workflows/workflow_api_tutorial/1_get_step_types.py +0 -60
  26. datalab_python_sdk-0.13.0/recipes/workflows/workflow_api_tutorial/2_get_workflows.py +0 -47
  27. datalab_python_sdk-0.13.0/recipes/workflows/workflow_api_tutorial/3_create_workflow.py +0 -156
  28. datalab_python_sdk-0.13.0/recipes/workflows/workflow_api_tutorial/4_execute_workflow.py +0 -63
  29. datalab_python_sdk-0.13.0/recipes/workflows/workflow_api_tutorial/5_poll_workflow.py +0 -125
  30. datalab_python_sdk-0.13.0/recipes/workflows/workflow_api_tutorial/README.md +0 -143
  31. datalab_python_sdk-0.13.0/recipes/workflows/workflow_definitions/README.md +0 -190
  32. datalab_python_sdk-0.13.0/recipes/workflows/workflow_definitions/eval_segmentation.json +0 -71
  33. datalab_python_sdk-0.13.0/recipes/workflows/workflow_definitions/parse_segment.json +0 -22
  34. datalab_python_sdk-0.13.0/recipes/workflows/workflow_definitions/segment_parallel_extract.json +0 -113
  35. datalab_python_sdk-0.13.0/recipes/workflows/workflow_definitions/slack_alert.json +0 -41
  36. datalab_python_sdk-0.13.0/tests/test_workflows.py +0 -460
  37. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/.github/workflows/ci.yml +0 -0
  38. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/.gitignore +0 -0
  39. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/.pre-commit-config.yaml +0 -0
  40. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/.python-version +0 -0
  41. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/LICENSE +0 -0
  42. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/08-Lambda-Calculus.pptx +0 -0
  43. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/adversarial.pdf +0 -0
  44. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/bid_evaluation.docx +0 -0
  45. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/book_review.ppt +0 -0
  46. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/book_store.xls +0 -0
  47. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/chi_hind.png +0 -0
  48. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/how_to_read.doc +0 -0
  49. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/normandy.epub +0 -0
  50. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/sample-1-sheet.xlsx +0 -0
  51. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/thinkpython.pdf +0 -0
  52. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/data/vibe.html +0 -0
  53. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/exceptions.py +0 -0
  54. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/mimetypes.py +0 -0
  55. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/datalab_sdk/settings.py +0 -0
  56. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/integration/README.md +0 -0
  57. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/integration/__init__.py +0 -0
  58. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/integration/test_live_api.py +0 -0
  59. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/integration/test_readme_examples.py +0 -0
  60. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/pytest.ini +0 -0
  61. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/__init__.py +0 -0
  62. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/conftest.py +0 -0
  63. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_api_consistency.py +0 -0
  64. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_client_methods.py +0 -0
  65. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_device_login.py +0 -0
  66. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_errors.py +0 -0
  67. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_progress.py +0 -0
  68. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_streaming_retries.py +0 -0
  69. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_timeout_recovery.py +0 -0
  70. {datalab_python_sdk-0.13.0 → datalab_python_sdk-0.15.0}/tests/test_transport_audit.py +0 -0
@@ -3,6 +3,106 @@
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.15.0
7
+
8
+ Removed:
9
+
10
+ - The workflow methods (`create_workflow`, `get_workflow`, `list_workflows`,
11
+ `delete_workflow`, `execute_workflow`, `get_execution_status`,
12
+ `get_step_types`), their models (`Workflow`, `WorkflowStep`,
13
+ `WorkflowExecution`, `InputConfig`) and the workflow CLI commands,
14
+ including `visualize-workflow`. The API removed the Workflows API, so these
15
+ methods already failed with a 404. Use pipelines.
16
+
17
+ Deprecated:
18
+
19
+ - The custom processor management methods (`list_custom_processors`,
20
+ `get_custom_processor_status`, `list_custom_processor_versions`,
21
+ `set_active_processor_version`, `archive_custom_processor`) warn. Their
22
+ `/api/v1/custom_processors` routes are deprecated, and the sunset date
23
+ (October 31, 2026) has passed, so they can stop responding without
24
+ further notice. `run_custom_processor()` and `run_custom_pipeline()`
25
+ already warned. Run processors with `run_agent()` and
26
+ `AgentOptions(processor="cp_XXXXX")`.
27
+
28
+ Fixed:
29
+
30
+ - `save_output()` keeps every dot in the name you pass, so
31
+ `save_output("output/v1.2.report")` writes `v1.2.report.md`. Before, it
32
+ wrote `v1.2.md`. A path that ends in an extension `save_output()` writes or
33
+ a document type the API reads, such as `report.md` or `scan.jpg`, still has
34
+ that one extension replaced, as before. The CLI keeps the whole stem of an
35
+ input: `v1.2.report.pdf` saves `v1.2.report.md`, and `report.json.pdf`
36
+ saves `report.json.md` (before, `v1.2.md` and `report.md`).
37
+ - `datalab compare get` and `compare run --wait` list each file's ID and
38
+ status. When a file completed, they print the `compare differences`
39
+ command that takes the ID.
40
+ - The `file_id` docstrings of `get_file_metadata()`,
41
+ `get_file_download_url()` and `delete_file()` no longer say a hashid works:
42
+ the API takes the integer `file_id`.
43
+ - The `custom-pipeline` CLI help and warning give the passed sunset date.
44
+
45
+ ## 0.14.0
46
+
47
+ Behavior changes:
48
+
49
+ - The CLI exits with status 1 when any file fails, and `compare run --wait`
50
+ exits with status 1 when the comparison or any of its files fails. Before,
51
+ both exited 0, so scripts and CI couldn't tell. The summary names the
52
+ output directory only when a file was saved, says `No output was saved.`
53
+ when none was, and a run that saves nothing leaves no empty output
54
+ directory.
55
+ - The key saved by `datalab login` is only sent to the host it was saved
56
+ for: the same scheme, host and port. A client or CLI command with another
57
+ `base_url`, including `https://datalab.to` for a key saved for
58
+ `https://www.datalab.to`, no longer uses it, and the error names the saved
59
+ host and `datalab login --host`. Before, the client sent the saved key to
60
+ any `base_url`.
61
+ - An empty `api_key` (or `--api_key ""`) raises an error instead of being
62
+ sent. An empty or blank `DATALAB_API_KEY` counts as unset, and whitespace
63
+ around a key, such as a newline from a `.env` file, is removed.
64
+ - The CLI saves results to `./output/` when `--output_dir` is not given,
65
+ instead of the working directory. Scripts that read results from the
66
+ working directory, such as `./report/report.md` after
67
+ `datalab convert report.pdf`, now find them at `./output/report/report.md`.
68
+ Pass `--output_dir .` to keep the old location. The CLI prints the full
69
+ output path when a run starts and in its summary.
70
+ - The CLI's output folders mirror the input directory: `a/report.pdf`
71
+ saves to `<output_dir>/a/report/report.md`. Before, every input saved to
72
+ `<output_dir>/<stem>/`, so `a/report.pdf` and `b/report.pdf` overwrote
73
+ each other. With the same `--output_dir`, a single file keeps its old
74
+ path.
75
+
76
+ Fixed:
77
+
78
+ - `import datalab_sdk` no longer raises a `DeprecationWarning` with
79
+ tenacity 9.2 or later, so it works under
80
+ `python -W error::DeprecationWarning`. Retries keep the same backoff.
81
+ - An error from the sync `DatalabClient` is no longer chained to
82
+ `RuntimeError: There is no current event loop`. This happened whenever no
83
+ event loop was set: in every script on Python 3.14, and on earlier
84
+ versions in a worker thread or after an earlier `asyncio.run()`.
85
+ - The sync `DatalabClient` works under `-W error::DeprecationWarning` on
86
+ Python 3.12 and 3.13. Before, every call failed with "There is no current
87
+ event loop".
88
+ - A CLI directory scan skips folders that the CLI saved results to: each
89
+ has a `.datalab-output` file. Before, a second run in the same folder
90
+ processed and billed the first run's HTML and images as new inputs.
91
+ Results saved by 0.13.0 and earlier have no such file, so move or delete
92
+ them before you scan a folder that holds them.
93
+ - The CLI checks every output folder before it submits anything. It stops
94
+ when two inputs would save to the same folder (such as `report.pdf` and
95
+ `report.docx` side by side, or names that differ only in case on a file
96
+ system that ignores case), when one input's folder would be inside
97
+ another's (such as `report.pdf` next to a `report/` folder of documents),
98
+ when a folder already exists and is not a CLI output folder, or when a
99
+ folder holds another input's results from an earlier run. The error for
100
+ inputs with the same name suggests `--extensions` to process one type.
101
+ - Every `datalab` CLI command uses the key saved by `datalab login`. Before,
102
+ `convert`, `create-document`, `compare` and the other processing commands
103
+ asked for `--api_key` or `DATALAB_API_KEY`. The SDK and the CLI now pick a
104
+ key the same way: `api_key`, then `DATALAB_API_KEY`, then the saved key.
105
+
6
106
  ## 0.13.0
7
107
 
8
108
  New:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datalab-python-sdk
3
- Version: 0.13.0
3
+ Version: 0.15.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"
@@ -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, and uses it when `DATALAB_API_KEY` is not set. `datalab logout` deletes it.
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
 
@@ -201,10 +201,6 @@ With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
201
201
  files from disk and limits the number of active uploads. Results retain the
202
202
  input order. Use `AsyncDatalabClient` inside an existing async event loop.
203
203
 
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
204
  ## CLI Usage
209
205
 
210
206
  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"
@@ -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, and uses it when `DATALAB_API_KEY` is not set. `datalab logout` deletes it.
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
 
@@ -180,10 +180,6 @@ With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
180
180
  files from disk and limits the number of active uploads. Results retain the
181
181
  input order. Use `AsyncDatalabClient` inside an existing async event loop.
182
182
 
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
183
  ## CLI Usage
188
184
 
189
185
  The SDK includes a command-line interface:
@@ -40,13 +40,9 @@ from .models import (
40
40
  FormFieldsResult,
41
41
  AgentOptions,
42
42
  AgentResult,
43
- ExtractionSchemaSuggestions,
44
- Workflow,
45
- WorkflowStep,
46
- WorkflowExecution,
47
- InputConfig,
48
43
  UploadedFileMetadata,
49
44
  ExtractionSchema,
45
+ ExtractionSchemaSuggestions,
50
46
  PipelineProcessor,
51
47
  PipelineConfig,
52
48
  PipelineVersion,
@@ -111,13 +107,9 @@ __all__ = [
111
107
  "FormFieldsResult",
112
108
  "AgentOptions",
113
109
  "AgentResult",
114
- "ExtractionSchemaSuggestions",
115
- "Workflow",
116
- "WorkflowStep",
117
- "WorkflowExecution",
118
- "InputConfig",
119
110
  "UploadedFileMetadata",
120
111
  "ExtractionSchema",
112
+ "ExtractionSchemaSuggestions",
121
113
  "PipelineProcessor",
122
114
  "PipelineConfig",
123
115
  "PipelineVersion",
@@ -0,0 +1,196 @@
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._output_names import exact_output_base
17
+ from datalab_sdk.exceptions import DatalabError
18
+
19
+ OUTPUT_MARKER = ".datalab-output"
20
+
21
+
22
+ def _nearest_existing(path: Path) -> Path:
23
+ path = path.absolute()
24
+ while not path.exists() and path != path.parent:
25
+ path = path.parent
26
+ return path
27
+
28
+
29
+ def ignores_case(directory: Path) -> bool:
30
+ """Whether the file system that holds directory (or its nearest existing
31
+ parent) ignores case in names. Assumes it does when it can't tell."""
32
+ probe_dir = _nearest_existing(directory)
33
+ try:
34
+ with tempfile.NamedTemporaryFile(prefix=".datalab-Case-", dir=probe_dir) as f:
35
+ name = os.path.basename(f.name)
36
+ return os.path.exists(os.path.join(probe_dir, name.swapcase()))
37
+ except OSError:
38
+ return True
39
+
40
+
41
+ def _extension(file_path: Path) -> str:
42
+ return file_path.suffix.lstrip(".").lower()
43
+
44
+
45
+ def _marker_owner(marker: Path) -> str:
46
+ """The name of the input whose results a marked folder holds, if recorded."""
47
+ try:
48
+ return marker.read_text(encoding="utf-8")
49
+ except (OSError, UnicodeDecodeError):
50
+ return ""
51
+
52
+
53
+ class OutputLayout:
54
+ """The output folder of each input in one CLI run.
55
+
56
+ plan() checks every folder before anything is submitted. Entering the
57
+ layout creates the folders and their markers; leaving it, also after an
58
+ error or Ctrl-C, removes markers from folders that got no results and the
59
+ folders this run created that are left empty.
60
+ """
61
+
62
+ def __init__(self, folders: Dict[Path, Path]):
63
+ self._folders = folders
64
+ self._created: List[Path] = []
65
+
66
+ @classmethod
67
+ def plan(
68
+ cls, files: List[Path], input_root: Optional[Path], output_dir: Path
69
+ ) -> "OutputLayout":
70
+ """Plan each input's folder: its path under input_root, without the
71
+ extension. Without input_root, a folder is named after the file alone.
72
+
73
+ Raises DatalabError when two inputs would share a folder, one folder
74
+ would be inside another, a folder exists and is not an output folder,
75
+ or a folder holds another input's results from an earlier run.
76
+ """
77
+ case_blind = ignores_case(output_dir)
78
+ folders: Dict[Path, Path] = {}
79
+ seen: Dict[str, Path] = {}
80
+ for file_path in files:
81
+ try:
82
+ relative = file_path.relative_to(input_root) if input_root else None
83
+ except ValueError:
84
+ relative = None
85
+ relative = relative or Path(file_path.name)
86
+ folder = output_dir / relative.parent / file_path.stem
87
+ key = str(folder.resolve())
88
+ if case_blind:
89
+ key = key.casefold()
90
+ if key in seen:
91
+ # The folders are only the same because case is ignored when
92
+ # their names differ, as for Doc.png and doc.pdf.
93
+ only_case = folders[seen[key]] != folder
94
+ raise DatalabError(
95
+ f"{seen[key]} and {file_path} would save to the same output "
96
+ f"folder {folder}"
97
+ + (", because this file system ignores case" if only_case else "")
98
+ + f". Process one type with --extensions {_extension(file_path)}, "
99
+ "rename one of them, or use another --output_dir."
100
+ )
101
+ marker = folder / OUTPUT_MARKER
102
+ if folder.exists() and not marker.is_file():
103
+ raise DatalabError(
104
+ f"The output folder for {file_path}, {folder}, already exists "
105
+ "and is not a datalab output folder. Move it, or choose another "
106
+ "--output_dir."
107
+ )
108
+ owner = _marker_owner(marker)
109
+ if owner and (
110
+ owner.casefold() != file_path.name.casefold()
111
+ if case_blind
112
+ else owner != file_path.name
113
+ ):
114
+ raise DatalabError(
115
+ f"The output folder for {file_path}, {folder}, holds the results "
116
+ f"of {owner} from an earlier run. Move them, process one type "
117
+ f"with --extensions {_extension(file_path)}, or use another "
118
+ "--output_dir."
119
+ )
120
+ seen[key] = file_path
121
+ folders[file_path] = folder
122
+
123
+ # One input's folder inside another's could put a folder where the other
124
+ # input's result file goes, for example report/report.md/.
125
+ for inner, inner_file in seen.items():
126
+ for parent in Path(inner).parents:
127
+ outer_file = seen.get(str(parent))
128
+ if outer_file is not None:
129
+ raise DatalabError(
130
+ f"The output folder for {inner_file} would be inside the "
131
+ f"output folder for {outer_file}. Rename one of them, or "
132
+ "process one with another --output_dir."
133
+ )
134
+ return cls(folders)
135
+
136
+ @property
137
+ def folders(self) -> List[Path]:
138
+ return list(self._folders.values())
139
+
140
+ def output_path(self, file_path: Path) -> Path:
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)
144
+
145
+ def __enter__(self) -> "OutputLayout":
146
+ # A with statement doesn't call __exit__ when __enter__ raises, so any
147
+ # error here, Ctrl-C included, cleans up what was made so far.
148
+ try:
149
+ for file_path, folder in self._folders.items():
150
+ missing = []
151
+ path = folder
152
+ while not path.exists() and path != path.parent:
153
+ missing.append(path)
154
+ path = path.parent
155
+ for path in reversed(missing):
156
+ path.mkdir()
157
+ self._created.append(path)
158
+ marker = folder / OUTPUT_MARKER
159
+ marker.write_text(file_path.name, encoding="utf-8")
160
+ except OSError as e:
161
+ self.__exit__(None, None, None)
162
+ raise DatalabError(f"Can't create the output folder {folder}: {e}")
163
+ except BaseException:
164
+ self.__exit__(None, None, None)
165
+ raise
166
+ return self
167
+
168
+ def __exit__(self, *exc) -> None:
169
+ for folder in self._folders.values():
170
+ try:
171
+ if [p.name for p in folder.iterdir()] == [OUTPUT_MARKER]:
172
+ (folder / OUTPUT_MARKER).unlink()
173
+ folder.rmdir()
174
+ except OSError:
175
+ pass
176
+ for path in reversed(self._created):
177
+ try:
178
+ path.rmdir()
179
+ except OSError:
180
+ pass
181
+
182
+ def snapshot(self, file_path: Path) -> Dict[str, int]:
183
+ """The names and modification times of an input's results so far."""
184
+ try:
185
+ return {
186
+ p.name: p.stat().st_mtime_ns
187
+ for p in self._folders[file_path].iterdir()
188
+ if p.name != OUTPUT_MARKER
189
+ }
190
+ except OSError:
191
+ return {}
192
+
193
+ def wrote_output(self, file_path: Path, before: Dict[str, int]) -> bool:
194
+ """Whether a result was written for an input since snapshot() gave `before`."""
195
+ after = self.snapshot(file_path)
196
+ return any(before.get(name) != mtime for name, mtime in after.items())
@@ -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")
@@ -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. DATALAB_API_KEY in the environment always wins over the saved key.
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 load_saved_api_key() -> Optional[str]:
38
+ def _load_config() -> dict:
36
39
  try:
37
- return json.loads(config_path().read_text()).get("api_key") or None
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: