Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,153 +1,86 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import torch
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import matplotlib.pyplot as plt
|
| 5 |
-
|
| 6 |
-
from transformers import AutoTokenizer
|
| 7 |
-
from huggingface_hub import hf_hub_download
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
# ----------------------------
|
| 11 |
-
# Config
|
| 12 |
-
# ----------------------------
|
| 13 |
-
EMOTIONS = ['anger', 'fear', 'joy', 'sadness', 'surprise']
|
| 14 |
-
MODEL_NAME = "roberta-base"
|
| 15 |
-
|
| 16 |
-
st.set_page_config(page_title="Emotion Classifier", page_icon="🎭", layout="
|
| 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 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
# ----------------------------
|
| 89 |
-
# UI Layout
|
| 90 |
-
# ----------------------------
|
| 91 |
-
st.title("🎭 Emotion Detection AI")
|
| 92 |
-
st.markdown("### Understand emotions in text using **AI-driven emotion analysis**")
|
| 93 |
-
st.write("") # spacing
|
| 94 |
-
|
| 95 |
-
input_text = st.text_area(
|
| 96 |
-
"Enter your text here:",
|
| 97 |
-
placeholder="Type something like: 'I am extremely happy today!' 😄",
|
| 98 |
-
height=150
|
| 99 |
-
)
|
| 100 |
-
|
| 101 |
-
predict_btn = st.button("🔮 Analyze Emotions", use_container_width=True)
|
| 102 |
-
|
| 103 |
-
if predict_btn and input_text.strip() != "":
|
| 104 |
-
with st.spinner("AI thinking..."):
|
| 105 |
-
results = predict_emotions(input_text.strip())
|
| 106 |
-
|
| 107 |
-
df = pd.DataFrame(results.items(), columns=["Emotion", "Probability"])
|
| 108 |
-
dominant = df.iloc[df["Probability"].idxmax()]["Emotion"]
|
| 109 |
-
|
| 110 |
-
st.markdown(f"### 🎯 Dominant Emotion: **{dominant.upper()}**")
|
| 111 |
-
|
| 112 |
-
col_chart, col_cards = st.columns([1.2, 1])
|
| 113 |
-
|
| 114 |
-
# ---------------------------
|
| 115 |
-
# Matplotlib Bar Chart
|
| 116 |
-
# ---------------------------
|
| 117 |
-
with col_chart:
|
| 118 |
-
fig, ax = plt.subplots()
|
| 119 |
-
ax.bar(df["Emotion"], df["Probability"])
|
| 120 |
-
ax.set_ylim(0, 1)
|
| 121 |
-
ax.set_ylabel("Probability Score")
|
| 122 |
-
ax.set_title("Emotion Prediction Distribution")
|
| 123 |
-
st.pyplot(fig)
|
| 124 |
-
|
| 125 |
-
# ---------------------------
|
| 126 |
-
# Emotion Cards
|
| 127 |
-
# ---------------------------
|
| 128 |
-
with col_cards:
|
| 129 |
-
st.markdown("### 📊 Emotion Strength")
|
| 130 |
-
for emo, val in results.items():
|
| 131 |
-
style = "dominant" if emo == dominant else "sub"
|
| 132 |
-
st.markdown(
|
| 133 |
-
f"<div class='emotion-card {style}'>{emo.capitalize()} — {val}</div>",
|
| 134 |
-
unsafe_allow_html=True
|
| 135 |
-
)
|
| 136 |
-
|
| 137 |
-
# Save Prediction History
|
| 138 |
-
row = {"text": input_text, **results}
|
| 139 |
-
try:
|
| 140 |
-
old_df = pd.read_csv("./predictions.csv")
|
| 141 |
-
except FileNotFoundError:
|
| 142 |
-
old_df = pd.DataFrame(columns=["text"] + EMOTIONS)
|
| 143 |
-
|
| 144 |
-
new_df = pd.concat([old_df, pd.DataFrame([row])], ignore_index=True)
|
| 145 |
-
new_df.to_csv("./predictions.csv", index=False)
|
| 146 |
-
|
| 147 |
-
with st.expander("📂 View Recent Predictions"):
|
| 148 |
-
st.dataframe(new_df.tail(10), use_container_width=True)
|
| 149 |
-
|
| 150 |
-
st.success("Result saved successfully! ✨")
|
| 151 |
-
|
| 152 |
-
st.markdown("---")
|
| 153 |
-
st.caption("Built with ❤️ using Streamlit & PyTorch — deployed on HuggingFace Spaces")
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from transformers import AutoTokenizer
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
from BertEmotionClassifier import BertEmotionClassifier
|
| 9 |
+
|
| 10 |
+
# ----------------------------
|
| 11 |
+
# Config
|
| 12 |
+
# ----------------------------
|
| 13 |
+
EMOTIONS = ['anger', 'fear', 'joy', 'sadness', 'surprise']
|
| 14 |
+
MODEL_NAME = "roberta-base"
|
| 15 |
+
|
| 16 |
+
st.set_page_config(page_title="Emotion Classifier", page_icon="🎭", layout="centered")
|
| 17 |
+
|
| 18 |
+
st.title("🎭 Emotion Detection AI")
|
| 19 |
+
st.markdown("Predict emotional sentiment from text using a fine-tuned RoBERTa model.")
|
| 20 |
+
|
| 21 |
+
# ----------------------------
|
| 22 |
+
# Load Model
|
| 23 |
+
# ----------------------------
|
| 24 |
+
@st.cache_resource
|
| 25 |
+
def load_model():
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 27 |
+
model = BertEmotionClassifier(model_name=MODEL_NAME, num_labels=len(EMOTIONS))
|
| 28 |
+
|
| 29 |
+
model_path = hf_hub_download(repo_id="aadhi3/RoBert_Model", filename="model.pth")
|
| 30 |
+
|
| 31 |
+
state_dict = torch.load(model_path, map_location="cpu")
|
| 32 |
+
state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
|
| 33 |
+
model.load_state_dict(state_dict)
|
| 34 |
+
model.eval()
|
| 35 |
+
return tokenizer, model
|
| 36 |
+
|
| 37 |
+
tokenizer, model = load_model()
|
| 38 |
+
|
| 39 |
+
# ----------------------------
|
| 40 |
+
# Prediction Function
|
| 41 |
+
# ----------------------------
|
| 42 |
+
def predict_emotions(text: str):
|
| 43 |
+
encoding = tokenizer(
|
| 44 |
+
text,
|
| 45 |
+
add_special_tokens=True,
|
| 46 |
+
max_length=256,
|
| 47 |
+
padding="max_length",
|
| 48 |
+
truncation=True,
|
| 49 |
+
return_tensors="pt"
|
| 50 |
+
)
|
| 51 |
+
with torch.no_grad():
|
| 52 |
+
logits = model(**encoding)
|
| 53 |
+
probs = F.softmax(logits, dim=-1)[0].cpu()
|
| 54 |
+
|
| 55 |
+
return {emo: round(float(probs[i]), 4) for i, emo in enumerate(EMOTIONS)}
|
| 56 |
+
|
| 57 |
+
# ----------------------------
|
| 58 |
+
# UI Layout
|
| 59 |
+
# ----------------------------
|
| 60 |
+
input_text = st.text_area("Enter text to analyze:", height=120)
|
| 61 |
+
|
| 62 |
+
if st.button("🔮 Analyze"):
|
| 63 |
+
if input_text.strip():
|
| 64 |
+
with st.spinner("Analyzing emotions..."):
|
| 65 |
+
results = predict_emotions(input_text.strip())
|
| 66 |
+
df = pd.DataFrame(results.items(), columns=["Emotion", "Probability"])
|
| 67 |
+
dominant = df.loc[df["Probability"].idxmax(), "Emotion"]
|
| 68 |
+
|
| 69 |
+
st.markdown(f"### 🎯 Dominant Emotion: **{dominant.upper()}**")
|
| 70 |
+
|
| 71 |
+
# Chart
|
| 72 |
+
fig, ax = plt.subplots(figsize=(5, 3))
|
| 73 |
+
ax.bar(df["Emotion"], df["Probability"])
|
| 74 |
+
ax.set_ylim(0, 1)
|
| 75 |
+
ax.set_ylabel("Probability")
|
| 76 |
+
ax.set_title("Emotion Prediction")
|
| 77 |
+
st.pyplot(fig)
|
| 78 |
+
|
| 79 |
+
st.markdown("### 📊 Prediction Details")
|
| 80 |
+
cols = st.columns(len(EMOTIONS))
|
| 81 |
+
|
| 82 |
+
for col, (emo, val) in zip(cols, results.items()):
|
| 83 |
+
col.metric(label=emo.capitalize(), value=f"{val}")
|
| 84 |
+
|
| 85 |
+
st.markdown("---")
|
| 86 |
+
st.caption("Built with ❤️ using Streamlit & PyTorch — deployed on Hugging Face Spaces")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|