from flask import Flask, render_template, request, redirect, Response, send_file import multiprocessing import face_recognition #from numba import jit import numpy as np import os #from flask_cors import CORS app = Flask(__name__) #CORS(app) lst = [] Gallery="Gallery" People='People' @app.route('/', methods=['GET']) def resume(): #return render_template('index.html') return 'Attendence app running' def createEncodings(image): print("Encoding") """ Create face encodings for a given image and also return face locations in the given image. Parameters ------- image : cv2 mat Image you want to detect faces from. Returns ------- known_encodings : list of np array List of face encodings in a given image face_locations : list of tuples list of tuples for face locations in a given image """ # Find face locations for all faces in an image face_locations = face_recognition.face_locations(image) # Create encodings for all faces in an image known_encodings = face_recognition.face_encodings(image, known_face_locations=face_locations) return known_encodings, face_locations #@app.route('/registered', methods=["POST","GET"]) def registered(url_list): input=url_list from pathlib import Path Path(People).mkdir(exist_ok=True) Path(People+"/" + input["FileName"]).mkdir(exist_ok=True) a = input # print(a) x = a['FileData'] # print(x) y = a['FileName'] #z = a['FileType'] z='jpg' # CreatedBy=a['CreatedBy'] name = y+ '.'+ z print(name) # print(y) # image = y.split("/") # filename=image[-1] # print(x) try: img_data = x.encode() except AttributeError: return "Successfully saved encoding........." import base64 with open(People+"/" + input["FileName"] + "/" + name, "wb") as fh: fh.write(base64.decodebytes(img_data)) img = People+"/" + y + "/" + name saveLocation = People+"/" + y + "/" + y + ".pickle" ############ detecting no of faceses ####################### # import cv2 # import numpy as np # import dlib # # Connects to your computer's default camera # cap = cv2.imread(img) # # Detect the coordinates # detector = dlib.get_frontal_face_detector() # number_of_faces=[] # # Capture frames continuously # # while True: # # Capture frame-by-frame # # ret, frame = cap # frame = cap # # RGB to grayscale # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # faces = detector(gray) # # Iterator to count faces # i = 0 # for face in faces: # # Get the coordinates of faces # x, y = face.left(), face.top() # x1, y1 = face.right(), face.bottom() # cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2) # # Increment iterator for each face in faces # i = i+1 # # Display the box and faces # cv2.putText(frame, 'face num'+str(i), (x-10, y-10), # cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # # if len(i)>1: # # print(i) # number_of_faces.append(i) # if (len(number_of_faces))>1: # print("Group Photo") # return "Group Photo" # elif (len(number_of_faces))==1: # print("Single Photo") # pass def saveEncodings(encs, names, fname='encodings.pickle'): """ Save encodings in a pickle file to be used in future. Parameters ---------- encs : List of np arrays List of face encodings. names : List of strings List of names for each face encoding. fname : String, optional Name/Location for pickle file. The default is "encodings.pickle". Returns ------- None. """ data = [] d = [{"name": nm, "encoding": enc} for (nm, enc) in zip(names, encs)] data.extend(d) encodingsFile = fname # dump the facial encodings data to disk print("[INFO] serializing encodings...") print("[INFO] Encodings Created sucessfully") f = open(encodingsFile, "wb") f.write(pickle.dumps(data)) f.close() # Function to create encodings and get face locations def processKnownPeopleImages(img=img, saveLocation=saveLocation): """ Process images of known people and create face encodings to compare in future. Eaach image should have just 1 face in it. Parameters ---------- path : STRING, optional Path for known people dataset. The default is "C:/inetpub/vhosts/port82/wwwroot/_files/People". It should be noted that each image in this dataset should contain only 1 face. saveLocation : STRING, optional Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory". Returns ------- None. """ known_encodings = [] known_names = [] # for img in os.listdir(path): imgPath = img # Read image image = cv2.imread(imgPath) name = img.rsplit('.')[0] # Resize try: print(image.shape) except AttributeError: return "Successfully saved encoding........." image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR) # Get locations and encodings encs, locs = createEncodings(image) try: known_encodings.append(encs[0]) except IndexError: os.remove(saveLocation) print('------------------------------------- save location --------------------------------') print(saveLocation) return "hello world!" # known_encodings.append(encs[0]) known_names.append(name) for loc in locs: top, right, bottom, left = loc # Show Image # cv2.rectangle(image, (left, top), (right, bottom), color=(255, 0, 0), thickness=2) # cv2.imshow("Image", image) # cv2.waitKey(1) # cv2.destroyAllWindows() saveEncodings(known_encodings, known_names, saveLocation) import cv2 #import face_recognition import pickle processKnownPeopleImages(img, saveLocation) return 'Successfully saved encoding.........' # ******************************** COMPARUISION ********************************************************* #@app.route('/submit', methods=["POST","GET"]) def submit(url_list): from datetime import datetime import pytz tz_NY = pytz.timezone('Asia/Kolkata') datetime_NY = datetime.now(tz_NY) India_Date = (datetime_NY.strftime("%Y-%m-%d")) India_Date = str(India_Date) # India_Time = (datetime_NY.strftime("%I:%M:%S %p")) # India_Time = str(India_Time) input=url_list import pickle import cv2 from pathlib import Path Path(Gallery).mkdir(exist_ok=True) Path(Gallery+"/"+ India_Date).mkdir(exist_ok=True) Path(Gallery+"/"+ India_Date +'/'+ input["FileName"]).mkdir(exist_ok=True) a = input # print(a) x = a['FileData'] # print(x) y = a['FileName'] # z = a['FileType'] z='jpg' # CreatedBy=a['CreatedBy'] name = y + '.' + z # print(name) # print(y) # image = y.split("/") # filename=image[-1] # print(x) img_data = x.encode() import base64 with open(Gallery+"/"+India_Date+'/' + input["FileName"] + "/" + name, "wb") as fh: fh.write(base64.decodebytes(img_data)) path = Gallery+"/" +India_Date+'/'+ y + "/" + name pickle_location = People+"/" + y + "/" + y + ".pickle" import pathlib file = pathlib.Path(pickle_location) if file.exists (): pass else: print ("pickle File not exist") print(name) return "Face not found in profile (please change your profile)" check_faces=People+"/" + y + "/" + y + ".jpg" print(check_faces) ############ detecting no of faceses ####################### import cv2 import numpy as np import dlib # Connects to your computer's default camera cap = cv2.imread(check_faces) # Detect the coordinates detector = dlib.get_frontal_face_detector() number_of_faces=[] # Capture frames continuously # while True: # Capture frame-by-frame # ret, frame = cap frame = cap # RGB to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray) # Iterator to count faces i = 0 for face in faces: # Get the coordinates of faces x, y = face.left(), face.top() x1, y1 = face.right(), face.bottom() cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2) # Increment iterator for each face in faces i = i+1 # Display the box and faces cv2.putText(frame, 'face num'+str(i), (x-10, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # if len(i)>1: # print(i) number_of_faces.append(i) if (len(number_of_faces))>1: print("Group Photo") return "Group Photo" elif (len(number_of_faces))==1: print("Single Photo") pass def readEncodingsPickle(fname): """ Read Pickle file. Parameters ---------- fname : String Name of pickle file.(Full location) Returns ------- encodings : list of np arrays list of all saved encodings names : List of Strings List of all saved names """ data = pickle.loads(open(fname, "rb").read()) data = np.array(data) encodings = [d["encoding"] for d in data] names = [d["name"] for d in data] return encodings, names def compareFaceEncodings(unknown_encoding, known_encodings, known_names): """ Compares face encodings to check if 2 faces are same or not. Parameters ---------- unknown_encoding : np array Face encoding of unknown people. known_encodings : np array Face encodings of known people. known_names : list of strings Names of known people Returns ------- acceptBool : Bool face matched or not duplicateName : String Name of matched face distance : Float Distance between 2 faces """ duplicateName = "" distance = 0.0 matches = face_recognition.compare_faces(known_encodings, unknown_encoding, tolerance=0.54) face_distances = face_recognition.face_distance(known_encodings, unknown_encoding) best_match_index = np.argmin(face_distances) distance = face_distances[best_match_index] if matches[best_match_index]: acceptBool = True duplicateName = known_names[best_match_index] else: acceptBool = False duplicateName = "" return acceptBool, duplicateName, distance #p = [] def processDatasetImages(path=path, pickle_location=pickle_location): """ Process image in dataset from where you want to separate images. It separates the images into directories of known people, groups and any unknown people images. Parameters ---------- path : STRING, optional Path for known people dataset. The default is "D:/port1004/port1004/wwwroot/_files/People". It should be noted that each image in this dataset should contain only 1 face. saveLocation : STRING, optional Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory". Returns ------- None. """ # Read pickle file for known people to compare faces from people_encodings, names = readEncodingsPickle(pickle_location) # print(p) # imgPath = path + img # Read image # path=r"C:\Users\katku\Pictures\final\100011460000611.jpg" image = cv2.imread(path) #orig = image.copy() # Resize image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR) # Get locations and encodings encs, locs = createEncodings(image) # Save image to a group image folder if more than one face is in image # if len(locs) > 1: # saveImageToDirectory(orig, "Group", img) # Processing image for each face i = 0 knownFlag = 0 for loc in locs: top, right, bottom, left = loc unknown_encoding = encs[i] i += 1 acceptBool, duplicateName, distance = compareFaceEncodings(unknown_encoding, people_encodings, names) if acceptBool: # saveImageToDirectory(orig, duplicateName,name) knownFlag = 1 if knownFlag == 1: print("Match Found") #print(path) with_extension = path.split("/")[-1] without_extension = with_extension.split(".")[0] # output_s = {"FileID": without_extension, # "Date": India_Date, # "Time": India_Time} # output_json = json.dumps(output_s) output_json='Matched successfully' print(loc) lst.append(output_json) print(output_json) # exit() else: print('Not Matched') pass # saveImageToDirectory(orig, "0",name) import numpy as np import json processDatasetImages(path, pickle_location) return lst[0] #return 'matched successfully' @app.route('/uat01_detect', methods=["POST"]) def detect(): if __name__ == "__main__": url_list=[] Dataset= request.get_json() # id = "100013660000125" url_list.append(Dataset) # multiprocessing pool_size = multiprocessing.cpu_count() * 2 with multiprocessing.Pool(pool_size) as pool: try: results = pool.map(submit, url_list) except FileNotFoundError: return 'plese get registered with your PhotoID' except IndexError: #return 'unable to recognize face' return 'failed' pool.close() return results[0] @app.route('/uat01_register', methods=["POST"]) def register(): print("hello start..........") if __name__ == "__main__": url_list=[] Dataset= request.get_json() # id = "100013660000125" url_list.append(Dataset) UserLocation=Dataset["FilePath"] print(UserLocation) # if "cO2" in UserLocation or UserLocation is None: # pass # else: # return "Please update the URL in the integration" # multiprocessing pool_size = multiprocessing.cpu_count() * 2 with multiprocessing.Pool(pool_size) as pool: try: results = pool.map(registered, url_list) except IndexError: pass print('face not found') except FileNotFoundError: pass #os.remove(img) # return 'unable to recognize face' pool.close() #return results[0] return 'Successfully saved encoding.........' if __name__ == "__main__": app.run(host='0.0.0.0',port =5005,debug=False)