import os

os.system(
    "pip install uvicorn --upgrade;\
pip install gradio==3.47.1;\
pip install transformers;\
pip install diffusers;\
pip install accelerate;\
pip install torch"
)

import gradio as gr
from PIL import Image

import torch
from diffusers import AutoPipelineForInpainting
from diffusers.utils import load_image

def draw_on_image(image, prompt):
    print(image, prompt)

    if not prompt:
        return

    init_image = load_image(
        image["image"]
    )
    mask_image = load_image(
        image["mask"]
    )

    res_image = pipeline(prompt=prompt, image=init_image, mask_image=mask_image, num_inference_steps=5).images[0]

    return res_image

inputs = [
        gr.Image(tool="sketch", label="Image", type="pil"),
        gr.Text(max_lines=1)
]

if torch.cuda.is_available():
    torch_dtype = torch.float16
    device = "cuda"
else:
    torch_dtype = torch.float32
    device = "cpu"

pipeline = AutoPipelineForInpainting.from_pretrained(
    "Lykon/absolute-reality-1.6525-inpainting", torch_dtype=torch_dtype
)

pipeline.to(device)

app = gr.Interface(draw_on_image, inputs=inputs, outputs="image", title="Stable Diffusion Inpainting", description="EN: To use it, you need to select an object in the image and enter in the prompt line what you want to see in place of this object.\nIf you received a black image, then the neural networks in HuggingFace identified the result as pornography. Try again.\n \nRU: Для использования, вам необходимо выделить объект на изображении и ввести в строку \"prompt\" то, что вы хотите видеть на месте данного объекта.\nЕсли вы получили изображение черного цвета, то классификатору не нравится ваша фотка. Попробуйте снова.\n\n\n**Топовый антиспам для телеграм-групп: https://t.me/RuModeratorAI_Bot**")
app.queue()
app.launch(share=True)