patchwell 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.
- patchwell-0.1.0/LICENSE +9 -0
- patchwell-0.1.0/PKG-INFO +105 -0
- patchwell-0.1.0/README.md +89 -0
- patchwell-0.1.0/patchwell/__init__.py +246 -0
- patchwell-0.1.0/patchwell.egg-info/PKG-INFO +105 -0
- patchwell-0.1.0/patchwell.egg-info/SOURCES.txt +9 -0
- patchwell-0.1.0/patchwell.egg-info/dependency_links.txt +1 -0
- patchwell-0.1.0/patchwell.egg-info/top_level.txt +1 -0
- patchwell-0.1.0/pyproject.toml +21 -0
- patchwell-0.1.0/setup.cfg +4 -0
- patchwell-0.1.0/tests/test_sdk.py +196 -0
patchwell-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Patchwell
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
patchwell-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: patchwell
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Transcription, data cleaning and cited research for scripts, pipelines and AI agents. Pay per result.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://patchwell.io
|
|
7
|
+
Project-URL: Documentation, https://patchwell.io/quickstart
|
|
8
|
+
Keywords: transcription,data cleaning,deduplication,research,api,whisper,csv
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# patchwell
|
|
18
|
+
|
|
19
|
+
Transcription, data cleaning and cited web research from Python. Pay per result: a failed or refused call costs
|
|
20
|
+
nothing. Standard library only, so it runs in Lambda, Airflow, cron jobs and notebooks.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install patchwell
|
|
24
|
+
export PATCHWELL_KEY=pw_live_... # a free key with $1 of credit: https://patchwell.io/#try
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from patchwell import Patchwell
|
|
29
|
+
|
|
30
|
+
pw = Patchwell()
|
|
31
|
+
|
|
32
|
+
# Clean a file, a list of dicts, or several sources merged into one table
|
|
33
|
+
clean = pw.clean_data(url="https://example.com/leads.csv")
|
|
34
|
+
clean = pw.clean_data(rows=[{"Email": "ANN@X.COM", "Name": "ann lee"}])
|
|
35
|
+
clean = pw.clean_data(inputs=[{"url": "https://example.com/crm.csv"}, {"rows": scraped, "name": "web"}])
|
|
36
|
+
|
|
37
|
+
# Only the rows you haven't sent before, for a daily job
|
|
38
|
+
new = pw.clean_data(url=export_url, only_new={"state": "daily-leads", "key": ["Email"]})
|
|
39
|
+
|
|
40
|
+
# Check rows against your rules and map them onto your import template
|
|
41
|
+
ready = pw.clean_data(rows=rows, rules=[{"column": "Age", "range": [0, 120]}],
|
|
42
|
+
target={"columns": [{"name": "email", "required": True}, {"name": "name"}]})
|
|
43
|
+
|
|
44
|
+
# Transcribe: waits for long recordings (polls with the server's Retry-After)
|
|
45
|
+
t = pw.transcribe("https://example.com/interview.mp3")
|
|
46
|
+
print(t["text"])
|
|
47
|
+
open("interview.srt", "w").write(t["srt"])
|
|
48
|
+
|
|
49
|
+
# Research with a cited source for every claim
|
|
50
|
+
# ($0.02 per answered question; declined and unanswered questions are free)
|
|
51
|
+
a = pw.research("Which EU countries require B2B e-invoicing in 2026?")
|
|
52
|
+
print(a["answer"], a["gaps"])
|
|
53
|
+
|
|
54
|
+
# Hard multi-step questions: depth="deep" searches about twice as wide ($0.06 per answered question).
|
|
55
|
+
# private=True keeps the question inside Modal, the cloud Patchwell runs on: same price.
|
|
56
|
+
d = pw.research("How old was the author of Dracula when it was published?", depth="deep")
|
|
57
|
+
# A worked-out answer's claim has "derived": True, "derived_from" (the facts it rests on) and "calc"
|
|
58
|
+
|
|
59
|
+
# Results as files
|
|
60
|
+
open("clean.xlsx", "wb").write(pw.export(clean, "xlsx"))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Retries never charge twice
|
|
64
|
+
|
|
65
|
+
Every POST carries an `Idempotency-Key`. On a retryable error (`rate_limited`, `unavailable`, a request still running)
|
|
66
|
+
the SDK waits for `Retry-After` and sends the same key again, so you get the first response and pay once.
|
|
67
|
+
Pass your own `idempotency_key=` (an order or row id) and a later rerun of the same item, by cron or by hand,
|
|
68
|
+
returns the first result instead of paying again.
|
|
69
|
+
|
|
70
|
+
## Errors
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from patchwell import PatchwellError
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
pw.clean_data(url=url)
|
|
77
|
+
except PatchwellError as e:
|
|
78
|
+
if e.code == "insufficient_credit":
|
|
79
|
+
... # top up at https://patchwell.io/#buy
|
|
80
|
+
print(e.code, e.retryable, e.request_id)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Codes:
|
|
84
|
+
<!-- facts:error-codes-list -->
|
|
85
|
+
`invalid_input`, `unauthorized`, `insufficient_credit`, `forbidden`, `not_found`, `method_not_allowed`, `too_large`, `idempotency_in_progress`, `idempotency_mismatch`, `rate_limited`, `source_unavailable`, `unavailable`, `tool_paused`, `internal`, `cancelled`, `expired`, `network`, `timeout`, `job_failed`.
|
|
86
|
+
<!-- /facts:error-codes-list -->
|
|
87
|
+
`source_unavailable`: the site hosting your file failed for a moment. A job that fails while you wait
|
|
88
|
+
raises with the server's own `code` and `retryable`.
|
|
89
|
+
|
|
90
|
+
## Long jobs without waiting
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
job = pw.transcribe(url, wait=False) # {"status": "running", "job_id": "fc-..."}
|
|
94
|
+
result = pw.wait(job["job_id"], timeout=3600)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Or send `callback_url=` and verify the webhook:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from patchwell import verify_webhook
|
|
101
|
+
|
|
102
|
+
ok = verify_webhook(secret, request.body, request.headers["Patchwell-Signature"])
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The full API reference: https://patchwell.io/quickstart
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# patchwell
|
|
2
|
+
|
|
3
|
+
Transcription, data cleaning and cited web research from Python. Pay per result: a failed or refused call costs
|
|
4
|
+
nothing. Standard library only, so it runs in Lambda, Airflow, cron jobs and notebooks.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
pip install patchwell
|
|
8
|
+
export PATCHWELL_KEY=pw_live_... # a free key with $1 of credit: https://patchwell.io/#try
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from patchwell import Patchwell
|
|
13
|
+
|
|
14
|
+
pw = Patchwell()
|
|
15
|
+
|
|
16
|
+
# Clean a file, a list of dicts, or several sources merged into one table
|
|
17
|
+
clean = pw.clean_data(url="https://example.com/leads.csv")
|
|
18
|
+
clean = pw.clean_data(rows=[{"Email": "ANN@X.COM", "Name": "ann lee"}])
|
|
19
|
+
clean = pw.clean_data(inputs=[{"url": "https://example.com/crm.csv"}, {"rows": scraped, "name": "web"}])
|
|
20
|
+
|
|
21
|
+
# Only the rows you haven't sent before, for a daily job
|
|
22
|
+
new = pw.clean_data(url=export_url, only_new={"state": "daily-leads", "key": ["Email"]})
|
|
23
|
+
|
|
24
|
+
# Check rows against your rules and map them onto your import template
|
|
25
|
+
ready = pw.clean_data(rows=rows, rules=[{"column": "Age", "range": [0, 120]}],
|
|
26
|
+
target={"columns": [{"name": "email", "required": True}, {"name": "name"}]})
|
|
27
|
+
|
|
28
|
+
# Transcribe: waits for long recordings (polls with the server's Retry-After)
|
|
29
|
+
t = pw.transcribe("https://example.com/interview.mp3")
|
|
30
|
+
print(t["text"])
|
|
31
|
+
open("interview.srt", "w").write(t["srt"])
|
|
32
|
+
|
|
33
|
+
# Research with a cited source for every claim
|
|
34
|
+
# ($0.02 per answered question; declined and unanswered questions are free)
|
|
35
|
+
a = pw.research("Which EU countries require B2B e-invoicing in 2026?")
|
|
36
|
+
print(a["answer"], a["gaps"])
|
|
37
|
+
|
|
38
|
+
# Hard multi-step questions: depth="deep" searches about twice as wide ($0.06 per answered question).
|
|
39
|
+
# private=True keeps the question inside Modal, the cloud Patchwell runs on: same price.
|
|
40
|
+
d = pw.research("How old was the author of Dracula when it was published?", depth="deep")
|
|
41
|
+
# A worked-out answer's claim has "derived": True, "derived_from" (the facts it rests on) and "calc"
|
|
42
|
+
|
|
43
|
+
# Results as files
|
|
44
|
+
open("clean.xlsx", "wb").write(pw.export(clean, "xlsx"))
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Retries never charge twice
|
|
48
|
+
|
|
49
|
+
Every POST carries an `Idempotency-Key`. On a retryable error (`rate_limited`, `unavailable`, a request still running)
|
|
50
|
+
the SDK waits for `Retry-After` and sends the same key again, so you get the first response and pay once.
|
|
51
|
+
Pass your own `idempotency_key=` (an order or row id) and a later rerun of the same item, by cron or by hand,
|
|
52
|
+
returns the first result instead of paying again.
|
|
53
|
+
|
|
54
|
+
## Errors
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from patchwell import PatchwellError
|
|
58
|
+
|
|
59
|
+
try:
|
|
60
|
+
pw.clean_data(url=url)
|
|
61
|
+
except PatchwellError as e:
|
|
62
|
+
if e.code == "insufficient_credit":
|
|
63
|
+
... # top up at https://patchwell.io/#buy
|
|
64
|
+
print(e.code, e.retryable, e.request_id)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Codes:
|
|
68
|
+
<!-- facts:error-codes-list -->
|
|
69
|
+
`invalid_input`, `unauthorized`, `insufficient_credit`, `forbidden`, `not_found`, `method_not_allowed`, `too_large`, `idempotency_in_progress`, `idempotency_mismatch`, `rate_limited`, `source_unavailable`, `unavailable`, `tool_paused`, `internal`, `cancelled`, `expired`, `network`, `timeout`, `job_failed`.
|
|
70
|
+
<!-- /facts:error-codes-list -->
|
|
71
|
+
`source_unavailable`: the site hosting your file failed for a moment. A job that fails while you wait
|
|
72
|
+
raises with the server's own `code` and `retryable`.
|
|
73
|
+
|
|
74
|
+
## Long jobs without waiting
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
job = pw.transcribe(url, wait=False) # {"status": "running", "job_id": "fc-..."}
|
|
78
|
+
result = pw.wait(job["job_id"], timeout=3600)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Or send `callback_url=` and verify the webhook:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from patchwell import verify_webhook
|
|
85
|
+
|
|
86
|
+
ok = verify_webhook(secret, request.body, request.headers["Patchwell-Signature"])
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
The full API reference: https://patchwell.io/quickstart
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Patchwell for Python: transcription, data cleaning and cited research, pay per result.
|
|
2
|
+
|
|
3
|
+
from patchwell import Patchwell
|
|
4
|
+
pw = Patchwell() # reads PATCHWELL_KEY
|
|
5
|
+
clean = pw.clean_data(url="https://example.com/leads.csv")
|
|
6
|
+
notes = pw.transcribe("https://example.com/call.mp3") # waits for long recordings
|
|
7
|
+
answer = pw.research("Which EU countries require e-invoicing in 2026?")
|
|
8
|
+
|
|
9
|
+
Standard library only, so it runs anywhere (Lambda, Airflow, cron, notebooks). Every call carries an
|
|
10
|
+
Idempotency-Key: a retry after a timeout returns the first response and is never charged twice. Errors raise
|
|
11
|
+
PatchwellError with the API's stable `code` and whether retrying can succeed."""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import hmac
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import time
|
|
19
|
+
import urllib.error
|
|
20
|
+
import urllib.request
|
|
21
|
+
import uuid
|
|
22
|
+
|
|
23
|
+
__version__ = "0.1.0"
|
|
24
|
+
__all__ = ["Patchwell", "PatchwellError", "PatchwellTimeout", "verify_webhook"]
|
|
25
|
+
|
|
26
|
+
DEFAULT_BASE = "https://patchwell.io"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PatchwellError(Exception):
|
|
30
|
+
"""An error answer. code is stable (invalid_input, unauthorized, insufficient_credit, rate_limited, ...): branch on
|
|
31
|
+
it, never on the message. retryable says whether sending the same request again can succeed."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, status: int, message: str, code: str = "", retryable: bool = False, request_id: str = "",
|
|
34
|
+
body: dict | None = None):
|
|
35
|
+
super().__init__(f"{message} ({code or status}{', request ' + request_id if request_id else ''})")
|
|
36
|
+
self.status, self.message, self.code, self.retryable, self.request_id = status, message, code, retryable, request_id
|
|
37
|
+
self.body = body or {}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PatchwellTimeout(PatchwellError):
|
|
41
|
+
"""A long job didn't finish within the wait. It keeps running; fetch it later with job(job_id)."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, job_id: str, waited_s: float):
|
|
44
|
+
super().__init__(0, f"job {job_id} still running after {waited_s:.0f} s", "timeout", True)
|
|
45
|
+
self.job_id = job_id
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _urllib_send(method: str, url: str, headers: dict, body: bytes | None, timeout: float):
|
|
49
|
+
req = urllib.request.Request(url, data=body, method=method, headers=headers)
|
|
50
|
+
try:
|
|
51
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
52
|
+
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read()
|
|
53
|
+
except urllib.error.HTTPError as e:
|
|
54
|
+
return e.code, {k.lower(): v for k, v in (e.headers or {}).items()}, e.read()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Patchwell:
|
|
58
|
+
def __init__(self, api_key: str | None = None, base_url: str | None = None, timeout: float = 150.0,
|
|
59
|
+
max_retries: int = 4, transport=None, sleep=time.sleep, clock=time.monotonic):
|
|
60
|
+
self.api_key = api_key or os.environ.get("PATCHWELL_KEY") or os.environ.get("PATCHWELL_API_KEY")
|
|
61
|
+
if not self.api_key:
|
|
62
|
+
raise ValueError("pass api_key or set PATCHWELL_KEY (a free key with $1 of credit: POST "
|
|
63
|
+
"https://patchwell.io/v1/credits/trial with your email)")
|
|
64
|
+
self.base_url = (base_url or os.environ.get("PATCHWELL_BASE_URL") or DEFAULT_BASE).rstrip("/")
|
|
65
|
+
self.timeout, self.max_retries = timeout, max_retries
|
|
66
|
+
self._send, self._sleep, self._clock = transport or _urllib_send, sleep, clock
|
|
67
|
+
|
|
68
|
+
# ------------------------------------------------------------------ plumbing
|
|
69
|
+
def request(self, method: str, path: str, body: dict | bytes | None = None, headers: dict | None = None,
|
|
70
|
+
raw: bool = False):
|
|
71
|
+
"""One API call with retries on retryable errors (same Idempotency-Key every time). Returns the parsed JSON,
|
|
72
|
+
or (bytes, headers) with raw=True."""
|
|
73
|
+
h = {"Authorization": f"Bearer {self.api_key}", "User-Agent": f"patchwell-python/{__version__}",
|
|
74
|
+
"Accept": "application/json"}
|
|
75
|
+
data = None
|
|
76
|
+
if body is not None:
|
|
77
|
+
data = body if isinstance(body, bytes) else json.dumps(body, default=str).encode()
|
|
78
|
+
h["Content-Type"] = "application/json"
|
|
79
|
+
if method == "POST":
|
|
80
|
+
h["Idempotency-Key"] = "pw-sdk-" + uuid.uuid4().hex
|
|
81
|
+
h.update(headers or {})
|
|
82
|
+
for attempt in range(self.max_retries + 1):
|
|
83
|
+
try:
|
|
84
|
+
status, rh, content = self._send(method, self.base_url + path, h, data, self.timeout)
|
|
85
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
|
|
86
|
+
if attempt >= self.max_retries:
|
|
87
|
+
raise PatchwellError(0, f"network error: {e}", "network", True) from e
|
|
88
|
+
self._sleep(min(2 ** attempt, 30))
|
|
89
|
+
continue
|
|
90
|
+
if status < 400:
|
|
91
|
+
if raw:
|
|
92
|
+
return content, rh
|
|
93
|
+
parsed = json.loads(content or b"{}")
|
|
94
|
+
if isinstance(parsed, dict) and rh.get("retry-after"):
|
|
95
|
+
parsed.setdefault("_retry_after", rh["retry-after"])
|
|
96
|
+
return parsed
|
|
97
|
+
try:
|
|
98
|
+
j = json.loads(content or b"{}")
|
|
99
|
+
except ValueError:
|
|
100
|
+
j = {}
|
|
101
|
+
err = PatchwellError(status, str(j.get("error") or j.get("detail") or f"HTTP {status}"), j.get("code", ""),
|
|
102
|
+
bool(j.get("retryable", status >= 500 or status == 429)), j.get("request_id")
|
|
103
|
+
or rh.get("x-request-id", ""), j)
|
|
104
|
+
if not err.retryable or attempt >= self.max_retries:
|
|
105
|
+
raise err
|
|
106
|
+
self._sleep(float(rh.get("retry-after") or min(2 ** attempt, 30)))
|
|
107
|
+
raise AssertionError("unreachable")
|
|
108
|
+
|
|
109
|
+
def _tool(self, path: str, body: dict, wait: bool, timeout: float) -> dict:
|
|
110
|
+
key = body.pop("idempotency_key", None)
|
|
111
|
+
body = {k: v for k, v in body.items() if v is not None}
|
|
112
|
+
h = {"Prefer": "respond-async"}
|
|
113
|
+
if key: # the caller's own key: a rerun of the same item (a cron retry) never pays twice
|
|
114
|
+
h["Idempotency-Key"] = str(key)
|
|
115
|
+
r = self.request("POST", path, body, headers=h)
|
|
116
|
+
if isinstance(r, dict) and r.get("status") == "running" and r.get("job_id"):
|
|
117
|
+
ra = r.pop("_retry_after", None)
|
|
118
|
+
if not wait:
|
|
119
|
+
return r
|
|
120
|
+
return self.wait(r["job_id"], timeout=timeout, first_wait=float(ra or 10))
|
|
121
|
+
if isinstance(r, dict):
|
|
122
|
+
r.pop("_retry_after", None)
|
|
123
|
+
return r
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------------------------ tools
|
|
126
|
+
def clean_data(self, url: str | None = None, *, rows: list | None = None, csv_text: str | None = None,
|
|
127
|
+
content: bytes | None = None, filename: str | None = None, inputs: list | None = None,
|
|
128
|
+
wait: bool = True, timeout: float = 3600, **options) -> dict:
|
|
129
|
+
"""Clean a file or data into typed, deduplicated rows with a log of each change. One of url, rows (a list of
|
|
130
|
+
dicts), csv_text, content (+ filename) or inputs (several sources merged). Options are the API's:
|
|
131
|
+
only_new={"state": ..., "key": [...]}, rules=[...], target={...}, output="summary", preview=True, ..."""
|
|
132
|
+
body = dict(options, url=url, rows=rows, csv_text=csv_text, inputs=inputs, filename=filename)
|
|
133
|
+
if content is not None:
|
|
134
|
+
import base64
|
|
135
|
+
body["content_base64"] = base64.b64encode(content).decode()
|
|
136
|
+
body["filename"] = filename or "upload.csv"
|
|
137
|
+
return self._tool("/v1/clean_data", body, wait, timeout)
|
|
138
|
+
|
|
139
|
+
def transcribe(self, url: str, *, wait: bool = True, timeout: float = 4 * 3600, **options) -> dict:
|
|
140
|
+
"""Transcript with word timings, speaker labels, SRT and VTT. Options: language, speakers, max_seconds,
|
|
141
|
+
callback_url, idempotency_key (your own id for this item: sending it again never pays twice)."""
|
|
142
|
+
return self._tool("/v1/transcribe", dict(options, url=url), wait, timeout)
|
|
143
|
+
|
|
144
|
+
def research(self, ask: str, *, context: str | None = None, wait: bool = True, timeout: float = 900,
|
|
145
|
+
**options) -> dict:
|
|
146
|
+
"""An answer from the live web with a cited source for each claim, and what it couldn't confirm.
|
|
147
|
+
$0.02 per answered question; declined and unanswered questions are free. Options: depth="deep" ($0.06,
|
|
148
|
+
searches about twice as wide for hard multi-step questions), private=True (stays inside Modal, the cloud
|
|
149
|
+
Patchwell runs on; same price), callback_url. A worked-out answer's claim carries derived, derived_from and calc."""
|
|
150
|
+
return self._tool("/v1/research", dict(options, ask=ask, context=context), wait, timeout)
|
|
151
|
+
|
|
152
|
+
# ------------------------------------------------------------------ jobs and files
|
|
153
|
+
def job(self, job_id: str) -> dict:
|
|
154
|
+
r = self.request("GET", f"/v1/jobs/{job_id}")
|
|
155
|
+
if isinstance(r, dict):
|
|
156
|
+
r.pop("_retry_after", None)
|
|
157
|
+
return r
|
|
158
|
+
|
|
159
|
+
def wait(self, job_id: str, timeout: float = 3600, first_wait: float = 10) -> dict:
|
|
160
|
+
"""Poll a long job until it's done or failed, honouring Retry-After."""
|
|
161
|
+
start, pause = self._clock(), first_wait
|
|
162
|
+
while True:
|
|
163
|
+
if self._clock() - start + pause > timeout:
|
|
164
|
+
raise PatchwellTimeout(job_id, self._clock() - start)
|
|
165
|
+
self._sleep(pause)
|
|
166
|
+
r = self.request("GET", f"/v1/jobs/{job_id}")
|
|
167
|
+
pause = float((r or {}).pop("_retry_after", None) or 10) if isinstance(r, dict) else 10
|
|
168
|
+
if not isinstance(r, dict) or r.get("status") != "running":
|
|
169
|
+
if isinstance(r, dict) and r.get("status") in ("failed", "cancelled"):
|
|
170
|
+
raise PatchwellError(200, r.get("error") or f"the job {r['status']}",
|
|
171
|
+
r.get("code") or ("cancelled" if r["status"] == "cancelled" else "job_failed"),
|
|
172
|
+
bool(r.get("retryable", False)), body=r)
|
|
173
|
+
return r
|
|
174
|
+
|
|
175
|
+
def export(self, result: dict, format: str = "csv") -> bytes:
|
|
176
|
+
"""A result as a file: csv / xlsx for cleaned data; srt, vtt, txt, md, csv, docx for transcripts. Free."""
|
|
177
|
+
content, _ = self.request("POST", f"/v1/export?format={format}", result, raw=True)
|
|
178
|
+
return content
|
|
179
|
+
|
|
180
|
+
def me(self) -> dict:
|
|
181
|
+
"""Check the key: its type, balance and the tools it can call."""
|
|
182
|
+
return self.request("GET", "/v1/me")
|
|
183
|
+
|
|
184
|
+
def reset_only_new(self, state: str) -> dict:
|
|
185
|
+
return self.request("DELETE", f"/v1/clean_data/only_new/{state}")
|
|
186
|
+
|
|
187
|
+
def cancel_job(self, job_id: str) -> dict:
|
|
188
|
+
"""Stop a running job. Nothing is charged."""
|
|
189
|
+
return self.request("POST", f"/v1/jobs/{job_id}/cancel")
|
|
190
|
+
|
|
191
|
+
# ------------------------------------------------------------------ batches: many items, run in parallel
|
|
192
|
+
def quote(self, tool: str, items: list | None = None, *, count: int | None = None) -> dict:
|
|
193
|
+
"""What a batch would cost (a low-high range) and roughly how long it takes at this key's share. Free."""
|
|
194
|
+
body = {"tool": tool, **({"items": items} if items is not None else {"count": count})}
|
|
195
|
+
return self.request("POST", "/v1/quotes", body)
|
|
196
|
+
|
|
197
|
+
def batch(self, tool: str, items: list | None = None, *, items_url: str | None = None,
|
|
198
|
+
max_cost_usd: float | None = None, callback_url: str | None = None, wait: bool = False,
|
|
199
|
+
timeout: float = 24 * 3600) -> dict:
|
|
200
|
+
"""Queue many items for one tool (each the input that tool takes, optionally {"custom_id", "input"}). They
|
|
201
|
+
run in parallel at this key's share, each priced like a single call; failed items are free. wait=True blocks
|
|
202
|
+
until the batch ends and returns it; read the items with batch_results()."""
|
|
203
|
+
body = {"tool": tool, "items": items, "items_url": items_url, "max_cost_usd": max_cost_usd,
|
|
204
|
+
"callback_url": callback_url}
|
|
205
|
+
r = self.request("POST", "/v1/batches", {k: v for k, v in body.items() if v is not None})
|
|
206
|
+
r.pop("_retry_after", None)
|
|
207
|
+
return self.wait_batch(r["id"], timeout=timeout) if wait else r
|
|
208
|
+
|
|
209
|
+
def get_batch(self, batch_id: str) -> dict:
|
|
210
|
+
r = self.request("GET", f"/v1/batches/{batch_id}")
|
|
211
|
+
r.pop("_retry_after", None)
|
|
212
|
+
return r
|
|
213
|
+
|
|
214
|
+
def wait_batch(self, batch_id: str, timeout: float = 24 * 3600, every: float = 10) -> dict:
|
|
215
|
+
"""Poll a batch until it ends (completed, partially_completed, failed, cancelled or expired)."""
|
|
216
|
+
start = self._clock()
|
|
217
|
+
while True:
|
|
218
|
+
r = self.get_batch(batch_id)
|
|
219
|
+
if r.get("status") in ("completed", "partially_completed", "failed", "cancelled", "expired"):
|
|
220
|
+
return r
|
|
221
|
+
if self._clock() - start + every > timeout:
|
|
222
|
+
raise PatchwellTimeout(batch_id, self._clock() - start)
|
|
223
|
+
self._sleep(every)
|
|
224
|
+
|
|
225
|
+
def batch_results(self, batch_id: str, status: str | None = None) -> list[dict]:
|
|
226
|
+
"""Finished items, one dict each: index, custom_id, status and result (or error). Works while it runs."""
|
|
227
|
+
q = f"?status={status}" if status else ""
|
|
228
|
+
content, _ = self.request("GET", f"/v1/batches/{batch_id}/results{q}", raw=True)
|
|
229
|
+
return [json.loads(x) for x in content.decode("utf-8").splitlines() if x.strip()]
|
|
230
|
+
|
|
231
|
+
def cancel_batch(self, batch_id: str) -> dict:
|
|
232
|
+
"""Stop starting new items; running ones finish and are billed."""
|
|
233
|
+
return self.request("POST", f"/v1/batches/{batch_id}/cancel")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def verify_webhook(secret: str, raw_body: bytes, signature_header: str, tolerance_s: int = 300) -> bool:
|
|
237
|
+
"""True when a delivery's Patchwell-Signature matches its exact bytes and is under tolerance_s seconds old."""
|
|
238
|
+
try:
|
|
239
|
+
parts = dict(p.split("=", 1) for p in signature_header.split(","))
|
|
240
|
+
ts = int(parts["t"])
|
|
241
|
+
except (ValueError, KeyError, AttributeError):
|
|
242
|
+
return False
|
|
243
|
+
if abs(time.time() - ts) > tolerance_s:
|
|
244
|
+
return False
|
|
245
|
+
good = hmac.new(secret.encode(), f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()
|
|
246
|
+
return hmac.compare_digest(good, parts.get("v1", ""))
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: patchwell
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Transcription, data cleaning and cited research for scripts, pipelines and AI agents. Pay per result.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://patchwell.io
|
|
7
|
+
Project-URL: Documentation, https://patchwell.io/quickstart
|
|
8
|
+
Keywords: transcription,data cleaning,deduplication,research,api,whisper,csv
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# patchwell
|
|
18
|
+
|
|
19
|
+
Transcription, data cleaning and cited web research from Python. Pay per result: a failed or refused call costs
|
|
20
|
+
nothing. Standard library only, so it runs in Lambda, Airflow, cron jobs and notebooks.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install patchwell
|
|
24
|
+
export PATCHWELL_KEY=pw_live_... # a free key with $1 of credit: https://patchwell.io/#try
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from patchwell import Patchwell
|
|
29
|
+
|
|
30
|
+
pw = Patchwell()
|
|
31
|
+
|
|
32
|
+
# Clean a file, a list of dicts, or several sources merged into one table
|
|
33
|
+
clean = pw.clean_data(url="https://example.com/leads.csv")
|
|
34
|
+
clean = pw.clean_data(rows=[{"Email": "ANN@X.COM", "Name": "ann lee"}])
|
|
35
|
+
clean = pw.clean_data(inputs=[{"url": "https://example.com/crm.csv"}, {"rows": scraped, "name": "web"}])
|
|
36
|
+
|
|
37
|
+
# Only the rows you haven't sent before, for a daily job
|
|
38
|
+
new = pw.clean_data(url=export_url, only_new={"state": "daily-leads", "key": ["Email"]})
|
|
39
|
+
|
|
40
|
+
# Check rows against your rules and map them onto your import template
|
|
41
|
+
ready = pw.clean_data(rows=rows, rules=[{"column": "Age", "range": [0, 120]}],
|
|
42
|
+
target={"columns": [{"name": "email", "required": True}, {"name": "name"}]})
|
|
43
|
+
|
|
44
|
+
# Transcribe: waits for long recordings (polls with the server's Retry-After)
|
|
45
|
+
t = pw.transcribe("https://example.com/interview.mp3")
|
|
46
|
+
print(t["text"])
|
|
47
|
+
open("interview.srt", "w").write(t["srt"])
|
|
48
|
+
|
|
49
|
+
# Research with a cited source for every claim
|
|
50
|
+
# ($0.02 per answered question; declined and unanswered questions are free)
|
|
51
|
+
a = pw.research("Which EU countries require B2B e-invoicing in 2026?")
|
|
52
|
+
print(a["answer"], a["gaps"])
|
|
53
|
+
|
|
54
|
+
# Hard multi-step questions: depth="deep" searches about twice as wide ($0.06 per answered question).
|
|
55
|
+
# private=True keeps the question inside Modal, the cloud Patchwell runs on: same price.
|
|
56
|
+
d = pw.research("How old was the author of Dracula when it was published?", depth="deep")
|
|
57
|
+
# A worked-out answer's claim has "derived": True, "derived_from" (the facts it rests on) and "calc"
|
|
58
|
+
|
|
59
|
+
# Results as files
|
|
60
|
+
open("clean.xlsx", "wb").write(pw.export(clean, "xlsx"))
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Retries never charge twice
|
|
64
|
+
|
|
65
|
+
Every POST carries an `Idempotency-Key`. On a retryable error (`rate_limited`, `unavailable`, a request still running)
|
|
66
|
+
the SDK waits for `Retry-After` and sends the same key again, so you get the first response and pay once.
|
|
67
|
+
Pass your own `idempotency_key=` (an order or row id) and a later rerun of the same item, by cron or by hand,
|
|
68
|
+
returns the first result instead of paying again.
|
|
69
|
+
|
|
70
|
+
## Errors
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from patchwell import PatchwellError
|
|
74
|
+
|
|
75
|
+
try:
|
|
76
|
+
pw.clean_data(url=url)
|
|
77
|
+
except PatchwellError as e:
|
|
78
|
+
if e.code == "insufficient_credit":
|
|
79
|
+
... # top up at https://patchwell.io/#buy
|
|
80
|
+
print(e.code, e.retryable, e.request_id)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Codes:
|
|
84
|
+
<!-- facts:error-codes-list -->
|
|
85
|
+
`invalid_input`, `unauthorized`, `insufficient_credit`, `forbidden`, `not_found`, `method_not_allowed`, `too_large`, `idempotency_in_progress`, `idempotency_mismatch`, `rate_limited`, `source_unavailable`, `unavailable`, `tool_paused`, `internal`, `cancelled`, `expired`, `network`, `timeout`, `job_failed`.
|
|
86
|
+
<!-- /facts:error-codes-list -->
|
|
87
|
+
`source_unavailable`: the site hosting your file failed for a moment. A job that fails while you wait
|
|
88
|
+
raises with the server's own `code` and `retryable`.
|
|
89
|
+
|
|
90
|
+
## Long jobs without waiting
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
job = pw.transcribe(url, wait=False) # {"status": "running", "job_id": "fc-..."}
|
|
94
|
+
result = pw.wait(job["job_id"], timeout=3600)
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Or send `callback_url=` and verify the webhook:
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
from patchwell import verify_webhook
|
|
101
|
+
|
|
102
|
+
ok = verify_webhook(secret, request.body, request.headers["Patchwell-Signature"])
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The full API reference: https://patchwell.io/quickstart
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
patchwell
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "patchwell"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Transcription, data cleaning and cited research for scripts, pipelines and AI agents. Pay per result."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["transcription", "data cleaning", "deduplication", "research", "api", "whisper", "csv"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://patchwell.io"
|
|
18
|
+
Documentation = "https://patchwell.io/quickstart"
|
|
19
|
+
|
|
20
|
+
[tool.setuptools]
|
|
21
|
+
packages = ["patchwell"]
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""The Python SDK against the real Patchwell app (FastAPI TestClient as the transport): retries reuse one
|
|
2
|
+
Idempotency-Key, long jobs are waited for, errors carry the contract's code, webhooks verify.
|
|
3
|
+
python -m pytest storefronts/sdk-python/tests -q"""
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import SimpleNamespace
|
|
10
|
+
|
|
11
|
+
import pytest
|
|
12
|
+
|
|
13
|
+
ROOT = Path(__file__).resolve().parents[3]
|
|
14
|
+
sys.path.insert(0, str(ROOT / "storefronts" / "sdk-python"))
|
|
15
|
+
sys.path.insert(0, str(ROOT / "engine"))
|
|
16
|
+
sys.path.insert(0, str(ROOT / "engine" / "tools"))
|
|
17
|
+
os.environ.setdefault("PATCHWELL_KEYS", "k1:alice,k2:bob")
|
|
18
|
+
import patchwell # noqa: E402
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def app_transport(client, log):
|
|
22
|
+
def send(method, url, headers, body, timeout):
|
|
23
|
+
path = url.split("://", 1)[-1].split("/", 1)[-1]
|
|
24
|
+
r = client.request(method, "/" + path, headers=headers, content=body)
|
|
25
|
+
log.append((method, "/" + path, dict(headers)))
|
|
26
|
+
return r.status_code, {k.lower(): v for k, v in r.headers.items()}, r.content
|
|
27
|
+
return send
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@pytest.fixture()
|
|
31
|
+
def env(monkeypatch):
|
|
32
|
+
import warnings
|
|
33
|
+
warnings.simplefilter("ignore")
|
|
34
|
+
import app as A
|
|
35
|
+
from fastapi.testclient import TestClient
|
|
36
|
+
calls = []
|
|
37
|
+
|
|
38
|
+
class Done: # a cleaning job that has already finished
|
|
39
|
+
def __init__(self, r):
|
|
40
|
+
self.object_id, self.r = f"fc-{len(calls)}", r
|
|
41
|
+
self.get = SimpleNamespace(aio=self._get)
|
|
42
|
+
|
|
43
|
+
async def _get(self, timeout=None):
|
|
44
|
+
return self.r
|
|
45
|
+
|
|
46
|
+
async def spawn(**kw):
|
|
47
|
+
calls.append(kw)
|
|
48
|
+
return Done({"rows": [{"Email": "a@x.com", "_source_rows": [2]}], "changes": [], "review": [],
|
|
49
|
+
"columns": {"Email": {"kind": "email"}}, "stats": {"input_rows": 1, "clean_records": 1}, "compute_s": 0.1})
|
|
50
|
+
monkeypatch.setattr(A, "clean_data", SimpleNamespace(spawn=SimpleNamespace(aio=spawn)))
|
|
51
|
+
with TestClient(A.build_web(), raise_server_exceptions=False) as c:
|
|
52
|
+
log = []
|
|
53
|
+
pw = patchwell.Patchwell("k1", base_url="https://patchwell.io", transport=app_transport(c, log), sleep=lambda s: None)
|
|
54
|
+
yield SimpleNamespace(pw=pw, log=log, calls=calls, A=A, c=c)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_clean_data_sends_one_call_with_an_idempotency_key(env):
|
|
58
|
+
r = env.pw.clean_data(rows=[{"Email": "A@X.COM"}], output="summary")
|
|
59
|
+
assert r["rows"][0]["Email"] == "a@x.com" and env.calls[0]["rows"] == [{"Email": "A@X.COM"}]
|
|
60
|
+
method, path, headers = env.log[-1]
|
|
61
|
+
assert (method, path) == ("POST", "/v1/clean_data") and headers["Idempotency-Key"].startswith("pw-sdk-")
|
|
62
|
+
assert headers["Authorization"] == "Bearer k1" and headers["User-Agent"].startswith("patchwell-python/")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_errors_carry_the_contract():
|
|
66
|
+
pw = patchwell.Patchwell("nope", transport=lambda m, u, h, b, t: (401, {"x-request-id": "req_1"}, json.dumps(
|
|
67
|
+
{"error": "missing or invalid API key", "code": "unauthorized", "retryable": False, "request_id": "req_1"}).encode()))
|
|
68
|
+
with pytest.raises(patchwell.PatchwellError) as e:
|
|
69
|
+
pw.me()
|
|
70
|
+
assert (e.value.status, e.value.code, e.value.retryable, e.value.request_id) == (401, "unauthorized", False, "req_1")
|
|
71
|
+
assert "missing or invalid API key" in str(e.value)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_retryable_errors_retry_with_the_same_key_and_honour_retry_after():
|
|
75
|
+
seen, waits = [], []
|
|
76
|
+
answers = [(503, {"retry-after": "7"}, json.dumps({"error": "busy", "code": "unavailable", "retryable": True}).encode()),
|
|
77
|
+
(409, {"retry-after": "2"}, json.dumps({"error": "running", "code": "idempotency_in_progress", "retryable": True}).encode()),
|
|
78
|
+
(200, {}, json.dumps({"rows": [], "stats": {}}).encode())]
|
|
79
|
+
|
|
80
|
+
def t(m, u, h, b, timeout):
|
|
81
|
+
seen.append(h.get("Idempotency-Key"))
|
|
82
|
+
return answers[len(seen) - 1]
|
|
83
|
+
pw = patchwell.Patchwell("k", transport=t, sleep=waits.append)
|
|
84
|
+
assert pw.clean_data(url="https://x.test/a.csv") == {"rows": [], "stats": {}}
|
|
85
|
+
assert len(set(seen)) == 1 and len(seen) == 3 and waits == [7.0, 2.0]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_non_retryable_errors_do_not_retry():
|
|
89
|
+
n = []
|
|
90
|
+
pw = patchwell.Patchwell("k", transport=lambda m, u, h, b, t: n.append(1) or (402, {}, json.dumps(
|
|
91
|
+
{"error": "not enough credit", "code": "insufficient_credit", "retryable": False}).encode()), sleep=lambda s: None)
|
|
92
|
+
with pytest.raises(patchwell.PatchwellError, match="not enough credit"):
|
|
93
|
+
pw.research("What is the capital of France?")
|
|
94
|
+
assert len(n) == 1
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_long_jobs_are_waited_for():
|
|
98
|
+
answers = [(202, {"location": "/v1/jobs/fc-1", "retry-after": "10"}, json.dumps({"status": "running", "job_id": "fc-1"}).encode()),
|
|
99
|
+
(200, {"retry-after": "10"}, json.dumps({"status": "running", "job_id": "fc-1"}).encode()),
|
|
100
|
+
(200, {}, json.dumps({"status": "done", "job_id": "fc-1", "text": "hello"}).encode())]
|
|
101
|
+
sent, waits = [], []
|
|
102
|
+
|
|
103
|
+
def t(m, u, h, b, timeout):
|
|
104
|
+
sent.append((m, u.split("patchwell.io")[-1], h.get("Prefer")))
|
|
105
|
+
return answers[len(sent) - 1]
|
|
106
|
+
pw = patchwell.Patchwell("k", transport=t, sleep=waits.append)
|
|
107
|
+
r = pw.transcribe("https://x.test/a.mp3")
|
|
108
|
+
assert r["text"] == "hello" and sent[0] == ("POST", "/v1/transcribe", "respond-async")
|
|
109
|
+
assert sent[1][:2] == ("GET", "/v1/jobs/fc-1") and waits == [10.0, 10.0]
|
|
110
|
+
r = patchwell.Patchwell("k", transport=lambda m, u, h, b, t_: answers[0], sleep=lambda s: None).transcribe(
|
|
111
|
+
"https://x.test/a.mp3", wait=False)
|
|
112
|
+
assert r == {"status": "running", "job_id": "fc-1"}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_waiting_gives_up_at_the_timeout():
|
|
116
|
+
clock = [0.0]
|
|
117
|
+
pw = patchwell.Patchwell("k", transport=lambda m, u, h, b, t: (200, {"retry-after": "30"}, json.dumps(
|
|
118
|
+
{"status": "running", "job_id": "fc-9"}).encode()), sleep=lambda s: clock.__setitem__(0, clock[0] + s),
|
|
119
|
+
clock=lambda: clock[0])
|
|
120
|
+
with pytest.raises(patchwell.PatchwellTimeout) as e:
|
|
121
|
+
pw.wait("fc-9", timeout=100)
|
|
122
|
+
assert e.value.job_id == "fc-9"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_webhook_verification_matches_the_server_signer():
|
|
126
|
+
import automation as au
|
|
127
|
+
body = json.dumps({"tool": "transcribe", "result": {"text": "hi"}}).encode()
|
|
128
|
+
now = int(time.time())
|
|
129
|
+
header = au.sign("sec", body, now)
|
|
130
|
+
assert patchwell.verify_webhook("sec", body, header)
|
|
131
|
+
assert not patchwell.verify_webhook("sec", body + b" ", header)
|
|
132
|
+
assert not patchwell.verify_webhook("other", body, header)
|
|
133
|
+
assert not patchwell.verify_webhook("sec", body, au.sign("sec", body, now - 3600)) # too old: a replay
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_export_returns_bytes(env):
|
|
137
|
+
data = env.pw.export({"rows": [{"a": 1}], "columns": {"a": {"kind": "number"}}}, "csv")
|
|
138
|
+
assert isinstance(data, bytes) and data.lstrip(b"\xef\xbb\xbf").startswith(b"a,") # BOM: Excel opens it right
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_batches_submit_wait_and_read_results():
|
|
142
|
+
sent, polls = [], iter(["queued", "running", "completed"])
|
|
143
|
+
|
|
144
|
+
def t(m, u, h, b, timeout):
|
|
145
|
+
path = u.split("patchwell.io", 1)[1]
|
|
146
|
+
sent.append((m, path, json.loads(b) if b else None))
|
|
147
|
+
if (m, path) == ("POST", "/v1/batches"):
|
|
148
|
+
return 202, {"retry-after": "10"}, json.dumps({"id": "bt_1", "status": "queued"}).encode()
|
|
149
|
+
if path == "/v1/batches/bt_1":
|
|
150
|
+
return 200, {}, json.dumps({"id": "bt_1", "status": next(polls)}).encode()
|
|
151
|
+
if path.startswith("/v1/batches/bt_1/results"):
|
|
152
|
+
return 200, {}, b'{"index": 0, "custom_id": "a", "status": "succeeded"}\n'
|
|
153
|
+
if path == "/v1/quotes":
|
|
154
|
+
return 200, {}, json.dumps({"cost_usd": {"low": 0, "high": 0.3}}).encode()
|
|
155
|
+
return 200, {}, b"{}"
|
|
156
|
+
pw = patchwell.Patchwell("k", base_url="https://patchwell.io", transport=t, sleep=lambda s: None)
|
|
157
|
+
assert pw.quote("research", count=2)["cost_usd"]["high"] == 0.3
|
|
158
|
+
done = pw.batch("research", [{"custom_id": "a", "ask": "q"}], max_cost_usd=1, wait=True)
|
|
159
|
+
assert done["status"] == "completed"
|
|
160
|
+
assert sent[1] == ("POST", "/v1/batches", {"tool": "research", "items": [{"custom_id": "a", "ask": "q"}],
|
|
161
|
+
"max_cost_usd": 1})
|
|
162
|
+
assert pw.batch_results("bt_1") == [{"index": 0, "custom_id": "a", "status": "succeeded"}]
|
|
163
|
+
pw.batch_results("bt_1", status="failed")
|
|
164
|
+
assert sent[-1][1] == "/v1/batches/bt_1/results?status=failed"
|
|
165
|
+
pw.cancel_batch("bt_1")
|
|
166
|
+
pw.cancel_job("fc-9")
|
|
167
|
+
assert [s[1] for s in sent[-2:]] == ["/v1/batches/bt_1/cancel", "/v1/jobs/fc-9/cancel"]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def test_a_callers_own_idempotency_key_is_sent_as_is():
|
|
171
|
+
"""2026-11-22 audit: a process-level retry (a cron rerun of the same item) minted a new key and paid twice."""
|
|
172
|
+
seen = []
|
|
173
|
+
|
|
174
|
+
def t(m, u, h, b, timeout):
|
|
175
|
+
seen.append(h.get("Idempotency-Key"))
|
|
176
|
+
return (200, {}, json.dumps({"rows": [], "stats": {}}).encode())
|
|
177
|
+
pw = patchwell.Patchwell("k", transport=t, sleep=lambda s: None)
|
|
178
|
+
pw.clean_data(url="https://x.test/a.csv", idempotency_key="order-1234")
|
|
179
|
+
pw.clean_data(url="https://x.test/a.csv", idempotency_key="order-1234")
|
|
180
|
+
assert seen == ["order-1234", "order-1234"]
|
|
181
|
+
assert "idempotency_key" not in json.dumps(seen)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@pytest.mark.parametrize("final,code,retryable", [
|
|
185
|
+
({"status": "failed", "job_id": "fc-1", "error": "container stopped", "code": "internal", "retryable": True},
|
|
186
|
+
"internal", True),
|
|
187
|
+
({"status": "cancelled", "job_id": "fc-1", "error": "cancelled by the caller", "code": "cancelled",
|
|
188
|
+
"retryable": False}, "cancelled", False)])
|
|
189
|
+
def test_a_failed_or_cancelled_job_raises_with_the_servers_code(final, code, retryable):
|
|
190
|
+
answers = [(202, {}, json.dumps({"status": "running", "job_id": "fc-1"}).encode()), (200, {}, json.dumps(final).encode())]
|
|
191
|
+
n = []
|
|
192
|
+
pw = patchwell.Patchwell("k", transport=lambda m, u, h, b, t: n.append(1) or answers[len(n) - 1],
|
|
193
|
+
sleep=lambda s: None)
|
|
194
|
+
with pytest.raises(patchwell.PatchwellError) as e:
|
|
195
|
+
pw.transcribe("https://x.test/a.mp3")
|
|
196
|
+
assert e.value.code == code and e.value.retryable is retryable
|