File size: 28,914 Bytes
2acde75
 
 
 
8e4d957
 
a94357a
2acde75
bba2e95
 
4e1b760
 
8e4d957
d3f5a3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e4d957
bba2e95
8e4d957
 
 
 
94517a5
8e4d957
 
 
 
 
 
 
 
 
578f6c4
8e4d957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
578f6c4
8e4d957
 
 
 
 
 
 
 
d3f5a3e
 
 
 
94517a5
 
 
 
 
d3f5a3e
94517a5
 
 
d3f5a3e
94517a5
 
 
 
d3f5a3e
94517a5
d3f5a3e
94517a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c37a
94517a5
e14c37a
94517a5
 
 
 
 
 
 
 
 
 
 
e14c37a
94517a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c37a
94517a5
e14c37a
 
94517a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e14c37a
94517a5
 
e14c37a
94517a5
 
 
 
 
 
 
e14c37a
94517a5
e14c37a
 
 
 
94517a5
 
 
 
 
 
e14c37a
 
 
 
 
 
 
 
 
 
8f516cc
 
 
 
 
 
 
e14c37a
94517a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3f5a3e
 
e14c37a
94517a5
 
 
 
 
 
 
e14c37a
94517a5
 
 
 
 
abd0699
d3f5a3e
2acde75
 
8e4d957
d3f5a3e
2acde75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3f5a3e
 
 
2acde75
 
 
d3f5a3e
 
 
7ba9b3a
d3f5a3e
 
7ba9b3a
d3f5a3e
 
8e4d957
 
 
 
 
d76c9ff
8e4d957
 
 
 
 
 
 
 
 
d772244
8e4d957
 
2acde75
8e4d957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25d0fe8
 
8e4d957
 
 
 
 
25d0fe8
8e4d957
 
25d0fe8
8e4d957
 
697d223
2acde75
8e4d957
d3f5a3e
8e4d957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3f5a3e
8e4d957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3f5a3e
8e4d957
 
 
 
 
d3f5a3e
8e4d957
 
d3f5a3e
8e4d957
e14c37a
8e4d957
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
import os
import gradio as gr
import requests
import json
import cv2
import numpy as np
import time
from PIL import Image
from fr.engine.header import *
from fl.engine.header import *
import fr.engine.header as fr_header
import fl.engine.header as fl_header

css = """
.example-image img{
    display: flex; /* Use flexbox to align items */
    justify-content: center; /* Center the image horizontally */
    align-items: center; /* Center the image vertically */
    height: 300px; /* Set the height of the container */
    object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
}

.example-image{
    display: flex; /* Use flexbox to align items */
    justify-content: center; /* Center the image horizontally */
    align-items: center; /* Center the image vertically */
    height: 350px; /* Set the height of the container */
    object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
}

.face-row {
    display: flex;
    justify-content: space-around; /* Distribute space evenly between elements */
    align-items: center; /* Align items vertically */
    width: 100%; /* Set the width of the row to 100% */
}

.face-image{
    justify-content: center; /* Center the image horizontally */
    align-items: center; /* Center the image vertically */
    height: 160px; /* Set the height of the container */
    width: 160px;
    object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
}

.face-image img{
    justify-content: center; /* Center the image horizontally */
    align-items: center; /* Center the image vertically */
    height: 160px; /* Set the height of the container */
    object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
}

.markdown-success-container {
    background-color: #F6FFED;
    padding: 20px;
    margin: 20px;
    border-radius: 1px;
    border: 2px solid green;
    text-align: center;
}

.markdown-fail-container {
    background-color: #FFF1F0;
    padding: 20px;
    margin: 20px;
    border-radius: 1px;
    border: 2px solid red;
    text-align: center;
}

.markdown-attribute-container {
    display: flex;
    justify-content: space-around; /* Distribute space evenly between elements */
    align-items: center; /* Align items vertically */
    padding: 10px;
    margin: 10px;
}

.block-background {
    # background-color: #202020; /* Set your desired background color */
    border-radius: 5px;
}

"""

file_path = os.path.abspath(__file__)
root_path = os.path.dirname(file_path)

g_fr_activation_result = -1
g_fl_activation_result = -1
MATCH_THRESHOLD = 0.67
SPOOF_THRESHOLD = 0.5

def activate_fr_sdk():
    fr_key = os.environ.get("FR_LICENSE_KEY")
    fr_dict_path = os.path.join(root_path, "fr/engine/bin")

    ret = -1
    if fr_key is None:
        print_warning("Recognition online license key not found!")
    else:
        ret = fr_header.init_sdk(fr_dict_path.encode('utf-8'), fr_key.encode('utf-8'))

    if ret == 0:
        print_log("Successfully init FR SDK!")
    else:
        print_error(f"Falied to init FR SDK, Error code {ret}")

    return ret

def activate_fl_sdk():
    fl_key = os.environ.get("FL_LICENSE_KEY")
    fl_dict_path = os.path.join(root_path, "fl/engine/bin")

    ret = -1
    if fl_key is None:
        print_warning("Liveness Detection online license key not found!")
    else:
        ret = fl_header.init_sdk(fl_dict_path.encode('utf-8'), fl_key.encode('utf-8'))

    if ret == 0:
        print_log("Successfully init FL SDK!")
    else:
        print_error(f"Falied to init FL SDK, Error code {ret}")
        
    return ret
    
def convert_fun(input_str):
    # Remove line breaks and extra whitespaces
    return ' '.join(input_str.split())

# def get_attributes(frame):    
#     url = "https://recognito.p.rapidapi.com/api/analyze_face"
#     try:
#         files = {'image': open(frame, 'rb')}
#         headers = {"X-RapidAPI-Key": os.environ.get("API_KEY")}

#         r = requests.post(url=url, files=files, headers=headers)
#     except:
#         raise gr.Error("Please select images file!")

#     faces = None
#     face_crop, one_line_attribute = None, ""
#     try:
#         image = Image.open(frame)

#         face = Image.new('RGBA',(150, 150), (80,80,80,0))
        
#         res = r.json().get('image')
#         if res is not None and res:
#             face = res.get('detection')
#             x1 = face.get('x')
#             y1 = face.get('y')
#             x2 = x1 + face.get('w')
#             y2 = y1 + face.get('h')

#             if x1 < 0:
#                 x1 = 0
#             if y1 < 0:
#                 y1 = 0
#             if x2 >= image.width:
#                 x2 = image.width - 1
#             if y2 >= image.height:
#                 y2 = image.height - 1

#             face_crop = image.crop((x1, y1, x2, y2))
#             face_image_ratio = face_crop.width / float(face_crop.height)
#             resized_w = int(face_image_ratio * 150)
#             resized_h = 150

#             face_crop = face_crop.resize((int(resized_w), int(resized_h)))
            
#             attr = res.get('attribute')
            
#             age = attr.get('age')
#             gender = attr.get('gender')
#             emotion = attr.get('emotion')
#             ethnicity = attr.get('ethnicity')

#             mask = attr.get('face_mask')
#             glass = 'No Glasses'
#             if attr.get('glasses') == 'USUAL':
#                 glass = 'Glasses'
#             if attr.get('glasses') == 'DARK':
#                 glass = 'Sunglasses'
            
#             open_eye_thr = 0.3
#             left_eye = 'Close'
#             if attr.get('eye_left') >= open_eye_thr:
#                 left_eye = 'Open'

#             right_eye = 'Close'
#             if attr.get('eye_right') >= open_eye_thr:
#                 right_eye = 'Open'

#             facehair = attr.get('facial_hair')
#             haircolor = attr.get('hair_color')
#             hairtype = attr.get('hair_type')
#             headwear = attr.get('headwear')

#             pitch = attr.get('pitch')
#             roll = attr.get('roll')
#             yaw = attr.get('yaw')
#             quality = attr.get('quality')

#             attribute = f"""
#             <br/>
#             <div class="markdown-attribute-container">
#             <table>
#             <tr>
#                 <th style="text-align: center;">Attribute</th>
#                 <th style="text-align: center;">Result</th>
#                 <th style="text-align: center;">Score</th>
#                 <th style="text-align: center;">Threshold</th>
#             </tr>
#             <tr>
#                 <td>Gender</td>
#                 <td>{gender}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Age</td>
#                 <td>{int(age)}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Pitch</td>
#                 <td>{"{:.4f}".format(pitch)}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Yaw</td>
#                 <td>{"{:.4f}".format(yaw)}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Roll</td>
#                 <td>{"{:.4f}".format(roll)}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Emotion</td>
#                 <td>{emotion}</td>
#                 <td></td><td></td>
#             </tr>
#                 <tr>
#                 <td>Left Eye</td>
#                 <td>{left_eye}</td>
#                 <td>{"{:.4f}".format(attr.get('eye_left'))}</td>
#                 <td>{open_eye_thr}</td>
#             </tr>
#             <tr>
#                 <td>Right Eye</td>
#                 <td>{right_eye}</td>
#                 <td>{"{:.4f}".format(attr.get('eye_right'))}</td>
#                 <td>{open_eye_thr}</td>
#             </tr>
#             <tr>
#                 <td>Mask</td>
#                 <td>{mask}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Glass</td>
#                 <td>{glass}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>FaceHair</td>
#                 <td>{facehair}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>HairColor</td>
#                 <td>{haircolor}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>HairType</td>
#                 <td>{hairtype}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>HeadWear</td>
#                 <td>{headwear}</td>
#                 <td></td><td></td>
#             </tr>
#             <tr>
#                 <td>Image Quality</td>
#                 <td>{"{:.4f}".format(quality)}</td>
#                 <td></td><td></td>
#             </tr>
#             </table>
#             </div>
#             """
#             one_line_attribute = convert_fun(attribute)
#     except:
#         pass
    
#     return face_crop, one_line_attribute

def check_liveness(frame):
    # url = "https://recognito-faceliveness.p.rapidapi.com/api/check_liveness"
    # try:
    #     files = {'image': open(frame, 'rb')}
    #     headers = {"X-RapidAPI-Key": os.environ.get("API_KEY")}

    #     r = requests.post(url=url, files=files, headers=headers)
    # except:
    #     raise gr.Error("Please select images file!")

    # faces = None

    # face_crop, liveness_result, liveness_score = None, "", -200
    # try:
    #     image = Image.open(frame)

    #     face = Image.new('RGBA',(150, 150), (80,80,80,0))
    #     res = r.json().get('data')
    #     if res is not None and res:
    #         face = res.get('face_rect')
    #         x1 = face.get('x')
    #         y1 = face.get('y')
    #         x2 = x1 + face.get('w')
    #         y2 = y1 + face.get('h')

    #         if x1 < 0:
    #             x1 = 0
    #         if y1 < 0:
    #             y1 = 0
    #         if x2 >= image.width:
    #             x2 = image.width - 1
    #         if y2 >= image.height:
    #             y2 = image.height - 1

    #         face_crop = image.crop((x1, y1, x2, y2))
    #         face_image_ratio = face_crop.width / float(face_crop.height)
    #         resized_w = int(face_image_ratio * 150)
    #         resized_h = 150

    #         face_crop = face_crop.resize((int(resized_w), int(resized_h)))
    #         liveness_score = res.get('liveness_score')
    #         liveness = res.get('result')

    #         if liveness == 'REAL':
    #             liveness_result = f"""<br/><div class="markdown-success-container"><p style="text-align: center; font-size: 20px; color: green;">Liveness Check:  REAL<br/>Score: {liveness_score}</p></div>"""
    #         else:
    #             liveness_result = f"""<br/><div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check:  {liveness}<br/>Score: {liveness_score}</p></div>"""

    # except:
    #     pass
    
    # return face_crop, liveness_result, liveness_score
    
    global g_fl_activation_result
    if g_fl_activation_result != 0:
        gr.Warning("FL SDK Activation Failed!")
        return None, None, None

    try:
        image = open(frame, 'rb')
    except:
        raise gr.Error("Please select image file!")
    
    image_mat = cv2.imdecode(np.frombuffer(image.read(), np.uint8), cv2.IMREAD_COLOR)
    start_time = time.time()
    result, face_rect, score, angles = fl_header.check_liveness(image_mat, SPOOF_THRESHOLD)
    end_time = time.time()
    process_time = (end_time - start_time) * 1000

    face_crop, one_line_attribute = None, ""
    try:
        image = Image.open(frame)

        face = Image.new('RGBA',(150, 150), (80,80,80,0))
        
        if face_rect is not None:
            x1 = int(face_rect[0])
            y1 = int(face_rect[1])
            x2 = int(face_rect[2])
            y2 = int(face_rect[3])

            if x1 < 0:
                x1 = 0
            if y1 < 0:
                y1 = 0
            if x2 >= image.width:
                x2 = image.width - 1
            if y2 >= image.height:
                y2 = image.height - 1

            if (x2 - x1) != 0 and (y2 - y1) != 0:    
                face_crop = image.crop((x1, y1, x2, y2))
                face_image_ratio = face_crop.width / float(face_crop.height)
                resized_w = int(face_image_ratio * 150)
                resized_h = 150
    
                face_crop = face_crop.resize((int(resized_w), int(resized_h)))

        if angles is not None:
            yaw = angles[0]
            roll = angles[1]
            pitch = angles[2]

        attribute = f"""
        <br/>
        <div class="markdown-attribute-container">
        <table>
        <tr>
            <th>Field</th>
            <th colspan="2">Value</th>
        </tr>
        <tr>
            <th rowspan="4">Face Rect</th>
            <td>x</td>
            <td>{x1}</td>
        </tr>
        <tr>
            <td>y</td>
            <td>{y1}</td>
        </tr>
        <tr>
            <td>width</td>
            <td>{x2 - x1 + 1}</td>
        </tr>
        <tr>
            <td>height</td>
            <td>{y2 - y1 + 1}</td>
        </tr>
        <tr>
            <th rowspan="3">Face Angle</th>
            <td>Pitch</td>
            <td>{"{:.4f}".format(pitch)}</td>
        </tr>
        <tr>
            <td>Yaw</td>
            <td>{"{:.4f}".format(yaw)}</td>
        </tr>
        <tr>
            <td>Roll</td>
            <td>{"{:.4f}".format(roll)}</td>
        </tr>
        </table>
        </div>
        """
        
        one_line_attribute = convert_fun(attribute)
    except:
        pass

    str_score = str("{:.4f}".format(score))
    if result == "REAL":
        liveness_result = f"""<br/><div class="markdown-success-container"><p style="text-align: center; font-size: 20px; color: green;">Liveness Check:  REAL<br/>Score: {str_score}</p></div>"""        
    else:
        liveness_result = f"""<br/><div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check:  {result}<br/>Score: {str_score}</p></div>"""  
        
    return face_crop, liveness_result, one_line_attribute

def analyze_face(frame):
    # face_crop_1, liveness_result, liveness_score = check_liveness(frame)
    # face_crop_2, attribute = get_attributes(frame)
    # face_crop = face_crop_1 if (face_crop_1 is not None) else face_crop_2
    face_crop, liveness_result, attribute = check_liveness(frame)
    return [face_crop, liveness_result, attribute]


def compare_face(frame1, frame2):
    """
    url = "https://recognito.p.rapidapi.com/api/compare_face"
    try:
        files = {'image1': open(frame1, 'rb'), 'image2': open(frame2, 'rb')}
        headers = {"X-RapidAPI-Key": os.environ.get("API_KEY")}

        r = requests.post(url=url, files=files, headers=headers)
    except:
        raise gr.Error("Please select images files!")

    faces = None

    try:
        image1 = Image.open(frame1)
        image2 = Image.open(frame2)

        face1 = Image.new('RGBA',(150, 150), (80,80,80,0))
        face2 = Image.new('RGBA',(150, 150), (80,80,80,0))

        res1 = r.json().get('image1')
        
        if res1 is not None and res1:
            face = res1.get('detection')
            x1 = face.get('x')
            y1 = face.get('y')
            x2 = x1 + face.get('w')
            y2 = y1 + face.get('h')
            if x1 < 0:
                x1 = 0
            if y1 < 0:
                y1 = 0
            if x2 >= image1.width:
                x2 = image1.width - 1
            if y2 >= image1.height:
                y2 = image1.height - 1

            face1 = image1.crop((x1, y1, x2, y2))
            face_image_ratio = face1.width / float(face1.height)
            resized_w = int(face_image_ratio * 150)
            resized_h = 150

            face1 = face1.resize((int(resized_w), int(resized_h)))

        res2 = r.json().get('image2')
        if res2 is not None and res2:
            face = res2.get('detection')
            x1 = face.get('x')
            y1 = face.get('y')
            x2 = x1 + face.get('w')
            y2 = y1 + face.get('h')

            if x1 < 0:
                x1 = 0
            if y1 < 0:
                y1 = 0
            if x2 >= image2.width:
                x2 = image2.width - 1
            if y2 >= image2.height:
                y2 = image2.height - 1

            face2 = image2.crop((x1, y1, x2, y2))
            face_image_ratio = face2.width / float(face2.height)
            resized_w = int(face_image_ratio * 150)
            resized_h = 150

            face2 = face2.resize((int(resized_w), int(resized_h)))
    except:
        pass
        
    matching_result = Image.open("icons/blank.png")
    similarity_score = ""
    if face1 is not None and face2 is not None:
        matching_score = r.json().get('matching_score')
        if matching_score is not None:
            str_score = str("{:.4f}".format(matching_score))
            if matching_score >= 0.7:
                matching_result = Image.open("icons/same.png")
                similarity_score = 
            else:
                matching_result = Image.open("icons/different.png")
                similarity_score = 
    
    return [face1, face2, matching_result, similarity_score]
    """
    global g_fr_activation_result
    if g_fr_activation_result != 0:
        gr.Warning("FR SDK Activation Failed!")
        return None, None, None, None
        
    try:
        image1 = open(frame1, 'rb')
        image2 = open(frame2, 'rb')
    except:
        raise gr.Error("Please select images files!")

    image_mat1 = cv2.imdecode(np.frombuffer(image1.read(), np.uint8), cv2.IMREAD_COLOR)
    image_mat2 = cv2.imdecode(np.frombuffer(image2.read(), np.uint8), cv2.IMREAD_COLOR)
    start_time = time.time()
    result, score, face_bboxes, face_features = fr_header.compare_face(image_mat1, image_mat2, MATCH_THRESHOLD)
    end_time = time.time()
    process_time = (end_time - start_time) * 1000

    try:
        image1 = Image.open(frame1)
        image2 = Image.open(frame2)
        images = [image1, image2]

        face1 = Image.new('RGBA',(150, 150), (80,80,80,0))
        face2 = Image.new('RGBA',(150, 150), (80,80,80,0))
        faces = [face1, face2]

        face_bboxes_result = []
        if face_bboxes is not None:
            for i, bbox in enumerate(face_bboxes):
                x1 = bbox[0]
                y1 = bbox[1]
                x2 = bbox[2]
                y2 = bbox[3]
                if x1 < 0:
                    x1 = 0
                if y1 < 0:
                    y1 = 0
                if x2 >= images[i].width:
                    x2 = images[i].width - 1
                if y2 >= images[i].height:
                    y2 = images[i].height - 1

                face_bbox_str = f"x1: {x1}, y1: {y1}, x2: {x2}, y2: {y2}"
                face_bboxes_result.append(face_bbox_str)

                faces[i] = images[i].crop((x1, y1, x2, y2))
                face_image_ratio = faces[i].width / float(faces[i].height)
                resized_w = int(face_image_ratio * 150)
                resized_h = 150

                faces[i] = faces[i].resize((int(resized_w), int(resized_h)))
    except:
        pass

    matching_result = Image.open("icons/blank.png")
    similarity_score = ""
    if faces[0] is not None and faces[1] is not None:
        if score is not None:
            str_score = str("{:.4f}".format(score))
            if result == "SAME PERSON":
                matching_result = Image.open("icons/same.png")
                similarity_score = f"""<br/><div class="markdown-success-container"><p style="text-align: center; font-size: 20px; color: green;">Similarity score: {str_score}</p></div>"""
            else:
                matching_result = Image.open("icons/different.png")
                similarity_score = f"""<br/><div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Similarity score: {str_score}</p></div>"""
    
    return faces[0], faces[1], matching_result, similarity_score

        

def launch_demo(activate_fr_result, activate_fl_result):
    with gr.Blocks(css=css) as demo:
        gr.Markdown(
            """
            <a href="https://recognito.vision" style="display: flex; align-items: center;">
                <img src="https://recognito.vision/wp-content/uploads/2024/03/Recognito-modified.png" style="width: 8%; margin-right: 15px;"/>
                <div>
                    <p style="font-size: 32px; font-weight: bold; margin: 0;">Recognito</p>
                    <p style="font-size: 18px; margin: 0;">www.recognito.vision</p>
                </div>
            </a>
    
            <p style="font-size: 20px; font-weight: bold;">✨ NIST FRVT Top #1 Face Recognition Algorithm Developer</p>
            <div style="display: flex; align-items: center;">
                &emsp;&emsp;<a href="https://pages.nist.gov/frvt/html/frvt11.html"> <p style="font-size: 14px;">πŸ‘‰πŸ» Latest NIST FRVT Report</p></a>
            </div>
            <p style="font-size: 20px; font-weight: bold;">πŸ“˜ Product Documentation</p>
            <div style="display: flex; align-items: center;">          
                &emsp;&emsp;<a href="https://docs.recognito.vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/05/book.png" style="width: 48px; margin-right: 5px;"/></a>
            </div>
            <p style="font-size: 20px; font-weight: bold;">🏠 Visit Recognito</p>
            <div style="display: flex; align-items: center;">
                &emsp;&emsp;<a href="https://recognito.vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/recognito_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://www.linkedin.com/company/recognito-vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/linkedin_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://huggingface.co/recognito" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/hf_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/recognito-vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/github_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://hub.docker.com/u/recognito" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/docker_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://www.youtube.com/@recognito-vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/04/youtube_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
            </div>
            <p style="font-size: 20px; font-weight: bold;">🀝 Contact us for our on-premise Face Recognition, Liveness Detection SDKs deployment</p>
            <div style="display: flex; align-items: center;">
                &emsp;&emsp;<a target="_blank" href="mailto:[email protected]"><img src="https://img.shields.io/badge/[email protected]?logo=gmail " alt="www.recognito.vision"></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a target="_blank" href="https://wa.me/+14158003112"><img src="https://img.shields.io/badge/whatsapp-+14158003112-blue.svg?logo=whatsapp " alt="www.recognito.vision"></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a target="_blank" href="https://t.me/recognito_vision"><img src="https://img.shields.io/badge/telegram-@recognito__vision-blue.svg?logo=telegram " alt="www.recognito.vision"></a>
                &nbsp;&nbsp;&nbsp;&nbsp;<a target="_blank" href="https://join.slack.com/t/recognito-workspace/shared_invite/zt-2d4kscqgn-"><img src="https://img.shields.io/badge/slack-recognito__workspace-blue.svg?logo=slack " alt="www.recognito.vision"></a>
            </div>
            <br/><br/><br/>
            """
        )
        
        with gr.Tabs():
            with gr.Tab("Face Recognition"):
                with gr.Row():
                    with gr.Column(scale=2):
                        with gr.Row():
                            with gr.Column(scale=1):
                                compare_face_input1 = gr.Image(label="Image1", type='filepath', elem_classes="example-image")
                                gr.Examples(['examples/1.jpg', 'examples/2.jpg', 'examples/3.jpg', 'examples/4.jpg'], 
                                            inputs=compare_face_input1)
                            with gr.Column(scale=1):
                                compare_face_input2 = gr.Image(label="Image2", type='filepath', elem_classes="example-image")
                                gr.Examples(['examples/5.jpg', 'examples/6.jpg', 'examples/7.jpg', 'examples/8.jpg'], 
                                            inputs=compare_face_input2)
                                
                    with gr.Blocks():
                        with gr.Column(scale=1, min_width=400, elem_classes="block-background"):     
                            compare_face_button = gr.Button("Compare Face", variant="primary", size="lg")
                            with gr.Row(elem_classes="face-row"):
                                face_output1 = gr.Image(value="icons/face.jpg", label="Face 1", scale=0, elem_classes="face-image", show_share_button=False, show_download_button=False, show_fullscreen_button=False)
                                compare_result = gr.Image(value="icons/blank.png", min_width=30, scale=0, show_download_button=False, show_label=False, show_share_button=False, show_fullscreen_button=False)
                                face_output2 = gr.Image(value="icons/face.jpg", label="Face 2", scale=0, elem_classes="face-image", show_share_button=False, show_download_button=False, show_fullscreen_button=False)
                            similarity_markdown = gr.Markdown("")
    
                            compare_face_button.click(compare_face, inputs=[compare_face_input1, compare_face_input2], outputs=[face_output1, face_output2, compare_result, similarity_markdown])
                    
            with gr.Tab("Face Liveness, Analysis"):
                with gr.Row():
                    with gr.Column(scale=1):
                        face_input = gr.Image(label="Image", type='filepath', elem_classes="example-image")
                        gr.Examples(['examples/att_1.jpg', 'examples/att_2.jpg', 'examples/att_3.jpg', 'examples/att_4.jpg', 'examples/att_5.jpg', 'examples/att_6.jpg', 'examples/att_7.jpg'], 
                                    inputs=face_input)
    
                    with gr.Blocks():
                        with gr.Column(scale=1, elem_classes="block-background"):     
                            analyze_face_button = gr.Button("Analyze Face", variant="primary", size="lg")
                            with gr.Row(elem_classes="face-row"):
                                face_output = gr.Image(value="icons/face.jpg", label="Face", scale=0, elem_classes="face-image", show_share_button=False, show_download_button=False, show_fullscreen_button=False)
                            
                            liveness_result = gr.Markdown("")
                            attribute_result = gr.Markdown("")
                        
                        analyze_face_button.click(analyze_face, inputs=face_input, outputs=[face_output, liveness_result, attribute_result])
    
        gr.HTML('<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FRecognito%2FFaceRecognition-LivenessDetection-FaceAnalysis"><img src="https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FRecognito%2FFaceRecognition-LivenessDetection-FaceAnalysis&countColor=%2337d67a&style=flat&labelStyle=upper" /></a>')
        
    demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)

if __name__ == '__main__':
    g_fr_activation_result = activate_fr_sdk()
    g_fl_activation_result = activate_fl_sdk()
    launch_demo(g_fr_activation_result, g_fl_activation_result)