#!/usr/bin/env python3
"""Remove o fundo da foto oficial do Francisco Borrello com rembg."""
from pathlib import Path
from rembg import remove, new_session
from PIL import Image
import io

SRC = Path("/opt/mia/workspace/clientes/francisco_borrello/foto_borrello_oficial.jpg")
DST = Path("/opt/mia/workspace/clientes/francisco_borrello/_recortes/foto_oficial_cutout.png")

DST.parent.mkdir(parents=True, exist_ok=True)

# Modelo isnet-general-use costuma dar melhor recorte para retrato de estudio
session = new_session("isnet-general-use")

with open(SRC, "rb") as f:
    src_bytes = f.read()

out_bytes = remove(src_bytes, session=session, alpha_matting=True,
                   alpha_matting_foreground_threshold=240,
                   alpha_matting_background_threshold=15,
                   alpha_matting_erode_size=8)

img = Image.open(io.BytesIO(out_bytes)).convert("RGBA")

# Crop pra tirar espaco vazio ao redor
bbox = img.getbbox()
if bbox:
    img = img.crop(bbox)

img.save(DST, "PNG", optimize=True)
print(f"OK -> {DST}  ({img.size[0]}x{img.size[1]})")
