-
Notifications
You must be signed in to change notification settings - Fork 2
/
flux_schnell_manifold_function.py
263 lines (222 loc) · 8.8 KB
/
flux_schnell_manifold_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""
title: FLUX.1 Schnell Manifold Function for Black Forest Lab Image Generation Models
authors: bgeneto
funding_url: https://github.com/open-webui
version: 0.1.4
license: MIT
requirements: pydantic, requests
environment_variables: FLUX_SCHNELL_API_BASE_URL, FLUX_SCHNELL_API_KEY
supported providers: huggingface.co, replicate.com, together.xyz
https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell
https://api.replicate.com/v1/models/black-forest-labs/flux-schnell/predictions
https://api.together.xyz/v1/images/generations
"""
import base64
import os
from typing import Any, Dict, Generator, Iterator, List, Union
import requests
from open_webui.utils.misc import get_last_user_message
from pydantic import BaseModel, Field
class Pipe:
"""
Class representing the FLUX.1 Schnell Manifold Function.
"""
class Valves(BaseModel):
"""
Pydantic model for storing API keys and base URLs.
"""
FLUX_SCHNELL_API_KEY: str = Field(
default="", description="Your API Key for Flux.1 Schnell"
)
FLUX_SCHNELL_API_BASE_URL: str = Field(
default="https://api.replicate.com/v1/models/black-forest-labs/flux-schnell/predictions",
description="Base URL for the API",
)
def __init__(self):
"""
Initialize the Pipe class with default values and environment variables.
"""
self.type = "manifold"
self.id = "FLUX.1[schnell]"
self.name = "FLUX.1: "
self.valves = self.Valves(
FLUX_SCHNELL_API_KEY=os.getenv("FLUX_SCHNELL_API_KEY", ""),
FLUX_SCHNELL_API_BASE_URL=os.getenv(
"FLUX_SCHNELL_API_BASE_URL",
"https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell",
),
)
def url_to_img_data(self, url: str) -> str:
"""
Convert a URL to base64-encoded image data.
Args:
url (str): The URL of the image.
Returns:
str: Base64-encoded image data.
"""
headers = {"Authorization": f"Bearer {self.valves.FLUX_SCHNELL_API_KEY}"}
response = requests.get(url, headers=headers)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "application/octet-stream")
encoded_content = base64.b64encode(response.content).decode("utf-8")
return f"data:{content_type};base64,{encoded_content}"
def stream_response(
self, headers: Dict[str, str], payload: Dict[str, Any]
) -> Generator[str, None, None]:
yield self.non_stream_response(headers, payload)
def get_img_extension(self, img_data: str) -> Union[str, None]:
"""
Get the image extension based on the base64-encoded data.
Args:
img_data (str): Base64-encoded image data.
Returns:
Union[str, None]: The image extension or None if unsupported.
"""
if img_data.startswith("/9j/"):
return "jpeg"
elif img_data.startswith("iVBOR"):
return "png"
elif img_data.startswith("R0lG"):
return "gif"
elif img_data.startswith("UklGR"):
return "webp"
return None
def handle_json_response(self, response: requests.Response) -> str:
"""
Handle JSON response from the API.
Args:
response (requests.Response): The response object.
Returns:
str: The formatted image data or an error message.
"""
resp = response.json()
if "output" in resp:
img_data = resp["output"][0]
elif "data" in resp and "b64_json" in resp["data"][0]:
img_data = resp["data"][0]["b64_json"]
else:
return "Error: Unexpected response format for the image provider!"
# split ;base64, from img_data
try:
img_data = img_data.split(";base64,")[1]
except IndexError:
pass
img_ext = self.get_img_extension(img_data[:9])
if not img_ext:
return "Error: Unsupported image format!"
# rebuild img_data with proper format
img_data = f"data:image/{img_ext};base64,{img_data}"
return f"![Image]({img_data})\n`GeneratedImage.{img_ext}`"
def handle_image_response(self, response: requests.Response) -> str:
"""
Handle image response from the API.
Args:
response (requests.Response): The response object.
Returns:
str: The formatted image data.
"""
content_type = response.headers.get("Content-Type", "")
# check image type in the content type
img_ext = "png"
if "image/" in content_type:
img_ext = content_type.split("/")[-1]
image_base64 = base64.b64encode(response.content).decode("utf-8")
return f"![Image](data:{content_type};base64,{image_base64})\n`GeneratedImage.{img_ext}`"
def non_stream_response(
self, headers: Dict[str, str], payload: Dict[str, Any]
) -> str:
"""
Get a non-streaming response from the API.
Args:
headers (Dict[str, str]): The headers for the request.
payload (Dict[str, Any]): The payload for the request.
Returns:
str: The response from the API.
"""
try:
response = requests.post(
url=self.valves.FLUX_SCHNELL_API_BASE_URL,
headers=headers,
json=payload,
stream=False,
timeout=(3.05, 60),
)
response.raise_for_status()
content_type = response.headers.get("Content-Type", "")
if "application/json" in content_type:
return self.handle_json_response(response)
elif "image/" in content_type:
return self.handle_image_response(response)
else:
return f"Error: Unsupported content type {content_type}"
except requests.exceptions.RequestException as e:
return f"Error: Request failed: {e}"
except Exception as e:
return f"Error: {e}"
def pipes(self) -> List[Dict[str, str]]:
"""
Get the list of available pipes.
Returns:
List[Dict[str, str]]: The list of pipes.
"""
return [{"id": "flux_schnell", "name": "Schnell"}]
def pipe(
self, body: Dict[str, Any]
) -> Union[str, Generator[str, None, None], Iterator[str]]:
"""
Process the pipe request.
Args:
body (Dict[str, Any]): The request body.
Returns:
Union[str, Generator[str, None, None], Iterator[str]]: The response from the API.
"""
headers = {
"Authorization": f"Bearer {self.valves.FLUX_SCHNELL_API_KEY}",
"Content-Type": "application/json",
}
body["stream"] = False
prompt = get_last_user_message(body["messages"])
headers_map = {
"huggingface.co": {"x-wait-for-model": "true"},
"replicate.com": {"Prefer": "wait"},
"together.xyz": {},
}
payload_map = {
"huggingface.co": {"inputs": prompt},
"replicate.com": {
"input": {
"prompt": prompt,
"go_fast": True,
"num_outputs": 1,
"aspect_ratio": "1:1",
"output_format": "webp",
"output_quality": 90,
}
},
"together.xyz": {
"model": "black-forest-labs/FLUX.1-schnell",
"prompt": prompt,
"width": 1024,
"height": 1024,
"steps": 4,
"n": 1,
"response_format": "b64_json",
},
}
payload = None
for key in payload_map:
if key in self.valves.FLUX_SCHNELL_API_BASE_URL:
payload = payload_map[key]
headers.update(headers_map.get(key, {}))
break
if payload is None:
return "Error: Unsupported API base URL! Remember, that's the beauty of open-source: you can add your own..."
try:
if body.get("stream", False):
return self.stream_response(headers, payload)
else:
return self.non_stream_response(headers, payload)
except requests.exceptions.RequestException as e:
return f"Error: Request failed: {e}"
except Exception as e:
return f"Error: {e}"