html-css-to-image 0.2.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.
@@ -0,0 +1,75 @@
1
+ """Official Python client for the HTML/CSS to Image API."""
2
+
3
+ from ._version import __version__
4
+ from .client import HtmlCssToImageClient
5
+ from .exceptions import UnexpectedResponseError
6
+ from .models import (
7
+ ApiErrorResponse,
8
+ BaseCreateImageRequest,
9
+ BatchCreateImageRequest,
10
+ ColorSchemeType,
11
+ CreateHtmlCssImageRequest,
12
+ CreateImageBatchResponse,
13
+ CreateImageBatchSuccessResponse,
14
+ CreateImageRequest,
15
+ CreateImageResponse,
16
+ CreateImageSuccessResponse,
17
+ CreateTemplatedImageRequest,
18
+ CreateUrlImageRequest,
19
+ DeleteImageResponse,
20
+ DeleteImageSuccessResponse,
21
+ ImageFormat,
22
+ MediaType,
23
+ PDFMargins,
24
+ PDFOptions,
25
+ PDFUnit,
26
+ PDFValueInput,
27
+ PDFValueWithUnits,
28
+ RenderImageAspectRatio,
29
+ RenderImageCrop,
30
+ RenderImageCropOrigin,
31
+ RenderImageCropPosition,
32
+ RenderImageCropSize,
33
+ RenderImageCropSpan,
34
+ RenderImageFormat,
35
+ RenderImageOptions,
36
+ RenderImageValueUnit,
37
+ ValidationError,
38
+ )
39
+
40
+ __all__ = [
41
+ "ApiErrorResponse",
42
+ "BaseCreateImageRequest",
43
+ "BatchCreateImageRequest",
44
+ "ColorSchemeType",
45
+ "CreateHtmlCssImageRequest",
46
+ "CreateImageBatchResponse",
47
+ "CreateImageBatchSuccessResponse",
48
+ "CreateImageRequest",
49
+ "CreateImageResponse",
50
+ "CreateImageSuccessResponse",
51
+ "CreateTemplatedImageRequest",
52
+ "CreateUrlImageRequest",
53
+ "DeleteImageResponse",
54
+ "DeleteImageSuccessResponse",
55
+ "HtmlCssToImageClient",
56
+ "ImageFormat",
57
+ "MediaType",
58
+ "PDFMargins",
59
+ "PDFOptions",
60
+ "PDFUnit",
61
+ "PDFValueInput",
62
+ "PDFValueWithUnits",
63
+ "RenderImageAspectRatio",
64
+ "RenderImageCrop",
65
+ "RenderImageCropOrigin",
66
+ "RenderImageCropPosition",
67
+ "RenderImageCropSize",
68
+ "RenderImageCropSpan",
69
+ "RenderImageFormat",
70
+ "RenderImageOptions",
71
+ "RenderImageValueUnit",
72
+ "UnexpectedResponseError",
73
+ "ValidationError",
74
+ "__version__",
75
+ ]
@@ -0,0 +1,198 @@
1
+ """Internal mapping from public request models to API payloads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ from .models import (
9
+ BaseCreateImageRequest,
10
+ BatchCreateImageRequest,
11
+ CreateHtmlCssImageRequest,
12
+ CreateImageRequest,
13
+ CreateTemplatedImageRequest,
14
+ CreateUrlImageRequest,
15
+ PDFOptions,
16
+ PDFValueInput,
17
+ PDFValueWithUnits,
18
+ )
19
+
20
+
21
+ class RequestMapper:
22
+ """Serialize typed request models for HCTI API operations."""
23
+
24
+ @classmethod
25
+ def map_request(
26
+ cls,
27
+ request: CreateImageRequest,
28
+ *,
29
+ in_batch: bool,
30
+ ) -> dict[str, Any]:
31
+ if isinstance(request, CreateHtmlCssImageRequest):
32
+ return cls._map_html_request(request, in_batch=in_batch)
33
+ if isinstance(request, CreateUrlImageRequest):
34
+ return cls._map_url_request(request, in_batch=in_batch)
35
+ if isinstance(request, CreateTemplatedImageRequest):
36
+ if in_batch:
37
+ raise TypeError("Template requests cannot be used in a batch")
38
+ return cls.without_none(
39
+ {
40
+ "template_id": request.template_id,
41
+ "template_version": request.template_version,
42
+ "template_values": dict(request.template_values),
43
+ "format": request.format,
44
+ }
45
+ )
46
+ raise TypeError(f"Unsupported request type: {type(request).__name__}")
47
+
48
+ @classmethod
49
+ def map_batch_request(
50
+ cls,
51
+ request: BatchCreateImageRequest,
52
+ ) -> dict[str, Any]:
53
+ if not isinstance(
54
+ request,
55
+ (CreateHtmlCssImageRequest, CreateUrlImageRequest),
56
+ ):
57
+ raise TypeError("Batch requests must contain HTML/CSS or URL requests")
58
+ return cls.map_request(request, in_batch=True)
59
+
60
+ @classmethod
61
+ def common_payload(
62
+ cls,
63
+ request: BaseCreateImageRequest,
64
+ *,
65
+ include_dedupe: bool = True,
66
+ ) -> dict[str, Any]:
67
+ """Map fields shared by POST and signed-URL operations."""
68
+
69
+ return cls.without_none(
70
+ {
71
+ "format": request.format,
72
+ "selector": request.selector,
73
+ "device_scale": request.device_scale,
74
+ "viewport_height": request.viewport_height,
75
+ "viewport_width": request.viewport_width,
76
+ "max_wait_ms": request.max_wait_ms,
77
+ "ms_delay": request.ms_delay,
78
+ "render_when_ready": request.render_when_ready,
79
+ "max_render_once": request.max_render_once,
80
+ "disable_twemoji": request.disable_twemoji,
81
+ "color_scheme": request.color_scheme,
82
+ "timezone": request.timezone,
83
+ "viewport_mobile": request.viewport_mobile,
84
+ "viewport_touch": request.viewport_touch,
85
+ "viewport_landscape": request.viewport_landscape,
86
+ "media_type": request.media_type,
87
+ "proxy_id": request.proxy_id,
88
+ "jumbo_max_width": request.jumbo_max_width,
89
+ "jumbo_max_height": request.jumbo_max_height,
90
+ "dedupe_duration_s": (
91
+ request.dedupe_duration_s if include_dedupe else None
92
+ ),
93
+ "storage_destination_id": request.storage_destination_id,
94
+ "transparent_background": request.transparent_background,
95
+ "pdf_options": cls._map_pdf_options(request.pdf_options),
96
+ }
97
+ )
98
+
99
+ @staticmethod
100
+ def without_none(values: Mapping[str, Any]) -> dict[str, Any]:
101
+ """Remove fields whose values are ``None`` while preserving ``False``."""
102
+
103
+ return {key: value for key, value in values.items() if value is not None}
104
+
105
+ @classmethod
106
+ def _map_html_request(
107
+ cls,
108
+ request: CreateHtmlCssImageRequest,
109
+ *,
110
+ in_batch: bool,
111
+ ) -> dict[str, Any]:
112
+ payload = cls.common_payload(request, include_dedupe=not in_batch)
113
+ payload["html"] = request.html or None if in_batch else request.html
114
+ payload["css"] = request.css
115
+
116
+ if request.google_fonts:
117
+ fonts: list[str] = []
118
+ for font in request.google_fonts:
119
+ processed = font.strip().replace(" ", "+")
120
+ if processed and processed not in fonts:
121
+ fonts.append(processed)
122
+ if fonts:
123
+ payload["google_fonts"] = "|".join(fonts)
124
+
125
+ return cls.without_none(payload)
126
+
127
+ @classmethod
128
+ def _map_url_request(
129
+ cls,
130
+ request: CreateUrlImageRequest,
131
+ *,
132
+ in_batch: bool,
133
+ ) -> dict[str, Any]:
134
+ payload = cls.common_payload(request, include_dedupe=not in_batch)
135
+ payload.update(
136
+ {
137
+ "url": request.url or None if in_batch else request.url,
138
+ "css": request.css,
139
+ "headers": (
140
+ dict(request.headers) if request.headers is not None else None
141
+ ),
142
+ "additional_header_origins": (
143
+ list(request.additional_header_origins)
144
+ if request.additional_header_origins is not None
145
+ else None
146
+ ),
147
+ "include_headers_on_subrequests": (
148
+ request.include_headers_on_subrequests
149
+ ),
150
+ "identify_as_hcti": request.identify_as_hcti,
151
+ "full_screen": request.full_screen,
152
+ "block_consent_banners": request.block_consent_banners,
153
+ }
154
+ )
155
+ return cls.without_none(payload)
156
+
157
+ @classmethod
158
+ def _map_pdf_options(
159
+ cls,
160
+ options: PDFOptions | None,
161
+ ) -> dict[str, Any] | None:
162
+ if options is None:
163
+ return None
164
+
165
+ payload: dict[str, Any] = {
166
+ "print_background": options.print_background,
167
+ "scale": options.scale,
168
+ "page_height": (
169
+ cls._pdf_value_to_string(options.page_height)
170
+ if options.page_height is not None
171
+ else None
172
+ ),
173
+ "page_width": (
174
+ cls._pdf_value_to_string(options.page_width)
175
+ if options.page_width is not None
176
+ else None
177
+ ),
178
+ }
179
+ if options.margins is not None:
180
+ payload["margins"] = [
181
+ cls._pdf_value_to_string(options.margins.top),
182
+ cls._pdf_value_to_string(options.margins.right),
183
+ cls._pdf_value_to_string(options.margins.bottom),
184
+ cls._pdf_value_to_string(options.margins.left),
185
+ ]
186
+ return cls.without_none(payload)
187
+
188
+ @classmethod
189
+ def _pdf_value_to_string(cls, value: PDFValueInput) -> str:
190
+ if isinstance(value, PDFValueWithUnits):
191
+ return f"{cls._number_to_string(value.value)}{value.unit}"
192
+ return f"{cls._number_to_string(value)}px"
193
+
194
+ @staticmethod
195
+ def _number_to_string(value: int | float) -> str:
196
+ if isinstance(value, float) and value.is_integer():
197
+ return str(int(value))
198
+ return str(value)
@@ -0,0 +1,168 @@
1
+ """Internal mapping from HTTP responses to public response models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ from .exceptions import UnexpectedResponseError
11
+ from .models import (
12
+ ApiErrorResponse,
13
+ CreateImageBatchResponse,
14
+ CreateImageBatchSuccessResponse,
15
+ CreateImageResponse,
16
+ CreateImageSuccessResponse,
17
+ DeleteImageResponse,
18
+ DeleteImageSuccessResponse,
19
+ ValidationError,
20
+ )
21
+
22
+
23
+ class ResponseMapper:
24
+ """Create typed response models and reject malformed successful bodies."""
25
+
26
+ @classmethod
27
+ def map_image_response(cls, response: httpx.Response) -> CreateImageResponse:
28
+ """Map one image-creation response."""
29
+
30
+ if not response.is_success:
31
+ return cls._map_error_response(response)
32
+ data = cls._decode_success_object(response, "image creation")
33
+ return cls._map_success_image(data, response, "image creation response")
34
+
35
+ @classmethod
36
+ def map_batch_response(
37
+ cls,
38
+ response: httpx.Response,
39
+ ) -> CreateImageBatchResponse:
40
+ """Map a batch image-creation response."""
41
+
42
+ if not response.is_success:
43
+ return cls._map_error_response(response)
44
+ data = cls._decode_success_object(response, "batch image creation")
45
+ raw_images = data.get("images")
46
+ if not isinstance(raw_images, list):
47
+ raise cls._unexpected(
48
+ response,
49
+ "Batch image creation response must contain an images array.",
50
+ )
51
+
52
+ images = tuple(
53
+ cls._map_batch_image(item, index, response)
54
+ for index, item in enumerate(raw_images)
55
+ )
56
+ return CreateImageBatchSuccessResponse(images=images)
57
+
58
+ @classmethod
59
+ def map_delete_response(cls, response: httpx.Response) -> DeleteImageResponse:
60
+ """Map an image-deletion response."""
61
+
62
+ if response.is_success:
63
+ return DeleteImageSuccessResponse()
64
+ return cls._map_error_response(response)
65
+
66
+ @classmethod
67
+ def _map_batch_image(
68
+ cls,
69
+ item: object,
70
+ index: int,
71
+ response: httpx.Response,
72
+ ) -> CreateImageSuccessResponse:
73
+ if not isinstance(item, dict):
74
+ raise cls._unexpected(
75
+ response,
76
+ f"Batch image result at index {index} must be an object.",
77
+ )
78
+ return cls._map_success_image(
79
+ item,
80
+ response,
81
+ f"batch image result at index {index}",
82
+ )
83
+
84
+ @classmethod
85
+ def _map_success_image(
86
+ cls,
87
+ data: Mapping[str, Any],
88
+ response: httpx.Response,
89
+ description: str,
90
+ ) -> CreateImageSuccessResponse:
91
+ image_id = data.get("id")
92
+ url = data.get("url")
93
+ if not isinstance(image_id, str) or not image_id:
94
+ raise cls._unexpected(
95
+ response,
96
+ f"The {description} must contain a non-empty string id.",
97
+ )
98
+ if not isinstance(url, str) or not url:
99
+ raise cls._unexpected(
100
+ response,
101
+ f"The {description} must contain a non-empty string url.",
102
+ )
103
+ return CreateImageSuccessResponse(id=image_id, url=url)
104
+
105
+ @classmethod
106
+ def _decode_success_object(
107
+ cls,
108
+ response: httpx.Response,
109
+ operation: str,
110
+ ) -> dict[str, Any]:
111
+ try:
112
+ decoded = response.json()
113
+ except ValueError as error:
114
+ raise cls._unexpected(
115
+ response,
116
+ f"Successful {operation} response was not valid JSON.",
117
+ ) from error
118
+ if not isinstance(decoded, dict):
119
+ raise cls._unexpected(
120
+ response,
121
+ f"Successful {operation} response must be a JSON object.",
122
+ )
123
+ return decoded
124
+
125
+ @classmethod
126
+ def _map_error_response(cls, response: httpx.Response) -> ApiErrorResponse:
127
+ data = cls._decode_error_object(response)
128
+ raw_validation_errors = data.get("validation_errors")
129
+ validation_errors: tuple[ValidationError, ...] | None = None
130
+ if isinstance(raw_validation_errors, list):
131
+ validation_errors = tuple(
132
+ ValidationError(
133
+ path=str(item.get("path", "")),
134
+ message=str(item.get("message", "")),
135
+ )
136
+ for item in raw_validation_errors
137
+ if isinstance(item, dict)
138
+ )
139
+ message = data.get("message")
140
+ return ApiErrorResponse(
141
+ status_code=response.status_code,
142
+ error=str(data.get("error", "Unknown error")),
143
+ message=str(message) if message is not None else None,
144
+ validation_errors=validation_errors,
145
+ )
146
+
147
+ @staticmethod
148
+ def _decode_error_object(response: httpx.Response) -> dict[str, Any]:
149
+ try:
150
+ decoded = response.json()
151
+ if isinstance(decoded, dict):
152
+ return decoded
153
+ except ValueError:
154
+ pass
155
+ return {
156
+ "error": "Internal Server Error",
157
+ "message": (
158
+ "The server returned an unexpected response "
159
+ f"(Status: {response.status_code})."
160
+ ),
161
+ }
162
+
163
+ @staticmethod
164
+ def _unexpected(
165
+ response: httpx.Response,
166
+ message: str,
167
+ ) -> UnexpectedResponseError:
168
+ return UnexpectedResponseError(message, status_code=response.status_code)
@@ -0,0 +1,71 @@
1
+ """Internal HTTP transport for HCTI API requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import re
7
+ from collections.abc import Mapping
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from ._version import __version__
13
+
14
+ _USER_AGENT = f"HCTIPython/{re.sub(r'[^A-Za-z0-9._+-]', '-', __version__)}"
15
+
16
+
17
+ class HttpTransport:
18
+ """Send authenticated requests through an owned or injected HTTPX client."""
19
+
20
+ def __init__(
21
+ self,
22
+ api_id: str,
23
+ api_key: str,
24
+ *,
25
+ http_client: httpx.Client | None,
26
+ base_url: str,
27
+ ) -> None:
28
+ self._base_url = base_url
29
+ self._owns_http_client = http_client is None
30
+ self._http_client = http_client or httpx.Client(timeout=30.0)
31
+ credentials = base64.b64encode(f"{api_id}:{api_key}".encode()).decode()
32
+ self._auth_header = f"Basic {credentials}"
33
+
34
+ def post(self, path: str, payload: Mapping[str, Any]) -> httpx.Response:
35
+ """Send a JSON POST request."""
36
+
37
+ return self._http_client.post(
38
+ f"{self._base_url}{path}",
39
+ headers={
40
+ "Authorization": self._auth_header,
41
+ "Content-Type": "application/json",
42
+ "User-Agent": _USER_AGENT,
43
+ },
44
+ json=payload,
45
+ )
46
+
47
+ def delete(
48
+ self,
49
+ path: str,
50
+ payload: Mapping[str, Any] | None = None,
51
+ ) -> httpx.Response:
52
+ """Send a DELETE request with an optional JSON body."""
53
+
54
+ headers = {
55
+ "Authorization": self._auth_header,
56
+ "User-Agent": _USER_AGENT,
57
+ }
58
+ if payload is not None:
59
+ headers["Content-Type"] = "application/json"
60
+ return self._http_client.request(
61
+ "DELETE",
62
+ f"{self._base_url}{path}",
63
+ headers=headers,
64
+ json=payload,
65
+ )
66
+
67
+ def close(self) -> None:
68
+ """Close only an HTTPX client created by this transport."""
69
+
70
+ if self._owns_http_client:
71
+ self._http_client.close()