from flask import Flask, request, jsonify from flask_cors import CORS import face_recognition import os import numpy as np import pickle app = Flask(__name__) CORS(app) #pip install Flask flask-cors face_recognition # Directory to save student images and encodings STUDENT_IMAGES_DIR = 'student_images' STUDENT_ENCODINGS_FILE = 'student_encodings.pkl' # Ensure the directory exists os.makedirs(STUDENT_IMAGES_DIR, exist_ok=True) # Load existing encodings if available if os.path.exists(STUDENT_ENCODINGS_FILE): with open(STUDENT_ENCODINGS_FILE, 'rb') as f: student_encodings = pickle.load(f) else: student_encodings = {} @app.route('/upload_images', methods=['POST']) def upload_images(): student_id = request.form.get('student_id') if 'images' not in request.files or not student_id: return jsonify({"error": "No images or student ID provided"}), 400 images = request.files.getlist('images') encodings = [] for image in images: image_path = os.path.join(STUDENT_IMAGES_DIR, f"{student_id}_{image.filename}") image.save(image_path) # Load the image and get the face encodings img = face_recognition.load_image_file(image_path) img_encodings = face_recognition.face_encodings(img) if img_encodings: encodings.append(img_encodings[0]) if encodings: student_encodings[student_id] = np.mean(encodings, axis=0) # Save the encodings to file with open(STUDENT_ENCODINGS_FILE, 'wb') as f: pickle.dump(student_encodings, f) return jsonify({"message": "Images uploaded and processed successfully"}), 200 else: return jsonify({"error": "No faces found in the uploaded images"}), 400 @app.route('/recognize', methods=['POST']) def recognize(): if 'image' not in request.files: return jsonify({"error": "No image provided"}), 400 image = request.files['image'] img = face_recognition.load_image_file(image) img_encodings = face_recognition.face_encodings(img) if img_encodings: img_encoding = img_encodings[0] distances = {student_id: np.linalg.norm(encoding - img_encoding) for student_id, encoding in student_encodings.items()} student_id = min(distances, key=distances.get) return jsonify({"student_id": student_id}), 200 else: return jsonify({"error": "No face found in the uploaded image"}), 400 if __name__ == '__main__': app.run(debug=True)