Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import random | |
| from sklearn.ensemble import IsolationForest | |
| # Global login history | |
| login_history = [] | |
| # Simulate typing speed (chars/sec) | |
| def simulate_typing_speed(normal=True): | |
| return round(random.uniform(3.0, 6.0), 2) if normal else round(random.uniform(0.5, 2.5), 2) | |
| # Simulate login attempt | |
| def simulate_login(normal=True): | |
| login_time = random.randint(8, 18) if normal else random.choice([0, 23]) | |
| actions = random.randint(5, 20) if normal else random.randint(25, 100) | |
| typing_speed = simulate_typing_speed(normal) | |
| # For demo: simulate device hash and IP | |
| device = "device_1" if normal else random.choice(["device_2", "device_3"]) | |
| ip = "192.168.0.1" if normal else random.choice(["10.0.0.1", "172.16.0.1"]) | |
| return {"time": login_time, "actions": actions, "typing_speed": typing_speed, "device": device, "ip": ip} | |
| # Risk scoring function | |
| def evaluate_risk(new_login, history): | |
| # Default matches | |
| device_match = any(l["device"] == new_login["device"] for l in history) | |
| ip_match = any(l["ip"] == new_login["ip"] for l in history) | |
| # Anomaly detection only on numeric features | |
| if len(history) >= 10: | |
| df = pd.DataFrame(history + [new_login]) | |
| model = IsolationForest(contamination=0.1) | |
| model.fit(df[["time", "actions", "typing_speed"]]) | |
| pred = model.predict(df[["time", "actions", "typing_speed"]]) | |
| is_anomaly = pred[-1] == -1 | |
| else: | |
| is_anomaly = False # not enough data | |
| # Risk logic | |
| if not is_anomaly and device_match and ip_match: | |
| risk = "Low Risk ✅" | |
| color = "green" | |
| elif is_anomaly and device_match and ip_match: | |
| risk = "Medium Risk ⚠️" | |
| color = "yellow" | |
| else: | |
| risk = "High Risk 🚨" | |
| color = "red" | |
| return risk, color | |
| # Main function for Gradio | |
| def login(action): | |
| global login_history | |
| new_login = simulate_login(normal=(action=="Normal Login")) | |
| login_history.append(new_login) | |
| risk, color = evaluate_risk(new_login, login_history) | |
| # Convert history to DataFrame for display | |
| df = pd.DataFrame(login_history) | |
| df = df.rename(columns={"time":"Login Time","actions":"Actions","typing_speed":"Typing Speed","device":"Device","ip":"IP Address"}) | |
| return df, f"{risk}" | |
| # Gradio interface | |
| iface = gr.Interface( | |
| fn=login, | |
| inputs=gr.Radio(["Normal Login","Suspicious Login"], label="Select Login Type"), | |
| outputs=[gr.Dataframe(headers=["Login Time","Actions","Typing Speed","Device","IP Address"]), | |
| gr.Textbox(label="Risk Status")], | |
| live=True, | |
| title="🛡️ IdentityGuard AI", | |
| description="AI-powered behavioral login monitoring with anomaly detection and risk scoring" | |
| ) | |
| iface.launch() |