IDS_project_app / app.py
dev1461's picture
Update app.py
72214ec verified
import gradio as gr
import numpy as np
import random
# =========================
# DATABASE (temporary)
# =========================
users = {}
otp_store = {}
# =========================
# SIGNUP FUNCTION
# =========================
def signup(username, password):
if username in users:
return "❌ User already exists"
users[username] = password
return "βœ… Signup successful! Now go to Login tab."
# =========================
# LOGIN FUNCTION
# =========================
def login(username, password):
if username in users and users[username] == password:
otp = random.randint(1000, 9999)
otp_store[username] = otp
return f"βœ… OTP generated: {otp} (for demo use this OTP)"
return "❌ Invalid username or password"
# =========================
# OTP VERIFICATION
# =========================
def verify_otp(username, otp_input):
if username in otp_store and str(otp_store[username]) == str(otp_input):
return "βœ… Login Successful! You can now use IDS Dashboard.", True
return "❌ Invalid OTP", False
# =========================
# IDS PREDICTION FUNCTION
# =========================
def predict(logged_in, duration, src_bytes, dst_bytes, failed_logins,
count, error_rate, same_srv_rate, diff_srv_rate,
host_count, login_attempts):
# πŸ” Access control
if not logged_in:
return """
🚫 **Access Denied**
You must:
1. Signup
2. Login
3. Verify OTP
πŸ‘‰ Only then you can access IDS Dashboard
"""
# Prepare data
data = np.array([
duration, src_bytes, dst_bytes, failed_logins,
count, error_rate, same_srv_rate, diff_srv_rate,
host_count, login_attempts
])
score = np.sum(data)
# Decision logic
if score < 30:
status = "βœ… Normal Traffic"
explanation = "Low activity and safe behavior detected."
recommendation = "No action needed."
elif score < 60:
status = "⚠️ Suspicious Activity"
explanation = "Moderate anomaly detected."
recommendation = "Monitor the system."
else:
status = "🚨 Attack Detected!"
explanation = "High anomaly detected. Possible malicious activity."
recommendation = "Immediate action required!"
return f"""
{status}
### πŸ”’ Risk Score: {score:.2f}
The risk score represents combined network activity intensity.
### πŸ“Š Interpretation:
- 0 – 30 β†’ Normal (Low Risk)
- 30 – 60 β†’ Suspicious (Medium Risk)
- 60+ β†’ Attack (High Risk)
### 🧠 Analysis:
{explanation}
### πŸ›‘οΈ Recommendation:
{recommendation}
"""
# =========================
# UI DESIGN
# =========================
with gr.Blocks() as demo:
logged_in = gr.State(False)
gr.Markdown("# πŸ” Secure Intrusion Detection System")
with gr.Tabs():
# ================= SIGNUP =================
with gr.Tab("Signup"):
gr.Markdown("### Create a new account")
su_user = gr.Textbox(label="Username")
su_pass = gr.Textbox(label="Password", type="password")
su_btn = gr.Button("Signup")
su_out = gr.Textbox()
su_btn.click(signup, [su_user, su_pass], su_out)
# ================= LOGIN =================
with gr.Tab("Login"):
gr.Markdown("### Enter credentials")
li_user = gr.Textbox(label="Username")
li_pass = gr.Textbox(label="Password", type="password")
li_btn = gr.Button("Login")
li_out = gr.Textbox()
li_btn.click(login, [li_user, li_pass], li_out)
# ================= OTP =================
with gr.Tab("OTP Verification"):
gr.Markdown("### Enter OTP sent after login")
otp_user = gr.Textbox(label="Username")
otp_input = gr.Textbox(label="OTP")
otp_btn = gr.Button("Verify OTP")
otp_out = gr.Textbox()
otp_btn.click(
verify_otp,
[otp_user, otp_input],
[otp_out, logged_in]
)
# ================= IDS DASHBOARD =================
with gr.Tab("IDS Dashboard"):
gr.Markdown("### Analyze Network Traffic")
duration = gr.Number(label="Connection Duration")
src_bytes = gr.Number(label="Source Bytes (Data Sent)")
dst_bytes = gr.Number(label="Destination Bytes (Data Received)")
failed_logins = gr.Number(label="Failed Login Attempts")
login_attempts = gr.Number(label="Total Login Attempts")
count = gr.Number(label="Connection Count")
error_rate = gr.Number(label="Error Rate")
same_srv_rate = gr.Number(label="Same Service Rate")
diff_srv_rate = gr.Number(label="Different Service Rate")
host_count = gr.Number(label="Host Count")
pred_btn = gr.Button("πŸ” Analyze Traffic")
output = gr.Markdown()
pred_btn.click(
predict,
[
logged_in,
duration, src_bytes, dst_bytes, failed_logins,
count, error_rate, same_srv_rate, diff_srv_rate,
host_count, login_attempts
],
output
)
demo.launch()