Browse Source

Upload files to 'Attendence'

SadhulaSaiKumar 1 year ago
parent
commit
a75b588e61
1 changed files with 564 additions and 0 deletions
  1. 564
    0
      Attendence/attendence.py

+ 564
- 0
Attendence/attendence.py View File

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

Loading…
Cancel
Save