datalab-python-sdk 0.13.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.13.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
 
@@ -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,,
@@ -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:
datalab_sdk/cli.py CHANGED
@@ -28,6 +28,8 @@ from datalab_sdk.models import (
28
28
  InputConfig,
29
29
  ComparisonVariant,
30
30
  )
31
+ from datalab_sdk._output_layout import OUTPUT_MARKER, OutputLayout
32
+ from datalab_sdk.auth import resolve_api_key
31
33
  from datalab_sdk.exceptions import DatalabError
32
34
  from datalab_sdk.settings import settings
33
35
  import dataclasses
@@ -83,7 +85,12 @@ def common_options(func):
83
85
  """Common options for all commands"""
84
86
  func = click.option("--api_key", required=False, help="Datalab API key")(func)
85
87
  func = click.option(
86
- "--output_dir", "-o", required=False, type=click.Path(), help="Output directory"
88
+ "--output_dir",
89
+ "-o",
90
+ required=False,
91
+ type=click.Path(),
92
+ help="Output directory (default: ./output). Each input saves to its "
93
+ "own folder, such as a/report/ for a/report.pdf.",
87
94
  )(func)
88
95
  func = click.option(
89
96
  "--max_pages", type=int, help="Maximum number of pages to process"
@@ -186,24 +193,39 @@ def convert_extra_options(func):
186
193
  return func
187
194
 
188
195
 
196
+ # The output root when --output_dir is not given, under the working directory.
197
+ DEFAULT_OUTPUT_DIR = "output"
198
+
199
+
189
200
  def find_files_in_directory(
190
201
  directory: Path, extensions: Optional[List[str]] = None
191
202
  ) -> List[Path]:
192
- """Find all supported files in a directory"""
203
+ """Find all supported files in a directory.
204
+
205
+ The scan skips folders that the CLI saved output to (they hold
206
+ OUTPUT_MARKER), so a later run doesn't process an earlier run's output.
207
+ """
193
208
  if extensions is None:
194
209
  extensions = SUPPORTED_EXTENSIONS
195
210
 
196
211
  files = []
197
- for file_path in directory.rglob("*"):
198
- if file_path.is_file() and file_path.suffix.lower() in extensions:
199
- files.append(file_path)
212
+ for dirpath, dirnames, filenames in os.walk(directory):
213
+ current = Path(dirpath)
214
+ if OUTPUT_MARKER in filenames:
215
+ dirnames[:] = []
216
+ continue
217
+ dirnames.sort()
218
+ for name in sorted(filenames):
219
+ file_path = current / name
220
+ if file_path.suffix.lower() in extensions and file_path.is_file():
221
+ files.append(file_path)
200
222
 
201
223
  return files
202
224
 
203
225
 
204
226
  async def process_files_async(
205
227
  files: List[Path],
206
- output_dir: Path,
228
+ layout: OutputLayout,
207
229
  method: str,
208
230
  options: Optional[ProcessingOptions] = None,
209
231
  max_concurrent: int = 5,
@@ -212,7 +234,8 @@ async def process_files_async(
212
234
  max_polls: int = 300,
213
235
  poll_interval: int = 1,
214
236
  ) -> List[dict]:
215
- """Process files asynchronously"""
237
+ """Process files asynchronously. Each file saves to its folder in `layout`,
238
+ which the caller has entered."""
216
239
  semaphore = asyncio.Semaphore(max_concurrent)
217
240
 
218
241
  async def call_api(client, file_path, output_path):
@@ -241,13 +264,10 @@ async def process_files_async(
241
264
 
242
265
  async def process_single_file(file_path: Path) -> dict:
243
266
  async with semaphore:
267
+ output_path = layout.output_path(file_path)
268
+ # The folder can hold an earlier run's results: only new writes count.
269
+ before = layout.snapshot(file_path)
244
270
  try:
245
- # Create output path
246
- relative_path = file_path.name
247
- output_path = (
248
- output_dir / Path(relative_path).stem / Path(relative_path).stem
249
- )
250
-
251
271
  async with AsyncDatalabClient(
252
272
  api_key=api_key, base_url=base_url
253
273
  ) as client:
@@ -259,6 +279,7 @@ async def process_files_async(
259
279
  "success": result.success,
260
280
  "error": result.error,
261
281
  "page_count": result.page_count,
282
+ "saved": layout.wrote_output(file_path, before),
262
283
  }
263
284
  except Exception as e:
264
285
  return {
@@ -267,6 +288,8 @@ async def process_files_async(
267
288
  "success": False,
268
289
  "error": str(e),
269
290
  "page_count": None,
291
+ # A save can fail after writing some of the results.
292
+ "saved": layout.wrote_output(file_path, before),
270
293
  }
271
294
 
272
295
  # Process all files concurrently with progress bar
@@ -287,13 +310,11 @@ async def process_files_async(
287
310
 
288
311
 
289
312
  def setup_output_directory(output_dir: Optional[str]) -> Path:
290
- """Setup and return output directory"""
313
+ """Return the output directory. Each input's folder is created under it
314
+ before its request is submitted, so a run that saves nothing makes nothing."""
291
315
  if output_dir is None:
292
- output_dir = os.getcwd()
293
-
294
- output_dir = Path(output_dir)
295
- output_dir.mkdir(parents=True, exist_ok=True)
296
- return output_dir
316
+ output_dir = DEFAULT_OUTPUT_DIR
317
+ return Path(output_dir)
297
318
 
298
319
 
299
320
  def parse_extensions(extensions: Optional[str]) -> Optional[List[str]]:
@@ -320,9 +341,14 @@ def get_files_to_process(
320
341
  return find_files_in_directory(path, file_extensions)
321
342
 
322
343
 
323
- def show_results(results: List[dict], operation: str, output_dir: Path):
324
- """Display processing results"""
344
+ def show_results(results: List[dict], operation: str, output_dir: Path) -> int:
345
+ """Print a summary of the results, and return the number of failed files.
346
+
347
+ The summary names the output folder only when this run wrote a result to
348
+ it, which a failed file can do when its save fails partway.
349
+ """
325
350
  successful = sum(1 for r in results if r["success"])
351
+ saved = any(r["saved"] for r in results)
326
352
  failed = len(results) - successful
327
353
 
328
354
  click.echo(f"\n{operation} Summary:")
@@ -336,7 +362,11 @@ def show_results(results: List[dict], operation: str, output_dir: Path):
336
362
  if not result["success"]:
337
363
  click.echo(f" - {result['file_path']}: {result['error']}")
338
364
 
339
- click.echo(f"\nOutput saved to: {output_dir}")
365
+ if saved:
366
+ click.echo(f"\nOutput saved to: {output_dir.absolute()}")
367
+ else:
368
+ click.echo("\nNo output was saved.")
369
+ return failed
340
370
 
341
371
 
342
372
  def process_documents(
@@ -372,19 +402,10 @@ def process_documents(
372
402
  """Unified document processing function"""
373
403
  try:
374
404
  # Validate inputs
375
- if api_key is None:
376
- api_key = settings.DATALAB_API_KEY
377
-
378
- if api_key is None:
379
- raise DatalabError(
380
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
381
- "Get a free API key at https://www.datalab.to/app/keys"
382
- )
383
-
384
405
  if base_url is None:
385
406
  base_url = settings.DATALAB_HOST
407
+ api_key = resolve_api_key(api_key, base_url)
386
408
 
387
- output_dir_path = setup_output_directory(output_dir)
388
409
  file_extensions = parse_extensions(extensions)
389
410
 
390
411
  # Get files to process
@@ -394,8 +415,12 @@ def process_documents(
394
415
  if not to_process:
395
416
  click.echo(f"No supported files found in {path}", err=True)
396
417
  sys.exit(1)
418
+ output_dir_path = setup_output_directory(output_dir)
419
+ input_root = path if path.is_dir() else path.parent
420
+ layout = OutputLayout.plan(to_process, input_root, output_dir_path)
397
421
 
398
422
  click.echo(f"Found {len(to_process)} files to process")
423
+ click.echo(f"Saving results to: {output_dir_path.absolute()}")
399
424
 
400
425
  # Create processing options based on method
401
426
  if options_override:
@@ -457,19 +482,20 @@ def process_documents(
457
482
  skip_cache=skip_cache,
458
483
  )
459
484
 
460
- results = asyncio.run(
461
- process_files_async(
462
- to_process,
463
- output_dir_path,
464
- method,
465
- options=options,
466
- max_concurrent=max_concurrent,
467
- api_key=api_key,
468
- base_url=base_url,
469
- max_polls=max_polls,
470
- poll_interval=poll_interval,
485
+ with layout:
486
+ results = asyncio.run(
487
+ process_files_async(
488
+ to_process,
489
+ layout,
490
+ method,
491
+ options=options,
492
+ max_concurrent=max_concurrent,
493
+ api_key=api_key,
494
+ base_url=base_url,
495
+ max_polls=max_polls,
496
+ poll_interval=poll_interval,
497
+ )
471
498
  )
472
- )
473
499
 
474
500
  # Show results
475
501
  operation_names = {
@@ -484,7 +510,9 @@ def process_documents(
484
510
  "ocr": "OCR",
485
511
  }
486
512
  operation = operation_names.get(method, method.title())
487
- show_results(results, operation, output_dir_path)
513
+ failed = show_results(results, operation, output_dir_path)
514
+ if failed:
515
+ sys.exit(1)
488
516
 
489
517
  except DatalabError as e:
490
518
  click.echo(f"Error: {e}", err=True)
@@ -1036,7 +1064,12 @@ def form_fields(
1036
1064
  @webhook_option
1037
1065
  @click.option("--api_key", required=False, help="Datalab API key")
1038
1066
  @click.option(
1039
- "--output_dir", "-o", required=False, type=click.Path(), help="Output directory"
1067
+ "--output_dir",
1068
+ "-o",
1069
+ required=False,
1070
+ type=click.Path(),
1071
+ help="Output directory (default: ./output). Each input saves to its "
1072
+ "own folder, such as a/report/ for a/report.pdf.",
1040
1073
  )
1041
1074
  @click.option(
1042
1075
  "--extensions", help="Comma-separated list of file extensions (for directories)"
@@ -1118,15 +1151,6 @@ def create_document(
1118
1151
  ):
1119
1152
  """Create a DOCX document from markdown"""
1120
1153
  try:
1121
- if api_key is None:
1122
- api_key = settings.DATALAB_API_KEY
1123
-
1124
- if api_key is None:
1125
- raise DatalabError(
1126
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1127
- "Get a free API key at https://www.datalab.to/app/keys"
1128
- )
1129
-
1130
1154
  # Check if markdown_input is a file path
1131
1155
  md_path = Path(markdown_input)
1132
1156
  if md_path.exists() and md_path.is_file():
@@ -1159,17 +1183,6 @@ def create_document(
1159
1183
  _LEGACY_EVAL_META = "datalab_legacy_eval"
1160
1184
 
1161
1185
 
1162
- def _compare_client(api_key: Optional[str], base_url: str) -> DatalabClient:
1163
- if api_key is None:
1164
- api_key = settings.DATALAB_API_KEY
1165
- if api_key is None:
1166
- raise DatalabError(
1167
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1168
- "Get a free API key at https://www.datalab.to/app/keys"
1169
- )
1170
- return DatalabClient(api_key=api_key, base_url=base_url)
1171
-
1172
-
1173
1186
  def _legacy_eval() -> bool:
1174
1187
  """True when the command runs as the deprecated `datalab eval`."""
1175
1188
  return bool(click.get_current_context().meta.get(_LEGACY_EVAL_META))
@@ -1210,6 +1223,9 @@ def _print_comparison_summary(comparison) -> None:
1210
1223
  f" {variant.name}: share={share} decided={variant.decided} won={variant.won} "
1211
1224
  f"rate={rate} speed={speed}"
1212
1225
  )
1226
+ for file in comparison.files or []:
1227
+ if file.comparison_error:
1228
+ click.echo(f" {file.file_name}: {file.comparison_error}")
1213
1229
 
1214
1230
 
1215
1231
  compare_option_api_key = click.option(
@@ -1304,7 +1320,7 @@ def compare_run(
1304
1320
  for v in data
1305
1321
  ]
1306
1322
 
1307
- client = _compare_client(api_key, base_url)
1323
+ client = DatalabClient(api_key=api_key, base_url=base_url)
1308
1324
  file_ids = None
1309
1325
  if paths:
1310
1326
  uploaded = client.upload_files(list(paths))
@@ -1327,6 +1343,19 @@ def compare_run(
1327
1343
  _echo_json(comparison)
1328
1344
  else:
1329
1345
  _print_comparison_summary(comparison)
1346
+ failed_files = [
1347
+ f for f in comparison.files or [] if f.comparison == "failed"
1348
+ ]
1349
+ if comparison.status == "failed":
1350
+ click.echo(f"Comparison {comparison.comparison_id} failed.", err=True)
1351
+ sys.exit(1)
1352
+ if failed_files:
1353
+ click.echo(
1354
+ f"Comparison {comparison.comparison_id}: {len(failed_files)} of "
1355
+ f"{len(comparison.files)} files failed.",
1356
+ err=True,
1357
+ )
1358
+ sys.exit(1)
1330
1359
  elif json_output:
1331
1360
  _echo_json(comparison)
1332
1361
  else:
@@ -1349,7 +1378,7 @@ def compare_get(
1349
1378
  ):
1350
1379
  """[Open beta] Get a comparison's status and each variant's result."""
1351
1380
  try:
1352
- client = _compare_client(api_key, base_url)
1381
+ client = DatalabClient(api_key=api_key, base_url=base_url)
1353
1382
  comparison = client.get_comparison(comparison_id)
1354
1383
  if json_output:
1355
1384
  _echo_json(comparison)
@@ -1379,7 +1408,7 @@ def compare_list(
1379
1408
  ):
1380
1409
  """[Open beta] List the team's comparisons, newest first."""
1381
1410
  try:
1382
- client = _compare_client(api_key, base_url)
1411
+ client = DatalabClient(api_key=api_key, base_url=base_url)
1383
1412
  result = client.list_comparisons(
1384
1413
  pipeline_id=pipeline_id,
1385
1414
  collection_id=collection_id,
@@ -1414,7 +1443,7 @@ def compare_differences(
1414
1443
  ):
1415
1444
  """[Open beta] Show where a comparison's variants read one document differently."""
1416
1445
  try:
1417
- client = _compare_client(api_key, base_url)
1446
+ client = DatalabClient(api_key=api_key, base_url=base_url)
1418
1447
  result = client.get_comparison_differences(comparison_id, file_id)
1419
1448
  if json_output:
1420
1449
  _echo_json(result)
@@ -1466,15 +1495,6 @@ def create_workflow(
1466
1495
  """[Deprecated: the API removed workflows] Create a new workflow"""
1467
1496
  _echo_workflows_removed()
1468
1497
  try:
1469
- if api_key is None:
1470
- api_key = settings.DATALAB_API_KEY
1471
-
1472
- if api_key is None:
1473
- raise DatalabError(
1474
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1475
- "Get a free API key at https://www.datalab.to/app/keys"
1476
- )
1477
-
1478
1498
  # Parse steps from JSON string or file
1479
1499
  steps_path = Path(steps)
1480
1500
  if steps_path.exists():
@@ -1520,15 +1540,6 @@ def get_workflow(workflow_id: int, api_key: Optional[str], base_url: str):
1520
1540
  """[Deprecated: the API removed workflows] Get a workflow by ID"""
1521
1541
  _echo_workflows_removed()
1522
1542
  try:
1523
- if api_key is None:
1524
- api_key = settings.DATALAB_API_KEY
1525
-
1526
- if api_key is None:
1527
- raise DatalabError(
1528
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1529
- "Get a free API key at https://www.datalab.to/app/keys"
1530
- )
1531
-
1532
1543
  client = DatalabClient(api_key=api_key, base_url=base_url)
1533
1544
  workflow = client.get_workflow(workflow_id)
1534
1545
 
@@ -1558,15 +1569,6 @@ def get_step_types(api_key: Optional[str], base_url: str):
1558
1569
  """[Deprecated: the API removed workflows] Get all available workflow step types"""
1559
1570
  _echo_workflows_removed()
1560
1571
  try:
1561
- if api_key is None:
1562
- api_key = settings.DATALAB_API_KEY
1563
-
1564
- if api_key is None:
1565
- raise DatalabError(
1566
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1567
- "Get a free API key at https://www.datalab.to/app/keys"
1568
- )
1569
-
1570
1572
  client = DatalabClient(api_key=api_key, base_url=base_url)
1571
1573
  response = client.get_step_types()
1572
1574
 
@@ -1601,15 +1603,6 @@ def list_workflows(api_key: Optional[str], base_url: str):
1601
1603
  """[Deprecated: the API removed workflows] List all workflows for your team"""
1602
1604
  _echo_workflows_removed()
1603
1605
  try:
1604
- if api_key is None:
1605
- api_key = settings.DATALAB_API_KEY
1606
-
1607
- if api_key is None:
1608
- raise DatalabError(
1609
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1610
- "Get a free API key at https://www.datalab.to/app/keys"
1611
- )
1612
-
1613
1606
  client = DatalabClient(api_key=api_key, base_url=base_url)
1614
1607
  workflows = client.list_workflows()
1615
1608
 
@@ -1649,15 +1642,6 @@ def execute_workflow(
1649
1642
  """[Deprecated: the API removed workflows] Trigger a workflow execution"""
1650
1643
  _echo_workflows_removed()
1651
1644
  try:
1652
- if api_key is None:
1653
- api_key = settings.DATALAB_API_KEY
1654
-
1655
- if api_key is None:
1656
- raise DatalabError(
1657
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1658
- "Get a free API key at https://www.datalab.to/app/keys"
1659
- )
1660
-
1661
1645
  # Parse input_config from JSON string or file
1662
1646
  input_path = Path(input_config)
1663
1647
  if input_path.exists():
@@ -1737,15 +1721,6 @@ def get_execution_status(
1737
1721
  """[Deprecated: the API removed workflows] Get the status of a workflow execution"""
1738
1722
  _echo_workflows_removed()
1739
1723
  try:
1740
- if api_key is None:
1741
- api_key = settings.DATALAB_API_KEY
1742
-
1743
- if api_key is None:
1744
- raise DatalabError(
1745
- "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1746
- "Get a free API key at https://www.datalab.to/app/keys"
1747
- )
1748
-
1749
1724
  client = DatalabClient(api_key=api_key, base_url=base_url)
1750
1725
  execution = client.get_execution_status(
1751
1726
  execution_id=execution_id,
datalab_sdk/client.py CHANGED
@@ -23,11 +23,13 @@ from tenacity import (
23
23
  retry_if_exception_type,
24
24
  retry_if_not_exception_type,
25
25
  stop_after_attempt,
26
- wait_exponential_jitter,
26
+ wait_exponential,
27
+ wait_random,
27
28
  )
28
29
  from pathlib import Path
29
30
  from typing import Union, Optional, Dict, Any, Callable, Awaitable
30
31
 
32
+ from datalab_sdk.auth import resolve_api_key
31
33
  from datalab_sdk.exceptions import (
32
34
  DatalabAPIError,
33
35
  DatalabError,
@@ -122,7 +124,12 @@ _TERMINAL_PIPELINE_STATUSES = (
122
124
  )
123
125
 
124
126
  _SUBMIT_RETRY_STATUSES = (429, 503)
125
- _BACKOFF = wait_exponential_jitter(initial=5, max=120)
127
+ # Exponential backoff with jitter: 5, 10, 20... seconds plus up to 1 second,
128
+ # at most 120 in all (_wait_retry_after_or_backoff clamps it).
129
+ # wait_exponential_jitter's `initial` is deprecated in tenacity 9.2, and its
130
+ # replacement isn't in 8.2.3, the oldest tenacity the SDK supports.
131
+ _BACKOFF = wait_exponential(multiplier=5, max=120) + wait_random(0, 1)
132
+ _MAX_BACKOFF_SECONDS = 120.0
126
133
  _MAX_RETRY_AFTER_SECONDS = 120.0
127
134
  # The first FAST_POLL_SECONDS of a result poll check every FAST_POLL_INTERVAL
128
135
  # seconds, then every poll_interval.
@@ -141,7 +148,7 @@ def _wait_retry_after_or_backoff(retry_state) -> float:
141
148
  retry_after = getattr(exc, "retry_after", None)
142
149
  if retry_after is not None:
143
150
  return min(max(retry_after, 0.0), _MAX_RETRY_AFTER_SECONDS)
144
- return _BACKOFF(retry_state)
151
+ return min(_BACKOFF(retry_state), _MAX_BACKOFF_SECONDS)
145
152
 
146
153
 
147
154
  def _is_retryable_submit_error(e: BaseException) -> bool:
@@ -397,24 +404,14 @@ class AsyncDatalabClient:
397
404
  Initialize the async Datalab client
398
405
 
399
406
  Args:
400
- api_key: Your Datalab API key
407
+ api_key: Your Datalab API key. Defaults to DATALAB_API_KEY, then to
408
+ the key saved by `datalab login` when base_url is the host it
409
+ was saved for.
401
410
  base_url: Base URL for the API (default: https://www.datalab.to)
402
411
  timeout: Default timeout for requests in seconds
403
412
  """
404
- if api_key is None:
405
- api_key = settings.DATALAB_API_KEY
406
- if api_key is None:
407
- from datalab_sdk.auth import load_saved_api_key
408
-
409
- api_key = load_saved_api_key()
410
- if api_key is None:
411
- raise DatalabAPIError(
412
- "No API key. Run `datalab login`, set DATALAB_API_KEY, or pass api_key. "
413
- "Get a free API key at https://www.datalab.to/app/keys"
414
- )
415
-
416
- self.api_key = api_key
417
413
  self.base_url = base_url.rstrip("/")
414
+ self.api_key = resolve_api_key(api_key, self.base_url)
418
415
  self.timeout = timeout
419
416
  self._session = None
420
417
 
@@ -3505,7 +3502,9 @@ class DatalabClient:
3505
3502
  Initialize the Datalab client
3506
3503
 
3507
3504
  Args:
3508
- api_key: Your Datalab API key
3505
+ api_key: Your Datalab API key. Defaults to DATALAB_API_KEY, then to
3506
+ the key saved by `datalab login` when base_url is the host it
3507
+ was saved for.
3509
3508
  base_url: Base URL for the API (default: https://www.datalab.to)
3510
3509
  timeout: Default timeout for requests in seconds
3511
3510
  """
@@ -3515,9 +3514,16 @@ class DatalabClient:
3515
3514
  """Run async coroutine in sync context"""
3516
3515
  try:
3517
3516
  loop = asyncio.get_event_loop()
3518
- except RuntimeError:
3519
- # Only a missing loop should select asyncio.run. RuntimeError from
3520
- # the operation itself must propagate without rerunning it.
3517
+ except (RuntimeError, DeprecationWarning):
3518
+ # No current loop: the normal case in a script on Python 3.14. On
3519
+ # 3.12 and 3.13 the same case warns, which raises under
3520
+ # -W error::DeprecationWarning. An installed idle loop is reused,
3521
+ # because asyncio.run() would unset it for the caller.
3522
+ loop = None
3523
+ # Run outside the except block, so an error from the operation isn't
3524
+ # chained to the RuntimeError above. RuntimeError from the operation
3525
+ # itself propagates without rerunning it.
3526
+ if loop is None or loop.is_closed():
3521
3527
  return asyncio.run(self._async_wrapper(coro))
3522
3528
  if loop.is_running():
3523
3529
  coro.close()
@@ -3525,8 +3531,6 @@ class DatalabClient:
3525
3531
  "DatalabClient cannot run inside an active event loop; "
3526
3532
  "use AsyncDatalabClient instead."
3527
3533
  )
3528
- if loop.is_closed():
3529
- return asyncio.run(self._async_wrapper(coro))
3530
3534
  return loop.run_until_complete(self._async_wrapper(coro))
3531
3535
 
3532
3536
  async def _async_wrapper(self, coro):
@@ -1,13 +0,0 @@
1
- datalab_sdk/__init__.py,sha256=MRRQMFIAhGx5sLnOzvVyKlusLzKj1F2k-_SaE6ivk6o,3455
2
- datalab_sdk/auth.py,sha256=X2eccKzpdxogFEDoS4geOHIOeECQ8u3kANxKoqF0PVk,4388
3
- datalab_sdk/cli.py,sha256=g_qR_xMJS19PYVOf19HRD3nl3GnzHf1bIohh7WY5AO0,63928
4
- datalab_sdk/client.py,sha256=i8ykHqFiYrmNS-8oW9Z96WZZIa6qU820fsqyJIHgqRA,171577
5
- datalab_sdk/exceptions.py,sha256=GFRAZQoxP2cHYJ3Q-OBjU_3I34Om3avcz11vczc_GNs,4420
6
- datalab_sdk/mimetypes.py,sha256=a4ULJmHxoR_RMsD0j51hx0t2Q7In_PzNm7UlWX07eEE,932
7
- datalab_sdk/models.py,sha256=j6UruxDaGp1gfcc7YHMNr7ZUg6ez0Jx-8gzJ18efNkQ,43374
8
- datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
9
- datalab_python_sdk-0.13.0.dist-info/METADATA,sha256=kEfjCus4oyKDL-HNY8R30cRr_esw_0AyiMWzvBsZDSw,11417
10
- datalab_python_sdk-0.13.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
- datalab_python_sdk-0.13.0.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
12
- datalab_python_sdk-0.13.0.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
13
- datalab_python_sdk-0.13.0.dist-info/RECORD,,