vikramjeetthakur commited on
Commit
0382c01
·
verified ·
1 Parent(s): de189f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -245
app.py CHANGED
@@ -1,249 +1,83 @@
1
- import streamlit as st
2
  import cv2
 
3
  import face_recognition
4
  import os
5
  from datetime import datetime
6
- import sqlite3
7
- import pandas as pd
8
- import numpy as np
9
- from PIL import Image
10
- from pathlib import Path
11
- import logging
12
-
13
- # Configure logging
14
- logging.basicConfig(level=logging.INFO)
15
- logger = logging.getLogger(__name__)
16
-
17
- class AttendanceSystem:
18
- def __init__(self):
19
- """Initialize the attendance system."""
20
- self.setup_page_config()
21
- self.setup_database()
22
- self.load_known_faces()
23
-
24
- def setup_page_config(self):
25
- """Configure Streamlit page settings."""
26
- st.set_page_config(
27
- page_title="Face Recognition Attendance",
28
- page_icon="✅",
29
- layout="wide"
30
- )
31
-
32
- def setup_database(self):
33
- """Initialize database connection and create necessary tables."""
34
- try:
35
- # Use Path to handle paths consistently across platforms
36
- db_path = Path("data/attendance.db")
37
- db_path.parent.mkdir(exist_ok=True)
38
-
39
- self.conn = sqlite3.connect(str(db_path))
40
- self.cursor = self.conn.cursor()
41
-
42
- self.cursor.execute('''
43
- CREATE TABLE IF NOT EXISTS attendance (
44
- id INTEGER PRIMARY KEY AUTOINCREMENT,
45
- name TEXT,
46
- roll_no TEXT,
47
- date TEXT,
48
- time TEXT,
49
- status TEXT
50
- )
51
- ''')
52
- self.conn.commit()
53
- except Exception as e:
54
- logger.error(f"Database setup error: {e}")
55
- st.error("Error setting up database. Please check logs.")
56
-
57
- def load_known_faces(self):
58
- """Load and encode known faces from the Photos directory."""
59
- try:
60
- photos_dir = Path("Photos")
61
- photos_dir.mkdir(exist_ok=True)
62
-
63
- self.images = []
64
- self.classnames = []
65
-
66
- for img_path in photos_dir.glob("*.[jJ][pP][gG]"):
67
- img = cv2.imread(str(img_path))
68
- if img is not None:
69
- self.images.append(img)
70
- self.classnames.append(img_path.stem)
71
-
72
- self.encode_known_faces()
73
- except Exception as e:
74
- logger.error(f"Error loading known faces: {e}")
75
- st.error("Error loading known faces. Please check the Photos directory.")
76
-
77
- def encode_known_faces(self):
78
- """Encode loaded face images."""
79
- try:
80
- self.encodings = []
81
- for img in self.images:
82
- rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
83
- face_encodings = face_recognition.face_encodings(rgb_img)
84
- if face_encodings:
85
- self.encodings.append(face_encodings[0])
86
- else:
87
- logger.warning("No face found in image")
88
- except Exception as e:
89
- logger.error(f"Error encoding faces: {e}")
90
- st.error("Error encoding faces. Please check image quality.")
91
-
92
- def add_new_face(self):
93
- """Add a new face to the system."""
94
- st.subheader("Add New Face")
95
-
96
- col1, col2 = st.columns(2)
97
- with col1:
98
- new_name = st.text_input("Enter your name:")
99
- with col2:
100
- roll_no = st.text_input("Enter your roll number:")
101
-
102
- img_file_buffer = st.camera_input("Take a picture")
103
-
104
- if img_file_buffer and new_name and roll_no:
105
- try:
106
- image = np.array(Image.open(img_file_buffer))
107
- photos_dir = Path("Photos")
108
- img_path = photos_dir / f"{new_name}_{roll_no}.jpg"
109
-
110
- # Save image
111
- cv2.imwrite(str(img_path), cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
112
-
113
- # Update known faces
114
- self.load_known_faces()
115
-
116
- # Record registration
117
- self.record_attendance(new_name, roll_no, 'Registered')
118
- st.success(f"Successfully registered {new_name}")
119
- except Exception as e:
120
- logger.error(f"Error adding new face: {e}")
121
- st.error("Error adding new face. Please try again.")
122
-
123
- def recognize_face(self):
124
- """Perform face recognition and mark attendance."""
125
- st.subheader("Face Recognition")
126
- img_file_buffer = st.camera_input("Take a picture")
127
-
128
- if img_file_buffer:
129
- try:
130
- image = np.array(Image.open(img_file_buffer))
131
- small_image = cv2.resize(image, (0, 0), None, 0.25, 0.25)
132
- rgb_small_image = cv2.cvtColor(small_image, cv2.COLOR_BGR2RGB)
133
-
134
- face_locations = face_recognition.face_locations(rgb_small_image)
135
- face_encodings = face_recognition.face_encodings(rgb_small_image, face_locations)
136
-
137
- for encodeFace, faceLoc in zip(face_encodings, face_locations):
138
- matches = face_recognition.compare_faces(self.encodings, encodeFace, tolerance=0.6)
139
- face_distances = face_recognition.face_distance(self.encodings, encodeFace)
140
-
141
- if len(face_distances) > 0:
142
- best_match_index = np.argmin(face_distances)
143
- if matches[best_match_index]:
144
- name, roll_no = self.classnames[best_match_index].split("_")
145
- self.draw_face_box(image, faceLoc, name)
146
-
147
- if not self.check_duplicate_attendance(name):
148
- status = st.radio("Mark Attendance:", ("Present", "Absent"))
149
- if st.button("Confirm Attendance"):
150
- self.record_attendance(name, roll_no, status)
151
- else:
152
- st.warning("Face not recognized")
153
-
154
- st.image(image, caption="Recognized Face", use_container_width=True)
155
- except Exception as e:
156
- logger.error(f"Error in face recognition: {e}")
157
- st.error("Error processing image. Please try again.")
158
-
159
- def draw_face_box(self, image, face_location, name):
160
- """Draw bounding box and name for recognized face."""
161
- y1, x2, y2, x1 = [coord * 4 for coord in face_location]
162
- cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
163
- cv2.rectangle(image, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
164
- cv2.putText(image, name, (x1 + 6, y2 - 6),
165
- cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
166
-
167
- def check_duplicate_attendance(self, name):
168
- """Check if attendance has already been marked today."""
169
- today = datetime.now().strftime('%Y-%m-%d')
170
- self.cursor.execute(
171
- "SELECT * FROM attendance WHERE name=? AND date=?",
172
- (name, today)
173
- )
174
- return bool(self.cursor.fetchone())
175
-
176
- def record_attendance(self, name, roll_no, status):
177
- """Record attendance in the database."""
178
- try:
179
- current_time = datetime.now()
180
- self.cursor.execute(
181
- """INSERT INTO attendance (name, roll_no, date, time, status)
182
- VALUES (?, ?, ?, ?, ?)""",
183
- (name, roll_no, current_time.strftime('%Y-%m-%d'),
184
- current_time.strftime('%H:%M:%S'), status)
185
- )
186
- self.conn.commit()
187
- st.success(f"Attendance recorded for {name}")
188
- except Exception as e:
189
- logger.error(f"Error recording attendance: {e}")
190
- st.error("Error recording attendance. Please try again.")
191
-
192
- def view_attendance_records(self):
193
- """Display attendance records."""
194
- st.subheader("Attendance Records")
195
- try:
196
- self.cursor.execute(
197
- "SELECT * FROM attendance ORDER BY date DESC, time DESC"
198
- )
199
- records = self.cursor.fetchall()
200
-
201
- if records:
202
- df = pd.DataFrame(
203
- records,
204
- columns=["ID", "Name", "Roll No", "Date", "Time", "Status"]
205
- )
206
- st.dataframe(df)
207
- else:
208
- st.info("No attendance records found")
209
- except Exception as e:
210
- logger.error(f"Error viewing records: {e}")
211
- st.error("Error loading attendance records")
212
-
213
- def run(self):
214
- """Run the main application."""
215
- st.title("Face Recognition Attendance System")
216
-
217
- # Simple authentication
218
- if not self.authenticate():
219
- return
220
-
221
- # Navigation
222
- app_mode = st.sidebar.selectbox(
223
- "Select Mode",
224
- ["Recognize", "Add New Face", "View Records"]
225
- )
226
-
227
- # Route to appropriate function
228
- if app_mode == "Recognize":
229
- self.recognize_face()
230
- elif app_mode == "Add New Face":
231
- self.add_new_face()
232
- elif app_mode == "View Records":
233
- self.view_attendance_records()
234
-
235
- def authenticate(self):
236
- """Simple authentication system."""
237
- password = st.sidebar.text_input("Enter password", type="password")
238
- return password == "123"
239
-
240
- def __del__(self):
241
- """Cleanup database connection."""
242
- try:
243
- self.conn.close()
244
- except:
245
- pass
246
-
247
- if __name__ == "__main__":
248
- app = AttendanceSystem()
249
- app.run()
 
 
1
  import cv2
2
+ import numpy as np
3
  import face_recognition
4
  import os
5
  from datetime import datetime
6
+
7
+ # from PIL import ImageGrab
8
+
9
+ path = 'Training_images'
10
+ images = []
11
+ classNames = []
12
+ myList = os.listdir(path)
13
+ print(myList)
14
+ for cl in myList:
15
+ curImg = cv2.imread(f'{path}/{cl}')
16
+ images.append(curImg)
17
+ classNames.append(os.path.splitext(cl)[0])
18
+ print(classNames)
19
+
20
+
21
+ def findEncodings(images):
22
+ encodeList = []
23
+
24
+
25
+ for img in images:
26
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
27
+ encode = face_recognition.face_encodings(img)[0]
28
+ encodeList.append(encode)
29
+ return encodeList
30
+
31
+
32
+ def markAttendance(name):
33
+ with open('Attendance.csv', 'r+') as f:
34
+ myDataList = f.readlines()
35
+
36
+
37
+ nameList = []
38
+ for line in myDataList:
39
+ entry = line.split(',')
40
+ nameList.append(entry[0])
41
+ if name not in nameList:
42
+ now = datetime.now()
43
+ dtString = now.strftime('%H:%M:%S')
44
+ f.writelines(f'\n{name},{dtString}')
45
+
46
+ #### FOR CAPTURING SCREEN RATHER THAN WEBCAM
47
+ # def captureScreen(bbox=(300,300,690+300,530+300)):
48
+ # capScr = np.array(ImageGrab.grab(bbox))
49
+ # capScr = cv2.cvtColor(capScr, cv2.COLOR_RGB2BGR)
50
+ # return capScr
51
+
52
+ encodeListKnown = findEncodings(images)
53
+ print('Encoding Complete')
54
+
55
+ cap = cv2.VideoCapture(0)
56
+
57
+ while True:
58
+ success, img = cap.read()
59
+ # img = captureScreen()
60
+ imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
61
+ imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
62
+
63
+ facesCurFrame = face_recognition.face_locations(imgS)
64
+ encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame)
65
+
66
+ for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame):
67
+ matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
68
+ faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
69
+ # print(faceDis)
70
+ matchIndex = np.argmin(faceDis)
71
+
72
+ if matches[matchIndex]:
73
+ name = classNames[matchIndex].upper()
74
+ # print(name)
75
+ y1, x2, y2, x1 = faceLoc
76
+ y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
77
+ cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
78
+ cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
79
+ cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
80
+ markAttendance(name)
81
+
82
+ cv2.imshow('Webcam', img)
83
+ cv2.waitKey(1)