-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
256 lines (212 loc) · 9.1 KB
/
app.py
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import streamlit as st
st.set_page_config(
page_title="Kai Sen App",
page_icon="🚄",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://github.com/Insomniagung',
'About': "Aplikasi Sentimen Analisis oleh Agung Gunawan."
}
)
import time
import streamlit_authenticator as stauth
import base64
# --- import pages ---
# import predictor as pr
import predictor_user as pru
from dash_admin.admin_home import admin_home_page
from dash_admin.admin_analysis import admin_analysis_page
from dash_admin.admin_report import admin_report_page
from dash_admin.admin_database import admin_database_page
from dash_admin.analysis_upload import analysis_upload_page
from dash_user.user_home import user_home_page
from dash_user.user_database import user_database_page
from deta import Deta
#database
deta = Deta(st.secrets["DETA_PROJECT_KEY"])
db = deta.Base("users")
# def get_user(key):
# return db.get(key)
def get_user(key):
user_data = db.get(str(key))
if user_data is not None:
return user_data
else:
return {}
def put_user(username, name, password, role):
return db.put({"key": username, "name": name, "password": password, "role": role})
def get_all_keys():
users = db.fetch().items
keys = [user["key"] for user in users]
return keys
# alert
def red_alert(str):
st.write("")
with st.error(str):
time.sleep(2)
st.empty()
def green_alert(str):
st.write("")
with st.success(str):
time.sleep(2)
st.empty()
# --- css ---
def add_background():
image_file = 'img/bg_images.png'
with open(image_file, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
st.markdown(
f"""
<style>
.stApp {{
background-image: url(data:image/{"png"};base64,{encoded_string.decode()});
background-size: cover
}}
</style>
""",
unsafe_allow_html=True
)
st.markdown("""
<style>
div.stButton > button:first-child {
background-color: #01080d;
border-radius:25px;
padding:7px 18px 7px 18px;
}
div.stButton > button:hover {
background-color: #05263d;
}
</style>""",
unsafe_allow_html=True)
def main():
add_background()
# --- authenticator ---
users = db.fetch().items
usernames = [user["key"] for user in users]
names = [users["name"] for users in users]
passwords = [user["password"] for user in users]
credentials = {"usernames":{}}
for un, name, pw in zip(usernames, names, passwords):
user_dict = {"name": name, "password": pw}
credentials["usernames"].update({un: user_dict})
authenticator = stauth.Authenticate(credentials, "login_cookie", "key_login", cookie_expiry_days=7)
authenticator._check_cookie()
if not st.session_state['authentication_status']:
menu = ["Login", "Register"]
selected = st.radio(label = " **FORM** ",
options = menu,
index=0,
horizontal=True,
label_visibility = "collapsed")
if selected == "Login":
name_auth, authentication_status, username_auth = authenticator.login("Login", "main")
st.session_state['name'] = name_auth
st.session_state['authentication_status'] = authentication_status
st.session_state['username'] = username_auth
if authentication_status == False:
st.error("Username atau password salah. Mohon isi kolom dengan benar.")
if authentication_status == None:
st.warning("Silakan login terlebih dahulu.")
if selected == "Register":
all_keys = get_all_keys()
st.info("Silakan isi form untuk mendaftar user baru.", icon="ℹ️")
form_register = st.form('form_register', clear_on_submit=False)
form_register.subheader("Register")
# form_register.write("")
txt_username = form_register.text_input("Input Username :")
txt_name = form_register.text_input("Input Nama :")
txt_role = "user"
txt_password = form_register.text_input("Input Password :", type="password")
# HashSha256
hashed_password = stauth.Hasher([txt_password]).generate()
hashed_password = hashed_password[0]
if form_register.form_submit_button("Register"):
if txt_username and txt_name and txt_password and txt_role:
if txt_username in all_keys:
red_alert("Username sudah ada, coba yang lain.")
else:
result_put = put_user(txt_username, txt_name, hashed_password, txt_role)
if result_put != None:
green_alert("Registrasi berhasil. Data tersimpan.")
# st.experimental_rerun()
else:
red_alert("Mohon isi kolom yang masih kosong.")
# --- main pages ---
else:
authenticator.logout("Logout", "sidebar")
username = st.session_state['username']
role = get_user(username).get('role')
st.session_state['role'] = role
# ROLE ADMIN
if role == "admin":
#sidebar
with st.sidebar:
st.divider()
# menu = ["🏡 Home", "📋 Sentiment Analysis",
# "📂 Sentiment Upload","💬 Sentiment Predictor",
# "📚 Report", "⚙️ Account Management"]
menu = ["🏡 Home", "📋 Sentiment Analysis",
"📂 Sentiment Upload",
"📚 Report", "⚙️ Account Management"]
selected = st.selectbox(label = " **DASHBOARD** ",
options = menu,
index=0,
label_visibility = "visible")
# st.info(f"Username: **{username.capitalize()}**", icon="ℹ️")
# st.info(f"Role: **{role.capitalize()}**", icon="ℹ️")
#contents
if selected == "🏡 Home":
st.sidebar.info(f"Username: **{username.capitalize()}**", icon="ℹ️")
st.sidebar.info(f"Role: **{role.capitalize()}**", icon="ℹ️")
admin_home_page()
elif selected == "📋 Sentiment Analysis":
admin_analysis_page()
elif selected == "📂 Sentiment Upload":
analysis_upload_page()
# elif selected == "💬 Sentiment Predictor":
# pr.predictor_page()
elif selected == "📚 Report":
admin_report_page()
elif selected == "⚙️ Account Management":
admin_database_page()
# ROLE USER
elif role == "user":
#sidebar
with st.sidebar:
st.divider()
# menu = ["🏡 Home", "💬 Sentiment Predictor", "⚙️ Account Management"]
menu = ["💬 Sentiment Predictor", "⚙️ Account Management"]
selected = st.selectbox(label = " **DASHBOARD** ",
options = menu,
index=0,
label_visibility = "visible")
# st.info(f"Username: **{username.capitalize()}**", icon="ℹ️")
# st.info(f"Role: **{role.capitalize()}**", icon="ℹ️")
#contents
if selected == "🏡 Home":
st.sidebar.info(f"Username: **{username.capitalize()}**", icon="ℹ️")
st.sidebar.info(f"Role: **{role.capitalize()}**", icon="ℹ️")
user_home_page()
elif selected == "💬 Sentiment Predictor":
st.sidebar.info(f"Username: **{username.capitalize()}**", icon="ℹ️")
st.sidebar.info(f"Role: **{role.capitalize()}**", icon="ℹ️")
st.sidebar.info(f"Welcome, **_{name}_**!", icon="ℹ️")
pru.predictor_page()
# pr.predictor_page()
elif selected == "⚙️ Account Management":
user_database_page()
st.write("")
st.divider()
st.write('''
<p style="text-decoration: none;
font-family: 'Open Sans'; font-size: 13px; font-weight: bold;
color: white; background-color: #00386b;
border-radius: 5px; padding: 9px 22px;">
© Agung Gunawan (2019230012) | Sentiment Analysis Random Forest Classifier</p>
''', unsafe_allow_html = True)
# with st.expander("Session"):
# st.session_state
if __name__ == "__main__":
main()
hide_streamlit = """ <style> footer {visibility: hidden;} </style> """
st.markdown(hide_streamlit, unsafe_allow_html=True)