Spaces:
Sleeping
Sleeping
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 | |
# Initialize session state - must be first | |
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 | |
class ModelGenerator: | |
def generate_midjourney(prompt, token): | |
try: | |
client = Client("mukaist/Midjourney", hf_token=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, tuple): | |
image_data = result[0] if len(result) > 0 else None | |
elif isinstance(result, list): | |
image_data = result[0] if len(result) > 0 else None | |
else: | |
image_data = result | |
if image_data: | |
if isinstance(image_data, str): | |
if image_data.startswith('http'): | |
response = requests.get(image_data) | |
return ("Midjourney", Image.open(io.BytesIO(response.content))) | |
return ("Midjourney", Image.open(image_data)) | |
elif isinstance(image_data, bytes): | |
return ("Midjourney", Image.open(io.BytesIO(image_data))) | |
elif hasattr(image_data, 'read'): # File-like object | |
return ("Midjourney", Image.open(image_data)) | |
return ("Midjourney", "Error: No valid image data found") | |
except Exception as e: | |
return ("Midjourney", f"Error: {str(e)}") | |
def generate_stable_cascade(prompt, token): | |
try: | |
client = Client("multimodalart/stable-cascade", hf_token=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, (str, bytes)): | |
return ("Stable Cascade", Image.open(io.BytesIO(result) if isinstance(result, bytes) else result)) | |
elif isinstance(result, list) and len(result) > 0: | |
return ("Stable Cascade", Image.open(io.BytesIO(result[0]) if isinstance(result[0], bytes) else result[0])) | |
return ("Stable Cascade", "Error: No valid image data found") | |
except Exception as e: | |
return ("Stable Cascade", f"Error: {str(e)}") | |
def generate_stable_diffusion_3(prompt, token): | |
try: | |
client = Client("stabilityai/stable-diffusion-3-medium", hf_token=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, bytes): | |
return ("SD 3 Medium", Image.open(io.BytesIO(result))) | |
elif isinstance(result, str): | |
if result.startswith('http'): | |
response = requests.get(result) | |
return ("SD 3 Medium", Image.open(io.BytesIO(response.content))) | |
return ("SD 3 Medium", Image.open(result)) | |
elif isinstance(result, list) and len(result) > 0: | |
image_data = result[0] | |
if isinstance(image_data, bytes): | |
return ("SD 3 Medium", Image.open(io.BytesIO(image_data))) | |
elif isinstance(image_data, str): | |
if image_data.startswith('http'): | |
response = requests.get(image_data) | |
return ("SD 3 Medium", Image.open(io.BytesIO(response.content))) | |
return ("SD 3 Medium", Image.open(image_data)) | |
return ("SD 3 Medium", "Error: No valid image data found") | |
except Exception as e: | |
return ("SD 3 Medium", f"Error: {str(e)}") | |
def generate_stable_diffusion_35(prompt, token): | |
try: | |
client = Client("stabilityai/stable-diffusion-3.5-large", hf_token=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, bytes): | |
return ("SD 3.5 Large", Image.open(io.BytesIO(result))) | |
elif isinstance(result, str): | |
if result.startswith('http'): | |
response = requests.get(result) | |
return ("SD 3.5 Large", Image.open(io.BytesIO(response.content))) | |
return ("SD 3.5 Large", Image.open(result)) | |
elif isinstance(result, list) and len(result) > 0: | |
image_data = result[0] | |
if isinstance(image_data, bytes): | |
return ("SD 3.5 Large", Image.open(io.BytesIO(image_data))) | |
elif isinstance(image_data, str): | |
if image_data.startswith('http'): | |
response = requests.get(image_data) | |
return ("SD 3.5 Large", Image.open(io.BytesIO(response.content))) | |
return ("SD 3.5 Large", Image.open(image_data)) | |
return ("SD 3.5 Large", "Error: No valid image data found") | |
except Exception as e: | |
return ("SD 3.5 Large", f"Error: {str(e)}") | |
def generate_playground_v2_5(prompt, token): | |
try: | |
client = Client("https://playgroundai-playground-v2-5.hf.space/--replicas/ji5gy/", | |
hf_token=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 = st.session_state.get('hf_token') | |
if not token: | |
return [("Error", "No authentication token found")] | |
results = [] | |
with concurrent.futures.ThreadPoolExecutor() as executor: | |
futures = [] | |
model_map = { | |
"Midjourney": lambda p: ModelGenerator.generate_midjourney(p, token), | |
"Stable Cascade": lambda p: ModelGenerator.generate_stable_cascade(p, token), | |
"SD 3 Medium": lambda p: ModelGenerator.generate_stable_diffusion_3(p, token), | |
"SD 3.5 Large": lambda p: ModelGenerator.generate_stable_diffusion_35(p, token), | |
"Playground v2.5": lambda p: ModelGenerator.generate_playground_v2_5(p, token) | |
} | |
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.get('is_authenticated') or not st.session_state.get('hf_token'): | |
st.error("Please login with your HuggingFace account first!") | |
return | |
st.session_state[f'selected_prompt_{key}'] = prompt_text | |
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[f'generated_images_{key}'] = results | |
st.success("Artwork generated successfully!") | |
def main(): | |
st.title("๐จ Multi-Model Art Generator") | |
# Handle authentication in sidebar | |
with st.sidebar: | |
st.header("๐ Authentication") | |
if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'): | |
st.success("โ Logged in to HuggingFace") | |
if st.button("Logout"): | |
st.session_state['hf_token'] = None | |
st.session_state['is_authenticated'] = False | |
st.rerun() | |
else: | |
token = st.text_input("Enter HuggingFace Token", type="password", | |
help="Get your token from https://huggingface.co/settings/tokens") | |
if st.button("Login"): | |
if token: | |
try: | |
# Verify token is valid | |
api = HfApi(token=token) | |
api.whoami() | |
st.session_state['hf_token'] = token | |
st.session_state['is_authenticated'] = True | |
st.success("Successfully logged in!") | |
st.rerun() | |
except Exception as e: | |
st.error(f"Authentication failed: {str(e)}") | |
else: | |
st.error("Please enter your HuggingFace token") | |
if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'): | |
st.markdown("---") | |
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 | |
""") | |
# Only show the main interface if authenticated | |
if st.session_state.get('is_authenticated') and st.session_state.get('hf_token'): | |
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:") | |
for key in st.session_state: | |
if key.startswith('selected_prompt_'): | |
idx = key.split('_')[-1] | |
images_key = f'generated_images_{idx}' | |
if images_key in st.session_state: | |
st.write("Prompt:", st.session_state[key]) | |
cols = st.columns(len(st.session_state[images_key])) | |
for col, (model_name, result) in zip(cols, st.session_state[images_key]): | |
with col: | |
st.markdown(f"**{model_name}**") | |
if isinstance(result, str) and result.startswith("Error"): | |
st.error(result) | |
else: | |
st.image(result, use_container_width=True) | |
else: | |
st.info("Please login with your HuggingFace account to use the app") | |
if __name__ == "__main__": | |
main() |