akhaliq HF staff commited on
Commit
6ed0225
1 Parent(s): b7133f4
Files changed (1) hide show
  1. app.py +42 -95
app.py CHANGED
@@ -13,7 +13,6 @@ 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
 
@@ -29,9 +28,6 @@ pipe = StableDiffusionInpaintingPipeline.from_pretrained(
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(),
@@ -39,26 +35,10 @@ transform = transforms.Compose([
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
 
@@ -77,11 +57,6 @@ css = '''
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:
@@ -96,79 +71,51 @@ with image_blocks as demo:
96
  font-size: 1.75rem;
97
  "
98
  >
99
- <svg
100
- width="0.65em"
101
- height="0.65em"
102
- viewBox="0 0 115 115"
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>
131
- </svg>
132
  <h1 style="font-weight: 900; margin-bottom: 7px;">
133
- Stable Diffusion Multi Inpainting
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
  """
141
  )
142
- with gr.Row():
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 = """
151
- () => {
152
- css_style = document.styleSheets[document.styleSheets.length - 1]
153
- last_item = css_style.cssRules[css_style.cssRules.length - 1]
154
- last_item.style.display = ["flex", ""].includes(last_item.style.display) ? "none" : "flex";
155
- }""")
156
- btn = gr.Button("Run")
157
- with gr.Column():
158
- result = gr.Image(label="Result")
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()
 
13
  from matplotlib import pyplot as plt
14
  from inpainting import StableDiffusionInpaintingPipeline
15
  from torchvision import transforms
 
16
 
17
  auth_token = os.environ.get("API_TOKEN") or True
18
 
 
28
  use_auth_token=auth_token,
29
  ).to(device)
30
 
 
 
 
31
 
32
  transform = transforms.Compose([
33
  transforms.ToTensor(),
 
35
  transforms.Resize((512, 512)),
36
  ])
37
 
38
+ def predict(dict, prompt=""):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  with autocast("cuda"):
40
+ init_image = dict["image"].convert("RGB").resize((512, 512))
41
+ mask = dict["mask"].convert("RGB").resize((512, 512))
42
  images = pipe(prompt = prompt, init_image=init_image, mask_image=mask, strength=0.8)["sample"]
43
  return images[0]
44
 
 
57
  .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
58
  #image_upload .touch-none{display: flex}
59
  '''
 
 
 
 
 
60
 
61
  image_blocks = gr.Blocks(css=css)
62
  with image_blocks as demo:
 
71
  font-size: 1.75rem;
72
  "
73
  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  <h1 style="font-weight: 900; margin-bottom: 7px;">
75
+ Stable Diffusion Inpainting
76
  </h1>
77
  </div>
78
  <p style="margin-bottom: 10px; font-size: 94%">
79
+ Stable Diffusion Inpainting by RunwayML, add a mask and text prompt for what you want to replace <br>For faster generation you can try
80
+ <a
81
+ href="https://app.runwayml.com/video-tools/teams/akhaliq/ai-tools/erase-and-replace"
82
+ style="text-decoration: underline;"
83
+ target="_blank"
84
+ >erase and replace tool on Runway</a
85
+ >
86
  </p>
87
  </div>
88
  """
89
  )
90
+ with gr.Group():
91
+ with gr.Box():
92
  image = gr.Image(source='upload', tool='sketch', elem_id="image_upload", type="pil", label="Upload").style(height=400)
93
+
94
+ with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
95
+ prompt = gr.Textbox(label = 'Your prompt (what you want to replace)')
96
+ btn = gr.Button("Generate image").style(
97
+ margin=False,
98
+ rounded=(False, True, True, False),
99
+ full_width=False,
100
+ )
101
+
102
+ btn.click(fn=predict, inputs=[image, prompt], outputs=image)
103
+
104
+
105
+
106
+ gr.HTML(
107
+ """
108
+ <div class="footer">
109
+ <p>Model by <a href="https://huggingface.co/runwayml" style="text-decoration: underline;" target="_blank">RunwayML</a> - Gradio Demo by 🤗 Hugging Face
110
+ </p>
111
+ </div>
112
+ <div class="acknowledgments">
113
+ <p><h4>LICENSE</h4>
114
+ 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>
115
+ <p><h4>Biases and content acknowledgment</h4>
116
+ 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>
117
+ </div>
118
+ """
119
+ )
120
+
121
+ image_blocks.launch()