JustKiddo commited on
Commit
ea1c43d
·
verified ·
1 Parent(s): 91c397e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -65
app.py CHANGED
@@ -227,87 +227,87 @@ def main():
227
  )
228
 
229
  if st.button("Load Dataset"):
230
- st.session_state.chatbot = None
231
- st.session_state.messages = []
232
- st.rerun() # Changed from experimental_rerun() to rerun()
 
 
 
 
 
233
 
234
- # Initialize or get chatbot from session state
235
  if 'chatbot' not in st.session_state:
236
- with st.spinner("Loading dataset and initializing model..."):
237
- try:
238
- st.session_state.chatbot = initialize_chatbot(
239
- dataset_name, text_column, split, max_samples
240
- )
241
- # Display dataset info
242
- info = st.session_state.chatbot.get_dataset_info()
243
- st.success(f"Successfully loaded {info['name']} dataset")
244
- st.info(f"Total documents: {info['total_documents']}\nTopics found: {info['topics_found']}")
245
- except Exception as e:
246
- st.error(f"Error initializing chatbot: {str(e)}")
247
- return
248
-
249
- chatbot = st.session_state.chatbot
250
 
251
  # Create tabs for chat and metrics
252
  chat_tab, metrics_tab = st.tabs(["Chat", "Metrics"])
253
 
254
  with chat_tab:
255
- # Initialize messages if not exists
256
- if 'messages' not in st.session_state:
257
- st.session_state.messages = []
258
-
259
- # Display chat messages
260
  for message in st.session_state.messages:
261
  with st.chat_message(message["role"]):
262
  st.markdown(message["content"])
263
 
264
- # User input
265
- if prompt := st.chat_input("Hãy nói đó..."):
266
- # Add user message to chat history
267
- st.session_state.messages.append({"role": "user", "content": prompt})
268
-
269
- # Display user message
270
- with st.chat_message("user"):
271
- st.markdown(prompt)
272
 
273
- # Get chatbot response and metrics
274
- response, metrics = chatbot.get_response(prompt)
275
 
276
- # Display chatbot response
277
- with st.chat_message("assistant"):
278
- st.markdown(response)
279
- with st.expander("Response Metrics"):
280
- st.json(metrics)
281
-
282
- # Add assistant message to chat history
283
- st.session_state.messages.append({"role": "assistant", "content": response})
 
284
 
285
  with metrics_tab:
286
- # Get and display visualizations
287
- fig_similarity, fig_response_time, fig_tokens, fig_topics = chatbot.get_metrics_visualizations()
288
-
289
- col1, col2 = st.columns(2)
290
- with col1:
291
- st.plotly_chart(fig_similarity, use_container_width=True)
292
- st.plotly_chart(fig_tokens, use_container_width=True)
293
-
294
- with col2:
295
- st.plotly_chart(fig_response_time, use_container_width=True)
296
- st.plotly_chart(fig_topics, use_container_width=True)
 
 
297
 
298
- # Add overall statistics
299
- st.subheader("Overall Statistics")
300
- if len(chatbot.metrics_history['similarities']) > 0:
301
- stats_col1, stats_col2, stats_col3 = st.columns(3)
302
- with stats_col1:
303
- st.metric("Avg Similarity",
304
- f"{np.mean(list(chatbot.metrics_history['similarities'])):.3f}")
305
- with stats_col2:
306
- st.metric("Avg Response Time",
307
- f"{np.mean(list(chatbot.metrics_history['response_times'])):.3f}s")
308
- with stats_col3:
309
- st.metric("Total Tokens Used",
310
- sum(chatbot.metrics_history['token_counts']))
 
 
 
 
 
 
 
311
 
312
  if __name__ == "__main__":
313
  main()
 
227
  )
228
 
229
  if st.button("Load Dataset"):
230
+ with st.spinner("Loading dataset and initializing model..."):
231
+ try:
232
+ st.session_state.chatbot = initialize_chatbot(
233
+ dataset_name, text_column, split, max_samples
234
+ )
235
+ st.success("Dataset loaded successfully!")
236
+ except Exception as e:
237
+ st.error(f"Error loading dataset: {str(e)}")
238
 
239
+ # Initialize session state variables if they don't exist
240
  if 'chatbot' not in st.session_state:
241
+ st.session_state.chatbot = None
242
+
243
+ if 'messages' not in st.session_state:
244
+ st.session_state.messages = []
 
 
 
 
 
 
 
 
 
 
245
 
246
  # Create tabs for chat and metrics
247
  chat_tab, metrics_tab = st.tabs(["Chat", "Metrics"])
248
 
249
  with chat_tab:
250
+ # Display existing messages
 
 
 
 
251
  for message in st.session_state.messages:
252
  with st.chat_message(message["role"]):
253
  st.markdown(message["content"])
254
 
255
+ # Only show chat input if chatbot is initialized
256
+ if st.session_state.chatbot is not None:
257
+ if prompt := st.chat_input("Hãy nói đó..."):
258
+ # Add user message
259
+ st.session_state.messages.append({"role": "user", "content": prompt})
260
+ with st.chat_message("user"):
261
+ st.markdown(prompt)
 
262
 
263
+ # Get chatbot response
264
+ response, metrics = st.session_state.chatbot.get_response(prompt)
265
 
266
+ # Add assistant response
267
+ with st.chat_message("assistant"):
268
+ st.markdown(response)
269
+ with st.expander("Response Metrics"):
270
+ st.json(metrics)
271
+
272
+ st.session_state.messages.append({"role": "assistant", "content": response})
273
+ else:
274
+ st.info("Please load a dataset first to start chatting.")
275
 
276
  with metrics_tab:
277
+ if st.session_state.chatbot is not None:
278
+ try:
279
+ # Get visualizations from session state chatbot
280
+ fig_similarity, fig_response_time, fig_tokens, fig_topics = st.session_state.chatbot.get_metrics_visualizations()
281
+
282
+ col1, col2 = st.columns(2)
283
+ with col1:
284
+ st.plotly_chart(fig_similarity, use_container_width=True)
285
+ st.plotly_chart(fig_tokens, use_container_width=True)
286
+
287
+ with col2:
288
+ st.plotly_chart(fig_response_time, use_container_width=True)
289
+ st.plotly_chart(fig_topics, use_container_width=True)
290
 
291
+ # Display statistics
292
+ st.subheader("Overall Statistics")
293
+ metrics_history = st.session_state.chatbot.metrics_history
294
+ if len(metrics_history['similarities']) > 0:
295
+ stats_col1, stats_col2, stats_col3 = st.columns(3)
296
+ with stats_col1:
297
+ st.metric("Avg Similarity",
298
+ f"{np.mean(list(metrics_history['similarities'])):.3f}")
299
+ with stats_col2:
300
+ st.metric("Avg Response Time",
301
+ f"{np.mean(list(metrics_history['response_times'])):.3f}s")
302
+ with stats_col3:
303
+ st.metric("Total Tokens Used",
304
+ sum(metrics_history['token_counts']))
305
+ else:
306
+ st.info("No chat history available yet. Start a conversation to see metrics.")
307
+ except Exception as e:
308
+ st.error(f"Error displaying metrics: {str(e)}")
309
+ else:
310
+ st.info("Please load a dataset first to view metrics.")
311
 
312
  if __name__ == "__main__":
313
  main()