Spaces:
				
			
			
	
			
			
		Runtime error
		
	
	
	
			
			
	
	
	
	
		
		
		Runtime error
		
	Update app.py
Browse files
    	
        app.py
    CHANGED
    
    | @@ -1,51 +1,44 @@ | |
| 1 | 
             
            import gradio as gr
         | 
| 2 | 
             
            from random import randint
         | 
| 3 | 
             
            from all_models import models
         | 
| 4 | 
            -
             | 
| 5 | 
             
            from externalmod import gr_Interface_load, randomize_seed
         | 
| 6 | 
            -
             | 
| 7 | 
             
            import asyncio
         | 
| 8 | 
             
            import os
         | 
| 9 | 
             
            from threading import RLock
         | 
| 10 |  | 
| 11 | 
             
            # Create a lock to ensure thread safety when accessing shared resources
         | 
| 12 | 
             
            lock = RLock()
         | 
|  | |
| 13 | 
             
            # Load Hugging Face token from environment variable, if available
         | 
| 14 | 
            -
            HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None | 
| 15 |  | 
| 16 | 
             
            # Function to load all models specified in the 'models' list
         | 
| 17 | 
             
            def load_fn(models):
         | 
| 18 | 
             
                global models_load
         | 
| 19 | 
             
                models_load = {}
         | 
| 20 | 
            -
             | 
| 21 | 
             
                # Iterate through all models to load them
         | 
| 22 | 
             
                for model in models:
         | 
| 23 | 
             
                    if model not in models_load.keys():
         | 
| 24 | 
             
                        try:
         | 
| 25 | 
            -
                            # Log model loading attempt
         | 
| 26 | 
             
                            print(f"Attempting to load model: {model}")
         | 
| 27 | 
            -
                            # Load model interface using externalmod function
         | 
| 28 | 
             
                            m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
         | 
| 29 | 
             
                            print(f"Successfully loaded model: {model}")
         | 
| 30 | 
             
                        except Exception as error:
         | 
| 31 | 
            -
                            # In case of an error, print it and create a placeholder interface
         | 
| 32 | 
             
                            print(f"Error loading model {model}: {error}")
         | 
| 33 | 
             
                            m = gr.Interface(lambda: None, ['text'], ['image'])
         | 
| 34 | 
            -
                        # Update the models_load dictionary with the loaded model
         | 
| 35 | 
             
                        models_load.update({model: m})
         | 
| 36 |  | 
| 37 | 
            -
            # Load all models defined in the 'models' list
         | 
| 38 | 
             
            print("Loading models...")
         | 
| 39 | 
             
            load_fn(models)
         | 
| 40 | 
             
            print("Models loaded successfully.")
         | 
| 41 |  | 
| 42 | 
            -
            num_models =  | 
| 43 |  | 
| 44 | 
             
            # Set the default models to use for inference
         | 
| 45 | 
             
            default_models = models[:num_models]
         | 
| 46 | 
             
            inference_timeout = 600
         | 
| 47 | 
             
            MAX_SEED = 3999999999
         | 
| 48 | 
            -
            # Generate a starting seed randomly between 1941 and 2024
         | 
| 49 | 
             
            starting_seed = randint(1941, 2024)
         | 
| 50 | 
             
            print(f"Starting seed: {starting_seed}")
         | 
| 51 |  | 
| @@ -65,31 +58,35 @@ def update_imgbox(choices): | |
| 65 | 
             
                return imgboxes
         | 
| 66 |  | 
| 67 | 
             
            # Asynchronous function to perform inference on a given model
         | 
| 68 | 
            -
            async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
         | 
| 69 | 
             
                from pathlib import Path
         | 
| 70 | 
             
                kwargs = {}
         | 
| 71 | 
             
                noise = ""
         | 
| 72 | 
             
                kwargs["seed"] = seed
         | 
| 73 | 
            -
                 | 
| 74 | 
            -
                 | 
| 75 | 
            -
                 | 
| 76 | 
            -
             | 
| 77 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 78 | 
             
                try:
         | 
| 79 | 
            -
                    # Wait for the task to complete within the specified timeout
         | 
| 80 | 
             
                    result = await asyncio.wait_for(task, timeout=timeout)
         | 
| 81 | 
             
                    print(f"Inference completed for model: {model_str}")
         | 
| 82 | 
             
                except (Exception, asyncio.TimeoutError) as e:
         | 
| 83 | 
            -
                    # Handle any exceptions or timeout errors
         | 
| 84 | 
             
                    print(f"Error during inference for model {model_str}: {e}")
         | 
| 85 | 
             
                    if not task.done():
         | 
| 86 | 
             
                        task.cancel()
         | 
| 87 | 
             
                        print(f"Task cancelled for model: {model_str}")
         | 
| 88 | 
             
                    result = None
         | 
| 89 | 
            -
                # If the task completed successfully, save the result as an image
         | 
| 90 | 
             
                if task.done() and result is not None:
         | 
| 91 | 
             
                    with lock:
         | 
| 92 | 
            -
                        png_path = "image. | 
| 93 | 
             
                        result.save(png_path)
         | 
| 94 | 
             
                        image = str(Path(png_path).resolve())
         | 
| 95 | 
             
                        print(f"Result saved as image: {image}")
         | 
| @@ -98,21 +95,20 @@ async def infer(model_str, prompt, seed=1, timeout=inference_timeout): | |
| 98 | 
             
                return None
         | 
| 99 |  | 
| 100 | 
             
            # Function to generate an image based on the given model, prompt, and seed
         | 
| 101 | 
            -
            def gen_fnseed(model_str, prompt, seed=1):
         | 
| 102 | 
             
                if model_str == 'NA':
         | 
| 103 | 
             
                    print(f"Model is 'NA', skipping generation.")
         | 
| 104 | 
             
                    return None
         | 
| 105 | 
             
                try:
         | 
| 106 | 
            -
                     | 
| 107 | 
            -
                    print(f"Generating image for model: {model_str} with prompt: '{prompt}' and seed: {seed}")
         | 
| 108 | 
             
                    loop = asyncio.new_event_loop()
         | 
| 109 | 
            -
                    result = loop.run_until_complete( | 
|  | |
|  | |
| 110 | 
             
                except (Exception, asyncio.CancelledError) as e:
         | 
| 111 | 
            -
                    # Handle any exceptions or cancelled tasks
         | 
| 112 | 
             
                    print(f"Error during generation for model {model_str}: {e}")
         | 
| 113 | 
             
                    result = None
         | 
| 114 | 
             
                finally:
         | 
| 115 | 
            -
                    # Close the event loop
         | 
| 116 | 
             
                    loop.close()
         | 
| 117 | 
             
                    print(f"Event loop closed for model: {model_str}")
         | 
| 118 | 
             
                return result
         | 
| @@ -122,51 +118,41 @@ print("Creating Gradio interface...") | |
| 122 | 
             
            with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
         | 
| 123 | 
             
                gr.HTML("<center><h1>Multi-models-prompt-to-image-generation</h1></center>")
         | 
| 124 | 
             
                with gr.Tab('Compare-6'):
         | 
| 125 | 
            -
                    # Text input for user prompt
         | 
| 126 | 
             
                    txt_input = gr.Textbox(label='Your prompt:', lines=4)
         | 
| 127 | 
            -
                    # Button to generate images
         | 
| 128 | 
             
                    gen_button = gr.Button('Generate up to 6 images in up to 3 minutes total')
         | 
| 129 | 
             
                    with gr.Row():
         | 
| 130 | 
            -
                         | 
| 131 | 
            -
                         | 
| 132 | 
            -
                        # Button to randomize the seed
         | 
| 133 | 
            -
                        seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary", scale=1)    
         | 
| 134 | 
            -
                    # Set up click event to randomize the seed
         | 
| 135 | 
             
                    seed_rand.click(randomize_seed, None, [seed], queue=False)
         | 
| 136 | 
            -
             | 
| 137 | 
            -
                    #  | 
| 138 | 
            -
                     | 
| 139 | 
            -
                     | 
|  | |
| 140 |  | 
| 141 | 
             
                    with gr.Row():
         | 
| 142 | 
            -
                        # Create image output components for each model
         | 
| 143 | 
             
                        output = [gr.Image(label=m, min_width=480) for m in default_models]
         | 
| 144 | 
            -
                        # Create hidden textboxes to store the current models
         | 
| 145 | 
             
                        current_models = [gr.Textbox(m, visible=False) for m in default_models]
         | 
| 146 |  | 
| 147 | 
            -
                        # Set up generation events for each model and output image
         | 
| 148 | 
             
                        for m, o in zip(current_models, output):
         | 
| 149 | 
             
                            print(f"Setting up generation event for model: {m.value}")
         | 
| 150 | 
            -
                            gen_event = gr.on( | 
| 151 | 
            -
             | 
| 152 | 
            -
             | 
| 153 | 
            -
             | 
| 154 | 
            -
             | 
|  | |
|  | |
|  | |
| 155 | 
             
                    with gr.Accordion('Model selection'):
         | 
| 156 | 
            -
                         | 
| 157 | 
            -
                        model_choice = gr.CheckboxGroup(models, label=f'Choose up to {int(num_models)} different models from the {len(models)} available!', value=default_models, interactive=True)
         | 
| 158 | 
            -
                        # Update image boxes and current models based on model selection
         | 
| 159 | 
             
                        model_choice.change(update_imgbox, model_choice, output)
         | 
| 160 | 
             
                        model_choice.change(extend_choices, model_choice, current_models)
         | 
| 161 | 
            -
                        print("Model selection setup complete.")
         | 
| 162 | 
             
                    with gr.Row():
         | 
| 163 | 
            -
                         | 
| 164 | 
            -
                        gr.HTML(
         | 
| 165 | 
            -
            )
         | 
| 166 |  | 
| 167 | 
            -
            # Queue settings for handling multiple concurrent requests
         | 
| 168 | 
             
            print("Setting up queue...")
         | 
| 169 | 
             
            demo.queue(default_concurrency_limit=200, max_size=200)
         | 
| 170 | 
             
            print("Launching Gradio interface...")
         | 
| 171 | 
             
            demo.launch(show_api=False, max_threads=400)
         | 
| 172 | 
            -
            print("Gradio interface launched successfully.")
         | 
|  | |
| 1 | 
             
            import gradio as gr
         | 
| 2 | 
             
            from random import randint
         | 
| 3 | 
             
            from all_models import models
         | 
|  | |
| 4 | 
             
            from externalmod import gr_Interface_load, randomize_seed
         | 
|  | |
| 5 | 
             
            import asyncio
         | 
| 6 | 
             
            import os
         | 
| 7 | 
             
            from threading import RLock
         | 
| 8 |  | 
| 9 | 
             
            # Create a lock to ensure thread safety when accessing shared resources
         | 
| 10 | 
             
            lock = RLock()
         | 
| 11 | 
            +
             | 
| 12 | 
             
            # Load Hugging Face token from environment variable, if available
         | 
| 13 | 
            +
            HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None  # If private or gated models aren't used, ENV setting is unnecessary.
         | 
| 14 |  | 
| 15 | 
             
            # Function to load all models specified in the 'models' list
         | 
| 16 | 
             
            def load_fn(models):
         | 
| 17 | 
             
                global models_load
         | 
| 18 | 
             
                models_load = {}
         | 
| 19 | 
            +
             | 
| 20 | 
             
                # Iterate through all models to load them
         | 
| 21 | 
             
                for model in models:
         | 
| 22 | 
             
                    if model not in models_load.keys():
         | 
| 23 | 
             
                        try:
         | 
|  | |
| 24 | 
             
                            print(f"Attempting to load model: {model}")
         | 
|  | |
| 25 | 
             
                            m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
         | 
| 26 | 
             
                            print(f"Successfully loaded model: {model}")
         | 
| 27 | 
             
                        except Exception as error:
         | 
|  | |
| 28 | 
             
                            print(f"Error loading model {model}: {error}")
         | 
| 29 | 
             
                            m = gr.Interface(lambda: None, ['text'], ['image'])
         | 
|  | |
| 30 | 
             
                        models_load.update({model: m})
         | 
| 31 |  | 
|  | |
| 32 | 
             
            print("Loading models...")
         | 
| 33 | 
             
            load_fn(models)
         | 
| 34 | 
             
            print("Models loaded successfully.")
         | 
| 35 |  | 
| 36 | 
            +
            num_models = 6
         | 
| 37 |  | 
| 38 | 
             
            # Set the default models to use for inference
         | 
| 39 | 
             
            default_models = models[:num_models]
         | 
| 40 | 
             
            inference_timeout = 600
         | 
| 41 | 
             
            MAX_SEED = 3999999999
         | 
|  | |
| 42 | 
             
            starting_seed = randint(1941, 2024)
         | 
| 43 | 
             
            print(f"Starting seed: {starting_seed}")
         | 
| 44 |  | 
|  | |
| 58 | 
             
                return imgboxes
         | 
| 59 |  | 
| 60 | 
             
            # Asynchronous function to perform inference on a given model
         | 
| 61 | 
            +
            async def infer(model_str, prompt, seed=1, batch_size=1, output_format="PNG", priority="medium", timeout=inference_timeout):
         | 
| 62 | 
             
                from pathlib import Path
         | 
| 63 | 
             
                kwargs = {}
         | 
| 64 | 
             
                noise = ""
         | 
| 65 | 
             
                kwargs["seed"] = seed
         | 
| 66 | 
            +
                kwargs["batch_size"] = batch_size
         | 
| 67 | 
            +
                kwargs["priority"] = priority
         | 
| 68 | 
            +
                print(f"Starting inference for model: {model_str} with prompt: '{prompt}' and seed: {seed}, batch_size: {batch_size}, priority: {priority}")
         | 
| 69 | 
            +
                task = asyncio.create_task(
         | 
| 70 | 
            +
                    asyncio.to_thread(
         | 
| 71 | 
            +
                        models_load[model_str].fn,
         | 
| 72 | 
            +
                        prompt=f'{prompt} {noise}',
         | 
| 73 | 
            +
                        **kwargs,
         | 
| 74 | 
            +
                        token=HF_TOKEN
         | 
| 75 | 
            +
                    )
         | 
| 76 | 
            +
                )
         | 
| 77 | 
            +
                await asyncio.sleep(0)
         | 
| 78 | 
             
                try:
         | 
|  | |
| 79 | 
             
                    result = await asyncio.wait_for(task, timeout=timeout)
         | 
| 80 | 
             
                    print(f"Inference completed for model: {model_str}")
         | 
| 81 | 
             
                except (Exception, asyncio.TimeoutError) as e:
         | 
|  | |
| 82 | 
             
                    print(f"Error during inference for model {model_str}: {e}")
         | 
| 83 | 
             
                    if not task.done():
         | 
| 84 | 
             
                        task.cancel()
         | 
| 85 | 
             
                        print(f"Task cancelled for model: {model_str}")
         | 
| 86 | 
             
                    result = None
         | 
|  | |
| 87 | 
             
                if task.done() and result is not None:
         | 
| 88 | 
             
                    with lock:
         | 
| 89 | 
            +
                        png_path = f"image.{output_format.lower()}"
         | 
| 90 | 
             
                        result.save(png_path)
         | 
| 91 | 
             
                        image = str(Path(png_path).resolve())
         | 
| 92 | 
             
                        print(f"Result saved as image: {image}")
         | 
|  | |
| 95 | 
             
                return None
         | 
| 96 |  | 
| 97 | 
             
            # Function to generate an image based on the given model, prompt, and seed
         | 
| 98 | 
            +
            def gen_fnseed(model_str, prompt, seed=1, batch_size=1, output_format="PNG", priority="medium"):
         | 
| 99 | 
             
                if model_str == 'NA':
         | 
| 100 | 
             
                    print(f"Model is 'NA', skipping generation.")
         | 
| 101 | 
             
                    return None
         | 
| 102 | 
             
                try:
         | 
| 103 | 
            +
                    print(f"Generating image for model: {model_str} with prompt: '{prompt}', seed: {seed}, batch_size: {batch_size}, priority: {priority}")
         | 
|  | |
| 104 | 
             
                    loop = asyncio.new_event_loop()
         | 
| 105 | 
            +
                    result = loop.run_until_complete(
         | 
| 106 | 
            +
                        infer(model_str, prompt, seed, batch_size=batch_size, output_format=output_format, priority=priority)
         | 
| 107 | 
            +
                    )
         | 
| 108 | 
             
                except (Exception, asyncio.CancelledError) as e:
         | 
|  | |
| 109 | 
             
                    print(f"Error during generation for model {model_str}: {e}")
         | 
| 110 | 
             
                    result = None
         | 
| 111 | 
             
                finally:
         | 
|  | |
| 112 | 
             
                    loop.close()
         | 
| 113 | 
             
                    print(f"Event loop closed for model: {model_str}")
         | 
| 114 | 
             
                return result
         | 
|  | |
| 118 | 
             
            with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
         | 
| 119 | 
             
                gr.HTML("<center><h1>Multi-models-prompt-to-image-generation</h1></center>")
         | 
| 120 | 
             
                with gr.Tab('Compare-6'):
         | 
|  | |
| 121 | 
             
                    txt_input = gr.Textbox(label='Your prompt:', lines=4)
         | 
|  | |
| 122 | 
             
                    gen_button = gr.Button('Generate up to 6 images in up to 3 minutes total')
         | 
| 123 | 
             
                    with gr.Row():
         | 
| 124 | 
            +
                        seed = gr.Slider(label="Seed (max 3999999999)", minimum=0, maximum=MAX_SEED, step=1, value=starting_seed, scale=3)
         | 
| 125 | 
            +
                        seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary", scale=1)
         | 
|  | |
|  | |
|  | |
| 126 | 
             
                    seed_rand.click(randomize_seed, None, [seed], queue=False)
         | 
| 127 | 
            +
             | 
| 128 | 
            +
                    # Add batch size slider
         | 
| 129 | 
            +
                    batch_size_slider = gr.Slider(label="Batch Size", minimum=1, maximum=10, step=1, value=1)
         | 
| 130 | 
            +
                    output_format_dropdown = gr.Dropdown(["PNG", "JPEG"], label="Output Format", value="PNG")
         | 
| 131 | 
            +
                    priority_dropdown = gr.Dropdown(["low", "medium", "high"], label="Model Priority", value="medium")
         | 
| 132 |  | 
| 133 | 
             
                    with gr.Row():
         | 
|  | |
| 134 | 
             
                        output = [gr.Image(label=m, min_width=480) for m in default_models]
         | 
|  | |
| 135 | 
             
                        current_models = [gr.Textbox(m, visible=False) for m in default_models]
         | 
| 136 |  | 
|  | |
| 137 | 
             
                        for m, o in zip(current_models, output):
         | 
| 138 | 
             
                            print(f"Setting up generation event for model: {m.value}")
         | 
| 139 | 
            +
                            gen_event = gr.on(
         | 
| 140 | 
            +
                                triggers=[gen_button.click, txt_input.submit],
         | 
| 141 | 
            +
                                fn=gen_fnseed,
         | 
| 142 | 
            +
                                inputs=[m, txt_input, seed, batch_size_slider, output_format_dropdown, priority_dropdown],
         | 
| 143 | 
            +
                                outputs=[o],
         | 
| 144 | 
            +
                                concurrency_limit=None,
         | 
| 145 | 
            +
                                queue=False
         | 
| 146 | 
            +
                            )
         | 
| 147 | 
             
                    with gr.Accordion('Model selection'):
         | 
| 148 | 
            +
                        model_choice = gr.CheckboxGroup(models, label=f'Choose up to {int(num_models)} different models!', value=default_models, interactive=True)
         | 
|  | |
|  | |
| 149 | 
             
                        model_choice.change(update_imgbox, model_choice, output)
         | 
| 150 | 
             
                        model_choice.change(extend_choices, model_choice, current_models)
         | 
|  | |
| 151 | 
             
                    with gr.Row():
         | 
| 152 | 
            +
                        gr.HTML("<p>Additional UI elements can go here</p>")
         | 
|  | |
|  | |
| 153 |  | 
|  | |
| 154 | 
             
            print("Setting up queue...")
         | 
| 155 | 
             
            demo.queue(default_concurrency_limit=200, max_size=200)
         | 
| 156 | 
             
            print("Launching Gradio interface...")
         | 
| 157 | 
             
            demo.launch(show_api=False, max_threads=400)
         | 
| 158 | 
            +
            print("Gradio interface launched successfully.")
         | 
