glt3953 commited on
Commit
0b9e50e
1 Parent(s): 6268742

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +416 -0
  2. requirements.txt +12 -0
app.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from diffusers import DiffusionPipeline
4
+ import torch
5
+
6
+ import base64
7
+ from io import BytesIO
8
+ import os
9
+ import gc
10
+
11
+ from share_btn import community_icon_html, loading_icon_html, share_js
12
+
13
+ # SDXL code: https://github.com/huggingface/diffusers/pull/3859
14
+
15
+ model_dir = os.getenv("SDXL_MODEL_DIR")
16
+ access_token = os.getenv("ACCESS_TOKEN")
17
+
18
+ if model_dir:
19
+ # Use local model
20
+ model_key_base = os.path.join(model_dir, "stable-diffusion-xl-base-0.9")
21
+ model_key_refiner = os.path.join(model_dir, "stable-diffusion-xl-refiner-0.9")
22
+ else:
23
+ model_key_base = "stabilityai/stable-diffusion-xl-base-0.9"
24
+ model_key_refiner = "stabilityai/stable-diffusion-xl-refiner-0.9"
25
+
26
+ # Use refiner (enabled by default)
27
+ enable_refiner = os.getenv("ENABLE_REFINER", "true").lower() == "true"
28
+ # Output images before the refiner and after the refiner
29
+ output_images_before_refiner = os.getenv("OUTPUT_IMAGES_BEFORE_REFINER", "false").lower() == "true"
30
+
31
+ # Create public link
32
+ share = os.getenv("SHARE", "false").lower() == "true"
33
+
34
+ print("Loading model", model_key_base)
35
+ pipe = DiffusionPipeline.from_pretrained(model_key_base, torch_dtype=torch.float16, use_safetensors=True, variant="fp16", use_auth_token=access_token)
36
+
37
+ pipe.enable_model_cpu_offload()
38
+ # pipe.to("cuda")
39
+
40
+ # if using torch < 2.0
41
+ # pipe.enable_xformers_memory_efficient_attention()
42
+
43
+ # pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
44
+
45
+ if enable_refiner:
46
+ print("Loading model", model_key_refiner)
47
+ pipe_refiner = DiffusionPipeline.from_pretrained(model_key_refiner, torch_dtype=torch.float16, use_safetensors=True, variant="fp16", use_auth_token=access_token)
48
+ pipe_refiner.enable_model_cpu_offload()
49
+ # pipe_refiner.to("cuda")
50
+
51
+ # if using torch < 2.0
52
+ # pipe_refiner.enable_xformers_memory_efficient_attention()
53
+
54
+ # pipe_refiner.unet = torch.compile(pipe_refiner.unet, mode="reduce-overhead", fullgraph=True)
55
+
56
+ # NOTE: we do not have word list filtering in this gradio demo
57
+
58
+ is_gpu_busy = False
59
+ def infer(prompt, negative, scale, samples=4, steps=50, refiner_strength=0.3):
60
+ prompt, negative = [prompt] * samples, [negative] * samples
61
+ images = pipe(prompt=prompt, negative_prompt=negative, guidance_scale=scale, num_inference_steps=steps).images
62
+
63
+ gc.collect()
64
+ torch.cuda.empty_cache()
65
+
66
+ images_b64_list = []
67
+
68
+ if enable_refiner:
69
+ if output_images_before_refiner:
70
+ for image in images:
71
+ buffered = BytesIO()
72
+ image.save(buffered, format="JPEG")
73
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
74
+
75
+ image_b64 = (f"data:image/jpeg;base64,{img_str}")
76
+ images_b64_list.append(image_b64)
77
+
78
+ images = pipe_refiner(prompt=prompt, negative_prompt=negative, image=images, num_inference_steps=steps, strength=refiner_strength).images
79
+
80
+ gc.collect()
81
+ torch.cuda.empty_cache()
82
+
83
+ for image in images:
84
+ buffered = BytesIO()
85
+ image.save(buffered, format="JPEG")
86
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
87
+
88
+ image_b64 = (f"data:image/jpeg;base64,{img_str}")
89
+ images_b64_list.append(image_b64)
90
+
91
+ return images_b64_list
92
+
93
+
94
+ css = """
95
+ .gradio-container {
96
+ font-family: 'IBM Plex Sans', sans-serif;
97
+ }
98
+ .gr-button {
99
+ color: white;
100
+ border-color: black;
101
+ background: black;
102
+ }
103
+ input[type='range'] {
104
+ accent-color: black;
105
+ }
106
+ .dark input[type='range'] {
107
+ accent-color: #dfdfdf;
108
+ }
109
+ .container {
110
+ max-width: 730px;
111
+ margin: auto;
112
+ padding-top: 1.5rem;
113
+ }
114
+ #gallery {
115
+ min-height: 22rem;
116
+ margin-bottom: 15px;
117
+ margin-left: auto;
118
+ margin-right: auto;
119
+ border-bottom-right-radius: .5rem !important;
120
+ border-bottom-left-radius: .5rem !important;
121
+ }
122
+ #gallery>div>.h-full {
123
+ min-height: 20rem;
124
+ }
125
+ .details:hover {
126
+ text-decoration: underline;
127
+ }
128
+ .gr-button {
129
+ white-space: nowrap;
130
+ }
131
+ .gr-button:focus {
132
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
133
+ outline: none;
134
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
135
+ --tw-border-opacity: 1;
136
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
137
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
138
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
139
+ --tw-ring-opacity: .5;
140
+ }
141
+ #advanced-btn {
142
+ font-size: .7rem !important;
143
+ line-height: 19px;
144
+ margin-top: 12px;
145
+ margin-bottom: 12px;
146
+ padding: 2px 8px;
147
+ border-radius: 14px !important;
148
+ }
149
+ #advanced-options {
150
+ display: none;
151
+ margin-bottom: 20px;
152
+ }
153
+ .footer {
154
+ margin-bottom: 45px;
155
+ margin-top: 35px;
156
+ text-align: center;
157
+ border-bottom: 1px solid #e5e5e5;
158
+ }
159
+ .footer>p {
160
+ font-size: .8rem;
161
+ display: inline-block;
162
+ padding: 0 10px;
163
+ transform: translateY(10px);
164
+ background: white;
165
+ }
166
+ .dark .footer {
167
+ border-color: #303030;
168
+ }
169
+ .dark .footer>p {
170
+ background: #0b0f19;
171
+ }
172
+ .acknowledgments h4{
173
+ margin: 1.25em 0 .25em 0;
174
+ font-weight: bold;
175
+ font-size: 115%;
176
+ }
177
+ .animate-spin {
178
+ animation: spin 1s linear infinite;
179
+ }
180
+ @keyframes spin {
181
+ from {
182
+ transform: rotate(0deg);
183
+ }
184
+ to {
185
+ transform: rotate(360deg);
186
+ }
187
+ }
188
+ #share-btn-container {
189
+ 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;
190
+ margin-top: 10px;
191
+ margin-left: auto;
192
+ }
193
+ #share-btn {
194
+ 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;right:0;
195
+ }
196
+ #share-btn * {
197
+ all: unset;
198
+ }
199
+ #share-btn-container div:nth-child(-n+2){
200
+ width: auto !important;
201
+ min-height: 0px !important;
202
+ }
203
+ #share-btn-container .wrap {
204
+ display: none !important;
205
+ }
206
+
207
+ .gr-form{
208
+ flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;
209
+ }
210
+ #prompt-container{
211
+ gap: 0;
212
+ }
213
+ #prompt-text-input, #negative-prompt-text-input{padding: .45rem 0.625rem}
214
+ #component-16{border-top-width: 1px!important;margin-top: 1em}
215
+ .image_duplication{position: absolute; width: 100px; left: 50px}
216
+ """
217
+
218
+ block = gr.Blocks(css=css)
219
+
220
+ examples = [
221
+ [
222
+ 'A high tech solarpunk utopia in the Amazon rainforest',
223
+ 'low quality',
224
+ 9
225
+ ],
226
+ [
227
+ 'A pikachu fine dining with a view to the Eiffel Tower',
228
+ 'low quality',
229
+ 9
230
+ ],
231
+ [
232
+ 'A mecha robot in a favela in expressionist style',
233
+ 'low quality, 3d, photorealistic',
234
+ 9
235
+ ],
236
+ [
237
+ 'an insect robot preparing a delicious meal',
238
+ 'low quality, illustration',
239
+ 9
240
+ ],
241
+ [
242
+ "A small cabin on top of a snowy mountain in the style of Disney, artstation",
243
+ 'low quality, ugly',
244
+ 9
245
+ ],
246
+ ]
247
+
248
+
249
+ with block:
250
+ gr.HTML(
251
+ """
252
+ <div style="text-align: center; margin: 0 auto;">
253
+ <div
254
+ style="
255
+ display: inline-flex;
256
+ align-items: center;
257
+ gap: 0.8rem;
258
+ font-size: 1.75rem;
259
+ "
260
+ >
261
+ <svg
262
+ width="0.65em"
263
+ height="0.65em"
264
+ viewBox="0 0 115 115"
265
+ fill="none"
266
+ xmlns="http://www.w3.org/2000/svg"
267
+ >
268
+ <rect width="23" height="23" fill="white"></rect>
269
+ <rect y="69" width="23" height="23" fill="white"></rect>
270
+ <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
271
+ <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
272
+ <rect x="46" width="23" height="23" fill="white"></rect>
273
+ <rect x="46" y="69" width="23" height="23" fill="white"></rect>
274
+ <rect x="69" width="23" height="23" fill="black"></rect>
275
+ <rect x="69" y="69" width="23" height="23" fill="black"></rect>
276
+ <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
277
+ <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
278
+ <rect x="115" y="46" width="23" height="23" fill="white"></rect>
279
+ <rect x="115" y="115" width="23" height="23" fill="white"></rect>
280
+ <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
281
+ <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
282
+ <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
283
+ <rect x="92" y="69" width="23" height="23" fill="white"></rect>
284
+ <rect x="69" y="46" width="23" height="23" fill="white"></rect>
285
+ <rect x="69" y="115" width="23" height="23" fill="white"></rect>
286
+ <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
287
+ <rect x="46" y="46" width="23" height="23" fill="black"></rect>
288
+ <rect x="46" y="115" width="23" height="23" fill="black"></rect>
289
+ <rect x="46" y="69" width="23" height="23" fill="black"></rect>
290
+ <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
291
+ <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
292
+ <rect x="23" y="69" width="23" height="23" fill="black"></rect>
293
+ </svg>
294
+ <h1 style="font-weight: 900; margin-bottom: 7px;margin-top:5px">
295
+ Stable Diffusion XL 0.9 Demo
296
+ </h1>
297
+ </div>
298
+ <p style="margin-bottom: 10px; font-size: 94%; line-height: 23px;">
299
+ Stable Diffusion XL 0.9 is the latest text-to-image model from StabilityAI.
300
+ <a style="text-decoration: underline;" href="https://huggingface.co/spaces/stabilityai/stable-diffusion">Access SD v2.1 Space</a> <a style="text-decoration: underline;" href="https://huggingface.co/spaces/stabilityai/stable-diffusion-1">SD v1 Space</a>
301
+ <br/>
302
+ For faster generation and API access you can try
303
+ <a
304
+ href="http://beta.dreamstudio.ai/"
305
+ style="text-decoration: underline;"
306
+ target="_blank"
307
+ >DreamStudio Beta</a
308
+ >.</a>
309
+ </p>
310
+ </div>
311
+ """
312
+ )
313
+ with gr.Group():
314
+ with gr.Box():
315
+ with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
316
+ with gr.Column():
317
+ text = gr.Textbox(
318
+ label="Enter your prompt",
319
+ show_label=False,
320
+ max_lines=1,
321
+ placeholder="Enter your prompt",
322
+ elem_id="prompt-text-input",
323
+ ).style(
324
+ border=(True, False, True, True),
325
+ rounded=(True, False, False, True),
326
+ container=False,
327
+ )
328
+ negative = gr.Textbox(
329
+ label="Enter your negative prompt",
330
+ show_label=False,
331
+ max_lines=1,
332
+ placeholder="Enter a negative prompt",
333
+ elem_id="negative-prompt-text-input",
334
+ ).style(
335
+ border=(True, False, True, True),
336
+ rounded=(True, False, False, True),
337
+ container=False,
338
+ )
339
+ btn = gr.Button("Generate image").style(
340
+ margin=False,
341
+ rounded=(False, True, True, False),
342
+ full_width=False,
343
+ )
344
+
345
+ gallery = gr.Gallery(
346
+ label="Generated images", show_label=False, elem_id="gallery"
347
+ ).style(grid=[2], height="auto")
348
+
349
+ with gr.Group(elem_id="container-advanced-btns"):
350
+ #advanced_button = gr.Button("Advanced options", elem_id="advanced-btn")
351
+ with gr.Group(elem_id="share-btn-container"):
352
+ community_icon = gr.HTML(community_icon_html)
353
+ loading_icon = gr.HTML(loading_icon_html)
354
+ share_button = gr.Button("Share to community", elem_id="share-btn")
355
+
356
+ with gr.Accordion("Advanced settings", open=False):
357
+ # gr.Markdown("Advanced settings are temporarily unavailable")
358
+ samples = gr.Slider(label="Images", minimum=1, maximum=4, value=1, step=1)
359
+ steps = gr.Slider(label="Steps", minimum=1, maximum=250, value=50, step=1)
360
+ if enable_refiner:
361
+ refiner_strength = gr.Slider(label="Refiner Strength", minimum=0, maximum=1.0, value=0.3, step=0.1)
362
+ else:
363
+ refiner_strength = gr.Slider(label="Refiner Strength (refiner not enabled)", minimum=0, maximum=0, value=0, step=0)
364
+ guidance_scale = gr.Slider(
365
+ label="Guidance Scale", minimum=0, maximum=50, value=9, step=0.1
366
+ )
367
+ # seed = gr.Slider(
368
+ # label="Seed",
369
+ # minimum=0,
370
+ # maximum=2147483647,
371
+ # step=1,
372
+ # randomize=True,
373
+ # )
374
+
375
+ ex = gr.Examples(examples=examples, fn=infer, inputs=[text, negative, guidance_scale], outputs=[gallery, community_icon, loading_icon, share_button], cache_examples=False)
376
+ ex.dataset.headers = [""]
377
+ negative.submit(infer, inputs=[text, negative, guidance_scale, samples, steps, refiner_strength], outputs=[gallery], postprocess=False)
378
+ text.submit(infer, inputs=[text, negative, guidance_scale, samples, steps, refiner_strength], outputs=[gallery], postprocess=False)
379
+ btn.click(infer, inputs=[text, negative, guidance_scale, samples, steps, refiner_strength], outputs=[gallery], postprocess=False)
380
+
381
+ #advanced_button.click(
382
+ # None,
383
+ # [],
384
+ # text,
385
+ # _js="""
386
+ # () => {
387
+ # const options = document.querySelector("body > gradio-app").querySelector("#advanced-options");
388
+ # options.style.display = ["none", ""].includes(options.style.display) ? "flex" : "none";
389
+ # }""",
390
+ #)
391
+ share_button.click(
392
+ None,
393
+ [],
394
+ [],
395
+ _js=share_js,
396
+ )
397
+ gr.HTML(
398
+ """
399
+ <div class="footer">
400
+ <p>Model by <a href="https://huggingface.co/stabilityai" style="text-decoration: underline;" target="_blank">StabilityAI</a> - Gradio Demo by 🤗 Hugging Face and <a style="text-decoration: underline;" href="https://tonylian.com/">Long (Tony) Lian</a>
401
+ </p>
402
+ </div>
403
+ """
404
+ )
405
+ with gr.Accordion(label="License", open=False):
406
+ gr.HTML(
407
+ """<div class="acknowledgments">
408
+ <p><h4>LICENSE</h4>
409
+ The model is licensed with a <a href="https://huggingface.co/stabilityai/stable-diffusion-2/blob/main/LICENSE-MODEL" style="text-decoration: underline;" target="_blank">CreativeML OpenRAIL++</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>
410
+ <p><h4>Biases and content acknowledgment</h4>
411
+ 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>
412
+ </div>
413
+ """
414
+ )
415
+
416
+ block.queue().launch(share=share)
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cu113
2
+ torch==2.0.1
3
+ python-dotenv
4
+ accelerate
5
+ transformers
6
+ invisible-watermark
7
+ numpy>=1.17
8
+ PyWavelets>=1.1.1
9
+ opencv-python>=4.1.0.25
10
+ safetensors
11
+ gradio==3.11.0
12
+ git+https://github.com/huggingface/diffusers.git