Browse Source

Delete 'Attendence/attendence.py'

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

+ 0
- 561
Attendence/attendence.py View File

@@ -1,561 +0,0 @@
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 "Face not found in profile (please change your profile)"
282
-
283
-    check_faces=People+"/" + y + "/" + y + ".jpg"
284
-    print(check_faces)
285
-
286
-
287
-    ############ detecting no of faceses #######################
288
-
289
-
290
-    import cv2
291
-    import numpy as np
292
-    import dlib
293
-
294
-
295
-    # Connects to your computer's default camera
296
-    cap = cv2.imread(check_faces)
297
-
298
-    # Detect the coordinates
299
-    detector = dlib.get_frontal_face_detector()
300
-
301
-    number_of_faces=[]
302
-    # Capture frames continuously
303
-    # while True:
304
-
305
-    # Capture frame-by-frame
306
-    # ret, frame = cap
307
-    frame = cap
308
-
309
-    # RGB to grayscale
310
-    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
311
-    faces = detector(gray)
312
-
313
-    # Iterator to count faces
314
-    i = 0
315
-    for face in faces:
316
-
317
-        # Get the coordinates of faces
318
-        x, y = face.left(), face.top()
319
-        x1, y1 = face.right(), face.bottom()
320
-        cv2.rectangle(frame, (x, y), (x1, y1), (0, 255, 0), 2)
321
-    # Increment iterator for each face in faces
322
-        i = i+1
323
-
324
-    # Display the box and faces
325
-        cv2.putText(frame, 'face num'+str(i), (x-10, y-10),
326
-                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
327
-        
328
-        # if len(i)>1:
329
-        #     print(i)
330
-        number_of_faces.append(i)
331
-
332
-
333
-    if (len(number_of_faces))>1:
334
-        print("Group Photo")
335
-        return "Group Photo"
336
-    elif (len(number_of_faces))==1:
337
-        print("Single Photo")
338
-        pass
339
-
340
-
341
-
342
-
343
-    def readEncodingsPickle(fname):
344
-        """
345
-        Read Pickle file.
346
-
347
-        Parameters
348
-        ----------
349
-        fname : String
350
-            Name of pickle file.(Full location)
351
-
352
-        Returns
353
-        -------
354
-        encodings : list of np arrays
355
-            list of all saved encodings
356
-        names : List of Strings
357
-            List of all saved names
358
-
359
-        """
360
-
361
-
362
-        data = pickle.loads(open(fname, "rb").read())
363
-
364
-
365
-        data = np.array(data)
366
-        encodings = [d["encoding"] for d in data]
367
-        names = [d["name"] for d in data]
368
-        return encodings, names
369
-
370
-
371
-    def compareFaceEncodings(unknown_encoding, known_encodings, known_names):
372
-        """
373
-        Compares face encodings to check if 2 faces are same or not.
374
-
375
-        Parameters
376
-        ----------
377
-        unknown_encoding : np array
378
-            Face encoding of unknown people.
379
-        known_encodings : np array
380
-            Face encodings of known people.
381
-        known_names : list of strings
382
-            Names of known people
383
-
384
-        Returns
385
-        -------
386
-        acceptBool : Bool
387
-            face matched or not
388
-        duplicateName : String
389
-            Name of matched face
390
-        distance : Float
391
-            Distance between 2 faces
392
-
393
-        """
394
-        duplicateName = ""
395
-        distance = 0.0
396
-        matches = face_recognition.compare_faces(known_encodings, unknown_encoding, tolerance=0.54)
397
-        face_distances = face_recognition.face_distance(known_encodings, unknown_encoding)
398
-
399
-        best_match_index = np.argmin(face_distances)
400
-
401
-        distance = face_distances[best_match_index]
402
-        if matches[best_match_index]:
403
-            acceptBool = True
404
-            duplicateName = known_names[best_match_index]
405
-        else:
406
-            acceptBool = False
407
-            duplicateName = ""
408
-        return acceptBool, duplicateName, distance
409
-
410
-        #p = []
411
-
412
-
413
-    def processDatasetImages(path=path, pickle_location=pickle_location):
414
-        """
415
-        Process image in dataset from where you want to separate images.
416
-        It separates the images into directories of known people, groups and any unknown people images.
417
-        Parameters
418
-        ----------
419
-        path : STRING, optional
420
-            Path for known people dataset. The default is "D:/port1004/port1004/wwwroot/_files/People".
421
-            It should be noted that each image in this dataset should contain only 1 face.
422
-        saveLocation : STRING, optional
423
-            Path for storing encodings for known people dataset. The default is "./known_encodings.pickle in current directory".
424
-
425
-        Returns
426
-        -------
427
-        None.
428
-
429
-        """
430
-        # Read pickle file for known people to compare faces from
431
-
432
-        people_encodings, names = readEncodingsPickle(pickle_location)
433
-        # print(p)
434
-        #  imgPath = path + img
435
-
436
-        # Read image
437
-        # path=r"C:\Users\katku\Pictures\final\100011460000611.jpg"
438
-        image = cv2.imread(path)
439
-        #orig = image.copy()
440
-
441
-        # Resize
442
-        image = cv2.resize(image, (0, 0), fx=0.9, fy=0.9, interpolation=cv2.INTER_LINEAR)
443
-
444
-        # Get locations and encodings
445
-        encs, locs = createEncodings(image)
446
-
447
-        # Save image to a group image folder if more than one face is in image
448
-        # if len(locs) > 1:
449
-        #     saveImageToDirectory(orig, "Group", img)
450
-
451
-        # Processing image for each face
452
-        i = 0
453
-        knownFlag = 0
454
-        for loc in locs:
455
-            top, right, bottom, left = loc
456
-            unknown_encoding = encs[i]
457
-            i += 1
458
-            acceptBool, duplicateName, distance = compareFaceEncodings(unknown_encoding, people_encodings, names)
459
-            if acceptBool:
460
-                # saveImageToDirectory(orig, duplicateName,name)
461
-                knownFlag = 1
462
-        if knownFlag == 1:
463
-            print("Match Found")
464
-
465
-
466
-            #print(path)
467
-            with_extension = path.split("/")[-1]
468
-            without_extension = with_extension.split(".")[0]
469
-
470
-            # output_s = {"FileID": without_extension,
471
-            #             "Date": India_Date,
472
-            #             "Time": India_Time}
473
-            # output_json = json.dumps(output_s)
474
-            output_json='Matched successfully'
475
-            print(loc)
476
-            lst.append(output_json)
477
-
478
-            print(output_json)
479
-            # exit()
480
-
481
-        else:
482
-            print('Not Matched')
483
-            pass
484
-            # saveImageToDirectory(orig, "0",name)
485
-
486
-
487
-    import numpy as np
488
-    import json
489
-
490
-    processDatasetImages(path, pickle_location)
491
-    return lst[0]
492
-    #return 'matched successfully'
493
-
494
-
495
-@app.route('/detect', methods=["POST"])
496
-def detect():
497
-    if __name__ == "__main__":
498
-
499
-        url_list=[]
500
-        Dataset=  request.get_json()
501
-        # id = "100013660000125"
502
-        url_list.append(Dataset)
503
-        # multiprocessing
504
-        pool_size = multiprocessing.cpu_count() * 2
505
-        with multiprocessing.Pool(pool_size) as pool:
506
-            try:
507
-                results = pool.map(submit, url_list)
508
-            except FileNotFoundError:
509
-                return 'plese get registered with your PhotoID'
510
-            except IndexError:
511
-                #return 'unable to recognize face'
512
-                return 'failed'
513
-
514
-        pool.close()
515
-
516
-        return results[0]
517
-
518
-
519
-
520
-@app.route('/register', methods=["POST"])
521
-def register():
522
-    print("hello start..........")
523
-    if __name__ == "__main__":
524
-
525
-        url_list=[]
526
-        Dataset=  request.get_json()
527
-        # id = "100013660000125"
528
-        url_list.append(Dataset)
529
-        UserLocation=Dataset["FilePath"]
530
-        print(UserLocation)
531
-
532
-        # if "cO2" in UserLocation or UserLocation is None:
533
-        #     pass
534
-        # else:
535
-        #     return "Please update the URL in the integration"
536
-
537
-
538
-        # multiprocessing
539
-        pool_size = multiprocessing.cpu_count() * 2
540
-        with multiprocessing.Pool(pool_size) as pool:
541
-            try:
542
-                results = pool.map(registered, url_list)
543
-            except IndexError:
544
-                pass
545
-                print('face not found')
546
-            except FileNotFoundError:
547
-                pass
548
-                
549
-            
550
-                #os.remove(img)
551
-               # return 'unable to recognize face'
552
-
553
-        pool.close()
554
-        #return results[0]
555
-        return 'Successfully saved encoding.........'
556
-
557
-
558
-
559
-
560
-if __name__ == "__main__":
561
-    app.run(host='0.0.0.0',port =5003,debug=False)

Loading…
Cancel
Save