-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemotion_analyzer.py
More file actions
178 lines (146 loc) · 6.87 KB
/
emotion_analyzer.py
File metadata and controls
178 lines (146 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
Emotion Analyzer for Math Tutor Bot
Detects student emotions from text to provide adaptive tutoring responses
"""
from textblob import TextBlob
import re
class EmotionAnalyzer:
"""
Analyzes student text input to detect emotional state.
Uses sentiment analysis + keyword detection for better accuracy.
"""
def __init__(self):
# Keywords indicating different emotional states
self.frustration_keywords = [
"frustrated", "confusing", "confused", "don't understand",
"doesn't make sense", "give up", "too hard", "impossible",
"stuck", "lost", "hate", "stupid", "difficult"
]
self.anxiety_keywords = [
"worried", "nervous", "anxious", "scared", "afraid",
"test", "exam", "grade", "fail", "stress", "pressure"
]
self.confidence_keywords = [
"easy", "got it", "understand", "makes sense", "clear",
"know", "sure", "confident", "good", "great"
]
self.confusion_keywords = [
"confused", "don't get", "what does", "how do", "why",
"explain", "unclear", "lost", "help", "stuck"
]
def analyze(self, text):
"""
Analyze text and return emotional state with confidence score.
Returns:
dict: {
'emotion': str (frustrated, confused, confident, anxious, neutral),
'sentiment_score': float (-1 to 1),
'confidence': float (0 to 1),
'details': str (explanation)
}
"""
text_lower = text.lower()
# Get sentiment using TextBlob
blob = TextBlob(text)
sentiment_score = blob.sentiment.polarity # -1 (negative) to 1 (positive)
# Count keyword matches for each emotion
frustration_count = sum(1 for kw in self.frustration_keywords if kw in text_lower)
anxiety_count = sum(1 for kw in self.anxiety_keywords if kw in text_lower)
confidence_count = sum(1 for kw in self.confidence_keywords if kw in text_lower)
confusion_count = sum(1 for kw in self.confusion_keywords if kw in text_lower)
# Detect question patterns (often indicate confusion)
has_question = '?' in text or any(text_lower.startswith(q) for q in ['what', 'how', 'why', 'when', 'where'])
# Determine primary emotion
emotion = "neutral"
confidence = 0.5
details = "Student appears neutral"
# Frustration detection (negative sentiment + frustration keywords)
if frustration_count > 0 and sentiment_score < 0:
emotion = "frustrated"
confidence = min(0.9, 0.6 + (frustration_count * 0.15))
details = f"Detected frustration (keywords: {frustration_count}, sentiment: {sentiment_score:.2f})"
# Anxiety detection
elif anxiety_count > 0:
emotion = "anxious"
confidence = min(0.9, 0.5 + (anxiety_count * 0.2))
details = f"Detected anxiety (keywords: {anxiety_count})"
# Confusion detection (questions + confusion keywords)
elif confusion_count > 1 or (has_question and confusion_count > 0):
emotion = "confused"
confidence = min(0.85, 0.5 + (confusion_count * 0.15))
details = f"Detected confusion (keywords: {confusion_count}, has question: {has_question})"
# Confidence detection (positive sentiment + confidence keywords)
elif confidence_count > 0 and sentiment_score > 0.2:
emotion = "confident"
confidence = min(0.9, 0.6 + (confidence_count * 0.15))
details = f"Detected confidence (keywords: {confidence_count}, sentiment: {sentiment_score:.2f})"
# Fallback to sentiment-based detection
elif sentiment_score < -0.3:
emotion = "frustrated"
confidence = 0.6
details = f"Low sentiment detected ({sentiment_score:.2f})"
elif sentiment_score > 0.5:
emotion = "confident"
confidence = 0.65
details = f"High sentiment detected ({sentiment_score:.2f})"
return {
'emotion': emotion,
'sentiment_score': sentiment_score,
'confidence': confidence,
'details': details
}
def get_adaptive_prompt(self, emotion, base_prompt):
"""
Modify the system prompt based on detected emotion.
Args:
emotion: str (frustrated, confused, confident, anxious, neutral)
base_prompt: str (original system prompt)
Returns:
str: Modified system prompt
"""
emotion_prompts = {
'frustrated': (
base_prompt + " The student seems frustrated. Be extra patient and encouraging. "
"Break down concepts into smaller steps. Acknowledge their effort and remind them "
"that struggle is part of learning. Use simpler language and more examples."
),
'confused': (
base_prompt + " The student appears confused. Provide clearer explanations with "
"step-by-step breakdowns. Use analogies and real-world examples. Ask if they "
"understand each step before moving forward. Be ready to explain the same concept "
"in different ways."
),
'anxious': (
base_prompt + " The student seems anxious or worried. Be reassuring and supportive. "
"Remind them that making mistakes is normal and part of learning. Focus on building "
"confidence. Celebrate small wins. Reduce pressure by emphasizing understanding "
"over speed."
),
'confident': (
base_prompt + " The student appears confident and engaged. You can introduce "
"slightly more challenging concepts or ask thought-provoking questions. "
"Encourage them to explain their reasoning. Consider extension problems "
"or alternative approaches."
),
'neutral': base_prompt
}
return emotion_prompts.get(emotion, base_prompt)
# Convenience function for quick testing
if __name__ == "__main__":
analyzer = EmotionAnalyzer()
test_cases = [
"I don't understand this at all, it's so frustrating!",
"What does this mean? I'm confused about the steps.",
"I think I got it! That makes sense now.",
"I'm really worried about the test tomorrow.",
"Can you help me with this problem?",
]
print("Emotion Analyzer Test Cases")
print("=" * 60)
for text in test_cases:
result = analyzer.analyze(text)
print(f"\nText: {text}")
print(f"Emotion: {result['emotion']} (confidence: {result['confidence']:.2f})")
print(f"Sentiment: {result['sentiment_score']:.2f}")
print(f"Details: {result['details']}")
print("\n" + "=" * 60)