yash1506 commited on
Commit
cb51936
Β·
verified Β·
1 Parent(s): 2897fa4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -100
app.py CHANGED
@@ -1,126 +1,139 @@
1
  import streamlit as st
2
  import pandas as pd
3
- from pathlib import Path
4
  from processor import DataProcessor
5
- from llm_handler import LLMHandler
6
 
7
  class DDoSResistanceHelper:
8
  def __init__(self):
9
- # Configure Streamlit app
10
  st.set_page_config(
11
- page_title="DDoS Resistance Helper URF LLM Network Analyzer",
12
- page_icon=":shield:",
13
- layout="wide",
14
- initial_sidebar_state="expanded"
15
  )
16
 
17
  # Initialize session state
18
- self.initialize_session_state()
19
 
20
  # Initialize processor and LLM handler
21
  self.processor = DataProcessor()
22
- self.llm_handler = LLMHandler()
23
-
24
- def initialize_session_state(self):
25
- """Set up Streamlit session state variables."""
26
- session_keys = [
27
- 'current_file', 'preprocessed_data', 'analysis_results', 'chat_history'
28
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  for key in session_keys:
30
  if key not in st.session_state:
31
- st.session_state[key] = None if key != 'chat_history' else []
32
-
33
- def render_top_bar(self):
34
- """Render the top bar with theme and upload options."""
35
- col1, col2 = st.columns([8, 2])
36
-
37
- with col1:
38
- st.title("πŸ›‘οΈ DDoS Resistance Helper URF LLM Network Analyzer")
39
-
40
- with col2:
41
- st.markdown("### Theme Selector")
42
- if st.button("Light"):
43
- st.markdown("<style>.stApp { background-color: #ffffff; }</style>", unsafe_allow_html=True)
44
- elif st.button("Dark"):
45
- st.markdown("<style>.stApp { background-color: #1f1f1f; color: white; }</style>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  def render_file_upload(self):
48
- """Render the file upload component."""
49
- uploaded_file = st.file_uploader("Upload Network Traffic Data (CSV)", type=["csv"],
50
- label_visibility="collapsed")
51
  if uploaded_file:
52
- try:
53
- df = pd.read_csv(uploaded_file)
54
- st.session_state.current_file = df
55
- st.success("File uploaded successfully!")
56
- except Exception as e:
57
- st.error(f"Error reading file: {e}")
58
-
59
- def render_analysis(self):
60
- """Render the analysis results."""
61
- if st.session_state.current_file is None:
62
- st.info("Please upload a CSV file to start analysis.")
63
- return
64
-
65
- # Preprocess the data
66
- st.subheader("Preprocessing Data")
67
- with st.spinner("Preprocessing data..."):
68
- try:
69
- preprocessed_data = self.processor.preprocess_data(st.session_state.current_file)
70
- st.session_state.preprocessed_data = preprocessed_data
71
- st.success("Data preprocessed successfully!")
72
- except Exception as e:
73
- st.error(f"Error during preprocessing: {e}")
74
-
75
- # Perform LLM analysis
76
- st.subheader("Performing LLM Analysis")
77
- with st.spinner("Analyzing data with LLM..."):
78
- try:
79
- results = self.llm_handler.analyze_data(st.session_state.preprocessed_data)
80
- st.session_state.analysis_results = results
81
- st.success("Analysis completed successfully!")
82
- except Exception as e:
83
- st.error(f"Error during LLM analysis: {e}")
84
-
85
- # Show results
86
- if st.session_state.analysis_results is not None:
87
- st.subheader("Analysis Results")
88
- st.dataframe(st.session_state.analysis_results)
89
- csv_path = Path("~/.dataset/PROBABILITY_OF_EACH_ROW_DDOS_AND_BENGNIN.csv").expanduser()
90
- st.download_button("Download Results as CSV", csv_path.read_bytes(), "analysis_results.csv")
91
 
92
  def render_chat_interface(self):
93
- """Render a chat interface for interacting with the LLM."""
94
  st.sidebar.header("πŸ’¬ Chat Interface")
95
- # Display chat history
96
- for message in st.session_state.chat_history:
97
- with st.chat_message(message['role']):
98
- st.write(message['content'])
99
-
100
- # Chat input
101
- if prompt := st.sidebar.text_input("Ask about the analysis or mitigation steps..."):
102
- # Add user message to chat history
103
- st.session_state.chat_history.append({
104
- 'role': 'user',
105
- 'content': prompt
106
- })
107
-
108
- # Get LLM response
109
- response = self.llm_handler.get_chat_response(prompt)
110
-
111
- # Add LLM response to chat history
112
- st.session_state.chat_history.append({
113
- 'role': 'assistant',
114
- 'content': response
115
- })
116
-
117
- def run(self):
118
- """Run the Streamlit app."""
119
- self.render_top_bar()
120
  self.render_file_upload()
121
- self.render_analysis()
122
  self.render_chat_interface()
123
 
124
  if __name__ == "__main__":
125
  app = DDoSResistanceHelper()
126
- app.run()
 
1
  import streamlit as st
2
  import pandas as pd
 
3
  from processor import DataProcessor
4
+ from llm_handler import DDoSInference
5
 
6
  class DDoSResistanceHelper:
7
  def __init__(self):
8
+ # Set up Streamlit page configuration
9
  st.set_page_config(
10
+ page_title="DDoS Resistance Helper | LLM Network Analyzer",
11
+ page_icon="πŸ›‘οΈ",
12
+ layout="wide"
 
13
  )
14
 
15
  # Initialize session state
16
+ self.setup_session_state()
17
 
18
  # Initialize processor and LLM handler
19
  self.processor = DataProcessor()
20
+ self.llm_handler = DDoSInference()
21
+
22
+ # Define themes
23
+ self.themes = {
24
+ 'Light': {
25
+ 'base': 'light',
26
+ 'primaryColor': '#3B82F6',
27
+ 'backgroundColor': '#FFFFFF',
28
+ 'secondaryBackgroundColor': '#F3F4F6',
29
+ 'textColor': '#000000'
30
+ },
31
+ 'Dark': {
32
+ 'base': 'dark',
33
+ 'primaryColor': '#10B981',
34
+ 'backgroundColor': '#1F2937',
35
+ 'secondaryBackgroundColor': '#374151',
36
+ 'textColor': '#FFFFFF'
37
+ },
38
+ 'Neon': {
39
+ 'base': 'dark',
40
+ 'primaryColor': '#22D3EE',
41
+ 'backgroundColor': '#000000',
42
+ 'secondaryBackgroundColor': '#1F2937',
43
+ 'textColor': '#22D3EE'
44
+ }
45
+ }
46
+
47
+ def setup_session_state(self):
48
+ """Initialize Streamlit session state variables."""
49
+ st.write("Initializing session state...")
50
+ session_keys = ['chat_history', 'current_file', 'analysis_complete', 'selected_theme', 'preview_data']
51
  for key in session_keys:
52
  if key not in st.session_state:
53
+ st.session_state[key] = [] if key == 'chat_history' else None
54
+ st.write("Session state initialized.")
55
+
56
+ def apply_theme(self):
57
+ """Apply selected theme to Streamlit app."""
58
+ theme_name = st.session_state.get('selected_theme', 'Light')
59
+ theme = self.themes[theme_name]
60
+ st.markdown(f"""
61
+ <style>
62
+ .stApp {{
63
+ background-color: {theme['backgroundColor']};
64
+ color: {theme['textColor']};
65
+ }}
66
+ </style>
67
+ """, unsafe_allow_html=True)
68
+
69
+ def render_theme_selector(self):
70
+ """Render theme selection icons on the top-right corner."""
71
+ st.sidebar.empty()
72
+ st.write(f'<div style="position: absolute; top: 15px; right: 15px;">', unsafe_allow_html=True)
73
+ if st.button("🌞 Light", key="light_theme"):
74
+ st.session_state.selected_theme = 'Light'
75
+ self.apply_theme()
76
+ if st.button("πŸŒ™ Dark", key="dark_theme"):
77
+ st.session_state.selected_theme = 'Dark'
78
+ self.apply_theme()
79
+ if st.button("πŸ’‘ Neon", key="neon_theme"):
80
+ st.session_state.selected_theme = 'Neon'
81
+ self.apply_theme()
82
 
83
  def render_file_upload(self):
84
+ """Render file upload section with an upload icon in the main header."""
85
+ st.title("DDoS Resistance Helper | LLM Network Analyzer")
86
+ uploaded_file = st.file_uploader("Upload Data File πŸ“‚", type=['csv'])
87
  if uploaded_file:
88
+ st.session_state.current_file = uploaded_file
89
+ st.session_state.preview_data = pd.read_csv(uploaded_file).head(5)
90
+ if st.button("πŸš€ Process Data"):
91
+ self.process_uploaded_file(uploaded_file)
92
+
93
+ def process_uploaded_file(self, file):
94
+ """Process the uploaded file and perform analysis."""
95
+ try:
96
+ st.write("Processing file...")
97
+ with st.spinner("Analyzing data..."):
98
+ # Preprocess the uploaded file
99
+ df = self.processor.preprocess_data(file)
100
+
101
+ # Perform LLM analysis
102
+ results = self.llm_handler.analyze_data(df)
103
+
104
+ st.session_state.analysis_complete = True
105
+ st.success("Analysis completed!")
106
+ except Exception as e:
107
+ st.error(f"Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  def render_chat_interface(self):
110
+ """Render chat interface in the sidebar."""
111
  st.sidebar.header("πŸ’¬ Chat Interface")
112
+ for msg in st.session_state.chat_history:
113
+ st.sidebar.write(f"[{msg['role'].capitalize()}]: {msg['content']}")
114
+ new_chat = st.sidebar.text_input("Ask a question...")
115
+ if new_chat:
116
+ st.session_state.chat_history.append({"role": "user", "content": new_chat})
117
+ response = self.llm_handler.get_chat_response(new_chat)
118
+ st.session_state.chat_history.append({"role": "assistant", "content": response})
119
+
120
+ def render_analysis_interface(self):
121
+ """Render analysis results interface."""
122
+ st.subheader("πŸ“‹ Data Preview")
123
+ if st.session_state.preview_data is not None:
124
+ st.dataframe(st.session_state.preview_data)
125
+ if st.session_state.analysis_complete:
126
+ st.subheader("πŸ” Analysis Results")
127
+ st.info("Analysis complete. Visualizations and results here.")
128
+
129
+ def main(self):
130
+ """Main application runner."""
131
+ self.apply_theme()
132
+ self.render_theme_selector()
 
 
 
 
133
  self.render_file_upload()
134
+ self.render_analysis_interface()
135
  self.render_chat_interface()
136
 
137
  if __name__ == "__main__":
138
  app = DDoSResistanceHelper()
139
+ app.main()