Kowo
Update app.py
c179942 verified
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import time
import numpy as np
import seaborn as sns
import tensorflow as tf
from streamlit_extras.dataframe_explorer import dataframe_explorer
import os
# Constants
APP_TITLE = "SAVE_ME"
APP_LOGO = "matrix-hacker-background.jpg"
FEEDBACK_FILE = 'predictions_feedback.csv'
DESCRIPTION = """
<h2 style='color: #7D7D7D;'>Système de Détection d'Intrusion Basé sur l'Apprentissage Profond</h2>
<p>Dans un monde numérique en constante évolution, les menaces en ligne deviennent de plus en plus sophistiquées. Les systèmes de détection d'intrusion traditionnels peuvent ne pas suffire pour contrer ces attaques avancées. C'est pourquoi nous avons développé un système de détection d'intrusion (IDS) <strong>révolutionnaire</strong> basé sur l'apprentissage profond, offrant une sécurité renforcée et une détection précise des anomalies.</p>
"""
parameters = {
"Action": {
"description": "C'est la décision finale de votre modèle, indiquant s'il considère le trafic comme une intrusion ou non. Valeurs possibles: 'Intrusion' ou 'Non Intrusion'.",
"image": "hackers-film-ddos-attack-threat-video.jpg"
},
"Bytes Sent": {
"description": "Nombre total d'octets envoyés par l'entité au cours de la connexion.",
"image": "blue-optic-fiber-with-ethernet-cables.jpg"
},
"Bytes Received": {
"description": "Nombre total d'octets reçus par l'entité au cours de la connexion.",
"image": "computer-hacker-hooded-shirt-typing-software-algorithms-stealing-data-from-computer-network-laptop.jpg"
}
}
params = {
"pkts_sent": {
"description": "Nombre total de paquets envoyés durant la connexion.",
"image": "password-with-hand-holding-tweezers-binary-code.jpg"
},
"pkts_received": {
"description": "Nombre total de paquets reçus durant la connexion.",
"image": "hackers-film-ddos-attack-threat-video.jpg"
},
"Elapsed Time (sec)": {
"description": "Temps écoulé en secondes durant la connexion ou l'événement observé.",
"image": "html-css-collage-concept-with-hacker.jpg"
}
}
st.set_page_config(layout="wide", page_title=APP_TITLE, page_icon=APP_LOGO, initial_sidebar_state="expanded")
@st.cache_data
def loadDataframe(path):
return pd.read_csv(path)
@st.cache_data
def loadModel():
return tf.keras.models.load_model("security.h5")
def simulate_intrusion():
col1, col2 = st.columns(2)
with col1:
bytes_sent = st.number_input("Bytes Sent", min_value=0, value=1)
bytes_received = st.number_input("Bytes Received", min_value=0, value=1)
elapsed_time = st.number_input("Elapsed Time (sec)", min_value=0, value=1)
with col2:
pkts_sent = st.number_input("Packets Sent", min_value=0, value=1)
pkts_received = st.number_input("Packets Received", min_value=0, value=12)
input_data = {
"Bytes Sent": [bytes_sent if bytes_sent else 0],
"Bytes Received": [bytes_received if bytes_received else 0],
"Elapsed Time (sec)": [elapsed_time if elapsed_time else 0],
"pkts_sent": [pkts_sent if pkts_sent else 0],
"pkts_received": [pkts_received if pkts_received else 0]
}
return pd.DataFrame(input_data, index=[0])
def save_feedback(data):
data.to_csv(FEEDBACK_FILE, mode='a', header=not os.path.exists(FEEDBACK_FILE), index=False)
def check_feedback(input_data):
existing = feedback_data[
(feedback_data['Bytes Sent'] == input_data['Bytes Sent'][0]) &
(feedback_data['Bytes Received'] == input_data['Bytes Received'][0]) &
(feedback_data['Elapsed Time (sec)'] == input_data['Elapsed Time (sec)'][0]) &
(feedback_data['pkts_sent'] == input_data['pkts_sent'][0]) &
(feedback_data['pkts_received'] == input_data['pkts_received'][0])
]
return existing
# Load model and feedback data
MODEL = loadModel()
DATA = loadDataframe("finalDf.csv")
if os.path.exists(FEEDBACK_FILE):
feedback_data = pd.read_csv(FEEDBACK_FILE)
else:
feedback_data = pd.DataFrame(columns=['Bytes Sent', 'Bytes Received', 'Elapsed Time (sec)',
'pkts_sent', 'pkts_received', 'Model Prediction', 'User Correction'])
MenuNavigation = ["🏠 Accueil", "📈 Analyse", "📊 Visualisation", "🤺 Simulation"]
st.sidebar.image(APP_LOGO, width=255)
chooseMenu = st.sidebar.selectbox("Où allons 🚔 nous Aujourd'hui? ", MenuNavigation)
if chooseMenu == MenuNavigation[0]:
st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase; text-tranform:underline,'><u>{} </u></h1>".format(APP_TITLE), unsafe_allow_html=True)
st.markdown("<p style='text-align:center; color: gray;'><i>Securité Sécurisée</i></p>", unsafe_allow_html=True)
st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase; text-tranform:underline,'>{}: La meilleure approche pour votre sécurité</h1>".format(APP_TITLE), unsafe_allow_html=True)
col1, col2 = st.columns((1, 2))
with col1:
st.image("html-css-collage-concept-with-hacker.jpg")
with col2:
st.write(DESCRIPTION, unsafe_allow_html=True)
st.markdown("<h1 style='text-align:center; text-transform: uppercase; text-tranform:underline; color: #005580'>LES PARAMETRES DE NOTRE MODEL</h1>", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
for param, info in parameters.items():
col1x, col2x = st.columns([1, 3])
with col1x:
st.image(info['image'], use_column_width=True)
with col2x:
st.markdown(f"""
### Paramètre: **{param}**
{info['description']}
""", unsafe_allow_html=True)
with col2:
for param, info in params.items():
col1x, col2x = st.columns([1, 3])
with col1x:
st.image(info['image'], use_column_width=True)
with col2x:
st.markdown(f"""
### Paramètre: **{param}**
{info['description']}
""", unsafe_allow_html=True)
elif chooseMenu == MenuNavigation[1]:
col1, col2, col3, col4, col5 = st.columns(5)
sumByte = np.sum(DATA["Bytes Sent"]) + np.sum(DATA["Bytes Received"])
col1.metric(label="Nombre De Données", value=DATA.shape[0], delta=5000)
col2.metric(label="Nombre Moyens de Paquets ", value=int((DATA.pkts_sent.sum() + DATA.pkts_received.sum()) / DATA.shape[0]), delta=100)
col3.metric(label="Nombre Moyen de Bytes", value=int(sumByte / DATA.shape[0]), delta=10000)
col4.metric(label="Moyenne du temps des requêtes", value=int(DATA["Elapsed Time (sec)"].sum() / DATA.shape[0]), delta=1000)
col5.metric(label="Maximum de Paquets", value=max(DATA.pkts_sent.astype(int) + DATA.pkts_received.astype(int)), delta=82)
st.title("Filtrez le dataFrame")
filtered_DataFrame = dataframe_explorer(DATA, case=False)
st.dataframe(filtered_DataFrame, use_container_width=True)
st.dataframe(DATA.drop("Action", axis=1).describe(), use_container_width=True, hide_index=False)
elif chooseMenu == MenuNavigation[2]:
st.markdown("<h1 style='text-align:center;color: gray; text-transform: uppercase; text-tranform:underline; color: #005580'>Observons Nos données Avec les Graphes</h1>", unsafe_allow_html=True)
my_grid = grid(2, [2, 4, 1], 1, 4, vertical_align="bottom")
my_grid.line_chart(DATA.drop(["Bytes Sent", "Bytes Received", "Action", "Elapsed Time (sec)"], axis=1), use_container_width=True)
my_grid.line_chart(DATA[["pkts_sent", "pkts_received"]], use_container_width=True)
col1, col2 = st.columns(2)
with col1:
st.write(DATA.drop("Action", axis=1).describe())
with col2:
mask = np.triu(np.ones_like(DATA.drop("Action", axis=1).corr(), dtype=bool))
f, ax = plt.subplots(figsize=(3, 4))
cmap = sns.diverging_palette(230, 20, as_cmap=True)
sns.heatmap(DATA.drop("Action", axis=1).corr(), mask=mask, cmap=cmap, vmax=.2, center=0,
square=True, linewidths=.3, cbar_kws={"shrink": .4})
st.pyplot(f, use_container_width=False)
st.title("Variable Vs Action")
varMenu = ['Bytes Sent', 'Bytes Received', 'Elapsed Time (sec)', 'pkts_sent', 'pkts_received']
colx = st.selectbox("Exprimer", varMenu)
fig, ax = plt.subplots(figsize=(4, 2))
sns.histplot(data=DATA[DATA[colx] < 100], x=colx, hue="Action", bins=12, kde=True, palette=["red", "green"], ax=ax)
ax.set_title(f'Distribution de {colx} VS Action')
st.pyplot(fig, use_container_width=False)
elif chooseMenu == MenuNavigation[3]:
st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase; text-tranform:underline,'>SIMULATION DE VOS REQUETES </h1>", unsafe_allow_html=True)
data_Input = simulate_intrusion()
y_pred = MODEL.predict(data_Input)
y_pred_class = (y_pred > 0.5).astype(int).flatten()
data_Input["Model Prediction"] = ["Intrusion" if x == 0 else "No Intrusion" for x in y_pred_class]
existing_feedback = check_feedback(data_Input)
if not existing_feedback.empty:
st.write("Cette situation a déjà été rencontrée.")
st.write(f"Ancienne Prédiction du modèle: {existing_feedback['Model Prediction'].values[0]}")
st.write(f"Action corrigée par l'utilisateur : {existing_feedback['User Correction'].values[0]}")
data_Input["Model Prediction"]=existing_feedback['User Correction'].values[0]
else:
st.write("Prédiction du Modèle: " + data_Input["Model Prediction"].values[0])
user_correction = st.selectbox("Cette prédiction est-elle correcte?", ["Oui", "Non"])
corrected_action=""
if user_correction == "Non":
# Set corrected_action to the inverse of the prediction
if data_Input["Model Prediction"].values[0] == "Intrusion":
corrected_action = "No Intrusion"
else:
corrected_action = "Intrusion"
feedback_entry = data_Input.copy()
feedback_entry["User Correction"] = corrected_action
feedback_entry["Model Prediction"] = data_Input["Model Prediction"].values[0] # Keep original prediction
save_feedback(feedback_entry)
st.dataframe(data_Input, use_container_width=True)