omarrama555 commited on
Commit
8ffcd79
Β·
verified Β·
1 Parent(s): 6adcbf9

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +102 -196
streamlit_app.py CHANGED
@@ -7,18 +7,12 @@ import datetime
7
  import os
8
  import random
9
  import cv2
10
-
11
- # Try to import streamlit_webrtc, but handle if it's not installed
12
- try:
13
- from streamlit_webrtc import webrtc_streamer, VideoTransformerBase, ClientSettings
14
- WEBRTC_AVAILABLE = True
15
- except ImportError:
16
- st.warning("streamlit_webrtc not found. Live camera analysis will be disabled.")
17
- WEBRTC_AVAILABLE = False
18
 
19
  # ================= PAGE CONFIG =================
20
  st.set_page_config(
21
- page_title="SolarGuard AI Pro",
22
  page_icon="β˜€οΈ",
23
  layout="wide",
24
  initial_sidebar_state="expanded"
@@ -112,29 +106,19 @@ div[data-testid="stAlert"] div[data-testid="stMarkdownContainer"] p {
112
  # ================= MODEL =================
113
  @st.cache_resource
114
  def load_model():
115
- # Update this path to where your model is actually located
116
  model_path = 'best.pt'
117
  if os.path.exists(model_path):
118
  return YOLO(model_path)
119
- else:
120
- st.sidebar.error(f"Model file not found at: {model_path}")
121
- return None
122
 
123
  model = load_model()
124
 
125
  # ================= HELPER FUNCTIONS =================
126
  def convert_to_infrared(image_pil):
127
- # Convert PIL Image to OpenCV format (BGR)
128
  image_cv = np.array(image_pil)
129
  image_cv = cv2.cvtColor(image_cv, cv2.COLOR_RGB2BGR)
130
-
131
- # Convert to grayscale
132
  gray_image = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY)
133
-
134
- # Apply a colormap to simulate infrared effect (e.g., COLORMAP_JET)
135
  infrared_simulated = cv2.applyColorMap(gray_image, cv2.COLORMAP_JET)
136
-
137
- # Convert back to PIL Image for Streamlit display
138
  infrared_pil = Image.fromarray(cv2.cvtColor(infrared_simulated, cv2.COLOR_BGR2RGB))
139
  return infrared_pil
140
 
@@ -144,20 +128,16 @@ if 'logged_in' not in st.session_state:
144
  if 'entered_site' not in st.session_state:
145
  st.session_state.entered_site = False
146
  if 'users' not in st.session_state:
147
- # In a real application, this would be loaded from a database
148
- st.session_state.users = {'admin': 'solar2026'} # Example user
149
 
150
  # ================= LOGIN / REGISTRATION PAGE =================
151
  if not st.session_state.logged_in:
152
- st.markdown('<div class="project-title">β˜€οΈ SolarGuard AI Pro</div>', unsafe_allow_html=True)
153
  st.markdown('<div class="subtitle">Smart Solar AI Monitoring</div>', unsafe_allow_html=True)
154
-
155
  st.markdown('<div class="glass-box">', unsafe_allow_html=True)
156
-
157
  st.subheader("Login or Register")
158
 
159
  tab1, tab2 = st.tabs(["Login", "Register"])
160
-
161
  with tab1:
162
  st.markdown("#### Existing User Login")
163
  username_login = st.text_input("Username", key="username_login")
@@ -166,11 +146,9 @@ if not st.session_state.logged_in:
166
  if username_login in st.session_state.users and st.session_state.users[username_login] == password_login:
167
  st.session_state.logged_in = True
168
  st.session_state.current_user = username_login
169
- st.success(f"Welcome, {username_login}!")
170
  st.rerun()
171
  else:
172
  st.error("Invalid username or password")
173
-
174
  with tab2:
175
  st.markdown("#### New User Registration")
176
  username_register = st.text_input("New Username", key="username_register")
@@ -180,7 +158,7 @@ if not st.session_state.logged_in:
180
  if not username_register or not password_register or not confirm_password_register:
181
  st.warning("All fields are required.")
182
  elif username_register in st.session_state.users:
183
- st.error("Username already exists. Please choose a different one.")
184
  elif password_register != confirm_password_register:
185
  st.error("Passwords do not match.")
186
  else:
@@ -190,235 +168,163 @@ if not st.session_state.logged_in:
190
 
191
  # ================= LANDING =================
192
  elif not st.session_state.entered_site:
193
- st.markdown('<div class="project-title">β˜€οΈ SolarGuard AI Pro</div>', unsafe_allow_html=True)
194
  st.markdown('<div class="subtitle">AI Renewable Energy Intelligence</div>', unsafe_allow_html=True)
195
-
196
  st.markdown("## Welcome to Solar Intelligence Platform")
197
-
198
  c1, c2, c3, c4 = st.columns(4)
199
  c1.metric("Panels", "1240+")
200
  c2.metric("Accuracy", "97%")
201
  c3.metric("Alerts", "12")
202
  c4.metric("Energy Saved", "32%")
203
-
204
  if st.button("πŸš€ Enter Dashboard", use_container_width=True):
205
  st.session_state.entered_site = True
206
  st.rerun()
207
 
208
  # ================= DASHBOARD =================
209
  else:
210
- st.sidebar.title("β˜€οΈ SolarGuard AI Pro")
211
-
212
  menu = st.sidebar.selectbox(
213
  "Navigation",
214
- ["Home Dashboard", "AI Analysis", "Smart Maintenance Prediction", "Self-Learning System", "Live Camera Analysis", "Video Analysis", "Reports", "About Us", "Contact"]
215
  )
216
 
217
  # ---------------- HOME ----------------
218
  if menu == "Home Dashboard":
219
  st.markdown("## πŸ“Š Smart Dashboard")
220
-
221
- c1, c2, c3 = st.columns(3)
222
  c1.metric("Total Panels", "1,240")
223
- c2.metric("Healthy", "95%")
224
- c3.metric("Critical", "12")
225
-
226
- chart = pd.DataFrame(np.random.randn(24, 1), columns=["KWh"])
227
- st.area_chart(chart)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
  # ---------------- AI ANALYSIS ----------------
230
  elif menu == "AI Analysis":
231
  st.markdown("## πŸ€– AI Multi Panel Analysis")
232
-
233
- files = st.file_uploader(
234
- "Upload up to 5 images",
235
- type=['jpg', 'png', 'jpeg'],
236
- accept_multiple_files=True
237
- )
238
 
239
  if files:
240
- cols = st.columns(min(len(files), 5))
241
- ir_cols = st.columns(min(len(files), 5))
242
- results_list = []
243
-
244
- for i, file in enumerate(files[:5]):
245
- img = Image.open(file)
246
-
247
- with cols[i]:
248
- st.image(img, caption=f"Original: {file.name}", use_container_width=True)
249
-
250
- # Convert to infrared and display
251
- infrared_img = convert_to_infrared(img)
252
- with ir_cols[i]:
253
- st.image(infrared_img, caption=f"Infrared: {file.name}", use_container_width=True)
254
-
255
- # ===== AI OR DEMO =====
256
- if model:
257
- temp_path = f"temp_{i}.jpg"
258
- img.save(temp_path)
259
-
260
- res = model.predict(temp_path, conf=0.5)
261
-
262
- if len(res[0].boxes) == 0:
263
- label = "Clean"
264
- score = 100
 
 
265
  else:
266
- label = model.names[int(res[0].boxes[0].cls[0])]
267
- if label == 'Clean':
268
- score = float(res[0].boxes[0].conf[0]) * 100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  else:
270
- score = (1 - float(res[0].boxes[0].conf[0])) * 100
271
- os.remove(temp_path)
272
- else:
273
- label = random.choice(["Clean", "Dust", "Crack", "Bird-Drop"])
274
- score = random.randint(75, 99)
275
-
276
- results_list.append({
277
- "Panel": file.name,
278
- "Health Score": round(score, 1),
279
- "Status": label
280
- })
281
-
282
- st.markdown("### 🎯 Results")
283
- df = pd.DataFrame(results_list).sort_values(by="Health Score", ascending=False)
284
- st.dataframe(df, use_container_width=True)
285
-
286
- # --- Download Report ---
287
- st.markdown("### Download Report")
288
- csv_report = df.to_csv(index=False).encode('utf-8')
289
- st.download_button(
290
- label="Download Results as CSV",
291
- data=csv_report,
292
- file_name="solar_analysis_report.csv",
293
- mime="text/csv",
294
- use_container_width=True
295
- )
296
-
297
- st.info("To send real WhatsApp messages, you need to set up a WhatsApp Business API account (e.g., via Twilio, MessageBird) and provide credentials. This is a conceptual integration.")
298
-
299
- phone_number = st.text_input("Enter WhatsApp Phone Number (e.g., +1234567890)", key="whatsapp_num")
300
- whatsapp_message = f"SolarGuard AI Report:\n\n{df.to_string(index=False)}\n\nFor more details, visit your SolarGuard dashboard."
301
-
302
- if st.button("Send WhatsApp Message", use_container_width=True):
303
- if phone_number:
304
- st.success(f"Simulating WhatsApp message sent to {phone_number}.\n\nMessage Content:\n{whatsapp_message}")
305
- else:
306
- st.warning("Please enter a phone number.")
307
-
308
-
309
- # ---------------- SMART MAINTENANCE PREDICTION ----------------
310
- elif menu == "Smart Maintenance Prediction":
311
- st.markdown("## πŸ’‘ Smart Maintenance Prediction")
312
- st.write("This section will provide intelligent predictions for solar panel maintenance based on analysis.")
313
- st.info("Feature under development: Upload an image here to get a detailed maintenance prediction and schedule.")
314
 
315
  # ---------------- SELF-LEARNING SYSTEM ----------------
316
  elif menu == "Self-Learning System":
317
  st.markdown("## 🧠 Self-Learning System")
318
  st.write("Help improve the AI model by providing new labeled data.")
319
- st.warning("If the model misidentified an issue, you can upload the image and correct its label here.")
320
-
321
  uploaded_image_sl = st.file_uploader("Upload an image for retraining", type=['jpg', 'png', 'jpeg'], key="sl_image")
322
  if uploaded_image_sl:
323
  st.image(uploaded_image_sl, caption="Image for Self-Learning", use_container_width=True)
324
- correct_label = st.selectbox(
325
- "Select the correct label for this image:",
326
- ["Clean", "Dusty", "Bird-drop", "Electrical-damage", "Physical-damage"],
327
- key="sl_label"
328
- )
329
- if st.button("Submit for Retraining Data", use_container_width=True):
330
- st.success(f"Image '{uploaded_image_sl.name}' with label '{correct_label}' submitted for self-learning dataset.")
331
- st.info("This data will be used to improve the model in future updates.")
332
-
333
- # ---------------- LIVE CAMERA ANALYSIS ----------------
334
- elif menu == "Live Camera Analysis":
335
- st.markdown("## πŸŽ₯ Live Camera Feed Analysis")
336
- st.write("Connect a live camera to detect solar panel defects in real-time.")
337
-
338
- if WEBRTC_AVAILABLE and model:
339
- st.warning("For live camera to work in Colab, you might need to grant camera permissions in your browser. Performance may vary.")
340
-
341
- class VideoProcessor(VideoTransformerBase):
342
- def __init__(self, model):
343
- self.model = model
344
-
345
- def recv(self, frame):
346
- img = frame.to_ndarray(format="bgr24")
347
- results = self.model.predict(img, conf=0.5, verbose=False)
348
- annotated_img = img.copy()
349
- for r in results:
350
- annotated_img = r.plot()
351
- return frame.from_ndarray(annotated_img, format="bgr24")
352
-
353
- webrtc_streamer(
354
- key="live_camera_analysis",
355
- video_transformer_factory=lambda: VideoProcessor(model),
356
- client_settings=ClientSettings(
357
- rtc_configuration={
358
- "iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}
359
- ,
360
- media_stream_constraints={
361
- "video": True,
362
- "audio": False,
363
- },
364
- ),
365
- )
366
- elif not WEBRTC_AVAILABLE:
367
- st.error("streamlit_webrtc library is not installed. Please install it using `pip install streamlit-webrtc`.")
368
- else:
369
- st.info("Model not loaded or not available for live analysis.")
370
 
371
  # ---------------- VIDEO ANALYSIS ----------------
372
  elif menu == "Video Analysis":
373
  st.markdown("## 🎬 Video Upload and Analysis")
374
- st.write("Upload a video of solar panels for frame-by-frame defect detection.")
375
- st.warning("Video processing can be resource-intensive. Frames will be extracted and analyzed sequentially.")
376
-
377
  uploaded_video = st.file_uploader("Upload a video file", type=['mp4', 'avi', 'mov'], key="video_upload")
378
-
379
  if uploaded_video and model:
380
- tfile = uploaded_video.name
381
  with open(tfile, "wb") as f:
382
  f.write(uploaded_video.getbuffer())
383
-
384
  cap = cv2.VideoCapture(tfile)
385
- if not cap.isOpened():
386
- st.error("Error: Could not open video file.")
387
- else:
388
- st.info("Processing video... This might take a while depending on video length.")
389
- frame_count = 0
390
  st_frame = st.empty()
391
-
392
  while True:
393
  ret, frame = cap.read()
394
- if not ret:
395
- break
396
-
397
  results = model.predict(frame, conf=0.5, verbose=False)
398
- annotated_frame = frame.copy()
399
- for r in results:
400
- annotated_frame = r.plot()
401
-
402
- st_frame.image(annotated_frame, channels="BGR", use_column_width=True, caption=f"Frame {frame_count}")
403
- frame_count += 1
404
-
405
  cap.release()
406
  os.remove(tfile)
407
  st.success("Video processing complete!")
408
- elif uploaded_video and not model:
409
- st.warning("Model is not loaded, cannot perform video analysis.")
410
- else:
411
- st.info("Please upload a video file to begin analysis.")
412
 
413
  # ---------------- REPORTS ----------------
414
  elif menu == "Reports":
415
  st.markdown("## πŸ“‹ Reports")
416
  st.success("Weekly report generated successfully")
 
 
 
 
 
 
417
 
418
  # ---------------- ABOUT ----------------
419
  elif menu == "About Us":
420
  st.markdown("## 🌍 About SolarGuard")
421
- st.write("SolarGuard AI Pro is an advanced artificial intelligence platform designed to revolutionize solar energy monitoring and maintenance. Our system leverages state-of-the-art computer vision and deep learning models to automatically detect defects in solar panels such as dust accumulation, cracks, bird droppings, and electrical damage. By combining real-time image analysis, predictive maintenance, and intelligent reporting, SolarGuard helps solar farm operators increase efficiency, reduce maintenance costs and maximize energy output. The platform also integrates interactive dashboards, live camera analysis, and video processing to provide a complete end-to-end monitoring solution. Our mission is to make renewable energy systems smarter, safer, and more efficient through AI-driven automation and continuous learning.")
422
 
423
  # ---------------- CONTACT ----------------
424
  elif menu == "Contact":
 
7
  import os
8
  import random
9
  import cv2
10
+ import plotly.express as px
11
+ import plotly.graph_objects as go
 
 
 
 
 
 
12
 
13
  # ================= PAGE CONFIG =================
14
  st.set_page_config(
15
+ page_title="SolarGuard AI",
16
  page_icon="β˜€οΈ",
17
  layout="wide",
18
  initial_sidebar_state="expanded"
 
106
  # ================= MODEL =================
107
  @st.cache_resource
108
  def load_model():
 
109
  model_path = 'best.pt'
110
  if os.path.exists(model_path):
111
  return YOLO(model_path)
112
+ return None
 
 
113
 
114
  model = load_model()
115
 
116
  # ================= HELPER FUNCTIONS =================
117
  def convert_to_infrared(image_pil):
 
118
  image_cv = np.array(image_pil)
119
  image_cv = cv2.cvtColor(image_cv, cv2.COLOR_RGB2BGR)
 
 
120
  gray_image = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY)
 
 
121
  infrared_simulated = cv2.applyColorMap(gray_image, cv2.COLORMAP_JET)
 
 
122
  infrared_pil = Image.fromarray(cv2.cvtColor(infrared_simulated, cv2.COLOR_BGR2RGB))
123
  return infrared_pil
124
 
 
128
  if 'entered_site' not in st.session_state:
129
  st.session_state.entered_site = False
130
  if 'users' not in st.session_state:
131
+ st.session_state.users = {'admin': 'solar2026'}
 
132
 
133
  # ================= LOGIN / REGISTRATION PAGE =================
134
  if not st.session_state.logged_in:
135
+ st.markdown('<div class="project-title">β˜€οΈ SolarGuard AI</div>', unsafe_allow_html=True)
136
  st.markdown('<div class="subtitle">Smart Solar AI Monitoring</div>', unsafe_allow_html=True)
 
137
  st.markdown('<div class="glass-box">', unsafe_allow_html=True)
 
138
  st.subheader("Login or Register")
139
 
140
  tab1, tab2 = st.tabs(["Login", "Register"])
 
141
  with tab1:
142
  st.markdown("#### Existing User Login")
143
  username_login = st.text_input("Username", key="username_login")
 
146
  if username_login in st.session_state.users and st.session_state.users[username_login] == password_login:
147
  st.session_state.logged_in = True
148
  st.session_state.current_user = username_login
 
149
  st.rerun()
150
  else:
151
  st.error("Invalid username or password")
 
152
  with tab2:
153
  st.markdown("#### New User Registration")
154
  username_register = st.text_input("New Username", key="username_register")
 
158
  if not username_register or not password_register or not confirm_password_register:
159
  st.warning("All fields are required.")
160
  elif username_register in st.session_state.users:
161
+ st.error("Username already exists.")
162
  elif password_register != confirm_password_register:
163
  st.error("Passwords do not match.")
164
  else:
 
168
 
169
  # ================= LANDING =================
170
  elif not st.session_state.entered_site:
171
+ st.markdown('<div class="project-title">β˜€οΈ SolarGuard AI</div>', unsafe_allow_html=True)
172
  st.markdown('<div class="subtitle">AI Renewable Energy Intelligence</div>', unsafe_allow_html=True)
 
173
  st.markdown("## Welcome to Solar Intelligence Platform")
 
174
  c1, c2, c3, c4 = st.columns(4)
175
  c1.metric("Panels", "1240+")
176
  c2.metric("Accuracy", "97%")
177
  c3.metric("Alerts", "12")
178
  c4.metric("Energy Saved", "32%")
 
179
  if st.button("πŸš€ Enter Dashboard", use_container_width=True):
180
  st.session_state.entered_site = True
181
  st.rerun()
182
 
183
  # ================= DASHBOARD =================
184
  else:
185
+ st.sidebar.title("β˜€οΈ SolarGuard AI")
 
186
  menu = st.sidebar.selectbox(
187
  "Navigation",
188
+ ["Home Dashboard", "AI Analysis", "Self-Learning System", "Video Analysis", "Reports", "About Us", "Contact"]
189
  )
190
 
191
  # ---------------- HOME ----------------
192
  if menu == "Home Dashboard":
193
  st.markdown("## πŸ“Š Smart Dashboard")
194
+ c1, c2, c3, c4 = st.columns(4)
 
195
  c1.metric("Total Panels", "1,240")
196
+ c2.metric("Healthy", "95%", "2%")
197
+ c3.metric("Critical", "12", "-3")
198
+ c4.metric("Efficiency", "92%", "5%")
199
+
200
+ col_left, col_right = st.columns(2)
201
+
202
+ with col_left:
203
+ # Power Generation Chart
204
+ df_gen = pd.DataFrame({
205
+ 'Hour': list(range(24)),
206
+ 'Power (kW)': [0,0,0,0,0,5,15,35,60,85,110,125,130,125,110,85,60,35,15,5,0,0,0,0]
207
+ })
208
+ fig_gen = px.area(df_gen, x='Hour', y='Power (kW)', title='Daily Power Generation Profile',
209
+ color_discrete_sequence=['#ff8c00'])
210
+ fig_gen.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color="white")
211
+ st.plotly_chart(fig_gen, use_container_width=True)
212
+
213
+ with col_right:
214
+ # Fault Distribution Chart
215
+ fault_data = {'Category': ['Clean', 'Dust', 'Crack', 'Bird-Drop'], 'Count': [1180, 40, 12, 8]}
216
+ fig_fault = px.pie(fault_data, values='Count', names='Category', title='Panel Status Distribution',
217
+ color_discrete_sequence=px.colors.sequential.Oranges_r)
218
+ fig_fault.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color="white")
219
+ st.plotly_chart(fig_fault, use_container_width=True)
220
 
221
  # ---------------- AI ANALYSIS ----------------
222
  elif menu == "AI Analysis":
223
  st.markdown("## πŸ€– AI Multi Panel Analysis")
224
+ files = st.file_uploader("Upload up to 5 images", type=['jpg', 'png', 'jpeg'], accept_multiple_files=True)
 
 
 
 
 
225
 
226
  if files:
227
+ # Using a container to prevent "tabs hanging" and improve rendering
228
+ with st.container():
229
+ cols = st.columns(min(len(files), 5))
230
+ ir_cols = st.columns(min(len(files), 5))
231
+ results_list = []
232
+
233
+ for i, file in enumerate(files[:5]):
234
+ img = Image.open(file)
235
+ with cols[i]:
236
+ st.image(img, caption=f"Original: {file.name}", use_container_width=True)
237
+
238
+ infrared_img = convert_to_infrared(img)
239
+ with ir_cols[i]:
240
+ st.image(infrared_img, caption=f"Infrared: {file.name}", use_container_width=True)
241
+
242
+ if model:
243
+ # Fix for FileNotFoundError: Convert PIL to numpy for direct prediction
244
+ img_np = np.array(img)
245
+ res = model.predict(img_np, conf=0.5)
246
+
247
+ if len(res[0].boxes) == 0:
248
+ label = "Clean"
249
+ score = 100
250
+ else:
251
+ label = model.names[int(res[0].boxes[0].cls[0])]
252
+ conf = float(res[0].boxes[0].conf[0])
253
+ score = conf * 100 if label == 'Clean' else (1 - conf) * 100
254
  else:
255
+ label = random.choice(["Clean", "Dust", "Crack", "Bird-Drop"])
256
+ score = random.randint(75, 99)
257
+
258
+ results_list.append({"Panel": file.name, "Health Score": round(score, 1), "Status": label})
259
+
260
+ st.markdown("### 🎯 Results")
261
+ df = pd.DataFrame(results_list).sort_values(by="Health Score", ascending=False)
262
+ st.dataframe(df, use_container_width=True)
263
+
264
+ st.markdown("### Actions")
265
+ c1, c2 = st.columns(2)
266
+ with c1:
267
+ csv_report = df.to_csv(index=False).encode('utf-8')
268
+ st.download_button("Download CSV Report", data=csv_report, file_name="solar_report.csv", mime="text/csv", use_container_width=True)
269
+ with c2:
270
+ phone_number = st.text_input("WhatsApp Number", placeholder="+1234567890")
271
+ if st.button("Send via WhatsApp", use_container_width=True):
272
+ if phone_number:
273
+ whatsapp_message = f"SolarGuard AI Report:\n\n{df.to_string(index=False)}"
274
+ st.success(f"Simulated WhatsApp sent to {phone_number}")
275
  else:
276
+ st.warning("Please enter a phone number.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  # ---------------- SELF-LEARNING SYSTEM ----------------
279
  elif menu == "Self-Learning System":
280
  st.markdown("## 🧠 Self-Learning System")
281
  st.write("Help improve the AI model by providing new labeled data.")
 
 
282
  uploaded_image_sl = st.file_uploader("Upload an image for retraining", type=['jpg', 'png', 'jpeg'], key="sl_image")
283
  if uploaded_image_sl:
284
  st.image(uploaded_image_sl, caption="Image for Self-Learning", use_container_width=True)
285
+ correct_label = st.selectbox("Select correct label:", ["Clean", "Dusty", "Bird-drop", "Electrical-damage", "Physical-damage"])
286
+ if st.button("Submit for Retraining", use_container_width=True):
287
+ st.success(f"Submitted '{uploaded_image_sl.name}' with label '{correct_label}'.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
  # ---------------- VIDEO ANALYSIS ----------------
290
  elif menu == "Video Analysis":
291
  st.markdown("## 🎬 Video Upload and Analysis")
 
 
 
292
  uploaded_video = st.file_uploader("Upload a video file", type=['mp4', 'avi', 'mov'], key="video_upload")
 
293
  if uploaded_video and model:
294
+ tfile = "temp_video.mp4"
295
  with open(tfile, "wb") as f:
296
  f.write(uploaded_video.getbuffer())
 
297
  cap = cv2.VideoCapture(tfile)
298
+ if cap.isOpened():
299
+ st.info("Processing video...")
 
 
 
300
  st_frame = st.empty()
 
301
  while True:
302
  ret, frame = cap.read()
303
+ if not ret: break
 
 
304
  results = model.predict(frame, conf=0.5, verbose=False)
305
+ annotated_frame = results[0].plot()
306
+ st_frame.image(annotated_frame, channels="BGR", use_container_width=True)
 
 
 
 
 
307
  cap.release()
308
  os.remove(tfile)
309
  st.success("Video processing complete!")
310
+ elif not model and uploaded_video:
311
+ st.warning("Model not loaded.")
 
 
312
 
313
  # ---------------- REPORTS ----------------
314
  elif menu == "Reports":
315
  st.markdown("## πŸ“‹ Reports")
316
  st.success("Weekly report generated successfully")
317
+ report_data = pd.DataFrame({
318
+ 'Date': pd.date_range(start='2026-04-01', periods=7),
319
+ 'Efficiency': [91, 92, 89, 94, 95, 93, 92],
320
+ 'Faults Detected': [2, 1, 4, 0, 1, 2, 1]
321
+ })
322
+ st.line_chart(report_data.set_index('Date'))
323
 
324
  # ---------------- ABOUT ----------------
325
  elif menu == "About Us":
326
  st.markdown("## 🌍 About SolarGuard")
327
+ st.write("SolarGuard AI is an advanced artificial intelligence platform designed to revolutionize solar energy monitoring and maintenance. Our system leverages state-of-the-art computer vision and deep learning models to automatically detect defects in solar panels such as dust accumulation, cracks, bird droppings, and electrical damage. By combining real-time image analysis, predictive maintenance, and intelligent reporting, SolarGuard helps solar farm operators increase efficiency, reduce maintenance costs and maximize energy output. Our mission is to make renewable energy systems smarter, safer, and more efficient through AI-driven automation and continuous learning.")
328
 
329
  # ---------------- CONTACT ----------------
330
  elif menu == "Contact":