File size: 12,496 Bytes
2fae413
 
 
 
 
 
 
 
 
 
 
b1fabaf
 
 
2fae413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15820
 
 
 
 
 
 
 
 
 
 
 
 
 
3e70fb3
 
 
 
9e15820
 
2fae413
9e15820
 
2fae413
 
 
 
 
 
 
 
3e70fb3
 
2fae413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15820
 
3e70fb3
 
9e15820
 
3e70fb3
9e15820
3e70fb3
9e15820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e70fb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e15820
 
 
 
 
 
 
 
 
 
 
 
 
 
e7a54c0
 
 
9e15820
 
 
 
 
 
 
 
 
 
 
 
2fae413
9e15820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fae413
 
3e70fb3
2fae413
9e15820
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
import os
import requests
import gradio as gr

HTML_HEADER = """
<header style="text-align: center; padding: 20px; border-bottom: 2px solid #cc3300;">
    <h1>Demo of Face Liveness Detection</h1>
    <p style="font-size: 18px;">
        To learn more, visit our website: <a href="https://dataspike.io/" target="_blank" style="font-size: 20px; text-decoration: none;">
        https://dataspike.io/ </a>
    </p>
    <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2Fdataspike%2FFace-Liveness-Detection&countColor=%23263759" 
         alt="Visitor Count" 
         style="display: none;">
</header>
"""

HTML_IQA_FAILED = """
<h3 style="color: #cc3300;">Liveness Checks Not Performed</h3>
<p>
        The liveness checks could not be conducted because the quality of the submitted image is not acceptable. 
        Please ensure that your selfie meets the following criteria for optimal quality:
    </p>
    <ul>
        <li>The face should be clearly visible and not obscured.</li>
        <li>The lighting should be adequate, avoiding extreme shadows or bright spots.</li>
        <li>The image should be in focus, without any blurriness.</li>
        <li>Avoid using filters or effects that alter the appearance of your face.</li>
    </ul>
    <p>
        Please re-upload a clearer selfie to proceed with the liveness verification.
    </p>
"""

HTML_HEAD_POSITION_FAILED = """
<h4 style="color: #cc3300;">Liveness Checks Not Performed</h4>
<p>
    The liveness checks could not be conducted because the position of the head in the submitted image does not meet the required criteria. 
    Please ensure that your selfie adheres to the following guidelines for optimal head positioning:
</p>
<ul>
    <li>The entire head should be visible in the frame without any cropping.</li>
    <li>The head should not be tilted more than 25 degrees in any direction.</li>
    <li>The face should be facing forward, with both eyes clearly visible.</li>
    <li>Avoid extreme angles or positions that obscure facial features.</li>
</ul>
<p>
    Please re-upload a selfie that meets these criteria to proceed with the liveness verification.
</p>
"""

HTML_SUCCESSFUL_PRECHECKS = """
<h3>Explanation of Results</h3>
<p>Below is an explanation of the checks we run on the uploaded selfie to determine its quality, head position, and whether the selfie is genuine or not.</p>

<ul>
    <li><strong>Overall Status</strong>: Indicates whether all checks were successful. The selfie must meet the requirements for image quality, head position, and pass the liveness checks for the status to be <em>success</em>.</li>

    <li><strong>Ran Checks</strong>: A list of checks performed on the selfie. These include prechecks for image quality (e.g., ensuring the image is not blurred, the head is fully visible and not tilted beyond acceptable angles). If these prechecks pass, liveness checks are performed to assess if the selfie is genuine.</li>

    <li><strong>Face Box</strong>: The coordinates of the detected face, represented as (x1, y1, x2, y2), which define a rectangle surrounding the face within the image.</li>

    <li><strong>Head Position Metrics</strong>:
        <ul>
            <li><strong>Pitch</strong>: The up or down tilt of the head. A positive value indicates a downward tilt, while a negative value indicates an upward tilt.</li>
            <li><strong>Yaw</strong>: The left or right rotation of the head. Positive values indicate a turn to the right, and negative values indicate a turn to the left.</li>
            <li><strong>Roll</strong>: The sideways tilt of the head. Positive values show a tilt to the right, and negative values show a tilt to the left.</li>
        </ul>
    </li>

    <li><strong>Eye Aspect Ratio (EAR)</strong>: A measure of eye openness. A low EAR value indicates the eyes may be closed or blinking. This is an important metric for determining whether the person is actively looking at the camera.</li>

    <li><strong>Liveness Score</strong>: A score ranging from 0 to 1 that estimates the likelihood that the selfie is of a real person. A higher score means a higher probability of authenticity.</li>
    </ul>
"""

HTML_FACE_COMPARISON_HEADER = """
<header style="text-align: center; padding: 20px; border-bottom: 2px solid #cc3300;">
    <h1>Demo of Face Comparison</h1>
    <p style="font-size: 18px;">
        To learn more, visit our website: <a href="https://dataspike.io/" target="_blank" style="font-size: 20px; text-decoration: none;">
        https://dataspike.io/ </a>
    </p>
</header>
"""

HTML_FACE_COMPARISON_EXPLANATION = """
<h3 style="color:#2E86C1;">🔍 Face Comparison Results Explanation</h3>
<p>The system compares two photos and provides one of four results:</p>
<ul>
    <li><strong style="color:#2ECC71;">Same Person</strong>: The same person appears in both photos.</li>
    <li><strong style="color:#E74C3C;">Different Person</strong>: The photos show different individuals.</li>
    <li><strong style="color:#F1C40F;">Same Photo</strong>: Identical faces detected, possibly indicating a duplicate or edited image.</li>
    <li><strong style="color:#95A5A6;">Failure</strong>: Face comparison failed due to undetected or unclear faces.</li>
</ul>
"""


def check_liveness(file_path):
    if file_path:
        url = "https://api.dataspike.io/api/v4/upload/liveness-demo"
        headers = {"ds-api-token": os.getenv("API_KEY")}
        files = {"file": open(file_path, "rb")}
        response = requests.post(url, headers=headers, files=files)
        liveness_result = response.json()

        if (
            "ran_checks" not in liveness_result.keys()
            or len(liveness_result["ran_checks"]) == 0
        ):
            msg = ""
        elif liveness_result["ran_checks"] == ["ImageQuality"]:
            msg = HTML_IQA_FAILED
        elif liveness_result["ran_checks"] == ["ImageQuality", "HeadPosition"]:
            msg = HTML_HEAD_POSITION_FAILED
        else:
            msg = HTML_SUCCESSFUL_PRECHECKS

        return liveness_result, msg, True
    else:
        liveness_result = {
            "overallStatus": "Failure",
            "errors": [
                "The image is not found. Please, submit an image first and then click the button 'Check Liveness!'"
            ],
        }
        return liveness_result, "", False


def map_fc_result(api_status: str):
    mapping = {
        "FaceComparisonVerified": {"label": "Same Person", "color": "#2ECC71"},
        "FaceComparisonUnknown": {"label": "Failure", "color": "#95A5A6"},
        "FaceComparisonFailedDifferentFaces": {
            "label": "Different Person",
            "color": "#E74C3C",
        },
        "FaceComparisonFailedSamePhotos": {"label": "Same Photo", "color": "#F1C40F"},
    }
    status = api_status["status"] if "status" in api_status.keys() else ""
    return mapping.get(status, {"label": "Unknown", "color": "gray"})


def compare_faces(image1_path, image2_path):
    if image1_path and image2_path:
        url = "https://api.dataspike.io/api/v4/upload/face-comparison-demo"
        headers = {"ds-api-token": os.getenv("API_KEY")}
        files = {"left": open(image1_path, "rb"), "right": open(image2_path, "rb")}
        response = requests.post(url, headers=headers, files=files)
        comparison_result = response.json()
        result = map_fc_result(comparison_result)
        return gr.Label(value=result["label"], color=result["color"]), True
        # return comparison_result, True
    else:
        comparison_result = {
            "overallStatus": "Failure",
            "errors": ["Please submit both images before comparing"],
        }
        return comparison_result, "", False


tabs_css = """
/* Style all Gradio tab buttons */
button[role="tab"] {
    font-size: 14px !important;
    font-family: 'Montserrat', sans-serif !important;
    font-weight: 600 !important;
    padding: 12px 24px !important;
    margin: 0 6px !important;
    background-color: #0B0F19 !important;
    color: #F3F4F6 !important;
    border-radius: 8px !important;
    border: 1px solid #1a1a1a !important;
    box-shadow: none !important;
    transition: all 0.2s ease !important;
}

/* Style selected tab button */
button[role="tab"].selected {
    background-color: #635bff !important;
    color: white !important;
    box-shadow: 0 0 6px rgba(99, 91, 255, 0.5) !important;
}

/* Inactive tab style */
button[role="tab"]:not(.selected) {
    font-size: 14px !important;
    font-family: 'Montserrat', sans-serif !important;
    font-weight: 600 !important;
    padding: 12px 24px !important;
    margin: 0 6px !important;
    background-color: #9D2C53 !important;
    color: #F3F4F6 !important;
    border-radius: 8px !important;
    border: 1px solid #1a1a1a !important;
    box-shadow: none !important;
    transition: all 0.2s ease !important;
}

/* Optional: hover effect */
button[role="tab"]:hover {
    background-color: #1a1a2b !important;
    color: white !important;
}
"""


with gr.Blocks(theme=gr.themes.Soft(), css=tabs_css) as Demo:
    with gr.Tabs():
        with gr.Tab("Liveness Detection"):
            header_box = gr.HTML(HTML_HEADER)
            with gr.Row():
                with gr.Column(scale=1):
                    input_img_path = gr.Image(
                        label="Input Image", type="filepath", height=300
                    )
                    gr.Examples(
                        [
                            "images/real_client054_android_SD_scene01.jpg",
                            "images/attack_client006_android_SD_ipad_video_scene01.jpg",
                            "images/attack_client055_android_SD_iphone_video_scene01.jpg",
                            "images/attack_client026_android_SD_printed_photo_scene01.jpg",
                            "images/attack_deepfake_1.jpg",
                            "images/attack_deepfake_3.jpg",
                            "images/attack_mask.jpg",
                            "images/tiktok_3d_mask.jpeg",
                        ],
                        inputs=input_img_path,
                    )
                    check_button = gr.Button("Check Liveness!", variant="primary")
                with gr.Column():
                    liveness_result = gr.JSON(label="Liveness Result")
                    explanation_box = gr.HTML("", visible=False)

            state = gr.State(False)
            check_button.click(
                check_liveness,
                inputs=input_img_path,
                outputs=[liveness_result, explanation_box, state],
            )
            state.change(
                lambda show: gr.update(visible=show),
                inputs=state,
                outputs=explanation_box,
            )

        with gr.Tab("Face Comparison"):
            gr.HTML(HTML_FACE_COMPARISON_HEADER)
            with gr.Row():
                with gr.Column():
                    image1_input = gr.Image(
                        label="First Image", type="filepath", height=300
                    )
                    gr.Examples(
                        [
                            "images/brad_pitt_1.jpeg",
                            "images/brad_pitt_2.jpeg",
                            "images/angelina-jolie-1.jpeg",
                            "images/angelina-jolie-2.jpeg",
                        ],
                        inputs=image1_input,
                    )
                with gr.Column():
                    image2_input = gr.Image(
                        label="Second Image", type="filepath", height=300
                    )
                    gr.Examples(
                        [
                            "images/brad_pitt_1.jpeg",
                            "images/brad_pitt_2.jpeg",
                            "images/angelina-jolie-1.jpeg",
                            "images/angelina-jolie-2.jpeg",
                        ],
                        inputs=image2_input,
                    )

            compare_button = gr.Button("Compare Faces!", variant="primary")
            comparison_result = gr.Label(label="Comparison Result")
            gr.HTML(HTML_FACE_COMPARISON_EXPLANATION)

            comparison_state = gr.State(False)
            compare_button.click(
                compare_faces,
                inputs=[image1_input, image2_input],
                outputs=[comparison_result, comparison_state],
            )


if __name__ == "__main__":
    Demo.launch()