nincy123's picture
Upload 4 files
a9f069f verified
import streamlit as st
import pickle
import pandas as pd
import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
# Custom Styling (Changes text area label color)
st.markdown(
"""
<style>
html, body, [class*="st-"] {
background-color: white !important;
color: black !important;
}
label[data-testid="stTextAreaLabel"] {
color: blue !important;
font-size: 18px;
font-weight: bold;
}
</style>
""",
unsafe_allow_html=True,
)
# Display an Image (Check if File Exists)
image_path = "Innomatics-Logo1.png"
if os.path.exists(image_path):
st.image(image_path, width=700)
else:
st.warning("Image not found! Check the file path.")
# Streamlit UI
st.title("😊 Emotion Detection from Text")
# 1. Business and Data Understanding
st.header("πŸ“Œ 1. Business and Data Understanding")
# a) Business Problem
st.subheader("πŸ“ a) Business Problem of Emotion Detection Using ML")
st.write("""
Emotion detection using machine learning aims to classify human emotions from text data.
The goal is to develop an AI-driven system that can accurately recognize emotions from written sentences.
This has applications in:
- **Customer Support:** Detecting customer sentiment in reviews and chat conversations.
- **Mental Health Monitoring:** Identifying distress or emotional patterns in patients.
- **Marketing & Brand Monitoring:** Understanding customer sentiment towards products and services.
- **Social Media & Content Analysis:** Identifying trends and reactions from social media posts.
""")
# b) Business Objective
st.subheader("πŸ“ b) Business Objective")
st.write("""
The primary objective is to build a machine learning model that can classify emotions accurately based on textual input.
The model should:
- Provide **high accuracy** in emotion classification.
- Be **efficient** for real-time or batch processing.
- Offer **interpretability** for business use cases.
""")
# c) Business Constraints
st.subheader("πŸ“ c) Business Constraints")
st.write("""
- **Accuracy vs. Speed:** The model must balance accuracy and computational efficiency.
- **Data Privacy & Compliance:** Sensitive emotional data should be handled with care.
- **Scalability:** The system should be scalable for real-time analysis.
- **Bias & Fairness:** The model should minimize biases in emotion detection.
""")
# d) Data Understanding
st.subheader("πŸ“ d) Data Understanding")
st.write("""
- **Dataset Size:** 422,746 text samples.
- **Columns:**
1. **sentence (Text Feature)** – Contains textual data representing different emotional expressions.
2. **emotion (Target Label)** – Represents the classified emotion associated with each sentence (e.g., happy, sad, fear, etc.).
""")
# Load the trained model
with open("emotion_model.pkl", "rb") as file:
model = pickle.load(file)
# Load CountVectorizer (required for text processing)
vectorizer = model.named_steps["BOW"]
# Project Description
st.header("🎭 About This Project")
st.write("""
This **Emotion Detection Model** analyzes text and predicts the **emotion behind the sentence**.
It uses **Natural Language Processing (NLP)** and a **NaΓ―ve Bayes classifier** trained on labeled emotions.
Simply enter a sentence, and the model will detect whether it expresses happiness, sadness, anger, surprise, or other emotions!
""")
# Load dataset again to calculate accuracy & F1-score
file_path = "combined_emotion.csv" # Ensure this file is available
if os.path.exists(file_path):
df = pd.read_csv(file_path)
# Extract features and labels
X = df["sentence"]
y = df["emotion"]
# Split dataset to evaluate model
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Transform test data
X_test_transformed = vectorizer.transform(X_test)
# Predict and calculate metrics
y_pred = model.named_steps["Algorithm"].predict(X_test_transformed)
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred, average="weighted")
# Display model performance **AFTER** project description
st.subheader("πŸ“Š Model Performance")
st.write(f"βœ… **Accuracy:** {accuracy:.2f}")
st.write(f"βœ… **F1-Score:** {f1:.2f}")
else:
st.warning("Dataset not found! Accuracy and F1-score cannot be displayed.")
# Define emotion emojis
emotion_emojis = {
"joy": "😊",
"sad": "😒",
"anger": "😠",
"fear": "😨",
"surprise": "😲",
"neutral": "😐",
"love": "❀️",
"disgust": "🀒"
}
# User input with custom color
user_input = st.text_area("Enter text here:")
if st.button("Predict Emotion"):
if user_input.strip() != "":
# Transform input using the same vectorizer
transformed_input = vectorizer.transform([user_input])
# Predict emotion
prediction = model.named_steps["Algorithm"].predict(transformed_input)[0]
# Get corresponding emoji (default to 😢 if emotion not in dictionary)
emoji = emotion_emojis.get(prediction.lower(), "😢")
# Display result with emoji
st.success(f"Predicted Emotion: **{prediction}** {emoji}")
else:
st.warning("Please enter some text before predicting.")