import gradio as gr from random import randint from all_models import models from externalmod import gr_Interface_load, randomize_seed import asyncio import os from threading import RLock # Create a lock to ensure thread safety when accessing shared resources lock = RLock() # Load Hugging Face token from environment variable, if available 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. # Function to load all models specified in the 'models' list def load_fn(models): global models_load models_load = {} # Iterate through all models to load them for model in models: if model not in models_load.keys(): try: # Log model loading attempt print(f"Attempting to load model: {model}") # Load model interface using externalmod function m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN) print(f"Successfully loaded model: {model}") except Exception as error: # In case of an error, print it and create a placeholder interface print(f"Error loading model {model}: {error}") m = gr.Interface(lambda: None, ['text'], ['image']) # Update the models_load dictionary with the loaded model models_load.update({model: m}) # Load all models defined in the 'models' list print("Loading models...") load_fn(models) print("Models loaded successfully.") num_models = 6 # Set the default models to use for inference default_models = models[:num_models] inference_timeout = 600 MAX_SEED = 3999999999 # Generate a starting seed randomly between 1941 and 2024 starting_seed = randint(1941, 2024) print(f"Starting seed: {starting_seed}") # Extend the choices list to ensure it contains 'num_models' elements def extend_choices(choices): print(f"Extending choices: {choices}") extended = choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA'] print(f"Extended choices: {extended}") return extended # Update the image boxes based on selected models def update_imgbox(choices): print(f"Updating image boxes with choices: {choices}") choices_plus = extend_choices(choices[:num_models]) imgboxes = [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_plus] print(f"Updated image boxes: {imgboxes}") return imgboxes # Asynchronous function to perform inference on a given model async def infer(model_str, prompt, seed=1, timeout=inference_timeout): from pathlib import Path kwargs = {} noise = "" kwargs["seed"] = seed # Create an asynchronous task to run the model inference print(f"Starting inference for model: {model_str} with prompt: '{prompt}' and seed: {seed}") task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=f'{prompt} {noise}', **kwargs, token=HF_TOKEN)) await asyncio.sleep(0) # Allow other tasks to run try: # Wait for the task to complete within the specified timeout result = await asyncio.wait_for(task, timeout=timeout) print(f"Inference completed for model: {model_str}") except (Exception, asyncio.TimeoutError) as e: # Handle any exceptions or timeout errors print(f"Error during inference for model {model_str}: {e}") if not task.done(): task.cancel() print(f"Task cancelled for model: {model_str}") result = None # If the task completed successfully, save the result as an image if task.done() and result is not None: with lock: png_path = "image.png" result.save(png_path) image = str(Path(png_path).resolve()) print(f"Result saved as image: {image}") return image print(f"No result for model: {model_str}") return None # Function to generate an image based on the given model, prompt, and seed def gen_fnseed(model_str, prompt, seed=1): if model_str == 'NA': print(f"Model is 'NA', skipping generation.") return None try: # Create a new event loop to run the asynchronous inference function print(f"Generating image for model: {model_str} with prompt: '{prompt}' and seed: {seed}") loop = asyncio.new_event_loop() result = loop.run_until_complete(infer(model_str, prompt, seed, inference_timeout)) except (Exception, asyncio.CancelledError) as e: # Handle any exceptions or cancelled tasks print(f"Error during generation for model {model_str}: {e}") result = None finally: # Close the event loop loop.close() print(f"Event loop closed for model: {model_str}") return result # Create the Gradio Blocks interface with a custom theme print("Creating Gradio interface...") with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo: gr.HTML("