-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
134 lines (111 loc) · 5.07 KB
/
controller.py
File metadata and controls
134 lines (111 loc) · 5.07 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
# controller.py
import cv2
import pandas as pd
import pickle
import os
from datetime import datetime
import csv
import numpy as np
import streamlit as st
import subprocess
from insightface.app import FaceAnalysis
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
def mark_attendance():
st.header("Video File Attendance")
ENCODING_DIR = "split_encodings"
ATTENDANCE_DIR = "attendance_logs"
TIMETABLE_CSV = "timetable.csv"
CAMERA_MAP_CSV = "camera_mapping.csv"
TOLERANCE = 0.85
FRAME_SKIP = 8
RESIZE_SCALE = 0.5
os.makedirs(ATTENDANCE_DIR, exist_ok=True)
now = datetime.now()
current_day = now.strftime("%A")
current_time = now.strftime("%H:%M")
st.info(f"Day: {current_day}, Time: {current_time}")
df = pd.read_csv(TIMETABLE_CSV)
df['start_time'] = pd.to_datetime(df['start_time'], format='%H:%M').dt.strftime('%H:%M')
df['end_time'] = pd.to_datetime(df['end_time'], format='%H:%M').dt.strftime('%H:%M')
current_class = df[
(df['day'] == current_day) &
(df['start_time'] <= current_time) &
(df['end_time'] > current_time)
]
if current_class.empty:
st.warning("No class is scheduled right now.")
else:
camera_df = pd.read_csv(CAMERA_MAP_CSV)
face_app = FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
face_app.prepare(ctx_id=0)
for _, row in current_class.iterrows():
classroom = row['classroom']
branch = row['branch']
semester = row['semester']
section = row['section']
subject = row['subject']
start_time = row['start_time']
end_time = row['end_time']
encoding_file = os.path.join(ENCODING_DIR, f"{branch}_{semester}.pickle")
if not os.path.exists(encoding_file):
st.warning(f"Encoding file not found for {branch}_{semester}")
continue
camera_url = camera_df.loc[camera_df['class_id'] == classroom, 'camera_url'].values
if len(camera_url) == 0:
st.warning(f"Camera not mapped for {classroom}")
continue
camera_url = camera_url[0]
st.subheader(f"🧑🏫 {branch}-{semester}-{section} | 📍 {classroom} | 📚 {subject}")
st.text(f"🎥 Using camera: {camera_url}")
with open(encoding_file, 'rb') as f:
data = pickle.load(f)
known_encodings = np.array(data['encodings'])
known_names = data['metadata']
seen_names = set()
cap = cv2.VideoCapture(camera_url)
frame_count = 0
if not cap.isOpened():
st.error(f"Could not open camera: {camera_url}")
continue
status_box = st.empty()
while True:
ret, frame = cap.read()
if not ret:
break
frame_count += 1
if frame_count % FRAME_SKIP != 0:
continue
small_frame = cv2.resize(frame, (0, 0), fx=RESIZE_SCALE, fy=RESIZE_SCALE)
rgb = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)
faces = face_app.get(rgb)
for face in faces:
embedding = face.normed_embedding
dists = np.linalg.norm(known_encodings - embedding, axis=1)
min_dist = np.min(dists)
min_idx = np.argmin(dists)
name = "Unknown"
if min_dist < TOLERANCE:
name = known_names[min_idx]['name']
if name != "Unknown" and name not in seen_names:
seen_names.add(name)
date_str = now.strftime("%Y-%m-%d")
start_safe = start_time.replace(":", "_")
end_safe = end_time.replace(":", "_")
filename = f"{branch}-{semester}-{section}-{subject}-{start_safe}-{end_safe}-{date_str}.csv"
branch_path = os.path.join(ATTENDANCE_DIR, branch)
semester_path = os.path.join(branch_path, str(semester))
os.makedirs(semester_path, exist_ok=True)
attendance_path = os.path.join(semester_path, filename)
write_header = not os.path.exists(attendance_path)
with open(attendance_path, 'a', newline='') as f:
writer = csv.writer(f)
if write_header:
writer.writerow(["Name", "Time", "Branch", "Semester", "Section", "Classroom"])
writer.writerow([name, now.strftime("%H:%M:%S"), branch, semester, section, classroom])
status_box.success(f"✓ Marked Present: {name}")
if len(seen_names) >= 5:
break
cap.release()
st.success(f"✅ Attendance saved for {branch}-{semester}-{section}.")
print("✅ All active classrooms processed.")