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/_client.py ADDED
@@ -0,0 +1,916 @@
1
+ """The synchronous client.
2
+
3
+ ``_async_client.py`` mirrors this file method for method; change both together.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import datetime
9
+ import time
10
+ from types import TracebackType
11
+ from typing import Any, Callable, Dict, Iterator, List, Literal, Mapping, Optional, Sequence, Type, Union, cast
12
+
13
+ import httpx
14
+
15
+ from . import webhooks as _webhooks
16
+ from ._base import (
17
+ DEFAULT_MAX_RETRIES,
18
+ DEFAULT_TIMEOUT,
19
+ DEFAULT_WAIT_TIMEOUT,
20
+ FINAL_RUN_STATUSES,
21
+ BaseClient,
22
+ FileInput,
23
+ Params,
24
+ Result,
25
+ Upload,
26
+ analytics_params,
27
+ api_error_from_response,
28
+ backoff_delay,
29
+ design_generate_body,
30
+ media_source,
31
+ next_poll_interval,
32
+ page_cursor,
33
+ parse_success,
34
+ path_segment,
35
+ render_body,
36
+ retry_delay,
37
+ run_body,
38
+ signed_url_body,
39
+ social_post_body,
40
+ unwrap,
41
+ workflow_body,
42
+ )
43
+ from .errors import APIConnectionError, APITimeoutError, DesignJobFailedError, RenderJobFailedError, WaitTimeoutError
44
+ from .types import (
45
+ AiStatus,
46
+ AuthResult,
47
+ BackgroundRemoval,
48
+ BrandValues,
49
+ Design,
50
+ DesignDetail,
51
+ DesignGenerateAccepted,
52
+ DesignGenerateJob,
53
+ DesignPage,
54
+ DesignSource,
55
+ Modifications,
56
+ RenderAiOptions,
57
+ RenderItem,
58
+ RenderJob,
59
+ RenderJobAccepted,
60
+ RenderOptions,
61
+ RenderPage,
62
+ RenderResponse,
63
+ SignedUrlKeyRotation,
64
+ SignedUrlOptions,
65
+ SignedUrlResponse,
66
+ SocialAccount,
67
+ SocialAnalyticsDaily,
68
+ SocialAnalyticsInsights,
69
+ SocialAnalyticsOverview,
70
+ SocialPost,
71
+ SocialPostCreated,
72
+ SocialPostInput,
73
+ SocialPostPage,
74
+ Transcription,
75
+ WebhookEventType,
76
+ WebhookSubscription,
77
+ WebhookSubscriptionPage,
78
+ WebhookSubscriptionWithSecret,
79
+ WebhookTestResult,
80
+ Workflow,
81
+ WorkflowCreateInput,
82
+ WorkflowRun,
83
+ WorkflowRunPage,
84
+ WorkflowRunWithRows,
85
+ WorkflowUpdateInput,
86
+ )
87
+
88
+ Day = Union[str, datetime.date]
89
+ """A day: ``"2026-11-19"`` or a ``datetime.date``."""
90
+ Many = Union[str, Sequence[str]]
91
+ """One value, or several (sent comma-separated)."""
92
+
93
+
94
+ class Client(BaseClient):
95
+ """A synchronous client for the v1 API.
96
+
97
+ >>> client = Client() # reads JAMFRAME_API_KEY (and JAMFRAME_BASE_URL)
98
+ >>> client.render("tpl_id", {"title": "Hello"})["data"]["content"]
99
+
100
+ ``base_url`` is the API's origin (``https://api.jamframe.com``) or its
101
+ root (``…/v1``; the older ``…/api/v1`` also works). ``timeout`` is per
102
+ HTTP request, in seconds.
103
+ ``max_retries`` applies to 429s (every call) and to 5xx answers,
104
+ connection errors and timeouts of idempotent calls. Pass your own
105
+ ``http_client`` (an ``httpx.Client``) for proxies or custom transports;
106
+ the SDK won't close it.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ api_key: Optional[str] = None,
112
+ *,
113
+ base_url: Optional[str] = None,
114
+ timeout: float = DEFAULT_TIMEOUT,
115
+ max_retries: int = DEFAULT_MAX_RETRIES,
116
+ http_client: Optional[httpx.Client] = None,
117
+ user_agent: Optional[str] = None,
118
+ ) -> None:
119
+ super().__init__(api_key, base_url, timeout, max_retries, user_agent)
120
+ self._owns_http = http_client is None
121
+ self._http = http_client if http_client is not None else httpx.Client(timeout=timeout)
122
+ # Testing hooks.
123
+ self._sleep: Callable[[float], None] = time.sleep
124
+ self._clock: Callable[[], float] = time.monotonic
125
+
126
+ self.designs = Designs(self)
127
+ self.design_jobs = DesignJobs(self)
128
+ self.renders = Renders(self)
129
+ self.render_jobs = RenderJobs(self)
130
+ self.signed_urls = SignedUrls(self)
131
+ self.social = Social(self)
132
+ self.workflows = Workflows(self)
133
+ self.ai = Ai(self)
134
+ self.webhooks = Webhooks(self)
135
+
136
+ # ------------------------------------------------------------ lifecycle
137
+
138
+ def close(self) -> None:
139
+ """Close the connection pool (only when the SDK created it)."""
140
+ if self._owns_http:
141
+ self._http.close()
142
+
143
+ def __enter__(self) -> "Client":
144
+ return self
145
+
146
+ def __exit__(
147
+ self,
148
+ exc_type: Optional[Type[BaseException]],
149
+ exc: Optional[BaseException],
150
+ tb: Optional[TracebackType],
151
+ ) -> None:
152
+ self.close()
153
+
154
+ # ------------------------------------------------------------ transport
155
+
156
+ def _request(
157
+ self,
158
+ method: str,
159
+ path: str,
160
+ *,
161
+ params: Optional[Params] = None,
162
+ json_body: Any = None,
163
+ idempotent: Optional[bool] = None,
164
+ upload: Optional[Upload] = None,
165
+ form: Optional[Mapping[str, Any]] = None,
166
+ ) -> Result:
167
+ if idempotent is None:
168
+ idempotent = method in ("GET", "HEAD", "DELETE")
169
+ args = self._request_args(method, path, params, json_body, upload, form)
170
+ attempt = 0
171
+ while True:
172
+ try:
173
+ response = self._http.request(**args)
174
+ except httpx.TimeoutException as exc:
175
+ if idempotent and attempt < self.max_retries:
176
+ self._sleep(backoff_delay(attempt, self._random))
177
+ attempt += 1
178
+ continue
179
+ raise APITimeoutError(f"{method} {path} timed out after {self.timeout:g} s") from exc
180
+ except httpx.TransportError as exc:
181
+ if idempotent and attempt < self.max_retries:
182
+ self._sleep(backoff_delay(attempt, self._random))
183
+ attempt += 1
184
+ continue
185
+ raise APIConnectionError(f"{method} {path} failed: {exc}") from exc
186
+ if response.status_code < 400:
187
+ return parse_success(response)
188
+ error = api_error_from_response(response)
189
+ delay = retry_delay(
190
+ error, attempt, idempotent=idempotent, max_retries=self.max_retries, rand=self._random
191
+ )
192
+ if delay is None:
193
+ raise error
194
+ self._sleep(delay)
195
+ attempt += 1
196
+
197
+ # ------------------------------------------------------------ top-level calls
198
+
199
+ def whoami(self) -> AuthResult:
200
+ """Check the API key: ``{ workspaceId, username }`` (``POST /auth``)."""
201
+ return cast(AuthResult, self._request("POST", "/auth", idempotent=True).data)
202
+
203
+ def render(
204
+ self,
205
+ template_id: str,
206
+ modifications: Optional[Modifications] = None,
207
+ *,
208
+ response: Optional[RenderOptions] = None,
209
+ expires_in: Optional[int] = None,
210
+ translate: Optional[bool] = None,
211
+ lang: Optional[str] = None,
212
+ ai: Optional[RenderAiOptions] = None,
213
+ wait_timeout: float = DEFAULT_WAIT_TIMEOUT,
214
+ poll_interval: float = 1.0,
215
+ ) -> RenderResponse:
216
+ """Render a template and return ``{ data, warnings }``.
217
+
218
+ ``template_id`` is a template's id or a library template's slug.
219
+ Images and PDFs answer at once. An MP4 the API is still rendering
220
+ after 90 s (a ``202``) is waited for here, up to ``wait_timeout``.
221
+ Spends credits: 1 per image or PDF page, 1 per second of video.
222
+
223
+ ``expires_in``: seconds the file links work (300 to 604800).
224
+ ``translate`` with ``lang`` (``"es"``, ``"pt-BR"``…) translates every
225
+ text layer with AI. ``ai={"onError": "fallback"}`` renders AI layers'
226
+ saved text and images instead of failing.
227
+ """
228
+ body = render_body(
229
+ template_id, modifications, response, expires_in=expires_in, translate=translate, lang=lang, ai=ai
230
+ )
231
+ result = self._request("POST", "/render", json_body=body, idempotent=False)
232
+ if result.status_code == 202:
233
+ accepted = cast(RenderJobAccepted, unwrap(result, "data"))
234
+ job = self.render_jobs.wait(accepted["jobId"], timeout=wait_timeout, poll_interval=poll_interval)
235
+ return {"data": cast(Any, job["result"]), "warnings": list(job.get("warnings") or [])}
236
+ payload = cast(Dict[str, Any], result.data)
237
+ return {"data": payload["data"], "warnings": list(payload.get("warnings") or [])}
238
+
239
+ def render_async(
240
+ self,
241
+ template_id: str,
242
+ modifications: Optional[Modifications] = None,
243
+ *,
244
+ response: Optional[RenderOptions] = None,
245
+ webhook_url: Optional[str] = None,
246
+ expires_in: Optional[int] = None,
247
+ translate: Optional[bool] = None,
248
+ lang: Optional[str] = None,
249
+ ai: Optional[RenderAiOptions] = None,
250
+ ) -> RenderJobAccepted:
251
+ """Queue a render job and return ``{ jobId, status }`` at once (``"async": true``).
252
+
253
+ ``webhook_url`` receives ``{ event, job }`` when the job ends (unsigned:
254
+ confirm with :meth:`RenderJobs.get`). The other options are as in :meth:`render`.
255
+ """
256
+ body = render_body(
257
+ template_id,
258
+ modifications,
259
+ response,
260
+ run_async=True,
261
+ webhook_url=webhook_url,
262
+ expires_in=expires_in,
263
+ translate=translate,
264
+ lang=lang,
265
+ ai=ai,
266
+ )
267
+ result = self._request("POST", "/render", json_body=body, idempotent=False)
268
+ return cast(RenderJobAccepted, unwrap(result, "data"))
269
+
270
+ def render_and_wait(
271
+ self,
272
+ template_id: str,
273
+ modifications: Optional[Modifications] = None,
274
+ *,
275
+ response: Optional[RenderOptions] = None,
276
+ webhook_url: Optional[str] = None,
277
+ expires_in: Optional[int] = None,
278
+ translate: Optional[bool] = None,
279
+ lang: Optional[str] = None,
280
+ ai: Optional[RenderAiOptions] = None,
281
+ timeout: float = DEFAULT_WAIT_TIMEOUT,
282
+ poll_interval: float = 1.0,
283
+ ) -> RenderJob:
284
+ """Queue a render job and poll it until it succeeds; returns the job (files in ``result``).
285
+
286
+ Raises :class:`RenderJobFailedError` if it fails (no credits are
287
+ charged) and :class:`WaitTimeoutError` after ``timeout`` seconds.
288
+ """
289
+ accepted = self.render_async(
290
+ template_id,
291
+ modifications,
292
+ response=response,
293
+ webhook_url=webhook_url,
294
+ expires_in=expires_in,
295
+ translate=translate,
296
+ lang=lang,
297
+ ai=ai,
298
+ )
299
+ return self.render_jobs.wait(accepted["jobId"], timeout=timeout, poll_interval=poll_interval)
300
+
301
+ def _poll(
302
+ self,
303
+ job_id: str,
304
+ what: str,
305
+ get: Callable[[], Mapping[str, Any]],
306
+ done: Callable[[Mapping[str, Any]], bool],
307
+ timeout: float,
308
+ poll_interval: float,
309
+ ) -> Any:
310
+ """Call ``get`` until ``done`` says so (it may raise to end the wait).
311
+
312
+ Polls start ``poll_interval`` apart and grow 1.5x up to 5 s. After
313
+ ``timeout`` seconds raises :class:`WaitTimeoutError`; the job keeps running.
314
+ """
315
+ deadline = self._clock() + timeout
316
+ interval = poll_interval
317
+ while True:
318
+ job = get()
319
+ if done(job):
320
+ return job
321
+ remaining = deadline - self._clock()
322
+ if remaining <= 0:
323
+ raise WaitTimeoutError(job_id, job, timeout, what)
324
+ self._sleep(min(interval, remaining))
325
+ interval = next_poll_interval(interval, poll_interval)
326
+
327
+
328
+ class _Resource:
329
+ def __init__(self, client: Client) -> None:
330
+ self._client = client
331
+
332
+
333
+ class RenderJobs(_Resource):
334
+ """MP4 renders and ``async`` renders (``GET /render-jobs/{id}``)."""
335
+
336
+ def get(self, job_id: str) -> RenderJob:
337
+ result = self._client._request("GET", f"/render-jobs/{path_segment(job_id)}")
338
+ return cast(RenderJob, unwrap(result, "job"))
339
+
340
+ def wait(
341
+ self, job_id: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 1.0
342
+ ) -> RenderJob:
343
+ """Poll until the job succeeds (returned) or fails (:class:`RenderJobFailedError`).
344
+
345
+ Polls start ``poll_interval`` apart and grow 1.5x up to 5 s. After
346
+ ``timeout`` seconds raises :class:`WaitTimeoutError`; the job keeps running.
347
+ """
348
+
349
+ def done(job: Mapping[str, Any]) -> bool:
350
+ if job["status"] == "failed":
351
+ raise RenderJobFailedError(cast(RenderJob, job))
352
+ return bool(job["status"] == "succeeded")
353
+
354
+ job = self._client._poll(job_id, "Render job", lambda: self.get(job_id), done, timeout, poll_interval)
355
+ return cast(RenderJob, job)
356
+
357
+
358
+ class Designs(_Resource):
359
+ """Templates: the workspace's own, or the template library (``source="library"``)."""
360
+
361
+ def list(
362
+ self,
363
+ *,
364
+ source: DesignSource = "workspace",
365
+ q: Optional[str] = None,
366
+ cursor: Optional[str] = None,
367
+ limit: Optional[int] = None,
368
+ ) -> DesignPage:
369
+ """One page, newest first: ``{ designs, pagination }``.
370
+
371
+ ``q`` keeps the designs whose name contains it, ignoring case (at most
372
+ 100 characters), for either ``source``.
373
+ """
374
+ params: Dict[str, Any] = {"source": source, "q": q, "cursor": cursor, "limit": limit}
375
+ return cast(DesignPage, self._client._request("GET", "/designs", params=params).data)
376
+
377
+ def iter(
378
+ self, *, source: DesignSource = "workspace", q: Optional[str] = None, limit: Optional[int] = None
379
+ ) -> Iterator[Design]:
380
+ """Every design (matching ``q``), fetching pages of ``limit`` (default 25, at most 100) as needed."""
381
+ cursor: Optional[str] = None
382
+ while True:
383
+ page = self.list(source=source, q=q, cursor=cursor, limit=limit)
384
+ yield from page["designs"]
385
+ cursor = page_cursor(page)
386
+ if cursor is None:
387
+ return
388
+
389
+ def get(self, design_id: str) -> DesignDetail:
390
+ """One template (yours or a library one) with its ``pages``, ``parameters`` and ``sizes``."""
391
+ result = self._client._request("GET", f"/designs/{path_segment(design_id)}")
392
+ return cast(DesignDetail, unwrap(result, "design"))
393
+
394
+ def generate(
395
+ self,
396
+ prompt: str,
397
+ *,
398
+ size: Optional[str] = None,
399
+ width: Optional[int] = None,
400
+ height: Optional[int] = None,
401
+ pages: Optional[int] = None,
402
+ video: Optional[bool] = None,
403
+ brand: Union[bool, BrandValues, None] = None,
404
+ reference_image_url: Optional[str] = None,
405
+ name: Optional[str] = None,
406
+ wait_timeout: float = DEFAULT_WAIT_TIMEOUT,
407
+ poll_interval: float = 1.0,
408
+ ) -> DesignGenerateJob:
409
+ """Design a new template with AI from a description and save it in the workspace.
410
+
411
+ The brand kit is applied and parameter keys set (``title``, ``photo``…);
412
+ the job's ``design`` is ready to render. The API waits about 25 s; a
413
+ longer design is polled here, up to ``wait_timeout``. Costs 15 to 30 AI
414
+ credits, refunded when it fails (:class:`DesignJobFailedError`).
415
+
416
+ ``size``: a preset id (``instagram-story``, ``linkedin-carousel``…),
417
+ ``square``/``portrait``/``story``/``landscape`` or ``"WIDTHxHEIGHT"``.
418
+ ``brand``: ``True`` (the brand library, default), ``False``, or
419
+ ``{"colors": [...], "fonts": [...], "logo": url}``.
420
+ """
421
+ body = design_generate_body(
422
+ prompt,
423
+ size=size,
424
+ width=width,
425
+ height=height,
426
+ pages=pages,
427
+ video=video,
428
+ brand=brand,
429
+ reference_image_url=reference_image_url,
430
+ name=name,
431
+ )
432
+ result = self._client._request("POST", "/designs/generate", json_body=body, idempotent=False)
433
+ job = cast(DesignGenerateJob, unwrap(result, "data"))
434
+ if job["status"] == "failed":
435
+ raise DesignJobFailedError(job)
436
+ if job["status"] == "succeeded" and job.get("design"):
437
+ return job
438
+ return self._client.design_jobs.wait(job["jobId"], timeout=wait_timeout, poll_interval=poll_interval)
439
+
440
+ def generate_async(
441
+ self,
442
+ prompt: str,
443
+ *,
444
+ size: Optional[str] = None,
445
+ width: Optional[int] = None,
446
+ height: Optional[int] = None,
447
+ pages: Optional[int] = None,
448
+ video: Optional[bool] = None,
449
+ brand: Union[bool, BrandValues, None] = None,
450
+ reference_image_url: Optional[str] = None,
451
+ name: Optional[str] = None,
452
+ webhook_url: Optional[str] = None,
453
+ ) -> DesignGenerateAccepted:
454
+ """Start an AI design and return ``{ jobId, status }`` at once.
455
+
456
+ Wait for it with :meth:`DesignJobs.wait`, or pass ``webhook_url`` to
457
+ receive ``{ event, job }`` when it ends (unsigned: confirm with
458
+ :meth:`DesignJobs.get`).
459
+ """
460
+ body = design_generate_body(
461
+ prompt,
462
+ size=size,
463
+ width=width,
464
+ height=height,
465
+ pages=pages,
466
+ video=video,
467
+ brand=brand,
468
+ reference_image_url=reference_image_url,
469
+ name=name,
470
+ run_async=True,
471
+ webhook_url=webhook_url,
472
+ )
473
+ result = self._client._request("POST", "/designs/generate", json_body=body, idempotent=False)
474
+ data = unwrap(result, "data")
475
+ return {"jobId": data["jobId"], "status": "running"}
476
+
477
+
478
+ class DesignJobs(_Resource):
479
+ """AI design generations (``GET /designs/generate/{jobId}``)."""
480
+
481
+ def get(self, job_id: str) -> DesignGenerateJob:
482
+ result = self._client._request("GET", f"/designs/generate/{path_segment(job_id)}")
483
+ return cast(DesignGenerateJob, unwrap(result, "data"))
484
+
485
+ def wait(
486
+ self, job_id: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 1.0
487
+ ) -> DesignGenerateJob:
488
+ """Poll until the design is made (returned, with ``design``) or the generation fails
489
+ (:class:`DesignJobFailedError`). After ``timeout`` seconds raises :class:`WaitTimeoutError`."""
490
+
491
+ def done(job: Mapping[str, Any]) -> bool:
492
+ if job["status"] == "failed":
493
+ raise DesignJobFailedError(cast(DesignGenerateJob, job))
494
+ return bool(job["status"] == "succeeded" and job.get("design"))
495
+
496
+ job = self._client._poll(job_id, "Design generation", lambda: self.get(job_id), done, timeout, poll_interval)
497
+ return cast(DesignGenerateJob, job)
498
+
499
+
500
+ class Renders(_Resource):
501
+ """The render log (``GET /renders``, ``GET /renders/{id}``)."""
502
+
503
+ def get(self, render_id: str) -> RenderItem:
504
+ """One render by id (a ``renderId`` from a render or a job's result), as the log lists it."""
505
+ result = self._client._request("GET", f"/renders/{path_segment(render_id)}")
506
+ return cast(RenderItem, unwrap(result, "render"))
507
+
508
+ def list(
509
+ self,
510
+ *,
511
+ status: Optional[str] = None,
512
+ design_id: Optional[str] = None,
513
+ cursor: Optional[str] = None,
514
+ limit: Optional[int] = None,
515
+ ) -> RenderPage:
516
+ """One page, newest first: ``{ renders, pagination, totals }`` (totals: this period's credits)."""
517
+ params = {"status": status, "designId": design_id, "cursor": cursor, "limit": limit}
518
+ return cast(RenderPage, self._client._request("GET", "/renders", params=params).data)
519
+
520
+ def iter(
521
+ self,
522
+ *,
523
+ status: Optional[str] = None,
524
+ design_id: Optional[str] = None,
525
+ limit: Optional[int] = None,
526
+ ) -> Iterator[RenderItem]:
527
+ cursor: Optional[str] = None
528
+ while True:
529
+ page = self.list(status=status, design_id=design_id, cursor=cursor, limit=limit)
530
+ yield from page["renders"]
531
+ cursor = page_cursor(page)
532
+ if cursor is None:
533
+ return
534
+
535
+
536
+ class SignedUrls(_Resource):
537
+ """Public, tamper-proof render URLs (``POST /signed-urls``)."""
538
+
539
+ def create(
540
+ self,
541
+ template_id: str,
542
+ modifications: Optional[Mapping[str, Any]] = None,
543
+ *,
544
+ response: Optional[SignedUrlOptions] = None,
545
+ expires_in: Optional[int] = None,
546
+ cache_seconds: Optional[int] = None,
547
+ ) -> SignedUrlResponse:
548
+ """Sign a render into a URL (``{ data: { url, … }, warnings? }``). Free until the URL is opened."""
549
+ body = signed_url_body(template_id, modifications, response, expires_in, cache_seconds)
550
+ result = self._client._request("POST", "/signed-urls", json_body=body, idempotent=True)
551
+ return cast(SignedUrlResponse, result.data)
552
+
553
+ def rotate_key(self) -> SignedUrlKeyRotation:
554
+ """Revoke every signed URL of the workspace at once: ``{ rotatedAt }``."""
555
+ result = self._client._request("POST", "/signed-urls/rotate-key", idempotent=False)
556
+ return cast(SignedUrlKeyRotation, unwrap(result, "data"))
557
+
558
+
559
+ class SocialAccounts(_Resource):
560
+ def list(self) -> List[SocialAccount]:
561
+ """The workspace's connected accounts (connect them in the app)."""
562
+ result = self._client._request("GET", "/social/accounts")
563
+ return cast(List[SocialAccount], unwrap(result, "accounts"))
564
+
565
+
566
+ class SocialPosts(_Resource):
567
+ def create(self, body: Optional[SocialPostInput] = None, **kwargs: Any) -> SocialPostCreated:
568
+ """Post now, at ``scheduledAt`` or as a ``draft``: ``{ post, checks }``.
569
+
570
+ Pass the API body as a dict, as keyword arguments, or both
571
+ (``template_id``, ``render_id``, ``media_urls`` and ``scheduled_at``
572
+ are accepted for their camelCase names).
573
+ """
574
+ payload = social_post_body(body, kwargs)
575
+ result = self._client._request("POST", "/social/posts", json_body=payload, idempotent=False)
576
+ return cast(SocialPostCreated, result.data)
577
+
578
+ def list(
579
+ self, *, status: Optional[str] = None, cursor: Optional[str] = None, limit: Optional[int] = None
580
+ ) -> SocialPostPage:
581
+ """``status``: ``queue``, ``drafts``, ``published``, ``attention``, ``canceled`` or a post status."""
582
+ params = {"status": status, "cursor": cursor, "limit": limit}
583
+ return cast(SocialPostPage, self._client._request("GET", "/social/posts", params=params).data)
584
+
585
+ def iter(self, *, status: Optional[str] = None, limit: Optional[int] = None) -> Iterator[SocialPost]:
586
+ cursor: Optional[str] = None
587
+ while True:
588
+ page = self.list(status=status, cursor=cursor, limit=limit)
589
+ yield from page["posts"]
590
+ cursor = page_cursor(page)
591
+ if cursor is None:
592
+ return
593
+
594
+ def get(self, post_id: str) -> SocialPost:
595
+ result = self._client._request("GET", f"/social/posts/{path_segment(post_id)}")
596
+ return cast(SocialPost, unwrap(result, "post"))
597
+
598
+ def cancel(self, post_id: str) -> SocialPost:
599
+ result = self._client._request(
600
+ "POST", f"/social/posts/{path_segment(post_id)}/cancel", idempotent=False
601
+ )
602
+ return cast(SocialPost, unwrap(result, "post"))
603
+
604
+ def retry(self, post_id: str, target_id: Optional[str] = None) -> SocialPost:
605
+ """Queue the failed accounts again (or just ``target_id``)."""
606
+ body = {"targetId": target_id} if target_id else {}
607
+ result = self._client._request(
608
+ "POST", f"/social/posts/{path_segment(post_id)}/retry", json_body=body, idempotent=False
609
+ )
610
+ return cast(SocialPost, unwrap(result, "post"))
611
+
612
+
613
+ class SocialAnalytics(_Resource):
614
+ """What the workspace's posts gained: impressions or views, reach, likes,
615
+ comments, shares, saves, clicks and engagement (``None`` when the
616
+ platforms in scope don't report one).
617
+
618
+ Every report takes ``from_`` and ``to`` (days, in the organization's
619
+ analytics time zone; default the last 28 days), and ``platform`` and
620
+ ``account_id`` (one or several).
621
+ """
622
+
623
+ def overview(
624
+ self,
625
+ *,
626
+ from_: Optional[Day] = None,
627
+ to: Optional[Day] = None,
628
+ platform: Optional[Many] = None,
629
+ account_id: Optional[Many] = None,
630
+ ) -> SocialAnalyticsOverview:
631
+ """Totals for the range, the same for the period before, and the change in percent."""
632
+ params = analytics_params(from_, to, platform, account_id)
633
+ return cast(SocialAnalyticsOverview, self._client._request("GET", "/social/analytics/overview", params=params).data)
634
+
635
+ def daily(
636
+ self,
637
+ *,
638
+ from_: Optional[Day] = None,
639
+ to: Optional[Day] = None,
640
+ platform: Optional[Many] = None,
641
+ account_id: Optional[Many] = None,
642
+ ) -> SocialAnalyticsDaily:
643
+ """One row per day, oldest first."""
644
+ params = analytics_params(from_, to, platform, account_id)
645
+ return cast(SocialAnalyticsDaily, self._client._request("GET", "/social/analytics/daily", params=params).data)
646
+
647
+ def insights(
648
+ self,
649
+ *,
650
+ from_: Optional[Day] = None,
651
+ to: Optional[Day] = None,
652
+ platform: Optional[Many] = None,
653
+ account_id: Optional[Many] = None,
654
+ ) -> SocialAnalyticsInsights:
655
+ """The top posts, the best weekday and hour to post, and each platform's numbers."""
656
+ params = analytics_params(from_, to, platform, account_id)
657
+ return cast(SocialAnalyticsInsights, self._client._request("GET", "/social/analytics/insights", params=params).data)
658
+
659
+
660
+ class Social:
661
+ """Social publishing: ``social.accounts``, ``social.posts`` and ``social.analytics``."""
662
+
663
+ def __init__(self, client: Client) -> None:
664
+ self.accounts = SocialAccounts(client)
665
+ self.posts = SocialPosts(client)
666
+ self.analytics = SocialAnalytics(client)
667
+
668
+
669
+ class WorkflowRuns(_Resource):
670
+ """A workflow's runs."""
671
+
672
+ def list(self, workflow_id: str, *, cursor: Optional[str] = None, limit: Optional[int] = None) -> WorkflowRunPage:
673
+ """One page, newest first: ``{ runs, pagination }``."""
674
+ params = {"cursor": cursor, "limit": limit}
675
+ result = self._client._request("GET", f"/workflows/{path_segment(workflow_id)}/runs", params=params)
676
+ return cast(WorkflowRunPage, result.data)
677
+
678
+ def iter(self, workflow_id: str, *, limit: Optional[int] = None) -> Iterator[WorkflowRun]:
679
+ cursor: Optional[str] = None
680
+ while True:
681
+ page = self.list(workflow_id, cursor=cursor, limit=limit)
682
+ yield from page["runs"]
683
+ cursor = page_cursor(page)
684
+ if cursor is None:
685
+ return
686
+
687
+ def get(self, workflow_id: str, run_id: str) -> WorkflowRunWithRows:
688
+ """The run with each row's result (at most 1,000 rows)."""
689
+ result = self._client._request("GET", f"/workflows/{path_segment(workflow_id)}/runs/{path_segment(run_id)}")
690
+ return cast(WorkflowRunWithRows, unwrap(result, "run"))
691
+
692
+ def cancel(self, workflow_id: str, run_id: str) -> WorkflowRun:
693
+ """Rows not started yet are skipped. A finished run raises :class:`ConflictError`."""
694
+ result = self._client._request(
695
+ "POST", f"/workflows/{path_segment(workflow_id)}/runs/{path_segment(run_id)}/cancel", idempotent=False
696
+ )
697
+ return cast(WorkflowRun, unwrap(result, "run"))
698
+
699
+ def wait(
700
+ self, workflow_id: str, run_id: str, *, timeout: float = DEFAULT_WAIT_TIMEOUT, poll_interval: float = 1.0
701
+ ) -> WorkflowRunWithRows:
702
+ """Poll until the run ends (``succeeded``, ``partial``, ``failed`` or ``canceled``) and return it.
703
+
704
+ A failed run is returned, not raised: check ``status`` and each row.
705
+ After ``timeout`` seconds raises :class:`WaitTimeoutError`.
706
+ """
707
+ run = self._client._poll(
708
+ run_id,
709
+ "Workflow run",
710
+ lambda: self.get(workflow_id, run_id),
711
+ lambda run: run["status"] in FINAL_RUN_STATUSES,
712
+ timeout,
713
+ poll_interval,
714
+ )
715
+ return cast(WorkflowRunWithRows, run)
716
+
717
+
718
+ class Workflows(_Resource):
719
+ """Workflows: rows from a sheet, a file, Airtable or a webhook, each
720
+ rendered with a template and delivered. Build them in the app or here."""
721
+
722
+ def __init__(self, client: Client) -> None:
723
+ super().__init__(client)
724
+ self.runs = WorkflowRuns(client)
725
+
726
+ def list(self) -> List[Workflow]:
727
+ """Most recently changed first (at most 200)."""
728
+ return cast(List[Workflow], unwrap(self._client._request("GET", "/workflows"), "workflows"))
729
+
730
+ def get(self, workflow_id: str) -> Workflow:
731
+ result = self._client._request("GET", f"/workflows/{path_segment(workflow_id)}")
732
+ return cast(Workflow, unwrap(result, "workflow"))
733
+
734
+ def create(self, body: Optional[WorkflowCreateInput] = None, **kwargs: Any) -> Workflow:
735
+ """A draft from a ``definition``, from an Explore ``starter``, or a blank one.
736
+
737
+ What it still needs before it can run is in ``problems``.
738
+ """
739
+ payload = workflow_body(body, kwargs)
740
+ result = self._client._request("POST", "/workflows", json_body=payload, idempotent=False)
741
+ return cast(Workflow, unwrap(result, "workflow"))
742
+
743
+ def update(self, workflow_id: str, body: Optional[WorkflowUpdateInput] = None, **kwargs: Any) -> Workflow:
744
+ """The fields sent replace the old ones. ``status="active"`` needs a complete definition."""
745
+ payload = workflow_body(body, kwargs)
746
+ result = self._client._request(
747
+ "PATCH", f"/workflows/{path_segment(workflow_id)}", json_body=payload, idempotent=True
748
+ )
749
+ return cast(Workflow, unwrap(result, "workflow"))
750
+
751
+ def delete(self, workflow_id: str) -> None:
752
+ """Delete the workflow and its run history. Renders and posts it made stay."""
753
+ self._client._request("DELETE", f"/workflows/{path_segment(workflow_id)}")
754
+
755
+ def run(self, workflow_id: str, *, payload: Any = None, max_rows: Optional[int] = None) -> WorkflowRun:
756
+ """Queue a run now (drafts too) and return it. Each row costs render credits.
757
+
758
+ ``payload``: rows for a webhook-payload source. ``max_rows``: render
759
+ only the first rows (a test run).
760
+ """
761
+ result = self._client._request(
762
+ "POST",
763
+ f"/workflows/{path_segment(workflow_id)}/run",
764
+ json_body=run_body(payload, max_rows),
765
+ idempotent=False,
766
+ )
767
+ return cast(WorkflowRun, unwrap(result, "run"))
768
+
769
+ def run_and_wait(
770
+ self,
771
+ workflow_id: str,
772
+ *,
773
+ payload: Any = None,
774
+ max_rows: Optional[int] = None,
775
+ timeout: float = DEFAULT_WAIT_TIMEOUT,
776
+ poll_interval: float = 1.0,
777
+ ) -> WorkflowRunWithRows:
778
+ """Queue a run and poll it until it ends; returns it with each row's result. Check ``status``."""
779
+ run = self.run(workflow_id, payload=payload, max_rows=max_rows)
780
+ return self.runs.wait(workflow_id, run["id"], timeout=timeout, poll_interval=poll_interval)
781
+
782
+ def rotate_webhook_url(self, workflow_id: str) -> str:
783
+ """A new incoming webhook URL. The old one stops working at once."""
784
+ result = self._client._request(
785
+ "POST", f"/workflows/{path_segment(workflow_id)}/webhook-token", idempotent=False
786
+ )
787
+ return cast(str, unwrap(result, "webhookUrl"))
788
+
789
+
790
+ class Ai(_Resource):
791
+ """AI calls that aren't renders. They spend AI credits, refunded when a call fails."""
792
+
793
+ def status(self) -> AiStatus:
794
+ """Whether AI runs, the price list and the organization's AI credits. Free."""
795
+ return cast(AiStatus, self._client._request("GET", "/ai/status").data)
796
+
797
+ def remove_background(
798
+ self,
799
+ *,
800
+ url: Optional[str] = None,
801
+ file: Optional[FileInput] = None,
802
+ filename: Optional[str] = None,
803
+ name: Optional[str] = None,
804
+ ) -> BackgroundRemoval:
805
+ """Cut the subject out of a picture and store a transparent PNG in the brand library.
806
+
807
+ Pass the picture's ``url``, or a ``file`` to upload (bytes, a
808
+ ``pathlib.Path`` or a binary file object; PNG, JPEG, GIF or WebP up to
809
+ 10 MB). The answer's ``url`` is ready for an image parameter. 1 AI credit.
810
+ """
811
+ upload = media_source(url, file, filename)
812
+ if upload is not None:
813
+ result = self._client._request(
814
+ "POST", "/images/remove-background", upload=upload, form={"name": name}, idempotent=False
815
+ )
816
+ else:
817
+ body = {"url": url, **({"name": name} if name else {})}
818
+ result = self._client._request("POST", "/images/remove-background", json_body=body, idempotent=False)
819
+ return cast(BackgroundRemoval, result.data)
820
+
821
+ def transcribe(
822
+ self,
823
+ *,
824
+ url: Optional[str] = None,
825
+ file: Optional[FileInput] = None,
826
+ filename: Optional[str] = None,
827
+ language: Optional[str] = None,
828
+ style: Optional[Literal["standard", "short"]] = None,
829
+ max_chars_per_line: Optional[int] = None,
830
+ max_lines: Optional[int] = None,
831
+ start: Optional[float] = None,
832
+ duration: Optional[float] = None,
833
+ offset: Optional[float] = None,
834
+ words: Optional[bool] = None,
835
+ ) -> Transcription:
836
+ """The speech in an audio file or a video's sound as subtitle cues, SRT and WebVTT.
837
+
838
+ Pass a ``url`` or a ``file`` (up to 100 MB). ``style="short"``: one
839
+ line of up to 24 characters. ``start``/``duration`` pick a window of
840
+ the file; ``offset`` moves the cues to where it sits on your video.
841
+ Pass ``cues`` as ``modifications["subtitles"]`` in an MP4 render.
842
+ 1 AI credit per minute of audio.
843
+ """
844
+ upload = media_source(url, file, filename)
845
+ fields = {
846
+ "language": language,
847
+ "style": style,
848
+ "maxCharsPerLine": max_chars_per_line,
849
+ "maxLines": max_lines,
850
+ "start": start,
851
+ "duration": duration,
852
+ "offset": offset,
853
+ "words": words,
854
+ }
855
+ if upload is not None:
856
+ result = self._client._request("POST", "/ai/transcribe", upload=upload, form=fields, idempotent=False)
857
+ else:
858
+ body = {"url": url, **{k: v for k, v in fields.items() if v is not None}}
859
+ result = self._client._request("POST", "/ai/transcribe", json_body=body, idempotent=False)
860
+ return cast(Transcription, result.data)
861
+
862
+
863
+ class WebhookSubscriptions(_Resource):
864
+ def list(self, *, cursor: Optional[str] = None, limit: Optional[int] = None) -> WebhookSubscriptionPage:
865
+ params = {"cursor": cursor, "limit": limit}
866
+ result = self._client._request("GET", "/webhooks/subscriptions", params=params)
867
+ return cast(WebhookSubscriptionPage, result.data)
868
+
869
+ def iter(self, *, limit: Optional[int] = None) -> Iterator[WebhookSubscription]:
870
+ cursor: Optional[str] = None
871
+ while True:
872
+ page = self.list(cursor=cursor, limit=limit)
873
+ yield from page["subscriptions"]
874
+ cursor = page_cursor(page)
875
+ if cursor is None:
876
+ return
877
+
878
+ def get(self, subscription_id: str) -> WebhookSubscription:
879
+ result = self._client._request("GET", f"/webhooks/subscriptions/{path_segment(subscription_id)}")
880
+ return cast(WebhookSubscription, unwrap(result, "subscription"))
881
+
882
+ def create(self, url: str, events: Sequence[WebhookEventType]) -> WebhookSubscriptionWithSecret:
883
+ """Subscribe ``url`` to ``events``. The ``signingSecret`` in the answer is shown once."""
884
+ body = {"url": url, "events": list(events)}
885
+ result = self._client._request("POST", "/webhooks/subscriptions", json_body=body, idempotent=False)
886
+ return cast(WebhookSubscriptionWithSecret, result.data)
887
+
888
+ def delete(self, subscription_id: str) -> None:
889
+ self._client._request("DELETE", f"/webhooks/subscriptions/{path_segment(subscription_id)}")
890
+
891
+ def test(self, subscription_id: str, event_type: Optional[WebhookEventType] = None) -> WebhookTestResult:
892
+ """Queue a sample delivery (``event_type`` defaults to the subscription's first event)."""
893
+ body = {"eventType": event_type} if event_type else {}
894
+ result = self._client._request(
895
+ "POST",
896
+ f"/webhooks/subscriptions/{path_segment(subscription_id)}/test",
897
+ json_body=body,
898
+ idempotent=False,
899
+ )
900
+ return cast(WebhookTestResult, result.data)
901
+
902
+ def rotate_secret(self, subscription_id: str) -> WebhookSubscriptionWithSecret:
903
+ result = self._client._request(
904
+ "POST", f"/webhooks/subscriptions/{path_segment(subscription_id)}/rotate-secret", idempotent=False
905
+ )
906
+ return cast(WebhookSubscriptionWithSecret, result.data)
907
+
908
+
909
+ class Webhooks:
910
+ """``webhooks.subscriptions``, plus the signature helpers of :mod:`jamframe.webhooks`."""
911
+
912
+ verify_signature = staticmethod(_webhooks.verify_signature)
913
+ construct_event = staticmethod(_webhooks.construct_event)
914
+
915
+ def __init__(self, client: Client) -> None:
916
+ self.subscriptions = WebhookSubscriptions(client)