Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -9,150 +9,124 @@ from threading import RLock
|
|
9 |
# Create a lock to ensure thread safety when accessing shared resources
|
10 |
lock = RLock()
|
11 |
|
12 |
-
# Load Hugging Face token from environment variable
|
13 |
-
HF_TOKEN = os.environ.get("HF_TOKEN"
|
14 |
|
15 |
-
#
|
16 |
-
def
|
17 |
-
global
|
18 |
-
|
19 |
-
|
20 |
-
# Iterate through all models to load them
|
21 |
for model in models:
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
models_load.update({model: m})
|
31 |
|
32 |
print("Loading models...")
|
33 |
-
|
34 |
-
print("Models loaded
|
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 |
|
45 |
-
# Extend
|
46 |
def extend_choices(choices):
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
# Update the image boxes based on selected models
|
53 |
-
def update_imgbox(choices):
|
54 |
-
print(f"Updating image boxes with choices: {choices}")
|
55 |
-
choices_plus = extend_choices(choices[:num_models])
|
56 |
-
imgboxes = [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_plus]
|
57 |
-
print(f"Updated image boxes: {imgboxes}")
|
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 |
-
|
81 |
-
except
|
82 |
-
print(f"
|
83 |
-
|
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}")
|
93 |
-
return image
|
94 |
-
print(f"No result for model: {model_str}")
|
95 |
-
return None
|
96 |
|
97 |
-
#
|
98 |
-
def
|
99 |
-
if
|
100 |
-
print(f"
|
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(
|
107 |
)
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
|
|
|
|
|
|
111 |
finally:
|
112 |
loop.close()
|
113 |
-
print(f"Event loop closed for model: {model_str}")
|
114 |
-
return result
|
115 |
|
116 |
-
|
|
|
|
|
117 |
print("Creating Gradio interface...")
|
118 |
with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
|
119 |
-
gr.HTML("<center><h1>Multi-
|
120 |
-
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
123 |
with gr.Row():
|
124 |
-
seed = gr.Slider(label="Seed
|
125 |
-
seed_rand = gr.Button("Randomize Seed 🎲"
|
126 |
-
|
|
|
|
|
127 |
|
128 |
-
|
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 |
-
|
135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
-
for
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
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
|
158 |
-
print("Gradio interface launched successfully.")
|
|
|
9 |
# Create a lock to ensure thread safety when accessing shared resources
|
10 |
lock = RLock()
|
11 |
|
12 |
+
# Load Hugging Face token from environment variable
|
13 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", None)
|
14 |
|
15 |
+
# Load models
|
16 |
+
def load_models(models):
|
17 |
+
global models_loaded
|
18 |
+
models_loaded = {}
|
|
|
|
|
19 |
for model in models:
|
20 |
+
try:
|
21 |
+
print(f"Loading model: {model}")
|
22 |
+
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
23 |
+
print(f"Successfully loaded model: {model}")
|
24 |
+
models_loaded[model] = m
|
25 |
+
except Exception as e:
|
26 |
+
print(f"Error loading model {model}: {e}")
|
27 |
+
models_loaded[model] = None
|
|
|
28 |
|
29 |
print("Loading models...")
|
30 |
+
load_models(models)
|
31 |
+
print("Models loaded.")
|
32 |
|
33 |
+
# Global variables
|
34 |
num_models = 6
|
|
|
|
|
|
|
35 |
inference_timeout = 600
|
36 |
MAX_SEED = 3999999999
|
37 |
starting_seed = randint(1941, 2024)
|
|
|
38 |
|
39 |
+
# Extend model choices to match the required number
|
40 |
def extend_choices(choices):
|
41 |
+
return choices[:num_models] + (['NA'] * (num_models - len(choices[:num_models])))
|
42 |
+
|
43 |
+
# Function to perform inference asynchronously
|
44 |
+
async def infer(model_name, prompt, seed, batch_size, priority, timeout):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
try:
|
46 |
+
kwargs = {"seed": seed, "batch_size": batch_size, "priority": priority}
|
47 |
+
print(f"Running inference for model: {model_name} with prompt: {prompt} and seed: {seed}")
|
48 |
+
|
49 |
+
task = asyncio.create_task(
|
50 |
+
asyncio.to_thread(
|
51 |
+
models_loaded[model_name].fn,
|
52 |
+
prompt=prompt,
|
53 |
+
**kwargs,
|
54 |
+
token=HF_TOKEN
|
55 |
+
)
|
56 |
+
)
|
57 |
result = await asyncio.wait_for(task, timeout=timeout)
|
58 |
+
return result
|
59 |
+
except Exception as e:
|
60 |
+
print(f"Inference failed for model {model_name}: {e}")
|
61 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
+
# Generate images for each model
|
64 |
+
def generate_image(model_name, prompt, seed, batch_size, output_format, priority):
|
65 |
+
if model_name == 'NA' or models_loaded.get(model_name) is None:
|
66 |
+
print(f"Skipping model: {model_name} (Not available or NA)")
|
67 |
return None
|
68 |
+
|
69 |
try:
|
|
|
70 |
loop = asyncio.new_event_loop()
|
71 |
+
asyncio.set_event_loop(loop)
|
72 |
result = loop.run_until_complete(
|
73 |
+
infer(model_name, prompt, seed, batch_size, priority, inference_timeout)
|
74 |
)
|
75 |
+
if result:
|
76 |
+
output_path = f"output.{output_format.lower()}"
|
77 |
+
result.save(output_path)
|
78 |
+
print(f"Image saved: {output_path}")
|
79 |
+
return output_path
|
80 |
+
except Exception as e:
|
81 |
+
print(f"Error generating image for model {model_name}: {e}")
|
82 |
finally:
|
83 |
loop.close()
|
|
|
|
|
84 |
|
85 |
+
return None
|
86 |
+
|
87 |
+
# Gradio Interface
|
88 |
print("Creating Gradio interface...")
|
89 |
with gr.Blocks(theme="Nymbo/Nymbo_Theme") as demo:
|
90 |
+
gr.HTML("<center><h1>Multi-Model Prompt-to-Image Generator</h1></center>")
|
91 |
+
|
92 |
+
# Input area
|
93 |
+
with gr.Tab('Generate'):
|
94 |
+
txt_input = gr.Textbox(label='Your Prompt', lines=4)
|
95 |
+
gen_button = gr.Button('Generate Images')
|
96 |
+
|
97 |
with gr.Row():
|
98 |
+
seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=starting_seed)
|
99 |
+
seed_rand = gr.Button("Randomize Seed 🎲")
|
100 |
+
batch_size = gr.Slider(label="Batch Size", minimum=1, maximum=10, step=1, value=1)
|
101 |
+
output_format = gr.Dropdown(["PNG", "JPEG"], label="Output Format", value="PNG")
|
102 |
+
priority = gr.Dropdown(["low", "medium", "high"], label="Priority", value="medium")
|
103 |
|
104 |
+
seed_rand.click(randomize_seed, None, [seed], queue=False)
|
|
|
|
|
|
|
105 |
|
106 |
+
# Outputs
|
107 |
with gr.Row():
|
108 |
+
output_images = [gr.Image(label=f"Model {i+1}") for i in range(num_models)]
|
109 |
+
|
110 |
+
# Model selection
|
111 |
+
with gr.Accordion("Model Selection", open=False):
|
112 |
+
model_choice = gr.CheckboxGroup(models, label=f"Choose up to {num_models} models", value=models[:num_models])
|
113 |
+
|
114 |
+
# Generation logic
|
115 |
+
def generate_images(prompt, seed, batch_size, output_format, priority, selected_models):
|
116 |
+
results = []
|
117 |
+
selected_models = extend_choices(selected_models)
|
118 |
|
119 |
+
for model in selected_models:
|
120 |
+
result = generate_image(model, prompt, seed, batch_size, output_format, priority)
|
121 |
+
results.append(result)
|
122 |
+
|
123 |
+
return results
|
124 |
+
|
125 |
+
gen_button.click(
|
126 |
+
fn=generate_images,
|
127 |
+
inputs=[txt_input, seed, batch_size, output_format, priority, model_choice],
|
128 |
+
outputs=output_images
|
129 |
+
)
|
|
|
|
|
|
|
|
|
|
|
130 |
|
|
|
|
|
131 |
print("Launching Gradio interface...")
|
132 |
+
demo.launch(show_api=False)
|
|