jamframe 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.
jamframe/_base.py ADDED
@@ -0,0 +1,458 @@
1
+ """What the sync and async clients share: configuration, request building,
2
+ error mapping and the retry policy. Neither does any I/O here."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import datetime
7
+ import email.utils
8
+ import os
9
+ import random
10
+ import time
11
+ from typing import IO, Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union
12
+ from urllib.parse import quote
13
+
14
+ import httpx
15
+
16
+ from . import _brand
17
+ from ._version import __version__
18
+ from .errors import APIError, RateLimitError, SDKError, error_class_for
19
+ from .types import (
20
+ BrandValues,
21
+ Modifications,
22
+ RenderAiOptions,
23
+ RenderOptions,
24
+ SignedUrlOptions,
25
+ SocialPostInput,
26
+ WorkflowCreateInput,
27
+ WorkflowUpdateInput,
28
+ )
29
+
30
+ API_PREFIX = "/v1"
31
+ DEFAULT_TIMEOUT = 120.0
32
+ DEFAULT_MAX_RETRIES = 2
33
+ # A 429 asking to wait longer than this is raised instead of slept through.
34
+ MAX_RETRY_AFTER = 60.0
35
+ # Render job polling: start at `poll_interval`, x1.5 each poll, at most this.
36
+ MAX_POLL_INTERVAL = 5.0
37
+ DEFAULT_WAIT_TIMEOUT = 600.0
38
+ # A workflow run has ended in one of these.
39
+ FINAL_RUN_STATUSES = frozenset({"succeeded", "partial", "failed", "canceled"})
40
+
41
+ Params = Mapping[str, Union[str, int, float, bool, None]]
42
+
43
+ FileInput = Union[bytes, bytearray, memoryview, "os.PathLike[str]", IO[bytes]]
44
+ """A file to upload: its bytes, a path (``pathlib.Path``) or a binary file object."""
45
+
46
+ Upload = Tuple[str, bytes]
47
+ """A file to send as multipart: its name and its bytes."""
48
+
49
+
50
+ def normalize_base_url(base_url: str) -> str:
51
+ """``https://host`` or ``https://host/v1`` -> ``https://host/v1``.
52
+
53
+ A URL ending in the older ``/api/v1`` is kept as given.
54
+ """
55
+ url = base_url.strip().rstrip("/")
56
+ if not url.startswith(("http://", "https://")):
57
+ raise SDKError(f"base_url must start with http:// or https:// (got {base_url!r})")
58
+ if url.endswith(API_PREFIX):
59
+ return url
60
+ return url + API_PREFIX
61
+
62
+
63
+ def path_segment(value: str) -> str:
64
+ """An id, escaped for use as one URL path segment."""
65
+ if not isinstance(value, str) or not value:
66
+ raise SDKError("An id must be a non-empty string")
67
+ return quote(value, safe="")
68
+
69
+
70
+ def clean_params(params: Optional[Params]) -> Dict[str, Union[str, int, float, bool]]:
71
+ return {k: v for k, v in (params or {}).items() if v is not None}
72
+
73
+
74
+ def backoff_delay(attempt: int, rand: Callable[[], float]) -> float:
75
+ """Exponential backoff with jitter: 0.5 s, 1 s, 2 s … at most 8 s, times 0.5–1."""
76
+ base = min(8.0, 0.5 * (2**attempt))
77
+ return float(base * (0.5 + rand() / 2))
78
+
79
+
80
+ def parse_retry_after(value: Optional[str], now: Optional[float] = None) -> Optional[float]:
81
+ """``Retry-After`` as seconds (a number of seconds or an HTTP date)."""
82
+ if value is None:
83
+ return None
84
+ text = value.strip()
85
+ if not text:
86
+ return None
87
+ try:
88
+ return max(0.0, float(text))
89
+ except ValueError:
90
+ pass
91
+ try:
92
+ when = email.utils.parsedate_to_datetime(text)
93
+ except (TypeError, ValueError, IndexError):
94
+ return None
95
+ if when is None: # pragma: no cover - older Pythons returned None
96
+ return None
97
+ current = time.time() if now is None else now
98
+ return max(0.0, when.timestamp() - current)
99
+
100
+
101
+ def api_error_from_response(response: httpx.Response) -> APIError:
102
+ status = response.status_code
103
+ headers = dict(response.headers.items())
104
+ body: Any
105
+ try:
106
+ body = response.json()
107
+ except ValueError:
108
+ body = None
109
+ if isinstance(body, dict) and isinstance(body.get("error"), str):
110
+ code = str(body["error"])
111
+ message = str(body.get("message") or code)
112
+ detail = body.get("detail") if isinstance(body.get("detail"), dict) else None
113
+ else:
114
+ code = f"HTTP_{status}"
115
+ text = response.text.strip() if response.content else ""
116
+ message = text[:300] if text else (response.reason_phrase or f"HTTP {status}")
117
+ detail = None
118
+ body = body if body is not None else (response.text if response.content else None)
119
+ cls = error_class_for(status)
120
+ if cls is RateLimitError:
121
+ retry_after = parse_retry_after(response.headers.get("retry-after"))
122
+ if retry_after is None and detail and isinstance(detail.get("retryAfter"), (int, float)):
123
+ retry_after = float(detail["retryAfter"])
124
+ return RateLimitError(status, code, message, detail=detail, headers=headers, body=body, retry_after=retry_after)
125
+ return cls(status, code, message, detail=detail, headers=headers, body=body)
126
+
127
+
128
+ def retry_delay(
129
+ error: APIError,
130
+ attempt: int,
131
+ *,
132
+ idempotent: bool,
133
+ max_retries: int,
134
+ rand: Callable[[], float],
135
+ ) -> Optional[float]:
136
+ """Seconds to wait before retrying ``error``, or ``None`` to raise it.
137
+
138
+ A 429 is retried for every call: the rate limiter refuses a request
139
+ before it reaches the handler, so nothing happened. A 5xx is retried only
140
+ for idempotent calls: a render may have run (and been charged) before a
141
+ proxy answered 502.
142
+ """
143
+ if attempt >= max_retries:
144
+ return None
145
+ if isinstance(error, RateLimitError):
146
+ if error.retry_after is not None:
147
+ return None if error.retry_after > MAX_RETRY_AFTER else error.retry_after
148
+ return backoff_delay(attempt, rand)
149
+ if error.status >= 500 and idempotent:
150
+ return backoff_delay(attempt, rand)
151
+ return None
152
+
153
+
154
+ class Result:
155
+ """A 2xx answer: its status, parsed JSON (``None`` when empty) and headers."""
156
+
157
+ __slots__ = ("status_code", "data", "headers")
158
+
159
+ def __init__(self, status_code: int, data: Any, headers: httpx.Headers) -> None:
160
+ self.status_code = status_code
161
+ self.data = data
162
+ self.headers = headers
163
+
164
+
165
+ def parse_success(response: httpx.Response) -> Result:
166
+ data: Any = None
167
+ if response.content:
168
+ try:
169
+ data = response.json()
170
+ except ValueError as exc:
171
+ raise APIError(
172
+ response.status_code,
173
+ "INVALID_RESPONSE",
174
+ "The API answered with something that isn't JSON.",
175
+ headers=dict(response.headers.items()),
176
+ body=response.text[:1000],
177
+ ) from exc
178
+ return Result(response.status_code, data, response.headers)
179
+
180
+
181
+ class BaseClient:
182
+ """Configuration shared by :class:`Client` and :class:`AsyncClient`."""
183
+
184
+ def __init__(
185
+ self,
186
+ api_key: Optional[str],
187
+ base_url: Optional[str],
188
+ timeout: float,
189
+ max_retries: int,
190
+ user_agent: Optional[str],
191
+ ) -> None:
192
+ key = api_key if api_key is not None else os.environ.get(_brand.API_KEY_ENV)
193
+ if not key:
194
+ raise SDKError(f"No API key: pass api_key=... or set {_brand.API_KEY_ENV}.")
195
+ self.api_key = key
196
+ self.base_url = normalize_base_url(
197
+ base_url or os.environ.get(_brand.BASE_URL_ENV) or _brand.DEFAULT_BASE_URL
198
+ )
199
+ self.timeout = timeout
200
+ if max_retries < 0:
201
+ raise SDKError("max_retries must be 0 or more")
202
+ self.max_retries = max_retries
203
+ agent = f"{_brand.USER_AGENT_PREFIX}/{__version__}"
204
+ self.user_agent = f"{user_agent} {agent}" if user_agent else agent
205
+ # Testing hook: a function returning [0, 1), for retry jitter.
206
+ self._random: Callable[[], float] = random.random
207
+
208
+ def __repr__(self) -> str:
209
+ return f"{type(self).__name__}(base_url={self.base_url!r})"
210
+
211
+ def _headers(self) -> Dict[str, str]:
212
+ return {
213
+ "Authorization": f"Bearer {self.api_key}",
214
+ "Accept": "application/json",
215
+ "User-Agent": self.user_agent,
216
+ }
217
+
218
+ def _request_args(
219
+ self,
220
+ method: str,
221
+ path: str,
222
+ params: Optional[Params],
223
+ json_body: Any,
224
+ upload: Optional[Upload] = None,
225
+ form: Optional[Mapping[str, Any]] = None,
226
+ ) -> Dict[str, Any]:
227
+ args: Dict[str, Any] = {
228
+ "method": method,
229
+ "url": self.base_url + path,
230
+ "headers": self._headers(),
231
+ "timeout": self.timeout,
232
+ }
233
+ query = clean_params(params)
234
+ if query:
235
+ args["params"] = query
236
+ if upload is not None:
237
+ # Multipart: the file, and the other fields as strings.
238
+ args["files"] = {"file": upload}
239
+ args["data"] = form_fields(form or {})
240
+ elif json_body is not None:
241
+ args["json"] = json_body
242
+ return args
243
+
244
+
245
+ # ---------------------------------------------------------------- request bodies
246
+
247
+
248
+ def render_body(
249
+ template_id: str,
250
+ modifications: Optional[Modifications],
251
+ response: Optional[RenderOptions],
252
+ *,
253
+ run_async: bool = False,
254
+ webhook_url: Optional[str] = None,
255
+ expires_in: Optional[int] = None,
256
+ translate: Optional[bool] = None,
257
+ lang: Optional[str] = None,
258
+ ai: Optional[RenderAiOptions] = None,
259
+ ) -> Dict[str, Any]:
260
+ if not isinstance(template_id, str) or not template_id:
261
+ raise SDKError("template_id must be a non-empty string")
262
+ body: Dict[str, Any] = {"templateId": template_id}
263
+ if modifications:
264
+ body["modifications"] = dict(modifications)
265
+ if response:
266
+ body["response"] = dict(response)
267
+ if run_async:
268
+ body["async"] = True
269
+ if webhook_url:
270
+ body["webhookUrl"] = webhook_url
271
+ if expires_in is not None:
272
+ body["expiresIn"] = expires_in
273
+ if translate is not None:
274
+ body["translate"] = translate
275
+ if lang:
276
+ body["lang"] = lang
277
+ if ai:
278
+ body["ai"] = dict(ai)
279
+ return body
280
+
281
+
282
+ def design_generate_body(
283
+ prompt: str,
284
+ *,
285
+ size: Optional[str],
286
+ width: Optional[int],
287
+ height: Optional[int],
288
+ pages: Optional[int],
289
+ video: Optional[bool],
290
+ brand: Union[bool, BrandValues, None],
291
+ reference_image_url: Optional[str],
292
+ name: Optional[str],
293
+ run_async: bool = False,
294
+ webhook_url: Optional[str] = None,
295
+ ) -> Dict[str, Any]:
296
+ if not isinstance(prompt, str) or not prompt.strip():
297
+ raise SDKError("prompt must be a non-empty string")
298
+ body: Dict[str, Any] = {"prompt": prompt}
299
+ fields = {
300
+ "size": size,
301
+ "width": width,
302
+ "height": height,
303
+ "pages": pages,
304
+ "video": video,
305
+ "brand": dict(brand) if isinstance(brand, dict) else brand,
306
+ "referenceImageUrl": reference_image_url,
307
+ "name": name,
308
+ "webhookUrl": webhook_url,
309
+ }
310
+ body.update({k: v for k, v in fields.items() if v is not None})
311
+ if run_async:
312
+ body["async"] = True
313
+ return body
314
+
315
+
316
+ def workflow_body(body: Union[WorkflowCreateInput, WorkflowUpdateInput, None], kwargs: Mapping[str, Any]) -> Dict[str, Any]:
317
+ merged: Dict[str, Any] = dict(body or {})
318
+ merged.update(kwargs)
319
+ return merged
320
+
321
+
322
+ def run_body(payload: Any, max_rows: Optional[int]) -> Dict[str, Any]:
323
+ body: Dict[str, Any] = {}
324
+ if payload is not None:
325
+ body["payload"] = payload
326
+ if max_rows is not None:
327
+ body["maxRows"] = max_rows
328
+ return body
329
+
330
+
331
+ def analytics_params(
332
+ from_: Union[str, datetime.date, None],
333
+ to: Union[str, datetime.date, None],
334
+ platform: Union[str, Sequence[str], None],
335
+ account_id: Union[str, Sequence[str], None],
336
+ ) -> Dict[str, Optional[str]]:
337
+ """Query of the social analytics reports: dates as ``YYYY-MM-DD``, lists comma-separated."""
338
+
339
+ def day(value: Union[str, datetime.date, None]) -> Optional[str]:
340
+ return value.isoformat() if isinstance(value, datetime.date) else value
341
+
342
+ def joined(value: Union[str, Sequence[str], None]) -> Optional[str]:
343
+ return value if value is None or isinstance(value, str) else ",".join(value)
344
+
345
+ return {"from": day(from_), "to": day(to), "platform": joined(platform), "accountId": joined(account_id)}
346
+
347
+
348
+ def read_upload(file: FileInput, filename: Optional[str]) -> Upload:
349
+ """The file's name and bytes, read once so a retried request can send them again."""
350
+ if isinstance(file, (bytes, bytearray, memoryview)):
351
+ return (filename or "upload", bytes(file))
352
+ if isinstance(file, os.PathLike):
353
+ path = os.fspath(file)
354
+ with open(path, "rb") as handle:
355
+ return (filename or os.path.basename(path), handle.read())
356
+ if hasattr(file, "read"):
357
+ data = file.read()
358
+ if not isinstance(data, bytes):
359
+ raise SDKError("Open the file in binary mode ('rb')")
360
+ own = getattr(file, "name", None)
361
+ return (filename or (os.path.basename(own) if isinstance(own, str) else "upload"), data)
362
+ raise SDKError("file must be bytes, a path (pathlib.Path) or a binary file object")
363
+
364
+
365
+ def form_fields(fields: Mapping[str, Any]) -> Dict[str, str]:
366
+ """Multipart text fields: ``None`` dropped, booleans as ``true``/``false``."""
367
+ out: Dict[str, str] = {}
368
+ for key, value in fields.items():
369
+ if value is None:
370
+ continue
371
+ out[key] = ("true" if value else "false") if isinstance(value, bool) else str(value)
372
+ return out
373
+
374
+
375
+ def media_source(url: Optional[str], file: Optional[FileInput], filename: Optional[str]) -> Optional[Upload]:
376
+ """Checks that exactly one of ``url`` and ``file`` is given; returns the upload for a file."""
377
+ if (url is None) == (file is None):
378
+ raise SDKError("Pass either url=... or file=..., not both")
379
+ return None if file is None else read_upload(file, filename)
380
+
381
+
382
+ def signed_url_body(
383
+ template_id: str,
384
+ modifications: Optional[Mapping[str, Any]],
385
+ response: Optional[SignedUrlOptions],
386
+ expires_in: Optional[int],
387
+ cache_seconds: Optional[int],
388
+ ) -> Dict[str, Any]:
389
+ if not isinstance(template_id, str) or not template_id:
390
+ raise SDKError("template_id must be a non-empty string")
391
+ body: Dict[str, Any] = {"templateId": template_id}
392
+ if modifications:
393
+ body["modifications"] = dict(modifications)
394
+ if response:
395
+ body["response"] = dict(response)
396
+ if expires_in is not None:
397
+ body["expiresIn"] = expires_in
398
+ if cache_seconds is not None:
399
+ body["cacheSeconds"] = cache_seconds
400
+ return body
401
+
402
+
403
+ # Python-style spellings accepted by social.posts.create(**kwargs).
404
+ _SOCIAL_KWARG_NAMES = {
405
+ "template_id": "templateId",
406
+ "render_id": "renderId",
407
+ "media_urls": "mediaUrls",
408
+ "scheduled_at": "scheduledAt",
409
+ }
410
+
411
+
412
+ def social_post_body(body: Optional[SocialPostInput], kwargs: Mapping[str, Any]) -> Dict[str, Any]:
413
+ merged: Dict[str, Any] = dict(body or {})
414
+ for key, value in kwargs.items():
415
+ merged[_SOCIAL_KWARG_NAMES.get(key, key)] = value
416
+ return merged
417
+
418
+
419
+ def page_cursor(page: Mapping[str, Any]) -> Optional[str]:
420
+ """The next page's cursor, or ``None`` on the last page."""
421
+ pagination = page.get("pagination") or {}
422
+ cursor = pagination.get("nextCursor")
423
+ if not pagination.get("hasMore") or not cursor:
424
+ return None
425
+ return str(cursor)
426
+
427
+
428
+ def sized_urls(content: Any) -> List[str]:
429
+ """Every file URL of a render's ``content`` (a string, a list, or sized entries)."""
430
+ if isinstance(content, str):
431
+ return [content]
432
+ urls: List[str] = []
433
+ for item in content or []:
434
+ if isinstance(item, str):
435
+ urls.append(item)
436
+ elif isinstance(item, dict):
437
+ if isinstance(item.get("url"), str):
438
+ urls.append(item["url"])
439
+ urls.extend(u for u in item.get("urls") or [] if isinstance(u, str))
440
+ return urls
441
+
442
+
443
+ def next_poll_interval(current: float, initial: float) -> float:
444
+ return min(current * 1.5, max(MAX_POLL_INTERVAL, initial))
445
+
446
+
447
+ def unwrap(result: Result, key: str) -> Any:
448
+ data = result.data
449
+ if isinstance(data, dict) and key in data:
450
+ return data[key]
451
+ raise APIError(
452
+ result.status_code,
453
+ "INVALID_RESPONSE",
454
+ f"The API answer has no {key!r} field.",
455
+ headers=dict(result.headers.items()),
456
+ body=data,
457
+ )
458
+
jamframe/_brand.py ADDED
@@ -0,0 +1,19 @@
1
+ """Every product-specific string of the SDK, in one place.
2
+
3
+ A rename means editing this file, the
4
+ ``name`` in ``pyproject.toml`` and the package directory (``src/jamframe``);
5
+ nothing else in the code spells the brand.
6
+ """
7
+
8
+ NAME = "JamFrame"
9
+ DEFAULT_BASE_URL = "https://api.jamframe.com"
10
+
11
+ # Environment variables read when the client is built without arguments.
12
+ API_KEY_ENV = "JAMFRAME_API_KEY"
13
+ BASE_URL_ENV = "JAMFRAME_BASE_URL"
14
+
15
+ # The live smoke test (tests/test_live_smoke.py) runs only when this is set.
16
+ SMOKE_API_KEY_ENV = "JAMFRAME_SMOKE_API_KEY"
17
+ SMOKE_BASE_URL_ENV = "JAMFRAME_SMOKE_BASE_URL"
18
+
19
+ USER_AGENT_PREFIX = "jamframe-python"