datalab-python-sdk 0.9.2__py3-none-any.whl → 0.10.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.9.2
3
+ Version: 0.10.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
@@ -125,6 +125,12 @@ print(result.extraction_schema_json, result.extraction_score_average)
125
125
 
126
126
  When you do not set the parse `mode`, the API picks the parse mode that matches `extraction_mode`.
127
127
 
128
+ **Open beta (SDK 0.9.2):** set `citation_granularity="phrase"` in
129
+ `ExtractOptions` for matching words, offsets and match scores. A citation includes
130
+ a box only when the phrase can be located; some citations keep only block/page
131
+ references. Phrase citations cost nothing extra. Turbo returns no citations. See the
132
+ [phrase citation guide](https://documentation.datalab.to/docs/recipes/structured-extraction/api-overview#phrase-level-citations).
133
+
128
134
  ## Redaction
129
135
 
130
136
  **Open beta (SDK 0.9.0):** the redaction API may change.
@@ -153,7 +159,7 @@ PDF, including one with failed verification. Redaction returns a typed result;
153
159
 
154
160
  | Method | Endpoint |
155
161
  | --- | --- |
156
- | `run_agent()` | **Beta:** run an existing published processor (`AgentOptions(processor="cp_...")`) |
162
+ | `run_agent()` | **Beta:** run an existing published processor (`AgentOptions(processor="cp_...")`, or built-in `jats` / `wcag`) |
157
163
  | `segment()` | Split a document into sections (`SegmentOptions`) |
158
164
  | `fill()` | Fill a PDF or image form (`FormFillingOptions`) |
159
165
  | `form_fields()` | Find the fillable fields in a PDF or image |
@@ -166,6 +172,11 @@ PDF, including one with failed verification. Redaction returns a typed result;
166
172
 
167
173
  `run_custom_processor()` and `ocr()` call deprecated API endpoints. Use `run_agent()` and `convert()` instead.
168
174
 
175
+ The published `jats` processor returns JATS XML; `wcag` returns an Accessible PDF.
176
+ Inspect `finished`, `verdict` and `verifier_metrics` before using either artifact.
177
+ [Fixed processor examples](https://documentation.datalab.to/docs/recipes/document-agent/jats-and-accessible-pdf)
178
+ show the result fields and version pinning.
179
+
169
180
  Published-agent execution is in open beta; the API may change. Processor design and raw-prompt execution are not included.
170
181
 
171
182
  ## Inputs, polling and errors
@@ -0,0 +1,13 @@
1
+ datalab_sdk/__init__.py,sha256=mkxth8TTkcU5KHgp8B6G_Mec_lx_OY0LYx_ZTssCfDY,2809
2
+ datalab_sdk/auth.py,sha256=X2eccKzpdxogFEDoS4geOHIOeECQ8u3kANxKoqF0PVk,4388
3
+ datalab_sdk/cli.py,sha256=_thBW6ZWb9TzAAeLZy4E3xtNrFJrlV1jYAAXiMxxteo,62565
4
+ datalab_sdk/client.py,sha256=NPgd9BHn5RZT_YAcQdXUwtIT4QNpXctWF4TAmjpfH9Q,153111
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=Xm6MLl5DL32jFcmNv4t858qbmmO9FEMZQgiq1N5zFRw,41454
8
+ datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
9
+ datalab_python_sdk-0.10.0.dist-info/METADATA,sha256=wiHF5_waERJS-TyHlF00d90ypuwI2Rgi6t6VCb131JE,10034
10
+ datalab_python_sdk-0.10.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ datalab_python_sdk-0.10.0.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
12
+ datalab_python_sdk-0.10.0.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
13
+ datalab_python_sdk-0.10.0.dist-info/RECORD,,
datalab_sdk/__init__.py CHANGED
@@ -52,6 +52,15 @@ from .models import (
52
52
  PipelineExecutionStepResult,
53
53
  CustomProcessor,
54
54
  CustomProcessorVersion,
55
+ Eval,
56
+ EvalDifference,
57
+ EvalDifferences,
58
+ EvalField,
59
+ EvalDocumentResult,
60
+ EvalFile,
61
+ EvalList,
62
+ EvalVariant,
63
+ EvalVariantResult,
55
64
  )
56
65
  from .settings import settings
57
66
 
@@ -102,4 +111,13 @@ __all__ = [
102
111
  "PipelineExecutionStepResult",
103
112
  "CustomProcessor",
104
113
  "CustomProcessorVersion",
114
+ "Eval",
115
+ "EvalDifference",
116
+ "EvalDifferences",
117
+ "EvalField",
118
+ "EvalDocumentResult",
119
+ "EvalFile",
120
+ "EvalList",
121
+ "EvalVariant",
122
+ "EvalVariantResult",
105
123
  ]
datalab_sdk/cli.py CHANGED
@@ -26,9 +26,11 @@ from datalab_sdk.models import (
26
26
  ProcessingOptions,
27
27
  WorkflowStep,
28
28
  InputConfig,
29
+ EvalVariant,
29
30
  )
30
31
  from datalab_sdk.exceptions import DatalabError
31
32
  from datalab_sdk.settings import settings
33
+ import dataclasses
32
34
  import json
33
35
 
34
36
 
@@ -963,10 +965,16 @@ def fill(
963
965
 
964
966
  @click.command("form-fields")
965
967
  @click.argument("path", type=click.Path(exists=True))
968
+ @click.option(
969
+ "--include_text",
970
+ is_flag=True,
971
+ help="Also read the page text and mark each field in it (slower)",
972
+ )
966
973
  @webhook_option
967
974
  @common_options
968
975
  def form_fields(
969
976
  path: str,
977
+ include_text: bool,
970
978
  webhook_url: Optional[str],
971
979
  api_key: str,
972
980
  output_dir: str,
@@ -985,6 +993,7 @@ def form_fields(
985
993
  max_pages=max_pages,
986
994
  page_range=page_range,
987
995
  skip_cache=skip_cache,
996
+ include_text=include_text,
988
997
  )
989
998
  process_documents(
990
999
  path=path,
@@ -1144,6 +1153,239 @@ def create_document(
1144
1153
  sys.exit(1)
1145
1154
 
1146
1155
 
1156
+ # Eval commands (open beta; the API may change)
1157
+
1158
+
1159
+ def _eval_client(api_key: Optional[str], base_url: str) -> DatalabClient:
1160
+ if api_key is None:
1161
+ api_key = settings.DATALAB_API_KEY
1162
+ if api_key is None:
1163
+ raise DatalabError(
1164
+ "You must either pass in an api key via --api_key or set the DATALAB_API_KEY env variable. "
1165
+ "Get a free API key at https://www.datalab.to/app/keys"
1166
+ )
1167
+ return DatalabClient(api_key=api_key, base_url=base_url)
1168
+
1169
+
1170
+ def _print_eval_summary(evaluation) -> None:
1171
+ click.echo(
1172
+ f"Eval {evaluation.eval_id}: {evaluation.status} "
1173
+ f"(pipeline {evaluation.pipeline_id}, compares {evaluation.compared_step})"
1174
+ )
1175
+ for variant in evaluation.variants:
1176
+ share = f"{variant.share * 100:.0f}%" if variant.share is not None else "n/a"
1177
+ rate = (
1178
+ f"${variant.rate_per_1000_pages_cents / 100:.2f}/1000 pages"
1179
+ if variant.rate_per_1000_pages_cents is not None
1180
+ else "n/a"
1181
+ )
1182
+ speed = (
1183
+ f"{variant.seconds_per_page:.2f}s/page"
1184
+ if variant.seconds_per_page is not None
1185
+ else "n/a"
1186
+ )
1187
+ click.echo(
1188
+ f" {variant.name}: share={share} decided={variant.decided} won={variant.won} "
1189
+ f"rate={rate} speed={speed}"
1190
+ )
1191
+
1192
+
1193
+ eval_option_api_key = click.option("--api_key", required=False, help="Datalab API key")
1194
+ eval_option_base_url = click.option(
1195
+ "--base_url", default=settings.DATALAB_HOST, help="API base URL"
1196
+ )
1197
+ eval_option_json = click.option(
1198
+ "--json", "json_output", is_flag=True, help="Print the raw result as JSON"
1199
+ )
1200
+
1201
+
1202
+ @click.group("eval")
1203
+ def eval_group():
1204
+ """[Open beta] Compare pipeline variants, head to head."""
1205
+ pass
1206
+
1207
+
1208
+ @eval_group.command("run")
1209
+ @click.argument("paths", nargs=-1, type=click.Path(exists=True))
1210
+ @click.option(
1211
+ "--pipeline",
1212
+ "pipeline_id",
1213
+ required=True,
1214
+ help="Pipeline ID to evaluate (pl_XXXXX)",
1215
+ )
1216
+ @click.option(
1217
+ "--collection_id",
1218
+ type=int,
1219
+ help="Collection ID to evaluate, instead of FILE paths",
1220
+ )
1221
+ @click.option(
1222
+ "--variant-json",
1223
+ "variants_json",
1224
+ help='Variants as JSON or a path to a JSON file: [{"name": "Accurate", '
1225
+ '"steps": {"convert": {"output_mode": "accurate"}}}, ...]. Omit to '
1226
+ "compare the default Fast/Balanced/Accurate modes.",
1227
+ )
1228
+ @click.option(
1229
+ "--version", type=int, help="Pipeline version to run (0=draft, omit=active)"
1230
+ )
1231
+ @click.option(
1232
+ "--wait", is_flag=True, help="Poll until the Eval finishes and print a summary"
1233
+ )
1234
+ @click.option(
1235
+ "--poll_interval", default=10, type=int, help="Seconds between polls with --wait"
1236
+ )
1237
+ @click.option(
1238
+ "--timeout", default=7200, type=int, help="Maximum seconds to wait with --wait"
1239
+ )
1240
+ @eval_option_json
1241
+ @eval_option_api_key
1242
+ @eval_option_base_url
1243
+ def eval_run(
1244
+ paths,
1245
+ pipeline_id: str,
1246
+ collection_id: Optional[int],
1247
+ variants_json: Optional[str],
1248
+ version: Optional[int],
1249
+ wait: bool,
1250
+ poll_interval: int,
1251
+ timeout: int,
1252
+ json_output: bool,
1253
+ api_key: Optional[str],
1254
+ base_url: str,
1255
+ ):
1256
+ """[Open beta] Run an Eval: compare pipeline variants on FILE paths or a collection."""
1257
+ try:
1258
+ if bool(paths) == bool(collection_id):
1259
+ raise click.UsageError(
1260
+ "Give either FILE paths or --collection_id, not both."
1261
+ )
1262
+ variants = None
1263
+ if variants_json is not None:
1264
+ data = _load_json_option(variants_json, "--variant-json")
1265
+ variants = [
1266
+ EvalVariant(name=v["name"], steps=v.get("steps", {})) for v in data
1267
+ ]
1268
+
1269
+ client = _eval_client(api_key, base_url)
1270
+ file_ids = None
1271
+ if paths:
1272
+ uploaded = client.upload_files(list(paths))
1273
+ if not isinstance(uploaded, list):
1274
+ uploaded = [uploaded]
1275
+ file_ids = [u.file_id for u in uploaded]
1276
+
1277
+ evaluation = client.create_eval(
1278
+ pipeline_id,
1279
+ file_ids=file_ids,
1280
+ collection_id=collection_id,
1281
+ variants=variants,
1282
+ version=version,
1283
+ )
1284
+ if wait:
1285
+ evaluation = client.wait_for_eval(
1286
+ evaluation.eval_id, poll_interval=poll_interval, timeout=timeout
1287
+ )
1288
+ if json_output:
1289
+ click.echo(json.dumps(dataclasses.asdict(evaluation), indent=2))
1290
+ else:
1291
+ _print_eval_summary(evaluation)
1292
+ elif json_output:
1293
+ click.echo(json.dumps(dataclasses.asdict(evaluation), indent=2))
1294
+ else:
1295
+ click.echo(f"Eval {evaluation.eval_id} started ({evaluation.status}).")
1296
+ click.echo(f"Check it with: datalab eval get {evaluation.eval_id}")
1297
+ except DatalabError as e:
1298
+ click.echo(f"Error: {e}", err=True)
1299
+ sys.exit(1)
1300
+
1301
+
1302
+ @eval_group.command("get")
1303
+ @click.argument("eval_id", type=int)
1304
+ @eval_option_json
1305
+ @eval_option_api_key
1306
+ @eval_option_base_url
1307
+ def eval_get(eval_id: int, json_output: bool, api_key: Optional[str], base_url: str):
1308
+ """[Open beta] Get an Eval's status and each variant's result."""
1309
+ try:
1310
+ client = _eval_client(api_key, base_url)
1311
+ evaluation = client.get_eval(eval_id)
1312
+ if json_output:
1313
+ click.echo(json.dumps(dataclasses.asdict(evaluation), indent=2))
1314
+ else:
1315
+ _print_eval_summary(evaluation)
1316
+ except DatalabError as e:
1317
+ click.echo(f"Error: {e}", err=True)
1318
+ sys.exit(1)
1319
+
1320
+
1321
+ @eval_group.command("list")
1322
+ @click.option("--pipeline_id", help="Only Evals of this pipeline")
1323
+ @click.option("--collection_id", type=int, help="Only Evals of this collection")
1324
+ @click.option("--limit", default=20, type=int, help="Maximum number to return")
1325
+ @click.option("--offset", default=0, type=int, help="Offset for pagination")
1326
+ @eval_option_json
1327
+ @eval_option_api_key
1328
+ @eval_option_base_url
1329
+ def eval_list(
1330
+ pipeline_id: Optional[str],
1331
+ collection_id: Optional[int],
1332
+ limit: int,
1333
+ offset: int,
1334
+ json_output: bool,
1335
+ api_key: Optional[str],
1336
+ base_url: str,
1337
+ ):
1338
+ """[Open beta] List the team's Evals, newest first."""
1339
+ try:
1340
+ client = _eval_client(api_key, base_url)
1341
+ result = client.list_evals(
1342
+ pipeline_id=pipeline_id,
1343
+ collection_id=collection_id,
1344
+ limit=limit,
1345
+ offset=offset,
1346
+ )
1347
+ if json_output:
1348
+ click.echo(json.dumps(dataclasses.asdict(result), indent=2))
1349
+ else:
1350
+ click.echo(f"{result.total} Eval(s):")
1351
+ for evaluation in result.evals:
1352
+ click.echo(
1353
+ f" {evaluation.eval_id}: {evaluation.status} (pipeline {evaluation.pipeline_id})"
1354
+ )
1355
+ except DatalabError as e:
1356
+ click.echo(f"Error: {e}", err=True)
1357
+ sys.exit(1)
1358
+
1359
+
1360
+ @eval_group.command("differences")
1361
+ @click.argument("eval_id", type=int)
1362
+ @click.argument("file_id", type=int)
1363
+ @eval_option_json
1364
+ @eval_option_api_key
1365
+ @eval_option_base_url
1366
+ def eval_differences(
1367
+ eval_id: int, file_id: int, json_output: bool, api_key: Optional[str], base_url: str
1368
+ ):
1369
+ """[Open beta] Show where an Eval's variants read one document differently."""
1370
+ try:
1371
+ client = _eval_client(api_key, base_url)
1372
+ result = client.get_eval_differences(eval_id, file_id)
1373
+ if json_output:
1374
+ click.echo(json.dumps(dataclasses.asdict(result), indent=2))
1375
+ else:
1376
+ click.echo(
1377
+ f"File {result.file_id}: variants {', '.join(result.variant_names)}"
1378
+ )
1379
+ for d in result.differences:
1380
+ label = d.question or d.before[:40]
1381
+ click.echo(
1382
+ f" page {d.page} [{d.verdict}] {label!r} -> winners {d.winners}"
1383
+ )
1384
+ except DatalabError as e:
1385
+ click.echo(f"Error: {e}", err=True)
1386
+ sys.exit(1)
1387
+
1388
+
1147
1389
  # Workflow commands
1148
1390
  def _echo_workflows_removed():
1149
1391
  click.echo(
@@ -1652,6 +1894,7 @@ cli.add_command(fill)
1652
1894
  cli.add_command(form_fields)
1653
1895
  cli.add_command(agent)
1654
1896
  cli.add_command(create_document)
1897
+ cli.add_command(eval_group)
1655
1898
  cli.add_command(create_workflow)
1656
1899
  cli.add_command(get_workflow)
1657
1900
  cli.add_command(get_step_types)
datalab_sdk/client.py CHANGED
@@ -65,6 +65,15 @@ from datalab_sdk.models import (
65
65
  PipelineExecutionStepResult,
66
66
  CustomProcessor,
67
67
  CustomProcessorVersion,
68
+ Eval,
69
+ EvalDifference,
70
+ EvalDifferences,
71
+ EvalDocumentResult,
72
+ EvalField,
73
+ EvalFile,
74
+ EvalList,
75
+ EvalVariant,
76
+ EvalVariantResult,
68
77
  )
69
78
  from datalab_sdk.settings import settings
70
79
 
@@ -94,6 +103,16 @@ class _ProgressReporter:
94
103
 
95
104
  # HTTP status codes that a POST submission can safely retry. The API sends
96
105
  # 429 for rate limits and 503 when it cannot queue the job ("please retry").
106
+ # Pipeline execution statuses that end polling. ``needs_review``: the output is
107
+ # ready, but a blocking Check failed or the Request hit its cost limit.
108
+ _OUTPUT_READY_PIPELINE_STATUSES = ("completed", "needs_review")
109
+ _TERMINAL_PIPELINE_STATUSES = (
110
+ "completed",
111
+ "completed_with_errors",
112
+ "needs_review",
113
+ "failed",
114
+ )
115
+
97
116
  _SUBMIT_RETRY_STATUSES = (429, 503)
98
117
  _BACKOFF = wait_exponential_jitter(initial=5, max=120)
99
118
  _MAX_RETRY_AFTER_SECONDS = 120.0
@@ -1480,7 +1499,8 @@ class AsyncDatalabClient:
1480
1499
  Find the fillable fields on each page of a PDF or image
1481
1500
 
1482
1501
  The API finds blank lines, empty boxes, tick boxes and signature
1483
- blanks, with their printed labels.
1502
+ blanks, with their printed labels. With options.include_text, it also
1503
+ reads the page text and marks each field in that text.
1484
1504
 
1485
1505
  Args:
1486
1506
  file_path: Path to the PDF or image
@@ -1518,6 +1538,8 @@ class AsyncDatalabClient:
1518
1538
  success=result_data.get("success"),
1519
1539
  error=result_data.get("error"),
1520
1540
  pages=result_data.get("pages"),
1541
+ json=result_data.get("json"),
1542
+ text_error=result_data.get("text_error"),
1521
1543
  page_count=result_data.get("page_count"),
1522
1544
  cost_breakdown=result_data.get("cost_breakdown"),
1523
1545
  runtime=result_data.get("runtime"),
@@ -2620,15 +2642,12 @@ class AsyncDatalabClient:
2620
2642
  execution = self._build_pipeline_execution(response)
2621
2643
  progress = _ProgressReporter(on_progress)
2622
2644
  await progress.report(
2623
- execution.progress_percent, complete=execution.status == "completed"
2645
+ execution.progress_percent,
2646
+ complete=execution.status in _OUTPUT_READY_PIPELINE_STATUSES,
2624
2647
  )
2625
2648
 
2626
2649
  # Poll if requested
2627
- if max_polls > 1 and execution.status not in (
2628
- "completed",
2629
- "completed_with_errors",
2630
- "failed",
2631
- ):
2650
+ if max_polls > 1 and execution.status not in _TERMINAL_PIPELINE_STATUSES:
2632
2651
 
2633
2652
  async def forward_progress(percent: int) -> None:
2634
2653
  await progress.report(percent, complete=percent == 100)
@@ -2664,10 +2683,11 @@ class AsyncDatalabClient:
2664
2683
  )
2665
2684
  execution = self._build_pipeline_execution(response)
2666
2685
  await progress.report(
2667
- execution.progress_percent, complete=execution.status == "completed"
2686
+ execution.progress_percent,
2687
+ complete=execution.status in _OUTPUT_READY_PIPELINE_STATUSES,
2668
2688
  )
2669
2689
 
2670
- if execution.status in ("completed", "completed_with_errors", "failed"):
2690
+ if execution.status in _TERMINAL_PIPELINE_STATUSES:
2671
2691
  return execution
2672
2692
 
2673
2693
  if i < max_polls - 1:
@@ -2860,6 +2880,240 @@ class AsyncDatalabClient:
2860
2880
  "POST", f"/api/v1/custom_processors/{processor_id}/archive"
2861
2881
  )
2862
2882
 
2883
+ # --- Eval methods ---
2884
+
2885
+ async def create_eval(
2886
+ self,
2887
+ pipeline_id: str,
2888
+ *,
2889
+ file_ids: Optional[list[int]] = None,
2890
+ collection_id: Optional[int] = None,
2891
+ variants: Optional[list[EvalVariant]] = None,
2892
+ version: Optional[int] = None,
2893
+ ) -> Eval:
2894
+ """
2895
+ Run 2 to 4 variants of a pipeline on the same documents and compare them.
2896
+
2897
+ Open beta: the API may change.
2898
+
2899
+ Give exactly one of file_ids (uploaded with upload_files()) or
2900
+ collection_id. With no variants, the Eval compares the Fast,
2901
+ Balanced and Accurate modes. A variant may change only the mode
2902
+ settings: for a pipeline of Convert steps, output_mode and
2903
+ merge_cross_page; for a pipeline with one Extract step,
2904
+ extraction_mode and the Convert output_mode.
2905
+
2906
+ Args:
2907
+ pipeline_id: Pipeline ID string (e.g. pl_k8Hx9mP2nQ4v)
2908
+ file_ids: Uploaded file IDs to compare (mutually exclusive with collection_id)
2909
+ collection_id: Collection whose files to compare (mutually exclusive with file_ids)
2910
+ variants: 2 to 4 EvalVariant objects, each with a different name.
2911
+ Omit to compare the default modes.
2912
+ version: Pipeline version to run (0=draft, omit=active)
2913
+ """
2914
+ if (file_ids is None) == (collection_id is None):
2915
+ raise DatalabValidationError(
2916
+ "Give exactly one of file_ids or collection_id."
2917
+ )
2918
+ payload: Dict[str, Any] = {}
2919
+ if file_ids is not None:
2920
+ payload["file_ids"] = file_ids
2921
+ if collection_id is not None:
2922
+ payload["collection_id"] = collection_id
2923
+ if variants is not None:
2924
+ payload["variants"] = [v.to_dict() for v in variants]
2925
+ if version is not None:
2926
+ payload["version"] = version
2927
+ response = await self._make_request(
2928
+ "POST", f"/api/v1/pipelines/{pipeline_id}/evals", json=payload
2929
+ )
2930
+ return self._build_eval(response)
2931
+
2932
+ async def get_eval(self, eval_id: int) -> Eval:
2933
+ """
2934
+ Get an Eval's status, each variant's share of the differences, and each document
2935
+
2936
+ Open beta: the API may change.
2937
+
2938
+ Args:
2939
+ eval_id: The Eval's ID
2940
+ """
2941
+ response = await self._make_request("GET", f"/api/v1/evals/{eval_id}")
2942
+ return self._build_eval(response)
2943
+
2944
+ async def list_evals(
2945
+ self,
2946
+ pipeline_id: Optional[str] = None,
2947
+ collection_id: Optional[int] = None,
2948
+ limit: int = 20,
2949
+ offset: int = 0,
2950
+ ) -> EvalList:
2951
+ """
2952
+ List the team's Evals, newest first, without per-document results
2953
+
2954
+ Open beta: the API may change.
2955
+
2956
+ Args:
2957
+ pipeline_id: Only Evals of this pipeline
2958
+ collection_id: Only Evals of this collection
2959
+ limit: Maximum number to return (default: 20, max: 100)
2960
+ offset: Offset for pagination (default: 0)
2961
+ """
2962
+ params = f"limit={limit}&offset={offset}"
2963
+ if pipeline_id is not None:
2964
+ params += f"&pipeline_id={pipeline_id}"
2965
+ if collection_id is not None:
2966
+ params += f"&collection_id={collection_id}"
2967
+ response = await self._make_request("GET", f"/api/v1/evals?{params}")
2968
+ return EvalList(
2969
+ evals=[self._build_eval(e) for e in response.get("evals", [])],
2970
+ total=response.get("total", 0),
2971
+ )
2972
+
2973
+ async def get_eval_differences(self, eval_id: int, file_id: int) -> EvalDifferences:
2974
+ """
2975
+ Get where an Eval's variants read one document differently, and which reading
2976
+ matches the page
2977
+
2978
+ Open beta: the API may change.
2979
+
2980
+ Args:
2981
+ eval_id: The Eval's ID
2982
+ file_id: The file's ID, from get_eval().files
2983
+ """
2984
+ response = await self._make_request(
2985
+ "GET", f"/api/v1/evals/{eval_id}/files/{file_id}/differences"
2986
+ )
2987
+ return EvalDifferences(
2988
+ file_id=response.get("file_id", file_id),
2989
+ variant_names=response.get("variant_names") or [],
2990
+ differences=[
2991
+ self._build_eval_difference(d)
2992
+ for d in response.get("differences") or []
2993
+ ],
2994
+ fields=[
2995
+ EvalField(
2996
+ path=f.get("path", ""),
2997
+ description=f.get("description", ""),
2998
+ values=f.get("values") or [],
2999
+ )
3000
+ for f in response.get("fields") or []
3001
+ ],
3002
+ )
3003
+
3004
+ async def wait_for_eval(
3005
+ self,
3006
+ eval_id: int,
3007
+ *,
3008
+ poll_interval: int = 10,
3009
+ timeout: int = 7200,
3010
+ ) -> Eval:
3011
+ """
3012
+ Poll get_eval() until the Eval completes or fails
3013
+
3014
+ Open beta: the API may change.
3015
+
3016
+ Args:
3017
+ eval_id: The Eval's ID
3018
+ poll_interval: Seconds between polls
3019
+ timeout: Maximum seconds to wait before raising DatalabTimeoutError
3020
+ """
3021
+ slept = 0
3022
+ while True:
3023
+ result = await self.get_eval(eval_id)
3024
+ if result.status in ("completed", "failed"):
3025
+ return result
3026
+ if slept >= timeout:
3027
+ raise DatalabTimeoutError(
3028
+ f"Eval {eval_id} did not finish within {timeout} seconds"
3029
+ )
3030
+ await asyncio.sleep(poll_interval)
3031
+ slept += poll_interval
3032
+
3033
+ @staticmethod
3034
+ def _build_eval_document_result(data: Dict[str, Any]) -> EvalDocumentResult:
3035
+ return EvalDocumentResult(
3036
+ file_name=data.get("file_name", ""),
3037
+ status=data.get("status", ""),
3038
+ file_id=data.get("file_id"),
3039
+ lookup_key=data.get("lookup_key"),
3040
+ request_id=data.get("request_id"),
3041
+ share=data.get("share"),
3042
+ won=data.get("won", 0),
3043
+ decided=data.get("decided", 0),
3044
+ undecided=data.get("undecided", 0),
3045
+ )
3046
+
3047
+ @staticmethod
3048
+ def _build_eval_file(data: Dict[str, Any]) -> EvalFile:
3049
+ return EvalFile(
3050
+ file_id=data["file_id"],
3051
+ file_name=data.get("file_name", ""),
3052
+ comparison=data.get("comparison", "pending"),
3053
+ comparison_error=data.get("comparison_error"),
3054
+ )
3055
+
3056
+ @staticmethod
3057
+ def _build_eval_difference(data: Dict[str, Any]) -> EvalDifference:
3058
+ return EvalDifference(
3059
+ page=data.get("page", 0),
3060
+ before=data.get("before", ""),
3061
+ after=data.get("after", ""),
3062
+ readings=data.get("readings") or [],
3063
+ winners=data.get("winners") or [],
3064
+ verdict=data.get("verdict", "none"),
3065
+ decided_by=data.get("decided_by", ""),
3066
+ weight=data.get("weight", 0.0),
3067
+ question=data.get("question", ""),
3068
+ boxes=data.get("boxes") or [],
3069
+ description=data.get("description", ""),
3070
+ )
3071
+
3072
+ @classmethod
3073
+ def _build_eval_variant_result(cls, data: Dict[str, Any]) -> EvalVariantResult:
3074
+ documents = data.get("documents")
3075
+ return EvalVariantResult(
3076
+ name=data.get("name", ""),
3077
+ steps=data.get("steps") or {},
3078
+ status=data.get("status", ""),
3079
+ share=data.get("share"),
3080
+ won=data.get("won", 0),
3081
+ decided=data.get("decided", 0),
3082
+ documents_compared=data.get("documents_compared", 0),
3083
+ documents_total=data.get("documents_total", 0),
3084
+ page_breaks_passed=data.get("page_breaks_passed", 0),
3085
+ page_breaks_total=data.get("page_breaks_total", 0),
3086
+ convert_settings=data.get("convert_settings") or {},
3087
+ extract_settings=data.get("extract_settings") or {},
3088
+ undecided=data.get("undecided", 0),
3089
+ rate_per_1000_pages_cents=data.get("rate_per_1000_pages_cents"),
3090
+ seconds_per_page=data.get("seconds_per_page"),
3091
+ documents=[cls._build_eval_document_result(d) for d in documents]
3092
+ if documents is not None
3093
+ else None,
3094
+ )
3095
+
3096
+ @classmethod
3097
+ def _build_eval(cls, data: Dict[str, Any]) -> Eval:
3098
+ files = data.get("files")
3099
+ return Eval(
3100
+ eval_id=data.get("eval_id"),
3101
+ pipeline_id=data.get("pipeline_id", ""),
3102
+ status=data.get("status", ""),
3103
+ variants=[
3104
+ cls._build_eval_variant_result(v) for v in data.get("variants") or []
3105
+ ],
3106
+ pipeline_name=data.get("pipeline_name"),
3107
+ pipeline_version=data.get("pipeline_version"),
3108
+ compared_step=data.get("compared_step", "convert"),
3109
+ collection_id=data.get("collection_id"),
3110
+ file_ids=data.get("file_ids"),
3111
+ files=[cls._build_eval_file(f) for f in files]
3112
+ if files is not None
3113
+ else None,
3114
+ created=data.get("created"),
3115
+ )
3116
+
2863
3117
 
2864
3118
  class DatalabClient:
2865
3119
  """Synchronous wrapper around AsyncDatalabClient"""
@@ -3339,8 +3593,6 @@ class DatalabClient:
3339
3593
  """Delete the stored result of a finished request (sync version)"""
3340
3594
  return self._run_async(self._async_client.delete_result(request_id=request_id))
3341
3595
 
3342
- # --- Eval Rubric methods (sync) ---
3343
-
3344
3596
  # Workflow methods (sync)
3345
3597
  def create_workflow(
3346
3598
  self,
@@ -3815,3 +4067,68 @@ class DatalabClient:
3815
4067
  return self._run_async(
3816
4068
  self._async_client.archive_custom_processor(processor_id=processor_id)
3817
4069
  )
4070
+
4071
+ # --- Eval methods (sync) ---
4072
+
4073
+ def create_eval(
4074
+ self,
4075
+ pipeline_id: str,
4076
+ *,
4077
+ file_ids: Optional[list[int]] = None,
4078
+ collection_id: Optional[int] = None,
4079
+ variants: Optional[list[EvalVariant]] = None,
4080
+ version: Optional[int] = None,
4081
+ ) -> Eval:
4082
+ """Run and compare pipeline variants (sync version). Open beta: the API may change."""
4083
+ return self._run_async(
4084
+ self._async_client.create_eval(
4085
+ pipeline_id,
4086
+ file_ids=file_ids,
4087
+ collection_id=collection_id,
4088
+ variants=variants,
4089
+ version=version,
4090
+ )
4091
+ )
4092
+
4093
+ def get_eval(self, eval_id: int) -> Eval:
4094
+ """Get an Eval's status and results (sync version). Open beta: the API may change."""
4095
+ return self._run_async(self._async_client.get_eval(eval_id))
4096
+
4097
+ def list_evals(
4098
+ self,
4099
+ pipeline_id: Optional[str] = None,
4100
+ collection_id: Optional[int] = None,
4101
+ limit: int = 20,
4102
+ offset: int = 0,
4103
+ ) -> EvalList:
4104
+ """List the team's Evals (sync version). Open beta: the API may change."""
4105
+ return self._run_async(
4106
+ self._async_client.list_evals(
4107
+ pipeline_id=pipeline_id,
4108
+ collection_id=collection_id,
4109
+ limit=limit,
4110
+ offset=offset,
4111
+ )
4112
+ )
4113
+
4114
+ def get_eval_differences(self, eval_id: int, file_id: int) -> EvalDifferences:
4115
+ """Get one document's differences (sync version). Open beta: the API may change."""
4116
+ return self._run_async(
4117
+ self._async_client.get_eval_differences(eval_id, file_id)
4118
+ )
4119
+
4120
+ def wait_for_eval(
4121
+ self,
4122
+ eval_id: int,
4123
+ *,
4124
+ poll_interval: int = 10,
4125
+ timeout: int = 7200,
4126
+ ) -> Eval:
4127
+ """Poll until the Eval completes or fails (sync version). Open beta: the API may change."""
4128
+ return self._run_async(
4129
+ self._async_client.wait_for_eval(
4130
+ eval_id,
4131
+ poll_interval=poll_interval,
4132
+ timeout=timeout,
4133
+ )
4134
+ )
datalab_sdk/models.py CHANGED
@@ -297,6 +297,9 @@ class FormFieldsOptions(ProcessingOptions):
297
297
 
298
298
  webhook_url: Optional[str] = None
299
299
  processing_location: Optional[str] = None # residency region, e.g. "eu"
300
+ # Also read the page text (fast mode OCR, in parallel) and put each field into
301
+ # it. Slower, and billed as a fast parse plus form fields.
302
+ include_text: bool = False
300
303
 
301
304
 
302
305
  @dataclass
@@ -811,14 +814,23 @@ class FormFieldsResult:
811
814
  """Result from fillable field detection (/form-fields endpoint)
812
815
 
813
816
  Each page is a dict with 'page', 'fields' and 'error' keys. Each field
814
- has 'field_type', 'bbox' ([x0, y0, x1, y1] as page fractions) and
815
- 'label'.
817
+ has 'field_type', 'bbox' ([x0, y0, x1, y1] as page fractions), 'label'
818
+ (the printed label) and 'name' (a short descriptive name, empty when the
819
+ printed label is enough).
820
+
821
+ With FormFieldsOptions(include_text=True), each page also has 'text' (the
822
+ page text with every field marked where a reader meets it) and 'json' is
823
+ the fast mode parse JSON with an <input data-field-index> tag in the HTML
824
+ of each block that holds a field. 'text_error' is set when the page text
825
+ could not be read; the fields are still returned.
816
826
  """
817
827
 
818
828
  status: str
819
829
  success: Optional[bool] = None
820
830
  error: Optional[str] = None
821
831
  pages: Optional[List[Dict[str, Any]]] = None
832
+ json: Optional[Dict[str, Any]] = None
833
+ text_error: Optional[str] = None
822
834
  page_count: Optional[int] = None
823
835
  cost_breakdown: Optional[Dict[str, Any]] = None
824
836
  runtime: Optional[float] = None
@@ -838,6 +850,8 @@ class FormFieldsResult:
838
850
  "success": self.success,
839
851
  "error": self.error,
840
852
  "pages": self.pages,
853
+ "json": self.json,
854
+ "text_error": self.text_error,
841
855
  "page_count": self.page_count,
842
856
  },
843
857
  indent=2,
@@ -971,7 +985,9 @@ class PipelineExecution:
971
985
  execution_id: str # pex_XXXXX
972
986
  pipeline_id: str # pl_XXXXX
973
987
  pipeline_version: int
974
- status: str # pending, running, completed, completed_with_errors, failed
988
+ status: (
989
+ str # pending, running, completed, completed_with_errors, needs_review, failed
990
+ )
975
991
  steps: List[PipelineExecutionStepResult] = field(default_factory=list)
976
992
  started_at: Optional[str] = None
977
993
  completed_at: Optional[str] = None
@@ -1013,3 +1029,164 @@ class CustomProcessorVersion:
1013
1029
  created_at: Optional[str] = None
1014
1030
  runtime: Optional[float] = None
1015
1031
  is_active: bool = False
1032
+
1033
+
1034
+ # --- Eval models (open beta; the API may change) ---
1035
+
1036
+
1037
+ @dataclass
1038
+ class EvalVariant:
1039
+ """One variant that an Eval runs and compares, with its own settings.
1040
+
1041
+ `steps` maps a step type ("convert" or "extract") to the settings that
1042
+ this variant merges into that step's settings, for example
1043
+ {"convert": {"output_mode": "accurate"}}. Open beta: the API may change.
1044
+ """
1045
+
1046
+ name: str
1047
+ steps: Dict[str, Dict[str, Any]] = field(default_factory=dict)
1048
+
1049
+ def to_dict(self) -> Dict[str, Any]:
1050
+ """Convert to a dict for the create_eval request body"""
1051
+ return {"name": self.name, "steps": self.steps}
1052
+
1053
+
1054
+ @dataclass
1055
+ class EvalDocumentResult:
1056
+ """One document's result for one variant of an Eval (open beta).
1057
+
1058
+ `share` is this variant's share of the decided places (won / decided) on
1059
+ this document. None until the comparison ends, or when nothing was
1060
+ decided.
1061
+ """
1062
+
1063
+ file_name: str
1064
+ status: str # processing, completed, failed
1065
+ file_id: Optional[int] = None
1066
+ lookup_key: Optional[str] = None
1067
+ request_id: Optional[int] = None
1068
+ share: Optional[float] = None
1069
+ won: int = 0
1070
+ decided: int = 0
1071
+ undecided: Optional[int] = 0
1072
+
1073
+
1074
+ @dataclass
1075
+ class EvalFile:
1076
+ """One file of an Eval, with its comparison status (open beta)."""
1077
+
1078
+ file_id: int
1079
+ file_name: str
1080
+ comparison: str = (
1081
+ "pending" # pending, starting, running, completed, failed, skipped
1082
+ )
1083
+ comparison_error: Optional[str] = None
1084
+
1085
+
1086
+ @dataclass
1087
+ class EvalVariantResult:
1088
+ """One variant's settings and result in an Eval (open beta; the API may change).
1089
+
1090
+ `share` is this variant's share of the decided places (won / decided)
1091
+ over the documents compared so far. It is relative to the other
1092
+ variants in the same Eval, not an absolute quality score.
1093
+ """
1094
+
1095
+ name: str
1096
+ steps: Dict[str, Dict[str, Any]]
1097
+ status: str # running, completed, failed
1098
+ share: Optional[float] = None
1099
+ won: int = 0
1100
+ decided: int = 0
1101
+ documents_compared: int = 0
1102
+ documents_total: int = 0
1103
+ # Tables that continue across a page break, kept as one table. Zero total
1104
+ # when the variants do not differ in merge_cross_page, or no table crosses a break.
1105
+ page_breaks_passed: int = 0
1106
+ page_breaks_total: int = 0
1107
+ # The scored Convert settings this variant ran with: output_mode and merge_cross_page.
1108
+ convert_settings: Dict[str, Any] = field(default_factory=dict)
1109
+ # The scored Extract settings of the variant (extraction_mode), for an Eval of Extract.
1110
+ extract_settings: Dict[str, Any] = field(default_factory=dict)
1111
+ # Places where the variants differ but no reading was decided. None when unknown.
1112
+ undecided: Optional[int] = 0
1113
+ # The list price per 1,000 pages quoted when the variant's requests started
1114
+ # (before any discount), in cents.
1115
+ rate_per_1000_pages_cents: Optional[float] = None
1116
+ seconds_per_page: Optional[float] = None
1117
+ # Per-document results. Only present on get_eval(), not on create_eval() or list_evals().
1118
+ documents: Optional[List[EvalDocumentResult]] = None
1119
+
1120
+
1121
+ @dataclass
1122
+ class Eval:
1123
+ """Status and results of an Eval that compares pipeline variants (open beta; the API may change)."""
1124
+
1125
+ eval_id: int
1126
+ pipeline_id: str
1127
+ status: str # running, completed, failed
1128
+ variants: List[EvalVariantResult] = field(default_factory=list)
1129
+ pipeline_name: Optional[str] = None
1130
+ pipeline_version: Optional[int] = None
1131
+ # "convert" (the pages) or "extract" (the fields of the pipeline's Extract step)
1132
+ compared_step: str = "convert"
1133
+ collection_id: Optional[int] = None
1134
+ file_ids: Optional[List[int]] = None
1135
+ # The files of the Eval, with names and comparison status. Only on get_eval().
1136
+ files: Optional[List[EvalFile]] = None
1137
+ created: Optional[str] = None
1138
+
1139
+
1140
+ @dataclass
1141
+ class EvalList:
1142
+ """A page of the team's Evals, newest first (open beta; the API may change)."""
1143
+
1144
+ evals: List[Eval] = field(default_factory=list)
1145
+ total: int = 0
1146
+
1147
+
1148
+ @dataclass
1149
+ class EvalDifference:
1150
+ """One place where an Eval's variants read a document differently (open beta).
1151
+
1152
+ `verdict` is "decided", "none", "unclear" or "ignored". `decided_by` is
1153
+ "text_layer", "judge", or "" when not decided. For a table difference,
1154
+ `question` holds the question about the cell in place of before/after.
1155
+ For an Eval of Extract, `description` is the schema's description of the
1156
+ field that `question` names.
1157
+ """
1158
+
1159
+ page: int
1160
+ before: str
1161
+ after: str
1162
+ readings: List[str] = field(default_factory=list)
1163
+ winners: List[int] = field(default_factory=list)
1164
+ verdict: str = "none"
1165
+ decided_by: str = ""
1166
+ weight: float = 0.0
1167
+ question: str = ""
1168
+ boxes: List[List[float]] = field(default_factory=list)
1169
+ description: str = ""
1170
+
1171
+
1172
+ @dataclass
1173
+ class EvalField:
1174
+ """An Eval of Extract: one compared field and each variant's value, equal or not (open beta).
1175
+
1176
+ `values` follows EvalDifferences.variant_names. An empty string means no value.
1177
+ """
1178
+
1179
+ path: str
1180
+ description: str = ""
1181
+ values: List[str] = field(default_factory=list)
1182
+
1183
+
1184
+ @dataclass
1185
+ class EvalDifferences:
1186
+ """Where an Eval's variants read one document differently (open beta; the API may change)."""
1187
+
1188
+ file_id: int
1189
+ variant_names: List[str] = field(default_factory=list)
1190
+ differences: List[EvalDifference] = field(default_factory=list)
1191
+ # An Eval of Extract: every compared field with each variant's value. Empty for Convert.
1192
+ fields: List[EvalField] = field(default_factory=list)
@@ -1,13 +0,0 @@
1
- datalab_sdk/__init__.py,sha256=O95y4a-N34dxyDak6YWrUjEG4kdtVirgBqShh1L6z_Q,2475
2
- datalab_sdk/auth.py,sha256=X2eccKzpdxogFEDoS4geOHIOeECQ8u3kANxKoqF0PVk,4388
3
- datalab_sdk/cli.py,sha256=6tYZhkx1f4enOU2tvqC43aDW1dI_agJrOCBG5RAJwvg,54490
4
- datalab_sdk/client.py,sha256=NaGY8NKAcOjaBIV0adS_n6diOu710Az581zYdt4jwKM,141435
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=tr5pGsbI9x7GDrN4BAyWMEMWLcF1goJ5Ot8X4pFeT5k,35081
8
- datalab_sdk/settings.py,sha256=B_B42QQADAz6ePXQTOqENZllcppFR4JpwonEk2vlzhw,693
9
- datalab_python_sdk-0.9.2.dist-info/METADATA,sha256=_6OLIHKgM0EZAh0BUC5-0VcuxXCHO3DV4mXRrBEwQYQ,9236
10
- datalab_python_sdk-0.9.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
- datalab_python_sdk-0.9.2.dist-info/entry_points.txt,sha256=rqWxO21UV57JxxyeF20iBTxHpzBYOA69hCHIqwdn-Ok,48
12
- datalab_python_sdk-0.9.2.dist-info/licenses/LICENSE,sha256=XGjT-Uz6t7UZzr3JCZfilsGcZEgMm_1aONcRunohxWg,1064
13
- datalab_python_sdk-0.9.2.dist-info/RECORD,,