Yntec commited on
Commit
b2c6964
β€’
1 Parent(s): 759203c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -63
app.py CHANGED
@@ -2,7 +2,9 @@ import gradio as gr
2
  from random import randint
3
  from all_models import models
4
  from externalmod import gr_Interface_load
5
-
 
 
6
 
7
  def load_fn(models):
8
  global models_load
@@ -13,7 +15,8 @@ def load_fn(models):
13
  try:
14
  m = gr_Interface_load(f'models/{model}')
15
  except Exception as error:
16
- m = gr.Interface(lambda txt: None, ['text'], ['image'])
 
17
  models_load.update({model: m})
18
 
19
 
@@ -22,75 +25,160 @@ load_fn(models)
22
 
23
  num_models = 6
24
  default_models = models[:num_models]
25
-
26
-
27
 
28
  def extend_choices(choices):
29
- return choices[0:num_models] + (num_models - len(choices[0:num_models])) * ['NA']
30
 
31
 
32
  def update_imgbox(choices):
33
- choices_plus = extend_choices(choices[0:num_models])
34
  return [gr.Image(None, label = m, visible = (m != 'NA')) for m in choices_plus]
35
 
36
-
37
- def gen_fn(model_str, prompt):
38
- if model_str == 'NA':
39
- return None
40
- noise = str('') #str(randint(0, 99999999999))
41
- return models_load[model_str](f'{prompt} {noise}')
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
 
45
- with gr.Blocks() as demo:
46
- gr.HTML(
47
- """
48
- <div>
49
- <p> <center>For simultaneous generations without queue check out <a href="https://huggingface.co/spaces/Yntec/ToyWorld">Toy World</a>! For different behavior and galleries check out <a href="https://huggingface.co/spaces/Yntec/Diffusion80XX4">Diffusion80XX4</a> and <a href="https://huggingface.co/spaces/John6666/Diffusion80XX4g">Diffusion80XX4g</a> by John6666!</center>
50
- </p></div>
51
- """
52
- )
53
-
54
- with gr.Tab('The Dream'):
55
- txt_input = gr.Textbox(label = 'Your prompt:', lines=4) #.style(container=False,min_width=1200)
56
- gen_button = gr.Button('Generate up to 6 images from 1 minute to 18 minutes total wait time')
57
- stop_button = gr.Button('Stop', variant = 'secondary', interactive = False)
58
- gen_button.click(lambda s: gr.update(interactive = True), None, stop_button)
59
- gr.HTML(
60
- """
61
- <div style="text-align: center; max-width: 1200px; margin: 0 auto;">
62
- <div>
63
- <body>
64
- <div class="center"><p style="margin-bottom: 10px; color: #000000;">Scroll down to see more images and select models.</p>
65
- </div>
66
- </body>
67
- </div>
68
- </div>
69
- """
70
- )
71
- with gr.Row():
72
- output = [gr.Image(label = m, min_width=480) for m in default_models]
73
- current_models = [gr.Textbox(m, visible = False) for m in default_models]
74
-
75
- for m, o in zip(current_models, output):
76
- gen_event = gen_button.click(gen_fn, [m, txt_input], o)
77
- stop_button.click(lambda s: gr.update(interactive = False), None, stop_button, cancels = [gen_event])
78
- with gr.Accordion('Model selection'):
79
- #model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 866 available!', value = default_models, multiselect = True, max_choices = num_models, interactive = True, filterable = False)
80
- #model_choice.change(update_imgbox, model_choice, output)
81
- #model_choice.change(extend_choices, model_choice, current_models)
82
- model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 874 available!', value = default_models, interactive = True)
83
- #model_choice.change(lambda x: x[0:num_models], [model_choice], [model_choice])
84
- model_choice.change(update_imgbox, model_choice, output)
85
- model_choice.change(extend_choices, model_choice, current_models)
86
- with gr.Row():
87
- gr.HTML(
88
- """
89
- <div class="footer">
90
- <p> Based on the <a href="https://huggingface.co/spaces/derwahnsinn/TestGen">TestGen</a> Space by derwahnsinn, the <a href="https://huggingface.co/spaces/RdnUser77/SpacIO_v1">SpacIO</a> Space by RdnUser77 and Omnibus's Maximum Multiplier!
91
- </p>
92
- """
93
- )
94
-
95
- demo.queue()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  demo.launch()
 
2
  from random import randint
3
  from all_models import models
4
  from externalmod import gr_Interface_load
5
+ import asyncio
6
+ from threading import RLock
7
+ lock = RLock()
8
 
9
  def load_fn(models):
10
  global models_load
 
15
  try:
16
  m = gr_Interface_load(f'models/{model}')
17
  except Exception as error:
18
+ print(error)
19
+ m = gr.Interface(lambda: None, ['text'], ['image'])
20
  models_load.update({model: m})
21
 
22
 
 
25
 
26
  num_models = 6
27
  default_models = models[:num_models]
28
+ timeout = 60
 
29
 
30
  def extend_choices(choices):
31
+ return choices[:num_models] + (num_models - len(choices[:num_models])) * ['NA']
32
 
33
 
34
  def update_imgbox(choices):
35
+ choices_plus = extend_choices(choices[:num_models])
36
  return [gr.Image(None, label = m, visible = (m != 'NA')) for m in choices_plus]
37
 
 
 
 
 
 
 
38
 
39
+ def update_imgbox_gallery(choices):
40
+ choices_plus = extend_choices(choices[:num_models])
41
+ return [gr.Gallery(None, label = m, visible = (m != 'NA')) for m in choices_plus]
42
+
43
+
44
+ async def infer(model_str, prompt, timeout):
45
+ from PIL import Image
46
+ noise = ""
47
+ rand = randint(1, 500)
48
+ for i in range(rand):
49
+ noise += " "
50
+ task = asyncio.create_task(asyncio.to_thread(models_load[model_str], f'{prompt} {noise}'))
51
+ await asyncio.sleep(0)
52
+ try:
53
+ result = await asyncio.wait_for(task, timeout=timeout)
54
+ except (Exception, asyncio.TimeoutError) as e:
55
+ print(e)
56
+ print(f"Task timed out: {model_str}")
57
+ if not task.done(): task.cancel()
58
+ result = None
59
+ if task.done() and result is not None:
60
+ with lock:
61
+ image = Image.open(result).convert('RGBA')
62
+ return image
63
+ return None
64
 
65
 
66
+ def gen_fn(model_str, prompt):
67
+ if model_str == 'NA':
68
+ return None
69
+ try:
70
+ loop = asyncio.new_event_loop()
71
+ result = loop.run_until_complete(infer(model_str, prompt, timeout))
72
+ except (Exception, asyncio.CancelledError) as e:
73
+ print(e)
74
+ print(f"Task aborted: {model_str}")
75
+ result = None
76
+ finally:
77
+ loop.close()
78
+ return result
79
+
80
+
81
+ def add_gallery(image, model_str, gallery):
82
+ if gallery is None: gallery = []
83
+ with lock:
84
+ if image is not None: gallery.insert(0, (image, model_str))
85
+ return gallery
86
+
87
+
88
+ def gen_fn_gallery(model_str, prompt, gallery):
89
+ if gallery is None: gallery = []
90
+ if model_str == 'NA':
91
+ yield gallery
92
+ try:
93
+ loop = asyncio.new_event_loop()
94
+ result = loop.run_until_complete(infer(model_str, prompt, timeout))
95
+ with lock:
96
+ if result: gallery.insert(0, result)
97
+ except (Exception, asyncio.CancelledError) as e:
98
+ print(e)
99
+ print(f"Task aborted: {model_str}")
100
+ finally:
101
+ loop.close()
102
+ yield gallery
103
+
104
+
105
+ CSS="""
106
+ #container { max-width: 1200px; margin: 0 auto; !important; }
107
+ .output { width=112px; height=112px; !important; }
108
+ .gallery { width=100%; min_height=768px; !important; }
109
+ .guide { text-align: center; !important; }
110
+ """
111
+
112
+ with gr.Blocks(theme='Nymbo/Nymbo_Theme', fill_width=True, css=CSS) as demo:
113
+ with gr.Tab('The Dream'):
114
+ with gr.Column(scale=2):
115
+ txt_input = gr.Textbox(label='Your prompt:', lines=4)
116
+ with gr.Row():
117
+ gen_button = gr.Button('Generate up to 6 images in up to 3 minutes total', scale=2)
118
+ stop_button = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
119
+ gen_button.click(lambda: gr.update(interactive = True), None, stop_button)
120
+ gr.Markdown("Scroll down to see more images and select models.", elem_classes="guide")
121
+
122
+ with gr.Column(scale=1):
123
+ with gr.Group():
124
+ with gr.Row():
125
+ output = [gr.Image(label=m, show_download_button=True, elem_classes="output", interactive=False, min_width=80, show_share_button=False, visible=True) for m in default_models]
126
+ #output = [gr.Image(label=m, show_download_button=True, elem_classes="output", interactive=False, show_share_button=True) for m in default_models]
127
+ #output = [gr.Gallery(label=m, show_download_button=True, elem_classes="output", interactive=False, show_share_button=True, container=True, format="png", object_fit="cover") for m in default_models]
128
+ current_models = [gr.Textbox(m, visible=False) for m in default_models]
129
+
130
+ with gr.Column(scale=2):
131
+ gallery = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
132
+ interactive=False, show_share_button=True, container=True, format="png",
133
+ preview=True, object_fit="cover", columns=2, rows=2)
134
+
135
+ for m, o in zip(current_models, output):
136
+ #gen_event = gen_button.click(gen_fn, [m, txt_input], o)
137
+ #gen_event = gen_button.click(gen_fn_gallery, [m, txt_input, o], o)
138
+ gen_event = gr.on(triggers=[gen_button.click, txt_input.submit], fn=gen_fn, inputs=[m, txt_input], outputs=[o])
139
+ o.change(add_gallery, [o, m, gallery], [gallery])
140
+ stop_button.click(lambda: gr.update(interactive = False), None, stop_button, cancels = [gen_event])
141
+
142
+ with gr.Column(scale=4):
143
+ with gr.Accordion('Model selection'):
144
+ model_choice = gr.CheckboxGroup(models, label = f'Choose up to {num_models} different models from the 866 available!', value=default_models, interactive=True)
145
+ model_choice.change(update_imgbox, model_choice, output)
146
+ #model_choice.change(update_imgbox_gallery, model_choice, output)
147
+ model_choice.change(extend_choices, model_choice, current_models)
148
+
149
+ with gr.Tab('Single model'):
150
+ with gr.Column(scale=2):
151
+ model_choice2 = gr.Dropdown(models, label='Choose model', value=models[0])
152
+ txt_input2 = gr.Textbox(label='Your prompt:', lines=4)
153
+
154
+ max_images = 6
155
+ num_images = gr.Slider(1, max_images, value=max_images, step=1, label='Number of images')
156
+
157
+ with gr.Row():
158
+ gen_button2 = gr.Button('Generate', scale=2)
159
+ stop_button2 = gr.Button('Stop', variant='secondary', interactive=False, scale=1)
160
+ gen_button2.click(lambda: gr.update(interactive = True), None, stop_button2)
161
+
162
+ with gr.Column(scale=1):
163
+ with gr.Group():
164
+ with gr.Row():
165
+ output2 = [gr.Image(label = '', show_download_button=True, elem_classes="output", interactive=False, min_width=80, visible=True, show_share_button=False, show_label=False) for _ in range(max_images)]
166
+ #output2 = [gr.Image(label = '') for _ in range(max_images)]
167
+
168
+ with gr.Column(scale=2):
169
+ gallery2 = gr.Gallery(label="Output", show_download_button=True, elem_classes="gallery",
170
+ interactive=False, show_share_button=True, container=True, format="png",
171
+ preview=True, object_fit="cover", columns=2, rows=2)
172
+
173
+ for i, o in enumerate(output2):
174
+ img_i = gr.Number(i, visible = False)
175
+ num_images.change(lambda i, n: gr.update(visible = (i < n)), [img_i, num_images], o)
176
+ #gen_event2 = gen_button2.click(lambda i, n, m, t: gen_fn(m, t) if (i < n) else None, [img_i, num_images, model_choice2, txt_input2], o)
177
+ gen_event2 = gr.on(triggers=[gen_button2.click, txt_input2.submit], fn=lambda i, n, m, t: gen_fn(m, t) if (i < n) else None, inputs=[img_i, num_images, model_choice2, txt_input2], outputs=[o])
178
+ o.change(add_gallery, [o, model_choice2, gallery2], [gallery2])
179
+ stop_button2.click(lambda: gr.update(interactive = False), None, stop_button2, cancels = [gen_event2])
180
+
181
+ 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!")
182
+
183
+ demo.queue()
184
  demo.launch()