Bez popisu
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

attendence.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. from flask import Flask, render_template, request, redirect, Response, send_file
  2. import multiprocessing
  3. import face_recognition
  4. #from numba import jit
  5. import numpy as np
  6. import os
  7. #from flask_cors import CORS
  8. app = Flask(__name__)
  9. #CORS(app)
  10. lst = []
  11. @app.route('/', methods=['GET'])
  12. def resume():
  13. #return render_template('index.html')
  14. return 'Attendence app running'
  15. def createEncodings(image):
  16. print("Encoding")
  17. """
  18. Create face encodings for a given image and also return face locations in the given image.
  19. Parameters
  20. -------
  21. image : cv2 mat
  22. Image you want to detect faces from.
  23. Returns
  24. -------
  25. known_encodings : list of np array
  26. List of face encodings in a given image
  27. face_locations : list of tuples
  28. list of tuples for face locations in a given image
  29. """
  30. # Find face locations for all faces in an image
  31. face_locations = face_recognition.face_locations(image)
  32. # Create encodings for all faces in an image
  33. known_encodings = face_recognition.face_encodings(image, known_face_locations=face_locations)
  34. return known_encodings, face_locations
  35. #@app.route('/registered', methods=["POST","GET"])
  36. def registered(url_list):
  37. input=url_list
  38. from pathlib import Path
  39. Path("ppeople").mkdir(exist_ok=True)
  40. Path("ppeople/" + input["FileName"]).mkdir(exist_ok=True)
  41. a = input
  42. # print(a)
  43. x = a['FileData']
  44. # print(x)
  45. y = a['FileName']
  46. #z = a['FileType']
  47. z='jpg'
  48. # CreatedBy=a['CreatedBy']
  49. name = y+ '.'+ z
  50. print(name)
  51. # print(y)
  52. # image = y.split("/")
  53. # filename=image[-1]
  54. # print(x)
  55. try:
  56. img_data = x.encode()
  57. except AttributeError:
  58. return "Successfully saved encoding........."
  59. import base64
  60. with open("ppeople/" + input["FileName"] + "/" + name, "wb") as fh:
  61. fh.write(base64.decodebytes(img_data))
  62. img = "ppeople/" + y + "/" + name
  63. saveLocation = "ppeople/" + y + "/" + y + ".pickle"
  64. ############ detecting no of faceses #######################
  65. # import cv2
  66. # import numpy as np
  67. # import dlib
  68. # # Connects to your computer's default camera
  69. # cap = cv2.imread(img)
  70. # # Detect the coordinates
  71. # detector = dlib.get_frontal_face_detector()
  72. # number_of_faces=[]
  73. # # Capture frames continuously
  74. # # while True:
  75. # # Capture frame-by-frame
  76. # # ret, frame = cap
  77. # frame = cap
  78. # # RGB to grayscale
  79. # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  80. # faces = detector(gray)
  81. # # Iterator to count faces
  82. # i = 0
  83. # for face in faces:
  84. # # Get the coordinates of faces
  85. # x, y = face.left(), face.top()
  86. # x1, y1 = face.right(), face.bottom()
  87. # cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
  88. # # Increment iterator for each face in faces
  89. # i = i+1
  90. # # Display the box and faces
  91. # cv2.putText(frame, 'face num'+str(i), (x-10, y-10),
  92. # cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  93. # # if len(i)>1:
  94. # # print(i)
  95. # number_of_faces.append(i)
  96. # if (len(number_of_faces))>1:
  97. # print("Group Photo")
  98. # return "Group Photo"
  99. # elif (len(number_of_faces))==1:
  100. # print("Single Photo")
  101. # pass
  102. def saveEncodings(encs, names, fname='encodings.pickle'):
  103. """
  104. Save encodings in a pickle file to be used in future.
  105. Parameters
  106. ----------
  107. encs : List of np arrays
  108. List of face encodings.
  109. names : List of strings
  110. List of names for each face encoding.
  111. fname : String, optional
  112. Name/Location for pickle file. The default is "encodings.pickle".
  113. Returns
  114. -------
  115. None.
  116. """
  117. data = []
  118. d = [{"name": nm, "encoding": enc} for (nm, enc) in zip(names, encs)]
  119. data.extend(d)
  120. encodingsFile = fname
  121. # dump the facial encodings data to disk
  122. print("[INFO] serializing encodings...")
  123. print("[INFO] Encodings Created sucessfully")
  124. f = open(encodingsFile, "wb")
  125. f.write(pickle.dumps(data))
  126. f.close()
  127. # Function to create encodings and get face locations
  128. def processKnownPeopleImages(img=img, saveLocation=saveLocation):
  129. """
  130. Process images of known people and create face encodings to compare in future.
  131. Eaach image should have just 1 face in it.
  132. Parameters
  133. ----------
  134. path : STRING, optional
  135. Path for known people dataset. The default is "C:/inetpub/vhosts/port82/wwwroot/_files/People".
  136. It should be noted that each image in this dataset should contain only 1 face.
  137. saveLocation : STRING, optional
  138. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  139. Returns
  140. -------
  141. None.
  142. """
  143. known_encodings = []
  144. known_names = []
  145. # for img in os.listdir(path):
  146. imgPath = img
  147. # Read image
  148. image = cv2.imread(imgPath)
  149. name = img.rsplit('.')[0]
  150. # Resize
  151. try:
  152. print(image.shape)
  153. except AttributeError:
  154. return "Successfully saved encoding........."
  155. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  156. # Get locations and encodings
  157. encs, locs = createEncodings(image)
  158. try:
  159. known_encodings.append(encs[0])
  160. except IndexError:
  161. os.remove(saveLocation)
  162. print('------------------------------------- save location --------------------------------')
  163. print(saveLocation)
  164. return "hello world!"
  165. # known_encodings.append(encs[0])
  166. known_names.append(name)
  167. for loc in locs:
  168. top, right, bottom, left = loc
  169. # Show Image
  170. # cv2.rectangle(image, (left, top), (right, bottom), color=(255, 0, 0), thickness=2)
  171. # cv2.imshow("Image", image)
  172. # cv2.waitKey(1)
  173. # cv2.destroyAllWindows()
  174. saveEncodings(known_encodings, known_names, saveLocation)
  175. import cv2
  176. #import face_recognition
  177. import pickle
  178. processKnownPeopleImages(img, saveLocation)
  179. return 'Successfully saved encoding.........'
  180. # ******************************** COMPARUISION *********************************************************
  181. #@app.route('/submit', methods=["POST","GET"])
  182. def submit(url_list):
  183. from datetime import datetime
  184. import pytz
  185. tz_NY = pytz.timezone('Asia/Kolkata')
  186. datetime_NY = datetime.now(tz_NY)
  187. India_Date = (datetime_NY.strftime("%Y-%m-%d"))
  188. India_Date = str(India_Date)
  189. # India_Time = (datetime_NY.strftime("%I:%M:%S %p"))
  190. # India_Time = str(India_Time)
  191. input=url_list
  192. import pickle
  193. import cv2
  194. from pathlib import Path
  195. Path("GGallery/"+ India_Date).mkdir(exist_ok=True)
  196. Path("GGallery/"+ India_Date +'/'+ input["FileName"]).mkdir(exist_ok=True)
  197. a = input
  198. # print(a)
  199. x = a['FileData']
  200. # print(x)
  201. y = a['FileName']
  202. # z = a['FileType']
  203. z='jpg'
  204. # CreatedBy=a['CreatedBy']
  205. name = y + '.' + z
  206. # print(name)
  207. # print(y)
  208. # image = y.split("/")
  209. # filename=image[-1]
  210. # print(x)
  211. img_data = x.encode()
  212. import base64
  213. with open("GGallery/"+India_Date+'/' + input["FileName"] + "/" + name, "wb") as fh:
  214. fh.write(base64.decodebytes(img_data))
  215. path = "GGallery/" +India_Date+'/'+ y + "/" + name
  216. pickle_location = "ppeople/" + y + "/" + y + ".pickle"
  217. import pathlib
  218. file = pathlib.Path(pickle_location)
  219. if file.exists ():
  220. pass
  221. else:
  222. print ("pickle File not exist")
  223. print(name)
  224. return "Face not found in profile (please change your profile)"
  225. check_faces="ppeople/" + y + "/" + y + ".jpg"
  226. print(check_faces)
  227. ############ detecting no of faceses #######################
  228. import cv2
  229. import numpy as np
  230. import dlib
  231. # Connects to your computer's default camera
  232. cap = cv2.imread(check_faces)
  233. # Detect the coordinates
  234. detector = dlib.get_frontal_face_detector()
  235. number_of_faces=[]
  236. # Capture frames continuously
  237. # while True:
  238. # Capture frame-by-frame
  239. # ret, frame = cap
  240. frame = cap
  241. # RGB to grayscale
  242. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  243. faces = detector(gray)
  244. # Iterator to count faces
  245. i = 0
  246. for face in faces:
  247. # Get the coordinates of faces
  248. x, y = face.left(), face.top()
  249. x1, y1 = face.right(), face.bottom()
  250. cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
  251. # Increment iterator for each face in faces
  252. i = i+1
  253. # Display the box and faces
  254. cv2.putText(frame, 'face num'+str(i), (x-10, y-10),
  255. cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
  256. # if len(i)>1:
  257. # print(i)
  258. number_of_faces.append(i)
  259. if (len(number_of_faces))>1:
  260. print("Group Photo")
  261. return "Group Photo"
  262. elif (len(number_of_faces))==1:
  263. print("Single Photo")
  264. pass
  265. def readEncodingsPickle(fname):
  266. """
  267. Read Pickle file.
  268. Parameters
  269. ----------
  270. fname : String
  271. Name of pickle file.(Full location)
  272. Returns
  273. -------
  274. encodings : list of np arrays
  275. list of all saved encodings
  276. names : List of Strings
  277. List of all saved names
  278. """
  279. data = pickle.loads(open(fname, "rb").read())
  280. data = np.array(data)
  281. encodings = [d["encoding"] for d in data]
  282. names = [d["name"] for d in data]
  283. return encodings, names
  284. def compareFaceEncodings(unknown_encoding, known_encodings, known_names):
  285. """
  286. Compares face encodings to check if 2 faces are same or not.
  287. Parameters
  288. ----------
  289. unknown_encoding : np array
  290. Face encoding of unknown people.
  291. known_encodings : np array
  292. Face encodings of known people.
  293. known_names : list of strings
  294. Names of known people
  295. Returns
  296. -------
  297. acceptBool : Bool
  298. face matched or not
  299. duplicateName : String
  300. Name of matched face
  301. distance : Float
  302. Distance between 2 faces
  303. """
  304. duplicateName = ""
  305. distance = 0.0
  306. matches = face_recognition.compare_faces(known_encodings, unknown_encoding, tolerance=0.51)
  307. face_distances = face_recognition.face_distance(known_encodings, unknown_encoding)
  308. best_match_index = np.argmin(face_distances)
  309. distance = face_distances[best_match_index]
  310. if matches[best_match_index]:
  311. acceptBool = True
  312. duplicateName = known_names[best_match_index]
  313. else:
  314. acceptBool = False
  315. duplicateName = ""
  316. return acceptBool, duplicateName, distance
  317. #p = []
  318. def processDatasetImages(path=path, pickle_location=pickle_location):
  319. """
  320. Process image in dataset from where you want to separate images.
  321. It separates the images into directories of known people, groups and any unknown people images.
  322. Parameters
  323. ----------
  324. path : STRING, optional
  325. Path for known people dataset. The default is "D:/port1004/port1004/wwwroot/_files/People".
  326. It should be noted that each image in this dataset should contain only 1 face.
  327. saveLocation : STRING, optional
  328. Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
  329. Returns
  330. -------
  331. None.
  332. """
  333. # Read pickle file for known people to compare faces from
  334. people_encodings, names = readEncodingsPickle(pickle_location)
  335. # print(p)
  336. # imgPath = path + img
  337. # Read image
  338. # path=r"C:\Users\katku\Pictures\final\100011460000611.jpg"
  339. image = cv2.imread(path)
  340. #orig = image.copy()
  341. # Resize
  342. image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
  343. # Get locations and encodings
  344. encs, locs = createEncodings(image)
  345. # Save image to a group image folder if more than one face is in image
  346. # if len(locs) > 1:
  347. # saveImageToDirectory(orig, "Group", img)
  348. # Processing image for each face
  349. i = 0
  350. knownFlag = 0
  351. for loc in locs:
  352. top, right, bottom, left = loc
  353. unknown_encoding = encs[i]
  354. i += 1
  355. acceptBool, duplicateName, distance = compareFaceEncodings(unknown_encoding, people_encodings, names)
  356. if acceptBool:
  357. # saveImageToDirectory(orig, duplicateName,name)
  358. knownFlag = 1
  359. if knownFlag == 1:
  360. print("Match Found")
  361. #print(path)
  362. with_extension = path.split("/")[-1]
  363. without_extension = with_extension.split(".")[0]
  364. # output_s = {"FileID": without_extension,
  365. # "Date": India_Date,
  366. # "Time": India_Time}
  367. # output_json = json.dumps(output_s)
  368. output_json='Matched successfully'
  369. print(loc)
  370. lst.append(output_json)
  371. print(output_json)
  372. # exit()
  373. else:
  374. print('Not Matched')
  375. pass
  376. # saveImageToDirectory(orig, "0",name)
  377. import numpy as np
  378. import json
  379. processDatasetImages(path, pickle_location)
  380. return lst[0]
  381. #return 'matched successfully'
  382. @app.route('/detect', methods=["POST"])
  383. def detect():
  384. if __name__ == "__main__":
  385. url_list=[]
  386. Dataset= request.get_json()
  387. # id = "100013660000125"
  388. url_list.append(Dataset)
  389. # multiprocessing
  390. pool_size = multiprocessing.cpu_count() * 2
  391. with multiprocessing.Pool(pool_size) as pool:
  392. try:
  393. results = pool.map(submit, url_list)
  394. except FileNotFoundError:
  395. return 'plese get registered with your PhotoID'
  396. except IndexError:
  397. #return 'unable to recognize face'
  398. return 'failed'
  399. pool.close()
  400. return results[0]
  401. @app.route('/register', methods=["POST"])
  402. def register():
  403. print("hello start..........")
  404. if __name__ == "__main__":
  405. url_list=[]
  406. Dataset= request.get_json()
  407. # id = "100013660000125"
  408. url_list.append(Dataset)
  409. UserLocation=Dataset["FilePath"]
  410. print(UserLocation)
  411. # if "cO2" in UserLocation or UserLocation is None:
  412. # pass
  413. # else:
  414. # return "Please update the URL in the integration"
  415. # multiprocessing
  416. pool_size = multiprocessing.cpu_count() * 2
  417. with multiprocessing.Pool(pool_size) as pool:
  418. try:
  419. results = pool.map(registered, url_list)
  420. except IndexError:
  421. pass
  422. print('face not found')
  423. except FileNotFoundError:
  424. pass
  425. #os.remove(img)
  426. # return 'unable to recognize face'
  427. pool.close()
  428. #return results[0]
  429. return 'Successfully saved encoding.........'
  430. if __name__ == "__main__":
  431. app.run(host='0.0.0.0',port =5003,debug=False)