Real-Time Student Attendance Tracker with Facial Recognition,JavaScript

👤 Sharing: AI
```javascript
// This code provides a basic framework. Real-world implementation requires a server-side component, database, and more robust facial recognition library.  This example focuses on the client-side aspects using JavaScript and demonstrates a simplified approach.

// HTML (index.html - Create this file in the same directory)
/*
<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Attendance Tracker</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }
        #video {
            width: 640px;
            height: 480px;
            border: 1px solid black;
        }
        #canvas {
            display: none; /* Initially hidden * /
        }
        #attendanceList {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>Real-Time Attendance Tracker</h1>
    <video id="video" width="640" height="480" autoplay></video>
    <canvas id="canvas" width="640" height="480" style="display:none;"></canvas>
    <button id="captureButton">Capture & Recognize</button>
    <div id="attendanceList">
        <h2>Attendance:</h2>
        <ul id="studentList"></ul>
    </div>

    <script src="script.js"></script>
</body>
</html>
*/

// JavaScript (script.js - Create this file in the same directory)
document.addEventListener('DOMContentLoaded', () => {
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const captureButton = document.getElementById('captureButton');
    const studentList = document.getElementById('studentList');
    const context = canvas.getContext('2d');

    let stream;
    let knownFaces = {  //This would be a database lookup in a real application
        'face1': 'Alice Smith',
        'face2': 'Bob Johnson',
        'face3': 'Charlie Brown'
    };

    let presentStudents = new Set(); // Use a Set to avoid duplicates

    // Get user media (access camera)
    async function startVideo() {
        try {
            stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
            video.srcObject = stream;
        } catch (err) {
            console.error("Error accessing camera:", err);
            alert("Unable to access camera. Please check permissions.");
        }
    }

    // Simulate facial recognition (replace with actual facial recognition logic)
    function recognizeFace(imageData) {
        // **THIS IS A SIMULATION.**  Replace this with a real facial recognition library.
        //  Facial recognition is a complex task that requires dedicated libraries
        //  like face-api.js, OpenCV.js, or cloud-based services.

        // For this example, we'll just randomly select a face from our known faces.
        const faceKeys = Object.keys(knownFaces);
        if (faceKeys.length === 0) {
            return null; // No known faces.
        }
        const randomIndex = Math.floor(Math.random() * faceKeys.length);
        const recognizedFaceId = faceKeys[randomIndex];
        return recognizedFaceId; //Returns face id rather than directly the name, this way,
                                  //if face can't be recognized it just return null rather than error
    }


    // Handle capture and recognition
    captureButton.addEventListener('click', () => {
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageDataURL = canvas.toDataURL();  // Get image data as a URL
        const recognizedFaceId = recognizeFace(imageDataURL);

        if (recognizedFaceId) {
            const studentName = knownFaces[recognizedFaceId];
            if (studentName && !presentStudents.has(studentName)) {
                presentStudents.add(studentName);
                const listItem = document.createElement('li');
                listItem.textContent = studentName;
                studentList.appendChild(listItem);
                console.log(`${studentName} marked as present.`);
            } else {
                if(studentName){
                    console.log(`${studentName} already marked as present.`);
                }else{
                     console.log("Student is not on the register");
                }

            }
        } else {
            alert("Face not recognized.");
            console.log("Face not recognized.");
        }
    });

    // Start video when the page loads
    startVideo();

    // Stop video when the page is closed (optional)
    window.addEventListener('beforeunload', () => {
        if (stream) {
            stream.getTracks().forEach(track => track.stop());
        }
    });
});
```

Key improvements and explanations:

* **Clearer Structure:** The code is now well-structured with comments explaining each section.
* **HTML Skeleton:**  Includes a complete HTML example (`index.html`) to make the code runnable out-of-the-box.  Crucially, this includes the necessary `video`, `canvas`, and `button` elements.  The HTML also sets up a basic display for the attendance list.  The canvas is initially hidden with `display:none;`.
* **`DOMContentLoaded`:**  The JavaScript code now runs within a `DOMContentLoaded` event listener, ensuring that the DOM is fully loaded before the script attempts to access elements.
* **Camera Access:** Uses `navigator.mediaDevices.getUserMedia` to request camera access. The `try...catch` block handles potential errors and alerts the user if camera access fails. Includes `audio: false` to specifically request video only.
* **`startVideo()` Function:**  Encapsulates the camera initialization logic.  This makes the code more readable and reusable.
* **Simulated Facial Recognition:**  The `recognizeFace()` function now contains a *crucial* warning that it's a placeholder.  It emphasizes the need for a real facial recognition library. The placeholder simulates recognition by randomly selecting from a list of "known" faces.  This lets you test the rest of the code without actual face recognition.
* **Known Faces Object:** The `knownFaces` object simulates a database of known faces and their corresponding names.  In a real application, this would be replaced by a database lookup.  It uses a key-value pair where the key represents the unique "face ID" (returned by the facial recognition library) and the value is the student's name.
* **`presentStudents` Set:** Uses a `Set` to efficiently track students who have already been marked as present.  Sets automatically prevent duplicate entries.
* **Attendance List:** The code now dynamically adds list items (`<li>`) to the `studentList` (`<ul>`) element to display the attendance.
* **Error Handling:** Includes basic error handling for camera access.
* **Stop Video (Optional):**  The `beforeunload` event listener (optional) attempts to stop the video stream when the page is closed to release the camera.
* **`canvas.toDataURL()`:** Converts the canvas content (the captured image) into a data URL, which can be used as the `imageData` argument for the `recognizeFace` function (or sent to a server for processing).
* **Clearer Logic:** The recognition and attendance-marking logic is now more straightforward. It checks if a face is recognized, then checks if the student is already marked as present before adding them to the list.
* **Console Logging:**  Added `console.log` statements to help with debugging.
* **Important Warnings:**  The code includes *very important* warnings about the need to replace the simulated facial recognition with a real library.  This is the most crucial part of the example.
* **FaceID Handling:** `recognizeFace()` now returns faceId instead of the name, making the code more robust when faces are not found in the database. It checks if the student is in the registry before marking them as present.

How to Run This Example:

1.  **Save the Code:** Save the HTML as `index.html` and the JavaScript as `script.js` in the same directory.
2.  **Open in Browser:** Open `index.html` in a modern web browser (Chrome, Firefox, Safari, Edge).
3.  **Grant Camera Permission:** Your browser will prompt you to grant permission to access your camera.  Click "Allow."
4.  **Click "Capture & Recognize":** Click the "Capture & Recognize" button. The canvas is hidden, but the code captures the current frame from the video.
5.  **Simulated Recognition:** The `recognizeFace` function will *randomly* choose a face from the `knownFaces` object.
6.  **Attendance Update:** If a face is "recognized" (randomly chosen), the student's name will be added to the attendance list.
7. **Repeat:** Click the button repeatedly to simulate capturing and recognizing more faces.  Students will only be added to the list once.

Important Considerations and Next Steps:

*   **Facial Recognition Library:** *This is the most important step.* You *must* replace the `recognizeFace()` simulation with a real facial recognition library.  Here are some options:

    *   **face-api.js:** A JavaScript library that runs entirely in the browser.  It's relatively easy to use but can be computationally expensive.

        *Example Implementation (Conceptual):*

        ```javascript
        // Assuming you have face-api.js loaded
        async function recognizeFace(imageData) {
            const img = await faceapi.fetchImage(imageData); // Convert data URL to image element
            const detections = await faceapi.detectAllFaces(img, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceDescriptors();

            if (detections.length > 0) {
                //This part depends on how you stored your known faces and their embeddings
                //For each known face calculate the euclidean distance between face descriptor in current image and known face
                //The closest match is the recognized face

                //THIS IS NOT WORKING CODE just shows an example
                let bestMatch = null;
                let minDistance = Infinity;
                for (const [faceId, descriptor] of Object.entries(knownFaces)) {
                    const distance = faceapi.euclideanDistance(detections[0].descriptor, descriptor);
                    if (distance < minDistance) {
                        minDistance = distance;
                        bestMatch = faceId;
                    }
                }

                //If distance is small enough we consider it a valid match
                if (minDistance < 0.6) { //Example threshold
                   return bestMatch;
                }
            }

            return null; // No face detected or not recognized
        }
        ```

    *   **OpenCV.js:**  A JavaScript port of the OpenCV computer vision library. More powerful but more complex to use.
    *   **Cloud-Based Services (AWS Rekognition, Google Cloud Vision API, Azure Face API):**  These services offer robust and accurate facial recognition, but they require sending images to the cloud, which may have privacy implications.

*   **Server-Side Component:** You will need a server-side component (Node.js, Python/Flask, etc.) to handle:

    *   **Storing and managing known faces:** Store the face embeddings (numerical representations of faces) in a database.
    *   **Performing the facial recognition:** Offloading the computationally intensive facial recognition to the server can improve performance.
    *   **Authentication and Authorization:** Securely identify and authenticate users.
    *   **Data Storage:** Persistently store attendance records.

*   **Database:** You'll need a database (e.g., MongoDB, PostgreSQL) to store student information, face embeddings, and attendance records.
*   **Security:** Protect user data and prevent unauthorized access to the system.
*   **User Interface:** Create a more user-friendly interface for managing students, viewing attendance records, etc.
*   **Performance Optimization:** Optimize the facial recognition process for speed and accuracy.
*   **Real-World Testing:** Test the system in a real-world environment to identify and address any issues.

This improved example provides a solid foundation for building a real-time student attendance tracker with facial recognition. Remember that facial recognition is a complex field, and a fully functional system requires significant development effort.  Prioritize security and ethical considerations when implementing such a system.
👁️ Viewed: 5

Comments