File size: 826 Bytes
0cdae6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from transformers import pipeline
import logging

logger = logging.getLogger("emotion_detection")
logger.setLevel(logging.INFO)

try:
    # Using a popular emotion detection model from Hugging Face
    emotion_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base", return_all_scores=False)
    logger.info("Emotion detection model initialized successfully")
except Exception as e:
    logger.warning(f"Failed to load emotion detection model: {e}")
    emotion_classifier = None

def get_primary_emotion(text):
    if not emotion_classifier:
        return "neutral"
    try:
        result = emotion_classifier(text)
        return result[0]["label"].lower()
    except Exception as e:
        logger.warning(f"Emotion detection failed: {e}")
        return "neutral"