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.
hyperapi/client.py ADDED
@@ -0,0 +1,2947 @@
1
+ """HyperAPI Client.
2
+
3
+ Architecture
4
+ ============
5
+ Every long-running pipeline op (`parse`, `extract`, `classify`, `split`,
6
+ `process`) goes through **submit + poll** under the hood:
7
+
8
+ 1. POST /v1/<op> with X-Async: true → 202 {job_id, poll_url}
9
+ 2. GET /v1/jobs/{job_id} (every poll_interval) → {status, result?, error?}
10
+
11
+ This keeps every individual HTTP request short (sub-second), so the SDK is
12
+ **timeout-immune** at any edge — works behind CloudFront's 30 s
13
+ `origin_response_timeout`, Cloudflare's 100 s, a raw ALB, or no edge at all.
14
+ The convenience methods (``parse(...)``, ``extract(...)``, ...) hide the
15
+ ``job_id`` from callers; advanced users who want fire-and-forget or custom
16
+ progress UIs can call ``submit_<op>(...)`` and ``wait_for_job(...)`` directly.
17
+
18
+ Pipeline (server-side, transparent to callers):
19
+
20
+ OCR (always runs)
21
+ Upload → page images → OCR text (full_text + page_texts)
22
+
23
+ Task-specific processing (skipped for parse)
24
+ parse: OCR text only (no task step)
25
+ extract: OCR output → structured extraction
26
+ classify: OCR output → classification
27
+ split: OCR output → document splitting
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import contextlib
33
+ import json
34
+ import logging
35
+ import os
36
+ import random
37
+ import sys
38
+ import time
39
+ import uuid
40
+ import warnings
41
+ from dataclasses import dataclass, field
42
+ from datetime import datetime, timezone
43
+ from email.utils import parsedate_to_datetime
44
+ from pathlib import Path
45
+ from typing import Any, Literal
46
+ from collections.abc import Callable, Iterable
47
+ from urllib.parse import quote
48
+
49
+ import httpx
50
+
51
+ from .exceptions import (
52
+ AuthenticationError,
53
+ ClassifyError,
54
+ DocumentUploadError,
55
+ ExtractError,
56
+ HyperAPIError,
57
+ JobCancelledError,
58
+ JobTimeoutError,
59
+ ParseError,
60
+ RateLimitError,
61
+ RedactError,
62
+ SplitError,
63
+ _strip_api_key,
64
+ )
65
+
66
+
67
+ # File extension -> upload content_type. Every value must be one the API's
68
+ # upload endpoint accepts; any other type is answered with 415. An unknown
69
+ # extension falls back to application/octet-stream and is rejected.
70
+ CONTENT_TYPES = {
71
+ ".pdf": "application/pdf",
72
+ # Images
73
+ ".png": "image/png",
74
+ ".jpg": "image/jpeg",
75
+ ".jpeg": "image/jpeg",
76
+ ".gif": "image/gif",
77
+ ".webp": "image/webp",
78
+ ".tiff": "image/tiff",
79
+ ".tif": "image/tiff",
80
+ ".heic": "image/heic",
81
+ ".heif": "image/heif",
82
+ # Office documents
83
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
84
+ ".doc": "application/msword",
85
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
86
+ ".xls": "application/vnd.ms-excel",
87
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
88
+ ".ppt": "application/vnd.ms-powerpoint",
89
+ # Text and data
90
+ ".csv": "text/csv",
91
+ ".txt": "text/plain",
92
+ ".md": "text/markdown",
93
+ ".rtf": "application/rtf",
94
+ ".json": "application/json",
95
+ ".xml": "application/xml",
96
+ # Fixed-layout pages
97
+ ".xps": "application/vnd.ms-xpsdocument",
98
+ ".oxps": "application/oxps",
99
+ # Email
100
+ ".eml": "message/rfc822",
101
+ ".msg": "application/vnd.ms-outlook",
102
+ }
103
+
104
+ ParseMode = Literal["fast", "advanced"]
105
+ # Basic extract document family. ``financial`` (platform default) uses the built-in
106
+ # invoice and receipt fields; ``non_financial`` uses the generic
107
+ # single-pass extractor. Advanced extraction (auto-detect) is a separate method.
108
+ ExtractCategory = Literal["financial", "non_financial"]
109
+
110
+ # Per-HTTP-call defaults — single submit / single poll, NOT total job time.
111
+ _DEFAULT_TIMEOUT = 120.0
112
+
113
+ # Polling defaults. Document jobs can run for many minutes, so the SDK
114
+ # deadline is deliberately longer than a typical interactive request.
115
+ _DEFAULT_POLL_INTERVAL_S = 3.0
116
+ _DEFAULT_POLL_TIMEOUT_S = 3600.0
117
+ _DEFAULT_POLL_MAX_TRANSIENT_RETRIES = 3
118
+ _DEFAULT_POLL_TRANSIENT_RETRY_DELAY_S = 0.5
119
+
120
+
121
+ _DEFAULT_BASE_URL = "https://apis.hyperbots.com"
122
+ _LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
123
+
124
+
125
+ def _resolve_base_url(base_url: str | httpx.URL | None) -> str:
126
+ """Pick the API base URL and check that it is safe to send the API key to.
127
+
128
+ The API key travels in a header on every request, so the URL must be an
129
+ absolute ``http(s)`` URL with a host. Plain ``http`` is accepted (local and
130
+ test servers need it) but warns unless the host is a loopback address.
131
+ Non-string values such as ``httpx.URL`` are converted with ``str()``.
132
+ """
133
+ if base_url is not None and not isinstance(base_url, str):
134
+ base_url = str(base_url)
135
+ raw = (base_url or os.environ.get("HYPERAPI_URL") or _DEFAULT_BASE_URL).strip()
136
+ try:
137
+ url = httpx.URL(raw)
138
+ except Exception as exc: # httpx raises InvalidURL or ValueError
139
+ raise ValueError(f"Invalid base_url {raw!r}: {exc}") from None
140
+ if url.scheme not in ("https", "http") or not url.host:
141
+ raise ValueError(
142
+ f"Invalid base_url {raw!r}: use an absolute https:// URL, "
143
+ f"for example {_DEFAULT_BASE_URL!r}."
144
+ )
145
+ # "https://apis.hyperbots.com@other.example" sends the key to other.example,
146
+ # and credentials in the URL would show up in reprs and error messages.
147
+ if url.userinfo:
148
+ raise ValueError(
149
+ f"Invalid base_url for host {url.host!r}: it must not contain "
150
+ "a username or password ('user@host')."
151
+ )
152
+ # An empty "?" or "#" parses as no query/fragment but would still be glued
153
+ # in front of every request path ("https://host?/v1/parse").
154
+ if url.query or url.fragment or "?" in raw or "#" in raw or any(c.isspace() for c in raw):
155
+ raise ValueError(
156
+ f"Invalid base_url {raw!r}: it must not contain a query string, "
157
+ "a fragment or whitespace."
158
+ )
159
+ if url.scheme == "http" and url.host not in _LOOPBACK_HOSTS:
160
+ warnings.warn(
161
+ f"base_url {raw!r} uses plain http: the API key is sent unencrypted. "
162
+ "Use https:// outside local testing.",
163
+ stacklevel=3,
164
+ )
165
+ return raw.rstrip("/")
166
+
167
+
168
+ _API_KEY_REQUIRED = "API key required. Pass api_key or set HYPERAPI_KEY environment variable."
169
+
170
+
171
+ def _clean_api_key(value: str | None) -> str:
172
+ """Return the API key with surrounding whitespace removed, or refuse it.
173
+
174
+ Keys read from files and secret mounts often carry a trailing newline; left
175
+ in, the HTTP layer rejects the header with an error that quotes the full
176
+ key. Inner whitespace, control characters and non-ASCII cannot be part of
177
+ an issued key and cannot travel in a header, so they are refused here — and
178
+ the message never includes the key.
179
+ """
180
+ key = value.strip() if isinstance(value, str) else ""
181
+ if not key:
182
+ raise AuthenticationError(_API_KEY_REQUIRED)
183
+ if not key.isascii() or any(ch.isspace() or not ch.isprintable() for ch in key):
184
+ raise AuthenticationError(
185
+ "API key contains whitespace or control characters; "
186
+ "check how it is loaded (for example a stray newline)."
187
+ )
188
+ return key
189
+
190
+
191
+ def _load_schema(schema: dict | str | os.PathLike | None) -> dict | None:
192
+ """Resolve an extract ``schema`` argument to a dict (or None).
193
+
194
+ * ``dict`` — returned as is.
195
+ * ``pathlib.Path`` (any ``os.PathLike``) — the file is read and parsed.
196
+ * ``str`` — always parsed as JSON text; never treated as a file name.
197
+
198
+ A ``str`` never touches the filesystem: an application that forwards
199
+ user-supplied schema text must not be steerable into reading (and
200
+ uploading) local files, and a long JSON string must not be handed to
201
+ ``Path.exists()`` (which raises ``OSError: File name too long``).
202
+ """
203
+ if schema is None or isinstance(schema, dict):
204
+ return schema
205
+
206
+ if isinstance(schema, os.PathLike):
207
+ path = Path(schema)
208
+ if not path.exists():
209
+ raise FileNotFoundError(f"Schema file not found: {path}")
210
+ try:
211
+ parsed = json.loads(path.read_text())
212
+ except ValueError as e:
213
+ raise ValueError(f"Schema file {path} is not valid JSON: {e}") from None
214
+ elif isinstance(schema, str):
215
+ try:
216
+ parsed = json.loads(schema)
217
+ except ValueError as e:
218
+ if schema.strip().lower().endswith(".json"):
219
+ hint = (
220
+ "This string ends in '.json' but a str schema is always JSON "
221
+ "text, never a file name; to load a schema file pass "
222
+ 'pathlib.Path("...") instead.'
223
+ )
224
+ else:
225
+ hint = 'To load a schema from a file, pass pathlib.Path("...").'
226
+ raise ValueError(f"schema string is not valid JSON ({e}). {hint}") from None
227
+ else:
228
+ raise TypeError(
229
+ "schema must be a dict, a JSON string, or a pathlib.Path, "
230
+ f"not {type(schema).__name__}"
231
+ )
232
+
233
+ if not isinstance(parsed, dict):
234
+ raise ValueError("schema must resolve to a JSON object")
235
+ return parsed
236
+
237
+
238
+ logger = logging.getLogger("hyperapi")
239
+
240
+
241
+ # Ops the SDK can submit asynchronously. Used as the per-op error class registry.
242
+ _OP_TO_ERROR: dict[str, type] = {
243
+ "parse": ParseError,
244
+ "extract": ExtractError,
245
+ "classify": ClassifyError,
246
+ "split": SplitError,
247
+ "redact": RedactError,
248
+ }
249
+
250
+
251
+ @dataclass
252
+ class Job:
253
+ """Handle returned by ``client.submit_<op>(...)``.
254
+
255
+ Pass to :py:meth:`HyperAPIClient.wait_for_job` to block until the job is
256
+ done, or to :py:meth:`HyperAPIClient.get_job` for a single-shot status
257
+ check. The ``op`` field is what tells :py:meth:`wait_for_job` which typed
258
+ exception to raise on ``status: "failed"``.
259
+ """
260
+
261
+ job_id: str
262
+ status: str
263
+ poll_url: str
264
+ op: str # "parse" | "extract" | "classify" | "split" | "redact"
265
+ submitted_at: float = field(default_factory=time.monotonic)
266
+
267
+
268
+ # ── Helpers (module-private) ────────────────────────────────────────────────
269
+
270
+
271
+ def _parse_retry_after(value: str | None, *, default: int = 60) -> int:
272
+ """Parse a `Retry-After` header into whole seconds-from-now.
273
+
274
+ RFC 7231 permits both ``delta-seconds`` and an ``HTTP-date``. Gateways and
275
+ CDNs may use either form, so handle both and floor the result at zero.
276
+ """
277
+ if not value:
278
+ return default
279
+ value = value.strip()
280
+ try:
281
+ return max(0, int(value))
282
+ except (TypeError, ValueError):
283
+ pass
284
+ # HTTP-date form, e.g. "Wed, 21 Oct 2026 07:28:00 GMT".
285
+ try:
286
+ dt = parsedate_to_datetime(value)
287
+ except (TypeError, ValueError):
288
+ return default
289
+ if dt is None: # some Python versions return None on unparseable input
290
+ return default
291
+ if dt.tzinfo is None: # RFC dates are UTC; treat naive as UTC
292
+ dt = dt.replace(tzinfo=timezone.utc)
293
+ delta = (dt - datetime.now(timezone.utc)).total_seconds()
294
+ return max(0, int(delta))
295
+
296
+
297
+ def _safe_text(response: httpx.Response) -> str:
298
+ """Return the response body as a string with API keys scrubbed."""
299
+ try:
300
+ return _strip_api_key(response.text) or ""
301
+ except Exception: # noqa: BLE001 # pragma: no cover
302
+ # Unreachable in practice: httpx.Response.text never raises for the codepaths we hit.
303
+ return ""
304
+
305
+
306
+ def _dict_message(body: dict) -> str:
307
+ """One readable line for an error body that is itself a JSON object.
308
+
309
+ Prefers a human string under ``message`` / ``detail`` / ``error``; with
310
+ none, summarises the object as ``key=value`` pairs so an exception never
311
+ shows a Python dict repr.
312
+ """
313
+ for key in ("message", "detail", "error"):
314
+ text = body.get(key)
315
+ if isinstance(text, str) and text.strip():
316
+ return text
317
+ parts = []
318
+ for key, value in body.items():
319
+ if value is None:
320
+ continue
321
+ if isinstance(value, (dict, list)):
322
+ value = json.dumps(value, separators=(",", ":"), default=str)
323
+ parts.append(f"{key}={value}")
324
+ return ", ".join(parts)
325
+
326
+
327
+ def _server_error(response: httpx.Response) -> tuple[str | None, str | None, dict | None]:
328
+ """Decode the API's error envelope into ``(message, code, details)``.
329
+
330
+ The API answers every error as ``{"error": {"code": str, "message": str,
331
+ "details"?: dict}}``. ``code`` is the stable machine-readable reason (a
332
+ status-derived constant such as ``"NOT_FOUND"``, or a specific one such as
333
+ ``"page_quota_exceeded"``); ``details`` is optional and carries the numbers
334
+ behind a refusal. Parsing stays tolerant of other shapes — a bare
335
+ ``{"message": ...}`` or ``{"detail": ...}`` from an intermediary, or a
336
+ non-JSON body — so a proxy error page never turns into a parse failure.
337
+ Where the human text is itself an object (a structured refusal such as a
338
+ quota answer), the message is a readable line built from it and the
339
+ object is returned as ``details``.
340
+ Every field returned is API-key-scrubbed; each is ``None`` when absent.
341
+ """
342
+ body = _safe_text(response)
343
+ try:
344
+ parsed = json.loads(body)
345
+ except (json.JSONDecodeError, ValueError):
346
+ return None, None, None
347
+ if not isinstance(parsed, dict):
348
+ return None, None, None
349
+
350
+ code: str | None = None
351
+ details: dict | None = None
352
+ message: str | None = None
353
+ for key in ("error", "message", "detail"):
354
+ val = parsed.get(key)
355
+ if not val:
356
+ continue
357
+ if isinstance(val, dict):
358
+ inner_code = val.get("code")
359
+ if isinstance(inner_code, str) and code is None:
360
+ code = inner_code
361
+ inner_details = val.get("details")
362
+ if isinstance(inner_details, dict) and details is None:
363
+ details = inner_details
364
+ # Prefer the nested human text over stringifying the whole dict
365
+ # (which would surface a Python dict repr like "{'code': ...}").
366
+ text = val.get("message") or val.get("detail") or val.get("error")
367
+ if isinstance(text, dict):
368
+ # The text slot holds a structured refusal, e.g.
369
+ # {"error": {"code": ..., "message": {"error": "quota_exceeded", ...}}}.
370
+ nested_code = text.get("code")
371
+ if isinstance(nested_code, str) and code is None:
372
+ code = nested_code
373
+ if details is None:
374
+ details = text
375
+ text = _dict_message(text)
376
+ elif details is None and inner_code is None and not isinstance(
377
+ val.get("message"), str
378
+ ):
379
+ # A bare object that is not the standard envelope, e.g.
380
+ # {"detail": {"error": "quota_exceeded", "list_price_cents": 5}}.
381
+ details = val
382
+ val = text if text else _dict_message(val)
383
+ if message is None:
384
+ message = _strip_api_key(str(val))
385
+ if code is None:
386
+ top_code = parsed.get("code")
387
+ if isinstance(top_code, str):
388
+ code = top_code
389
+ return message, code, details
390
+
391
+
392
+ def _server_message(response: httpx.Response, fallback: str) -> str:
393
+ """Pull a human-readable message out of a server response.
394
+
395
+ Prefers the envelope's ``error.message`` (see :func:`_server_error`), falls
396
+ back to the body text, and finally to the supplied fallback. Always
397
+ API-key-scrubbed.
398
+ """
399
+ message, _, _ = _server_error(response)
400
+ if message:
401
+ return message
402
+ return _safe_text(response) or fallback
403
+
404
+
405
+ def _error_fields(response: httpx.Response) -> dict[str, Any]:
406
+ """``code``/``details`` keyword arguments for an exception built from ``response``.
407
+
408
+ Splat into any ``HyperAPIError`` constructor so the envelope's stable
409
+ reason code and its optional ``details`` travel with the exception.
410
+ """
411
+ _, code, details = _server_error(response)
412
+ return {"code": code, "details": details}
413
+
414
+
415
+ _CANCELLED_PREFIX = "cancelled:"
416
+
417
+
418
+ def _cancelled_job_error(envelope: dict, job_id: str) -> JobCancelledError | None:
419
+ """Decode a ``status="failed"`` envelope that is really a cancel.
420
+
421
+ ``DELETE /v1/jobs/{id}`` leaves the job in ``status="failed"`` with an
422
+ ``error`` beginning ``"cancelled:"``. Returns ``None`` for any other
423
+ failure so the caller raises its usual per-op exception.
424
+ """
425
+ error = envelope.get("error")
426
+ if not (isinstance(error, str) and error.startswith(_CANCELLED_PREFIX)):
427
+ return None
428
+ return JobCancelledError(
429
+ f"Job {job_id} was cancelled before it completed "
430
+ "(DELETE /v1/jobs/{id}); submit the document again to re-run it.",
431
+ job_id=job_id,
432
+ request_id=envelope.get("request_id"),
433
+ )
434
+
435
+
436
+ def _request_id_of(response: httpx.Response, sent: str | None = None) -> str | None:
437
+ """Best-effort extraction of the request id we should attach to errors."""
438
+ return (
439
+ response.headers.get("x-request-id")
440
+ or response.headers.get("x-correlation-id")
441
+ or sent
442
+ )
443
+
444
+
445
+ _NOT_JSON = object()
446
+
447
+
448
+ def _json_object(
449
+ resp: httpx.Response,
450
+ *,
451
+ request_id: str | None,
452
+ error_cls: type[HyperAPIError] = HyperAPIError,
453
+ required: Iterable[str] = (),
454
+ what: str = "server",
455
+ ) -> dict:
456
+ """Decode a success reply that must be a JSON object, or raise ``error_cls``.
457
+
458
+ A proxy error page served with 200, a JSON list, or an envelope without
459
+ the keys the SDK needs would otherwise escape as ``JSONDecodeError``,
460
+ ``AttributeError`` or ``KeyError``. ``required`` keys must be present and
461
+ not ``None`` or empty. The raised error carries the HTTP status and the
462
+ request id.
463
+ """
464
+ try:
465
+ body = resp.json()
466
+ except ValueError: # JSONDecodeError and UnicodeDecodeError are ValueErrors
467
+ body = _NOT_JSON
468
+ problem = None
469
+ if body is _NOT_JSON:
470
+ problem = "the body is not JSON"
471
+ elif not isinstance(body, dict):
472
+ problem = f"expected a JSON object, got {type(body).__name__}"
473
+ else:
474
+ missing = [key for key in required if body.get(key) in (None, "")]
475
+ if missing:
476
+ problem = "missing " + ", ".join(repr(key) for key in missing)
477
+ if problem is not None:
478
+ raise error_cls(
479
+ f"Malformed {what} response (HTTP {resp.status_code}): {problem}.",
480
+ status_code=resp.status_code,
481
+ request_id=request_id,
482
+ )
483
+ return body
484
+
485
+
486
+ def _path_id(value: Any, *, name: str = "id") -> str:
487
+ """Percent-encode a job or batch id for use as one URL path segment.
488
+
489
+ Ids come from callers (and are often stored and replayed), so an id such
490
+ as ``"../limits?x="`` must stay inside its own path segment instead of
491
+ walking to another endpoint or adding a query string. Every reserved
492
+ character, including ``/``, is encoded.
493
+ """
494
+ text = "" if value is None else str(value)
495
+ if not text.strip():
496
+ raise ValueError(f"{name} must be a non-empty string")
497
+ return quote(text, safe="")
498
+
499
+
500
+ def _parse_params(
501
+ *,
502
+ mode: str | None,
503
+ include_boxes: bool | None,
504
+ include_image: bool | None,
505
+ include_layout: bool | None,
506
+ parse_figures: str | None,
507
+ groups_profile: str | None,
508
+ ) -> dict[str, Any]:
509
+ """Query parameters for ``POST /v1/parse`` — only what the caller set.
510
+
511
+ Every parse option is omitted when ``None`` so the API's own default
512
+ applies. This matters most for the ``include_*`` flags: the API treats an
513
+ omitted flag as ON (in ``"fast"`` mode) and a literal ``false`` as an
514
+ opt-out, so sending ``False`` on the caller's behalf would silently strip
515
+ boxes, layout and page images from every result. Shared by both clients.
516
+ """
517
+ params: dict[str, Any] = {}
518
+ if mode is not None:
519
+ params["mode"] = mode
520
+ if include_boxes is not None:
521
+ params["include_boxes"] = include_boxes
522
+ if include_image is not None:
523
+ params["include_image"] = include_image
524
+ if include_layout is not None:
525
+ params["include_layout"] = include_layout
526
+ if parse_figures is not None:
527
+ params["parse_figures"] = parse_figures
528
+ if groups_profile is not None:
529
+ params["groups_profile"] = groups_profile
530
+ return params
531
+
532
+
533
+ def _parse_ocr_text(parse_result: Any) -> Any:
534
+ """OCR text from a parse job result. The parse envelope nests its payload
535
+ under `result` (parse_result["result"]["ocr"]); a flattened shape would put
536
+ it at the top level. None if absent."""
537
+ if not isinstance(parse_result, dict):
538
+ return None
539
+ inner = parse_result.get("result")
540
+ if isinstance(inner, dict) and "ocr" in inner:
541
+ return inner["ocr"]
542
+ return parse_result.get("ocr")
543
+
544
+
545
+ def _pages_of(result: Any) -> list[dict]:
546
+ """Find the page list in any op's result, whichever nesting it arrived in.
547
+
548
+ ``parse`` and ``redact`` return the platform envelope, so the pages sit at
549
+ ``result["result"]["pages"]``. A caller who already unwrapped the envelope
550
+ holds them at ``result["pages"]``; both are accepted.
551
+ """
552
+ if not isinstance(result, dict):
553
+ raise ValueError(
554
+ "Expected the dict returned by parse() or redact(output=\"urls\")"
555
+ )
556
+ for candidate in (result.get("result"), result):
557
+ if isinstance(candidate, dict) and isinstance(candidate.get("pages"), list):
558
+ return candidate["pages"]
559
+ raise ValueError(
560
+ "No 'pages' in this result. Pass the value returned by parse() with page "
561
+ "images on (the default), or by redact(output=\"urls\")."
562
+ )
563
+
564
+
565
+ def _page_number(page: dict, fallback: int) -> int:
566
+ """The page's own ``page_number``, else its 1-based position in the list."""
567
+ value = page.get("page_number")
568
+ if isinstance(value, int) and not isinstance(value, bool):
569
+ return value
570
+ return fallback
571
+
572
+
573
+ def _image_suffix(url: str) -> str:
574
+ """Extension from the URL path — redact serves .png, parse serves .webp. Never guess:
575
+ writing webp bytes into a .png name breaks anything that trusts the extension."""
576
+ stem = url.split("?", 1)[0].rsplit("/", 1)[-1]
577
+ suffix = Path(stem).suffix.lower()
578
+ return (
579
+ suffix
580
+ if suffix in {".png", ".webp", ".jpg", ".jpeg", ".tif", ".tiff"}
581
+ else ".png"
582
+ )
583
+
584
+
585
+ def _page_targets(
586
+ result: Any, dest_dir: str | Path, prefix: str
587
+ ) -> list[tuple[str, Path]]:
588
+ """Pair each page's presigned URL with the local path it should be written to."""
589
+ pages = _pages_of(result)
590
+ dest = Path(dest_dir)
591
+ out: list[tuple[str, Path]] = []
592
+ for i, page in enumerate(pages):
593
+ page = page or {}
594
+ url = page.get("image_url")
595
+ if not url:
596
+ raise ValueError(
597
+ f"Page {_page_number(page, i + 1)} has no 'image_url' to download. "
598
+ "For parse(), leave include_image unset or pass include_image=True."
599
+ )
600
+ out.append(
601
+ (url, dest / f"{prefix}-{_page_number(page, i + 1)}{_image_suffix(url)}")
602
+ )
603
+ return out
604
+
605
+
606
+ # Downloads and uploads of presigned URLs.
607
+ _DEFAULT_MAX_PAGE_BYTES = 200 * 1024 * 1024
608
+ # The async client runs at most this many presigned transfers at once.
609
+ _TRANSFER_CONCURRENCY = 8
610
+
611
+
612
+ def _check_server_url(
613
+ url: Any,
614
+ *,
615
+ base_url: str,
616
+ what: str,
617
+ error_cls: type[HyperAPIError] = HyperAPIError,
618
+ ) -> None:
619
+ """Refuse a server-supplied URL (presigned upload/download) that is not https.
620
+
621
+ Plain ``http`` is accepted only when the client itself talks to a plain
622
+ ``http`` base URL (a local or test server). The URL is never echoed in
623
+ the error: presigned URLs carry a signature.
624
+ """
625
+ scheme = ""
626
+ if isinstance(url, str) and url:
627
+ try:
628
+ scheme = httpx.URL(url).scheme
629
+ except Exception: # noqa: BLE001 # httpx raises InvalidURL or ValueError
630
+ scheme = ""
631
+ if scheme == "https":
632
+ return
633
+ if scheme == "http" and httpx.URL(base_url).scheme == "http":
634
+ return
635
+ raise error_cls(
636
+ f"Refusing a {what} that does not use https (scheme {scheme or 'missing'!r}). "
637
+ "Presigned URLs from the API are always https; plain http is accepted only "
638
+ "when base_url itself is http (local testing)."
639
+ )
640
+
641
+
642
+ # Redirects a presigned GET may follow (S3 sends one 307 to the regional endpoint).
643
+ _MAX_PRESIGNED_REDIRECTS = 5
644
+
645
+
646
+ def _next_presigned_hop(resp: httpx.Response, hops: int, *, base_url: str) -> httpx.Request:
647
+ """The redirect target of ``resp``, checked BEFORE it is requested.
648
+
649
+ Redirects are followed by hand rather than with ``follow_redirects=True``,
650
+ so the https rule applies to every hop: an https -> http -> https chain is
651
+ refused before the plain-http request is sent, not only judged by its
652
+ final URL.
653
+ """
654
+ if hops > _MAX_PRESIGNED_REDIRECTS:
655
+ raise HyperAPIError(
656
+ f"Refusing a page image download: more than {_MAX_PRESIGNED_REDIRECTS} redirects."
657
+ )
658
+ nxt = resp.next_request
659
+ assert nxt is not None # the caller loops only while there is one
660
+ _check_server_url(str(nxt.url), base_url=base_url, what="page image redirect")
661
+ return nxt
662
+
663
+
664
+ @contextlib.contextmanager
665
+ def _stream_presigned_get(client: httpx.Client, url: str, *, base_url: str):
666
+ """Stream a presigned GET, following redirects hop by hop (see above)."""
667
+ resp = client.send(client.build_request("GET", url), stream=True, follow_redirects=False)
668
+ try:
669
+ hops = 0
670
+ while resp.next_request is not None:
671
+ hops += 1
672
+ nxt = _next_presigned_hop(resp, hops, base_url=base_url)
673
+ resp.close()
674
+ resp = client.send(nxt, stream=True, follow_redirects=False)
675
+ yield resp
676
+ finally:
677
+ resp.close()
678
+
679
+
680
+ def _regular_file(file_path: str | Path) -> Path:
681
+ """The upload path, which must be an existing regular file.
682
+
683
+ A directory, FIFO or device would hang or fail obscurely on read.
684
+ """
685
+ path = Path(file_path)
686
+ if not path.exists():
687
+ raise FileNotFoundError(f"File not found: {path}")
688
+ if not path.is_file():
689
+ raise ValueError(
690
+ f"Not a regular file: {path}. Directories, pipes and devices cannot be uploaded."
691
+ )
692
+ return path
693
+
694
+
695
+ def _check_page_cap(max_page_bytes: int) -> None:
696
+ if (
697
+ isinstance(max_page_bytes, bool)
698
+ or not isinstance(max_page_bytes, int)
699
+ or max_page_bytes <= 0
700
+ ):
701
+ raise ValueError("max_page_bytes must be a positive int")
702
+
703
+
704
+ def _partial_path(path: Path) -> Path:
705
+ """A unique temporary name next to ``path``; renamed over it once complete."""
706
+ return path.with_name(f".{path.name}.{uuid.uuid4().hex[:12]}.part")
707
+
708
+
709
+ def _page_too_large(path: Path, max_page_bytes: int) -> HyperAPIError:
710
+ return HyperAPIError(
711
+ f"Could not download {path.name}: the image is larger than "
712
+ f"max_page_bytes ({max_page_bytes} bytes). Nothing was written; "
713
+ "raise max_page_bytes if this page is expected to be this large."
714
+ )
715
+
716
+
717
+ def _check_download_reply(
718
+ resp: httpx.Response, path: Path, *, base_url: str, max_page_bytes: int
719
+ ) -> None:
720
+ """Status, final-URL and declared-size checks before a page body is read."""
721
+ if resp.status_code >= 400:
722
+ raise _download_error(path, resp.status_code)
723
+ # Redirects are followed (S3 sends a 307 to the regional endpoint); the
724
+ # final hop must meet the same https rule as the URL the API handed out.
725
+ _check_server_url(str(resp.url), base_url=base_url, what="page image redirect")
726
+ declared = resp.headers.get("content-length", "")
727
+ if declared.isdigit() and int(declared) > max_page_bytes:
728
+ raise _page_too_large(path, max_page_bytes)
729
+
730
+
731
+ def _download_transport_error(path: Path, exc: Exception) -> HyperAPIError:
732
+ return HyperAPIError(f"Could not download {path.name}: {exc}")
733
+
734
+
735
+ def _download_error(page_path: Path, status: int) -> HyperAPIError:
736
+ hint = ""
737
+ if status in (403, 401):
738
+ # SigV4 presigned URLs live ~15 min; the job itself survives 24 h.
739
+ hint = (
740
+ " The presigned URL has most likely expired — re-poll the job with "
741
+ "get_job(job_id) for fresh URLs, then download again."
742
+ )
743
+ return HyperAPIError(
744
+ f"Could not download {page_path.name} (HTTP {status}).{hint}",
745
+ status_code=status,
746
+ )
747
+
748
+
749
+ def _rate_limit_error_from(resp: httpx.Response, rid: str | None) -> RateLimitError:
750
+ """Build a RateLimitError from a 429 response envelope.
751
+
752
+ The API may rate-limit both submissions and job polls, and it also uses
753
+ 429 for a monthly page quota that is used up (``error.code ==
754
+ "page_quota_exceeded"``). The code is carried on the exception so callers
755
+ and the SDK's own poll loops can tell the two apart. This helper is shared
756
+ by both clients so envelope parsing stays consistent.
757
+ """
758
+ retry_after = _parse_retry_after(resp.headers.get("retry-after"))
759
+ tier = None
760
+ limit = None
761
+ window_seconds = None
762
+ degraded = False
763
+ try:
764
+ body = resp.json()
765
+ if isinstance(body, dict):
766
+ tier = body.get("tier")
767
+ limit = body.get("limit")
768
+ # The window length lets callers interpret the numeric limit.
769
+ window_seconds = body.get("window_seconds")
770
+ # A degraded response distinguishes transient enforcement trouble
771
+ # from a customer exceeding their configured quota.
772
+ degraded = bool(body.get("degraded", False))
773
+ except (json.JSONDecodeError, ValueError): # pragma: no cover
774
+ # Fall back to the response headers when the body is not JSON.
775
+ pass
776
+ return RateLimitError(
777
+ _server_message(resp, "Rate limit exceeded"),
778
+ retry_after=retry_after,
779
+ tier=tier,
780
+ limit=limit,
781
+ window_seconds=window_seconds,
782
+ degraded=degraded,
783
+ status_code=429,
784
+ request_id=rid,
785
+ **_error_fields(resp),
786
+ )
787
+
788
+
789
+ def _is_transient(err: HyperAPIError) -> bool:
790
+ """Whether a failed poll is worth retrying: no HTTP reply at all (network
791
+ error, timeout) or a 5xx. Every 4xx — and a malformed 2xx — fails fast:
792
+ asking again returns the same answer."""
793
+ return err.status_code is None or err.status_code >= 500
794
+
795
+
796
+ def _poll_deadline_error(
797
+ kind: str, ident: str, last: HyperAPIError, start: float | None
798
+ ) -> JobTimeoutError:
799
+ """The error for a poll that is still failing transiently when the caller's
800
+ deadline passes: the wait is over, so report a timeout (with the cause)."""
801
+ return JobTimeoutError(
802
+ f"{kind} {ident} did not complete in the time allowed; "
803
+ f"the last status poll failed: {last.message}",
804
+ job_id=ident,
805
+ elapsed_s=time.monotonic() - start if start is not None else 0.0,
806
+ request_id=last.request_id,
807
+ )
808
+
809
+
810
+ def _transient_delay(
811
+ err: HyperAPIError,
812
+ *,
813
+ attempt: int,
814
+ max_retries: int,
815
+ delay: float,
816
+ deadline: float | None,
817
+ kind: str,
818
+ ident: str,
819
+ start: float | None,
820
+ ) -> float:
821
+ """Seconds to sleep before retrying a failed poll, or raise.
822
+
823
+ Shared by both clients' retry loops. Raises ``err`` itself when it is not
824
+ transient or the retries are used up, and :class:`JobTimeoutError` when
825
+ the caller's ``deadline`` has passed. The sleep never runs past the
826
+ deadline.
827
+ """
828
+ if not _is_transient(err):
829
+ raise err
830
+ remaining = None if deadline is None else deadline - time.monotonic()
831
+ if remaining is not None and remaining <= 0:
832
+ raise _poll_deadline_error(kind, ident, err, start) from None
833
+ if attempt >= max_retries:
834
+ raise err
835
+ wait = delay if remaining is None else min(delay, remaining)
836
+ logger.info(
837
+ "poll_transient_retry",
838
+ extra={
839
+ f"{kind.lower()}_id": ident,
840
+ "attempt": attempt + 1,
841
+ "delay_s": wait,
842
+ "error": str(err)[:200],
843
+ },
844
+ )
845
+ return wait
846
+
847
+
848
+ def _rate_limit_wait(err: RateLimitError, remaining: float) -> float | None:
849
+ """Decide how to handle a 429 raised *during a poll loop*.
850
+
851
+ Job-status polls have their own per-organization limit, separate from
852
+ the plan's request limit, but a very large number of concurrently polled
853
+ jobs can still be throttled. That's transient: the window clears, so the
854
+ poll loop should sleep ``Retry-After`` and resume rather than fail the
855
+ whole wait.
856
+
857
+ Returns the seconds to sleep before re-polling, or ``None`` when the caller
858
+ should re-raise the ``RateLimitError`` instead: either the job's remaining
859
+ deadline can't outlast the rate window (the error still carries
860
+ ``retry_after`` so the user can wait and resume via ``submit_<op>`` +
861
+ ``wait_for_job``), or the 429 is not a rate window at all but an exhausted
862
+ monthly page quota (``err.is_quota_exhausted``), which no amount of waiting
863
+ within this call will clear. Shared by both clients so the sync/async
864
+ decision can't drift; each loop supplies its own sleep primitive.
865
+ """
866
+ if err.is_quota_exhausted:
867
+ return None
868
+ if remaining <= 0:
869
+ return None
870
+ # `retry_after` defaults to 60 and is floored at 0 by _parse_retry_after;
871
+ # floor to 1 here so a server-sent "retry now" (0) can't hot-spin the loop.
872
+ # `... or 0` guards a None from any future RateLimitError construction path.
873
+ wait = max(err.retry_after or 0, 1)
874
+ if wait > remaining:
875
+ return None
876
+ # Add a little jitter so a concurrent async fan-out (asyncio.gather over N
877
+ # jobs) doesn't wake every poller on the same tick and re-poll in a
878
+ # synchronized burst. Capped so wait+jitter never exceeds the budget.
879
+ jitter = random.uniform(0.0, min(0.5, remaining - wait))
880
+ return float(wait) + jitter
881
+
882
+
883
+ # ── Client ─────────────────────────────────────────────────────────────────
884
+
885
+
886
+ class HyperAPIClient:
887
+ """Client for the HyperAPI document intelligence platform.
888
+
889
+ Quickstart::
890
+
891
+ from hyperapi import HyperAPIClient
892
+
893
+ client = HyperAPIClient(api_key="hk_live_…")
894
+ result = client.extract("invoice.pdf")
895
+ print(result["result"])
896
+ client.close()
897
+
898
+ Or as a context manager::
899
+
900
+ with HyperAPIClient(api_key="hk_live_…") as client:
901
+ print(client.parse("invoice.pdf")["result"]["ocr"])
902
+
903
+ Threading
904
+ ---------
905
+ ``HyperAPIClient`` is **not** thread-safe (httpx.Client isn't either).
906
+ Construct one client per thread, or use ``threading.local()``.
907
+
908
+ Polling
909
+ -------
910
+ Long-running ops (parse/extract/classify/split/process) submit to the
911
+ server with ``X-Async: true`` and poll ``/v1/jobs/{job_id}`` until done.
912
+ Each individual HTTP request is sub-second so the SDK is edge-timeout
913
+ immune. Override the polling cadence per-call:
914
+
915
+ client.extract("scan.pdf", poll_timeout=600, poll_interval=5)
916
+
917
+ Or globally on the constructor (defaults match the platform playground).
918
+ """
919
+
920
+ def __init__(
921
+ self,
922
+ api_key: str | None = None,
923
+ base_url: str | None = None,
924
+ timeout: float = _DEFAULT_TIMEOUT,
925
+ *,
926
+ poll_interval: float = _DEFAULT_POLL_INTERVAL_S,
927
+ poll_timeout: float = _DEFAULT_POLL_TIMEOUT_S,
928
+ poll_max_transient_retries: int = _DEFAULT_POLL_MAX_TRANSIENT_RETRIES,
929
+ poll_transient_retry_delay: float = _DEFAULT_POLL_TRANSIENT_RETRY_DELAY_S,
930
+ ):
931
+ """Initialize a HyperAPI client.
932
+
933
+ Args:
934
+ api_key: API key for authentication. Falls back to ``HYPERAPI_KEY``
935
+ environment variable. Required.
936
+ base_url: API base URL. Falls back to ``HYPERAPI_URL`` env var,
937
+ then ``https://apis.hyperbots.com``.
938
+ timeout: Per-HTTP-call timeout in seconds (NOT the total time
939
+ allowed for an entire job — see ``poll_timeout`` for that).
940
+ Default 120 s, which generously covers a single submit or
941
+ a single status poll in normal use.
942
+ poll_interval: Seconds between successive polls of
943
+ ``/v1/jobs/{id}``. Default 3.0 (matches the platform
944
+ playground).
945
+ poll_timeout: Total wall-clock seconds the SDK will wait for a
946
+ single job to complete. Raises ``JobTimeoutError`` past this.
947
+ Default 3600.0 (60 min) — longer than the server-side
948
+ job budget, so an ordinary job finishes or fails before
949
+ the SDK stops waiting.
950
+ poll_max_transient_retries: How many times to retry a single
951
+ ``/v1/jobs/{id}`` (or batch status) GET if it returns 5xx or
952
+ has a connection error. Default 3. Every 4xx fails fast, and
953
+ retries stop once the wait's own timeout has passed.
954
+ poll_transient_retry_delay: Seconds to sleep between transient-retry
955
+ attempts on a single poll. Default 0.5; bump this if your
956
+ network is bursty enough that 3 retries in 1.5 s isn't enough
957
+ breathing room.
958
+ """
959
+ self._api_key = _clean_api_key(api_key or os.environ.get("HYPERAPI_KEY"))
960
+
961
+ self.base_url = _resolve_base_url(base_url)
962
+ self.timeout = timeout
963
+ self._poll_interval = poll_interval
964
+ self._poll_timeout = poll_timeout
965
+ self._poll_max_transient_retries = poll_max_transient_retries
966
+ self._poll_transient_retry_delay = poll_transient_retry_delay
967
+
968
+ from . import __version__ # local import to avoid circular at module load
969
+
970
+ # User-Agent includes the httpx + Python versions so server-side analytics
971
+ # and customer firewalls can identify the underlying HTTP stack + runtime
972
+ # without sniffing other headers. Format mirrors the de-facto convention
973
+ # popularized by the OpenAI / Stripe SDKs.
974
+ py_ver = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
975
+ self._user_agent = (
976
+ f"hyperapi-sdk-python/{__version__} "
977
+ f"(httpx/{httpx.__version__}; Python/{py_ver})"
978
+ )
979
+ self._client = httpx.Client(
980
+ timeout=timeout,
981
+ headers={"User-Agent": self._user_agent},
982
+ )
983
+
984
+ @property
985
+ def api_key(self) -> str:
986
+ """The API key this client sends (read-only; whitespace-stripped)."""
987
+ return self._api_key
988
+
989
+ # ── Repr ─────────────────────────────────────────────────────────────
990
+
991
+ def __repr__(self) -> str:
992
+ tail = self._api_key[-4:]
993
+ return f"HyperAPIClient(api_key='hk_***{tail}', base_url='{self.base_url}')"
994
+
995
+ # ── Headers ──────────────────────────────────────────────────────────
996
+
997
+ def _get_headers(self, *, async_mode: bool = False) -> dict[str, str]:
998
+ """Per-request headers. Generates a fresh X-Request-ID per call so
999
+ every request can be correlated end-to-end across the platform."""
1000
+ headers = {
1001
+ "X-API-Key": self._api_key,
1002
+ "X-Request-ID": str(uuid.uuid4()),
1003
+ }
1004
+ if async_mode:
1005
+ headers["X-Async"] = "true"
1006
+ return headers
1007
+
1008
+ # ── Path helpers ─────────────────────────────────────────────────────
1009
+
1010
+ def _resolve_path(
1011
+ self,
1012
+ file_path: str | Path | None,
1013
+ image_path: str | Path | None = None,
1014
+ ) -> Path:
1015
+ """Resolve and validate file path."""
1016
+ raw = file_path or image_path
1017
+ if raw is None:
1018
+ raise ValueError("file_path is required")
1019
+ path = Path(raw)
1020
+ if not path.exists():
1021
+ raise FileNotFoundError(f"File not found: {path}")
1022
+ return path
1023
+
1024
+ # ── Upload ───────────────────────────────────────────────────────────
1025
+
1026
+ def upload_document(
1027
+ self,
1028
+ file_path: str | Path,
1029
+ content_type: str | None = None,
1030
+ ) -> str:
1031
+ """Upload a document via the presigned-URL flow and return its document_key.
1032
+
1033
+ Performs the two HTTP hops (presigned-URL fetch + S3 PUT) so the
1034
+ returned ``document_key`` can be reused across subsequent calls
1035
+ without re-uploading the file.
1036
+
1037
+ Args:
1038
+ file_path: Path to the file to upload.
1039
+ content_type: MIME type. Auto-detected from the extension if omitted.
1040
+
1041
+ Returns:
1042
+ The ``document_key`` to pass to inference endpoints.
1043
+
1044
+ Raises:
1045
+ FileNotFoundError: If the file does not exist.
1046
+ ValueError: If the path is not a regular file (a directory, pipe or device).
1047
+ AuthenticationError: 401 from the server.
1048
+ DocumentUploadError: Any other failure on the presigned fetch or S3 PUT,
1049
+ including a presigned URL that is not https.
1050
+ """
1051
+ path = _regular_file(file_path)
1052
+
1053
+ if content_type is None:
1054
+ content_type = CONTENT_TYPES.get(
1055
+ path.suffix.lower(), "application/octet-stream"
1056
+ )
1057
+
1058
+ headers = self._get_headers()
1059
+ request_id = headers["X-Request-ID"]
1060
+
1061
+ # Send the file size so the server can pre-flight the size limit and
1062
+ # reject oversized files with a 413 here, before the S3 PUT, instead of
1063
+ # failing later at the PUT. Best-effort: skipped if stat() fails.
1064
+ body: dict[str, object] = {"filename": path.name, "content_type": content_type}
1065
+ try:
1066
+ body["content_length"] = path.stat().st_size
1067
+ except OSError:
1068
+ pass
1069
+
1070
+ # Step 1 — request an authenticated presigned upload URL.
1071
+ try:
1072
+ resp = self._client.post(
1073
+ f"{self.base_url}/v1/documents/upload",
1074
+ json=body,
1075
+ headers=headers,
1076
+ )
1077
+ except httpx.RequestError as e:
1078
+ raise DocumentUploadError(
1079
+ f"Failed to get upload URL: {e}", request_id=request_id
1080
+ ) from None
1081
+
1082
+ self._raise_for_known_status(
1083
+ resp,
1084
+ request_id=request_id,
1085
+ error_cls=DocumentUploadError,
1086
+ op_name="upload",
1087
+ )
1088
+ if resp.status_code != 200:
1089
+ raise DocumentUploadError(
1090
+ _server_message(resp, "Upload URL request failed"),
1091
+ status_code=resp.status_code,
1092
+ request_id=_request_id_of(resp, request_id),
1093
+ )
1094
+
1095
+ upload_data = _json_object(
1096
+ resp,
1097
+ request_id=_request_id_of(resp, request_id),
1098
+ error_cls=DocumentUploadError,
1099
+ required=("document_key", "upload_url"),
1100
+ what="upload-URL",
1101
+ )
1102
+ document_key = upload_data["document_key"]
1103
+ upload_url = upload_data["upload_url"]
1104
+ _check_server_url(
1105
+ upload_url,
1106
+ base_url=self.base_url,
1107
+ what="presigned upload URL",
1108
+ error_cls=DocumentUploadError,
1109
+ )
1110
+
1111
+ # Step 2 — upload bytes directly to object storage using the signed URL.
1112
+ try:
1113
+ with open(path, "rb") as f:
1114
+ s3_resp = self._client.put(
1115
+ upload_url,
1116
+ content=f.read(),
1117
+ headers={
1118
+ "Content-Type": content_type,
1119
+ "x-amz-server-side-encryption": "AES256",
1120
+ },
1121
+ )
1122
+ except httpx.RequestError as e:
1123
+ raise DocumentUploadError(
1124
+ f"S3 upload failed: {e}", request_id=request_id
1125
+ ) from None
1126
+
1127
+ if s3_resp.status_code not in (200, 204):
1128
+ raise DocumentUploadError(
1129
+ f"S3 PUT failed (status {s3_resp.status_code}). "
1130
+ "Ensure x-amz-server-side-encryption: AES256 is present.",
1131
+ status_code=s3_resp.status_code,
1132
+ request_id=request_id,
1133
+ )
1134
+
1135
+ logger.info(
1136
+ "document_uploaded",
1137
+ extra={"request_id": request_id, "document_key": document_key},
1138
+ )
1139
+ return document_key
1140
+
1141
+ # ── Limits ───────────────────────────────────────────────────────────
1142
+
1143
+ def get_limits(self) -> dict:
1144
+ """This key's per-task ceilings (``GET /v1/limits``) — a pure read.
1145
+
1146
+ Limits vary by plan, so pre-flight against this rather than hard-coding
1147
+ a number. The response is::
1148
+
1149
+ {
1150
+ "max_upload_bytes": int, # what upload itself admits
1151
+ "parse_fast": {"max_bytes": int, "max_pages": int | None},
1152
+ "parse_advanced": {"max_bytes": int, "max_pages": int | None},
1153
+ "bulk_parse": {...}, # only when offered to you
1154
+ "extract_fast": {...},
1155
+ "extract_advanced":{...}, # only when offered to you
1156
+ "classify": {...},
1157
+ "split": {...},
1158
+ "redact": {"max_bytes": int, "max_pages": int | None,
1159
+ "urls_max_pages": int | None}
1160
+ }
1161
+
1162
+ ``max_pages`` is ``None`` where the task does not reject on page
1163
+ count. The optional blocks (``bulk_parse``, ``extract_advanced``) are
1164
+ absent when that mode is not available to this key — absent means
1165
+ "not offered", never "unlimited". Likewise ``redact.urls_max_pages``
1166
+ is present only while ``output="urls"`` is accepted; its presence is
1167
+ the feature detection for that mode (see :py:meth:`submit_redact`).
1168
+
1169
+ Returns:
1170
+ The decoded JSON body as a dict.
1171
+
1172
+ Raises:
1173
+ AuthenticationError: 401 (bad key).
1174
+ RateLimitError: 429.
1175
+ HyperAPIError: Any other ≥400, or a malformed body.
1176
+ """
1177
+ headers = self._get_headers()
1178
+ request_id = headers["X-Request-ID"]
1179
+
1180
+ try:
1181
+ resp = self._client.get(f"{self.base_url}/v1/limits", headers=headers)
1182
+ except httpx.RequestError as e:
1183
+ raise HyperAPIError(f"Limits request failed: {e}", request_id=request_id) from None
1184
+
1185
+ rid = _request_id_of(resp, request_id)
1186
+ if resp.status_code == 401:
1187
+ raise AuthenticationError(
1188
+ "Invalid API key.", status_code=401, request_id=rid
1189
+ )
1190
+ if resp.status_code == 429:
1191
+ raise _rate_limit_error_from(resp, rid)
1192
+ if resp.status_code >= 400:
1193
+ raise HyperAPIError(
1194
+ _server_message(resp, f"Limits request failed (HTTP {resp.status_code})"),
1195
+ status_code=resp.status_code,
1196
+ request_id=rid,
1197
+ **_error_fields(resp),
1198
+ )
1199
+ try:
1200
+ body = resp.json()
1201
+ if not isinstance(body, dict):
1202
+ raise TypeError(f"body is {type(body).__name__}, expected object")
1203
+ return body
1204
+ except (json.JSONDecodeError, ValueError, TypeError) as e:
1205
+ raise HyperAPIError(
1206
+ f"Malformed limits response: {e}",
1207
+ status_code=200,
1208
+ request_id=rid,
1209
+ ) from e
1210
+
1211
+ # ── HTTP error classification ────────────────────────────────────────
1212
+
1213
+ def _raise_for_known_status(
1214
+ self,
1215
+ resp: httpx.Response,
1216
+ *,
1217
+ request_id: str | None,
1218
+ error_cls: type,
1219
+ op_name: str,
1220
+ ) -> None:
1221
+ """Raise the appropriate typed exception for well-known HTTP statuses.
1222
+
1223
+ Returns silently for 200/202 (success) and any other status that the
1224
+ caller wants to handle explicitly.
1225
+ """
1226
+ sc = resp.status_code
1227
+ rid = _request_id_of(resp, request_id)
1228
+
1229
+ if sc == 401:
1230
+ # Keep the message portable across hosted and self-hosted deployments.
1231
+ raise AuthenticationError(
1232
+ f"Invalid API key for {self.base_url}. "
1233
+ "Check your HyperAPI dashboard for the correct key.",
1234
+ status_code=401,
1235
+ request_id=rid,
1236
+ )
1237
+ if sc == 402:
1238
+ raise error_cls(
1239
+ f"Insufficient credits for {self.base_url}. "
1240
+ "Add credits via your HyperAPI dashboard.",
1241
+ status_code=402,
1242
+ request_id=rid,
1243
+ **_error_fields(resp),
1244
+ )
1245
+ if sc == 429:
1246
+ raise _rate_limit_error_from(resp, rid)
1247
+ if sc == 413:
1248
+ # Two different refusals share this status. On the upload endpoint
1249
+ # it is the file-size ceiling (error_cls is DocumentUploadError
1250
+ # there). On an operation endpoint it is that operation's page
1251
+ # cap, so it is raised as the operation's own error class.
1252
+ fallback = (
1253
+ "File exceeds upload size limit"
1254
+ if error_cls is DocumentUploadError
1255
+ else f"Document exceeds the page or size limit for {op_name}"
1256
+ )
1257
+ raise error_cls(
1258
+ _server_message(resp, fallback),
1259
+ status_code=413,
1260
+ request_id=rid,
1261
+ **_error_fields(resp),
1262
+ )
1263
+ if sc == 415:
1264
+ raise DocumentUploadError(
1265
+ _server_message(resp, "Unsupported file type"),
1266
+ status_code=415,
1267
+ request_id=rid,
1268
+ **_error_fields(resp),
1269
+ )
1270
+ if sc == 408:
1271
+ raise error_cls(
1272
+ _server_message(resp, "Service deadline exceeded"),
1273
+ status_code=408,
1274
+ request_id=rid,
1275
+ **_error_fields(resp),
1276
+ )
1277
+ if sc == 403:
1278
+ raise HyperAPIError(
1279
+ _server_message(resp, "Forbidden"),
1280
+ status_code=403,
1281
+ request_id=rid,
1282
+ **_error_fields(resp),
1283
+ )
1284
+
1285
+ # ── Async submission (X-Async: true) ─────────────────────────────────
1286
+
1287
+ def _submit_via_path(
1288
+ self,
1289
+ endpoint: str,
1290
+ op_name: str,
1291
+ file_path: Path,
1292
+ *,
1293
+ params: dict[str, Any],
1294
+ use_presigned: bool,
1295
+ force_refresh: bool = False,
1296
+ data: dict[str, Any] | None = None,
1297
+ timeout: float | None = None,
1298
+ ) -> Job:
1299
+ """Submit a pipeline op asynchronously. Returns a Job handle.
1300
+
1301
+ ``force_refresh=True`` adds ``?force_refresh=true``, which makes the
1302
+ API reprocess the document instead of returning the stored result
1303
+ (results are kept for 24 hours). Without it an identical (document +
1304
+ task + params) returns the STORED result, so a retry can look like a
1305
+ no-op. Only send it when the caller explicitly asked to re-run: a
1306
+ reprocess is billed at full price, where a stored result costs nothing.
1307
+
1308
+ Omitted entirely when False so an ordinary request is byte-identical to
1309
+ before this parameter existed.
1310
+
1311
+ ``data`` carries extra form fields beyond ``document_key`` (e.g. redact's
1312
+ ``pii_config``), sent in the form body alongside ``document_key``.
1313
+
1314
+ The op always uploads via the presigned-S3 flow: the API has no
1315
+ direct-upload path and only accepts a ``document_key``. ``use_presigned``
1316
+ is retained for backward compatibility; ``use_presigned=False`` emits a
1317
+ ``DeprecationWarning`` and falls back to the presigned flow.
1318
+ """
1319
+ request_timeout = timeout or self.timeout
1320
+ error_cls = _OP_TO_ERROR[op_name]
1321
+ content_type = CONTENT_TYPES.get(
1322
+ file_path.suffix.lower(), "application/octet-stream"
1323
+ )
1324
+ headers = self._get_headers(async_mode=True)
1325
+ request_id = headers["X-Request-ID"]
1326
+ extra_form = data or {}
1327
+
1328
+ if not use_presigned:
1329
+ warnings.warn(
1330
+ "use_presigned=False is no longer supported: the API has no "
1331
+ "direct-upload path and only accepts a presigned document_key. "
1332
+ "Falling back to the presigned upload flow.",
1333
+ DeprecationWarning,
1334
+ stacklevel=2,
1335
+ )
1336
+
1337
+ try:
1338
+ document_key = self.upload_document(file_path, content_type=content_type)
1339
+ response = self._client.post(
1340
+ f"{self.base_url}{endpoint}",
1341
+ data={"document_key": document_key, **extra_form},
1342
+ params={**params, "force_refresh": "true"} if force_refresh else params,
1343
+ headers=headers,
1344
+ timeout=request_timeout,
1345
+ )
1346
+ except httpx.TimeoutException:
1347
+ raise error_cls(
1348
+ "Request timed out",
1349
+ status_code=504,
1350
+ request_id=request_id,
1351
+ ) from None
1352
+ except httpx.RequestError as e:
1353
+ raise error_cls(f"Request failed: {e}", request_id=request_id) from None
1354
+
1355
+ self._raise_for_known_status(
1356
+ response, request_id=request_id, error_cls=error_cls, op_name=op_name
1357
+ )
1358
+ if response.status_code not in (200, 202):
1359
+ raise error_cls(
1360
+ _server_message(response, f"{op_name} submission failed"),
1361
+ status_code=response.status_code,
1362
+ request_id=_request_id_of(response, request_id),
1363
+ **_error_fields(response),
1364
+ )
1365
+
1366
+ return self._job_from_envelope(
1367
+ self._submit_reply(response, request_id, error_cls, op_name), op=op_name
1368
+ )
1369
+
1370
+ def _submit_via_doc_key(
1371
+ self,
1372
+ endpoint: str,
1373
+ op_name: str,
1374
+ document_key: str,
1375
+ *,
1376
+ params: dict[str, Any],
1377
+ timeout: float | None = None,
1378
+ ) -> Job:
1379
+ """Submit a pipeline op asynchronously when the document_key is already
1380
+ in hand (used by ``process()`` to share one upload between parse + extract)."""
1381
+ request_timeout = timeout or self.timeout
1382
+ error_cls = _OP_TO_ERROR[op_name]
1383
+ headers = self._get_headers(async_mode=True)
1384
+ request_id = headers["X-Request-ID"]
1385
+
1386
+ try:
1387
+ response = self._client.post(
1388
+ f"{self.base_url}{endpoint}",
1389
+ data={"document_key": document_key},
1390
+ params=params,
1391
+ headers=headers,
1392
+ timeout=request_timeout,
1393
+ )
1394
+ except httpx.TimeoutException:
1395
+ raise error_cls(
1396
+ "Request timed out", status_code=504, request_id=request_id
1397
+ ) from None
1398
+ except httpx.RequestError as e:
1399
+ raise error_cls(f"Request failed: {e}", request_id=request_id) from None
1400
+
1401
+ self._raise_for_known_status(
1402
+ response, request_id=request_id, error_cls=error_cls, op_name=op_name
1403
+ )
1404
+ if response.status_code not in (200, 202):
1405
+ raise error_cls(
1406
+ _server_message(response, f"{op_name} submission failed"),
1407
+ status_code=response.status_code,
1408
+ request_id=_request_id_of(response, request_id),
1409
+ **_error_fields(response),
1410
+ )
1411
+
1412
+ return self._job_from_envelope(
1413
+ self._submit_reply(response, request_id, error_cls, op_name), op=op_name
1414
+ )
1415
+
1416
+ @staticmethod
1417
+ def _submit_reply(
1418
+ response: httpx.Response, request_id: str, error_cls: type, op_name: str
1419
+ ) -> dict:
1420
+ """The submit reply as a dict that carries a ``job_id``, or ``error_cls``."""
1421
+ return _json_object(
1422
+ response,
1423
+ request_id=_request_id_of(response, request_id),
1424
+ error_cls=error_cls,
1425
+ required=("job_id",),
1426
+ what=f"{op_name} submission",
1427
+ )
1428
+
1429
+ @staticmethod
1430
+ def _job_from_envelope(envelope: dict, *, op: str) -> Job:
1431
+ return Job(
1432
+ job_id=envelope["job_id"],
1433
+ status=envelope.get("status", "pending"),
1434
+ poll_url=envelope.get(
1435
+ "poll_url", f"/v1/jobs/{_path_id(envelope['job_id'], name='job_id')}"
1436
+ ),
1437
+ op=op,
1438
+ )
1439
+
1440
+ # ── Polling ──────────────────────────────────────────────────────────
1441
+
1442
+ def get_job(self, job_id: str) -> dict:
1443
+ """Single-shot poll. No retry, no waiting. Raises on 4xx; returns the
1444
+ raw envelope on 200 (``{status, result?, error?, ...}``)."""
1445
+ headers = self._get_headers()
1446
+ request_id = headers["X-Request-ID"]
1447
+
1448
+ try:
1449
+ resp = self._client.get(
1450
+ f"{self.base_url}/v1/jobs/{_path_id(job_id, name='job_id')}",
1451
+ headers=headers,
1452
+ )
1453
+ except httpx.RequestError as e:
1454
+ raise HyperAPIError(f"Job poll failed: {e}", request_id=request_id) from None
1455
+
1456
+ rid = _request_id_of(resp, request_id)
1457
+ if resp.status_code == 401:
1458
+ raise AuthenticationError(
1459
+ "Invalid API key.", status_code=401, request_id=rid
1460
+ )
1461
+ if resp.status_code == 404:
1462
+ raise HyperAPIError(
1463
+ "Job not found or expired.",
1464
+ status_code=404,
1465
+ request_id=rid,
1466
+ )
1467
+ if resp.status_code == 429:
1468
+ # Surface poll-time and submit-time 429 responses consistently.
1469
+ raise _rate_limit_error_from(resp, rid)
1470
+ if resp.status_code >= 400:
1471
+ raise HyperAPIError(
1472
+ _server_message(resp, f"Poll failed (HTTP {resp.status_code})"),
1473
+ status_code=resp.status_code,
1474
+ request_id=rid,
1475
+ **_error_fields(resp),
1476
+ )
1477
+ # Defend against a 200 with malformed JSON — some misconfigured proxies will
1478
+ # return text/html bodies on 200. Without this guard, a JSONDecodeError
1479
+ # escapes to the caller as an un-typed exception.
1480
+ return _json_object(resp, request_id=rid, what="job-status")
1481
+
1482
+ # ── Jobs management ──────────────────────────────────────────────────
1483
+
1484
+ def list_recent_jobs(
1485
+ self,
1486
+ *,
1487
+ limit: int = 20,
1488
+ source: str | None = None,
1489
+ ) -> list[dict]:
1490
+ """List the org's recent jobs (summary rows, newest first).
1491
+
1492
+ Args:
1493
+ limit: Maximum rows to return. Valid range [1, 100]; out-of-range
1494
+ values are NOT clamped — the server silently falls back to
1495
+ the default 20 (e.g. ``limit=200`` returns 20 rows, not 100).
1496
+ source: Optional filter — ``"api"`` or ``"playground"``. Unknown
1497
+ values are ignored server-side (no error).
1498
+
1499
+ Returns:
1500
+ A list of summary dicts (``job_id``, ``request_id``, ``status``,
1501
+ ``task``, ``endpoint``, ``pages``, ``filename``, ``document_key``,
1502
+ ``source``, ``is_test``, ``created_at``, ``completed_at``,
1503
+ ``error``).
1504
+ ``status`` may be ``"cancelled"`` for jobs stopped via
1505
+ :py:meth:`delete_job`. Summaries never include results — fetch
1506
+ the full envelope for one job with :py:meth:`get_job`.
1507
+
1508
+ ``document_key`` is the server-side handle for that job's
1509
+ document, and is what to match on when reconciling a batch —
1510
+ ``filename`` is whatever was sent at upload and carries no
1511
+ uniqueness guarantee, so fifty documents named ``invoice.pdf``
1512
+ yield fifty rows you cannot tell apart. Note that ``submit_*``
1513
+ uploads internally and does not surface the ``document_key`` it
1514
+ used, and no public method accepts a pre-uploaded one, so retain
1515
+ the ``job_id`` if you need your own file→job map. ``None`` on older
1516
+ jobs.
1517
+ """
1518
+ headers = self._get_headers()
1519
+ request_id = headers["X-Request-ID"]
1520
+ params: dict[str, Any] = {"limit": limit}
1521
+ if source is not None:
1522
+ params["source"] = source
1523
+
1524
+ try:
1525
+ resp = self._client.get(
1526
+ f"{self.base_url}/v1/jobs/recent", params=params, headers=headers
1527
+ )
1528
+ except httpx.RequestError as e:
1529
+ raise HyperAPIError(
1530
+ f"Recent-jobs request failed: {e}", request_id=request_id
1531
+ ) from None
1532
+
1533
+ rid = _request_id_of(resp, request_id)
1534
+ if resp.status_code == 401:
1535
+ raise AuthenticationError(
1536
+ "Invalid API key.", status_code=401, request_id=rid
1537
+ )
1538
+ if resp.status_code == 429:
1539
+ raise _rate_limit_error_from(resp, rid)
1540
+ if resp.status_code >= 400:
1541
+ raise HyperAPIError(
1542
+ _server_message(
1543
+ resp, f"Recent-jobs request failed (HTTP {resp.status_code})"
1544
+ ),
1545
+ status_code=resp.status_code,
1546
+ request_id=rid,
1547
+ )
1548
+ # Same malformed-200 defence as get_job, plus envelope-shape guard:
1549
+ # the contract is {"jobs": [...]} — anything else is a broken proxy.
1550
+ try:
1551
+ jobs = resp.json()["jobs"]
1552
+ if not isinstance(jobs, list):
1553
+ raise TypeError(f"'jobs' is {type(jobs).__name__}, expected list")
1554
+ return jobs
1555
+ except (json.JSONDecodeError, ValueError, KeyError, TypeError) as e:
1556
+ raise HyperAPIError(
1557
+ f"Malformed recent-jobs response: {e}",
1558
+ status_code=200,
1559
+ request_id=rid,
1560
+ ) from e
1561
+
1562
+ def delete_job(self, job_id: str) -> None:
1563
+ """Cancel a job (``DELETE /v1/jobs/{job_id}``).
1564
+
1565
+ Despite the HTTP verb, the server semantics are *cancel*, not erase:
1566
+ a pending or running job is stopped; a job that already completed or
1567
+ failed is left untouched and keeps its result. Idempotent — missing,
1568
+ expired, and already-terminal job ids all return success, so calling
1569
+ this twice is safe.
1570
+
1571
+ How a cancelled job reports afterwards: ``GET /v1/jobs/{job_id}``
1572
+ (:py:meth:`get_job`) returns ``status="failed"`` with an ``error``
1573
+ beginning ``"cancelled:"`` — there is no separate ``"cancelled"``
1574
+ status on the job itself. :py:meth:`wait_for_job` and
1575
+ :py:meth:`wait_for_jobs` decode that and raise
1576
+ :class:`~hyperapi.JobCancelledError` rather than the per-op failure
1577
+ class. The summaries from :py:meth:`list_recent_jobs` do show such
1578
+ jobs as ``status="cancelled"``.
1579
+
1580
+ Raises:
1581
+ AuthenticationError: 401 (bad key).
1582
+ HyperAPIError: 404 (job belongs to a different org), or any other
1583
+ ≥400. A missing/expired job is *not* a 404 here — DELETE is
1584
+ idempotent and returns 204 (success) for ids that no longer
1585
+ exist; the only 404 is a cross-org id.
1586
+ """
1587
+ headers = self._get_headers()
1588
+ request_id = headers["X-Request-ID"]
1589
+
1590
+ try:
1591
+ resp = self._client.delete(
1592
+ f"{self.base_url}/v1/jobs/{_path_id(job_id, name='job_id')}",
1593
+ headers=headers,
1594
+ )
1595
+ except httpx.RequestError as e:
1596
+ raise HyperAPIError(f"Job cancel failed: {e}", request_id=request_id) from None
1597
+
1598
+ rid = _request_id_of(resp, request_id)
1599
+ if resp.status_code in (200, 204):
1600
+ return
1601
+ if resp.status_code == 401:
1602
+ raise AuthenticationError(
1603
+ "Invalid API key.", status_code=401, request_id=rid
1604
+ )
1605
+ if resp.status_code == 404:
1606
+ # On DELETE, a 404 means the job belongs to a different org
1607
+ # (opaque enumeration guard). Missing/expired ids short-circuit to
1608
+ # 204 above, so they never reach here.
1609
+ raise HyperAPIError(
1610
+ "Job not found.",
1611
+ status_code=404,
1612
+ request_id=rid,
1613
+ )
1614
+ if resp.status_code == 429:
1615
+ raise _rate_limit_error_from(resp, rid)
1616
+ raise HyperAPIError(
1617
+ _server_message(resp, f"Job cancel failed (HTTP {resp.status_code})"),
1618
+ status_code=resp.status_code,
1619
+ request_id=rid,
1620
+ )
1621
+
1622
+ def _retry_transient(
1623
+ self,
1624
+ fetch: Callable[[], dict],
1625
+ *,
1626
+ kind: str,
1627
+ ident: str,
1628
+ deadline: float | None = None,
1629
+ start: float | None = None,
1630
+ ) -> dict:
1631
+ """Run one status poll, retrying transient failures (network errors, 5xx).
1632
+
1633
+ Every 4xx fails fast (401, 403, 404, 400, 422, ...), as does a 429 —
1634
+ the wait loops handle rate limits themselves. Retries stop at
1635
+ ``poll_max_transient_retries`` and never run past ``deadline``: once it
1636
+ has passed, :class:`JobTimeoutError` is raised instead.
1637
+ """
1638
+ attempt = 0
1639
+ while True:
1640
+ try:
1641
+ return fetch()
1642
+ except (AuthenticationError, RateLimitError):
1643
+ raise
1644
+ except HyperAPIError as e:
1645
+ time.sleep(
1646
+ _transient_delay(
1647
+ e,
1648
+ attempt=attempt,
1649
+ max_retries=self._poll_max_transient_retries,
1650
+ delay=self._poll_transient_retry_delay,
1651
+ deadline=deadline,
1652
+ kind=kind,
1653
+ ident=ident,
1654
+ start=start,
1655
+ )
1656
+ )
1657
+ attempt += 1
1658
+
1659
+ def _poll_with_retry(
1660
+ self, job_id: str, *, deadline: float | None = None, start: float | None = None
1661
+ ) -> dict:
1662
+ """One job poll with the transient-retry policy of :meth:`_retry_transient`."""
1663
+ return self._retry_transient(
1664
+ lambda: self.get_job(job_id),
1665
+ kind="Job",
1666
+ ident=job_id,
1667
+ deadline=deadline,
1668
+ start=start,
1669
+ )
1670
+
1671
+ def wait_for_job(
1672
+ self,
1673
+ job: Job | str,
1674
+ *,
1675
+ timeout: float | None = None,
1676
+ interval: float | None = None,
1677
+ ) -> dict:
1678
+ """Poll a job until it completes, fails, or the timeout elapses.
1679
+
1680
+ Args:
1681
+ job: A :py:class:`Job` returned by ``submit_<op>`` (preferred — the
1682
+ ``op`` field lets us raise the right typed exception on
1683
+ failure), or a raw ``job_id`` string (falls back to generic
1684
+ ``HyperAPIError`` on failure).
1685
+ timeout: Total wall-clock seconds. Defaults to the constructor's
1686
+ ``poll_timeout``.
1687
+ interval: Seconds between polls. Defaults to the constructor's
1688
+ ``poll_interval``.
1689
+
1690
+ Returns:
1691
+ The final ``result`` envelope from the server when ``status=completed``.
1692
+
1693
+ Raises:
1694
+ JobTimeoutError: If ``timeout`` elapses with the job still pending.
1695
+ JobCancelledError: If the job was cancelled via
1696
+ :py:meth:`delete_job` while this call was waiting (the job
1697
+ reports ``status=failed`` with an ``error`` beginning
1698
+ ``"cancelled:"``; this is decoded for you).
1699
+ RateLimitError: If a poll is answered with a 429 that this call
1700
+ cannot wait out — either ``retry_after`` exceeds the remaining
1701
+ budget, or the 429 is an exhausted monthly page quota
1702
+ (``e.is_quota_exhausted``), which waiting would not clear.
1703
+ Ordinary rate-window 429s are absorbed by backing off.
1704
+ HyperAPIError (or subclass): If the job ends with ``status=failed``,
1705
+ or the poll itself fails after exhausting transient retries.
1706
+ """
1707
+ if isinstance(job, Job):
1708
+ job_id = job.job_id
1709
+ op = job.op
1710
+ # Use the Job's actual submission time so JobTimeoutError reports
1711
+ # total time-since-submit, not just the wait_for_job loop duration.
1712
+ # Useful when callers persist a Job and call wait_for_job later.
1713
+ start = job.submitted_at
1714
+ else:
1715
+ job_id = job
1716
+ op = "unknown"
1717
+ start = time.monotonic()
1718
+
1719
+ # Don't compute elapsed from `deadline - (timeout or self._poll_timeout)`
1720
+ # — `or` treats timeout=0 as falsy and silently swaps in the constructor.
1721
+ loop_start = time.monotonic()
1722
+ budget = timeout if timeout is not None else self._poll_timeout
1723
+ deadline = loop_start + budget
1724
+ wait_s = interval if interval is not None else self._poll_interval
1725
+
1726
+ while True:
1727
+ try:
1728
+ envelope = self._poll_with_retry(
1729
+ job_id, deadline=deadline, start=start
1730
+ )
1731
+ except RateLimitError as e:
1732
+ # Status polls have their own per-organization limit, but a
1733
+ # very large number of concurrently polled jobs can still be
1734
+ # throttled. Back off and resume within the deadline instead
1735
+ # of failing the wait.
1736
+ wait = _rate_limit_wait(e, deadline - time.monotonic())
1737
+ if wait is None:
1738
+ raise
1739
+ logger.info(
1740
+ "poll_rate_limited",
1741
+ extra={
1742
+ "job_id": job_id,
1743
+ "retry_after": wait,
1744
+ "degraded": e.degraded,
1745
+ },
1746
+ )
1747
+ time.sleep(wait)
1748
+ continue
1749
+ status = envelope.get("status")
1750
+ if status == "completed":
1751
+ logger.info(
1752
+ "job_completed",
1753
+ extra={
1754
+ "job_id": job_id,
1755
+ "op": op,
1756
+ "duration_ms": envelope.get("duration_ms"),
1757
+ },
1758
+ )
1759
+ # Return only the `result` payload — never the raw envelope,
1760
+ # which carries server-side status/timing/receipt fields. Coerce
1761
+ # a missing/null result to {} so the return is always a dict:
1762
+ # `.get("result")` never hits None (a bare `["result"]` still
1763
+ # KeyErrors, but never the old None TypeError). Matches wait_for_jobs.
1764
+ res = envelope.get("result")
1765
+ return res if isinstance(res, dict) else {}
1766
+ if status == "failed":
1767
+ raise self._exception_for_failed_job(op, envelope, job_id)
1768
+
1769
+ if time.monotonic() >= deadline:
1770
+ raise JobTimeoutError(
1771
+ (
1772
+ f"Job {job_id} did not complete within {budget}s. "
1773
+ "Pass a larger poll_timeout or use submit_<op>+wait_for_job "
1774
+ "to manage polling yourself."
1775
+ ),
1776
+ job_id=job_id,
1777
+ elapsed_s=time.monotonic() - start,
1778
+ )
1779
+
1780
+ # Sleep, but never past the deadline.
1781
+ remaining = deadline - time.monotonic()
1782
+ time.sleep(min(wait_s, max(0.0, remaining)))
1783
+
1784
+ def wait_for_jobs(
1785
+ self,
1786
+ jobs: Iterable[Job],
1787
+ *,
1788
+ timeout: float | None = None,
1789
+ interval: float | None = None,
1790
+ ) -> list[dict]:
1791
+ """Poll multiple jobs concurrently (round-robin).
1792
+
1793
+ Returns the results in the same order as ``jobs``. Single shared
1794
+ deadline. Raises on the first failed job (other in-flight jobs continue
1795
+ running on the server but are abandoned by the SDK). Useful for
1796
+ ``process()`` to collapse parse + extract polling overhead.
1797
+ """
1798
+ jobs_list = list(jobs)
1799
+ if not jobs_list:
1800
+ return []
1801
+
1802
+ start = time.monotonic()
1803
+ budget = timeout if timeout is not None else self._poll_timeout
1804
+ deadline = start + budget
1805
+ wait_s = interval if interval is not None else self._poll_interval
1806
+ # Placeholder `{}` (not None) means "completed, but the server's result envelope
1807
+ # was empty" — preserves order in the returned list. The loop only exits when
1808
+ # every index has been written, so we never return more or fewer entries than
1809
+ # the input.
1810
+ results: list[dict] = [{} for _ in jobs_list]
1811
+ pending: list[int] = list(range(len(jobs_list)))
1812
+
1813
+ while pending:
1814
+ still_pending: list[int] = []
1815
+ rate_limited = False
1816
+ for pos, idx in enumerate(pending):
1817
+ try:
1818
+ envelope = self._poll_with_retry(
1819
+ jobs_list[idx].job_id, deadline=deadline, start=start
1820
+ )
1821
+ except RateLimitError as e:
1822
+ # Every poll here draws on the same per-organization poll
1823
+ # limit: one 429 means the window is spent for all of them
1824
+ # this pass. Sleep Retry-After once, keep this and all
1825
+ # not-yet-polled jobs pending, and retry.
1826
+ wait = _rate_limit_wait(e, deadline - time.monotonic())
1827
+ if wait is None:
1828
+ raise
1829
+ logger.info(
1830
+ "poll_rate_limited",
1831
+ extra={
1832
+ "job_id": jobs_list[idx].job_id,
1833
+ "retry_after": wait,
1834
+ "degraded": e.degraded,
1835
+ },
1836
+ )
1837
+ time.sleep(wait)
1838
+ still_pending.extend(pending[pos:])
1839
+ rate_limited = True
1840
+ break
1841
+ status = envelope.get("status")
1842
+ if status == "completed":
1843
+ # Return only the `result` payload (never the raw envelope,
1844
+ # which carries status/timing/receipt fields); coerce a
1845
+ # missing/null result to {} to preserve list position.
1846
+ res = envelope.get("result")
1847
+ results[idx] = res if isinstance(res, dict) else {}
1848
+ elif status == "failed":
1849
+ raise self._exception_for_failed_job(
1850
+ jobs_list[idx].op, envelope, jobs_list[idx].job_id
1851
+ )
1852
+ else:
1853
+ still_pending.append(idx)
1854
+ pending = still_pending
1855
+
1856
+ if not pending:
1857
+ break
1858
+ if time.monotonic() >= deadline:
1859
+ pending_ids = ",".join(jobs_list[i].job_id for i in pending)
1860
+ raise JobTimeoutError(
1861
+ f"Jobs [{pending_ids}] did not complete within {budget}s.",
1862
+ job_id=pending_ids,
1863
+ elapsed_s=time.monotonic() - start,
1864
+ )
1865
+ if rate_limited:
1866
+ # Already slept Retry-After above; don't double-sleep the poll gap.
1867
+ continue
1868
+ remaining = deadline - time.monotonic()
1869
+ time.sleep(min(wait_s, max(0.0, remaining)))
1870
+
1871
+ # results is already in input-order; never filter — the input length is the
1872
+ # output length, always.
1873
+ return results
1874
+
1875
+ def _exception_for_failed_job(
1876
+ self, op: str, envelope: dict, job_id: str
1877
+ ) -> HyperAPIError:
1878
+ """Build the right typed exception for a ``status: failed`` envelope.
1879
+
1880
+ The op-to-class registry returns the per-op subclass when known
1881
+ (``ParseError``, ``ExtractError``, …) and falls back to
1882
+ ``HyperAPIError`` for raw-job-id calls where we couldn't determine
1883
+ which op originated the job. The HTTP status (if present in the
1884
+ envelope's ``status_code``) is prefixed onto the message so
1885
+ ``str(e)`` is self-describing in support tickets without needing the
1886
+ caller to also surface ``e.status_code``.
1887
+ """
1888
+ cancelled = _cancelled_job_error(envelope, job_id)
1889
+ if cancelled is not None:
1890
+ return cancelled
1891
+ raw = _strip_api_key(envelope.get("error")) or "Job failed"
1892
+ status_code = envelope.get("status_code")
1893
+ message = f"(HTTP {status_code}) {raw}" if status_code else raw
1894
+ cls = _OP_TO_ERROR.get(op, HyperAPIError)
1895
+ return cls(
1896
+ message,
1897
+ status_code=status_code,
1898
+ request_id=envelope.get("request_id"),
1899
+ code=envelope.get("error_code")
1900
+ if isinstance(envelope.get("error_code"), str)
1901
+ else None,
1902
+ )
1903
+
1904
+ # ── Public submit_<op> methods ───────────────────────────────────────
1905
+
1906
+ def submit_parse(
1907
+ self,
1908
+ file_path: str | Path | None = None,
1909
+ *,
1910
+ image_path: str | Path | None = None,
1911
+ mode: ParseMode | None = None,
1912
+ include_boxes: bool | None = None,
1913
+ include_image: bool | None = None,
1914
+ include_layout: bool | None = None,
1915
+ parse_figures: str | None = None,
1916
+ groups_profile: str | None = None,
1917
+ force_refresh: bool = False,
1918
+ use_presigned: bool = True,
1919
+ ) -> Job:
1920
+ """Submit a parse job asynchronously and return immediately.
1921
+
1922
+ ``image_path`` is a deprecated alias for ``file_path`` retained for
1923
+ v0.1.x backward compatibility — pass exactly one. The other
1924
+ ``submit_<op>`` methods don't take it because parse is the only op
1925
+ that historically accepted bare images via that name.
1926
+
1927
+ Omit ``mode`` to use the organization default (platform default:
1928
+ ``"fast"``). ``mode="advanced"`` explicitly runs layout-aware structured OCR: each
1929
+ ``result["result"]["pages"]`` entry gains a ``structured`` dict with ``html``,
1930
+ ``markdown``, and ``regions``. Only meaningful on the default OCR
1931
+ engine; noticeably slower than ``"fast"`` but, for documents under the
1932
+ page cap, well within the default ``poll_timeout``.
1933
+
1934
+ Output flags
1935
+ ------------
1936
+ ``include_boxes``, ``include_image`` and ``include_layout`` are
1937
+ tri-state. **Leave one at ``None`` (the default) and the SDK does not
1938
+ send it, so the API's own default applies — which, in ``"fast"`` mode,
1939
+ is ON for all three.** Pass ``False`` to opt out of that piece of
1940
+ output explicitly; pass ``True`` to ask for it regardless of the
1941
+ server default. Only a flag you set reaches the wire.
1942
+
1943
+ ``include_boxes`` controls, on each entry of ``result["result"]["pages"]``,
1944
+ a ``boxes`` list of line boxes (``{"text", "bbox": [left, top, right,
1945
+ bottom], "confidence"}``) and, for PDF, XPS and image inputs, a
1946
+ ``word_boxes`` list with one entry per word carrying typography:
1947
+ ``font``, ``size`` (in ``page_size["unit"]``), ``color``, ``bold``,
1948
+ ``italic``, ``background`` (only where it differs from the page) and
1949
+ ``font_source`` (``"document"`` when declared by the file's text layer,
1950
+ ``"model"`` when estimated from the pixels, which can be wrong). Keys are
1951
+ omitted when not stated; ``word_boxes`` is ``[]`` when none were
1952
+ produced. Box coordinates are pixels in the page's ``dimensions``
1953
+ space. Office documents (docx, pptx) return ``boxes`` only with page
1954
+ images on; ``mode="advanced"`` returns no boxes.
1955
+
1956
+ PDF, XPS and image pages from ``mode="fast"`` always carry
1957
+ ``dimensions`` (``{"width", "height"}`` in pixels), ``page_size``
1958
+ (``{"width", "height", "unit"}``, ``"pt"`` for PDF/XPS, ``"px"`` for
1959
+ images) and ``background`` (the page's background colour, hex).
1960
+
1961
+ ``include_image`` controls a presigned ``image_url`` on each
1962
+ ``result["result"]["pages"]`` entry, pointing to the deskew-corrected
1963
+ page image (plus ``dimensions`` where the page does not already carry
1964
+ it). The URL is valid for about 15 minutes; a page whose image cannot
1965
+ be presigned is returned without ``image_url`` rather than failing.
1966
+
1967
+ ``include_layout`` (``"fast"`` mode only) controls, per page, ``layout``
1968
+ (the detected regions in reading order, ``bbox`` in the same pixel
1969
+ space as ``boxes``) and ``layout_text``, plus ``result["result"]
1970
+ ["layout_text"]``, the text rebuilt around the regions. ``False`` also
1971
+ turns figure parsing off. ``mode="advanced"`` has its own
1972
+ ``structured`` layout; sending ``include_layout=True`` with it is a
1973
+ ``400``.
1974
+
1975
+ ``parse_figures`` (``"fast"`` mode, needs the layout on) is a
1976
+ comma-separated list of region kinds to parse further — any of
1977
+ ``"image"``, ``"chart"``, ``"table"`` (e.g. ``"table"`` or
1978
+ ``"image,chart,table"``). Each matching region gains ``content`` (a
1979
+ chart's data as a markdown table, an image's caption or text, a table
1980
+ as HTML) and a ``parse_status``; ``result["result"]["figure_parse"]``
1981
+ summarises the run. Best-effort: OCR and layout are returned even when
1982
+ a region cannot be parsed. Omitted, the API parses all three kinds
1983
+ when the layout is on. Pass ``"none"`` to opt out. An explicit list
1984
+ with ``include_layout=False`` is a ``400``.
1985
+
1986
+ ``groups_profile`` (``"fast"`` mode, layout on) selects how the
1987
+ document outline in ``result["result"]["groups"]`` is built: ``"A"``
1988
+ (the API default — every block in exactly one group, the tree in
1989
+ reading order, a ``preamble`` group before the first heading, one
1990
+ ``page_header`` / ``page_footer`` group per page) or ``"B"`` (headings
1991
+ ranked by measured type size, running titles marked ``furniture:
1992
+ true``, captions bound to their figure or table, tables joined across
1993
+ pages, no ``list`` groups; not in reading order — use
1994
+ ``blocks[].order``). Case-insensitive; unknown values are treated as
1995
+ ``"A"``. ``result["result"]["metadata"]["groups_profile"]`` reports the
1996
+ profile applied.
1997
+
1998
+ ``force_refresh=True`` re-runs OCR instead of returning the stored
1999
+ result. Parse results are cached as OCR output, so what this
2000
+ bypasses is the OCR output itself, for 24 hours. Without it a retry
2001
+ after a bad parse returns the same bad parse for the rest of the day.
2002
+ Covers both ``mode="fast"`` and ``mode="advanced"``, which sit in
2003
+ separate cache namespaces. A forced run is billed at full price where
2004
+ a cached one costs nothing, so send it only when the caller explicitly
2005
+ asked to re-run.
2006
+
2007
+ Large documents
2008
+ ---------------
2009
+ ``"fast"`` mode has no page limit. ``"advanced"`` mode accepts up to 60
2010
+ pages per the public reference (500 for eligible plans when submitted
2011
+ asynchronously, as this method always does) and answers ``413`` above
2012
+ that; the byte cap and the exact page figures for *your* key are
2013
+ returned by :py:meth:`get_limits` (``parse_advanced`` and, when
2014
+ offered, ``bulk_parse``). The server does not report which condition
2015
+ kept a document out of the larger allowance.
2016
+
2017
+ Such a document runs as page-range segments but stays ONE job. Its
2018
+ completed result differs in shape, so branch on it:
2019
+
2020
+ - ``pages`` / ``ocr`` are NOT inline. The payload is delivered via a
2021
+ presigned ``result["result_url"]``, re-signed on every poll and valid
2022
+ for minutes — fetch it promptly or re-poll for a fresh one.
2023
+ - ``result["metadata"]["gaps"]`` lists page ranges that failed after
2024
+ retries. The document still completes; only pages that actually
2025
+ processed are billed. Always present, empty when nothing failed.
2026
+ - Segment progress (``segments_total`` / ``segments_done`` /
2027
+ ``segments_failed``) sits on the job envelope from
2028
+ :py:meth:`get_job`, not on the result :py:meth:`wait_for_job` returns.
2029
+
2030
+ These can run past the default 3600 s ``poll_timeout``. Exceeding it
2031
+ raises ``JobTimeoutError`` but does NOT stop the job — re-attach with
2032
+ :py:meth:`get_job` (jobs live 24 h) or pass a larger ``poll_timeout``.
2033
+ """
2034
+ path = self._resolve_path(file_path, image_path)
2035
+ return self._submit_via_path(
2036
+ "/v1/parse",
2037
+ "parse",
2038
+ path,
2039
+ params=_parse_params(
2040
+ mode=mode,
2041
+ include_boxes=include_boxes,
2042
+ include_image=include_image,
2043
+ include_layout=include_layout,
2044
+ parse_figures=parse_figures,
2045
+ groups_profile=groups_profile,
2046
+ ),
2047
+ force_refresh=force_refresh,
2048
+ use_presigned=use_presigned,
2049
+ )
2050
+
2051
+ def submit_extract(
2052
+ self,
2053
+ file_path: str | Path,
2054
+ *,
2055
+ category: ExtractCategory | None = None,
2056
+ parse_mode: ParseMode | None = None,
2057
+ schema: dict | str | Path | None = None,
2058
+ force_refresh: bool = False,
2059
+ use_presigned: bool = True,
2060
+ ) -> Job:
2061
+ """Submit a Basic extract job asynchronously and return immediately.
2062
+
2063
+ ``category`` selects the Basic extractor. Omit it to use the organization
2064
+ default (platform default: ``"financial"``). ``"financial"`` (
2065
+ the built-in invoice and receipt fields) or ``"non_financial"``
2066
+ (template-driven — see ``schema`` below). For auto-detecting Advanced
2067
+ extraction, use :py:meth:`submit_extract_advanced`.
2068
+
2069
+ ``parse_mode`` explicitly selects the OCR engine, independent of
2070
+ ``category``: ``"fast"`` (fast text extraction) or
2071
+ ``"advanced"`` (advanced layout-aware parsing for dense tables/forms —
2072
+ higher accuracy, slower, costs more; Plus plan or higher). Omit it
2073
+ to use the organization default (platform default: ``"fast"``).
2074
+
2075
+ ``schema``: a blank template — the exact shape you want back, with
2076
+ ``None``/``False``/``"unselected"`` as placeholders, e.g.
2077
+ ``{"patient_name": None, "insurance": {"Medicare": "unselected",
2078
+ "Self-Pay": "unselected"}}``. Pass it as an already-loaded dict, a
2079
+ ``str`` of JSON text, or a ``pathlib.Path`` to a JSON file. A ``str``
2080
+ is always parsed as JSON and never read as a file name — to load a
2081
+ file, pass ``pathlib.Path("template.json")``. With
2082
+ ``category="non_financial"`` the template is filled directly from the
2083
+ document. With ``category="financial"`` the invoice extractor runs and
2084
+ its output is remapped into your template. A ``schema`` with no
2085
+ ``category`` is sent as ``"non_financial"``. Ephemeral — used for this
2086
+ call only, nothing is stored server-side; pass a different ``schema``
2087
+ next call for a different shape, no merge/versioning to reason about.
2088
+ Omit entirely to use this org's stored default template instead (set
2089
+ up separately, offline).
2090
+ """
2091
+ path = self._resolve_path(file_path)
2092
+ resolved_schema = _load_schema(schema)
2093
+ # `schema` is honoured on both categories: non_financial fills the
2094
+ # template directly, financial runs the invoice extractor and remaps
2095
+ # its output into the template. An explicit category is sent as given.
2096
+ #
2097
+ # A schema with no declared category: send non_financial explicitly
2098
+ # rather than deferring. The two categories treat a template
2099
+ # differently, and the SDK cannot read the organization default, so
2100
+ # deferring would make the same call behave differently per account.
2101
+ # Filling the template directly is the plain reading of "here is the
2102
+ # shape I want"; callers who want the invoice extractor say so.
2103
+ effective_category = (
2104
+ "non_financial" if category is None and resolved_schema is not None else category
2105
+ )
2106
+ data = (
2107
+ {"schema": json.dumps(resolved_schema)}
2108
+ if resolved_schema is not None
2109
+ else None
2110
+ )
2111
+ return self._submit_via_path(
2112
+ "/v1/extract",
2113
+ "extract",
2114
+ path,
2115
+ params={
2116
+ # Omitted when None so the server-side default applies — same
2117
+ # mechanism `parse_mode` below already uses. Sending a value
2118
+ # unconditionally is what made an organization's configured
2119
+ # default category unreachable from the SDK.
2120
+ **({"category": effective_category} if effective_category is not None else {}),
2121
+ **({"parse_mode": parse_mode} if parse_mode is not None else {}),
2122
+ },
2123
+ data=data,
2124
+ force_refresh=force_refresh,
2125
+ use_presigned=use_presigned,
2126
+ )
2127
+
2128
+ def submit_extract_advanced(
2129
+ self,
2130
+ file_path: str | Path,
2131
+ *,
2132
+ parse_mode: ParseMode | None = None,
2133
+ force_refresh: bool = False,
2134
+ use_presigned: bool = True,
2135
+ ) -> Job:
2136
+ """Submit an Advanced extract job asynchronously and return immediately.
2137
+
2138
+ Advanced extraction auto-detects the document type (no ``category``
2139
+ needed): invoice-family documents use the built-in invoice and receipt
2140
+ fields, everything else schema-less grounded extraction. Returns the same
2141
+ envelope shape as :py:meth:`submit_extract`.
2142
+
2143
+ ``parse_mode`` selects the OCR engine (``"fast"``/``"advanced"``,
2144
+ same meaning as :py:meth:`submit_extract`).
2145
+
2146
+ ``force_refresh=True`` reprocesses instead of returning the stored
2147
+ result for an identical document and options (same meaning and same
2148
+ billing caveat as on :py:meth:`submit_extract`).
2149
+ """
2150
+ path = self._resolve_path(file_path)
2151
+ # op_name="extract" is deliberate error-taxonomy reuse (same ExtractError,
2152
+ # same response envelope) — NOT a typo. There is no "extract-omni" key in
2153
+ # _OP_TO_ERROR; do not "fix" this to one (it would KeyError).
2154
+ return self._submit_via_path(
2155
+ "/v1/extract-omni",
2156
+ "extract",
2157
+ path,
2158
+ params={"parse_mode": parse_mode} if parse_mode is not None else {},
2159
+ force_refresh=force_refresh,
2160
+ use_presigned=use_presigned,
2161
+ )
2162
+
2163
+ def submit_classify(
2164
+ self,
2165
+ file_path: str | Path,
2166
+ *,
2167
+ mode: str = "default",
2168
+ options: dict | None = None,
2169
+ force_refresh: bool = False,
2170
+ use_presigned: bool = True,
2171
+ ) -> Job:
2172
+ """Submit a classify job asynchronously and return immediately.
2173
+
2174
+ ``options`` is an optional dict of classifier knobs, sent as a JSON
2175
+ form field and validated server-side. Accepted keys:
2176
+
2177
+ - ``mode`` (``"fast"`` | ``"balanced"`` | ``"thorough"``) — the
2178
+ pipeline depth, distinct from this method's ``mode=`` task selector.
2179
+ - ``active_classes`` — explicit list of class labels to consider.
2180
+ - ``active_classes_type`` (``"default"`` | ``"minimal"``, default
2181
+ ``"default"``) — picks the built-in label set (default = full set,
2182
+ minimal = reduced set).
2183
+ - ``custom_llm_classes`` — additional caller-defined class labels.
2184
+ - ``system_instruction`` — extra prompt guidance.
2185
+ - ``domain_options`` (str, optional) — pipe-separated list of allowed
2186
+ first-stage domain labels.
2187
+ - ``non_domain_label`` (str, optional, effective default
2188
+ ``"non_financial"``) — label used when the document falls outside
2189
+ the configured domain.
2190
+ - ``non_domain_exit_label`` (str, optional, effective default
2191
+ ``"other_non_financial"``) — terminal label for out-of-domain exits.
2192
+ - ``confusion_neighbors`` (dict of ``{label: [neighbor_label, ...]}``,
2193
+ optional) — disambiguation hints between easily-confused classes.
2194
+ - Token/page budgets: ``start_token_budget`` (default 3200, range
2195
+ 256–8192), ``end_token_budget`` (default 1600, range 256–8192),
2196
+ ``max_start_pages`` (default 4, range 1–20), ``max_end_pages``
2197
+ (default 2, range 0–10).
2198
+ """
2199
+ path = self._resolve_path(file_path)
2200
+ data = {"options": json.dumps(options)} if options is not None else None
2201
+ return self._submit_via_path(
2202
+ "/v1/classify",
2203
+ "classify",
2204
+ path,
2205
+ params={"mode": mode},
2206
+ data=data,
2207
+ force_refresh=force_refresh,
2208
+ use_presigned=use_presigned,
2209
+ )
2210
+
2211
+ def submit_split(
2212
+ self,
2213
+ file_path: str | Path,
2214
+ *,
2215
+ mode: str = "default",
2216
+ options: dict | None = None,
2217
+ force_refresh: bool = False,
2218
+ use_presigned: bool = True,
2219
+ ) -> Job:
2220
+ """Submit a split job asynchronously and return immediately.
2221
+
2222
+ ``options`` is an optional dict of splitter knobs, sent as a JSON
2223
+ form field and validated server-side: ``use_thinking``,
2224
+ ``segment_classes``, ``extend_segment_classes``, and
2225
+ ``custom_domain_guidelines`` — a nested object whose ``domain_name``
2226
+ sub-field is **required** when ``custom_domain_guidelines`` is given;
2227
+ the remaining sub-fields (``identifier_patterns``, ``binding_patterns``,
2228
+ ``heuristics``, ``examples``) are optional.
2229
+ """
2230
+ path = self._resolve_path(file_path)
2231
+ data = {"options": json.dumps(options)} if options is not None else None
2232
+ return self._submit_via_path(
2233
+ "/v1/split",
2234
+ "split",
2235
+ path,
2236
+ params={"mode": mode},
2237
+ data=data,
2238
+ force_refresh=force_refresh,
2239
+ use_presigned=use_presigned,
2240
+ )
2241
+
2242
+ def submit_redact(
2243
+ self,
2244
+ file_path: str | Path,
2245
+ *,
2246
+ mode: str = "redact",
2247
+ pii_config: dict | None = None,
2248
+ include_logos: bool = False,
2249
+ output: str = "inline",
2250
+ force_refresh: bool = False,
2251
+ use_presigned: bool = True,
2252
+ ) -> Job:
2253
+ """Submit a redact/deidentify job asynchronously and return immediately.
2254
+
2255
+
2256
+ A page cap applies to inline output; ``output="urls"`` raises it where
2257
+ your account offers that mode. Read the current values with
2258
+ :py:meth:`get_limits`: ``limits["redact"]["max_pages"]`` for inline
2259
+ and ``limits["redact"]["urls_max_pages"]`` for URL output (absent
2260
+ means URL output is not offered — feature-detect on that key).
2261
+ ``output="urls"`` returns masked pages as short-lived presigned links
2262
+ in ``result["result"]["pages"]`` (``{page_number, image_url}``)
2263
+ instead of inline base64 ``result["result"]["images"]`` —
2264
+ ``download_pages()`` accepts that result directly. An over-cap
2265
+ document is refused with ``413`` up front, before any OCR is billed,
2266
+ and raises ``RedactError`` (``status_code == 413``);
2267
+ ``output="urls"`` cannot be combined with ``include_logos`` (``400``).
2268
+
2269
+ ``mode="redact"`` applies black boxes; ``mode="deidentify"`` overlays
2270
+ synthetic values. ``pii_config`` (``{"mode": "extend"|"replace",
2271
+ "types": [...]}``) customizes the detected PII types. Built-in types
2272
+ include PERSON_NAME, COMPANY_NAME, EMAIL, ADDRESS, WEBSITE, PHONE,
2273
+ and CREDENTIALS (passwords, API keys, tokens, secrets) — all with
2274
+ synthetic replacements, so each works in both modes.
2275
+ """
2276
+ if output not in ("inline", "urls"):
2277
+ # Fail loudly client-side: only the non-default literal goes on the
2278
+ # wire, so a typo ("url", "URLS") would otherwise silently run
2279
+ # inline at the inline page cap with no server-side rejection possible.
2280
+ raise ValueError(f'output must be "inline" or "urls", got {output!r}')
2281
+ path = self._resolve_path(file_path)
2282
+ data = (
2283
+ {"pii_config": json.dumps(pii_config)} if pii_config is not None else None
2284
+ )
2285
+ return self._submit_via_path(
2286
+ "/v1/redact",
2287
+ "redact",
2288
+ path,
2289
+ params={"mode": mode, "include_logos": include_logos, **({"output": "urls"} if output == "urls" else {})},
2290
+ data=data,
2291
+ force_refresh=force_refresh,
2292
+ use_presigned=use_presigned,
2293
+ )
2294
+
2295
+ # ── Batch API (async, deferred) ──────────────────────────────────────
2296
+
2297
+ _BATCH_TERMINAL = frozenset(
2298
+ {"completed", "completed_with_errors", "failed", "canceled"}
2299
+ )
2300
+
2301
+ def _batch_request(
2302
+ self,
2303
+ method: str,
2304
+ path: str,
2305
+ *,
2306
+ json_body: dict | None = None,
2307
+ params: dict | None = None,
2308
+ extra_headers: dict[str, str] | None = None,
2309
+ required: tuple[str, ...] = (),
2310
+ ) -> dict:
2311
+ """Shared request+error handling for the /v1/batch endpoints.
2312
+
2313
+ Every batch reply must be a JSON object carrying the ``required`` keys.
2314
+ """
2315
+ headers = self._get_headers()
2316
+ request_id = headers["X-Request-ID"]
2317
+ if extra_headers:
2318
+ headers.update(extra_headers)
2319
+ try:
2320
+ resp = self._client.request(
2321
+ method,
2322
+ f"{self.base_url}{path}",
2323
+ headers=headers,
2324
+ json=json_body,
2325
+ params=params,
2326
+ )
2327
+ except httpx.RequestError as e:
2328
+ raise HyperAPIError(
2329
+ f"Batch request failed: {e}", request_id=request_id
2330
+ ) from None
2331
+
2332
+ rid = _request_id_of(resp, request_id)
2333
+ if resp.status_code == 401:
2334
+ raise AuthenticationError(
2335
+ "Invalid API key.", status_code=401, request_id=rid
2336
+ )
2337
+ if resp.status_code == 404 and path != "/v1/batch":
2338
+ # Only an id-addressed call (GET/DELETE /v1/batch/{id}) can mean
2339
+ # "no such batch". A 404 on the collection itself falls through
2340
+ # and reports what the server said.
2341
+ raise HyperAPIError(
2342
+ "Batch not found.",
2343
+ status_code=404,
2344
+ request_id=rid,
2345
+ **_error_fields(resp),
2346
+ )
2347
+ if resp.status_code == 429:
2348
+ raise _rate_limit_error_from(resp, rid)
2349
+ if resp.status_code >= 400:
2350
+ raise HyperAPIError(
2351
+ _server_message(
2352
+ resp, f"Batch request failed (HTTP {resp.status_code})"
2353
+ ),
2354
+ status_code=resp.status_code,
2355
+ request_id=rid,
2356
+ **_error_fields(resp),
2357
+ )
2358
+ return _json_object(resp, request_id=rid, required=required, what="batch")
2359
+
2360
+ def create_batch(
2361
+ self,
2362
+ *,
2363
+ endpoint: str,
2364
+ document_keys: list[str],
2365
+ options: dict | None = None,
2366
+ parse_mode: str | None = None,
2367
+ webhook_url: str | None = None,
2368
+ metadata: dict | None = None,
2369
+ estimated_pages_per_doc: int = 1,
2370
+ idempotency_key: str | None = None,
2371
+ ) -> dict:
2372
+ """Submit a batch of already-uploaded documents for async processing.
2373
+
2374
+ Returns immediately with ``{batch_id, status, total_items}``; the work
2375
+ runs on spare capacity. Poll :meth:`get_batch` (or :meth:`wait_for_batch`)
2376
+ for per-document results (each result lands in S3, keyed by ``doc_index``).
2377
+
2378
+ Args:
2379
+ endpoint: One of ``/v1/parse``, ``/v1/extract``,
2380
+ ``/v1/extract-omni`` (advanced extract), ``/v1/classify``,
2381
+ ``/v1/split``, ``/v1/redact``. The API rejects any other
2382
+ value with a ``400``.
2383
+ document_keys: Keys from :meth:`upload_document`, one per document.
2384
+ options: Task-specific options, forwarded to each document's run.
2385
+ parse_mode: ``fast`` (default) or ``advanced``, for ``/v1/parse`` only.
2386
+ ``advanced`` runs layout-aware parsing. Advanced parse may not
2387
+ be available for batch on your plan: the API then rejects the
2388
+ batch with a ``400`` or ``403`` whose message says why. Batch
2389
+ advanced parse runs on the lowest-priority lane, yielding to
2390
+ interactive traffic, so it may take longer under load (24h SLA).
2391
+ Ignored by non-``/v1/parse`` endpoints.
2392
+ webhook_url: Optional completion webhook (delivered when available).
2393
+ metadata: Optional caller-supplied key/value tags stored with the
2394
+ batch and echoed back on :meth:`get_batch` / :meth:`list_batches`
2395
+ and in the completion webhook payload.
2396
+ estimated_pages_per_doc: Hint for the up-front quota check.
2397
+ idempotency_key: Resubmitting with the same key returns the existing
2398
+ batch instead of creating a duplicate.
2399
+ """
2400
+ body: dict = {
2401
+ "endpoint": endpoint,
2402
+ "document_keys": document_keys,
2403
+ "options": options or {},
2404
+ "estimated_pages_per_doc": estimated_pages_per_doc,
2405
+ }
2406
+ if parse_mode is not None:
2407
+ body["parse_mode"] = parse_mode
2408
+ if webhook_url is not None:
2409
+ body["webhook_url"] = webhook_url
2410
+ if metadata is not None:
2411
+ body["metadata"] = metadata
2412
+ extra = {"Idempotency-Key": idempotency_key} if idempotency_key else None
2413
+ return self._batch_request(
2414
+ "POST",
2415
+ "/v1/batch",
2416
+ json_body=body,
2417
+ extra_headers=extra,
2418
+ required=("batch_id",),
2419
+ )
2420
+
2421
+ def create_batch_from_files(
2422
+ self,
2423
+ *,
2424
+ endpoint: str,
2425
+ file_paths: list[str | Path],
2426
+ **kwargs,
2427
+ ) -> dict:
2428
+ """Upload each file (presigned flow) then :meth:`create_batch`."""
2429
+ document_keys = [self.upload_document(p) for p in file_paths]
2430
+ return self.create_batch(
2431
+ endpoint=endpoint, document_keys=document_keys, **kwargs
2432
+ )
2433
+
2434
+ def get_batch(self, batch_id: str, *, limit: int = 200, offset: int = 0) -> dict:
2435
+ """Batch status: ``{status, counts, items:[{doc_index, status, ...}]}``."""
2436
+ return self._batch_request(
2437
+ "GET",
2438
+ f"/v1/batch/{_path_id(batch_id, name='batch_id')}",
2439
+ params={"limit": limit, "offset": offset},
2440
+ )
2441
+
2442
+ def list_batches(self, *, limit: int = 50, offset: int = 0) -> dict:
2443
+ """List the org's batches, newest first."""
2444
+ return self._batch_request(
2445
+ "GET", "/v1/batch", params={"limit": limit, "offset": offset}
2446
+ )
2447
+
2448
+ def cancel_batch(self, batch_id: str) -> dict:
2449
+ """Cancel a batch — stops queued items; in-flight items finish."""
2450
+ return self._batch_request(
2451
+ "DELETE", f"/v1/batch/{_path_id(batch_id, name='batch_id')}"
2452
+ )
2453
+
2454
+ def wait_for_batch(
2455
+ self,
2456
+ batch_id: str,
2457
+ *,
2458
+ timeout: float = 3600.0,
2459
+ poll_interval: float = 5.0,
2460
+ ) -> dict:
2461
+ """Poll :meth:`get_batch` until the batch reaches a terminal state.
2462
+
2463
+ Raises :class:`JobTimeoutError` if ``timeout`` elapses (the batch keeps
2464
+ running server-side — resume with a larger timeout or :meth:`get_batch`).
2465
+ """
2466
+ start = time.monotonic()
2467
+ deadline = start + timeout
2468
+ while True:
2469
+ try:
2470
+ status = self._retry_transient(
2471
+ lambda: self.get_batch(batch_id),
2472
+ kind="Batch",
2473
+ ident=batch_id,
2474
+ deadline=deadline,
2475
+ start=start,
2476
+ )
2477
+ except RateLimitError as e:
2478
+ wait = _rate_limit_wait(e, deadline - time.monotonic())
2479
+ if wait is None:
2480
+ raise
2481
+ logger.info(
2482
+ "batch_poll_rate_limited",
2483
+ extra={
2484
+ "batch_id": batch_id,
2485
+ "retry_after": wait,
2486
+ "degraded": e.degraded,
2487
+ },
2488
+ )
2489
+ time.sleep(wait)
2490
+ continue
2491
+ if status.get("status") in self._BATCH_TERMINAL:
2492
+ return status
2493
+ if time.monotonic() >= deadline:
2494
+ raise JobTimeoutError(
2495
+ f"Batch {batch_id} did not complete within {timeout}s.",
2496
+ job_id=batch_id,
2497
+ elapsed_s=time.monotonic() - start,
2498
+ )
2499
+ time.sleep(min(poll_interval, max(0.0, deadline - time.monotonic())))
2500
+
2501
+ # ── Public convenience methods (submit + wait) ───────────────────────
2502
+
2503
+ def parse(
2504
+ self,
2505
+ file_path: str | Path | None = None,
2506
+ *,
2507
+ image_path: str | Path | None = None,
2508
+ mode: ParseMode | None = None,
2509
+ include_boxes: bool | None = None,
2510
+ include_image: bool | None = None,
2511
+ include_layout: bool | None = None,
2512
+ parse_figures: str | None = None,
2513
+ groups_profile: str | None = None,
2514
+ force_refresh: bool = False,
2515
+ use_presigned: bool = True,
2516
+ poll_timeout: float | None = None,
2517
+ poll_interval: float | None = None,
2518
+ ) -> dict:
2519
+ """Parse a document using OCR. Submits asynchronously and polls until done.
2520
+
2521
+ The returned dict is the response envelope; the parse payload is nested
2522
+ one level under ``result`` — OCR text at ``result["result"]["ocr"]`` and
2523
+ the page list at ``result["result"]["pages"]``.
2524
+
2525
+ Args:
2526
+ file_path: Path to the file (PDF, PNG, JPG, WEBP, TIFF, GIF).
2527
+ image_path: Deprecated alias for file_path.
2528
+ mode: Explicit ``"fast"`` or ``"advanced"``. Omit to use the
2529
+ organization default (platform default: ``"fast"``). Advanced
2530
+ is layout-aware structured OCR: each ``result["result"]["pages"]``
2531
+ entry gains a ``structured`` dict with ``html``, ``markdown``,
2532
+ and ``regions``). Advanced only applies on the default OCR
2533
+ engine and is noticeably slower.
2534
+ include_boxes: Tri-state. ``None`` (default) sends nothing, so the
2535
+ API default applies — ON in ``"fast"`` mode. ``False`` opts
2536
+ out; ``True`` asks explicitly. When on, each
2537
+ ``result["result"]["pages"]`` entry includes a ``boxes`` list
2538
+ of line boxes (``{"text", "bbox": [left, top, right, bottom],
2539
+ "confidence"}``) and, for PDF, XPS and image inputs, a
2540
+ ``word_boxes`` list of per-word boxes with ``font``, ``size``,
2541
+ ``color``, ``bold``, ``italic``, ``background`` and
2542
+ ``font_source`` (``"document"`` or ``"model"``). Coordinates
2543
+ are pixels in the page's ``dimensions`` space.
2544
+ ``mode="advanced"`` returns no boxes. See :py:meth:`submit_parse`.
2545
+ include_image: Tri-state, same convention; the API default is ON.
2546
+ When on, each ``result["result"]["pages"]`` entry includes an
2547
+ ``image_url`` (presigned GET for the deskew-corrected page,
2548
+ valid about 15 minutes). ``dimensions`` (``{"width",
2549
+ "height"}`` in that image's pixel space, which matches the box
2550
+ coordinate space) is present on PDF, XPS and image pages in
2551
+ fast mode regardless, alongside ``page_size`` and
2552
+ ``background``.
2553
+ include_layout: Tri-state, same convention; the API default is ON
2554
+ in ``"fast"`` mode. When on, each page gains ``layout`` and
2555
+ ``layout_text`` and the result gains ``layout_text``. Not for
2556
+ ``mode="advanced"`` (``True`` there is a ``400``). See
2557
+ :py:meth:`submit_parse`.
2558
+ parse_figures: Comma-separated region kinds to parse further —
2559
+ ``"image"``, ``"chart"``, ``"table"`` — or ``"none"``.
2560
+ Omitted, the API parses all three when the layout is on.
2561
+ Needs the layout on. See :py:meth:`submit_parse`.
2562
+ groups_profile: ``"A"`` (API default) or ``"B"`` — how the
2563
+ document outline in ``result["result"]["groups"]`` is built.
2564
+ See :py:meth:`submit_parse`.
2565
+ force_refresh: Re-run OCR instead of returning the cached result
2566
+ (results are cached for 24 hours). See :py:meth:`submit_parse`.
2567
+ use_presigned: Use the presigned-S3 upload flow (default True).
2568
+ poll_timeout: Override the constructor's poll_timeout for this call.
2569
+ poll_interval: Override the constructor's poll_interval for this call.
2570
+
2571
+ Returns:
2572
+ Response envelope; OCR text at ``result["result"]["ocr"]`` and pages
2573
+ at ``result["result"]["pages"]``.
2574
+
2575
+ EXCEPT for a large advanced document (past the ordinary advanced
2576
+ page cap, admitted on plans that allow it — see
2577
+ :py:meth:`submit_parse` and :py:meth:`get_limits`): those carry no
2578
+ inline ``pages``/``ocr``. The payload is behind a presigned
2579
+ ``result["result_url"]`` and failed page ranges are listed in
2580
+ ``result["metadata"]["gaps"]``. Branch on ``result_url`` being
2581
+ present rather than assuming the inline shape, and raise
2582
+ ``poll_timeout`` — such a job can outlast the 3600 s default.
2583
+ """
2584
+ job = self.submit_parse(
2585
+ file_path=file_path,
2586
+ image_path=image_path,
2587
+ mode=mode,
2588
+ include_boxes=include_boxes,
2589
+ include_image=include_image,
2590
+ include_layout=include_layout,
2591
+ parse_figures=parse_figures,
2592
+ groups_profile=groups_profile,
2593
+ force_refresh=force_refresh,
2594
+ use_presigned=use_presigned,
2595
+ )
2596
+ return self.wait_for_job(job, timeout=poll_timeout, interval=poll_interval)
2597
+
2598
+ def extract(
2599
+ self,
2600
+ file_path: str | Path,
2601
+ *,
2602
+ category: ExtractCategory | None = None,
2603
+ parse_mode: ParseMode | None = None,
2604
+ schema: dict | str | Path | None = None,
2605
+ force_refresh: bool = False,
2606
+ use_presigned: bool = True,
2607
+ poll_timeout: float | None = None,
2608
+ poll_interval: float | None = None,
2609
+ ) -> dict:
2610
+ """Extract structured data from a document.
2611
+
2612
+ Submits asynchronously and polls until done. Bypasses any edge-timeout
2613
+ ceiling because each individual HTTP request stays sub-second.
2614
+
2615
+ This is the Basic extractor. ``category="financial"`` uses the
2616
+ built-in invoice and receipt fields. Omit ``category`` to use the
2617
+ organization default (platform default: ``"financial"``; a ``schema``
2618
+ with no ``category`` is sent as ``"non_financial"``). ``category="non_financial"``
2619
+ does no document-type detection; pass ``schema`` to
2620
+ describe the documents — a blank
2621
+ template with ``None``/``False``/``"unselected"`` as placeholders
2622
+ (e.g. ``{"patient_name": None, "insurance": {"Medicare":
2623
+ "unselected", "Self-Pay": "unselected"}}``, as a dict, a ``str`` of
2624
+ JSON text, or a ``pathlib.Path`` to a JSON file — a ``str`` is never
2625
+ read as a file name), and the response fills in that SAME
2626
+ structure from the document — nothing is stored server-side, pass a
2627
+ different ``schema`` next call for a different shape, no
2628
+ merge/versioning to reason about. Omit ``schema`` to use this org's
2629
+ stored default template instead (set up separately, offline — not
2630
+ through this SDK); with no schema and no stored default, this
2631
+ currently falls back to a generic extraction (a known gap, not yet
2632
+ unified with this flow). ``schema`` also works with
2633
+ ``category="financial"``: the invoice extractor runs and its output
2634
+ is remapped into your template. For auto-detecting Advanced
2635
+ extraction (no ``category`` needed), use :py:meth:`extract_advanced`.
2636
+
2637
+ Returns:
2638
+ Response envelope. For ``category="financial"``: the structured
2639
+ payload is one level under ``result``:
2640
+ ``result["result"]["entities"]`` (header/party fields),
2641
+ ``result["result"]["line_items"]`` (per-line rows), and
2642
+ ``result["result"]["summary"]`` (document-level totals/tax/currency —
2643
+ e.g. the grand total lives here, ``summary["total_amount"]``, NOT in
2644
+ entities). For ``category="non_financial"``: the
2645
+ filled-in template is at ``result["result"]["data"]`` (same shape
2646
+ as ``schema``, or the org's stored default). Raw OCR is at the
2647
+ envelope top level, ``result["ocr_text"]``, in both cases.
2648
+ """
2649
+ job = self.submit_extract(
2650
+ file_path,
2651
+ category=category,
2652
+ parse_mode=parse_mode,
2653
+ schema=schema,
2654
+ force_refresh=force_refresh,
2655
+ use_presigned=use_presigned,
2656
+ )
2657
+ return self.wait_for_job(job, timeout=poll_timeout, interval=poll_interval)
2658
+
2659
+ def extract_advanced(
2660
+ self,
2661
+ file_path: str | Path,
2662
+ *,
2663
+ parse_mode: ParseMode | None = None,
2664
+ force_refresh: bool = False,
2665
+ use_presigned: bool = True,
2666
+ poll_timeout: float | None = None,
2667
+ poll_interval: float | None = None,
2668
+ ) -> dict:
2669
+ """Advanced extraction — auto-detects the document type, no ``category``.
2670
+
2671
+ Invoice-family documents use the built-in invoice and receipt fields;
2672
+ everything else schema-less grounded extraction. Submits asynchronously and
2673
+ polls until done. Returns the same envelope shape as :py:meth:`extract`.
2674
+ ``force_refresh=True`` reprocesses instead of returning the stored
2675
+ result (see :py:meth:`submit_extract_advanced`).
2676
+ """
2677
+ job = self.submit_extract_advanced(
2678
+ file_path,
2679
+ parse_mode=parse_mode,
2680
+ force_refresh=force_refresh,
2681
+ use_presigned=use_presigned,
2682
+ )
2683
+ return self.wait_for_job(job, timeout=poll_timeout, interval=poll_interval)
2684
+
2685
+ def classify(
2686
+ self,
2687
+ file_path: str | Path,
2688
+ *,
2689
+ mode: str = "default",
2690
+ options: dict | None = None,
2691
+ force_refresh: bool = False,
2692
+ use_presigned: bool = True,
2693
+ poll_timeout: float | None = None,
2694
+ poll_interval: float | None = None,
2695
+ ) -> dict:
2696
+ """Classify a document type (invoice, contract, receipt, etc.).
2697
+
2698
+ ``options`` customizes the classifier (see :py:meth:`submit_classify`
2699
+ for the full key list): pipeline depth via ``options["mode"]``
2700
+ (``"fast"`` | ``"balanced"`` | ``"thorough"`` — distinct from the
2701
+ ``mode=`` task selector), ``active_classes``, ``active_classes_type``,
2702
+ ``custom_llm_classes``, ``system_instruction``, ``domain_options``,
2703
+ ``non_domain_label``, ``non_domain_exit_label``, ``confusion_neighbors``,
2704
+ and the token/page budgets (``start_token_budget``, ``end_token_budget``,
2705
+ ``max_start_pages``, ``max_end_pages``).
2706
+
2707
+ Returns:
2708
+ Response envelope. The prediction is one level under ``result``:
2709
+ ``result["result"]["document_type"]`` (e.g. ``"invoice"``), with
2710
+ ``confidence`` (a categorical label such as ``"very_high"``, not a
2711
+ float), ``domain``, and ``needs_review`` alongside it. Raw OCR is at
2712
+ the envelope top level in ``result["ocr_text"]``.
2713
+ """
2714
+ job = self.submit_classify(
2715
+ file_path,
2716
+ mode=mode,
2717
+ options=options,
2718
+ force_refresh=force_refresh,
2719
+ use_presigned=use_presigned,
2720
+ )
2721
+ return self.wait_for_job(job, timeout=poll_timeout, interval=poll_interval)
2722
+
2723
+ def split(
2724
+ self,
2725
+ file_path: str | Path,
2726
+ *,
2727
+ mode: str = "default",
2728
+ options: dict | None = None,
2729
+ force_refresh: bool = False,
2730
+ use_presigned: bool = True,
2731
+ poll_timeout: float | None = None,
2732
+ poll_interval: float | None = None,
2733
+ ) -> dict:
2734
+ """Split a multi-document PDF into individual document segments.
2735
+
2736
+ ``options`` customizes the splitter (see :py:meth:`submit_split`):
2737
+ ``use_thinking``, ``segment_classes``, ``extend_segment_classes``,
2738
+ and ``custom_domain_guidelines`` (its ``domain_name`` sub-field is
2739
+ required when the object is supplied).
2740
+
2741
+ Returns:
2742
+ Response envelope. The detected parts are at
2743
+ ``result["result"]["segmentation"]["splits"]`` — a list where each
2744
+ item has ``split_label``, ``start_page``, ``end_page``,
2745
+ ``confidence``, and ``sub_documents``. (Note the ``segmentation``
2746
+ wrapper: this is one level deeper than the other operations' payloads.)
2747
+ """
2748
+ job = self.submit_split(
2749
+ file_path,
2750
+ mode=mode,
2751
+ options=options,
2752
+ force_refresh=force_refresh,
2753
+ use_presigned=use_presigned,
2754
+ )
2755
+ return self.wait_for_job(job, timeout=poll_timeout, interval=poll_interval)
2756
+
2757
+ def redact(
2758
+ self,
2759
+ file_path: str | Path,
2760
+ *,
2761
+ mode: str = "redact",
2762
+ pii_config: dict | None = None,
2763
+ include_logos: bool = False,
2764
+ output: str = "inline",
2765
+ force_refresh: bool = False,
2766
+ use_presigned: bool = True,
2767
+ poll_timeout: float | None = None,
2768
+ poll_interval: float | None = None,
2769
+ ) -> dict:
2770
+ """Redact or deidentify PII in a document. Submits async + polls until done.
2771
+
2772
+
2773
+ A page cap applies to inline output; ``output="urls"`` raises it where
2774
+ your account offers that mode. Read the current values with
2775
+ :py:meth:`get_limits`: ``limits["redact"]["max_pages"]`` for inline
2776
+ and ``limits["redact"]["urls_max_pages"]`` for URL output (absent
2777
+ means URL output is not offered — feature-detect on that key).
2778
+ ``output="urls"`` returns masked pages as short-lived presigned links
2779
+ in ``result["result"]["pages"]`` (``{page_number, image_url}``)
2780
+ instead of inline base64 ``result["result"]["images"]`` —
2781
+ ``download_pages()`` accepts that result directly. An over-cap
2782
+ document is refused with ``413`` up front, before any OCR is billed,
2783
+ and raises ``RedactError`` (``status_code == 413``);
2784
+ ``output="urls"`` cannot be combined with ``include_logos`` (``400``).
2785
+
2786
+ ``mode="redact"`` masks PII with black boxes; ``mode="deidentify"``
2787
+ overlays synthetic replacements. ``include_logos=True`` also detects and
2788
+ masks logos. ``pii_config`` customizes the detected PII type set.
2789
+
2790
+ Returns:
2791
+ Response envelope with ``result`` containing the masked pages —
2792
+ ``images`` (inline base64, the default) or ``pages`` with
2793
+ presigned ``image_url`` links when ``output="urls"`` — plus
2794
+ ``updated_text_block`` and a ``summary`` of masked counts.
2795
+ """
2796
+ job = self.submit_redact(
2797
+ file_path,
2798
+ mode=mode,
2799
+ pii_config=pii_config,
2800
+ include_logos=include_logos,
2801
+ output=output,
2802
+ force_refresh=force_refresh,
2803
+ use_presigned=use_presigned,
2804
+ )
2805
+ return self.wait_for_job(job, timeout=poll_timeout, interval=poll_interval)
2806
+
2807
+ def download_pages(
2808
+ self,
2809
+ result: dict,
2810
+ dest_dir: str | Path,
2811
+ *,
2812
+ prefix: str = "page",
2813
+ max_page_bytes: int = _DEFAULT_MAX_PAGE_BYTES,
2814
+ ) -> list[Path]:
2815
+ """Download a result's page images to a folder.
2816
+
2817
+ Works with the dict returned by :py:meth:`parse` with page images on
2818
+ (the API default; do not pass ``include_image=False``) or by
2819
+ :py:meth:`redact` with ``output="urls"``. Files are written as
2820
+ ``<dest_dir>/<prefix>-<page number><ext>``, where the extension is the
2821
+ one the server served (``.webp`` for parse, ``.png`` for redact); the
2822
+ directory is created if needed.
2823
+
2824
+ Page images are served as **short-lived presigned URLs** (~15 min), so download
2825
+ promptly. If they have expired, re-poll with :py:meth:`get_job` — the server mints
2826
+ fresh URLs for the full 24 h the job lives — and call this again.
2827
+
2828
+ Args:
2829
+ result: The dict returned by an op that produced page images.
2830
+ dest_dir: Folder to write into. Created if it does not exist.
2831
+ prefix: Filename stem; defaults to ``page`` → ``page-1.png``.
2832
+ max_page_bytes: Largest page image accepted, in bytes (after any
2833
+ content decoding). Default 200 MiB. A larger page stops the
2834
+ download and raises ``HyperAPIError``.
2835
+
2836
+ Each page is streamed to a temporary file in ``dest_dir`` and renamed
2837
+ into place when complete, so a failure never leaves a partial page.
2838
+ Image URLs must be https (plain http only when ``base_url`` is http).
2839
+
2840
+ Returns:
2841
+ The written paths, in page order.
2842
+
2843
+ Raises:
2844
+ ValueError: If the result carries no pages, or a page has no ``image_url``.
2845
+ HyperAPIError: If a download fails — an expired URL reports as such — or a
2846
+ page exceeds ``max_page_bytes``, or an image URL is not https.
2847
+ """
2848
+ _check_page_cap(max_page_bytes)
2849
+ targets = _page_targets(result, dest_dir, prefix)
2850
+ for url, _ in targets:
2851
+ _check_server_url(url, base_url=self.base_url, what="page image URL")
2852
+ Path(dest_dir).mkdir(parents=True, exist_ok=True)
2853
+
2854
+ written: list[Path] = []
2855
+ for url, path in targets:
2856
+ self._download_page(url, path, max_page_bytes)
2857
+ written.append(path)
2858
+ return written
2859
+
2860
+ def _download_page(self, url: str, path: Path, max_page_bytes: int) -> None:
2861
+ """Stream one presigned page image to ``path`` (atomically, size-capped)."""
2862
+ partial = _partial_path(path)
2863
+ try:
2864
+ # Presigned URLs carry their own SigV4 signature — send no API-key headers.
2865
+ # Redirects are followed (S3 answers a cross-region GET with a 307 to the
2866
+ # regional endpoint), each hop checked for https before it is requested.
2867
+ with _stream_presigned_get(self._client, url, base_url=self.base_url) as resp:
2868
+ _check_download_reply(
2869
+ resp, path, base_url=self.base_url, max_page_bytes=max_page_bytes
2870
+ )
2871
+ received = 0
2872
+ with open(partial, "wb") as f:
2873
+ for chunk in resp.iter_bytes():
2874
+ received += len(chunk)
2875
+ if received > max_page_bytes:
2876
+ raise _page_too_large(path, max_page_bytes)
2877
+ f.write(chunk)
2878
+ os.replace(partial, path)
2879
+ except httpx.RequestError as e:
2880
+ raise _download_transport_error(path, e) from None
2881
+ finally:
2882
+ try:
2883
+ partial.unlink()
2884
+ except FileNotFoundError:
2885
+ pass
2886
+
2887
+ def process(
2888
+ self,
2889
+ file_path: str | Path | None = None,
2890
+ *,
2891
+ image_path: str | Path | None = None,
2892
+ poll_timeout: float | None = None,
2893
+ poll_interval: float | None = None,
2894
+ ) -> dict:
2895
+ """Parse and extract in one call.
2896
+
2897
+ Uploads the document once, then submits the parse and extract legs
2898
+ back-to-back (two sequential POSTs from the SDK). The platform runs
2899
+ the two legs concurrently on the server, reusing the shared
2900
+ ``document_key`` so OCR is computed once, so total wall-clock time
2901
+ ≈ max(parse, extract) + a small polling overhead, not their sum.
2902
+ Polls both jobs round-robin via ``wait_for_jobs``.
2903
+
2904
+ Returns:
2905
+ ``{"ocr": <parse text>, "data": <extract job envelope>}``.
2906
+ ``data`` is the extract job's full inference envelope (the same
2907
+ dict :py:meth:`extract` returns), not the fields themselves: the
2908
+ structured fields are at ``result["data"]["result"]["entities"]``,
2909
+ ``result["data"]["result"]["line_items"]`` and
2910
+ ``result["data"]["result"]["summary"]``.
2911
+ """
2912
+ path = self._resolve_path(file_path, image_path)
2913
+ document_key = self.upload_document(path)
2914
+ parse_job = self._submit_via_doc_key(
2915
+ "/v1/parse",
2916
+ "parse",
2917
+ document_key,
2918
+ params={},
2919
+ )
2920
+ extract_job = self._submit_via_doc_key(
2921
+ "/v1/extract",
2922
+ "extract",
2923
+ document_key,
2924
+ params={},
2925
+ )
2926
+ results = self.wait_for_jobs(
2927
+ [parse_job, extract_job],
2928
+ timeout=poll_timeout,
2929
+ interval=poll_interval,
2930
+ )
2931
+ parse_result, extract_result = results
2932
+ return {
2933
+ "ocr": _parse_ocr_text(parse_result),
2934
+ "data": extract_result if isinstance(extract_result, dict) else {},
2935
+ }
2936
+
2937
+ # ── Lifecycle ────────────────────────────────────────────────────────
2938
+
2939
+ def close(self) -> None:
2940
+ """Close the underlying HTTP client and release its connection pool."""
2941
+ self._client.close()
2942
+
2943
+ def __enter__(self) -> HyperAPIClient:
2944
+ return self
2945
+
2946
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
2947
+ self.close()