#!/usr/bin/env python3
"""Cutout for Hoodie-Zip With Love black - BACK view (flat), smooth edges."""
import numpy as np
from PIL import Image, ImageFilter
from rembg import remove, new_session
import gc

SRC = '/root/.hermes/image_cache/zrd_1x1/zl0a8547.jpg'
OUT = '/root/.hermes/image_cache/zrd_1x1/hoodie_back.png'
session = new_session('isnet-general-use')

cell = Image.open(SRC).convert('RGB')
scale = 2.0
cell_big = cell.resize((int(cell.width*scale), int(cell.height*scale)), Image.LANCZOS)
rgba = remove(cell_big, session=session, post_process_mask=True)
gc.collect()

a0 = np.array(rgba)[:, :, 3].astype(np.float32) / 255.0
rgb0 = np.array(rgba)[:, :, :3]

# decontaminate from white background
a = np.clip(a0, 0.0, 1.0)[..., None]
rgb_dc = (rgb0.astype(np.float32) - 255.0 * (1.0 - a)) / np.maximum(a, 1e-6)
rgb_dc = np.clip(rgb_dc, 0, 255).astype(np.uint8)

a_im = Image.fromarray((a0*255).astype(np.uint8), 'L').filter(ImageFilter.MinFilter(9))
a_im = a_im.filter(ImageFilter.GaussianBlur(3.0))
a2 = np.array(a_im).astype(np.float32) / 255.0

mix = np.clip(a2 / np.maximum(a0, 1e-6), 0, 1)[..., None]
rgb_final = (rgb_dc * mix + rgb0 * (1 - mix)).astype(np.uint8)

out = Image.fromarray(np.dstack([rgb_final, (a2*255).astype(np.uint8)]), 'RGBA')
bbox = out.getbbox()
if bbox:
    xa, ya, xb, yb = bbox
    m = 3
    out = out.crop((max(0,xa-m), max(0,ya-m), min(out.width,xb+m), min(out.height,yb+m)))
out.save(OUT)
print(OUT, out.size)
