-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
222 lines (176 loc) · 6.08 KB
/
streamlit_app.py
File metadata and controls
222 lines (176 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import os
import re
import time
import pickle
from pathlib import Path
import numpy as np
import pandas as pd
import streamlit as st
import tensorflow as tf
import torch
from tensorflow.keras.preprocessing.sequence import pad_sequences
from transformers import AutoTokenizer, AutoModelForSequenceClassification
# ============================================================
# Paths & Config
# ============================================================
BASE_DIR = Path(__file__).resolve().parent
MODEL_DIR = BASE_DIR / "artifacts/models"
BILSTM_MODEL_PATH = MODEL_DIR / "bilstm_attention_emotional_model/bilstm_attention_emotions.keras"
TOKENIZER_PATH = MODEL_DIR / "bilstm_attention_emotional_model/tokenizer.pkl"
BERT_MODEL_DIR = MODEL_DIR / "bert_emotion_model"
MAX_LEN = 80
ID2LABEL = {
0: "sadness",
1: "joy",
2: "love",
3: "anger",
4: "fear",
5: "surprise",
}
LABEL2EMOJI = {
"sadness": "😢",
"joy": "😄",
"love": "❤️",
"anger": "😡",
"fear": "😨",
"surprise": "😲",
}
# ============================================================
# Text Cleaning
# ============================================================
url_pattern = re.compile(r"http\S+|www\.\S+")
mention_pattern = re.compile(r"@\w+")
space_pattern = re.compile(r"\s+")
def clean_text(s: str) -> str:
s = str(s).lower()
s = url_pattern.sub(" ", s)
s = mention_pattern.sub(" ", s)
s = space_pattern.sub(" ", s)
return s.strip()
# ============================================================
# Custom Attention Layer (For BiLSTM)
# ============================================================
class Attention(tf.keras.layers.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def build(self, input_shape):
self.W = self.add_weight(
shape=(input_shape[-1], 1),
initializer="glorot_uniform",
trainable=True,
)
def call(self, inputs):
score = tf.matmul(inputs, self.W)
score = tf.squeeze(score, axis=-1)
alpha = tf.nn.softmax(score, axis=1)
alpha = tf.expand_dims(alpha, axis=-1)
context = tf.reduce_sum(inputs * alpha, axis=1)
return context
# ============================================================
# Loaders
# ============================================================
@st.cache_resource
def load_bilstm():
with open(TOKENIZER_PATH, "rb") as f:
tokenizer = pickle.load(f)
model = tf.keras.models.load_model(
BILSTM_MODEL_PATH,
custom_objects={"Attention": Attention}
)
return model, tokenizer
@st.cache_resource
def load_bert():
tokenizer = AutoTokenizer.from_pretrained(BERT_MODEL_DIR)
model = AutoModelForSequenceClassification.from_pretrained(BERT_MODEL_DIR)
model.eval()
return model, tokenizer
# ============================================================
# Prediction Functions
# ============================================================
def predict_bilstm(text, model, tokenizer):
cleaned = clean_text(text)
seq = tokenizer.texts_to_sequences([cleaned])
pad = pad_sequences(seq, maxlen=MAX_LEN, padding="post", truncating="post")
start = time.time()
probs = model.predict(pad, verbose=0)[0]
latency = time.time() - start
pred_id = int(np.argmax(probs))
label = ID2LABEL[pred_id]
return label, probs, latency
def predict_bert(text, model, tokenizer):
cleaned = clean_text(text)
inputs = tokenizer(
cleaned,
return_tensors="pt",
truncation=True,
padding=True,
max_length=MAX_LEN
)
start = time.time()
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=1).cpu().numpy()[0]
latency = time.time() - start
pred_id = int(np.argmax(probs))
label = ID2LABEL[pred_id]
return label, probs, latency
# ============================================================
# UI
# ============================================================
st.set_page_config(page_title="BiLSTM vs BERT Emotion Classifier", page_icon="🧠")
st.title("🧠 Emotion Classification — BiLSTM vs BERT")
st.markdown(
"""
Compare **Classical Deep Learning (BiLSTM + Attention)** vs
**Transformer (BERT)** side-by-side in real time.
"""
)
with st.spinner("Loading models..."):
bilstm_model, bilstm_tokenizer = load_bilstm()
bert_model, bert_tokenizer = load_bert()
user_text = st.text_area(
"Enter your text:",
value="I can't believe how amazing today has been!",
height=120
)
if st.button("🔍 Analyze Emotion", type="primary"):
if not user_text.strip():
st.warning("Enter some text first.")
else:
bilstm_label, bilstm_probs, bilstm_time = predict_bilstm(
user_text, bilstm_model, bilstm_tokenizer
)
bert_label, bert_probs, bert_time = predict_bert(
user_text, bert_model, bert_tokenizer
)
col1, col2 = st.columns(2)
# ================= BiLSTM =================
with col1:
st.subheader("BiLSTM + Attention")
st.markdown(
f"""
### {LABEL2EMOJI[bilstm_label]} **{bilstm_label.upper()}**
**Inference Time:** `{bilstm_time:.4f} sec`
"""
)
df_bilstm = pd.DataFrame({
"Emotion": [f"{LABEL2EMOJI[ID2LABEL[i]]} {ID2LABEL[i]}" for i in range(6)],
"Probability": bilstm_probs.tolist()
})
st.bar_chart(df_bilstm, x="Emotion", y="Probability")
# ================= BERT =================
with col2:
st.subheader("BERT (Transformer)")
st.markdown(
f"""
### {LABEL2EMOJI[bert_label]} **{bert_label.upper()}**
**Inference Time:** `{bert_time:.4f} sec`
"""
)
df_bert = pd.DataFrame({
"Emotion": [f"{LABEL2EMOJI[ID2LABEL[i]]} {ID2LABEL[i]}" for i in range(6)],
"Probability": bert_probs.tolist()
})
st.bar_chart(df_bert, x="Emotion", y="Probability")
else:
st.info("Enter text and click **Analyze Emotion** to compare both models.")