framera 1.0.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.
framera/__init__.py ADDED
@@ -0,0 +1,63 @@
1
+ """Framera API client for Python: films, avatars, UGC ads, images, audio, tools and swaps.
2
+
3
+ from framera import Framera
4
+
5
+ client = Framera() # reads FRAMERA_API_KEY
6
+ job = client.videos.create(prompt="…", duration_seconds=30)
7
+ done = client.jobs.wait(job["id"])
8
+ print(done["price"]["amount"], done["outputs"][0]["url"])
9
+ """
10
+
11
+ from . import types, webhooks
12
+ from ._base_client import DEFAULT_BASE_URL
13
+ from ._client import AsyncFramera, Framera
14
+ from ._errors import (
15
+ APIConnectionError,
16
+ APITimeoutError,
17
+ AuthenticationError,
18
+ ConflictError,
19
+ ContentRefusedError,
20
+ FrameraError,
21
+ IdempotencyConflictError,
22
+ InsufficientBalanceError,
23
+ InvalidRequestError,
24
+ JobNotCancellableError,
25
+ ModelPausedError,
26
+ NotFoundError,
27
+ PermissionDeniedError,
28
+ RateLimitError,
29
+ ServerError,
30
+ WaitTimeoutError,
31
+ WebhookVerificationError,
32
+ )
33
+ from ._version import __version__
34
+ from .pagination import AsyncPage, AsyncPaginator, SyncPage
35
+
36
+ __all__ = [
37
+ "__version__",
38
+ "DEFAULT_BASE_URL",
39
+ "Framera",
40
+ "AsyncFramera",
41
+ "SyncPage",
42
+ "AsyncPage",
43
+ "AsyncPaginator",
44
+ "types",
45
+ "webhooks",
46
+ "FrameraError",
47
+ "InvalidRequestError",
48
+ "AuthenticationError",
49
+ "InsufficientBalanceError",
50
+ "PermissionDeniedError",
51
+ "NotFoundError",
52
+ "ConflictError",
53
+ "IdempotencyConflictError",
54
+ "JobNotCancellableError",
55
+ "ContentRefusedError",
56
+ "RateLimitError",
57
+ "ModelPausedError",
58
+ "ServerError",
59
+ "APIConnectionError",
60
+ "APITimeoutError",
61
+ "WaitTimeoutError",
62
+ "WebhookVerificationError",
63
+ ]
@@ -0,0 +1,323 @@
1
+ """HTTP transport: auth, JSON, retries with backoff, Retry-After, idempotency keys."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import random
9
+ import time
10
+ import uuid
11
+ from typing import IO, Any, Dict, Mapping, Optional, Union
12
+
13
+ import httpx
14
+
15
+ from ._errors import (
16
+ APIConnectionError,
17
+ APITimeoutError,
18
+ AuthenticationError,
19
+ FrameraError,
20
+ make_error,
21
+ parse_retry_after,
22
+ )
23
+ from ._version import __version__
24
+
25
+ DEFAULT_BASE_URL = "https://api.framera.ai"
26
+ DEFAULT_TIMEOUT = 60.0
27
+ DEFAULT_MAX_RETRIES = 2
28
+ MAX_RETRY_DELAY = 60.0
29
+ USER_AGENT = f"framera-python/{__version__}"
30
+
31
+ # Module-level so tests can swap them out.
32
+ _sleep = time.sleep
33
+ _asleep = asyncio.sleep
34
+
35
+ FileSource = Union[bytes, bytearray, memoryview, str, "os.PathLike[str]", IO[bytes]]
36
+
37
+ # The file types POST /v1/uploads accepts, by extension.
38
+ _MIME = {
39
+ "png": "image/png",
40
+ "jpg": "image/jpeg",
41
+ "jpeg": "image/jpeg",
42
+ "webp": "image/webp",
43
+ "mp3": "audio/mpeg",
44
+ "wav": "audio/wav",
45
+ "m4a": "audio/mp4",
46
+ "aac": "audio/aac",
47
+ "mp4": "video/mp4",
48
+ "mov": "video/quicktime",
49
+ }
50
+
51
+
52
+ def guess_content_type(filename: str) -> str:
53
+ ext = filename.rsplit(".", 1)[-1].lower() if "." in filename else ""
54
+ return _MIME.get(ext, "application/octet-stream")
55
+
56
+
57
+ def read_source(source: FileSource, filename: Optional[str]) -> "tuple[bytes, str]":
58
+ """Bytes and a file name from bytes, a path, or a binary file object."""
59
+ if isinstance(source, (bytes, bytearray, memoryview)):
60
+ return bytes(source), filename or "upload"
61
+ if isinstance(source, (str, os.PathLike)):
62
+ path = os.fspath(source)
63
+ with open(path, "rb") as fh:
64
+ return fh.read(), filename or os.path.basename(path)
65
+ data = source.read()
66
+ if isinstance(data, str):
67
+ data = data.encode("utf-8")
68
+ name = filename or os.path.basename(str(getattr(source, "name", "") or "")) or "upload"
69
+ return bytes(data), name
70
+
71
+
72
+ def backoff(attempt: int) -> float:
73
+ base: float = min(8.0, 0.5 * float(2**attempt))
74
+ return base * (0.75 + random.random() * 0.5)
75
+
76
+
77
+ def retry_delay(attempt: int, headers: Optional[Mapping[str, str]]) -> float:
78
+ wait = parse_retry_after(headers)
79
+ return backoff(attempt) if wait is None else min(wait, MAX_RETRY_DELAY)
80
+
81
+
82
+ def strip_none(params: Mapping[str, Any]) -> Dict[str, Any]:
83
+ return {k: v for k, v in params.items() if v is not None}
84
+
85
+
86
+ def new_idempotency_key() -> str:
87
+ return str(uuid.uuid4())
88
+
89
+
90
+ def should_retry(status: int, can_retry: bool) -> bool:
91
+ """A 429 was refused before anything ran, so it is always safe to repeat; a 5xx only when the call is."""
92
+ return status == 429 or (status >= 500 and can_retry)
93
+
94
+
95
+ def error_from_response(response: httpx.Response) -> FrameraError:
96
+ try:
97
+ payload = response.json()
98
+ except ValueError:
99
+ payload = None
100
+ err = payload.get("error") if isinstance(payload, dict) else None
101
+ err = err if isinstance(err, dict) else {}
102
+ return make_error(
103
+ response.status_code,
104
+ err.get("code"),
105
+ err.get("message") or f"Framera API answered HTTP {response.status_code}",
106
+ err.get("details"),
107
+ dict(response.headers),
108
+ )
109
+
110
+
111
+ def _put_headers(content_type: str, data: bytes) -> Dict[str, str]:
112
+ return {"Content-Type": content_type, "Content-Length": str(len(data))}
113
+
114
+
115
+ def decode(response: httpx.Response) -> Any:
116
+ if not response.content:
117
+ return {}
118
+ return json.loads(response.content)
119
+
120
+
121
+ class _BaseClient:
122
+ def __init__(
123
+ self,
124
+ api_key: Optional[str],
125
+ base_url: Optional[str],
126
+ timeout: Optional[float],
127
+ max_retries: Optional[int],
128
+ ) -> None:
129
+ key = api_key if api_key is not None else os.environ.get("FRAMERA_API_KEY")
130
+ if not key:
131
+ raise AuthenticationError(
132
+ "Pass api_key or set FRAMERA_API_KEY. Create a key in the Framera developer console.",
133
+ code="missing_api_key",
134
+ )
135
+ self.api_key = key
136
+ self.base_url = (base_url or os.environ.get("FRAMERA_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
137
+ self.timeout = DEFAULT_TIMEOUT if timeout is None else timeout
138
+ self.max_retries = DEFAULT_MAX_RETRIES if max_retries is None else max_retries
139
+
140
+ def _headers(self, idempotency_key: Optional[str], has_body: bool) -> Dict[str, str]:
141
+ headers = {
142
+ "Authorization": f"Bearer {self.api_key}",
143
+ "Accept": "application/json",
144
+ "User-Agent": USER_AGENT,
145
+ }
146
+ if has_body:
147
+ headers["Content-Type"] = "application/json"
148
+ if idempotency_key:
149
+ headers["Idempotency-Key"] = idempotency_key
150
+ return headers
151
+
152
+ def _url(self, path: str) -> str:
153
+ return f"{self.base_url}{path}"
154
+
155
+ @staticmethod
156
+ def _query(query: Optional[Mapping[str, Any]]) -> Optional[Dict[str, Any]]:
157
+ if not query:
158
+ return None
159
+ return {k: v for k, v in query.items() if v is not None and v != ""} or None
160
+
161
+ @staticmethod
162
+ def _retriable(method: str, retriable: Optional[bool]) -> bool:
163
+ """Safe to repeat after a 5xx or a network failure: GETs and DELETEs, plus the calls that say so
164
+ (creates with an Idempotency-Key, quotes, cancels, updates, upload reservations)."""
165
+ if retriable is not None:
166
+ return retriable
167
+ return method in ("GET", "DELETE")
168
+
169
+
170
+ class SyncTransport(_BaseClient):
171
+ def __init__(
172
+ self,
173
+ api_key: Optional[str] = None,
174
+ base_url: Optional[str] = None,
175
+ timeout: Optional[float] = None,
176
+ max_retries: Optional[int] = None,
177
+ http_client: Optional[httpx.Client] = None,
178
+ ) -> None:
179
+ super().__init__(api_key, base_url, timeout, max_retries)
180
+ self._owns_http = http_client is None
181
+ self._http = http_client or httpx.Client(timeout=self.timeout)
182
+
183
+ def close(self) -> None:
184
+ if self._owns_http:
185
+ self._http.close()
186
+
187
+ def request(
188
+ self,
189
+ method: str,
190
+ path: str,
191
+ *,
192
+ body: Optional[Mapping[str, Any]] = None,
193
+ query: Optional[Mapping[str, Any]] = None,
194
+ idempotency_key: Optional[str] = None,
195
+ retriable: Optional[bool] = None,
196
+ ) -> Any:
197
+ can_retry = self._retriable(method, retriable)
198
+ headers = self._headers(idempotency_key, body is not None)
199
+ content = json.dumps(body).encode("utf-8") if body is not None else None
200
+ attempt = 0
201
+ while True:
202
+ try:
203
+ response = self._http.request(
204
+ method, self._url(path), headers=headers, content=content, params=self._query(query), timeout=self.timeout
205
+ )
206
+ except httpx.TimeoutException as exc:
207
+ if can_retry and attempt < self.max_retries:
208
+ _sleep(backoff(attempt))
209
+ attempt += 1
210
+ continue
211
+ raise APITimeoutError(f"Request timed out after {self.timeout} s", code="timeout") from exc
212
+ except httpx.TransportError as exc:
213
+ if can_retry and attempt < self.max_retries:
214
+ _sleep(backoff(attempt))
215
+ attempt += 1
216
+ continue
217
+ raise APIConnectionError(str(exc) or type(exc).__name__, code="network_error") from exc
218
+
219
+ if response.is_success:
220
+ return decode(response)
221
+ if should_retry(response.status_code, can_retry) and attempt < self.max_retries:
222
+ _sleep(retry_delay(attempt, response.headers))
223
+ attempt += 1
224
+ continue
225
+ raise error_from_response(response)
226
+
227
+ def put_bytes(self, url: str, data: bytes, content_type: str) -> None:
228
+ """PUT to a signed URL (no API key) with exactly the reserved Content-Type and Content-Length,
229
+ retrying network failures and 5xx."""
230
+ attempt = 0
231
+ while True:
232
+ try:
233
+ response = self._http.put(url, content=data, headers=_put_headers(content_type, data), timeout=self.timeout * 5)
234
+ except httpx.TransportError as exc:
235
+ if attempt < self.max_retries:
236
+ _sleep(backoff(attempt))
237
+ attempt += 1
238
+ continue
239
+ raise APIConnectionError(f"Upload failed: {exc}", code="network_error") from exc
240
+ if response.is_success:
241
+ return
242
+ if response.status_code >= 500 and attempt < self.max_retries:
243
+ _sleep(backoff(attempt))
244
+ attempt += 1
245
+ continue
246
+ raise make_error(response.status_code, None, f"Upload PUT answered HTTP {response.status_code}", response.text)
247
+
248
+
249
+ class AsyncTransport(_BaseClient):
250
+ def __init__(
251
+ self,
252
+ api_key: Optional[str] = None,
253
+ base_url: Optional[str] = None,
254
+ timeout: Optional[float] = None,
255
+ max_retries: Optional[int] = None,
256
+ http_client: Optional[httpx.AsyncClient] = None,
257
+ ) -> None:
258
+ super().__init__(api_key, base_url, timeout, max_retries)
259
+ self._owns_http = http_client is None
260
+ self._http = http_client or httpx.AsyncClient(timeout=self.timeout)
261
+
262
+ async def aclose(self) -> None:
263
+ if self._owns_http:
264
+ await self._http.aclose()
265
+
266
+ async def request(
267
+ self,
268
+ method: str,
269
+ path: str,
270
+ *,
271
+ body: Optional[Mapping[str, Any]] = None,
272
+ query: Optional[Mapping[str, Any]] = None,
273
+ idempotency_key: Optional[str] = None,
274
+ retriable: Optional[bool] = None,
275
+ ) -> Any:
276
+ can_retry = self._retriable(method, retriable)
277
+ headers = self._headers(idempotency_key, body is not None)
278
+ content = json.dumps(body).encode("utf-8") if body is not None else None
279
+ attempt = 0
280
+ while True:
281
+ try:
282
+ response = await self._http.request(
283
+ method, self._url(path), headers=headers, content=content, params=self._query(query), timeout=self.timeout
284
+ )
285
+ except httpx.TimeoutException as exc:
286
+ if can_retry and attempt < self.max_retries:
287
+ await _asleep(backoff(attempt))
288
+ attempt += 1
289
+ continue
290
+ raise APITimeoutError(f"Request timed out after {self.timeout} s", code="timeout") from exc
291
+ except httpx.TransportError as exc:
292
+ if can_retry and attempt < self.max_retries:
293
+ await _asleep(backoff(attempt))
294
+ attempt += 1
295
+ continue
296
+ raise APIConnectionError(str(exc) or type(exc).__name__, code="network_error") from exc
297
+
298
+ if response.is_success:
299
+ return decode(response)
300
+ if should_retry(response.status_code, can_retry) and attempt < self.max_retries:
301
+ await _asleep(retry_delay(attempt, response.headers))
302
+ attempt += 1
303
+ continue
304
+ raise error_from_response(response)
305
+
306
+ async def put_bytes(self, url: str, data: bytes, content_type: str) -> None:
307
+ attempt = 0
308
+ while True:
309
+ try:
310
+ response = await self._http.put(url, content=data, headers=_put_headers(content_type, data), timeout=self.timeout * 5)
311
+ except httpx.TransportError as exc:
312
+ if attempt < self.max_retries:
313
+ await _asleep(backoff(attempt))
314
+ attempt += 1
315
+ continue
316
+ raise APIConnectionError(f"Upload failed: {exc}", code="network_error") from exc
317
+ if response.is_success:
318
+ return
319
+ if response.status_code >= 500 and attempt < self.max_retries:
320
+ await _asleep(backoff(attempt))
321
+ attempt += 1
322
+ continue
323
+ raise make_error(response.status_code, None, f"Upload PUT answered HTTP {response.status_code}", response.text)
framera/_client.py ADDED
@@ -0,0 +1,142 @@
1
+ """The two clients: ``Framera`` (sync) and ``AsyncFramera`` (asyncio)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from types import TracebackType
6
+ from typing import Awaitable, Optional, Type
7
+
8
+ import httpx
9
+
10
+ from ._base_client import AsyncTransport, SyncTransport
11
+ from .resources import (
12
+ AsyncEvents,
13
+ AsyncJobs,
14
+ AsyncUploads,
15
+ AsyncWebhookEndpoints,
16
+ AsyncWebhooks,
17
+ Audio,
18
+ Avatars,
19
+ BalanceResource,
20
+ Events,
21
+ Images,
22
+ Jobs,
23
+ Models,
24
+ Quotes,
25
+ Swap,
26
+ Tools,
27
+ Ugc,
28
+ Uploads,
29
+ Videos,
30
+ WebhookEndpoints,
31
+ Webhooks,
32
+ )
33
+ from .types import Balance, Job, ModelList, Quote
34
+
35
+ __all__ = ["Framera", "AsyncFramera"]
36
+
37
+
38
+ class Framera:
39
+ """Sync client.
40
+
41
+ >>> from framera import Framera
42
+ >>> client = Framera() # reads FRAMERA_API_KEY
43
+ >>> job = client.videos.create(model="odyssey-1-ultra", prompt="…", duration_seconds=30)
44
+ >>> done = client.jobs.wait(job["id"])
45
+
46
+ ``api_key`` defaults to ``FRAMERA_API_KEY``; ``base_url`` to https://api.framera.ai;
47
+ ``timeout`` (seconds) to 60; ``max_retries`` (on 429, 5xx and network errors) to 2.
48
+ Pass your own ``http_client`` (an ``httpx.Client``) for proxies or tests.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ *,
54
+ api_key: Optional[str] = None,
55
+ base_url: Optional[str] = None,
56
+ timeout: Optional[float] = None,
57
+ max_retries: Optional[int] = None,
58
+ http_client: Optional[httpx.Client] = None,
59
+ ) -> None:
60
+ self._transport = SyncTransport(api_key, base_url, timeout, max_retries, http_client)
61
+ t = self._transport
62
+ self.models: Models[ModelList] = Models(t)
63
+ self.quotes: Quotes[Quote] = Quotes(t)
64
+ self.videos: Videos[Job] = Videos(t)
65
+ self.avatars: Avatars[Job] = Avatars(t)
66
+ self.ugc: Ugc[Job] = Ugc(t)
67
+ self.images: Images[Job] = Images(t)
68
+ self.tools: Tools[Job] = Tools(t)
69
+ self.audio: Audio[Job] = Audio(t)
70
+ self.swap: Swap[Job] = Swap(t)
71
+ self.uploads = Uploads(t)
72
+ self.jobs = Jobs(t)
73
+ self.balance: BalanceResource[Balance] = BalanceResource(t)
74
+ self.webhook_endpoints = WebhookEndpoints(t)
75
+ self.events = Events(t)
76
+ self.webhooks = Webhooks(t)
77
+
78
+ @property
79
+ def base_url(self) -> str:
80
+ return self._transport.base_url
81
+
82
+ def close(self) -> None:
83
+ self._transport.close()
84
+
85
+ def __enter__(self) -> "Framera":
86
+ return self
87
+
88
+ def __exit__(
89
+ self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]
90
+ ) -> None:
91
+ self.close()
92
+
93
+
94
+ class AsyncFramera:
95
+ """Asyncio client: the same resources as :class:`Framera`, every call awaited.
96
+
97
+ >>> async with AsyncFramera() as client:
98
+ ... job = await client.videos.create(model="odyssey-1-ultra", prompt="…", duration_seconds=30)
99
+ ... done = await client.jobs.wait(job["id"])
100
+ """
101
+
102
+ def __init__(
103
+ self,
104
+ *,
105
+ api_key: Optional[str] = None,
106
+ base_url: Optional[str] = None,
107
+ timeout: Optional[float] = None,
108
+ max_retries: Optional[int] = None,
109
+ http_client: Optional[httpx.AsyncClient] = None,
110
+ ) -> None:
111
+ self._transport = AsyncTransport(api_key, base_url, timeout, max_retries, http_client)
112
+ t = self._transport
113
+ self.models: Models[Awaitable[ModelList]] = Models(t)
114
+ self.quotes: Quotes[Awaitable[Quote]] = Quotes(t)
115
+ self.videos: Videos[Awaitable[Job]] = Videos(t)
116
+ self.avatars: Avatars[Awaitable[Job]] = Avatars(t)
117
+ self.ugc: Ugc[Awaitable[Job]] = Ugc(t)
118
+ self.images: Images[Awaitable[Job]] = Images(t)
119
+ self.tools: Tools[Awaitable[Job]] = Tools(t)
120
+ self.audio: Audio[Awaitable[Job]] = Audio(t)
121
+ self.swap: Swap[Awaitable[Job]] = Swap(t)
122
+ self.uploads = AsyncUploads(t)
123
+ self.jobs = AsyncJobs(t)
124
+ self.balance: BalanceResource[Awaitable[Balance]] = BalanceResource(t)
125
+ self.webhook_endpoints = AsyncWebhookEndpoints(t)
126
+ self.events = AsyncEvents(t)
127
+ self.webhooks = AsyncWebhooks(t)
128
+
129
+ @property
130
+ def base_url(self) -> str:
131
+ return self._transport.base_url
132
+
133
+ async def aclose(self) -> None:
134
+ await self._transport.aclose()
135
+
136
+ async def __aenter__(self) -> "AsyncFramera":
137
+ return self
138
+
139
+ async def __aexit__(
140
+ self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]
141
+ ) -> None:
142
+ await self.aclose()