project / app.py
byteforcegokul's picture
Create app.py
13ac427 verified
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()