JustKiddo commited on
Commit
005fe99
·
verified ·
1 Parent(s): 83ee1a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -121
app.py CHANGED
@@ -22,63 +22,9 @@ class BERTopicChatbot:
22
  def __init__(self, dataset_name, text_column, split="train", max_samples=10000):
23
  # Initialize BERT sentence transformer
24
  self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
25
-
26
- # Initialize label mapping
27
- self.label_mapping = {
28
- 0: 'BPD',
29
- 1: 'bipolar',
30
- 2: 'depression',
31
- 3: 'Anxiety',
32
- 4: 'schizophrenia',
33
- 5: 'mentalillness'
34
- }
35
-
36
- # Initialize comfort responses
37
- self.comfort_responses = {
38
- 'BPD': [
39
- "I understand BPD can be overwhelming. You're not alone in this journey.",
40
- "Your feelings are valid. BPD is challenging, but there are people who understand.",
41
- "Taking things one day at a time with BPD is okay. You're showing great strength."
42
- ],
43
- 'bipolar': [
44
- "Bipolar disorder can feel like a roller coaster. Remember, stability is possible.",
45
- "You're so strong for managing bipolar disorder. Take it one day at a time.",
46
- "Both the highs and lows are temporary. You've gotten through them before."
47
- ],
48
- 'depression': [
49
- "Depression is heavy, but you don't have to carry it alone.",
50
- "Even small steps forward are progress. You're doing better than you think.",
51
- "This feeling won't last forever. You've made it through difficult times before."
52
- ],
53
- 'Anxiety': [
54
- "Your anxiety doesn't define you. You're stronger than your fears.",
55
- "Remember to breathe. You're safe, and this feeling will pass.",
56
- "It's okay to take things at your own pace. You're handling this well."
57
- ],
58
- 'schizophrenia': [
59
- "You're not your diagnosis. You're a person first, and you matter.",
60
- "Managing schizophrenia takes incredible strength. You're doing well.",
61
- "There's support available, and you deserve all the help you need."
62
- ],
63
- 'mentalillness': [
64
- "Mental health challenges don't define your worth. You are valuable.",
65
- "Recovery isn't linear, and that's okay. Every step counts.",
66
- "You're not alone in this journey. There's a community that understands."
67
- ]
68
- }
69
-
70
- # Initialize metrics storage
71
- self.metrics_history = {
72
- 'similarities': deque(maxlen=100),
73
- 'response_times': deque(maxlen=100),
74
- 'token_counts': deque(maxlen=100),
75
- 'topics_accessed': {}
76
- }
77
-
78
  # Load dataset from Hugging Face
79
  try:
80
  dataset = load_dataset(dataset_name, split=split)
81
-
82
  # Convert to pandas DataFrame and sample if necessary
83
  if len(dataset) > max_samples:
84
  dataset = dataset.shuffle(seed=42).select(range(max_samples))
@@ -89,32 +35,23 @@ class BERTopicChatbot:
89
  if text_column not in self.df.columns:
90
  raise ValueError(f"Column '{text_column}' not found in dataset. Available columns: {self.df.columns}")
91
 
92
- # Initialize documents
93
  self.documents = self.df[text_column].tolist()
94
 
95
- # Create document embeddings
96
- self.doc_embeddings = self.sentence_model.encode(self.documents)
97
-
98
- # Initialize label-specific storage
99
- self.label_embeddings = {label: [] for label in self.label_mapping.values()}
100
- self.label_documents = {label: [] for label in self.label_mapping.values()}
101
-
102
- # Organize documents by label
103
- for idx, doc in enumerate(self.documents):
104
- label_idx = self.df['label'].iloc[idx]
105
- if label_idx in self.label_mapping:
106
- label = self.label_mapping[label_idx]
107
- self.label_embeddings[label].append(self.doc_embeddings[idx])
108
- self.label_documents[label].append(doc)
109
-
110
- # Convert to numpy arrays
111
- for label in self.label_mapping.values():
112
- self.label_embeddings[label] = np.array(self.label_embeddings[label])
113
-
114
  # Create and train BERTopic model
115
  self.topic_model = BERTopic(embedding_model=self.sentence_model)
116
  self.topics, self.probs = self.topic_model.fit_transform(self.documents)
117
 
 
 
 
 
 
 
 
 
 
 
 
118
  # Store dataset info
119
  self.dataset_info = {
120
  'name': dataset_name,
@@ -127,26 +64,6 @@ class BERTopicChatbot:
127
  st.error(f"Error loading dataset: {str(e)}")
128
  raise
129
 
130
- def classify_query(self, query_embedding, threshold=0.6):
131
- """
132
- Classify query by finding the label with highest similarity scores
133
- """
134
- label_scores = {}
135
-
136
- for label, embeddings in self.label_embeddings.items():
137
- if len(embeddings) > 0:
138
- similarities = cosine_similarity([query_embedding], embeddings)[0]
139
- # Take average of top 3 similarities
140
- label_scores[label] = np.mean(np.sort(similarities)[-3:])
141
-
142
- # Get label with highest score
143
- best_label = max(label_scores.items(), key=lambda x: x[1])
144
-
145
- # Return label only if similarity is above threshold
146
- if best_label[1] >= threshold:
147
- return best_label[0], best_label[1]
148
- return 'mentalillness', best_label[1] # Default to general category if uncertain
149
-
150
  def get_metrics_visualizations(self):
151
  """Generate visualizations for chatbot metrics"""
152
  # Similarity trend
@@ -220,48 +137,40 @@ class BERTopicChatbot:
220
  try:
221
  start_time = datetime.now()
222
 
223
- # Get most similar documents and label
224
- similar_docs, similarities, predicted_label = self.get_most_similar_document(user_query)
225
 
226
- # Get comfort response
227
- comfort_messages = self.comfort_responses[predicted_label]
228
- comfort_response = np.random.choice(comfort_messages)
229
 
230
- # Generate response based on similarity and classification
231
- if not similar_docs or (similarities and max(similarities) < 0.5):
232
- response = (f"I understand you might be experiencing challenges related to {predicted_label}. "
233
- f"{comfort_response}")
 
 
 
 
234
  else:
235
- relevant_info = similar_docs[0]
236
- response = f"{relevant_info}\n\n{comfort_response}"
237
 
238
  # Track metrics
239
  end_time = datetime.now()
 
 
 
 
240
  metrics = {
241
- 'similarity': float(max(similarities)) if similarities else 0.0,
242
  'response_time': (end_time - start_time).total_seconds(),
243
  'tokens': len(response.split()),
244
- 'detected_condition': predicted_label
245
  }
246
 
247
- # Update metrics history
248
- self._update_metrics(metrics)
249
-
250
  return response, metrics
251
 
252
  except Exception as e:
253
  return f"Error processing query: {str(e)}", {'error': str(e)}
254
-
255
- def _update_metrics(self, metrics):
256
- """Helper method to update metrics history"""
257
- self.metrics_history['similarities'].append(metrics['similarity'])
258
- self.metrics_history['response_times'].append(metrics['response_time'])
259
- self.metrics_history['token_counts'].append(metrics['tokens'])
260
-
261
- # Track condition access
262
- condition = metrics['detected_condition']
263
- self.metrics_history['topics_accessed'][condition] = \
264
- self.metrics_history['topics_accessed'].get(condition, 0) + 1
265
 
266
  def get_dataset_info(self):
267
  #Return information about the loaded dataset and metrics
 
22
  def __init__(self, dataset_name, text_column, split="train", max_samples=10000):
23
  # Initialize BERT sentence transformer
24
  self.sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # Load dataset from Hugging Face
26
  try:
27
  dataset = load_dataset(dataset_name, split=split)
 
28
  # Convert to pandas DataFrame and sample if necessary
29
  if len(dataset) > max_samples:
30
  dataset = dataset.shuffle(seed=42).select(range(max_samples))
 
35
  if text_column not in self.df.columns:
36
  raise ValueError(f"Column '{text_column}' not found in dataset. Available columns: {self.df.columns}")
37
 
 
38
  self.documents = self.df[text_column].tolist()
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  # Create and train BERTopic model
41
  self.topic_model = BERTopic(embedding_model=self.sentence_model)
42
  self.topics, self.probs = self.topic_model.fit_transform(self.documents)
43
 
44
+ # Create document embeddings for similarity search
45
+ self.doc_embeddings = self.sentence_model.encode(self.documents)
46
+
47
+ # Initialize metrics storage
48
+ self.metrics_history = {
49
+ 'similarities': deque(maxlen=100),
50
+ 'response_times': deque(maxlen=100),
51
+ 'token_counts': deque(maxlen=100),
52
+ 'topics_accessed': {}
53
+ }
54
+
55
  # Store dataset info
56
  self.dataset_info = {
57
  'name': dataset_name,
 
64
  st.error(f"Error loading dataset: {str(e)}")
65
  raise
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  def get_metrics_visualizations(self):
68
  """Generate visualizations for chatbot metrics"""
69
  # Similarity trend
 
137
  try:
138
  start_time = datetime.now()
139
 
140
+ # Get most similar documents
141
+ similar_docs, similarities = self.get_most_similar_document(user_query)
142
 
143
+ # Get topic for the query
144
+ query_topic, _ = self.topic_model.transform([user_query])
 
145
 
146
+ # Track topic access
147
+ topic_id = str(query_topic[0])
148
+ self.metrics_history['topics_accessed'][topic_id] = \
149
+ self.metrics_history['topics_accessed'].get(topic_id, 0) + 1
150
+
151
+ # If similarity is too low, return a default response
152
+ if max(similarities) < 0.2:
153
+ response = "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."
154
  else:
155
+ response = similar_docs[0]
 
156
 
157
  # Track metrics
158
  end_time = datetime.now()
159
+ self.metrics_history['similarities'].append(float(max(similarities)))
160
+ self.metrics_history['response_times'].append((end_time - start_time).total_seconds())
161
+ self.metrics_history['token_counts'].append(len(response.split()))
162
+
163
  metrics = {
164
+ 'similarity': float(max(similarities)),
165
  'response_time': (end_time - start_time).total_seconds(),
166
  'tokens': len(response.split()),
167
+ 'topic': topic_id
168
  }
169
 
 
 
 
170
  return response, metrics
171
 
172
  except Exception as e:
173
  return f"Error processing query: {str(e)}", {'error': str(e)}
 
 
 
 
 
 
 
 
 
 
 
174
 
175
  def get_dataset_info(self):
176
  #Return information about the loaded dataset and metrics