deskew-sdk 0.1.0__tar.gz
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.
- deskew_sdk-0.1.0/.gitignore +23 -0
- deskew_sdk-0.1.0/LICENSE +21 -0
- deskew_sdk-0.1.0/PKG-INFO +244 -0
- deskew_sdk-0.1.0/README.md +218 -0
- deskew_sdk-0.1.0/examples/background_job.py +32 -0
- deskew_sdk-0.1.0/examples/quickstart.py +28 -0
- deskew_sdk-0.1.0/examples/webhook_fastapi.py +34 -0
- deskew_sdk-0.1.0/examples/webhook_server.py +62 -0
- deskew_sdk-0.1.0/pyproject.toml +66 -0
- deskew_sdk-0.1.0/src/deskew_sdk/__init__.py +159 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_client.py +473 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_core.py +502 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_errors.py +231 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_extractors.py +580 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_models.py +1410 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_packets.py +313 -0
- deskew_sdk-0.1.0/src/deskew_sdk/_version.py +1 -0
- deskew_sdk-0.1.0/src/deskew_sdk/py.typed +0 -0
- deskew_sdk-0.1.0/src/deskew_sdk/webhooks.py +92 -0
- deskew_sdk-0.1.0/tests/__init__.py +0 -0
- deskew_sdk-0.1.0/tests/conftest.py +188 -0
- deskew_sdk-0.1.0/tests/test_errors.py +181 -0
- deskew_sdk-0.1.0/tests/test_extract.py +248 -0
- deskew_sdk-0.1.0/tests/test_extractors.py +1042 -0
- deskew_sdk-0.1.0/tests/test_packets.py +618 -0
- deskew_sdk-0.1.0/tests/test_resources.py +167 -0
- deskew_sdk-0.1.0/tests/test_webhooks.py +79 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Python
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.pyc
|
|
4
|
+
.venv/
|
|
5
|
+
venv/
|
|
6
|
+
dist/
|
|
7
|
+
build/
|
|
8
|
+
*.egg-info/
|
|
9
|
+
.pytest_cache/
|
|
10
|
+
.ruff_cache/
|
|
11
|
+
.mypy_cache/
|
|
12
|
+
uv.lock
|
|
13
|
+
|
|
14
|
+
# Node
|
|
15
|
+
node_modules/
|
|
16
|
+
coverage/
|
|
17
|
+
*.tsbuildinfo
|
|
18
|
+
|
|
19
|
+
# OS / editors
|
|
20
|
+
.DS_Store
|
|
21
|
+
.idea/
|
|
22
|
+
.vscode/
|
|
23
|
+
.venv*/
|
deskew_sdk-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Deskew
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: deskew-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the Deskew document extraction API.
|
|
5
|
+
Project-URL: Homepage, https://deskew.dev
|
|
6
|
+
Project-URL: Documentation, https://docs.deskew.dev
|
|
7
|
+
Project-URL: Source, https://github.com/Metricall-AI-Lab/deskew-sdks
|
|
8
|
+
Author: Deskew
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: api,deskew,document,extraction,ocr,pdf
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
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: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Requires-Dist: httpx<1,>=0.24
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# deskew
|
|
28
|
+
|
|
29
|
+
Official Python SDK for the [Deskew](https://deskew.dev) document extraction API. Send a PDF, Office file, image or email; get back Markdown, text, blocks, tables and fields.
|
|
30
|
+
|
|
31
|
+
- Python 3.9+, one dependency (`httpx`)
|
|
32
|
+
- Sync (`Deskew`) and async (`AsyncDeskew`) clients with the same surface
|
|
33
|
+
- Typed results (`ExtractResult`, `Table`, `Job`, `Usage`, `Extraction`), typed errors
|
|
34
|
+
- Extractors end to end: create, test set, test runs, publish, versions, rollback, suggest-from-document, starters, lookup lists
|
|
35
|
+
- Retries with backoff on 429 / 5xx / connection errors, `Retry-After` honoured
|
|
36
|
+
- Automatic `Idempotency-Key` so retries never bill twice
|
|
37
|
+
- Webhook signature verification
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install deskew-sdk
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quickstart
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from deskew_sdk import Deskew
|
|
49
|
+
|
|
50
|
+
client = Deskew() # reads DESKEW_API_KEY
|
|
51
|
+
|
|
52
|
+
result = client.extract("invoice.pdf", output="json", fields=True, wait=True)
|
|
53
|
+
print(result.markdown)
|
|
54
|
+
for table in result.tables or []:
|
|
55
|
+
print(table.csv)
|
|
56
|
+
print(result.fields)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`extract()` returns an `ExtractResult` when the document was processed inline (HTTP 200) and a `Job` when it was queued (202). `wait=True` polls the job for you.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
out = client.extract(url="https://example.com/report.pdf", mode="async")
|
|
63
|
+
if isinstance(out, Job):
|
|
64
|
+
result = client.jobs.wait(out.id, poll_timeout=900)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Extractors
|
|
68
|
+
|
|
69
|
+
An [extractor](https://docs.deskew.dev/extractors/) is a named, versioned definition of one kind of document and the JSON you want out of it. Create it, prove it on a test set, publish, then pass `extractor=` to `extract()`.
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from deskew_sdk import Deskew, ExtractorTestsFailing
|
|
73
|
+
|
|
74
|
+
client = Deskew()
|
|
75
|
+
|
|
76
|
+
# 1. Create a draft (or clone a starter: client.extractors.create("hospital-invoice", from_starter="hospital-invoice"))
|
|
77
|
+
client.extractors.create(
|
|
78
|
+
"hospital-invoice",
|
|
79
|
+
{
|
|
80
|
+
"title": "Hospital invoice",
|
|
81
|
+
"document": {
|
|
82
|
+
"must_contain": ["itemised charges", "a total"],
|
|
83
|
+
"reject_if": ["a prescription"],
|
|
84
|
+
},
|
|
85
|
+
"fields": [
|
|
86
|
+
{"name": "invoice_number", "type": "string", "required": True, "aliases": ["Bill No"]},
|
|
87
|
+
{"name": "total", "type": "money", "required": True},
|
|
88
|
+
{
|
|
89
|
+
"name": "line_items",
|
|
90
|
+
"type": "group",
|
|
91
|
+
"fields": [
|
|
92
|
+
{"name": "description", "type": "string"},
|
|
93
|
+
{"name": "amount", "type": "money"},
|
|
94
|
+
],
|
|
95
|
+
},
|
|
96
|
+
],
|
|
97
|
+
"rules": [
|
|
98
|
+
{
|
|
99
|
+
"id": "items_sum",
|
|
100
|
+
"check": "abs(sum(line_items[].amount) - total) <= 1",
|
|
101
|
+
"message": "Line items do not add up",
|
|
102
|
+
}
|
|
103
|
+
],
|
|
104
|
+
},
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
# 2. Test: attach samples with the expected output, run the set, read the per-field diff
|
|
108
|
+
client.extractors.test_documents.add(
|
|
109
|
+
"hospital-invoice",
|
|
110
|
+
"samples/bill-0912.pdf",
|
|
111
|
+
expected={"invoice_number": "INV-2026/0912", "total": 29800},
|
|
112
|
+
)
|
|
113
|
+
run = client.extractors.test_runs.start("hospital-invoice")
|
|
114
|
+
run = client.extractors.test_runs.wait("hospital-invoice", run.id)
|
|
115
|
+
print(run.summary.field_accuracy, run.summary.worst_fields)
|
|
116
|
+
|
|
117
|
+
# 3. Publish (refused with ExtractorTestsFailing while the test set fails; force=True overrides)
|
|
118
|
+
try:
|
|
119
|
+
version = client.extractors.publish("hospital-invoice", notes="first version")
|
|
120
|
+
except ExtractorTestsFailing as e:
|
|
121
|
+
print(e.test_summary.failed, "documents fail; run", e.test_run_id)
|
|
122
|
+
raise
|
|
123
|
+
|
|
124
|
+
# 4. Extract
|
|
125
|
+
result = client.extract(
|
|
126
|
+
"bill.pdf", extractor="hospital-invoice", wait=True
|
|
127
|
+
) # or "hospital-invoice@3", "@draft"
|
|
128
|
+
ex = result.extraction
|
|
129
|
+
print(ex.status, ex.data["total"], ex.evidence["total"].page, [f.rule for f in ex.flags])
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`client.extractors` also has `list`, `get(name, version=, draft=)`, `save_draft`, `validate`, `versions`, `version`, `rollback`, `archive`, `runs` / `iter_runs` and `suggest(file, wait=True)` (propose a definition from a sample document). `client.starters.list()` / `.get(id)` read the Deskew-maintained definitions; `client.lists.put(name, csv, key=)` / `.get` / `.download` / `.remove` manage the lookup lists that rules match with `lookup()`. The `schema=` argument and `client.schemas` still work but are deprecated aliases for extractors.
|
|
133
|
+
|
|
134
|
+
## Packets
|
|
135
|
+
|
|
136
|
+
A [packet](https://docs.deskew.dev/extractors/packets/) is several documents submitted together: each is routed to (or assigned) an extractor, and a packet definition names the *roles* they fill plus cross-document rules. `client.packets` wraps `/v1/packets`, `client.packets.definitions` the definitions and `client.packet_starters` the Deskew-maintained definitions to clone.
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from deskew_sdk import Deskew, PacketTimeout
|
|
140
|
+
|
|
141
|
+
client = Deskew()
|
|
142
|
+
|
|
143
|
+
# A definition: roles (each an extractor you have published) and cross-document rules
|
|
144
|
+
client.packets.definitions.create(
|
|
145
|
+
"health-claim",
|
|
146
|
+
{
|
|
147
|
+
"title": "Health claim packet",
|
|
148
|
+
"roles": {
|
|
149
|
+
"claim": {"extractor": "health-claim-form", "min": 1, "max": 1},
|
|
150
|
+
"bill": {"extractor": "hospital-invoice", "min": 1, "max": 1},
|
|
151
|
+
"pharmacy_bills": {"extractor": "pharmacy-bill", "min": 0, "max": None},
|
|
152
|
+
},
|
|
153
|
+
"rules": [
|
|
154
|
+
{
|
|
155
|
+
"id": "claimed_matches_bill",
|
|
156
|
+
"check": "abs(claim.claimed_total - bill.total) <= 1",
|
|
157
|
+
"message": "Claimed amount differs from the bill",
|
|
158
|
+
}
|
|
159
|
+
],
|
|
160
|
+
},
|
|
161
|
+
) # or: create("health-claim", from_starter="health-claim")
|
|
162
|
+
|
|
163
|
+
# Submit three files as one packet and wait for it (202, then polled)
|
|
164
|
+
try:
|
|
165
|
+
packet = client.packets.create(
|
|
166
|
+
[
|
|
167
|
+
"claim-form.pdf",
|
|
168
|
+
"final-bill.pdf",
|
|
169
|
+
"pharmacy-1.jpg",
|
|
170
|
+
], # paths, open files or (name, bytes)
|
|
171
|
+
packet="health-claim",
|
|
172
|
+
assignments={"claim-form.pdf": "health-claim-form"}, # skip routing for this one
|
|
173
|
+
wait=True,
|
|
174
|
+
)
|
|
175
|
+
except PacketTimeout as e:
|
|
176
|
+
print("still", e.packet.status)
|
|
177
|
+
raise
|
|
178
|
+
|
|
179
|
+
print(packet.status) # "completed", "flagged", "failed" or "canceled"
|
|
180
|
+
print(packet.data["bill"]["total"], packet.data["pharmacy_bills"])
|
|
181
|
+
for doc in packet.documents:
|
|
182
|
+
print(
|
|
183
|
+
doc.file_name,
|
|
184
|
+
doc.role,
|
|
185
|
+
doc.extractor,
|
|
186
|
+
doc.routing.confidence,
|
|
187
|
+
doc.extraction and doc.extraction.status,
|
|
188
|
+
)
|
|
189
|
+
for flag in packet.flags:
|
|
190
|
+
print(flag.severity, flag.rule, flag.message, flag.fields)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
`client.packets` also has `list(status=, limit=, starting_after=)` / `iter`, `get`, `cancel` and `wait(id, timeout=1800, interval=2)`; `client.packets.definitions` has `list(include_archived=)`, `create`, `get`, `update` (returns `valid` plus `problems`; nothing is stored when invalid) and `archive`; `client.packet_starters.list()` / `.get(id)`. A `packet.completed` webhook carries the packet without `data`.
|
|
194
|
+
|
|
195
|
+
## Errors
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
from deskew_sdk import Deskew, DeskewError, DocumentError, RateLimitError
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
result = client.extract("scan.pdf", wait=True)
|
|
202
|
+
except DocumentError as e: # password_protected, corrupt_file, ...
|
|
203
|
+
print(e.code, e.message)
|
|
204
|
+
except RateLimitError as e:
|
|
205
|
+
print("slow down", e.retry_after)
|
|
206
|
+
except DeskewError as e:
|
|
207
|
+
print(e.status, e.code, e.request_id)
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
| Class | When |
|
|
211
|
+
|---|---|
|
|
212
|
+
| `AuthenticationError` | 401 |
|
|
213
|
+
| `ForbiddenError` | 403 |
|
|
214
|
+
| `QuotaExceededError` | 402 |
|
|
215
|
+
| `NotFoundError` | 404 |
|
|
216
|
+
| `RateLimitError` | 429 (`.retry_after`) |
|
|
217
|
+
| `DocumentError` | 4xx with `type: document_error` |
|
|
218
|
+
| `InvalidRequestError` | any other 4xx |
|
|
219
|
+
| `ExtractorTestsFailing` | 409 `extractor_tests_failing` on publish (`.test_summary`, `.test_run_id`) |
|
|
220
|
+
| `APIError` | 5xx |
|
|
221
|
+
| `APIConnectionError` / `APITimeoutError` | no response |
|
|
222
|
+
| `JobFailed` / `JobTimeout` | raised by `wait` |
|
|
223
|
+
| `TestRunTimeout` | raised by `extractors.test_runs.wait` |
|
|
224
|
+
|
|
225
|
+
## Webhooks
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
from deskew_sdk import webhooks, SignatureVerificationError
|
|
229
|
+
|
|
230
|
+
event = webhooks.verify(raw_body, request.headers["Deskew-Signature"], SECRET)
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
See [`examples/`](examples/) for a webhook receiver and the [SDK docs](https://docs.deskew.dev/sdks/python/).
|
|
234
|
+
|
|
235
|
+
## Development
|
|
236
|
+
|
|
237
|
+
```bash
|
|
238
|
+
uv sync
|
|
239
|
+
uv run pytest
|
|
240
|
+
uv run ruff check .
|
|
241
|
+
uv run mypy
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
MIT licence.
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# deskew
|
|
2
|
+
|
|
3
|
+
Official Python SDK for the [Deskew](https://deskew.dev) document extraction API. Send a PDF, Office file, image or email; get back Markdown, text, blocks, tables and fields.
|
|
4
|
+
|
|
5
|
+
- Python 3.9+, one dependency (`httpx`)
|
|
6
|
+
- Sync (`Deskew`) and async (`AsyncDeskew`) clients with the same surface
|
|
7
|
+
- Typed results (`ExtractResult`, `Table`, `Job`, `Usage`, `Extraction`), typed errors
|
|
8
|
+
- Extractors end to end: create, test set, test runs, publish, versions, rollback, suggest-from-document, starters, lookup lists
|
|
9
|
+
- Retries with backoff on 429 / 5xx / connection errors, `Retry-After` honoured
|
|
10
|
+
- Automatic `Idempotency-Key` so retries never bill twice
|
|
11
|
+
- Webhook signature verification
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install deskew-sdk
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quickstart
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from deskew_sdk import Deskew
|
|
23
|
+
|
|
24
|
+
client = Deskew() # reads DESKEW_API_KEY
|
|
25
|
+
|
|
26
|
+
result = client.extract("invoice.pdf", output="json", fields=True, wait=True)
|
|
27
|
+
print(result.markdown)
|
|
28
|
+
for table in result.tables or []:
|
|
29
|
+
print(table.csv)
|
|
30
|
+
print(result.fields)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`extract()` returns an `ExtractResult` when the document was processed inline (HTTP 200) and a `Job` when it was queued (202). `wait=True` polls the job for you.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
out = client.extract(url="https://example.com/report.pdf", mode="async")
|
|
37
|
+
if isinstance(out, Job):
|
|
38
|
+
result = client.jobs.wait(out.id, poll_timeout=900)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Extractors
|
|
42
|
+
|
|
43
|
+
An [extractor](https://docs.deskew.dev/extractors/) is a named, versioned definition of one kind of document and the JSON you want out of it. Create it, prove it on a test set, publish, then pass `extractor=` to `extract()`.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from deskew_sdk import Deskew, ExtractorTestsFailing
|
|
47
|
+
|
|
48
|
+
client = Deskew()
|
|
49
|
+
|
|
50
|
+
# 1. Create a draft (or clone a starter: client.extractors.create("hospital-invoice", from_starter="hospital-invoice"))
|
|
51
|
+
client.extractors.create(
|
|
52
|
+
"hospital-invoice",
|
|
53
|
+
{
|
|
54
|
+
"title": "Hospital invoice",
|
|
55
|
+
"document": {
|
|
56
|
+
"must_contain": ["itemised charges", "a total"],
|
|
57
|
+
"reject_if": ["a prescription"],
|
|
58
|
+
},
|
|
59
|
+
"fields": [
|
|
60
|
+
{"name": "invoice_number", "type": "string", "required": True, "aliases": ["Bill No"]},
|
|
61
|
+
{"name": "total", "type": "money", "required": True},
|
|
62
|
+
{
|
|
63
|
+
"name": "line_items",
|
|
64
|
+
"type": "group",
|
|
65
|
+
"fields": [
|
|
66
|
+
{"name": "description", "type": "string"},
|
|
67
|
+
{"name": "amount", "type": "money"},
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
"rules": [
|
|
72
|
+
{
|
|
73
|
+
"id": "items_sum",
|
|
74
|
+
"check": "abs(sum(line_items[].amount) - total) <= 1",
|
|
75
|
+
"message": "Line items do not add up",
|
|
76
|
+
}
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# 2. Test: attach samples with the expected output, run the set, read the per-field diff
|
|
82
|
+
client.extractors.test_documents.add(
|
|
83
|
+
"hospital-invoice",
|
|
84
|
+
"samples/bill-0912.pdf",
|
|
85
|
+
expected={"invoice_number": "INV-2026/0912", "total": 29800},
|
|
86
|
+
)
|
|
87
|
+
run = client.extractors.test_runs.start("hospital-invoice")
|
|
88
|
+
run = client.extractors.test_runs.wait("hospital-invoice", run.id)
|
|
89
|
+
print(run.summary.field_accuracy, run.summary.worst_fields)
|
|
90
|
+
|
|
91
|
+
# 3. Publish (refused with ExtractorTestsFailing while the test set fails; force=True overrides)
|
|
92
|
+
try:
|
|
93
|
+
version = client.extractors.publish("hospital-invoice", notes="first version")
|
|
94
|
+
except ExtractorTestsFailing as e:
|
|
95
|
+
print(e.test_summary.failed, "documents fail; run", e.test_run_id)
|
|
96
|
+
raise
|
|
97
|
+
|
|
98
|
+
# 4. Extract
|
|
99
|
+
result = client.extract(
|
|
100
|
+
"bill.pdf", extractor="hospital-invoice", wait=True
|
|
101
|
+
) # or "hospital-invoice@3", "@draft"
|
|
102
|
+
ex = result.extraction
|
|
103
|
+
print(ex.status, ex.data["total"], ex.evidence["total"].page, [f.rule for f in ex.flags])
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`client.extractors` also has `list`, `get(name, version=, draft=)`, `save_draft`, `validate`, `versions`, `version`, `rollback`, `archive`, `runs` / `iter_runs` and `suggest(file, wait=True)` (propose a definition from a sample document). `client.starters.list()` / `.get(id)` read the Deskew-maintained definitions; `client.lists.put(name, csv, key=)` / `.get` / `.download` / `.remove` manage the lookup lists that rules match with `lookup()`. The `schema=` argument and `client.schemas` still work but are deprecated aliases for extractors.
|
|
107
|
+
|
|
108
|
+
## Packets
|
|
109
|
+
|
|
110
|
+
A [packet](https://docs.deskew.dev/extractors/packets/) is several documents submitted together: each is routed to (or assigned) an extractor, and a packet definition names the *roles* they fill plus cross-document rules. `client.packets` wraps `/v1/packets`, `client.packets.definitions` the definitions and `client.packet_starters` the Deskew-maintained definitions to clone.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from deskew_sdk import Deskew, PacketTimeout
|
|
114
|
+
|
|
115
|
+
client = Deskew()
|
|
116
|
+
|
|
117
|
+
# A definition: roles (each an extractor you have published) and cross-document rules
|
|
118
|
+
client.packets.definitions.create(
|
|
119
|
+
"health-claim",
|
|
120
|
+
{
|
|
121
|
+
"title": "Health claim packet",
|
|
122
|
+
"roles": {
|
|
123
|
+
"claim": {"extractor": "health-claim-form", "min": 1, "max": 1},
|
|
124
|
+
"bill": {"extractor": "hospital-invoice", "min": 1, "max": 1},
|
|
125
|
+
"pharmacy_bills": {"extractor": "pharmacy-bill", "min": 0, "max": None},
|
|
126
|
+
},
|
|
127
|
+
"rules": [
|
|
128
|
+
{
|
|
129
|
+
"id": "claimed_matches_bill",
|
|
130
|
+
"check": "abs(claim.claimed_total - bill.total) <= 1",
|
|
131
|
+
"message": "Claimed amount differs from the bill",
|
|
132
|
+
}
|
|
133
|
+
],
|
|
134
|
+
},
|
|
135
|
+
) # or: create("health-claim", from_starter="health-claim")
|
|
136
|
+
|
|
137
|
+
# Submit three files as one packet and wait for it (202, then polled)
|
|
138
|
+
try:
|
|
139
|
+
packet = client.packets.create(
|
|
140
|
+
[
|
|
141
|
+
"claim-form.pdf",
|
|
142
|
+
"final-bill.pdf",
|
|
143
|
+
"pharmacy-1.jpg",
|
|
144
|
+
], # paths, open files or (name, bytes)
|
|
145
|
+
packet="health-claim",
|
|
146
|
+
assignments={"claim-form.pdf": "health-claim-form"}, # skip routing for this one
|
|
147
|
+
wait=True,
|
|
148
|
+
)
|
|
149
|
+
except PacketTimeout as e:
|
|
150
|
+
print("still", e.packet.status)
|
|
151
|
+
raise
|
|
152
|
+
|
|
153
|
+
print(packet.status) # "completed", "flagged", "failed" or "canceled"
|
|
154
|
+
print(packet.data["bill"]["total"], packet.data["pharmacy_bills"])
|
|
155
|
+
for doc in packet.documents:
|
|
156
|
+
print(
|
|
157
|
+
doc.file_name,
|
|
158
|
+
doc.role,
|
|
159
|
+
doc.extractor,
|
|
160
|
+
doc.routing.confidence,
|
|
161
|
+
doc.extraction and doc.extraction.status,
|
|
162
|
+
)
|
|
163
|
+
for flag in packet.flags:
|
|
164
|
+
print(flag.severity, flag.rule, flag.message, flag.fields)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`client.packets` also has `list(status=, limit=, starting_after=)` / `iter`, `get`, `cancel` and `wait(id, timeout=1800, interval=2)`; `client.packets.definitions` has `list(include_archived=)`, `create`, `get`, `update` (returns `valid` plus `problems`; nothing is stored when invalid) and `archive`; `client.packet_starters.list()` / `.get(id)`. A `packet.completed` webhook carries the packet without `data`.
|
|
168
|
+
|
|
169
|
+
## Errors
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from deskew_sdk import Deskew, DeskewError, DocumentError, RateLimitError
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
result = client.extract("scan.pdf", wait=True)
|
|
176
|
+
except DocumentError as e: # password_protected, corrupt_file, ...
|
|
177
|
+
print(e.code, e.message)
|
|
178
|
+
except RateLimitError as e:
|
|
179
|
+
print("slow down", e.retry_after)
|
|
180
|
+
except DeskewError as e:
|
|
181
|
+
print(e.status, e.code, e.request_id)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
| Class | When |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `AuthenticationError` | 401 |
|
|
187
|
+
| `ForbiddenError` | 403 |
|
|
188
|
+
| `QuotaExceededError` | 402 |
|
|
189
|
+
| `NotFoundError` | 404 |
|
|
190
|
+
| `RateLimitError` | 429 (`.retry_after`) |
|
|
191
|
+
| `DocumentError` | 4xx with `type: document_error` |
|
|
192
|
+
| `InvalidRequestError` | any other 4xx |
|
|
193
|
+
| `ExtractorTestsFailing` | 409 `extractor_tests_failing` on publish (`.test_summary`, `.test_run_id`) |
|
|
194
|
+
| `APIError` | 5xx |
|
|
195
|
+
| `APIConnectionError` / `APITimeoutError` | no response |
|
|
196
|
+
| `JobFailed` / `JobTimeout` | raised by `wait` |
|
|
197
|
+
| `TestRunTimeout` | raised by `extractors.test_runs.wait` |
|
|
198
|
+
|
|
199
|
+
## Webhooks
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from deskew_sdk import webhooks, SignatureVerificationError
|
|
203
|
+
|
|
204
|
+
event = webhooks.verify(raw_body, request.headers["Deskew-Signature"], SECRET)
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
See [`examples/`](examples/) for a webhook receiver and the [SDK docs](https://docs.deskew.dev/sdks/python/).
|
|
208
|
+
|
|
209
|
+
## Development
|
|
210
|
+
|
|
211
|
+
```bash
|
|
212
|
+
uv sync
|
|
213
|
+
uv run pytest
|
|
214
|
+
uv run ruff check .
|
|
215
|
+
uv run mypy
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
MIT licence.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Queue a large document, watch its progress, then download the result.
|
|
2
|
+
|
|
3
|
+
python background_job.py https://example.com/annual-report.pdf
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from deskew_sdk import Deskew, ExtractResult, JobFailed
|
|
10
|
+
|
|
11
|
+
client = Deskew()
|
|
12
|
+
url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com/annual-report.pdf"
|
|
13
|
+
|
|
14
|
+
out = client.extract(url=url, mode="async", quality="accurate")
|
|
15
|
+
if isinstance(out, ExtractResult): # mode="async" always queues, but handle both anyway
|
|
16
|
+
print(out.markdown)
|
|
17
|
+
sys.exit()
|
|
18
|
+
|
|
19
|
+
print("queued", out.id)
|
|
20
|
+
while True:
|
|
21
|
+
job = client.jobs.get(out.id)
|
|
22
|
+
print(f"{job.status:<11} {job.pages.done}/{job.pages.total} pages, eta {job.eta_seconds}s")
|
|
23
|
+
if job.is_terminal:
|
|
24
|
+
break
|
|
25
|
+
time.sleep(2)
|
|
26
|
+
|
|
27
|
+
if job.status != "completed":
|
|
28
|
+
raise JobFailed(job)
|
|
29
|
+
|
|
30
|
+
result = client.jobs.result(job.id)
|
|
31
|
+
print(result.markdown[:500])
|
|
32
|
+
print(f"{result.usage.credits} credits, result expires at {job.expires_at}")
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Extract one document and print what came back.
|
|
2
|
+
|
|
3
|
+
export DESKEW_API_KEY=deskew_test_sk_...
|
|
4
|
+
python quickstart.py invoice.pdf
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from deskew_sdk import Deskew, DeskewError
|
|
10
|
+
|
|
11
|
+
path = sys.argv[1] if len(sys.argv) > 1 else "invoice.pdf"
|
|
12
|
+
|
|
13
|
+
client = Deskew()
|
|
14
|
+
try:
|
|
15
|
+
result = client.extract(path, output="json", fields=True, wait=True)
|
|
16
|
+
except DeskewError as e:
|
|
17
|
+
sys.exit(f"{e.status} {e.code}: {e.message} (request {e.request_id})")
|
|
18
|
+
|
|
19
|
+
print(result.markdown)
|
|
20
|
+
print()
|
|
21
|
+
for i, table in enumerate(result.tables or []):
|
|
22
|
+
print(f"--- table {i} (page {table.page}) ---")
|
|
23
|
+
print(table.csv)
|
|
24
|
+
print()
|
|
25
|
+
print("fields:", result.fields)
|
|
26
|
+
print("usage:", result.usage.pages, "pages,", result.usage.credits, "credits")
|
|
27
|
+
for w in result.warnings:
|
|
28
|
+
print("warning:", w)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""The same receiver with FastAPI (pip install fastapi uvicorn).
|
|
2
|
+
|
|
3
|
+
uvicorn webhook_fastapi:app --port 8080
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request
|
|
9
|
+
|
|
10
|
+
from deskew_sdk import Deskew, SignatureVerificationError, webhooks
|
|
11
|
+
|
|
12
|
+
SECRET = os.environ["DESKEW_WEBHOOK_SECRET"]
|
|
13
|
+
client = Deskew()
|
|
14
|
+
app = FastAPI()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def download(job_id: str) -> None:
|
|
18
|
+
result = client.jobs.result(job_id)
|
|
19
|
+
print(job_id, result.usage.credits, "credits")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@app.post("/webhooks/deskew", status_code=204)
|
|
23
|
+
async def deskew_webhook(
|
|
24
|
+
request: Request,
|
|
25
|
+
background: BackgroundTasks,
|
|
26
|
+
deskew_signature: str = Header(default="", alias="Deskew-Signature"),
|
|
27
|
+
) -> None:
|
|
28
|
+
body = await request.body() # raw bytes: never verify a re-serialised JSON body
|
|
29
|
+
try:
|
|
30
|
+
event = webhooks.verify(body, deskew_signature, SECRET)
|
|
31
|
+
except SignatureVerificationError as e:
|
|
32
|
+
raise HTTPException(status_code=400, detail=str(e)) from e
|
|
33
|
+
if event["type"] == "job.completed" and not event.get("test"):
|
|
34
|
+
background.add_task(download, event["data"]["id"])
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Receive Deskew webhooks with the standard library only.
|
|
2
|
+
|
|
3
|
+
export DESKEW_API_KEY=deskew_test_sk_...
|
|
4
|
+
export DESKEW_WEBHOOK_SECRET=whsec_...
|
|
5
|
+
python webhook_server.py # listens on :8080/webhooks/deskew
|
|
6
|
+
|
|
7
|
+
Point an endpoint at this URL (through a tunnel such as ngrok) from the dashboard and press
|
|
8
|
+
"Send test". Each job.completed event triggers a download of the result.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import threading
|
|
14
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
15
|
+
|
|
16
|
+
from deskew_sdk import Deskew, SignatureVerificationError, webhooks
|
|
17
|
+
|
|
18
|
+
SECRET = os.environ["DESKEW_WEBHOOK_SECRET"]
|
|
19
|
+
client = Deskew()
|
|
20
|
+
seen: set = set()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def handle_completed(job_id: str) -> None:
|
|
24
|
+
result = client.jobs.result(job_id)
|
|
25
|
+
print(f"[{job_id}] {result.pages} pages, {len(result.tables or [])} tables")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Handler(BaseHTTPRequestHandler):
|
|
29
|
+
def do_POST(self) -> None:
|
|
30
|
+
if self.path != "/webhooks/deskew":
|
|
31
|
+
self.send_response(404)
|
|
32
|
+
self.end_headers()
|
|
33
|
+
return
|
|
34
|
+
body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
|
|
35
|
+
try:
|
|
36
|
+
event = webhooks.verify(body, self.headers.get("Deskew-Signature", ""), SECRET)
|
|
37
|
+
except SignatureVerificationError as e:
|
|
38
|
+
print("rejected:", e)
|
|
39
|
+
self.send_response(400)
|
|
40
|
+
self.end_headers()
|
|
41
|
+
return
|
|
42
|
+
|
|
43
|
+
# Respond fast, work after. Deduplicate on X-Delivery-Id (retries reuse it).
|
|
44
|
+
self.send_response(204)
|
|
45
|
+
self.end_headers()
|
|
46
|
+
delivery = self.headers.get("X-Delivery-Id") or event["id"]
|
|
47
|
+
if delivery in seen:
|
|
48
|
+
return
|
|
49
|
+
seen.add(delivery)
|
|
50
|
+
|
|
51
|
+
data = event.get("data", {})
|
|
52
|
+
print(f"{event['type']} {data.get('id')} {json.dumps(data.get('error'))}")
|
|
53
|
+
if event["type"] == "job.completed" and not event.get("test"):
|
|
54
|
+
threading.Thread(target=handle_completed, args=(data["id"],), daemon=True).start()
|
|
55
|
+
|
|
56
|
+
def log_message(self, *_: object) -> None:
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
if __name__ == "__main__":
|
|
61
|
+
print("listening on http://0.0.0.0:8080/webhooks/deskew")
|
|
62
|
+
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
|