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