aadhi3 commited on
Commit
fa06ee5
·
verified ·
1 Parent(s): 4a03f67

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -153
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
- 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")
 
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")