Spaces:
Runtime error
Runtime error
Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
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 = '''
|
67 |
+
.container {max-width: 1150px;margin: auto;padding-top: 1.5rem}
|
68 |
+
#image_upload{min-height:400px}
|
69 |
+
#image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px}
|
70 |
+
#mask_radio .gr-form{background:transparent; border: none}
|
71 |
+
#word_mask{margin-top: .75em !important}
|
72 |
+
#word_mask textarea:disabled{opacity: 0.3}
|
73 |
+
.footer {margin-bottom: 45px;margin-top: 35px;text-align: center;border-bottom: 1px solid #e5e5e5}
|
74 |
+
.footer>p {font-size: .8rem; display: inline-block; padding: 0 10px;transform: translateY(10px);background: white}
|
75 |
+
.dark .footer {border-color: #303030}
|
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:
|
88 |
+
gr.HTML(
|
89 |
+
"""
|
90 |
+
<div style="text-align: center; max-width: 650px; margin: 0 auto;">
|
91 |
+
<div
|
92 |
+
style="
|
93 |
+
display: inline-flex;
|
94 |
+
align-items: center;
|
95 |
+
gap: 0.8rem;
|
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()
|