Anupam202224's picture
Update app.py
3ecaeaf verified
raw
history blame
3.96 kB
import dash
from dash import dcc, html
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
import plotly.graph_objs as go
# Initialize the Dash app
app = dash.Dash(__name__)
server = app.server
# Generate mock data
def generate_mock_data(n_samples=100):
current_time = datetime.now()
timestamps = [current_time - timedelta(minutes=i) for i in range(n_samples)]
data = pd.DataFrame({
'timestamp': timestamps,
'network_traffic': np.random.normal(1000, 200, n_samples),
'failed_logins': np.random.poisson(5, n_samples),
'suspicious_ips': np.random.poisson(2, n_samples),
'data_exfiltration': np.random.normal(50, 10, n_samples)
})
return data
# Detect anomalies
def detect_anomalies(df):
isolation_forest = IsolationForest(contamination=0.1, random_state=42)
scaler = StandardScaler()
features = ['network_traffic', 'failed_logins', 'suspicious_ips', 'data_exfiltration']
X = df[features]
X_scaled = scaler.fit_transform(X)
return isolation_forest.fit_predict(X_scaled) == -1
# Generate data and detect anomalies
df = generate_mock_data()
anomalies = detect_anomalies(df)
# Create figures
def create_network_traffic_figure():
fig = go.Figure()
# Normal traffic
fig.add_trace(go.Scatter(
x=df[~anomalies]['timestamp'],
y=df[~anomalies]['network_traffic'],
name='Normal Traffic',
mode='lines',
line=dict(color='blue')
))
# Anomalies
fig.add_trace(go.Scatter(
x=df[anomalies]['timestamp'],
y=df[anomalies]['network_traffic'],
name='Anomalies',
mode='markers',
marker=dict(color='red', size=10)
))
fig.update_layout(
title='Network Traffic with Anomaly Detection',
xaxis_title='Time',
yaxis_title='Network Traffic (bytes)',
template='plotly_white'
)
return fig
# Create metrics
def generate_metrics():
return {
'Total Anomalies': int(sum(anomalies)),
'Average Network Traffic': f"{float(df['network_traffic'].mean()):.2f}",
'Max Failed Logins': int(df['failed_logins'].max()),
}
# Define the app layout
app.layout = html.Div([
html.H1("AI-Enhanced Cybersecurity Dashboard",
style={'textAlign': 'center', 'padding': '20px'}),
# Metrics Section
html.Div([
html.H2("Key Metrics", style={'textAlign': 'center'}),
html.Div([
html.Table(
[html.Tr([html.Th(k), html.Td(v)]) for k, v in generate_metrics().items()],
style={'margin': 'auto', 'border-collapse': 'collapse'}
)
])
], style={'padding': '20px'}),
# Network Traffic Graph
html.Div([
html.H2("Network Traffic Analysis", style={'textAlign': 'center'}),
dcc.Graph(figure=create_network_traffic_figure())
], style={'padding': '20px'})
])
# Add CSS
app.index_string = '''
<!DOCTYPE html>
<html>
<head>
{%metas%}
<title>Cybersecurity Dashboard</title>
{%favicon%}
{%css%}
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
background-color: #f0f2f5;
}
table {
width: 100%;
max-width: 600px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f8f9fa;
}
</style>
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>
'''
if __name__ == '__main__':
app.run_server(debug=True)