"""Run the SMIRK encoder (Retsinas et al., CVPR 2024; MIT code) on one photo, CPU only.

Crops the face the way SMIRK's demo does (MediaPipe landmark box x1.4, 224x224) and saves FLAME 2020
parameters: 50 expressions, 2 eyelid closures, jaw pose, plus SMIRK's own shape and pose guesses.
usage: python -I smirk_run.py --est <dir with image.png, landmarks.npy> --out smirk.npz
"""
import argparse, sys
import numpy as np, torch
from PIL import Image
from skimage.transform import estimate_transform, warp

S = "/work/third_party/smirk"
sys.path.insert(0, S)
import timm
_create = timm.create_model
timm.create_model = lambda name, pretrained=True, **kw: _create(name, pretrained=False, **kw)   # weights come from SMIRK's checkpoint
from src.smirk_encoder import SmirkEncoder

ap = argparse.ArgumentParser(); ap.add_argument("--est", required=True); ap.add_argument("--out", required=True)
a = ap.parse_args()
img = np.asarray(Image.open(f"{a.est}/image.png").convert("RGB"))
H, W = img.shape[:2]
L = np.load(f"{a.est}/landmarks.npy")[:, :2] * [W, H]

left, right, top, bottom = L[:, 0].min(), L[:, 0].max(), L[:, 1].min(), L[:, 1].max()
size = int((right - left + bottom - top) / 2 * 1.4); cx, cy = (left + right) / 2, (top + bottom) / 2
src = np.array([[cx - size / 2, cy - size / 2], [cx - size / 2, cy + size / 2], [cx + size / 2, cy - size / 2]])
tform = estimate_transform("similarity", src, np.array([[0, 0], [0, 223], [223, 0]]))
crop = warp(img, tform.inverse, output_shape=(224, 224), preserve_range=True).astype(np.uint8)
Image.fromarray(crop).save(a.out.replace(".npz", "_crop.png"))

enc = SmirkEncoder().eval()
ck = torch.load(f"{S}/pretrained_models/SMIRK_em1.pt", map_location="cpu", weights_only=True)
enc.load_state_dict({k.replace("smirk_encoder.", ""): v for k, v in ck.items() if "smirk_encoder" in k})
with torch.no_grad():
    out = enc(torch.tensor(crop).permute(2, 0, 1)[None].float() / 255)
res = {k: v[0].numpy() for k, v in out.items()}
np.savez(a.out, **res)
for k, v in res.items():
    print(f"{k:18s} {v.shape}  {np.round(v[:6], 3)}")
