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/__init__.py +48 -0
- hyperapi/async_client.py +2181 -0
- hyperapi/client.py +2947 -0
- hyperapi/exceptions.py +250 -0
- hyperapi/py.typed +0 -0
- hyperapi_sdk-0.7.1.dist-info/METADATA +906 -0
- hyperapi_sdk-0.7.1.dist-info/RECORD +11 -0
- hyperapi_sdk-0.7.1.dist-info/WHEEL +5 -0
- hyperapi_sdk-0.7.1.dist-info/licenses/LICENSE +202 -0
- hyperapi_sdk-0.7.1.dist-info/licenses/NOTICE +4 -0
- hyperapi_sdk-0.7.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,906 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hyperapi-sdk
|
|
3
|
+
Version: 0.7.1
|
|
4
|
+
Summary: HyperAPI Python SDK - Document intelligence APIs (parse, extract, classify, split, redact)
|
|
5
|
+
Author-email: HyperAPI <research@hyperbots.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://apis.hyperbots.com
|
|
8
|
+
Project-URL: Documentation, https://apis.hyperbots.com/docs
|
|
9
|
+
Project-URL: Repository, https://github.com/hyprbots/hyperapi-sdk
|
|
10
|
+
Project-URL: Issues, https://github.com/hyprbots/hyperapi-sdk/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/hyprbots/hyperapi-sdk/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: ocr,document-processing,invoice,financial,api
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
License-File: NOTICE
|
|
28
|
+
Requires-Dist: httpx<1.0,>=0.28.1
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
32
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
|
|
33
|
+
Requires-Dist: respx>=0.20.0; extra == "dev"
|
|
34
|
+
Requires-Dist: ruff==0.8.6; extra == "dev"
|
|
35
|
+
Requires-Dist: pre-commit>=4.0.0; extra == "dev"
|
|
36
|
+
Provides-Extra: socks
|
|
37
|
+
Requires-Dist: httpx[socks]<1.0,>=0.28.1; extra == "socks"
|
|
38
|
+
Dynamic: license-file
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
<p align="center">
|
|
42
|
+
<a href="https://apis.hyperbots.com/"><img src="https://images.g2crowd.com/uploads/vendor/image/1515319/9eadfb55dd882c428f4f82ee306dabcd.png" width="115"></a>
|
|
43
|
+
<p align="center"><strong>HyperAPI: </strong>Stop Prompting, Start Programming Financial Intelligence.</p>
|
|
44
|
+
</p>
|
|
45
|
+
<p align="center">
|
|
46
|
+
<a href="https://github.com/hyprbots/hyperapi-sdk"><img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="Python 3.9+"></a>
|
|
47
|
+
<a href="https://github.com/hyprbots/hyperapi-sdk/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License"></a>
|
|
48
|
+
</p>
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
**HyperAPI-SDK** is a document intelligence framework composed of Parse, Extract, Classify, Split, Redact, and more APIs. Whether you are dealing with low-quality scans or complex multi-document binders, HyperAPI is engineered for production-grade reliability.
|
|
53
|
+
|
|
54
|
+
## Architecture
|
|
55
|
+
|
|
56
|
+
Every operation follows the same **OCR → task** path on the server:
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
┌─────────────────┐
|
|
60
|
+
│ Upload Document │
|
|
61
|
+
└────────┬────────┘
|
|
62
|
+
│
|
|
63
|
+
┌──────────────▼──────────────┐
|
|
64
|
+
│ OCR │
|
|
65
|
+
│ │
|
|
66
|
+
│ ┌──────────┐ ┌───────────┐ │
|
|
67
|
+
│ │ fast │ │ advanced │ │
|
|
68
|
+
│ │ (default)│ │ (layout) │ │
|
|
69
|
+
│ └──────────┘ └───────────┘ │
|
|
70
|
+
└──────────────┬──────────────┘
|
|
71
|
+
│ OCR output
|
|
72
|
+
┌──────────────▼──────────────┐
|
|
73
|
+
│ Task processing │
|
|
74
|
+
│ │
|
|
75
|
+
│ parse → (skip, OCR only) │
|
|
76
|
+
│ extract → structured extract│
|
|
77
|
+
│ classify → classification │
|
|
78
|
+
│ split → document splitting │
|
|
79
|
+
│ redact → redaction │
|
|
80
|
+
└─────────────────────────────┘
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The API runs OCR first, then applies the task you asked for to the OCR output. For `parse`, the task step is skipped — you get the OCR result directly.
|
|
84
|
+
|
|
85
|
+
## Why Choose HyperAPI?
|
|
86
|
+
|
|
87
|
+
Commercial LLMs (GPT, Claude, Gemini) understand what they *see*. HyperAPI understands what's *correct*.
|
|
88
|
+
|
|
89
|
+
Real-World Case: The Billing Typo
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
Invoice Line Item:
|
|
93
|
+
Date: 08/11/2025
|
|
94
|
+
Activity: Hours
|
|
95
|
+
Quantity: 0.15 ← Document shows "0.15" (typo for 0:15)
|
|
96
|
+
Rate: 350.00
|
|
97
|
+
Amount: 87.50
|
|
98
|
+
|
|
99
|
+
❌ Commercial LLMs: quantity = 0.15 (52.50 ≠ 87.50, math doesn't work)
|
|
100
|
+
✅ HyperAPI: quantity = 0:15 (validates: 0.25 hrs × 350 = 87.50 ✓)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Installation
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
pip install hyperapi-sdk
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
The package installs as `hyperapi-sdk` and imports as `hyperapi`. Python 3.9 or later.
|
|
110
|
+
|
|
111
|
+
> **Install `hyperapi-sdk`, never `hyperapi`.** The `hyperapi` name on PyPI does not
|
|
112
|
+
> belong to us. The only official package is
|
|
113
|
+
> [`hyperapi-sdk`](https://pypi.org/project/hyperapi-sdk/), published from this repository
|
|
114
|
+
> with PyPI Trusted Publishing and signed attestations.
|
|
115
|
+
|
|
116
|
+
To install from a local clone instead:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
git clone https://github.com/hyprbots/hyperapi-sdk
|
|
120
|
+
cd hyperapi-sdk
|
|
121
|
+
python3 -m venv .venv
|
|
122
|
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
|
123
|
+
python -m pip install .
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Quick Start
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from hyperapi import HyperAPIClient
|
|
130
|
+
|
|
131
|
+
# Set HYPERAPI_KEY in your environment before starting the application.
|
|
132
|
+
client = HyperAPIClient()
|
|
133
|
+
|
|
134
|
+
# Process a financial document (parse + extract in one call)
|
|
135
|
+
result = client.process("invoice.png")
|
|
136
|
+
|
|
137
|
+
print(result["ocr"]) # parsed text of the document
|
|
138
|
+
fields = result["data"]["result"] # extracted fields
|
|
139
|
+
print(fields["entities"]) # header and party fields
|
|
140
|
+
print(fields["line_items"]) # validated line items
|
|
141
|
+
print(fields["summary"]) # totals, tax and currency
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
These fields come from the financial extractor, which is the default. If your
|
|
145
|
+
organization's default extract category is set to `non_financial`, the fields are
|
|
146
|
+
under `result["data"]["result"]["data"]` instead; call `client.extract(...,
|
|
147
|
+
category="financial")` to choose explicitly.
|
|
148
|
+
|
|
149
|
+
## Two-Step Pipeline
|
|
150
|
+
|
|
151
|
+
For more control, use parse and extract separately:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
# Step 1: Parse document (OCR)
|
|
155
|
+
ocr_result = client.parse("invoice.png")
|
|
156
|
+
print(ocr_result["result"]["ocr"]) # plain text, laid out like the page
|
|
157
|
+
|
|
158
|
+
# Step 2: Extract structured fields (from the same file)
|
|
159
|
+
fields = client.extract("invoice.png")
|
|
160
|
+
print(fields["result"])
|
|
161
|
+
|
|
162
|
+
# Parse a document with complex layout
|
|
163
|
+
ocr_result = client.parse("complex_table.pdf")
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## Advanced Parse (structured layout)
|
|
167
|
+
|
|
168
|
+
`mode="advanced"` (Plus plan or higher) returns structured output: each page gains a
|
|
169
|
+
`structured` dict with `html`, `markdown`, and `regions` — tables come back as
|
|
170
|
+
tables, not flattened text. Slower than `mode="fast"`. When `mode` is omitted
|
|
171
|
+
the SDK sends nothing and the API default applies (`fast` unless your
|
|
172
|
+
organization is configured otherwise).
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
result = client.parse("annual_report.pdf", mode="advanced")
|
|
176
|
+
page = result["result"]["pages"][0]
|
|
177
|
+
print(page["structured"]["markdown"]) # the page as markdown
|
|
178
|
+
print(page["structured"]["regions"]) # typed regions with bounding boxes
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### Fast-mode response shape
|
|
182
|
+
|
|
183
|
+
In `fast` mode the API returns boxes, page images and the document layout by
|
|
184
|
+
default. The SDK's `include_boxes`, `include_image`, `include_layout` and
|
|
185
|
+
`parse_figures` arguments default to `None`, which leaves the choice to the API;
|
|
186
|
+
pass `False` (or `parse_figures="none"`) to opt out of a part you do not need.
|
|
187
|
+
`mode="advanced"` returns `structured` instead and produces none of the fields
|
|
188
|
+
below.
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
result = client.parse("invoice.pdf") # API defaults: everything on
|
|
192
|
+
lean = client.parse("invoice.pdf", include_boxes=False, include_image=False,
|
|
193
|
+
include_layout=False) # text and geometry only
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
| Field | Where | Meaning |
|
|
197
|
+
|---|---|---|
|
|
198
|
+
| `ocr` | `result` | Full text of the document, pages joined by blank lines; prefer `pages` for per-page work |
|
|
199
|
+
| `pages[].text` | per page | The page's text |
|
|
200
|
+
| `pages[].dimensions` / `page_size` / `background` | per page | Pixel space of every `bbox`; the page's own size (`pt` for PDF/XPS, `px` for images); page background colour. PDF, XPS and image inputs |
|
|
201
|
+
| `pages[].boxes` | per page | Line boxes `{text, bbox: [left, top, right, bottom], confidence}`. Off with `include_boxes=False`. Office documents return boxes only together with a page image |
|
|
202
|
+
| `pages[].word_boxes` | per page | Per-word boxes with typography: `font`, `size`, `color`, `bold`, `italic`, `background`, `font_source` (`document` from the file's text layer, `model` estimated from pixels). PDF, XPS and images; keys omitted when not stated |
|
|
203
|
+
| `pages[].image_url` | per page | Presigned page image, valid about 15 minutes. Off with `include_image=False` |
|
|
204
|
+
| `pages[].layout` / `pages[].layout_text` | per page | Detected regions in reading order with `bbox`, and the text rebuilt around them. `result.layout_text` carries the whole document. Off with `include_layout=False` |
|
|
205
|
+
| `pages[].gaps` | per page | Large empty vertical bands between two consecutive blocks in the same column, as `{bbox, height, after, before, ratio}`. Present only on pages that have one. Information only |
|
|
206
|
+
| `blocks[]` | `result` | The document's components (headings, paragraphs, tables, figures, …) in reading order across all pages: `id` (`b<page>-<n>`), `order`, `page`, `label`, `bbox`, `html`, `heading` (level 1-6), `group`, `furniture`, `style`. `empty: true` marks a block with no text and nothing drawn that is kept because it still occupies its box. `paint` on an embedded-picture block gives its `index` in the page's paint order and the `asset` it was drawn from |
|
|
207
|
+
| `groups[]` | `result` | The outline built over `blocks`: `section` and `preamble` groups form the tree; `figure`, `table`, `list`, `formula`, `algorithm`, `note` and `aside` are self-contained; `page_header` / `page_footer` hold running heads and feet (skip them when rebuilding text). Each has `id`, `kind`, `pages`, `children` (block and group ids in reading order), `boxes`, and `level` / `heading` on sections |
|
|
208
|
+
| `figure_parse` | `result` | Summary of figure parsing: `requested`, `available`, `blocks_total`, `blocks_parsed`, `blocks_skipped`, `gaps`. Regions that were parsed gain `content` and `parse_status` in `layout` |
|
|
209
|
+
| `metadata.groups_profile` | envelope | The grouping profile actually applied, reported when `groups_profile="B"` was requested (falls back to `A` where `B` cannot be used) |
|
|
210
|
+
|
|
211
|
+
`parse_figures` takes a comma-separated subset of `image`, `chart`, `table` (or
|
|
212
|
+
`"none"`) and requires the layout to be on; a parsed chart's `content` is a
|
|
213
|
+
markdown table, an image's is its caption or text, a table's is HTML.
|
|
214
|
+
`groups_profile="A"` (the default) gives a tree in reading order in which every
|
|
215
|
+
block belongs to exactly one group; `"B"` ranks headings by measured type size,
|
|
216
|
+
binds captions to their figure or table, joins tables that continue across
|
|
217
|
+
pages and is not in reading order (use `blocks[].order`). The full field
|
|
218
|
+
reference is on the public docs site at
|
|
219
|
+
[apis.hyperbots.com/docs/api/parse](https://apis.hyperbots.com/docs/api/parse).
|
|
220
|
+
|
|
221
|
+
Re-parsing the same document within 24 hours returns the **cached** OCR output,
|
|
222
|
+
so a retry after a bad parse hands back the same bad parse. Pass
|
|
223
|
+
`force_refresh=True` to re-run OCR and overwrite the stored result:
|
|
224
|
+
|
|
225
|
+
```python
|
|
226
|
+
result = client.parse("annual_report.pdf", mode="advanced", force_refresh=True)
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
A forced run is billed at full price where a cached one costs nothing, so use
|
|
230
|
+
it when a result actually looks wrong — not as a default.
|
|
231
|
+
|
|
232
|
+
### Large documents (beyond the advanced page cap)
|
|
233
|
+
|
|
234
|
+
Advanced parse has a page and byte ceiling that depends on your plan; past
|
|
235
|
+
either limit the server returns `413`. Read the effective numbers for your
|
|
236
|
+
account from `client.get_limits()` rather than hard-coding them:
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
limits = client.get_limits() # GET /v1/limits
|
|
240
|
+
print(limits["parse_advanced"]) # {"max_bytes": ..., "max_pages": ...}
|
|
241
|
+
print(limits.get("bulk_parse")) # None when the raised path is not offered
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
The raised ceiling (`bulk_parse` in the limits response) applies only when every
|
|
245
|
+
one of these holds, or you get the ordinary `413`:
|
|
246
|
+
|
|
247
|
+
| Condition | Why |
|
|
248
|
+
|---|---|
|
|
249
|
+
| `mode="advanced"` | `mode="fast"` is never page-capped |
|
|
250
|
+
| Submitted **asynchronously** | A multi-hour job can't be served on one connection |
|
|
251
|
+
| Plan that includes bulk advanced parse | Hours of processing time is a provisioned privilege |
|
|
252
|
+
| Called with an **API key** (not the dashboard) | The playground has a human waiting on a short timeout |
|
|
253
|
+
| Within the `bulk_parse` page and byte limits | The hard ceiling for this path |
|
|
254
|
+
|
|
255
|
+
The SDK already satisfies the async and API-key conditions — every convenience
|
|
256
|
+
method submits with `X-Async: true`, and the server records the source of the
|
|
257
|
+
request. Nothing to pass; the server decides. The server never tells you *which*
|
|
258
|
+
condition you missed, so a surprise `413` on a large document is most likely
|
|
259
|
+
the plan.
|
|
260
|
+
|
|
261
|
+
> **Availability.** The raised ceiling is not offered on every account. If
|
|
262
|
+
> `bulk_parse` is absent from `get_limits()`, the standard `parse_advanced`
|
|
263
|
+
> ceiling stands.
|
|
264
|
+
|
|
265
|
+
The document is processed in page ranges, but stays **one**
|
|
266
|
+
request — one `request_id`, one usage record, one job. Two things differ from an
|
|
267
|
+
ordinary parse:
|
|
268
|
+
|
|
269
|
+
**1. The result arrives as a URL, not inline.** A 500-page structured result is
|
|
270
|
+
far too large to embed in the job, so `pages` and `ocr` are *absent* and you get
|
|
271
|
+
a presigned `result_url` instead:
|
|
272
|
+
|
|
273
|
+
```python
|
|
274
|
+
import httpx
|
|
275
|
+
|
|
276
|
+
job = client.submit_parse("500_page_report.pdf", mode="advanced")
|
|
277
|
+
result = client.wait_for_job(job, timeout=7200) # see the deadline note below
|
|
278
|
+
|
|
279
|
+
if url := result.get("result_url"): # large-document delivery
|
|
280
|
+
payload = httpx.get(url).json() # fetch promptly — expires in minutes
|
|
281
|
+
pages = payload["result"]["pages"]
|
|
282
|
+
else:
|
|
283
|
+
pages = result["result"]["pages"] # ordinary inline result
|
|
284
|
+
|
|
285
|
+
meta = result["metadata"]
|
|
286
|
+
print(meta["total_pages"], meta["segments_total"], meta["segments_failed"])
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
`result_url` is re-signed on **every poll** and expires in minutes. If it lapses,
|
|
290
|
+
call `get_job(job.job_id)` again for a fresh one — the job itself lives 24 h.
|
|
291
|
+
|
|
292
|
+
**2. It can complete with `gaps`.** Page ranges that failed after retries are
|
|
293
|
+
reported in `metadata["gaps"]`; the document still completes, and **only pages
|
|
294
|
+
that actually processed are billed**. `gaps` is always present on a large-document
|
|
295
|
+
result, empty when every segment succeeded — so test the field, don't infer
|
|
296
|
+
completeness from counts:
|
|
297
|
+
|
|
298
|
+
```python
|
|
299
|
+
for gap in result["metadata"]["gaps"]:
|
|
300
|
+
print(f"pages {gap} missing")
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
To watch progress while it runs, poll `get_job()` yourself — the segment counters
|
|
304
|
+
sit on the job envelope, and `wait_for_job` returns only the result:
|
|
305
|
+
|
|
306
|
+
```python
|
|
307
|
+
import time
|
|
308
|
+
|
|
309
|
+
job = client.submit_parse("500_page_report.pdf", mode="advanced")
|
|
310
|
+
while (envelope := client.get_job(job.job_id))["status"] == "pending":
|
|
311
|
+
print(envelope.get("segments_done"), "/", envelope.get("segments_total"))
|
|
312
|
+
time.sleep(30)
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
> **Raise `poll_timeout` for these.** The default is **3600 s (60 min)**, and a
|
|
316
|
+
> 500-page advanced parse can exceed it. `wait_for_job` gives up at the deadline,
|
|
317
|
+
> but the job **keeps running** server-side — a `JobTimeoutError` is the client
|
|
318
|
+
> abandoning the wait, not the platform abandoning the work. Re-attach with
|
|
319
|
+
> `client.get_job(job.job_id)` (jobs live 24 h, and progress refreshes that
|
|
320
|
+
> window). Pass a deadline that matches the document, e.g.
|
|
321
|
+
> `client.parse(..., poll_timeout=7200)`.
|
|
322
|
+
|
|
323
|
+
## Limits by operation
|
|
324
|
+
|
|
325
|
+
Upload accepts any supported file up to your byte ceiling, but each operation
|
|
326
|
+
enforces its own page ceiling when the document is submitted — **before** any
|
|
327
|
+
billable processing runs. The ceilings can differ by plan and change over time,
|
|
328
|
+
so read them from the API instead of hard-coding them:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
limits = client.get_limits()
|
|
332
|
+
for task, ceiling in limits.items():
|
|
333
|
+
if isinstance(ceiling, dict):
|
|
334
|
+
print(task, ceiling["max_bytes"], ceiling.get("max_pages")) # max_pages None = no page cap
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
| Key in `get_limits()` | Operation | Notes |
|
|
338
|
+
|---|---|---|
|
|
339
|
+
| `max_upload_bytes` | upload | Your effective upload grant; a task may admit less than this |
|
|
340
|
+
| `parse_fast` | Parse (fast) | `max_pages` is `null`: never page-capped |
|
|
341
|
+
| `parse_advanced` | Parse (advanced) | Page-capped |
|
|
342
|
+
| `bulk_parse` | Parse (advanced, async, bulk) | Present only where the raised ceiling above is offered |
|
|
343
|
+
| `extract_fast` | Extract (fast) | Never page-capped |
|
|
344
|
+
| `extract_advanced` | Extract (advanced) | Present only where advanced extract is offered |
|
|
345
|
+
| `classify` | Classify | Reads the first pages it needs |
|
|
346
|
+
| `split` | Split | |
|
|
347
|
+
| `redact` | Redact / Deidentify | `max_pages` caps inline output. `urls_max_pages` is present only where `output="urls"` is offered and caps that mode. Over-cap documents return `413` up front, before any OCR is billed |
|
|
348
|
+
|
|
349
|
+
A missing key means that mode is not offered to your account, never "unlimited".
|
|
350
|
+
The same `limits` object rides on every `/v1/documents/upload` response.
|
|
351
|
+
Asynchronous submissions return `200` when the job is *accepted* — the final
|
|
352
|
+
verdict, including a limit rejection, lands on the job record you poll.
|
|
353
|
+
|
|
354
|
+
A submission the server refuses outright with `413` (a document over the
|
|
355
|
+
operation's page cap) raises that operation's error — `ParseError`,
|
|
356
|
+
`ExtractError`, `ClassifyError`, `SplitError` or `RedactError` — with
|
|
357
|
+
`status_code == 413` and the server's message. `DocumentUploadError` is raised
|
|
358
|
+
only by the upload step, for example a file over `max_upload_bytes`.
|
|
359
|
+
|
|
360
|
+
## Extract: Basic vs Advanced
|
|
361
|
+
|
|
362
|
+
Basic `extract()` runs the tier you select with `category`; **Advanced**
|
|
363
|
+
`extract_advanced()` auto-detects the document type for you (no `category`).
|
|
364
|
+
|
|
365
|
+
```python
|
|
366
|
+
# Basic Financial: HyperAPI uses the invoice and receipt fields
|
|
367
|
+
fields = client.extract("invoice.pdf") # no category: organization default (platform default: financial)
|
|
368
|
+
|
|
369
|
+
# Basic Other: define the exact output shape for this request
|
|
370
|
+
schema = {
|
|
371
|
+
"policy_number": None,
|
|
372
|
+
"active": False,
|
|
373
|
+
"coverage": {"medical": "unselected"},
|
|
374
|
+
}
|
|
375
|
+
fields = client.extract(
|
|
376
|
+
"policy.pdf",
|
|
377
|
+
category="non_financial",
|
|
378
|
+
schema=schema,
|
|
379
|
+
)
|
|
380
|
+
print(fields["result"]["data"])
|
|
381
|
+
|
|
382
|
+
# The schema can also come from a JSON file: pass a Path.
|
|
383
|
+
# A plain str is always read as JSON text, never as a file name.
|
|
384
|
+
from pathlib import Path
|
|
385
|
+
fields = client.extract("policy.pdf", category="non_financial",
|
|
386
|
+
schema=Path("schema.json"))
|
|
387
|
+
|
|
388
|
+
# Advanced — auto-detects the type, no category to pick
|
|
389
|
+
fields = client.extract_advanced("mixed_document.pdf")
|
|
390
|
+
print(fields["result"]["entities"])
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Both also accept `parse_mode` to pick the parse mode — `"fast"`
|
|
394
|
+
(default, quick text extraction) or `"advanced"` (structured output with markdown,
|
|
395
|
+
suited to dense tables and forms; slower, costs more, Plus plan or higher).
|
|
396
|
+
It's independent of `category` and of the Basic/Advanced split:
|
|
397
|
+
|
|
398
|
+
```python
|
|
399
|
+
fields = client.extract("dense_invoice.pdf", parse_mode="advanced")
|
|
400
|
+
fields = client.extract_advanced("complex_form.pdf", parse_mode="advanced")
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
## Classify / Split Options
|
|
404
|
+
|
|
405
|
+
`classify()` and `split()` accept an `options` dict of service-level knobs,
|
|
406
|
+
validated server-side:
|
|
407
|
+
|
|
408
|
+
```python
|
|
409
|
+
# Classifier: pipeline depth, restricted class set, custom instructions
|
|
410
|
+
client.classify(
|
|
411
|
+
"doc.pdf",
|
|
412
|
+
options={
|
|
413
|
+
"mode": "thorough", # "fast" | "balanced" | "thorough"
|
|
414
|
+
"active_classes": ["invoice", "purchase_order"],
|
|
415
|
+
"system_instruction": "Prefer invoice when ambiguous.",
|
|
416
|
+
},
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
# Splitter: thinking toggle, custom segment classes, domain guidelines
|
|
420
|
+
client.split(
|
|
421
|
+
"binder.pdf",
|
|
422
|
+
options={
|
|
423
|
+
"use_thinking": True,
|
|
424
|
+
"extend_segment_classes": True,
|
|
425
|
+
"segment_classes": {"remittance_advice": "Payment remittance advice"},
|
|
426
|
+
},
|
|
427
|
+
)
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
Note: `options["mode"]` (classifier pipeline depth) is a different knob from
|
|
431
|
+
the top-level `mode=` keyword (task selector) — they travel in different parts
|
|
432
|
+
of the request.
|
|
433
|
+
|
|
434
|
+
## Redact / Deidentify
|
|
435
|
+
|
|
436
|
+
> A page cap applies to redact — an over-cap file is refused with `413` (raised
|
|
437
|
+
> as `RedactError`) before any processing is billed. Read the current values
|
|
438
|
+
> with `client.get_limits()["redact"]`; see
|
|
439
|
+
> [Limits by operation](#limits-by-operation).
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
`redact()` masks PII with black boxes; `mode="deidentify"` overlays synthetic
|
|
443
|
+
replacements instead. Built-in PII types: PERSON_NAME, COMPANY_NAME, EMAIL,
|
|
444
|
+
ADDRESS, WEBSITE, PHONE, and CREDENTIALS (passwords, API keys, tokens,
|
|
445
|
+
secrets).
|
|
446
|
+
|
|
447
|
+
```python
|
|
448
|
+
result = client.redact("contract.pdf", mode="deidentify", include_logos=True)
|
|
449
|
+
for page_png_b64 in result["result"]["images"]:
|
|
450
|
+
... # masked page images (inline base64)
|
|
451
|
+
print(result["result"]["summary"]) # {"PERSON_NAME": 2, "EMAIL": 1, ...}
|
|
452
|
+
|
|
453
|
+
# Streaming output — masked pages as short-lived presigned links instead of
|
|
454
|
+
# inline base64, with a higher page cap. Feature-detect first:
|
|
455
|
+
# client.get_limits()["redact"] carries urls_max_pages only where the mode is
|
|
456
|
+
# offered. Not combinable with include_logos.
|
|
457
|
+
result = client.redact("long-contract.pdf", output="urls")
|
|
458
|
+
client.download_pages(result, "masked/") # pages[*].image_url — works as-is
|
|
459
|
+
|
|
460
|
+
# Customize the detected PII type set
|
|
461
|
+
client.redact(
|
|
462
|
+
"form.pdf",
|
|
463
|
+
pii_config={"mode": "extend", "types": [{"name": "SSN"}]},
|
|
464
|
+
)
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
## Saving page images
|
|
468
|
+
|
|
469
|
+
`download_pages()` writes a result's page images into a folder, so you don't have
|
|
470
|
+
to chase presigned URLs before they expire. It works with `parse()` results that
|
|
471
|
+
carry page images (on by default) and with `redact(output="urls")`.
|
|
472
|
+
|
|
473
|
+
```python
|
|
474
|
+
parsed = client.parse("contract.pdf")
|
|
475
|
+
paths = client.download_pages(parsed, "out/pages")
|
|
476
|
+
print(paths) # [PosixPath('out/pages/page-1.webp'), …]
|
|
477
|
+
|
|
478
|
+
masked = client.redact("contract.pdf", output="urls")
|
|
479
|
+
client.download_pages(masked, "out/masked", prefix="masked") # out/masked/masked-1.png …
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
The folder is created if missing, files are named `<prefix>-<page number>.<ext>`, and the
|
|
483
|
+
extension follows what the server actually served — `.webp` for parse, `.png` for redact.
|
|
484
|
+
On the async client it's the same call with `await`, and pages download concurrently.
|
|
485
|
+
|
|
486
|
+
If the URLs have already expired you get a clear error rather than a bare 403 — re-poll
|
|
487
|
+
with `get_job(job_id)` for fresh ones (the job lives 24 h) and call it again.
|
|
488
|
+
|
|
489
|
+
> Default (inline) `redact()` is the exception: it returns `images` as **inline base64
|
|
490
|
+
> strings**, not URLs, so there is nothing to download — decode them yourself with
|
|
491
|
+
> `base64.b64decode()`. With `output="urls"` the result carries `pages[*].image_url`
|
|
492
|
+
> instead, and `download_pages()` accepts it like any other paged result.
|
|
493
|
+
|
|
494
|
+
## Jobs Management
|
|
495
|
+
|
|
496
|
+
```python
|
|
497
|
+
# List the org's recent jobs (summary rows, newest first)
|
|
498
|
+
for row in client.list_recent_jobs(limit=100, source="api"):
|
|
499
|
+
print(row["job_id"], row["task"], row["status"])
|
|
500
|
+
|
|
501
|
+
# Cancel an in-flight job (idempotent; completed jobs keep their result)
|
|
502
|
+
job = client.submit_extract("big_binder.pdf")
|
|
503
|
+
client.delete_job(job.job_id)
|
|
504
|
+
```
|
|
505
|
+
|
|
506
|
+
A cancelled job is reported by `get_job()` as `status: "failed"` with an `error`
|
|
507
|
+
that starts with `cancelled:`. `wait_for_job()` on such a job raises
|
|
508
|
+
`JobCancelledError` (carrying `job_id`) as soon as it sees that state, rather
|
|
509
|
+
than waiting until its deadline.
|
|
510
|
+
|
|
511
|
+
### Recovering which job belongs to which document
|
|
512
|
+
|
|
513
|
+
Each summary row carries a `document_key` — the server-side handle for that
|
|
514
|
+
job's document — alongside `filename`. If you are reconciling a batch, match on
|
|
515
|
+
`document_key` and not on `filename`: `filename` is whatever was sent at upload
|
|
516
|
+
and is not required to be unique, so fifty documents named `invoice.pdf`
|
|
517
|
+
produce fifty rows you cannot tell apart.
|
|
518
|
+
|
|
519
|
+
```python
|
|
520
|
+
for row in client.list_recent_jobs(limit=100):
|
|
521
|
+
print(row["job_id"], row["document_key"], row["filename"], row["status"])
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
The robust pattern with this SDK is to keep the `job_id` at submit time —
|
|
525
|
+
`submit_*` returns a `Job` immediately, so the mapping costs nothing:
|
|
526
|
+
|
|
527
|
+
```python
|
|
528
|
+
submitted = {}
|
|
529
|
+
for path in paths:
|
|
530
|
+
job = client.submit_parse(path)
|
|
531
|
+
submitted[job.job_id] = path # your own record
|
|
532
|
+
|
|
533
|
+
for job_id, path in submitted.items():
|
|
534
|
+
print(path, client.get_job(job_id)["status"])
|
|
535
|
+
```
|
|
536
|
+
|
|
537
|
+
> **Note.** `submit_*` performs the upload internally and does not surface the
|
|
538
|
+
> `document_key` it used, and no public method accepts a pre-uploaded
|
|
539
|
+
> `document_key`. So while `document_key` identifies rows uniquely, you cannot
|
|
540
|
+
> currently pre-compute it to build your own key→file map through the SDK —
|
|
541
|
+
> retain the `job_id` instead. `document_key` is `None` on older jobs, and the
|
|
542
|
+
> listing only covers the last 24 hours.
|
|
543
|
+
|
|
544
|
+
## Batch API (async, deferred)
|
|
545
|
+
|
|
546
|
+
Process many documents in one async job. You submit already-uploaded documents,
|
|
547
|
+
get a `batch_id` back immediately, and poll (or wait) for per-document results —
|
|
548
|
+
the work runs on spare capacity, so it never competes with your interactive
|
|
549
|
+
calls. Supported endpoints: `/v1/parse`, `/v1/extract`, `/v1/extract-omni` (advanced extract), `/v1/classify`, `/v1/split`, `/v1/redact`.
|
|
550
|
+
|
|
551
|
+
For `/v1/parse` batches, `parse_mode="advanced"` requests advanced parsing.
|
|
552
|
+
Advanced parse in a batch is plan-dependent: a batch that asks for it may be
|
|
553
|
+
rejected with `400` or `403` where it is not available to your account. Each
|
|
554
|
+
finished item's `result_url` is a time-limited presigned link to its result
|
|
555
|
+
JSON — download it promptly, and re-poll `get_batch()` for a fresh one if it
|
|
556
|
+
has lapsed.
|
|
557
|
+
|
|
558
|
+
```python
|
|
559
|
+
# Upload first, or use the convenience that uploads for you:
|
|
560
|
+
batch = client.create_batch_from_files(
|
|
561
|
+
endpoint="/v1/classify",
|
|
562
|
+
file_paths=["a.pdf", "b.pdf", "c.pdf"],
|
|
563
|
+
idempotency_key="nightly-2026-07-07", # resubmitting returns the same batch
|
|
564
|
+
)
|
|
565
|
+
print(batch["batch_id"], batch["status"], batch["total_items"])
|
|
566
|
+
|
|
567
|
+
# Block until the batch finishes (or poll get_batch yourself):
|
|
568
|
+
result = client.wait_for_batch(batch["batch_id"], timeout=3600)
|
|
569
|
+
print(result["counts"]) # {total, queued, processing, done, failed}
|
|
570
|
+
for item in result["items"]:
|
|
571
|
+
print(item["doc_index"], item["status"], item.get("result_url"))
|
|
572
|
+
|
|
573
|
+
# Or drive it manually:
|
|
574
|
+
client.get_batch(batch["batch_id"]) # single status poll
|
|
575
|
+
client.list_batches(limit=20) # your recent batches
|
|
576
|
+
client.cancel_batch(batch["batch_id"]) # stop queued items (in-flight finish)
|
|
577
|
+
|
|
578
|
+
# Already have document_keys (from client.upload_document)? Skip the upload:
|
|
579
|
+
client.create_batch(endpoint="/v1/parse", document_keys=[k1, k2], parse_mode="fast")
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
The async client mirrors every method (`await async_client.create_batch(...)`,
|
|
583
|
+
`await async_client.wait_for_batch(...)`, and `create_batch_from_files` uploads
|
|
584
|
+
the files concurrently).
|
|
585
|
+
|
|
586
|
+
## How It Works (Submit + Poll)
|
|
587
|
+
|
|
588
|
+
Every long-running operation (`parse`, `extract`, `classify`, `split`, `process`) submits asynchronously and polls a job-status endpoint under the hood. From the caller's perspective the SDK looks synchronous — `result = client.extract(file)` blocks until the result is ready — but **each individual HTTP request stays sub-second**, so the SDK is timeout-immune at any CDN edge.
|
|
589
|
+
|
|
590
|
+
```
|
|
591
|
+
client.extract(file)
|
|
592
|
+
│
|
|
593
|
+
├─ POST /v1/documents/upload (presigned S3 URL)
|
|
594
|
+
├─ PUT <S3 URL> (upload bytes directly)
|
|
595
|
+
├─ POST /v1/extract X-Async: true → { job_id, poll_url }
|
|
596
|
+
├─ GET /v1/jobs/{id} (every 3 s, retries on 5xx)
|
|
597
|
+
├─ GET /v1/jobs/{id} …
|
|
598
|
+
└─ GET /v1/jobs/{id} → { status: "completed", result: {...} }
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
This is the pattern used by [LlamaParse](https://docs.llamaindex.ai/en/stable/llama_cloud/llama_parse/) and [Reducto](https://docs.reducto.ai/) for the same reason.
|
|
602
|
+
|
|
603
|
+
> **Rate limits and polling.** The API rate-limits requests **per organization** over a rolling 60-second window; the **free tier allows 1 request per 60 s**. Job-status polls (`GET /v1/jobs/{id}`) have their own generous per-organization limit and do not use up your plan's request limit, so a submit followed by polling does not trip a `429` on its own. Polling a very large number of jobs at the same time can still be throttled; when that happens, `wait_for_job` / `wait_for_jobs` / `wait_for_batch` **sleep for the server's `Retry-After` and resume**, rather than failing the call. If the remaining `poll_timeout` is shorter than that wait, the call raises `RateLimitError` (with `retry_after` set) so you can wait and resume with `wait_for_job`. A single-shot `get_job()` still raises `RateLimitError` immediately — only the *waiting* helpers back off. Submissions are what your plan limits: a rate-limited `submit_<op>` (or convenience call) raises `RateLimitError`, so on the free tier run one operation at a time.
|
|
604
|
+
|
|
605
|
+
## Async client
|
|
606
|
+
|
|
607
|
+
`AsyncHyperAPIClient` is an `async`/`await` twin of `HyperAPIClient` for code that already runs inside an event loop — FastAPI / Starlette / aiohttp servers, LLM agent loops, Discord/Slack bots, and any high-concurrency processor that fans out with `asyncio.gather`. Same constructor signature, same method names, same `Job` dataclass, same typed exceptions — swap the import and add `await`.
|
|
608
|
+
|
|
609
|
+
```python
|
|
610
|
+
import asyncio
|
|
611
|
+
from hyperapi import AsyncHyperAPIClient
|
|
612
|
+
|
|
613
|
+
async def main():
|
|
614
|
+
async with AsyncHyperAPIClient() as client: # reads HYPERAPI_KEY
|
|
615
|
+
result = await client.extract("invoice.pdf")
|
|
616
|
+
print(result)
|
|
617
|
+
|
|
618
|
+
asyncio.run(main())
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
### When to pick which client
|
|
622
|
+
|
|
623
|
+
> **If your code already says `async def` somewhere — use the async client. Otherwise, use sync.**
|
|
624
|
+
|
|
625
|
+
| You're building… | Use |
|
|
626
|
+
|---|---|
|
|
627
|
+
| Python script / Jupyter notebook / Airflow task / Celery worker | `HyperAPIClient` (sync) |
|
|
628
|
+
| FastAPI / Starlette / aiohttp service | `AsyncHyperAPIClient` |
|
|
629
|
+
| LLM agent loop that interleaves multiple `await` calls | `AsyncHyperAPIClient` |
|
|
630
|
+
| Discord / Slack / Telegram bot | `AsyncHyperAPIClient` |
|
|
631
|
+
| Fan-out across many docs in one process | `AsyncHyperAPIClient` + `asyncio.gather` |
|
|
632
|
+
|
|
633
|
+
A sync call inside an async event loop blocks the **entire** event loop (not just your handler) for the duration of the call. For HyperAPI's multi-minute extracts that means every other in-flight request stalls. The async client yields between polls so the loop stays responsive.
|
|
634
|
+
|
|
635
|
+
### FastAPI integration
|
|
636
|
+
|
|
637
|
+
One client per application, reused across requests, closed on shutdown via the lifespan handler:
|
|
638
|
+
|
|
639
|
+
```python
|
|
640
|
+
from contextlib import asynccontextmanager
|
|
641
|
+
from fastapi import FastAPI, UploadFile
|
|
642
|
+
from hyperapi import AsyncHyperAPIClient
|
|
643
|
+
|
|
644
|
+
@asynccontextmanager
|
|
645
|
+
async def lifespan(app: FastAPI):
|
|
646
|
+
app.state.hyperapi = AsyncHyperAPIClient() # reads HYPERAPI_KEY
|
|
647
|
+
try:
|
|
648
|
+
yield
|
|
649
|
+
finally:
|
|
650
|
+
await app.state.hyperapi.aclose() # release connection pool
|
|
651
|
+
|
|
652
|
+
app = FastAPI(lifespan=lifespan)
|
|
653
|
+
|
|
654
|
+
@app.post("/extract")
|
|
655
|
+
async def extract_endpoint(file: UploadFile):
|
|
656
|
+
# save UploadFile to a tmp path, then:
|
|
657
|
+
return await app.state.hyperapi.extract(tmp_path)
|
|
658
|
+
```
|
|
659
|
+
|
|
660
|
+
A runnable version (standalone CLI + FastAPI snippet) lives at [`examples/async_quickstart.py`](https://github.com/hyprbots/hyperapi-sdk/blob/main/examples/async_quickstart.py).
|
|
661
|
+
|
|
662
|
+
### Concurrent fan-out
|
|
663
|
+
|
|
664
|
+
`asyncio.gather` runs many operations concurrently on one event loop — no thread pool, no GIL contention:
|
|
665
|
+
|
|
666
|
+
```python
|
|
667
|
+
async with AsyncHyperAPIClient() as client:
|
|
668
|
+
results = await asyncio.gather(*(client.extract(p) for p in paths))
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
Each submission counts against your plan's request limit, so size the fan-out to
|
|
672
|
+
it: a submission over the limit raises `RateLimitError` (with `retry_after`).
|
|
673
|
+
The status polls behind each call have their own limit and do not add to it.
|
|
674
|
+
|
|
675
|
+
### Notes on parity
|
|
676
|
+
|
|
677
|
+
- **`wait_for_jobs([...])`** uses `asyncio.gather` under the hood — true concurrent polling, with each job given the full timeout. The first job to fail or time out raises, and the rest are cancelled; a timeout raises `JobTimeoutError` whose `job_id` is that one job's id. The sync client shares one deadline across all jobs instead, and on timeout raises a single `JobTimeoutError` whose `job_id` is the comma-joined ids of every job still pending (for example `"A,B"`).
|
|
678
|
+
- **Submit-and-poll is identical** — `AsyncHyperAPIClient.submit_extract(...)` returns the same `Job` dataclass; `await client.wait_for_job(job)` blocks the coroutine without blocking the event loop.
|
|
679
|
+
- **`User-Agent`** carries an `-async` suffix so server-side analytics can split traffic by client type.
|
|
680
|
+
|
|
681
|
+
### Advanced: explicit submit + poll
|
|
682
|
+
|
|
683
|
+
If you want fire-and-forget semantics (e.g., to integrate with your own job queue or render a custom progress UI), use `submit_<op>(...)` to get a `Job` handle, then `wait_for_job(...)` or `get_job(...)` yourself:
|
|
684
|
+
|
|
685
|
+
```python
|
|
686
|
+
from hyperapi import HyperAPIClient
|
|
687
|
+
|
|
688
|
+
client = HyperAPIClient(api_key="hk_live_your_key")
|
|
689
|
+
|
|
690
|
+
# Submit and walk away
|
|
691
|
+
job = client.submit_extract("contract.pdf")
|
|
692
|
+
print(job.job_id)
|
|
693
|
+
|
|
694
|
+
# … later, in a different process ...
|
|
695
|
+
status = client.get_job(job.job_id) # one-shot poll, no waiting
|
|
696
|
+
if status["status"] == "completed":
|
|
697
|
+
print(status["result"])
|
|
698
|
+
|
|
699
|
+
# or block until done with full control over cadence
|
|
700
|
+
result = client.wait_for_job(job, timeout=600, interval=5)
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
`submit_parse`, `submit_extract`, `submit_classify`, `submit_split`, and `submit_redact` are all available.
|
|
704
|
+
|
|
705
|
+
### Polling configuration
|
|
706
|
+
|
|
707
|
+
Polling cadence is configurable on the constructor (defaults match the platform playground):
|
|
708
|
+
|
|
709
|
+
```python
|
|
710
|
+
client = HyperAPIClient(
|
|
711
|
+
api_key="hk_live_…",
|
|
712
|
+
poll_interval=3.0, # seconds between polls (default 3)
|
|
713
|
+
poll_timeout=3600.0, # max wait per job in seconds (default 3600)
|
|
714
|
+
poll_max_transient_retries=3, # per-poll retries on transient 5xx (default 3)
|
|
715
|
+
)
|
|
716
|
+
```
|
|
717
|
+
|
|
718
|
+
Or per-call:
|
|
719
|
+
|
|
720
|
+
```python
|
|
721
|
+
result = client.extract("scan.pdf", poll_timeout=600, poll_interval=5)
|
|
722
|
+
```
|
|
723
|
+
|
|
724
|
+
## API Reference
|
|
725
|
+
|
|
726
|
+
### `HyperAPIClient` and `AsyncHyperAPIClient`
|
|
727
|
+
|
|
728
|
+
```python
|
|
729
|
+
client = HyperAPIClient(
|
|
730
|
+
api_key: str = None, # API key (or set HYPERAPI_KEY env var)
|
|
731
|
+
base_url: str = None, # API endpoint (default: https://apis.hyperbots.com)
|
|
732
|
+
timeout: float = 120.0, # per-HTTP-call timeout (NOT total job time)
|
|
733
|
+
poll_interval: float = 3.0, # seconds between job-status polls
|
|
734
|
+
poll_timeout: float = 3600.0, # max wall-clock seconds to wait for a job
|
|
735
|
+
poll_max_transient_retries: int = 3,# transient-5xx retries on a single poll
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
# Async equivalent — identical constructor signature, every method is `async def`:
|
|
739
|
+
client = AsyncHyperAPIClient(api_key=..., base_url=..., ...)
|
|
740
|
+
# Use as an async context manager so the httpx.AsyncClient pool is released:
|
|
741
|
+
async with AsyncHyperAPIClient() as client:
|
|
742
|
+
result = await client.extract("invoice.pdf")
|
|
743
|
+
```
|
|
744
|
+
|
|
745
|
+
### Methods
|
|
746
|
+
|
|
747
|
+
Every method below exists on both clients with identical signatures. On `AsyncHyperAPIClient` each is a coroutine — prefix with `await`.
|
|
748
|
+
|
|
749
|
+
| Method | Pipeline | Description |
|
|
750
|
+
|--------|----------|-------------|
|
|
751
|
+
| `upload_document(file)` | presigned upload | Upload file, returns `document_key` (valid 24 h). |
|
|
752
|
+
| `parse(file)` | OCR only | Parse document into structured text. Submit + poll under the hood. |
|
|
753
|
+
| `extract(file, *, category=None, schema=None)` | OCR → structured extraction | Basic extractor. Financial uses the built-in fields. Other (`non_financial`) accepts a JSON output schema. Submit + poll. |
|
|
754
|
+
| `extract_advanced(file)` | OCR → structured extraction | Advanced extractor — auto-detects the document type (no `category`). Submit + poll. |
|
|
755
|
+
| `classify(file)` | OCR → classification | Classify document type. Submit + poll. |
|
|
756
|
+
| `split(file)` | OCR → document splitting | Split multi-document binders. Submit + poll. |
|
|
757
|
+
| `redact(file)` | OCR → redaction | Mask or deidentify PII (and optionally logos). Submit + poll. |
|
|
758
|
+
| `download_pages(result, dir, *, max_page_bytes=200 MiB)` | — | Write a result's page images to a folder (`parse()` with page images, or `redact(output="urls")`). A page larger than `max_page_bytes` raises `HyperAPIError` and leaves no file. |
|
|
759
|
+
| `process(file)` | OCR → parse + extract | Combined parse + extract sharing one upload. Submit + poll on both legs. |
|
|
760
|
+
| `submit_parse / submit_extract / submit_extract_advanced / submit_classify / submit_split / submit_redact` | OCR (+ task) | Submit asynchronously, return a `Job` immediately. |
|
|
761
|
+
| `get_job(job_id)` | — | One-shot status poll. No waiting, no retry. |
|
|
762
|
+
| `get_limits()` | — | Your account's effective upload and per-operation ceilings (`GET /v1/limits`). |
|
|
763
|
+
| `list_recent_jobs(*, limit=20, source=None)` | — | List the org's recent jobs (summary rows, newest first). |
|
|
764
|
+
| `delete_job(job_id)` | — | Cancel a job. Idempotent; completed jobs keep their result. A cancelled job reads back as `failed` with an error starting `cancelled:`. |
|
|
765
|
+
| `wait_for_job(job, *, timeout=None, interval=None)` | — | Block until the job completes, fails, or `timeout` elapses. |
|
|
766
|
+
| `wait_for_jobs([job1, job2], …)` | — | Poll multiple jobs concurrently. Sync: round-robin loop. Async: `asyncio.gather`. |
|
|
767
|
+
| **Lifecycle (sync)** `close()` / `with HyperAPIClient() as client:` | — | Release HTTP connection pool. |
|
|
768
|
+
| **Lifecycle (async)** `await aclose()` / `async with AsyncHyperAPIClient() as client:` | — | Release HTTP connection pool. |
|
|
769
|
+
|
|
770
|
+
### Common Parameters
|
|
771
|
+
|
|
772
|
+
| Parameter | Type | Default | Available On |
|
|
773
|
+
|-----------|------|---------|-------------|
|
|
774
|
+
| `mode` (parse) | `"fast"` \| `"advanced"` \| `None` | `None` (API default: `"fast"`) | parse — when omitted nothing is sent and the API default applies; `"advanced"` adds per-page `structured` layout |
|
|
775
|
+
| `include_boxes` (parse) | `bool \| None` | `None` (API default: on in `fast` mode) | parse — `False` leaves out `boxes` and `word_boxes` |
|
|
776
|
+
| `include_image` (parse) | `bool \| None` | `None` (API default: on in `fast` mode) | parse — `False` leaves out per-page `image_url` |
|
|
777
|
+
| `include_layout` (parse) | `bool \| None` | `None` (API default: on in `fast` mode) | parse — `False` leaves out `layout`, `layout_text`, `blocks`, `groups` and turns figure parsing off. `fast` mode only; `True` with `mode="advanced"` returns `400` |
|
|
778
|
+
| `parse_figures` (parse) | `str \| None` | `None` (API default: `"image,chart,table"` when the layout is on) | parse — comma-separated subset of `image`, `chart`, `table`, or `"none"`; requires the layout |
|
|
779
|
+
| `groups_profile` (parse) | `"A"` \| `"B"` \| `None` | `None` (API default: `"A"`) | parse — how `groups[]` is built; see the fast-mode response shape above |
|
|
780
|
+
| `force_refresh` | `bool` | `False` | parse / extract / extract_advanced / classify / split / redact — re-run instead of returning the cached result (a forced run is billed) |
|
|
781
|
+
| `category` (extract) | `"financial"` \| `"non_financial"` \| `None` | `None` (organization default; platform default `"financial"`; `"non_financial"` if `schema` is given) | extract — Basic extractor profile; `extract_advanced()` auto-detects instead (no `category`) |
|
|
782
|
+
| `schema` (extract) | `dict \| str \| Path \| None` | `None` | extract — blank JSON template that defines the output shape for this request. With `category="non_financial"` the template is filled directly; with `category="financial"` the invoice extractor runs and its output is remapped into your template. A `schema` with no `category` is sent as `"non_financial"`. A `str` is parsed as JSON text; pass a `pathlib.Path` to load a JSON file |
|
|
783
|
+
| `mode` (classify / split) | `str` | `"default"` | classify / split — task selector |
|
|
784
|
+
| `mode` (redact) | `"redact"` \| `"deidentify"` | `"redact"` | redact |
|
|
785
|
+
| `output` (redact) | `"inline"` \| `"urls"` | `"inline"` | redact — `"urls"` returns masked pages as presigned `pages[*].image_url` links with a higher page cap, where offered; other values raise `ValueError` client-side |
|
|
786
|
+
| `options` | `dict \| None` | `None` | classify / split — service knobs, sent as a JSON form field |
|
|
787
|
+
| `pii_config` / `include_logos` | `dict \| None` / `bool` | `None` / `False` | redact |
|
|
788
|
+
| `source` (list_recent_jobs) | `"api"` \| `"playground"` \| `None` | `None` | list_recent_jobs — channel filter; omitted returns all channels |
|
|
789
|
+
| `use_presigned` | `bool` | `True` | parse / extract / classify / split / redact |
|
|
790
|
+
| `poll_timeout` | `float` | constructor's | parse / extract / classify / split / redact / process |
|
|
791
|
+
| `poll_interval` | `float` | constructor's | parse / extract / classify / split / redact / process |
|
|
792
|
+
|
|
793
|
+
### Exceptions
|
|
794
|
+
|
|
795
|
+
| Class | Raised on |
|
|
796
|
+
|---|---|
|
|
797
|
+
| `HyperAPIError` | Base — anything not specifically classified |
|
|
798
|
+
| `AuthenticationError` | 401 from server, missing API key |
|
|
799
|
+
| `RateLimitError` | 429 from server (carries `retry_after`, `tier`, `limit`) |
|
|
800
|
+
| `ParseError` / `ExtractError` / `ClassifyError` / `SplitError` / `RedactError` | The corresponding op fails — including a `413` when the document is over that operation's page cap (`status_code == 413`; the message says which limit) |
|
|
801
|
+
| `DocumentUploadError` | The upload step fails: the upload-URL request or the file upload itself, including a file over the upload size limit (`413`) or of an unsupported type (`415`) |
|
|
802
|
+
| `JobTimeoutError` | `wait_for_job` exceeded its timeout (job still running on server) |
|
|
803
|
+
| `JobCancelledError` | The job being waited on was cancelled with `delete_job()` (reported by the API as `failed` with an error starting `cancelled:`); carries `job_id` |
|
|
804
|
+
|
|
805
|
+
Every exception carries `status_code` (HTTP status if applicable), `request_id`
|
|
806
|
+
(the `X-Request-ID` the SDK sent — include it when you open a
|
|
807
|
+
[GitHub issue](https://github.com/hyprbots/hyperapi-sdk/issues) or contact
|
|
808
|
+
support at hyperapi-support@hyperbots.com) and `code`, the
|
|
809
|
+
machine-readable error code from the API's error envelope when one was
|
|
810
|
+
returned (for example `page_quota_exceeded`), otherwise `None`. A quota
|
|
811
|
+
exhaustion (`code == "page_quota_exceeded"`) is not retried: the waiting
|
|
812
|
+
helpers raise immediately instead of backing off, since retrying cannot
|
|
813
|
+
succeed until the quota resets or the plan changes.
|
|
814
|
+
|
|
815
|
+
### Supported Formats
|
|
816
|
+
|
|
817
|
+
The upload content type is derived from the file extension:
|
|
818
|
+
|
|
819
|
+
| Family | Extensions |
|
|
820
|
+
|---|---|
|
|
821
|
+
| PDF | `.pdf` |
|
|
822
|
+
| Images | `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.tiff`, `.tif`, `.heic`, `.heif` |
|
|
823
|
+
| Office documents | `.docx`, `.doc`, `.xlsx`, `.xls`, `.pptx`, `.ppt` |
|
|
824
|
+
| Text and data | `.csv`, `.txt`, `.md`, `.rtf`, `.json`, `.xml` |
|
|
825
|
+
| Fixed-layout pages | `.xps`, `.oxps` |
|
|
826
|
+
| Email | `.eml`, `.msg` |
|
|
827
|
+
|
|
828
|
+
An unrecognised extension is rejected by the upload step with `415`.
|
|
829
|
+
|
|
830
|
+
## Operational Notes
|
|
831
|
+
|
|
832
|
+
### Threading and concurrency
|
|
833
|
+
- `HyperAPIClient` is **not thread-safe** (httpx.Client isn't either). Construct one client per worker thread, or use `threading.local()`.
|
|
834
|
+
- `AsyncHyperAPIClient` **is coroutine-safe** — a single instance can be shared across many concurrent `asyncio.gather` operations. Construct one client per application, not per request.
|
|
835
|
+
|
|
836
|
+
### Corporate proxy / custom CA
|
|
837
|
+
Standard httpx env vars are honored — `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE`. To pin a custom CA bundle:
|
|
838
|
+
|
|
839
|
+
```bash
|
|
840
|
+
export SSL_CERT_FILE=/path/to/corporate-ca.pem
|
|
841
|
+
```
|
|
842
|
+
|
|
843
|
+
### SOCKS proxy
|
|
844
|
+
If your environment routes through a SOCKS proxy, install the socks extra:
|
|
845
|
+
|
|
846
|
+
```bash
|
|
847
|
+
pip install "hyperapi-sdk[socks]"
|
|
848
|
+
```
|
|
849
|
+
|
|
850
|
+
### Logging
|
|
851
|
+
You can turn on SDK logs at any level:
|
|
852
|
+
|
|
853
|
+
```python
|
|
854
|
+
import logging
|
|
855
|
+
logging.getLogger("hyperapi").setLevel(logging.INFO)
|
|
856
|
+
```
|
|
857
|
+
|
|
858
|
+
The SDK never logs API keys, file contents, or presigned-URL signatures.
|
|
859
|
+
|
|
860
|
+
### Idempotency
|
|
861
|
+
The SDK does **not** auto-retry submit POSTs. Resubmitting after a transient failure would create a duplicate job and bill twice. If you need retries on submit, wrap the call in your own retry logic; the polling loop already retries transient failures during `GET /v1/jobs/{id}`.
|
|
862
|
+
|
|
863
|
+
## Tutorials
|
|
864
|
+
|
|
865
|
+
| Tutorial | Description |
|
|
866
|
+
|----------|-------------|
|
|
867
|
+
| [`tutorial/The_Billing_Typo.ipynb`](https://github.com/hyprbots/hyperapi-sdk/blob/main/tutorial/The_Billing_Typo.ipynb) | Compare HyperAPI vs GPT-4, Claude, Gemini on extraction task when typos are present|
|
|
868
|
+
| [`tutorial/HyperAPI_SDK_Walkthrough.ipynb`](https://github.com/hyprbots/hyperapi-sdk/blob/main/tutorial/HyperAPI_SDK_Walkthrough.ipynb) | One sample document through parse, classify, split, redact, extract and batch, with the response shape printed at each step |
|
|
869
|
+
|
|
870
|
+
## Papers
|
|
871
|
+
If you use **HyperAPI** or ideas related to its document intelligence and validation pipeline in your research, please cite the following papers:
|
|
872
|
+
|
|
873
|
+
```bibtex
|
|
874
|
+
@inproceedings{haq2026breaking,
|
|
875
|
+
title={Breaking the annotation barrier with DocuLite: A scalable and privacy-preserving framework for financial document understanding},
|
|
876
|
+
author={Haq, Saiful and Singh, Daman Deep and Bhat, Akshata A and Tamataam, Krishna Chaitanya Reddy and Khatri, Prashant and Nizami, Abdullah and Kaushik, Abhay and Chhaya, Niyati and Pandey, Piyush},
|
|
877
|
+
booktitle={4th Deployable AI Workshop},
|
|
878
|
+
year={2026}
|
|
879
|
+
}
|
|
880
|
+
```
|
|
881
|
+
|
|
882
|
+
```
|
|
883
|
+
@article{bhatsavior,
|
|
884
|
+
title={SAVIOR: Sample-efficient Alignment of Vision-Language Models for OCR Representation},
|
|
885
|
+
author={Bhat, Akshata A and Naganna, Sharath and Haq, Saiful and Khatri, Prashant and Arun, Neha and Chhaya, Niyati and Pandey, Piyush and Bhattacharyya, Pushpak}
|
|
886
|
+
}
|
|
887
|
+
```
|
|
888
|
+
|
|
889
|
+
## Testing
|
|
890
|
+
|
|
891
|
+
The public test suite is hermetic: it validates request construction, response
|
|
892
|
+
parsing, polling, and typed errors without contacting a live HyperAPI service.
|
|
893
|
+
|
|
894
|
+
```bash
|
|
895
|
+
pip install -e ".[dev]"
|
|
896
|
+
ruff check hyperapi/
|
|
897
|
+
pytest tests/ -v
|
|
898
|
+
```
|
|
899
|
+
|
|
900
|
+
## License
|
|
901
|
+
|
|
902
|
+
Apache License 2.0 - see [LICENSE](https://github.com/hyprbots/hyperapi-sdk/blob/main/LICENSE) and [NOTICE](https://github.com/hyprbots/hyperapi-sdk/blob/main/NOTICE) for details.
|
|
903
|
+
|
|
904
|
+
## Links
|
|
905
|
+
|
|
906
|
+
- **GitHub**: [github.com/hyprbots/hyperapi-sdk](https://github.com/hyprbots/hyperapi-sdk)
|