datalab-python-sdk 0.12.0__py3-none-any.whl → 0.14.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.12.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, 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
 
@@ -183,7 +183,18 @@ Published-agent execution is in open beta; the API may change. Processor design
183
183
 
184
184
  - Send a local file with `file_path`, or a URL or a `datalab://file-...` reference with `file_url`. When you set `processing_location`, send the document as `file_url`.
185
185
  - Processing methods poll until the result is ready. The first 8 seconds poll every 0.3 seconds. Set `max_polls` and `poll_interval` to change the limit (default: 300 polls, 1 second apart). Use `stream_response_to` to write a large result straight to disk. It returns a `FileResult` with the status, `output_path` and, when the poll response sends them, `request_id`, `page_count`, `parse_quality_score`, `versions`, `runtime` and `cost_breakdown`.
186
- - The SDK retries a submission that gets HTTP 429 or 503, and polls or result downloads that get 408, 429, 5xx or a connection error, including one that happens while a result streams. It waits for the `Retry-After` header when the API sends one.
186
+ - The SDK retries a submission that gets HTTP 429 or 503, and polls or result downloads that get 408, 429, 5xx or a connection error, including one that happens while a result streams. It tries each request at most 10 times, and waits for the `Retry-After` header when the API sends one. `timeout` applies to each request, including the whole download of a result. A finished result that times out while it downloads from a signed `result_url`, or streams with `stream_response_to`, is not retried.
187
+ - Timeouts raise `DatalabTimeoutError`. `DatalabPollingTimeoutError` means the polling budget ran out and the request is still running; `DatalabTransferTimeoutError` means the request finished but its result timed out while it downloaded, so raise `timeout` before you fetch it again. An error that a document-processing method raises after the API accepted the request has `request_id` and `check_url`. Pass `check_url` to `get_result()` to fetch the result without submitting the document again. For `run_pipeline()`, `request_id` holds the execution ID for `get_pipeline_execution()`.
188
+
189
+ ```python
190
+ from datalab_sdk import DatalabClient, DatalabPollingTimeoutError
191
+
192
+ client = DatalabClient()
193
+ try:
194
+ result = client.convert("big.pdf", max_polls=60)
195
+ except DatalabPollingTimeoutError as e:
196
+ result = client.get_result(e.check_url, max_polls=600)
197
+ ```
187
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`.
188
199
 
189
200
  With SDK 0.9.0, `upload_files(paths, max_concurrency=5)` streams
@@ -0,0 +1,14 @@
1
+ datalab_sdk/__init__.py,sha256=MRRQMFIAhGx5sLnOzvVyKlusLzKj1F2k-_SaE6ivk6o,3455
2
+ datalab_sdk/_output_layout.py,sha256=wQOUiAWYi_7vuyBSc0Nj9UA_WUKJElKX86tkwtCDWGQ,7833
3
+ datalab_sdk/auth.py,sha256=i7LzAMM5wjY5-J6BUf69do6g7zuKenQZQwueqbLJSNU,7704
4
+ datalab_sdk/cli.py,sha256=Ft7oufL1_mTRoPHGBi68PFS6ts51KW6Ar7Q3BN4qY8A,63497
5
+ datalab_sdk/client.py,sha256=rDCoHiaBuk-lna6-vjskAlQd8cF8J0qCxwiQAkzn6bE,172216
6
+ datalab_sdk/exceptions.py,sha256=GFRAZQoxP2cHYJ3Q-OBjU_3I34Om3avcz11vczc_GNs,4420
7
+ datalab_sdk/mimetypes.py,sha256=a4ULJmHxoR_RMsD0j51hx0t2Q7In_PzNm7UlWX07eEE,932
8
+ datalab_sdk/models.py,sha256=j6UruxDaGp1gfcc7YHMNr7ZUg6ez0Jx-8gzJ18efNkQ,43374
9
+ datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
10
+ datalab_python_sdk-0.14.0.dist-info/METADATA,sha256=enze4Ey2TNIEl4Yd93Mne_oFTJOt1d5tEy-2OYTjWGg,11513
11
+ datalab_python_sdk-0.14.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ datalab_python_sdk-0.14.0.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
13
+ datalab_python_sdk-0.14.0.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
14
+ datalab_python_sdk-0.14.0.dist-info/RECORD,,
datalab_sdk/__init__.py CHANGED
@@ -15,6 +15,8 @@ from .exceptions import (
15
15
  DatalabRateLimitError,
16
16
  DatalabServerError,
17
17
  DatalabTimeoutError,
18
+ DatalabTransferTimeoutError,
19
+ DatalabPollingTimeoutError,
18
20
  DatalabFileError,
19
21
  DatalabValidationError,
20
22
  )
@@ -86,6 +88,8 @@ __all__ = [
86
88
  "DatalabRateLimitError",
87
89
  "DatalabServerError",
88
90
  "DatalabTimeoutError",
91
+ "DatalabTransferTimeoutError",
92
+ "DatalabPollingTimeoutError",
89
93
  "DatalabFileError",
90
94
  "DatalabValidationError",
91
95
  "ConversionResult",
@@ -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())
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: