Przeglądaj źródła

Delete 'attendence.py'

SadhulaSaiKumar 2 lat temu
rodzic
commit
c84610b460
1 zmienionych plików z 0 dodań i 547 usunięć
  1. 0
    547
      attendence.py

+ 0
- 547
attendence.py Wyświetl plik

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

Ładowanie…
Anuluj
Zapisz