slakwik commited on
Commit
4e128c5
·
verified ·
1 Parent(s): 2856bc2

Upload streamlit_app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. streamlit_app.py +230 -0
streamlit_app.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import json
4
+ from datetime import datetime, timedelta
5
+ import pandas as pd
6
+ import time
7
+ from utils import zabbix_api, ollama_analysis
8
+ from config import ZABBIX_API_URL, OLLAMA_API_URL
9
+
10
+ # Set page config
11
+ st.set_page_config(
12
+ page_title="Zabbix Event Analyzer",
13
+ page_icon="📊",
14
+ layout="wide",
15
+ initial_sidebar_state="expanded"
16
+ )
17
+
18
+ # Custom CSS
19
+ st.markdown("""
20
+ <style>
21
+ .main-header {
22
+ font-size: 2.5rem;
23
+ font-weight: bold;
24
+ color: #1f77b4;
25
+ text-align: center;
26
+ margin-bottom: 1rem;
27
+ }
28
+ .sub-header {
29
+ font-size: 1.2rem;
30
+ color: #666;
31
+ text-align: center;
32
+ margin-bottom: 2rem;
33
+ }
34
+ .analysis-card {
35
+ border: 1px solid #ddd;
36
+ border-radius: 5px;
37
+ padding: 15px;
38
+ margin-bottom: 15px;
39
+ background-color: #f9f9f9;
40
+ }
41
+ .built-with {
42
+ position: fixed;
43
+ bottom: 10px;
44
+ right: 10px;
45
+ font-size: 0.8rem;
46
+ color: #666;
47
+ }
48
+ </style>
49
+ """, unsafe_allow_html=True)
50
+
51
+ # Header
52
+ st.markdown('<div class="main-header">Zabbix Event Analyzer</div>', unsafe_allow_html=True)
53
+ st.markdown('<div class="sub-header">Analyze Zabbix events with AI-powered insights</div>', unsafe_allow_html=True)
54
+
55
+ # Built with anycoder link
56
+ st.markdown('<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">Built with anycoder</a>', unsafe_allow_html=True)
57
+
58
+ # Initialize session state
59
+ if 'zabbix_auth_token' not in st.session_state:
60
+ st.session_state.zabbix_auth_token = None
61
+ if 'events_data' not in st.session_state:
62
+ st.session_state.events_data = None
63
+ if 'analysis_results' not in st.session_state:
64
+ st.session_state.analysis_results = None
65
+
66
+ # Sidebar
67
+ with st.sidebar:
68
+ st.header("Configuration")
69
+
70
+ # Zabbix API Configuration
71
+ with st.expander("Zabbix API Settings", expanded=True):
72
+ zabbix_url = st.text_input("Zabbix API URL", value=ZABBIX_API_URL)
73
+ zabbix_user = st.text_input("Username", value="Admin")
74
+ zabbix_password = st.text_input("Password", type="password")
75
+
76
+ if st.button("Connect to Zabbix"):
77
+ with st.spinner("Connecting to Zabbix..."):
78
+ try:
79
+ auth_token = zabbix_api.authenticate(zabbix_url, zabbix_user, zabbix_password)
80
+ if auth_token:
81
+ st.session_state.zabbix_auth_token = auth_token
82
+ st.success("Successfully connected to Zabbix!")
83
+ else:
84
+ st.error("Failed to authenticate with Zabbix")
85
+ except Exception as e:
86
+ st.error(f"Connection error: {str(e)}")
87
+
88
+ # Event Filtering
89
+ with st.expander("Event Filters", expanded=True):
90
+ if st.session_state.zabbix_auth_token:
91
+ # Get host groups
92
+ host_groups = zabbix_api.get_host_groups(zabbix_url, st.session_state.zabbix_auth_token)
93
+ selected_group = st.selectbox("Host Group", [""] + [g['name'] for g in host_groups])
94
+
95
+ # Get hosts based on selected group
96
+ hosts = []
97
+ if selected_group:
98
+ hosts = zabbix_api.get_hosts_by_group(zabbix_url, st.session_state.zabbix_auth_token, selected_group)
99
+ selected_host = st.selectbox("Host", [""] + [h['name'] for h in hosts])
100
+
101
+ # Time range
102
+ time_range = st.select_slider(
103
+ "Time Range (hours)",
104
+ options=[1, 6, 12, 24, 48, 72, 168],
105
+ value=24
106
+ )
107
+
108
+ # Event severity
109
+ severity_options = {
110
+ "Not classified": -1,
111
+ "Information": 0,
112
+ "Warning": 1,
113
+ "Average": 2,
114
+ "High": 3,
115
+ "Disaster": 4
116
+ }
117
+ selected_severities = st.multiselect(
118
+ "Severity Levels",
119
+ options=list(severity_options.keys()),
120
+ default=["Warning", "Average", "High", "Disaster"]
121
+ )
122
+
123
+ if st.button("Fetch Events"):
124
+ with st.spinner("Fetching events from Zabbix..."):
125
+ try:
126
+ end_time = int(time.time())
127
+ start_time = end_time - (time_range * 3600)
128
+
129
+ events = zabbix_api.get_events(
130
+ zabbix_url,
131
+ st.session_state.zabbix_auth_token,
132
+ start_time,
133
+ end_time,
134
+ [severity_options[s] for s in selected_severities],
135
+ selected_host
136
+ )
137
+
138
+ if events:
139
+ st.session_state.events_data = events
140
+ st.success(f"Fetched {len(events)} events")
141
+ else:
142
+ st.warning("No events found matching the criteria")
143
+ except Exception as e:
144
+ st.error(f"Error fetching events: {str(e)}")
145
+ else:
146
+ st.warning("Please connect to Zabbix first")
147
+
148
+ # Ollama Configuration
149
+ with st.expander("Ollama Settings", expanded=True):
150
+ ollama_url = st.text_input("Ollama API URL", value=OLLAMA_API_URL)
151
+ model_name = st.selectbox(
152
+ "Analysis Model",
153
+ ["llama3", "mistral", "gemma", "phi3"],
154
+ index=0
155
+ )
156
+
157
+ # Main content
158
+ if st.session_state.events_data:
159
+ st.header("Event Analysis")
160
+
161
+ # Display events
162
+ with st.expander("Raw Events Data", expanded=False):
163
+ events_df = pd.DataFrame(st.session_state.events_data)
164
+ st.dataframe(events_df, use_container_width=True)
165
+
166
+ # Analyze events
167
+ if st.button("Analyze Events with Ollama"):
168
+ with st.spinner("Analyzing events with Ollama..."):
169
+ try:
170
+ # Prepare event summaries for analysis
171
+ event_summaries = []
172
+ for event in st.session_state.events_data[:10]: # Limit to 10 events for demo
173
+ summary = (
174
+ f"Event: {event.get('name', 'N/A')}\n"
175
+ f"Host: {event.get('host', 'N/A')}\n"
176
+ f"Severity: {event.get('severity', 'N/A')}\n"
177
+ f"Time: {datetime.fromtimestamp(int(event.get('clock', 0))).strftime('%Y-%m-%d %H:%M:%S')}\n"
178
+ f"Status: {event.get('value', 'N/A')}\n"
179
+ f"Description: {event.get('description', 'N/A')}"
180
+ )
181
+ event_summaries.append(summary)
182
+
183
+ # Combine all events into a single prompt
184
+ prompt = (
185
+ "Analyze the following Zabbix monitoring events and provide:\n"
186
+ "1. A summary of the overall system health\n"
187
+ "2. Identification of any patterns or recurring issues\n"
188
+ "3. Recommendations for resolution or investigation\n\n"
189
+ "Events:\n" + "\n\n".join(event_summaries)
190
+ )
191
+
192
+ # Get analysis from Ollama
193
+ analysis = ollama_analysis.get_analysis(
194
+ ollama_url,
195
+ model_name,
196
+ prompt
197
+ )
198
+
199
+ if analysis:
200
+ st.session_state.analysis_results = analysis
201
+ else:
202
+ st.error("Failed to get analysis from Ollama")
203
+
204
+ except Exception as e:
205
+ st.error(f"Analysis error: {str(e)}")
206
+
207
+ # Display analysis results
208
+ if st.session_state.analysis_results:
209
+ st.subheader("Analysis Results")
210
+
211
+ # Display in a nice card format
212
+ st.markdown(f"""
213
+ <div class="analysis-card">
214
+ <h3>📊 System Health Summary</h3>
215
+ <p>{st.session_state.analysis_results}</p>
216
+ </div>
217
+ """, unsafe_allow_html=True)
218
+
219
+ # Download button for analysis
220
+ st.download_button(
221
+ label="Download Analysis",
222
+ data=st.session_state.analysis_results,
223
+ file_name=f"zabbix_analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
224
+ mime="text/plain"
225
+ )
226
+ else:
227
+ if st.session_state.zabbix_auth_token:
228
+ st.info("Connect to Zabbix and fetch events to begin analysis")
229
+ else:
230
+ st.info("Please configure and connect to Zabbix to begin")