diff --git a/.gitignore b/.gitignore index a6665a7..636309c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ lib lib64 +uploads +students_data.pkl \ No newline at end of file diff --git a/app.py b/app.py index 927470c..7a45837 100644 --- a/app.py +++ b/app.py @@ -1,77 +1,86 @@ -from flask import Flask, request, jsonify, render_template, send_from_directory, make_response -from flask_cors import CORS -import face_recognition +from flask import Flask, request, jsonify import os -import numpy as np +import face_recognition import pickle +from werkzeug.utils import secure_filename +from time import time app = Flask(__name__) -CORS(app) -#pip install Flask flask-cors face_recognition +app.config['UPLOAD_FOLDER'] = 'uploads/' +app.config['STUDENT_DATA_FILE'] = 'students_data.pkl' -# Directory to save student images and encodings -STUDENT_IMAGES_DIR = 'student_images' -STUDENT_ENCODINGS_FILE = 'student_encodings.pkl' +if not os.path.exists(app.config['UPLOAD_FOLDER']): + os.makedirs(app.config['UPLOAD_FOLDER']) -# 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) +# Load or initialize student data +if os.path.exists(app.config['STUDENT_DATA_FILE']): + with open(app.config['STUDENT_DATA_FILE'], 'rb') as f: + students_db = pickle.load(f) else: - student_encodings = {} + students_db = {} -@app.route('/upload', 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 +def save_student_data(): + with open(app.config['STUDENT_DATA_FILE'], 'wb') as f: + pickle.dump(students_db, f) - images = request.files.getlist('images') - encodings = [] +@app.route('/upl', methods=['POST']) +def upload_image(): + if 'face' not in request.files or 'student_id' not in request.form: + return jsonify({'error': 'Image or student_id not provided'}), 400 - for image in images: - - image_path = os.path.join(STUDENT_IMAGES_DIR, f"{student_id}_{image.filename}") - image.save(image_path) + image = request.files['face'] + student_id = request.form['student_id'] + timestamp = int(time()) + filename = secure_filename(f"{timestamp}.jpg") + student_folder = os.path.join(app.config['UPLOAD_FOLDER'], student_id) + if not os.path.exists(student_folder): + os.makedirs(student_folder) + filepath = os.path.join(student_folder, filename) + image.save(filepath) - # Load the image and get the face encodings - img = face_recognition.load_image_file(image_path) - img_encodings = face_recognition.face_encodings(img) + # Load the image file into a numpy array + image_array = face_recognition.load_image_file(filepath) + # Get the face encoding for the image + face_encodings = face_recognition.face_encodings(image_array) - 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 + if len(face_encodings) > 0: + # Assuming the first face found in the image is the correct one + students_db[student_id] = face_encodings[0] + save_student_data() + return jsonify({'message': 'Image uploaded and student registered successfully', 'student_id': student_id}), 200 else: - return jsonify({"error": "No faces found in the uploaded images"}), 400 + return jsonify({'error': 'No faces found in the image'}), 400 -@app.route('/recognize', methods=['POST']) -def recognize(): - if 'image' not in request.files: - return jsonify({"error": "No image provided"}), 400 +@app.route('/rec', methods=['POST']) +def recognize_image(): + if 'face' not in request.files: + return jsonify({'error': 'Image not provided'}), 400 - image = request.files['image'] - img = face_recognition.load_image_file(image) - img_encodings = face_recognition.face_encodings(img) + image = request.files['face'] + # Load the uploaded image file into a numpy array + unknown_image = face_recognition.load_image_file(image) + # Get the face encodings for the uploaded image + unknown_encodings = face_recognition.face_encodings(unknown_image) - 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) + if len(unknown_encodings) > 0: + unknown_encoding = unknown_encodings[0] + best_match_id = None + best_match_score = None - return jsonify({"student_id": student_id}), 200 - else: - return jsonify({"error": "No face found in the uploaded image"}), 400 + for student_id, known_encoding in students_db.items(): + # Calculate the distance between the known encoding and the uploaded image encoding + distance = face_recognition.face_distance([known_encoding], unknown_encoding)[0] + # Convert distance to accuracy score (the closer the distance, the higher the accuracy) + accuracy_score = (1 - distance) * 100 + + if best_match_score is None or accuracy_score > best_match_score: + best_match_id = student_id + best_match_score = accuracy_score + + if best_match_id: + return jsonify({'student_id': best_match_id, 'accuracy_score': best_match_score}), 200 + + return jsonify({'error': 'Student not recognized'}), 404 if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=5005) diff --git a/app2.py b/app2.py deleted file mode 100644 index d491081..0000000 --- a/app2.py +++ /dev/null @@ -1,80 +0,0 @@ -from flask import Flask, request, jsonify, render_template, send_from_directory, make_response -from flask_restful import Api, Resource -import os -import face_recognition -from werkzeug.utils import secure_filename -from PIL import Image -import numpy as np - -app = Flask(__name__) -api = Api(app) - -UPLOAD_FOLDER = 'upload' -if not os.path.exists(UPLOAD_FOLDER): - os.makedirs(UPLOAD_FOLDER) - -app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER - -# Helper function to save image -def save_image(image, roll_number): - roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number) - if not os.path.exists(roll_number_folder): - os.makedirs(roll_number_folder) - image_count = len(os.listdir(roll_number_folder)) + 1 - image_path = os.path.join(roll_number_folder, f"{image_count}.jpg") - image.save(image_path) - return image_path - -# Helper function to load known faces -def load_known_faces(): - known_faces = [] - known_roll_numbers = [] - for roll_number in os.listdir(app.config['UPLOAD_FOLDER']): - roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number) - for filename in os.listdir(roll_number_folder): - image_path = os.path.join(roll_number_folder, filename) - image = face_recognition.load_image_file(image_path) - encodings = face_recognition.face_encodings(image) - if encodings: - known_faces.append(encodings[0]) - known_roll_numbers.append(roll_number) - return known_faces, known_roll_numbers - -class UploadImage(Resource): - def post(self): - roll_number = request.form['roll_number'] - if 'image' not in request.files: - return jsonify({"error": "No image provided"}), 400 - image = request.files['image'] - filename = secure_filename(image.filename) - image = Image.open(image) - image_path = save_image(image, roll_number) - return jsonify({"message": f"Image saved as {image_path}"}), 200 - -class RecognizeStudent(Resource): - def post(self): - if 'image' not in request.files: - return jsonify({"error": "No image provided"}), 400 - image = request.files['image'] - filename = secure_filename(image.filename) - image = face_recognition.load_image_file(image) - unknown_encodings = face_recognition.face_encodings(image) - if not unknown_encodings: - return jsonify({"error": "No faces found in the image"}), 400 - unknown_encoding = unknown_encodings[0] - - known_faces, known_roll_numbers = load_known_faces() - results = face_recognition.compare_faces(known_faces, unknown_encoding) - - if True in results: - matched_index = results.index(True) - roll_number = known_roll_numbers[matched_index] - return jsonify({"roll_number": roll_number}), 200 - else: - return jsonify({"error": "No matching student found"}), 404 - -api.add_resource(UploadImage, '/upload') -api.add_resource(RecognizeStudent, '/recognize') - -if __name__ == '__main__': - app.run(debug=True, host="0.0.0.0", port=5005) diff --git a/app3.py b/app3.py deleted file mode 100644 index 93a0028..0000000 --- a/app3.py +++ /dev/null @@ -1,84 +0,0 @@ -from flask import Flask, request, jsonify, render_template, send_from_directory, make_response -from flask_restful import Api, Resource -import os -import face_recognition -from werkzeug.utils import secure_filename -from PIL import Image -import numpy as np - -app = Flask(__name__) -api = Api(app) - -UPLOAD_FOLDER = 'upload' -if not os.path.exists(UPLOAD_FOLDER): - os.makedirs(UPLOAD_FOLDER) - -app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER - -# Helper function to save image -def save_image(image, roll_number): - roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number) - if not os.path.exists(roll_number_folder): - os.makedirs(roll_number_folder) - image_count = len(os.listdir(roll_number_folder)) + 1 - image_path = os.path.join(roll_number_folder, f"{image_count}.jpg") - image.save(image_path) - return image_path - -# Helper function to load known faces -def load_known_faces(): - known_faces = [] - known_roll_numbers = [] - for roll_number in os.listdir(app.config['UPLOAD_FOLDER']): - roll_number_folder = os.path.join(app.config['UPLOAD_FOLDER'], roll_number) - for filename in os.listdir(roll_number_folder): - image_path = os.path.join(roll_number_folder, filename) - image = face_recognition.load_image_file(image_path) - encodings = face_recognition.face_encodings(image) - if encodings: - known_faces.append(encodings[0]) - known_roll_numbers.append(roll_number) - return known_faces, known_roll_numbers - -@app.route('/') -def index(): - return render_template('./upload.html') - -class UploadImage(Resource): - def post(self): - roll_number = request.form['roll_number'] - if 'image' not in request.files: - return jsonify({"error": "No image provided"}), 400 - image = request.files['image'] - filename = secure_filename(image.filename) - image = Image.open(image) - image_path = save_image(image, roll_number) - return jsonify({"message": f"Image saved as {image_path}"}), 200 - -class RecognizeStudent(Resource): - def post(self): - if 'image' not in request.files: - return jsonify({"error": "No image provided"}), 400 - image = request.files['image'] - filename = secure_filename(image.filename) - image = face_recognition.load_image_file(image) - unknown_encodings = face_recognition.face_encodings(image) - if not unknown_encodings: - return jsonify({"error": "No faces found in the image"}), 400 - unknown_encoding = unknown_encodings[0] - - known_faces, known_roll_numbers = load_known_faces() - results = face_recognition.compare_faces(known_faces, unknown_encoding) - - if True in results: - matched_index = results.index(True) - roll_number = known_roll_numbers[matched_index] - return jsonify({"roll_number": roll_number}), 200 - else: - return jsonify({"error": "No matching student found"}), 404 - -api.add_resource(UploadImage, '/upload') -api.add_resource(RecognizeStudent, '/recognize') - -if __name__ == '__main__': - app.run(debug=True, host="0.0.0.0", port=5005) diff --git a/app4.py b/app4.py deleted file mode 100644 index 164e767..0000000 --- a/app4.py +++ /dev/null @@ -1,93 +0,0 @@ -import os -from flask import Flask, request, jsonify -import face_recognition -import pickle -from PIL import Image -import numpy as np - -app = Flask(__name__) - -UPLOAD_FOLDER = 'student_roll/uploads/' -FACE_DATA_FOLDER = 'student_roll/face_data/' - -os.makedirs(UPLOAD_FOLDER, exist_ok=True) -os.makedirs(FACE_DATA_FOLDER, exist_ok=True) - -def convert_image_to_8bit_rgb(image_path): - with Image.open(image_path) as img: - if img.mode != 'RGB': - img = img.convert('RGB') - img = img.convert('RGB') # Ensure conversion to 8-bit per channel - img_array = np.array(img) - return img_array - -@app.route('/upload', methods=['POST']) -def upload_image(): - if 'image' not in request.files: - return jsonify({"error": "No image part in the request"}), 400 - - file = request.files['image'] - if file.filename == '': - return jsonify({"error": "No selected file"}), 400 - - student_roll = request.form.get('student_roll') - if not student_roll: - return jsonify({"error": "Student roll number is required"}), 400 - - file_path = os.path.join(UPLOAD_FOLDER, f"{student_roll}.jpg") - file.save(file_path) - - try: - # Convert image to 8-bit RGB if necessary - image = convert_image_to_8bit_rgb(file_path) - face_encodings = face_recognition.face_encodings(image) - - if not face_encodings: - return jsonify({"error": "No face found in the image"}), 400 - - face_data_path = os.path.join(FACE_DATA_FOLDER, f"{student_roll}.pkl") - with open(face_data_path, 'wb') as f: - pickle.dump(face_encodings[0], f) - - return jsonify({"message": "Image and face data uploaded successfully"}), 200 - except Exception as e: - return jsonify({"error": str(e)}), 500 - -@app.route('/recognize_student', methods=['POST']) -def recognize_student(): - if 'image' not in request.files: - return jsonify({"error": "No image part in the request"}), 400 - - file = request.files['image'] - if file.filename == '': - return jsonify({"error": "No selected file"}), 400 - - file_path = os.path.join(UPLOAD_FOLDER, "temp.jpg") - file.save(file_path) - - try: - # Convert image to 8-bit RGB if necessary - image = convert_image_to_8bit_rgb(file_path) - face_encodings = face_recognition.face_encodings(image) - - if not face_encodings: - return jsonify({"error": "No face found in the image"}), 400 - - uploaded_face_encoding = face_encodings[0] - - # Load all stored face data - for face_data_file in os.listdir(FACE_DATA_FOLDER): - with open(os.path.join(FACE_DATA_FOLDER, face_data_file), 'rb') as f: - known_face_encoding = pickle.load(f) - matches = face_recognition.compare_faces([known_face_encoding], uploaded_face_encoding) - - if matches[0]: - student_roll = os.path.splitext(face_data_file)[0] - return jsonify({"student_roll": student_roll}), 200 - - return jsonify({"error": "No matching student found"}), 404 - except Exception as e: - return jsonify({"error": str(e)}), 500 - -if __name__ == '__main__': - app.run(debug=True, host="0.0.0.0", port=5005) diff --git a/app5.py b/app5.py deleted file mode 100644 index 1916ab2..0000000 --- a/app5.py +++ /dev/null @@ -1,81 +0,0 @@ -from flask import Flask, request, jsonify -import os -import face_recognition -import pickle -from werkzeug.utils import secure_filename - -app = Flask(__name__) -app.config['UPLOAD_FOLDER'] = 'uploads/' -app.config['STUDENT_DATA_FILE'] = 'students_data.pkl' - -if not os.path.exists(app.config['UPLOAD_FOLDER']): - os.makedirs(app.config['UPLOAD_FOLDER']) - -# Load or initialize student data -if os.path.exists(app.config['STUDENT_DATA_FILE']): - with open(app.config['STUDENT_DATA_FILE'], 'rb') as f: - students_db = pickle.load(f) -else: - students_db = {} - -def save_student_data(): - with open(app.config['STUDENT_DATA_FILE'], 'wb') as f: - pickle.dump(students_db, f) - -@app.route('/upload', methods=['POST']) -def upload_image(): - if 'image' not in request.files or 'student_id' not in request.form: - return jsonify({'error': 'Image or student_id not provided'}), 400 - - image = request.files['image'] - student_id = request.form['student_id'] - filename = secure_filename(f"{student_id}_{image.filename}") - filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) - image.save(filepath) - - # Load the image file into a numpy array - image = face_recognition.load_image_file(filepath) - # Get the face encoding for the image - face_encodings = face_recognition.face_encodings(image) - - if len(face_encodings) > 0: - # Assuming the first face found in the image is the correct one - students_db[student_id] = face_encodings[0] - save_student_data() - return jsonify({'message': 'Image uploaded and student registered successfully', 'student_id': student_id}), 200 - else: - return jsonify({'error': 'No faces found in the image'}), 400 - -@app.route('/recognize_image', methods=['POST']) -def recognize_image(): - if 'image' not in request.files: - return jsonify({'error': 'Image not provided'}), 400 - - image = request.files['image'] - # Load the uploaded image file into a numpy array - unknown_image = face_recognition.load_image_file(image) - # Get the face encodings for the uploaded image - unknown_encodings = face_recognition.face_encodings(unknown_image) - - if len(unknown_encodings) > 0: - unknown_encoding = unknown_encodings[0] - best_match_id = None - best_match_score = None - - for student_id, known_encoding in students_db.items(): - # Calculate the distance between the known encoding and the uploaded image encoding - distance = face_recognition.face_distance([known_encoding], unknown_encoding)[0] - # Convert distance to accuracy score (the closer the distance, the higher the accuracy) - accuracy_score = (1 - distance) * 100 - - if best_match_score is None or accuracy_score > best_match_score: - best_match_id = student_id - best_match_score = accuracy_score - - if best_match_id: - return jsonify({'student_id': best_match_id, 'accuracy_score': best_match_score}), 200 - - return jsonify({'error': 'Student not recognized'}), 404 - -if __name__ == '__main__': - app.run(debug=True, host="0.0.0.0", port=5005) diff --git a/app6.py b/app6.py deleted file mode 100644 index c844647..0000000 --- a/app6.py +++ /dev/null @@ -1,86 +0,0 @@ -from flask import Flask, request, jsonify -import os -import face_recognition -import pickle -from werkzeug.utils import secure_filename -from time import time - -app = Flask(__name__) -app.config['UPLOAD_FOLDER'] = 'uploads/' -app.config['STUDENT_DATA_FILE'] = 'students_data.pkl' - -if not os.path.exists(app.config['UPLOAD_FOLDER']): - os.makedirs(app.config['UPLOAD_FOLDER']) - -# Load or initialize student data -if os.path.exists(app.config['STUDENT_DATA_FILE']): - with open(app.config['STUDENT_DATA_FILE'], 'rb') as f: - students_db = pickle.load(f) -else: - students_db = {} - -def save_student_data(): - with open(app.config['STUDENT_DATA_FILE'], 'wb') as f: - pickle.dump(students_db, f) - -@app.route('/upl', methods=['POST']) -def upload_image(): - if 'face' not in request.files or 'student_id' not in request.form: - return jsonify({'error': 'Image or student_id not provided'}), 400 - - image = request.files['face'] - student_id = request.form['student_id'] - timestamp = int(time()) - filename = secure_filename(f"{timestamp}.jpg") - student_folder = os.path.join(app.config['UPLOAD_FOLDER'], student_id) - if not os.path.exists(student_folder): - os.makedirs(student_folder) - filepath = os.path.join(student_folder, filename) - image.save(filepath) - - # Load the image file into a numpy array - image_array = face_recognition.load_image_file(filepath) - # Get the face encoding for the image - face_encodings = face_recognition.face_encodings(image_array) - - if len(face_encodings) > 0: - # Assuming the first face found in the image is the correct one - students_db[student_id] = face_encodings[0] - save_student_data() - return jsonify({'message': 'Image uploaded and student registered successfully', 'student_id': student_id}), 200 - else: - return jsonify({'error': 'No faces found in the image'}), 400 - -@app.route('/rec', methods=['POST']) -def recognize_image(): - if 'image' not in request.files: - return jsonify({'error': 'Image not provided'}), 400 - - image = request.files['image'] - # Load the uploaded image file into a numpy array - unknown_image = face_recognition.load_image_file(image) - # Get the face encodings for the uploaded image - unknown_encodings = face_recognition.face_encodings(unknown_image) - - if len(unknown_encodings) > 0: - unknown_encoding = unknown_encodings[0] - best_match_id = None - best_match_score = None - - for student_id, known_encoding in students_db.items(): - # Calculate the distance between the known encoding and the uploaded image encoding - distance = face_recognition.face_distance([known_encoding], unknown_encoding)[0] - # Convert distance to accuracy score (the closer the distance, the higher the accuracy) - accuracy_score = (1 - distance) * 100 - - if best_match_score is None or accuracy_score > best_match_score: - best_match_id = student_id - best_match_score = accuracy_score - - if best_match_id: - return jsonify({'student_id': best_match_id, 'accuracy_score': best_match_score}), 200 - - return jsonify({'error': 'Student not recognized'}), 404 - -if __name__ == '__main__': - app.run(debug=True, host="0.0.0.0", port=5005) diff --git a/student_encodings.pkl b/student_encodings.pkl deleted file mode 100644 index cbc3e9b..0000000 Binary files a/student_encodings.pkl and /dev/null differ diff --git a/templates/upload.html b/templates/upload.html deleted file mode 100644 index f4b207c..0000000 --- a/templates/upload.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - Upload Student Image - - -

Upload Student Image

-
- - -

- - -

- -
- - diff --git a/upload.py b/upload.py deleted file mode 100644 index f0893b8..0000000 --- a/upload.py +++ /dev/null @@ -1,29 +0,0 @@ -from flask import Flask, render_template, request, jsonify, make_response -import os - -app = Flask(__name__) -UPLOAD_FOLDER = 'uploads' -app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER - -@app.route('/') -def upload_form(): - return render_template('upload.html') - -@app.route('/upload', methods=['POST']) -def upload_file(): - folder_number = request.form['roll_number'] - images = request.files.getlist('images[]') - - folder_path = os.path.join(app.config['UPLOAD_FOLDER'], folder_number) - os.makedirs(folder_path, exist_ok=True) - - for image in images: - if image.filename == '': - continue - filename = image.filename - image.save(os.path.join(folder_path, filename)) - - return make_response(jsonify('success'), 200) - -if __name__ == '__main__': - app.run(debug=True, host="0.0.0.0", port=5005)