vncgabriel commited on
Commit
2ab3de8
·
verified ·
1 Parent(s): cbabead

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -24
app.py CHANGED
@@ -1,37 +1,58 @@
 
1
  import gradio as gr
2
  import torch
3
- import numpy as np
4
- from PIL import Image
5
  from huggingface_hub import hf_hub_download
6
- from model import UNet
 
 
7
 
8
- repo_id = "vncgabriel/instance-segmentation-model"
9
- model_file = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin")
 
 
 
 
10
 
11
- model = UNet()
12
- state = torch.load(model_file, map_location="cpu")
13
- model.load_state_dict(state, strict=False) # use strict=False to ignore mismatched keys
14
- model.eval()
15
  device = "cuda" if torch.cuda.is_available() else "cpu"
16
- model.to(device)
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- def segment(image):
19
- img = image.resize((512, 512))
20
- tensor = torch.from_numpy((np.array(img)/255.0).transpose(2,0,1)).unsqueeze(0).to(device).float()
21
- with torch.no_grad():
22
- out = model(tensor)
23
- mask = (out > 0.5).squeeze().cpu().numpy()
24
- mask_img = Image.fromarray((mask*255).astype(np.uint8), mode="L").resize(image.size)
25
- overlay = Image.new("RGBA", image.size, (255,0,0,80))
26
- base = image.convert("RGBA")
27
- base.paste(overlay, mask=mask_img)
28
- return base.convert("RGB")
29
 
 
 
 
 
 
 
 
 
30
  iface = gr.Interface(
31
  fn=segment,
32
  inputs=gr.Image(type="pil"),
33
  outputs=gr.Image(type="pil"),
34
- title="Instance Segmentation Demo",
35
- allow_flagging="never"
 
 
 
 
 
36
  )
37
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
 
 
1
+ # app.py
2
  import gradio as gr
3
  import torch
 
 
4
  from huggingface_hub import hf_hub_download
5
+ from inference import load_model, predict
6
+ from PIL import Image
7
+ import numpy as np
8
 
9
+ # 1. Baixa o peso do modelo diretamente do Hugging Face Hub
10
+ model_path = hf_hub_download(
11
+ repo_id="vncgabriel/instancia-segmentation-model",
12
+ filename="pytorch_model.pth",
13
+ repo_type="model",
14
+ )
15
 
16
+ # 2. Carrega o modelo na CPU (ou GPU, se disponível)
 
 
 
17
  device = "cuda" if torch.cuda.is_available() else "cpu"
18
+ model = load_model(model_path, device=device)
19
+
20
+ # 3. Função de predição para o Gradio
21
+ def segment(image: Image.Image):
22
+ """
23
+ Recebe uma PIL Image, converte para tensor, normaliza e gera máscara.
24
+ Retorna imagem original sobreposta com a máscara.
25
+ """
26
+ # Converter PIL -> np.array -> tensor
27
+ img_arr = np.array(image).astype(np.float32) / 255.0
28
+ # formato HWC -> CHW
29
+ img_tensor = torch.from_numpy(img_arr).permute(2, 0, 1).to(device)
30
 
31
+ # predição
32
+ mask = predict(model, img_tensor).cpu().numpy()
33
+ # máscara binária
34
+ bin_mask = (mask > 0.5).astype(np.uint8) * 255
 
 
 
 
 
 
 
35
 
36
+ # sobrepor máscara vermelha semitransparente
37
+ overlay = image.convert("RGBA")
38
+ mask_img = Image.fromarray(bin_mask).convert("L")
39
+ red = Image.new("RGBA", image.size, color=(255, 0, 0, 100))
40
+ overlay.paste(red, mask=mask_img)
41
+ return overlay
42
+
43
+ # 4. Define a interface Gradio
44
  iface = gr.Interface(
45
  fn=segment,
46
  inputs=gr.Image(type="pil"),
47
  outputs=gr.Image(type="pil"),
48
+ title="Segmentación de Instancias",
49
+ description="Sube una imagen y obtén la segmentación de instancias usando UNet preentrenado.",
50
+ examples=[
51
+ # opcional: caminhos locais ou URLs para imagens de exemplo
52
+ ["example1.jpg"],
53
+ ["example2.jpg"],
54
+ ],
55
  )
56
+
57
+ if __name__ == "__main__":
58
+ iface.launch(server_name="0.0.0.0", server_port=7860)