Spaces:
Sleeping
Sleeping
| 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() | |