Brak opisu
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.

test_attendence.py 15KB

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