CoolFace
Apppublic

GPUModelSpotlight/Analysis-Of-Image-Song-Video-Prompts

sourceHugging Facemitupdated 2y agoView on Hugging Face
1likes
app.py284 linesDownload Raw Back to root
1import streamlit as st2from gradio_client import Client3import time4import concurrent.futures5import os6from PIL import Image7import io8import requests9 10# Get token from environment variable11HF_TOKEN = os.getenv('ArtToken')12if not HF_TOKEN:13    raise ValueError("Please set the 'ArtToken' environment variable with your Hugging Face token")14 15class ModelGenerator:16    @staticmethod17    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 different types of results34            if isinstance(result, tuple):35                # If it's a tuple, the first element might be the image gallery36                if len(result) > 0 and isinstance(result[0], list):37                    image_data = result[0][0]  # Get first image from gallery38                    if isinstance(image_data, dict) and 'image' in image_data:39                        return ("Midjourney", image_data['image'])40                    elif isinstance(image_data, (str, bytes)):41                        return ("Midjourney", image_data)42                else:43                    return ("Midjourney", result[0])  # Try first element of tuple44            elif isinstance(result, list) and len(result) > 0:45                # If it's a list, get the first element46                image_data = result[0]47                if isinstance(image_data, dict) and 'image' in image_data:48                    return ("Midjourney", image_data['image'])49                else:50                    return ("Midjourney", image_data)51            elif isinstance(result, str):52                # If it's a direct string (URL or path)53                return ("Midjourney", result)54            else:55                return ("Midjourney", f"Error: Unexpected result format: {type(result)}")56        except Exception as e:57            return ("Midjourney", f"Error: {str(e)}")58 59    @staticmethod60    def generate_stable_cascade(prompt):61        try:62            client = Client("multimodalart/stable-cascade", hf_token=HF_TOKEN)63            result = client.predict(64                prompt=prompt,65                negative_prompt=prompt,66                seed=0,67                width=1024,68                height=1024,69                prior_num_inference_steps=20,70                prior_guidance_scale=4,71                decoder_num_inference_steps=10,72                decoder_guidance_scale=0,73                num_images_per_prompt=1,74                api_name="/run"75            )76            return ("Stable Cascade", result)77        except Exception as e:78            return ("Stable Cascade", f"Error: {str(e)}")79 80    @staticmethod81    def generate_stable_diffusion_3(prompt):82        try:83            client = Client("stabilityai/stable-diffusion-3-medium", hf_token=HF_TOKEN)84            result = client.predict(85                prompt=prompt,86                negative_prompt=prompt,87                seed=0,88                randomize_seed=True,89                width=1024,90                height=1024,91                guidance_scale=5,92                num_inference_steps=28,93                api_name="/infer"94            )95            return ("SD 3 Medium", result)96        except Exception as e:97            return ("SD 3 Medium", f"Error: {str(e)}")98 99    @staticmethod100    def generate_stable_diffusion_35(prompt):101        try:102            client = Client("stabilityai/stable-diffusion-3.5-large", hf_token=HF_TOKEN)103            result = client.predict(104                prompt=prompt,105                negative_prompt=prompt,106                seed=0,107                randomize_seed=True,108                width=1024,109                height=1024,110                guidance_scale=4.5,111                num_inference_steps=40,112                api_name="/infer"113            )114            return ("SD 3.5 Large", result)115        except Exception as e:116            return ("SD 3.5 Large", f"Error: {str(e)}")117 118    @staticmethod119    def generate_playground_v2_5(prompt):120        try:121            client = Client("https://playgroundai-playground-v2-5.hf.space/--replicas/ji5gy/", hf_token=HF_TOKEN)122            result = client.predict(123                prompt,124                prompt,  # negative prompt125                True,    # use negative prompt126                0,      # seed127                1024,   # width128                1024,   # height129                7.5,    # guidance scale130                True,   # randomize seed131                api_name="/run"132            )133            # Result is a tuple (gallery, seed), we want just the first image from gallery134            if result and isinstance(result, tuple) and result[0]:135                return ("Playground v2.5", result[0][0]['image'])136            return ("Playground v2.5", "Error: No image generated")137        except Exception as e:138            return ("Playground v2.5", f"Error: {str(e)}")139 140def generate_images(prompt, selected_models):141    results = []142    with concurrent.futures.ThreadPoolExecutor() as executor:143        futures = []144        model_map = {145            "Midjourney": ModelGenerator.generate_midjourney,146            "Stable Cascade": ModelGenerator.generate_stable_cascade,147            "SD 3 Medium": ModelGenerator.generate_stable_diffusion_3,148            "SD 3.5 Large": ModelGenerator.generate_stable_diffusion_35,149            "Playground v2.5": ModelGenerator.generate_playground_v2_5150        }151        152        for model in selected_models:153            if model in model_map:154                futures.append(executor.submit(model_map[model], prompt))155        156        for future in concurrent.futures.as_completed(futures):157            results.append(future.result())158    159    return results160 161def handle_prompt_click(prompt_text, key):162    if not HF_TOKEN:163        st.error("Environment variable 'ArtToken' is not set!")164        return165        166    st.session_state[f'selected_prompt_{key}'] = prompt_text167    168    selected_models = st.session_state.get('selected_models', [])169    170    if not selected_models:171        st.warning("Please select at least one model from the sidebar!")172        return173 174    with st.spinner('Generating artwork...'):175        results = generate_images(prompt_text, selected_models)176        st.session_state[f'generated_images_{key}'] = results177        st.success("Artwork generated successfully!")178 179def main():180    st.title("๐ŸŽจ Multi-Model Art Generator")181 182    with st.sidebar:183        st.header("Configuration")184        185        # Show token status186        if HF_TOKEN:187            st.success("โœ“ ArtToken loaded from environment")188        else:189            st.error("โš  ArtToken not found in environment")190        191        st.markdown("---")192        st.header("Model Selection")193        st.session_state['selected_models'] = st.multiselect(194            "Choose AI Models",195            ["Midjourney", "Stable Cascade", "SD 3 Medium", "SD 3.5 Large", "Playground v2.5"],196            default=["Midjourney"]197        )198        199        st.markdown("---")200        st.markdown("### Selected Models:")201        for model in st.session_state['selected_models']:202            st.write(f"โœ“ {model}")203        204        st.markdown("---")205        st.markdown("### Model Information:")206        st.markdown("""207        - **Midjourney**: Best for artistic and creative imagery208        - **Stable Cascade**: New architecture with high detail209        - **SD 3 Medium**: Fast and efficient generation210        - **SD 3.5 Large**: Highest quality, slower generation211        - **Playground v2.5**: Advanced model with high customization212        """)213 214    st.markdown("### Select a prompt style to generate artwork:")215 216    prompt_emojis = {217        "AIart/AIArtistCommunity": "๐Ÿค–",218        "Black & White": "โšซโšช",219        "Black & Yellow": "โšซ๐Ÿ’›",220        "Blindfold": "๐Ÿ™ˆ",221        "Break": "๐Ÿ’”",222        "Broken": "๐Ÿ”จ",223        "Christmas Celebrations art": "๐ŸŽ„",224        "Colorful Art": "๐ŸŽจ",225        "Crimson art": "๐Ÿ”ด",226        "Eyes Art": "๐Ÿ‘๏ธ",227        "Going out with Style": "๐Ÿ’ƒ",228        "Hooded Girl": "๐Ÿงฅ",229        "Lips": "๐Ÿ‘„",230        "MAEKHLONG": "๐Ÿฎ",231        "Mermaid": "๐Ÿงœโ€โ™€๏ธ",232        "Morning Sunshine": "๐ŸŒ…",233        "Music Art": "๐ŸŽต",234        "Owl": "๐Ÿฆ‰",235        "Pink": "๐Ÿ’—",236        "Purple": "๐Ÿ’œ",237        "Rain": "๐ŸŒง๏ธ",238        "Red Moon": "๐ŸŒ‘",239        "Rose": "๐ŸŒน",240        "Snow": "โ„๏ธ",241        "Spacesuit Girl": "๐Ÿ‘ฉโ€๐Ÿš€",242        "Steampunk": "โš™๏ธ",243        "Succubus": "๐Ÿ˜ˆ",244        "Sunlight": "โ˜€๏ธ",245        "Weird art": "๐ŸŽญ",246        "White Hair": "๐Ÿ‘ฑโ€โ™€๏ธ",247        "Wings art": "๐Ÿ‘ผ",248        "Woman with Sword": "โš”๏ธ"249    }250 251    col1, col2, col3 = st.columns(3)252    253    for idx, (prompt, emoji) in enumerate(prompt_emojis.items()):254        full_prompt = f"QT {prompt}"255        col = [col1, col2, col3][idx % 3]256        257        with col:258            if st.button(f"{emoji} {prompt}", key=f"btn_{idx}"):259                handle_prompt_click(full_prompt, idx)260 261    st.markdown("---")262    st.markdown("### Generated Artwork:")263    264    for key in st.session_state:265        if key.startswith('selected_prompt_'):266            idx = key.split('_')[-1]267            images_key = f'generated_images_{idx}'268            269            if images_key in st.session_state:270                st.write("Prompt:", st.session_state[key])271                272                cols = st.columns(len(st.session_state[images_key]))273                274                for col, (model_name, result) in zip(cols, st.session_state[images_key]):275                    with col:276                        st.markdown(f"**{model_name}**")277                        if isinstance(result, str) and result.startswith("Error"):278                            st.error(result)279                        else:280                            # Updated to use use_container_width instead of use_column_width281                            st.image(result, use_container_width=True)282 283if __name__ == "__main__":284    main()