DHEIVER commited on
Commit
fe87a10
·
verified ·
1 Parent(s): ca55fe0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -26
app.py CHANGED
@@ -1,36 +1,73 @@
1
- from transformers import AutoModel
2
- import gradio as gr
3
- from PIL import Image
4
  import torch
 
 
 
 
 
 
5
 
6
- # Carregar o modelo
7
- model = AutoModel.from_pretrained("openbmb/MiniCPM-o-2_6", trust_remote_code=True)
 
 
 
8
 
9
- # Função para processar a imagem e gerar uma resposta
10
- def process_image(input_image):
11
- # Pré-processamento da imagem (se necessário)
12
- # Exemplo: redimensionar, normalizar, converter para tensor, etc.
13
- input_image = input_image.resize((224, 224)) # Redimensionar para o tamanho esperado pelo modelo
14
- input_tensor = torch.tensor(np.array(input_image)).permute(2, 0, 1).unsqueeze(0).float() # Converter para tensor
15
 
16
- # Passar a imagem pelo modelo
17
- with torch.no_grad():
18
- output = model(input_tensor)
 
 
19
 
20
- # Processar a saída do modelo (depende do que o modelo retorna)
21
- # Aqui estou apenas simulando uma resposta
22
- response = "Processamento concluído. Saída do modelo disponível."
23
 
24
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  # Criar a interface Gradio
27
- interface = gr.Interface(
28
- fn=process_image, # Função que processa a imagem
29
- inputs="image", # Tipo de entrada: imagem
30
- outputs="text", # Tipo de saída: texto
31
- title="MiniCPM-o-2_6 - Processamento de Imagens", # Título da interface
32
- description="Envie uma imagem e veja a resposta do modelo MiniCPM-o-2_6." # Descrição
33
- )
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  # Iniciar a interface
36
- interface.launch()
 
 
 
 
1
  import torch
2
+ from PIL import Image
3
+ from transformers import AutoModel, AutoTokenizer
4
+ import gradio as gr
5
+
6
+ # Configuração inicial
7
+ torch.manual_seed(100)
8
 
9
+ # Carregar o modelo e o tokenizer
10
+ model = AutoModel.from_pretrained('openbmb/MiniCPM-o-2_6', trust_remote_code=True,
11
+ attn_implementation='sdpa', torch_dtype=torch.bfloat16)
12
+ model = model.eval().cuda()
13
+ tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-o-2_6', trust_remote_code=True)
14
 
15
+ # Função para interagir com o modelo
16
+ def chat_with_model(image, question, chat_history=None):
17
+ if chat_history is None:
18
+ chat_history = []
 
 
19
 
20
+ # Converter a imagem para RGB (se necessário)
21
+ if isinstance(image, str):
22
+ image = Image.open(image).convert('RGB')
23
+ else:
24
+ image = image.convert('RGB')
25
 
26
+ # Preparar a mensagem para o modelo
27
+ msgs = [{'role': 'user', 'content': [image, question]}]
 
28
 
29
+ # Adicionar histórico de conversa, se houver
30
+ for msg in chat_history:
31
+ msgs.append(msg)
32
+
33
+ # Gerar resposta do modelo
34
+ answer = model.chat(
35
+ msgs=msgs,
36
+ tokenizer=tokenizer
37
+ )
38
+
39
+ # Atualizar o histórico de conversa
40
+ chat_history.append({"role": "user", "content": [image, question]})
41
+ chat_history.append({"role": "assistant", "content": [answer]})
42
+
43
+ # Retornar a resposta e o histórico atualizado
44
+ return answer, chat_history
45
+
46
+ # Interface Gradio
47
+ def gradio_interface(image, question, chat_history=None):
48
+ response, updated_history = chat_with_model(image, question, chat_history)
49
+ return response, updated_history
50
 
51
  # Criar a interface Gradio
52
+ with gr.Blocks() as demo:
53
+ gr.Markdown("# MiniCPM-o-2_6 Chat with Images")
54
+ gr.Markdown("Envie uma imagem e faça perguntas sobre ela.")
55
+
56
+ with gr.Row():
57
+ image_input = gr.Image(label="Upload Image", type="pil")
58
+ question_input = gr.Textbox(label="Your Question", placeholder="What is in the image?")
59
+
60
+ chat_history = gr.State([]) # Armazenar o histórico de conversa
61
+ output_text = gr.Textbox(label="Model Response", interactive=False)
62
+
63
+ submit_button = gr.Button("Submit")
64
+
65
+ # Ação ao clicar no botão
66
+ submit_button.click(
67
+ fn=gradio_interface,
68
+ inputs=[image_input, question_input, chat_history],
69
+ outputs=[output_text, chat_history]
70
+ )
71
 
72
  # Iniciar a interface
73
+ demo.launch()