-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
235 lines (198 loc) · 7.94 KB
/
Copy pathapp.py
File metadata and controls
235 lines (198 loc) · 7.94 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
223
224
225
226
227
228
229
230
231
232
233
234
235
from flask import Flask, request, jsonify, render_template, session, redirect, url_for
import mysql.connector
from mysql.connector import Error
import pandas as pd
from database import create_connection
app = Flask(__name__)
app.secret_key = 'your_super_secret_key_12345'
@app.route('/')
def home():
if 'user_id' in session:
return redirect(url_for('dashboard'))
return redirect(url_for('login_page'))
@app.route('/login')
def login_page():
return render_template('login.html')
@app.route('/register')
def register_page():
return render_template('register.html')
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session:
return redirect(url_for('login_page'))
return render_template('dashboard.html', user_name=session.get('user_name'))
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('login_page'))
@app.route('/api/login', methods=['POST'])
def login_api():
data = request.get_json()
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM Students WHERE Email = %s AND Password = %s", (data['email'], data['password']))
user = cursor.fetchone()
cursor.close()
conn.close()
if user:
# login is successful, store the user's ID and name in the session.
session['user_id'] = user['ID']
session['user_name'] = user['Name']
return jsonify({'message': 'Login successful'})
else:
return jsonify({'error': 'Invalid credentials'}), 401
@app.route('/api/register', methods=['POST'])
def register_api():
data = request.get_json()
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO Students (Name, Email, Password) VALUES (%s, %s, %s)",
(data['name'], data['email'], data['password']))
conn.commit()
return jsonify({'message': 'User registered successfully!'})
except Error as e:
return jsonify({'error': str(e)}), 400
finally:
cursor.close()
conn.close()
@app.route('/api/subjects', methods=['GET', 'POST'])
def subjects_api():
if 'user_id' not in session:
return jsonify({'error': 'Not authenticated'}), 401
student_id = session['user_id']
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
cursor = conn.cursor(dictionary=True)
if request.method == 'POST':
data = request.get_json()
try:
cursor.execute("INSERT INTO Subjects (Name, Difficulty_Level, Student_ID) VALUES (%s, %s, %s)",
(data['name'], data['difficulty'], student_id))
conn.commit()
return jsonify({'message': 'Subject added successfully!'})
except Error as e:
return jsonify({'error': str(e)}), 400
finally:
cursor.close()
conn.close()
if request.method == 'GET':
try:
cursor.execute("SELECT * FROM Subjects WHERE Student_ID = %s", (student_id,))
subjects = cursor.fetchall()
return jsonify(subjects)
except Error as e:
return jsonify({'error': str(e)}), 400
finally:
cursor.close()
conn.close()
@app.route('/api/study-history', methods=['POST'])
def study_history_api():
if 'user_id' not in session:
return jsonify({'error': 'Not authenticated'}), 401
student_id = session['user_id']
data = request.get_json()
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO Study_History (Student_ID, Subject_ID, Date, Hours_Studied) VALUES (%s, %s, %s, %s)",
(student_id, data['subject_id'], data['date'], data['hours']))
conn.commit()
return jsonify({'message': 'Study session logged successfully!'})
except Error as e:
return jsonify({'error': str(e)}), 400
finally:
cursor.close()
conn.close()
@app.route('/api/assignments', methods=['GET', 'POST'])
def assignments_api():
if 'user_id' not in session:
return jsonify({'error': 'Not authenticated'}), 401
student_id = session['user_id']
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
cursor = conn.cursor(dictionary=True)
if request.method == 'POST':
data = request.get_json()
try:
cursor.execute("INSERT INTO Assignments (Subject_ID, Due_Date, Status, Student_ID) VALUES (%s, %s, %s, %s)",
(data['subject_id'], data['due_date'], 'Pending', student_id))
conn.commit()
return jsonify({'message': 'Assignment added successfully!'})
except Error as e:
return jsonify({'error': str(e)}), 400
finally:
cursor.close()
conn.close()
if request.method == 'GET':
query = """
SELECT s.Name as Subject_Name, a.Due_Date, a.Status
FROM Assignments a
JOIN Subjects s ON a.Subject_ID = s.Subject_ID
WHERE a.Student_ID = %s ORDER BY a.Due_Date ASC
"""
try:
cursor.execute(query, (student_id,))
assignments = cursor.fetchall()
for assignment in assignments:
assignment['Due_Date'] = assignment['Due_Date'].strftime('%Y-%m-%d')
return jsonify(assignments)
except Error as e:
return jsonify({'error': str(e)}), 400
finally:
cursor.close()
conn.close()
@app.route('/api/recommendations')
def recommendations_api():
if 'user_id' not in session:
return jsonify({'error': 'Not authenticated'}), 401
student_id = session['user_id']
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
query = "SELECT Hours_Studied FROM Study_History WHERE Student_ID = %s"
try:
df = pd.read_sql(query, conn, params=(student_id,))
if len(df) < 2:
return jsonify({'recommendations': 'Log at least two study sessions to get a personalized plan.'})
baseline_hours = df['Hours_Studied'].mean()
multipliers = {'Hard': 1.5, 'Medium': 1.0, 'Easy': 0.75}
recommendations = {
'Easy': f"{baseline_hours * multipliers['Easy']:.2f} hours",
'Medium': f"{baseline_hours * multipliers['Medium']:.2f} hours",
'Hard': f"{baseline_hours * multipliers['Hard']:.2f} hours"
}
return jsonify({'recommendations': recommendations})
except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
if conn and conn.is_connected():
conn.close()
@app.route('/api/chart-data')
def chart_data_api():
if 'user_id' not in session:
return jsonify({'error': 'Not authenticated'}), 401
student_id = session['user_id']
conn = create_connection()
if not conn: return jsonify({'error': 'Database connection failed'}), 500
query = """
SELECT s.Name, SUM(sh.Hours_Studied) as Total_Hours
FROM Study_History sh JOIN Subjects s ON sh.Subject_ID = s.Subject_ID
WHERE sh.Student_ID = %s
GROUP BY s.Name ORDER BY Total_Hours DESC
"""
try:
df = pd.read_sql(query, conn, params=(student_id,))
if df.empty:
return jsonify({'error': 'No study data available to create charts.'}), 404
chart_data = {'labels': df['Name'].tolist(), 'data': df['Total_Hours'].tolist()}
return jsonify(chart_data)
except Error as e:
return jsonify({'error': str(e)}), 500
finally:
if conn and conn.is_connected():
conn.close()
if __name__ == '__main__':
app.run(debug=True)