TpsNandhini commited on
Commit
d597984
1 Parent(s): 3278269

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -161
app.py CHANGED
@@ -1,202 +1,249 @@
1
  import streamlit as st
2
  import mysql.connector
3
  import bcrypt
4
- import re
5
  import datetime
 
6
  import pytz
7
- import pandas as pd
8
- import plotly.express as px
9
 
10
  # MySQL Connection
11
- def get_database_connection():
12
- connection = mysql.connector.connect(
13
- host="gateway01.ap-southeast-1.prod.aws.tidbcloud.com",
14
- port=4000,
15
- user="37QUb7dvTn3P6E8.root",
16
- password="MBAg14V0HaMdxwX0"
17
- )
18
- return connection
19
 
20
- # Initialize database and tables
21
- def init_database():
22
- connection = get_database_connection()
23
- cursor = connection.cursor(buffered=True)
24
-
25
- cursor.execute("CREATE DATABASE IF NOT EXISTS EmployeePerformance")
26
- cursor.execute('USE EmployeePerformance')
27
-
28
- # Create User_data table
29
- cursor.execute('''CREATE TABLE IF NOT EXISTS User_data (
30
- id INT AUTO_INCREMENT PRIMARY KEY,
31
- username VARCHAR(50) UNIQUE NOT NULL,
32
- password VARCHAR(255) NOT NULL,
33
- email VARCHAR(255) UNIQUE NOT NULL,
34
- registered_date TIMESTAMP,
35
- last_login TIMESTAMP
36
- )''')
37
-
38
- # Create Employee_data table
39
- cursor.execute('''CREATE TABLE IF NOT EXISTS Employee_data (
40
- id INT AUTO_INCREMENT PRIMARY KEY,
41
- employee_id VARCHAR(50) UNIQUE NOT NULL,
42
- name VARCHAR(100) NOT NULL,
43
- age INT,
44
- last_performance_score FLOAT,
45
- current_performance_score FLOAT,
46
- future_advancement TEXT,
47
- employee_rank INT
48
- )''')
49
-
50
- connection.commit()
51
- cursor.close()
52
- connection.close()
53
 
54
- # User authentication functions
55
  def username_exists(username):
56
- connection = get_database_connection()
57
- cursor = connection.cursor(buffered=True)
58
- cursor.execute('USE EmployeePerformance')
59
- cursor.execute("SELECT * FROM User_data WHERE username = %s", (username,))
60
- result = cursor.fetchone() is not None
61
- cursor.close()
62
- connection.close()
63
- return result
64
 
65
  def email_exists(email):
66
- connection = get_database_connection()
67
- cursor = connection.cursor(buffered=True)
68
- cursor.execute('USE EmployeePerformance')
69
- cursor.execute("SELECT * FROM User_data WHERE email = %s", (email,))
70
- result = cursor.fetchone() is not None
71
- cursor.close()
72
- connection.close()
73
- return result
74
 
75
  def is_valid_email(email):
76
  pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
77
  return re.match(pattern, email) is not None
78
 
79
- def create_user(username, password, email):
80
  if username_exists(username):
81
  return 'username_exists'
 
82
  if email_exists(email):
83
  return 'email_exists'
84
 
85
- connection = get_database_connection()
86
- cursor = connection.cursor(buffered=True)
87
- cursor.execute('USE EmployeePerformance')
88
-
89
  hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
90
- registered_date = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))
91
-
92
- cursor.execute(
93
  "INSERT INTO User_data (username, password, email, registered_date) VALUES (%s, %s, %s, %s)",
94
  (username, hashed_password, email, registered_date)
95
  )
96
-
97
  connection.commit()
98
- cursor.close()
99
- connection.close()
100
  return 'success'
101
 
102
  def verify_user(username, password):
103
- connection = get_database_connection()
104
- cursor = connection.cursor(buffered=True)
105
- cursor.execute('USE EmployeePerformance')
106
-
107
- cursor.execute("SELECT password FROM User_data WHERE username = %s", (username,))
108
- record = cursor.fetchone()
109
-
110
  if record and bcrypt.checkpw(password.encode('utf-8'), record[0].encode('utf-8')):
111
- cursor.execute("UPDATE User_data SET last_login = %s WHERE username = %s",
112
- (datetime.datetime.now(pytz.timezone('Asia/Kolkata')), username))
113
  connection.commit()
114
- cursor.close()
115
- connection.close()
116
  return True
117
-
118
- cursor.close()
119
- connection.close()
120
  return False
121
 
122
- # Employee data functions
123
- def get_employee_data():
124
- connection = get_database_connection()
125
- cursor = connection.cursor(buffered=True)
126
- cursor.execute('USE EmployeePerformance')
127
-
128
- cursor.execute("SELECT * FROM Employee_data")
129
- columns = [col[0] for col in cursor.description]
130
- employees = [dict(zip(columns, row)) for row in cursor.fetchall()]
131
-
132
- cursor.close()
133
- connection.close()
134
- return employees
135
 
136
- # Streamlit app
137
- def main():
138
- st.set_page_config(page_title="Employee Performance Dashboard", layout="wide")
139
-
140
- init_database()
141
-
142
- if 'logged_in' not in st.session_state:
143
- st.session_state.logged_in = False
144
-
145
- if not st.session_state.logged_in:
146
- login_page()
147
- else:
148
- home_page()
149
 
150
- def login_page():
151
- st.title("Login")
152
-
153
- username = st.text_input("Username")
154
- password = st.text_input("Password", type="password")
155
-
156
- if st.button("Login"):
157
- if verify_user(username, password):
158
- st.session_state.logged_in = True
159
- st.session_state.username = username
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
  st.experimental_rerun()
161
- else:
162
- st.error("Invalid username or password")
163
 
164
- def home_page():
165
- st.title("Employee Performance Dashboard")
166
- st.write(f"Welcome, {st.session_state.username}!")
167
-
168
- employees = get_employee_data()
169
-
170
- if not employees:
171
- st.warning("No employee data available.")
172
- return
173
-
174
- # Display employee information
175
- for employee in employees:
176
- st.subheader(f"Employee: {employee['name']}")
177
- col1, col2, col3 = st.columns(3)
178
- col1.metric("Employee ID", employee['employee_id'])
179
- col2.metric("Age", employee['age'])
180
- col3.metric("Rank", employee['employee_rank'])
181
-
182
- col4, col5 = st.columns(2)
183
- col4.metric("Last Performance Score", f"{employee['last_performance_score']:.2f}")
184
- col5.metric("Current Performance Score", f"{employee['current_performance_score']:.2f}")
185
-
186
- st.write("Future Advancement:", employee['future_advancement'])
187
- st.markdown("---")
188
-
189
- # Performance visualization
190
- st.subheader("Performance Overview")
191
- df = pd.DataFrame(employees)
192
- fig = px.scatter(df, x="age", y="current_performance_score", size="employee_rank",
193
- hover_data=["name", "employee_id"], color="current_performance_score",
194
- labels={"current_performance_score": "Current Performance Score"})
195
- st.plotly_chart(fig)
196
-
197
- if st.button("Logout"):
198
- st.session_state.logged_in = False
199
  st.experimental_rerun()
200
 
201
- if __name__ == "__main__":
202
- main()
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import mysql.connector
3
  import bcrypt
 
4
  import datetime
5
+ import re
6
  import pytz
 
 
7
 
8
  # MySQL Connection
9
+ connection = mysql.connector.connect(
10
+ host="gateway01.ap-southeast-1.prod.aws.tidbcloud.com",
11
+ port=4000,
12
+ user="37QUb7dvTn3P6E8.root",
13
+ password="MBAg14V0HaMdxwX0"
14
+ )
 
 
15
 
16
+ mycursor = connection.cursor(buffered=True)
17
+
18
+ mycursor.execute("CREATE DATABASE IF NOT EXISTS PerformancePrediction")
19
+ mycursor.execute('USE PerformancePrediction')
20
+
21
+ mycursor.execute('''CREATE TABLE IF NOT EXISTS User_data
22
+ (id INT AUTO_INCREMENT PRIMARY KEY,
23
+ username VARCHAR(50) UNIQUE NOT NULL,
24
+ password VARCHAR(255) NOT NULL,
25
+ email VARCHAR(255) UNIQUE NOT NULL,
26
+ registered_date TIMESTAMP,
27
+ last_login TIMESTAMP)''')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
 
29
  def username_exists(username):
30
+ mycursor.execute("SELECT * FROM User_data WHERE username = %s", (username,))
31
+ return mycursor.fetchone() is not None
 
 
 
 
 
 
32
 
33
  def email_exists(email):
34
+ mycursor.execute("SELECT * FROM User_data WHERE email = %s", (email,))
35
+ return mycursor.fetchone() is not None
 
 
 
 
 
 
36
 
37
  def is_valid_email(email):
38
  pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
39
  return re.match(pattern, email) is not None
40
 
41
+ def create_user(username, password, email, registered_date):
42
  if username_exists(username):
43
  return 'username_exists'
44
+
45
  if email_exists(email):
46
  return 'email_exists'
47
 
 
 
 
 
48
  hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
49
+ mycursor.execute(
 
 
50
  "INSERT INTO User_data (username, password, email, registered_date) VALUES (%s, %s, %s, %s)",
51
  (username, hashed_password, email, registered_date)
52
  )
 
53
  connection.commit()
 
 
54
  return 'success'
55
 
56
  def verify_user(username, password):
57
+ mycursor.execute("SELECT password FROM User_data WHERE username = %s", (username,))
58
+ record = mycursor.fetchone()
 
 
 
 
 
59
  if record and bcrypt.checkpw(password.encode('utf-8'), record[0].encode('utf-8')):
60
+ mycursor.execute("UPDATE User_data SET last_login = %s WHERE username = %s", (datetime.datetime.now(pytz.timezone('Asia/Kolkata')), username))
 
61
  connection.commit()
 
 
62
  return True
 
 
 
63
  return False
64
 
65
+ def reset_password(username, new_password):
66
+ hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
67
+ mycursor.execute(
68
+ "UPDATE User_data SET password = %s WHERE username = %s",
69
+ (hashed_password, username)
70
+ )
71
+ connection.commit()
 
 
 
 
 
 
72
 
73
+ # Session state management
74
+ if 'sign_up_successful' not in st.session_state:
75
+ st.session_state.sign_up_successful = False
76
+ if 'login_successful' not in st.session_state:
77
+ st.session_state.login_successful = False
78
+ if 'reset_password' not in st.session_state:
79
+ st.session_state.reset_password = False
80
+ if 'username' not in st.session_state:
81
+ st.session_state.username = ''
82
+ if 'current_page' not in st.session_state:
83
+ st.session_state.current_page = 'login'
 
 
84
 
85
+ # Page styling
86
+ st.markdown("""
87
+ <style>
88
+ @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap');
89
+ body {
90
+ font-family: 'Roboto', sans-serif;
91
+ background-color: #f0f2f6;
92
+ }
93
+ .big-font {
94
+ font-size: 36px !important;
95
+ font-weight: bold;
96
+ color: #1E88E5;
97
+ margin-bottom: 30px;
98
+ text-align: center;
99
+ }
100
+ .stButton > button {
101
+ width: 100%;
102
+ background-color: #1E88E5;
103
+ color: white;
104
+ font-weight: bold;
105
+ border: none;
106
+ padding: 10px 0;
107
+ border-radius: 5px;
108
+ cursor: pointer;
109
+ transition: background-color 0.3s ease;
110
+ }
111
+ .stButton > button:hover {
112
+ background-color: #1565C0;
113
+ }
114
+ .stTextInput > div > div > input {
115
+ border-radius: 5px;
116
+ border: 2px solid #90CAF9;
117
+ }
118
+ .stTextInput > div > div > input:focus {
119
+ border-color: #1E88E5;
120
+ box-shadow: 0 0 0 1px #1E88E5;
121
+ }
122
+ .link-text {
123
+ color: #1E88E5;
124
+ text-align: center;
125
+ cursor: pointer;
126
+ transition: color 0.3s ease;
127
+ }
128
+ .link-text:hover {
129
+ color: #1565C0;
130
+ text-decoration: underline;
131
+ }
132
+ </style>
133
+ """, unsafe_allow_html=True)
134
+
135
+ # Login page
136
+ def login():
137
+ st.markdown('<p class="big-font">Performance Prediction Login</p>', unsafe_allow_html=True)
138
+
139
+ col1, col2, col3 = st.columns([1, 2, 1])
140
+
141
+ with col2:
142
+ with st.form(key='login_form', clear_on_submit=True):
143
+ username = st.text_input(label='Username', placeholder='Enter Username')
144
+ password = st.text_input(label='Password', placeholder='Enter Password', type='password')
145
+
146
+ st.markdown("<br>", unsafe_allow_html=True)
147
+
148
+ if st.form_submit_button('Login'):
149
+ if not username or not password:
150
+ st.error("Please enter all credentials")
151
+ elif verify_user(username, password):
152
+ st.success(f"Welcome, {username}!")
153
+ st.session_state.login_successful = True
154
+ st.session_state.username = username
155
+ st.session_state.current_page = 'home'
156
+ st.experimental_rerun()
157
+ else:
158
+ st.error("Incorrect username or password. Please try again or sign up if you don't have an account.")
159
+
160
+ if not st.session_state.get('login_successful', False):
161
+ st.markdown("<br>", unsafe_allow_html=True)
162
+ col_a, col_b = st.columns(2)
163
+ with col_a:
164
+ st.markdown("<div class='link-text'>New user?</div>", unsafe_allow_html=True)
165
+ if st.button('Sign Up'):
166
+ st.session_state.current_page = 'sign_up'
167
+ st.experimental_rerun()
168
+ with col_b:
169
+ st.markdown("<div class='link-text'>Forgot Password?</div>", unsafe_allow_html=True)
170
+ if st.button('Reset Password'):
171
+ st.session_state.current_page = 'reset_password'
172
+ st.experimental_rerun()
173
+
174
+ # Sign up page
175
+ def signup():
176
+ st.markdown('<p class="big-font">Sign Up for Performance Prediction</p>', unsafe_allow_html=True)
177
+
178
+ with st.form(key='signup_form', clear_on_submit=True):
179
+ email = st.text_input(label='Email', placeholder='Enter Your Email')
180
+ username = st.text_input(label='Username', placeholder='Enter Your Username')
181
+ password = st.text_input(label='Password', placeholder='Enter Your Password', type='password')
182
+ re_password = st.text_input(label='Confirm Password', placeholder='Confirm Your Password', type='password')
183
+
184
+ if st.form_submit_button('Sign Up'):
185
+ if not email or not username or not password or not re_password:
186
+ st.error("Enter all the Credentials")
187
+ elif len(password) <= 3:
188
+ st.error("Password too short")
189
+ elif password != re_password:
190
+ st.error("Passwords do not match! Please Re-enter")
191
+ else:
192
+ result = create_user(username, password, email, datetime.datetime.now(pytz.timezone('Asia/Kolkata')))
193
+ if result == 'success':
194
+ st.success("Account created successfully!")
195
+ st.session_state.sign_up_successful = True
196
+ st.session_state.current_page = 'login'
197
+ st.experimental_rerun()
198
+
199
+ if not st.session_state.get('sign_up_successful', False):
200
+ st.markdown("<br>", unsafe_allow_html=True)
201
+ st.markdown("<div class='link-text'>Already have an account?</div>", unsafe_allow_html=True)
202
+ if st.button('Login'):
203
+ st.session_state.current_page = 'login'
204
  st.experimental_rerun()
 
 
205
 
206
+ # Reset password page
207
+ def reset_password_page():
208
+ st.markdown('<p class="big-font">Reset Password</p>', unsafe_allow_html=True)
209
+
210
+ with st.form(key='reset_password_form', clear_on_submit=True):
211
+ username = st.text_input(label='Username', value='', placeholder='Enter your username')
212
+ new_password = st.text_input(label='New Password', type='password', placeholder='Enter new password')
213
+ re_password = st.text_input(label='Confirm New Password', type='password', placeholder='Confirm new password')
214
+
215
+ if st.form_submit_button('Reset Password'):
216
+ if not username:
217
+ st.error("Enter your username.")
218
+ elif not username_exists(username):
219
+ st.error("Username not found. Enter a valid username.")
220
+ elif not new_password or not re_password:
221
+ st.error("Enter all the credentials.")
222
+ elif len(new_password) <= 3:
223
+ st.error("Password too short. Must be at least 4 characters.")
224
+ elif new_password != re_password:
225
+ st.error("Passwords do not match. Please re-enter.")
226
+ else:
227
+ reset_password(username, new_password)
228
+ st.success("Password has been reset successfully! Please login with your new password.")
229
+ st.session_state.current_page = 'login'
230
+ st.experimental_rerun()
231
+
232
+ st.markdown("<br>", unsafe_allow_html=True)
233
+ st.markdown("<div class='link-text'>Remember your password?</div>", unsafe_allow_html=True)
234
+ if st.button('Login'):
235
+ st.session_state.current_page = 'login'
 
 
 
 
 
236
  st.experimental_rerun()
237
 
238
+ # Main app logic
239
+ if st.session_state.current_page == 'login':
240
+ login()
241
+ elif st.session_state.current_page == 'sign_up':
242
+ signup()
243
+ elif st.session_state.current_page == 'reset_password':
244
+ reset_password_page()
245
+ elif st.session_state.current_page == 'home':
246
+ st.write("Welcome to the Performance Prediction Dashboard!")
247
+ # Implement your home page / dashboard here
248
+ else:
249
+ st.error("Page not found or not implemented yet.")