awacke1 commited on
Commit
0e426ef
ยท
verified ยท
1 Parent(s): 9fa0b24

Create backup1-app.py

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