harshdhane commited on
Commit
cdc9786
·
verified ·
1 Parent(s): f863580

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -784
app.py DELETED
@@ -1,784 +0,0 @@
1
- from flask import Flask, render_template, request, jsonify, session, redirect, url_for, send_file
2
- from flask_sqlalchemy import SQLAlchemy
3
- from flask_mail import Mail, Message
4
- from werkzeug.security import generate_password_hash, check_password_hash
5
- import sqlite3
6
- import pandas as pd
7
- import os
8
- import cv2
9
- import numpy as np
10
- from datetime import datetime, time
11
- import base64
12
- import json
13
-
14
- app = Flask(__name__)
15
- app.config['SECRET_KEY'] = 'your_secret_key_here'
16
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
17
- app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
18
-
19
- # Email configuration
20
- app.config['MAIL_SERVER'] = 'smtp.gmail.com'
21
- app.config['MAIL_PORT'] = 465
22
- app.config['MAIL_USERNAME'] = 'your_email@gmail.com' # Replace with your email
23
- app.config['MAIL_PASSWORD'] = 'your_password' # Replace with your password
24
- app.config['MAIL_USE_TLS'] = False
25
- app.config['MAIL_USE_SSL'] = True
26
-
27
- db = SQLAlchemy(app)
28
- mail = Mail(app)
29
-
30
- # User Model
31
- class User(db.Model):
32
- id = db.Column(db.Integer, primary_key=True)
33
- full_name = db.Column(db.String(100), nullable=False)
34
- email = db.Column(db.String(100), unique=True, nullable=False)
35
- username = db.Column(db.String(50), unique=True, nullable=False)
36
- password = db.Column(db.String(100), nullable=False)
37
- role = db.Column(db.String(10), nullable=False)
38
- enrollment_number = db.Column(db.String(20), unique=True, nullable=True)
39
- phone_number = db.Column(db.String(20), nullable=True)
40
- student_number = db.Column(db.String(20), unique=True, nullable=True)
41
- parent_number = db.Column(db.String(20), nullable=True)
42
- parent_email = db.Column(db.String(100), nullable=True)
43
- selected_class = db.Column(db.String(10), nullable=True)
44
- selected_regular_subjects = db.Column(db.Text, nullable=True) # JSON list
45
- selected_specializations = db.Column(db.Text, nullable=True) # JSON list
46
- selected_batch = db.Column(db.String(20), nullable=True)
47
- selected_practicals = db.Column(db.Text, nullable=True) # JSON list
48
-
49
- # Timetable Database Setup
50
- def get_db_connection():
51
- conn = sqlite3.connect('config.db')
52
- conn.row_factory = sqlite3.Row
53
- return conn
54
-
55
- def init_timetable_db():
56
- conn = get_db_connection()
57
- conn.execute('''
58
- CREATE TABLE IF NOT EXISTS teacher_config (
59
- id INTEGER PRIMARY KEY AUTOINCREMENT,
60
- class_name TEXT NOT NULL,
61
- config_type TEXT NOT NULL,
62
- name TEXT NOT NULL
63
- )
64
- ''')
65
- conn.commit()
66
- conn.close()
67
-
68
- # Create databases
69
- with app.app_context():
70
- db.create_all()
71
- init_timetable_db()
72
-
73
- # Attendance System Setup
74
- face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
75
- dataset_path = "./face_dataset/"
76
- attendance_path = "./attendance_data/"
77
- os.makedirs(dataset_path, exist_ok=True)
78
- os.makedirs(attendance_path, exist_ok=True)
79
-
80
- # Combined Routes
81
- @app.route('/')
82
- def index():
83
- return render_template('index.html')
84
-
85
- @app.route('/signup', methods=['POST'])
86
- def signup():
87
- data = request.json
88
- full_name = data.get('full_name')
89
- email = data.get('email')
90
- username = data.get('username')
91
- password = data.get('password')
92
- role = data.get('role')
93
- enrollment = data.get('enrollment_number') if role == 'student' else None
94
- phone_number = data.get('phone_number') if role == 'teacher' else None
95
- student_number = data.get('student_number') if role == 'student' else None
96
- parent_number = data.get('parent_number') if role == 'student' else None
97
- parent_email = data.get('parent_email') if role == 'student' else None
98
-
99
- if not all([full_name, email, username, password, role]):
100
- return jsonify({'success': False, 'message': 'All fields are required!'})
101
- if role == 'student' and not enrollment:
102
- return jsonify({'success': False, 'message': 'Enrollment number is required for students!'})
103
- if role == 'teacher' and not phone_number:
104
- return jsonify({'success': False, 'message': 'Phone number is required for teachers!'})
105
-
106
- if User.query.filter((User.username == username) | (User.email == email) |
107
- (User.enrollment_number == enrollment) | (User.student_number == student_number)).first():
108
- return jsonify({'success': False, 'message': 'Username, email, enrollment, or student number already exists!'})
109
-
110
- hashed = generate_password_hash(password)
111
- u = User(
112
- full_name=full_name, email=email,
113
- username=username, password=hashed, role=role,
114
- enrollment_number=enrollment,
115
- phone_number=phone_number,
116
- student_number=student_number,
117
- parent_number=parent_number,
118
- parent_email=parent_email
119
- )
120
- db.session.add(u)
121
- db.session.commit()
122
- return jsonify({'success': True, 'message': 'Account created successfully! Please log in.'})
123
-
124
- @app.route('/login', methods=['POST'])
125
- def login():
126
- data = request.json
127
- username = data.get('username')
128
- password = data.get('password')
129
- role = data.get('role')
130
-
131
- user = User.query.filter_by(username=username, role=role).first()
132
- if user and check_password_hash(user.password, password):
133
- session['user_id'] = user.id
134
- session['role'] = user.role
135
- redirect_url = '/teacher_dashboard' if role == 'teacher' else '/student_dashboard'
136
- return jsonify({'success': True, 'redirect': redirect_url})
137
- return jsonify({'success': False, 'message': 'Invalid username or password'})
138
-
139
- @app.route('/logout')
140
- def logout():
141
- session.clear()
142
- return redirect(url_for('index'))
143
-
144
- @app.route('/teacher_dashboard')
145
- def teacher_dashboard():
146
- if 'user_id' not in session or session['role'] != 'teacher':
147
- return redirect(url_for('index'))
148
- user = db.session.get(User, session['user_id'])
149
- return render_template('teacher_dashboard.html', user=user, selected_class=user.selected_class)
150
-
151
- @app.route('/api/update_teacher_profile', methods=['POST'])
152
- def update_teacher_profile():
153
- if 'user_id' not in session or session['role'] != 'teacher':
154
- return jsonify({'success': False, 'message': 'Unauthorized'}), 401
155
- data = request.json
156
- user = db.session.get(User, session['user_id'])
157
- user.full_name = data['full_name']
158
- user.email = data['email']
159
- user.phone_number = data['phone_number']
160
- db.session.commit()
161
- return jsonify({'success': True, 'message': 'Profile updated'})
162
-
163
- @app.route('/get_students', methods=['GET'])
164
- def get_students():
165
- class_name = request.args.get('class')
166
- students = User.query.filter_by(role='student', selected_class=class_name).all()
167
- students_data = [{'id': s.id, 'full_name': s.full_name, 'enrollment_number': s.enrollment_number} for s in students]
168
- return jsonify({'students': students_data})
169
-
170
- @app.route('/api/select_teacher_class', methods=['POST'])
171
- def select_teacher_class():
172
- if 'user_id' not in session or session['role'] != 'teacher':
173
- return jsonify({'success': False}), 401
174
- data = request.json
175
- cls = data.get('class')
176
- user = db.session.get(User, session['user_id'])
177
- user.selected_class = cls
178
- db.session.commit()
179
- return jsonify({'success': True})
180
-
181
- @app.route('/get_student_details', methods=['GET'])
182
- def get_student_details():
183
- student_id = request.args.get('id')
184
- student = db.session.get(User, student_id)
185
- if not student or student.role != 'student':
186
- return jsonify({'error': 'Student not found'}), 404
187
-
188
- subject_attendance = get_subject_attendance(student)
189
-
190
- regular_subjects = [{'name': subj, 'attendance_count': subject_attendance['regular'].get(subj, {'attendance': 0})['attendance'], 'total_count': subject_attendance['regular'].get(subj, {'total': 0})['total']} for subj in json.loads(student.selected_regular_subjects or '[]')]
191
- specialization_subjects = [{'name': subj, 'attendance_count': subject_attendance['specialization'].get(subj, {'attendance': 0})['attendance'], 'total_count': subject_attendance['specialization'].get(subj, {'total': 0})['total']} for subj in json.loads(student.selected_specializations or '[]')]
192
- practical_subjects = [{'name': subj, 'batch': student.selected_batch or 'N/A', 'attendance_count': subject_attendance['practical'].get(subj, {'attendance': 0})['attendance'], 'total_count': subject_attendance['practical'].get(subj, {'total': 0})['total']} for subj in json.loads(student.selected_practicals or '[]')]
193
-
194
- face_folder = os.path.join(dataset_path, student.selected_class or '')
195
- face_file = f"{student.enrollment_number}_{student.full_name}.npy"
196
- face_registered = os.path.exists(os.path.join(face_folder, face_file))
197
-
198
- student_data = {
199
- 'enrollment_number': student.enrollment_number,
200
- 'email': student.email,
201
- 'student_number': student.student_number,
202
- 'parent_number': student.parent_number,
203
- 'parent_email': student.parent_email,
204
- 'regular_subjects': regular_subjects,
205
- 'specialization_subjects': specialization_subjects,
206
- 'practical_subjects': practical_subjects,
207
- 'face_registered': face_registered
208
- }
209
- return jsonify(student_data)
210
-
211
- @app.route('/student_dashboard')
212
- def student_dashboard():
213
- if 'user_id' not in session or session['role'] != 'student':
214
- return redirect(url_for('index'))
215
- user = db.session.get(User, session['user_id'])
216
- face_folder = os.path.join(dataset_path, (user.selected_class or ''))
217
- face_file = f"{user.enrollment_number}_{user.full_name}.npy"
218
- face_exists = os.path.exists(os.path.join(face_folder, face_file))
219
- subject_attendance = get_subject_attendance(user)
220
- teachers = User.query.filter_by(role='teacher', selected_class=user.selected_class).all()
221
- return render_template('student_dashboard.html',
222
- user=user,
223
- selected_regular_subjects=json.loads(user.selected_regular_subjects or '[]'),
224
- selected_specializations=json.loads(user.selected_specializations or '[]'),
225
- selected_practicals=json.loads(user.selected_practicals or '[]'),
226
- subject_attendance=subject_attendance,
227
- face_exists=face_exists,
228
- teachers=teachers)
229
-
230
- @app.route('/api/update_profile', methods=['POST'])
231
- def update_profile():
232
- if 'user_id' not in session or session['role'] != 'student':
233
- return jsonify({'success': False, 'message': 'Unauthorized'}), 401
234
- data = request.json
235
- user = db.session.get(User, session['user_id'])
236
- user.full_name = data['full_name']
237
- user.enrollment_number = data['enrollment_number']
238
- user.email = data['email']
239
- user.student_number = data['student_number']
240
- user.parent_number = data['parent_number']
241
- user.parent_email = data['parent_email']
242
- db.session.commit()
243
- return jsonify({'success': True, 'message': 'Profile updated'})
244
-
245
- @app.route('/api/select_class', methods=['POST'])
246
- def api_select_class():
247
- if 'user_id' not in session or session['role'] != 'student':
248
- return jsonify({'success': False}), 401
249
- data = request.json
250
- cls = data.get('class')
251
- user = db.session.get(User, session['user_id'])
252
- user.selected_class = cls
253
- db.session.commit()
254
- return jsonify({'success': True})
255
-
256
- @app.route('/api/update_regular_subjects', methods=['POST'])
257
- def update_regular_subjects():
258
- if 'user_id' not in session:
259
- return jsonify(success=False), 401
260
- subjects = request.json.get('subjects')
261
- u = db.session.get(User, session['user_id'])
262
- u.selected_regular_subjects = json.dumps(subjects)
263
- db.session.commit()
264
- return jsonify(success=True)
265
-
266
- @app.route('/api/update_specializations', methods=['POST'])
267
- def update_specializations():
268
- if 'user_id' not in session:
269
- return jsonify(success=False), 401
270
- subjects = request.json.get('subjects')
271
- u = db.session.get(User, session['user_id'])
272
- u.selected_specializations = json.dumps(subjects)
273
- db.session.commit()
274
- return jsonify(success=True)
275
-
276
- @app.route('/api/update_batch', methods=['POST'])
277
- def update_batch():
278
- if 'user_id' not in session:
279
- return jsonify(success=False), 401
280
- batch = request.json.get('batch')
281
- u = db.session.get(User, session['user_id'])
282
- u.selected_batch = batch
283
- db.session.commit()
284
- return jsonify(success=True)
285
-
286
- @app.route('/api/update_practicals', methods=['POST'])
287
- def update_practicals():
288
- if 'user_id' not in session:
289
- return jsonify(success=False), 401
290
- practs = request.json.get('practicals')
291
- u = db.session.get(User, session['user_id'])
292
- u.selected_practicals = json.dumps(practs)
293
- db.session.commit()
294
- return jsonify(success=True)
295
-
296
- def get_excel_filename(class_name):
297
- if class_name:
298
- return f"{class_name}_timetable.xlsx"
299
- return "timetable.xlsx"
300
-
301
- @app.route('/timetable')
302
- def timetable_page():
303
- if 'user_id' not in session or session['role'] != 'teacher':
304
- return redirect(url_for('index'))
305
- return render_template('timetable.html')
306
-
307
- @app.route('/add_config', methods=['POST'])
308
- def add_config():
309
- data = request.get_json()
310
- class_name = data.get("class")
311
- config_type = data.get("type")
312
- name = data.get("name")
313
- if not (class_name and config_type and name):
314
- return jsonify({"error": "Missing parameters"}), 400
315
- conn = get_db_connection()
316
- conn.execute('INSERT INTO teacher_config (class_name, config_type, name) VALUES (?, ?, ?)',
317
- (class_name, config_type, name))
318
- conn.commit()
319
- conn.close()
320
- return jsonify({"message": "Added successfully"})
321
-
322
- @app.route('/delete_config', methods=['POST'])
323
- def delete_config():
324
- data = request.get_json()
325
- class_name = data.get("class")
326
- config_type = data.get("type")
327
- name = data.get("name")
328
- if not (class_name and config_type and name):
329
- return jsonify({"error": "Missing parameters"}), 400
330
- conn = get_db_connection()
331
- conn.execute('DELETE FROM teacher_config WHERE class_name=? AND config_type=? AND name=?',
332
- (class_name, config_type, name))
333
- conn.commit()
334
- conn.close()
335
- return jsonify({"message": "Deleted successfully"})
336
-
337
- @app.route('/get_config', methods=['GET'])
338
- def get_config():
339
- class_name = request.args.get("class")
340
- config_type = request.args.get("type")
341
- if not (class_name and config_type):
342
- return jsonify([])
343
- conn = get_db_connection()
344
- configs = conn.execute('SELECT name FROM teacher_config WHERE class_name=? AND config_type=?',
345
- (class_name, config_type)).fetchall()
346
- conn.close()
347
- return jsonify([row["name"] for row in configs])
348
-
349
- @app.route('/load', methods=['GET'])
350
- def load_timetable():
351
- class_name = request.args.get('class')
352
- filename = get_excel_filename(class_name)
353
- if not os.path.exists(filename):
354
- return jsonify({})
355
- df = pd.read_excel(filename, index_col=0)
356
- return df.to_json()
357
-
358
- @app.route('/save', methods=['POST'])
359
- def save_timetable():
360
- payload = request.get_json()
361
- teacher_class = payload.get("class", "")
362
- data = payload.get("timetable", {})
363
- filename = get_excel_filename(teacher_class)
364
- df = pd.DataFrame(data)
365
- df.to_excel(filename)
366
- return jsonify({'message': f'Saved successfully to {filename}!'})
367
-
368
- @app.route('/download_excel', methods=['GET'])
369
- def download_excel():
370
- class_name = request.args.get('class')
371
- filename = get_excel_filename(class_name)
372
- if not os.path.exists(filename):
373
- return "File not found", 404
374
- return send_file(filename, as_attachment=True)
375
-
376
- def distance(v1, v2):
377
- return np.sqrt(((v1 - v2) ** 2).sum())
378
-
379
- def knn(train, test, k=5):
380
- dist = []
381
- for i in range(train.shape[0]):
382
- ix = train[i, :-1]
383
- iy = train[i, -1]
384
- d = distance(test, ix)
385
- dist.append([d, iy])
386
- dk = sorted(dist, key=lambda x: x[0])[:k]
387
- labels = np.array(dk)[:, -1]
388
- return np.unique(labels, return_counts=True)[0][0]
389
-
390
- class AttendanceSystem:
391
- def __init__(self, class_name):
392
- self.class_name = class_name
393
- self.main_file = os.path.join(attendance_path, f"{class_name}.xlsx")
394
- self.pending_file = os.path.join(attendance_path, f"{class_name}_pending.xlsx")
395
- self.columns = ["Enrollment", "Name", "Date", "Day", "CheckIn", "CheckOut"]
396
-
397
- for f in [self.main_file, self.pending_file]:
398
- if not os.path.exists(f):
399
- pd.DataFrame(columns=self.columns).to_excel(f, index=False)
400
-
401
- def checkin(self, enrollment, name):
402
- now = datetime.now()
403
- today = now.strftime("%Y-%m-%d")
404
- checkin_time = now.strftime("%H.%M")
405
-
406
- df_main = pd.read_excel(self.main_file)
407
- if ((df_main["Enrollment"] == enrollment) & (df_main["Date"] == today)).any():
408
- return False, "You have already checked in and checked out today."
409
-
410
- df_pending = pd.read_excel(self.pending_file)
411
- if ((df_pending["Enrollment"] == enrollment) & (df_pending["Date"] == today)).any():
412
- return False, "You have already checked in today. Please check out first."
413
-
414
- if now.time() < datetime.strptime("08:00", "%H:%M").time():
415
- return False, "Check-in starts at 8 AM."
416
-
417
- day_name = now.strftime("%A")
418
- new_entry = pd.DataFrame([[enrollment, name, today, day_name, checkin_time, ""]],
419
- columns=self.columns)
420
- df_pending = pd.concat([df_pending, new_entry], ignore_index=True)
421
- df_pending.to_excel(self.pending_file, index=False)
422
-
423
- return True, "Check-in successful. Please remember to check out later."
424
-
425
- def checkout(self, enrollment):
426
- now = datetime.now()
427
- today = now.strftime("%Y-%m-%d")
428
- checkout_time = now.strftime("%H.%M")
429
-
430
- df_pending = pd.read_excel(self.pending_file)
431
- df_main = pd.read_excel(self.main_file)
432
-
433
- has_main = ((df_main["Enrollment"] == enrollment) & (df_main["Date"] == today)).any()
434
- has_pending = ((df_pending["Enrollment"] == enrollment) & (df_pending["Date"] == today)).any()
435
-
436
- if not has_pending and has_main:
437
- return False, "You have already checked out today."
438
-
439
- if not has_pending:
440
- return False, "No pending check-in found. Please check in first."
441
-
442
- if now.time() > datetime.strptime("18:00", "%H:%M").time():
443
- return False, "You missed check-out time. Contact your class teacher."
444
-
445
- idx = df_pending[(df_pending["Enrollment"] == enrollment) & (df_pending["Date"] == today)].index[0]
446
- pending_entry = df_pending.loc[idx]
447
-
448
- new_row = {
449
- "Enrollment": pending_entry["Enrollment"],
450
- "Name": pending_entry["Name"],
451
- "Date": today,
452
- "Day": pending_entry["Day"],
453
- "CheckIn": pending_entry["CheckIn"],
454
- "CheckOut": checkout_time
455
- }
456
- df_main = pd.concat([df_main, pd.DataFrame([new_row])], ignore_index=True)
457
- df_main.to_excel(self.main_file, index=False)
458
-
459
- df_pending = df_pending.drop(idx)
460
- df_pending.to_excel(self.pending_file, index=False)
461
-
462
- return True, "Check-out successful. Attendance recorded."
463
-
464
- import pandas as pd
465
- from datetime import datetime, time
466
-
467
- def parse_time(val):
468
- if pd.isna(val):
469
- return None
470
- s = str(val).replace('.', ':')
471
- if ':' not in s and len(s) >= 3 and s.isdigit():
472
- s = s[:-2] + ':' + s[-2:]
473
- try:
474
- return datetime.strptime(s, '%H:%M').time()
475
- except ValueError:
476
- return datetime.strptime(s, '%I:%M').time()
477
-
478
- def parse_timetable_time(time_str):
479
- time_str = time_str.replace('.', ':')
480
- hour, minute = map(int, time_str.split(':'))
481
- if 1 <= hour <= 5:
482
- hour += 12
483
- return time(hour, minute)
484
-
485
- def get_slot_type(content):
486
- content = "" if pd.isna(content) else str(content)
487
- if "Batch" in content:
488
- return "practical"
489
- elif "<br>" in content:
490
- return "specialization"
491
- elif content in ["Short Break", "Lunch Break"]:
492
- return "break"
493
- elif content.strip() == "":
494
- return "break"
495
- else:
496
- return "regular"
497
-
498
- def parse_practical(content):
499
- lines = content.split('<br>')
500
- batch_subjects = {}
501
- for line in lines:
502
- if ':' in line:
503
- batch, subject = line.split(':')
504
- batch = batch.strip().replace('Batch ', '')
505
- subject = subject.strip()
506
- batch_subjects[batch] = subject
507
- return batch_subjects
508
-
509
- def parse_specialization(content):
510
- return [subj.strip() for subj in content.split('<br>')]
511
-
512
- def get_slots(df, day):
513
- row = df.loc[day]
514
- slots = []
515
- for col in df.columns:
516
- start_str, end_str = col.split(" - ")
517
- start_time = parse_timetable_time(start_str)
518
- end_time = parse_timetable_time(end_str)
519
- content = row[col]
520
- if pd.isna(content) or str(content).strip() == "":
521
- continue
522
- slots.append({
523
- "start": start_time,
524
- "end": end_time,
525
- "content": str(content)
526
- })
527
- return slots
528
-
529
- def get_subject_attendance(user):
530
- class_name = user.selected_class
531
- attendance_file = os.path.join(attendance_path, f"{class_name}.xlsx")
532
- if not os.path.exists(attendance_file):
533
- return {'regular': {}, 'specialization': {}, 'practical': {}}
534
- df_att = pd.read_excel(attendance_file)
535
- all_dates = df_att['Date'].unique()
536
- timetable_file = f"{class_name}_timetable.xlsx"
537
- if not os.path.exists(timetable_file):
538
- return {'regular': {}, 'specialization': {}, 'practical': {}}
539
- df_timetable = pd.read_excel(timetable_file, index_col=0)
540
- regular_counts = {subj: {'attendance': 0, 'total': 0} for subj in json.loads(user.selected_regular_subjects or '[]')}
541
- spec_counts = {subj: {'attendance': 0, 'total': 0} for subj in json.loads(user.selected_specializations or '[]')}
542
- prac_counts = {subj: {'attendance': 0, 'total': 0} for subj in json.loads(user.selected_practicals or '[]')}
543
- for date in all_dates:
544
- day = datetime.strptime(date, '%Y-%m-%d').strftime('%A')
545
- if day not in df_timetable.index:
546
- continue
547
- slots = get_slots(df_timetable, day)
548
- student_att = df_att[(df_att['Enrollment'] == user.enrollment_number) & (df_att['Date'] == date)]
549
- if not student_att.empty:
550
- check_in_str = student_att['CheckIn'].values[0]
551
- check_out_str = student_att['CheckOut'].values[0]
552
- check_in_time = parse_time(check_in_str)
553
- check_out_time = parse_time(check_out_str)
554
- else:
555
- check_in_time = None
556
- check_out_time = None
557
- for slot in slots:
558
- slot_start = slot['start']
559
- slot_end = slot['end']
560
- content = slot['content']
561
- slot_type = get_slot_type(content)
562
- if slot_type == 'regular':
563
- subject = content
564
- if subject in regular_counts:
565
- regular_counts[subject]['total'] += 1
566
- if check_in_time and check_in_time <= slot_start and check_out_time >= slot_end:
567
- regular_counts[subject]['attendance'] += 1
568
- elif slot_type == 'specialization':
569
- subjects = parse_specialization(content)
570
- selected_specs = json.loads(user.selected_specializations or '[]')
571
- for selected_spec in selected_specs:
572
- if selected_spec in subjects:
573
- spec_counts[selected_spec]['total'] += 1
574
- if check_in_time and check_in_time <= slot_start and check_out_time >= slot_end:
575
- spec_counts[selected_spec]['attendance'] += 1
576
- elif slot_type == 'practical':
577
- batch_subjects = parse_practical(content)
578
- if user.selected_batch in batch_subjects:
579
- subject = batch_subjects[user.selected_batch]
580
- if subject in prac_counts:
581
- prac_counts[subject]['total'] += 1
582
- if check_in_time and check_in_time <= slot_start and check_out_time >= slot_end:
583
- prac_counts[subject]['attendance'] += 1
584
- return {
585
- 'regular': regular_counts,
586
- 'specialization': spec_counts,
587
- 'practical': prac_counts
588
- }
589
-
590
- @app.route('/check_attendance', methods=['GET'])
591
- def check_attendance():
592
- students = User.query.filter_by(role='student').all()
593
- for student in students:
594
- subject_attendance = get_subject_attendance(student)
595
- total_attendance = 0
596
- total_possible = 0
597
- for subj_type in ['regular', 'specialization', 'practical']:
598
- for subj, counts in subject_attendance[subj_type].items():
599
- total_attendance += counts['attendance']
600
- total_possible += counts['total']
601
- if total_possible > 0:
602
- overall_percentage = (total_attendance / total_possible) * 100
603
- if overall_percentage < 75:
604
- details = {
605
- 'regular': [],
606
- 'specialization': [],
607
- 'practical': []
608
- }
609
- for subj_type in ['regular', 'specialization', 'practical']:
610
- for subj, counts in subject_attendance[subj_type].items():
611
- percentage = (counts['attendance'] / counts['total'] * 100) if counts['total'] > 0 else 0
612
- details[subj_type].append({
613
- 'subject': subj,
614
- 'attendance_count': counts['attendance'],
615
- 'total_count': counts['total'],
616
- 'percentage': round(percentage, 2)
617
- })
618
- send_attendance_email(student, overall_percentage, details)
619
- return 'Attendance check completed'
620
-
621
- def send_attendance_email(student, overall_percentage, details):
622
- subject = "Low Attendance Alert"
623
- recipients = [student.email]
624
- if student.parent_email:
625
- recipients.append(student.parent_email)
626
- body = f"""
627
- Dear {student.full_name},
628
-
629
- Your overall attendance average is {overall_percentage:.2f}%, which is below the required 75%.
630
-
631
- Here are your attendance details:
632
-
633
- Regular Subjects:
634
- """
635
- for subj in details['regular']:
636
- body += f"- {subj['subject']}: {subj['attendance_count']}/{subj['total_count']} ({subj['percentage']}%\n"
637
- body += "\nSpecialization Subjects:\n"
638
- for subj in details['specialization']:
639
- body += f"- {subj['subject']}: {subj['attendance_count']}/{subj['total_count']} ({subj['percentage']}%\n"
640
- body += "\nPractical Subjects:\n"
641
- for subj in details['practical']:
642
- body += f"- {subj['subject']}: {subj['attendance_count']}/{subj['total_count']} ({subj['percentage']}%\n"
643
- body += "\nPlease take necessary actions to improve your attendance.\n\nBest regards,\nAttendance System"
644
-
645
- msg = Message(subject, recipients=recipients, body=body)
646
- mail.send(msg)
647
-
648
- @app.route('/mark_attendance')
649
- def mark_attendance_page():
650
- return render_template('mark.html')
651
-
652
- @app.route('/register_face')
653
- def register_face_page():
654
- if 'user_id' not in session or session['role'] != 'student':
655
- return redirect(url_for('index'))
656
- return render_template('register.html')
657
-
658
- @app.route('/api/register_face', methods=['POST'])
659
- def register_face():
660
- data = request.json
661
- class_name = data['class_name']
662
- name = data['name']
663
- enrollment = data['enrollment']
664
- images = data['images']
665
-
666
- class_folder = os.path.join(dataset_path, class_name)
667
- os.makedirs(class_folder, exist_ok=True)
668
-
669
- face_data = []
670
- for img_data in images:
671
- img_bytes = base64.b64decode(img_data.split(",")[1])
672
- np_arr = np.frombuffer(img_bytes, np.uint8)
673
- img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
674
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
675
- gray = cv2.equalizeHist(gray)
676
- faces = face_cascade.detectMultiScale(gray, 1.3, 5)
677
- for (x, y, w, h) in faces[:1]:
678
- face = img[y:y+h, x:x+w]
679
- face = cv2.resize(face, (100, 100))
680
- face_data.append(face.flatten())
681
- flipped = cv2.flip(face, 1)
682
- face_data.append(flipped.flatten())
683
-
684
- if face_data:
685
- face_data = np.array(face_data)
686
- filename = f"{enrollment}_{name}.npy"
687
- np.save(os.path.join(class_folder, filename), face_data)
688
- return jsonify({"status": "success", "message": f"{len(face_data)} faces saved"})
689
- return jsonify({"status": "fail", "message": "No faces detected"})
690
-
691
- @app.route('/api/identify_face', methods=['POST'])
692
- def identify_face():
693
- data = request.json
694
- class_name = data['class_name']
695
- img_data = data['image']
696
- img_bytes = base64.b64decode(img_data.split(",")[1])
697
- np_arr = np.frombuffer(img_bytes, np.uint8)
698
- img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
699
-
700
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
701
- faces = face_cascade.detectMultiScale(gray, 1.3, 5)
702
-
703
- class_folder = os.path.join(dataset_path, class_name)
704
- if not os.path.exists(class_folder):
705
- return jsonify({"status": "fail", "message": "No data for this class"})
706
-
707
- face_data = []
708
- labels = []
709
- names = {}
710
- class_id = 0
711
- for file in os.listdir(class_folder):
712
- if file.endswith('.npy'):
713
- data_arr = np.load(os.path.join(class_folder, file))
714
- face_data.append(data_arr)
715
- parts = file[:-4].split('_', 1)
716
- labels.extend([class_id] * data_arr.shape[0])
717
- names[class_id] = {'enrollment': parts[0], 'name': parts[1]}
718
- class_id += 1
719
-
720
- if not face_data:
721
- return jsonify({"status": "fail", "message": "No trained data found"})
722
-
723
- X_train = np.concatenate(face_data, axis=0)
724
- y_train = np.array(labels).reshape(-1, 1)
725
- trainset = np.hstack((X_train, y_train))
726
-
727
- for (x, y, w, h) in faces[:1]:
728
- face = img[y:y+h, x:x+w]
729
- face = cv2.resize(face, (100, 100)).flatten()
730
- pred_id = knn(trainset, face)
731
- info = names.get(pred_id)
732
- if info:
733
- return jsonify({
734
- "status": "success",
735
- "name": info['name'],
736
- "enrollment": info['enrollment']
737
- })
738
- return jsonify({"status": "fail", "message": "Face not recognized"})
739
-
740
- @app.route('/api/checkin', methods=['POST'])
741
- def api_checkin():
742
- data = request.json
743
- class_name = data['class_name']
744
- enrollment = data['enrollment']
745
- name = data['name']
746
- attendance = AttendanceSystem(class_name)
747
- ok, msg = attendance.checkin(enrollment, name)
748
- status = "success" if ok else "fail"
749
- return jsonify({"status": status, "message": msg})
750
-
751
- @app.route('/api/checkout', methods=['POST'])
752
- def api_checkout():
753
- data = request.json
754
- class_name = data['class_name']
755
- enrollment = data['enrollment']
756
- attendance = AttendanceSystem(class_name)
757
- ok, msg = attendance.checkout(enrollment)
758
- status = "success" if ok else "fail"
759
- return jsonify({"status": status, "message": msg})
760
-
761
- # New endpoint to get the overall attendance average
762
- @app.route('/api/get_attendance_average', methods=['POST'])
763
- def get_attendance_average():
764
- data = request.json
765
- class_name = data['class_name']
766
- enrollment = data['enrollment']
767
- user = User.query.filter_by(enrollment_number=enrollment, selected_class=class_name, role='student').first()
768
- if not user:
769
- return jsonify({'error': 'Student not found'}), 404
770
- subject_attendance = get_subject_attendance(user)
771
- total_attendance = 0
772
- total_possible = 0
773
- for subj_type in ['regular', 'specialization', 'practical']:
774
- for subj, counts in subject_attendance[subj_type].items():
775
- total_attendance += counts['attendance']
776
- total_possible += counts['total']
777
- if total_possible > 0:
778
- overall_percentage = (total_attendance / total_possible) * 100
779
- else:
780
- overall_percentage = 0
781
- return jsonify({'overall_percentage': round(overall_percentage, 2)})
782
-
783
- if __name__ == '__main__':
784
- app.run(host='0.0.0.0', port=7860, debug=True)