Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,349 +1,355 @@
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
-
import random
|
3 |
-
import uuid
|
4 |
-
import base64
|
5 |
-
import gradio as gr
|
6 |
-
import numpy as np
|
7 |
from PIL import Image
|
8 |
-
import
|
9 |
-
import
|
10 |
-
import
|
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 |
-
use_safetensors=True,
|
132 |
-
)
|
133 |
-
pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
|
134 |
-
|
135 |
-
pipe.load_lora_weights("ehristoforu/dalle-3-xl-v2", weight_name="dalle-3-xl-lora-v2.safetensors", adapter_name="dalle")
|
136 |
-
pipe.set_adapters("dalle")
|
137 |
-
|
138 |
-
pipe.to("cuda")
|
139 |
-
|
140 |
-
@spaces.GPU(enable_queue=True)
|
141 |
-
def generate(
|
142 |
-
prompt: str,
|
143 |
-
negative_prompt: str = "",
|
144 |
-
use_negative_prompt: bool = False,
|
145 |
-
seed: int = 0,
|
146 |
-
width: int = 1024,
|
147 |
-
height: int = 1024,
|
148 |
-
guidance_scale: float = 3,
|
149 |
-
randomize_seed: bool = False,
|
150 |
-
progress=gr.Progress(track_tqdm=True),
|
151 |
-
):
|
152 |
-
seed = int(randomize_seed_fn(seed, randomize_seed))
|
153 |
-
|
154 |
-
if not use_negative_prompt:
|
155 |
-
negative_prompt = ""
|
156 |
-
|
157 |
-
images = pipe(
|
158 |
-
prompt=prompt,
|
159 |
-
negative_prompt=negative_prompt,
|
160 |
-
width=width,
|
161 |
-
height=height,
|
162 |
-
guidance_scale=guidance_scale,
|
163 |
-
num_inference_steps=20,
|
164 |
-
num_images_per_prompt=1,
|
165 |
-
cross_attention_kwargs={"scale": 0.65},
|
166 |
-
output_type="pil",
|
167 |
-
).images
|
168 |
-
image_paths = [save_image(img, prompt) for img in images]
|
169 |
-
download_links = [create_download_link(path) for path in image_paths]
|
170 |
-
|
171 |
-
return image_paths, seed, download_links, get_image_gallery(), image_metadata.values.tolist()
|
172 |
-
|
173 |
-
examples = [
|
174 |
-
f"{get_random_style()} painting of a majestic lighthouse on a rocky coast. Use bold brushstrokes and a vibrant color palette to capture the interplay of light and shadow as the lighthouse beam cuts through a stormy night sky.",
|
175 |
-
f"{get_random_style()} still life featuring a pair of vintage eyeglasses. Focus on the intricate details of the frames and lenses, using a warm color scheme to evoke a sense of nostalgia and wisdom.",
|
176 |
-
f"{get_random_style()} depiction of a rustic wooden stool in a sunlit artist's studio. Emphasize the texture of the wood and the interplay of light and shadow, using a mix of earthy tones and highlights.",
|
177 |
-
f"{get_random_style()} scene viewed through an ornate window frame. Contrast the intricate details of the window with a dreamy, soft-focus landscape beyond, using a palette that transitions from cool interior tones to warm exterior hues.",
|
178 |
-
f"{get_random_style()} close-up study of interlaced fingers. Use a monochromatic color scheme to emphasize the form and texture of the hands, with dramatic lighting to create depth and emotion.",
|
179 |
-
f"{get_random_style()} composition featuring a set of dice in motion. Capture the energy and randomness of the throw, using a dynamic color palette and blurred lines to convey movement.",
|
180 |
-
f"{get_random_style()} interpretation of heaven. Create an ethereal atmosphere with soft, billowing clouds and radiant light, using a palette of celestial blues, golds, and whites.",
|
181 |
-
f"{get_random_style()} portrayal of an ancient, mystical gate. Combine architectural details with elements of fantasy, using a rich, jewel-toned palette to create an air of mystery and magic.",
|
182 |
-
f"{get_random_style()} portrait of a curious cat. Focus on capturing the feline's expressive eyes and sleek form, using a mix of bold and subtle colors to bring out the cat's personality.",
|
183 |
-
f"{get_random_style()} abstract representation of toes in sand. Use textured brushstrokes to convey the feeling of warm sand, with a palette inspired by a sun-drenched beach."
|
184 |
-
]
|
185 |
-
|
186 |
-
css = '''
|
187 |
-
.gradio-container{max-width: 1024px !important}
|
188 |
-
h1{text-align:center}
|
189 |
-
footer {
|
190 |
-
visibility: hidden
|
191 |
-
}
|
192 |
-
'''
|
193 |
-
|
194 |
-
with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
|
195 |
-
gr.Markdown(DESCRIPTION)
|
196 |
-
|
197 |
-
with gr.Tab("Generate Images"):
|
198 |
-
with gr.Group():
|
199 |
-
with gr.Row():
|
200 |
-
prompt = gr.Text(
|
201 |
-
label="Prompt",
|
202 |
-
show_label=False,
|
203 |
-
max_lines=1,
|
204 |
-
placeholder="Enter your prompt",
|
205 |
-
container=False,
|
206 |
-
)
|
207 |
-
run_button = gr.Button("Run", scale=0)
|
208 |
-
result = gr.Gallery(label="Result", columns=1, preview=True, show_label=False)
|
209 |
-
with gr.Accordion("Advanced options", open=False):
|
210 |
-
use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True)
|
211 |
-
negative_prompt = gr.Text(
|
212 |
-
label="Negative prompt",
|
213 |
-
lines=4,
|
214 |
-
max_lines=6,
|
215 |
-
value="""(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation, (NSFW:1.25)""",
|
216 |
-
placeholder="Enter a negative prompt",
|
217 |
-
visible=True,
|
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 |
-
guidance_scale = gr.Slider(
|
245 |
-
label="Guidance Scale",
|
246 |
-
minimum=0.1,
|
247 |
-
maximum=20.0,
|
248 |
-
step=0.1,
|
249 |
-
value=20.0,
|
250 |
-
)
|
251 |
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
heart_button = gr.Button("โค๏ธ Heart")
|
267 |
-
delete_image_button = gr.Button("๐๏ธ Delete Selected Image")
|
268 |
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
use_negative_prompt.change(
|
280 |
-
fn=lambda x: gr.update(visible=x),
|
281 |
-
inputs=use_negative_prompt,
|
282 |
-
outputs=negative_prompt,
|
283 |
-
api_name=False,
|
284 |
-
)
|
285 |
-
|
286 |
-
delete_all_button.click(
|
287 |
-
fn=delete_all_images,
|
288 |
-
inputs=[],
|
289 |
-
outputs=[image_gallery, metadata_df],
|
290 |
-
)
|
291 |
-
|
292 |
-
image_gallery.select(
|
293 |
-
fn=lambda evt: evt,
|
294 |
-
inputs=[],
|
295 |
-
outputs=[selected_image],
|
296 |
-
)
|
297 |
-
|
298 |
-
like_button.click(
|
299 |
-
fn=lambda x: vote(x, 'likes'),
|
300 |
-
inputs=[selected_image],
|
301 |
-
outputs=[image_gallery, metadata_df],
|
302 |
-
)
|
303 |
-
|
304 |
-
dislike_button.click(
|
305 |
-
fn=lambda x: vote(x, 'dislikes'),
|
306 |
-
inputs=[selected_image],
|
307 |
-
outputs=[image_gallery, metadata_df],
|
308 |
-
)
|
309 |
-
|
310 |
-
heart_button.click(
|
311 |
-
fn=lambda x: vote(x, 'hearts'),
|
312 |
-
inputs=[selected_image],
|
313 |
-
outputs=[image_gallery, metadata_df],
|
314 |
-
)
|
315 |
-
|
316 |
-
delete_image_button.click(
|
317 |
-
fn=delete_image,
|
318 |
-
inputs=[selected_image],
|
319 |
-
outputs=[image_gallery, metadata_df],
|
320 |
-
)
|
321 |
-
|
322 |
-
def update_gallery_and_metadata():
|
323 |
-
return gr.update(value=get_image_gallery()), gr.update(value=image_metadata.values.tolist())
|
324 |
-
|
325 |
-
gr.on(
|
326 |
-
triggers=[
|
327 |
-
prompt.submit,
|
328 |
-
negative_prompt.submit,
|
329 |
-
run_button.click,
|
330 |
-
],
|
331 |
-
fn=generate,
|
332 |
-
inputs=[
|
333 |
-
prompt,
|
334 |
-
negative_prompt,
|
335 |
-
use_negative_prompt,
|
336 |
-
seed,
|
337 |
-
width,
|
338 |
-
height,
|
339 |
-
guidance_scale,
|
340 |
-
randomize_seed,
|
341 |
-
],
|
342 |
-
outputs=[result, seed, gr.HTML(visible=False), image_gallery, metadata_df],
|
343 |
-
api_name="run",
|
344 |
-
)
|
345 |
|
346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
347 |
|
348 |
if __name__ == "__main__":
|
349 |
-
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from gradio_client import Client
|
3 |
+
import time
|
4 |
+
import concurrent.futures
|
5 |
import os
|
|
|
|
|
|
|
|
|
|
|
6 |
from PIL import Image
|
7 |
+
import io
|
8 |
+
import requests
|
9 |
+
from huggingface_hub import HfApi, login
|
10 |
+
|
11 |
+
# Initialize session state - must be first
|
12 |
+
if 'hf_token' not in st.session_state:
|
13 |
+
st.session_state['hf_token'] = None
|
14 |
+
if 'is_authenticated' not in st.session_state:
|
15 |
+
st.session_state['is_authenticated'] = False
|
16 |
+
|
17 |
+
class ModelGenerator:
|
18 |
+
@staticmethod
|
19 |
+
def generate_midjourney(prompt, token):
|
20 |
+
try:
|
21 |
+
client = Client("mukaist/Midjourney", hf_token=token)
|
22 |
+
result = client.predict(
|
23 |
+
prompt=prompt,
|
24 |
+
negative_prompt="(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, close up, cropped, out of frame, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck",
|
25 |
+
use_negative_prompt=True,
|
26 |
+
style="2560 x 1440",
|
27 |
+
seed=0,
|
28 |
+
width=1024,
|
29 |
+
height=1024,
|
30 |
+
guidance_scale=6,
|
31 |
+
randomize_seed=True,
|
32 |
+
api_name="/run"
|
33 |
+
)
|
34 |
+
|
35 |
+
if isinstance(result, tuple):
|
36 |
+
image_data = result[0] if len(result) > 0 else None
|
37 |
+
elif isinstance(result, list):
|
38 |
+
image_data = result[0] if len(result) > 0 else None
|
39 |
+
else:
|
40 |
+
image_data = result
|
41 |
+
|
42 |
+
if image_data:
|
43 |
+
if isinstance(image_data, str):
|
44 |
+
if image_data.startswith('http'):
|
45 |
+
response = requests.get(image_data)
|
46 |
+
return ("Midjourney", Image.open(io.BytesIO(response.content)))
|
47 |
+
return ("Midjourney", Image.open(image_data))
|
48 |
+
elif isinstance(image_data, bytes):
|
49 |
+
return ("Midjourney", Image.open(io.BytesIO(image_data)))
|
50 |
+
elif hasattr(image_data, 'read'): # File-like object
|
51 |
+
return ("Midjourney", Image.open(image_data))
|
52 |
+
return ("Midjourney", "Error: No valid image data found")
|
53 |
+
except Exception as e:
|
54 |
+
return ("Midjourney", f"Error: {str(e)}")
|
55 |
+
|
56 |
+
@staticmethod
|
57 |
+
def generate_stable_cascade(prompt, token):
|
58 |
+
try:
|
59 |
+
client = Client("multimodalart/stable-cascade", hf_token=token)
|
60 |
+
result = client.predict(
|
61 |
+
prompt=prompt,
|
62 |
+
negative_prompt=prompt,
|
63 |
+
seed=0,
|
64 |
+
width=1024,
|
65 |
+
height=1024,
|
66 |
+
prior_num_inference_steps=20,
|
67 |
+
prior_guidance_scale=4,
|
68 |
+
decoder_num_inference_steps=10,
|
69 |
+
decoder_guidance_scale=0,
|
70 |
+
num_images_per_prompt=1,
|
71 |
+
api_name="/run"
|
72 |
+
)
|
73 |
+
if isinstance(result, (str, bytes)):
|
74 |
+
return ("Stable Cascade", Image.open(io.BytesIO(result) if isinstance(result, bytes) else result))
|
75 |
+
elif isinstance(result, list) and len(result) > 0:
|
76 |
+
return ("Stable Cascade", Image.open(io.BytesIO(result[0]) if isinstance(result[0], bytes) else result[0]))
|
77 |
+
return ("Stable Cascade", "Error: No valid image data found")
|
78 |
+
except Exception as e:
|
79 |
+
return ("Stable Cascade", f"Error: {str(e)}")
|
80 |
+
|
81 |
+
@staticmethod
|
82 |
+
def generate_stable_diffusion_3(prompt, token):
|
83 |
+
try:
|
84 |
+
client = Client("stabilityai/stable-diffusion-3-medium", hf_token=token)
|
85 |
+
result = client.predict(
|
86 |
+
prompt=prompt,
|
87 |
+
negative_prompt=prompt,
|
88 |
+
seed=0,
|
89 |
+
randomize_seed=True,
|
90 |
+
width=1024,
|
91 |
+
height=1024,
|
92 |
+
guidance_scale=5,
|
93 |
+
num_inference_steps=28,
|
94 |
+
api_name="/infer"
|
95 |
+
)
|
96 |
+
if isinstance(result, bytes):
|
97 |
+
return ("SD 3 Medium", Image.open(io.BytesIO(result)))
|
98 |
+
elif isinstance(result, str):
|
99 |
+
if result.startswith('http'):
|
100 |
+
response = requests.get(result)
|
101 |
+
return ("SD 3 Medium", Image.open(io.BytesIO(response.content)))
|
102 |
+
return ("SD 3 Medium", Image.open(result))
|
103 |
+
elif isinstance(result, list) and len(result) > 0:
|
104 |
+
image_data = result[0]
|
105 |
+
if isinstance(image_data, bytes):
|
106 |
+
return ("SD 3 Medium", Image.open(io.BytesIO(image_data)))
|
107 |
+
elif isinstance(image_data, str):
|
108 |
+
if image_data.startswith('http'):
|
109 |
+
response = requests.get(image_data)
|
110 |
+
return ("SD 3 Medium", Image.open(io.BytesIO(response.content)))
|
111 |
+
return ("SD 3 Medium", Image.open(image_data))
|
112 |
+
return ("SD 3 Medium", "Error: No valid image data found")
|
113 |
+
except Exception as e:
|
114 |
+
return ("SD 3 Medium", f"Error: {str(e)}")
|
115 |
+
|
116 |
+
@staticmethod
|
117 |
+
def generate_stable_diffusion_35(prompt, token):
|
118 |
+
try:
|
119 |
+
client = Client("stabilityai/stable-diffusion-3.5-large", hf_token=token)
|
120 |
+
result = client.predict(
|
121 |
+
prompt=prompt,
|
122 |
+
negative_prompt=prompt,
|
123 |
+
seed=0,
|
124 |
+
randomize_seed=True,
|
125 |
+
width=1024,
|
126 |
+
height=1024,
|
127 |
+
guidance_scale=4.5,
|
128 |
+
num_inference_steps=40,
|
129 |
+
api_name="/infer"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
)
|
131 |
+
if isinstance(result, bytes):
|
132 |
+
return ("SD 3.5 Large", Image.open(io.BytesIO(result)))
|
133 |
+
elif isinstance(result, str):
|
134 |
+
if result.startswith('http'):
|
135 |
+
response = requests.get(result)
|
136 |
+
return ("SD 3.5 Large", Image.open(io.BytesIO(response.content)))
|
137 |
+
return ("SD 3.5 Large", Image.open(result))
|
138 |
+
elif isinstance(result, list) and len(result) > 0:
|
139 |
+
image_data = result[0]
|
140 |
+
if isinstance(image_data, bytes):
|
141 |
+
return ("SD 3.5 Large", Image.open(io.BytesIO(image_data)))
|
142 |
+
elif isinstance(image_data, str):
|
143 |
+
if image_data.startswith('http'):
|
144 |
+
response = requests.get(image_data)
|
145 |
+
return ("SD 3.5 Large", Image.open(io.BytesIO(response.content)))
|
146 |
+
return ("SD 3.5 Large", Image.open(image_data))
|
147 |
+
return ("SD 3.5 Large", "Error: No valid image data found")
|
148 |
+
except Exception as e:
|
149 |
+
return ("SD 3.5 Large", f"Error: {str(e)}")
|
150 |
+
|
151 |
+
@staticmethod
|
152 |
+
def generate_playground_v2_5(prompt, token):
|
153 |
+
try:
|
154 |
+
client = Client("https://playgroundai-playground-v2-5.hf.space/--replicas/ji5gy/",
|
155 |
+
hf_token=token)
|
156 |
+
result = client.predict(
|
157 |
+
prompt,
|
158 |
+
prompt, # negative prompt
|
159 |
+
True, # use negative prompt
|
160 |
+
0, # seed
|
161 |
+
1024, # width
|
162 |
+
1024, # height
|
163 |
+
7.5, # guidance scale
|
164 |
+
True, # randomize seed
|
165 |
+
api_name="/run"
|
166 |
)
|
167 |
+
if isinstance(result, tuple) and result[0] and len(result[0]) > 0:
|
168 |
+
image_data = result[0][0].get('image')
|
169 |
+
if image_data:
|
170 |
+
if isinstance(image_data, str):
|
171 |
+
if image_data.startswith('http'):
|
172 |
+
response = requests.get(image_data)
|
173 |
+
return ("Playground v2.5", Image.open(io.BytesIO(response.content)))
|
174 |
+
return ("Playground v2.5", Image.open(image_data))
|
175 |
+
return ("Playground v2.5", Image.open(io.BytesIO(image_data)))
|
176 |
+
return ("Playground v2.5", "Error: No image generated")
|
177 |
+
except Exception as e:
|
178 |
+
return ("Playground v2.5", f"Error: {str(e)}")
|
179 |
+
|
180 |
+
def generate_images(prompt, selected_models):
|
181 |
+
token = st.session_state.get('hf_token')
|
182 |
+
if not token:
|
183 |
+
return [("Error", "No authentication token found")]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
184 |
|
185 |
+
results = []
|
186 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
187 |
+
futures = []
|
188 |
+
model_map = {
|
189 |
+
"Midjourney": lambda p: ModelGenerator.generate_midjourney(p, token),
|
190 |
+
"Stable Cascade": lambda p: ModelGenerator.generate_stable_cascade(p, token),
|
191 |
+
"SD 3 Medium": lambda p: ModelGenerator.generate_stable_diffusion_3(p, token),
|
192 |
+
"SD 3.5 Large": lambda p: ModelGenerator.generate_stable_diffusion_35(p, token),
|
193 |
+
"Playground v2.5": lambda p: ModelGenerator.generate_playground_v2_5(p, token)
|
194 |
+
}
|
195 |
|
196 |
+
for model in selected_models:
|
197 |
+
if model in model_map:
|
198 |
+
futures.append(executor.submit(model_map[model], prompt))
|
|
|
|
|
199 |
|
200 |
+
for future in concurrent.futures.as_completed(futures):
|
201 |
+
try:
|
202 |
+
result = future.result()
|
203 |
+
if result:
|
204 |
+
results.append(result)
|
205 |
+
except Exception as e:
|
206 |
+
st.error(f"Error during image generation: {str(e)}")
|
207 |
+
|
208 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
209 |
|
210 |
+
def handle_prompt_click(prompt_text, key):
|
211 |
+
if not st.session_state.get('is_authenticated') or not st.session_state.get('hf_token'):
|
212 |
+
st.error("Please login with your HuggingFace account first!")
|
213 |
+
return
|
214 |
+
|
215 |
+
st.session_state[f'selected_prompt_{key}'] = prompt_text
|
216 |
+
|
217 |
+
selected_models = st.session_state.get('selected_models', [])
|
218 |
+
|
219 |
+
if not selected_models:
|
220 |
+
st.warning("Please select at least one model from the sidebar!")
|
221 |
+
return
|
222 |
+
|
223 |
+
with st.spinner('Generating artwork...'):
|
224 |
+
results = generate_images(prompt_text, selected_models)
|
225 |
+
st.session_state[f'generated_images_{key}'] = results
|
226 |
+
st.success("Artwork generated successfully!")
|
227 |
+
|
228 |
+
def main():
|
229 |
+
st.title("๐จ Multi-Model Art Generator")
|
230 |
+
|
231 |
+
# Handle authentication in sidebar
|
232 |
+
with st.sidebar:
|
233 |
+
st.header("๐ Authentication")
|
234 |
+
if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'):
|
235 |
+
st.success("โ Logged in to HuggingFace")
|
236 |
+
if st.button("Logout"):
|
237 |
+
st.session_state['hf_token'] = None
|
238 |
+
st.session_state['is_authenticated'] = False
|
239 |
+
st.rerun()
|
240 |
+
else:
|
241 |
+
token = st.text_input("Enter HuggingFace Token", type="password",
|
242 |
+
help="Get your token from https://huggingface.co/settings/tokens")
|
243 |
+
if st.button("Login"):
|
244 |
+
if token:
|
245 |
+
try:
|
246 |
+
# Verify token is valid
|
247 |
+
api = HfApi(token=token)
|
248 |
+
api.whoami()
|
249 |
+
st.session_state['hf_token'] = token
|
250 |
+
st.session_state['is_authenticated'] = True
|
251 |
+
st.success("Successfully logged in!")
|
252 |
+
st.rerun()
|
253 |
+
except Exception as e:
|
254 |
+
st.error(f"Authentication failed: {str(e)}")
|
255 |
+
else:
|
256 |
+
st.error("Please enter your HuggingFace token")
|
257 |
+
|
258 |
+
if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'):
|
259 |
+
st.markdown("---")
|
260 |
+
st.header("Model Selection")
|
261 |
+
st.session_state['selected_models'] = st.multiselect(
|
262 |
+
"Choose AI Models",
|
263 |
+
["Midjourney", "Stable Cascade", "SD 3 Medium", "SD 3.5 Large", "Playground v2.5"],
|
264 |
+
default=["Midjourney"]
|
265 |
+
)
|
266 |
+
|
267 |
+
st.markdown("---")
|
268 |
+
st.markdown("### Selected Models:")
|
269 |
+
for model in st.session_state['selected_models']:
|
270 |
+
st.write(f"โ {model}")
|
271 |
+
|
272 |
+
st.markdown("---")
|
273 |
+
st.markdown("### Model Information:")
|
274 |
+
st.markdown("""
|
275 |
+
- **Midjourney**: Best for artistic and creative imagery
|
276 |
+
- **Stable Cascade**: New architecture with high detail
|
277 |
+
- **SD 3 Medium**: Fast and efficient generation
|
278 |
+
- **SD 3.5 Large**: Highest quality, slower generation
|
279 |
+
- **Playground v2.5**: Advanced model with high customization
|
280 |
+
""")
|
281 |
+
|
282 |
+
# Only show the main interface if authenticated
|
283 |
+
if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'):
|
284 |
+
st.markdown("### Select a prompt style to generate artwork:")
|
285 |
+
|
286 |
+
prompt_emojis = {
|
287 |
+
"AIart/AIArtistCommunity": "๐ค",
|
288 |
+
"Black & White": "โซโช",
|
289 |
+
"Black & Yellow": "โซ๐",
|
290 |
+
"Blindfold": "๐",
|
291 |
+
"Break": "๐",
|
292 |
+
"Broken": "๐จ",
|
293 |
+
"Christmas Celebrations art": "๐",
|
294 |
+
"Colorful Art": "๐จ",
|
295 |
+
"Crimson art": "๐ด",
|
296 |
+
"Eyes Art": "๐๏ธ",
|
297 |
+
"Going out with Style": "๐",
|
298 |
+
"Hooded Girl": "๐งฅ",
|
299 |
+
"Lips": "๐",
|
300 |
+
"MAEKHLONG": "๐ฎ",
|
301 |
+
"Mermaid": "๐งโโ๏ธ",
|
302 |
+
"Morning Sunshine": "๐
",
|
303 |
+
"Music Art": "๐ต",
|
304 |
+
"Owl": "๐ฆ",
|
305 |
+
"Pink": "๐",
|
306 |
+
"Purple": "๐",
|
307 |
+
"Rain": "๐ง๏ธ",
|
308 |
+
"Red Moon": "๐",
|
309 |
+
"Rose": "๐น",
|
310 |
+
"Snow": "โ๏ธ",
|
311 |
+
"Spacesuit Girl": "๐ฉโ๐",
|
312 |
+
"Steampunk": "โ๏ธ",
|
313 |
+
"Succubus": "๐",
|
314 |
+
"Sunlight": "โ๏ธ",
|
315 |
+
"Weird art": "๐ญ",
|
316 |
+
"White Hair": "๐ฑโโ๏ธ",
|
317 |
+
"Wings art": "๐ผ",
|
318 |
+
"Woman with Sword": "โ๏ธ"
|
319 |
+
}
|
320 |
+
|
321 |
+
col1, col2, col3 = st.columns(3)
|
322 |
+
|
323 |
+
for idx, (prompt, emoji) in enumerate(prompt_emojis.items()):
|
324 |
+
full_prompt = f"QT {prompt}"
|
325 |
+
col = [col1, col2, col3][idx % 3]
|
326 |
+
|
327 |
+
with col:
|
328 |
+
if st.button(f"{emoji} {prompt}", key=f"btn_{idx}"):
|
329 |
+
handle_prompt_click(full_prompt, idx)
|
330 |
+
|
331 |
+
st.markdown("---")
|
332 |
+
st.markdown("### Generated Artwork:")
|
333 |
+
|
334 |
+
for key in st.session_state:
|
335 |
+
if key.startswith('selected_prompt_'):
|
336 |
+
idx = key.split('_')[-1]
|
337 |
+
images_key = f'generated_images_{idx}'
|
338 |
+
|
339 |
+
if images_key in st.session_state:
|
340 |
+
st.write("Prompt:", st.session_state[key])
|
341 |
+
|
342 |
+
cols = st.columns(len(st.session_state[images_key]))
|
343 |
+
|
344 |
+
for col, (model_name, result) in zip(cols, st.session_state[images_key]):
|
345 |
+
with col:
|
346 |
+
st.markdown(f"**{model_name}**")
|
347 |
+
if isinstance(result, str) and result.startswith("Error"):
|
348 |
+
st.error(result)
|
349 |
+
else:
|
350 |
+
st.image(result, use_container_width=True)
|
351 |
+
else:
|
352 |
+
st.info("Please login with your HuggingFace account to use the app")
|
353 |
|
354 |
if __name__ == "__main__":
|
355 |
+
main()
|