|
import gradio as gr |
|
from transformers import pipeline |
|
import numpy as np |
|
|
|
|
|
classifier = pipeline( |
|
"text-classification", |
|
model="SamLowe/roberta-base-go_emotions", |
|
top_k=None |
|
) |
|
|
|
def process_emotions(emotions): |
|
"""Convert raw emotions to our application's format""" |
|
|
|
emotion_dict = {item['label']: float(item['score']) for item in emotions} |
|
|
|
|
|
primary_emotion = max(emotion_dict.items(), key=lambda x: x[1]) |
|
|
|
|
|
max_score = primary_emotion[1] |
|
intensity = 'High' if max_score > 0.66 else 'Medium' if max_score > 0.33 else 'Low' |
|
|
|
|
|
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: |
|
|
|
emotions = classifier(text) |
|
|
|
|
|
result = process_emotions(emotions[0]) |
|
|
|
return result |
|
except Exception as e: |
|
return { |
|
'error': str(e), |
|
'success': False |
|
} |
|
|
|
|
|
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" |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|