Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,219 +1,211 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
from all_models import models
|
| 3 |
-
from externalmod import gr_Interface_load, save_image, randomize_seed
|
| 4 |
-
import asyncio
|
| 5 |
-
import os
|
| 6 |
-
from threading import RLock
|
| 7 |
-
lock = RLock()
|
| 8 |
-
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.
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def load_fn(models):
|
| 12 |
-
global models_load
|
| 13 |
-
models_load = {}
|
| 14 |
-
for model in models:
|
| 15 |
-
if model not in models_load.keys():
|
| 16 |
-
try:
|
| 17 |
-
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
| 18 |
-
except Exception as error:
|
| 19 |
-
print(error)
|
| 20 |
-
m = gr.Interface(lambda: None, ['text'], ['image'])
|
| 21 |
-
models_load.update({model: m})
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
load_fn(models)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
num_models = 6
|
| 28 |
-
max_images = 6
|
| 29 |
-
inference_timeout = 300
|
| 30 |
-
default_models = models[:num_models]
|
| 31 |
-
MAX_SEED = 2**32-1
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
def extend_choices(choices):
|
| 35 |
-
return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
def update_imgbox(choices):
|
| 39 |
-
choices_plus = extend_choices(choices[:num_models])
|
| 40 |
-
return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
def random_choices():
|
| 44 |
-
import random
|
| 45 |
-
random.seed()
|
| 46 |
-
return random.choices(models, k=num_models)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
# https://huggingface.co/docs/api-inference/detailed_parameters
|
| 50 |
-
# https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
|
| 51 |
-
async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
|
| 52 |
-
kwargs = {}
|
| 53 |
-
if height > 0: kwargs["height"] = height
|
| 54 |
-
if width > 0: kwargs["width"] = width
|
| 55 |
-
if steps > 0: kwargs["num_inference_steps"] = steps
|
| 56 |
-
if cfg > 0: cfg = kwargs["guidance_scale"] = cfg
|
| 57 |
-
if seed == -1: kwargs["seed"] = randomize_seed()
|
| 58 |
-
else: kwargs["seed"] = seed
|
| 59 |
-
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
|
| 60 |
-
prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
|
| 61 |
-
await asyncio.sleep(0)
|
| 62 |
-
try:
|
| 63 |
-
result = await asyncio.wait_for(task, timeout=timeout)
|
| 64 |
-
except asyncio.TimeoutError as e:
|
| 65 |
-
print(e)
|
| 66 |
-
print(f"Task timed out: {model_str}")
|
| 67 |
-
if not task.done(): task.cancel()
|
| 68 |
-
result = None
|
| 69 |
-
raise Exception(f"Task timed out: {model_str}") from e
|
| 70 |
-
except Exception as e:
|
| 71 |
-
print(e)
|
| 72 |
-
if not task.done(): task.cancel()
|
| 73 |
-
result = None
|
| 74 |
-
raise Exception() from e
|
| 75 |
-
if task.done() and result is not None and not isinstance(result, tuple):
|
| 76 |
-
with lock:
|
| 77 |
-
png_path = "image.png"
|
| 78 |
-
image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, seed)
|
| 79 |
-
return image
|
| 80 |
-
return None
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1):
|
| 84 |
-
try:
|
| 85 |
-
loop = asyncio.new_event_loop()
|
| 86 |
-
result = loop.run_until_complete(infer(model_str, prompt, nprompt,
|
| 87 |
-
height, width, steps, cfg, seed, inference_timeout))
|
| 88 |
-
except (Exception, asyncio.CancelledError) as e:
|
| 89 |
-
print(e)
|
| 90 |
-
print(f"Task aborted: {model_str}")
|
| 91 |
-
result = None
|
| 92 |
-
raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
|
| 93 |
-
finally:
|
| 94 |
-
loop.close()
|
| 95 |
-
return result
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def add_gallery(image, model_str, gallery):
|
| 99 |
-
if gallery is None: gallery = []
|
| 100 |
-
with lock:
|
| 101 |
-
if image is not None: gallery.insert(0, (image, model_str))
|
| 102 |
-
return gallery
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
CSS="""
|
| 106 |
-
.gradio-container { max-width: 1200px; margin: 0 auto; !important; }
|
| 107 |
-
.output { width=112px; height=112px; max_width=112px; max_height=112px; !important; }
|
| 108 |
-
.gallery { min_width=512px; min_height=512px; max_height=1024px; !important; }
|
| 109 |
-
.guide { text-align: center; !important; }
|
| 110 |
-
"""
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', fill_width=True, css=CSS) as demo:
|
| 114 |
-
gr.HTML(
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
with gr.
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
|
| 213 |
-
#stop_button2.click(lambda: gr.update(interactive=False), None, stop_button2, cancels=[gen_event2])
|
| 214 |
-
|
| 215 |
-
gr.Markdown("Based on the [TestGen](https://huggingface.co/spaces/derwahnsinn/TestGen) Space by derwahnsinn, the [SpacIO](https://huggingface.co/spaces/RdnUser77/SpacIO_v1) Space by RdnUser77 and Omnibus's Maximum Multiplier!")
|
| 216 |
-
|
| 217 |
-
#demo.queue(default_concurrency_limit=200, max_size=200)
|
| 218 |
-
demo.launch(show_api=False, max_threads=400)
|
| 219 |
-
# https://github.com/gradio-app/gradio/issues/6339
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from all_models import models
|
| 3 |
+
from externalmod import gr_Interface_load, save_image, randomize_seed
|
| 4 |
+
import asyncio
|
| 5 |
+
import os
|
| 6 |
+
from threading import RLock
|
| 7 |
+
lock = RLock()
|
| 8 |
+
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.
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def load_fn(models):
|
| 12 |
+
global models_load
|
| 13 |
+
models_load = {}
|
| 14 |
+
for model in models:
|
| 15 |
+
if model not in models_load.keys():
|
| 16 |
+
try:
|
| 17 |
+
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
| 18 |
+
except Exception as error:
|
| 19 |
+
print(error)
|
| 20 |
+
m = gr.Interface(lambda: None, ['text'], ['image'])
|
| 21 |
+
models_load.update({model: m})
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
load_fn(models)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
num_models = 6
|
| 28 |
+
max_images = 6
|
| 29 |
+
inference_timeout = 300
|
| 30 |
+
default_models = models[:num_models]
|
| 31 |
+
MAX_SEED = 2**32-1
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def extend_choices(choices):
|
| 35 |
+
return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def update_imgbox(choices):
|
| 39 |
+
choices_plus = extend_choices(choices[:num_models])
|
| 40 |
+
return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def random_choices():
|
| 44 |
+
import random
|
| 45 |
+
random.seed()
|
| 46 |
+
return random.choices(models, k=num_models)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# https://huggingface.co/docs/api-inference/detailed_parameters
|
| 50 |
+
# https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
|
| 51 |
+
async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
|
| 52 |
+
kwargs = {}
|
| 53 |
+
if height > 0: kwargs["height"] = height
|
| 54 |
+
if width > 0: kwargs["width"] = width
|
| 55 |
+
if steps > 0: kwargs["num_inference_steps"] = steps
|
| 56 |
+
if cfg > 0: cfg = kwargs["guidance_scale"] = cfg
|
| 57 |
+
if seed == -1: kwargs["seed"] = randomize_seed()
|
| 58 |
+
else: kwargs["seed"] = seed
|
| 59 |
+
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
|
| 60 |
+
prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
|
| 61 |
+
await asyncio.sleep(0)
|
| 62 |
+
try:
|
| 63 |
+
result = await asyncio.wait_for(task, timeout=timeout)
|
| 64 |
+
except asyncio.TimeoutError as e:
|
| 65 |
+
print(e)
|
| 66 |
+
print(f"Task timed out: {model_str}")
|
| 67 |
+
if not task.done(): task.cancel()
|
| 68 |
+
result = None
|
| 69 |
+
raise Exception(f"Task timed out: {model_str}") from e
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print(e)
|
| 72 |
+
if not task.done(): task.cancel()
|
| 73 |
+
result = None
|
| 74 |
+
raise Exception() from e
|
| 75 |
+
if task.done() and result is not None and not isinstance(result, tuple):
|
| 76 |
+
with lock:
|
| 77 |
+
png_path = "image.png"
|
| 78 |
+
image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, seed)
|
| 79 |
+
return image
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1):
|
| 84 |
+
try:
|
| 85 |
+
loop = asyncio.new_event_loop()
|
| 86 |
+
result = loop.run_until_complete(infer(model_str, prompt, nprompt,
|
| 87 |
+
height, width, steps, cfg, seed, inference_timeout))
|
| 88 |
+
except (Exception, asyncio.CancelledError) as e:
|
| 89 |
+
print(e)
|
| 90 |
+
print(f"Task aborted: {model_str}")
|
| 91 |
+
result = None
|
| 92 |
+
raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
|
| 93 |
+
finally:
|
| 94 |
+
loop.close()
|
| 95 |
+
return result
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def add_gallery(image, model_str, gallery):
|
| 99 |
+
if gallery is None: gallery = []
|
| 100 |
+
with lock:
|
| 101 |
+
if image is not None: gallery.insert(0, (image, model_str))
|
| 102 |
+
return gallery
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
CSS="""
|
| 106 |
+
.gradio-container { max-width: 1200px; margin: 0 auto; !important; }
|
| 107 |
+
.output { width=112px; height=112px; max_width=112px; max_height=112px; !important; }
|
| 108 |
+
.gallery { min_width=512px; min_height=512px; max_height=1024px; !important; }
|
| 109 |
+
.guide { text-align: center; !important; }
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', fill_width=True, css=CSS) as demo:
|
| 114 |
+
gr.HTML()
|
| 115 |
+
with gr.Tab('Huggingface Diffusion'):
|
| 116 |
+
with gr.Column(scale=2):
|
| 117 |
+
with gr.Group():
|
| 118 |
+
txt_input = gr.Textbox(label='Your prompt:', lines=4)
|
| 119 |
+
neg_input = gr.Textbox(label='Negative prompt:', lines=1)
|
| 120 |
+
with gr.Accordion("Advanced", open=False, visible=True):
|
| 121 |
+
with gr.Row():
|
| 122 |
+
width = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
| 123 |
+
height = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
| 124 |
+
with gr.Row():
|
| 125 |
+
steps = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
|
| 126 |
+
cfg = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
|
| 127 |
+
seed = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
| 128 |
+
seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
|
| 129 |
+
seed_rand.click(randomize_seed, None, [seed], queue=False)
|
| 130 |
+
with gr.Row():
|
| 131 |
+
gen_button = gr.Button(f'Generate up to {int(num_models)} images in up to 3 minutes total', variant='primary', scale=3)
|
| 132 |
+
random_button = gr.Button(f'Random {int(num_models)} 🎲', variant='secondary', scale=1)
|
| 133 |
+
#stop_button = gr.Button('Stop', variant='stop', interactive=False, scale=1)
|
| 134 |
+
#gen_button.click(lambda: gr.update(interactive=True), None, stop_button)
|
| 135 |
+
gr.Markdown("Scroll down to see more images and select models.", elem_classes="guide")
|
| 136 |
+
|
| 137 |
+
with gr.Column(scale=1):
|
| 138 |
+
with gr.Group():
|
| 139 |
+
with gr.Row():
|
| 140 |
+
output = [gr.Image(label=m, show_download_button=True, elem_classes="output",
|
| 141 |
+
interactive=False, width=112, height=112, show_share_button=False, format="png",
|
| 142 |
+
visible=True) for m in default_models]
|
| 143 |
+
current_models = [gr.Textbox(m, visible=False) for m in default_models]
|
| 144 |
+
|
| 145 |
+
with gr.Column(scale=2):
|
| 146 |
+
gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
|
| 147 |
+
interactive=False, show_share_button=True, container=True, format="png",
|
| 148 |
+
preview=True, object_fit="cover", columns=2, rows=2)
|
| 149 |
+
|
| 150 |
+
for m, o in zip(current_models, output):
|
| 151 |
+
gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
|
| 152 |
+
inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o],
|
| 153 |
+
concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button
|
| 154 |
+
o.change(add_gallery, [o, m, gallery], [gallery])
|
| 155 |
+
#stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event])
|
| 156 |
+
|
| 157 |
+
with gr.Column(scale=4):
|
| 158 |
+
with gr.Accordion('Model selection'):
|
| 159 |
+
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)
|
| 160 |
+
model_choice.change(update_imgbox, model_choice, output)
|
| 161 |
+
model_choice.change(extend_choices, model_choice, current_models)
|
| 162 |
+
random_button.click(random_choices, None, model_choice)
|
| 163 |
+
|
| 164 |
+
with gr.Tab('Single model'):
|
| 165 |
+
with gr.Column(scale=2):
|
| 166 |
+
model_choice2 = gr.Dropdown(models, label='Choose model', value=models[0])
|
| 167 |
+
with gr.Group():
|
| 168 |
+
txt_input2 = gr.Textbox(label='Your prompt:', lines=4)
|
| 169 |
+
neg_input2 = gr.Textbox(label='Negative prompt:', lines=1)
|
| 170 |
+
with gr.Accordion("Advanced", open=False, visible=True):
|
| 171 |
+
with gr.Row():
|
| 172 |
+
width2 = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
| 173 |
+
height2 = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
| 174 |
+
with gr.Row():
|
| 175 |
+
steps2 = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
|
| 176 |
+
cfg2 = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
|
| 177 |
+
seed2 = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
| 178 |
+
seed_rand2 = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
|
| 179 |
+
seed_rand2.click(randomize_seed, None, [seed2], queue=False)
|
| 180 |
+
num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
|
| 181 |
+
with gr.Row():
|
| 182 |
+
gen_button2 = gr.Button('Generate', variant='primary', scale=2)
|
| 183 |
+
#stop_button2 = gr.Button('Stop', variant='stop', interactive=False, scale=1)
|
| 184 |
+
#gen_button2.click(lambda: gr.update(interactive=True), None, stop_button2)
|
| 185 |
+
|
| 186 |
+
with gr.Column(scale=1):
|
| 187 |
+
with gr.Group():
|
| 188 |
+
with gr.Row():
|
| 189 |
+
output2 = [gr.Image(label='', show_download_button=True, elem_classes="output",
|
| 190 |
+
interactive=False, width=112, height=112, visible=True, format="png",
|
| 191 |
+
show_share_button=False, show_label=False) for _ in range(max_images)]
|
| 192 |
+
|
| 193 |
+
with gr.Column(scale=2):
|
| 194 |
+
gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
|
| 195 |
+
interactive=False, show_share_button=True, container=True, format="png",
|
| 196 |
+
preview=True, object_fit="cover", columns=2, rows=2)
|
| 197 |
+
|
| 198 |
+
for i, o in enumerate(output2):
|
| 199 |
+
img_i = gr.Number(i, visible=False)
|
| 200 |
+
num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o, queue=False)
|
| 201 |
+
gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit],
|
| 202 |
+
fn=lambda i, n, m, t1, t2, n1, n2, n3, n4, n5: gen_fn(m, t1, t2, n1, n2, n3, n4, n5) if (i < n) else None,
|
| 203 |
+
inputs=[img_i, num_images, model_choice2, txt_input2, neg_input2,
|
| 204 |
+
height2, width2, steps2, cfg2, seed2], outputs=[o],
|
| 205 |
+
concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button
|
| 206 |
+
o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
|
| 207 |
+
#stop_button2.click(lambda: gr.update(interactive=False), None, stop_button2, cancels=[gen_event2])
|
| 208 |
+
|
| 209 |
+
#demo.queue(default_concurrency_limit=200, max_size=200)
|
| 210 |
+
demo.launch(show_api=False, max_threads=400)
|
| 211 |
+
# https://github.com/gradio-app/gradio/issues/6339
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|