"""cine-24 demo: PhotoGuard's encoder attack (MadryLab/photoguard, MIT; settings from its official demo/app.py) on our
stand-in photo, then the same inpainting edit on the original, the immunised photo, and the immunised photo after a
resize and JPEG (the transformation the paper's own limitations section names). CPU only (CUDA_VISIBLE_DEVICES="").

    CUDA_VISIBLE_DEVICES= tools/audio/envs/acestep/bin/python guard.py PHOTO.png MASK.png MODEL_DIR OUT_DIR

PHOTO: the photo; MASK: white = the person (kept). Model: Stable Diffusion inpainting (stable-diffusion-v1-5/
stable-diffusion-inpainting, the repo the code's runwayml/stable-diffusion-inpainting moved to), fp16 weights run in fp32.
"""
import io, json, os, sys, time
import numpy as np
import torch
from PIL import Image, ImageOps
from diffusers import StableDiffusionInpaintPipeline

PHOTO, MASK, MODEL, OUT = sys.argv[1:5]
os.makedirs(OUT, exist_ok=True)
torch.set_num_threads(min(32, os.cpu_count() or 8))
log = open(os.path.join(OUT, "guard_log.txt"), "w")


def say(*a):
    s = " ".join(str(x) for x in a); print(s, flush=True); log.write(s + "\n"); log.flush()


PROMPT = os.environ.get("PROMPT", "a person standing in a prison cell")
SEED, GUIDANCE, STEPS = 1234, 7.5, int(os.environ.get("STEPS", "50"))      # demo app: seed 1234, guidance 7.5 (100 steps)
EPS, STEP, ITERS = 0.12, 0.01, int(os.environ.get("ITERS", "200"))          # demo app: eps 0.12, step 0.01, 200 iterations

# ---- utils.py from the repo (recover_image, preprocess, prepare_mask_and_masked_image), unchanged in substance
import torchvision.transforms as T
totensor, topil = T.ToTensor(), T.ToPILImage()


def recover_image(image, init_image, mask, background=False):
    image, mask, init_image = totensor(image), totensor(mask), totensor(init_image)
    result = mask * init_image + (1 - mask) * image if background else mask * image + (1 - mask) * init_image
    return topil(result)


def preprocess(image):
    image = np.array(image).astype(np.float32) / 255.0
    return 2.0 * torch.from_numpy(image[None].transpose(0, 3, 1, 2)) - 1.0


def prepare_mask_and_masked_image(image, mask):
    image = torch.from_numpy(np.array(image.convert("RGB"))[None].transpose(0, 3, 1, 2)).float() / 127.5 - 1.0
    m = np.array(mask.convert("L")).astype(np.float32) / 255.0
    m = m[None, None]; m[m < 0.5] = 0; m[m >= 0.5] = 1
    m = torch.from_numpy(m)
    return m, image * (m < 0.5)


init_image = Image.open(PHOTO).convert("RGB").resize((512, 512), Image.LANCZOS)
person = Image.open(MASK).convert("RGB").resize((512, 512), Image.NEAREST)
mask_image = ImageOps.invert(person)                       # the inpainting mask: white = what gets repainted (all but her)
init_image.save(os.path.join(OUT, "photo_512.png")); mask_image.save(os.path.join(OUT, "edit_mask.png"))

t0 = time.time()
pipe = StableDiffusionInpaintPipeline.from_pretrained(MODEL, variant="fp16", torch_dtype=torch.float32, safety_checker=None)
pipe.set_progress_bar_config(disable=True)
say(f"model loaded in {time.time() - t0:.0f} s; prompt: {PROMPT!r}; seed {SEED}; guidance {GUIDANCE}; steps {STEPS}")


def edit(img, tag):
    t = time.time()
    torch.manual_seed(SEED)
    out = pipe(prompt=PROMPT, image=img, mask_image=mask_image, height=512, width=512, eta=1,
               guidance_scale=GUIDANCE, num_inference_steps=STEPS).images[0]
    out = recover_image(out, init_image, mask_image)        # as the repo: keep her pixels from the original
    out.save(os.path.join(OUT, f"edit_{tag}.png"))
    say(f"edit {tag}: {time.time() - t:.0f} s")
    return out


# ---- 1. the edit on the original photo
edit(init_image, "original")

# ---- 2. immunise: PGD on the VAE encoder, pushing her pixels' latent toward a flat grey image's
mask, X = prepare_mask_and_masked_image(init_image, mask_image)
grey = Image.new("RGB", (512, 512), (128, 128, 128))
with torch.no_grad():
    target = pipe.vae.encode(preprocess(grey)).latent_dist.mean
X_adv = X.clone() + (torch.rand(*X.shape) * 2 * EPS - EPS)
t = time.time()
for i in range(ITERS):
    step = STEP - (STEP - STEP / 100) / ITERS * i
    X_adv.requires_grad_(True)
    loss = (pipe.vae.encode(X_adv).latent_dist.mean - target).norm()
    grad, = torch.autograd.grad(loss, [X_adv])
    X_adv = X_adv.detach() - grad.sign() * step
    X_adv = torch.minimum(torch.maximum(X_adv, X - EPS), X + EPS).clamp(-1, 1)
    X_adv = X_adv * (1 - mask)
    if i % 10 == 0 or i == ITERS - 1:
        say(f"attack step {i:3d}  loss {loss.item():9.2f}  ({time.time() - t:.0f} s)")
adv = topil((X_adv[0] / 2 + 0.5).clamp(0, 1)).convert("RGB")
adv = recover_image(adv, init_image, mask_image, background=True)
adv.save(os.path.join(OUT, "immunized.png"))
d = np.asarray(adv, np.float32) - np.asarray(init_image, np.float32)
say(f"immunised: max change {np.abs(d).max():.0f}/255, mean {np.abs(d).mean():.2f}/255 per channel")
Image.fromarray(np.clip(d * 6 + 128, 0, 255).astype(np.uint8)).save(os.path.join(OUT, "perturbation_x6.png"))

# ---- 3. the same edit on the immunised photo
edit(adv, "immunized")

# ---- 4. the paper's own caveat: a resize and a JPEG, then the same edit again
small = adv.resize((384, 384), Image.BICUBIC).resize((512, 512), Image.BICUBIC)
buf = io.BytesIO(); small.save(buf, "JPEG", quality=70); washed = Image.open(io.BytesIO(buf.getvalue())).convert("RGB")
washed.save(os.path.join(OUT, "washed.png"))
edit(washed, "washed")
json.dump({"prompt": PROMPT, "seed": SEED, "guidance": GUIDANCE, "steps": STEPS, "eps": EPS, "step": STEP, "iters": ITERS,
           "max_change_255": float(np.abs(d).max()), "mean_change_255": float(np.abs(d).mean()),
           "seconds": round(time.time() - t0)}, open(os.path.join(OUT, "guard.json"), "w"), indent=1)
say("done")
