File size: 7,188 Bytes
0092fd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
\
    import tkinter as tk
    from tkinter import ttk, messagebox
    import cv2, os, time, pickle, face_recognition, threading
    from PIL import Image, ImageTk

    BASE_DIR = os.path.dirname(__file__)
    IMAGES_FOLDER = os.path.join(BASE_DIR, "known_faces", "images")
    STUDENTS_FILE = os.path.join(BASE_DIR, "known_faces", "students.txt")
    ENCODINGS_FILE = os.path.join(BASE_DIR, "known_faces", "encodings.pkl")
    os.makedirs(IMAGES_FOLDER, exist_ok=True)

    def sanitize_filename(s):
        return "".join(c for c in s if c.isalnum() or c in (" ", "_", "-")).rstrip()

    def update_encodings():
        # Recreate encodings.pkl from students.txt
        known_face_encodings = []
        known_face_names = []
        known_face_classes = []
        if not os.path.exists(STUDENTS_FILE):
            return
        with open(STUDENTS_FILE, "r", encoding="utf-8") as f:
            for line in f:
                parts = line.strip().split(",")
                if len(parts) < 3:
                    continue
                image_file, name, student_class = parts[0].strip(), parts[1].strip(), parts[2].strip()
                image_path = os.path.join(IMAGES_FOLDER, image_file)
                if not os.path.exists(image_path):
                    print("Image missing:", image_path)
                    continue
                image = face_recognition.load_image_file(image_path)
                encodings = face_recognition.face_encodings(image)
                if len(encodings) > 0:
                    known_face_encodings.append(encodings[0])
                    known_face_names.append(name)
                    known_face_classes.append(student_class)
        with open(ENCODINGS_FILE, "wb") as f:
            pickle.dump((known_face_encodings, known_face_names, known_face_classes), f)
        print("✅ Encodings updated. Registered:", len(known_face_names))

    class RegisterApp:
        def __init__(self, root):
            self.root = root
            root.title("Register Student - Cythia")
            root.geometry("700x520")
            self.cap = None
            self.capturing = False

            # Left: camera preview
            self.preview_frame = ttk.Frame(root)
            self.preview_frame.grid(row=0, column=0, padx=10, pady=10, rowspan=6)
            self.lmain = tk.Label(self.preview_frame)
            self.lmain.pack()

            # Right: form
            ttk.Label(root, text="Full Name:").grid(row=0, column=1, sticky="w")
            self.name_entry = ttk.Entry(root, width=30)
            self.name_entry.grid(row=0, column=2, padx=5, pady=5)

            ttk.Label(root, text="Class:").grid(row=1, column=1, sticky="w")
            self.class_entry = ttk.Entry(root, width=30)
            self.class_entry.grid(row=1, column=2, padx=5, pady=5)

            self.capture_btn = ttk.Button(root, text="Start Camera", command=self.start_camera)
            self.capture_btn.grid(row=2, column=1, columnspan=2, pady=6, sticky="we")

            self.snap_btn = ttk.Button(root, text="Capture & Save", command=self.capture_and_save, state="disabled")
            self.snap_btn.grid(row=3, column=1, columnspan=2, pady=6, sticky="we")

            self.reset_btn = ttk.Button(root, text="Reset Today's Attendance", command=self.reset_attendance)
            self.reset_btn.grid(row=4, column=1, columnspan=2, pady=6, sticky="we")

            self.preview_list_btn = ttk.Button(root, text="Preview Registered Students", command=self.preview_registered)
            self.preview_list_btn.grid(row=5, column=1, columnspan=2, pady=6, sticky="we")

            self.quit_btn = ttk.Button(root, text="Quit", command=self.on_close)
            self.quit_btn.grid(row=6, column=1, columnspan=2, pady=10, sticky="we")

            root.protocol("WM_DELETE_WINDOW", self.on_close)

        def start_camera(self):
            if self.capturing:
                return
            self.cap = cv2.VideoCapture(0)
            self.capturing = True
            self.snap_btn.config(state="enabled")
            self.update_frame()

        def update_frame(self):
            if not self.capturing:
                return
            ret, frame = self.cap.read()
            if not ret:
                return
            # Resize for display
            display = cv2.resize(frame, (420, 320))
            display = cv2.cvtColor(display, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(display)
            imgtk = ImageTk.PhotoImage(image=img)
            self.lmain.imgtk = imgtk
            self.lmain.configure(image=imgtk)
            self.root.after(30, self.update_frame)

        def capture_and_save(self):
            name = self.name_entry.get().strip()
            student_class = self.class_entry.get().strip()
            if not name or not student_class:
                messagebox.showwarning("Missing data", "Please enter both Name and Class.")
                return
            if not self.capturing or self.cap is None:
                messagebox.showwarning("Camera", "Start the camera first.")
                return
            ret, frame = self.cap.read()
            if not ret:
                messagebox.showerror("Camera", "Failed to capture image.")
                return
            # Create safe filename
            safe = sanitize_filename(name).replace(" ", "_")
            timestamp = int(time.time())
            filename = f"{safe}_{timestamp}.jpg"
            path = os.path.join(IMAGES_FOLDER, filename)
            # Save image (BGR -> RGB conversion handled by OpenCV saved file)
            cv2.imwrite(path, frame)
            # Append to students.txt
            with open(STUDENTS_FILE, "a", encoding="utf-8") as f:
                f.write(f"{filename},{name},{student_class}\n")
            # Update encodings
            update_encodings()
            messagebox.showinfo("Saved", f"Saved {name} as {filename} and updated encodings.")

        def reset_attendance(self):
            from utils import reset_today_attendance
            reset_today_attendance()
            messagebox.showinfo("Reset", "Today's attendance files have been reset.")

        def preview_registered(self):
            # Load encodings and show names/classes in a popup
            if not os.path.exists(ENCODINGS_FILE):
                messagebox.showinfo("None", "No registered students found.")
                return
            with open(ENCODINGS_FILE, "rb") as f:
                enc, names, classes = pickle.load(f)
            win = tk.Toplevel(self.root)
            win.title("Registered Students")
            win.geometry("400x400")
            lb = tk.Listbox(win, width=60)
            lb.pack(fill="both", expand=True, padx=10, pady=10)
            for n,c in zip(names, classes):
                lb.insert("end", f"{n}  —  {c}")

        def on_close(self):
            self.capturing = False
            if self.cap is not None:
                try:
                    self.cap.release()
                except:
                    pass
            self.root.destroy()

    if __name__ == "__main__":
        root = tk.Tk()
        app = RegisterApp(root)
        root.mainloop()