awacke1 commited on
Commit
4c0a62a
ยท
verified ยท
1 Parent(s): 4994522

Create backup2-somework-app.py

Browse files
Files changed (1) hide show
  1. backup2-somework-app.py +302 -0
backup2-somework-app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, list) and len(result) > 0:
36
+ image_data = result[0]
37
+ if isinstance(image_data, str):
38
+ if image_data.startswith('http'):
39
+ response = requests.get(image_data)
40
+ image = Image.open(io.BytesIO(response.content))
41
+ else:
42
+ image = Image.open(image_data)
43
+ else:
44
+ image = Image.open(io.BytesIO(image_data))
45
+ return ("Midjourney", image)
46
+ else:
47
+ return ("Midjourney", f"Error: Unexpected result format: {type(result)}")
48
+ except Exception as e:
49
+ return ("Midjourney", f"Error: {str(e)}")
50
+
51
+ @staticmethod
52
+ def generate_stable_cascade(prompt, token):
53
+ try:
54
+ client = Client("multimodalart/stable-cascade", hf_token=token)
55
+ result = client.predict(
56
+ prompt=prompt,
57
+ negative_prompt=prompt,
58
+ seed=0,
59
+ width=1024,
60
+ height=1024,
61
+ prior_num_inference_steps=20,
62
+ prior_guidance_scale=4,
63
+ decoder_num_inference_steps=10,
64
+ decoder_guidance_scale=0,
65
+ num_images_per_prompt=1,
66
+ api_name="/run"
67
+ )
68
+ return ("Stable Cascade", result)
69
+ except Exception as e:
70
+ return ("Stable Cascade", f"Error: {str(e)}")
71
+
72
+ @staticmethod
73
+ def generate_stable_diffusion_3(prompt, token):
74
+ try:
75
+ client = Client("stabilityai/stable-diffusion-3-medium", hf_token=token)
76
+ result = client.predict(
77
+ prompt=prompt,
78
+ negative_prompt=prompt,
79
+ seed=0,
80
+ randomize_seed=True,
81
+ width=1024,
82
+ height=1024,
83
+ guidance_scale=5,
84
+ num_inference_steps=28,
85
+ api_name="/infer"
86
+ )
87
+ return ("SD 3 Medium", result)
88
+ except Exception as e:
89
+ return ("SD 3 Medium", f"Error: {str(e)}")
90
+
91
+ @staticmethod
92
+ def generate_stable_diffusion_35(prompt, token):
93
+ try:
94
+ client = Client("stabilityai/stable-diffusion-3.5-large", hf_token=token)
95
+ result = client.predict(
96
+ prompt=prompt,
97
+ negative_prompt=prompt,
98
+ seed=0,
99
+ randomize_seed=True,
100
+ width=1024,
101
+ height=1024,
102
+ guidance_scale=4.5,
103
+ num_inference_steps=40,
104
+ api_name="/infer"
105
+ )
106
+ return ("SD 3.5 Large", result)
107
+ except Exception as e:
108
+ return ("SD 3.5 Large", f"Error: {str(e)}")
109
+
110
+ @staticmethod
111
+ def generate_playground_v2_5(prompt, token):
112
+ try:
113
+ client = Client("https://playgroundai-playground-v2-5.hf.space/--replicas/ji5gy/",
114
+ hf_token=token)
115
+ result = client.predict(
116
+ prompt,
117
+ prompt, # negative prompt
118
+ True, # use negative prompt
119
+ 0, # seed
120
+ 1024, # width
121
+ 1024, # height
122
+ 7.5, # guidance scale
123
+ True, # randomize seed
124
+ api_name="/run"
125
+ )
126
+ if result and isinstance(result, tuple) and result[0]:
127
+ return ("Playground v2.5", result[0][0]['image'])
128
+ return ("Playground v2.5", "Error: No image generated")
129
+ except Exception as e:
130
+ return ("Playground v2.5", f"Error: {str(e)}")
131
+
132
+ def generate_images(prompt, selected_models):
133
+ token = st.session_state.get('hf_token')
134
+ if not token:
135
+ return [("Error", "No authentication token found")]
136
+
137
+ results = []
138
+ with concurrent.futures.ThreadPoolExecutor() as executor:
139
+ futures = []
140
+ model_map = {
141
+ "Midjourney": lambda p: ModelGenerator.generate_midjourney(p, token),
142
+ "Stable Cascade": lambda p: ModelGenerator.generate_stable_cascade(p, token),
143
+ "SD 3 Medium": lambda p: ModelGenerator.generate_stable_diffusion_3(p, token),
144
+ "SD 3.5 Large": lambda p: ModelGenerator.generate_stable_diffusion_35(p, token),
145
+ "Playground v2.5": lambda p: ModelGenerator.generate_playground_v2_5(p, token)
146
+ }
147
+
148
+ for model in selected_models:
149
+ if model in model_map:
150
+ futures.append(executor.submit(model_map[model], prompt))
151
+
152
+ for future in concurrent.futures.as_completed(futures):
153
+ results.append(future.result())
154
+
155
+ return results
156
+
157
+ def handle_prompt_click(prompt_text, key):
158
+ if not st.session_state.get('is_authenticated') or not st.session_state.get('hf_token'):
159
+ st.error("Please login with your HuggingFace account first!")
160
+ return
161
+
162
+ st.session_state[f'selected_prompt_{key}'] = prompt_text
163
+
164
+ selected_models = st.session_state.get('selected_models', [])
165
+
166
+ if not selected_models:
167
+ st.warning("Please select at least one model from the sidebar!")
168
+ return
169
+
170
+ with st.spinner('Generating artwork...'):
171
+ results = generate_images(prompt_text, selected_models)
172
+ st.session_state[f'generated_images_{key}'] = results
173
+ st.success("Artwork generated successfully!")
174
+
175
+ def main():
176
+ st.title("๐ŸŽจ Multi-Model Art Generator")
177
+
178
+ # Handle authentication in sidebar
179
+ with st.sidebar:
180
+ st.header("๐Ÿ” Authentication")
181
+ if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'):
182
+ st.success("โœ“ Logged in to HuggingFace")
183
+ if st.button("Logout"):
184
+ st.session_state['hf_token'] = None
185
+ st.session_state['is_authenticated'] = False
186
+ st.rerun()
187
+ else:
188
+ token = st.text_input("Enter HuggingFace Token", type="password",
189
+ help="Get your token from https://huggingface.co/settings/tokens")
190
+ if st.button("Login"):
191
+ if token:
192
+ try:
193
+ # Verify token is valid
194
+ api = HfApi(token=token)
195
+ api.whoami()
196
+ st.session_state['hf_token'] = token
197
+ st.session_state['is_authenticated'] = True
198
+ st.success("Successfully logged in!")
199
+ st.rerun()
200
+ except Exception as e:
201
+ st.error(f"Authentication failed: {str(e)}")
202
+ else:
203
+ st.error("Please enter your HuggingFace token")
204
+
205
+ if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'):
206
+ st.markdown("---")
207
+ st.header("Model Selection")
208
+ st.session_state['selected_models'] = st.multiselect(
209
+ "Choose AI Models",
210
+ ["Midjourney", "Stable Cascade", "SD 3 Medium", "SD 3.5 Large", "Playground v2.5"],
211
+ default=["Midjourney"]
212
+ )
213
+
214
+ st.markdown("---")
215
+ st.markdown("### Selected Models:")
216
+ for model in st.session_state['selected_models']:
217
+ st.write(f"โœ“ {model}")
218
+
219
+ st.markdown("---")
220
+ st.markdown("### Model Information:")
221
+ st.markdown("""
222
+ - **Midjourney**: Best for artistic and creative imagery
223
+ - **Stable Cascade**: New architecture with high detail
224
+ - **SD 3 Medium**: Fast and efficient generation
225
+ - **SD 3.5 Large**: Highest quality, slower generation
226
+ - **Playground v2.5**: Advanced model with high customization
227
+ """)
228
+
229
+ # Only show the main interface if authenticated
230
+ if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'):
231
+ st.markdown("### Select a prompt style to generate artwork:")
232
+
233
+ prompt_emojis = {
234
+ "AIart/AIArtistCommunity": "๐Ÿค–",
235
+ "Black & White": "โšซโšช",
236
+ "Black & Yellow": "โšซ๐Ÿ’›",
237
+ "Blindfold": "๐Ÿ™ˆ",
238
+ "Break": "๐Ÿ’”",
239
+ "Broken": "๐Ÿ”จ",
240
+ "Christmas Celebrations art": "๐ŸŽ„",
241
+ "Colorful Art": "๐ŸŽจ",
242
+ "Crimson art": "๐Ÿ”ด",
243
+ "Eyes Art": "๐Ÿ‘๏ธ",
244
+ "Going out with Style": "๐Ÿ’ƒ",
245
+ "Hooded Girl": "๐Ÿงฅ",
246
+ "Lips": "๐Ÿ‘„",
247
+ "MAEKHLONG": "๐Ÿฎ",
248
+ "Mermaid": "๐Ÿงœโ€โ™€๏ธ",
249
+ "Morning Sunshine": "๐ŸŒ…",
250
+ "Music Art": "๐ŸŽต",
251
+ "Owl": "๐Ÿฆ‰",
252
+ "Pink": "๐Ÿ’—",
253
+ "Purple": "๐Ÿ’œ",
254
+ "Rain": "๐ŸŒง๏ธ",
255
+ "Red Moon": "๐ŸŒ‘",
256
+ "Rose": "๐ŸŒน",
257
+ "Snow": "โ„๏ธ",
258
+ "Spacesuit Girl": "๐Ÿ‘ฉโ€๐Ÿš€",
259
+ "Steampunk": "โš™๏ธ",
260
+ "Succubus": "๐Ÿ˜ˆ",
261
+ "Sunlight": "โ˜€๏ธ",
262
+ "Weird art": "๐ŸŽญ",
263
+ "White Hair": "๐Ÿ‘ฑโ€โ™€๏ธ",
264
+ "Wings art": "๐Ÿ‘ผ",
265
+ "Woman with Sword": "โš”๏ธ"
266
+ }
267
+
268
+ col1, col2, col3 = st.columns(3)
269
+
270
+ for idx, (prompt, emoji) in enumerate(prompt_emojis.items()):
271
+ full_prompt = f"QT {prompt}"
272
+ col = [col1, col2, col3][idx % 3]
273
+
274
+ with col:
275
+ if st.button(f"{emoji} {prompt}", key=f"btn_{idx}"):
276
+ handle_prompt_click(full_prompt, idx)
277
+
278
+ st.markdown("---")
279
+ st.markdown("### Generated Artwork:")
280
+
281
+ for key in st.session_state:
282
+ if key.startswith('selected_prompt_'):
283
+ idx = key.split('_')[-1]
284
+ images_key = f'generated_images_{idx}'
285
+
286
+ if images_key in st.session_state:
287
+ st.write("Prompt:", st.session_state[key])
288
+
289
+ cols = st.columns(len(st.session_state[images_key]))
290
+
291
+ for col, (model_name, result) in zip(cols, st.session_state[images_key]):
292
+ with col:
293
+ st.markdown(f"**{model_name}**")
294
+ if isinstance(result, str) and result.startswith("Error"):
295
+ st.error(result)
296
+ else:
297
+ st.image(result, use_container_width=True)
298
+ else:
299
+ st.info("Please login with your HuggingFace account to use the app")
300
+
301
+ if __name__ == "__main__":
302
+ main()