imejis 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.
imejis/__init__.py ADDED
@@ -0,0 +1,62 @@
1
+ """Official imejis SDK for Python: list designs, read their fields and render images."""
2
+
3
+ from ._client import AsyncDesigns, AsyncImejis, Designs, Imejis
4
+ from ._core import BULK_MAX_ITEMS, EXPIRES_IN_MAX_MINUTES, RENDER_FORMATS
5
+ from ._errors import (
6
+ AuthenticationError,
7
+ BadRequestError,
8
+ ConnectionError,
9
+ GoneError,
10
+ ImejisConfigError,
11
+ ImejisError,
12
+ InternalServerError,
13
+ NotFoundError,
14
+ PermissionDeniedError,
15
+ RateLimitError,
16
+ TimeoutError,
17
+ )
18
+ from ._types import (
19
+ BulkItem,
20
+ BulkResponse,
21
+ BulkResult,
22
+ DesignConfig,
23
+ DesignPage,
24
+ DesignSummary,
25
+ FieldSpec,
26
+ RenderedImage,
27
+ SizeVariation,
28
+ StoredRender,
29
+ )
30
+ from ._version import __version__
31
+
32
+ __all__ = [
33
+ "AsyncDesigns",
34
+ "AsyncImejis",
35
+ "AuthenticationError",
36
+ "BULK_MAX_ITEMS",
37
+ "BadRequestError",
38
+ "BulkItem",
39
+ "BulkResponse",
40
+ "BulkResult",
41
+ "ConnectionError",
42
+ "Designs",
43
+ "DesignConfig",
44
+ "DesignPage",
45
+ "DesignSummary",
46
+ "EXPIRES_IN_MAX_MINUTES",
47
+ "FieldSpec",
48
+ "GoneError",
49
+ "Imejis",
50
+ "ImejisConfigError",
51
+ "ImejisError",
52
+ "InternalServerError",
53
+ "NotFoundError",
54
+ "PermissionDeniedError",
55
+ "RENDER_FORMATS",
56
+ "RateLimitError",
57
+ "RenderedImage",
58
+ "SizeVariation",
59
+ "StoredRender",
60
+ "TimeoutError",
61
+ "__version__",
62
+ ]
imejis/_base.py ADDED
@@ -0,0 +1,459 @@
1
+ """The client's logic, written once.
2
+
3
+ Each operation is a generator that yields :class:`_Request` objects and gets a
4
+ :class:`_Response` back for each, then returns its result. The sync and async
5
+ clients only differ in how they send a request (see ``_client.py``), so every
6
+ rule (render-key lookup, render-code resolution, validation, parsing) lives
7
+ here, once.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import random
15
+ import re
16
+ from dataclasses import dataclass, field
17
+ from email.utils import parsedate_to_datetime
18
+ from time import time
19
+ from typing import Any, Dict, Generator, List, Mapping, Optional, Sequence, TypeVar, Union
20
+ from urllib.parse import unquote
21
+
22
+ from . import _core as core
23
+ from ._errors import ImejisConfigError, ImejisError, error_from_response
24
+ from ._types import (
25
+ BulkItem,
26
+ BulkResponse,
27
+ BulkResult,
28
+ DesignConfig,
29
+ DesignPage,
30
+ DesignSummary,
31
+ Overrides,
32
+ RenderedImage,
33
+ StoredRender,
34
+ )
35
+ from ._version import __version__
36
+
37
+ DEFAULT_RENDER_KEY_NAME = "imejis SDK"
38
+ DEFAULT_TIMEOUT = 60.0
39
+ DEFAULT_MAX_RETRIES = 2
40
+ _MONGO_ID = re.compile(r"^[a-f0-9]{24}$", re.I)
41
+ _RETRY_STATUSES = {408, 409, 500, 502, 503, 504}
42
+
43
+
44
+ @dataclass
45
+ class _Request:
46
+ method: str
47
+ url: str
48
+ expect: str = "json" # or "bytes"
49
+ headers: Dict[str, str] = field(default_factory=dict)
50
+ params: Dict[str, Any] = field(default_factory=dict)
51
+ json: Any = None
52
+
53
+
54
+ @dataclass
55
+ class _Response:
56
+ status: int
57
+ headers: Mapping[str, str]
58
+ data: Any
59
+
60
+
61
+ T = TypeVar("T")
62
+ Op = Generator[_Request, _Response, T]
63
+
64
+
65
+ def backoff_seconds(attempt: int) -> float:
66
+ """~0.5s, 1s, 2s ... capped at 8s, with jitter."""
67
+ base: float = min(8.0, 0.5 * 2.0 ** (attempt - 1))
68
+ return base * (0.75 + random.random() * 0.5)
69
+
70
+
71
+ def retry_after_seconds(headers: Mapping[str, str]) -> Optional[float]:
72
+ value = headers.get("retry-after")
73
+ if not value:
74
+ return None
75
+ try:
76
+ seconds = float(value)
77
+ except ValueError:
78
+ try:
79
+ seconds = parsedate_to_datetime(value).timestamp() - time()
80
+ except (TypeError, ValueError):
81
+ return None
82
+ return float(min(max(seconds, 0.0), 60.0))
83
+
84
+
85
+ def should_retry(status: int, headers: Mapping[str, str]) -> bool:
86
+ """A 429 retries only with Retry-After: a spent render quota is a 429 too."""
87
+ if status in _RETRY_STATUSES:
88
+ return True
89
+ return status == 429 and retry_after_seconds(headers) is not None
90
+
91
+
92
+ def parse_body(content: bytes) -> Any:
93
+ if not content:
94
+ return None
95
+ try:
96
+ return json.loads(content)
97
+ except ValueError:
98
+ return content.decode("utf-8", "replace")
99
+
100
+
101
+ def finish(req: _Request, status: int, headers: Mapping[str, str], content: bytes) -> _Response:
102
+ """Turn a raw response into a :class:`_Response`, or raise the right error."""
103
+ request_id = headers.get("x-request-id")
104
+ if status >= 400:
105
+ raise error_from_response(status, parse_body(content), request_id)
106
+ if req.expect == "bytes":
107
+ return _Response(status, headers, content)
108
+ body = parse_body(content)
109
+ soft = core.soft_failure_message(body)
110
+ if soft:
111
+ raise ImejisError(soft, status=status, body=body, request_id=request_id)
112
+ return _Response(status, headers, body)
113
+
114
+
115
+ def _decode_warnings(header: Optional[str]) -> List[str]:
116
+ if not header:
117
+ return []
118
+ try:
119
+ parsed = json.loads(unquote(header))
120
+ except ValueError:
121
+ return []
122
+ return [w for w in parsed if isinstance(w, str)] if isinstance(parsed, list) else []
123
+
124
+
125
+ def _check(fmt: Optional[str] = None, quality: Optional[int] = None, expires_in: Optional[int] = None) -> None:
126
+ if fmt is not None and fmt not in core.RENDER_FORMATS:
127
+ raise ImejisConfigError(f'format must be one of {", ".join(core.RENDER_FORMATS)}; got "{fmt}".')
128
+ if quality is not None and (
129
+ isinstance(quality, bool) or not isinstance(quality, int) or not core.QUALITY_MIN <= quality <= core.QUALITY_MAX
130
+ ):
131
+ raise ImejisConfigError(
132
+ f"quality must be a whole number from {core.QUALITY_MIN} to {core.QUALITY_MAX}; got {quality!r}."
133
+ )
134
+ if expires_in is not None and (
135
+ isinstance(expires_in, bool)
136
+ or not isinstance(expires_in, int)
137
+ or not 1 <= expires_in <= core.EXPIRES_IN_MAX_MINUTES
138
+ ):
139
+ raise ImejisConfigError(
140
+ f"expires_in must be whole minutes from 1 to {core.EXPIRES_IN_MAX_MINUTES}; got {expires_in!r}."
141
+ )
142
+
143
+
144
+ def _clean_overrides(overrides: Optional[Overrides]) -> Dict[str, Any]:
145
+ out: Dict[str, Any] = {}
146
+ for key, value in (overrides or {}).items():
147
+ if not key or value is None:
148
+ continue
149
+ if key in core.RESERVED_RENDER_KEYS:
150
+ raise ImejisConfigError(
151
+ f'"{key}" is a render option, not a layer override. Pass it as a keyword argument instead.'
152
+ )
153
+ out[key] = value
154
+ return out
155
+
156
+
157
+ def _drop_none(d: Dict[str, Any]) -> Dict[str, Any]:
158
+ return {k: v for k, v in d.items() if v is not None}
159
+
160
+
161
+ class BaseClient:
162
+ def __init__(
163
+ self,
164
+ *,
165
+ api_key: Optional[str] = None,
166
+ access_token: Optional[str] = None,
167
+ render_key_name: str = DEFAULT_RENDER_KEY_NAME,
168
+ base_url: str = core.DEFAULT_API_BASE_URL,
169
+ render_base_url: str = core.DEFAULT_RENDER_BASE_URL,
170
+ timeout: float = DEFAULT_TIMEOUT,
171
+ max_retries: int = DEFAULT_MAX_RETRIES,
172
+ ) -> None:
173
+ self._api_key = api_key or os.environ.get("IMEJIS_API_KEY") or None
174
+ self._access_token = access_token or os.environ.get("IMEJIS_ACCESS_TOKEN") or None
175
+ if not self._api_key and not self._access_token:
176
+ raise ImejisConfigError(
177
+ "Pass api_key (a render key from imejis Settings > API keys) or an OAuth "
178
+ "access_token, or set IMEJIS_API_KEY."
179
+ )
180
+ self._render_key_name = render_key_name
181
+ self._api = core.ApiEndpoints(base_url)
182
+ self._render = core.RenderEndpoints(render_base_url)
183
+ self._timeout = timeout
184
+ self._max_retries = max(0, int(max_retries))
185
+ self._user_agent = f"imejis-python/{__version__}"
186
+ self._render_key: Optional[str] = self._api_key
187
+ self._codes: Dict[str, str] = {}
188
+
189
+ # ── plumbing ─────────────────────────────────────────────────────────────
190
+
191
+ def _bearer(self) -> Dict[str, str]:
192
+ if not self._access_token:
193
+ raise ImejisConfigError(
194
+ "This call reads your imejis account, which needs an OAuth access_token. An API key only renders."
195
+ )
196
+ return {"authorization": f"Bearer {self._access_token}"}
197
+
198
+ def _api_get(self, url: str) -> Op[Any]:
199
+ resp = yield _Request("GET", url, headers=self._bearer())
200
+ return resp.data
201
+
202
+ def _op_render_key(self) -> Op[str]:
203
+ if self._render_key:
204
+ return self._render_key
205
+ listing = yield from self._api_get(f"{self._api.api_keys}?$limit=100")
206
+ docs = [d for d in (listing or {}).get("docs") or [] if isinstance(d, dict) and d.get("key")]
207
+ reuse: Optional[Dict[str, Any]] = next(
208
+ (d for d in docs if d.get("name") == self._render_key_name and d.get("active") is not False),
209
+ None,
210
+ ) or next((d for d in docs if d.get("active")), None)
211
+ if reuse:
212
+ key = str(reuse["key"])
213
+ else:
214
+ resp = yield _Request(
215
+ "POST", self._api.api_keys_create, headers=self._bearer(), json={"name": self._render_key_name}
216
+ )
217
+ created = resp.data.get("key") if isinstance(resp.data, dict) else None
218
+ if not isinstance(created, str) or not created:
219
+ raise ImejisError(
220
+ "imejis could not provide a render key for this account. "
221
+ "Create an API key in imejis settings and pass it as api_key."
222
+ )
223
+ key = created
224
+ self._render_key = key
225
+ return key
226
+
227
+ def _op_render_code(self, design: str) -> Op[str]:
228
+ if not design:
229
+ raise ImejisConfigError("A design render code or id is required.")
230
+ if not _MONGO_ID.match(design) or not self._access_token:
231
+ return design
232
+ if design in self._codes:
233
+ return self._codes[design]
234
+ config = yield from self._op_config(design)
235
+ self._codes[design] = config.render_code
236
+ return config.render_code
237
+
238
+ def _render_request(self, key: str, url: str, expect: str, params: Dict[str, Any], body: Any) -> _Request:
239
+ return _Request("POST", url, expect=expect, headers={"dma-api-key": key}, params=_drop_none(params), json=body)
240
+
241
+ # ── designs ──────────────────────────────────────────────────────────────
242
+
243
+ def _op_list(self, page: int = 1, limit: int = core.MAX_PAGE_SIZE) -> Op[DesignPage]:
244
+ body = yield from self._api_get(self._api.list_designs(page, limit))
245
+ return core.parse_design_page(body)
246
+
247
+ def _op_search(self, query: str, max_pages: int, limit: int) -> Op[List[DesignSummary]]:
248
+ wanted = query.strip().lower()
249
+ if not wanted:
250
+ return []
251
+ exact: List[DesignSummary] = []
252
+ partial: List[DesignSummary] = []
253
+ for page in range(1, max_pages + 1):
254
+ result = yield from self._op_list(page)
255
+ for d in result.designs:
256
+ name = d.name.lower()
257
+ if name == wanted:
258
+ exact.append(d)
259
+ elif wanted in name:
260
+ partial.append(d)
261
+ if len(exact) + len(partial) >= limit or not result.has_next_page:
262
+ break
263
+ return (exact + partial)[:limit]
264
+
265
+ def _op_config(self, design_id: str) -> Op[DesignConfig]:
266
+ if not design_id:
267
+ raise ImejisConfigError("design_id is required.")
268
+ body = yield from self._api_get(self._api.design_config(design_id))
269
+ render = body.get("render") if isinstance(body, dict) else None
270
+ render = render if isinstance(render, str) else None
271
+ return DesignConfig(
272
+ id=design_id,
273
+ render_code=core.render_code_from_url(render, design_id),
274
+ render_url=render,
275
+ fields=core.sort_fields_for_form(core.config_to_fields(body)),
276
+ sizes=core.config_to_variations(body),
277
+ )
278
+
279
+ def _op_profile(self) -> Op[Dict[str, Any]]:
280
+ body = yield from self._api_get(self._api.profile)
281
+ return body if isinstance(body, dict) else {}
282
+
283
+ # ── rendering ────────────────────────────────────────────────────────────
284
+
285
+ def _op_render(
286
+ self,
287
+ design: str,
288
+ overrides: Optional[Overrides],
289
+ fmt: Optional[str],
290
+ quality: Optional[int],
291
+ size: Optional[str],
292
+ ) -> Op[RenderedImage]:
293
+ _check(fmt, quality)
294
+ body = _clean_overrides(overrides)
295
+ code = yield from self._op_render_code(design)
296
+ key = yield from self._op_render_key()
297
+ resp = yield self._render_request(
298
+ key,
299
+ self._render.render(code),
300
+ "bytes",
301
+ {"delivery": "stream", "format": fmt, "quality": quality, "variation": size},
302
+ body,
303
+ )
304
+ content_type = (resp.headers.get("content-type") or core.mime_type_for(fmt)).split(";")[0].strip()
305
+ return RenderedImage(
306
+ data=resp.data,
307
+ content_type=content_type,
308
+ format=fmt or core.format_from_mime(content_type),
309
+ warnings=_decode_warnings(resp.headers.get("x-dma-warnings")),
310
+ )
311
+
312
+ def _op_render_stored(
313
+ self,
314
+ design: str,
315
+ overrides: Optional[Overrides],
316
+ delivery: str,
317
+ fmt: Optional[str],
318
+ quality: Optional[int],
319
+ size: Optional[str],
320
+ expires_in: Optional[int],
321
+ ) -> Op[StoredRender]:
322
+ _check(fmt, quality, expires_in)
323
+ body = _clean_overrides(overrides)
324
+ code = yield from self._op_render_code(design)
325
+ key = yield from self._op_render_key()
326
+ resp = yield self._render_request(
327
+ key,
328
+ self._render.render(code),
329
+ "json",
330
+ {
331
+ "delivery": delivery,
332
+ "format": fmt,
333
+ "quality": quality,
334
+ "variation": size,
335
+ "expiresIn": expires_in if delivery == "signed" else None,
336
+ },
337
+ body,
338
+ )
339
+ stored = core.parse_stored_image(resp.data)
340
+ if not stored:
341
+ raise ImejisError("imejis answered without an image URL.", body=resp.data)
342
+ return stored
343
+
344
+ def _op_all_sizes(
345
+ self,
346
+ design: str,
347
+ overrides: Optional[Overrides],
348
+ sizes: Optional[Sequence[str]],
349
+ delivery: str,
350
+ fmt: Optional[str],
351
+ quality: Optional[int],
352
+ expires_in: Optional[int],
353
+ ) -> Op[BulkResponse]:
354
+ _check(fmt, quality, expires_in)
355
+ body = _clean_overrides(overrides)
356
+ picked = [s for s in (sizes or []) if s]
357
+ variations: Union[List[str], str]
358
+ if picked:
359
+ code = yield from self._op_render_code(design)
360
+ variations = picked
361
+ elif self._access_token:
362
+ config = yield from self._op_config(design)
363
+ code = config.render_code
364
+ variations = [s.id for s in config.sizes] or ["master"]
365
+ else:
366
+ # The render host expands "all" to master plus each of the design's sizes.
367
+ code = yield from self._op_render_code(design)
368
+ variations = "all"
369
+ if isinstance(variations, list) and len(variations) > core.BULK_MAX_ITEMS:
370
+ raise ImejisConfigError(
371
+ f"Too many sizes: {len(variations)}. One call renders at most {core.BULK_MAX_ITEMS}; pass fewer sizes."
372
+ )
373
+ result = yield from self._op_bulk_post(
374
+ _drop_none(
375
+ {
376
+ "designId": code,
377
+ "variations": variations,
378
+ "overrides": body,
379
+ "delivery": delivery,
380
+ "format": fmt,
381
+ "quality": quality,
382
+ "expiresIn": expires_in if delivery == "signed" else None,
383
+ }
384
+ )
385
+ )
386
+ return result
387
+
388
+ def _op_bulk(
389
+ self,
390
+ items: Sequence[Union[BulkItem, Mapping[str, Any]]],
391
+ delivery: str,
392
+ fmt: Optional[str],
393
+ quality: Optional[int],
394
+ expires_in: Optional[int],
395
+ ) -> Op[BulkResponse]:
396
+ _check(fmt, quality, expires_in)
397
+ if not items:
398
+ raise ImejisConfigError("render_bulk needs at least one item.")
399
+ if len(items) > core.BULK_MAX_ITEMS:
400
+ raise ImejisConfigError(
401
+ f"Too many items: {len(items)}. One call renders at most {core.BULK_MAX_ITEMS}; split the batch."
402
+ )
403
+ resolved = []
404
+ for raw in items:
405
+ item = raw if isinstance(raw, BulkItem) else BulkItem(**dict(raw))
406
+ _check(item.format, item.quality)
407
+ code = yield from self._op_render_code(item.design)
408
+ resolved.append(
409
+ _drop_none(
410
+ {
411
+ "designId": code,
412
+ "variation": item.size,
413
+ "overrides": _clean_overrides(item.overrides),
414
+ "format": item.format,
415
+ "quality": item.quality,
416
+ "filename": item.filename,
417
+ }
418
+ )
419
+ )
420
+ result = yield from self._op_bulk_post(
421
+ _drop_none(
422
+ {
423
+ "items": resolved,
424
+ "delivery": delivery,
425
+ "format": fmt,
426
+ "quality": quality,
427
+ "expiresIn": expires_in if delivery == "signed" else None,
428
+ }
429
+ )
430
+ )
431
+ return result
432
+
433
+ def _op_bulk_post(self, body: Dict[str, Any]) -> Op[BulkResponse]:
434
+ key = yield from self._op_render_key()
435
+ resp = yield self._render_request(key, self._render.bulk, "json", {}, body)
436
+ rows = (resp.data or {}).get("results") or [] if isinstance(resp.data, dict) else []
437
+ results: List[BulkResult] = []
438
+ for i, row in enumerate(r for r in rows if isinstance(r, dict)):
439
+ stored = core.parse_stored_image(row)
440
+ ok = row.get("success") is not False and stored is not None
441
+ results.append(
442
+ BulkResult(
443
+ index=row["index"] if isinstance(row.get("index"), int) else i,
444
+ ok=ok,
445
+ design_id=str(row.get("designId") or ""),
446
+ size=row.get("variation"),
447
+ url=stored.url if stored else None,
448
+ format=stored.format if stored else None,
449
+ expires_at=stored.expires_at if stored else None,
450
+ filename=row.get("filename"),
451
+ error=None if ok else (row.get("error") or "render failed"),
452
+ warnings=stored.warnings if stored else [],
453
+ )
454
+ )
455
+ succeeded = sum(1 for r in results if r.ok)
456
+ return BulkResponse(results=results, succeeded=succeeded, failed=len(results) - succeeded)
457
+
458
+
459
+ __all__ = ["BaseClient"]