import gradio as gr
from PIL import Image, ImageDraw
from transparent_background import Remover
import numpy as np
from gradio_imageslider import ImageSlider


def resize(img: Image, target_size_px: int):
    aspect_ratio = img.width / img.height

    if img.width > img.height:
        new_width = target_size_px
        new_height = int(target_size_px / aspect_ratio)
    else:
        new_height = target_size_px
        new_width = int(target_size_px * aspect_ratio)

    img = img.resize((new_width, new_height))

    return img


def infer(img: Image):

    img_resized = resize(img, 512)

    remover = Remover(mode="fast")
    masked_image = remover.process(img_resized, type="map")

    gray_image = masked_image.convert("L")
    binary_image = gray_image.point(lambda x: 0 if x < 128 else 255, "1")

    image_array = np.array(binary_image)
    white_pixels = np.where(image_array == True)

    x_coords = white_pixels[1]
    y_coords = white_pixels[0]

    min_x = np.min(x_coords)
    max_x = np.max(x_coords)
    min_y = np.min(y_coords)
    max_y = np.max(y_coords)

    draw = ImageDraw.Draw(img_resized)
    draw.rectangle([(min_x, min_y), (max_x, max_y)], outline="red", width=2)

    return img_resized, masked_image


gr.Interface(
    fn=infer,
    description="""
    This space performs salient object detection on an image uploaded by the user. I.e. it will detect the object(s) in the image foreground and draw a red rectangle around it.
    
    It uses the [transparent-background](https://github.com/plemeri/transparent-background) library, which is built on [InSPyReNet](https://github.com/plemeri/inspyrenet).
    """,
    inputs=gr.components.Image(type="pil", label="Input Image"),
    outputs=ImageSlider(label="Output", type="pil"),
    title="Salient Object Detection",
).launch()