DHEIVER commited on
Commit
2c74f1f
·
verified ·
1 Parent(s): f7211bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -35
app.py CHANGED
@@ -3,20 +3,14 @@ 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-V', trust_remote_code=True,
11
- attn_implementation='sdpa', torch_dtype=torch.bfloat16)
12
- model = model.eval().cuda()
13
  tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V', 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')
@@ -24,49 +18,43 @@ def chat_with_model(image, question, chat_history=None):
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
 
3
  from transformers import AutoModel, AutoTokenizer
4
  import gradio as gr
5
 
 
 
 
6
  # Carregar o modelo e o tokenizer
7
+ model = AutoModel.from_pretrained('openbmb/MiniCPM-V', trust_remote_code=True, torch_dtype=torch.bfloat16)
8
+ model = model.to(device='cuda', dtype=torch.bfloat16) # Ajuste para o dispositivo e tipo de dados adequados
 
9
  tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V', trust_remote_code=True)
10
+ model.eval()
11
 
12
+ # Função para processar a imagem e a pergunta
13
+ def chat_with_model(image, question):
 
 
 
14
  # Converter a imagem para RGB (se necessário)
15
  if isinstance(image, str):
16
  image = Image.open(image).convert('RGB')
 
18
  image = image.convert('RGB')
19
 
20
  # Preparar a mensagem para o modelo
21
+ msgs = [{'role': 'user', 'content': question}]
 
 
 
 
22
 
23
  # Gerar resposta do modelo
24
+ res, context, _ = model.chat(
25
+ image=image,
26
  msgs=msgs,
27
+ context=None,
28
+ tokenizer=tokenizer,
29
+ sampling=True,
30
+ temperature=0.7
31
  )
32
 
33
+ return res
 
 
 
 
 
34
 
35
  # Interface Gradio
36
+ def gradio_interface(image, question):
37
+ response = chat_with_model(image, question)
38
+ return response
39
 
40
  # Criar a interface Gradio
41
  with gr.Blocks() as demo:
42
+ gr.Markdown("# MiniCPM-V Chat with Images")
43
  gr.Markdown("Envie uma imagem e faça perguntas sobre ela.")
44
 
45
  with gr.Row():
46
+ image_input = gr.Image(label="Upload Image", type="pil") # Campo para upload de imagem
47
+ question_input = gr.Textbox(label="Your Question", placeholder="What is in the image?") # Campo para a pergunta
48
 
49
+ output_text = gr.Textbox(label="Model Response", interactive=False) # Campo para exibir a resposta
 
50
 
51
+ submit_button = gr.Button("Submit") # Botão para enviar
52
 
53
  # Ação ao clicar no botão
54
  submit_button.click(
55
  fn=gradio_interface,
56
+ inputs=[image_input, question_input],
57
+ outputs=output_text
58
  )
59
 
60
  # Iniciar a interface