"""IC-Light (Zhang, Rao, Agrawala; Apache-2.0) foreground-conditioned relighting on CPU.

Learned relighting: a Stable Diffusion 1.5 model fine-tuned to redraw a cut-out subject under new light.
Light direction comes from IC-Light's trick of starting the diffusion from a brightness gradient
("initial latent"); here the gradient can point any way, so the light can come from any angle.

Differences from the official demo: CPU, float32; the subject mask comes from our MoGe-2 depth split
instead of BRIA RMBG (non-commercial); a second pass at the same resolution refines detail.

usage: python -I iclight_run.py --est <dir> --angles 0,45,90 --out <dir> [--prompt ...]
angle: direction the light comes FROM, degrees, 0 = from the right, 90 = from above, 180 = from the left.
"""
import argparse, math, os, time
import numpy as np, torch
from PIL import Image
import safetensors.torch as sf
from diffusers import (AutoencoderKL, UNet2DConditionModel, DPMSolverMultistepScheduler,
                       StableDiffusionImg2ImgPipeline)
from diffusers.models.attention_processor import AttnProcessor2_0
from transformers import CLIPTextModel, CLIPTokenizer

ap = argparse.ArgumentParser()
ap.add_argument("--est", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--angles", default="180,90,0")
ap.add_argument("--prompt", default="portrait of a smiling man in a dark suit and bow tie")
ap.add_argument("--light", default="soft studio light")
ap.add_argument("--width", type=int, default=512)
ap.add_argument("--height", type=int, default=640)
ap.add_argument("--steps", type=int, default=25)
ap.add_argument("--seed", type=int, default=12345)
ap.add_argument("--model", default="/models/iclight_sd15_fc.safetensors")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
torch.set_num_threads(14)

# ---------------------------------------------------------------- subject cut-out (grey background, as IC-Light expects)
img = np.asarray(Image.open(f"{a.est}/image.png").convert("RGB")).astype(np.float32)
P = np.load(f"{a.est}/points.npy"); valid = np.load(f"{a.est}/mask.npy").astype(bool)
z = np.where(valid, P[..., 2], np.nan); lz = np.log(z[valid]); hist, edges = np.histogram(lz, 256)
w0 = np.cumsum(hist); w1 = w0[-1] - w0; m_ = np.cumsum(hist * edges[:-1])
mu0 = m_ / np.maximum(w0, 1); mu1 = (m_[-1] - m_) / np.maximum(w1, 1)
thr = np.exp(edges[np.argmax(w0 * w1 * (mu0 - mu1) ** 2)])
alpha = (valid & (z < thr)).astype(np.float32)
from PIL import ImageFilter
alpha = np.asarray(Image.fromarray((alpha * 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(1.5)), np.float32) / 255
fg = (127 + (img - 127) * alpha[..., None]).clip(0, 255).astype(np.uint8)

def fit(im, w, h):                      # resize + centre crop to w x h
    pil = Image.fromarray(im); s = max(w / pil.width, h / pil.height)
    pil = pil.resize((round(pil.width * s), round(pil.height * s)), Image.LANCZOS)
    l, t = (pil.width - w) // 2, (pil.height - h) // 2
    return np.asarray(pil.crop((l, t, l + w, t + h)))
W, H = a.width, a.height
fg_r = fit(fg, W, H); Image.fromarray(fg_r).save(f"{a.out}/input_fg.png")
alpha_r = fit((alpha * 255).astype(np.uint8), W, H); Image.fromarray(alpha_r).save(f"{a.out}/alpha.png")

# ---------------------------------------------------------------- model: SD1.5 (Realistic Vision 5.1) + IC-Light offsets, 8-channel conv_in
sd15 = "stablediffusionapi/realistic-vision-v51"
tok = CLIPTokenizer.from_pretrained(sd15, subfolder="tokenizer")
te = CLIPTextModel.from_pretrained(sd15, subfolder="text_encoder")
vae = AutoencoderKL.from_pretrained(sd15, subfolder="vae")
unet = UNet2DConditionModel.from_pretrained(sd15, subfolder="unet")
with torch.no_grad():
    ci = torch.nn.Conv2d(8, unet.conv_in.out_channels, unet.conv_in.kernel_size, unet.conv_in.stride, unet.conv_in.padding)
    ci.weight.zero_(); ci.weight[:, :4].copy_(unet.conv_in.weight); ci.bias = unet.conv_in.bias; unet.conv_in = ci
orig_forward = unet.forward
def hooked(sample, timestep, encoder_hidden_states, **kw):
    c = kw["cross_attention_kwargs"]["concat_conds"].to(sample)
    c = torch.cat([c] * (sample.shape[0] // c.shape[0]), 0)
    kw["cross_attention_kwargs"] = {}
    return orig_forward(torch.cat([sample, c], 1), timestep, encoder_hidden_states, **kw)
unet.forward = hooked
off = sf.load_file(a.model); sd = unet.state_dict()
unet.load_state_dict({k: sd[k] + off[k] for k in sd}, strict=True); del off, sd
unet.set_attn_processor(AttnProcessor2_0()); vae.set_attn_processor(AttnProcessor2_0())
sched = DPMSolverMultistepScheduler(num_train_timesteps=1000, beta_start=0.00085, beta_end=0.012,
                                    algorithm_type="sde-dpmsolver++", use_karras_sigmas=True, steps_offset=1)
pipe = StableDiffusionImg2ImgPipeline(vae=vae, text_encoder=te, tokenizer=tok, unet=unet, scheduler=sched,
                                      safety_checker=None, requires_safety_checker=False, feature_extractor=None)

def to_t(im): return torch.from_numpy(np.asarray(im, np.float32) / 127.0 - 1.0).permute(2, 0, 1)[None]
def to_np(x): return ((x[0].permute(1, 2, 0).clamp(-1, 1) + 1) * 127.5).round().byte().numpy()
def enc(im): return vae.encode(to_t(im)).latent_dist.mode() * vae.config.scaling_factor
def prompt_embeds(p, n):
    ids = tok([p, n], padding="max_length", max_length=77, truncation=True, return_tensors="pt").input_ids
    e = te(ids)[0]; return e[:1], e[1:]

with torch.inference_mode():
    cond_fg = enc(fg_r)
    for ang in [float(x) for x in a.angles.split(",")]:
        t0 = time.time()
        th = math.radians(ang); ux, uy = math.cos(th), -math.sin(th)       # image y points down
        X, Y = np.meshgrid(np.linspace(-1, 1, W), np.linspace(-1, 1, H) * H / W)
        g = (X * ux + Y * uy); g = (g - g.min()) / (g.max() - g.min())
        bg = np.repeat((g * 255).astype(np.uint8)[..., None], 3, -1)
        side = {0: "right", 45: "upper right", 90: "above", 135: "upper left", 180: "left",
                225: "lower left", 270: "below", 315: "lower right"}.get(int(ang) % 360, f"{ang:.0f} degrees")
        c, u = prompt_embeds(f"{a.prompt}, {a.light} from the {side}" if side != "above" else f"{a.prompt}, {a.light} from above",
                             "lowres, bad anatomy, bad hands, cropped, worst quality")
        gen = torch.Generator().manual_seed(a.seed)
        lat = pipe(image=enc(bg), strength=0.9, prompt_embeds=c, negative_prompt_embeds=u, width=W, height=H,
                   num_inference_steps=round(a.steps / 0.9), generator=gen, output_type="latent", guidance_scale=2.0,
                   cross_attention_kwargs={"concat_conds": cond_fg}).images
        lat = pipe(image=lat, strength=0.5, prompt_embeds=c, negative_prompt_embeds=u, width=W, height=H,
                   num_inference_steps=round(a.steps / 0.5), generator=gen, output_type="latent", guidance_scale=2.0,
                   cross_attention_kwargs={"concat_conds": cond_fg}).images
        out = to_np(vae.decode(lat / vae.config.scaling_factor).sample)
        Image.fromarray(out).save(f"{a.out}/light_{int(ang):03d}.png")
        print(f"angle {ang:.0f} ({side}) done in {time.time()-t0:.0f}s", flush=True)
print("DONE", flush=True)
