chasetank commited on
Commit
70beac5
1 Parent(s): 00a12d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -28
app.py CHANGED
@@ -1,28 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  VISUAL_CHATGPT_PREFIX = """Visual ChatGPT 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. Visual ChatGPT is 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.
2
-
3
  Visual ChatGPT is able to process and understand large amounts of text and image. As a language model, Visual ChatGPT can not directly read images, but it has a list of tools to finish different visual tasks. Each image will have a file name formed as "image/xxx.png", and Visual ChatGPT can invoke different tools to indirectly understand pictures. When talking about images, Visual ChatGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, Visual ChatGPT is also known that the image may not be the same as user's demand, and will use other visual question answering tools or description tools to observe the real image. Visual ChatGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.
4
-
5
  Human may provide new figures to Visual ChatGPT with a description. The description helps Visual ChatGPT to understand this image, but Visual ChatGPT should use tools to finish following tasks, rather than directly imagine from the description.
6
-
7
  Overall, Visual ChatGPT is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.
8
-
9
-
10
  TOOLS:
11
  ------
12
-
13
  Visual ChatGPT has access to the following tools:"""
14
 
15
  VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
16
-
17
  ```
18
  Thought: Do I need to use a tool? Yes
19
  Action: the action to take, should be one of [{tool_names}]
20
  Action Input: the input to the action
21
  Observation: the result of the action
22
  ```
23
-
24
  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:
25
-
26
  ```
27
  Thought: Do I need to use a tool? No
28
  {ai_prefix}: [your response here]
@@ -31,12 +60,9 @@ Thought: Do I need to use a tool? No
31
 
32
  VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if not exists.
33
  You will remember to provide the image file name loyally if it's provided in the last tool observation.
34
-
35
  Begin!
36
-
37
  Previous conversation history:
38
  {chat_history}
39
-
40
  New input: {input}
41
  Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
42
  The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human.
@@ -73,7 +99,7 @@ class ConversationBot:
73
  print(f"Initializing VisualChatGPT, load_dict={load_dict}")
74
  if 'ImageCaptioning' not in load_dict:
75
  raise ValueError("You have to load ImageCaptioning as a basic function for VisualChatGPT")
76
-
77
  self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
78
  self.models = dict()
79
  for class_name, device in load_dict.items():
@@ -85,18 +111,6 @@ class ConversationBot:
85
  if e.startswith('inference'):
86
  func = getattr(instance, e)
87
  self.tools.append(Tool(name=func.name, description=func.description, func=func))
88
- self.llm = OpenAI(
89
- temperature=0, openai_api_key=os.environ['OPENAI_API_KEY']
90
- )
91
-
92
- self.agent = initialize_agent(
93
- self.tools,
94
- self.llm,
95
- agent="conversational-react-description",
96
- verbose=True,
97
- memory=self.memory,
98
- return_intermediate_steps=True,
99
- agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}, )
100
 
101
  def run_text(self, text, state):
102
  self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
@@ -130,6 +144,18 @@ class ConversationBot:
130
  f"Current Memory: {self.agent.memory.buffer}")
131
  return state, state, f'{txt} {image_filename} '
132
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  bot = ConversationBot({'Text2Image': 'cuda:0',
135
  'ImageCaptioning': 'cuda:0',
@@ -145,7 +171,13 @@ bot = ConversationBot({'Text2Image': 'cuda:0',
145
  with gr.Blocks(css="#chatbot {overflow:auto; height:500px;}") as demo:
146
  gr.Markdown("<h3><center>Visual ChatGPT</center></h3>")
147
 
148
-
 
 
 
 
 
 
149
 
150
  chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
151
  state = gr.State([])
@@ -179,7 +211,6 @@ with gr.Blocks(css="#chatbot {overflow:auto; height:500px;}") as demo:
179
  <a href="https://huggingface.co/spaces/microsoft/visual_chatgpt?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
180
  </center>''')
181
 
182
-
183
  bot.init_agent()
184
  txt.submit(bot.run_text, [txt, state], [chatbot, state])
185
  txt.submit(lambda: "", None, txt)
@@ -190,4 +221,5 @@ with gr.Blocks(css="#chatbot {overflow:auto; height:500px;}") as demo:
190
  clear.click(lambda: [], None, chatbot)
191
  clear.click(lambda: [], None, state)
192
 
193
- demo.queue(concurrency_count=10).launch(server_name="0.0.0.0", server_port=7860)
 
 
1
+ Hugging Face's logo
2
+ Hugging Face
3
+ Search models, datasets, users...
4
+ Models
5
+ Datasets
6
+ Spaces
7
+ Docs
8
+ Solutions
9
+ Pricing
10
+
11
+
12
+
13
+ Spaces:
14
+
15
+ microsoft
16
+ /
17
+ visual_chatgpt Copied
18
+ like
19
+ 280
20
+ App
21
+ Files and versions
22
+ Community
23
+ 6
24
+ visual_chatgpt
25
+ /
26
+ app.py
27
+ yinsming's picture
28
+ yinsming
29
+ update app
30
+ 811467e
31
+ 4 days ago
32
+ raw
33
+ history
34
+ blame
35
+ contribute
36
+ delete
37
+ No virus
38
+ 10.9 kB
39
  VISUAL_CHATGPT_PREFIX = """Visual ChatGPT 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. Visual ChatGPT is 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.
 
40
  Visual ChatGPT is able to process and understand large amounts of text and image. As a language model, Visual ChatGPT can not directly read images, but it has a list of tools to finish different visual tasks. Each image will have a file name formed as "image/xxx.png", and Visual ChatGPT can invoke different tools to indirectly understand pictures. When talking about images, Visual ChatGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, Visual ChatGPT is also known that the image may not be the same as user's demand, and will use other visual question answering tools or description tools to observe the real image. Visual ChatGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.
 
41
  Human may provide new figures to Visual ChatGPT with a description. The description helps Visual ChatGPT to understand this image, but Visual ChatGPT should use tools to finish following tasks, rather than directly imagine from the description.
 
42
  Overall, Visual ChatGPT is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.
 
 
43
  TOOLS:
44
  ------
 
45
  Visual ChatGPT has access to the following tools:"""
46
 
47
  VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
 
48
  ```
49
  Thought: Do I need to use a tool? Yes
50
  Action: the action to take, should be one of [{tool_names}]
51
  Action Input: the input to the action
52
  Observation: the result of the action
53
  ```
 
54
  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:
 
55
  ```
56
  Thought: Do I need to use a tool? No
57
  {ai_prefix}: [your response here]
 
60
 
61
  VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if not exists.
62
  You will remember to provide the image file name loyally if it's provided in the last tool observation.
 
63
  Begin!
 
64
  Previous conversation history:
65
  {chat_history}
 
66
  New input: {input}
67
  Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
68
  The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human.
 
99
  print(f"Initializing VisualChatGPT, load_dict={load_dict}")
100
  if 'ImageCaptioning' not in load_dict:
101
  raise ValueError("You have to load ImageCaptioning as a basic function for VisualChatGPT")
102
+
103
  self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
104
  self.models = dict()
105
  for class_name, device in load_dict.items():
 
111
  if e.startswith('inference'):
112
  func = getattr(instance, e)
113
  self.tools.append(Tool(name=func.name, description=func.description, func=func))
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  def run_text(self, text, state):
116
  self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
 
144
  f"Current Memory: {self.agent.memory.buffer}")
145
  return state, state, f'{txt} {image_filename} '
146
 
147
+ def init_agent(self, openai_api_key=os.environ['OPENAI_API_KEY']):
148
+ self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
149
+ self.agent = initialize_agent(
150
+ self.tools,
151
+ self.llm,
152
+ agent="conversational-react-description",
153
+ verbose=True,
154
+ memory=self.memory,
155
+ return_intermediate_steps=True,
156
+ agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}, )
157
+
158
+ return gr.update(visible = True)
159
 
160
  bot = ConversationBot({'Text2Image': 'cuda:0',
161
  'ImageCaptioning': 'cuda:0',
 
171
  with gr.Blocks(css="#chatbot {overflow:auto; height:500px;}") as demo:
172
  gr.Markdown("<h3><center>Visual ChatGPT</center></h3>")
173
 
174
+ with gr.Row():
175
+ openai_api_key_textbox = gr.Textbox(
176
+ placeholder="Paste your OpenAI API key here to start Visual ChatGPT(sk-...) and press Enter ↵️",
177
+ show_label=False,
178
+ lines=1,
179
+ type="password",
180
+ )
181
 
182
  chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
183
  state = gr.State([])
 
211
  <a href="https://huggingface.co/spaces/microsoft/visual_chatgpt?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
212
  </center>''')
213
 
 
214
  bot.init_agent()
215
  txt.submit(bot.run_text, [txt, state], [chatbot, state])
216
  txt.submit(lambda: "", None, txt)
 
221
  clear.click(lambda: [], None, chatbot)
222
  clear.click(lambda: [], None, state)
223
 
224
+ demo.queue(concurrency_count=10).launch(server_name="0.0.0.0", server_port=7860)
225
+