File size: 2,419 Bytes
9bbfdd0
 
c6f7445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
!pip install transformers streamlit
!pip install torch  # for PyTorch

import streamlit as st
from transformers import pipeline

# 1. Emotion Detection Model (Using Hugging Face's transformer)
# Choose a suitable model -  'emotion-classification' is the task, you can specify a model from Hugging Face Model Hub.
emotion_classifier = pipeline("text-classification", model="SamLowe/roberta-base-go_emotions")  # Or choose another model

# 2. Conversational Agent Logic
def get_ai_response(user_input, emotion_predictions):
    """Generates AI response based on user input and detected emotions."""

    # Basic response generation based on detected emotions
    responses = {
        "anger": "I understand you're feeling angry.  Let's take a deep breath and try to resolve this.",
        "sadness": "I'm sorry to hear you're feeling sad. Is there anything I can do to help?",
        "joy": "That's wonderful! I'm so happy for you!",
        "surprise": "Wow, that's surprising! Tell me more.",
        "fear": "I understand you're afraid. How can I help?",
        "neutral": "Understood.", # or a more neutral response
        "default": "I am not able to understand the emotion, please try again"
    }


    dominant_emotion = None
    max_score = 0

    for prediction in emotion_predictions:
      if prediction['score'] > max_score:
        max_score = prediction['score']
        dominant_emotion = prediction['label']


    # Handle cases where no specific emotion is clear
    if dominant_emotion is None:
       return responses["default"]  # or use default message if no emotion is detected.
    elif dominant_emotion in responses:
        return responses[dominant_emotion]
    else:
        return "I'm detecting some emotion, but I'm not sure how to respond." #Handle unexpected emotion labels.

# 3. Streamlit Frontend
st.title("Emotionally Aware Chatbot")

# Input Text Box
user_input = st.text_input("Enter your message:", "")

if user_input:
    # Emotion Detection
    emotion_predictions = emotion_classifier(user_input)

    # Display Emotions
    st.subheader("Detected Emotions:")
    for prediction in emotion_predictions:
        st.write(f"- {prediction['label']}: {prediction['score']:.2f}") # Show emotion score.

    # Get AI Response
    ai_response = get_ai_response(user_input, emotion_predictions)

    # Display AI Response
    st.subheader("AI Response:")
    st.write(ai_response)