Spaces:
Sleeping
Sleeping
File size: 2,614 Bytes
13ac427 | 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 | import gradio as gr
import cv2
import numpy as np
import mediapipe as mp
from sklearn.ensemble import IsolationForest
# -----------------------
# FACE RECOGNITION MODEL
# -----------------------
mp_face = mp.solutions.face_mesh
mp_drawing = mp.solutions.drawing_utils
# SIMPLE FACE EMBEDDING (using face landmarks)
def get_face_embedding(image):
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
with mp_face.FaceMesh(static_image_mode=True) as face_mesh:
result = face_mesh.process(image_rgb)
if not result.multi_face_landmarks:
return None
landmarks = result.multi_face_landmarks[0]
points = []
for lm in landmarks.landmark:
points.append([lm.x, lm.y, lm.z])
return np.array(points).flatten() # simple embedding
# -----------------------
# LIVENESS CHECK (Blink)
# -----------------------
def liveness_check(image1, image2):
emb1 = get_face_embedding(image1)
emb2 = get_face_embedding(image2)
if emb1 is None or emb2 is None:
return False, "Face not detected"
diff = np.linalg.norm(emb1 - emb2)
if diff > 0.05:
return True, "Liveness Passed (Blink Detected)"
else:
return False, "No blink detected, image may be fake"
# -----------------------
# ANOMALY DETECTION
# -----------------------
model = IsolationForest(contamination=0.05)
model.fit([[1], [2], [3], [4], [5], [6]]) # dummy training
def check_anomaly(vote_count):
pred = model.predict([[vote_count]])
if pred[0] == -1:
return "ALERT: Suspicious voting pattern detected!"
return "Normal voting behavior"
# -----------------------
# MAIN PIPELINE FUNCTION
# -----------------------
def process(face_img, blink_img, vote_number):
if face_img is None or blink_img is None:
return "Upload 2 images!"
# Step 1 β Extract embedding
emb = get_face_embedding(face_img)
if emb is None:
return "Face not detected!"
# Step 2 β Liveness Detection
live, msg = liveness_check(face_img, blink_img)
# Step 3 β Anomaly Detection
anomaly_msg = check_anomaly(vote_number)
return f"""
π§ Face Verified: YES
ποΈ Liveness Result: {msg}
π Anomaly Check: {anomaly_msg}
"""
# -----------------------
# GRADIO UI
# -----------------------
ui = gr.Interface(
fn=process,
inputs=[
gr.Image(type="numpy", label="Upload Face Image"),
gr.Image(type="numpy", label="Upload Blink Image"),
gr.Number(label="Enter Vote Count")
],
outputs=gr.Textbox(label="Result"),
title="AI Module for Blockchain Voting System"
)
ui.launch()
|