DasariHarshitha commited on
Commit
e7155e9
Β·
verified Β·
1 Parent(s): 8d208fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -77
app.py CHANGED
@@ -1,77 +1,112 @@
1
- import streamlit as st
2
- from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
- import torch
4
-
5
- # Load pre-trained emotion detection model
6
- model_name = "j-hartmann/emotion-english-distilroberta-base"
7
- tokenizer = AutoTokenizer.from_pretrained(model_name)
8
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
9
-
10
- # Get the actual emotion labels from the model
11
- emotion_labels = model.config.id2label
12
-
13
- # Emotion styles (emoji + colors)
14
- emotion_styles = {
15
- "joy": {"emoji": "πŸ˜ƒ", "color": "#E6E6FA"},
16
- "sadness": {"emoji": "😒", "color": "#3498DB"},
17
- "anger": {"emoji": "😑", "color": "#FFDAB9"},
18
- "fear": {"emoji": "😨", "color": "#FFFACD"},
19
- "surprise": {"emoji": "😲", "color": "#98FB98"},
20
- "disgust": {"emoji": "🀒", "color": "#FFB6C1"},
21
- "neutral": {"emoji": "😐", "color": "#D3D3D3"}
22
- }
23
-
24
- # Streamlit UI
25
- st.set_page_config(page_title="Emotion Detection", layout="centered")
26
-
27
- # 🎨 Change Background Color
28
- st.markdown(
29
- """
30
- <style>
31
- body {
32
- background-color:#AFEEEE; /* Light Grayish Blue */
33
- }
34
- </style>
35
- """,
36
- unsafe_allow_html=True
37
- )
38
-
39
- # 🎯 Add Image at the Top
40
- st.image("innomatics-footer-logo.webp", use_container_width=True,width=300)
41
-
42
- st.markdown("<h1 style='text-align: center; color: #7D3C98;'>Emotion Detection using ML</h1>", unsafe_allow_html=True)
43
- st.markdown("<h3 style='text-align: left; color: #3498DB;'>πŸ“ Enter the text:</h3>", unsafe_allow_html=True)
44
-
45
- # User Input
46
- user_text = st.text_input("", placeholder="Type your text here...")
47
-
48
- if st.button("Submit"):
49
- if user_text:
50
- # Tokenize input text
51
- inputs = tokenizer(user_text, return_tensors="pt")
52
-
53
- # Get model predictions
54
- with torch.no_grad():
55
- outputs = model(**inputs)
56
-
57
- # Get the predicted emotion
58
- scores = outputs.logits[0]
59
- predicted_label_id = torch.argmax(scores).item()
60
- predicted_emotion = emotion_labels[predicted_label_id].strip().lower()
61
-
62
- # Get emoji & color
63
- emotion_data = emotion_styles.get(predicted_emotion, {"emoji": "😐", "color": "#D3D3D3"})
64
- emoji_display = emotion_data["emoji"]
65
- text_color = emotion_data["color"]
66
-
67
- # Display Results with Color
68
- st.markdown(
69
- f"""
70
- <div style="text-align: center; padding: 10px; border-radius: 10px; background-color: {text_color}; color: black; font-size: 24px;">
71
- <b>Detected Emotion:</b> {predicted_emotion.capitalize()} {emoji_display}
72
- </div>
73
- """,
74
- unsafe_allow_html=True
75
- )
76
- else:
77
- st.warning("Please enter some text!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
3
+ import torch
4
+
5
+ # Load Pre-trained Emotion Detection Model
6
+ MODEL_NAME = "j-hartmann/emotion-english-distilroberta-base"
7
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
8
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
9
+
10
+ # Emotion Mapping (Emojis & Colors)
11
+ emotion_styles = {
12
+ "joy": {"emoji": "πŸ˜ƒ", "color": "#E6E6FA"},
13
+ "sadness": {"emoji": "😒", "color": "#3498DB"},
14
+ "anger": {"emoji": "😑", "color": "#FFDAB9"},
15
+ "fear": {"emoji": "😨", "color": "#FFFACD"},
16
+ "surprise": {"emoji": "😲", "color": "#98FB98"},
17
+ "disgust": {"emoji": "🀒", "color": "#FFB6C1"},
18
+ "neutral": {"emoji": "😐", "color": "#D3D3D3"}
19
+ }
20
+
21
+ # Configure Streamlit Page
22
+ st.set_page_config(page_title="Emotion Detection", layout="centered")
23
+
24
+ # Custom CSS for Background and Styling
25
+ st.markdown(
26
+ """
27
+ <style>
28
+ body { background-color: black; color: white; }
29
+ .result-box {
30
+ text-align: center;
31
+ padding: 15px;
32
+ border-radius: 10px;
33
+ font-size: 22px;
34
+ font-weight: bold;
35
+ }
36
+ </style>
37
+ """,
38
+ unsafe_allow_html=True
39
+ )
40
+
41
+ # Header Section
42
+ st.image("innomatics-footer-logo.webp", use_container_width=True) # Replace with your image file
43
+ st.markdown("<h1 style='text-align: center; color: blue;'>πŸ” Emotion Detection 😊</h1>", unsafe_allow_html=True)
44
+
45
+ # Business Context
46
+ st.markdown("<h2 style='color: orange;'> 🎯 Business Context</h2>",unsafe_allow_html=True)
47
+
48
+ st.markdown("<h3 style='color: red;'>πŸ“Œ Business Problem</h3>", unsafe_allow_html=True)
49
+ st.markdown("""
50
+ Businesses struggle to understand customer emotions in real-time. Traditional feedback methods, such as surveys and reviews, fail to capture spontaneous emotional responses, leading to:
51
+
52
+ - **Missed opportunities** for improving customer experience.
53
+ - **Delayed insights** into customer satisfaction.
54
+ - **Inability to personalize interactions** based on real emotions.
55
+
56
+ An effective emotion detection system can help businesses analyze customer sentiments instantly, enabling proactive engagement and improved decision-making.
57
+ """, unsafe_allow_html=True)
58
+
59
+ st.markdown("<h3 style='color: green;'>🎯 Business Objective</h3>", unsafe_allow_html=True)
60
+ st.markdown("""
61
+ The primary goal of this Emotion Detection System is to enhance customer experience by identifying emotions in real-time from text-based interactions.
62
+
63
+ ##### **Key Objectives:**
64
+ - βœ… **Real-time Emotion Analysis** – Detect emotions from customer messages, emails, and social media interactions.
65
+ - βœ… **Improved Customer Satisfaction** – Address negative sentiments promptly to enhance brand loyalty.
66
+ - βœ… **Personalized Engagement** – Tailor responses based on detected emotions for a better user experience.
67
+ - βœ… **Data-Driven Decisions** – Provide insights for optimizing services, marketing strategies, and customer interactions.
68
+ - βœ… **Operational Efficiency** – Automate sentiment analysis, reducing manual effort and response time.
69
+ """, unsafe_allow_html=True)
70
+
71
+ st.markdown("<h3 style='color: blue;'>βš–οΈ Business Constraints</h3>", unsafe_allow_html=True)
72
+ st.markdown("""
73
+ The system must meet the following business and technical constraints:
74
+
75
+ - 1️⃣ **Data Privacy & Compliance** – Must adhere to regulations like **GDPR** and **CCPA** to ensure user data protection.
76
+ - 2️⃣ **Real-time Processing** – The model should analyze and respond to emotions instantly, without significant delays.
77
+ - 3️⃣ **System Integration** – Should seamlessly integrate with **chatbots, CRMs, call centers, and social media platforms**.
78
+ - 4️⃣ **Accuracy & Reliability** – High **precision with minimal false positives** to avoid misinterpretations.
79
+ - 5️⃣ **Scalability** – Should efficiently handle **large-scale interactions** across multiple customer touchpoints.
80
+ - 6️⃣ **Cost-effectiveness** – Must be financially viable while delivering measurable ROI.
81
+ - 7️⃣ **Multi-language & Multi-model Support** – Capable of detecting emotions across **various languages** and communication channels **(text, voice, images)**.
82
+ """, unsafe_allow_html=True)
83
+
84
+ # User Input Section
85
+ st.markdown("<h2 style='color: purple;'> πŸ“ Enter Your Text Below</h2>",unsafe_allow_html=True)
86
+ user_text = st.text_input("", placeholder="Type your text here...")
87
+
88
+ # Emotion Prediction
89
+ if st.button("Predict Emotion"):
90
+ if user_text:
91
+ inputs = tokenizer(user_text, return_tensors="pt")
92
+
93
+ with torch.no_grad():
94
+ outputs = model(**inputs)
95
+
96
+ # Get predicted emotion
97
+ scores = outputs.logits[0]
98
+ predicted_label_id = torch.argmax(scores).item()
99
+ predicted_emotion = model.config.id2label[predicted_label_id].lower()
100
+
101
+ # Display Results
102
+ emotion_data = emotion_styles.get(predicted_emotion, {"emoji": "😐", "color": "#95A5A6"})
103
+ st.markdown(
104
+ f"""
105
+ <div class="result-box" style="background-color: {emotion_data['color']}; color: black;">
106
+ Detected Emotion: <b>{predicted_emotion.capitalize()} {emotion_data['emoji']}</b>
107
+ </div>
108
+ """,
109
+ unsafe_allow_html=True
110
+ )
111
+ else:
112
+ st.warning("Please enter some text!")