File size: 2,504 Bytes
227d279
ef82e95
 
227d279
ef82e95
 
 
 
 
 
227d279
ef82e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227d279
ef82e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227d279
ef82e95
 
 
 
 
 
 
 
 
 
 
227d279
ef82e95
227d279
 
ef82e95
227d279
 
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
import gradio as gr
from transformers import pipeline
import numpy as np

# Initialize the sentiment classifier
classifier = pipeline(
    "text-classification",
    model="SamLowe/roberta-base-go_emotions",
    top_k=None  # Return all emotions
)

def process_emotions(emotions):
    """Convert raw emotions to our application's format"""
    # Convert to dictionary format
    emotion_dict = {item['label']: float(item['score']) for item in emotions}
    
    # Find primary emotion
    primary_emotion = max(emotion_dict.items(), key=lambda x: x[1])
    
    # Calculate intensity
    max_score = primary_emotion[1]
    intensity = 'High' if max_score > 0.66 else 'Medium' if max_score > 0.33 else 'Low'
    
    # Check if needs attention
    needs_attention = (
        primary_emotion[0] in ['anger', 'anxiety', 'depression'] 
        and max_score > 0.5
    )
    
    return {
        'emotions': emotion_dict,
        'primaryEmotion': primary_emotion[0],
        'emotionalState': {
            'state': primary_emotion[0],
            'intensity': intensity,
            'needsAttention': needs_attention,
            'description': f"Detected {primary_emotion[0]} with {round(max_score * 100)}% confidence"
        },
        'success': True,
        'needsAttention': needs_attention
    }

def analyze_text(text):
    """Analyze text and return processed emotions"""
    if not text or not text.strip():
        return {
            'error': 'Please provide some text to analyze',
            'success': False
        }
    
    try:
        # Get raw emotions from model
        emotions = classifier(text)
        
        # Process emotions into our format
        result = process_emotions(emotions[0])
        
        return result
    except Exception as e:
        return {
            'error': str(e),
            'success': False
        }

# Create Gradio interface
demo = gr.Interface(
    fn=analyze_text,
    inputs=gr.Textbox(label="Enter text to analyze", lines=3),
    outputs=gr.JSON(label="Sentiment Analysis Results"),
    title="Mental Health Sentiment Analysis",
    description="Analyzes text for emotions related to mental health using the RoBERTa model.",
    examples=[
        ["I'm feeling really anxious about my upcoming presentation"],
        ["Today was a great day, I accomplished all my goals!"],
        ["I've been feeling down and unmotivated lately"],
    ],
    allow_flagging="never"
)

# Launch the app
if __name__ == "__main__":
    demo.launch()