Abinivesh commited on
Commit
7cb0a88
·
verified ·
1 Parent(s): 4ff15b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -116
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, 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
 
45
- # Extend the choices list to ensure it contains 'num_models' elements
46
  def extend_choices(choices):
47
- print(f"Extending choices: {choices}")
48
- extended = choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
49
- print(f"Extended choices: {extended}")
50
- return extended
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
- 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}")
93
- return image
94
- print(f"No result for model: {model_str}")
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
115
 
116
- # Create the Gradio Blocks interface with a custom theme
 
 
117
  print("Creating Gradio interface...")
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.")
 
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)