File size: 1,733 Bytes
d65ec7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
import os
import torch
from PIL import Image
import gradio as gr
from transformers import BlipProcessor, BlipForConditionalGeneration

# 1. Carregar o modelo BLIP finetuned
MODEL_DIR = "Frame_30K_gpu_01_pto"  # Substitua pelo nome correto da pasta do seu modelo

# Verifique se o diretório do modelo existe localmente

processor = BlipProcessor.from_pretrained(MODEL_DIR)
model = BlipForConditionalGeneration.from_pretrained(MODEL_DIR)

# Mover o modelo para o dispositivo disponível
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

def generate_caption(image):
    """

    Gera uma legenda para a imagem fornecida usando o modelo BLIP finetuned.



    Args:

        image (PIL.Image.Image): Imagem carregada.



    Returns:

        str: Legenda gerada.

    """
    if image is None:
        return "Nenhuma imagem fornecida."

    # Preprocessar a imagem
    inputs = processor(images=image, return_tensors="pt").to(device)

    # Gerar legenda
    out = model.generate(**inputs)
    caption = processor.decode(out[0], skip_special_tokens=True)
    
    return caption

# Configurar a interface Gradio
iface = gr.Interface(
    fn=generate_caption,
    inputs=gr.Image(type="pil", label="Enviar Imagem"),
    outputs=gr.Textbox(label="Legenda Gerada"),
    title="BLIP Português - Geração de Legendas para Imagens",
    description="Envie uma imagem e o modelo BLIP finetuned em português irá gerar uma legenda descritiva para ela.",
    examples=[
        ["examples/image1.jpg"],
        ["examples/image2.jpg"],
        ["examples/image3.jpg"],
    ],
    allow_flagging="never"
)

if __name__ == "__main__":
    iface.launch()