Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,172 +1,100 @@
|
|
| 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
|
| 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 # If private or gated models aren't used, ENV setting is unnecessary.
|
| 15 |
|
| 16 |
-
#
|
|
|
|
|
|
|
|
|
|
| 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
|
| 24 |
try:
|
| 25 |
-
|
| 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 |
-
|
| 30 |
-
except Exception as
|
| 31 |
-
|
| 32 |
-
|
| 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 = 6
|
| 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 |
-
|
|
|
|
| 51 |
|
| 52 |
-
# Extend the choices list to ensure it contains 'num_models' elements
|
| 53 |
def extend_choices(choices):
|
| 54 |
-
|
| 55 |
-
extended = choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
|
| 56 |
-
print(f"Extended choices: {extended}")
|
| 57 |
-
return extended
|
| 58 |
|
| 59 |
-
# Update the image boxes based on selected models
|
| 60 |
def update_imgbox(choices):
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
imgboxes = [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_plus]
|
| 64 |
-
print(f"Updated image boxes: {imgboxes}")
|
| 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 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
kwargs
|
| 73 |
-
# Create an asynchronous task to run the model inference
|
| 74 |
-
print(f"Starting inference for model: {model_str} with prompt: '{prompt}' and seed: {seed}")
|
| 75 |
-
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
|
| 76 |
-
prompt=f'{prompt} {noise}', **kwargs, token=HF_TOKEN))
|
| 77 |
-
await asyncio.sleep(0) # Allow other tasks to run
|
| 78 |
try:
|
| 79 |
-
|
| 80 |
-
result = await asyncio.
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 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.png"
|
| 93 |
-
result.save(png_path)
|
| 94 |
-
image = str(Path(png_path).resolve())
|
| 95 |
-
print(f"Result saved as image: {image}")
|
| 96 |
-
return image
|
| 97 |
-
print(f"No result for model: {model_str}")
|
| 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 |
-
# Create a new event loop to run the asynchronous inference function
|
| 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(infer(model_str, prompt, seed, inference_timeout))
|
| 110 |
-
except
|
| 111 |
-
|
| 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
|
| 119 |
|
| 120 |
-
# Create the Gradio Blocks interface with a custom theme
|
| 121 |
print("Creating Gradio interface...")
|
| 122 |
with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
|
| 123 |
gr.HTML("<center><h1>Compare-6</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 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
seed = gr.Slider(label="Use a seed to replicate the same image later (maximum 3999999999)", minimum=0, maximum=MAX_SEED, step=1, value=starting_seed, scale=3)
|
| 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 |
-
|
| 142 |
-
|
| 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(triggers=[gen_button.click, txt_input.submit], fn=gen_fnseed,
|
| 151 |
-
inputs=[m, txt_input, seed], outputs=[o], concurrency_limit=None, queue=False)
|
| 152 |
-
# The commented stop button could be used to cancel the generation event
|
| 153 |
-
#stop_button.click(lambda s: gr.update(interactive=False), None, stop_button, cancels=[gen_event])
|
| 154 |
-
# Accordion to allow model selection
|
| 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 |
-
# Placeholder HTML to add additional UI elements if needed
|
| 164 |
-
gr.HTML(
|
| 165 |
-
)
|
| 166 |
|
| 167 |
-
|
| 168 |
-
|
| 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 |
+
from pathlib import Path
|
| 9 |
|
| 10 |
+
# Create a lock for thread safety
|
| 11 |
lock = RLock()
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
# Load Hugging Face token from environment variable (if available)
|
| 14 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 15 |
+
|
| 16 |
+
# Function to load models
|
| 17 |
def load_fn(models):
|
| 18 |
global models_load
|
| 19 |
models_load = {}
|
|
|
|
|
|
|
| 20 |
for model in models:
|
| 21 |
+
if model not in models_load:
|
| 22 |
try:
|
| 23 |
+
print(f"Loading model: {model}")
|
|
|
|
|
|
|
| 24 |
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
| 25 |
+
models_load[model] = m
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"Error loading model {model}: {e}")
|
| 28 |
+
models_load[model] = gr.Interface(lambda: None, ['text'], ['image'])
|
|
|
|
|
|
|
|
|
|
| 29 |
|
|
|
|
| 30 |
print("Loading models...")
|
| 31 |
load_fn(models)
|
| 32 |
print("Models loaded successfully.")
|
| 33 |
|
| 34 |
num_models = 6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
starting_seed = randint(1941, 2024)
|
| 36 |
+
MAX_SEED = 3999999999
|
| 37 |
+
inference_timeout = 600
|
| 38 |
|
|
|
|
| 39 |
def extend_choices(choices):
|
| 40 |
+
return choices[:num_models] + ['NA'] * (num_models - len(choices))
|
|
|
|
|
|
|
|
|
|
| 41 |
|
|
|
|
| 42 |
def update_imgbox(choices):
|
| 43 |
+
choices_extended = extend_choices(choices)
|
| 44 |
+
return [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_extended]
|
|
|
|
|
|
|
|
|
|
| 45 |
|
|
|
|
| 46 |
async def infer(model_str, prompt, seed=1, timeout=inference_timeout):
|
| 47 |
+
if model_str not in models_load:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
kwargs = {"seed": seed}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
+
print(f"Running inference for model: {model_str} with prompt: '{prompt}'")
|
| 53 |
+
result = await asyncio.to_thread(models_load[model_str].fn, prompt=prompt, **kwargs, token=HF_TOKEN)
|
| 54 |
+
if result:
|
| 55 |
+
with lock:
|
| 56 |
+
png_path = "image.png"
|
| 57 |
+
result.save(png_path)
|
| 58 |
+
return str(Path(png_path).resolve())
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"Error during inference for {model_str}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
return None
|
| 62 |
|
|
|
|
| 63 |
def gen_fnseed(model_str, prompt, seed=1):
|
| 64 |
if model_str == 'NA':
|
|
|
|
| 65 |
return None
|
| 66 |
try:
|
|
|
|
|
|
|
| 67 |
loop = asyncio.new_event_loop()
|
| 68 |
+
asyncio.set_event_loop(loop)
|
| 69 |
result = loop.run_until_complete(infer(model_str, prompt, seed, inference_timeout))
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print(f"Error generating image for {model_str}: {e}")
|
|
|
|
| 72 |
result = None
|
| 73 |
finally:
|
|
|
|
| 74 |
loop.close()
|
|
|
|
| 75 |
return result
|
| 76 |
|
|
|
|
| 77 |
print("Creating Gradio interface...")
|
| 78 |
with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
|
| 79 |
gr.HTML("<center><h1>Compare-6</h1></center>")
|
| 80 |
with gr.Tab('Compare-6'):
|
|
|
|
| 81 |
txt_input = gr.Textbox(label='Your prompt:', lines=4)
|
| 82 |
+
gen_button = gr.Button('Generate up to 6 images')
|
| 83 |
+
seed = gr.Slider("Seed (0 to MAX)", minimum=0, maximum=MAX_SEED, value=starting_seed)
|
| 84 |
+
seed_rand = gr.Button("Randomize Seed 🎲")
|
| 85 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
seed_rand.click(randomize_seed, None, [seed], queue=False)
|
| 87 |
+
|
| 88 |
+
output = [gr.Image(label=m) for m in models[:num_models]]
|
| 89 |
+
current_models = [gr.Textbox(m, visible=False) for m in models[:num_models]]
|
| 90 |
+
|
| 91 |
+
for m, o in zip(current_models, output):
|
| 92 |
+
gen_button.click(gen_fnseed, inputs=[m, txt_input, seed], outputs=[o], queue=False)
|
| 93 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
with gr.Accordion('Model selection'):
|
| 95 |
+
model_choice = gr.CheckboxGroup(models, label=f'Choose up to {num_models} models')
|
|
|
|
|
|
|
| 96 |
model_choice.change(update_imgbox, model_choice, output)
|
| 97 |
model_choice.change(extend_choices, model_choice, current_models)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
demo.queue(default_concurrency_limit=50, max_size=100)
|
| 100 |
+
demo.launch(show_api=False)
|
|
|
|
|
|
|
|
|
|
|
|