CoolFace
Apppublic

mansi14883md/AI-Keystroke-Security-System

sourceHugging Faceupdated 4mo agoView on Hugging Face
1likes
authenticate.py160 linesDownload Raw Back to root
1import os2import time3import tkinter as tk4from tkinter import messagebox, ttk5from typing import List, Optional, Tuple6 7from backend_utils import authenticate_registered_user, list_registered_users, log_auth_attempt8 9 10TARGET_TEXT = "secure123"11 12 13class AuthenticationCaptureWindow:14    def __init__(self) -> None:15        self.root = tk.Tk()16        self.root.title("Authentication Capture")17        self.root.geometry("520x320")18        self.root.resizable(False, False)19 20        self.press_times = {}21        self.hold_times: List[float] = []22        self.result: Optional[List[float]] = None23        self.selected_user = tk.StringVar()24 25        self.build_gui()26 27    def build_gui(self) -> None:28        tk.Label(29            self.root,30            text="Authentication Window",31            font=("Arial", 16, "bold"),32            pady=10,33        ).pack()34 35        tk.Label(36            self.root,37            text=f"Type this text exactly: {TARGET_TEXT}",38            font=("Arial", 13, "bold"),39            pady=12,40        ).pack()41 42        users = list_registered_users()43        tk.Label(self.root, text="Select user profile", font=("Arial", 11, "bold")).pack()44        self.user_combo = ttk.Combobox(self.root, textvariable=self.selected_user, values=users, state="readonly", width=22)45        self.user_combo.pack(pady=(4, 14))46        if users:47            self.user_combo.current(0)48 49        self.entry = tk.Entry(self.root, font=("Arial", 16), width=25)50        self.entry.pack(pady=18)51        self.entry.focus_set()52        self.entry.bind("<KeyPress>", self.on_key_press)53        self.entry.bind("<KeyRelease>", self.on_key_release)54 55        tk.Button(56            self.root,57            text="Authenticate",58            command=self.submit_sample,59            font=("Arial", 12, "bold"),60            width=18,61            bg="#2e8b57",62            fg="white",63        ).pack(pady=8)64 65        tk.Button(66            self.root,67            text="Clear",68            command=self.clear_entry,69            font=("Arial", 11),70            width=18,71        ).pack()72 73    def on_key_press(self, event) -> None:74        if event.keysym in {"BackSpace", "Delete"}:75            self.clear_entry()76            return77        self.press_times[event.keysym] = time.time()78 79    def on_key_release(self, event) -> None:80        if event.keysym not in self.press_times:81            return82 83        hold_time = time.time() - self.press_times[event.keysym]84        self.hold_times.append(round(hold_time, 6))85 86    def clear_entry(self) -> None:87        self.entry.delete(0, tk.END)88        self.press_times.clear()89        self.hold_times.clear()90 91    def submit_sample(self) -> None:92        typed_text = self.entry.get()93        if typed_text != TARGET_TEXT:94            messagebox.showwarning("Invalid Text", "Please type the fixed text exactly.")95            self.clear_entry()96            return97 98        if len(self.hold_times) < len(TARGET_TEXT):99            messagebox.showwarning("Incomplete Sample", "Please type the full text normally.")100            self.clear_entry()101            return102 103        self.result = self.hold_times[: len(TARGET_TEXT)]104        self.root.destroy()105 106    def run(self) -> Optional[List[float]]:107        self.root.mainloop()108        return self.result109 110 111def predict_authentication(hold_times: List[float]) -> Tuple[str, float]:112    users = list_registered_users()113    if not users:114        raise FileNotFoundError("No registered user profiles found. Run register_user.py first.")115 116    prediction_result = authenticate_registered_user(users[0], hold_times)117    prediction = prediction_result["prediction"]118    confidence = float(prediction_result["confidence"])119 120    if prediction == 1:121        return "Access Granted", confidence122    return "Access Denied", confidence123 124 125def main() -> None:126    users = list_registered_users()127    if not users:128        print("No registered user profiles found. Run register_user.py first.")129        return130 131    window = AuthenticationCaptureWindow()132    hold_times = window.run()133    if hold_times is None:134        print("Authentication cancelled.")135        return136 137    username = window.selected_user.get().strip()138    if not username:139        print("No user selected.")140        return141 142    prediction_result = authenticate_registered_user(username, hold_times)143    result = "Access Granted" if prediction_result["prediction"] == 1 else "Access Denied"144    confidence = prediction_result["confidence"]145    log_auth_attempt(result, confidence, prediction_result["genuine_probability"], prediction_result["best_model"], username=username)146    print(f"\nResult: {result}")147    print(f"Confidence: {confidence * 100:.2f}%")148    print(f"Best model used: {prediction_result['best_model']}")149    print(f"Genuine probability: {prediction_result['genuine_probability'] * 100:.2f}%")150    print(f"Profile similarity: {prediction_result['profile_similarity'] * 100:.2f}%")151    print(f"Selected user: {username}")152    if result == "Access Granted":153        print("System decision: Typing pattern matches the genuine user.")154    else:155        print("System decision: Typing pattern does not match the genuine user.")156 157 158if __name__ == "__main__":159    main()160