John6666 commited on
Commit
2b41d09
β€’
1 Parent(s): 8f9f1c4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +203 -156
app.py CHANGED
@@ -1,159 +1,206 @@
1
  import gradio as gr
2
- import os
3
- import sys
4
- from pathlib import Path
5
  from all_models import models
6
  from externalmod import gr_Interface_load
7
- from prompt_extend import extend_prompt
8
-
9
- text_gen1 = extend_prompt
10
- current_model = models[0]
11
-
12
- #text_gen1=gr.Interface.load("spaces/phenomenon1981/MagicPrompt-Stable-Diffusion")
13
- #text_gen1=gr.Interface.load("spaces/Yntec/prompt-extend")
14
- #text_gen1=gr.Interface.load("spaces/daspartho/prompt-extend")
15
- #text_gen1=gr.Interface.load("spaces/Omnibus/MagicPrompt-Stable-Diffusion_link")
16
-
17
- models2 = [gr_Interface_load(f"models/{m}",live=False, preprocess=True, postprocess=False) for m in models]
18
-
19
- def text_it1(inputs,text_gen1=text_gen1):
20
- go_t1=text_gen1(inputs)
21
- return(go_t1)
22
-
23
- def set_model(current_model):
24
- current_model = models[current_model]
25
- return gr.update(label=(f"{current_model}"))
26
-
27
- def send_it1(inputs, model_choice): #negative_prompt,
28
- proc1=models2[model_choice]
29
- output1=proc1(inputs)
30
- #negative_prompt=negative_prompt
31
- return(output1)
32
-
33
- css=""""""
34
-
35
- with gr.Blocks(css=css) as myface:
36
- gr.HTML("""
37
- <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
38
- <div>
39
- <style>
40
- h1 {
41
- font-size: 6em;
42
- color: #ffc99f;
43
- margin-top: 30px;
44
- margin-bottom: 30px;
45
- text-shadow: 3px 3px 0 rgba(0, 0, 0, 1) !important;
46
- }
47
- h3 {
48
- color: #ffc99f; !important;
49
- }
50
- h4 {
51
- display: inline-block;
52
- color: #ffffff !important;
53
- }
54
- .wrapper img {
55
- font-size: 98% !important;
56
- white-space: nowrap !important;
57
- text-align: center !important;
58
- display: inline-block !important;
59
- color: #ffffff !important;
60
- }
61
- .wrapper {
62
- color: #ffffff !important;
63
- }
64
- .gradio-container {
65
- background-image: linear-gradient(#254150, #1e2f40, #182634) !important;
66
- color: #ffaa66 !important;
67
- font-family: 'IBM Plex Sans', sans-serif !important;
68
- }
69
- .text-gray-500 {
70
- color: #ffc99f !important;
71
- }
72
- .gr-box {
73
- background-image: linear-gradient(#182634, #1e2f40, #254150) !important;
74
- border-top-color: #000000 !important;
75
- border-right-color: #ffffff !important;
76
- border-bottom-color: #ffffff !important;
77
- border-left-color: #000000 !important;
78
- }
79
- .gr-input {
80
- color: #ffc99f; !important;
81
- background-color: #254150 !important;
82
- }
83
- :root {
84
- --neutral-100: #000000 !important;
85
- }
86
- </style>
87
- <body>
88
- <div class="center"><h1>Blitz Diffusion</h1>
89
- </div>
90
- </body>
91
- </div>
92
- <p style="margin-bottom: 1px; color: #ffaa66;">
93
- <h3>899 Stable Diffusion models, but why? For your enjoyment!</h3></p>
94
- <br><div class="wrapper">9.3 <img src="https://huggingface.co/Yntec/DucHaitenLofi/resolve/main/NEW.webp" alt="NEW!" style="width:32px;height:16px;">This has become a legacy backup copy of old <u><a href="https://huggingface.co/spaces/Yntec/ToyWorld">ToyWorld</a></u>'s UI! Newer models added dailty over there! 25 new models since last update!</div>
95
- <p style="margin-bottom: 1px; font-size: 98%">
96
- <br><h4>If a model is already loaded each new image takes less than <b>10</b> seconds to generate!</h4></p>
97
- <p style="margin-bottom: 1px; color: #ffffff;">
98
- <br><div class="wrapper">Generate 6 images from 1 prompt at the <u><a href="https://huggingface.co/spaces/Yntec/PrintingPress">PrintingPress</a></u>, and use 6 different models at <u><a href="https://huggingface.co/spaces/Yntec/diffusion80xx">Huggingface Diffusion!</a></u>!
99
- </p></p>
100
- </div>
101
- """)
102
- with gr.Row():
103
- with gr.Column(scale=100):
104
- #Model selection dropdown
105
- model_name1 = gr.Dropdown(label="Select Model", choices=[m for m in models], type="index", value=current_model, interactive=True)
106
- with gr.Row():
107
- with gr.Column(scale=100):
108
- magic1 = gr.Textbox(label="Your Prompt", lines=4) #Positive
109
- #with gr.Column(scale=100):
110
- #negative_prompt=gr.Textbox(label="Negative Prompt", lines=1)
111
- gr.HTML("""<style> .gr-button {
112
- color: #ffffff !important;
113
- text-shadow: 1px 1px 0 rgba(0, 0, 0, 1) !important;
114
- background-image: linear-gradient(#76635a, #d2a489) !important;
115
- border-radius: 24px !important;
116
- border: solid 1px !important;
117
- border-top-color: #ffc99f !important;
118
- border-right-color: #000000 !important;
119
- border-bottom-color: #000000 !important;
120
- border-left-color: #ffc99f !important;
121
- padding: 6px 30px;
122
- }
123
- .gr-button:active {
124
- color: #ffc99f !important;
125
- font-size: 98% !important;
126
- text-shadow: 0px 0px 0 rgba(0, 0, 0, 1) !important;
127
- background-image: linear-gradient(#d2a489, #76635a) !important;
128
- border-top-color: #000000 !important;
129
- border-right-color: #ffffff !important;
130
- border-bottom-color: #ffffff !important;
131
- border-left-color: #000000 !important;
132
- }
133
- .gr-button:hover {
134
- filter: brightness(130%);
135
- }
136
- </style>""")
137
- run = gr.Button("Generate Image")
138
- with gr.Row():
139
- with gr.Column():
140
- output1 = gr.Image(label=(f"{current_model}"))
141
-
142
- with gr.Row():
143
- with gr.Column(scale=50):
144
- input_text=gr.Textbox(label="Use this box to extend an idea automagically, by typing some words and clicking Extend Idea", lines=2)
145
- see_prompts=gr.Button("Extend Idea -> overwrite the contents of the `Your PromptΒ΄ box above")
146
- use_short=gr.Button("Copy the contents of this box to the `Your PromptΒ΄ box above")
147
- def short_prompt(inputs):
148
- return(inputs)
149
-
150
- model_name1.change(set_model, inputs=model_name1, outputs=[output1])
151
-
152
- run.click(send_it1, inputs=[magic1, model_name1], outputs=[output1])
153
-
154
- use_short.click(short_prompt,inputs=[input_text], outputs=magic1)
155
-
156
- see_prompts.click(text_it1,inputs=[input_text], outputs=magic1)
157
-
158
- myface.queue()
159
- myface.launch(show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from random import randint
 
 
3
  from all_models import models
4
  from externalmod import gr_Interface_load
5
+ import asyncio
6
+ import os
7
+ from threading import RLock
8
+ lock = RLock()
9
+ 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.
10
+
11
+
12
+ def load_fn(models):
13
+ global models_load
14
+ models_load = {}
15
+ for model in models:
16
+ if model not in models_load.keys():
17
+ try:
18
+ m = gr_Interface_load(f'models/{model}', hf_token=HF_TOKEN)
19
+ except Exception as error:
20
+ print(error)
21
+ m = gr.Interface(lambda: None, ['text'], ['image'])
22
+ models_load.update({model: m})
23
+
24
+
25
+ load_fn(models)
26
+
27
+
28
+ num_models = 6
29
+ max_images = 6
30
+ inference_timeout = 300
31
+ default_models = models[:num_models]
32
+ MAX_SEED = 2**32-1
33
+
34
+
35
+ def extend_choices(choices):
36
+ return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
37
+
38
+
39
+ def update_imgbox(choices):
40
+ choices_plus = extend_choices(choices[:num_models])
41
+ return [gr.Image(None, label = m, visible = (m != 'NA')) for m in choices_plus]
42
+
43
+
44
+ def random_choices():
45
+ import random
46
+ random.seed()
47
+ return random.choices(models, k = num_models)
48
+
49
+
50
+ # https://huggingface.co/docs/api-inference/detailed_parameters
51
+ # https://huggingface.co/docs/huggingface_hub/package_reference/inference_client
52
+ async def infer(model_str, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1, timeout=inference_timeout):
53
+ from pathlib import Path
54
+ kwargs = {}
55
+ if height is not None and height >= 256: kwargs["height"] = height
56
+ if width is not None and width >= 256: kwargs["width"] = width
57
+ if steps is not None and steps >= 1: kwargs["num_inference_steps"] = steps
58
+ if cfg is not None and cfg > 0: cfg = kwargs["guidance_scale"] = cfg
59
+ noise = ""
60
+ if seed >= 0: kwargs["seed"] = seed
61
+ else:
62
+ rand = randint(1, 500)
63
+ for i in range(rand):
64
+ noise += " "
65
+ task = asyncio.create_task(asyncio.to_thread(models_load[model_str].fn,
66
+ prompt=f'{prompt} {noise}', negative_prompt=nprompt, **kwargs, token=HF_TOKEN))
67
+ await asyncio.sleep(0)
68
+ try:
69
+ result = await asyncio.wait_for(task, timeout=timeout)
70
+ except (Exception, asyncio.TimeoutError) as e:
71
+ print(e)
72
+ print(f"Task timed out: {model_str}")
73
+ if not task.done(): task.cancel()
74
+ result = None
75
+ if task.done() and result is not None:
76
+ with lock:
77
+ png_path = "image.png"
78
+ result.save(png_path)
79
+ image = str(Path(png_path).resolve())
80
+ return image
81
+ return None
82
+
83
+
84
+ def gen_fn(model_str, prompt, nprompt="", height=None, width=None, steps=None, cfg=None, seed=-1):
85
+ if model_str == 'NA':
86
+ return None
87
+ try:
88
+ loop = asyncio.new_event_loop()
89
+ result = loop.run_until_complete(infer(model_str, prompt, nprompt,
90
+ height, width, steps, cfg, seed, inference_timeout))
91
+ except (Exception, asyncio.CancelledError) as e:
92
+ print(e)
93
+ print(f"Task aborted: {model_str}")
94
+ result = None
95
+ finally:
96
+ loop.close()
97
+ return result
98
+
99
+
100
+ def add_gallery(image, model_str, gallery):
101
+ if gallery is None: gallery = []
102
+ with lock:
103
+ if image is not None: gallery.insert(0, (image, model_str))
104
+ return gallery
105
+
106
+
107
+ CSS="""
108
+ #container { max-width: 1200px; margin: 0 auto; !important; }
109
+ .output { width=112px; height=112px; !important; }
110
+ .gallery { width=100%; min_height=768px; !important; }
111
+ .guide { text-align: center; !important; }
112
+ """
113
+
114
+ with gr.Blocks(theme='Nymbo/Nymbo_Theme', fill_width=True, css=CSS) as demo:
115
+ with gr.Tab('The Dream'):
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.Number(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
123
+ height = gr.Number(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
124
+ with gr.Row():
125
+ steps = gr.Number(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
126
+ cfg = gr.Number(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
+ with gr.Row():
129
+ gen_button = gr.Button(f'Generate up to {int(num_models)} images in up to 3 minutes total', scale=3)
130
+ random_button = gr.Button(f'Random {int(num_models)} 🎲', variant='secondary', scale=1)
131
+ stop_button = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
132
+ gen_button.click(lambda: gr.update(interactive=True), None, stop_button)
133
+ gr.Markdown("Scroll down to see more images and select models.", elem_classes="guide")
134
+
135
+ with gr.Column(scale=1):
136
+ with gr.Group():
137
+ with gr.Row():
138
+ output = [gr.Image(label=m, show_download_button=True, elem_classes="output",
139
+ interactive=False, min_width=80, show_share_button=False, format=".png",
140
+ visible=True) for m in default_models]
141
+ current_models = [gr.Textbox(m, visible=False) for m in default_models]
142
+
143
+ with gr.Column(scale=2):
144
+ gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
145
+ interactive=False, show_share_button=True, container=True, format="png",
146
+ preview=True, object_fit="cover", columns=2, rows=2)
147
+
148
+ for m, o in zip(current_models, output):
149
+ gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn,
150
+ inputs=[m, txt_input, neg_input, height, width, steps, cfg, seed], outputs=[o])
151
+ o.change(add_gallery, [o, m, gallery], [gallery])
152
+ stop_button.click(lambda: gr.update(interactive=False), None, stop_button, cancels=[gen_event])
153
+
154
+ with gr.Column(scale=4):
155
+ with gr.Accordion('Model selection'):
156
+ 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)
157
+ model_choice.change(update_imgbox, model_choice, output)
158
+ model_choice.change(extend_choices, model_choice, current_models)
159
+ random_button.click(random_choices, None, model_choice)
160
+
161
+ with gr.Tab('Single model'):
162
+ with gr.Column(scale=2):
163
+ model_choice2 = gr.Dropdown(models, label='Choose model', value=models[0])
164
+ with gr.Group():
165
+ txt_input2 = gr.Textbox(label='Your prompt:', lines=4)
166
+ neg_input2 = gr.Textbox(label='Negative prompt:', lines=1)
167
+ with gr.Accordion("Advanced", open=False, visible=True):
168
+ with gr.Row():
169
+ width2 = gr.Number(label="Width", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
170
+ height2 = gr.Number(label="Height", info="If 0, the default value is used.", maximum=1216, step=32, value=0)
171
+ with gr.Row():
172
+ steps2 = gr.Number(label="Number of inference steps", info="If 0, the default value is used.", maximum=100, step=1, value=0)
173
+ cfg2 = gr.Number(label="Guidance scale", info="If 0, the default value is used.", maximum=30.0, step=0.1, value=0)
174
+ seed2 = gr.Slider(label="Seed", info="Randomize Seed if -1.", minimum=-1, maximum=MAX_SEED, step=1, value=-1)
175
+ num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
176
+ with gr.Row():
177
+ gen_button2 = gr.Button('Generate', scale=2)
178
+ stop_button2 = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
179
+ gen_button2.click(lambda: gr.update(interactive=True), None, stop_button2)
180
+
181
+ with gr.Column(scale=1):
182
+ with gr.Group():
183
+ with gr.Row():
184
+ output2 = [gr.Image(label='', show_download_button=True, elem_classes="output",
185
+ interactive=False, min_width=80, visible=True, format=".png",
186
+ show_share_button=False, show_label=False) for _ in range(max_images)]
187
+
188
+ with gr.Column(scale=2):
189
+ gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
190
+ interactive=False, show_share_button=True, container=True, format="png",
191
+ preview=True, object_fit="cover", columns=2, rows=2)
192
+
193
+ for i, o in enumerate(output2):
194
+ img_i = gr.Number(i, visible = False)
195
+ num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o)
196
+ gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit],
197
+ 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,
198
+ inputs=[img_i, num_images, model_choice2, txt_input2, neg_input2,
199
+ height2, width2, steps2, cfg2, seed2], outputs=[o])
200
+ o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
201
+ stop_button2.click(lambda: gr.update(interactive=False), None, stop_button2, cancels=[gen_event2])
202
+
203
+ 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!")
204
+
205
+ demo.queue()
206
+ demo.launch()