File size: 2,469 Bytes
5e0532d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Dict

class EmotionService:
    def __init__(self):
        self.positive_keywords = {
            "happy", "joy", "blessed", "grateful", "peace", "hope", "love", 
            "excited", "good", "great", "wonderful", "calm", "content"
        }
        self.negative_keywords = {
            "sad", "depressed", "anxious", "afraid", "scared", "fear", 
            "lonely", "hurt", "pain", "grief", "broken", "suffering", 
            "angry", "mad", "upset", "bad", "terrible", "hate"
        }
        self.high_distress_keywords = {
            "kill", "suicide", "die", "end it all", "hopeless", "worthless",
            "unbearable", "can't go on", "no way out"
        }

    async def analyze_tone(self, text: str) -> Dict[str, any]:
        """
        Returns sentiment and emotional intensity.
        """
        text_lower = text.lower()
        words = text_lower.split()
        total_words = len(words) if words else 1
        
        pos_count = sum(1 for word in words if word in self.positive_keywords)
        neg_count = sum(1 for word in words if word in self.negative_keywords)
        
        # Determine sentiment
        if pos_count > neg_count:
            sentiment = "positive"
        elif neg_count > pos_count:
            sentiment = "negative"
        else:
            sentiment = "neutral"
            
        # Calculate intensity (simple heuristic: fraction of emotional words)
        emotional_word_count = pos_count + neg_count
        # Normalize intensity to be somewhat reasonable (0.0 to 1.0)
        # Assuming if 30% of words are emotional, it's very intense.
        raw_intensity = emotional_word_count / total_words
        intensity = min(raw_intensity * 3.0, 1.0) 
        
        return {
            "sentiment": sentiment, 
            "intensity": round(intensity, 2),
            "pos_count": pos_count,
            "neg_count": neg_count
        }

    def is_distress_high(self, text: str, emotion_data: Dict[str, any]) -> bool:
        text_lower = text.lower()
        
        # Check for specific trigger words
        for keyword in self.high_distress_keywords:
            if keyword in text_lower:
                return True
                
        # Check for high negative intensity
        if emotion_data.get("sentiment") == "negative" and emotion_data.get("intensity", 0) > 0.8:
            return True
            
        return False

emotion_service = EmotionService()