nightfury commited on
Commit
6c4be6b
1 Parent(s): daebf44

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -199
app.py CHANGED
@@ -15,142 +15,52 @@ from inpainting import StableDiffusionInpaintingPipeline
15
  from torchvision import transforms
16
  from clipseg.models.clipseg import CLIPDensePredT
17
 
18
- Image.LOAD_TRUNCATED_IMAGES = True
19
-
20
  auth_token = os.environ.get("API_TOKEN") or True
21
 
22
  def download_image(url):
23
  response = requests.get(url)
24
  return PIL.Image.open(BytesIO(response.content)).convert("RGB")
25
 
26
- #device = "cpu" #"cuda" if torch.cuda.is_available() else "cpu"
27
-
28
- device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
29
- print("The model will be running on :: ", device, " ~device")
30
- # Convert model parameters and buffers to CPU or Cuda
31
-
32
- model_id_or_path = "CompVis/stable-diffusion-v1-4"
33
  pipe = StableDiffusionInpaintingPipeline.from_pretrained(
34
- model_id_or_path,
35
- #revision="fp16",
36
  torch_dtype=torch.float16,
37
- use_auth_token=auth_token
38
  ).to(device)
39
 
40
- #pipe = pipe.to(device)
41
- #self.register_buffer('n_', ...)
42
- #print ("torch.backends.mps.is_available: ", torch.backends.mps.is_available())
43
-
44
- model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, complex_trans_conv=True)
45
-
46
- model = model.to(torch.device(device))
47
- model.eval().float()
48
- #model = model.type(torch.HalfTensor)
49
-
50
- weightsPATH = './clipseg/weights/rd64-uni.pth'
51
-
52
- #state = {'model': model.state_dict()}
53
- #torch.save(state, weightsPATH)
54
-
55
- model.load_state_dict(torch.load(weightsPATH, map_location=torch.device(device)), strict=False) #False
56
- #model.load_state_dict(torch.load(weightsPATH)['model'])
57
-
58
- print ("Torch load(model) : ", model)
59
- print ("Weights : ")
60
- # print weights
61
- for k, v in model.named_parameters():
62
- print(k, v)
63
-
64
- imgRes = 256
65
 
66
  transform = transforms.Compose([
67
  transforms.ToTensor(),
68
  transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
69
- transforms.Resize((imgRes, imgRes)),
70
  ])
71
 
72
  def predict(radio, dict, word_mask, prompt=""):
73
  if(radio == "draw a mask above"):
74
- #with autocast(device): #"cuda"
75
- with autocast(enable=(False if device=='cpu' else True)):
76
- init_image = dict["image"].convert("RGB").resize((imgRes, imgRes))
77
- mask = dict["mask"].convert("RGB").resize((imgRes, imgRes))
78
- elif(radio == "type what to keep"):
79
- img = transform(dict["image"]).squeeze(0)
80
-
81
- #-----New Lines-----
82
- if torch.cuda.is_available():
83
- img.cuda()
84
- print ("yes, CUDA is available here !! ")
85
-
86
- #------------------
87
-
88
- word_masks = [word_mask]
89
- with torch.no_grad():
90
- #torch.cuda.amp.autocast(): #
91
- preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0]
92
-
93
- #model = model.to(torch.device(device))
94
- img = img.to(torch.device(device))
95
- #prompt = prompt.to(torch.device(device))
96
- #---------
97
-
98
- init_image = dict['image'].convert('RGB').resize((imgRes, imgRes))
99
- filename = f"{uuid.uuid4()}.png"
100
- plt.imsave(filename,torch.sigmoid(preds[0][0]))
101
-
102
- img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
103
- img = Image.fromarray(img)
104
-
105
- #img2 = cv2.imread(filename)
106
-
107
- #if ret == True:
108
- gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
109
-
110
- (thresh, bw_image) = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
111
- cv2.cvtColor(bw_image, cv2.COLOR_BGR2RGB)
112
- mask = Image.fromarray(np.uint8(bw_image)).convert('RGB')
113
- os.remove(filename)
114
  else:
115
  img = transform(dict["image"]).unsqueeze(0)
116
-
117
- #-----New Lines-----
118
- if torch.cuda.is_available():
119
- img.cuda()
120
- print ("yes, CUDA is available here !! ")
121
-
122
- #------------------
123
-
124
  word_masks = [word_mask]
125
- #with torch.cuda.amp.autocast(): #
126
  with torch.no_grad():
127
  preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0]
128
-
129
-
130
- #model = model.to(torch.device(device))
131
- img = img.to(torch.device(device))
132
- #prompt = prompt.to(torch.device(device))
133
-
134
- init_image = dict['image'].convert('RGB').resize((imgRes, imgRes))
135
  filename = f"{uuid.uuid4()}.png"
136
  plt.imsave(filename,torch.sigmoid(preds[0][0]))
137
- #img2 = cv2.imread(filename)
138
-
139
- img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
140
- img = Image.fromarray(img)
141
-
142
- #if ret == True:
143
- gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
144
  (thresh, bw_image) = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
145
  cv2.cvtColor(bw_image, cv2.COLOR_BGR2RGB)
146
  mask = Image.fromarray(np.uint8(bw_image)).convert('RGB')
147
  os.remove(filename)
148
-
149
- #with autocast(device): #"cuda"
150
- with autocast(enable=(False if device=='cpu' else True)):
151
- #with autocast(device_type="cpu", dtype=torch.bfloat16):
152
- images = pipe(prompt = prompt, init_image=init_image, mask_image=mask, strength=0.8)["sample"]
153
- return images[0]
154
 
155
  # examples = [[dict(image="init_image.png", mask="mask_image.png"), "A panda sitting on a bench"]]
156
  css = '''
@@ -166,13 +76,12 @@ css = '''
166
  .dark .footer>p {background: #0b0f19}
167
  .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
168
  #image_upload .touch-none{display: flex}
169
-
170
  '''
171
  def swap_word_mask(radio_option):
172
- if(radio_option == "draw a mask above"):
173
- return gr.update(interactive=False, placeholder="Disabled")
174
- else:
175
  return gr.update(interactive=True, placeholder="A cat")
 
 
176
 
177
  image_blocks = gr.Blocks(css=css)
178
  with image_blocks as demo:
@@ -194,28 +103,28 @@ with image_blocks as demo:
194
  fill="none"
195
  xmlns="http://www.w3.org/2000/svg"
196
  >
197
- <rect width="23" height="23" fill="#AEAEAE"></rect>
198
- <rect y="69" width="23" height="23" fill="black"></rect>
199
  <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
200
  <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
201
- <rect x="46" width="23" height="23" fill="#D9D9D9"></rect>
202
  <rect x="46" y="69" width="23" height="23" fill="white"></rect>
203
  <rect x="69" width="23" height="23" fill="black"></rect>
204
  <rect x="69" y="69" width="23" height="23" fill="black"></rect>
205
  <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
206
  <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
207
- <rect x="115" y="46" width="23" height="23" fill="black"></rect>
208
- <rect x="115" y="115" width="23" height="23" fill="black"></rect>
209
  <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
210
  <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
211
  <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
212
  <rect x="92" y="69" width="23" height="23" fill="white"></rect>
213
- <rect x="69" y="46" width="23" height="23" fill="black"></rect>
214
  <rect x="69" y="115" width="23" height="23" fill="white"></rect>
215
  <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
216
- <rect x="46" y="46" width="23" height="23" fill="white"></rect>
217
  <rect x="46" y="115" width="23" height="23" fill="black"></rect>
218
- <rect x="46" y="69" width="23" height="23" fill="white"></rect>
219
  <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
220
  <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
221
  <rect x="23" y="69" width="23" height="23" fill="black"></rect>
@@ -225,7 +134,7 @@ with image_blocks as demo:
225
  </h1>
226
  </div>
227
  <p style="margin-bottom: 10px; font-size: 94%">
228
- Inpaint Stable Diffusion by either drawing a mask or typing what to replace & what to keep !!!
229
  </p>
230
  </div>
231
  """
@@ -234,11 +143,8 @@ with image_blocks as demo:
234
  with gr.Column():
235
  image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil", label="Upload").style(height=400)
236
  with gr.Box(elem_id="mask_radio").style(border=False):
237
- radio = gr.Radio(["draw a mask above", "type what to mask below", "type what to keep"], value="draw a mask above", show_label=False, interactive=True).style(container=False)
238
  word_mask = gr.Textbox(label = "What to find in your image", interactive=False, elem_id="word_mask", placeholder="Disabled").style(container=False)
239
-
240
- img_res = gr.Dropdown(['512*512', '256*256'], label="Image Resolution")
241
-
242
  prompt = gr.Textbox(label = 'Your prompt (what you want to add in place of what you are removing)')
243
  radio.change(fn=swap_word_mask, inputs=radio, outputs=word_mask,show_progress=False)
244
  radio.change(None, inputs=[], outputs=image_blocks, _js = """
@@ -253,85 +159,16 @@ with image_blocks as demo:
253
  btn.click(fn=predict, inputs=[radio, image, word_mask, prompt], outputs=result)
254
  gr.HTML(
255
  """
256
- <div class="footer">
257
- <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 <a href="https://github.com/" style="text-decoration: underline;" target="_blank">NightFury</a> using clipseg[model] with bit modification - Gradio Demo on 🤗 Hugging Face
258
  </p>
259
  </div>
260
-
261
-
262
- <div class="acknowledgments" >
263
- <h1 dir="auto"><a id="user-content-image-segmentation-using-text-and-image-prompts" aria-hidden="true" href="#image-segmentation-using-text-and-image-prompts"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Image Segmentation Using Text and Image Prompts</h1>
264
- <p dir="auto">This repository contains the code used in the paper <a href="https://arxiv.org/abs/2112.10003" rel="nofollow">"Image Segmentation Using Text and Image Prompts"</a>.</p>
265
-
266
- <p dir="auto"><a target="_blank" rel="noopener noreferrer" href="/ThereforeGames/txt2mask/blob/main/repositories/clipseg/overview.png"><img src="/ThereforeGames/txt2mask/raw/main/repositories/clipseg/overview.png" alt="drawing" style="max-width: 100%;" height="200em"></a></p>
267
- <p dir="auto">The systems allows to create segmentation models without training based on:</p>
268
- <ul dir="auto">
269
- <li>An arbitrary text query</li>
270
- <li>Or an image with a mask highlighting stuff or an object.</li>
271
- </ul>
272
- <h3 dir="auto"><a id="user-content-quick-start" aria-hidden="true" href="#quick-start"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Quick Start</h3>
273
- <p dir="auto">In the <code>Quickstart.ipynb</code> notebook we provide the code for using a pre-trained CLIPSeg model. If you run the notebook locally, make sure you downloaded the <code>rd64-uni.pth</code> weights, either manually or via git lfs extension.
274
- It can also be used interactively using <a href="https://mybinder.org/v2/gh/timojl/clipseg/HEAD?labpath=Quickstart.ipynb" rel="nofollow">MyBinder</a>
275
- (please note that the VM does not use a GPU, thus inference takes a few seconds).</p>
276
- <h3 dir="auto"><a id="user-content-dependencies" aria-hidden="true" href="#dependencies"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Dependencies</h3>
277
- <p dir="auto">This code base depends on pytorch, torchvision and clip (<code>pip install git+https://github.com/openai/CLIP.git</code>).
278
- Additional dependencies are hidden for double blind review.</p>
279
- <h3 dir="auto"><a id="user-content-datasets" aria-hidden="true" href="#datasets"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Datasets</h3>
280
- <ul dir="auto">
281
- <li><code>PhraseCut</code> and <code>PhraseCutPlus</code>: Referring expression dataset</li>
282
- <li><code>PFEPascalWrapper</code>: Wrapper class for PFENet's Pascal-5i implementation</li>
283
- <li><code>PascalZeroShot</code>: Wrapper class for PascalZeroShot</li>
284
- <li><code>COCOWrapper</code>: Wrapper class for COCO.</li>
285
- </ul>
286
- <h3 dir="auto"><a id="user-content-models" aria-hidden="true" href="#models"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Models</h3>
287
- <ul dir="auto">
288
- <li><code>CLIPDensePredT</code>: CLIPSeg model with transformer-based decoder.</li>
289
- <li><code>ViTDensePredT</code>: CLIPSeg model with transformer-based decoder.</li>
290
- </ul>
291
- <h3 dir="auto"><a id="user-content-third-party-dependencies" aria-hidden="true" href="#third-party-dependencies"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Third Party Dependencies</h3>
292
- <p dir="auto">For some of the datasets third party dependencies are required. Run the following commands in the <code>third_party</code> folder.</p>
293
- <div dir="auto"><pre>git clone https://github.com/cvlab-yonsei/JoEm
294
- git clone https://github.com/Jia-Research-Lab/PFENet.git
295
- git clone https://github.com/ChenyunWu/PhraseCutDataset.git
296
- git clone https://github.com/juhongm999/hsnet.git</pre><div >
297
- <clipboard-copy aria-label="Copy" data-copy-feedback="Copied!" data-tooltip-direction="w" value="git clone https://github.com/cvlab-yonsei/JoEm
298
- git clone https://github.com/Jia-Research-Lab/PFENet.git
299
- git clone https://github.com/ChenyunWu/PhraseCutDataset.git
300
- git clone https://github.com/juhongm999/hsnet.git" tabindex="0" role="button">
301
- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2">
302
- <path fill-rule="evenodd" d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 010 1.5h-1.5a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-1.5a.75.75 0 011.5 0v1.5A1.75 1.75 0 019.25 16h-7.5A1.75 1.75 0 010 14.25v-7.5z"></path><path fill-rule="evenodd" d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0114.25 11h-7.5A1.75 1.75 0 015 9.25v-7.5zm1.75-.25a.25.25 0 00-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 00.25-.25v-7.5a.25.25 0 00-.25-.25h-7.5z"></path>
303
- </svg>
304
- <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2">
305
- <path fill-rule="evenodd" d="M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z"></path>
306
- </svg>
307
- </clipboard-copy>
308
- </div></div>
309
-
310
- <h3 dir="auto"><a id="user-content-weights" aria-hidden="true" href="#weights"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Weights</h3>
311
- <p dir="auto">The MIT license does not apply to these weights.</p>
312
- <ul dir="auto">
313
- <li><a href="https://github.com/timojl/clipseg/raw/master/weights/rd64-uni.pth">CLIPSeg-D64</a> (4.1MB, without CLIP weights)</li>
314
- <li><a href="https://github.com/timojl/clipseg/raw/master/weights/rd16-uni.pth">CLIPSeg-D16</a> (1.1MB, without CLIP weights)</li>
315
- </ul>
316
-
317
- <h3 dir="auto"><a id="user-content-training-and-evaluation" aria-hidden="true" href="#training-and-evaluation"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Training and Evaluation</h3>
318
- <p dir="auto">To train use the <code>training.py</code> script with experiment file and experiment id parameters. E.g. <code>python training.py phrasecut.yaml 0</code> will train the first phrasecut experiment which is defined by the <code>configuration</code> and first <code>individual_configurations</code> parameters. Model weights will be written in <code>logs/</code>.</p>
319
- <p dir="auto">For evaluation use <code>score.py</code>. E.g. <code>python score.py phrasecut.yaml 0 0</code> will train the first phrasecut experiment of <code>test_configuration</code> and the first configuration in <code>individual_configurations</code>.</p>
320
-
321
- <h3 dir="auto"><a id="user-content-usage-of-pfenet-wrappers" aria-hidden="true" href="#usage-of-pfenet-wrappers"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>Usage of PFENet Wrappers</h3>
322
- <p dir="auto">In order to use the dataset and model wrappers for PFENet, the PFENet repository needs to be cloned to the root folder.
323
- <code>git clone https://github.com/Jia-Research-Lab/PFENet.git </code></p>
324
-
325
- <h4 dir="auto"><a id="user-content-license" aria-hidden="true" href="#license"><svg class="octicon octicon-link" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z"></path></svg></a>LICENSE</h4>
326
- <p dir="auto">The source code files in this repository (excluding model weights) are released under MIT license.</p>
327
-
328
- <p>
329
  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>
330
  <p><h4>Biases and content acknowledgment</h4>
331
  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>
332
-
333
-
334
- </div>
335
  """
336
  )
337
- demo.launch()
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
+ device = "cuda" if torch.cuda.is_available() else "cpu"
 
 
 
 
 
 
25
  pipe = StableDiffusionInpaintingPipeline.from_pretrained(
26
+ "CompVis/stable-diffusion-v1-4",
27
+ revision="fp16",
28
  torch_dtype=torch.float16,
29
+ use_auth_token=auth_token,
30
  ).to(device)
31
 
32
+ model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64)
33
+ model.eval()
34
+ model.load_state_dict(torch.load('./clipseg/weights/rd64-uni.pth', map_location=torch.device('cuda')), strict=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
  transform = transforms.Compose([
37
  transforms.ToTensor(),
38
  transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
39
+ transforms.Resize((512, 512)),
40
  ])
41
 
42
  def predict(radio, dict, word_mask, prompt=""):
43
  if(radio == "draw a mask above"):
44
+ with autocast("cuda"):
45
+ init_image = dict["image"].convert("RGB").resize((512, 512))
46
+ mask = dict["mask"].convert("RGB").resize((512, 512))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  else:
48
  img = transform(dict["image"]).unsqueeze(0)
 
 
 
 
 
 
 
 
49
  word_masks = [word_mask]
 
50
  with torch.no_grad():
51
  preds = model(img.repeat(len(word_masks),1,1,1), word_masks)[0]
52
+ init_image = dict['image'].convert('RGB').resize((512, 512))
 
 
 
 
 
 
53
  filename = f"{uuid.uuid4()}.png"
54
  plt.imsave(filename,torch.sigmoid(preds[0][0]))
55
+ img2 = cv2.imread(filename)
56
+ gray_image = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
 
 
 
 
 
57
  (thresh, bw_image) = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)
58
  cv2.cvtColor(bw_image, cv2.COLOR_BGR2RGB)
59
  mask = Image.fromarray(np.uint8(bw_image)).convert('RGB')
60
  os.remove(filename)
61
+ with autocast("cuda"):
62
+ images = pipe(prompt = prompt, init_image=init_image, mask_image=mask, strength=0.8)["sample"]
63
+ return images[0]
 
 
 
64
 
65
  # examples = [[dict(image="init_image.png", mask="mask_image.png"), "A panda sitting on a bench"]]
66
  css = '''
76
  .dark .footer>p {background: #0b0f19}
77
  .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
78
  #image_upload .touch-none{display: flex}
 
79
  '''
80
  def swap_word_mask(radio_option):
81
+ if(radio_option == "type what to mask below"):
 
 
82
  return gr.update(interactive=True, placeholder="A cat")
83
+ else:
84
+ return gr.update(interactive=False, placeholder="Disabled")
85
 
86
  image_blocks = gr.Blocks(css=css)
87
  with image_blocks as demo:
103
  fill="none"
104
  xmlns="http://www.w3.org/2000/svg"
105
  >
106
+ <rect width="23" height="23" fill="white"></rect>
107
+ <rect y="69" width="23" height="23" fill="white"></rect>
108
  <rect x="23" width="23" height="23" fill="#AEAEAE"></rect>
109
  <rect x="23" y="69" width="23" height="23" fill="#AEAEAE"></rect>
110
+ <rect x="46" width="23" height="23" fill="white"></rect>
111
  <rect x="46" y="69" width="23" height="23" fill="white"></rect>
112
  <rect x="69" width="23" height="23" fill="black"></rect>
113
  <rect x="69" y="69" width="23" height="23" fill="black"></rect>
114
  <rect x="92" width="23" height="23" fill="#D9D9D9"></rect>
115
  <rect x="92" y="69" width="23" height="23" fill="#AEAEAE"></rect>
116
+ <rect x="115" y="46" width="23" height="23" fill="white"></rect>
117
+ <rect x="115" y="115" width="23" height="23" fill="white"></rect>
118
  <rect x="115" y="69" width="23" height="23" fill="#D9D9D9"></rect>
119
  <rect x="92" y="46" width="23" height="23" fill="#AEAEAE"></rect>
120
  <rect x="92" y="115" width="23" height="23" fill="#AEAEAE"></rect>
121
  <rect x="92" y="69" width="23" height="23" fill="white"></rect>
122
+ <rect x="69" y="46" width="23" height="23" fill="white"></rect>
123
  <rect x="69" y="115" width="23" height="23" fill="white"></rect>
124
  <rect x="69" y="69" width="23" height="23" fill="#D9D9D9"></rect>
125
+ <rect x="46" y="46" width="23" height="23" fill="black"></rect>
126
  <rect x="46" y="115" width="23" height="23" fill="black"></rect>
127
+ <rect x="46" y="69" width="23" height="23" fill="black"></rect>
128
  <rect x="23" y="46" width="23" height="23" fill="#D9D9D9"></rect>
129
  <rect x="23" y="115" width="23" height="23" fill="#AEAEAE"></rect>
130
  <rect x="23" y="69" width="23" height="23" fill="black"></rect>
134
  </h1>
135
  </div>
136
  <p style="margin-bottom: 10px; font-size: 94%">
137
+ Inpaint Stable Diffusion by either drawing a mask or typing what to replace
138
  </p>
139
  </div>
140
  """
143
  with gr.Column():
144
  image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil", label="Upload").style(height=400)
145
  with gr.Box(elem_id="mask_radio").style(border=False):
146
+ 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)
147
  word_mask = gr.Textbox(label = "What to find in your image", interactive=False, elem_id="word_mask", placeholder="Disabled").style(container=False)
 
 
 
148
  prompt = gr.Textbox(label = 'Your prompt (what you want to add in place of what you are removing)')
149
  radio.change(fn=swap_word_mask, inputs=radio, outputs=word_mask,show_progress=False)
150
  radio.change(None, inputs=[], outputs=image_blocks, _js = """
159
  btn.click(fn=predict, inputs=[radio, image, word_mask, prompt], outputs=result)
160
  gr.HTML(
161
  """
162
+ <div class="footer">
163
+ <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 <a href="https://github.com/nagolinc" style="text-decoration: underline;" target="_blank">nagolinc</a> and <a href="https://github.com/patil-suraj" style="text-decoration: underline;">patil-suraj</a>, inpainting with words by <a href="https://twitter.com/yvrjsharma/" style="text-decoration: underline;" target="_blank">@yvrjsharma</a> and <a href="https://twitter.com/1littlecoder" style="text-decoration: underline;">@1littlecoder</a> - Gradio Demo by 🤗 Hugging Face
164
  </p>
165
  </div>
166
+ <div class="acknowledgments">
167
+ <p><h4>LICENSE</h4>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  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>
169
  <p><h4>Biases and content acknowledgment</h4>
170
  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>
171
+ </div>
 
 
172
  """
173
  )
174
+ demo.launch()