File size: 4,183 Bytes
f239a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import pandas as pd
from datetime import datetime
from deepface import DeepFace
import gradio as gr
from PIL import Image

# Ensure necessary directories exist
os.makedirs("registered_faces", exist_ok=True)
os.makedirs("attendance", exist_ok=True)

# Adjust the similarity threshold
SIMILARITY_THRESHOLD = 0.4  # Lower means stricter; increase for more flexibility

# 1. Register a face
def register_face(image, name):
    if not name.strip():
        return "Please provide a valid name."
    
    file_path = f"registered_faces/{name}.jpg"
    image.save(file_path)
    return f"Face registered for {name}!"

# 2. Recognize a face and mark attendance
def recognize_face(image):
    if not os.listdir("registered_faces"):
        return "No registered faces found. Please register a face first."

    recognized_name = "Unknown"
    debug_logs = []  # Store debug information

    # Save the uploaded image temporarily
    temp_image_path = "temp_recognition.jpg"
    image.save(temp_image_path)

    for registered_file in os.listdir("registered_faces"):
        registered_path = f"registered_faces/{registered_file}"
        try:
            # Perform face verification
            result = DeepFace.verify(
                img1_path=registered_path, 
                img2_path=temp_image_path, 
                enforce_detection=True,  # Ensure face detection
                model_name="Facenet",  # Use a different model for testing
                distance_metric="cosine"  # Use cosine distance for better comparison
            )
            similarity = result["distance"]
            debug_logs.append(f"Compared with {registered_file}: Verified={result['verified']}, Distance={similarity}")

            # If a match is found
            if similarity < SIMILARITY_THRESHOLD:
                recognized_name = os.path.splitext(registered_file)[0]
                break
        except Exception as e:
            debug_logs.append(f"Error comparing with {registered_file}: {str(e)}")
            continue

    # Remove temporary file after processing
    if os.path.exists(temp_image_path):
        os.remove(temp_image_path)

    # Log attendance if recognized
    if recognized_name != "Unknown":
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        attendance_file = "attendance/attendance.csv"

        if not os.path.exists(attendance_file):
            df = pd.DataFrame(columns=["Name", "Time"])
        else:
            df = pd.read_csv(attendance_file)
        
        df = pd.concat([df, pd.DataFrame({"Name": [recognized_name], "Time": [now]})], ignore_index=True)
        df.to_csv(attendance_file, index=False)

    # Debug output
    return f"Recognized: {recognized_name}\nDebug Logs:\n" + "\n".join(debug_logs)

# 3. Download attendance records
def download_attendance():
    attendance_file = "attendance/attendance.csv"
    if os.path.exists(attendance_file):
        return attendance_file
    else:
        return "No attendance records found."

# 4. Delete all registered faces
def delete_registered_faces():
    folder = "registered_faces"
    if os.listdir(folder):
        for file in os.listdir(folder):
            os.remove(os.path.join(folder, file))
        return "All registered faces have been deleted."
    return "No registered faces to delete."

# Gradio interfaces
register_interface = gr.Interface(
    fn=register_face,
    inputs=[gr.Image(type="pil"), gr.Text(label="Name")],
    outputs="text",
    title="Register Face"
)

recognize_interface = gr.Interface(
    fn=recognize_face,
    inputs=gr.Image(type="pil"),  # Corrected to use "pil"
    outputs="text",
    title="Recognize Face"
)

download_interface = gr.Interface(
    fn=download_attendance,
    inputs=None,
    outputs="file",
    title="Download Attendance"
)

delete_interface = gr.Interface(
    fn=delete_registered_faces,
    inputs=None,
    outputs="text",
    title="Delete Registered Faces"
)

# Tabbed Gradio App
app = gr.TabbedInterface(
    [register_interface, recognize_interface, download_interface, delete_interface],
    ["Register", "Recognize", "Download Attendance", "Delete Faces"]
)

# Launch Gradio app
app.launch()