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