Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,15 +5,43 @@ from sentence_transformers import SentenceTransformer
|
|
| 5 |
import numpy as np
|
| 6 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
class BERTopicChatbot:
|
| 10 |
-
def __init__(self,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# Initialize BERT sentence transformer
|
| 12 |
self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 13 |
|
| 14 |
-
# Load
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
# Create and train BERTopic model
|
| 19 |
self.topic_model = BERTopic(embedding_model=self.sentence_model)
|
|
@@ -21,74 +49,146 @@ class BERTopicChatbot:
|
|
| 21 |
|
| 22 |
# Create document embeddings for similarity search
|
| 23 |
self.doc_embeddings = self.sentence_model.encode(self.documents)
|
| 24 |
-
|
| 25 |
-
def get_most_similar_document(self, query, top_k=3):
|
| 26 |
-
# Encode the query
|
| 27 |
-
query_embedding = self.sentence_model.encode([query])[0]
|
| 28 |
-
|
| 29 |
-
# Calculate similarities
|
| 30 |
-
similarities = cosine_similarity([query_embedding], self.doc_embeddings)[0]
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
# Get topic for the query
|
| 43 |
-
query_topic, _ = self.topic_model.transform([user_query])
|
| 44 |
-
|
| 45 |
-
# If similarity is too low, return a default response
|
| 46 |
-
if max(similarities) < 0.5:
|
| 47 |
-
return "Xin lỗi, tôi không có đủ thông tin để trả lời câu hỏi này một cách chính xác."
|
| 48 |
-
|
| 49 |
-
# Construct response using the most similar document
|
| 50 |
-
response = similar_docs[0]
|
| 51 |
-
|
| 52 |
-
return response
|
| 53 |
|
| 54 |
@st.cache_resource
|
| 55 |
-
def initialize_chatbot():
|
| 56 |
-
return BERTopicChatbot(
|
| 57 |
|
| 58 |
def main():
|
| 59 |
st.title("🤖 Trợ Lý AI - BERTopic")
|
| 60 |
st.caption("Trò chuyện với chúng mình nhé!")
|
| 61 |
|
| 62 |
-
#
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
|
| 66 |
-
if 'messages' not in st.session_state:
|
| 67 |
-
st.session_state.messages = []
|
| 68 |
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
with st.chat_message(message["role"]):
|
| 72 |
-
st.markdown(message["content"])
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
# Display
|
| 80 |
-
|
| 81 |
-
st.
|
|
|
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
# Add
|
| 91 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
if __name__ == "__main__":
|
| 94 |
main()
|
|
|
|
| 5 |
import numpy as np
|
| 6 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
import pandas as pd
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import json
|
| 11 |
+
from collections import deque
|
| 12 |
+
from datasets import load_dataset
|
| 13 |
|
| 14 |
class BERTopicChatbot:
|
| 15 |
+
def __init__(self, dataset_name, text_column, split="train", max_samples=10000):
|
| 16 |
+
"""
|
| 17 |
+
Initialize chatbot with a Hugging Face dataset
|
| 18 |
+
dataset_name: name of the dataset on Hugging Face (e.g., 'vietnam/legal')
|
| 19 |
+
text_column: name of the column containing the text data
|
| 20 |
+
split: which split of the dataset to use ('train', 'test', 'validation')
|
| 21 |
+
max_samples: maximum number of samples to use (to manage memory)
|
| 22 |
+
"""
|
| 23 |
# Initialize BERT sentence transformer
|
| 24 |
self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 25 |
|
| 26 |
+
# Load dataset from Hugging Face
|
| 27 |
+
try:
|
| 28 |
+
dataset = load_dataset(dataset_name, split=split)
|
| 29 |
+
|
| 30 |
+
# Convert to pandas DataFrame and sample if necessary
|
| 31 |
+
if len(dataset) > max_samples:
|
| 32 |
+
dataset = dataset.shuffle(seed=42).select(range(max_samples))
|
| 33 |
+
|
| 34 |
+
self.df = dataset.to_pandas()
|
| 35 |
+
|
| 36 |
+
# Ensure text column exists
|
| 37 |
+
if text_column not in self.df.columns:
|
| 38 |
+
raise ValueError(f"Column '{text_column}' not found in dataset. Available columns: {self.df.columns}")
|
| 39 |
+
|
| 40 |
+
self.documents = self.df[text_column].tolist()
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
st.error(f"Error loading dataset: {str(e)}")
|
| 44 |
+
raise
|
| 45 |
|
| 46 |
# Create and train BERTopic model
|
| 47 |
self.topic_model = BERTopic(embedding_model=self.sentence_model)
|
|
|
|
| 49 |
|
| 50 |
# Create document embeddings for similarity search
|
| 51 |
self.doc_embeddings = self.sentence_model.encode(self.documents)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Initialize metrics storage
|
| 54 |
+
self.metrics_history = {
|
| 55 |
+
'similarities': deque(maxlen=100),
|
| 56 |
+
'response_times': deque(maxlen=100),
|
| 57 |
+
'token_counts': deque(maxlen=100),
|
| 58 |
+
'topics_accessed': {}
|
| 59 |
+
}
|
| 60 |
|
| 61 |
+
# Store dataset info
|
| 62 |
+
self.dataset_info = {
|
| 63 |
+
'name': dataset_name,
|
| 64 |
+
'split': split,
|
| 65 |
+
'total_documents': len(self.documents),
|
| 66 |
+
'topics_found': len(set(self.topics))
|
| 67 |
+
}
|
| 68 |
|
| 69 |
+
# ... [Previous methods remain the same] ...
|
| 70 |
+
|
| 71 |
+
def get_dataset_info(self):
|
| 72 |
+
"""Return information about the loaded dataset"""
|
| 73 |
+
return self.dataset_info
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
@st.cache_resource
|
| 76 |
+
def initialize_chatbot(dataset_name, text_column, split="train", max_samples=10000):
|
| 77 |
+
return BERTopicChatbot(dataset_name, text_column, split, max_samples)
|
| 78 |
|
| 79 |
def main():
|
| 80 |
st.title("🤖 Trợ Lý AI - BERTopic")
|
| 81 |
st.caption("Trò chuyện với chúng mình nhé!")
|
| 82 |
|
| 83 |
+
# Dataset selection sidebar
|
| 84 |
+
with st.sidebar:
|
| 85 |
+
st.header("Dataset Configuration")
|
| 86 |
+
dataset_name = st.text_input(
|
| 87 |
+
"Hugging Face Dataset Name",
|
| 88 |
+
value="vietnam/legal",
|
| 89 |
+
help="Enter the name of a dataset from Hugging Face (e.g., 'vietnam/legal')"
|
| 90 |
+
)
|
| 91 |
+
text_column = st.text_input(
|
| 92 |
+
"Text Column Name",
|
| 93 |
+
value="text",
|
| 94 |
+
help="Enter the name of the column containing the text data"
|
| 95 |
+
)
|
| 96 |
+
split = st.selectbox(
|
| 97 |
+
"Dataset Split",
|
| 98 |
+
options=["train", "test", "validation"],
|
| 99 |
+
index=0
|
| 100 |
+
)
|
| 101 |
+
max_samples = st.number_input(
|
| 102 |
+
"Maximum Samples",
|
| 103 |
+
min_value=100,
|
| 104 |
+
max_value=100000,
|
| 105 |
+
value=10000,
|
| 106 |
+
step=1000,
|
| 107 |
+
help="Maximum number of samples to load from the dataset"
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if st.button("Load Dataset"):
|
| 111 |
+
st.session_state.chatbot = None
|
| 112 |
+
st.session_state.messages = []
|
| 113 |
+
st.experimental_rerun()
|
| 114 |
+
|
| 115 |
+
# Initialize or get chatbot from session state
|
| 116 |
+
if 'chatbot' not in st.session_state:
|
| 117 |
+
with st.spinner("Loading dataset and initializing model..."):
|
| 118 |
+
try:
|
| 119 |
+
st.session_state.chatbot = initialize_chatbot(
|
| 120 |
+
dataset_name, text_column, split, max_samples
|
| 121 |
+
)
|
| 122 |
+
# Display dataset info
|
| 123 |
+
info = st.session_state.chatbot.get_dataset_info()
|
| 124 |
+
st.success(f"Successfully loaded {info['name']} dataset")
|
| 125 |
+
st.info(f"Total documents: {info['total_documents']}\nTopics found: {info['topics_found']}")
|
| 126 |
+
except Exception as e:
|
| 127 |
+
st.error(f"Error initializing chatbot: {str(e)}")
|
| 128 |
+
return
|
| 129 |
|
| 130 |
+
chatbot = st.session_state.chatbot
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
# Create tabs for chat and metrics
|
| 133 |
+
chat_tab, metrics_tab = st.tabs(["Chat", "Metrics"])
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
with chat_tab:
|
| 136 |
+
# Initialize messages if not exists
|
| 137 |
+
if 'messages' not in st.session_state:
|
| 138 |
+
st.session_state.messages = []
|
| 139 |
+
|
| 140 |
+
# Display chat messages
|
| 141 |
+
for message in st.session_state.messages:
|
| 142 |
+
with st.chat_message(message["role"]):
|
| 143 |
+
st.markdown(message["content"])
|
| 144 |
|
| 145 |
+
# User input
|
| 146 |
+
if prompt := st.chat_input("Hãy nói gì đó..."):
|
| 147 |
+
# Add user message to chat history
|
| 148 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 149 |
+
|
| 150 |
+
# Display user message
|
| 151 |
+
with st.chat_message("user"):
|
| 152 |
+
st.markdown(prompt)
|
| 153 |
+
|
| 154 |
+
# Get chatbot response and metrics
|
| 155 |
+
response, metrics = chatbot.get_response(prompt)
|
| 156 |
+
|
| 157 |
+
# Display chatbot response
|
| 158 |
+
with st.chat_message("assistant"):
|
| 159 |
+
st.markdown(response)
|
| 160 |
+
with st.expander("Response Metrics"):
|
| 161 |
+
st.json(metrics)
|
| 162 |
|
| 163 |
+
# Add assistant message to chat history
|
| 164 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 165 |
+
|
| 166 |
+
with metrics_tab:
|
| 167 |
+
# Get and display visualizations
|
| 168 |
+
fig_similarity, fig_response_time, fig_tokens, fig_topics = chatbot.get_metrics_visualizations()
|
| 169 |
+
|
| 170 |
+
col1, col2 = st.columns(2)
|
| 171 |
+
with col1:
|
| 172 |
+
st.plotly_chart(fig_similarity, use_container_width=True)
|
| 173 |
+
st.plotly_chart(fig_tokens, use_container_width=True)
|
| 174 |
+
|
| 175 |
+
with col2:
|
| 176 |
+
st.plotly_chart(fig_response_time, use_container_width=True)
|
| 177 |
+
st.plotly_chart(fig_topics, use_container_width=True)
|
| 178 |
|
| 179 |
+
# Add overall statistics
|
| 180 |
+
st.subheader("Overall Statistics")
|
| 181 |
+
if len(chatbot.metrics_history['similarities']) > 0:
|
| 182 |
+
stats_col1, stats_col2, stats_col3 = st.columns(3)
|
| 183 |
+
with stats_col1:
|
| 184 |
+
st.metric("Avg Similarity",
|
| 185 |
+
f"{np.mean(list(chatbot.metrics_history['similarities'])):.3f}")
|
| 186 |
+
with stats_col2:
|
| 187 |
+
st.metric("Avg Response Time",
|
| 188 |
+
f"{np.mean(list(chatbot.metrics_history['response_times'])):.3f}s")
|
| 189 |
+
with stats_col3:
|
| 190 |
+
st.metric("Total Tokens Used",
|
| 191 |
+
sum(chatbot.metrics_history['token_counts']))
|
| 192 |
|
| 193 |
if __name__ == "__main__":
|
| 194 |
main()
|