voiddo-utils 1.1.3__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.
- voiddo_utils/__init__.py +21 -0
- voiddo_utils/_client.py +295 -0
- voiddo_utils/_generated.py +1218 -0
- voiddo_utils/_version.py +3 -0
- voiddo_utils/errors.py +97 -0
- voiddo_utils/py.typed +0 -0
- voiddo_utils-1.1.3.dist-info/METADATA +132 -0
- voiddo_utils-1.1.3.dist-info/RECORD +11 -0
- voiddo_utils-1.1.3.dist-info/WHEEL +5 -0
- voiddo_utils-1.1.3.dist-info/licenses/LICENSE +21 -0
- voiddo_utils-1.1.3.dist-info/top_level.txt +1 -0
voiddo_utils/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""voiddo-utils: Python client for the vøiddo utilities API (https://data.voiddo.com).
|
|
2
|
+
|
|
3
|
+
from voiddo_utils import Client
|
|
4
|
+
|
|
5
|
+
client = Client() # free tier: 20 calls per day per IP; or Client(api_key="vd_...")
|
|
6
|
+
png = client.call("qr_code", text="https://example.com") # bytes
|
|
7
|
+
country = client.call("iso_codes", type="country", query="IL") # dict
|
|
8
|
+
|
|
9
|
+
The tool methods (``client.qr_code(...)``, ``client.pdf_merge(...)``, ...) and the ``CAPABILITIES`` table are generated from
|
|
10
|
+
https://data.voiddo.com/openapi.json by ``scripts/build_sdk.py``.
|
|
11
|
+
"""
|
|
12
|
+
from ._client import Client, Result, prepare_inputs
|
|
13
|
+
from ._generated import API_VERSION, CAPABILITIES, OPENAPI_FINGERPRINT, Capability, Field, FileInput
|
|
14
|
+
from ._version import DEFAULT_BASE_URL, DEFAULT_SRC, __version__
|
|
15
|
+
from .errors import VoiddoConnectionError, VoiddoError, VoiddoPaymentRequired, VoiddoRateLimited
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"API_VERSION", "CAPABILITIES", "Capability", "Client", "DEFAULT_BASE_URL", "DEFAULT_SRC", "Field", "FileInput",
|
|
19
|
+
"VoiddoConnectionError", "VoiddoError", "VoiddoPaymentRequired", "VoiddoRateLimited", "OPENAPI_FINGERPRINT", "Result",
|
|
20
|
+
"__version__", "prepare_inputs",
|
|
21
|
+
]
|
voiddo_utils/_client.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""The vøiddo client: a thin ``requests`` wrapper around ``POST /v1/<slug>`` (see https://data.voiddo.com/llms.txt)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import json
|
|
6
|
+
import keyword
|
|
7
|
+
import os
|
|
8
|
+
import random
|
|
9
|
+
import re
|
|
10
|
+
import time
|
|
11
|
+
import uuid
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, List, Mapping, Optional, Union
|
|
15
|
+
|
|
16
|
+
import requests
|
|
17
|
+
|
|
18
|
+
from ._generated import CAPABILITIES, CapabilityMethods, Timeout
|
|
19
|
+
from ._version import DEFAULT_BASE_URL, DEFAULT_SRC, __version__
|
|
20
|
+
from .errors import VoiddoConnectionError, VoiddoError, error_from_response
|
|
21
|
+
|
|
22
|
+
_SLUG_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Result:
|
|
27
|
+
"""The full answer to one call (what :meth:`Client.run` returns; :meth:`Client.call` returns only :attr:`value`)."""
|
|
28
|
+
|
|
29
|
+
slug: str
|
|
30
|
+
data: Any = None # the JSON result of a JSON tool
|
|
31
|
+
content: Optional[bytes] = None # the file of a file tool (PNG, PDF, CSV, ...)
|
|
32
|
+
mime: Optional[str] = None
|
|
33
|
+
filename: Optional[str] = None
|
|
34
|
+
credits_charged: int = 0 # credits debited for this call (0 on the free tier)
|
|
35
|
+
balance: Optional[int] = None # credits left; only when an API key was used
|
|
36
|
+
free_remaining: Optional[int] = None # free calls left today for this IP; only without a key
|
|
37
|
+
meta: Dict[str, Any] = field(default_factory=dict)
|
|
38
|
+
request_id: Optional[str] = None
|
|
39
|
+
replayed: bool = False # True when a retried request id was answered without charging again
|
|
40
|
+
|
|
41
|
+
@property
|
|
42
|
+
def is_file(self) -> bool:
|
|
43
|
+
return self.content is not None
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def value(self) -> Union[Dict[str, Any], bytes]:
|
|
47
|
+
"""``bytes`` for a file result, the JSON ``data`` otherwise."""
|
|
48
|
+
return self.content if self.content is not None else self.data
|
|
49
|
+
|
|
50
|
+
def save(self, path: Union[str, "os.PathLike[str]"]) -> Path:
|
|
51
|
+
"""Write a file result to ``path`` and return the path."""
|
|
52
|
+
if self.content is None:
|
|
53
|
+
raise ValueError("this result is JSON data, not a file")
|
|
54
|
+
target = Path(path)
|
|
55
|
+
target.write_bytes(self.content)
|
|
56
|
+
return target
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ----- request bodies -------------------------------------------------------------------------------------------------
|
|
60
|
+
def _wire_name(name: str) -> str:
|
|
61
|
+
"""``from_`` -> ``from``: Python keywords cannot be keyword arguments, so a trailing underscore is dropped."""
|
|
62
|
+
return name[:-1] if name.endswith("_") and keyword.iskeyword(name[:-1]) else name
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _b64(raw: bytes) -> str:
|
|
66
|
+
return base64.b64encode(raw).decode("ascii")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _encode(value: Any, as_file: bool) -> Any:
|
|
70
|
+
"""JSON-ready form of one input value. Bytes and open files become base64; local paths are read when the field is a file."""
|
|
71
|
+
if isinstance(value, (bytes, bytearray, memoryview)):
|
|
72
|
+
return _b64(bytes(value))
|
|
73
|
+
if hasattr(value, "read"):
|
|
74
|
+
data = value.read()
|
|
75
|
+
return _b64(data.encode("utf-8") if isinstance(data, str) else bytes(data))
|
|
76
|
+
if isinstance(value, os.PathLike):
|
|
77
|
+
return _b64(Path(value).read_bytes()) if as_file else os.fspath(value)
|
|
78
|
+
if isinstance(value, Mapping):
|
|
79
|
+
return dict(value)
|
|
80
|
+
if isinstance(value, (list, tuple)):
|
|
81
|
+
return [_encode(v, as_file) for v in value]
|
|
82
|
+
return value
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def prepare_inputs(slug: str, inputs: Mapping[str, Any]) -> Dict[str, Any]:
|
|
86
|
+
"""The JSON object to send: ``None`` values are dropped (the API default applies), ``from_`` becomes ``from``, file inputs are encoded."""
|
|
87
|
+
cap = CAPABILITIES.get(slug)
|
|
88
|
+
file_fields = set(cap.file_inputs) if cap else None # None: an unknown tool, treat paths as files
|
|
89
|
+
out: Dict[str, Any] = {}
|
|
90
|
+
for key, value in inputs.items():
|
|
91
|
+
if value is None:
|
|
92
|
+
continue
|
|
93
|
+
name = _wire_name(key)
|
|
94
|
+
out[name] = _encode(value, file_fields is None or name in file_fields)
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _parse_json(resp: requests.Response) -> Any:
|
|
99
|
+
try:
|
|
100
|
+
return resp.json()
|
|
101
|
+
except ValueError:
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _short(exc: BaseException) -> str:
|
|
106
|
+
return str(exc).replace("\n", " ")[:200]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class Client(CapabilityMethods):
|
|
110
|
+
"""Client for the vøiddo utilities API.
|
|
111
|
+
|
|
112
|
+
>>> from voiddo_utils import Client
|
|
113
|
+
>>> client = Client() # free tier, or Client(api_key="vd_...") / env VOIDDO_API_KEY
|
|
114
|
+
>>> png = client.call("qr_code", text="https://example.com") # bytes (a file result)
|
|
115
|
+
>>> info = client.call("iso_codes", type="country", query="IL") # dict (a JSON result)
|
|
116
|
+
>>> client.qr_code(text="https://example.com", format="svg") # the same call as a typed method
|
|
117
|
+
|
|
118
|
+
``call`` returns the result only; use :meth:`run` for credits, balance and metadata. Errors raise :class:`VoiddoError`
|
|
119
|
+
(HTTP 402 raises :class:`VoiddoPaymentRequired` with ``checkout_url``). Idempotent retries: every call carries an
|
|
120
|
+
``X-Request-Id``; calls made with an API key are retried (``max_retries``) after a connection error, HTTP 503 or a rate
|
|
121
|
+
limit without being charged twice. Calls without a key are retried only when the API says nothing was executed.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, *, timeout: Timeout = (10.0, 120.0),
|
|
125
|
+
max_retries: int = 2, retry_backoff: float = 0.5, max_retry_wait: float = 20.0, src: str = DEFAULT_SRC,
|
|
126
|
+
session: Optional[requests.Session] = None) -> None:
|
|
127
|
+
key = api_key if api_key is not None else (os.environ.get("VOIDDO_API_KEY") or os.environ.get("MINT_API_KEY"))
|
|
128
|
+
self.api_key: Optional[str] = (key or "").strip() or None
|
|
129
|
+
root = (base_url or os.environ.get("VOIDDO_BASE_URL") or os.environ.get("MINT_BASE_URL") or DEFAULT_BASE_URL).strip().rstrip("/")
|
|
130
|
+
if not re.match(r"^https?://[^\s/]+", root):
|
|
131
|
+
raise ValueError("base_url must start with http:// or https://")
|
|
132
|
+
self.base_url = root
|
|
133
|
+
self.timeout = timeout
|
|
134
|
+
self.max_retries = max(0, int(max_retries))
|
|
135
|
+
self.retry_backoff = max(0.0, float(retry_backoff))
|
|
136
|
+
self.max_retry_wait = max(0.0, float(max_retry_wait))
|
|
137
|
+
self.src = src
|
|
138
|
+
self.user_agent = f"voiddo-utils-python/{__version__}"
|
|
139
|
+
self._session = session or requests.Session()
|
|
140
|
+
self._sleep = time.sleep
|
|
141
|
+
|
|
142
|
+
def __repr__(self) -> str:
|
|
143
|
+
return f"Client(base_url={self.base_url!r}, api_key={'<set>' if self.api_key else None})"
|
|
144
|
+
|
|
145
|
+
def close(self) -> None:
|
|
146
|
+
self._session.close()
|
|
147
|
+
|
|
148
|
+
def __enter__(self) -> "Client":
|
|
149
|
+
return self
|
|
150
|
+
|
|
151
|
+
def __exit__(self, *exc: Any) -> None:
|
|
152
|
+
self.close()
|
|
153
|
+
|
|
154
|
+
# ----- the calls ----------------------------------------------------------------------------------------------------
|
|
155
|
+
def run(self, slug: str, inputs: Optional[Mapping[str, Any]] = None, *, request_id: Optional[str] = None,
|
|
156
|
+
timeout: Optional[Timeout] = None) -> Result:
|
|
157
|
+
"""Run one tool and return the full :class:`Result`. ``inputs`` is the tool's input object (see ``capabilities()``)."""
|
|
158
|
+
if not isinstance(slug, str) or not _SLUG_RE.match(slug):
|
|
159
|
+
raise ValueError("slug must look like 'qr_code' (lower-case letters, digits and underscores)")
|
|
160
|
+
body = json.dumps(prepare_inputs(slug, inputs or {}), ensure_ascii=False, separators=(",", ":"),
|
|
161
|
+
allow_nan=False).encode("utf-8")
|
|
162
|
+
rid = request_id or uuid.uuid4().hex
|
|
163
|
+
resp = self._request("POST", f"/v1/{slug}", params={"src": self.src}, body=body, request_id=rid, timeout=timeout)
|
|
164
|
+
payload = self._checked(resp, rid)
|
|
165
|
+
if not isinstance(payload, dict) or not ("data" in payload or "file_base64" in payload):
|
|
166
|
+
raise VoiddoError("the API answered 200 with something that is not a result", status=resp.status_code,
|
|
167
|
+
error="bad_response", request_id=rid)
|
|
168
|
+
content = None
|
|
169
|
+
if "file_base64" in payload:
|
|
170
|
+
try:
|
|
171
|
+
content = base64.b64decode(payload.get("file_base64") or "")
|
|
172
|
+
except (ValueError, TypeError) as exc:
|
|
173
|
+
raise VoiddoError("the API sent a file that could not be decoded", status=resp.status_code, error="bad_response",
|
|
174
|
+
request_id=rid) from exc
|
|
175
|
+
return Result(slug=slug, data=payload.get("data"), content=content, mime=payload.get("mime"),
|
|
176
|
+
filename=payload.get("filename"), credits_charged=int(payload.get("credits_charged") or 0),
|
|
177
|
+
balance=payload.get("balance"), free_remaining=payload.get("free_remaining"),
|
|
178
|
+
meta=dict(payload.get("meta") or {}), request_id=payload.get("request_id") or rid,
|
|
179
|
+
replayed=bool(payload.get("replayed")))
|
|
180
|
+
|
|
181
|
+
def call(self, slug: str, /, **inputs: Any) -> Union[Dict[str, Any], bytes]:
|
|
182
|
+
"""Run one tool: ``bytes`` for tools that produce a file, a ``dict`` for tools that produce JSON.
|
|
183
|
+
|
|
184
|
+
File inputs accept ``bytes``, ``pathlib.Path``, an open binary file, a base64 / ``data:`` string or ``{"url": "https://..."}``.
|
|
185
|
+
Python keywords get a trailing underscore: ``from_="USD"`` is sent as ``from``.
|
|
186
|
+
"""
|
|
187
|
+
return self.run(slug, inputs).value
|
|
188
|
+
|
|
189
|
+
def _invoke(self, slug: str, inputs: Mapping[str, Any], request_id: Optional[str] = None,
|
|
190
|
+
timeout: Optional[Timeout] = None) -> Union[Dict[str, Any], bytes]:
|
|
191
|
+
return self.run(slug, inputs, request_id=request_id, timeout=timeout).value
|
|
192
|
+
|
|
193
|
+
def capabilities(self) -> List[Dict[str, Any]]:
|
|
194
|
+
"""The tool catalogue (slug, title, price in credits, input schema, examples) as the API serves it."""
|
|
195
|
+
payload = self._get("/v1/capabilities")
|
|
196
|
+
return list(payload.get("capabilities") or []) if isinstance(payload, dict) else []
|
|
197
|
+
|
|
198
|
+
def capability(self, slug: str) -> Dict[str, Any]:
|
|
199
|
+
"""The catalogue entry of one tool."""
|
|
200
|
+
if not _SLUG_RE.match(slug or ""):
|
|
201
|
+
raise ValueError("slug must look like 'qr_code'")
|
|
202
|
+
return self._get(f"/v1/capabilities/{slug}")
|
|
203
|
+
|
|
204
|
+
def wallet(self) -> Dict[str, Any]:
|
|
205
|
+
"""Balance, lifetime purchases, recent ledger rows and the checkout URL of the API key (needs a key)."""
|
|
206
|
+
return self._get("/v1/wallet", need_key=True)
|
|
207
|
+
|
|
208
|
+
def usage(self, days: int = 7) -> Dict[str, Any]:
|
|
209
|
+
"""Calls and credits per day and tool for the last ``days`` (1 to 31) days (needs a key)."""
|
|
210
|
+
return self._get("/v1/usage", params={"days": int(days)}, need_key=True)
|
|
211
|
+
|
|
212
|
+
def create_key(self, email: Optional[str] = None) -> Dict[str, Any]:
|
|
213
|
+
"""Create a new API key (the response shows it once; it starts with 0 credits). Does not change this client's key."""
|
|
214
|
+
body = json.dumps({"email": email} if email else {}).encode("utf-8")
|
|
215
|
+
resp = self._request("POST", "/v1/keys", params={"src": self.src}, body=body, request_id=None, timeout=None)
|
|
216
|
+
return self._checked(resp, None)
|
|
217
|
+
|
|
218
|
+
# ----- plumbing -----------------------------------------------------------------------------------------------------
|
|
219
|
+
def _get(self, path: str, *, params: Optional[Mapping[str, Any]] = None, need_key: bool = False) -> Any:
|
|
220
|
+
if need_key and not self.api_key:
|
|
221
|
+
raise VoiddoError("this call needs an API key: pass api_key=... or set VOIDDO_API_KEY (create one with create_key())",
|
|
222
|
+
error="missing_api_key")
|
|
223
|
+
resp = self._request("GET", path, params=params, body=None, request_id=None, timeout=None)
|
|
224
|
+
return self._checked(resp, None)
|
|
225
|
+
|
|
226
|
+
def _checked(self, resp: requests.Response, rid: Optional[str]) -> Any:
|
|
227
|
+
request_id = resp.headers.get("X-Request-Id") or rid
|
|
228
|
+
payload = _parse_json(resp)
|
|
229
|
+
if 300 <= resp.status_code < 400:
|
|
230
|
+
raise VoiddoError(f"unexpected redirect to {resp.headers.get('Location')!r}; use the canonical https base_url",
|
|
231
|
+
status=resp.status_code, error="redirect", request_id=request_id)
|
|
232
|
+
if resp.status_code >= 400:
|
|
233
|
+
raise error_from_response(resp.status_code, payload, request_id=request_id,
|
|
234
|
+
retry_after_header=resp.headers.get("Retry-After"), text=resp.text)
|
|
235
|
+
return payload
|
|
236
|
+
|
|
237
|
+
def _request(self, method: str, path: str, *, params: Optional[Mapping[str, Any]], body: Optional[bytes],
|
|
238
|
+
request_id: Optional[str], timeout: Optional[Timeout]) -> requests.Response:
|
|
239
|
+
headers = {"Accept": "*/*", "User-Agent": self.user_agent} # */* keeps the answer a JSON envelope for every tool
|
|
240
|
+
if self.api_key:
|
|
241
|
+
headers["Authorization"] = "Bearer " + self.api_key
|
|
242
|
+
if request_id:
|
|
243
|
+
headers["X-Request-Id"] = request_id
|
|
244
|
+
if body is not None:
|
|
245
|
+
headers["Content-Type"] = "application/json"
|
|
246
|
+
safe = method == "GET" or bool(self.api_key) # re-sending cannot consume a free-tier slot or charge twice
|
|
247
|
+
attempt = 0
|
|
248
|
+
while True:
|
|
249
|
+
try:
|
|
250
|
+
resp = self._session.request(method, self.base_url + path, params=params, data=body, headers=headers,
|
|
251
|
+
timeout=self.timeout if timeout is None else timeout, allow_redirects=False)
|
|
252
|
+
except requests.exceptions.RequestException as exc:
|
|
253
|
+
transient = isinstance(exc, (requests.exceptions.ConnectionError, requests.exceptions.Timeout))
|
|
254
|
+
if safe and transient and attempt < self.max_retries:
|
|
255
|
+
self._sleep(self._delay(attempt, None))
|
|
256
|
+
attempt += 1
|
|
257
|
+
continue
|
|
258
|
+
raise VoiddoConnectionError(f"cannot reach {self.base_url}: {type(exc).__name__}: {_short(exc)}",
|
|
259
|
+
request_id=request_id) from exc
|
|
260
|
+
wait = self._retry_wait(resp, attempt, safe)
|
|
261
|
+
if wait is not None and attempt < self.max_retries:
|
|
262
|
+
resp.close()
|
|
263
|
+
self._sleep(wait)
|
|
264
|
+
attempt += 1
|
|
265
|
+
continue
|
|
266
|
+
return resp
|
|
267
|
+
|
|
268
|
+
def _delay(self, attempt: int, hint: Optional[float]) -> float:
|
|
269
|
+
if hint is not None:
|
|
270
|
+
return min(max(hint, 0.0), self.max_retry_wait)
|
|
271
|
+
base = self.retry_backoff * (2 ** attempt)
|
|
272
|
+
return min(base * (1.0 + 0.25 * random.random()), self.max_retry_wait)
|
|
273
|
+
|
|
274
|
+
def _retry_wait(self, resp: requests.Response, attempt: int, safe: bool) -> Optional[float]:
|
|
275
|
+
"""Seconds to wait before re-sending, or None when this answer is final. Only answers that mean 'nothing was run'."""
|
|
276
|
+
status = resp.status_code
|
|
277
|
+
try:
|
|
278
|
+
hint: Optional[float] = float(resp.headers.get("Retry-After")) if resp.headers.get("Retry-After") else None
|
|
279
|
+
except ValueError:
|
|
280
|
+
hint = None
|
|
281
|
+
if status == 503: # all worker slots busy: rejected before anything ran
|
|
282
|
+
return self._delay(attempt, hint)
|
|
283
|
+
payload = _parse_json(resp) if status in (409, 429) else None
|
|
284
|
+
payload = payload if isinstance(payload, dict) else {}
|
|
285
|
+
code = payload.get("error")
|
|
286
|
+
if status == 429 and code == "rate_limited":
|
|
287
|
+
detail = payload.get("detail")
|
|
288
|
+
if isinstance(detail, dict) and isinstance(detail.get("retry_after_s"), (int, float)):
|
|
289
|
+
hint = float(detail["retry_after_s"])
|
|
290
|
+
if hint is not None and hint > self.max_retry_wait: # a long wait is the caller's decision
|
|
291
|
+
return None
|
|
292
|
+
return self._delay(attempt, hint)
|
|
293
|
+
if status == 409 and code == "request_in_progress" and safe:
|
|
294
|
+
return self._delay(attempt, hint)
|
|
295
|
+
return None
|