123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565 |
- 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 "Please get registered with your Profile Picture",500
- # return "Face not found in profile (please change your profile)",500
-
-
- 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 "Too Many Faces in Profile Picture",500
- 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('/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 'please get registered with your PhotoID',500
- except IndexError:
- #return 'unable to recognize face'
- #return 'failed',500
- return "Face does not Match with Profile Picture",500
-
- pool.close()
-
- return results[0]
-
-
-
- @app.route('/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]
- result=registered(url_list)
- return 'Successfully saved encoding.........'
-
-
-
-
- if __name__ == "__main__":
- app.run(host='0.0.0.0',port =5003,debug=False)
|