hyperapi-sdk 0.7.1__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.
@@ -0,0 +1,2181 @@
1
+ """HyperAPI Async Client.
2
+
3
+ Async-native twin of :class:`hyperapi.client.HyperAPIClient`. The HTTP contract
4
+ is identical (submit + poll, same envelopes, same error mapping); the only
5
+ difference is that every public method is a coroutine and the polling loop
6
+ yields to the event loop via ``asyncio.sleep`` instead of blocking the thread
7
+ with ``time.sleep``.
8
+
9
+ Use this client when your code already runs inside an event loop:
10
+
11
+ * FastAPI / Starlette / aiohttp request handlers
12
+ * LLM agent loops that interleave HyperAPI with other ``await`` calls
13
+ * Discord / Slack / Telegram bots
14
+ * High-concurrency processors that fan out with ``asyncio.gather``
15
+
16
+ For batch scripts, Airflow tasks, Celery workers, and Jupyter notebooks the
17
+ sync :class:`hyperapi.client.HyperAPIClient` is the right choice — async adds
18
+ boilerplate without benefit in those contexts.
19
+
20
+ Quickstart
21
+ ==========
22
+
23
+ ::
24
+
25
+ import asyncio
26
+ from hyperapi import AsyncHyperAPIClient
27
+
28
+ async def main():
29
+ async with AsyncHyperAPIClient(api_key="hk_live_…") as client:
30
+ result = await client.extract("invoice.pdf")
31
+ print(result["result"])
32
+
33
+ asyncio.run(main())
34
+
35
+ Inside FastAPI::
36
+
37
+ from fastapi import FastAPI, UploadFile
38
+ from hyperapi import AsyncHyperAPIClient
39
+
40
+ app = FastAPI()
41
+ client = AsyncHyperAPIClient() # reads HYPERAPI_KEY from env
42
+
43
+ @app.post("/extract")
44
+ async def extract(file: UploadFile):
45
+ # Save UploadFile to a tmp path, then:
46
+ return await client.extract(tmp_path)
47
+
48
+ @app.on_event("shutdown")
49
+ async def shutdown():
50
+ await client.aclose()
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import asyncio
56
+ import contextlib
57
+ import json
58
+ import logging
59
+ import os
60
+ import sys
61
+ import time
62
+ import uuid
63
+ import warnings
64
+ from pathlib import Path
65
+ from typing import Any
66
+ from collections.abc import Awaitable, Callable, Iterable
67
+
68
+ import httpx
69
+
70
+ # Reuse the sync client's pure helpers + constants + Job + op→error registry.
71
+ # Importing rather than duplicating keeps the two clients behaviorally aligned
72
+ # and means bug fixes in error parsing / scrubbing land in both.
73
+ from .client import (
74
+ CONTENT_TYPES,
75
+ ExtractCategory,
76
+ Job,
77
+ ParseMode,
78
+ _DEFAULT_POLL_INTERVAL_S,
79
+ _DEFAULT_POLL_MAX_TRANSIENT_RETRIES,
80
+ _DEFAULT_POLL_TIMEOUT_S,
81
+ _DEFAULT_POLL_TRANSIENT_RETRY_DELAY_S,
82
+ _DEFAULT_MAX_PAGE_BYTES,
83
+ _DEFAULT_TIMEOUT,
84
+ _OP_TO_ERROR,
85
+ _TRANSFER_CONCURRENCY,
86
+ _cancelled_job_error,
87
+ _check_download_reply,
88
+ _check_page_cap,
89
+ _check_server_url,
90
+ _next_presigned_hop,
91
+ _clean_api_key,
92
+ _download_transport_error,
93
+ _error_fields,
94
+ _json_object,
95
+ _load_schema,
96
+ _page_targets,
97
+ _parse_ocr_text,
98
+ _page_too_large,
99
+ _parse_params,
100
+ _partial_path,
101
+ _path_id,
102
+ _rate_limit_error_from,
103
+ _rate_limit_wait,
104
+ _regular_file,
105
+ _request_id_of,
106
+ _resolve_base_url,
107
+ _transient_delay,
108
+ _server_message,
109
+ )
110
+ from .exceptions import (
111
+ AuthenticationError,
112
+ DocumentUploadError,
113
+ HyperAPIError,
114
+ JobTimeoutError,
115
+ RateLimitError,
116
+ _strip_api_key,
117
+ )
118
+
119
+
120
+ logger = logging.getLogger("hyperapi")
121
+
122
+
123
+ async def _bounded_map(
124
+ fn: Callable[..., Awaitable[Any]], items: Iterable[Any], limit: int
125
+ ) -> list[Any]:
126
+ """``await fn(item)`` for every item, at most ``limit`` at once, in input order.
127
+
128
+ Each coroutine is created only once a slot is free, so nothing is left
129
+ un-awaited when the rest are cancelled. On the first failure the remaining
130
+ tasks are cancelled (and drained), so a failed batch upload or page
131
+ download does not keep transferring after the caller has its exception.
132
+ """
133
+ sem = asyncio.Semaphore(limit)
134
+
135
+ async def _run(item: Any) -> Any:
136
+ async with sem:
137
+ return await fn(item)
138
+
139
+ tasks = [asyncio.ensure_future(_run(item)) for item in items]
140
+ try:
141
+ return list(await asyncio.gather(*tasks))
142
+ except BaseException:
143
+ for t in tasks:
144
+ t.cancel()
145
+ await asyncio.gather(*tasks, return_exceptions=True)
146
+ raise
147
+
148
+
149
+ @contextlib.asynccontextmanager
150
+ async def _stream_presigned_get(client: httpx.AsyncClient, url: str, *, base_url: str):
151
+ """Async twin of ``client._stream_presigned_get``: every redirect hop is
152
+ checked for https before it is requested."""
153
+ resp = await client.send(
154
+ client.build_request("GET", url), stream=True, follow_redirects=False
155
+ )
156
+ try:
157
+ hops = 0
158
+ while resp.next_request is not None:
159
+ hops += 1
160
+ nxt = _next_presigned_hop(resp, hops, base_url=base_url)
161
+ await resp.aclose()
162
+ resp = await client.send(nxt, stream=True, follow_redirects=False)
163
+ yield resp
164
+ finally:
165
+ await resp.aclose()
166
+
167
+ class AsyncHyperAPIClient:
168
+ """Async client for the HyperAPI document intelligence platform.
169
+
170
+ Mirrors :class:`hyperapi.client.HyperAPIClient` one-to-one — same
171
+ constructor signature, same method names, same return shapes, same typed
172
+ exceptions. Pick this client when your runtime is async (FastAPI, agent
173
+ loops, asyncio-based services); otherwise use the sync client.
174
+
175
+ Lifecycle
176
+ ---------
177
+ The underlying :class:`httpx.AsyncClient` holds a connection pool that
178
+ must be released. Use as an async context manager::
179
+
180
+ async with AsyncHyperAPIClient() as client:
181
+ ...
182
+
183
+ Or close manually::
184
+
185
+ client = AsyncHyperAPIClient()
186
+ try:
187
+ ...
188
+ finally:
189
+ await client.aclose()
190
+
191
+ Concurrency
192
+ -----------
193
+ A single ``AsyncHyperAPIClient`` instance can be shared across many
194
+ concurrent ``asyncio.gather`` operations — ``httpx.AsyncClient`` is
195
+ coroutine-safe. Construct one client per application, not per request.
196
+ """
197
+
198
+ def __init__(
199
+ self,
200
+ api_key: str | None = None,
201
+ base_url: str | None = None,
202
+ timeout: float = _DEFAULT_TIMEOUT,
203
+ *,
204
+ poll_interval: float = _DEFAULT_POLL_INTERVAL_S,
205
+ poll_timeout: float = _DEFAULT_POLL_TIMEOUT_S,
206
+ poll_max_transient_retries: int = _DEFAULT_POLL_MAX_TRANSIENT_RETRIES,
207
+ poll_transient_retry_delay: float = _DEFAULT_POLL_TRANSIENT_RETRY_DELAY_S,
208
+ ):
209
+ """Initialize an async HyperAPI client.
210
+
211
+ Args mirror :class:`hyperapi.client.HyperAPIClient` exactly — see
212
+ that class for full descriptions.
213
+ """
214
+ self._api_key = _clean_api_key(api_key or os.environ.get("HYPERAPI_KEY"))
215
+
216
+ self.base_url = _resolve_base_url(base_url)
217
+ self.timeout = timeout
218
+ self._poll_interval = poll_interval
219
+ self._poll_timeout = poll_timeout
220
+ self._poll_max_transient_retries = poll_max_transient_retries
221
+ self._poll_transient_retry_delay = poll_transient_retry_delay
222
+
223
+ from . import __version__ # local import to avoid circular at module load
224
+
225
+ py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
226
+ # Note the "-async" suffix in the User-Agent so server-side analytics can
227
+ # distinguish sync vs async client usage without sniffing other signals.
228
+ self._user_agent = (
229
+ f"hyperapi-sdk-python/{__version__}-async "
230
+ f"(httpx/{httpx.__version__}; Python/{py_ver})"
231
+ )
232
+ self._client = httpx.AsyncClient(
233
+ timeout=timeout,
234
+ headers={"User-Agent": self._user_agent},
235
+ )
236
+
237
+ @property
238
+ def api_key(self) -> str:
239
+ """The API key this client sends (read-only; whitespace-stripped)."""
240
+ return self._api_key
241
+
242
+ # ── Repr ─────────────────────────────────────────────────────────────
243
+
244
+ def __repr__(self) -> str:
245
+ tail = self._api_key[-4:]
246
+ return (
247
+ f"AsyncHyperAPIClient(api_key='hk_***{tail}', base_url='{self.base_url}')"
248
+ )
249
+
250
+ # ── Headers ──────────────────────────────────────────────────────────
251
+
252
+ def _get_headers(self, *, async_mode: bool = False) -> dict[str, str]:
253
+ """Per-request headers. Generates a fresh X-Request-ID per call.
254
+
255
+ ``async_mode`` here refers to the HTTP-contract flag (``X-Async: true``)
256
+ that tells the server to return a job handle, not Python's async/await.
257
+ """
258
+ headers = {
259
+ "X-API-Key": self._api_key,
260
+ "X-Request-ID": str(uuid.uuid4()),
261
+ }
262
+ if async_mode:
263
+ headers["X-Async"] = "true"
264
+ return headers
265
+
266
+ # ── Path helpers ─────────────────────────────────────────────────────
267
+
268
+ def _resolve_path(
269
+ self,
270
+ file_path: str | Path | None,
271
+ image_path: str | Path | None = None,
272
+ ) -> Path:
273
+ """Resolve and validate file path."""
274
+ raw = file_path or image_path
275
+ if raw is None:
276
+ raise ValueError("file_path is required")
277
+ path = Path(raw)
278
+ if not path.exists():
279
+ raise FileNotFoundError(f"File not found: {path}")
280
+ return path
281
+
282
+ # ── Upload ───────────────────────────────────────────────────────────
283
+
284
+ async def upload_document(
285
+ self,
286
+ file_path: str | Path,
287
+ content_type: str | None = None,
288
+ ) -> str:
289
+ """Upload a document via the presigned-URL flow and return its document_key.
290
+
291
+ Two awaits under the hood: a presigned-URL fetch and the direct upload
292
+ PUT. The returned ``document_key`` is reusable across subsequent
293
+ inference calls without re-uploading.
294
+
295
+ Raises:
296
+ FileNotFoundError: If the file does not exist.
297
+ ValueError: If the path is not a regular file (a directory, pipe or device).
298
+ AuthenticationError: 401 from the server.
299
+ DocumentUploadError: Any other failure on the presigned fetch or S3 PUT,
300
+ including a presigned URL that is not https.
301
+ """
302
+ path = _regular_file(file_path)
303
+
304
+ if content_type is None:
305
+ content_type = CONTENT_TYPES.get(
306
+ path.suffix.lower(), "application/octet-stream"
307
+ )
308
+
309
+ headers = self._get_headers()
310
+ request_id = headers["X-Request-ID"]
311
+
312
+ # Send the file size so the server can pre-flight the size limit and
313
+ # reject oversized files with a 413 here, before the S3 PUT, instead of
314
+ # failing later at the PUT. Best-effort: skipped if stat() fails.
315
+ body: dict[str, object] = {"filename": path.name, "content_type": content_type}
316
+ try:
317
+ body["content_length"] = path.stat().st_size
318
+ except OSError:
319
+ pass
320
+
321
+ # Step 1 — request an authenticated presigned upload URL.
322
+ try:
323
+ resp = await self._client.post(
324
+ f"{self.base_url}/v1/documents/upload",
325
+ json=body,
326
+ headers=headers,
327
+ )
328
+ except httpx.RequestError as e:
329
+ raise DocumentUploadError(
330
+ f"Failed to get upload URL: {e}", request_id=request_id
331
+ ) from None
332
+
333
+ self._raise_for_known_status(
334
+ resp,
335
+ request_id=request_id,
336
+ error_cls=DocumentUploadError,
337
+ op_name="upload",
338
+ )
339
+ if resp.status_code != 200:
340
+ raise DocumentUploadError(
341
+ _server_message(resp, "Upload URL request failed"),
342
+ status_code=resp.status_code,
343
+ request_id=_request_id_of(resp, request_id),
344
+ )
345
+
346
+ upload_data = _json_object(
347
+ resp,
348
+ request_id=_request_id_of(resp, request_id),
349
+ error_cls=DocumentUploadError,
350
+ required=("document_key", "upload_url"),
351
+ what="upload-URL",
352
+ )
353
+ document_key = upload_data["document_key"]
354
+ upload_url = upload_data["upload_url"]
355
+ _check_server_url(
356
+ upload_url,
357
+ base_url=self.base_url,
358
+ what="presigned upload URL",
359
+ error_cls=DocumentUploadError,
360
+ )
361
+
362
+ # Step 2 — upload bytes directly to object storage using the signed URL.
363
+ # The file is read in a worker thread so the event loop keeps running.
364
+ file_bytes = await asyncio.to_thread(path.read_bytes)
365
+ try:
366
+ s3_resp = await self._client.put(
367
+ upload_url,
368
+ content=file_bytes,
369
+ headers={
370
+ "Content-Type": content_type,
371
+ "x-amz-server-side-encryption": "AES256",
372
+ },
373
+ )
374
+ except httpx.RequestError as e:
375
+ raise DocumentUploadError(
376
+ f"S3 upload failed: {e}", request_id=request_id
377
+ ) from None
378
+
379
+ if s3_resp.status_code not in (200, 204):
380
+ raise DocumentUploadError(
381
+ f"S3 PUT failed (status {s3_resp.status_code}). "
382
+ "Ensure x-amz-server-side-encryption: AES256 is present.",
383
+ status_code=s3_resp.status_code,
384
+ request_id=request_id,
385
+ )
386
+
387
+ logger.info(
388
+ "document_uploaded",
389
+ extra={"request_id": request_id, "document_key": document_key},
390
+ )
391
+ return document_key
392
+
393
+ # ── Limits ───────────────────────────────────────────────────────────
394
+
395
+ async def get_limits(self) -> dict:
396
+ """This key's per-task ceilings (``GET /v1/limits``) — a pure read.
397
+
398
+ Limits vary by plan, so pre-flight against this rather than hard-coding
399
+ a number. The response is::
400
+
401
+ {
402
+ "max_upload_bytes": int, # what upload itself admits
403
+ "parse_fast": {"max_bytes": int, "max_pages": int | None},
404
+ "parse_advanced": {"max_bytes": int, "max_pages": int | None},
405
+ "bulk_parse": {...}, # only when offered to you
406
+ "extract_fast": {...},
407
+ "extract_advanced":{...}, # only when offered to you
408
+ "classify": {...},
409
+ "split": {...},
410
+ "redact": {"max_bytes": int, "max_pages": int | None,
411
+ "urls_max_pages": int | None}
412
+ }
413
+
414
+ ``max_pages`` is ``None`` where the task does not reject on page
415
+ count. The optional blocks (``bulk_parse``, ``extract_advanced``) are
416
+ absent when that mode is not available to this key — absent means
417
+ "not offered", never "unlimited". Likewise ``redact.urls_max_pages``
418
+ is present only while ``output="urls"`` is accepted; its presence is
419
+ the feature detection for that mode (see :py:meth:`submit_redact`).
420
+
421
+ Returns:
422
+ The decoded JSON body as a dict.
423
+
424
+ Raises:
425
+ AuthenticationError: 401 (bad key).
426
+ RateLimitError: 429.
427
+ HyperAPIError: Any other ≥400, or a malformed body.
428
+ """
429
+ headers = self._get_headers()
430
+ request_id = headers["X-Request-ID"]
431
+
432
+ try:
433
+ resp = await self._client.get(
434
+ f"{self.base_url}/v1/limits", headers=headers
435
+ )
436
+ except httpx.RequestError as e:
437
+ raise HyperAPIError(f"Limits request failed: {e}", request_id=request_id) from None
438
+
439
+ rid = _request_id_of(resp, request_id)
440
+ if resp.status_code == 401:
441
+ raise AuthenticationError(
442
+ "Invalid API key.", status_code=401, request_id=rid
443
+ )
444
+ if resp.status_code == 429:
445
+ raise _rate_limit_error_from(resp, rid)
446
+ if resp.status_code >= 400:
447
+ raise HyperAPIError(
448
+ _server_message(resp, f"Limits request failed (HTTP {resp.status_code})"),
449
+ status_code=resp.status_code,
450
+ request_id=rid,
451
+ **_error_fields(resp),
452
+ )
453
+ try:
454
+ body = resp.json()
455
+ if not isinstance(body, dict):
456
+ raise TypeError(f"body is {type(body).__name__}, expected object")
457
+ return body
458
+ except (json.JSONDecodeError, ValueError, TypeError) as e:
459
+ raise HyperAPIError(
460
+ f"Malformed limits response: {e}",
461
+ status_code=200,
462
+ request_id=rid,
463
+ ) from e
464
+
465
+ # ── HTTP error classification ────────────────────────────────────────
466
+
467
+ def _raise_for_known_status(
468
+ self,
469
+ resp: httpx.Response,
470
+ *,
471
+ request_id: str | None,
472
+ error_cls: type,
473
+ op_name: str,
474
+ ) -> None:
475
+ """Raise the appropriate typed exception for well-known HTTP statuses.
476
+
477
+ Returns silently for 200/202 (success) and any other status that the
478
+ caller wants to handle explicitly. Mirrors the sync client's mapping
479
+ byte-for-byte.
480
+ """
481
+ sc = resp.status_code
482
+ rid = _request_id_of(resp, request_id)
483
+
484
+ if sc == 401:
485
+ # Same env-aware behavior as the sync client: reference self.base_url
486
+ # so customers on staging / on-prem aren't pointed at the prod dashboard.
487
+ raise AuthenticationError(
488
+ f"Invalid API key for {self.base_url}. "
489
+ "Check your HyperAPI dashboard for the correct key.",
490
+ status_code=401,
491
+ request_id=rid,
492
+ )
493
+ if sc == 402:
494
+ raise error_cls(
495
+ f"Insufficient credits for {self.base_url}. "
496
+ "Add credits via your HyperAPI dashboard.",
497
+ status_code=402,
498
+ request_id=rid,
499
+ **_error_fields(resp),
500
+ )
501
+ if sc == 429:
502
+ raise _rate_limit_error_from(resp, rid)
503
+ if sc == 413:
504
+ # Two different refusals share this status. On the upload endpoint
505
+ # it is the file-size ceiling (error_cls is DocumentUploadError
506
+ # there). On an operation endpoint it is that operation's page
507
+ # cap, so it is raised as the operation's own error class.
508
+ fallback = (
509
+ "File exceeds upload size limit"
510
+ if error_cls is DocumentUploadError
511
+ else f"Document exceeds the page or size limit for {op_name}"
512
+ )
513
+ raise error_cls(
514
+ _server_message(resp, fallback),
515
+ status_code=413,
516
+ request_id=rid,
517
+ **_error_fields(resp),
518
+ )
519
+ if sc == 415:
520
+ raise DocumentUploadError(
521
+ _server_message(resp, "Unsupported file type"),
522
+ status_code=415,
523
+ request_id=rid,
524
+ **_error_fields(resp),
525
+ )
526
+ if sc == 408:
527
+ raise error_cls(
528
+ _server_message(resp, "Service deadline exceeded"),
529
+ status_code=408,
530
+ request_id=rid,
531
+ **_error_fields(resp),
532
+ )
533
+ if sc == 403:
534
+ raise HyperAPIError(
535
+ _server_message(resp, "Forbidden"),
536
+ status_code=403,
537
+ request_id=rid,
538
+ **_error_fields(resp),
539
+ )
540
+
541
+ # ── Async submission (X-Async: true) ─────────────────────────────────
542
+
543
+ async def _submit_via_path(
544
+ self,
545
+ endpoint: str,
546
+ op_name: str,
547
+ file_path: Path,
548
+ *,
549
+ params: dict[str, Any],
550
+ use_presigned: bool,
551
+ force_refresh: bool = False,
552
+ data: dict[str, Any] | None = None,
553
+ timeout: float | None = None,
554
+ ) -> Job:
555
+ """Submit a pipeline op asynchronously. Returns a Job handle.
556
+
557
+ ``force_refresh=True`` adds ``?force_refresh=true``, which makes the
558
+ API reprocess the document instead of returning the stored result
559
+ (results are kept for 24 hours). Without it an identical (document +
560
+ task + params) returns the STORED result, so a retry can look like a
561
+ no-op. Only send it when the caller explicitly asked to re-run: a
562
+ reprocess is billed at full price, where a stored result costs nothing.
563
+
564
+ Omitted entirely when False so an ordinary request is byte-identical to
565
+ before this parameter existed.
566
+
567
+ ``data`` carries extra form fields beyond ``document_key`` (e.g. redact's
568
+ ``pii_config``), sent in the form body alongside ``document_key``.
569
+
570
+ The op always uploads via the presigned-S3 flow: the API has no
571
+ direct-upload path and only accepts a ``document_key``. ``use_presigned``
572
+ is retained for backward compatibility; ``use_presigned=False`` emits a
573
+ ``DeprecationWarning`` and falls back to the presigned flow.
574
+ """
575
+ request_timeout = timeout or self.timeout
576
+ error_cls = _OP_TO_ERROR[op_name]
577
+ content_type = CONTENT_TYPES.get(
578
+ file_path.suffix.lower(), "application/octet-stream"
579
+ )
580
+ headers = self._get_headers(async_mode=True)
581
+ request_id = headers["X-Request-ID"]
582
+ extra_form = data or {}
583
+
584
+ if not use_presigned:
585
+ warnings.warn(
586
+ "use_presigned=False is no longer supported: the API has no "
587
+ "direct-upload path and only accepts a presigned document_key. "
588
+ "Falling back to the presigned upload flow.",
589
+ DeprecationWarning,
590
+ stacklevel=2,
591
+ )
592
+
593
+ try:
594
+ document_key = await self.upload_document(
595
+ file_path, content_type=content_type
596
+ )
597
+ response = await self._client.post(
598
+ f"{self.base_url}{endpoint}",
599
+ data={"document_key": document_key, **extra_form},
600
+ params={**params, "force_refresh": "true"} if force_refresh else params,
601
+ headers=headers,
602
+ timeout=request_timeout,
603
+ )
604
+ except httpx.TimeoutException:
605
+ raise error_cls(
606
+ "Request timed out",
607
+ status_code=504,
608
+ request_id=request_id,
609
+ ) from None
610
+ except httpx.RequestError as e:
611
+ raise error_cls(f"Request failed: {e}", request_id=request_id) from None
612
+
613
+ self._raise_for_known_status(
614
+ response, request_id=request_id, error_cls=error_cls, op_name=op_name
615
+ )
616
+ if response.status_code not in (200, 202):
617
+ raise error_cls(
618
+ _server_message(response, f"{op_name} submission failed"),
619
+ status_code=response.status_code,
620
+ request_id=_request_id_of(response, request_id),
621
+ **_error_fields(response),
622
+ )
623
+
624
+ return self._job_from_envelope(
625
+ self._submit_reply(response, request_id, error_cls, op_name), op=op_name
626
+ )
627
+
628
+ async def _submit_via_doc_key(
629
+ self,
630
+ endpoint: str,
631
+ op_name: str,
632
+ document_key: str,
633
+ *,
634
+ params: dict[str, Any],
635
+ timeout: float | None = None,
636
+ ) -> Job:
637
+ """Submit a pipeline op asynchronously when the document_key is already
638
+ in hand (used by ``process()`` to share one upload between parse + extract)."""
639
+ request_timeout = timeout or self.timeout
640
+ error_cls = _OP_TO_ERROR[op_name]
641
+ headers = self._get_headers(async_mode=True)
642
+ request_id = headers["X-Request-ID"]
643
+
644
+ try:
645
+ response = await self._client.post(
646
+ f"{self.base_url}{endpoint}",
647
+ data={"document_key": document_key},
648
+ params=params,
649
+ headers=headers,
650
+ timeout=request_timeout,
651
+ )
652
+ except httpx.TimeoutException:
653
+ raise error_cls(
654
+ "Request timed out", status_code=504, request_id=request_id
655
+ ) from None
656
+ except httpx.RequestError as e:
657
+ raise error_cls(f"Request failed: {e}", request_id=request_id) from None
658
+
659
+ self._raise_for_known_status(
660
+ response, request_id=request_id, error_cls=error_cls, op_name=op_name
661
+ )
662
+ if response.status_code not in (200, 202):
663
+ raise error_cls(
664
+ _server_message(response, f"{op_name} submission failed"),
665
+ status_code=response.status_code,
666
+ request_id=_request_id_of(response, request_id),
667
+ **_error_fields(response),
668
+ )
669
+
670
+ return self._job_from_envelope(
671
+ self._submit_reply(response, request_id, error_cls, op_name), op=op_name
672
+ )
673
+
674
+ @staticmethod
675
+ def _submit_reply(
676
+ response: httpx.Response, request_id: str, error_cls: type, op_name: str
677
+ ) -> dict:
678
+ """The submit reply as a dict that carries a ``job_id``, or ``error_cls``."""
679
+ return _json_object(
680
+ response,
681
+ request_id=_request_id_of(response, request_id),
682
+ error_cls=error_cls,
683
+ required=("job_id",),
684
+ what=f"{op_name} submission",
685
+ )
686
+
687
+ @staticmethod
688
+ def _job_from_envelope(envelope: dict, *, op: str) -> Job:
689
+ return Job(
690
+ job_id=envelope["job_id"],
691
+ status=envelope.get("status", "pending"),
692
+ poll_url=envelope.get(
693
+ "poll_url", f"/v1/jobs/{_path_id(envelope['job_id'], name='job_id')}"
694
+ ),
695
+ op=op,
696
+ )
697
+
698
+ # ── Polling ──────────────────────────────────────────────────────────
699
+
700
+ async def get_job(self, job_id: str) -> dict:
701
+ """Single-shot async poll. No retry, no waiting. Raises on 4xx; returns
702
+ the raw envelope on 200 (``{status, result?, error?, ...}``)."""
703
+ headers = self._get_headers()
704
+ request_id = headers["X-Request-ID"]
705
+
706
+ try:
707
+ resp = await self._client.get(
708
+ f"{self.base_url}/v1/jobs/{_path_id(job_id, name='job_id')}",
709
+ headers=headers,
710
+ )
711
+ except httpx.RequestError as e:
712
+ raise HyperAPIError(f"Job poll failed: {e}", request_id=request_id) from None
713
+
714
+ rid = _request_id_of(resp, request_id)
715
+ if resp.status_code == 401:
716
+ raise AuthenticationError(
717
+ "Invalid API key.", status_code=401, request_id=rid
718
+ )
719
+ if resp.status_code == 404:
720
+ raise HyperAPIError(
721
+ "Job not found or expired.",
722
+ status_code=404,
723
+ request_id=rid,
724
+ )
725
+ if resp.status_code == 429:
726
+ # Surface poll-time and submit-time 429 responses consistently.
727
+ raise _rate_limit_error_from(resp, rid)
728
+ if resp.status_code >= 400:
729
+ raise HyperAPIError(
730
+ _server_message(resp, f"Poll failed (HTTP {resp.status_code})"),
731
+ status_code=resp.status_code,
732
+ request_id=rid,
733
+ **_error_fields(resp),
734
+ )
735
+ return _json_object(resp, request_id=rid, what="job-status")
736
+
737
+ # ── Jobs management ──────────────────────────────────────────────────
738
+
739
+ async def list_recent_jobs(
740
+ self,
741
+ *,
742
+ limit: int = 20,
743
+ source: str | None = None,
744
+ ) -> list[dict]:
745
+ """List the org's recent jobs (summary rows, newest first).
746
+
747
+ Args:
748
+ limit: Maximum rows to return. Valid range [1, 100]; out-of-range
749
+ values are NOT clamped — the server silently falls back to
750
+ the default 20 (e.g. ``limit=200`` returns 20 rows, not 100).
751
+ source: Optional filter — ``"api"`` or ``"playground"``. Unknown
752
+ values are ignored server-side (no error).
753
+
754
+ Returns:
755
+ A list of summary dicts (``job_id``, ``request_id``, ``status``,
756
+ ``task``, ``endpoint``, ``pages``, ``filename``, ``document_key``,
757
+ ``source``, ``is_test``, ``created_at``, ``completed_at``,
758
+ ``error``).
759
+ ``status`` may be ``"cancelled"`` for jobs stopped via
760
+ :py:meth:`delete_job`. Summaries never include results — fetch
761
+ the full envelope for one job with :py:meth:`get_job`.
762
+
763
+ ``document_key`` is the server-side handle for that job's
764
+ document, and is what to match on when reconciling a batch —
765
+ ``filename`` is whatever was sent at upload and carries no
766
+ uniqueness guarantee, so fifty documents named ``invoice.pdf``
767
+ yield fifty rows you cannot tell apart. Note that ``submit_*``
768
+ uploads internally and does not surface the ``document_key`` it
769
+ used, and no public method accepts a pre-uploaded one, so retain
770
+ the ``job_id`` if you need your own file→job map. ``None`` on older
771
+ jobs.
772
+ """
773
+ headers = self._get_headers()
774
+ request_id = headers["X-Request-ID"]
775
+ params: dict[str, Any] = {"limit": limit}
776
+ if source is not None:
777
+ params["source"] = source
778
+
779
+ try:
780
+ resp = await self._client.get(
781
+ f"{self.base_url}/v1/jobs/recent", params=params, headers=headers
782
+ )
783
+ except httpx.RequestError as e:
784
+ raise HyperAPIError(
785
+ f"Recent-jobs request failed: {e}", request_id=request_id
786
+ ) from None
787
+
788
+ rid = _request_id_of(resp, request_id)
789
+ if resp.status_code == 401:
790
+ raise AuthenticationError(
791
+ "Invalid API key.", status_code=401, request_id=rid
792
+ )
793
+ if resp.status_code == 429:
794
+ raise _rate_limit_error_from(resp, rid)
795
+ if resp.status_code >= 400:
796
+ raise HyperAPIError(
797
+ _server_message(
798
+ resp, f"Recent-jobs request failed (HTTP {resp.status_code})"
799
+ ),
800
+ status_code=resp.status_code,
801
+ request_id=rid,
802
+ )
803
+ try:
804
+ jobs = resp.json()["jobs"]
805
+ if not isinstance(jobs, list):
806
+ raise TypeError(f"'jobs' is {type(jobs).__name__}, expected list")
807
+ return jobs
808
+ except (json.JSONDecodeError, ValueError, KeyError, TypeError) as e:
809
+ raise HyperAPIError(
810
+ f"Malformed recent-jobs response: {e}",
811
+ status_code=200,
812
+ request_id=rid,
813
+ ) from e
814
+
815
+ async def delete_job(self, job_id: str) -> None:
816
+ """Cancel a job (``DELETE /v1/jobs/{job_id}``).
817
+
818
+ Despite the HTTP verb, the server semantics are *cancel*, not erase:
819
+ a pending or running job is stopped; a job that already completed or
820
+ failed is left untouched and keeps its result. Idempotent — missing,
821
+ expired, and already-terminal job ids all return success, so calling
822
+ this twice is safe.
823
+
824
+ How a cancelled job reports afterwards: ``GET /v1/jobs/{job_id}``
825
+ (:py:meth:`get_job`) returns ``status="failed"`` with an ``error``
826
+ beginning ``"cancelled:"`` — there is no separate ``"cancelled"``
827
+ status on the job itself. :py:meth:`wait_for_job` and
828
+ :py:meth:`wait_for_jobs` decode that and raise
829
+ :class:`~hyperapi.JobCancelledError` rather than the per-op failure
830
+ class. The summaries from :py:meth:`list_recent_jobs` do show such
831
+ jobs as ``status="cancelled"``.
832
+
833
+ Raises:
834
+ AuthenticationError: 401 (bad key).
835
+ HyperAPIError: 404 (job belongs to a different org), or any other
836
+ ≥400. A missing/expired job is *not* a 404 here — DELETE is
837
+ idempotent and returns 204 (success) for ids that no longer
838
+ exist; the only 404 is a cross-org id.
839
+ """
840
+ headers = self._get_headers()
841
+ request_id = headers["X-Request-ID"]
842
+
843
+ try:
844
+ resp = await self._client.delete(
845
+ f"{self.base_url}/v1/jobs/{_path_id(job_id, name='job_id')}",
846
+ headers=headers,
847
+ )
848
+ except httpx.RequestError as e:
849
+ raise HyperAPIError(f"Job cancel failed: {e}", request_id=request_id) from None
850
+
851
+ rid = _request_id_of(resp, request_id)
852
+ if resp.status_code in (200, 204):
853
+ return
854
+ if resp.status_code == 401:
855
+ raise AuthenticationError(
856
+ "Invalid API key.", status_code=401, request_id=rid
857
+ )
858
+ if resp.status_code == 404:
859
+ # On DELETE, a 404 means the job belongs to a different org
860
+ # (opaque enumeration guard). Missing/expired ids short-circuit to
861
+ # 204 above, so they never reach here.
862
+ raise HyperAPIError(
863
+ "Job not found.",
864
+ status_code=404,
865
+ request_id=rid,
866
+ )
867
+ if resp.status_code == 429:
868
+ raise _rate_limit_error_from(resp, rid)
869
+ raise HyperAPIError(
870
+ _server_message(resp, f"Job cancel failed (HTTP {resp.status_code})"),
871
+ status_code=resp.status_code,
872
+ request_id=rid,
873
+ )
874
+
875
+ async def _retry_transient(
876
+ self,
877
+ fetch: Callable[[], Awaitable[dict]],
878
+ *,
879
+ kind: str,
880
+ ident: str,
881
+ deadline: float | None = None,
882
+ start: float | None = None,
883
+ ) -> dict:
884
+ """Run one status poll, retrying transient failures (network errors, 5xx).
885
+
886
+ Same policy as the sync client: every 4xx and 429 fails fast, retries
887
+ stop at ``poll_max_transient_retries`` and never run past ``deadline``
888
+ (then :class:`JobTimeoutError`).
889
+ """
890
+ attempt = 0
891
+ while True:
892
+ try:
893
+ return await fetch()
894
+ except (AuthenticationError, RateLimitError):
895
+ raise
896
+ except HyperAPIError as e:
897
+ await asyncio.sleep(
898
+ _transient_delay(
899
+ e,
900
+ attempt=attempt,
901
+ max_retries=self._poll_max_transient_retries,
902
+ delay=self._poll_transient_retry_delay,
903
+ deadline=deadline,
904
+ kind=kind,
905
+ ident=ident,
906
+ start=start,
907
+ )
908
+ )
909
+ attempt += 1
910
+
911
+ async def _poll_with_retry(
912
+ self, job_id: str, *, deadline: float | None = None, start: float | None = None
913
+ ) -> dict:
914
+ """One job poll with the transient-retry policy of :meth:`_retry_transient`."""
915
+ return await self._retry_transient(
916
+ lambda: self.get_job(job_id),
917
+ kind="Job",
918
+ ident=job_id,
919
+ deadline=deadline,
920
+ start=start,
921
+ )
922
+
923
+ async def wait_for_job(
924
+ self,
925
+ job: Job | str,
926
+ *,
927
+ timeout: float | None = None,
928
+ interval: float | None = None,
929
+ ) -> dict:
930
+ """Poll a job until it completes, fails, or the timeout elapses.
931
+
932
+ Yields to the event loop between polls (``await asyncio.sleep``)
933
+ instead of blocking the thread; otherwise identical to the sync client.
934
+
935
+ Args:
936
+ job: A :py:class:`Job` returned by ``submit_<op>`` (preferred — the
937
+ ``op`` field lets us raise the right typed exception on
938
+ failure), or a raw ``job_id`` string (falls back to generic
939
+ ``HyperAPIError`` on failure).
940
+ timeout: Total wall-clock seconds. Defaults to the constructor's
941
+ ``poll_timeout``.
942
+ interval: Seconds between polls. Defaults to the constructor's
943
+ ``poll_interval``.
944
+
945
+ Returns:
946
+ The final ``result`` envelope from the server when ``status=completed``.
947
+
948
+ Raises:
949
+ JobTimeoutError: If ``timeout`` elapses with the job still pending.
950
+ JobCancelledError: If the job was cancelled via
951
+ :py:meth:`delete_job` while this call was waiting (the job
952
+ reports ``status=failed`` with an ``error`` beginning
953
+ ``"cancelled:"``; this is decoded for you).
954
+ RateLimitError: If a poll is answered with a 429 that this call
955
+ cannot wait out — either ``retry_after`` exceeds the remaining
956
+ budget, or the 429 is an exhausted monthly page quota
957
+ (``e.is_quota_exhausted``), which waiting would not clear.
958
+ Ordinary rate-window 429s are absorbed by backing off.
959
+ HyperAPIError (or subclass): If the job ends with ``status=failed``,
960
+ or the poll itself fails after exhausting transient retries.
961
+ """
962
+ if isinstance(job, Job):
963
+ job_id = job.job_id
964
+ op = job.op
965
+ start = job.submitted_at
966
+ else:
967
+ job_id = job
968
+ op = "unknown"
969
+ start = time.monotonic()
970
+
971
+ loop_start = time.monotonic()
972
+ budget = timeout if timeout is not None else self._poll_timeout
973
+ deadline = loop_start + budget
974
+ wait_s = interval if interval is not None else self._poll_interval
975
+
976
+ while True:
977
+ try:
978
+ envelope = await self._poll_with_retry(
979
+ job_id, deadline=deadline, start=start
980
+ )
981
+ except RateLimitError as e:
982
+ # Status polls have their own per-organization limit, but a
983
+ # very large number of concurrently polled jobs can still be
984
+ # throttled. Back off and resume within the deadline instead
985
+ # of failing the wait.
986
+ wait = _rate_limit_wait(e, deadline - time.monotonic())
987
+ if wait is None:
988
+ raise
989
+ logger.info(
990
+ "poll_rate_limited",
991
+ extra={
992
+ "job_id": job_id,
993
+ "retry_after": wait,
994
+ "degraded": e.degraded,
995
+ },
996
+ )
997
+ await asyncio.sleep(wait)
998
+ continue
999
+ status = envelope.get("status")
1000
+ if status == "completed":
1001
+ logger.info(
1002
+ "job_completed",
1003
+ extra={
1004
+ "job_id": job_id,
1005
+ "op": op,
1006
+ "duration_ms": envelope.get("duration_ms"),
1007
+ },
1008
+ )
1009
+ # Return only the `result` payload — never the raw envelope,
1010
+ # which carries server-side status/timing/receipt fields. Coerce
1011
+ # a missing/null result to {} so the return is always a dict:
1012
+ # `.get("result")` never hits None (a bare `["result"]` still
1013
+ # KeyErrors, but never the old None TypeError). Matches wait_for_jobs.
1014
+ res = envelope.get("result")
1015
+ return res if isinstance(res, dict) else {}
1016
+ if status == "failed":
1017
+ raise self._exception_for_failed_job(op, envelope, job_id)
1018
+
1019
+ if time.monotonic() >= deadline:
1020
+ raise JobTimeoutError(
1021
+ (
1022
+ f"Job {job_id} did not complete within {budget}s. "
1023
+ "Pass a larger poll_timeout or use submit_<op>+wait_for_job "
1024
+ "to manage polling yourself."
1025
+ ),
1026
+ job_id=job_id,
1027
+ elapsed_s=time.monotonic() - start,
1028
+ )
1029
+
1030
+ remaining = deadline - time.monotonic()
1031
+ await asyncio.sleep(min(wait_s, max(0.0, remaining)))
1032
+
1033
+ async def wait_for_jobs(
1034
+ self,
1035
+ jobs: Iterable[Job],
1036
+ *,
1037
+ timeout: float | None = None,
1038
+ interval: float | None = None,
1039
+ ) -> list[dict]:
1040
+ """Poll multiple jobs concurrently and return results in input order.
1041
+
1042
+ Uses ``asyncio.gather`` for true concurrent polling — each job runs on
1043
+ its own task in the event loop. This is the natural async fan-out and
1044
+ is strictly more concurrent than the sync client's round-robin loop.
1045
+
1046
+ Behavior matches the sync client otherwise: shared timeout budget per
1047
+ job, first failure raises (others are cancelled), returns ``[]`` for
1048
+ empty input.
1049
+
1050
+ Raises:
1051
+ JobTimeoutError: If any job exceeds ``timeout``.
1052
+ HyperAPIError (or subclass): If any job ends with status=failed.
1053
+ """
1054
+ jobs_list = list(jobs)
1055
+ if not jobs_list:
1056
+ return []
1057
+
1058
+ # Each task waits up to `budget`. `gather` propagates the first failure
1059
+ # but does NOT cancel its siblings — so on failure we cancel them
1060
+ # explicitly. This matters more now that a rate-limited poll backs off
1061
+ # (sleeps Retry-After) instead of fast-failing: without the cancel, one
1062
+ # failed/timed-out job would leave the others polling for up to the full
1063
+ # poll_timeout. Cancelling gives the sync round-robin's "first failure
1064
+ # wins; pending jobs abandoned" semantics.
1065
+ budget = timeout if timeout is not None else self._poll_timeout
1066
+
1067
+ tasks = [
1068
+ asyncio.ensure_future(
1069
+ self.wait_for_job(j, timeout=budget, interval=interval)
1070
+ )
1071
+ for j in jobs_list
1072
+ ]
1073
+ try:
1074
+ results = await asyncio.gather(*tasks)
1075
+ except BaseException:
1076
+ for t in tasks:
1077
+ t.cancel()
1078
+ # Drain the cancellations so they don't surface as "Task exception
1079
+ # was never retrieved" on the event loop.
1080
+ await asyncio.gather(*tasks, return_exceptions=True)
1081
+ raise
1082
+
1083
+ # `wait_for_job` returns the envelope's `result` payload ({} if missing
1084
+ # or null). Coerce non-dicts to {} so positional ordering is preserved
1085
+ # exactly like the sync version.
1086
+ normalized: list[dict] = []
1087
+ for res in results:
1088
+ normalized.append(res if isinstance(res, dict) else {})
1089
+ return normalized
1090
+
1091
+ def _exception_for_failed_job(
1092
+ self, op: str, envelope: dict, job_id: str
1093
+ ) -> HyperAPIError:
1094
+ """Build the right typed exception for a ``status: failed`` envelope.
1095
+
1096
+ Same registry as the sync client — per-op subclass when known
1097
+ (ParseError, ExtractError, …), HyperAPIError otherwise.
1098
+ """
1099
+ cancelled = _cancelled_job_error(envelope, job_id)
1100
+ if cancelled is not None:
1101
+ return cancelled
1102
+ raw = _strip_api_key(envelope.get("error")) or "Job failed"
1103
+ status_code = envelope.get("status_code")
1104
+ message = f"(HTTP {status_code}) {raw}" if status_code else raw
1105
+ cls = _OP_TO_ERROR.get(op, HyperAPIError)
1106
+ return cls(
1107
+ message,
1108
+ status_code=status_code,
1109
+ request_id=envelope.get("request_id"),
1110
+ code=envelope.get("error_code")
1111
+ if isinstance(envelope.get("error_code"), str)
1112
+ else None,
1113
+ )
1114
+
1115
+ # ── Public submit_<op> methods ───────────────────────────────────────
1116
+
1117
+ async def submit_parse(
1118
+ self,
1119
+ file_path: str | Path | None = None,
1120
+ *,
1121
+ image_path: str | Path | None = None,
1122
+ mode: ParseMode | None = None,
1123
+ include_boxes: bool | None = None,
1124
+ include_image: bool | None = None,
1125
+ include_layout: bool | None = None,
1126
+ parse_figures: str | None = None,
1127
+ groups_profile: str | None = None,
1128
+ force_refresh: bool = False,
1129
+ use_presigned: bool = True,
1130
+ ) -> Job:
1131
+ """Submit a parse job asynchronously and return immediately.
1132
+
1133
+ ``image_path`` is a deprecated alias for ``file_path`` retained for
1134
+ v0.1.x backward compatibility — pass exactly one.
1135
+
1136
+ Omit ``mode`` to use the organization default (platform default:
1137
+ ``"fast"``). ``mode="advanced"`` explicitly runs layout-aware structured OCR: each
1138
+ ``result["result"]["pages"]`` entry gains a ``structured`` dict with ``html``,
1139
+ ``markdown``, and ``regions``. Only meaningful on the default OCR
1140
+ engine; noticeably slower than ``"fast"`` but, for documents under the
1141
+ page cap, well within the default ``poll_timeout``.
1142
+
1143
+ Output flags
1144
+ ------------
1145
+ ``include_boxes``, ``include_image`` and ``include_layout`` are
1146
+ tri-state. **Leave one at ``None`` (the default) and the SDK does not
1147
+ send it, so the API's own default applies — which, in ``"fast"`` mode,
1148
+ is ON for all three.** Pass ``False`` to opt out of that piece of
1149
+ output explicitly; pass ``True`` to ask for it regardless of the
1150
+ server default. Only a flag you set reaches the wire.
1151
+
1152
+ ``include_boxes`` controls, on each entry of ``result["result"]["pages"]``,
1153
+ a ``boxes`` list of line boxes (``{"text", "bbox": [left, top, right,
1154
+ bottom], "confidence"}``) and, for PDF, XPS and image inputs, a
1155
+ ``word_boxes`` list with one entry per word carrying typography:
1156
+ ``font``, ``size`` (in ``page_size["unit"]``), ``color``, ``bold``,
1157
+ ``italic``, ``background`` (only where it differs from the page) and
1158
+ ``font_source`` (``"document"`` when declared by the file's text layer,
1159
+ ``"model"`` when estimated from the pixels, which can be wrong). Keys are
1160
+ omitted when not stated; ``word_boxes`` is ``[]`` when none were
1161
+ produced. Box coordinates are pixels in the page's ``dimensions``
1162
+ space. Office documents (docx, pptx) return ``boxes`` only with page
1163
+ images on; ``mode="advanced"`` returns no boxes.
1164
+
1165
+ PDF, XPS and image pages from ``mode="fast"`` always carry
1166
+ ``dimensions`` (``{"width", "height"}`` in pixels), ``page_size``
1167
+ (``{"width", "height", "unit"}``, ``"pt"`` for PDF/XPS, ``"px"`` for
1168
+ images) and ``background`` (the page's background colour, hex).
1169
+
1170
+ ``include_image`` controls a presigned ``image_url`` on each
1171
+ ``result["result"]["pages"]`` entry, pointing to the deskew-corrected
1172
+ page image (plus ``dimensions`` where the page does not already carry
1173
+ it). The URL is valid for about 15 minutes; a page whose image cannot
1174
+ be presigned is returned without ``image_url`` rather than failing.
1175
+
1176
+ ``include_layout`` (``"fast"`` mode only) controls, per page, ``layout``
1177
+ (the detected regions in reading order, ``bbox`` in the same pixel
1178
+ space as ``boxes``) and ``layout_text``, plus ``result["result"]
1179
+ ["layout_text"]``, the text rebuilt around the regions. ``False`` also
1180
+ turns figure parsing off. ``mode="advanced"`` has its own
1181
+ ``structured`` layout; sending ``include_layout=True`` with it is a
1182
+ ``400``.
1183
+
1184
+ ``parse_figures`` (``"fast"`` mode, needs the layout on) is a
1185
+ comma-separated list of region kinds to parse further — any of
1186
+ ``"image"``, ``"chart"``, ``"table"`` (e.g. ``"table"`` or
1187
+ ``"image,chart,table"``). Each matching region gains ``content`` (a
1188
+ chart's data as a markdown table, an image's caption or text, a table
1189
+ as HTML) and a ``parse_status``; ``result["result"]["figure_parse"]``
1190
+ summarises the run. Best-effort: OCR and layout are returned even when
1191
+ a region cannot be parsed. Omitted, the API parses all three kinds
1192
+ when the layout is on. Pass ``"none"`` to opt out. An explicit list
1193
+ with ``include_layout=False`` is a ``400``.
1194
+
1195
+ ``groups_profile`` (``"fast"`` mode, layout on) selects how the
1196
+ document outline in ``result["result"]["groups"]`` is built: ``"A"``
1197
+ (the API default — every block in exactly one group, the tree in
1198
+ reading order, a ``preamble`` group before the first heading, one
1199
+ ``page_header`` / ``page_footer`` group per page) or ``"B"`` (headings
1200
+ ranked by measured type size, running titles marked ``furniture:
1201
+ true``, captions bound to their figure or table, tables joined across
1202
+ pages, no ``list`` groups; not in reading order — use
1203
+ ``blocks[].order``). Case-insensitive; unknown values are treated as
1204
+ ``"A"``. ``result["result"]["metadata"]["groups_profile"]`` reports the
1205
+ profile applied.
1206
+
1207
+ ``force_refresh=True`` re-runs OCR instead of returning the stored
1208
+ result. Parse results are cached as OCR output, so what this
1209
+ bypasses is the OCR output itself, for 24 hours. Without it a retry
1210
+ after a bad parse returns the same bad parse for the rest of the day.
1211
+ Covers both ``mode="fast"`` and ``mode="advanced"``, which sit in
1212
+ separate cache namespaces. A forced run is billed at full price where
1213
+ a cached one costs nothing, so send it only when the caller explicitly
1214
+ asked to re-run.
1215
+
1216
+ Large documents
1217
+ ---------------
1218
+ ``"fast"`` mode has no page limit. ``"advanced"`` mode accepts up to 60
1219
+ pages per the public reference (500 for eligible plans when submitted
1220
+ asynchronously, as this method always does) and answers ``413`` above
1221
+ that; the byte cap and the exact page figures for *your* key are
1222
+ returned by :py:meth:`get_limits` (``parse_advanced`` and, when
1223
+ offered, ``bulk_parse``). The server does not report which condition
1224
+ kept a document out of the larger allowance.
1225
+
1226
+ Such a document runs as page-range segments but stays ONE job. Its
1227
+ completed result differs in shape, so branch on it:
1228
+
1229
+ - ``pages`` / ``ocr`` are NOT inline. The payload is delivered via a
1230
+ presigned ``result["result_url"]``, re-signed on every poll and valid
1231
+ for minutes — fetch it promptly or re-poll for a fresh one.
1232
+ - ``result["metadata"]["gaps"]`` lists page ranges that failed after
1233
+ retries. The document still completes; only pages that actually
1234
+ processed are billed. Always present, empty when nothing failed.
1235
+ - Segment progress (``segments_total`` / ``segments_done`` /
1236
+ ``segments_failed``) sits on the job envelope from
1237
+ :py:meth:`get_job`, not on the result :py:meth:`wait_for_job` returns.
1238
+
1239
+ These can run past the default 3600 s ``poll_timeout``. Exceeding it
1240
+ raises ``JobTimeoutError`` but does NOT stop the job — re-attach with
1241
+ :py:meth:`get_job` (jobs live 24 h) or pass a larger ``poll_timeout``.
1242
+ """
1243
+ path = self._resolve_path(file_path, image_path)
1244
+ return await self._submit_via_path(
1245
+ "/v1/parse",
1246
+ "parse",
1247
+ path,
1248
+ params=_parse_params(
1249
+ mode=mode,
1250
+ include_boxes=include_boxes,
1251
+ include_image=include_image,
1252
+ include_layout=include_layout,
1253
+ parse_figures=parse_figures,
1254
+ groups_profile=groups_profile,
1255
+ ),
1256
+ force_refresh=force_refresh,
1257
+ use_presigned=use_presigned,
1258
+ )
1259
+
1260
+ async def submit_extract(
1261
+ self,
1262
+ file_path: str | Path,
1263
+ *,
1264
+ category: ExtractCategory | None = None,
1265
+ parse_mode: ParseMode | None = None,
1266
+ schema: dict | str | Path | None = None,
1267
+ force_refresh: bool = False,
1268
+ use_presigned: bool = True,
1269
+ ) -> Job:
1270
+ """Submit a Basic extract job asynchronously and return immediately.
1271
+
1272
+ ``category`` selects the Basic extractor. Omit it to use the organization
1273
+ default (platform default: ``"financial"``). ``"financial"`` (
1274
+ the built-in invoice and receipt fields) or ``"non_financial"``
1275
+ (template-driven — see ``schema`` below). For auto-detecting Advanced
1276
+ extraction, use :py:meth:`submit_extract_advanced`.
1277
+
1278
+ ``parse_mode`` explicitly selects the OCR engine, independent of
1279
+ ``category``: ``"fast"`` (fast text extraction) or
1280
+ ``"advanced"`` (advanced layout-aware parsing for dense tables/forms —
1281
+ higher accuracy, slower, costs more; Plus plan or higher). Omit it
1282
+ to use the organization default (platform default: ``"fast"``).
1283
+
1284
+ ``schema``: a blank template — the exact shape you want back, with
1285
+ ``None``/``False``/``"unselected"`` as placeholders, e.g.
1286
+ ``{"patient_name": None, "insurance": {"Medicare": "unselected",
1287
+ "Self-Pay": "unselected"}}``. Pass it as an already-loaded dict, a
1288
+ ``str`` of JSON text, or a ``pathlib.Path`` to a JSON file. A ``str``
1289
+ is always parsed as JSON and never read as a file name — to load a
1290
+ file, pass ``pathlib.Path("template.json")``. With
1291
+ ``category="non_financial"`` the template is filled directly from the
1292
+ document. With ``category="financial"`` the invoice extractor runs and
1293
+ its output is remapped into your template. A ``schema`` with no
1294
+ ``category`` is sent as ``"non_financial"``. Ephemeral — used for this
1295
+ call only, nothing is stored server-side; pass a different ``schema``
1296
+ next call for a different shape, no merge/versioning to reason about.
1297
+ Omit entirely to use this org's stored default template instead (set
1298
+ up separately, offline).
1299
+ """
1300
+ path = self._resolve_path(file_path)
1301
+ resolved_schema = _load_schema(schema)
1302
+ # `schema` is honoured on both categories: non_financial fills the
1303
+ # template directly, financial runs the invoice extractor and remaps
1304
+ # its output into the template. An explicit category is sent as given.
1305
+ #
1306
+ # A schema with no declared category: send non_financial explicitly
1307
+ # rather than deferring. The two categories treat a template
1308
+ # differently, and the SDK cannot read the organization default, so
1309
+ # deferring would make the same call behave differently per account.
1310
+ # Filling the template directly is the plain reading of "here is the
1311
+ # shape I want"; callers who want the invoice extractor say so.
1312
+ effective_category = (
1313
+ "non_financial" if category is None and resolved_schema is not None else category
1314
+ )
1315
+ data = (
1316
+ {"schema": json.dumps(resolved_schema)}
1317
+ if resolved_schema is not None
1318
+ else None
1319
+ )
1320
+ return await self._submit_via_path(
1321
+ "/v1/extract",
1322
+ "extract",
1323
+ path,
1324
+ params={
1325
+ # Omitted when None so the server-side default applies — same
1326
+ # mechanism `parse_mode` below already uses. Sending a value
1327
+ # unconditionally is what made an organization's configured
1328
+ # default category unreachable from the SDK.
1329
+ **({"category": effective_category} if effective_category is not None else {}),
1330
+ **({"parse_mode": parse_mode} if parse_mode is not None else {}),
1331
+ },
1332
+ data=data,
1333
+ force_refresh=force_refresh,
1334
+ use_presigned=use_presigned,
1335
+ )
1336
+
1337
+ async def submit_extract_advanced(
1338
+ self,
1339
+ file_path: str | Path,
1340
+ *,
1341
+ parse_mode: ParseMode | None = None,
1342
+ force_refresh: bool = False,
1343
+ use_presigned: bool = True,
1344
+ ) -> Job:
1345
+ """Submit an Advanced extract job asynchronously and return immediately.
1346
+
1347
+ Advanced extraction auto-detects the document type (no ``category``
1348
+ needed): invoice-family documents use the built-in invoice and receipt
1349
+ fields, everything else schema-less grounded extraction. Returns the same
1350
+ envelope shape as :py:meth:`submit_extract`.
1351
+
1352
+ ``parse_mode`` selects the OCR engine (``"fast"``/``"advanced"``,
1353
+ same meaning as :py:meth:`submit_extract`).
1354
+
1355
+ ``force_refresh=True`` reprocesses instead of returning the stored
1356
+ result for an identical document and options (same meaning and same
1357
+ billing caveat as on :py:meth:`submit_extract`).
1358
+ """
1359
+ path = self._resolve_path(file_path)
1360
+ # op_name="extract" is deliberate error-taxonomy reuse (same ExtractError,
1361
+ # same response envelope) — NOT a typo. There is no "extract-omni" key in
1362
+ # _OP_TO_ERROR; do not "fix" this to one (it would KeyError).
1363
+ return await self._submit_via_path(
1364
+ "/v1/extract-omni",
1365
+ "extract",
1366
+ path,
1367
+ params={"parse_mode": parse_mode} if parse_mode is not None else {},
1368
+ force_refresh=force_refresh,
1369
+ use_presigned=use_presigned,
1370
+ )
1371
+
1372
+ async def submit_classify(
1373
+ self,
1374
+ file_path: str | Path,
1375
+ *,
1376
+ mode: str = "default",
1377
+ options: dict | None = None,
1378
+ force_refresh: bool = False,
1379
+ use_presigned: bool = True,
1380
+ ) -> Job:
1381
+ """Submit a classify job asynchronously and return immediately.
1382
+
1383
+ ``options`` is an optional dict of classifier knobs, sent as a JSON
1384
+ form field and validated server-side. Accepted keys:
1385
+
1386
+ - ``mode`` (``"fast"`` | ``"balanced"`` | ``"thorough"``) — the
1387
+ pipeline depth, distinct from this method's ``mode=`` task selector.
1388
+ - ``active_classes`` — explicit list of class labels to consider.
1389
+ - ``active_classes_type`` (``"default"`` | ``"minimal"``, default
1390
+ ``"default"``) — picks the built-in label set (default = full set,
1391
+ minimal = reduced set).
1392
+ - ``custom_llm_classes`` — additional caller-defined class labels.
1393
+ - ``system_instruction`` — extra prompt guidance.
1394
+ - ``domain_options`` (str, optional) — pipe-separated list of allowed
1395
+ first-stage domain labels.
1396
+ - ``non_domain_label`` (str, optional, effective default
1397
+ ``"non_financial"``) — label used when the document falls outside
1398
+ the configured domain.
1399
+ - ``non_domain_exit_label`` (str, optional, effective default
1400
+ ``"other_non_financial"``) — terminal label for out-of-domain exits.
1401
+ - ``confusion_neighbors`` (dict of ``{label: [neighbor_label, ...]}``,
1402
+ optional) — disambiguation hints between easily-confused classes.
1403
+ - Token/page budgets: ``start_token_budget`` (default 3200, range
1404
+ 256–8192), ``end_token_budget`` (default 1600, range 256–8192),
1405
+ ``max_start_pages`` (default 4, range 1–20), ``max_end_pages``
1406
+ (default 2, range 0–10).
1407
+ """
1408
+ path = self._resolve_path(file_path)
1409
+ data = {"options": json.dumps(options)} if options is not None else None
1410
+ return await self._submit_via_path(
1411
+ "/v1/classify",
1412
+ "classify",
1413
+ path,
1414
+ params={"mode": mode},
1415
+ data=data,
1416
+ force_refresh=force_refresh,
1417
+ use_presigned=use_presigned,
1418
+ )
1419
+
1420
+ async def submit_split(
1421
+ self,
1422
+ file_path: str | Path,
1423
+ *,
1424
+ mode: str = "default",
1425
+ options: dict | None = None,
1426
+ force_refresh: bool = False,
1427
+ use_presigned: bool = True,
1428
+ ) -> Job:
1429
+ """Submit a split job asynchronously and return immediately.
1430
+
1431
+ ``options`` is an optional dict of splitter knobs, sent as a JSON
1432
+ form field and validated server-side: ``use_thinking``,
1433
+ ``segment_classes``, ``extend_segment_classes``, and
1434
+ ``custom_domain_guidelines`` — a nested object whose ``domain_name``
1435
+ sub-field is **required** when ``custom_domain_guidelines`` is given;
1436
+ the remaining sub-fields (``identifier_patterns``, ``binding_patterns``,
1437
+ ``heuristics``, ``examples``) are optional.
1438
+ """
1439
+ path = self._resolve_path(file_path)
1440
+ data = {"options": json.dumps(options)} if options is not None else None
1441
+ return await self._submit_via_path(
1442
+ "/v1/split",
1443
+ "split",
1444
+ path,
1445
+ params={"mode": mode},
1446
+ data=data,
1447
+ force_refresh=force_refresh,
1448
+ use_presigned=use_presigned,
1449
+ )
1450
+
1451
+ async def submit_redact(
1452
+ self,
1453
+ file_path: str | Path,
1454
+ *,
1455
+ mode: str = "redact",
1456
+ pii_config: dict | None = None,
1457
+ include_logos: bool = False,
1458
+ output: str = "inline",
1459
+ force_refresh: bool = False,
1460
+ use_presigned: bool = True,
1461
+ ) -> Job:
1462
+ """Submit a redact/deidentify job asynchronously and return immediately.
1463
+
1464
+
1465
+ A page cap applies to inline output; ``output="urls"`` raises it where
1466
+ your account offers that mode. Read the current values with
1467
+ :py:meth:`get_limits`: ``limits["redact"]["max_pages"]`` for inline
1468
+ and ``limits["redact"]["urls_max_pages"]`` for URL output (absent
1469
+ means URL output is not offered — feature-detect on that key).
1470
+ ``output="urls"`` returns masked pages as short-lived presigned links
1471
+ in ``result["result"]["pages"]`` (``{page_number, image_url}``)
1472
+ instead of inline base64 ``result["result"]["images"]`` —
1473
+ ``download_pages()`` accepts that result directly. An over-cap
1474
+ document is refused with ``413`` up front, before any OCR is billed,
1475
+ and raises ``RedactError`` (``status_code == 413``);
1476
+ ``output="urls"`` cannot be combined with ``include_logos`` (``400``).
1477
+
1478
+ ``mode="redact"`` applies black boxes; ``mode="deidentify"`` overlays
1479
+ synthetic values. ``pii_config`` (``{"mode": "extend"|"replace",
1480
+ "types": [...]}``) customizes the detected PII types. Built-in types
1481
+ include PERSON_NAME, COMPANY_NAME, EMAIL, ADDRESS, WEBSITE, PHONE,
1482
+ and CREDENTIALS (passwords, API keys, tokens, secrets) — all with
1483
+ synthetic replacements, so each works in both modes.
1484
+ """
1485
+ if output not in ("inline", "urls"):
1486
+ # Fail loudly client-side: only the non-default literal goes on the
1487
+ # wire, so a typo ("url", "URLS") would otherwise silently run
1488
+ # inline at the inline page cap with no server-side rejection possible.
1489
+ raise ValueError(f'output must be "inline" or "urls", got {output!r}')
1490
+ path = self._resolve_path(file_path)
1491
+ data = (
1492
+ {"pii_config": json.dumps(pii_config)} if pii_config is not None else None
1493
+ )
1494
+ return await self._submit_via_path(
1495
+ "/v1/redact",
1496
+ "redact",
1497
+ path,
1498
+ params={"mode": mode, "include_logos": include_logos, **({"output": "urls"} if output == "urls" else {})},
1499
+ data=data,
1500
+ force_refresh=force_refresh,
1501
+ use_presigned=use_presigned,
1502
+ )
1503
+
1504
+ # ── Batch API (async, deferred) ──────────────────────────────────────
1505
+
1506
+ _BATCH_TERMINAL = frozenset(
1507
+ {"completed", "completed_with_errors", "failed", "canceled"}
1508
+ )
1509
+
1510
+ async def _batch_request(
1511
+ self,
1512
+ method: str,
1513
+ path: str,
1514
+ *,
1515
+ json_body: dict | None = None,
1516
+ params: dict | None = None,
1517
+ extra_headers: dict[str, str] | None = None,
1518
+ required: tuple[str, ...] = (),
1519
+ ) -> dict:
1520
+ """Shared request+error handling for the /v1/batch endpoints.
1521
+
1522
+ Every batch reply must be a JSON object carrying the ``required`` keys.
1523
+ """
1524
+ headers = self._get_headers()
1525
+ request_id = headers["X-Request-ID"]
1526
+ if extra_headers:
1527
+ headers.update(extra_headers)
1528
+ try:
1529
+ resp = await self._client.request(
1530
+ method,
1531
+ f"{self.base_url}{path}",
1532
+ headers=headers,
1533
+ json=json_body,
1534
+ params=params,
1535
+ )
1536
+ except httpx.RequestError as e:
1537
+ raise HyperAPIError(
1538
+ f"Batch request failed: {e}", request_id=request_id
1539
+ ) from None
1540
+
1541
+ rid = _request_id_of(resp, request_id)
1542
+ if resp.status_code == 401:
1543
+ raise AuthenticationError(
1544
+ "Invalid API key.", status_code=401, request_id=rid
1545
+ )
1546
+ if resp.status_code == 404 and path != "/v1/batch":
1547
+ # Only an id-addressed call (GET/DELETE /v1/batch/{id}) can mean
1548
+ # "no such batch". A 404 on the collection itself falls through
1549
+ # and reports what the server said.
1550
+ raise HyperAPIError(
1551
+ "Batch not found.",
1552
+ status_code=404,
1553
+ request_id=rid,
1554
+ **_error_fields(resp),
1555
+ )
1556
+ if resp.status_code == 429:
1557
+ raise _rate_limit_error_from(resp, rid)
1558
+ if resp.status_code >= 400:
1559
+ raise HyperAPIError(
1560
+ _server_message(
1561
+ resp, f"Batch request failed (HTTP {resp.status_code})"
1562
+ ),
1563
+ status_code=resp.status_code,
1564
+ request_id=rid,
1565
+ **_error_fields(resp),
1566
+ )
1567
+ return _json_object(resp, request_id=rid, required=required, what="batch")
1568
+
1569
+ async def create_batch(
1570
+ self,
1571
+ *,
1572
+ endpoint: str,
1573
+ document_keys: list[str],
1574
+ options: dict | None = None,
1575
+ parse_mode: str | None = None,
1576
+ webhook_url: str | None = None,
1577
+ metadata: dict | None = None,
1578
+ estimated_pages_per_doc: int = 1,
1579
+ idempotency_key: str | None = None,
1580
+ ) -> dict:
1581
+ """Submit a batch of already-uploaded documents for async processing.
1582
+
1583
+ Returns immediately with ``{batch_id, status, total_items}``; the work
1584
+ runs on spare capacity. Poll :meth:`get_batch` (or :meth:`wait_for_batch`)
1585
+ for per-document results (each result lands in S3, keyed by ``doc_index``).
1586
+
1587
+ Args:
1588
+ endpoint: One of ``/v1/parse``, ``/v1/extract``,
1589
+ ``/v1/extract-omni`` (advanced extract), ``/v1/classify``,
1590
+ ``/v1/split``, ``/v1/redact``. The API rejects any other
1591
+ value with a ``400``.
1592
+ document_keys: Keys from :meth:`upload_document`, one per document.
1593
+ options: Task-specific options, forwarded to each document's run.
1594
+ parse_mode: ``fast`` (default) or ``advanced``, for ``/v1/parse`` only.
1595
+ ``advanced`` runs layout-aware parsing. Advanced parse may not
1596
+ be available for batch on your plan: the API then rejects the
1597
+ batch with a ``400`` or ``403`` whose message says why. Batch
1598
+ advanced parse runs on the lowest-priority lane, yielding to
1599
+ interactive traffic, so it may take longer under load (24h SLA).
1600
+ Ignored by non-``/v1/parse`` endpoints.
1601
+ webhook_url: Optional completion webhook (delivered when available).
1602
+ metadata: Optional caller-supplied key/value tags stored with the
1603
+ batch and echoed back on :meth:`get_batch` / :meth:`list_batches`
1604
+ and in the completion webhook payload.
1605
+ estimated_pages_per_doc: Hint for the up-front quota check.
1606
+ idempotency_key: Resubmitting with the same key returns the existing
1607
+ batch instead of creating a duplicate.
1608
+ """
1609
+ body: dict = {
1610
+ "endpoint": endpoint,
1611
+ "document_keys": document_keys,
1612
+ "options": options or {},
1613
+ "estimated_pages_per_doc": estimated_pages_per_doc,
1614
+ }
1615
+ if parse_mode is not None:
1616
+ body["parse_mode"] = parse_mode
1617
+ if webhook_url is not None:
1618
+ body["webhook_url"] = webhook_url
1619
+ if metadata is not None:
1620
+ body["metadata"] = metadata
1621
+ extra = {"Idempotency-Key": idempotency_key} if idempotency_key else None
1622
+ return await self._batch_request(
1623
+ "POST",
1624
+ "/v1/batch",
1625
+ json_body=body,
1626
+ extra_headers=extra,
1627
+ required=("batch_id",),
1628
+ )
1629
+
1630
+ async def create_batch_from_files(
1631
+ self,
1632
+ *,
1633
+ endpoint: str,
1634
+ file_paths: list[str | Path],
1635
+ **kwargs,
1636
+ ) -> dict:
1637
+ """Upload the files concurrently (presigned flow) then :meth:`create_batch`.
1638
+
1639
+ At most 8 uploads run at once; if one fails the others are cancelled.
1640
+ """
1641
+ document_keys = await _bounded_map(
1642
+ self.upload_document, file_paths, _TRANSFER_CONCURRENCY
1643
+ )
1644
+ return await self.create_batch(
1645
+ endpoint=endpoint, document_keys=document_keys, **kwargs
1646
+ )
1647
+
1648
+ async def get_batch(
1649
+ self, batch_id: str, *, limit: int = 200, offset: int = 0
1650
+ ) -> dict:
1651
+ """Batch status: ``{status, counts, items:[{doc_index, status, ...}]}``."""
1652
+ return await self._batch_request(
1653
+ "GET",
1654
+ f"/v1/batch/{_path_id(batch_id, name='batch_id')}",
1655
+ params={"limit": limit, "offset": offset},
1656
+ )
1657
+
1658
+ async def list_batches(self, *, limit: int = 50, offset: int = 0) -> dict:
1659
+ """List the org's batches, newest first."""
1660
+ return await self._batch_request(
1661
+ "GET", "/v1/batch", params={"limit": limit, "offset": offset}
1662
+ )
1663
+
1664
+ async def cancel_batch(self, batch_id: str) -> dict:
1665
+ """Cancel a batch — stops queued items; in-flight items finish."""
1666
+ return await self._batch_request(
1667
+ "DELETE", f"/v1/batch/{_path_id(batch_id, name='batch_id')}"
1668
+ )
1669
+
1670
+ async def wait_for_batch(
1671
+ self,
1672
+ batch_id: str,
1673
+ *,
1674
+ timeout: float = 3600.0,
1675
+ poll_interval: float = 5.0,
1676
+ ) -> dict:
1677
+ """Poll :meth:`get_batch` until the batch reaches a terminal state.
1678
+
1679
+ Raises :class:`JobTimeoutError` if ``timeout`` elapses (the batch keeps
1680
+ running server-side).
1681
+ """
1682
+ start = time.monotonic()
1683
+ deadline = start + timeout
1684
+ while True:
1685
+ try:
1686
+ status = await self._retry_transient(
1687
+ lambda: self.get_batch(batch_id),
1688
+ kind="Batch",
1689
+ ident=batch_id,
1690
+ deadline=deadline,
1691
+ start=start,
1692
+ )
1693
+ except RateLimitError as e:
1694
+ wait = _rate_limit_wait(e, deadline - time.monotonic())
1695
+ if wait is None:
1696
+ raise
1697
+ logger.info(
1698
+ "batch_poll_rate_limited",
1699
+ extra={
1700
+ "batch_id": batch_id,
1701
+ "retry_after": wait,
1702
+ "degraded": e.degraded,
1703
+ },
1704
+ )
1705
+ await asyncio.sleep(wait)
1706
+ continue
1707
+ if status.get("status") in self._BATCH_TERMINAL:
1708
+ return status
1709
+ if time.monotonic() >= deadline:
1710
+ raise JobTimeoutError(
1711
+ f"Batch {batch_id} did not complete within {timeout}s.",
1712
+ job_id=batch_id,
1713
+ elapsed_s=time.monotonic() - start,
1714
+ )
1715
+ await asyncio.sleep(
1716
+ min(poll_interval, max(0.0, deadline - time.monotonic()))
1717
+ )
1718
+
1719
+ # ── Public convenience methods (submit + wait) ───────────────────────
1720
+
1721
+ async def parse(
1722
+ self,
1723
+ file_path: str | Path | None = None,
1724
+ *,
1725
+ image_path: str | Path | None = None,
1726
+ mode: ParseMode | None = None,
1727
+ include_boxes: bool | None = None,
1728
+ include_image: bool | None = None,
1729
+ include_layout: bool | None = None,
1730
+ parse_figures: str | None = None,
1731
+ groups_profile: str | None = None,
1732
+ force_refresh: bool = False,
1733
+ use_presigned: bool = True,
1734
+ poll_timeout: float | None = None,
1735
+ poll_interval: float | None = None,
1736
+ ) -> dict:
1737
+ """Parse a document using OCR. Submits asynchronously and polls until done.
1738
+
1739
+ The returned dict is the response envelope; the parse payload is nested
1740
+ one level under ``result`` — OCR text at ``result["result"]["ocr"]`` and
1741
+ the page list at ``result["result"]["pages"]``.
1742
+
1743
+ Args:
1744
+ file_path: Path to the file (PDF, PNG, JPG, WEBP, TIFF, GIF).
1745
+ image_path: Deprecated alias for file_path.
1746
+ mode: Explicit ``"fast"`` or ``"advanced"``. Omit to use the
1747
+ organization default (platform default: ``"fast"``). Advanced
1748
+ is layout-aware structured OCR: each ``result["result"]["pages"]``
1749
+ entry gains a ``structured`` dict with ``html``, ``markdown``,
1750
+ and ``regions``). Advanced only applies on the default OCR
1751
+ engine and is noticeably slower.
1752
+ include_boxes: Tri-state. ``None`` (default) sends nothing, so the
1753
+ API default applies — ON in ``"fast"`` mode. ``False`` opts
1754
+ out; ``True`` asks explicitly. When on, each
1755
+ ``result["result"]["pages"]`` entry includes a ``boxes`` list
1756
+ of line boxes (``{"text", "bbox": [left, top, right, bottom],
1757
+ "confidence"}``) and, for PDF, XPS and image inputs, a
1758
+ ``word_boxes`` list of per-word boxes with ``font``, ``size``,
1759
+ ``color``, ``bold``, ``italic``, ``background`` and
1760
+ ``font_source`` (``"document"`` or ``"model"``). Coordinates
1761
+ are pixels in the page's ``dimensions`` space.
1762
+ ``mode="advanced"`` returns no boxes. See :py:meth:`submit_parse`.
1763
+ include_image: Tri-state, same convention; the API default is ON.
1764
+ When on, each ``result["result"]["pages"]`` entry includes an
1765
+ ``image_url`` (presigned GET for the deskew-corrected page,
1766
+ valid about 15 minutes). ``dimensions`` (``{"width",
1767
+ "height"}`` in that image's pixel space, which matches the box
1768
+ coordinate space) is present on PDF, XPS and image pages in
1769
+ fast mode regardless, alongside ``page_size`` and
1770
+ ``background``.
1771
+ include_layout: Tri-state, same convention; the API default is ON
1772
+ in ``"fast"`` mode. When on, each page gains ``layout`` and
1773
+ ``layout_text`` and the result gains ``layout_text``. Not for
1774
+ ``mode="advanced"`` (``True`` there is a ``400``). See
1775
+ :py:meth:`submit_parse`.
1776
+ parse_figures: Comma-separated region kinds to parse further —
1777
+ ``"image"``, ``"chart"``, ``"table"`` — or ``"none"``.
1778
+ Omitted, the API parses all three when the layout is on.
1779
+ Needs the layout on. See :py:meth:`submit_parse`.
1780
+ groups_profile: ``"A"`` (API default) or ``"B"`` — how the
1781
+ document outline in ``result["result"]["groups"]`` is built.
1782
+ See :py:meth:`submit_parse`.
1783
+ force_refresh: Re-run OCR instead of returning the cached result
1784
+ (results are cached for 24 hours). See :py:meth:`submit_parse`.
1785
+ use_presigned: Use the presigned-S3 upload flow (default True).
1786
+ poll_timeout: Override the constructor's poll_timeout for this call.
1787
+ poll_interval: Override the constructor's poll_interval for this call.
1788
+
1789
+ Returns:
1790
+ Response envelope; OCR text at ``result["result"]["ocr"]`` and pages
1791
+ at ``result["result"]["pages"]``.
1792
+
1793
+ EXCEPT for a large advanced document (past the ordinary advanced
1794
+ page cap, admitted on plans that allow it — see
1795
+ :py:meth:`submit_parse` and :py:meth:`get_limits`): those carry no
1796
+ inline ``pages``/``ocr``. The payload is behind a presigned
1797
+ ``result["result_url"]`` and failed page ranges are listed in
1798
+ ``result["metadata"]["gaps"]``. Branch on ``result_url`` being
1799
+ present rather than assuming the inline shape, and raise
1800
+ ``poll_timeout`` — such a job can outlast the 3600 s default.
1801
+ """
1802
+ job = await self.submit_parse(
1803
+ file_path=file_path,
1804
+ image_path=image_path,
1805
+ mode=mode,
1806
+ include_boxes=include_boxes,
1807
+ include_image=include_image,
1808
+ include_layout=include_layout,
1809
+ parse_figures=parse_figures,
1810
+ groups_profile=groups_profile,
1811
+ force_refresh=force_refresh,
1812
+ use_presigned=use_presigned,
1813
+ )
1814
+ return await self.wait_for_job(
1815
+ job, timeout=poll_timeout, interval=poll_interval
1816
+ )
1817
+
1818
+ async def extract(
1819
+ self,
1820
+ file_path: str | Path,
1821
+ *,
1822
+ category: ExtractCategory | None = None,
1823
+ parse_mode: ParseMode | None = None,
1824
+ schema: dict | str | Path | None = None,
1825
+ force_refresh: bool = False,
1826
+ use_presigned: bool = True,
1827
+ poll_timeout: float | None = None,
1828
+ poll_interval: float | None = None,
1829
+ ) -> dict:
1830
+ """Extract structured data from a document.
1831
+
1832
+ Submits asynchronously and polls until done. Bypasses any edge-timeout
1833
+ ceiling because each individual HTTP request stays sub-second.
1834
+
1835
+ This is the Basic extractor. ``category="financial"`` uses the
1836
+ built-in invoice and receipt fields. Omit ``category`` to use the
1837
+ organization default (platform default: ``"financial"``; a ``schema``
1838
+ with no ``category`` is sent as ``"non_financial"``). ``category="non_financial"``
1839
+ does no document-type detection; pass ``schema`` to
1840
+ describe the documents — a blank
1841
+ template with ``None``/``False``/``"unselected"`` as placeholders
1842
+ (e.g. ``{"patient_name": None, "insurance": {"Medicare":
1843
+ "unselected", "Self-Pay": "unselected"}}``, as a dict, a ``str`` of
1844
+ JSON text, or a ``pathlib.Path`` to a JSON file — a ``str`` is never
1845
+ read as a file name), and the response fills in that SAME
1846
+ structure from the document — nothing is stored server-side, pass a
1847
+ different ``schema`` next call for a different shape, no
1848
+ merge/versioning to reason about. Omit ``schema`` to use this org's
1849
+ stored default template instead (set up separately, offline — not
1850
+ through this SDK); with no schema and no stored default, this
1851
+ currently falls back to a generic extraction (a known gap, not yet
1852
+ unified with this flow). ``schema`` also works with
1853
+ ``category="financial"``: the invoice extractor runs and its output
1854
+ is remapped into your template. For auto-detecting Advanced
1855
+ extraction (no ``category`` needed), use :py:meth:`extract_advanced`.
1856
+
1857
+ Returns:
1858
+ Response envelope. For ``category="financial"``: the structured
1859
+ payload is one level under ``result``:
1860
+ ``result["result"]["entities"]`` (header/party fields),
1861
+ ``result["result"]["line_items"]`` (per-line rows), and
1862
+ ``result["result"]["summary"]`` (document-level totals/tax/currency —
1863
+ e.g. the grand total lives here, ``summary["total_amount"]``, NOT in
1864
+ entities). For ``category="non_financial"``: the
1865
+ filled-in template is at ``result["result"]["data"]`` (same shape
1866
+ as ``schema``, or the org's stored default). Raw OCR is at the
1867
+ envelope top level, ``result["ocr_text"]``, in both cases.
1868
+ """
1869
+ job = await self.submit_extract(
1870
+ file_path,
1871
+ category=category,
1872
+ parse_mode=parse_mode,
1873
+ schema=schema,
1874
+ force_refresh=force_refresh,
1875
+ use_presigned=use_presigned,
1876
+ )
1877
+ return await self.wait_for_job(
1878
+ job, timeout=poll_timeout, interval=poll_interval
1879
+ )
1880
+
1881
+ async def extract_advanced(
1882
+ self,
1883
+ file_path: str | Path,
1884
+ *,
1885
+ parse_mode: ParseMode | None = None,
1886
+ force_refresh: bool = False,
1887
+ use_presigned: bool = True,
1888
+ poll_timeout: float | None = None,
1889
+ poll_interval: float | None = None,
1890
+ ) -> dict:
1891
+ """Advanced extraction — auto-detects the document type, no ``category``.
1892
+
1893
+ Invoice-family documents use the built-in invoice and receipt fields;
1894
+ everything else schema-less grounded extraction. Submits asynchronously and
1895
+ polls until done. Returns the same envelope shape as :py:meth:`extract`.
1896
+ ``force_refresh=True`` reprocesses instead of returning the stored
1897
+ result (see :py:meth:`submit_extract_advanced`).
1898
+ """
1899
+ job = await self.submit_extract_advanced(
1900
+ file_path,
1901
+ parse_mode=parse_mode,
1902
+ force_refresh=force_refresh,
1903
+ use_presigned=use_presigned,
1904
+ )
1905
+ return await self.wait_for_job(
1906
+ job, timeout=poll_timeout, interval=poll_interval
1907
+ )
1908
+
1909
+ async def classify(
1910
+ self,
1911
+ file_path: str | Path,
1912
+ *,
1913
+ mode: str = "default",
1914
+ options: dict | None = None,
1915
+ force_refresh: bool = False,
1916
+ use_presigned: bool = True,
1917
+ poll_timeout: float | None = None,
1918
+ poll_interval: float | None = None,
1919
+ ) -> dict:
1920
+ """Classify a document type (invoice, contract, receipt, etc.).
1921
+
1922
+ ``options`` customizes the classifier (see :py:meth:`submit_classify`
1923
+ for the full key list): pipeline depth via ``options["mode"]``
1924
+ (``"fast"`` | ``"balanced"`` | ``"thorough"`` — distinct from the
1925
+ ``mode=`` task selector), ``active_classes``, ``active_classes_type``,
1926
+ ``custom_llm_classes``, ``system_instruction``, ``domain_options``,
1927
+ ``non_domain_label``, ``non_domain_exit_label``, ``confusion_neighbors``,
1928
+ and the token/page budgets (``start_token_budget``, ``end_token_budget``,
1929
+ ``max_start_pages``, ``max_end_pages``).
1930
+
1931
+ Returns:
1932
+ Response envelope. The prediction is one level under ``result``:
1933
+ ``result["result"]["document_type"]`` (e.g. ``"invoice"``), with
1934
+ ``confidence`` (a categorical label such as ``"very_high"``, not a
1935
+ float), ``domain``, and ``needs_review`` alongside it. Raw OCR is at
1936
+ the envelope top level in ``result["ocr_text"]``.
1937
+ """
1938
+ job = await self.submit_classify(
1939
+ file_path,
1940
+ mode=mode,
1941
+ options=options,
1942
+ force_refresh=force_refresh,
1943
+ use_presigned=use_presigned,
1944
+ )
1945
+ return await self.wait_for_job(
1946
+ job, timeout=poll_timeout, interval=poll_interval
1947
+ )
1948
+
1949
+ async def split(
1950
+ self,
1951
+ file_path: str | Path,
1952
+ *,
1953
+ mode: str = "default",
1954
+ options: dict | None = None,
1955
+ force_refresh: bool = False,
1956
+ use_presigned: bool = True,
1957
+ poll_timeout: float | None = None,
1958
+ poll_interval: float | None = None,
1959
+ ) -> dict:
1960
+ """Split a multi-document PDF into individual document segments.
1961
+
1962
+ ``options`` customizes the splitter (see :py:meth:`submit_split`):
1963
+ ``use_thinking``, ``segment_classes``, ``extend_segment_classes``,
1964
+ and ``custom_domain_guidelines`` (its ``domain_name`` sub-field is
1965
+ required when the object is supplied).
1966
+
1967
+ Returns:
1968
+ Response envelope. The detected parts are at
1969
+ ``result["result"]["segmentation"]["splits"]`` — a list where each
1970
+ item has ``split_label``, ``start_page``, ``end_page``,
1971
+ ``confidence``, and ``sub_documents``. (Note the ``segmentation``
1972
+ wrapper: this is one level deeper than the other operations' payloads.)
1973
+ """
1974
+ job = await self.submit_split(
1975
+ file_path,
1976
+ mode=mode,
1977
+ options=options,
1978
+ force_refresh=force_refresh,
1979
+ use_presigned=use_presigned,
1980
+ )
1981
+ return await self.wait_for_job(
1982
+ job, timeout=poll_timeout, interval=poll_interval
1983
+ )
1984
+
1985
+ async def redact(
1986
+ self,
1987
+ file_path: str | Path,
1988
+ *,
1989
+ mode: str = "redact",
1990
+ pii_config: dict | None = None,
1991
+ include_logos: bool = False,
1992
+ output: str = "inline",
1993
+ force_refresh: bool = False,
1994
+ use_presigned: bool = True,
1995
+ poll_timeout: float | None = None,
1996
+ poll_interval: float | None = None,
1997
+ ) -> dict:
1998
+ """Redact or deidentify PII in a document. Submits async + polls until done.
1999
+
2000
+
2001
+ A page cap applies to inline output; ``output="urls"`` raises it where
2002
+ your account offers that mode. Read the current values with
2003
+ :py:meth:`get_limits`: ``limits["redact"]["max_pages"]`` for inline
2004
+ and ``limits["redact"]["urls_max_pages"]`` for URL output (absent
2005
+ means URL output is not offered — feature-detect on that key).
2006
+ ``output="urls"`` returns masked pages as short-lived presigned links
2007
+ in ``result["result"]["pages"]`` (``{page_number, image_url}``)
2008
+ instead of inline base64 ``result["result"]["images"]`` —
2009
+ ``download_pages()`` accepts that result directly. An over-cap
2010
+ document is refused with ``413`` up front, before any OCR is billed,
2011
+ and raises ``RedactError`` (``status_code == 413``);
2012
+ ``output="urls"`` cannot be combined with ``include_logos`` (``400``).
2013
+
2014
+ ``mode="redact"`` masks PII with black boxes; ``mode="deidentify"``
2015
+ overlays synthetic replacements. ``include_logos=True`` also masks logos.
2016
+ ``pii_config`` customizes the detected PII type set. Returns the response
2017
+ envelope with ``result`` (``images``, ``updated_text_block``, ``summary``).
2018
+ """
2019
+ job = await self.submit_redact(
2020
+ file_path,
2021
+ mode=mode,
2022
+ pii_config=pii_config,
2023
+ include_logos=include_logos,
2024
+ output=output,
2025
+ force_refresh=force_refresh,
2026
+ use_presigned=use_presigned,
2027
+ )
2028
+ return await self.wait_for_job(
2029
+ job, timeout=poll_timeout, interval=poll_interval
2030
+ )
2031
+
2032
+ async def download_pages(
2033
+ self,
2034
+ result: dict,
2035
+ dest_dir: str | Path,
2036
+ *,
2037
+ prefix: str = "page",
2038
+ max_page_bytes: int = _DEFAULT_MAX_PAGE_BYTES,
2039
+ ) -> list[Path]:
2040
+ """Download a result's page images to a folder.
2041
+
2042
+ Works with the dict returned by :py:meth:`parse` with page images on
2043
+ (the API default; do not pass ``include_image=False``) or by
2044
+ :py:meth:`redact` with ``output="urls"``. Files are written as
2045
+ ``<dest_dir>/<prefix>-<page number><ext>``, where the extension is the
2046
+ one the server served (``.webp`` for parse, ``.png`` for redact); the
2047
+ directory is created if needed.
2048
+ Pages are downloaded concurrently, at most 8 at a time.
2049
+
2050
+ Page images are served as **short-lived presigned URLs** (~15 min), so download
2051
+ promptly. If they have expired, re-poll with :py:meth:`get_job` — the server mints
2052
+ fresh URLs for the full 24 h the job lives — and call this again.
2053
+
2054
+ Args:
2055
+ result: The dict returned by an op that produced page images.
2056
+ dest_dir: Folder to write into. Created if it does not exist.
2057
+ prefix: Filename stem; defaults to ``page`` → ``page-1.png``.
2058
+ max_page_bytes: Largest page image accepted, in bytes (after any
2059
+ content decoding). Default 200 MiB. A larger page stops the
2060
+ download and raises ``HyperAPIError``.
2061
+
2062
+ Each page is streamed to a temporary file in ``dest_dir`` and renamed
2063
+ into place when complete, so a failure never leaves a partial page.
2064
+ Image URLs must be https (plain http only when ``base_url`` is http).
2065
+
2066
+ Returns:
2067
+ The written paths, in page order.
2068
+
2069
+ Raises:
2070
+ ValueError: If the result carries no pages, or a page has no ``image_url``.
2071
+ HyperAPIError: If a download fails — an expired URL reports as such — or a
2072
+ page exceeds ``max_page_bytes``, or an image URL is not https.
2073
+ """
2074
+ _check_page_cap(max_page_bytes)
2075
+ targets = _page_targets(result, dest_dir, prefix)
2076
+ for url, _ in targets:
2077
+ _check_server_url(url, base_url=self.base_url, what="page image URL")
2078
+ await asyncio.to_thread(Path(dest_dir).mkdir, parents=True, exist_ok=True)
2079
+
2080
+ async def _one(target: tuple[str, Path]) -> Path:
2081
+ url, path = target
2082
+ await self._download_page(url, path, max_page_bytes)
2083
+ return path
2084
+
2085
+ return await _bounded_map(_one, targets, _TRANSFER_CONCURRENCY)
2086
+
2087
+ async def _download_page(self, url: str, path: Path, max_page_bytes: int) -> None:
2088
+ """Stream one presigned page image to ``path`` (atomically, size-capped).
2089
+
2090
+ File writes run in a worker thread so the event loop is never blocked.
2091
+ """
2092
+ partial = _partial_path(path)
2093
+ try:
2094
+ # Presigned URLs carry their own SigV4 signature — send no API-key headers.
2095
+ # Redirects are followed (S3 answers a cross-region GET with a 307 to the
2096
+ # regional endpoint), each hop checked for https before it is requested.
2097
+ async with _stream_presigned_get(self._client, url, base_url=self.base_url) as resp:
2098
+ _check_download_reply(
2099
+ resp, path, base_url=self.base_url, max_page_bytes=max_page_bytes
2100
+ )
2101
+ f = await asyncio.to_thread(open, partial, "wb")
2102
+ try:
2103
+ received = 0
2104
+ async for chunk in resp.aiter_bytes():
2105
+ received += len(chunk)
2106
+ if received > max_page_bytes:
2107
+ raise _page_too_large(path, max_page_bytes)
2108
+ await asyncio.to_thread(f.write, chunk)
2109
+ finally:
2110
+ f.close()
2111
+ await asyncio.to_thread(os.replace, partial, path)
2112
+ except httpx.RequestError as e:
2113
+ raise _download_transport_error(path, e) from None
2114
+ finally:
2115
+ try:
2116
+ partial.unlink()
2117
+ except FileNotFoundError:
2118
+ pass
2119
+
2120
+ async def process(
2121
+ self,
2122
+ file_path: str | Path | None = None,
2123
+ *,
2124
+ image_path: str | Path | None = None,
2125
+ poll_timeout: float | None = None,
2126
+ poll_interval: float | None = None,
2127
+ ) -> dict:
2128
+ """Parse and extract in one call.
2129
+
2130
+ Uploads the document once, then submits the parse and extract legs
2131
+ back-to-back. The server runs the two legs concurrently; the SDK polls
2132
+ both jobs concurrently via ``asyncio.gather``.
2133
+ Total wall-clock ≈ max(parse, extract) + small polling overhead.
2134
+
2135
+ Returns:
2136
+ ``{"ocr": <parse text>, "data": <extract job envelope>}``.
2137
+ ``data`` is the extract job's full inference envelope (the same
2138
+ dict :py:meth:`extract` returns), not the fields themselves: the
2139
+ structured fields are at ``result["data"]["result"]["entities"]``,
2140
+ ``result["data"]["result"]["line_items"]`` and
2141
+ ``result["data"]["result"]["summary"]``.
2142
+ """
2143
+ path = self._resolve_path(file_path, image_path)
2144
+ document_key = await self.upload_document(path)
2145
+ # The two submissions could in principle be gathered too, but keeping
2146
+ # them sequential matches the sync client's behavior and the server
2147
+ # serializes them anyway through the shared document_key.
2148
+ parse_job = await self._submit_via_doc_key(
2149
+ "/v1/parse",
2150
+ "parse",
2151
+ document_key,
2152
+ params={},
2153
+ )
2154
+ extract_job = await self._submit_via_doc_key(
2155
+ "/v1/extract",
2156
+ "extract",
2157
+ document_key,
2158
+ params={},
2159
+ )
2160
+ results = await self.wait_for_jobs(
2161
+ [parse_job, extract_job],
2162
+ timeout=poll_timeout,
2163
+ interval=poll_interval,
2164
+ )
2165
+ parse_result, extract_result = results
2166
+ return {
2167
+ "ocr": _parse_ocr_text(parse_result),
2168
+ "data": extract_result if isinstance(extract_result, dict) else {},
2169
+ }
2170
+
2171
+ # ── Lifecycle ────────────────────────────────────────────────────────
2172
+
2173
+ async def aclose(self) -> None:
2174
+ """Close the underlying HTTP client and release its connection pool."""
2175
+ await self._client.aclose()
2176
+
2177
+ async def __aenter__(self) -> AsyncHyperAPIClient:
2178
+ return self
2179
+
2180
+ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
2181
+ await self.aclose()