freddyaboulton HF staff commited on
Commit
aa57eec
1 Parent(s): 5318168

Upload app.py

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