import gradio as gr import numpy as np from PIL import Image import cv2 from insightface.app import FaceAnalysis from huggingface_hub import snapshot_download import time import subprocess import os # --- Configuration --- SECURITYLEVELS = ["128", "196", "256"] FRMODELS = ["AuraFace-v1"] EXAMPLE_IMAGES_ENROLL = ['./VGGFace2/n000001/0002_01.jpg', './VGGFace2/n000149/0002_01.jpg', './VGGFace2/n000082/0001_02.jpg', './VGGFace2/n000148/0014_01.jpg'] EXAMPLE_IMAGES_AUTH = ['./VGGFace2/n000001/0013_01.jpg', './VGGFace2/n000149/0019_01.jpg', './VGGFace2/n000082/0003_03.jpg', './VGGFace2/n000148/0043_01.jpg'] # --- Global Variables --- face_app = None # --- Helper Functions --- def initialize_face_app(): """Initializes the FaceAnalysis model.""" global face_app if face_app is None: print("Initializing FaceAnalysis model...") snapshot_download("fal/AuraFace-v1", local_dir="./models/auraface") face_app = FaceAnalysis(name="auraface", providers=["CPUExecutionProvider"], root=".") face_app.prepare(ctx_id=0, det_size=(128, 128)) print("FaceAnalysis model initialized.") return face_app def run_binary(bin_path, *args): """Runs a compiled binary file and returns the result.""" if not os.path.isfile(bin_path): raise gr.Error(f"Error: Compiled binary not found at {bin_path}") command = [bin_path] + list(args) print(f"Running command: {' '.join(command)}") cwd = "." try: os.chmod(bin_path, 0o755) start_time = time.time() result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True, cwd=cwd) duration = time.time() - start_time print(f"Binary execution successful. Duration: {duration:.2f}s") return result.stdout, duration except subprocess.CalledProcessError as e: print(f"Error executing binary: {e.stderr}") raise gr.Error(f"Execution failed: {e.stderr}") except Exception as e: print(f"An unexpected error occurred: {e}") raise gr.Error(f"An unexpected error occurred: {str(e)}") def extract_embedding(image_path, mode=None): """Extracts face embedding from an image path.""" if image_path is None: raise gr.Error("Please upload or select an image first.") app = initialize_face_app() try: pil_image = Image.open(image_path).convert("RGB") except Exception as e: raise gr.Error(f"Failed to open or read image file: {e}") cv2_image = np.array(pil_image) cv2_image = cv2_image[:, :, ::-1] faces = app.get(cv2_image) if not faces: raise gr.Error("No face detected. Please try another image.") embedding = faces[0].normed_embedding if mode: # For 1:1 recognition, save to the respective binary folder if mode in ["enroll", "auth"]: emb_path = f'./{mode}-emb.txt' # For 1:N search, create a subject-specific path in the search folder else: # search_enroll, search_auth if "VGGFace2" in image_path: subject = image_path.split('/')[-2] else: subject = 'uploadedSubj' os.makedirs(f'./embeddings/{subject}', exist_ok=True) emb_path = f'./embeddings/{subject}/{mode}-emb.txt' np.savetxt(emb_path, embedding.reshape(1, -1), fmt="%.6f", delimiter=',') return embedding.tolist(), emb_path return embedding.tolist() # --- UI Components --- def create_image_selection_ui(label, gallery_images): with gr.Group(): gr.HTML(f'

{label}

') image_state = gr.State() image_display = gr.Image(type="filepath", label="Selected Image", interactive=False) with gr.Tabs(): with gr.TabItem("Upload"): image_upload = gr.Image(type="filepath", label=f"Upload Image") with gr.TabItem("Select from Gallery"): image_gallery = gr.Gallery(value=gallery_images, columns=4, height="auto", object_fit="contain") # Event handlers that directly update both the hidden state and the visible display def on_select(evt: gr.SelectData): selected_image = gallery_images[evt.index] # Get the actual image path from the gallery list return selected_image, selected_image def on_upload(filepath): return filepath, filepath image_upload.change(on_upload, inputs=image_upload, outputs=[image_state, image_display]) image_gallery.select(on_select, None, outputs=[image_state, image_display]) return image_state # --- UI Styling and Theming --- css = """ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap'); :root { --background: #EEEEEC; --background-alt: #EEEEEC; --card-bg: #FFFFFF; --card-bg-alt: rgba(255, 208, 134, 0.3); --foreground: #222; --foreground-muted: #333; --accent-orange: rgb(255, 208, 134); --accent-gradient: linear-gradient(90deg, var(--accent-orange) 0%, #333333 100%); --font-sans: 'Inter', Arial, Helvetica, sans-serif; --gray-333: #333333; } body, .gradio-container { background: var(--background); color: var(--foreground); font-family: var(--font-sans); font-size: 16px; line-height: 1.6; } .main-header { padding: 1rem; text-align: center; margin-bottom: 2rem; background: var(--gray-333); color: var(--background); border-radius: 15px; } .main-header h1 { font-size: 2.5rem; font-weight: 700; color: var(--accent-orange); margin:0; } .main-header p { font-size: 1.1rem; opacity: 0.9; margin: 0.5rem 0 0 0; } .main-header a { color: var(--background); text-decoration: none; background: transparent; padding: 0.6rem 1.5rem; border-radius: 25px; border: 1px solid var(--accent-orange); font-weight: 500; transition: all 0.3s ease; display: inline-block; margin-top: 1rem; } .main-header a:hover { background: var(--accent-orange); color: var(--gray-333); } .section-header { text-align: center; margin: 2rem 0; padding: 0 1rem; } .section-header h1 { color: var(--foreground); font-size: 2.2rem; font-weight: 600; margin-bottom: 0.5rem; } .section-header h2 { color: var(--foreground-muted); font-size: 1.5rem; font-weight: 400; margin: 0; } .narrative-section { background: var(--card-bg); border-top: 4px solid var(--accent-orange); padding: 2rem; margin: 1.5rem 0; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); } .narrative-header { color: var(--foreground); margin: 0 0 1.5rem 0; font-size: 1.8rem; font-weight: 600; } .step-header { color: var(--foreground); margin: 0 0 1.5rem 0; font-size: 1.3rem; font-weight: 600; } .info-card { background: var(--card-bg-alt); border: 1px solid var(--accent-orange); border-radius: 12px; padding: 1.5rem; margin: 1.5rem 0; } .info-card h3 { color: var(--foreground); margin: 0 0 1rem 0; font-size: 1.3rem; font-weight: 600; } .info-card p { margin: 0 0 1rem 0; color: var(--foreground-muted); line-height: 1.6; } .warning-card { background: #ffebee; border: 1px solid #c62828; border-radius: 12px; padding: 1.5rem; margin: 1.5rem 0; } .warning-card h3 { color: #c62828; margin: 0 0 1rem 0; font-size: 1.3rem; font-weight: 600; } .warning-card p { margin: 0; color: #424242; line-height: 1.6; } .result-container { padding: 2rem; border-radius: 15px; text-align: center; margin-top: 1rem; color: white; } .result-container h2 { margin: 0 0 0.5rem 0; font-size: 2rem; font-weight: 600; color: white; } .result-container p { margin: 0; opacity: 0.95; font-size: 1rem; } .match-verified { background: linear-gradient(135deg, #4caf50 0%, #45a049 100%); } .no-match { background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%); } .icon-lock { font-size: 4rem; margin: 1rem; } .status-text { font-size: 1.1rem; color: var(--foreground-muted); margin-top: 1rem; } """ # --- Gradio UI Definition --- with gr.Blocks(css=css) as demo: # --- Header --- gr.HTML("""
Suraksh.AI Logo

Suraksh AI

The Future of Secure Biometrics

🌐 Visit Our Website
""") # --- Main Tabs for Demo Mode --- with gr.Tabs() as mode_tabs: # --- 1:1 Recognition Demo --- with gr.TabItem("πŸ‘οΈ Face Recognition (1:1)"): gr.HTML("""

Is this the same person?

A one-to-one verification demo.

""") with gr.Tabs(): # --- Vulnerable System Tab --- with gr.TabItem("🚨 The Vulnerable System"): with gr.Group(elem_classes="narrative-section"): gr.HTML('

The Problem: How Your Face Can Be Stolen

') gr.HTML("""

⚠️ Your Biometric Data is Exposed!

Most systems handle biometric data in plaintext. This means your facial embeddingβ€”a digital map of your faceβ€”can be stolen and used to reconstruct your image, creating a major privacy risk.

""") with gr.Row(): with gr.Column(): vuln_image_in = create_image_selection_ui("1. Select an Image", EXAMPLE_IMAGES_ENROLL) with gr.Column(): gr.HTML('

2. Reconstruct the Face

Click below to simulate an attacker stealing the embedding and recreating the face.

') reconstruct_btn = gr.Button("😱 Reconstruct My Face!", variant="stop") vuln_image_out = gr.Image(type="filepath", label="Reconstructed Face", interactive=False) reconstruct_btn.click(lambda x: "./static/reconstructed.png" if x else None, inputs=vuln_image_in, outputs=vuln_image_out) # --- Secure System Tab --- with gr.TabItem("βœ… The Suraksh.AI Solution"): with gr.Group(elem_classes="narrative-section"): gr.HTML('

The Solution: Verification with FHE

') gr.HTML("""

The Locked Box Analogy

With Suraksh.AI, your biometric data is encrypted inside a "locked box" before it ever leaves your device. We can perform the verification on the encrypted data without ever seeing your real face. It's mathematically impossible for us to decrypt it.

""") with gr.Row(): with gr.Column(): rec_ref_img = create_image_selection_ui("1. Provide Reference Image", EXAMPLE_IMAGES_ENROLL) with gr.Column(): rec_probe_img = create_image_selection_ui("2. Provide Probe Image", EXAMPLE_IMAGES_AUTH) with gr.Accordion("Advanced Settings", open=False): rec_threshold = gr.Slider(-512*5, 512*5, value=133, label="Match Strictness", info="A higher value means a stricter match is required.") rec_sec_level = gr.Dropdown(SECURITYLEVELS, value="128", label="Security Level") rec_run_btn = gr.Button("πŸš€ Perform Secure 1:1 Match", variant="primary", size="lg") rec_status = gr.HTML(elem_classes="status-text") rec_result = gr.HTML() def secure_recognition_flow(ref_img, probe_img, threshold, sec_level): yield "Initializing...", "" bin_path = "./bin/genKeys.bin" run_binary(bin_path, sec_level, "genkeys") yield "βœ… Keys Generated... Encrypting Reference...", "" _, _ = extract_embedding(ref_img, "enroll") run_binary("./bin/encReference.bin", sec_level, "encrypt") yield "βœ… Reference Encrypted... Encrypting Probe...", "" _, _ = extract_embedding(probe_img, "auth") run_binary("./bin/encProbe.bin", sec_level, "encrypt") yield "βœ… Probe Encrypted... Performing Secure Match...", "" run_binary("./bin/recDecision.bin", sec_level, "decision", str(threshold)) yield "βœ… Match Computed... Decrypting Result...", "" output, _ = run_binary("./bin/decDecision.bin", sec_level, "decision") if "match" in output.lower(): result_html = """

βœ… MATCH VERIFIED

Identity successfully confirmed under FHE.

""" else: result_html = """

❌ NO MATCH

Identity verification failed.

""" yield "Done!", result_html rec_run_btn.click( fn=secure_recognition_flow, inputs=[rec_ref_img, rec_probe_img, rec_threshold, rec_sec_level], outputs=[rec_status, rec_result] ) # --- 1:N Search Demo --- with gr.TabItem("πŸ” Face Search (1:N)"): gr.HTML("""

Who is this person?

A one-to-many search demo against an encrypted database.

""") with gr.Tabs(): # --- Secure System Tab --- with gr.TabItem("βœ… The Suraksh.AI Solution"): with gr.Group(elem_classes="narrative-section"): gr.HTML('

Building and Searching a Secure Database

') gr.HTML("""

From Verification to Identification

This demo shows how FHE can be used to search for a person in a database without ever decrypting the database itself. This is ideal for large-scale, privacy-preserving identification systems.

""") with gr.Row(): with gr.Column(): search_enroll_img = create_image_selection_ui("1. Enroll Subjects into DB", EXAMPLE_IMAGES_ENROLL) search_offset = gr.Number(label="Subject Offset ID", info="A unique ID for this person in the DB.", precision=0) search_enroll_btn = gr.Button("βž• Encrypt & Add to Database", variant="secondary") search_enroll_status = gr.HTML() with gr.Column(): search_probe_img = create_image_selection_ui("2. Search for a Subject", EXAMPLE_IMAGES_AUTH) search_run_btn = gr.Button("πŸš€ Perform Secure 1:N Search", variant="primary", size="lg") search_status = gr.HTML(elem_classes="status-text") search_result = gr.HTML() with gr.Accordion("Advanced Settings", open=False): search_threshold = gr.Slider(-512*5, 512*5, value=133, label="Match Strictness") search_sec_level = gr.Dropdown(SECURITYLEVELS, value="128", label="Security Level") demo.load(lambda: run_binary("./bin/search.bin", "128", "genkeys"), None, None) def secure_enroll_flow(image, offset, sec_level): if image is None or offset is None: raise gr.Error("Please provide an image and a unique offset ID.") yield "Encrypting and adding subject..." _, emb_path = extract_embedding(image, "search_enroll") run_binary("./bin/search.bin", sec_level, "encRef", emb_path, str(int(offset))) run_binary("./bin/search.bin", sec_level, "addRef") yield f"βœ… Subject with ID {int(offset)} added to the secure database." def secure_search_flow(image, threshold, sec_level): if image is None: raise gr.Error("Please provide an image to search.") yield "Initializing secure search...", "" _, emb_path = extract_embedding(image, "search_auth") run_binary("./bin/search.bin", sec_level, "encProbe", emb_path) yield "βœ… Probe encrypted... Searching database...", "" run_binary("./bin/search.bin", sec_level, "search") yield "βœ… Search complete... Decrypting results...", "" output, _ = run_binary("./bin/search.bin", sec_level, "decDecisionClear", str(threshold)) if "found" in output.lower(): result_html = """

βœ… SUBJECT FOUND

The subject was successfully found in the database.

""" else: result_html = """

❌ NOT FOUND

The subject was not found in the database.

""" yield "Done!", result_html search_enroll_btn.click( fn=secure_enroll_flow, inputs=[search_enroll_img, search_offset, search_sec_level], outputs=[search_enroll_status] ) search_run_btn.click( fn=secure_search_flow, inputs=[search_probe_img, search_threshold, search_sec_level], outputs=[search_status, search_result] ) # --- Launch the Application --- if __name__ == "__main__": demo.launch()