"""cine-24: what the encoder sees. VAE-encode (the inpainting model's own VAE) our photo, the immunised photo and a flat
grey image, and render each latent (64 x 64 x 4) as a small picture with the standard SD 1.5 latent-preview colour
map (a linear map from the 4 latent channels to RGB), so the "summary" can be shown. CPU only.

    CUDA_VISIBLE_DEVICES= tools/audio/envs/acestep/bin/python latents.py MODEL_DIR RAW_DIR OUT_DIR
"""
import os, sys
import numpy as np
import torch
from PIL import Image
from diffusers import AutoencoderKL

MODEL, RAW, OUT = sys.argv[1:4]
os.makedirs(OUT, exist_ok=True)
vae = AutoencoderKL.from_pretrained(MODEL, subfolder="vae", variant="fp16", torch_dtype=torch.float32)
M = torch.tensor([[0.298, 0.207, 0.208], [0.187, 0.286, 0.173], [-0.158, 0.189, 0.264], [-0.184, -0.271, -0.473]])


def lat(img):
    x = torch.from_numpy(np.asarray(img.convert("RGB").resize((512, 512)), np.float32) / 127.5 - 1)[None].permute(0, 3, 1, 2)
    with torch.no_grad():
        return vae.encode(x).latent_dist.mean[0] * 0.18215


def show(z, name):
    rgb = torch.einsum("chw,cr->hwr", z, M)
    a = ((rgb + 1) / 2).clamp(0, 1).numpy()
    Image.fromarray((a * 255).astype(np.uint8)).save(os.path.join(OUT, name))
    return z


zs = {}
for src, name in (("photo_512.png", "latent_photo.png"), ("immunized.png", "latent_immunized.png")):
    zs[name] = show(lat(Image.open(os.path.join(RAW, src))), name)
# what the inpainting model actually encodes: the part it keeps (her), the rest blanked to mid-grey (masked_image in
# the repo's prepare_mask_and_masked_image); this is the latent PhotoGuard pushes toward the grey image's
edit = np.asarray(Image.open(os.path.join(RAW, "edit_mask.png")).convert("L")) >= 128           # True = repainted


def masked(src):
    a = np.asarray(Image.open(os.path.join(RAW, src)).convert("RGB")).copy()
    a[edit] = 128
    return Image.fromarray(a)


for src, name in (("photo_512.png", "latent_her.png"), ("immunized.png", "latent_her_immunized.png")):
    zs[name] = show(lat(masked(src)), name)
    masked(src).save(os.path.join(OUT, name.replace("latent_", "masked_")))
zs["grey"] = show(lat(Image.new("RGB", (512, 512), (128, 128, 128))), "latent_grey.png")
for k in ("latent_photo.png", "latent_immunized.png", "latent_her.png", "latent_her_immunized.png"):
    d = (zs[k] - zs["grey"]).norm().item()
    print(f"{k}: distance to the grey image's latent {d:.1f}")
