Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image, ImageDraw
|
| 5 |
+
from huggingface_hub import hf_hub_download
|
| 6 |
+
|
| 7 |
+
# Baixa pesos do modelo
|
| 8 |
+
repo_id = "vncgabriel/instance-segmentation-model"
|
| 9 |
+
model_file = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin")
|
| 10 |
+
|
| 11 |
+
# Carrega o modelo UNet
|
| 12 |
+
from __main__ import UNet
|
| 13 |
+
model = UNet()
|
| 14 |
+
state_dict = torch.load(model_file, map_location="cpu")
|
| 15 |
+
model.load_state_dict(state_dict)
|
| 16 |
+
model.eval()
|
| 17 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
+
model.to(device)
|
| 19 |
+
|
| 20 |
+
# Função de inferência
|
| 21 |
+
|
| 22 |
+
def segment(image: Image.Image):
|
| 23 |
+
image_resized = image.resize((512, 512))
|
| 24 |
+
tensor = torch.from_numpy((np.array(image_resized)/255.0).transpose(2,0,1)).unsqueeze(0).to(device).float()
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
outputs = model(tensor)
|
| 27 |
+
mask = (outputs > 0.5).squeeze().cpu().numpy()
|
| 28 |
+
mask_img = Image.fromarray((mask*255).astype(np.uint8), mode="L").resize(image.size)
|
| 29 |
+
overlay = Image.new("RGBA", image.size, (255,0,0,80))
|
| 30 |
+
base = image.convert("RGBA")
|
| 31 |
+
base.paste(overlay, mask=mask_img)
|
| 32 |
+
return base.convert("RGB")
|
| 33 |
+
|
| 34 |
+
# Interface Gradio
|
| 35 |
+
iface = gr.Interface(
|
| 36 |
+
fn=segment,
|
| 37 |
+
inputs=gr.Image(type="pil"),
|
| 38 |
+
outputs=gr.Image(type="pil"),
|
| 39 |
+
title="Instance Segmentation Demo",
|
| 40 |
+
allow_flagging="never"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|