omarrama555 commited on
Commit
6adcbf9
ยท
verified ยท
1 Parent(s): 3e5f1db

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +14 -36
streamlit_app.py CHANGED
@@ -1,4 +1,3 @@
1
- %%writefile app.py
2
  import streamlit as st
3
  import pandas as pd
4
  import numpy as np
@@ -113,8 +112,13 @@ div[data-testid="stAlert"] div[data-testid="stMarkdownContainer"] p {
113
  # ================= MODEL =================
114
  @st.cache_resource
115
  def load_model():
116
- model_path = '/content/runs/detect/Solar_Fault_Detector/weights/best.pt'
117
- return YOLO(model_path) if os.path.exists(model_path) else None
 
 
 
 
 
118
 
119
  model = load_model()
120
 
@@ -182,8 +186,6 @@ if not st.session_state.logged_in:
182
  else:
183
  st.session_state.users[username_register] = password_register
184
  st.success("Registration successful! Please log in.")
185
- # In a real application, you would store this in a database
186
- # For example: save_user_to_database(username_register, password_register)
187
  st.markdown('</div>', unsafe_allow_html=True)
188
 
189
  # ================= LANDING =================
@@ -237,7 +239,7 @@ else:
237
  if files:
238
  cols = st.columns(min(len(files), 5))
239
  ir_cols = st.columns(min(len(files), 5))
240
- results_list = [] # Changed variable name to avoid conflict with `results` from model.predict
241
 
242
  for i, file in enumerate(files[:5]):
243
  img = Image.open(file)
@@ -262,11 +264,11 @@ else:
262
  score = 100
263
  else:
264
  label = model.names[int(res[0].boxes[0].cls[0])]
265
- # If a defect is detected, health score drops. Otherwise, high confidence of clean means high score.
266
  if label == 'Clean':
267
  score = float(res[0].boxes[0].conf[0]) * 100
268
  else:
269
- score = (1 - float(res[0].boxes[0].conf[0])) * 100 # Inverted for non-clean detections
 
270
  else:
271
  label = random.choice(["Clean", "Dust", "Crack", "Bird-Drop"])
272
  score = random.randint(75, 99)
@@ -292,8 +294,6 @@ else:
292
  use_container_width=True
293
  )
294
 
295
- # --- WhatsApp Messaging (Placeholder) ---
296
- st.markdown("### Send Results via WhatsApp")
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")
@@ -301,21 +301,6 @@ else:
301
 
302
  if st.button("Send WhatsApp Message", use_container_width=True):
303
  if phone_number:
304
- # In a real scenario, you would use an API client here.
305
- # Example with Twilio (requires installation and credentials):
306
- # from twilio.rest import Client
307
- # account_sid = os.environ.get("TWILIO_ACCOUNT_SID")
308
- # auth_token = os.environ.get("TWILIO_AUTH_TOKEN")
309
- # client = Client(account_sid, auth_token)
310
- # try:
311
- # message = client.messages.create(
312
- # from_='whatsapp:+14155238886', # Your Twilio WhatsApp number
313
- # body=whatsapp_message,
314
- # to=f'whatsapp:{phone_number}'
315
- # )
316
- # st.success(f"WhatsApp message sent to {phone_number} (SID: {message.sid})")
317
- # except Exception as e:
318
- # st.error(f"Failed to send WhatsApp message: {e}")
319
  st.success(f"Simulating WhatsApp message sent to {phone_number}.\n\nMessage Content:\n{whatsapp_message}")
320
  else:
321
  st.warning("Please enter a phone number.")
@@ -342,7 +327,6 @@ else:
342
  key="sl_label"
343
  )
344
  if st.button("Submit for Retraining Data", use_container_width=True):
345
- # In a real system, this would save the image and label to a dataset for future model retraining.
346
  st.success(f"Image '{uploaded_image_sl.name}' with label '{correct_label}' submitted for self-learning dataset.")
347
  st.info("This data will be used to improve the model in future updates.")
348
 
@@ -360,15 +344,10 @@ else:
360
 
361
  def recv(self, frame):
362
  img = frame.to_ndarray(format="bgr24")
363
-
364
- # Perform inference
365
  results = self.model.predict(img, conf=0.5, verbose=False)
366
-
367
- # Annotate the image
368
  annotated_img = img.copy()
369
  for r in results:
370
- annotated_img = r.plot() # YOLO's plot method returns annotated image
371
-
372
  return frame.from_ndarray(annotated_img, format="bgr24")
373
 
374
  webrtc_streamer(
@@ -385,7 +364,7 @@ else:
385
  ),
386
  )
387
  elif not WEBRTC_AVAILABLE:
388
- st.error("streamlit_webrtc library is not installed. Please install it using `!pip install streamlit-webrtc`.")
389
  else:
390
  st.info("Model not loaded or not available for live analysis.")
391
 
@@ -415,7 +394,6 @@ else:
415
  if not ret:
416
  break
417
 
418
- # Process frame with model
419
  results = model.predict(frame, conf=0.5, verbose=False)
420
  annotated_frame = frame.copy()
421
  for r in results:
@@ -425,7 +403,7 @@ else:
425
  frame_count += 1
426
 
427
  cap.release()
428
- os.remove(tfile) # Clean up temp file
429
  st.success("Video processing complete!")
430
  elif uploaded_video and not model:
431
  st.warning("Model is not loaded, cannot perform video analysis.")
@@ -440,7 +418,7 @@ else:
440
  # ---------------- ABOUT ----------------
441
  elif menu == "About Us":
442
  st.markdown("## ๐ŸŒ About SolarGuard")
443
- 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")
444
 
445
  # ---------------- CONTACT ----------------
446
  elif menu == "Contact":
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import numpy as np
 
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
 
 
186
  else:
187
  st.session_state.users[username_register] = password_register
188
  st.success("Registration successful! Please log in.")
 
 
189
  st.markdown('</div>', unsafe_allow_html=True)
190
 
191
  # ================= LANDING =================
 
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)
 
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)
 
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")
 
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.")
 
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
 
 
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(
 
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
 
 
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:
 
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.")
 
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":