Baobab4983 commited on
Commit
6ec55cf
·
1 Parent(s): af9245f

My initial chatbot

Browse files
Files changed (1) hide show
  1. app.py +91 -45
app.py CHANGED
@@ -62,65 +62,111 @@ css = """
62
  }
63
  """
64
 
65
-
66
- # gradio chatbot main function
67
  def registry(name, token, examples=None, **kwargs):
68
  client = genai.Client(api_key=token)
69
- chat = client.chats.create(
 
 
 
 
 
 
70
  model=name,
71
  config=types.GenerateContentConfig(
72
- system_instruction=system_instruction,
73
- temperature=0.5,
74
  ),
75
- )
 
76
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- # send user message to Gemini and append the answer at the chatbot history
79
- def llm_response(history, text, img):
80
- if not img:
81
- response = chat.send_message(text)
82
- history += [(None, response.text)]
83
- return history, "", None
84
- if img:
85
  try:
86
- img = Image.open(img)
87
- response = chat.send_message([text, img])
88
- history += [(None, response.text)]
89
- return history, "", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  except Exception as e:
91
- print("something wrong happened at the llm_response call")
92
- print(str(e))
93
- return history, "", None
94
 
95
- # instantiate the gradio chatbot
96
  print("Building the gradio app...")
97
  with gr.Blocks(css=css) as app:
98
- gr.HTML(TITLE)
99
- gr.HTML(SUBTITLE)
100
- with gr.Row():
101
- # define the input fields - image input
102
- image_box = gr.Image(type="filepath")
103
- chatbot = gr.Chatbot(
104
- scale=2,
105
- height=500,
106
- container=True
107
- )
108
-
109
- # define the input fields - text input
110
- text_box = gr.Textbox(
111
- placeholder="Type your message and press enter and optionally upload an image",
112
- container=False,
113
  )
114
 
115
- # define the main chatbot logic
116
- btn = gr.Button("Send")
117
- clicked = btn.click(query_message,
118
- [chatbot,text_box,image_box],
119
- [chatbot]
120
- ).then(llm_response,
121
- [chatbot,text_box,image_box],
122
- [chatbot, text_box, image_box]
123
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  return app
125
 
126
  if __name__ == "__main__":
 
62
  }
63
  """
64
 
65
+ # initialize the chat model and sets up the Gradio interface
 
66
  def registry(name, token, examples=None, **kwargs):
67
  client = genai.Client(api_key=token)
68
+ chat_locks = {} # Dictionary to hold locks for each user's chat
69
+ chat_sessions = {} # Dictionary to hold each user chat
70
+
71
+
72
+ # create a new chat session with the specified model and configuration
73
+ def create_chat():
74
+ return client.chats.create(
75
  model=name,
76
  config=types.GenerateContentConfig(
77
+ system_instruction=system_instruction,
78
+ temperature=0.5,
79
  ),
80
+ )
81
+
82
 
83
+ # send a user message to Gemini, streams the response back to the chatbot
84
+ # and updates the history
85
+ def stream_response(history, text, img, request: gr.Request):
86
+ user_id = request.client.host
87
+ if user_id not in chat_locks:
88
+ chat_locks[user_id] = Lock()
89
+ chat_sessions[user_id] = create_chat()
90
+
91
+ lock = chat_locks[user_id]
92
+ chat = chat_sessions[user_id]
93
 
 
 
 
 
 
 
 
94
  try:
95
+ with lock:
96
+ if not img:
97
+ response_stream = chat.send_message_stream(text)
98
+ else:
99
+ try:
100
+ img = Image.open(img)
101
+ response_stream = chat.send_message_stream([text, img])
102
+ except Exception as e:
103
+ print(f"Error processing image: {str(e)}")
104
+ return
105
+
106
+ partial_message = ""
107
+ for chunk in response_stream:
108
+ if chunk.text:
109
+ partial_message += chunk.text
110
+ history[-1] = (history[-1][0], partial_message)
111
+ yield history
112
+ time.sleep(0.02) # Small delay to ensure smooth streaming
113
+
114
  except Exception as e:
115
+ print(f"Error in stream_response: {str(e)}")
116
+ return
 
117
 
 
118
  print("Building the gradio app...")
119
  with gr.Blocks(css=css) as app:
120
+ gr.HTML(TITLE)
121
+ gr.HTML(SUBTITLE)
122
+
123
+ with gr.Row():
124
+ image_box = gr.Image(type="filepath")
125
+ chatbot = gr.Chatbot(
126
+ scale=2,
127
+ height=500,
128
+ container=True
 
 
 
 
 
 
129
  )
130
 
131
+ text_box = gr.Textbox(
132
+ placeholder="Type your message and press enter and optionally upload an image",
133
+ container=False,
134
+ )
135
+
136
+ btn = gr.Button("Send")
137
+
138
+ # Update the event handlers to use streaming
139
+ btn.click(
140
+ fn=query_message,
141
+ inputs=[chatbot, text_box, image_box],
142
+ outputs=[chatbot],
143
+ ).then(
144
+ fn=stream_response,
145
+ inputs=[chatbot, text_box, image_box],
146
+ outputs=[chatbot],
147
+ api_name="stream_response"
148
+ ).then(
149
+ fn=lambda: (None, ""), # Clear the image and text inputs after sending
150
+ inputs=None,
151
+ outputs=[image_box, text_box],
152
+ )
153
+
154
+ # Add enter key handler
155
+ text_box.submit(
156
+ fn=query_message,
157
+ inputs=[chatbot, text_box, image_box],
158
+ outputs=[chatbot],
159
+ ).then(
160
+ fn=stream_response,
161
+ inputs=[chatbot, text_box, image_box],
162
+ outputs=[chatbot],
163
+ api_name="stream_response"
164
+ ).then(
165
+ fn=lambda: (None, ""), # Clear the image and text inputs after sending
166
+ inputs=None,
167
+ outputs=[image_box, text_box],
168
+ )
169
+
170
  return app
171
 
172
  if __name__ == "__main__":