taesiri commited on
Commit
07c39b0
1 Parent(s): 7183fd3

added chat

Browse files
Files changed (1) hide show
  1. app.py +79 -33
app.py CHANGED
@@ -1,59 +1,105 @@
1
  import os
2
- import torch
3
- from PIL import Image
4
  import numpy as np
5
- from PIL import Image
6
  from lavis.models import load_model_and_preprocess
7
- import gradio as gr
8
 
9
  device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
10
 
11
-
12
  model, vis_processors, _ = load_model_and_preprocess(
13
  name="blip2_opt", model_type="pretrain_opt2.7b", is_eval=True, device=device
14
  )
15
 
16
 
17
- def answer_question(image, prompt):
18
- image = vis_processors["eval"](image).unsqueeze(0).to(device)
19
- response = model.generate({"image": image, "prompt": f"Question: {prompt} Answer:"})
20
- response = '\n'.join(response)
21
- return response
22
-
23
  def generate_caption(image, caption_type):
24
  image = vis_processors["eval"](image).unsqueeze(0).to(device)
25
-
26
  if caption_type == "Beam Search":
27
  caption = model.generate({"image": image})
28
  else:
29
- caption = model.generate({"image": image}, use_nucleus_sampling=True, num_captions=3)
30
-
31
- caption = '\n'.join(caption)
32
-
 
 
33
  return caption
34
 
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  with gr.Blocks() as demo:
37
-
38
- gr.Markdown("## BLIP-2 Demo")
39
- gr.Markdown("Using `OPT2.7B` - [Github](https://github.com/salesforce/LAVIS/tree/main/projects/blip2) - [Paper](https://arxiv.org/abs/2301.12597)")
40
-
41
-
 
 
 
42
  with gr.Row():
43
  with gr.Column():
44
  input_image = gr.Image(label="Image", type="pil")
45
- caption_type = gr.Radio(["Beam Search", "Nucleus Sampling"], label="Caption Type", value="Beam Search")
 
 
 
 
46
  btn_caption = gr.Button("Generate Caption")
47
-
 
 
 
 
 
48
  question_txt = gr.Textbox(label="Question", lines=1)
49
  btn_answer = gr.Button("Generate Answer")
50
-
51
- with gr.Column():
52
- output_text = gr.Textbox(label="Answer", lines=5)
53
-
54
- btn_caption.click(generate_caption, inputs=[input_image, caption_type], outputs=[output_text])
55
- btn_answer.click(answer_question, inputs=[input_image, question_txt], outputs=[output_text])
56
-
57
- gr.Examples([['./merlion.png', 'Beam Search', 'which city is this?']], inputs=[input_image, caption_type, question_txt])
58
-
59
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
+
3
+ import gradio as gr
4
  import numpy as np
5
+ import torch
6
  from lavis.models import load_model_and_preprocess
7
+ from PIL import Image
8
 
9
  device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
10
 
 
11
  model, vis_processors, _ = load_model_and_preprocess(
12
  name="blip2_opt", model_type="pretrain_opt2.7b", is_eval=True, device=device
13
  )
14
 
15
 
 
 
 
 
 
 
16
  def generate_caption(image, caption_type):
17
  image = vis_processors["eval"](image).unsqueeze(0).to(device)
18
+
19
  if caption_type == "Beam Search":
20
  caption = model.generate({"image": image})
21
  else:
22
+ caption = model.generate(
23
+ {"image": image}, use_nucleus_sampling=True, num_captions=3
24
+ )
25
+
26
+ caption = "\n".join(caption)
27
+
28
  return caption
29
 
30
 
31
+ def chat(input_image, question, history):
32
+ history = history or []
33
+ question = question.lower()
34
+
35
+ image = vis_processors["eval"](input_image).unsqueeze(0).to(device)
36
+
37
+ clean = lambda x: x.replace("<p>", "").replace("</p>", "").replace("\n", "")
38
+ clean_h = lambda x: (clean(x[0]), clean(x[1]))
39
+ context = list(map(clean_h, history))
40
+ template = "Question: {} Answer: {}."
41
+ prompt = (
42
+ " ".join(
43
+ [template.format(context[i][0], context[i][1]) for i in range(len(context))]
44
+ )
45
+ + " Question: "
46
+ + question
47
+ + " Answer:"
48
+ )
49
+
50
+ response = model.generate({"image": image, "prompt": prompt})
51
+ history.append((question, response[0]))
52
+
53
+ return history, history
54
+
55
+
56
+ def clear_chat(history):
57
+ return [], []
58
+
59
+
60
  with gr.Blocks() as demo:
61
+ gr.Markdown("# BLIP-2")
62
+ gr.Markdown(
63
+ "## Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models"
64
+ )
65
+ gr.Markdown(
66
+ "This demo uses `OPT2.7B` weights. For more information please see [Github](https://github.com/salesforce/LAVIS/tree/main/projects/blip2) or [Paper](https://arxiv.org/abs/2301.12597)."
67
+ )
68
+
69
  with gr.Row():
70
  with gr.Column():
71
  input_image = gr.Image(label="Image", type="pil")
72
+ caption_type = gr.Radio(
73
+ ["Beam Search", "Nucleus Sampling"],
74
+ label="Caption Type",
75
+ value="Beam Search",
76
+ )
77
  btn_caption = gr.Button("Generate Caption")
78
+ output_text = gr.Textbox(label="Answer", lines=5)
79
+
80
+ with gr.Column():
81
+ chatbot = gr.Chatbot().style(color_map=("green", "pink"))
82
+ chat_state = gr.State()
83
+
84
  question_txt = gr.Textbox(label="Question", lines=1)
85
  btn_answer = gr.Button("Generate Answer")
86
+ btn_clear = gr.Button("Clear Chat")
87
+
88
+ btn_caption.click(
89
+ generate_caption, inputs=[input_image, caption_type], outputs=[output_text]
90
+ )
91
+
92
+ btn_answer.click(
93
+ chat,
94
+ inputs=[input_image, question_txt, chat_state],
95
+ outputs=[chatbot, chat_state],
96
+ )
97
+
98
+ btn_clear.click(clear_chat, inputs=[chat_state], outputs=[chatbot, chat_state])
99
+
100
+ gr.Examples(
101
+ [["./merlion.png", "Beam Search", "which city is this?", None, None]],
102
+ inputs=[input_image, caption_type, question_txt, chat_state, chatbot],
103
+ )
104
+
105
+ demo.launch()