Dhruv Diddi commited on
Commit
0bb1fd1
1 Parent(s): b36e944

update file

Browse files
Files changed (1) hide show
  1. app.py +32 -305
app.py CHANGED
@@ -1,312 +1,64 @@
1
  import gradio as gr
2
- #import torch
3
- #from torch import autocast
4
- #from diffusers import StableDiffusionPipeline
5
  from datasets import load_dataset
6
  from PIL import Image
7
- #from io import BytesIO
8
- #import base64
9
  import re
10
  import os
11
- import requests
12
-
13
-
14
- from share_btn import community_icon_html, loading_icon_html, share_js
15
 
 
16
  model_id = "CompVis/stable-diffusion-v1-4"
17
- device = "cuda"
18
-
19
- #If you are running this code locally, you need to either do a 'huggingface-cli login` or paste your User Access Token from here https://huggingface.co/settings/tokens into the use_auth_token field below.
20
- #pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True, revision="fp16", torch_dtype=torch.float16)
21
- #pipe = pipe.to(device)
22
- #torch.backends.cudnn.benchmark = True
23
-
24
- #When running locally, you won`t have access to this, so you can remove this part
25
- word_list_dataset = load_dataset("stabilityai/word-list", data_files="list.txt", use_auth_token="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")
26
- word_list = word_list_dataset["train"]['text']
27
-
28
- is_gpu_busy = False
29
- def infer(prompt):
30
- global is_gpu_busy
31
- samples = 4
32
- steps = 50
33
- scale = 7.5
34
- #When running locally you can also remove this filter
35
- for filter in word_list:
36
- if re.search(rf"\b{filter}\b", prompt):
37
- raise gr.Error("Unsafe content found. Please try again with different prompts.")
38
-
39
- #generator = torch.Generator(device=device).manual_seed(seed)
40
- #print("Is GPU busy? ", is_gpu_busy)
41
  images = []
42
- #if(not is_gpu_busy):
43
- # is_gpu_busy = True
44
- # images_list = pipe(
45
- # [prompt] * samples,
46
- # num_inference_steps=steps,
47
- # guidance_scale=scale,
48
- #generator=generator,
49
- # )
50
- # is_gpu_busy = False
51
- # safe_image = Image.open(r"unsafe.png")
52
- # for i, image in enumerate(images_list["sample"]):
53
- # if(images_list["nsfw_content_detected"][i]):
54
- # images.append(safe_image)
55
- # else:
56
- # images.append(image)
57
- #else:
58
- url = os.getenv('JAX_BACKEND_URL')
59
- payload = {'prompt': prompt}
60
- images_request = requests.post(url, json = payload)
61
- for image in images_request.json()["images"]:
62
- image_b64 = (f"data:image/jpeg;base64,{image}")
63
- images.append(image_b64)
64
-
65
  return images
66
 
67
-
68
- css = """
69
- .gradio-container {
70
- font-family: 'IBM Plex Sans', sans-serif;
71
- }
72
- .gr-button {
73
- color: white;
74
- border-color: black;
75
- background: black;
76
- }
77
- input[type='range'] {
78
- accent-color: black;
79
- }
80
- .dark input[type='range'] {
81
- accent-color: #dfdfdf;
82
- }
83
- .container {
84
- max-width: 730px;
85
- margin: auto;
86
- padding-top: 1.5rem;
87
- }
88
- #gallery {
89
- min-height: 22rem;
90
- margin-bottom: 15px;
91
- margin-left: auto;
92
- margin-right: auto;
93
- border-bottom-right-radius: .5rem !important;
94
- border-bottom-left-radius: .5rem !important;
95
- }
96
- #gallery>div>.h-full {
97
- min-height: 20rem;
98
- }
99
- .details:hover {
100
- text-decoration: underline;
101
- }
102
- .gr-button {
103
- white-space: nowrap;
104
- }
105
- .gr-button:focus {
106
- border-color: rgb(147 197 253 / var(--tw-border-opacity));
107
- outline: none;
108
- box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
109
- --tw-border-opacity: 1;
110
- --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
111
- --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
112
- --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
113
- --tw-ring-opacity: .5;
114
- }
115
- #advanced-btn {
116
- font-size: .7rem !important;
117
- line-height: 19px;
118
- margin-top: 12px;
119
- margin-bottom: 12px;
120
- padding: 2px 8px;
121
- border-radius: 14px !important;
122
- }
123
- #advanced-options {
124
- display: none;
125
- margin-bottom: 20px;
126
- }
127
- .footer {
128
- margin-bottom: 45px;
129
- margin-top: 35px;
130
- text-align: center;
131
- border-bottom: 1px solid #e5e5e5;
132
- }
133
- .footer>p {
134
- font-size: .8rem;
135
- display: inline-block;
136
- padding: 0 10px;
137
- transform: translateY(10px);
138
- background: white;
139
- }
140
- .dark .footer {
141
- border-color: #303030;
142
- }
143
- .dark .footer>p {
144
- background: #0b0f19;
145
- }
146
- .acknowledgments h4{
147
- margin: 1.25em 0 .25em 0;
148
- font-weight: bold;
149
- font-size: 115%;
150
- }
151
- #container-advanced-btns{
152
- display: flex;
153
- flex-wrap: wrap;
154
- justify-content: space-between;
155
- align-items: center;
156
- }
157
- .animate-spin {
158
- animation: spin 1s linear infinite;
159
- }
160
- @keyframes spin {
161
- from {
162
- transform: rotate(0deg);
163
- }
164
- to {
165
- transform: rotate(360deg);
166
- }
167
- }
168
- .gr-form{
169
- flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;
170
- }
171
- #prompt-container{
172
- gap: 0;
173
- }
174
- """
175
 
176
- block = gr.Blocks(css=css)
177
-
178
- examples = [
179
- [
180
- 'A high tech solarpunk utopia in the Amazon rainforest',
181
- # 4,
182
- # 45,
183
- # 7.5,
184
- # 1024,
185
- ],
186
- [
187
- 'A pikachu fine dining with a view to the Eiffel Tower',
188
- # 4,
189
- # 45,
190
- # 7,
191
- # 1024,
192
- ],
193
- [
194
- 'A mecha robot in a favela in expressionist style',
195
- # 4,
196
- # 45,
197
- # 7,
198
- # 1024,
199
- ],
200
- [
201
- 'an insect robot preparing a delicious meal',
202
- # 4,
203
- # 45,
204
- # 7,
205
- # 1024,
206
- ],
207
- [
208
- "A small cabin on top of a snowy mountain in the style of Disney, artstation",
209
- # 4,
210
- # 45,
211
- # 7,
212
- # 1024,
213
- ],
214
- ]
215
 
 
216
 
217
  with block:
218
- gr.HTML(
219
- """
220
- <div style="text-align: center; max-width: 650px; margin: 0 auto;">
221
- <div
222
- style="
223
- display: inline-flex;
224
- align-items: center;
225
- gap: 0.8rem;
226
- font-size: 1.75rem;
227
- "
228
- >
229
- <svg
230
- width="0.65em"
231
- height="0.65em"
232
- viewBox="0 0 115 115"
233
- fill="none"
234
- xmlns="http://www.w3.org/2000/svg"
235
- >
236
- <rect width="23" height="23" fill="white"></rect>
237
- <rect y="69" width="23" height="23" fill="white"></rect>
238
- <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
239
- <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
240
- <rect x="46" width="23" height="23" fill="white"></rect>
241
- <rect x="46" y="69" width="23" height="23" fill="white"></rect>
242
- <rect x="69" width="23" height="23" fill="black"></rect>
243
- <rect x="69" y="69" width="23" height="23" fill="black"></rect>
244
- <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
245
- <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
246
- <rect x="115" y="46" width="23" height="23" fill="white"></rect>
247
- <rect x="115" y="115" width="23" height="23" fill="white"></rect>
248
- <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
249
- <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
250
- <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
251
- <rect x="92" y="69" width="23" height="23" fill="white"></rect>
252
- <rect x="69" y="46" width="23" height="23" fill="white"></rect>
253
- <rect x="69" y="115" width="23" height="23" fill="white"></rect>
254
- <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
255
- <rect x="46" y="46" width="23" height="23" fill="black"></rect>
256
- <rect x="46" y="115" width="23" height="23" fill="black"></rect>
257
- <rect x="46" y="69" width="23" height="23" fill="black"></rect>
258
- <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
259
- <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
260
- <rect x="23" y="69" width="23" height="23" fill="black"></rect>
261
- </svg>
262
- </div>
263
- <p style="margin-bottom: 10px; font-size: 94%">
264
- Stable Diffusion is a state of the art text-to-image model that generates
265
- images from text.<br>For faster generation and forthcoming API
266
- access you can try
267
- <a
268
- href="http://beta.dreamstudio.ai/"
269
- style="text-decoration: underline;"
270
- target="_blank"
271
- >DreamStudio Beta</a
272
- >
273
- </p>
274
- </div>
275
- """
276
- )
277
  with gr.Group():
278
  with gr.Box():
279
- with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
280
  text = gr.Textbox(
281
- label="Enter prompt",
282
  show_label=False,
283
  max_lines=1,
284
- placeholder="Enter prompt",
285
- elem_id="prompt-text-input",
286
  ).style(
287
  border=(True, False, True, True),
288
  rounded=(True, False, False, True),
289
  container=False,
290
  )
291
- btn = gr.Button("^").style(
292
  margin=False,
293
  rounded=(False, True, True, False),
294
- full_width=False,
295
  )
296
-
297
  gallery = gr.Gallery(
298
- label="images", show_label=False, elem_id="gallery"
299
  ).style(grid=[2], height="auto")
300
 
301
- with gr.Group(elem_id="container-advanced-btns"):
302
- advanced_button = gr.Button("Advanced options", elem_id="advanced-btn")
303
- with gr.Group(elem_id="share-btn-container"):
304
- community_icon = gr.HTML(community_icon_html)
305
- loading_icon = gr.HTML(loading_icon_html)
306
- share_button = gr.Button("Share to community", elem_id="share-btn")
307
 
308
  with gr.Row(elem_id="advanced-options"):
309
- gr.Markdown("Advanced settings are temporarily unavailable")
310
  samples = gr.Slider(label="Images", minimum=1, maximum=4, value=4, step=1)
311
  steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=45, step=1)
312
  scale = gr.Slider(
@@ -319,37 +71,12 @@ with block:
319
  step=1,
320
  randomize=True,
321
  )
322
-
323
- ex = gr.Examples(examples=examples, fn=infer, inputs=text, outputs=[gallery, community_icon, loading_icon, share_button], cache_examples=False)
324
- ex.dataset.headers = [""]
325
-
326
- text.submit(infer, inputs=text, outputs=[gallery], postprocess=False)
327
- btn.click(infer, inputs=text, outputs=[gallery], postprocess=False)
328
-
329
  advanced_button.click(
330
  None,
331
  [],
332
  text,
333
- _js="""
334
- () => {
335
- const options = document.querySelector("body > gradio-app").querySelector("#advanced-options");
336
- options.style.display = ["none", ""].includes(options.style.display) ? "flex" : "none";
337
- }""",
338
  )
339
 
340
- gr.HTML(
341
- """
342
- <div class="footer">
343
- <p>Model by <a href="https://huggingface.co/CompVis" style="text-decoration: underline;" target="_blank">CompVis</a> and <a href="https://huggingface.co/stabilityai" style="text-decoration: underline;" target="_blank">Stability AI</a> - Gradio Demo by 🤗 Hugging Face
344
- </p>
345
- </div>
346
- <div class="acknowledgments">
347
- <p><h4>LICENSE</h4>
348
- The model is licensed with a <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" style="text-decoration: underline;" target="_blank">CreativeML Open RAIL-M</a> license. The authors claim no rights on the outputs you generate, you are free to use them and are accountable for their use which must not go against the provisions set in this license. The license forbids you from sharing any content that violates any laws, produce any harm to a person, disseminate any personal information that would be meant for harm, spread misinformation and target vulnerable groups. For the full list of restrictions please <a href="https://huggingface.co/spaces/CompVis/stable-diffusion-license" target="_blank" style="text-decoration: underline;" target="_blank">read the license</a></p>
349
- <p><h4>Biases and content acknowledgment</h4>
350
- Despite how impressive being able to turn text into image is, beware to the fact that this model may output content that reinforces or exacerbates societal biases, as well as realistic faces, pornography and violence. The model was trained on the <a href="https://laion.ai/blog/laion-5b/" style="text-decoration: underline;" target="_blank">LAION-5B dataset</a>, which scraped non-curated image-text-pairs from the internet (the exception being the removal of illegal content) and is meant for research purposes. You can read more in the <a href="https://huggingface.co/CompVis/stable-diffusion-v1-4" style="text-decoration: underline;" target="_blank">model card</a></p>
351
- </div>
352
- """
353
- )
354
-
355
- block.queue(concurrency_count=40, max_size=20).launch(max_threads=150)
 
1
  import gradio as gr
2
+ import torch
3
+ from torch import autocast
4
+ from diffusers import StableDiffusionPipeline
5
  from datasets import load_dataset
6
  from PIL import Image
 
 
7
  import re
8
  import os
 
 
 
 
9
 
10
+ auth_token = os.getenv("auth_token")
11
  model_id = "CompVis/stable-diffusion-v1-4"
12
+ device = "cpu"
13
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=auth_token, revision="fp16", torch_dtype=torch.float16)
14
+ pipe = pipe.to(device)
15
+
16
+ def infer(prompt, samples, steps, scale, seed):
17
+ generator = torch.Generator(device=device).manual_seed(seed)
18
+ images_list = pipe(
19
+ [prompt] * samples,
20
+ num_inference_steps=steps,
21
+ guidance_scale=scale,
22
+ generator=generator,
23
+ )
 
 
 
 
 
 
 
 
 
 
 
 
24
  images = []
25
+ safe_image = Image.open(r"unsafe.png")
26
+ for i, image in enumerate(images_list["sample"]):
27
+ if(images_list["nsfw_content_detected"][i]):
28
+ images.append(safe_image)
29
+ else:
30
+ images.append(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  return images
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ block = gr.Blocks()
36
 
37
  with block:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  with gr.Group():
39
  with gr.Box():
40
+ with gr.Row().style(mobile_collapse=False, equal_height=True):
41
  text = gr.Textbox(
42
+ label="Enter your prompt",
43
  show_label=False,
44
  max_lines=1,
45
+ placeholder="Enter your prompt",
 
46
  ).style(
47
  border=(True, False, True, True),
48
  rounded=(True, False, False, True),
49
  container=False,
50
  )
51
+ btn = gr.Button("Generate image").style(
52
  margin=False,
53
  rounded=(False, True, True, False),
 
54
  )
 
55
  gallery = gr.Gallery(
56
+ label="Generated images", show_label=False, elem_id="gallery"
57
  ).style(grid=[2], height="auto")
58
 
59
+ advanced_button = gr.Button("Advanced options", elem_id="advanced-btn")
 
 
 
 
 
60
 
61
  with gr.Row(elem_id="advanced-options"):
 
62
  samples = gr.Slider(label="Images", minimum=1, maximum=4, value=4, step=1)
63
  steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=45, step=1)
64
  scale = gr.Slider(
 
71
  step=1,
72
  randomize=True,
73
  )
74
+ text.submit(infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)
75
+ btn.click(infer, inputs=[text, samples, steps, scale, seed], outputs=gallery)
 
 
 
 
 
76
  advanced_button.click(
77
  None,
78
  [],
79
  text,
 
 
 
 
 
80
  )
81
 
82
+ block.launch()