datalab-python-sdk 0.11.0__py3-none-any.whl → 0.13.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.11.0
3
+ Version: 0.13.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
@@ -182,8 +182,19 @@ Published-agent execution is in open beta; the API may change. Processor design
182
182
  ## Inputs, polling and errors
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
- - 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.
186
- - The SDK retries a submission that gets HTTP 429 or 503, and polls that get 408, 429, 5xx or a connection error. It waits for the `Retry-After` header when the API sends one.
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 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,13 @@
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,,
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",
datalab_sdk/client.py CHANGED
@@ -3,6 +3,9 @@ Datalab API client - async core with sync wrapper
3
3
  """
4
4
 
5
5
  import asyncio
6
+ import contextlib
7
+ import dataclasses
8
+ import decimal
6
9
  import inspect
7
10
  import json as jsonlib
8
11
  import mimetypes
@@ -10,6 +13,7 @@ import os
10
13
  import shutil
11
14
  import tempfile
12
15
  import warnings
16
+ from urllib.parse import urlsplit
13
17
 
14
18
  import aiohttp
15
19
  import ijson
@@ -17,6 +21,7 @@ from tenacity import (
17
21
  retry,
18
22
  retry_if_exception,
19
23
  retry_if_exception_type,
24
+ retry_if_not_exception_type,
20
25
  stop_after_attempt,
21
26
  wait_exponential_jitter,
22
27
  )
@@ -25,7 +30,10 @@ from typing import Union, Optional, Dict, Any, Callable, Awaitable
25
30
 
26
31
  from datalab_sdk.exceptions import (
27
32
  DatalabAPIError,
33
+ DatalabError,
34
+ DatalabPollingTimeoutError,
28
35
  DatalabTimeoutError,
36
+ DatalabTransferTimeoutError,
29
37
  DatalabFileError,
30
38
  DatalabValidationError,
31
39
  api_error_for_status,
@@ -157,6 +165,50 @@ def _is_retryable_poll_error(e: BaseException) -> bool:
157
165
  )
158
166
 
159
167
 
168
+ # Polls are GETs, so a transient failure can be retried without submitting
169
+ # the request again. A transfer timeout is not retried: the timeout limits
170
+ # the whole request, so a result too large to transfer within it would time
171
+ # out again on every attempt.
172
+ _poll_retry = retry(
173
+ retry=(
174
+ (
175
+ retry_if_exception_type(DatalabTimeoutError)
176
+ & retry_if_not_exception_type(DatalabTransferTimeoutError)
177
+ )
178
+ | retry_if_exception(_is_retryable_poll_error)
179
+ ),
180
+ stop=stop_after_attempt(10),
181
+ wait=_wait_retry_after_or_backoff,
182
+ reraise=True,
183
+ )
184
+
185
+
186
+ @contextlib.contextmanager
187
+ def _request_handle(request_id: Optional[str], check_url: Optional[str] = None):
188
+ """Attach an accepted request to a DatalabError raised inside the block,
189
+ so the caller can resume it instead of submitting again."""
190
+ try:
191
+ yield
192
+ except DatalabError as e:
193
+ if e.request_id is None:
194
+ e.request_id = request_id
195
+ if e.check_url is None:
196
+ e.check_url = check_url
197
+ raise
198
+
199
+
200
+ # Top-level fields of a poll response that a streamed call returns on
201
+ # FileResult. A signed result_url download does not contain them.
202
+ _FILE_RESULT_FIELDS = (
203
+ "request_id",
204
+ "page_count",
205
+ "parse_quality_score",
206
+ "versions",
207
+ "runtime",
208
+ "cost_breakdown",
209
+ )
210
+
211
+
160
212
  def _error_message_from_body(error_data: Any, fallback: str) -> str:
161
213
  """Make a readable message from an API error body.
162
214
 
@@ -228,19 +280,108 @@ def _warn_eval_renamed(old: str, new: str) -> None:
228
280
  )
229
281
 
230
282
 
231
- class _AsyncIterableReader:
232
- """Adapts an async iterable of bytes into an async file-like object for ijson."""
283
+ def _floats(value: Any) -> Any:
284
+ """Turn the Decimals that ijson returns for fractions into floats."""
285
+ if isinstance(value, decimal.Decimal):
286
+ return float(value)
287
+ if isinstance(value, dict):
288
+ return {k: _floats(v) for k, v in value.items()}
289
+ if isinstance(value, list):
290
+ return [_floats(v) for v in value]
291
+ return value
233
292
 
234
- def __init__(self, async_iterable):
235
- self._iter = async_iterable.__aiter__()
236
293
 
237
- async def read(self, n=-1):
238
- if n == 0:
239
- return b""
240
- try:
241
- return await self._iter.__anext__()
242
- except StopAsyncIteration:
243
- return b""
294
+ async def _read_error_body(resp: aiohttp.ClientResponse) -> bytes:
295
+ """Read an error body, or return b"" if it fails.
296
+
297
+ The status is already known, so a cut-off or stalled error body must not
298
+ change whether the error is retried.
299
+ """
300
+ try:
301
+ return await resp.read()
302
+ except (aiohttp.ClientError, asyncio.TimeoutError):
303
+ return b""
304
+
305
+
306
+ class _StreamedPollFields:
307
+ """Reads the top-level fields of a streamed poll response from ijson events.
308
+
309
+ Only the small fields are kept; the output itself stays on disk.
310
+ """
311
+
312
+ def __init__(self):
313
+ self.status = None
314
+ self.success = None
315
+ self.error = None
316
+ self.result_url = None
317
+ self.progress_percent = None
318
+ self.fields: Dict[str, Any] = {}
319
+ self._builder = None
320
+ self._builder_key = None
321
+
322
+ def feed(self, events) -> None:
323
+ for prefix, event, value in events:
324
+ if self._builder is not None:
325
+ # Build an object or array field, such as cost_breakdown,
326
+ # until its closing event.
327
+ self._builder.event(event, value)
328
+ if prefix == self._builder_key and event in ("end_map", "end_array"):
329
+ self.fields[self._builder_key] = _floats(self._builder.value)
330
+ self._builder = None
331
+ elif prefix in _FILE_RESULT_FIELDS:
332
+ if event in ("start_map", "start_array"):
333
+ self._builder = ijson.ObjectBuilder()
334
+ self._builder.event(event, value)
335
+ self._builder_key = prefix
336
+ else:
337
+ self.fields[prefix] = _floats(value)
338
+ elif prefix == "status" and event == "string":
339
+ self.status = value
340
+ elif prefix == "success" and event == "boolean":
341
+ self.success = value
342
+ elif prefix == "error" and event in ("string", "null"):
343
+ self.error = value
344
+ elif prefix == "result_url" and event == "string":
345
+ self.result_url = value
346
+ elif prefix == "progress_percent" and event == "number":
347
+ self.progress_percent = value
348
+
349
+
350
+ def _save_to(result: Any, save_output: Union[str, Path]) -> None:
351
+ output_path = Path(save_output)
352
+ output_path.parent.mkdir(parents=True, exist_ok=True)
353
+ result.save_output(output_path)
354
+
355
+
356
+ def _save_successful(result: Any, save_output: Optional[Union[str, Path]]) -> None:
357
+ if save_output and result.success:
358
+ _save_to(result, save_output)
359
+
360
+
361
+ def _save_successful_document(
362
+ result: Any, save_output: Optional[Union[str, Path]]
363
+ ) -> None:
364
+ if save_output and result.success and result.output_base64:
365
+ _save_to(result, save_output)
366
+
367
+
368
+ def _save_redacted_document(
369
+ result: RedactResult, save_output: Optional[Union[str, Path]]
370
+ ) -> None:
371
+ # A redacted PDF is saved even when verification failed; see redact().
372
+ if save_output and result.output_base64:
373
+ _save_to(result, save_output)
374
+
375
+
376
+ @dataclasses.dataclass(frozen=True)
377
+ class _ResultPolicy:
378
+ """How one endpoint's poll response becomes its result. The processing
379
+ methods and get_result() share it through AsyncDatalabClient._finish()."""
380
+
381
+ build: Callable[..., Any]
382
+ save: Callable[[Any, Optional[Union[str, Path]]], None]
383
+ result_transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None
384
+ streamable: bool = True
244
385
 
245
386
 
246
387
  class AsyncDatalabClient:
@@ -374,6 +515,7 @@ class AsyncDatalabClient:
374
515
  fast_until = loop.time() + FAST_POLL_SECONDS if 0 < poll_interval <= 1 else 0.0
375
516
  budget = max_polls * poll_interval
376
517
  slept = 0.0
518
+ status = percent = None
377
519
  for i in range(max_polls if poll_interval <= 0 else _MAX_POLL_REQUESTS):
378
520
  if stream_response_to:
379
521
  result = await self._poll_get_streaming(full_url, stream_response_to)
@@ -411,19 +553,14 @@ class AsyncDatalabClient:
411
553
  await asyncio.sleep(delay)
412
554
  slept += delay
413
555
 
414
- raise DatalabTimeoutError(
415
- f"Polling timed out after {max_polls * poll_interval} seconds"
556
+ raise DatalabPollingTimeoutError(
557
+ f"Polling timed out after {max_polls * poll_interval} seconds. "
558
+ "The request is still running; call get_result() to keep waiting.",
559
+ status=status,
560
+ progress_percent=percent if type(percent) is int else None,
416
561
  )
417
562
 
418
- @retry(
419
- retry=(
420
- retry_if_exception_type(DatalabTimeoutError)
421
- | retry_if_exception(_is_retryable_poll_error)
422
- ),
423
- stop=stop_after_attempt(10),
424
- wait=_wait_retry_after_or_backoff,
425
- reraise=True,
426
- )
563
+ @_poll_retry
427
564
  async def _poll_get_with_retry(self, url: str) -> Dict[str, Any]:
428
565
  """GET wrapper for polling with scoped retries for transient failures"""
429
566
  return await self._make_request("GET", url)
@@ -435,6 +572,7 @@ class AsyncDatalabClient:
435
572
  headers={"User-Agent": f"datalab-python-sdk/{settings.VERSION}"},
436
573
  )
437
574
 
575
+ @_poll_retry
438
576
  async def _fetch_signed_result(self, url: str) -> Dict[str, Any]:
439
577
  """Download a result JSON from a signed result_url"""
440
578
  try:
@@ -442,30 +580,45 @@ class AsyncDatalabClient:
442
580
  async with session.get(url) as resp:
443
581
  if resp.status >= 400:
444
582
  raise _api_error_from_body(
445
- resp.status, await resp.read(), resp.reason, None
583
+ resp.status,
584
+ await _read_error_body(resp),
585
+ resp.reason,
586
+ resp.headers.get("Retry-After"),
446
587
  )
447
588
  return await resp.json(content_type=None)
448
589
  except asyncio.TimeoutError:
449
- raise DatalabTimeoutError(
590
+ raise DatalabTransferTimeoutError(
450
591
  f"Result download timed out after {self.timeout} seconds"
451
592
  )
452
593
  except aiohttp.ClientError as e:
453
594
  raise DatalabAPIError(f"Result download failed: {str(e)}")
454
595
 
455
596
  async def _download_signed_url_to_file(self, url: str, path: Path) -> None:
456
- """Stream a signed result_url to a file on disk"""
597
+ """Stream a signed result_url to a file on disk.
598
+
599
+ The bytes are copied without parsing, so the result is never held in
600
+ memory. It runs inside _poll_get_streaming, so a 5xx or connection
601
+ error retries the poll and the download on purpose: each retry gets
602
+ a fresh signed URL.
603
+ """
457
604
  try:
458
605
  async with self._signed_url_session() as session:
459
606
  async with session.get(url) as resp:
460
607
  if resp.status >= 400:
461
608
  raise _api_error_from_body(
462
- resp.status, await resp.read(), resp.reason, None
609
+ resp.status,
610
+ await _read_error_body(resp),
611
+ resp.reason,
612
+ resp.headers.get("Retry-After"),
463
613
  )
464
614
  with open(path, "wb") as f:
465
615
  async for chunk in resp.content.iter_any():
466
616
  f.write(chunk)
467
617
  except asyncio.TimeoutError:
468
- raise DatalabTimeoutError(
618
+ # Not retried: the request has finished, and the same download
619
+ # would time out again. Retrying it here also retried the poll,
620
+ # because _poll_get_streaming retries every other timeout.
621
+ raise DatalabTransferTimeoutError(
469
622
  f"Result download timed out after {self.timeout} seconds"
470
623
  )
471
624
  except aiohttp.ClientError as e:
@@ -490,22 +643,7 @@ class AsyncDatalabClient:
490
643
  merged.update({k: v for k, v in data.items() if v is not None})
491
644
  return merged
492
645
 
493
- @staticmethod
494
- async def _tee_stream_to_file(content, fd):
495
- """Async generator that writes each chunk to fd and yields it for ijson."""
496
- async for chunk in content.iter_any():
497
- os.write(fd, chunk)
498
- yield chunk
499
-
500
- @retry(
501
- retry=(
502
- retry_if_exception_type(DatalabTimeoutError)
503
- | retry_if_exception(_is_retryable_poll_error)
504
- ),
505
- stop=stop_after_attempt(10),
506
- wait=_wait_retry_after_or_backoff,
507
- reraise=True,
508
- )
646
+ @_poll_retry
509
647
  async def _poll_get_streaming(
510
648
  self, url: str, stream_response_to: Path
511
649
  ) -> FileResult:
@@ -530,34 +668,46 @@ class AsyncDatalabClient:
530
668
  if resp.status >= 400:
531
669
  raise _api_error_from_body(
532
670
  resp.status,
533
- await resp.read(),
671
+ await _read_error_body(resp),
534
672
  resp.reason,
535
673
  resp.headers.get("Retry-After"),
536
674
  )
537
675
 
538
- status = None
539
- success = None
540
- error = None
541
- result_url = None
542
- progress_percent = None
543
-
544
- tee_reader = _AsyncIterableReader(
545
- self._tee_stream_to_file(resp.content, fd)
676
+ # Push each chunk to ijson from this task. ijson.parse_async
677
+ # reads in another task, which turns an aiohttp timeout into
678
+ # a CancelledError.
679
+ poll = _StreamedPollFields()
680
+ events = ijson.sendable_list()
681
+ parser = ijson.parse_coro(events)
682
+ async for chunk in resp.content.iter_any():
683
+ os.write(fd, chunk)
684
+ parser.send(chunk)
685
+ poll.feed(events)
686
+ del events[:]
687
+ parser.close()
688
+ poll.feed(events)
689
+ except asyncio.TimeoutError:
690
+ # The API sends status near the start of the body. A finished
691
+ # result that times out would time out again, so it is not
692
+ # retried. Any other body is small, so its timeout is retried
693
+ # like any poll timeout.
694
+ if poll.status == "complete":
695
+ raise DatalabTransferTimeoutError(
696
+ f"Result transfer timed out after {self.timeout} seconds"
697
+ )
698
+ raise DatalabTimeoutError(
699
+ f"Request timed out after {self.timeout} seconds"
546
700
  )
547
- async for prefix, event, value in ijson.parse_async(tee_reader):
548
- if prefix == "status" and event == "string":
549
- status = value
550
- elif prefix == "success" and event == "boolean":
551
- success = value
552
- elif prefix == "error" and event in ("string", "null"):
553
- error = value
554
- elif prefix == "result_url" and event == "string":
555
- result_url = value
556
- elif prefix == "progress_percent" and event == "number":
557
- progress_percent = value
701
+ except aiohttp.ClientError as e:
702
+ # The body can fail after the headers arrive.
703
+ raise DatalabAPIError(f"Request failed: {str(e)}") from e
558
704
  finally:
559
705
  resp.release()
560
706
 
707
+ status, success, error = poll.status, poll.success, poll.error
708
+ result_url, progress_percent = poll.result_url, poll.progress_percent
709
+ fields = poll.fields
710
+
561
711
  if status is None:
562
712
  raise DatalabAPIError("Response missing 'status' field")
563
713
 
@@ -570,27 +720,21 @@ class AsyncDatalabClient:
570
720
 
571
721
  if status == "complete" and result_url:
572
722
  # The API sent a signed URL instead of the full result.
573
- # Stream the full result from that URL into the file.
723
+ # Stream the full result from that URL into the file. The
724
+ # FileResult fields come from the poll response only.
574
725
  await self._download_signed_url_to_file(result_url, Path(tmp_path))
575
726
 
576
727
  if status == "complete":
577
728
  shutil.move(tmp_path, stream_response_to)
578
729
  tmp_path = None
579
- return FileResult(
580
- success=success,
581
- status=status,
582
- output_path=stream_response_to,
583
- error=error,
584
- progress_percent=progress_percent,
585
- )
586
- else:
587
- return FileResult(
588
- success=success,
589
- status=status,
590
- output_path=stream_response_to,
591
- error=error,
592
- progress_percent=progress_percent,
593
- )
730
+ return FileResult(
731
+ success=success,
732
+ status=status,
733
+ output_path=stream_response_to,
734
+ error=error,
735
+ progress_percent=progress_percent,
736
+ **fields,
737
+ )
594
738
  finally:
595
739
  if fd is not None:
596
740
  try:
@@ -660,8 +804,9 @@ class AsyncDatalabClient:
660
804
 
661
805
  return form_data
662
806
 
807
+ @staticmethod
663
808
  def _build_conversion_result(
664
- self, result_data: Dict[str, Any], default_format: str = "markdown"
809
+ result_data: Dict[str, Any], default_format: str = "markdown"
665
810
  ) -> ConversionResult:
666
811
  """Build a ConversionResult from API response data"""
667
812
  return ConversionResult(
@@ -695,6 +840,122 @@ class AsyncDatalabClient:
695
840
  progress_percent=result_data.get("progress_percent"),
696
841
  )
697
842
 
843
+ @staticmethod
844
+ def _build_agent_result(result_data: Dict[str, Any]) -> AgentResult:
845
+ return AgentResult(
846
+ status=result_data.get("status", "complete"),
847
+ success=result_data.get("success"),
848
+ error=result_data.get("error"),
849
+ output_shape=result_data.get("output_shape"),
850
+ finished=result_data.get("finished"),
851
+ turns=result_data.get("turns"),
852
+ markdown=result_data.get("markdown"),
853
+ html=result_data.get("html"),
854
+ json=result_data.get("json"),
855
+ chunks=result_data.get("chunks"),
856
+ extraction_schema_json=result_data.get("extraction_schema_json"),
857
+ segments=result_data.get("segments"),
858
+ metadata=result_data.get("metadata"),
859
+ verdict=result_data.get("verdict"),
860
+ jats_xml=result_data.get("jats_xml"),
861
+ accessible_pdf=result_data.get("accessible_pdf"),
862
+ images=result_data.get("images"),
863
+ verifier_metrics=result_data.get("verifier_metrics"),
864
+ page_count=result_data.get("page_count"),
865
+ cost_breakdown=result_data.get("cost_breakdown"),
866
+ parse_quality_score=result_data.get("parse_quality_score"),
867
+ runtime=result_data.get("runtime"),
868
+ versions=result_data.get("versions"),
869
+ request_id=result_data.get("request_id"),
870
+ result_url=result_data.get("result_url"),
871
+ expires_in=result_data.get("expires_in"),
872
+ progress_percent=result_data.get("progress_percent"),
873
+ )
874
+
875
+ @staticmethod
876
+ def _build_create_document_result(
877
+ result_data: Dict[str, Any],
878
+ ) -> CreateDocumentResult:
879
+ return CreateDocumentResult(
880
+ status=result_data.get("status", "complete"),
881
+ success=result_data.get("success"),
882
+ error=result_data.get("error"),
883
+ output_format=result_data.get("output_format"),
884
+ output_base64=result_data.get("output_base64"),
885
+ runtime=result_data.get("runtime"),
886
+ page_count=result_data.get("page_count"),
887
+ cost_breakdown=result_data.get("cost_breakdown"),
888
+ versions=result_data.get("versions"),
889
+ request_id=result_data.get("request_id"),
890
+ result_url=result_data.get("result_url"),
891
+ expires_in=result_data.get("expires_in"),
892
+ progress_percent=result_data.get("progress_percent"),
893
+ )
894
+
895
+ @staticmethod
896
+ def _build_ocr_result(result_data: Dict[str, Any]) -> OCRResult:
897
+ return OCRResult(
898
+ success=result_data.get("success", False),
899
+ pages=result_data.get("pages", []),
900
+ error=result_data.get("error"),
901
+ page_count=result_data.get("page_count"),
902
+ status=result_data.get("status", "complete"),
903
+ versions=result_data.get("versions"),
904
+ cost_breakdown=result_data.get("cost_breakdown"),
905
+ request_id=result_data.get("request_id"),
906
+ progress_percent=result_data.get("progress_percent"),
907
+ )
908
+
909
+ @staticmethod
910
+ def _build_form_filling_result(result_data: Dict[str, Any]) -> FormFillingResult:
911
+ return FormFillingResult(
912
+ status=result_data.get("status", "complete"),
913
+ success=result_data.get("success"),
914
+ error=result_data.get("error"),
915
+ error_in=result_data.get("error_in"),
916
+ output_format=result_data.get("output_format"),
917
+ output_base64=result_data.get("output_base64"),
918
+ fields_filled=result_data.get("fields_filled"),
919
+ fields_not_found=result_data.get("fields_not_found"),
920
+ runtime=result_data.get("runtime"),
921
+ page_count=result_data.get("page_count"),
922
+ cost_breakdown=result_data.get("cost_breakdown"),
923
+ versions=result_data.get("versions"),
924
+ request_id=result_data.get("request_id"),
925
+ result_url=result_data.get("result_url"),
926
+ expires_in=result_data.get("expires_in"),
927
+ progress_percent=result_data.get("progress_percent"),
928
+ )
929
+
930
+ @staticmethod
931
+ def _build_form_fields_result(result_data: Dict[str, Any]) -> FormFieldsResult:
932
+ return FormFieldsResult(
933
+ status=result_data.get("status", "complete"),
934
+ success=result_data.get("success"),
935
+ error=result_data.get("error"),
936
+ pages=result_data.get("pages"),
937
+ json=result_data.get("json"),
938
+ text_error=result_data.get("text_error"),
939
+ page_count=result_data.get("page_count"),
940
+ cost_breakdown=result_data.get("cost_breakdown"),
941
+ runtime=result_data.get("runtime"),
942
+ versions=result_data.get("versions"),
943
+ request_id=result_data.get("request_id"),
944
+ result_url=result_data.get("result_url"),
945
+ expires_in=result_data.get("expires_in"),
946
+ progress_percent=result_data.get("progress_percent"),
947
+ )
948
+
949
+ @staticmethod
950
+ def _build_redact_result(result_data: Dict[str, Any]) -> RedactResult:
951
+ return RedactResult(
952
+ **{
953
+ key: value
954
+ for key, value in result_data.items()
955
+ if key in RedactResult.__dataclass_fields__
956
+ }
957
+ )
958
+
698
959
  async def _submit_and_poll(
699
960
  self,
700
961
  endpoint: str,
@@ -718,23 +979,66 @@ class AsyncDatalabClient:
718
979
  f"Request failed: {initial_data.get('error', 'Unknown error')}"
719
980
  )
720
981
 
721
- result = await self._poll_result(
982
+ result = await self._poll_request(
722
983
  initial_data["request_check_url"],
984
+ initial_data.get("request_id"),
723
985
  max_polls=max_polls,
724
986
  poll_interval=poll_interval,
725
987
  on_progress=on_progress,
726
988
  stream_response_to=stream_response_to,
727
- **(
728
- {"result_transform": result_transform}
729
- if result_transform is not None
730
- else {}
731
- ),
732
- )
733
- if isinstance(result, dict):
734
- result = dict(result)
735
- for key in ("request_id", "checkpoint_reused"):
736
- if result.get(key) is None and initial_data.get(key) is not None:
737
- result[key] = initial_data[key]
989
+ result_transform=result_transform,
990
+ )
991
+ # Only the submission response says whether a checkpoint was reused.
992
+ if (
993
+ isinstance(result, dict)
994
+ and result.get("checkpoint_reused") is None
995
+ and initial_data.get("checkpoint_reused") is not None
996
+ ):
997
+ result = {**result, "checkpoint_reused": initial_data["checkpoint_reused"]}
998
+ return result
999
+
1000
+ async def _poll_request(
1001
+ self,
1002
+ check_url: str,
1003
+ request_id: Optional[str],
1004
+ result_transform: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
1005
+ **poll_kwargs,
1006
+ ) -> Union[Dict[str, Any], FileResult]:
1007
+ """Poll a request the API accepted.
1008
+
1009
+ A DatalabError gets the request_id and check_url, so the caller can
1010
+ resume with get_result(). The result gets request_id when the poll
1011
+ response does not send it.
1012
+ """
1013
+ if result_transform is not None:
1014
+ poll_kwargs["result_transform"] = result_transform
1015
+ with _request_handle(request_id, check_url):
1016
+ result = await self._poll_result(check_url, **poll_kwargs)
1017
+ if request_id is None:
1018
+ return result
1019
+ if isinstance(result, FileResult):
1020
+ if result.request_id is None:
1021
+ result = dataclasses.replace(result, request_id=request_id)
1022
+ elif result.get("request_id") is None:
1023
+ result = {**result, "request_id": request_id}
1024
+ return result
1025
+
1026
+ def _finish(
1027
+ self,
1028
+ policy: _ResultPolicy,
1029
+ result_data: Union[Dict[str, Any], FileResult],
1030
+ save_output: Optional[Union[str, Path]],
1031
+ **build_kwargs,
1032
+ ) -> Any:
1033
+ """Build an endpoint's result from its poll response and save it.
1034
+
1035
+ The processing methods and get_result() share it, so a resumed
1036
+ request returns the same result as the method that submitted it.
1037
+ """
1038
+ if isinstance(result_data, FileResult):
1039
+ return result_data
1040
+ result = policy.build(result_data, **build_kwargs)
1041
+ policy.save(result, save_output)
738
1042
  return result
739
1043
 
740
1044
  @staticmethod
@@ -754,13 +1058,6 @@ class AsyncDatalabClient:
754
1058
  raise DatalabValidationError(f"Directory does not exist: {resolved.parent}")
755
1059
  return resolved
756
1060
 
757
- @staticmethod
758
- def _save_if_requested(result, save_output, has_output: bool = True) -> None:
759
- if save_output and result.success and has_output:
760
- output_path = Path(save_output)
761
- output_path.parent.mkdir(parents=True, exist_ok=True)
762
- result.save_output(output_path)
763
-
764
1061
  @staticmethod
765
1062
  def _check_file_or_checkpoint(file_path, file_url, checkpoint_id) -> None:
766
1063
  has_file = file_path is not None or file_url is not None
@@ -818,12 +1115,9 @@ class AsyncDatalabClient:
818
1115
  stream_response_to=resolved_stream_response_to,
819
1116
  )
820
1117
 
821
- if isinstance(result_data, FileResult):
822
- return result_data
823
-
824
- result = self._build_conversion_result(result_data, options.output_format)
825
- self._save_if_requested(result, save_output)
826
- return result
1118
+ return self._finish(
1119
+ _CONVERSION, result_data, save_output, default_format=options.output_format
1120
+ )
827
1121
 
828
1122
  async def extract(
829
1123
  self,
@@ -893,12 +1187,9 @@ class AsyncDatalabClient:
893
1187
  stream_response_to=resolved_stream_response_to,
894
1188
  )
895
1189
 
896
- if isinstance(result_data, FileResult):
897
- return result_data
898
-
899
- result = self._build_conversion_result(result_data, options.output_format)
900
- self._save_if_requested(result, save_output)
901
- return result
1190
+ return self._finish(
1191
+ _CONVERSION, result_data, save_output, default_format=options.output_format
1192
+ )
902
1193
 
903
1194
  async def segment(
904
1195
  self,
@@ -952,12 +1243,7 @@ class AsyncDatalabClient:
952
1243
  stream_response_to=resolved_stream_response_to,
953
1244
  )
954
1245
 
955
- if isinstance(result_data, FileResult):
956
- return result_data
957
-
958
- result = self._build_conversion_result(result_data, "markdown")
959
- self._save_if_requested(result, save_output)
960
- return result
1246
+ return self._finish(_CONVERSION, result_data, save_output)
961
1247
 
962
1248
  async def run_agent(
963
1249
  self,
@@ -1005,40 +1291,7 @@ class AsyncDatalabClient:
1005
1291
  stream_response_to=resolved_stream_response_to,
1006
1292
  )
1007
1293
 
1008
- if isinstance(result_data, FileResult):
1009
- return result_data
1010
-
1011
- result = AgentResult(
1012
- status=result_data.get("status", "complete"),
1013
- success=result_data.get("success"),
1014
- error=result_data.get("error"),
1015
- output_shape=result_data.get("output_shape"),
1016
- finished=result_data.get("finished"),
1017
- turns=result_data.get("turns"),
1018
- markdown=result_data.get("markdown"),
1019
- html=result_data.get("html"),
1020
- json=result_data.get("json"),
1021
- chunks=result_data.get("chunks"),
1022
- extraction_schema_json=result_data.get("extraction_schema_json"),
1023
- segments=result_data.get("segments"),
1024
- metadata=result_data.get("metadata"),
1025
- verdict=result_data.get("verdict"),
1026
- jats_xml=result_data.get("jats_xml"),
1027
- accessible_pdf=result_data.get("accessible_pdf"),
1028
- images=result_data.get("images"),
1029
- verifier_metrics=result_data.get("verifier_metrics"),
1030
- page_count=result_data.get("page_count"),
1031
- cost_breakdown=result_data.get("cost_breakdown"),
1032
- parse_quality_score=result_data.get("parse_quality_score"),
1033
- runtime=result_data.get("runtime"),
1034
- versions=result_data.get("versions"),
1035
- request_id=result_data.get("request_id"),
1036
- result_url=result_data.get("result_url"),
1037
- expires_in=result_data.get("expires_in"),
1038
- progress_percent=result_data.get("progress_percent"),
1039
- )
1040
- self._save_if_requested(result, save_output)
1041
- return result
1294
+ return self._finish(_AGENT, result_data, save_output)
1042
1295
 
1043
1296
  async def run_custom_processor(
1044
1297
  self,
@@ -1113,12 +1366,9 @@ class AsyncDatalabClient:
1113
1366
  stream_response_to=resolved_stream_response_to,
1114
1367
  )
1115
1368
 
1116
- if isinstance(result_data, FileResult):
1117
- return result_data
1118
-
1119
- result = self._build_conversion_result(result_data, options.output_format)
1120
- self._save_if_requested(result, save_output)
1121
- return result
1369
+ return self._finish(
1370
+ _CONVERSION, result_data, save_output, default_format=options.output_format
1371
+ )
1122
1372
 
1123
1373
  async def run_custom_pipeline(
1124
1374
  self,
@@ -1195,12 +1445,9 @@ class AsyncDatalabClient:
1195
1445
  stream_response_to=resolved_stream_response_to,
1196
1446
  )
1197
1447
 
1198
- if isinstance(result_data, FileResult):
1199
- return result_data
1200
-
1201
- result = self._build_conversion_result(result_data, options.output_format)
1202
- self._save_if_requested(result, save_output)
1203
- return result
1448
+ return self._finish(
1449
+ _CONVERSION, result_data, save_output, default_format=options.output_format
1450
+ )
1204
1451
 
1205
1452
  async def create_document(
1206
1453
  self,
@@ -1255,26 +1502,7 @@ class AsyncDatalabClient:
1255
1502
  stream_response_to=resolved_stream_response_to,
1256
1503
  )
1257
1504
 
1258
- if isinstance(result_data, FileResult):
1259
- return result_data
1260
-
1261
- result = CreateDocumentResult(
1262
- status=result_data.get("status", "complete"),
1263
- success=result_data.get("success"),
1264
- error=result_data.get("error"),
1265
- output_format=result_data.get("output_format"),
1266
- output_base64=result_data.get("output_base64"),
1267
- runtime=result_data.get("runtime"),
1268
- page_count=result_data.get("page_count"),
1269
- cost_breakdown=result_data.get("cost_breakdown"),
1270
- versions=result_data.get("versions"),
1271
- request_id=result_data.get("request_id"),
1272
- result_url=result_data.get("result_url"),
1273
- expires_in=result_data.get("expires_in"),
1274
- progress_percent=result_data.get("progress_percent"),
1275
- )
1276
- self._save_if_requested(result, save_output, bool(result.output_base64))
1277
- return result
1505
+ return self._finish(_CREATE_DOCUMENT, result_data, save_output)
1278
1506
 
1279
1507
  async def ocr(
1280
1508
  self,
@@ -1313,22 +1541,7 @@ class AsyncDatalabClient:
1313
1541
  stream_response_to=resolved_stream_response_to,
1314
1542
  )
1315
1543
 
1316
- if isinstance(result_data, FileResult):
1317
- return result_data
1318
-
1319
- result = OCRResult(
1320
- success=result_data.get("success", False),
1321
- pages=result_data.get("pages", []),
1322
- error=result_data.get("error"),
1323
- page_count=result_data.get("page_count"),
1324
- status=result_data.get("status", "complete"),
1325
- versions=result_data.get("versions"),
1326
- cost_breakdown=result_data.get("cost_breakdown"),
1327
- request_id=result_data.get("request_id"),
1328
- progress_percent=result_data.get("progress_percent"),
1329
- )
1330
- self._save_if_requested(result, save_output)
1331
- return result
1544
+ return self._finish(_OCR, result_data, save_output)
1332
1545
 
1333
1546
  @staticmethod
1334
1547
  def _normalize_redaction_result(data: Dict[str, Any]) -> Dict[str, Any]:
@@ -1408,21 +1621,10 @@ class AsyncDatalabClient:
1408
1621
  ),
1409
1622
  max_polls=max_polls,
1410
1623
  poll_interval=poll_interval,
1411
- result_transform=self._normalize_redaction_result,
1624
+ result_transform=_REDACT.result_transform,
1412
1625
  on_progress=on_progress,
1413
1626
  )
1414
- result = RedactResult(
1415
- **{
1416
- key: value
1417
- for key, value in result_data.items()
1418
- if key in RedactResult.__dataclass_fields__
1419
- }
1420
- )
1421
- if save_output and result.output_base64:
1422
- output_path = Path(save_output)
1423
- output_path.parent.mkdir(parents=True, exist_ok=True)
1424
- result.save_output(output_path)
1425
- return result
1627
+ return self._finish(_REDACT, result_data, save_output)
1426
1628
 
1427
1629
  async def get_redaction_presets(self) -> Dict[str, Any]:
1428
1630
  """Get built-in redaction preset IDs, labels, and specifications."""
@@ -1470,29 +1672,7 @@ class AsyncDatalabClient:
1470
1672
  stream_response_to=resolved_stream_response_to,
1471
1673
  )
1472
1674
 
1473
- if isinstance(result_data, FileResult):
1474
- return result_data
1475
-
1476
- result = FormFillingResult(
1477
- status=result_data.get("status", "complete"),
1478
- success=result_data.get("success"),
1479
- error=result_data.get("error"),
1480
- error_in=result_data.get("error_in"),
1481
- output_format=result_data.get("output_format"),
1482
- output_base64=result_data.get("output_base64"),
1483
- fields_filled=result_data.get("fields_filled"),
1484
- fields_not_found=result_data.get("fields_not_found"),
1485
- runtime=result_data.get("runtime"),
1486
- page_count=result_data.get("page_count"),
1487
- cost_breakdown=result_data.get("cost_breakdown"),
1488
- versions=result_data.get("versions"),
1489
- request_id=result_data.get("request_id"),
1490
- result_url=result_data.get("result_url"),
1491
- expires_in=result_data.get("expires_in"),
1492
- progress_percent=result_data.get("progress_percent"),
1493
- )
1494
- self._save_if_requested(result, save_output, bool(result.output_base64))
1495
- return result
1675
+ return self._finish(_FORM_FILLING, result_data, save_output)
1496
1676
 
1497
1677
  async def form_fields(
1498
1678
  self,
@@ -1540,27 +1720,7 @@ class AsyncDatalabClient:
1540
1720
  stream_response_to=resolved_stream_response_to,
1541
1721
  )
1542
1722
 
1543
- if isinstance(result_data, FileResult):
1544
- return result_data
1545
-
1546
- result = FormFieldsResult(
1547
- status=result_data.get("status", "complete"),
1548
- success=result_data.get("success"),
1549
- error=result_data.get("error"),
1550
- pages=result_data.get("pages"),
1551
- json=result_data.get("json"),
1552
- text_error=result_data.get("text_error"),
1553
- page_count=result_data.get("page_count"),
1554
- cost_breakdown=result_data.get("cost_breakdown"),
1555
- runtime=result_data.get("runtime"),
1556
- versions=result_data.get("versions"),
1557
- request_id=result_data.get("request_id"),
1558
- result_url=result_data.get("result_url"),
1559
- expires_in=result_data.get("expires_in"),
1560
- progress_percent=result_data.get("progress_percent"),
1561
- )
1562
- self._save_if_requested(result, save_output)
1563
- return result
1723
+ return self._finish(_FORM_FIELDS, result_data, save_output)
1564
1724
 
1565
1725
  async def generate_extraction_schemas(
1566
1726
  self,
@@ -1604,6 +1764,91 @@ class AsyncDatalabClient:
1604
1764
  request_id=result_data.get("request_id"),
1605
1765
  )
1606
1766
 
1767
+ async def get_result(
1768
+ self,
1769
+ request_id_or_check_url: str,
1770
+ endpoint: Optional[str] = None,
1771
+ save_output: Optional[Union[str, Path]] = None,
1772
+ stream_response_to: Optional[Union[str, Path]] = None,
1773
+ max_polls: int = 300,
1774
+ poll_interval: int = 1,
1775
+ on_progress: Optional[ProgressCallback] = None,
1776
+ ) -> Union[
1777
+ ConversionResult,
1778
+ AgentResult,
1779
+ CreateDocumentResult,
1780
+ FormFillingResult,
1781
+ FormFieldsResult,
1782
+ OCRResult,
1783
+ RedactResult,
1784
+ FileResult,
1785
+ ]:
1786
+ """
1787
+ Wait for the result of a request that was already submitted
1788
+
1789
+ Use it after a DatalabTimeoutError or another error that has a
1790
+ request_id: it polls the same request again, so the document is not
1791
+ submitted or charged a second time. It returns the same result type
1792
+ as the method that submitted the request. A check URL does not carry
1793
+ the output_format you asked for, so if the response omits it, a
1794
+ conversion result has output_format "markdown".
1795
+
1796
+ Args:
1797
+ request_id_or_check_url: The error's check_url, or a request ID.
1798
+ A check URL names its endpoint. Only its path is used; the
1799
+ request goes to this client's base_url.
1800
+ endpoint: With a request ID, the endpoint that received the
1801
+ request, for example "convert", "extract" or "agent".
1802
+ save_output: Optional path to save output files
1803
+ stream_response_to: Optional path to stream raw JSON response to disk
1804
+ max_polls: Maximum number of polling attempts
1805
+ poll_interval: Seconds between polling attempts
1806
+ on_progress: Optional callback for increasing estimated percentages (0-100).
1807
+ """
1808
+ value = request_id_or_check_url.strip()
1809
+ if "/" in value:
1810
+ if endpoint is not None:
1811
+ raise DatalabValidationError(
1812
+ "Pass endpoint only with a request ID; a check URL names its endpoint."
1813
+ )
1814
+ path = urlsplit(value).path.rstrip("/")
1815
+ prefix, _, request_id = path.rpartition("/")
1816
+ _, found, route = prefix.partition("/api/v1/")
1817
+ if not found or not request_id:
1818
+ raise DatalabValidationError(f"Not a request check URL: {value}")
1819
+ else:
1820
+ if endpoint is None:
1821
+ raise DatalabValidationError(
1822
+ "Pass endpoint with a request ID, or pass the check URL instead."
1823
+ )
1824
+ request_id, route = value, endpoint.strip("/")
1825
+ policy = _RESULT_ROUTES.get(route)
1826
+ if policy is None or not request_id:
1827
+ raise DatalabValidationError(
1828
+ f"get_result() does not support the {route!r} endpoint. "
1829
+ f"Supported: {', '.join(sorted(_RESULT_ROUTES))}."
1830
+ )
1831
+ if not policy.streamable and stream_response_to:
1832
+ raise DatalabValidationError(
1833
+ f"{route} results cannot use stream_response_to."
1834
+ )
1835
+ resolved_stream_response_to = self._resolve_stream_path(
1836
+ save_output, stream_response_to
1837
+ )
1838
+
1839
+ result_data = await self._poll_request(
1840
+ f"{self.base_url}/api/v1/{route}/{request_id}",
1841
+ request_id,
1842
+ max_polls=max_polls,
1843
+ poll_interval=poll_interval,
1844
+ stream_response_to=resolved_stream_response_to,
1845
+ on_progress=on_progress,
1846
+ result_transform=policy.result_transform,
1847
+ )
1848
+ # A check URL does not carry the output_format the caller asked for,
1849
+ # so a conversion result whose response omits it says "markdown".
1850
+ return self._finish(policy, result_data, save_output)
1851
+
1607
1852
  async def delete_result(self, request_id: str) -> Dict[str, Any]:
1608
1853
  """
1609
1854
  Delete the stored result of a finished request
@@ -2662,12 +2907,15 @@ class AsyncDatalabClient:
2662
2907
  async def forward_progress(percent: int) -> None:
2663
2908
  await progress.report(percent, complete=percent == 100)
2664
2909
 
2665
- return await self.get_pipeline_execution(
2666
- execution.execution_id,
2667
- max_polls=max_polls - 1,
2668
- poll_interval=poll_interval,
2669
- on_progress=forward_progress,
2670
- )
2910
+ # The run was accepted and is charged. An error carries the
2911
+ # execution ID as request_id, for get_pipeline_execution().
2912
+ with _request_handle(execution.execution_id):
2913
+ return await self.get_pipeline_execution(
2914
+ execution.execution_id,
2915
+ max_polls=max_polls - 1,
2916
+ poll_interval=poll_interval,
2917
+ on_progress=forward_progress,
2918
+ )
2671
2919
  return execution
2672
2920
 
2673
2921
  async def get_pipeline_execution(
@@ -3200,6 +3448,50 @@ class AsyncDatalabClient:
3200
3448
  )
3201
3449
 
3202
3450
 
3451
+ _CONVERSION = _ResultPolicy(
3452
+ AsyncDatalabClient._build_conversion_result, _save_successful
3453
+ )
3454
+ _AGENT = _ResultPolicy(AsyncDatalabClient._build_agent_result, _save_successful)
3455
+ _CREATE_DOCUMENT = _ResultPolicy(
3456
+ AsyncDatalabClient._build_create_document_result, _save_successful_document
3457
+ )
3458
+ _FORM_FILLING = _ResultPolicy(
3459
+ AsyncDatalabClient._build_form_filling_result, _save_successful_document
3460
+ )
3461
+ _FORM_FIELDS = _ResultPolicy(
3462
+ AsyncDatalabClient._build_form_fields_result, _save_successful
3463
+ )
3464
+ _OCR = _ResultPolicy(AsyncDatalabClient._build_ocr_result, _save_successful)
3465
+ _REDACT = _ResultPolicy(
3466
+ AsyncDatalabClient._build_redact_result,
3467
+ _save_redacted_document,
3468
+ result_transform=AsyncDatalabClient._normalize_redaction_result,
3469
+ streamable=False,
3470
+ )
3471
+
3472
+ # The result routes that get_result() accepts, by the path between /api/v1/
3473
+ # and the request ID. Each route returns its own response shape, so the route
3474
+ # sets the result policy. "marker" and its subpaths are the older routes that
3475
+ # some check URLs still use.
3476
+ _RESULT_ROUTES = {
3477
+ "convert": _CONVERSION,
3478
+ "extract": _CONVERSION,
3479
+ "segment": _CONVERSION,
3480
+ "track-changes": _CONVERSION,
3481
+ "custom-processor": _CONVERSION,
3482
+ "custom-pipeline": _CONVERSION,
3483
+ "marker": _CONVERSION,
3484
+ "marker/extraction": _CONVERSION,
3485
+ "marker/segmentation": _CONVERSION,
3486
+ "agent": _AGENT,
3487
+ "create-document": _CREATE_DOCUMENT,
3488
+ "fill": _FORM_FILLING,
3489
+ "form-fields": _FORM_FIELDS,
3490
+ "ocr": _OCR,
3491
+ "redact": _REDACT,
3492
+ }
3493
+
3494
+
3203
3495
  class DatalabClient:
3204
3496
  """Synchronous wrapper around AsyncDatalabClient"""
3205
3497
 
@@ -3674,6 +3966,41 @@ class DatalabClient:
3674
3966
  )
3675
3967
  )
3676
3968
 
3969
+ def get_result(
3970
+ self,
3971
+ request_id_or_check_url: str,
3972
+ endpoint: Optional[str] = None,
3973
+ save_output: Optional[Union[str, Path]] = None,
3974
+ stream_response_to: Optional[Union[str, Path]] = None,
3975
+ max_polls: int = 300,
3976
+ poll_interval: int = 1,
3977
+ on_progress: Optional[ProgressCallback] = None,
3978
+ ) -> Union[
3979
+ ConversionResult,
3980
+ AgentResult,
3981
+ CreateDocumentResult,
3982
+ FormFillingResult,
3983
+ FormFieldsResult,
3984
+ OCRResult,
3985
+ RedactResult,
3986
+ FileResult,
3987
+ ]:
3988
+ """Wait for the result of a request that was already submitted (sync version).
3989
+
3990
+ See AsyncDatalabClient.get_result().
3991
+ """
3992
+ return self._run_async(
3993
+ self._async_client.get_result(
3994
+ request_id_or_check_url,
3995
+ endpoint=endpoint,
3996
+ save_output=save_output,
3997
+ stream_response_to=stream_response_to,
3998
+ max_polls=max_polls,
3999
+ poll_interval=poll_interval,
4000
+ on_progress=on_progress,
4001
+ )
4002
+ )
4003
+
3677
4004
  def delete_result(self, request_id: str) -> Dict[str, Any]:
3678
4005
  """Delete the stored result of a finished request (sync version)"""
3679
4006
  return self._run_async(self._async_client.delete_result(request_id=request_id))
datalab_sdk/exceptions.py CHANGED
@@ -6,9 +6,18 @@ from typing import Any, Optional
6
6
 
7
7
 
8
8
  class DatalabError(Exception):
9
- """Base exception for Datalab SDK errors"""
9
+ """Base exception for Datalab SDK errors.
10
10
 
11
- pass
11
+ Attributes:
12
+ request_id: The request ID, when a document-processing method or
13
+ get_result() fails after the API accepted the request. Pass
14
+ check_url to get_result() to fetch the result without submitting
15
+ the document again. For run_pipeline(), the execution ID.
16
+ check_url: The URL that returns the request's status and result.
17
+ """
18
+
19
+ request_id: Optional[str] = None
20
+ check_url: Optional[str] = None
12
21
 
13
22
 
14
23
  class DatalabAPIError(DatalabError):
@@ -68,9 +77,45 @@ class DatalabServerError(DatalabAPIError):
68
77
 
69
78
 
70
79
  class DatalabTimeoutError(DatalabError):
71
- """Exception raised when a request times out"""
80
+ """A request or the polling budget timed out.
72
81
 
73
- pass
82
+ When request_id is None, the submission itself timed out, and the API
83
+ may still have accepted the request. Otherwise the subclass says what
84
+ happened to the request:
85
+
86
+ - DatalabPollingTimeoutError: the request is still running.
87
+ - DatalabTransferTimeoutError: the result timed out while it downloaded.
88
+ """
89
+
90
+
91
+ class DatalabTransferTimeoutError(DatalabTimeoutError):
92
+ """The result timed out while it downloaded. The request has finished.
93
+
94
+ The SDK does not retry this error: the timeout limits each whole
95
+ request, so a result too large to download within it would time out
96
+ again. Raise the client's timeout and call get_result().
97
+ """
98
+
99
+
100
+ class DatalabPollingTimeoutError(DatalabTimeoutError):
101
+ """The polling budget (max_polls * poll_interval) ran out before the
102
+ request finished. The request keeps running on the server and is
103
+ charged; call get_result() to wait for it again.
104
+
105
+ Attributes:
106
+ status: The status of the last poll, for example "processing".
107
+ progress_percent: The estimated progress of the last poll, if any.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ message: str,
113
+ status: Optional[str] = None,
114
+ progress_percent: Optional[int] = None,
115
+ ):
116
+ super().__init__(message)
117
+ self.status = status
118
+ self.progress_percent = progress_percent
74
119
 
75
120
 
76
121
  class DatalabFileError(DatalabError):
datalab_sdk/models.py CHANGED
@@ -879,14 +879,31 @@ class ExtractionSchemaSuggestions:
879
879
  @dataclass
880
880
  class FileResult:
881
881
  """Lightweight result returned when stream_response_to is used.
882
- The full JSON response is written directly to disk at output_path,
883
- never fully loaded into memory."""
882
+ The full JSON response is written directly to disk at output_path, and
883
+ the parsed result is never built in memory. While a poll response
884
+ streams, the SDK decodes each JSON string value whole, so peak memory is
885
+ at least the size of the largest text field, such as markdown. A result
886
+ from a signed result_url is copied to disk without parsing.
887
+
888
+ The page_count, parse_quality_score, versions, runtime and
889
+ cost_breakdown fields come from the poll response, and are None when it
890
+ does not send them. request_id comes from the poll response, or else
891
+ from the submit response. For a result from a signed result_url, the
892
+ poll response has no versions, and cost or runtime can be unset on an
893
+ early poll. The saved file can contain versions and runtime, but not
894
+ cost."""
884
895
 
885
896
  success: bool
886
897
  status: str
887
898
  output_path: Path
888
899
  error: Optional[str] = None
889
900
  progress_percent: Optional[int] = None
901
+ request_id: Optional[str] = None
902
+ page_count: Optional[int] = None
903
+ parse_quality_score: Optional[float] = None
904
+ versions: Optional[Union[Dict[str, Any], str]] = None
905
+ runtime: Optional[float] = None
906
+ cost_breakdown: Optional[Dict[str, Any]] = None
890
907
 
891
908
 
892
909
  # --- Extraction Schema models ---
@@ -1,13 +0,0 @@
1
- datalab_sdk/__init__.py,sha256=bgRAkvlqFmwVdUpZjPf4LfPDzkDM7GLq3FszGKAUn68,3321
2
- datalab_sdk/auth.py,sha256=X2eccKzpdxogFEDoS4geOHIOeECQ8u3kANxKoqF0PVk,4388
3
- datalab_sdk/cli.py,sha256=g_qR_xMJS19PYVOf19HRD3nl3GnzHf1bIohh7WY5AO0,63928
4
- datalab_sdk/client.py,sha256=fPp_tzNEeqtRV7VOviFGxtUPnc7USUzMyyAgQiWvZJ0,158547
5
- datalab_sdk/exceptions.py,sha256=5-lzlfvB7FKGOhvgyacceTFRRUxton_JqcIyuB8k_mU,2625
6
- datalab_sdk/mimetypes.py,sha256=a4ULJmHxoR_RMsD0j51hx0t2Q7In_PzNm7UlWX07eEE,932
7
- datalab_sdk/models.py,sha256=3r9xoAPBf5Tpx7Qg1rUQtKyVRjPKo91g0iHhTHQRe6Y,42408
8
- datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
9
- datalab_python_sdk-0.11.0.dist-info/METADATA,sha256=hd_ZyN5LPiickFxcJEXYEV_ebYMMu1-7VOgkfjMCp7o,10034
10
- datalab_python_sdk-0.11.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
- datalab_python_sdk-0.11.0.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
12
- datalab_python_sdk-0.11.0.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
13
- datalab_python_sdk-0.11.0.dist-info/RECORD,,