patchwell 0.1.0__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.
patchwell/__init__.py ADDED
@@ -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,6 @@
1
+ patchwell/__init__.py,sha256=62DCEBwJgUyo7tp2_fbDh6P4UyDiCAgjyDAdJmZiM4c,14194
2
+ patchwell-0.1.0.dist-info/licenses/LICENSE,sha256=3OP97WSQKI3HT1LNNPp8GPsplBuLct0DB2-RV2SF_r0,1066
3
+ patchwell-0.1.0.dist-info/METADATA,sha256=Vo6nK2TPCfUXWrTAh7gzEkQO2ywZlRndpwEA3LOPQ4M,4366
4
+ patchwell-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ patchwell-0.1.0.dist-info/top_level.txt,sha256=4bqC6yqThZE93X31TVohyuat2X2l8Kp8Fam3dk6jAZk,10
6
+ patchwell-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ patchwell