fal-client 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.
- fal_client/__init__.py +37 -0
- fal_client/auth.py +21 -0
- fal_client/client.py +323 -0
- fal_client/py.typed +0 -0
- fal_client-0.1.0.dist-info/METADATA +18 -0
- fal_client-0.1.0.dist-info/RECORD +8 -0
- fal_client-0.1.0.dist-info/WHEEL +5 -0
- fal_client-0.1.0.dist-info/top_level.txt +1 -0
fal_client/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
from fal_client.client import (
|
|
2
|
+
AsyncClient,
|
|
3
|
+
SyncClient,
|
|
4
|
+
Status,
|
|
5
|
+
Queued,
|
|
6
|
+
InProgress,
|
|
7
|
+
Completed,
|
|
8
|
+
SyncRequestHandle,
|
|
9
|
+
AsyncRequestHandle,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"SyncClient",
|
|
14
|
+
"AsyncClient",
|
|
15
|
+
"Status",
|
|
16
|
+
"Queued",
|
|
17
|
+
"InProgress",
|
|
18
|
+
"Completed",
|
|
19
|
+
"SyncRequestHandle",
|
|
20
|
+
"AsyncRequestHandle",
|
|
21
|
+
"run",
|
|
22
|
+
"submit",
|
|
23
|
+
"stream",
|
|
24
|
+
"run_async",
|
|
25
|
+
"submit_async",
|
|
26
|
+
"stream_async",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
sync_client = SyncClient()
|
|
30
|
+
run = sync_client.run
|
|
31
|
+
submit = sync_client.submit
|
|
32
|
+
stream = sync_client.stream
|
|
33
|
+
|
|
34
|
+
async_client = AsyncClient()
|
|
35
|
+
run_async = async_client.run
|
|
36
|
+
submit_async = async_client.submit
|
|
37
|
+
stream_async = async_client.stream
|
fal_client/auth.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class MissingCredentialsError(Exception):
|
|
5
|
+
pass
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
FAL_RUN_HOST = os.environ.get("FAL_RUN_HOST", "fal.run")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def fetch_credentials() -> str:
|
|
12
|
+
if key := os.getenv("FAL_KEY"):
|
|
13
|
+
return key
|
|
14
|
+
elif (key_id := os.getenv("FAL_KEY_ID")) and (
|
|
15
|
+
fal_key_secret := os.getenv("FAL_KEY_SECRET")
|
|
16
|
+
):
|
|
17
|
+
return f"{key_id}:{fal_key_secret}"
|
|
18
|
+
else:
|
|
19
|
+
raise MissingCredentialsError(
|
|
20
|
+
"Please set the FAL_KEY environment variable to your API key, or set the FAL_KEY_ID and FAL_KEY_SECRET environment variables."
|
|
21
|
+
)
|
fal_client/client.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import os
|
|
5
|
+
import httpx
|
|
6
|
+
import mimetypes
|
|
7
|
+
from httpx_sse import aconnect_sse, connect_sse
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from functools import cached_property
|
|
10
|
+
from fal_client.auth import FAL_RUN_HOST, fetch_credentials
|
|
11
|
+
from typing import Any, AsyncIterator, Iterator, TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from PIL import Image
|
|
15
|
+
|
|
16
|
+
AnyJSON = dict[str, Any]
|
|
17
|
+
|
|
18
|
+
RUN_URL_FORMAT = f"https://{FAL_RUN_HOST}/"
|
|
19
|
+
QUEUE_URL_FORMAT = f"https://queue.{FAL_RUN_HOST}/"
|
|
20
|
+
REALTIME_URL_FORMAT = f"wss://{FAL_RUN_HOST}/"
|
|
21
|
+
CDN_URL = "https://fal.media"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Status: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Queued(Status):
|
|
30
|
+
position: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class InProgress(Status):
|
|
35
|
+
logs: list[dict[str, Any]] | None = field()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Completed(Status):
|
|
40
|
+
logs: list[dict[str, Any]] | None = field()
|
|
41
|
+
metrics: dict[str, Any] = field()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class _BaseRequestHandle:
|
|
46
|
+
request_id: str
|
|
47
|
+
response_url: str = field(repr=False)
|
|
48
|
+
status_url: str = field(repr=False)
|
|
49
|
+
cancel_url: str = field(repr=False)
|
|
50
|
+
|
|
51
|
+
def parse_status(self, data: AnyJSON) -> Status:
|
|
52
|
+
if data["status"] == "IN_QUEUE":
|
|
53
|
+
return Queued(position=data["queue_position"])
|
|
54
|
+
elif data["status"] == "IN_PROGRESS":
|
|
55
|
+
return InProgress(logs=data["logs"])
|
|
56
|
+
elif data["status"] == "COMPLETED":
|
|
57
|
+
return Completed(logs=data["logs"], metrics=data["metrics"])
|
|
58
|
+
else:
|
|
59
|
+
raise ValueError(f"Unknown status: {data['status']}")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class SyncRequestHandle(_BaseRequestHandle):
|
|
64
|
+
client: httpx.Client = field(repr=False)
|
|
65
|
+
|
|
66
|
+
def status(self, *, with_logs: bool = False) -> Status:
|
|
67
|
+
"""Checks the status of the request. If `with_logs` is True, logs will be
|
|
68
|
+
included in the response."""
|
|
69
|
+
|
|
70
|
+
response = self.client.get(
|
|
71
|
+
self.status_url,
|
|
72
|
+
params={
|
|
73
|
+
"logs": with_logs,
|
|
74
|
+
},
|
|
75
|
+
)
|
|
76
|
+
response.raise_for_status()
|
|
77
|
+
|
|
78
|
+
return self.parse_status(response.json())
|
|
79
|
+
|
|
80
|
+
def iter_events(self, *, with_logs: bool = False) -> Iterator[Status]:
|
|
81
|
+
"""Yield all events regarding the given task till its completed."""
|
|
82
|
+
while True:
|
|
83
|
+
status = self.status(with_logs=with_logs)
|
|
84
|
+
yield status
|
|
85
|
+
if isinstance(status, Completed):
|
|
86
|
+
break
|
|
87
|
+
|
|
88
|
+
def get(self) -> AnyJSON:
|
|
89
|
+
"""Wait till the request is completed and return the result."""
|
|
90
|
+
for _ in self.iter_events(with_logs=False):
|
|
91
|
+
continue
|
|
92
|
+
|
|
93
|
+
response = self.client.get(self.response_url)
|
|
94
|
+
response.raise_for_status()
|
|
95
|
+
return response.json()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class AsyncRequestHandle(_BaseRequestHandle):
|
|
100
|
+
client: httpx.AsyncClient = field(repr=False)
|
|
101
|
+
|
|
102
|
+
async def status(self, *, with_logs: bool = False) -> Status:
|
|
103
|
+
"""Checks the status of the request. If `with_logs` is True, logs will be
|
|
104
|
+
included in the response."""
|
|
105
|
+
|
|
106
|
+
response = await self.client.get(
|
|
107
|
+
self.status_url,
|
|
108
|
+
params={
|
|
109
|
+
"logs": with_logs,
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
response.raise_for_status()
|
|
113
|
+
|
|
114
|
+
return self.parse_status(response.json())
|
|
115
|
+
|
|
116
|
+
async def iter_events(self, *, with_logs: bool = False) -> AsyncIterator[Status]:
|
|
117
|
+
"""Yield all events regarding the given task till its completed."""
|
|
118
|
+
while True:
|
|
119
|
+
status = await self.status(with_logs=with_logs)
|
|
120
|
+
yield status
|
|
121
|
+
if isinstance(status, Completed):
|
|
122
|
+
break
|
|
123
|
+
|
|
124
|
+
async def get(self) -> AnyJSON:
|
|
125
|
+
"""Wait till the request is completed and return the result."""
|
|
126
|
+
async for _ in self.iter_events(with_logs=False):
|
|
127
|
+
continue
|
|
128
|
+
|
|
129
|
+
response = await self.client.get(self.response_url)
|
|
130
|
+
response.raise_for_status()
|
|
131
|
+
return response.json()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass(frozen=True)
|
|
135
|
+
class AsyncClient:
|
|
136
|
+
key: str = field(default_factory=fetch_credentials, repr=False)
|
|
137
|
+
default_timeout: float = 60.0
|
|
138
|
+
|
|
139
|
+
@cached_property
|
|
140
|
+
def client(self) -> httpx.AsyncClient:
|
|
141
|
+
return httpx.AsyncClient(headers={"Authorization": f"Key {self.key}"})
|
|
142
|
+
|
|
143
|
+
async def run(
|
|
144
|
+
self,
|
|
145
|
+
application: str,
|
|
146
|
+
data: AnyJSON,
|
|
147
|
+
*,
|
|
148
|
+
path: str = "",
|
|
149
|
+
) -> AnyJSON:
|
|
150
|
+
url = RUN_URL_FORMAT + application
|
|
151
|
+
if path:
|
|
152
|
+
url += "/" + path.lstrip("/")
|
|
153
|
+
|
|
154
|
+
response = await self.client.post(
|
|
155
|
+
url,
|
|
156
|
+
json=data,
|
|
157
|
+
timeout=self.default_timeout,
|
|
158
|
+
)
|
|
159
|
+
response.raise_for_status()
|
|
160
|
+
return response.json()
|
|
161
|
+
|
|
162
|
+
async def submit(
|
|
163
|
+
self,
|
|
164
|
+
application: str,
|
|
165
|
+
data: AnyJSON,
|
|
166
|
+
*,
|
|
167
|
+
path: str = "",
|
|
168
|
+
) -> AsyncRequestHandle:
|
|
169
|
+
url = QUEUE_URL_FORMAT + application
|
|
170
|
+
if path:
|
|
171
|
+
url += "/" + path.lstrip("/")
|
|
172
|
+
|
|
173
|
+
response = await self.client.post(
|
|
174
|
+
url,
|
|
175
|
+
json=data,
|
|
176
|
+
timeout=self.default_timeout,
|
|
177
|
+
)
|
|
178
|
+
response.raise_for_status()
|
|
179
|
+
|
|
180
|
+
data = response.json()
|
|
181
|
+
return AsyncRequestHandle(
|
|
182
|
+
request_id=data["request_id"],
|
|
183
|
+
response_url=data["response_url"],
|
|
184
|
+
status_url=data["status_url"],
|
|
185
|
+
cancel_url=data["cancel_url"],
|
|
186
|
+
client=self.client,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
async def stream(
|
|
190
|
+
self,
|
|
191
|
+
application: str,
|
|
192
|
+
data: AnyJSON,
|
|
193
|
+
*,
|
|
194
|
+
path: str = "/stream",
|
|
195
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
196
|
+
url = RUN_URL_FORMAT + application
|
|
197
|
+
if path:
|
|
198
|
+
url += "/" + path.lstrip("/")
|
|
199
|
+
|
|
200
|
+
async with aconnect_sse(self.client, "POST", url, json=data) as events:
|
|
201
|
+
async for event in events.aiter_sse():
|
|
202
|
+
yield event.json()
|
|
203
|
+
|
|
204
|
+
async def upload(self, data: str | bytes, content_type: str) -> str:
|
|
205
|
+
response = await self.client.post(
|
|
206
|
+
CDN_URL + "/files/upload",
|
|
207
|
+
data=data,
|
|
208
|
+
headers={"Content-Type": content_type},
|
|
209
|
+
)
|
|
210
|
+
response.raise_for_status()
|
|
211
|
+
|
|
212
|
+
return response.json()["access_url"]
|
|
213
|
+
|
|
214
|
+
async def upload_file(self, path: os.PathLike) -> str:
|
|
215
|
+
mime_type, _ = mimetypes.guess_type(path)
|
|
216
|
+
if mime_type is None:
|
|
217
|
+
mime_type = "application/octet-stream"
|
|
218
|
+
|
|
219
|
+
with open(path, "rb") as file:
|
|
220
|
+
return await self.upload(file.read(), mime_type)
|
|
221
|
+
|
|
222
|
+
async def upload_image(self, image: Image.Image, format: str = "jpeg") -> str:
|
|
223
|
+
with io.BytesIO() as buffer:
|
|
224
|
+
image.save(buffer, format=format)
|
|
225
|
+
return await self.upload(buffer.getvalue(), f"image/{format}")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
@dataclass(frozen=True)
|
|
229
|
+
class SyncClient:
|
|
230
|
+
key: str = field(default_factory=fetch_credentials, repr=False)
|
|
231
|
+
default_timeout: float = 60.0
|
|
232
|
+
|
|
233
|
+
@cached_property
|
|
234
|
+
def client(self) -> httpx.Client:
|
|
235
|
+
return httpx.Client(
|
|
236
|
+
headers={"Authorization": f"Key {self.key}"},
|
|
237
|
+
timeout=self.default_timeout,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
def run(
|
|
241
|
+
self,
|
|
242
|
+
application: str,
|
|
243
|
+
data: AnyJSON,
|
|
244
|
+
*,
|
|
245
|
+
path: str = "",
|
|
246
|
+
timeout: float | None = None,
|
|
247
|
+
) -> AnyJSON:
|
|
248
|
+
url = RUN_URL_FORMAT + application
|
|
249
|
+
if path:
|
|
250
|
+
url += "/" + path.lstrip("/")
|
|
251
|
+
|
|
252
|
+
response = self.client.post(
|
|
253
|
+
url,
|
|
254
|
+
json=data,
|
|
255
|
+
timeout=timeout,
|
|
256
|
+
)
|
|
257
|
+
response.raise_for_status()
|
|
258
|
+
return response.json()
|
|
259
|
+
|
|
260
|
+
def submit(
|
|
261
|
+
self,
|
|
262
|
+
application: str,
|
|
263
|
+
data: AnyJSON,
|
|
264
|
+
*,
|
|
265
|
+
path: str = "",
|
|
266
|
+
) -> SyncRequestHandle:
|
|
267
|
+
url = QUEUE_URL_FORMAT + application
|
|
268
|
+
if path:
|
|
269
|
+
url += "/" + path.lstrip("/")
|
|
270
|
+
|
|
271
|
+
response = self.client.post(
|
|
272
|
+
url,
|
|
273
|
+
json=data,
|
|
274
|
+
timeout=self.default_timeout,
|
|
275
|
+
)
|
|
276
|
+
response.raise_for_status()
|
|
277
|
+
|
|
278
|
+
data = response.json()
|
|
279
|
+
return SyncRequestHandle(
|
|
280
|
+
request_id=data["request_id"],
|
|
281
|
+
response_url=data["response_url"],
|
|
282
|
+
status_url=data["status_url"],
|
|
283
|
+
cancel_url=data["cancel_url"],
|
|
284
|
+
client=self.client,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
def stream(
|
|
288
|
+
self,
|
|
289
|
+
application: str,
|
|
290
|
+
data: AnyJSON,
|
|
291
|
+
*,
|
|
292
|
+
path: str = "/stream",
|
|
293
|
+
) -> Iterator[dict[str, Any]]:
|
|
294
|
+
url = RUN_URL_FORMAT + application
|
|
295
|
+
if path:
|
|
296
|
+
url += "/" + path.lstrip("/")
|
|
297
|
+
|
|
298
|
+
with connect_sse(self.client, "POST", url, json=data) as events:
|
|
299
|
+
for event in events.iter_sse():
|
|
300
|
+
yield event.json()
|
|
301
|
+
|
|
302
|
+
def upload(self, data: str | bytes, content_type: str) -> str:
|
|
303
|
+
response = self.client.post(
|
|
304
|
+
CDN_URL + "/files/upload",
|
|
305
|
+
data=data,
|
|
306
|
+
headers={"Content-Type": content_type},
|
|
307
|
+
)
|
|
308
|
+
response.raise_for_status()
|
|
309
|
+
|
|
310
|
+
return response.json()["access_url"]
|
|
311
|
+
|
|
312
|
+
def upload_file(self, path: os.PathLike) -> str:
|
|
313
|
+
mime_type, _ = mimetypes.guess_type(path)
|
|
314
|
+
if mime_type is None:
|
|
315
|
+
mime_type = "application/octet-stream"
|
|
316
|
+
|
|
317
|
+
with open(path, "rb") as file:
|
|
318
|
+
return self.upload(file.read(), mime_type)
|
|
319
|
+
|
|
320
|
+
def upload_image(self, image: Image.Image, format: str = "jpeg") -> str:
|
|
321
|
+
with io.BytesIO() as buffer:
|
|
322
|
+
image.save(buffer, format=format)
|
|
323
|
+
return self.upload(buffer.getvalue(), f"image/{format}")
|
fal_client/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: fal_client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for fal.ai
|
|
5
|
+
Author: fal <hello@fal.ai>
|
|
6
|
+
Project-URL: homepage, https://fal.ai
|
|
7
|
+
Project-URL: repository, https://github.com/fal-ai/fal
|
|
8
|
+
Requires-Python: >=3.8
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
Requires-Dist: httpx <1,>=0.21.0
|
|
11
|
+
Requires-Dist: httpx-sse <0.5,>=0.4.0
|
|
12
|
+
|
|
13
|
+
# fal.ai Python client
|
|
14
|
+
|
|
15
|
+
This is a Python client library for interacting with ML models deployed on [fal.ai](https://fal.ai).
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
fal_client/__init__.py,sha256=kRRp9fS7R7ccKd0LABprQP0DPBqnqPDcT2rQWm10b48,666
|
|
2
|
+
fal_client/auth.py,sha256=N8h0Ae59fsKyAKq7PjtdfuPu5i0E4hDS0DMRWp_ASzw,565
|
|
3
|
+
fal_client/client.py,sha256=l0UbG8hl4uM188T8pPS8NLom40LV3qXZ3AbOauCh27g,9329
|
|
4
|
+
fal_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
fal_client-0.1.0.dist-info/METADATA,sha256=OcC84KMtDrpgzA1RQadpIqZzPOTZBAhOJ-xG_JkYYUU,471
|
|
6
|
+
fal_client-0.1.0.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
|
|
7
|
+
fal_client-0.1.0.dist-info/top_level.txt,sha256=lBTUJP_azR0EnVMhqidmemBj1S2pr1LnMHnroMjG-Ao,11
|
|
8
|
+
fal_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fal_client
|