dvs30 commited on
Commit
bbc1c7f
ยท
verified ยท
1 Parent(s): f3014f5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +184 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import altair as alt
3
+ import plotly.express as px
4
+ import pandas as pd
5
+ import numpy as np
6
+ from datetime import datetime
7
+ from transformers import pipeline
8
+
9
+ # Loading pre-trained emotion classifier pipeline
10
+ emotion_classifier = pipeline("text-classification", model="j-hartmann/emotion-english-roberta-large", top_k=None)
11
+
12
+ from track_utils import create_page_visited_table, add_page_visited_details, view_all_page_visited_details, add_prediction_details, view_all_prediction_details, create_emotionclf_table
13
+
14
+ def predict_emotions(docx):
15
+ results = emotion_classifier(docx)
16
+ results_sorted = sorted(results[0], key=lambda x: x['score'], reverse=True)
17
+ return results_sorted[0]['label']
18
+
19
+ def get_prediction_proba(docx):
20
+ results = emotion_classifier(docx)
21
+ return {result['label']: result['score'] for result in results[0]}
22
+
23
+
24
+ def set_bg_hack_url():
25
+ '''
26
+ A function to unpack an image from url and set as bg.
27
+ Returns
28
+ -------
29
+ The background.
30
+ '''
31
+
32
+ st.markdown(
33
+ f"""
34
+ <style>
35
+ .stApp {{
36
+ background: url("https://png.pngtree.com/background/20210709/original/pngtree-simple-technology-business-line-picture-image_938206.jpg");
37
+ background-size: cover;
38
+ }}
39
+ /* General body styling */
40
+ body {{
41
+ font-family: 'Arial', sans-serif;
42
+ }}
43
+ /* Sidebar styling */
44
+ [data-testid="stSidebar"] {{
45
+ background: linear-gradient(180deg, #52079A, #062879); /* Gradient from dark blue to orange */
46
+ color: white;
47
+ }}
48
+ [data-testid="stSidebar"] .css-1d391kg {{
49
+ color: white;
50
+ }}
51
+ /* Title and headers */
52
+ h1, h2, h3 {{
53
+ color: #FFFFFF; /* White */
54
+ }}
55
+ /* Custom button style */
56
+ .stButton button {{
57
+ background-color: #004080; /* Dark Blue */
58
+ color: white;
59
+ border-radius: 8px;
60
+ border: none;
61
+ font-size: 16px;
62
+ padding: 10px 20px;
63
+ cursor: pointer;
64
+ }}
65
+ .stButton button:hover {{
66
+ background-color: #FFA500; /* Orange */
67
+ }}
68
+ /* DataFrame styling */
69
+ .css-17z80pu {{
70
+ background-color: #d3d3d3; /* Grey */
71
+ border: 1px solid #ddd;
72
+ border-radius: 4px;
73
+ padding: 10px;
74
+ }}
75
+ /* Custom chart area */
76
+ .stAltairChart {{
77
+ background-color: #d3d3d3; /* Grey */
78
+ border: 1px solid #ddd;
79
+ border-radius: 5px;
80
+ padding: 10px;
81
+ }}
82
+ /* Text area styling */
83
+ .css-91z34k {{
84
+ background-color: #e0e0e0; /* Light Grey for Text Area Box */
85
+ border: 1px solid #ddd;
86
+ border-radius: 4px;
87
+ padding: 10px;
88
+ }}
89
+ /* Top bar styling */
90
+ header[data-testid="stHeader"] {{
91
+ background: rgba(0, 0, 0, 0); /* Transparent */
92
+ }}
93
+ </style>
94
+ """,
95
+ unsafe_allow_html=True
96
+ )
97
+
98
+
99
+
100
+ emotions_emoji_dict = {"anger":"๐Ÿ˜ ","disgust":"๐Ÿคฎ", "fear":"๐Ÿ˜จ๐Ÿ˜ฑ", "happiness":"๐Ÿค—", "joy":"๐Ÿ˜‚", "neutral":"๐Ÿ˜", "sadness":"๐Ÿ˜”", "surprise":"๐Ÿ˜ฎ"}
101
+
102
+ def main():
103
+ st.set_page_config(page_title="Emotion Classifier App: Veer", layout="wide")
104
+ set_bg_hack_url()
105
+
106
+ st.sidebar.title("Menu")
107
+ menu = ["๐Ÿ  Home", "๐Ÿ“Š Monitor", "โ„น๏ธ About"]
108
+ choice = st.sidebar.selectbox("Select an Option", menu)
109
+
110
+
111
+ create_page_visited_table()
112
+ create_emotionclf_table()
113
+
114
+ if choice == "๐Ÿ  Home":
115
+ add_page_visited_details("Home", datetime.now())
116
+ st.title("Emotion Classifier App")
117
+ st.subheader("Enter text to analyze its emotion")
118
+
119
+ with st.form(key='emotion_clf_form'):
120
+ raw_text = st.text_area("Type Here")
121
+ submit_text = st.form_submit_button(label='Submit')
122
+
123
+ if submit_text:
124
+ prediction = predict_emotions(raw_text)
125
+ probability = get_prediction_proba(raw_text)
126
+
127
+ add_prediction_details(raw_text, prediction, max(probability.values()), datetime.now())
128
+
129
+ col1, col2 = st.columns(2)
130
+
131
+ with col1:
132
+ st.success("Input Text")
133
+ st.write(raw_text)
134
+
135
+ st.success("Sentiment Prediction")
136
+ emoji_icon = emotions_emoji_dict[prediction]
137
+ st.write(f"{prediction}: {emoji_icon}")
138
+ st.write(f"Confidence: {max(probability.values()):.2f}")
139
+
140
+ with col2:
141
+ st.success("Prediction Probability")
142
+ proba_df = pd.DataFrame(list(probability.items()), columns=["emotions", "probability"])
143
+
144
+ fig = alt.Chart(proba_df).mark_bar().encode(x='emotions', y='probability', color='emotions')
145
+ st.altair_chart(fig, use_container_width=True)
146
+
147
+ elif choice == "๐Ÿ“Š Monitor":
148
+ add_page_visited_details("Monitor", datetime.now())
149
+ st.title("App Monitoring")
150
+
151
+ with st.expander("Page Metrics"):
152
+ page_visited_details = pd.DataFrame(view_all_page_visited_details(), columns=['Pagename','Time_of_Visit'])
153
+ st.dataframe(page_visited_details)
154
+
155
+ pg_count = page_visited_details['Pagename'].value_counts().rename_axis('Pagename').reset_index(name='Counts')
156
+ c = alt.Chart(pg_count).mark_bar().encode(x='Pagename', y='Counts', color='Pagename')
157
+ st.altair_chart(c, use_container_width=True)
158
+
159
+ p = px.pie(pg_count, values='Counts', names='Pagename')
160
+ st.plotly_chart(p, use_container_width=True)
161
+
162
+ with st.expander('Emotion Classifier Metrics'): #initially showed Unicode decode error: utf-8 codec cant decode byte; fix:
163
+ try:
164
+ prediction_details = view_all_prediction_details()
165
+ df_emotions = pd.DataFrame(prediction_details, columns=['Rawtext','Prediction','Probability','Time_of_Visit'])
166
+
167
+ # fix for unicodedecodeerror: Ensuring all columns are converted to strings to avoid decoding errors.
168
+ df_emotions = df_emotions.applymap(lambda x: x.decode('utf-8', 'ignore') if isinstance(x, bytes) else str(x))
169
+ st.dataframe(df_emotions)
170
+
171
+ prediction_count = df_emotions['Prediction'].value_counts().rename_axis('Prediction').reset_index(name='Counts')
172
+ pc = alt.Chart(prediction_count).mark_bar().encode(x='Prediction', y='Counts', color='Prediction')
173
+ st.altair_chart(pc, use_container_width=True)
174
+ except UnicodeDecodeError as e:
175
+ st.error(f"Error decoding data: {e}")
176
+
177
+ else:
178
+ st.title("About")
179
+ add_page_visited_details("About", datetime.now())
180
+ st.subheader("Emotion Classifier App")
181
+ st.text("A simple application to classify emotions from text.")
182
+
183
+ if __name__ == '__main__':
184
+ main()