shauray commited on
Commit
96b5ce9
1 Parent(s): 546ce74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +335 -407
app.py CHANGED
@@ -1,421 +1,349 @@
1
  import gradio as gr
2
- import torch
3
- from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
 
5
- from diffusers import StableDiffusionXLPipeline
6
- from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
7
- import torch
8
- from PIL import Image
9
 
10
- import diffusers
11
  from share_btn import community_icon_html, loading_icon_html, share_js
12
 
13
- device = "cuda" if torch.cuda.is_available() else "cpu"
14
-
15
- pipe = StableDiffusionXLPipeline.from_pretrained(
16
- "stabilityai/stable-diffusion-xl-base-1.0",
17
- torch_dtype=torch.float32,
18
- variants="fp32",
19
- use_safetensor=True,
20
- )
21
- pipe.to(device)
22
-
23
- @torch.no_grad()
24
- def call(
25
- pipe,
26
- prompt: Union[str, List[str]] = None,
27
- prompt2: Union[str, List[str]] = None,
28
- height: Optional[int] = None,
29
- width: Optional[int] = None,
30
- num_inference_steps: int = 50,
31
- denoising_end: Optional[float] = None,
32
- guidance_scale: float = 5.0,
33
- guidance_scale2: float = 5.0,
34
- negative_prompt: Optional[Union[str, List[str]]] = None,
35
- negative_prompt2: Optional[Union[str, List[str]]] = None,
36
- num_images_per_prompt: Optional[int] = 1,
37
- eta: float = 0.0,
38
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
39
- latents: Optional[torch.FloatTensor] = None,
40
- prompt_embeds: Optional[torch.FloatTensor] = None,
41
- negative_prompt_embeds: Optional[torch.FloatTensor] = None,
42
- pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
43
- negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
44
- output_type: Optional[str] = "pil",
45
- return_dict: bool = True,
46
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
47
- callback_steps: int = 1,
48
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
49
- guidance_rescale: float = 0.0,
50
- original_size: Optional[Tuple[int, int]] = None,
51
- crops_coords_top_left: Tuple[int, int] = (0, 0),
52
- target_size: Optional[Tuple[int, int]] = None,
53
- negative_original_size: Optional[Tuple[int, int]] = None,
54
- negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
55
- negative_target_size: Optional[Tuple[int, int]] = None,
56
- ):
57
- # 0. Default height and width to unet
58
- height = height or pipe.default_sample_size * pipe.vae_scale_factor
59
- width = width or pipe.default_sample_size * pipe.vae_scale_factor
60
-
61
- original_size = original_size or (height, width)
62
- target_size = target_size or (height, width)
63
-
64
- # 1. Check inputs. Raise error if not correct
65
- pipe.check_inputs(
66
- prompt,
67
- None,
68
- height,
69
- width,
70
- callback_steps,
71
- negative_prompt,
72
- None,
73
- prompt_embeds,
74
- negative_prompt_embeds,
75
- pooled_prompt_embeds,
76
- negative_pooled_prompt_embeds,
77
- )
78
-
79
- # 2. Define call parameters
80
- if prompt is not None and isinstance(prompt, str):
81
- batch_size = 1
82
- elif prompt is not None and isinstance(prompt, list):
83
- batch_size = len(prompt)
84
- else:
85
- batch_size = prompt_embeds.shape[0]
86
-
87
- device = pipe._execution_device
88
-
89
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
90
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
91
- # corresponds to doing no classifier free guidance.
92
- do_classifier_free_guidance = guidance_scale > 1.0
93
-
94
- # 3. Encode input prompt
95
- text_encoder_lora_scale = (
96
- cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
97
- )
98
-
99
- (
100
- prompt_embeds,
101
- negative_prompt_embeds,
102
- pooled_prompt_embeds,
103
- negative_pooled_prompt_embeds,
104
- ) = pipe.encode_prompt(
105
- prompt=prompt,
106
- device=device,
107
- num_images_per_prompt=num_images_per_prompt,
108
- do_classifier_free_guidance=do_classifier_free_guidance,
109
- negative_prompt=negative_prompt,
110
- prompt_embeds=None,
111
- negative_prompt_embeds=None,
112
- pooled_prompt_embeds=None,
113
- negative_pooled_prompt_embeds=None,
114
- lora_scale=text_encoder_lora_scale,
115
- )
116
-
117
- (
118
- prompt2_embeds,
119
- negative_prompt2_embeds,
120
- pooled_prompt2_embeds,
121
- negative_pooled_prompt2_embeds,
122
- ) = pipe.encode_prompt(
123
- prompt=prompt2,
124
- device=device,
125
- num_images_per_prompt=num_images_per_prompt,
126
- do_classifier_free_guidance=do_classifier_free_guidance,
127
- negative_prompt=negative_prompt2,
128
- prompt_embeds=None,
129
- negative_prompt_embeds=None,
130
- pooled_prompt_embeds=None,
131
- negative_pooled_prompt_embeds=None,
132
- lora_scale=text_encoder_lora_scale,
133
- )
134
-
135
- # 4. Prepare timesteps
136
- pipe.scheduler.set_timesteps(num_inference_steps, device=device)
137
-
138
- timesteps = pipe.scheduler.timesteps
139
-
140
- # 5. Prepare latent variables
141
- num_channels_latents = pipe.unet.config.in_channels
142
- latents = pipe.prepare_latents(
143
- batch_size * num_images_per_prompt,
144
- num_channels_latents,
145
- height,
146
- width,
147
- prompt_embeds.dtype,
148
- device,
149
- generator,
150
- latents,
151
- )
152
-
153
- # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
154
- extra_step_kwargs = pipe.prepare_extra_step_kwargs(generator, eta)
155
-
156
- # 7. Prepare added time ids & embeddings
157
- add_text_embeds = pooled_prompt_embeds
158
- add_text2_embeds = pooled_prompt2_embeds
159
-
160
- add_time_ids = pipe._get_add_time_ids(
161
- original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
162
- )
163
- add_time2_ids = pipe._get_add_time_ids(
164
- original_size, crops_coords_top_left, target_size, dtype=prompt2_embeds.dtype
165
- )
166
-
167
- if negative_original_size is not None and negative_target_size is not None:
168
- negative_add_time_ids = pipe._get_add_time_ids(
169
- negative_original_size,
170
- negative_crops_coords_top_left,
171
- negative_target_size,
172
- dtype=prompt_embeds.dtype,
173
- )
174
- else:
175
- negative_add_time_ids = add_time_ids
176
- negative_add_time2_ids = add_time2_ids
177
-
178
- if do_classifier_free_guidance:
179
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
180
- add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
181
- add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
182
-
183
- prompt2_embeds = torch.cat([negative_prompt2_embeds, prompt2_embeds], dim=0)
184
- add_text2_embeds = torch.cat([negative_pooled_prompt2_embeds, add_text2_embeds], dim=0)
185
- add_time2_ids = torch.cat([negative_add_time2_ids, add_time2_ids], dim=0)
186
-
187
- prompt_embeds = prompt_embeds.to(device)
188
- add_text_embeds = add_text_embeds.to(device)
189
- add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
190
-
191
- prompt2_embeds = prompt2_embeds.to(device)
192
- add_text2_embeds = add_text2_embeds.to(device)
193
- add_time2_ids = add_time2_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
194
-
195
- # 8. Denoising loop
196
- num_warmup_steps = max(len(timesteps) - num_inference_steps * pipe.scheduler.order, 0)
197
-
198
- # 7.1 Apply denoising_end
199
- if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
200
- discrete_timestep_cutoff = int(
201
- round(
202
- pipe.scheduler.config.num_train_timesteps
203
- - (denoising_end * pipe.scheduler.config.num_train_timesteps)
204
- )
205
- )
206
- num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
207
- timesteps = timesteps[:num_inference_steps]
208
-
209
- with pipe.progress_bar(total=num_inference_steps) as progress_bar:
210
- for i, t in enumerate(timesteps):
211
- if i % 2 == 0:
212
- # expand the latents if we are doing classifier-free guidance
213
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
214
-
215
- latent_model_input = pipe.scheduler.scale_model_input(latent_model_input, t)
216
-
217
- # predict the noise residual
218
- added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
219
- noise_pred = pipe.unet(
220
- latent_model_input,
221
- t,
222
- encoder_hidden_states=prompt_embeds,
223
- cross_attention_kwargs=cross_attention_kwargs,
224
- added_cond_kwargs=added_cond_kwargs,
225
- return_dict=False,
226
- )[0]
227
-
228
- # perform guidance
229
- if do_classifier_free_guidance:
230
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
231
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
232
- else:
233
- # expand the latents if we are doing classifier free guidance
234
- latent_model_input2 = torch.cat([latents.flip(2)] * 2) if do_classifier_free_guidance else latents
235
- latent_model_input2 = pipe.scheduler.scale_model_input(latent_model_input2, t)
236
-
237
- # predict the noise residual
238
- added_cond2_kwargs = {"text_embeds": add_text2_embeds, "time_ids": add_time2_ids}
239
- noise_pred2 = pipe.unet(
240
- latent_model_input2,
241
- t,
242
- encoder_hidden_states=prompt2_embeds,
243
- cross_attention_kwargs=cross_attention_kwargs,
244
- added_cond_kwargs=added_cond2_kwargs,
245
- return_dict=False,
246
- )[0]
247
-
248
- # perform guidance
249
- if do_classifier_free_guidance:
250
- noise_pred2_uncond, noise_pred2_text = noise_pred2.chunk(2)
251
- noise_pred2 = noise_pred2_uncond + guidance_scale2 * (noise_pred2_text - noise_pred2_uncond)
252
-
253
- noise_pred = noise_pred if i % 2 == 0 else noise_pred2.flip(2)
254
-
255
- # compute the previous noisy sample x_t -> x_t-1
256
- latents = pipe.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
257
-
258
- # call the callback, if provided
259
- if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % pipe.scheduler.order == 0):
260
- progress_bar.update()
261
- if callback is not None and i % callback_steps == 0:
262
- callback(i, t, latents)
263
-
264
- if not output_type == "latent":
265
- # make sure the VAE is in float32 mode, as it overflows in float16
266
- needs_upcasting = pipe.vae.dtype == torch.float16 and pipe.vae.config.force_upcast
267
-
268
- if needs_upcasting:
269
- pipe.upcast_vae()
270
- latents = latents.to(next(iter(pipe.vae.post_quant_conv.parameters())).dtype)
271
-
272
- image = pipe.vae.decode(latents / pipe.vae.config.scaling_factor, return_dict=False)[0]
273
-
274
- # cast back to fp16 if needed
275
- if needs_upcasting:
276
- pipe.vae.to(dtype=torch.float16)
277
- else:
278
- image = latents
279
-
280
- if not output_type == "latent":
281
- # apply watermark if available
282
- if pipe.watermark is not None:
283
- image = pipe.watermark.apply_watermark(image)
284
-
285
- image = pipe.image_processor.postprocess(image, output_type=output_type)
286
-
287
- # Offload all models
288
- pipe.maybe_free_model_hooks()
289
-
290
- if not return_dict:
291
- return (image,)
292
-
293
- return StableDiffusionXLPipelineOutput(images=image)
294
-
295
- def read_content(file_path: str) -> str:
296
- """read the content of target file
297
- """
298
- with open(file_path, 'r', encoding='utf-8') as f:
299
- content = f.read()
300
-
301
- return content
302
-
303
- def predict(dict, prompt="", negative_prompt="", guidance_scale=7.5, steps=20, strength=1.0, scheduler="EulerDiscreteScheduler"):
304
- if negative_prompt == "":
305
- negative_prompt = None
306
- scheduler_class_name = scheduler.split("-")[0]
307
-
308
- add_kwargs = {}
309
- if len(scheduler.split("-")) > 1:
310
- add_kwargs["use_karras"] = True
311
- if len(scheduler.split("-")) > 2:
312
- add_kwargs["algorithm_type"] = "sde-dpmsolver++"
313
-
314
- scheduler = getattr(diffusers, scheduler_class_name)
315
- pipe.scheduler = scheduler.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="scheduler", **add_kwargs)
316
 
317
- init_image = dict["image"].convert("RGB").resize((1024, 1024))
318
- mask = dict["mask"].convert("RGB").resize((1024, 1024))
319
 
320
- output = pipe(prompt = prompt, negative_prompt=negative_prompt, image=init_image, mask_image=mask, guidance_scale=guidance_scale, num_inference_steps=int(steps), strength=strength)
321
 
322
- return output.images[0], gr.update(visible=True)
323
-
324
-
325
- css = '''
326
- .gradio-container{max-width: 1100px !important}
327
- #image_upload{min-height:400px}
328
- #image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px}
329
- #mask_radio .gr-form{background:transparent; border: none}
330
- #word_mask{margin-top: .75em !important}
331
- #word_mask textarea:disabled{opacity: 0.3}
332
- .footer {margin-bottom: 45px;margin-top: 35px;text-align: center;border-bottom: 1px solid #e5e5e5}
333
- .footer>p {font-size: .8rem; display: inline-block; padding: 0 10px;transform: translateY(10px);background: white}
334
- .dark .footer {border-color: #303030}
335
- .dark .footer>p {background: #0b0f19}
336
- .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
337
- #image_upload .touch-none{display: flex}
338
- @keyframes spin {
339
- from {
340
- transform: rotate(0deg);
341
- }
342
- to {
343
- transform: rotate(360deg);
344
- }
345
- }
346
- #share-btn-container {padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; max-width: 13rem; margin-left: auto;}
347
- div#share-btn-container > div {flex-direction: row;background: black;align-items: center}
348
- #share-btn-container:hover {background-color: #060606}
349
- #share-btn {all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.5rem !important; padding-bottom: 0.5rem !important;right:0;}
350
- #share-btn * {all: unset}
351
- #share-btn-container div:nth-child(-n+2){width: auto !important;min-height: 0px !important;}
352
- #share-btn-container .wrap {display: none !important}
353
- #share-btn-container.hidden {display: none!important}
354
- #prompt input{width: calc(100% - 160px);border-top-right-radius: 0px;border-bottom-right-radius: 0px;}
355
- #run_button{position:absolute;margin-top: 11px;right: 0;margin-right: 0.8em;border-bottom-left-radius: 0px;
356
- border-top-left-radius: 0px;}
357
- #prompt-container{margin-top:-18px;}
358
- #prompt-container .form{border-top-left-radius: 0;border-top-right-radius: 0}
359
- #image_upload{border-bottom-left-radius: 0px;border-bottom-right-radius: 0px}
360
- '''
361
-
362
- image_blocks = gr.Blocks(css=css, elem_id="total-container")
363
- with image_blocks as demo:
364
- gr.HTML(read_content("header.html"))
365
- with gr.Row():
366
- with gr.Column():
367
- image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil", label="Upload",height=400)
368
- with gr.Row(elem_id="prompt-container", mobile_collapse=False, equal_height=True):
369
- with gr.Row():
370
- prompt = gr.Textbox(placeholder="Your prompt (what you want in place of what is erased)", show_label=False, elem_id="prompt")
371
- btn = gr.Button("Inpaint!", elem_id="run_button")
372
-
373
- with gr.Accordion(label="Advanced Settings", open=False):
374
- with gr.Row(mobile_collapse=False, equal_height=True):
375
- guidance_scale = gr.Number(value=7.5, minimum=1.0, maximum=20.0, step=0.1, label="guidance_scale")
376
- steps = gr.Number(value=20, minimum=10, maximum=30, step=1, label="steps")
377
- strength = gr.Number(value=0.99, minimum=0.01, maximum=0.99, step=0.01, label="strength")
378
- negative_prompt = gr.Textbox(label="negative_prompt", placeholder="Your negative prompt", info="what you don't want to see in the image")
379
- with gr.Row(mobile_collapse=False, equal_height=True):
380
- schedulers = ["DEISMultistepScheduler", "HeunDiscreteScheduler", "EulerDiscreteScheduler", "DPMSolverMultistepScheduler", "DPMSolverMultistepScheduler-Karras", "DPMSolverMultistepScheduler-Karras-SDE"]
381
- scheduler = gr.Dropdown(label="Schedulers", choices=schedulers, value="EulerDiscreteScheduler")
382
-
383
- with gr.Column():
384
- image_out = gr.Image(label="Output", elem_id="output-img", height=400)
385
- with gr.Group(elem_id="share-btn-container", visible=False) as share_btn_container:
386
- community_icon = gr.HTML(community_icon_html)
387
- loading_icon = gr.HTML(loading_icon_html)
388
- share_button = gr.Button("Share to community", elem_id="share-btn",visible=True)
389
-
390
-
391
- btn.click(fn=predict, inputs=[image, prompt, negative_prompt, guidance_scale, steps, strength, scheduler], outputs=[image_out, share_btn_container], api_name='run')
392
- prompt.submit(fn=predict, inputs=[image, prompt, negative_prompt, guidance_scale, steps, strength, scheduler], outputs=[image_out, share_btn_container])
393
- share_button.click(None, [], [], _js=share_js)
394
-
395
- gr.Examples(
396
- examples=[
397
- ["./imgs/aaa (8).png"],
398
- ["./imgs/download (1).jpeg"],
399
- ["./imgs/0_oE0mLhfhtS_3Nfm2.png"],
400
- ["./imgs/02_HubertyBlog-1-1024x1024.jpg"],
401
- ["./imgs/jdn_jacques_de_nuce-1024x1024.jpg"],
402
- ["./imgs/c4ca473acde04280d44128ad8ee09e8a.jpg"],
403
- ["./imgs/canam-electric-motorcycles-scaled.jpg"],
404
- ["./imgs/e8717ce80b394d1b9a610d04a1decd3a.jpeg"],
405
- ["./imgs/Nature___Mountains_Big_Mountain_018453_31.jpg"],
406
- ["./imgs/Multible-sharing-room_ccexpress-2-1024x1024.jpeg"],
407
- ],
408
- fn=predict,
409
- inputs=[image],
410
- cache_examples=False,
411
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  gr.HTML(
413
  """
414
- <div class="footer">
415
- <p>Model by <a href="https://huggingface.co/diffusers" style="text-decoration: underline;" target="_blank">Diffusers</a> - Gradio Demo by 🤗 Hugging Face
416
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  </div>
418
  """
419
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
- image_blocks.queue(max_size=25).launch()
 
1
  import gradio as gr
2
+ from datasets import load_dataset
3
+ from PIL import Image
4
 
5
+ import re
6
+ import os
7
+ import requests
 
8
 
 
9
  from share_btn import community_icon_html, loading_icon_html, share_js
10
 
11
+ word_list_dataset = load_dataset("stabilityai/word-list", data_files="list.txt", use_auth_token=True)
12
+ word_list = word_list_dataset["train"]['text']
13
+
14
+ is_gpu_busy = False
15
+ def infer(prompt, negative, scale):
16
+ global is_gpu_busy
17
+ for filter in word_list:
18
+ if re.search(rf"\b{filter}\b", prompt):
19
+ raise gr.Error("Unsafe content found. Please try again with different prompts.")
20
+
21
+ images = []
22
+ url = os.getenv('JAX_BACKEND_URL')
23
+ payload = {'prompt': prompt, 'negative_prompt': negative, 'guidance_scale': scale}
24
+ images_request = requests.post(url, json = payload)
25
+ for image in images_request.json()["images"]:
26
+ image_b64 = (f"data:image/jpeg;base64,{image}")
27
+ images.append(image_b64)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
+ return images
 
30
 
 
31
 
32
+ css = """
33
+ .gradio-container {
34
+ font-family: 'IBM Plex Sans', sans-serif;
35
+ }
36
+ .gr-button {
37
+ color: white;
38
+ border-color: black;
39
+ background: black;
40
+ }
41
+ input[type='range'] {
42
+ accent-color: black;
43
+ }
44
+ .dark input[type='range'] {
45
+ accent-color: #dfdfdf;
46
+ }
47
+ .container {
48
+ max-width: 730px;
49
+ margin: auto;
50
+ padding-top: 1.5rem;
51
+ }
52
+ #gallery {
53
+ min-height: 22rem;
54
+ margin-bottom: 15px;
55
+ margin-left: auto;
56
+ margin-right: auto;
57
+ border-bottom-right-radius: .5rem !important;
58
+ border-bottom-left-radius: .5rem !important;
59
+ }
60
+ #gallery>div>.h-full {
61
+ min-height: 20rem;
62
+ }
63
+ .details:hover {
64
+ text-decoration: underline;
65
+ }
66
+ .gr-button {
67
+ white-space: nowrap;
68
+ }
69
+ .gr-button:focus {
70
+ border-color: rgb(147 197 253 / var(--tw-border-opacity));
71
+ outline: none;
72
+ box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
73
+ --tw-border-opacity: 1;
74
+ --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
75
+ --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
76
+ --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
77
+ --tw-ring-opacity: .5;
78
+ }
79
+ #advanced-btn {
80
+ font-size: .7rem !important;
81
+ line-height: 19px;
82
+ margin-top: 12px;
83
+ margin-bottom: 12px;
84
+ padding: 2px 8px;
85
+ border-radius: 14px !important;
86
+ }
87
+ #advanced-options {
88
+ display: none;
89
+ margin-bottom: 20px;
90
+ }
91
+ .footer {
92
+ margin-bottom: 45px;
93
+ margin-top: 35px;
94
+ text-align: center;
95
+ border-bottom: 1px solid #e5e5e5;
96
+ }
97
+ .footer>p {
98
+ font-size: .8rem;
99
+ display: inline-block;
100
+ padding: 0 10px;
101
+ transform: translateY(10px);
102
+ background: white;
103
+ }
104
+ .dark .footer {
105
+ border-color: #303030;
106
+ }
107
+ .dark .footer>p {
108
+ background: #0b0f19;
109
+ }
110
+ .acknowledgments h4{
111
+ margin: 1.25em 0 .25em 0;
112
+ font-weight: bold;
113
+ font-size: 115%;
114
+ }
115
+ .animate-spin {
116
+ animation: spin 1s linear infinite;
117
+ }
118
+ @keyframes spin {
119
+ from {
120
+ transform: rotate(0deg);
121
+ }
122
+ to {
123
+ transform: rotate(360deg);
124
+ }
125
+ }
126
+ #share-btn-container {
127
+ 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;
128
+ margin-top: 10px;
129
+ margin-left: auto;
130
+ }
131
+ #share-btn {
132
+ 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;
133
+ }
134
+ #share-btn * {
135
+ all: unset;
136
+ }
137
+ #share-btn-container div:nth-child(-n+2){
138
+ width: auto !important;
139
+ min-height: 0px !important;
140
+ }
141
+ #share-btn-container .wrap {
142
+ display: none !important;
143
+ }
144
+
145
+ .gr-form{
146
+ flex: 1 1 50%; border-top-right-radius: 0; border-bottom-right-radius: 0;
147
+ }
148
+ #prompt-container{
149
+ gap: 0;
150
+ }
151
+ #prompt-text-input, #negative-prompt-text-input{padding: .45rem 0.625rem}
152
+ #component-16{border-top-width: 1px!important;margin-top: 1em}
153
+ .image_duplication{position: absolute; width: 100px; left: 50px}
154
+ """
155
+
156
+ block = gr.Blocks(css=css)
157
+
158
+ examples = [
159
+ [
160
+ 'A high tech solarpunk utopia in the Amazon rainforest',
161
+ 'low quality',
162
+ 9
163
+ ],
164
+ [
165
+ 'A pikachu fine dining with a view to the Eiffel Tower',
166
+ 'low quality',
167
+ 9
168
+ ],
169
+ [
170
+ 'A mecha robot in a favela in expressionist style',
171
+ 'low quality, 3d, photorealistic',
172
+ 9
173
+ ],
174
+ [
175
+ 'an insect robot preparing a delicious meal',
176
+ 'low quality, illustration',
177
+ 9
178
+ ],
179
+ [
180
+ "A small cabin on top of a snowy mountain in the style of Disney, artstation",
181
+ 'low quality, ugly',
182
+ 9
183
+ ],
184
+ ]
185
+
186
+
187
+ with block:
188
  gr.HTML(
189
  """
190
+ <div style="text-align: center; margin: 0 auto;">
191
+ <div
192
+ style="
193
+ display: inline-flex;
194
+ align-items: center;
195
+ gap: 0.8rem;
196
+ font-size: 1.75rem;
197
+ "
198
+ >
199
+ <svg
200
+ width="0.65em"
201
+ height="0.65em"
202
+ viewBox="0 0 115 115"
203
+ fill="none"
204
+ xmlns="http://www.w3.org/2000/svg"
205
+ >
206
+ <rect width="23" height="23" fill="white"></rect>
207
+ <rect y="69" width="23" height="23" fill="white"></rect>
208
+ <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
209
+ <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
210
+ <rect x="46" width="23" height="23" fill="white"></rect>
211
+ <rect x="46" y="69" width="23" height="23" fill="white"></rect>
212
+ <rect x="69" width="23" height="23" fill="black"></rect>
213
+ <rect x="69" y="69" width="23" height="23" fill="black"></rect>
214
+ <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
215
+ <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
216
+ <rect x="115" y="46" width="23" height="23" fill="white"></rect>
217
+ <rect x="115" y="115" width="23" height="23" fill="white"></rect>
218
+ <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
219
+ <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
220
+ <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
221
+ <rect x="92" y="69" width="23" height="23" fill="white"></rect>
222
+ <rect x="69" y="46" width="23" height="23" fill="white"></rect>
223
+ <rect x="69" y="115" width="23" height="23" fill="white"></rect>
224
+ <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
225
+ <rect x="46" y="46" width="23" height="23" fill="black"></rect>
226
+ <rect x="46" y="115" width="23" height="23" fill="black"></rect>
227
+ <rect x="46" y="69" width="23" height="23" fill="black"></rect>
228
+ <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
229
+ <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
230
+ <rect x="23" y="69" width="23" height="23" fill="black"></rect>
231
+ </svg>
232
+ <h1 style="font-weight: 900; margin-bottom: 7px;margin-top:5px">
233
+ Stable Diffusion 2.1 Demo
234
+ </h1>
235
+ </div>
236
+ <p style="margin-bottom: 10px; font-size: 94%; line-height: 23px;">
237
+ Stable Diffusion 2.1 is the latest text-to-image model from StabilityAI. <a style="text-decoration: underline;" href="https://huggingface.co/spaces/stabilityai/stable-diffusion-1">Access Stable Diffusion 1 Space here</a><br>For faster generation and API
238
+ access you can try
239
+ <a
240
+ href="http://beta.dreamstudio.ai/"
241
+ style="text-decoration: underline;"
242
+ target="_blank"
243
+ >DreamStudio Beta</a
244
+ >.</a>
245
+ </p>
246
  </div>
247
  """
248
  )
249
+ with gr.Group():
250
+ with gr.Box():
251
+ with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
252
+ with gr.Column():
253
+ text = gr.Textbox(
254
+ label="Enter your prompt",
255
+ show_label=False,
256
+ max_lines=1,
257
+ placeholder="Enter your prompt",
258
+ elem_id="prompt-text-input",
259
+ ).style(
260
+ border=(True, False, True, True),
261
+ rounded=(True, False, False, True),
262
+ container=False,
263
+ )
264
+ negative = gr.Textbox(
265
+ label="Enter your negative prompt",
266
+ show_label=False,
267
+ max_lines=1,
268
+ placeholder="Enter a negative prompt",
269
+ elem_id="negative-prompt-text-input",
270
+ ).style(
271
+ border=(True, False, True, True),
272
+ rounded=(True, False, False, True),
273
+ container=False,
274
+ )
275
+ btn = gr.Button("Generate image").style(
276
+ margin=False,
277
+ rounded=(False, True, True, False),
278
+ full_width=False,
279
+ )
280
+
281
+ gallery = gr.Gallery(
282
+ label="Generated images", show_label=False, elem_id="gallery"
283
+ ).style(grid=[2], height="auto")
284
+
285
+ with gr.Group(elem_id="container-advanced-btns"):
286
+ #advanced_button = gr.Button("Advanced options", elem_id="advanced-btn")
287
+ with gr.Group(elem_id="share-btn-container"):
288
+ community_icon = gr.HTML(community_icon_html)
289
+ loading_icon = gr.HTML(loading_icon_html)
290
+ share_button = gr.Button("Share to community", elem_id="share-btn")
291
+
292
+ with gr.Accordion("Advanced settings", open=False):
293
+ # gr.Markdown("Advanced settings are temporarily unavailable")
294
+ # samples = gr.Slider(label="Images", minimum=1, maximum=4, value=4, step=1)
295
+ # steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=45, step=1)
296
+ guidance_scale = gr.Slider(
297
+ label="Guidance Scale", minimum=0, maximum=50, value=9, step=0.1
298
+ )
299
+ # seed = gr.Slider(
300
+ # label="Seed",
301
+ # minimum=0,
302
+ # maximum=2147483647,
303
+ # step=1,
304
+ # randomize=True,
305
+ # )
306
+
307
+ ex = gr.Examples(examples=examples, fn=infer, inputs=[text, negative, guidance_scale], outputs=[gallery, community_icon, loading_icon, share_button], cache_examples=False)
308
+ ex.dataset.headers = [""]
309
+ negative.submit(infer, inputs=[text, negative, guidance_scale], outputs=[gallery], postprocess=False)
310
+ text.submit(infer, inputs=[text, negative, guidance_scale], outputs=[gallery], postprocess=False)
311
+ btn.click(infer, inputs=[text, negative, guidance_scale], outputs=[gallery], postprocess=False)
312
+
313
+ #advanced_button.click(
314
+ # None,
315
+ # [],
316
+ # text,
317
+ # _js="""
318
+ # () => {
319
+ # const options = document.querySelector("body > gradio-app").querySelector("#advanced-options");
320
+ # options.style.display = ["none", ""].includes(options.style.display) ? "flex" : "none";
321
+ # }""",
322
+ #)
323
+ share_button.click(
324
+ None,
325
+ [],
326
+ [],
327
+ _js=share_js,
328
+ )
329
+ gr.HTML(
330
+ """
331
+ <div class="footer">
332
+ <p>Model by <a href="https://huggingface.co/stabilityai" style="text-decoration: underline;" target="_blank">StabilityAI</a> - backend running JAX on TPUs due to generous support of <a href="https://sites.research.google/trc/about/" style="text-decoration: underline;" target="_blank">Google TRC program</a> - Gradio Demo by 🤗 Hugging Face
333
+ </p>
334
+ </div>
335
+ """
336
+ )
337
+ with gr.Accordion(label="License", open=False):
338
+ gr.HTML(
339
+ """<div class="acknowledgments">
340
+ <p><h4>LICENSE</h4>
341
+ 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>
342
+ <p><h4>Biases and content acknowledgment</h4>
343
+ 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>
344
+ </div>
345
+ """
346
+ )
347
+
348
 
349
+ block.queue(concurrency_count=80, max_size=100).launch(max_threads=150)