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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from io import BytesIO
|
| 2 |
+
import requests
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import requests
|
| 5 |
+
import torch
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from PIL import Image, ImageOps
|
| 8 |
+
from diffusers import StableDiffusionInpaintPipeline
|
| 9 |
+
from torchvision.transforms import ToPILImage
|
| 10 |
+
from utils import preprocess, prepare_mask_and_masked_image, recover_image, resize_and_crop
|
| 11 |
+
|
| 12 |
+
gr.close_all()
|
| 13 |
+
topil = ToPILImage()
|
| 14 |
+
|
| 15 |
+
pipe_inpaint = StableDiffusionInpaintPipeline.from_pretrained(
|
| 16 |
+
"runwayml/stable-diffusion-inpainting",
|
| 17 |
+
revision="fp16",
|
| 18 |
+
torch_dtype=torch.float16,
|
| 19 |
+
safety_checker=None,
|
| 20 |
+
)
|
| 21 |
+
pipe_inpaint = pipe_inpaint.to("cuda")
|
| 22 |
+
|
| 23 |
+
## Good params for editing that we used all over the paper --> decent quality and speed
|
| 24 |
+
GUIDANCE_SCALE = 7.5
|
| 25 |
+
NUM_INFERENCE_STEPS = 100
|
| 26 |
+
DEFAULT_SEED = 1234
|
| 27 |
+
|
| 28 |
+
def pgd(X, targets, model, criterion, eps=0.1, step_size=0.015, iters=40, clamp_min=0, clamp_max=1, mask=None):
|
| 29 |
+
X_adv = X.clone().detach() + (torch.rand(*X.shape)*2*eps-eps).cuda()
|
| 30 |
+
pbar = tqdm(range(iters))
|
| 31 |
+
for i in pbar:
|
| 32 |
+
actual_step_size = step_size - (step_size - step_size / 100) / iters * i
|
| 33 |
+
X_adv.requires_grad_(True)
|
| 34 |
+
|
| 35 |
+
loss = (model(X_adv).latent_dist.mean - targets).norm()
|
| 36 |
+
pbar.set_description(f"Loss {loss.item():.5f} | step size: {actual_step_size:.4}")
|
| 37 |
+
|
| 38 |
+
grad, = torch.autograd.grad(loss, [X_adv])
|
| 39 |
+
|
| 40 |
+
X_adv = X_adv - grad.detach().sign() * actual_step_size
|
| 41 |
+
X_adv = torch.minimum(torch.maximum(X_adv, X - eps), X + eps)
|
| 42 |
+
X_adv.data = torch.clamp(X_adv, min=clamp_min, max=clamp_max)
|
| 43 |
+
X_adv.grad = None
|
| 44 |
+
|
| 45 |
+
if mask is not None:
|
| 46 |
+
X_adv.data *= mask
|
| 47 |
+
|
| 48 |
+
return X_adv
|
| 49 |
+
|
| 50 |
+
def get_target():
|
| 51 |
+
target_url = 'https://www.rtings.com/images/test-materials/2015/204_Gray_Uniformity.png'
|
| 52 |
+
response = requests.get(target_url)
|
| 53 |
+
target_image = Image.open(BytesIO(response.content)).convert("RGB")
|
| 54 |
+
target_image = target_image.resize((512, 512))
|
| 55 |
+
return target_image
|
| 56 |
+
|
| 57 |
+
def immunize_fn(init_image, mask_image):
|
| 58 |
+
with torch.autocast('cuda'):
|
| 59 |
+
mask, X = prepare_mask_and_masked_image(init_image, mask_image)
|
| 60 |
+
X = X.half().cuda()
|
| 61 |
+
mask = mask.half().cuda()
|
| 62 |
+
|
| 63 |
+
targets = pipe_inpaint.vae.encode(preprocess(get_target()).half().cuda()).latent_dist.mean
|
| 64 |
+
|
| 65 |
+
adv_X = pgd(X,
|
| 66 |
+
targets = targets,
|
| 67 |
+
model=pipe_inpaint.vae.encode,
|
| 68 |
+
criterion=torch.nn.MSELoss(),
|
| 69 |
+
clamp_min=-1,
|
| 70 |
+
clamp_max=1,
|
| 71 |
+
eps=0.12,
|
| 72 |
+
step_size=0.01,
|
| 73 |
+
iters=200,
|
| 74 |
+
mask=1-mask
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
adv_X = (adv_X / 2 + 0.5).clamp(0, 1)
|
| 78 |
+
|
| 79 |
+
adv_image = topil(adv_X[0]).convert("RGB")
|
| 80 |
+
adv_image = recover_image(adv_image, init_image, mask_image, background=True)
|
| 81 |
+
return adv_image
|
| 82 |
+
|
| 83 |
+
def run(image, prompt, seed, guidance_scale, num_inference_steps, immunize=False):
|
| 84 |
+
if seed == '':
|
| 85 |
+
seed = DEFAULT_SEED
|
| 86 |
+
else:
|
| 87 |
+
seed = int(seed)
|
| 88 |
+
torch.manual_seed(seed)
|
| 89 |
+
|
| 90 |
+
init_image = Image.fromarray(image['image'])
|
| 91 |
+
init_image = resize_and_crop(init_image, (512,512))
|
| 92 |
+
mask_image = ImageOps.invert(Image.fromarray(image['mask']).convert('RGB'))
|
| 93 |
+
mask_image = resize_and_crop(mask_image, init_image.size)
|
| 94 |
+
|
| 95 |
+
if immunize:
|
| 96 |
+
immunized_image = immunize_fn(init_image, mask_image)
|
| 97 |
+
|
| 98 |
+
image_edited = pipe_inpaint(prompt=prompt,
|
| 99 |
+
image=init_image if not immunize else immunized_image,
|
| 100 |
+
mask_image=mask_image,
|
| 101 |
+
height = init_image.size[0],
|
| 102 |
+
width = init_image.size[1],
|
| 103 |
+
eta=1,
|
| 104 |
+
guidance_scale=guidance_scale,
|
| 105 |
+
num_inference_steps=num_inference_steps,
|
| 106 |
+
).images[0]
|
| 107 |
+
|
| 108 |
+
image_edited = recover_image(image_edited, init_image, mask_image)
|
| 109 |
+
|
| 110 |
+
if immunize:
|
| 111 |
+
return [(immunized_image, 'Immunized Image'), (image_edited, 'Edited After Immunization')]
|
| 112 |
+
else:
|
| 113 |
+
return [(image_edited, 'Edited Image (Without Immunization)')]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
description='''
|
| 117 |
+
Prevent malicious actors from using your photo to create DeepFakes and spread false information. Protect yourself today!
|
| 118 |
+
<br />
|
| 119 |
+
'''
|
| 120 |
+
|
| 121 |
+
examples_list = [
|
| 122 |
+
['./images/hadi_and_trevor.jpg', 'man attending a wedding', '329357', GUIDANCE_SCALE, NUM_INFERENCE_STEPS],
|
| 123 |
+
['./images/trevor_2.jpg', 'two men in prison', '329357', GUIDANCE_SCALE, NUM_INFERENCE_STEPS],
|
| 124 |
+
['./images/elon_2.jpg', 'man in a metro station', '214213', GUIDANCE_SCALE, NUM_INFERENCE_STEPS],
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
with gr.Blocks() as demo:
|
| 129 |
+
gr.HTML(value="""<h1 style="font-weight: 900; margin-bottom: 7px; margin-top: 5px;">
|
| 130 |
+
DigiShield: Protect your photos online today from DeepFake technologies </h1><br>
|
| 131 |
+
""")
|
| 132 |
+
gr.Markdown(description)
|
| 133 |
+
with gr.Accordion(label='How to use (step by step):', open=False):
|
| 134 |
+
gr.Markdown('''
|
| 135 |
+
*First, let's edit your image:*
|
| 136 |
+
+ Upload an image (or select from the examples below)
|
| 137 |
+
+ Use the brush to mask the parts of the image you want to keep unedited (e.g., faces of people)
|
| 138 |
+
+ Add a prompt to guide the edit (see examples below)
|
| 139 |
+
+ Play with the seed and click submit until you get a realistic edit that you are happy with (we provided good example seeds for you below)
|
| 140 |
+
|
| 141 |
+
*Now, let's immunize your image and try again:*
|
| 142 |
+
+ Click on the "Immunize" button, then submit.
|
| 143 |
+
+ You will get an immunized version of the image (which should look essentially identical to the original one) as well as its edited version (which should now look rather unrealistic)
|
| 144 |
+
''')
|
| 145 |
+
|
| 146 |
+
# with gr.Accordion(label='Example (video):', open=False):
|
| 147 |
+
# gr.HTML('''
|
| 148 |
+
# <center>
|
| 149 |
+
# <iframe width="920" height="600" src="https://www.youtube.com/embed/aTC59Q6ZDNM">
|
| 150 |
+
# allow="fullscreen;" frameborder="0">
|
| 151 |
+
# </iframe>
|
| 152 |
+
# </center>
|
| 153 |
+
# '''
|
| 154 |
+
# )
|
| 155 |
+
|
| 156 |
+
with gr.Row():
|
| 157 |
+
with gr.Column():
|
| 158 |
+
imgmask = gr.ImageMask(label='Drawing tool to mask regions you want to keep, e.g. faces')
|
| 159 |
+
prompt = gr.Textbox(label='Prompt', placeholder='A photo of a man in a wedding')
|
| 160 |
+
seed = gr.Textbox(label='Seed (Change to get different edits)', placeholder=str(DEFAULT_SEED), visible=True)
|
| 161 |
+
with gr.Accordion("Advanced Options", open=False):
|
| 162 |
+
scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=25.0, value=GUIDANCE_SCALE, step=0.1)
|
| 163 |
+
num_steps = gr.Slider(label="Number of Inference Steps", minimum=10, maximum=250, value=NUM_INFERENCE_STEPS, step=5)
|
| 164 |
+
immunize = gr.Checkbox(label='Immunize', value=False)
|
| 165 |
+
b1 = gr.Button('Submit')
|
| 166 |
+
with gr.Column():
|
| 167 |
+
genimages = gr.Gallery(label="Generated images",
|
| 168 |
+
show_label=False,
|
| 169 |
+
elem_id="gallery").style(grid=[1,2], height="auto")
|
| 170 |
+
duplicate = gr.HTML("""
|
| 171 |
+
<p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings.
|
| 172 |
+
<br/>
|
| 173 |
+
<a href="https://huggingface.co/spaces/hadisalman/photoguard?duplicate=true">
|
| 174 |
+
<img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
|
| 175 |
+
<p/>
|
| 176 |
+
""")
|
| 177 |
+
|
| 178 |
+
b1.click(run, [imgmask, prompt, seed, scale, num_steps, immunize], [genimages])
|
| 179 |
+
examples = gr.Examples(examples=examples_list,inputs = [imgmask, prompt, seed, scale, num_steps, immunize], outputs=[genimages], cache_examples=False, fn=run)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
# demo.launch()
|
| 183 |
+
demo.launch(server_name='0.0.0.0', share=True, server_port=7860, inline=False)
|