File size: 1,662 Bytes
67e4235
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed6996
 
 
ed034b3
 
 
 
dda4c50
ed034b3
 
 
3ed6996
 
dda4c50
3ed6996
ed034b3
3ed6996
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed034b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# ==========================================
# PATCH DE COMPATIBILIDADE (TRANSFORMERS 5.X + RMBG 1.4)
# Deve ficar no TOPO do arquivo, antes de tudo!
# ==========================================
import torch
_original_getattr = torch.nn.Module.__getattr__

def _patched_getattr(self, name):
    if name == "all_tied_weights_keys":
        return {}
    return _original_getattr(self, name)

torch.nn.Module.__getattr__ = _patched_getattr
# ==========================================
import gradio as gr
from transformers import pipeline
from PIL import Image
import spaces

# 1. Defina o dispositivo padrão (GPU se disponível, senão CPU)
# Nota: No ZeroGPU, isso inicializa na CPU, o spaces.GPU gerencia a mudança.
device = 0 if torch.cuda.is_available() else -1

print(f"Inicializando pipeline no dispositivo: {'GPU' if device == 0 else 'CPU'}")


# Função para remover o background da imagem
@spaces.GPU
def remove_background(image):
    pipe = pipeline("image-segmentation", model="briaai/RMBG-1.4", trust_remote_code=True, device=device)

    # Obter a máscara da imagem
    pillow_mask = pipe(image, return_mask=True)

    # Aplicar máscara na imagem original
    pillow_image = pipe(image)

    return pillow_image

# Criar uma interface Gradio
app = gr.Interface(
    fn=remove_background,
    inputs=gr.components.Image(type="pil"),
    outputs=gr.components.Image(type="pil", format="png"),  # Especificar saída como PNG
    title="Remoção de Background de Imagens",
    description="Envie uma imagem e veja o background sendo removido automaticamente. A imagem resultante será no formato PNG."
)

if __name__ == '__main__':
    app.launch()