Spaces:
Sleeping
Sleeping
File size: 7,181 Bytes
9befc9d 7dbbc1f c1ac3cd 9befc9d 9f08f28 9befc9d 7dbbc1f 9befc9d c5aeb39 9befc9d c5aeb39 9befc9d c5aeb39 9befc9d 9f08f28 c5aeb39 9f08f28 c5aeb39 7dbbc1f c5aeb39 9f08f28 c5aeb39 c1ac3cd c5aeb39 c1ac3cd c5aeb39 c1ac3cd c5aeb39 c1ac3cd c5aeb39 c1ac3cd c5aeb39 7dbbc1f | 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 | 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()
|