datalab-python-sdk 0.13.0__py3-none-any.whl → 0.15.0__py3-none-any.whl

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.
@@ -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:
@@ -0,0 +1,15 @@
1
+ datalab_sdk/__init__.py,sha256=EDF3pT5_7FuDmYdo9TilNg2lzLDmKnCpzAaTSc2FoEs,3303
2
+ datalab_sdk/_output_layout.py,sha256=mDtg2hZQkMw_LTsrfslxwJ4BOZ2H8wKpR9w9CaT8mBs,7989
3
+ datalab_sdk/_output_names.py,sha256=CVbXjF--VoX61ZSOB2eUmeg0jbq4g5EMLzWcLy1a9Gw,1001
4
+ datalab_sdk/auth.py,sha256=i7LzAMM5wjY5-J6BUf69do6g7zuKenQZQwueqbLJSNU,7704
5
+ datalab_sdk/cli.py,sha256=YZObu6fihyQ3TLvFaWurpWYZGHYTzTx3m1r6mOpHOsE,47696
6
+ datalab_sdk/client.py,sha256=xDhNsNkUPE4ZsOlVdcnDysT4IwlFivZGb7X1q7dJxxg,161003
7
+ datalab_sdk/exceptions.py,sha256=GFRAZQoxP2cHYJ3Q-OBjU_3I34Om3avcz11vczc_GNs,4420
8
+ datalab_sdk/mimetypes.py,sha256=a4ULJmHxoR_RMsD0j51hx0t2Q7In_PzNm7UlWX07eEE,932
9
+ datalab_sdk/models.py,sha256=L13qApU-VISHdAHQ2dWBLBZwGNSAxktdy92djpQXUxk,39890
10
+ datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
11
+ datalab_python_sdk-0.15.0.dist-info/METADATA,sha256=60Z-brfZerWCYF_YPwTK5vj0VlV5qiIssGLYnCVmPvc,11344
12
+ datalab_python_sdk-0.15.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ datalab_python_sdk-0.15.0.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
14
+ datalab_python_sdk-0.15.0.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
15
+ datalab_python_sdk-0.15.0.dist-info/RECORD,,
datalab_sdk/__init__.py CHANGED
@@ -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")
datalab_sdk/auth.py CHANGED
@@ -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: