import gradio as gr import face_recognition import cv2 import numpy as np import os from PIL import Image import io import firebase_admin from firebase_admin import credentials from firebase_admin import db from firebase_admin import storage from datetime import datetime # Initialize Firebase cred = credentials.Certificate("path/to/serviceAccountKey.json") # Update the path to your Firebase credentials firebase_admin.initialize_app(cred, { 'databaseURL': 'https://faceantendancerealtime-default-rtdb.firebaseio.com/', 'storageBucket': 'faceantendancerealtime.appspot.com' }) bucket = storage.bucket() # Load the known face encodings and their IDs from Firebase def load_known_encodings(): # Code to download the 'EncodeFile.p' from Firebase Storage # Assume 'EncodeFile.p' is already uploaded to Firebase Storage blob = bucket.blob('EncodeFile.p') blob.download_to_filename('/tmp/EncodeFile.p') with open('/tmp/EncodeFile.p', 'rb') as file: encodeListKnownWithIds = pickle.load(file) return encodeListKnownWithIds encodeListKnownWithIds = load_known_encodings() encodeListKnown, studentsIds = encodeListKnownWithIds def recognize_face(input_image): # Convert the PIL Image to a numpy array img = np.array(input_image) # Convert the image to RGB img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Resize image for faster processing img_small = cv2.resize(img, (0, 0), None, 0.25, 0.25) # Find faces in the image face_locations = face_recognition.face_locations(img_small) face_encodings = face_recognition.face_encodings(img_small, face_locations) # Convert the coordinates to full scale since the image was scaled to 1/4 size face_locations = [(top*4, right*4, bottom*4, left*4) for top, right, bottom, left in face_locations] # Recognize faces for face_encoding, (top, right, bottom, left) in zip(face_encodings, face_locations): matches = face_recognition.compare_faces(encodeListKnown, face_encoding) name = "Unknown" # Use the known face with the smallest distance to the new face face_distances = face_recognition.face_distance(encodeListKnown, face_encoding) best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = studentsIds[best_match_index] # Draw rectangles and names on the original image cv2.rectangle(img, (left, top), (right, bottom), (0, 0, 255), 2) cv2.putText(img, name, (left + 6, bottom - 6), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 255), 1) # Convert the image back to PIL format return Image.fromarray(img) # Define the Gradio interface iface = gr.Interface( fn=recognize_face, inputs=gr.inputs.Image(type="pil"), outputs=gr.outputs.Image(type="pil"), title="Face Recognition Attendance System", description="Upload an image to identify registered students." ) # Run the Gradio app if __name__ == "__main__": iface.launch()