calotype 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.
- calotype/__init__.py +56 -0
- calotype/_client.py +293 -0
- calotype/_version.py +1 -0
- calotype/errors.py +154 -0
- calotype/py.typed +0 -0
- calotype-0.1.0.dist-info/METADATA +154 -0
- calotype-0.1.0.dist-info/RECORD +9 -0
- calotype-0.1.0.dist-info/WHEEL +4 -0
- calotype-0.1.0.dist-info/licenses/LICENSE +21 -0
calotype/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Python client for Calotype, a hosted screenshot API (https://calotype.dev).
|
|
2
|
+
|
|
3
|
+
from calotype import Calotype
|
|
4
|
+
|
|
5
|
+
image = Calotype("cal_...").screenshot("https://example.com", format="webp")
|
|
6
|
+
|
|
7
|
+
Calotype and this client are built and run by Skewbald, an AI agent.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from ._client import (
|
|
11
|
+
DEFAULT_BASE_URL,
|
|
12
|
+
Calotype,
|
|
13
|
+
NewKey,
|
|
14
|
+
Request,
|
|
15
|
+
Response,
|
|
16
|
+
Screenshot,
|
|
17
|
+
Transport,
|
|
18
|
+
Usage,
|
|
19
|
+
)
|
|
20
|
+
from ._version import __version__
|
|
21
|
+
from .errors import (
|
|
22
|
+
APIConnectionError,
|
|
23
|
+
AuthenticationError,
|
|
24
|
+
BlockedTargetError,
|
|
25
|
+
CalotypeError,
|
|
26
|
+
CaptureFailedError,
|
|
27
|
+
InvalidRequestError,
|
|
28
|
+
PermissionDeniedError,
|
|
29
|
+
QuotaExceededError,
|
|
30
|
+
RateLimitError,
|
|
31
|
+
ServerBusyError,
|
|
32
|
+
ServerError,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"APIConnectionError",
|
|
37
|
+
"AuthenticationError",
|
|
38
|
+
"BlockedTargetError",
|
|
39
|
+
"Calotype",
|
|
40
|
+
"CalotypeError",
|
|
41
|
+
"CaptureFailedError",
|
|
42
|
+
"DEFAULT_BASE_URL",
|
|
43
|
+
"InvalidRequestError",
|
|
44
|
+
"NewKey",
|
|
45
|
+
"PermissionDeniedError",
|
|
46
|
+
"QuotaExceededError",
|
|
47
|
+
"RateLimitError",
|
|
48
|
+
"Request",
|
|
49
|
+
"Response",
|
|
50
|
+
"Screenshot",
|
|
51
|
+
"ServerBusyError",
|
|
52
|
+
"ServerError",
|
|
53
|
+
"Transport",
|
|
54
|
+
"Usage",
|
|
55
|
+
"__version__",
|
|
56
|
+
]
|
calotype/_client.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""The client: three calls over the Calotype HTTP API, with the standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import socket
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.request
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any, Callable, Literal, Mapping
|
|
12
|
+
from urllib.parse import urlsplit
|
|
13
|
+
|
|
14
|
+
from ._version import __version__
|
|
15
|
+
from .errors import APIConnectionError, AuthenticationError, CalotypeError, error_for
|
|
16
|
+
|
|
17
|
+
DEFAULT_BASE_URL = "https://calotype.dev"
|
|
18
|
+
USER_AGENT = f"calotype-python/{__version__}"
|
|
19
|
+
|
|
20
|
+
Format = Literal["png", "jpeg", "webp"]
|
|
21
|
+
WaitUntil = Literal["load", "domcontentloaded", "networkidle", "commit"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Request:
|
|
26
|
+
"""One HTTP request, as handed to the transport."""
|
|
27
|
+
|
|
28
|
+
method: str
|
|
29
|
+
url: str
|
|
30
|
+
headers: Mapping[str, str]
|
|
31
|
+
body: bytes | None
|
|
32
|
+
timeout: float
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Response:
|
|
37
|
+
"""One HTTP answer, as the transport returns it. Header names are lower case."""
|
|
38
|
+
|
|
39
|
+
status: int
|
|
40
|
+
headers: Mapping[str, str]
|
|
41
|
+
body: bytes
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
#: Sends a request and returns the answer, whatever its status. Raises
|
|
45
|
+
#: ``APIConnectionError`` when there is no answer. Pass your own to
|
|
46
|
+
#: ``Calotype(transport=...)`` to use another HTTP library, or a fake in tests.
|
|
47
|
+
Transport = Callable[[Request], Response]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def urllib_transport(request: Request) -> Response:
|
|
51
|
+
"""The default transport: ``urllib.request`` from the standard library."""
|
|
52
|
+
req = urllib.request.Request(request.url, data=request.body, method=request.method, headers=dict(request.headers))
|
|
53
|
+
try:
|
|
54
|
+
try:
|
|
55
|
+
with urllib.request.urlopen(req, timeout=request.timeout) as resp:
|
|
56
|
+
return Response(resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read())
|
|
57
|
+
except urllib.error.HTTPError as e: # an answer with an error status
|
|
58
|
+
try:
|
|
59
|
+
return Response(e.code, {k.lower(): v for k, v in e.headers.items()}, e.read())
|
|
60
|
+
finally:
|
|
61
|
+
e.close()
|
|
62
|
+
except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError, OSError) as e:
|
|
63
|
+
reason = getattr(e, "reason", e)
|
|
64
|
+
raise APIConnectionError(f"Could not reach the Calotype API ({type(reason).__name__}).") from e
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class Screenshot:
|
|
69
|
+
"""A captured page: the image and what the API said about it."""
|
|
70
|
+
|
|
71
|
+
image: bytes = field(repr=False)
|
|
72
|
+
content_type: str
|
|
73
|
+
#: Screenshots the key has used this month, and its monthly limit.
|
|
74
|
+
used: int | None
|
|
75
|
+
limit: int | None
|
|
76
|
+
#: The page's own HTTP status, when the API reported one.
|
|
77
|
+
target_status: int | None
|
|
78
|
+
#: True if the page passed the download limit and the image shows what had loaded by then.
|
|
79
|
+
truncated: bool
|
|
80
|
+
duration_ms: int | None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class NewKey:
|
|
85
|
+
"""A key from ``create_key``. ``key`` is shown this once; Calotype keeps only its hash."""
|
|
86
|
+
|
|
87
|
+
key: str = field(repr=False)
|
|
88
|
+
plan: str
|
|
89
|
+
monthly_quota: int
|
|
90
|
+
message: str = ""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class Usage:
|
|
95
|
+
"""A key's count for the current month."""
|
|
96
|
+
|
|
97
|
+
plan: str
|
|
98
|
+
month: str
|
|
99
|
+
used: int
|
|
100
|
+
limit: int
|
|
101
|
+
resets_at: str
|
|
102
|
+
#: Not secret: names this key to support without sending the key.
|
|
103
|
+
key_ref: str
|
|
104
|
+
#: The masked address quota notices go to, if the key has one.
|
|
105
|
+
email: str | None = None
|
|
106
|
+
notices: bool = False
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def remaining(self) -> int:
|
|
110
|
+
return max(0, self.limit - self.used)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _int(value: str | None) -> int | None:
|
|
114
|
+
try:
|
|
115
|
+
return int(value) # type: ignore[arg-type]
|
|
116
|
+
except (TypeError, ValueError):
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Calotype:
|
|
121
|
+
"""A client for the Calotype API.
|
|
122
|
+
|
|
123
|
+
``api_key`` defaults to the ``CALOTYPE_API_KEY`` environment variable.
|
|
124
|
+
``create_key`` needs no key. ``timeout`` is in seconds, per request.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(
|
|
128
|
+
self,
|
|
129
|
+
api_key: str | None = None,
|
|
130
|
+
*,
|
|
131
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
132
|
+
timeout: float = 90.0,
|
|
133
|
+
transport: Transport | None = None,
|
|
134
|
+
) -> None:
|
|
135
|
+
self.api_key = (api_key if api_key is not None else os.environ.get("CALOTYPE_API_KEY", "")).strip()
|
|
136
|
+
self.base_url = base_url.rstrip("/")
|
|
137
|
+
if urlsplit(self.base_url).scheme not in ("http", "https"):
|
|
138
|
+
raise ValueError("base_url must start with http:// or https://")
|
|
139
|
+
self.timeout = timeout
|
|
140
|
+
self._transport = transport or urllib_transport
|
|
141
|
+
|
|
142
|
+
def __repr__(self) -> str: # never the key
|
|
143
|
+
return f"Calotype(base_url={self.base_url!r}, api_key={'set' if self.api_key else 'not set'})"
|
|
144
|
+
|
|
145
|
+
# --- the three calls ------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
def screenshot(
|
|
148
|
+
self,
|
|
149
|
+
url: str,
|
|
150
|
+
*,
|
|
151
|
+
width: int | None = None,
|
|
152
|
+
height: int | None = None,
|
|
153
|
+
full_page: bool | None = None,
|
|
154
|
+
format: Format | None = None,
|
|
155
|
+
quality: int | None = None,
|
|
156
|
+
device_scale_factor: float | None = None,
|
|
157
|
+
delay_ms: int | None = None,
|
|
158
|
+
wait_until: WaitUntil | None = None,
|
|
159
|
+
block_ads: bool | None = None,
|
|
160
|
+
dark_mode: bool | None = None,
|
|
161
|
+
) -> bytes:
|
|
162
|
+
"""Capture ``url`` and return the image bytes.
|
|
163
|
+
|
|
164
|
+
Parameters left as ``None`` are not sent, so the API's defaults apply:
|
|
165
|
+
a 1280 by 800 PNG of the viewport. Reference: https://calotype.dev/docs
|
|
166
|
+
"""
|
|
167
|
+
return self.capture(
|
|
168
|
+
url,
|
|
169
|
+
width=width,
|
|
170
|
+
height=height,
|
|
171
|
+
full_page=full_page,
|
|
172
|
+
format=format,
|
|
173
|
+
quality=quality,
|
|
174
|
+
device_scale_factor=device_scale_factor,
|
|
175
|
+
delay_ms=delay_ms,
|
|
176
|
+
wait_until=wait_until,
|
|
177
|
+
block_ads=block_ads,
|
|
178
|
+
dark_mode=dark_mode,
|
|
179
|
+
).image
|
|
180
|
+
|
|
181
|
+
def capture(
|
|
182
|
+
self,
|
|
183
|
+
url: str,
|
|
184
|
+
*,
|
|
185
|
+
width: int | None = None,
|
|
186
|
+
height: int | None = None,
|
|
187
|
+
full_page: bool | None = None,
|
|
188
|
+
format: Format | None = None,
|
|
189
|
+
quality: int | None = None,
|
|
190
|
+
device_scale_factor: float | None = None,
|
|
191
|
+
delay_ms: int | None = None,
|
|
192
|
+
wait_until: WaitUntil | None = None,
|
|
193
|
+
block_ads: bool | None = None,
|
|
194
|
+
dark_mode: bool | None = None,
|
|
195
|
+
) -> Screenshot:
|
|
196
|
+
"""Like ``screenshot``, but also returns the usage count and the page's status."""
|
|
197
|
+
params = {
|
|
198
|
+
"url": url,
|
|
199
|
+
"width": width,
|
|
200
|
+
"height": height,
|
|
201
|
+
"full_page": full_page,
|
|
202
|
+
"format": format,
|
|
203
|
+
"quality": quality,
|
|
204
|
+
"device_scale_factor": device_scale_factor,
|
|
205
|
+
"delay_ms": delay_ms,
|
|
206
|
+
"wait_until": wait_until,
|
|
207
|
+
"block_ads": block_ads,
|
|
208
|
+
"dark_mode": dark_mode,
|
|
209
|
+
}
|
|
210
|
+
resp = self._send("POST", "/v1/screenshot", {k: v for k, v in params.items() if v is not None}, auth=True)
|
|
211
|
+
used, _, limit = resp.headers.get("x-calotype-usage", "").partition("/")
|
|
212
|
+
return Screenshot(
|
|
213
|
+
image=resp.body,
|
|
214
|
+
content_type=resp.headers.get("content-type", "").split(";")[0].strip(),
|
|
215
|
+
used=_int(used),
|
|
216
|
+
limit=_int(limit),
|
|
217
|
+
target_status=_int(resp.headers.get("x-calotype-target-status")),
|
|
218
|
+
truncated=bool(resp.headers.get("x-calotype-truncated")),
|
|
219
|
+
duration_ms=_int(resp.headers.get("x-calotype-duration-ms")),
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
def create_key(self, ref: str | None = "pypi", *, email: str | None = None) -> NewKey:
|
|
223
|
+
"""Create a free key. Needs no key and no account.
|
|
224
|
+
|
|
225
|
+
``ref`` is a short tag that tells Calotype where the key came from;
|
|
226
|
+
pass ``None`` to send none. ``email`` is optional and used only for
|
|
227
|
+
quota notices. The new key is returned, not stored on this client:
|
|
228
|
+
``Calotype(new.key)`` makes a client that uses it.
|
|
229
|
+
"""
|
|
230
|
+
body: dict[str, Any] = {}
|
|
231
|
+
if ref:
|
|
232
|
+
body["ref"] = ref
|
|
233
|
+
if email:
|
|
234
|
+
body["email"] = email
|
|
235
|
+
resp = self._send("POST", "/v1/keys", body, auth=False)
|
|
236
|
+
data = self._json(resp)
|
|
237
|
+
if not isinstance(data.get("key"), str):
|
|
238
|
+
raise CalotypeError("The API's answer held no key.", status=resp.status)
|
|
239
|
+
return NewKey(
|
|
240
|
+
key=data["key"],
|
|
241
|
+
plan=data.get("plan", ""),
|
|
242
|
+
monthly_quota=data.get("monthly_quota", 0),
|
|
243
|
+
message=data.get("message", ""),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
def usage(self) -> Usage:
|
|
247
|
+
"""This key's count for the current month."""
|
|
248
|
+
data = self._json(self._send("GET", "/v1/usage", None, auth=True))
|
|
249
|
+
return Usage(
|
|
250
|
+
plan=data.get("plan", ""),
|
|
251
|
+
month=data.get("month", ""),
|
|
252
|
+
used=data.get("used", 0),
|
|
253
|
+
limit=data.get("limit", 0),
|
|
254
|
+
resets_at=data.get("resets_at", ""),
|
|
255
|
+
key_ref=data.get("key_ref", ""),
|
|
256
|
+
email=data.get("email"),
|
|
257
|
+
notices=bool(data.get("notices", False)),
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# --- HTTP -----------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
def _send(self, method: str, path: str, body: Mapping[str, Any] | None, *, auth: bool) -> Response:
|
|
263
|
+
headers = {"User-Agent": USER_AGENT, "Accept": "*/*"}
|
|
264
|
+
if auth:
|
|
265
|
+
if not self.api_key:
|
|
266
|
+
raise AuthenticationError(
|
|
267
|
+
"No API key. Pass one to Calotype(...) or set CALOTYPE_API_KEY. "
|
|
268
|
+
"Calotype().create_key() makes a free one.",
|
|
269
|
+
code="missing_key",
|
|
270
|
+
)
|
|
271
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
272
|
+
data = None
|
|
273
|
+
if body is not None:
|
|
274
|
+
data = json.dumps(body).encode()
|
|
275
|
+
headers["Content-Type"] = "application/json"
|
|
276
|
+
resp = self._transport(Request(method, self.base_url + path, headers, data, self.timeout))
|
|
277
|
+
if not 200 <= resp.status < 300:
|
|
278
|
+
try:
|
|
279
|
+
error = json.loads(resp.body).get("error")
|
|
280
|
+
except Exception:
|
|
281
|
+
error = None
|
|
282
|
+
raise error_for(resp.status, error, resp.headers)
|
|
283
|
+
return resp
|
|
284
|
+
|
|
285
|
+
@staticmethod
|
|
286
|
+
def _json(resp: Response) -> dict[str, Any]:
|
|
287
|
+
try:
|
|
288
|
+
data = json.loads(resp.body)
|
|
289
|
+
except ValueError:
|
|
290
|
+
data = None
|
|
291
|
+
if not isinstance(data, dict):
|
|
292
|
+
raise CalotypeError("The API answered with something that is not a JSON object.", status=resp.status)
|
|
293
|
+
return data
|
calotype/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
calotype/errors.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Errors the client raises, one class per kind of API error code.
|
|
2
|
+
|
|
3
|
+
Every API error answers ``{"error": {"code": ..., "message": ...}}``. The code
|
|
4
|
+
is stable; ``error_for`` picks the class from it, then from the HTTP status.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, Mapping
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class CalotypeError(Exception):
|
|
13
|
+
"""Any error from the client. The base of every class below.
|
|
14
|
+
|
|
15
|
+
``code`` is the API's stable error code (``""`` when the answer had none),
|
|
16
|
+
``status`` the HTTP status (``None`` when there was no answer), and
|
|
17
|
+
``body`` the parsed ``error`` object with any extra fields.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
message: str,
|
|
23
|
+
*,
|
|
24
|
+
code: str = "",
|
|
25
|
+
status: int | None = None,
|
|
26
|
+
body: Mapping[str, Any] | None = None,
|
|
27
|
+
headers: Mapping[str, str] | None = None,
|
|
28
|
+
) -> None:
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.message = message
|
|
31
|
+
self.code = code
|
|
32
|
+
self.status = status
|
|
33
|
+
self.body: Mapping[str, Any] = body or {}
|
|
34
|
+
self.headers: Mapping[str, str] = headers or {}
|
|
35
|
+
|
|
36
|
+
def __str__(self) -> str:
|
|
37
|
+
return f"{self.code}: {self.message}" if self.code else self.message
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def retry_after(self) -> float | None:
|
|
41
|
+
"""Seconds the server asked the caller to wait, if it said."""
|
|
42
|
+
value = self.body.get("retry_after_s", self.headers.get("retry-after"))
|
|
43
|
+
try:
|
|
44
|
+
return float(value) # type: ignore[arg-type]
|
|
45
|
+
except (TypeError, ValueError):
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class APIConnectionError(CalotypeError):
|
|
50
|
+
"""The API could not be reached, or did not answer in time. Nothing was counted."""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class AuthenticationError(CalotypeError):
|
|
54
|
+
"""No key, or a key that is wrong or revoked (``missing_key``, ``invalid_key``)."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class PermissionDeniedError(CalotypeError):
|
|
58
|
+
"""The server refused the action (``plan_unavailable``, ``self_serve_disabled``)."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class InvalidRequestError(CalotypeError):
|
|
62
|
+
"""The request was not valid (``invalid_parameters``, ``invalid_url``,
|
|
63
|
+
``invalid_scheme``, ``invalid_json``, ``invalid_email``)."""
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def details(self) -> list[dict[str, str]]:
|
|
67
|
+
"""For ``invalid_parameters``: one ``{"field": ..., "message": ...}`` per bad field."""
|
|
68
|
+
details = self.body.get("details")
|
|
69
|
+
return list(details) if isinstance(details, list) else []
|
|
70
|
+
|
|
71
|
+
def __str__(self) -> str:
|
|
72
|
+
text = super().__str__()
|
|
73
|
+
if self.details:
|
|
74
|
+
text += " " + "; ".join(f"{d.get('field')}: {d.get('message')}" for d in self.details)
|
|
75
|
+
return text
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class BlockedTargetError(CalotypeError):
|
|
79
|
+
"""The address is private, local or otherwise not allowed (``blocked_target``)."""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class CaptureFailedError(CalotypeError):
|
|
83
|
+
"""The page could not be captured (``dns_error``, ``target_unreachable``,
|
|
84
|
+
``page_too_large``, ``timeout``). It was not counted against the quota."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class QuotaExceededError(CalotypeError):
|
|
88
|
+
"""The key has used its screenshots for the month (``quota_exceeded``)."""
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def plan(self) -> str | None:
|
|
92
|
+
return self.body.get("plan")
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def limit(self) -> int | None:
|
|
96
|
+
return self.body.get("limit")
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def used(self) -> int | None:
|
|
100
|
+
return self.body.get("used")
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def resets_at(self) -> str | None:
|
|
104
|
+
"""When the count resets, as an ISO 8601 UTC time."""
|
|
105
|
+
return self.body.get("resets_at")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class RateLimitError(CalotypeError):
|
|
109
|
+
"""Too many keys were created recently (``rate_limited``). See ``retry_after``."""
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ServerBusyError(CalotypeError):
|
|
113
|
+
"""All renderers are busy (``busy``). Retry after ``retry_after`` seconds."""
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ServerError(CalotypeError):
|
|
117
|
+
"""The service failed (``internal_error``, or any other 5xx answer)."""
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
_BY_CODE: dict[str, type[CalotypeError]] = {
|
|
121
|
+
"missing_key": AuthenticationError,
|
|
122
|
+
"invalid_key": AuthenticationError,
|
|
123
|
+
"plan_unavailable": PermissionDeniedError,
|
|
124
|
+
"self_serve_disabled": PermissionDeniedError,
|
|
125
|
+
"invalid_parameters": InvalidRequestError,
|
|
126
|
+
"invalid_url": InvalidRequestError,
|
|
127
|
+
"invalid_scheme": InvalidRequestError,
|
|
128
|
+
"invalid_json": InvalidRequestError,
|
|
129
|
+
"invalid_email": InvalidRequestError,
|
|
130
|
+
"blocked_target": BlockedTargetError,
|
|
131
|
+
"dns_error": CaptureFailedError,
|
|
132
|
+
"target_unreachable": CaptureFailedError,
|
|
133
|
+
"page_too_large": CaptureFailedError,
|
|
134
|
+
"timeout": CaptureFailedError,
|
|
135
|
+
"quota_exceeded": QuotaExceededError,
|
|
136
|
+
"rate_limited": RateLimitError,
|
|
137
|
+
"busy": ServerBusyError,
|
|
138
|
+
"internal_error": ServerError,
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
_BY_STATUS: dict[int, type[CalotypeError]] = {
|
|
142
|
+
400: InvalidRequestError,
|
|
143
|
+
401: AuthenticationError,
|
|
144
|
+
403: PermissionDeniedError,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def error_for(status: int, error: Mapping[str, Any] | None, headers: Mapping[str, str]) -> CalotypeError:
|
|
149
|
+
"""The exception for an answer that is not a success."""
|
|
150
|
+
error = error if isinstance(error, Mapping) else {}
|
|
151
|
+
code = error.get("code") if isinstance(error.get("code"), str) else ""
|
|
152
|
+
message = error.get("message") if isinstance(error.get("message"), str) else f"HTTP {status}"
|
|
153
|
+
cls = _BY_CODE.get(code) or _BY_STATUS.get(status) or (ServerError if status >= 500 else CalotypeError)
|
|
154
|
+
return cls(message, code=code, status=status, body=error, headers=headers)
|
calotype/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: calotype
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for Calotype, a hosted screenshot API: send a URL, get the page back as an image.
|
|
5
|
+
Project-URL: Homepage, https://calotype.dev
|
|
6
|
+
Project-URL: Documentation, https://calotype.dev/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/skewbald-labs/calotype
|
|
8
|
+
Project-URL: Issues, https://github.com/skewbald-labs/calotype/issues
|
|
9
|
+
Author-email: "Skewbald, an AI agent" <skewbald@agentmail.to>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-agent,calotype,screenshot,screenshot-api,website-screenshot
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
|
|
23
|
+
# calotype
|
|
24
|
+
|
|
25
|
+
Python client for [Calotype](https://calotype.dev), a hosted screenshot API: send a URL, get the page back as a PNG, JPEG or WebP.
|
|
26
|
+
|
|
27
|
+
Calotype and this client are built and run by **Skewbald, an AI agent**. It wrote this code, runs the service and answers support at skewbald@agentmail.to. A person backs the project; Dostal Technology LLC is the seller.
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
pip install calotype
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Python 3.9 or newer. No dependencies: the client uses the standard library.
|
|
34
|
+
|
|
35
|
+
## Use
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from calotype import Calotype
|
|
39
|
+
|
|
40
|
+
client = Calotype("cal_...") # or set CALOTYPE_API_KEY and call Calotype()
|
|
41
|
+
|
|
42
|
+
image = client.screenshot("https://example.com") # bytes: a 1280x800 PNG
|
|
43
|
+
open("example.png", "wb").write(image)
|
|
44
|
+
|
|
45
|
+
image = client.screenshot(
|
|
46
|
+
"https://calotype.dev/pricing",
|
|
47
|
+
format="webp",
|
|
48
|
+
full_page=True,
|
|
49
|
+
dark_mode=True,
|
|
50
|
+
block_ads=True,
|
|
51
|
+
)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### A free key
|
|
55
|
+
|
|
56
|
+
100 screenshots a month, with no account and no email. The key is shown once; Calotype stores only its hash.
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
new = Calotype().create_key() # sends {"ref": "pypi"}, a tag that says the key came from this package
|
|
60
|
+
print(new.plan, new.monthly_quota) # free 100
|
|
61
|
+
client = Calotype(new.key) # keep new.key somewhere safe
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
`create_key(ref=None)` sends no tag. `create_key(email="you@example.com")` adds an address for quota notices at 80% and 100%.
|
|
65
|
+
|
|
66
|
+
### Usage
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
usage = client.usage()
|
|
70
|
+
print(usage.used, usage.limit, usage.remaining, usage.resets_at)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### More than the bytes
|
|
74
|
+
|
|
75
|
+
`capture()` takes the same arguments as `screenshot()` and returns a `Screenshot`: `image`, `content_type`, `used` and `limit` (the key's count after this capture), `target_status` (the page's own HTTP status), `truncated` and `duration_ms`.
|
|
76
|
+
|
|
77
|
+
## Parameters
|
|
78
|
+
|
|
79
|
+
All optional and keyword-only. One left out is not sent, so the API's default applies. Full reference: [calotype.dev/docs](https://calotype.dev/docs).
|
|
80
|
+
|
|
81
|
+
| Parameter | Type | API default | Meaning |
|
|
82
|
+
|---|---|---|---|
|
|
83
|
+
| `width` | int, 100 to 3840 | 1280 | Viewport width in CSS pixels. |
|
|
84
|
+
| `height` | int, 100 to 2160 | 800 | Viewport height in CSS pixels. |
|
|
85
|
+
| `full_page` | bool | `False` | Capture the whole scrolling page (up to 20,000 px tall). |
|
|
86
|
+
| `format` | `"png"`, `"jpeg"`, `"webp"` | `"png"` | Image format. |
|
|
87
|
+
| `quality` | int, 1 to 100 | 80 | For jpeg and webp only. |
|
|
88
|
+
| `device_scale_factor` | float, 1 to 3 | 1 | Pixel density. |
|
|
89
|
+
| `delay_ms` | int, 0 to 10000 | 0 | Wait after the page loads. |
|
|
90
|
+
| `wait_until` | `"load"`, `"domcontentloaded"`, `"networkidle"`, `"commit"` | `"load"` | When the page counts as loaded. |
|
|
91
|
+
| `block_ads` | bool | `False` | Block requests to common ad and tracking domains. |
|
|
92
|
+
| `dark_mode` | bool | `False` | Ask the page for its dark colour scheme. |
|
|
93
|
+
|
|
94
|
+
## Errors
|
|
95
|
+
|
|
96
|
+
Every error is a `CalotypeError` with `.code` (the API's stable error code), `.status` (the HTTP status) and `.message`. Failed captures are not counted against the quota.
|
|
97
|
+
|
|
98
|
+
| Class | Codes | Meaning |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `AuthenticationError` | `missing_key`, `invalid_key` | No key, or one that is wrong or revoked. |
|
|
101
|
+
| `InvalidRequestError` | `invalid_parameters`, `invalid_url`, `invalid_scheme`, `invalid_json`, `invalid_email` | The request was not valid. `.details` lists the bad fields. |
|
|
102
|
+
| `BlockedTargetError` | `blocked_target` | The address is private, local or otherwise refused. |
|
|
103
|
+
| `CaptureFailedError` | `dns_error`, `target_unreachable`, `page_too_large`, `timeout` | The page could not be captured. |
|
|
104
|
+
| `QuotaExceededError` | `quota_exceeded` | The month's screenshots are used up. `.plan`, `.limit`, `.used`, `.resets_at`. |
|
|
105
|
+
| `RateLimitError` | `rate_limited` | Too many keys created recently. `.retry_after` seconds. |
|
|
106
|
+
| `ServerBusyError` | `busy` | All renderers are busy. `.retry_after` seconds. |
|
|
107
|
+
| `PermissionDeniedError` | `plan_unavailable`, `self_serve_disabled` | The server refused the action. |
|
|
108
|
+
| `ServerError` | `internal_error`, other 5xx | The service failed. |
|
|
109
|
+
| `APIConnectionError` | none | The API could not be reached or did not answer in time. |
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from calotype import BlockedTargetError, QuotaExceededError
|
|
113
|
+
|
|
114
|
+
try:
|
|
115
|
+
image = client.screenshot("http://localhost:3000")
|
|
116
|
+
except BlockedTargetError as e:
|
|
117
|
+
print(e) # blocked_target: ...
|
|
118
|
+
except QuotaExceededError as e:
|
|
119
|
+
print(e.resets_at)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Options
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
Calotype(api_key, base_url="https://calotype.dev", timeout=90.0, transport=None)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
- `base_url`: set it if you run your own Calotype.
|
|
129
|
+
- `timeout`: seconds per request.
|
|
130
|
+
- `transport`: a function `(calotype.Request) -> calotype.Response`, to use another HTTP library or a fake in tests. The default uses `urllib.request`, which honours the usual proxy environment variables.
|
|
131
|
+
|
|
132
|
+
The client is synchronous. In async code, run it in a thread: `await asyncio.to_thread(client.screenshot, url)`.
|
|
133
|
+
|
|
134
|
+
## What it sends
|
|
135
|
+
|
|
136
|
+
Only the calls you make: `POST /v1/screenshot`, `POST /v1/keys`, `GET /v1/usage`, each with `User-Agent: calotype-python/<version>`, and your key on the two that need it. Privacy notice: [calotype.dev/privacy](https://calotype.dev/privacy).
|
|
137
|
+
|
|
138
|
+
## MCP
|
|
139
|
+
|
|
140
|
+
This package has no MCP server. For agents, use the hosted one at `https://calotype.dev/mcp`, or the local `calotype-mcp` server for Node.js: [calotype.dev/agents](https://calotype.dev/agents).
|
|
141
|
+
|
|
142
|
+
## Develop
|
|
143
|
+
|
|
144
|
+
The source is in [`clients/python`](https://github.com/skewbald-labs/calotype/tree/main/clients/python) of the Calotype repository, next to the service itself. The service's own Python package is also named `calotype`, so run these from `clients/python`, never from the repository root:
|
|
145
|
+
|
|
146
|
+
```sh
|
|
147
|
+
uv run pytest # no network: the HTTP layer is faked
|
|
148
|
+
CALOTYPE_LIVE=1 uv run pytest # adds one keyless call to calotype.dev; creates no key
|
|
149
|
+
uv build
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## License
|
|
153
|
+
|
|
154
|
+
MIT. See `LICENSE`.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
calotype/__init__.py,sha256=ygG08A8NSSvA8HBbxp6nx54oxe5p1YBOEKO8mg_kKp0,1160
|
|
2
|
+
calotype/_client.py,sha256=4v5TjSMeeojmTYnjrM-tJ_bnGU6Fw6GmA4jglxvi8wI,10403
|
|
3
|
+
calotype/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
4
|
+
calotype/errors.py,sha256=k1wl_90VCwJ_b6jp4kuDKFVSGZ_2xSXsoIWih0qfFxQ,5331
|
|
5
|
+
calotype/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
calotype-0.1.0.dist-info/METADATA,sha256=MqimN1SlmWa9oyzAWBBgrHyae4jvKoq_qdiwaKm6zZY,6763
|
|
7
|
+
calotype-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
calotype-0.1.0.dist-info/licenses/LICENSE,sha256=ElKfjStKAKw-xeSVSty1oMMve9zYGhLcoreIn5TX5oM,1078
|
|
9
|
+
calotype-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dostal Technology LLC
|
|
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.
|