apolinario commited on
Commit
bdc1819
1 Parent(s): 8dbf1d5

First commit

Browse files
Files changed (5) hide show
  1. app.py +195 -0
  2. init_image.png +0 -0
  3. inpainting.py +194 -0
  4. mask_image.png +0 -0
  5. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from io import BytesIO
4
+ import requests
5
+ import PIL
6
+ from PIL import Image
7
+ import numpy as np
8
+ import os
9
+ import uuid
10
+ import torch
11
+ from torch import autocast
12
+ import cv2
13
+ from matplotlib import pyplot as plt
14
+ from inpainting import StableDiffusionInpaintingPipeline
15
+ from torchvision import transforms
16
+ from clipseg.models.clipseg import CLIPDensePredT
17
+
18
+ auth_token = os.environ.get("API_TOKEN") or True
19
+
20
+ def download_image(url):
21
+ response = requests.get(url)
22
+ return PIL.Image.open(BytesIO(response.content)).convert("RGB")
23
+
24
+ img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
25
+ mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
26
+
27
+ device = "cuda" if torch.cuda.is_available() else "cpu"
28
+ pipe = StableDiffusionInpaintingPipeline.from_pretrained(
29
+ "CompVis/stable-diffusion-v1-4",
30
+ revision="fp16",
31
+ torch_dtype=torch.float16,
32
+ use_auth_token=auth_token,
33
+ ).to(device)
34
+
35
+ model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64)
36
+ model.eval()
37
+ model.load_state_dict(torch.load('./clipseg/weights/rd64-uni.pth', map_location=torch.device('cuda')), strict=False)
38
+
39
+ transform = transforms.Compose([
40
+ transforms.ToTensor(),
41
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
42
+ transforms.Resize((512, 512)),
43
+ ])
44
+
45
+ def predict(radio, dict, word_mask, prompt=""):
46
+ if(radio == "draw a mask above"):
47
+ with autocast("cuda"):
48
+ init_image = dict["image"].convert("RGB").resize((512, 512))
49
+ mask = dict["mask"].convert("RGB").resize((512, 512))
50
+ else:
51
+ img = transform(dict["image"]).unsqueeze(0)
52
+ word_masks = [word_mask]
53
+ with torch.no_grad():
54
+ preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0]
55
+ init_image = dict['image'].convert('RGB').resize((512, 512))
56
+ filename = f"{uuid.uuid4()}.png"
57
+ plt.imsave(filename,torch.sigmoid(preds[0][0]))
58
+ img2 = cv2.imread(filename)
59
+ gray_image = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
60
+ (thresh, bw_image) = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
61
+ cv2.cvtColor(bw_image, cv2.COLOR_BGR2RGB)
62
+ mask = Image.fromarray(np.uint8(bw_image)).convert('RGB')
63
+ os.remove(filename)
64
+ with autocast("cuda"):
65
+ images = pipe(prompt = prompt, init_image=init_image, mask_image=mask, strength=0.8)["sample"]
66
+ return images[0]
67
+
68
+ # examples = [[dict(image="init_image.png", mask="mask_image.png"), "A panda sitting on a bench"]]
69
+ css = '''
70
+ #image_upload{min-height:400px}
71
+ #image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px}
72
+ #mask_radio .gr-form{background:transparent; border: none}
73
+ #word_mask{margin-top: .75em !important}
74
+ #word_mask textarea:disabled{opacity: 0.3}
75
+ .footer {
76
+ margin-bottom: 45px;
77
+ margin-top: 35px;
78
+ text-align: center;
79
+ border-bottom: 1px solid #e5e5e5;
80
+ }
81
+ .footer>p {
82
+ font-size: .8rem;
83
+ display: inline-block;
84
+ padding: 0 10px;
85
+ transform: translateY(10px);
86
+ background: white;
87
+ }
88
+ .dark .footer {
89
+ border-color: #303030;
90
+ }
91
+ .dark .footer>p {
92
+ background: #0b0f19;
93
+ }
94
+ .acknowledgments h4{
95
+ margin: 1.25em 0 .25em 0;
96
+ font-weight: bold;
97
+ font-size: 115%;
98
+ }
99
+ #image_upload .touch-none{display: flex}
100
+ '''
101
+ def swap_word_mask(radio_option):
102
+ if(radio_option == "type what to mask below"):
103
+ return gr.update(interactive=True, placeholder="A cat")
104
+ else:
105
+ return gr.update(interactive=False, placeholder="Disabled")
106
+
107
+ image_blocks = gr.Blocks(css=css)
108
+ with image_blocks as demo:
109
+ gr.HTML(
110
+ """
111
+ <div style="text-align: center; max-width: 650px; margin: 0 auto;">
112
+ <div
113
+ style="
114
+ display: inline-flex;
115
+ align-items: center;
116
+ gap: 0.8rem;
117
+ font-size: 1.75rem;
118
+ "
119
+ >
120
+ <svg
121
+ width="0.65em"
122
+ height="0.65em"
123
+ viewBox="0 0 115 115"
124
+ fill="none"
125
+ xmlns="http://www.w3.org/2000/svg"
126
+ >
127
+ <rect width="23" height="23" fill="white"></rect>
128
+ <rect y="69" width="23" height="23" fill="white"></rect>
129
+ <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
130
+ <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
131
+ <rect x="46" width="23" height="23" fill="white"></rect>
132
+ <rect x="46" y="69" width="23" height="23" fill="white"></rect>
133
+ <rect x="69" width="23" height="23" fill="black"></rect>
134
+ <rect x="69" y="69" width="23" height="23" fill="black"></rect>
135
+ <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
136
+ <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
137
+ <rect x="115" y="46" width="23" height="23" fill="white"></rect>
138
+ <rect x="115" y="115" width="23" height="23" fill="white"></rect>
139
+ <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
140
+ <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
141
+ <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
142
+ <rect x="92" y="69" width="23" height="23" fill="white"></rect>
143
+ <rect x="69" y="46" width="23" height="23" fill="white"></rect>
144
+ <rect x="69" y="115" width="23" height="23" fill="white"></rect>
145
+ <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
146
+ <rect x="46" y="46" width="23" height="23" fill="black"></rect>
147
+ <rect x="46" y="115" width="23" height="23" fill="black"></rect>
148
+ <rect x="46" y="69" width="23" height="23" fill="black"></rect>
149
+ <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
150
+ <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
151
+ <rect x="23" y="69" width="23" height="23" fill="black"></rect>
152
+ </svg>
153
+ <h1 style="font-weight: 900; margin-bottom: 7px;">
154
+ Stable Diffusion Inpainting
155
+ </h1>
156
+ </div>
157
+ <p style="margin-bottom: 10px; font-size: 94%">
158
+ Inpaint Stable Diffusion by either drawing a mask or typing what to replace
159
+ </p>
160
+ </div>
161
+ """
162
+ )
163
+ with gr.Row():
164
+ with gr.Column():
165
+ image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil").style(height=400)
166
+ with gr.Box(elem_id="mask_radio").style(border=False):
167
+ radio = gr.Radio(["draw a mask above", "type what to mask below"], value="draw a mask above", show_label=False, interactive=True).style(container=False)
168
+ word_mask = gr.Textbox(label = "What to find in your image", interactive=False, elem_id="word_mask", placeholder="Disabled").style(container=False)
169
+ prompt = gr.Textbox(label = 'Your prompt (what you want to add in place of what you are removing)')
170
+ radio.change(fn=swap_word_mask, inputs=radio, outputs=word_mask)
171
+ radio.change(None, inputs=[], outputs=image_blocks, _js = """
172
+ () => {
173
+ css_style = document.querySelector('gradio-app').shadowRoot.styleSheets[1]
174
+ last_item = css_style.cssRules[css_style.cssRules.length - 1]
175
+ last_item.style.display = ["flex", ""].includes(last_item.style.display) ? "none" : "flex";
176
+ }""")
177
+ btn = gr.Button("Run")
178
+ with gr.Column():
179
+ result = gr.Image()
180
+ btn.click(fn=predict, inputs=[radio, image, word_mask, prompt], outputs=result)
181
+ gr.HTML(
182
+ """
183
+ <div class="footer">
184
+ <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> - Inpainting by nagolinc and patil-suraj, inpainting with words by @yvrjsharma and @1littlecoder - Gradio Demo by 🤗 Hugging Face
185
+ </p>
186
+ </div>
187
+ <div class="acknowledgments">
188
+ <p><h4>LICENSE</h4>
189
+ 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>
190
+ <p><h4>Biases and content acknowledgment</h4>
191
+ 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>
192
+ </div>
193
+ """
194
+ )
195
+ demo.launch()
init_image.png ADDED
inpainting.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+
7
+ import PIL
8
+ from diffusers import AutoencoderKL, DDIMScheduler, DiffusionPipeline, PNDMScheduler, UNet2DConditionModel
9
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
10
+ from tqdm.auto import tqdm
11
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
12
+
13
+
14
+ def preprocess_image(image):
15
+ w, h = image.size
16
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
17
+ image = image.resize((w, h), resample=PIL.Image.LANCZOS)
18
+ image = np.array(image).astype(np.float32) / 255.0
19
+ image = image[None].transpose(0, 3, 1, 2)
20
+ image = torch.from_numpy(image)
21
+ return 2.0 * image - 1.0
22
+
23
+
24
+ def preprocess_mask(mask):
25
+ mask = mask.convert("L")
26
+ w, h = mask.size
27
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
28
+ mask = mask.resize((w // 8, h // 8), resample=PIL.Image.NEAREST)
29
+ mask = np.array(mask).astype(np.float32) / 255.0
30
+ mask = np.tile(mask, (4, 1, 1))
31
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
32
+ mask = 1 - mask # repaint white, keep black
33
+ mask = torch.from_numpy(mask)
34
+ return mask
35
+
36
+ class StableDiffusionInpaintingPipeline(DiffusionPipeline):
37
+ def __init__(
38
+ self,
39
+ vae: AutoencoderKL,
40
+ text_encoder: CLIPTextModel,
41
+ tokenizer: CLIPTokenizer,
42
+ unet: UNet2DConditionModel,
43
+ scheduler: Union[DDIMScheduler, PNDMScheduler],
44
+ safety_checker: StableDiffusionSafetyChecker,
45
+ feature_extractor: CLIPFeatureExtractor,
46
+ ):
47
+ super().__init__()
48
+ scheduler = scheduler.set_format("pt")
49
+ self.register_modules(
50
+ vae=vae,
51
+ text_encoder=text_encoder,
52
+ tokenizer=tokenizer,
53
+ unet=unet,
54
+ scheduler=scheduler,
55
+ safety_checker=safety_checker,
56
+ feature_extractor=feature_extractor,
57
+ )
58
+
59
+ @torch.no_grad()
60
+ def __call__(
61
+ self,
62
+ prompt: Union[str, List[str]],
63
+ init_image: torch.FloatTensor,
64
+ mask_image: torch.FloatTensor,
65
+ strength: float = 0.8,
66
+ num_inference_steps: Optional[int] = 50,
67
+ guidance_scale: Optional[float] = 7.5,
68
+ eta: Optional[float] = 0.0,
69
+ generator: Optional[torch.Generator] = None,
70
+ output_type: Optional[str] = "pil",
71
+ ):
72
+
73
+ if isinstance(prompt, str):
74
+ batch_size = 1
75
+ elif isinstance(prompt, list):
76
+ batch_size = len(prompt)
77
+ else:
78
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
79
+
80
+ if strength < 0 or strength > 1:
81
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
82
+
83
+ # set timesteps
84
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
85
+ extra_set_kwargs = {}
86
+ offset = 0
87
+ if accepts_offset:
88
+ offset = 1
89
+ extra_set_kwargs["offset"] = 1
90
+
91
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
92
+
93
+ # preprocess image
94
+ init_image = preprocess_image(init_image).to(self.device)
95
+
96
+ # encode the init image into latents and scale the latents
97
+ init_latent_dist = self.vae.encode(init_image).latent_dist
98
+ init_latents = init_latent_dist.sample(generator=generator)
99
+ init_latents = 0.18215 * init_latents
100
+
101
+ # prepare init_latents noise to latents
102
+ init_latents = torch.cat([init_latents] * batch_size)
103
+ init_latents_orig = init_latents
104
+
105
+ # preprocess mask
106
+ mask = preprocess_mask(mask_image).to(self.device)
107
+ mask = torch.cat([mask] * batch_size)
108
+
109
+ # check sizes
110
+ if not mask.shape == init_latents.shape:
111
+ raise ValueError(f"The mask and init_image should be the same size!")
112
+
113
+ # get the original timestep using init_timestep
114
+ init_timestep = int(num_inference_steps * strength) + offset
115
+ init_timestep = min(init_timestep, num_inference_steps)
116
+ timesteps = self.scheduler.timesteps[-init_timestep]
117
+ timesteps = torch.tensor([timesteps] * batch_size, dtype=torch.long, device=self.device)
118
+
119
+ # add noise to latents using the timesteps
120
+ noise = torch.randn(init_latents.shape, generator=generator, device=self.device)
121
+ init_latents = self.scheduler.add_noise(init_latents, noise, timesteps)
122
+
123
+ # get prompt text embeddings
124
+ text_input = self.tokenizer(
125
+ prompt,
126
+ padding="max_length",
127
+ max_length=self.tokenizer.model_max_length,
128
+ truncation=True,
129
+ return_tensors="pt",
130
+ )
131
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
132
+
133
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
134
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
135
+ # corresponds to doing no classifier free guidance.
136
+ do_classifier_free_guidance = guidance_scale > 1.0
137
+ # get unconditional embeddings for classifier free guidance
138
+ if do_classifier_free_guidance:
139
+ max_length = text_input.input_ids.shape[-1]
140
+ uncond_input = self.tokenizer(
141
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
142
+ )
143
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
144
+
145
+ # For classifier free guidance, we need to do two forward passes.
146
+ # Here we concatenate the unconditional and text embeddings into a single batch
147
+ # to avoid doing two forward passes
148
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
149
+
150
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
151
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
152
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
153
+ # and should be between [0, 1]
154
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
155
+ extra_step_kwargs = {}
156
+ if accepts_eta:
157
+ extra_step_kwargs["eta"] = eta
158
+
159
+ latents = init_latents
160
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
161
+ for i, t in tqdm(enumerate(self.scheduler.timesteps[t_start:])):
162
+ # expand the latents if we are doing classifier free guidance
163
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
164
+
165
+ # predict the noise residual
166
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
167
+
168
+ # perform guidance
169
+ if do_classifier_free_guidance:
170
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
171
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
172
+
173
+ # compute the previous noisy sample x_t -> x_t-1
174
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs)["prev_sample"]
175
+
176
+ # masking
177
+ init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, t)
178
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
179
+
180
+ # scale and decode the image latents with vae
181
+ latents = 1 / 0.18215 * latents
182
+ image = self.vae.decode(latents).sample
183
+
184
+ image = (image / 2 + 0.5).clamp(0, 1)
185
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
186
+
187
+ # run safety checker
188
+ safety_cheker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(self.device)
189
+ image, has_nsfw_concept = self.safety_checker(images=image, clip_input=safety_cheker_input.pixel_values)
190
+
191
+ if output_type == "pil":
192
+ image = self.numpy_to_pil(image)
193
+
194
+ return {"sample": image, "nsfw_content_detected": has_nsfw_concept}
mask_image.png ADDED
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ diffusers
4
+ transformers
5
+ ftfy
6
+ numpy
7
+ matplotlib
8
+ uuid
9
+ opencv-python