voiddo-utils 1.1.3__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 voiddo studio
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,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: voiddo-utils
3
+ Version: 1.1.3
4
+ Summary: Python client for the vøiddo utilities API (data.voiddo.com): PDF, image, QR, CSV/Excel, JSON/YAML conversion, HTML to PDF, DNS/RDAP and other lookups.
5
+ Author-email: voiddo studio <data@voiddo.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://data.voiddo.com
8
+ Project-URL: Documentation, https://data.voiddo.com/llms.txt
9
+ Project-URL: OpenAPI, https://data.voiddo.com/openapi.json
10
+ Keywords: pdf,qr-code,image-convert,csv,json-schema,dns,rdap,api-client,mcp
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Topic :: Software Development :: Libraries
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: requests>=2.20
21
+ Dynamic: license-file
22
+
23
+ # voiddo-utils
24
+
25
+ Python client for the **vøiddo utilities API** at <https://data.voiddo.com>: deterministic tools for PDF (merge, split, text, info),
26
+ images and SVG, QR codes, HTML to PDF or image, Markdown, CSV / Excel / JSON / YAML conversion, JSON Schema validation, and
27
+ DNS / RDAP / IP / currency / holiday / ISO-code / time-zone lookups. One thin class on top of `requests`; no other dependencies.
28
+
29
+ ## Install
30
+
31
+ The package is not on PyPI yet. Until it is, install the wheel the API serves (file names and checksums: <https://data.voiddo.com/sdk/>):
32
+
33
+ ```bash
34
+ pip install https://data.voiddo.com/sdk/voiddo_utils-1.1.3-py3-none-any.whl
35
+ ```
36
+
37
+ It is imported as `voiddo_utils`.
38
+
39
+ ## Use
40
+
41
+ ```python
42
+ from voiddo_utils import Client
43
+
44
+ client = Client() # free tier: 20 calls per day per IP. With a key: Client(api_key="vd_...") or env VOIDDO_API_KEY
45
+
46
+ png = client.call("qr_code", text="https://example.com") # bytes: tools that produce a file return bytes
47
+ open("qr.png", "wb").write(png)
48
+ country = client.call("iso_codes", type="country", query="IL") # dict: tools that produce JSON return a dict
49
+ svg = client.qr_code(text="https://example.com", format="svg") # every tool is also a typed, keyword-only method
50
+
51
+ # files go in as bytes, pathlib.Path, an open binary file, base64 / data: strings, or {"url": "https://..."}
52
+ from pathlib import Path
53
+ pages = client.pdf_text(file=Path("report.pdf"))
54
+ merged = client.pdf_merge(files=[Path("a.pdf"), Path("b.pdf")])
55
+
56
+ # inputs named like Python keywords get a trailing underscore: from_ is sent as "from"
57
+ yaml = client.json_yaml_convert(input='{"a": 1}', from_="json", to="yaml")
58
+
59
+ # run() returns the full Result: value, credits charged, balance, free calls left, metadata, request id
60
+ result = client.run("pdf_info", {"file": Path("report.pdf")})
61
+ print(result.data, result.credits_charged, result.balance, result.free_remaining)
62
+
63
+ client.wallet() # balance and recent ledger rows (needs a key)
64
+ client.usage(days=7) # calls and credits per day and tool (needs a key)
65
+ client.capabilities() # the tool catalogue exactly as the API serves it
66
+ client.create_key() # a new key, shown once, starting at 0 credits
67
+ ```
68
+
69
+ ## Money
70
+
71
+ * Without a key, 20 calls per day per client IP are free. After that, and whenever a key's balance is too low, the API answers
72
+ HTTP 402 and the client raises `VoiddoPaymentRequired`; its `checkout_url` leads to the credit packs and `packs` lists them.
73
+ * Credits are prepaid: **$5 = 500**, **$9 = 1,000**, **$29 = 4,000**.
74
+ * The table below lists each tool's base price. A few tools (PDF merge, split and text on long documents, XLSX output) charge
75
+ more for large jobs; `Result.credits_charged` is always the exact amount. A failed call is not charged credits (on the free tier
76
+ it still uses one of the 20 daily calls).
77
+ * `screenshot` is free-tier only and is not sold through credits.
78
+
79
+ ```python
80
+ from voiddo_utils import Client, VoiddoError, VoiddoPaymentRequired
81
+
82
+ try:
83
+ Client().call("qr_code", text="hello")
84
+ except VoiddoPaymentRequired as e:
85
+ print("buy credits:", e.checkout_url) # e.packs lists the packs
86
+ except VoiddoError as e:
87
+ print(e.status, e.message) # e.g. 400 invalid input at (root): 'query' is a required property
88
+ ```
89
+
90
+ ## Retries
91
+
92
+ Every call carries an `X-Request-Id`. With an API key the client re-sends after a connection error, HTTP 503 or a rate limit
93
+ (`max_retries`, default 2) and the API does not charge the same id twice (`Result.replayed`). Without a key a call is re-sent only
94
+ when the API says nothing ran (HTTP 503, rate limit), so a free-tier slot is never spent twice by accident.
95
+
96
+ ## Tools
97
+
98
+ <!-- BEGIN GENERATED:tools -->
99
+ | Method | Tool | Credits | Returns |
100
+ | --- | --- | --- | --- |
101
+ | `csv_profile(...)` | CSV and Excel data profiler | 1 | `dict` |
102
+ | `currency_rates(...)` | Currency exchange rates (ECB) | 1 | `dict` |
103
+ | `dns_lookup(...)` | DNS record lookup | 1 | `dict` |
104
+ | `holidays_lookup(...)` | Public holidays lookup | 1 | `dict` |
105
+ | `html_to_image(...)` | HTML to image | 3 | `bytes` (image/png, image/jpeg, image/webp) |
106
+ | `html_to_pdf(...)` | HTML to PDF | 3 | `bytes` (application/pdf) |
107
+ | `image_convert(...)` | Image converter | 1 | `bytes` (image/png, image/jpeg, image/webp, image/gif, image/bmp, image/tiff, image/x-icon) |
108
+ | `ip_lookup(...)` | IP address lookup | 1 | `dict` |
109
+ | `iso_codes(...)` | ISO code lookup | 1 | `dict` |
110
+ | `json_schema_validate(...)` | JSON Schema validator | 1 | `dict` |
111
+ | `json_yaml_convert(...)` | JSON and YAML converter | 1 | `bytes` (application/json, application/yaml) |
112
+ | `kdp_preflight(...)` | KDP paperback file checker | 5 | `dict` |
113
+ | `kdp_puzzle_book(...)` | KDP puzzle book maker | 500 | `bytes` (application/zip) |
114
+ | `kdp_report(...)` | KDP check report lookup | free tier only | `dict` |
115
+ | `kdp_spine_calc(...)` | KDP cover size and spine width calculator | 1 | `dict` |
116
+ | `markdown_render(...)` | Markdown renderer | 1 | `bytes` (text/html, application/pdf) |
117
+ | `pdf_info(...)` | PDF info reader | 1 | `dict` |
118
+ | `pdf_merge(...)` | PDF merger | 1 | `bytes` (application/pdf) |
119
+ | `pdf_split(...)` | PDF splitter | 1 | `bytes` (application/pdf, application/zip) |
120
+ | `pdf_text(...)` | PDF text extractor | 1 | `dict` |
121
+ | `qr_code(...)` | QR code generator | 1 | `bytes` (image/png, image/svg+xml) |
122
+ | `rdap_lookup(...)` | RDAP registration lookup | 1 | `dict` |
123
+ | `screenshot(...)` | Website screenshot | free tier only | `bytes` (image/png, image/jpeg, image/webp) |
124
+ | `svg_to_png(...)` | SVG to PNG renderer | 1 | `bytes` (image/png) |
125
+ | `tabular_convert(...)` | CSV, TSV, Excel and JSON converter | 1 | `bytes` (text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json) |
126
+ | `timezone_convert(...)` | Time zone converter | 1 | `dict` |
127
+ <!-- END GENERATED:tools -->
128
+
129
+ The same tools are available to agents over MCP at <https://data.voiddo.com/mcp> (streamable HTTP) and through the `voiddo-mcp`
130
+ stdio package; the API description is at <https://data.voiddo.com/openapi.json> and <https://data.voiddo.com/llms.txt>.
131
+
132
+ Support: data@voiddo.com. MIT licence.
@@ -0,0 +1,110 @@
1
+ # voiddo-utils
2
+
3
+ Python client for the **vøiddo utilities API** at <https://data.voiddo.com>: deterministic tools for PDF (merge, split, text, info),
4
+ images and SVG, QR codes, HTML to PDF or image, Markdown, CSV / Excel / JSON / YAML conversion, JSON Schema validation, and
5
+ DNS / RDAP / IP / currency / holiday / ISO-code / time-zone lookups. One thin class on top of `requests`; no other dependencies.
6
+
7
+ ## Install
8
+
9
+ The package is not on PyPI yet. Until it is, install the wheel the API serves (file names and checksums: <https://data.voiddo.com/sdk/>):
10
+
11
+ ```bash
12
+ pip install https://data.voiddo.com/sdk/voiddo_utils-1.1.3-py3-none-any.whl
13
+ ```
14
+
15
+ It is imported as `voiddo_utils`.
16
+
17
+ ## Use
18
+
19
+ ```python
20
+ from voiddo_utils import Client
21
+
22
+ client = Client() # free tier: 20 calls per day per IP. With a key: Client(api_key="vd_...") or env VOIDDO_API_KEY
23
+
24
+ png = client.call("qr_code", text="https://example.com") # bytes: tools that produce a file return bytes
25
+ open("qr.png", "wb").write(png)
26
+ country = client.call("iso_codes", type="country", query="IL") # dict: tools that produce JSON return a dict
27
+ svg = client.qr_code(text="https://example.com", format="svg") # every tool is also a typed, keyword-only method
28
+
29
+ # files go in as bytes, pathlib.Path, an open binary file, base64 / data: strings, or {"url": "https://..."}
30
+ from pathlib import Path
31
+ pages = client.pdf_text(file=Path("report.pdf"))
32
+ merged = client.pdf_merge(files=[Path("a.pdf"), Path("b.pdf")])
33
+
34
+ # inputs named like Python keywords get a trailing underscore: from_ is sent as "from"
35
+ yaml = client.json_yaml_convert(input='{"a": 1}', from_="json", to="yaml")
36
+
37
+ # run() returns the full Result: value, credits charged, balance, free calls left, metadata, request id
38
+ result = client.run("pdf_info", {"file": Path("report.pdf")})
39
+ print(result.data, result.credits_charged, result.balance, result.free_remaining)
40
+
41
+ client.wallet() # balance and recent ledger rows (needs a key)
42
+ client.usage(days=7) # calls and credits per day and tool (needs a key)
43
+ client.capabilities() # the tool catalogue exactly as the API serves it
44
+ client.create_key() # a new key, shown once, starting at 0 credits
45
+ ```
46
+
47
+ ## Money
48
+
49
+ * Without a key, 20 calls per day per client IP are free. After that, and whenever a key's balance is too low, the API answers
50
+ HTTP 402 and the client raises `VoiddoPaymentRequired`; its `checkout_url` leads to the credit packs and `packs` lists them.
51
+ * Credits are prepaid: **$5 = 500**, **$9 = 1,000**, **$29 = 4,000**.
52
+ * The table below lists each tool's base price. A few tools (PDF merge, split and text on long documents, XLSX output) charge
53
+ more for large jobs; `Result.credits_charged` is always the exact amount. A failed call is not charged credits (on the free tier
54
+ it still uses one of the 20 daily calls).
55
+ * `screenshot` is free-tier only and is not sold through credits.
56
+
57
+ ```python
58
+ from voiddo_utils import Client, VoiddoError, VoiddoPaymentRequired
59
+
60
+ try:
61
+ Client().call("qr_code", text="hello")
62
+ except VoiddoPaymentRequired as e:
63
+ print("buy credits:", e.checkout_url) # e.packs lists the packs
64
+ except VoiddoError as e:
65
+ print(e.status, e.message) # e.g. 400 invalid input at (root): 'query' is a required property
66
+ ```
67
+
68
+ ## Retries
69
+
70
+ Every call carries an `X-Request-Id`. With an API key the client re-sends after a connection error, HTTP 503 or a rate limit
71
+ (`max_retries`, default 2) and the API does not charge the same id twice (`Result.replayed`). Without a key a call is re-sent only
72
+ when the API says nothing ran (HTTP 503, rate limit), so a free-tier slot is never spent twice by accident.
73
+
74
+ ## Tools
75
+
76
+ <!-- BEGIN GENERATED:tools -->
77
+ | Method | Tool | Credits | Returns |
78
+ | --- | --- | --- | --- |
79
+ | `csv_profile(...)` | CSV and Excel data profiler | 1 | `dict` |
80
+ | `currency_rates(...)` | Currency exchange rates (ECB) | 1 | `dict` |
81
+ | `dns_lookup(...)` | DNS record lookup | 1 | `dict` |
82
+ | `holidays_lookup(...)` | Public holidays lookup | 1 | `dict` |
83
+ | `html_to_image(...)` | HTML to image | 3 | `bytes` (image/png, image/jpeg, image/webp) |
84
+ | `html_to_pdf(...)` | HTML to PDF | 3 | `bytes` (application/pdf) |
85
+ | `image_convert(...)` | Image converter | 1 | `bytes` (image/png, image/jpeg, image/webp, image/gif, image/bmp, image/tiff, image/x-icon) |
86
+ | `ip_lookup(...)` | IP address lookup | 1 | `dict` |
87
+ | `iso_codes(...)` | ISO code lookup | 1 | `dict` |
88
+ | `json_schema_validate(...)` | JSON Schema validator | 1 | `dict` |
89
+ | `json_yaml_convert(...)` | JSON and YAML converter | 1 | `bytes` (application/json, application/yaml) |
90
+ | `kdp_preflight(...)` | KDP paperback file checker | 5 | `dict` |
91
+ | `kdp_puzzle_book(...)` | KDP puzzle book maker | 500 | `bytes` (application/zip) |
92
+ | `kdp_report(...)` | KDP check report lookup | free tier only | `dict` |
93
+ | `kdp_spine_calc(...)` | KDP cover size and spine width calculator | 1 | `dict` |
94
+ | `markdown_render(...)` | Markdown renderer | 1 | `bytes` (text/html, application/pdf) |
95
+ | `pdf_info(...)` | PDF info reader | 1 | `dict` |
96
+ | `pdf_merge(...)` | PDF merger | 1 | `bytes` (application/pdf) |
97
+ | `pdf_split(...)` | PDF splitter | 1 | `bytes` (application/pdf, application/zip) |
98
+ | `pdf_text(...)` | PDF text extractor | 1 | `dict` |
99
+ | `qr_code(...)` | QR code generator | 1 | `bytes` (image/png, image/svg+xml) |
100
+ | `rdap_lookup(...)` | RDAP registration lookup | 1 | `dict` |
101
+ | `screenshot(...)` | Website screenshot | free tier only | `bytes` (image/png, image/jpeg, image/webp) |
102
+ | `svg_to_png(...)` | SVG to PNG renderer | 1 | `bytes` (image/png) |
103
+ | `tabular_convert(...)` | CSV, TSV, Excel and JSON converter | 1 | `bytes` (text/csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/json) |
104
+ | `timezone_convert(...)` | Time zone converter | 1 | `dict` |
105
+ <!-- END GENERATED:tools -->
106
+
107
+ The same tools are available to agents over MCP at <https://data.voiddo.com/mcp> (streamable HTTP) and through the `voiddo-mcp`
108
+ stdio package; the API description is at <https://data.voiddo.com/openapi.json> and <https://data.voiddo.com/llms.txt>.
109
+
110
+ Support: data@voiddo.com. MIT licence.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "voiddo-utils"
7
+ version = "1.1.3"
8
+ description = "Python client for the vøiddo utilities API (data.voiddo.com): PDF, image, QR, CSV/Excel, JSON/YAML conversion, HTML to PDF, DNS/RDAP and other lookups."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "voiddo studio", email = "data@voiddo.com" }]
14
+ keywords = ["pdf", "qr-code", "image-convert", "csv", "json-schema", "dns", "rdap", "api-client", "mcp"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Software Development :: Libraries",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = ["requests>=2.20"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://data.voiddo.com"
27
+ Documentation = "https://data.voiddo.com/llms.txt"
28
+ "OpenAPI" = "https://data.voiddo.com/openapi.json"
29
+
30
+ [tool.setuptools]
31
+ include-package-data = false
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["voiddo_utils*"]
35
+
36
+ [tool.setuptools.package-data]
37
+ voiddo_utils = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -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