Spaces:
Sleeping
Sleeping
File size: 13,095 Bytes
df64dc1 f3928c1 d597984 f3928c1 5855ed5 f3928c1 d597984 df64dc1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 f3928c1 d597984 0ee7187 df64dc1 d597984 f3928c1 7d22065 d597984 0ee7187 d597984 0ee7187 d597984 f3928c1 df64dc1 ee0def7 8e811fb ee0def7 e869210 ee0def7 0ee7187 ee0def7 8e811fb ee0def7 0ee7187 ee0def7 8e811fb ee0def7 0ee7187 8e811fb 0ee7187 8e811fb d597984 8e811fb d597984 8e811fb |
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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 |
import streamlit as st
import mysql.connector
import bcrypt
import datetime
import re
import pytz
import numpy as np
import pandas as pd
import plotly.express as px
# MySQL Connection
connection = mysql.connector.connect(
host="gateway01.ap-southeast-1.prod.aws.tidbcloud.com",
port=4000,
user="37QUb7dvTn3P6E8.root",
password="MBAg14V0HaMdxwX0"
)
mycursor = connection.cursor(buffered=True)
mycursor.execute("CREATE DATABASE IF NOT EXISTS PerformancePrediction")
mycursor.execute('USE PerformancePrediction')
mycursor.execute('''CREATE TABLE IF NOT EXISTS User_data
(id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
registered_date TIMESTAMP,
last_login TIMESTAMP)''')
def username_exists(username):
mycursor.execute("SELECT * FROM User_data WHERE username = %s", (username,))
return mycursor.fetchone() is not None
def email_exists(email):
mycursor.execute("SELECT * FROM User_data WHERE email = %s", (email,))
return mycursor.fetchone() is not None
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def create_user(username, password, email, registered_date):
if username_exists(username):
return 'username_exists'
if email_exists(email):
return 'email_exists'
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
mycursor.execute(
"INSERT INTO User_data (username, password, email, registered_date) VALUES (%s, %s, %s, %s)",
(username, hashed_password, email, registered_date)
)
connection.commit()
return 'success'
def verify_user(username, password):
mycursor.execute("SELECT password FROM User_data WHERE username = %s", (username,))
record = mycursor.fetchone()
if record and bcrypt.checkpw(password.encode('utf-8'), record[0].encode('utf-8')):
mycursor.execute("UPDATE User_data SET last_login = %s WHERE username = %s", (datetime.datetime.now(pytz.timezone('Asia/Kolkata')), username))
connection.commit()
return True
return False
def reset_password(username, new_password):
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
mycursor.execute(
"UPDATE User_data SET password = %s WHERE username = %s",
(hashed_password, username)
)
connection.commit()
# Session state management
if 'sign_up_successful' not in st.session_state:
st.session_state.sign_up_successful = False
if 'login_successful' not in st.session_state:
st.session_state.login_successful = False
if 'reset_password' not in st.session_state:
st.session_state.reset_password = False
if 'username' not in st.session_state:
st.session_state.username = ''
if 'current_page' not in st.session_state:
st.session_state.current_page = 'login'
if 'employee_submitted' not in st.session_state:
st.session_state.employee_submitted = False
# Page styling
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap');
body {
font-family: 'Roboto', sans-serif;
background-color: #f0f2f6;
}
.big-font {
font-size: 36px !important;
font-weight: bold;
color: #1E88E5;
margin-bottom: 30px;
text-align: center;
}
.stButton > button {
width: 100%;
background-color: #1E88E5;
color: white;
font-weight: bold;
border: none;
padding: 10px 0;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.stButton > button:hover {
background-color: #1565C0;
}
.stTextInput > div > div > input {
border-radius: 5px;
border: 2px solid #90CAF9;
}
.stTextInput > div > div > input:focus {
border-color: #1E88E5;
box-shadow: 0 0 0 1px #1E88E5;
}
.link-text {
color: #1E88E5;
text-align: center;
cursor: pointer;
transition: color 0.3s ease;
}
.link-text:hover {
color: #1565C0;
text-decoration: underline;
}
</style>
""", unsafe_allow_html=True)
# Login page
def login():
st.markdown('<p class="big-font">Performance Prediction Login</p>', unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
with st.form(key='login_form', clear_on_submit=True):
username = st.text_input(label='Username', placeholder='Enter Username')
password = st.text_input(label='Password', placeholder='Enter Password', type='password')
st.markdown("<br>", unsafe_allow_html=True)
if st.form_submit_button('Login'):
if not username or not password:
st.error("Please enter all credentials")
elif verify_user(username, password):
st.success(f"Welcome, {username}!")
st.session_state.login_successful = True
st.session_state.username = username
st.session_state.current_page = 'home'
st.experimental_rerun()
else:
st.error("Incorrect username or password. Please try again or sign up if you don't have an account.")
if not st.session_state.get('login_successful', False):
st.markdown("<br>", unsafe_allow_html=True)
col_a, col_b = st.columns(2)
with col_a:
st.markdown("<div class='link-text'>New user?</div>", unsafe_allow_html=True)
if st.button('Sign Up'):
st.session_state.current_page = 'sign_up'
st.experimental_rerun()
with col_b:
st.markdown("<div class='link-text'>Forgot Password?</div>", unsafe_allow_html=True)
if st.button('Reset Password'):
st.session_state.current_page = 'reset_password'
st.experimental_rerun()
# Sign up page
def signup():
st.markdown('<p class="big-font">Sign Up for Performance Prediction</p>', unsafe_allow_html=True)
with st.form(key='signup_form', clear_on_submit=True):
email = st.text_input(label='Email', placeholder='Enter Your Email')
username = st.text_input(label='Username', placeholder='Enter Your Username')
password = st.text_input(label='Password', placeholder='Enter Your Password', type='password')
re_password = st.text_input(label='Confirm Password', placeholder='Confirm Your Password', type='password')
if st.form_submit_button('Sign Up'):
if not email or not username or not password or not re_password:
st.error("Enter all the Credentials")
elif len(password) <= 3:
st.error("Password too short")
elif password != re_password:
st.error("Passwords do not match! Please Re-enter")
else:
result = create_user(username, password, email, datetime.datetime.now(pytz.timezone('Asia/Kolkata')))
if result == 'success':
st.success("Account created successfully!")
st.session_state.sign_up_successful = True
st.session_state.current_page = 'login'
st.experimental_rerun()
if not st.session_state.get('sign_up_successful', False):
st.markdown("<br>", unsafe_allow_html=True)
st.markdown("<div class='link-text'>Already have an account?</div>", unsafe_allow_html=True)
if st.button('Login'):
st.session_state.current_page = 'login'
st.experimental_rerun()
# Reset password page
def reset_password_page():
st.markdown('<p class="big-font">Reset Password</p>', unsafe_allow_html=True)
with st.form(key='reset_password_form', clear_on_submit=True):
username = st.text_input(label='Username', value='', placeholder='Enter your username')
new_password = st.text_input(label='New Password', type='password', placeholder='Enter new password')
re_password = st.text_input(label='Confirm New Password', type='password', placeholder='Confirm new password')
if st.form_submit_button('Reset Password'):
if not username:
st.error("Enter your username.")
elif not username_exists(username):
st.error("Username not found. Enter a valid username.")
elif not new_password or not re_password:
st.error("Enter all the credentials.")
elif len(new_password) <= 3:
st.error("Password too short. Enter a longer password.")
elif new_password != re_password:
st.error("Passwords do not match! Please re-enter.")
else:
reset_password(username, new_password)
st.success("Password has been reset successfully! Please login with your new password.")
st.session_state.current_page = 'login'
st.experimental_rerun()
st.markdown("<br>", unsafe_allow_html=True)
st.markdown("<div class='link-text'>Remember your password?</div>", unsafe_allow_html=True)
if st.button('Login'):
st.session_state.current_page = 'login'
st.experimental_rerun()
# Home page
def home_page():
st.sidebar.title(f"Welcome, {st.session_state.username}!")
# Sidebar for inputting employee details
st.sidebar.header("Enter Employee Details")
employee_name = st.sidebar.text_input("Employee Name")
employee_id = st.sidebar.text_input("Employee ID")
employee_age = st.sidebar.number_input("Employee Age", min_value=18, max_value=65, value=30)
employee_join_date = st.sidebar.date_input("Joining Date", value=datetime.date(2020, 1, 1))
employee_appraisal_date = st.sidebar.date_input("Last Appraisal Date", value=datetime.date(2023, 1, 1))
if st.sidebar.button("Submit"):
st.session_state.employee_submitted = True
st.sidebar.success(f"Employee {employee_name} (ID: {employee_id}, Age: {employee_age}) details submitted successfully!")
# Main dashboard area
st.title("Performance Prediction Dashboard")
if st.session_state.employee_submitted:
tab1, tab2 = st.tabs(["Overview", "Performance Insights"])
with tab1:
col1, col2 = st.columns(2)
with col1:
st.subheader("Employee Performance Score")
performance_score = np.random.randint(60, 100)
st.metric("Predicted Performance", f"{performance_score}%", "4%")
st.subheader("Key Factors Influencing Performance")
factors = pd.DataFrame({
'Factor': ['Experience', 'Training', 'Projects', 'Teamwork'],
'Impact': [0.3, 0.25, 0.28, 0.17]
})
fig = px.bar(factors, x='Impact', y='Factor', orientation='h', color='Factor',
color_discrete_sequence=px.colors.qualitative.Bold)
st.plotly_chart(fig)
with col2:
st.subheader("Performance Trend")
dates = pd.date_range(start="2023-01-01", end="2023-12-31", freq="M")
performance = np.random.randint(70, 100, size=len(dates))
trend_data = pd.DataFrame({"Date": dates, "Performance": performance})
fig = px.line(trend_data, x="Date", y="Performance", title='Performance Over Time',
line_shape='spline', render_mode='svg', color_discrete_sequence=['#1E88E5'])
st.plotly_chart(fig)
with tab2:
st.subheader("Performance Insights")
st.write(f"Based on the analysis for Employee ID {employee_id}:")
st.write(f"- Current performance is {'above' if performance_score > 80 else 'below'} average")
st.write(f"- Key area for improvement: {'Training' if performance_score < 80 else 'Project Management'}")
st.write(f"- Recommended action: {'Enroll in advanced skills program' if performance_score < 80 else 'Take on leadership role in upcoming project'}")
if st.button("Logout"):
st.session_state.login_successful = False
st.session_state.username = ''
st.session_state.current_page = 'login'
st.experimental_rerun()
# Main app logic
if st.session_state.current_page == 'login':
login()
elif st.session_state.current_page == 'sign_up':
signup()
elif st.session_state.current_page == 'reset_password':
reset_password_page()
elif st.session_state.current_page == 'home':
home_page()
else:
st.error("Page not found or not implemented yet.")
|