Spaces:
Sleeping
Sleeping
| app.py | |
| from flask import Flask, render_template, request, jsonify | |
| import os | |
| import cv2 | |
| import numpy as np | |
| import pandas as pd | |
| from datetime import datetime | |
| import base64 | |
| app = Flask(__name__) | |
| # Setup | |
| face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") | |
| dataset_path = "./face_dataset/" | |
| os.makedirs(dataset_path, exist_ok=True) | |
| # KNN distance | |
| def distance(v1, v2): | |
| return np.sqrt(((v1 - v2) ** 2).sum()) | |
| def knn(train, test, k=5): | |
| dist = [] | |
| for i in range(train.shape[0]): | |
| ix = train[i, :-1] | |
| iy = train[i, -1] | |
| d = distance(test, ix) | |
| dist.append([d, iy]) | |
| dk = sorted(dist, key=lambda x: x[0])[:k] | |
| labels = np.array(dk)[:, -1] | |
| return np.unique(labels, return_counts=True)[0][0] | |
| # Attendance system | |
| class AttendanceSystem: | |
| def __init__(self): | |
| self.file = "attendance.csv" | |
| self.columns = ["Name", "Date", "Time"] | |
| if not os.path.exists(self.file): | |
| pd.DataFrame(columns=self.columns).to_csv(self.file, index=False) | |
| def mark(self, name): | |
| today = datetime.now().strftime("%Y-%m-%d") | |
| now = datetime.now().strftime("%H:%M:%S") | |
| df = pd.read_csv(self.file) | |
| existing = df[(df["Name"] == name) & (df["Date"] == today)] | |
| if existing.empty: | |
| new_entry = pd.DataFrame([[name, today, now]], columns=self.columns) | |
| df = pd.concat([df, new_entry], ignore_index=True) | |
| df.to_csv(self.file, index=False) | |
| return True | |
| return False | |
| attendance = AttendanceSystem() | |
| # Home page | |
| @app.route('/') | |
| def index(): | |
| return render_template('index.html') | |
| @app.route('/register') | |
| def register(): | |
| return render_template('register.html') | |
| @app.route('/mark') | |
| def mark(): | |
| return render_template('mark.html') | |
| # API to save face during registration | |
| # Modified register_face endpoint with preprocessing | |
| @app.route('/api/register_face', methods=['POST']) | |
| def register_face(): | |
| data = request.json | |
| name = data['name'] | |
| images = data['images'] # List of base64 images | |
| face_data = [] | |
| for img_data in images: | |
| img_bytes = base64.b64decode(img_data.split(",")[1]) | |
| np_arr = np.frombuffer(img_bytes, np.uint8) | |
| img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) | |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| gray = cv2.equalizeHist(gray) # Histogram equalization | |
| faces = face_cascade.detectMultiScale(gray, 1.3, 5) | |
| for (x, y, w, h) in faces[:1]: | |
| face = img[y:y+h, x:x+w] | |
| face = cv2.resize(face, (100, 100)) | |
| # Original face | |
| face_data.append(face.flatten()) | |
| # Data augmentation: horizontal flip | |
| flipped_face = cv2.flip(face, 1) | |
| face_data.append(flipped_face.flatten()) | |
| if face_data: | |
| face_data = np.array(face_data) | |
| np.save(os.path.join(dataset_path, f"{name}.npy"), face_data) | |
| return jsonify({"status": "success", "message": f"{len(face_data)} faces saved"}) | |
| else: | |
| return jsonify({"status": "fail", "message": "No faces detected"}) | |
| # API to mark attendance | |
| @app.route('/api/mark_attendance', methods=['POST']) | |
| def mark_attendance(): | |
| img_data = request.json['image'] | |
| img_bytes = base64.b64decode(img_data.split(",")[1]) | |
| np_arr = np.frombuffer(img_bytes, np.uint8) | |
| img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR) | |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| faces = face_cascade.detectMultiScale(gray, 1.3, 5) | |
| # Load training data | |
| face_data = [] | |
| labels = [] | |
| names = {} | |
| class_id = 0 | |
| for file in os.listdir(dataset_path): | |
| if file.endswith('.npy'): | |
| data = np.load(os.path.join(dataset_path, file)) | |
| face_data.append(data) | |
| names[class_id] = file[:-4] | |
| labels.extend([class_id] * data.shape[0]) | |
| class_id += 1 | |
| if not face_data: | |
| return jsonify({"status": "fail", "message": "No trained data found"}) | |
| X_train = np.concatenate(face_data, axis=0) | |
| y_train = np.array(labels).reshape(-1, 1) | |
| trainset = np.hstack((X_train, y_train)) | |
| for (x, y, w, h) in faces[:1]: | |
| face = img[y:y+h, x:x+w] | |
| face = cv2.resize(face, (100, 100)).flatten() | |
| pred_id = knn(trainset, face) | |
| name = names.get(pred_id, "Unknown") | |
| if name != "Unknown": | |
| marked = attendance.mark(name) | |
| msg = "Attendance marked" if marked else "Already marked today" | |
| return jsonify({"status": "success", "name": name, "message": msg}) | |
| return jsonify({"status": "fail", "message": "No known face detected"}) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=5000, debug=True) | |
| index.html | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Face Attendance</title> | |
| <style> | |
| body { | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| margin: 0; | |
| padding: 0; | |
| background-color: #f5f5f5; | |
| color: #333; | |
| line-height: 1.6; | |
| } | |
| .container { | |
| width: 80%; | |
| max-width: 800px; | |
| margin: 50px auto; | |
| padding: 30px; | |
| background-color: #fff; | |
| border-radius: 8px; | |
| box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); | |
| text-align: center; | |
| } | |
| h2 { | |
| color: #2c3e50; | |
| margin-bottom: 30px; | |
| font-size: 32px; | |
| } | |
| .nav-links { | |
| display: flex; | |
| flex-direction: column; | |
| gap: 15px; | |
| margin-top: 25px; | |
| } | |
| .btn { | |
| display: inline-block; | |
| padding: 12px 24px; | |
| background-color: #3498db; | |
| color: white; | |
| text-decoration: none; | |
| border-radius: 5px; | |
| font-weight: 500; | |
| transition: background-color 0.3s; | |
| border: none; | |
| font-size: 16px; | |
| cursor: pointer; | |
| } | |
| .btn:hover { | |
| background-color: #2980b9; | |
| } | |
| .logo { | |
| font-size: 36px; | |
| color: #3498db; | |
| margin-bottom: 15px; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="logo"> | |
| <i class="fas fa-user-check"></i> | |
| </div> | |
| <h2>Welcome to Face Attendance System</h2> | |
| <div class="nav-links"> | |
| <a href="/register" class="btn">Register Face</a> | |
| <a href="/mark" class="btn">Mark Attendance</a> | |
| </div> | |
| </div> | |
| <!-- Add Font Awesome for icons --> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"></script> | |
| </body> | |
| </html> | |
| register.html | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Register Face</title> | |
| <style> | |
| body { | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| margin: 0; | |
| padding: 0; | |
| background-color: #f5f5f5; | |
| color: #333; | |
| line-height: 1.6; | |
| } | |
| .container { | |
| width: 80%; | |
| max-width: 800px; | |
| margin: 30px auto; | |
| padding: 30px; | |
| background-color: #fff; | |
| border-radius: 8px; | |
| box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); | |
| text-align: center; | |
| } | |
| h2 { | |
| color: #2c3e50; | |
| margin-bottom: 25px; | |
| font-size: 28px; | |
| } | |
| .btn { | |
| display: inline-block; | |
| padding: 12px 24px; | |
| background-color: #3498db; | |
| color: white; | |
| text-decoration: none; | |
| border-radius: 5px; | |
| font-weight: 500; | |
| transition: background-color 0.3s; | |
| border: none; | |
| font-size: 16px; | |
| cursor: pointer; | |
| margin-top: 15px; | |
| } | |
| .btn:hover { | |
| background-color: #2980b9; | |
| } | |
| input[type="text"] { | |
| width: 100%; | |
| padding: 12px; | |
| margin: 10px 0; | |
| border: 1px solid #ddd; | |
| border-radius: 4px; | |
| box-sizing: border-box; | |
| font-size: 16px; | |
| } | |
| video { | |
| margin: 20px auto; | |
| border-radius: 8px; | |
| box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); | |
| background-color: #eee; | |
| max-width: 100%; | |
| } | |
| #status { | |
| margin-top: 15px; | |
| font-weight: 500; | |
| color: #2c3e50; | |
| } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-bottom: 20px; | |
| } | |
| .back-link { | |
| color: #3498db; | |
| text-decoration: none; | |
| display: flex; | |
| align-items: center; | |
| font-weight: 500; | |
| } | |
| .back-link:hover { | |
| text-decoration: underline; | |
| } | |
| .form-container { | |
| margin-top: 20px; | |
| } | |
| .progress { | |
| margin-top: 10px; | |
| height: 10px; | |
| background-color: #eee; | |
| border-radius: 5px; | |
| overflow: hidden; | |
| position: relative; | |
| margin-bottom: 15px; | |
| } | |
| .progress-bar { | |
| height: 100%; | |
| background-color: #3498db; | |
| width: 0%; | |
| transition: width 0.5s ease; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <a href="/" class="back-link"> | |
| <i class="fas fa-arrow-left"></i> Back to Home | |
| </a> | |
| <h2>Register Face</h2> | |
| </div> | |
| <div class="form-container"> | |
| <input type="text" id="name" placeholder="Enter your name" required> | |
| <button onclick="startCapture()" class="btn"> | |
| <i class="fas fa-camera"></i> Start Capture | |
| </button> | |
| <div class="video-container"> | |
| <video id="video" width="300" autoplay></video> | |
| </div> | |
| <div class="progress"> | |
| <div class="progress-bar" id="progress-bar"></div> | |
| </div> | |
| <p id="status">Enter your name and click "Start Capture"</p> | |
| </div> | |
| </div> | |
| <script src="/static/js/webcam.js"></script> | |
| <!-- Modified script section --> | |
| <script> | |
| let frames = []; | |
| let interval; | |
| const TOTAL_FRAMES = 120; | |
| async function startCapture() { | |
| frames = []; | |
| const name = document.getElementById("name").value; | |
| if (!name) return alert("Please enter your name"); | |
| document.getElementById("status").innerHTML = | |
| "Capturing...<br><small>Slowly move your head - left, right, up, down</small>"; | |
| const progressBar = document.getElementById("progress-bar"); | |
| progressBar.style.width = "0%"; | |
| interval = setInterval(() => { | |
| captureFrame(frames); | |
| const progress = (frames.length / TOTAL_FRAMES) * 100; | |
| progressBar.style.width = progress + "%"; | |
| if (frames.length >= TOTAL_FRAMES) { | |
| clearInterval(interval); | |
| document.getElementById("status").innerHTML = "Processing...<br><small>This may take a moment</small>"; | |
| fetch('/api/register_face', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ name: name, images: frames }) | |
| }) | |
| .then(res => res.json()) | |
| .then(data => { | |
| let message = data.message; | |
| if (data.status === "success") { | |
| message += ". Please try to maintain consistent lighting in future sessions."; | |
| } | |
| document.getElementById("status").innerHTML = message; | |
| }); | |
| } | |
| }, 1000); // Slower interval (1 second) to allow movement | |
| } | |
| initWebcam("video"); | |
| </script> | |
| <!-- Add Font Awesome for icons --> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"></script> | |
| </body> | |
| </html> | |
| mark.html | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Mark Attendance</title> | |
| <style> | |
| body { | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| margin: 0; | |
| padding: 0; | |
| background-color: #f5f5f5; | |
| color: #333; | |
| line-height: 1.6; | |
| } | |
| .container { | |
| width: 80%; | |
| max-width: 800px; | |
| margin: 30px auto; | |
| padding: 30px; | |
| background-color: #fff; | |
| border-radius: 8px; | |
| box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); | |
| text-align: center; | |
| } | |
| h2 { | |
| color: #2c3e50; | |
| margin-bottom: 25px; | |
| font-size: 28px; | |
| } | |
| .btn { | |
| display: inline-block; | |
| padding: 12px 24px; | |
| background-color: #27ae60; | |
| color: white; | |
| text-decoration: none; | |
| border-radius: 5px; | |
| font-weight: 500; | |
| transition: background-color 0.3s; | |
| border: none; | |
| font-size: 16px; | |
| cursor: pointer; | |
| margin: 15px 0; | |
| } | |
| .btn:hover { | |
| background-color: #219653; | |
| } | |
| video { | |
| margin: 20px auto; | |
| border-radius: 8px; | |
| box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); | |
| background-color: #eee; | |
| max-width: 100%; | |
| } | |
| #status { | |
| margin-top: 20px; | |
| font-size: 18px; | |
| padding: 15px; | |
| border-radius: 5px; | |
| background-color: #f8f9fa; | |
| display: inline-block; | |
| min-width: 60%; | |
| } | |
| .success { | |
| color: #27ae60; | |
| font-weight: 600; | |
| } | |
| .error { | |
| color: #e74c3c; | |
| font-weight: 600; | |
| } | |
| .header { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| margin-bottom: 20px; | |
| } | |
| .back-link { | |
| color: #3498db; | |
| text-decoration: none; | |
| display: flex; | |
| align-items: center; | |
| font-weight: 500; | |
| } | |
| .back-link:hover { | |
| text-decoration: underline; | |
| } | |
| .video-container { | |
| position: relative; | |
| margin: 0 auto; | |
| width: 320px; | |
| max-width: 100%; | |
| } | |
| .camera-overlay { | |
| position: absolute; | |
| top: 0; | |
| left: 0; | |
| right: 0; | |
| bottom: 0; | |
| border: 2px solid rgba(52, 152, 219, 0.5); | |
| border-radius: 8px; | |
| pointer-events: none; | |
| } | |
| .loading { | |
| display: none; | |
| margin: 20px auto; | |
| border: 5px solid #f3f3f3; | |
| border-radius: 50%; | |
| border-top: 5px solid #3498db; | |
| width: 40px; | |
| height: 40px; | |
| animation: spin 1s linear infinite; | |
| } | |
| @keyframes spin { | |
| 0% { transform: rotate(0deg); } | |
| 100% { transform: rotate(360deg); } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <a href="/" class="back-link"> | |
| <i class="fas fa-arrow-left"></i> Back to Home | |
| </a> | |
| <h2>Mark Attendance</h2> | |
| </div> | |
| <div class="video-container"> | |
| <video id="video" width="300" autoplay></video> | |
| <div class="camera-overlay"></div> | |
| </div> | |
| <button onclick="markAttendance()" class="btn"> | |
| <i class="fas fa-user-check"></i> Mark Attendance | |
| </button> | |
| <div class="loading" id="loading"></div> | |
| <p id="status">Position your face in the camera and click the button</p> | |
| </div> | |
| <script src="/static/js/webcam.js"></script> | |
| <script> | |
| async function markAttendance() { | |
| document.getElementById("loading").style.display = "block"; | |
| document.getElementById("status").innerText = "Processing..."; | |
| captureFrame([], true).then(image => { | |
| fetch('/api/mark_attendance', { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ image: image }) | |
| }) | |
| .then(res => res.json()) | |
| .then(data => { | |
| document.getElementById("loading").style.display = "none"; | |
| const statusElem = document.getElementById("status"); | |
| if (data.name) { | |
| statusElem.innerHTML = `<span class="success">Welcome, ${data.name}!</span><br>${data.message}`; | |
| } else { | |
| statusElem.innerHTML = `<span class="error">Face not recognized</span><br>${data.message}`; | |
| } | |
| }) | |
| .catch(err => { | |
| document.getElementById("loading").style.display = "none"; | |
| document.getElementById("status").innerHTML = `<span class="error">Error: ${err.message}</span>`; | |
| }); | |
| }); | |
| } | |
| initWebcam("video"); | |
| </script> | |
| <!-- Add Font Awesome for icons --> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/js/all.min.js"></script> | |
| </body> | |
| </html> | |
| webcam.js | |
| function initWebcam(videoId) { | |
| const video = document.getElementById(videoId); | |
| navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { | |
| video.srcObject = stream; | |
| }); | |
| } | |
| function captureFrame(frameArray, single = false) { | |
| return new Promise((resolve) => { | |
| const video = document.getElementById("video"); | |
| const canvas = document.createElement("canvas"); | |
| canvas.width = video.videoWidth; | |
| canvas.height = video.videoHeight; | |
| const ctx = canvas.getContext("2d"); | |
| ctx.drawImage(video, 0, 0); | |
| // Check if frame contains content | |
| const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); | |
| const isEmpty = !imageData.data.some(channel => channel !== 0); | |
| if (!isEmpty) { | |
| const image = canvas.toDataURL("image/jpeg"); | |
| if (!single) { | |
| frameArray.push(image); | |
| } | |
| resolve(image); | |
| } else { | |
| resolve(null); | |
| } | |
| }); | |
| } | |