AamirMalik's picture
Update app.py
7e8f388 verified
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import requests
# Fetch real-time network traffic data (Open-source CSV dataset as a fallback)
def fetch_real_time_data():
try:
# Example open dataset: Replace with a valid open-source CSV URL
url = "https://people.sc.fsu.edu/~jburkardt/data/csv/airtravel.csv"
df = pd.read_csv(url)
# Simulating relevant columns for the app
df["Network_Usage"] = np.random.randint(50, 150, len(df))
df["Latency"] = np.random.uniform(10, 100, len(df))
df["Packet_Loss"] = np.random.uniform(0, 5, len(df))
df["Traffic_Anomaly"] = np.random.choice([0, 1], size=len(df), p=[0.9, 0.1])
df["Maintenance_Required"] = np.random.choice([0, 1], size=len(df), p=[0.8, 0.2])
return df
except Exception as e:
st.error(f"Failed to fetch open-source data. Error: {e}")
return generate_fallback_data()
# Simulated data generation for fallback
def generate_fallback_data():
np.random.seed(42)
data = {
"Date": pd.date_range(start="2023-01-01", periods=300),
"Network_Usage": np.random.randint(50, 150, 300), # MB/s
"Latency": np.random.uniform(10, 100, 300), # ms
"Packet_Loss": np.random.uniform(0, 5, 300), # %
"Traffic_Anomaly": np.random.choice([0, 1], size=300, p=[0.9, 0.1]),
"Maintenance_Required": np.random.choice([0, 1], size=300, p=[0.8, 0.2]),
}
return pd.DataFrame(data)
data = fetch_real_time_data()
data.to_csv("network_data.csv", index=False)
# Train AI models
def train_models(data):
features = ["Network_Usage", "Latency", "Packet_Loss"]
# Traffic management model
X_traffic = data[features]
y_traffic = data["Traffic_Anomaly"]
traffic_model = RandomForestClassifier()
traffic_model.fit(X_traffic, y_traffic)
# Predictive maintenance model
X_maintenance = data[features]
y_maintenance = data["Maintenance_Required"]
maintenance_model = RandomForestClassifier()
maintenance_model.fit(X_maintenance, y_maintenance)
return traffic_model, maintenance_model
traffic_model, maintenance_model = train_models(data)
# Blockchain integration simulation
def simulate_blockchain():
st.write("Using Decentralized Physical Infrastructure Networks (DePIN) for transparency and trust.")
blockchain_logs = pd.DataFrame({
"Timestamp": pd.date_range(start="2023-01-01", periods=10, freq="D"),
"Transaction": ["Maintenance Log", "Bandwidth Allocation", "Procurement", "Traffic Monitoring", "Resource Optimization"] * 2,
"Status": ["Completed", "Pending", "Completed", "Completed", "Pending", "Completed", "Completed", "Pending", "Pending", "Completed"],
})
st.dataframe(blockchain_logs)
# Resource allocation optimizer
def resource_allocation():
st.write("AI-driven tool to allocate resources efficiently based on network demands.")
resources = {
"Bandwidth (Mbps)": ["100", "200", "300"],
"Priority": ["Low", "Medium", "High"],
}
resource_df = pd.DataFrame(resources)
st.dataframe(resource_df)
st.write("Optimize resources based on criticality and real-time demand.")
# Procurement automation
def procurement_automation():
st.write("Streamline bidding processes with AI for transparency and efficiency.")
bids = pd.DataFrame({
"Vendor": ["Vendor A", "Vendor B", "Vendor C"],
"Bid Amount": [5000, 4500, 4800],
"Score": [85, 90, 87],
})
st.dataframe(bids)
st.write("AI recommends Vendor B based on the best score and bid amount.")
# Aesthetic Improvements
def add_aesthetics():
st.markdown(
"""
<style>
.stApp {
background: linear-gradient(to right, #74ebd5, #acb6e5);
font-family: 'Arial', sans-serif;
color: #333333;
}
.stMarkdown h1, .stMarkdown h2 {
color: #4A90E2;
text-align: center;
}
.stButton button {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
text-align: center;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
""",
unsafe_allow_html=True
)
add_aesthetics()
# Streamlit App
st.title("🌐 AI Network Lifecycle Manager")
st.write("AI tools for traffic management, predictive maintenance, network monitoring, and more.")
tabs = st.tabs(["Input Parameters", "Predictions", "Monitoring Dashboard", "Blockchain Integration", "Resource Allocation", "Procurement Automation"])
with tabs[0]:
st.header("📊 Network Input Parameters")
network_usage = st.slider("Network Usage (MB/s):", min_value=50, max_value=150, value=100)
latency = st.slider("Latency (ms):", min_value=10, max_value=100, value=50)
packet_loss = st.slider("Packet Loss (%):", min_value=0, max_value=5, value=1)
with tabs[1]:
st.header("🔍 Predictions")
input_data = [[network_usage, latency, packet_loss]]
# Traffic Anomaly Detection
traffic_prediction = traffic_model.predict(input_data)[0]
traffic_message = "🚨 Anomaly Detected" if traffic_prediction == 1 else "✅ Traffic Normal"
# Predictive Maintenance
maintenance_prediction = maintenance_model.predict(input_data)[0]
if traffic_prediction == 1:
maintenance_prediction = 1 # Raise maintenance flag if anomaly is detected
maintenance_message = "🔧 Maintenance Required" if maintenance_prediction == 1 else "✔️ No Maintenance Needed"
st.write(f"**Traffic Status:** {traffic_message}")
st.write(f"**Maintenance Status:** {maintenance_message}")
with tabs[2]:
st.header("📈 Network Monitoring Dashboard")
st.write("Real-time data visualization.")
fig = px.scatter(data, x="Network_Usage", y="Latency", color="Traffic_Anomaly",
title="Traffic Anomalies", labels={"Traffic_Anomaly": "Anomaly"})
st.plotly_chart(fig)
fig2 = px.scatter(data, x="Network_Usage", y="Latency", color="Maintenance_Required",
title="Maintenance Requirements", labels={"Maintenance_Required": "Maintenance"})
st.plotly_chart(fig2)
with tabs[3]:
st.header("Blockchain Integration")
simulate_blockchain()
with tabs[4]:
st.header("Resource Allocation Optimizer")
resource_allocation()
with tabs[5]:
st.header("Procurement Automation System")
procurement_automation()
# Footer
st.markdown("---")
st.markdown(
"**🌟 Built with passion to empower public sector connectivity.**"
)