Update app.py
Browse files
app.py
CHANGED
@@ -10,127 +10,99 @@ preSetPrompt = "High fashion studio foto shoot. tall slender 18+ caucasian woman
|
|
10 |
negPreSetPrompt = "[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry, text, fuzziness"
|
11 |
|
12 |
lock = RLock()
|
13 |
-
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None
|
14 |
|
15 |
def get_current_time():
|
16 |
-
|
17 |
-
now2 = now
|
18 |
-
current_time = now2.strftime("%y-%m-%d %H:%M:%S")
|
19 |
-
return current_time
|
20 |
|
21 |
def load_fn(models):
|
22 |
global models_load
|
23 |
models_load = {}
|
24 |
for model in models:
|
25 |
-
if model not in models_load
|
26 |
try:
|
27 |
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
28 |
except Exception as error:
|
29 |
print(error)
|
30 |
m = gr.Interface(lambda: None, ['text'], ['image'])
|
31 |
-
models_load
|
32 |
-
|
33 |
|
34 |
load_fn(models)
|
35 |
|
36 |
-
|
37 |
num_models = 6
|
38 |
max_images = 6
|
39 |
inference_timeout = 400
|
40 |
default_models = models[:num_models]
|
41 |
-
MAX_SEED = 2**32-1
|
42 |
-
|
43 |
|
44 |
def extend_choices(choices):
|
45 |
-
return choices[:num_models] + (num_models - len(choices
|
46 |
-
|
47 |
|
48 |
def update_imgbox(choices):
|
49 |
-
choices_plus = extend_choices(choices
|
50 |
-
return [gr.Image(None, label=m, visible=(m!='NA')) for m in choices_plus]
|
51 |
-
|
52 |
|
53 |
def random_choices():
|
54 |
import random
|
55 |
random.seed()
|
56 |
return random.choices(models, k=num_models)
|
57 |
|
58 |
-
|
59 |
-
# https://huggingface.co/docs/api-inference/detailed_parameters
|
60 |
-
# https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
|
61 |
async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
|
62 |
-
kwargs = {
|
63 |
-
|
64 |
-
|
65 |
-
if steps > 0: kwargs["num_inference_steps"] = steps
|
66 |
-
if cfg > 0: cfg = kwargs["guidance_scale"] = cfg
|
67 |
-
|
68 |
if seed == -1:
|
69 |
-
|
70 |
-
|
71 |
-
else:
|
72 |
kwargs["seed"] = seed
|
73 |
-
|
74 |
-
|
75 |
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
|
76 |
-
|
77 |
try:
|
78 |
result = await asyncio.wait_for(task, timeout=timeout)
|
79 |
except asyncio.TimeoutError as e:
|
80 |
-
print(e)
|
81 |
print(f"Task timed out: {model_str}")
|
82 |
-
|
83 |
result = None
|
84 |
-
raise Exception(f"Task timed out: {model_str}") from e
|
85 |
except Exception as e:
|
86 |
-
print(e)
|
87 |
-
|
88 |
result = None
|
89 |
-
|
90 |
-
if
|
|
|
91 |
with lock:
|
92 |
-
|
93 |
-
# png_path = get_current_time() + "_" + model_str.replace("/", "_") + ".png"
|
94 |
-
# png_path = model_str.replace("/", "_") + " - " + prompt + " - " + get_current_time() + ".png"
|
95 |
-
png_path = model_str.replace("/", "_") + " - " + get_current_time() + "_" + str(theSeed) + ".png"
|
96 |
-
image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, seed)
|
97 |
return image
|
98 |
return None
|
99 |
|
100 |
-
|
101 |
def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1):
|
|
|
102 |
try:
|
103 |
-
|
104 |
-
result = loop.run_until_complete(infer(model_str, prompt, nprompt,
|
105 |
-
height, width, steps, cfg, seed, inference_timeout))
|
106 |
except (Exception, asyncio.CancelledError) as e:
|
107 |
-
print(e)
|
108 |
-
print(f"Task aborted: {model_str}")
|
109 |
result = None
|
110 |
raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
|
111 |
finally:
|
112 |
loop.close()
|
113 |
return result
|
114 |
|
115 |
-
|
116 |
def add_gallery(image, model_str, gallery):
|
117 |
-
if
|
118 |
-
|
119 |
-
if image is not None: gallery.insert(0, (image, model_str))
|
120 |
return gallery
|
121 |
|
122 |
-
|
123 |
-
CSS="""
|
124 |
-
.gradio-container { max-width: 1200px; margin: 0 auto;
|
125 |
-
.output { width
|
126 |
-
.gallery {
|
127 |
-
.guide { text-align: center; !important; }
|
128 |
"""
|
129 |
|
130 |
js_func = """
|
131 |
function refresh() {
|
132 |
const url = new URL(window.location);
|
133 |
-
|
134 |
if (url.searchParams.get('__theme') !== 'dark') {
|
135 |
url.searchParams.set('__theme', 'dark');
|
136 |
window.location.href = url.href;
|
@@ -138,125 +110,62 @@ function refresh() {
|
|
138 |
}
|
139 |
"""
|
140 |
|
141 |
-
js_AutoSave="""
|
142 |
-
|
143 |
-
console.log("Yo");
|
144 |
-
|
145 |
-
var img1 = document.querySelector("div#component-355 .svelte-1kpcxni button.svelte-1kpcxni .svelte-1kpcxni img"),
|
146 |
-
observer = new MutationObserver((changes) => {
|
147 |
-
changes.forEach(change => {
|
148 |
-
if(change.attributeName.includes('src')){
|
149 |
-
console.log(img1.src);
|
150 |
-
document.querySelector("div#component-355 .svelte-1kpcxni .svelte-sr71km a.svelte-1s8vnbx button").click();
|
151 |
-
}
|
152 |
-
});
|
153 |
-
});
|
154 |
-
observer.observe(img1, {attributes : true});
|
155 |
-
|
156 |
-
"""
|
157 |
-
|
158 |
with gr.Blocks(theme='NoCrypt/miku@>=1.2.2', fill_width=True, css=CSS) as demo:
|
159 |
-
|
160 |
-
|
161 |
with gr.Tab('6 Models'):
|
162 |
with gr.Column(scale=2):
|
163 |
with gr.Group():
|
164 |
txt_input = gr.Textbox(label='Your prompt:', value=preSetPrompt, lines=3, autofocus=1)
|
165 |
neg_input = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
|
166 |
-
with gr.Accordion("Advanced", open=False
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
gr.Markdown("", elem_classes="guide")
|
182 |
-
|
183 |
-
with gr.Column(scale=1):
|
184 |
-
with gr.Group():
|
185 |
-
with gr.Row():
|
186 |
-
output = [gr.Image(label=m, show_download_button=True, elem_classes="output",
|
187 |
-
interactive=False, width=112, height=112, show_share_button=False, format="png",
|
188 |
-
visible=True) for m in default_models]
|
189 |
-
current_models = [gr.Textbox(m, visible=False) for m in default_models]
|
190 |
|
191 |
with gr.Column(scale=2):
|
192 |
-
gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
|
193 |
-
interactive=False, show_share_button=False, container=True, format="png",
|
194 |
-
preview=True, object_fit="cover", columns=2, rows=2)
|
195 |
|
196 |
for m, o in zip(current_models, output):
|
197 |
gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
|
198 |
-
inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o]
|
199 |
-
concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button
|
200 |
o.change(add_gallery, [o, m, gallery], [gallery])
|
201 |
-
#stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event])
|
202 |
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
model_choice.change(extend_choices, model_choice, current_models)
|
208 |
-
random_button.click(random_choices, None, model_choice)
|
209 |
|
210 |
with gr.Tab('Single model'):
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
# global negPreSetPrompt
|
216 |
-
txt_input2 = gr.Textbox(label='Your prompt:', value = preSetPrompt, lines=3, autofocus=1)
|
217 |
-
neg_input2 = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
|
218 |
-
with gr.Accordion("Advanced", open=False, visible=True):
|
219 |
-
with gr.Row():
|
220 |
-
width2 = gr.Slider(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
221 |
-
height2 = gr.Slider(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
|
222 |
-
with gr.Row():
|
223 |
-
steps2 = gr.Slider(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
|
224 |
-
cfg2 = gr.Slider(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
|
225 |
-
seed2 = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
226 |
-
seed_rand2 = gr.Button("Randomize Seed", size="sm", variant="secondary")
|
227 |
-
seed_rand2.click(randomize_seed, None, [seed2], queue=False)
|
228 |
-
num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
|
229 |
-
with gr.Row():
|
230 |
-
gen_button2 = gr.Button('Let the machine halucinate', variant='primary', scale=2)
|
231 |
-
#stop_button2 = gr.Button('Stop', variant='stop', interactive=False, scale=1)
|
232 |
-
#gen_button2.click(lambda: gr.update(interactive=True), None, stop_button2)
|
233 |
-
|
234 |
-
with gr.Column(scale=1):
|
235 |
-
with gr.Group():
|
236 |
-
with gr.Row():
|
237 |
-
output2 = [gr.Image(label='', show_download_button=True, elem_classes="output",
|
238 |
-
interactive=False, width=112, height=112, visible=True, format="png",
|
239 |
-
show_share_button=False, show_label=False) for _ in range(max_images)]
|
240 |
|
|
|
|
|
|
|
|
|
241 |
with gr.Column(scale=2):
|
242 |
-
gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
|
243 |
-
interactive=False, show_share_button=True, container=True, format="png",
|
244 |
-
preview=True, object_fit="cover", columns=2, rows=2)
|
245 |
|
246 |
for i, o in enumerate(output2):
|
247 |
-
|
248 |
-
num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o, queue=False)
|
249 |
gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit],
|
250 |
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,
|
251 |
-
inputs=[
|
252 |
-
height2, width2, steps2, cfg2, seed2], outputs=[o],
|
253 |
-
concurrency_limit=None, queue=False) # Be sure to delete ", queue=False" when activating the stop button
|
254 |
o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
|
255 |
-
#stop_button2.click(lambda: gr.update(interactive=False), None, stop_button2, cancels=[gen_event2])
|
256 |
-
|
257 |
-
# gr.Markdown(js_AutoSave)
|
258 |
-
gr.Markdown("")
|
259 |
|
260 |
-
|
261 |
demo.launch(show_api=False, max_threads=400)
|
262 |
-
# demo.launch(show_api=False, max_threads=400, js=js_AutoSave)
|
|
|
10 |
negPreSetPrompt = "[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry, text, fuzziness"
|
11 |
|
12 |
lock = RLock()
|
13 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") if os.environ.get("HF_TOKEN") else None
|
14 |
|
15 |
def get_current_time():
|
16 |
+
return datetime.now().strftime("%y-%m-%d %H:%M:%S")
|
|
|
|
|
|
|
17 |
|
18 |
def load_fn(models):
|
19 |
global models_load
|
20 |
models_load = {}
|
21 |
for model in models:
|
22 |
+
if model not in models_load:
|
23 |
try:
|
24 |
m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
|
25 |
except Exception as error:
|
26 |
print(error)
|
27 |
m = gr.Interface(lambda: None, ['text'], ['image'])
|
28 |
+
models_load[model] = m
|
|
|
29 |
|
30 |
load_fn(models)
|
31 |
|
|
|
32 |
num_models = 6
|
33 |
max_images = 6
|
34 |
inference_timeout = 400
|
35 |
default_models = models[:num_models]
|
36 |
+
MAX_SEED = 2**32 - 1
|
|
|
37 |
|
38 |
def extend_choices(choices):
|
39 |
+
return choices[:num_models] + (num_models - len(choices)) * ['NA']
|
|
|
40 |
|
41 |
def update_imgbox(choices):
|
42 |
+
choices_plus = extend_choices(choices)
|
43 |
+
return [gr.Image(None, label=m, visible=(m != 'NA')) for m in choices_plus]
|
|
|
44 |
|
45 |
def random_choices():
|
46 |
import random
|
47 |
random.seed()
|
48 |
return random.choices(models, k=num_models)
|
49 |
|
|
|
|
|
|
|
50 |
async def infer(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1, timeout=inference_timeout):
|
51 |
+
kwargs = {"height": height if height > 0 else None, "width": width if width > 0 else None,
|
52 |
+
"num_inference_steps": steps if steps > 0 else None, "guidance_scale": cfg if cfg > 0 else None}
|
53 |
+
|
|
|
|
|
|
|
54 |
if seed == -1:
|
55 |
+
kwargs["seed"] = randomize_seed()
|
56 |
+
else:
|
|
|
57 |
kwargs["seed"] = seed
|
58 |
+
|
|
|
59 |
task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn, prompt=prompt, negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
|
60 |
+
|
61 |
try:
|
62 |
result = await asyncio.wait_for(task, timeout=timeout)
|
63 |
except asyncio.TimeoutError as e:
|
|
|
64 |
print(f"Task timed out: {model_str}")
|
65 |
+
task.cancel()
|
66 |
result = None
|
|
|
67 |
except Exception as e:
|
68 |
+
print(f"Error generating image: {model_str} - {e}")
|
69 |
+
task.cancel()
|
70 |
result = None
|
71 |
+
|
72 |
+
if result and not isinstance(result, tuple):
|
73 |
+
png_path = f"{model_str.replace('/', '_')}_{get_current_time()}_{kwargs['seed']}.png"
|
74 |
with lock:
|
75 |
+
image = save_image(result, png_path, model_str, prompt, nprompt, height, width, steps, cfg, kwargs["seed"])
|
|
|
|
|
|
|
|
|
76 |
return image
|
77 |
return None
|
78 |
|
|
|
79 |
def gen_fn(model_str, prompt, nprompt="", height=0, width=0, steps=0, cfg=0, seed=-1):
|
80 |
+
loop = asyncio.new_event_loop()
|
81 |
try:
|
82 |
+
result = loop.run_until_complete(infer(model_str, prompt, nprompt, height, width, steps, cfg, seed, inference_timeout))
|
|
|
|
|
83 |
except (Exception, asyncio.CancelledError) as e:
|
84 |
+
print(f"Error generating image: {e}")
|
|
|
85 |
result = None
|
86 |
raise gr.Error(f"Task aborted: {model_str}, Error: {e}")
|
87 |
finally:
|
88 |
loop.close()
|
89 |
return result
|
90 |
|
|
|
91 |
def add_gallery(image, model_str, gallery):
|
92 |
+
if image is not None:
|
93 |
+
gallery = [(image, model_str)] + gallery[:5] # Keep only the latest 6 images
|
|
|
94 |
return gallery
|
95 |
|
96 |
+
# Interface Layout
|
97 |
+
CSS = """
|
98 |
+
.gradio-container { max-width: 1200px; margin: 0 auto; }
|
99 |
+
.output { width: 112px; height: 112px; }
|
100 |
+
.gallery { min-width: 512px; min-height: 512px; }
|
|
|
101 |
"""
|
102 |
|
103 |
js_func = """
|
104 |
function refresh() {
|
105 |
const url = new URL(window.location);
|
|
|
106 |
if (url.searchParams.get('__theme') !== 'dark') {
|
107 |
url.searchParams.set('__theme', 'dark');
|
108 |
window.location.href = url.href;
|
|
|
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 |
with gr.Tab('6 Models'):
|
117 |
with gr.Column(scale=2):
|
118 |
with gr.Group():
|
119 |
txt_input = gr.Textbox(label='Your prompt:', value=preSetPrompt, lines=3, autofocus=1)
|
120 |
neg_input = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
|
121 |
+
with gr.Accordion("Advanced", open=False):
|
122 |
+
width = gr.Slider(label="Width", maximum=1216, step=32, value=0)
|
123 |
+
height = gr.Slider(label="Height", maximum=1216, step=32, value=0)
|
124 |
+
steps = gr.Slider(label="Number of inference steps", maximum=100, step=1, value=0)
|
125 |
+
cfg = gr.Slider(label="Guidance scale", maximum=30.0, step=0.1, value=0)
|
126 |
+
seed = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
|
127 |
+
seed_rand = gr.Button("Randomize Seed 🎲", size="sm", variant="secondary")
|
128 |
+
seed_rand.click(randomize_seed, None, [seed], queue=False)
|
129 |
+
gen_button = gr.Button(f'Generate up to {num_models} images', variant='primary', scale=3)
|
130 |
+
random_button = gr.Button('Randomize Models', variant='secondary', scale=1)
|
131 |
+
gr.Markdown("")
|
132 |
+
|
133 |
+
with gr.Row():
|
134 |
+
output = [gr.Image(label=m, show_download_button=True, elem_classes="output", interactive=False, width=112, height=112, format="png", visible=True) for m in default_models]
|
135 |
+
current_models = [gr.Textbox(m, visible=False) for m in default_models]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
with gr.Column(scale=2):
|
138 |
+
gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery", interactive=False, format="png", preview=True, object_fit="cover", columns=2, rows=2)
|
|
|
|
|
139 |
|
140 |
for m, o in zip(current_models, output):
|
141 |
gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
|
142 |
+
inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o])
|
|
|
143 |
o.change(add_gallery, [o, m, gallery], [gallery])
|
|
|
144 |
|
145 |
+
model_choice = gr.CheckboxGroup(models, label=f'Choose up to {num_models} models', value=default_models)
|
146 |
+
model_choice.change(update_imgbox, model_choice, output)
|
147 |
+
model_choice.change(extend_choices, model_choice, current_models)
|
148 |
+
random_button.click(random_choices, None, model_choice)
|
|
|
|
|
149 |
|
150 |
with gr.Tab('Single model'):
|
151 |
+
model_choice2 = gr.Dropdown(models, label='Choose model', value=models[0])
|
152 |
+
txt_input2 = gr.Textbox(label='Your prompt:', value=preSetPrompt, lines=3, autofocus=1)
|
153 |
+
neg_input2 = gr.Textbox(label='Negative prompt:', value=negPreSetPrompt, lines=1)
|
154 |
+
num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
|
156 |
+
gen_button2 = gr.Button('Let the machine hallucinate', variant='primary', scale=2)
|
157 |
+
|
158 |
+
output2 = [gr.Image(label='', show_download_button=True, elem_classes="output", interactive=False, width=112, height=112, format="png", show_share_button=False) for _ in range(max_images)]
|
159 |
+
|
160 |
with gr.Column(scale=2):
|
161 |
+
gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery", interactive=False, show_share_button=True, format="png", preview=True, object_fit="cover", columns=2, rows=2)
|
|
|
|
|
162 |
|
163 |
for i, o in enumerate(output2):
|
164 |
+
num_images.change(lambda i, n: gr.update(visible=(i < n)), [i, num_images], o, queue=False)
|
|
|
165 |
gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit],
|
166 |
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,
|
167 |
+
inputs=[i, num_images, model_choice2, txt_input2, neg_input2, height, width, steps, cfg, seed], outputs=[o])
|
|
|
|
|
168 |
o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
|
|
|
|
|
|
|
|
|
169 |
|
170 |
+
gr.Markdown("")
|
171 |
demo.launch(show_api=False, max_threads=400)
|
|