Niki Zhang commited on
Commit
2367901
·
verified ·
1 Parent(s): 260b902

Create chatbox.py

Browse files

can select if use history

Files changed (1) hide show
  1. chatbox.py +229 -0
chatbox.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft
2
+ # Modified from Visual ChatGPT Project https://github.com/microsoft/TaskMatrix/blob/main/visual_chatgpt.py
3
+
4
+ import os
5
+ import gradio as gr
6
+ import re
7
+ import uuid
8
+ from PIL import Image, ImageDraw, ImageOps
9
+ import numpy as np
10
+ import argparse
11
+ import inspect
12
+
13
+ from langchain.agents.initialize import initialize_agent
14
+ from langchain.agents.tools import Tool
15
+ from langchain.chains.conversation.memory import ConversationBufferMemory
16
+ from langchain.llms.openai import OpenAI
17
+ import torch
18
+ from PIL import Image, ImageDraw, ImageOps
19
+ from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
20
+
21
+ VISUAL_CHATGPT_PREFIX = """
22
+ I want you act as Caption Anything Chatbox (short as CATchat), which is designed to be able to assist with a wide range of text and visual related tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. You are able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
23
+
24
+ As a language model, you can not directly read images, but can invoke VQA tool to indirectly understand pictures, by repeatly asking questions about the objects and scene of the image. You should carefully asking informative questions to maximize your information about this image content. Each image will have a file name formed as "chat_image/xxx.png", you are very strict to the file name and will never fabricate nonexistent files.
25
+
26
+ You have access to the following tools:"""
27
+
28
+
29
+ # TOOLS:
30
+ # ------
31
+
32
+ # Visual ChatGPT has access to the following tools:"""
33
+
34
+ VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
35
+
36
+ "Thought: Do I need to use a tool? Yes
37
+ Action: the action to take, should be one of [{tool_names}], remember the action must to be one tool
38
+ Action Input: the input to the action
39
+ Observation: the result of the action"
40
+
41
+ When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
42
+
43
+ "Thought: Do I need to use a tool? No
44
+ {ai_prefix}: [your response here]"
45
+
46
+ """
47
+
48
+ VISUAL_CHATGPT_SUFFIX = """
49
+ Begin Chatting!
50
+
51
+ Previous conversation history:
52
+ {chat_history}
53
+
54
+ New input: {input}
55
+ As a language model, you must repeatly to use VQA tools to observe images. You response should be consistent with the outputs of the VQA tool instead of imagination. Do not repeat asking the same question.
56
+
57
+ Thought: Do I need to use a tool? {agent_scratchpad} (You are strictly to use the aforementioned "Thought/Action/Action Input/Observation" format as the answer.)"""
58
+
59
+ os.makedirs('chat_image', exist_ok=True)
60
+
61
+
62
+ def prompts(name, description):
63
+ def decorator(func):
64
+ func.name = name
65
+ func.description = description
66
+ return func
67
+ return decorator
68
+
69
+ def cut_dialogue_history(history_memory, keep_last_n_words=500):
70
+ if history_memory is None or len(history_memory) == 0:
71
+ return history_memory
72
+ tokens = history_memory.split()
73
+ n_tokens = len(tokens)
74
+ print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")
75
+ if n_tokens < keep_last_n_words:
76
+ return history_memory
77
+ paragraphs = history_memory.split('\n')
78
+ last_n_tokens = n_tokens
79
+ while last_n_tokens >= keep_last_n_words:
80
+ last_n_tokens -= len(paragraphs[0].split(' '))
81
+ paragraphs = paragraphs[1:]
82
+ return '\n' + '\n'.join(paragraphs)
83
+
84
+ def get_new_image_name(folder='chat_image', func_name="update"):
85
+ this_new_uuid = str(uuid.uuid4())[:8]
86
+ new_file_name = f'{func_name}_{this_new_uuid}.png'
87
+ return os.path.join(folder, new_file_name)
88
+
89
+ class VisualQuestionAnswering:
90
+ def __init__(self, device):
91
+ print(f"Initializing VisualQuestionAnswering to {device}")
92
+ self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
93
+ self.device = device
94
+ self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
95
+ self.model = BlipForQuestionAnswering.from_pretrained(
96
+ "Salesforce/blip-vqa-base", torch_dtype=self.torch_dtype).to(self.device)
97
+ # self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-capfilt-large")
98
+ # self.model = BlipForQuestionAnswering.from_pretrained(
99
+ # "Salesforce/blip-vqa-capfilt-large", torch_dtype=self.torch_dtype).to(self.device)
100
+
101
+ @prompts(name="Answer Question About The Image",
102
+ description="VQA tool is useful when you need an answer for a question based on an image. "
103
+ "like: what is the color of an object, how many cats in this figure, where is the child sitting, what does the cat doing, why is he laughing."
104
+ "The input to this tool should be a comma separated string of two, representing the image path and the question.")
105
+ def inference(self, inputs):
106
+ image_path, question = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
107
+ raw_image = Image.open(image_path).convert('RGB')
108
+ inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device, self.torch_dtype)
109
+ out = self.model.generate(**inputs)
110
+ answer = self.processor.decode(out[0], skip_special_tokens=True)
111
+ print(f"\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, "
112
+ f"Output Answer: {answer}")
113
+ return answer
114
+
115
+ def build_chatbot_tools(load_dict):
116
+ print(f"Initializing ChatBot, load_dict={load_dict}")
117
+ models = {}
118
+ # Load Basic Foundation Models
119
+ for class_name, device in load_dict.items():
120
+ models[class_name] = globals()[class_name](device=device)
121
+
122
+ # Load Template Foundation Models
123
+ for class_name, module in globals().items():
124
+ if getattr(module, 'template_model', False):
125
+ template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}
126
+ loaded_names = set([type(e).__name__ for e in models.values()])
127
+ if template_required_names.issubset(loaded_names):
128
+ models[class_name] = globals()[class_name](
129
+ **{name: models[name] for name in template_required_names})
130
+
131
+ tools = []
132
+ for instance in models.values():
133
+ for e in dir(instance):
134
+ if e.startswith('inference'):
135
+ func = getattr(instance, e)
136
+ tools.append(Tool(name=func.name, description=func.description, func=func))
137
+ return tools
138
+
139
+ class ConversationBot:
140
+ def __init__(self, tools, api_key="",save_history=False):
141
+ # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}
142
+ llm = OpenAI(model_name="gpt-3.5-turbo", temperature=0.7, openai_api_key=api_key)
143
+ self.llm = llm
144
+ self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
145
+ self.tools = tools
146
+ self.current_image = None
147
+ self.point_prompt = ""
148
+ self.global_prompt = ""
149
+ self.save_history=save_history
150
+ self.agent = initialize_agent(
151
+ self.tools,
152
+ self.llm,
153
+ agent="conversational-react-description",
154
+ verbose=True,
155
+ memory=self.memory,
156
+ return_intermediate_steps=True,
157
+ agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS,
158
+ 'suffix': VISUAL_CHATGPT_SUFFIX}, )
159
+
160
+ def constructe_intermediate_steps(self, agent_res):
161
+ ans = []
162
+ for action, output in agent_res:
163
+ if hasattr(action, "tool_input"):
164
+ use_tool = "Yes"
165
+ act = (f"Thought: Do I need to use a tool? {use_tool}\nAction: {action.tool}\nAction Input: {action.tool_input}", f"Observation: {output}")
166
+ else:
167
+ use_tool = "No"
168
+ act = (f"Thought: Do I need to use a tool? {use_tool}", f"AI: {output}")
169
+ act= list(map(lambda x: x.replace('\n', '<br>'), act))
170
+ ans.append(act)
171
+ return ans
172
+
173
+ def run_text(self, text, state, aux_state):
174
+ if not self.save_history:
175
+ self.agent.memory.buffer = ""
176
+ else:
177
+ self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
178
+ if self.point_prompt != "":
179
+ Human_prompt = f'\nHuman: {self.point_prompt}\n'
180
+ AI_prompt = 'Ok'
181
+ self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
182
+ self.point_prompt = ""
183
+ res = self.agent({"input": text})
184
+ res['output'] = res['output'].replace("\\", "/")
185
+ response = re.sub('(chat_image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
186
+ state = state + [(text, response)]
187
+
188
+ aux_state = aux_state + [(f"User Input: {text}", None)]
189
+ aux_state = aux_state + self.constructe_intermediate_steps(res['intermediate_steps'])
190
+ print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"
191
+ f"Current Memory: {self.agent.memory.buffer}\n"
192
+ f"Aux state: {aux_state}\n"
193
+ )
194
+ return state, state, aux_state, aux_state
195
+
196
+
197
+ if __name__ == '__main__':
198
+ parser = argparse.ArgumentParser()
199
+ parser.add_argument('--load', type=str, default="VisualQuestionAnswering_cuda:0")
200
+ parser.add_argument('--port', type=int, default=1015)
201
+
202
+ args = parser.parse_args()
203
+ load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}
204
+ tools = build_chatbot_tools(load_dict)
205
+ bot = ConversationBot(tools)
206
+ with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
207
+ with gr.Row():
208
+ chatbot = gr.Chatbot(elem_id="chatbot", label="CATchat").style(height=1000,scale=0.5)
209
+ auxwindow = gr.Chatbot(elem_id="chatbot", label="Aux Window").style(height=1000,scale=0.5)
210
+ state = gr.State([])
211
+ aux_state = gr.State([])
212
+ with gr.Row():
213
+ with gr.Column(scale=0.7):
214
+ txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(
215
+ container=False)
216
+ with gr.Column(scale=0.15, min_width=0):
217
+ clear = gr.Button("Clear")
218
+ with gr.Column(scale=0.15, min_width=0):
219
+ btn = gr.UploadButton("Upload", file_types=["image"])
220
+
221
+ txt.submit(bot.run_text, [txt, state, aux_state], [chatbot, state, aux_state, auxwindow])
222
+ txt.submit(lambda: "", None, txt)
223
+ btn.upload(bot.run_image, [btn, state, txt, aux_state], [chatbot, state, txt, aux_state, auxwindow])
224
+ clear.click(bot.memory.clear)
225
+ clear.click(lambda: [], None, chatbot)
226
+ clear.click(lambda: [], None, auxwindow)
227
+ clear.click(lambda: [], None, state)
228
+ clear.click(lambda: [], None, aux_state)
229
+ demo.launch(server_name="0.0.0.0", server_port=args.port, share=True)