File size: 14,134 Bytes
0e426ef
 
 
 
 
 
 
 
5d6f17d
 
 
0e426ef
5d6f17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf3e246
5d6f17d
 
 
 
 
 
 
 
 
 
 
cf3e246
5d6f17d
 
 
 
0e426ef
 
5d6f17d
 
 
 
0e426ef
5d6f17d
0e426ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d6f17d
0e426ef
5d6f17d
0e426ef
5d6f17d
 
0e426ef
 
 
5d6f17d
0e426ef
5d6f17d
0e426ef
 
 
 
 
 
 
 
 
 
 
 
 
5d6f17d
 
 
 
 
 
 
 
 
 
 
0e426ef
 
 
5d6f17d
0e426ef
5d6f17d
0e426ef
 
 
 
 
 
 
 
 
 
 
5d6f17d
 
 
0e426ef
 
 
5d6f17d
0e426ef
5d6f17d
0e426ef
 
 
 
 
 
 
 
 
 
 
5d6f17d
 
 
0e426ef
 
 
5d6f17d
0e426ef
5d6f17d
0e426ef
 
 
 
 
 
 
 
 
 
 
5d6f17d
 
 
 
 
 
 
 
 
0e426ef
 
 
 
5d6f17d
0e426ef
 
 
5d6f17d
0e426ef
5d6f17d
 
 
 
 
0e426ef
 
 
 
 
 
 
5d6f17d
 
 
 
 
 
0e426ef
 
 
 
5d6f17d
 
0e426ef
 
 
 
 
 
 
 
 
5d6f17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e426ef
 
 
5d6f17d
 
 
0e426ef
5d6f17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e426ef
5d6f17d
0e426ef
5d6f17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e426ef
5d6f17d
0e426ef
5d6f17d
 
 
0e426ef
5d6f17d
 
 
 
 
 
 
 
 
 
 
 
0e426ef
5d6f17d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e426ef
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import streamlit as st
from gradio_client import Client
import time
import concurrent.futures
import os
from PIL import Image
import io
import requests
from huggingface_hub import HfApi, login
from pathlib import Path
import json

def init_session_state():
    """Initialize session state variables"""
    if 'hf_token' not in st.session_state:
        st.session_state.hf_token = None
    if 'is_authenticated' not in st.session_state:
        st.session_state.is_authenticated = False

def save_token(token):
    """Save token to session state"""
    st.session_state.hf_token = token
    st.session_state.is_authenticated = True

def authenticate_user():
    """Handle user authentication with HuggingFace"""
    st.sidebar.markdown("## ๐Ÿ” Authentication")
    
    if st.session_state.is_authenticated:
        st.sidebar.success("โœ“ Logged in to HuggingFace")
        if st.sidebar.button("Logout"):
            st.session_state.hf_token = None
            st.session_state.is_authenticated = False
            st.rerun()
    else:
        token = st.sidebar.text_input("Enter HuggingFace Token", type="password", 
                                    help="Get your token from https://huggingface.co/settings/tokens")
        if st.sidebar.button("Login"):
            if token:
                try:
                    # Verify token is valid
                    api = HfApi(token=token)
                    api.whoami()
                    save_token(token)
                    st.sidebar.success("Successfully logged in!")
                    st.rerun()
                except Exception as e:
                    st.sidebar.error(f"Authentication failed: {str(e)}")
            else:
                st.sidebar.error("Please enter your HuggingFace token")

class ModelGenerator:
    def __init__(self, token):
        self.token = token

    def generate_midjourney(self, prompt):
        try:
            client = Client("mukaist/Midjourney", hf_token=self.token)
            result = client.predict(
                prompt=prompt,
                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",
                use_negative_prompt=True,
                style="2560 x 1440",
                seed=0,
                width=1024,
                height=1024,
                guidance_scale=6,
                randomize_seed=True,
                api_name="/run"
            )
            
            if isinstance(result, list) and len(result) > 0:
                image_data = result[0]
                if isinstance(image_data, str):
                    if image_data.startswith('http'):
                        response = requests.get(image_data)
                        return ("Midjourney", Image.open(io.BytesIO(response.content)))
                    else:
                        return ("Midjourney", Image.open(image_data))
                else:
                    return ("Midjourney", Image.open(io.BytesIO(image_data)))
            return ("Midjourney", "Error: No image generated")
        except Exception as e:
            return ("Midjourney", f"Error: {str(e)}")

    def generate_stable_cascade(self, prompt):
        try:
            client = Client("multimodalart/stable-cascade", hf_token=self.token)
            result = client.predict(
                prompt=prompt,
                negative_prompt=prompt,
                seed=0,
                width=1024,
                height=1024,
                prior_num_inference_steps=20,
                prior_guidance_scale=4,
                decoder_num_inference_steps=10,
                decoder_guidance_scale=0,
                num_images_per_prompt=1,
                api_name="/run"
            )
            if isinstance(result, list) and len(result) > 0:
                image_data = result[0]
                if isinstance(image_data, str):
                    if image_data.startswith('http'):
                        response = requests.get(image_data)
                        return ("Stable Cascade", Image.open(io.BytesIO(response.content)))
                    else:
                        return ("Stable Cascade", Image.open(image_data))
                else:
                    return ("Stable Cascade", Image.open(io.BytesIO(image_data)))
            return ("Stable Cascade", "Error: No image generated")
        except Exception as e:
            return ("Stable Cascade", f"Error: {str(e)}")

    def generate_stable_diffusion_3(self, prompt):
        try:
            client = Client("stabilityai/stable-diffusion-3-medium", hf_token=self.token)
            result = client.predict(
                prompt=prompt,
                negative_prompt=prompt,
                seed=0,
                randomize_seed=True,
                width=1024,
                height=1024,
                guidance_scale=5,
                num_inference_steps=28,
                api_name="/infer"
            )
            if isinstance(result, (str, bytes)):
                return ("SD 3 Medium", Image.open(io.BytesIO(result) if isinstance(result, bytes) else result))
            return ("SD 3 Medium", "Error: Unexpected result format")
        except Exception as e:
            return ("SD 3 Medium", f"Error: {str(e)}")

    def generate_stable_diffusion_35(self, prompt):
        try:
            client = Client("stabilityai/stable-diffusion-3.5-large", hf_token=self.token)
            result = client.predict(
                prompt=prompt,
                negative_prompt=prompt,
                seed=0,
                randomize_seed=True,
                width=1024,
                height=1024,
                guidance_scale=4.5,
                num_inference_steps=40,
                api_name="/infer"
            )
            if isinstance(result, (str, bytes)):
                return ("SD 3.5 Large", Image.open(io.BytesIO(result) if isinstance(result, bytes) else result))
            return ("SD 3.5 Large", "Error: Unexpected result format")
        except Exception as e:
            return ("SD 3.5 Large", f"Error: {str(e)}")

    def generate_playground_v2_5(self, prompt):
        try:
            client = Client("https://playgroundai-playground-v2-5.hf.space/--replicas/ji5gy/", hf_token=self.token)
            result = client.predict(
                prompt,
                prompt,  # negative prompt
                True,    # use negative prompt
                0,      # seed
                1024,   # width
                1024,   # height
                7.5,    # guidance scale
                True,   # randomize seed
                api_name="/run"
            )
            if isinstance(result, tuple) and result[0] and len(result[0]) > 0:
                image_data = result[0][0].get('image')
                if image_data:
                    if isinstance(image_data, str):
                        if image_data.startswith('http'):
                            response = requests.get(image_data)
                            return ("Playground v2.5", Image.open(io.BytesIO(response.content)))
                        return ("Playground v2.5", Image.open(image_data))
                    return ("Playground v2.5", Image.open(io.BytesIO(image_data)))
            return ("Playground v2.5", "Error: No image generated")
        except Exception as e:
            return ("Playground v2.5", f"Error: {str(e)}")

def generate_images(prompt, selected_models, token):
    results = []
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = []
        generator = ModelGenerator(token)
        model_map = {
            "Midjourney": generator.generate_midjourney,
            "Stable Cascade": generator.generate_stable_cascade,
            "SD 3 Medium": generator.generate_stable_diffusion_3,
            "SD 3.5 Large": generator.generate_stable_diffusion_35,
            "Playground v2.5": generator.generate_playground_v2_5
        }
        
        for model in selected_models:
            if model in model_map:
                futures.append(executor.submit(model_map[model], prompt))
        
        for future in concurrent.futures.as_completed(futures):
            try:
                result = future.result()
                if result:
                    results.append(result)
            except Exception as e:
                st.error(f"Error during image generation: {str(e)}")
    
    return results

def handle_prompt_click(prompt_text, key):
    if not st.session_state.is_authenticated:
        st.error("Please login with your HuggingFace account first!")
        return
        
    selected_models = st.session_state.get('selected_models', [])
    
    if not selected_models:
        st.warning("Please select at least one model from the sidebar!")
        return

    with st.spinner('Generating artwork...'):
        results = generate_images(prompt_text, selected_models, st.session_state.hf_token)
        if results:
            st.session_state[f'generated_images_{key}'] = results
            st.success("Artwork generated successfully!")
            
            # Display images immediately
            cols = st.columns(len(results))
            for col, (model_name, result) in zip(cols, results):
                with col:
                    st.markdown(f"**{model_name}**")
                    if isinstance(result, str) and result.startswith("Error"):
                        st.error(result)
                    elif isinstance(result, Image.Image):
                        st.image(result, use_container_width=True)
                    else:
                        st.error(f"Unexpected result type: {type(result)}")

def main():
    st.title("๐ŸŽจ Multi-Model Art Generator")
    
    init_session_state()
    authenticate_user()

    if st.session_state.is_authenticated:
        with st.sidebar:
            st.header("Model Selection")
            st.session_state['selected_models'] = st.multiselect(
                "Choose AI Models",
                ["Midjourney", "Stable Cascade", "SD 3 Medium", "SD 3.5 Large", "Playground v2.5"],
                default=["Midjourney"]
            )
            
            st.markdown("---")
            st.markdown("### Selected Models:")
            for model in st.session_state['selected_models']:
                st.write(f"โœ“ {model}")
            
            st.markdown("---")
            st.markdown("### Model Information:")
            st.markdown("""
            - **Midjourney**: Best for artistic and creative imagery
            - **Stable Cascade**: New architecture with high detail
            - **SD 3 Medium**: Fast and efficient generation
            - **SD 3.5 Large**: Highest quality, slower generation
            - **Playground v2.5**: Advanced model with high customization
            """)

        st.markdown("### Select a prompt style to generate artwork:")

        prompt_emojis = {
            "AIart/AIArtistCommunity": "๐Ÿค–",
            "Black & White": "โšซโšช",
            "Black & Yellow": "โšซ๐Ÿ’›",
            "Blindfold": "๐Ÿ™ˆ",
            "Break": "๐Ÿ’”",
            "Broken": "๐Ÿ”จ",
            "Christmas Celebrations art": "๐ŸŽ„",
            "Colorful Art": "๐ŸŽจ",
            "Crimson art": "๐Ÿ”ด",
            "Eyes Art": "๐Ÿ‘๏ธ",
            "Going out with Style": "๐Ÿ’ƒ",
            "Hooded Girl": "๐Ÿงฅ",
            "Lips": "๐Ÿ‘„",
            "MAEKHLONG": "๐Ÿฎ",
            "Mermaid": "๐Ÿงœโ€โ™€๏ธ",
            "Morning Sunshine": "๐ŸŒ…",
            "Music Art": "๐ŸŽต",
            "Owl": "๐Ÿฆ‰",
            "Pink": "๐Ÿ’—",
            "Purple": "๐Ÿ’œ",
            "Rain": "๐ŸŒง๏ธ",
            "Red Moon": "๐ŸŒ‘",
            "Rose": "๐ŸŒน",
            "Snow": "โ„๏ธ",
            "Spacesuit Girl": "๐Ÿ‘ฉโ€๐Ÿš€",
            "Steampunk": "โš™๏ธ",
            "Succubus": "๐Ÿ˜ˆ",
            "Sunlight": "โ˜€๏ธ",
            "Weird art": "๐ŸŽญ",
            "White Hair": "๐Ÿ‘ฑโ€โ™€๏ธ",
            "Wings art": "๐Ÿ‘ผ",
            "Woman with Sword": "โš”๏ธ"
        }

        col1, col2, col3 = st.columns(3)
        
        for idx, (prompt, emoji) in enumerate(prompt_emojis.items()):
            full_prompt = f"QT {prompt}"
            col = [col1, col2, col3][idx % 3]
            
            with col:
                if st.button(f"{emoji} {prompt}", key=f"btn_{idx}"):
                    handle_prompt_click(full_prompt, idx)

        st.markdown("---")
        st.markdown("### Generated Artwork:")
        
        # Display any previously generated images
        for key in st.session_state:
            if key.startswith('generated_images_'):
                idx = key.split('_')[-1]
                prompt_key = f'selected_prompt_{idx}'
                
                if prompt_key in st.session_state:
                    st.write("Prompt:", st.session_state[prompt_key])
                    
                    cols = st.columns(len(st.session_state[key]))
                    for col, (model_name, result) in zip(cols, st.session_state[key]):
                        with col:
                            st.markdown(f"**{model_name}**")
                            if isinstance(result, str) and result.startswith("Error"):
                                st.error(result)
                            elif isinstance(result, Image.Image):
                                st.image(result, use_container_width=True)
                            else:
                                st.error(f"Unexpected result type: {type(result)}")
    else:
        st.info("Please login with your HuggingFace account to use the app")

if __name__ == "__main__":
    main()