aadhi3 commited on
Commit
ed035ae
·
verified ·
1 Parent(s): a657858

Upload 6 files

Browse files
Files changed (6) hide show
  1. BertEmotionClassifier.py +22 -0
  2. README.md +33 -19
  3. __init__.py +0 -0
  4. app.py +153 -0
  5. predictions.csv +3 -0
  6. requirements.txt +6 -3
BertEmotionClassifier.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------
2
+ # Model
3
+ # ---------------------------
4
+ import torch.nn as nn
5
+ from transformers import AutoModel
6
+
7
+ class BertEmotionClassifier(nn.Module):
8
+ def __init__(self, model_name: str = "roberta-base", num_labels: int = 5, dropout: float = 0.3):
9
+ super().__init__()
10
+ self.encoder = AutoModel.from_pretrained(model_name)
11
+ self.dropout = nn.Dropout(dropout)
12
+ self.classifier = nn.Linear(self.encoder.config.hidden_size, 128)
13
+ self.classifier1 = nn.Linear(128, num_labels)
14
+
15
+ def forward(self, input_ids, attention_mask):
16
+ out = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
17
+ cls = out.last_hidden_state[:, 0, :]
18
+ cls = self.classifier(cls)
19
+ cls = self.dropout(cls)
20
+ logits = self.classifier1(cls)
21
+ return logits
22
+
README.md CHANGED
@@ -1,19 +1,33 @@
1
- ---
2
- title: Dl Project
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: This is my DL-genAI project sep-2025
12
- ---
13
-
14
- # Welcome to Streamlit!
15
-
16
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
17
-
18
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🎭 Emotion Classifier — RoBERTa Based
2
+ A deep-learning model that classifies text into **five emotion categories**:
3
+ **anger, fear, joy, sadness, surprise**.
4
+
5
+ Built with **PyTorch, RoBERTa transformer, Streamlit UI** and deployed on **Hugging Face Spaces**.
6
+
7
+ ---
8
+
9
+ ## 🧠 Model Details
10
+ | Component | Description |
11
+ |-----------|-------------|
12
+ | Base model | `roberta-base` |
13
+ | Task | Single-label Emotion Classification |
14
+ | Input | Raw text |
15
+ | Output | Softmax probability distribution (5 emotions) |
16
+ | Framework | PyTorch + Transformers |
17
+
18
+ ### Load Model from Hugging Face
19
+ ```python
20
+ from huggingface_hub import hf_hub_download
21
+ import torch
22
+ from BertEmotionClassifier import BertEmotionClassifier
23
+
24
+ model_path = hf_hub_download(repo_id="aadhi3/RoBert_Model", filename="model.pth")
25
+
26
+ from transformers import AutoTokenizer
27
+ tokenizer = AutoTokenizer.from_pretrained("roberta-base")
28
+
29
+ model = BertEmotionClassifier(model_name="roberta-base", num_labels=5)
30
+ state_dict = torch.load(model_path, map_location="cpu")
31
+ model.load_state_dict(state_dict)
32
+ model.eval()
33
+ ```
__init__.py ADDED
File without changes
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ from BertEmotionClassifier import BertEmotionClassifier
6
+ from transformers import AutoTokenizer
7
+ from huggingface_hub import hf_hub_download
8
+ import torch.nn.functional as F
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="wide")
17
+
18
+ # ----------------------------
19
+ # Custom Styling
20
+ # ----------------------------
21
+ st.markdown("""
22
+ <style>
23
+ .emotion-card {
24
+ padding: 15px;
25
+ border-radius: 18px;
26
+ text-align: center;
27
+ font-size: 18px;
28
+ font-weight: 600;
29
+ color: white;
30
+ margin-bottom: 10px;
31
+ box-shadow: 0px 0px 10px rgba(0,0,0,0.4);
32
+ }
33
+ .dominant {
34
+ background: linear-gradient(135deg, #00c6ff, #0072ff);
35
+ }
36
+ .sub {
37
+ background: linear-gradient(135deg, #434343, #000000);
38
+ }
39
+ .main-container {
40
+ max-width: 900px;
41
+ margin: auto;
42
+ padding-top: 30px;
43
+ }
44
+ </style>
45
+ """, unsafe_allow_html=True)
46
+
47
+ # ----------------------------
48
+ # Load Model
49
+ # ----------------------------
50
+ @st.cache_resource
51
+ def load_model():
52
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
53
+
54
+ model = BertEmotionClassifier(model_name=MODEL_NAME, num_labels=len(EMOTIONS))
55
+
56
+ # Download model weights from HuggingFace Hub
57
+ model_path = hf_hub_download(repo_id="aadhi3/RoBert_Model", filename="model.pth")
58
+
59
+ # Load state dict from downloaded path
60
+ state_dict = torch.load(model_path, map_location="cpu")
61
+ state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()}
62
+ model.load_state_dict(state_dict)
63
+ model.eval()
64
+
65
+ return tokenizer, model
66
+
67
+ tokenizer, model = load_model()
68
+
69
+ # ----------------------------
70
+ # Prediction Function
71
+ # ----------------------------
72
+ def predict_emotions(text: str):
73
+ encoding = tokenizer(
74
+ text,
75
+ add_special_tokens=True,
76
+ max_length=256,
77
+ padding='max_length',
78
+ truncation=True,
79
+ return_tensors='pt'
80
+ )
81
+
82
+ with torch.no_grad():
83
+ logits = model(**encoding)
84
+ probs = F.softmax(logits, dim=-1)[0].cpu()
85
+
86
+ return {emo: round(float(probs[i]), 4) for i, emo in enumerate(EMOTIONS)}
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")
predictions.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ text,anger,fear,joy,sadness,surprise
2
+ Hi Today is a lucky day,0.0,0.0,1.0,0.0,0.0
3
+ What is the day of the week,0.0397,0.025,0.0156,0.0431,0.8766
requirements.txt CHANGED
@@ -1,3 +1,6 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
1
+ streamlit
2
+ torch
3
+ transformers
4
+ huggingface_hub
5
+ pandas
6
+ matplotlib