Spaces:
Sleeping
Sleeping
| from PIL import Image | |
| import numpy as np | |
| import cv2 | |
| import requests | |
| import face_recognition | |
| import os | |
| from datetime import datetime | |
| import streamlit as st | |
| import sqlite3 | |
| import pickle | |
| # Set page title and description | |
| st.set_page_config( | |
| page_title="Attendance System Using Face Recognition", | |
| page_icon="📷", | |
| layout="centered", | |
| initial_sidebar_state="collapsed" | |
| ) | |
| st.title("Attendance System Using Face Recognition 📷") | |
| st.markdown("This app recognizes faces in an image, verifies Aadhaar card details, and updates attendance records with the current timestamp & Location.") | |
| # Create or connect to the SQLite database | |
| conn = sqlite3.connect("attendance_database.db") | |
| cursor = conn.cursor() | |
| # Check if the 'faces' table exists, create it if not | |
| cursor.execute(''' | |
| CREATE TABLE IF NOT EXISTS faces ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| aadhaar TEXT, | |
| encoding BLOB | |
| ) | |
| ''') | |
| conn.commit() | |
| # Load images for face recognition | |
| def load_images(directory): | |
| Images = [] | |
| classnames = [] | |
| myList = os.listdir(directory) | |
| for cls in myList: | |
| if os.path.splitext(cls)[1] in [".jpg", ".jpeg"]: | |
| img_path = os.path.join(directory, cls) | |
| curImg = cv2.imread(img_path) | |
| Images.append(curImg) | |
| classnames.append(os.path.splitext(cls)[0]) | |
| return Images, classnames | |
| Images, classnames = load_images("photos") | |
| def find_encodings(images): | |
| encode_list = [] | |
| for img in images: | |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| encode = face_recognition.face_encodings(img)[0] | |
| encode_list.append(encode) | |
| return encode_list | |
| encodeListKnown = find_encodings(Images) | |
| # Function to validate Aadhaar card number | |
| def validate_aadhaar(aadhaar): | |
| # Implement your Aadhaar card validation logic here | |
| # For simplicity, let's assume any 4-digit number is a valid Aadhaar card | |
| return len(aadhaar) == 4 and aadhaar.isdigit() | |
| # Function to verify Aadhaar from the database | |
| def verify_aadhaar_from_database(aadhaar_number): | |
| cursor.execute("SELECT * FROM faces WHERE aadhaar = ?", (aadhaar_number,)) | |
| user_data = cursor.fetchone() | |
| return user_data is not None | |
| # Function to perform face recognition and Aadhaar verification | |
| def recognize_and_verify(image, encodeListKnown, aadhaar_number): | |
| imgS = cv2.resize(image, (0, 0), None, 0.25, 0.25) | |
| imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB) | |
| facesCurFrame = face_recognition.face_locations(imgS) | |
| encodesCurFrame = face_recognition.face_encodings(imgS, facesCurFrame) | |
| name = "Unknown" # Default name for unknown faces | |
| if len(encodesCurFrame) > 0: | |
| for encodeFace, faceLoc in zip(encodesCurFrame, facesCurFrame): | |
| matches = face_recognition.compare_faces(encodeListKnown, encodeFace) | |
| faceDis = face_recognition.face_distance(encodeListKnown, encodeFace) | |
| matchIndex = np.argmin(faceDis) | |
| if matches[matchIndex]: | |
| name = classnames[matchIndex].upper() | |
| y1, x2, y2, x1 = faceLoc | |
| y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4 | |
| cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2) | |
| cv2.rectangle(image, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED) | |
| cv2.putText(image, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2) | |
| if name != "Unknown": | |
| # Update Aadhaar data | |
| url = "https://attendanceviaface.000webhostapp.com" | |
| url1 = "/update.php" | |
| data1 = {'name': name, 'aadhaar': aadhaar_number} | |
| response = requests.post(url + url1, data=data1) | |
| if response.status_code == 200: | |
| st.success("Data updated on: " + url) | |
| else: | |
| st.warning("Data not updated") | |
| # Store face encoding and Aadhaar number in the database | |
| face_encoding_bytes = pickle.dumps(encodeFace) | |
| cursor.execute("INSERT INTO faces (aadhaar, encoding) VALUES (?, ?)", (aadhaar_number, face_encoding_bytes)) | |
| conn.commit() | |
| # Apply styling with CSS | |
| st.markdown('<style>img { animation: pulse 2s infinite; }</style>', unsafe_allow_html=True) | |
| st.image(image, use_column_width=True, output_format="PNG") | |
| if name == "Unknown": | |
| st.info("Face not detected. Please try again.") | |
| # Function to take attendance by clicking a photo | |
| def take_attendance_by_photo(encodeListKnown, aadhaar_number): | |
| # Capture photo using the camera | |
| captured_image = st.camera_input("Capture a photo for attendance") | |
| if captured_image is not None: | |
| # Process the captured image for face recognition | |
| captured_image = Image.open(captured_image) | |
| captured_image_np = np.asarray(captured_image) | |
| captured_image_rgb = cv2.cvtColor(captured_image_np, cv2.COLOR_BGR2RGB) | |
| # Find faces in the captured image | |
| faces_captured = face_recognition.face_locations(captured_image_rgb) | |
| encodes_captured = face_recognition.face_encodings(captured_image_rgb, faces_captured) | |
| if len(faces_captured) > 0: | |
| # Check if any of the captured faces match known faces | |
| for encode_captured, face_loc in zip(encodes_captured, faces_captured): | |
| matches_captured = face_recognition.compare_faces(encodeListKnown, encode_captured) | |
| face_dis_captured = face_recognition.face_distance(encodeListKnown, encode_captured) | |
| match_index_captured = np.argmin(face_dis_captured) | |
| if matches_captured[match_index_captured]: | |
| name_captured = classnames[match_index_captured].upper() | |
| # Verify Aadhaar from the database | |
| if verify_aadhaar_from_database(aadhaar_number): | |
| st.success(f"{name_captured}'s attendance recorded.") | |
| else: | |
| st.warning(f"{name_captured} is not registered with Aadhaar {aadhaar_number}.") | |
| else: | |
| st.warning("No matching face found in the database.") | |
| else: | |
| st.warning("No face detected in the captured photo. Please try again.") | |
| # Take picture using the camera and input Aadhaar card details | |
| img_file_buffer = st.file_uploader("Upload an image", type=["jpg", "jpeg"]) | |
| aadhaar_number = st.text_input("Enter Aadhaar Number:") | |
| # Face recognition and Aadhaar verification code... | |
| if img_file_buffer is not None: | |
| # Validate Aadhaar card number | |
| if validate_aadhaar(aadhaar_number): | |
| test_image = Image.open(img_file_buffer) | |
| image = np.asarray(test_image) | |
| recognize_and_verify(image, encodeListKnown, aadhaar_number) | |
| else: | |
| st.error("Invalid Aadhaar card number. Please enter a valid 4-digit Aadhaar number.") | |
| # Section to take attendance by clicking a photo | |
| st.header("Take Attendance by Clicking Photo") | |
| capture_button = st.button("Capture Photo for Attendance") | |
| if capture_button: | |
| take_attendance_by_photo(encodeListKnown, aadhaar_number) | |
| # Close the database connection | |
| conn.close() | |