SolarGuard-AI / src /streamlit_app.py
omarrama555's picture
Update src/streamlit_app.py
840dca1 verified
Raw History Blame Contribute Delete
46.2 kB
import streamlit as st import pandas as pd import numpy as np from ultralytics import YOLO from PIL import Image import datetime import os import random import cv2 import plotly.graph_objects as go import plotly.express as px from datetime import timedelta import time import torch import base64 import io os.environ['QT_QPA_PLATFORM'] = 'offscreen' os.environ['YOLO_VERBOSE'] = 'False' try: from streamlit_webrtc import webrtc_streamer, VideoTransformerBase, RTCConfiguration import av WEBRTC_AVAILABLE = True except ImportError: WEBRTC_AVAILABLE = False # ================= PAGE CONFIG ================= st.set_page_config( page_title=" SolarGuard AI — Enterprise Intelligence", page_icon="☀️", layout="wide", initial_sidebar_state="expanded" ) # ================= GLOBAL STYLE ================= st.markdown(""" <style> @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap'); html, body, [data-testid="stAppViewContainer"] { font-family: 'Inter', sans-serif; } /* ── Dark overlay on background ── */ [data-testid="stAppViewContainer"] { background-image: linear-gradient(rgba(4, 12, 24, 0.72), rgba(4, 12, 24, 0.72)), url("https://solar.com.ng/wp-content/uploads/2024/06/What-Factors-to-Consider-When-Choosing-Solar-Panels-in-Nigeria-750x375.webp"); background-size: cover; background-position: center; background-attachment: fixed; } /* ── All text defaults ── */ .main, .main p, .main span, .main div, .main label { color: #F0F4F8 !important; position: relative; z-index: 1; } /* ── Headings ── */ .main h1 { color: #FFFFFF !important; font-weight: 800; font-size: 2rem; letter-spacing: -0.5px; } .main h2 { color: #FFFFFF !important; font-weight: 700; font-size: 1.5rem; border-left: 4px solid #F59E0B; padding-left: 14px; margin-bottom: 6px; letter-spacing: -0.3px; } .main h3 { color: #E2E8F0 !important; font-weight: 600; font-size: 1.1rem; margin-bottom: 12px; } .main h4 { color: #CBD5E1 !important; font-weight: 600; } /* ── Subheader override ── */ [data-testid="stMarkdownContainer"] h2, [data-testid="stMarkdownContainer"] h3, [data-testid="stMarkdownContainer"] h4 { color: #FFFFFF !important; } /* ── Page subtitle tag ── */ .page-subtitle { color: #94A3B8 !important; font-size: 0.92rem; font-weight: 400; margin-top: -4px; margin-bottom: 28px; padding-left: 18px; } /* ── Glass card ── */ .glass-card { background: rgba(15, 23, 42, 0.60); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); border: 1px solid rgba(245, 158, 11, 0.18); border-radius: 16px; padding: 24px 28px; margin-bottom: 20px; } /* ── Metric cards ── */ div[data-testid="stMetric"] { background: rgba(15, 23, 42, 0.55); backdrop-filter: blur(16px); border: 1px solid rgba(245, 158, 11, 0.15); border-radius: 14px; padding: 18px 20px; } div[data-testid="stMetricLabel"] p { color: #94A3B8 !important; font-size: 0.78rem; font-weight: 500; text-transform: uppercase; letter-spacing: 0.8px; } div[data-testid="stMetricValue"] { color: #F59E0B !important; font-size: 1.9rem; font-weight: 800; } div[data-testid="stMetricDelta"] { color: #34D399 !important; font-size: 0.8rem; } /* ── Sidebar ── */ section[data-testid="stSidebar"] { background: rgba(7, 14, 28, 0.97) !important; border-right: 1px solid rgba(245, 158, 11, 0.12); } section[data-testid="stSidebar"] * { color: #CBD5E1 !important; } section[data-testid="stSidebar"] .stSelectbox label { color: #94A3B8 !important; font-size: 0.78rem; } /* ── Sidebar title ── */ .sidebar-brand { font-size: 1.25rem; font-weight: 800; color: #F59E0B !important; letter-spacing: -0.3px; margin-bottom: 2px; } .sidebar-edition { font-size: 0.72rem; color: #64748B !important; font-weight: 500; text-transform: uppercase; letter-spacing: 1.2px; margin-bottom: 20px; } /* ── Buttons ── */ .stButton > button { background: linear-gradient(135deg, #F59E0B, #D97706) !important; color: #0F172A !important; border: none !important; border-radius: 10px !important; padding: 10px 22px !important; font-weight: 700 !important; font-size: 0.85rem !important; letter-spacing: 0.3px !important; transition: all 0.25s ease !important; } .stButton > button:hover { background: linear-gradient(135deg, #FBBF24, #F59E0B) !important; box-shadow: 0 4px 20px rgba(245, 158, 11, 0.35) !important; transform: translateY(-1px) !important; } /* ── Download button ── */ .stDownloadButton > button { background: rgba(15, 23, 42, 0.7) !important; color: #F59E0B !important; border: 1px solid rgba(245, 158, 11, 0.4) !important; border-radius: 10px !important; font-weight: 600 !important; font-size: 0.83rem !important; } /* ── Input fields ── */ .stTextInput > div > div > input, .stTextArea > div > div > textarea { background: rgba(15, 23, 42, 0.6) !important; color: #F0F4F8 !important; border: 1px solid rgba(245, 158, 11, 0.2) !important; border-radius: 10px !important; } .stTextInput label, .stTextArea label, .stSelectbox label, .stDateInput label, .stFileUploader label { color: #94A3B8 !important; font-size: 0.8rem !important; font-weight: 500 !important; } /* ── Selectbox ── */ .stSelectbox > div > div { background: rgba(15, 23, 42, 0.6) !important; color: #F0F4F8 !important; border: 1px solid rgba(245, 158, 11, 0.2) !important; border-radius: 10px !important; } /* ── Alerts / info boxes ── */ .stSuccess, .stInfo, .stWarning, .stError { border-radius: 10px !important; } .stInfo > div { background: rgba(14, 165, 233, 0.12) !important; border-left: 3px solid #0EA5E9 !important; color: #E0F2FE !important; } .stSuccess > div { background: rgba(52, 211, 153, 0.12) !important; border-left: 3px solid #34D399 !important; color: #D1FAE5 !important; } .stWarning > div { background: rgba(251, 191, 36, 0.12) !important; border-left: 3px solid #FBBF24 !important; color: #FEF9C3 !important; } .stError > div { background: rgba(239, 68, 68, 0.12) !important; border-left: 3px solid #EF4444 !important; color: #FEE2E2 !important; } /* ── Dataframe / table ── */ .stDataFrame, .stTable { border-radius: 12px; overflow: hidden; } [data-testid="stDataFrameResizable"] { background: rgba(15, 23, 42, 0.5) !important; } /* ── Tabs ── */ .stTabs [data-baseweb="tab-list"] { background: rgba(15, 23, 42, 0.5); border-radius: 10px; } .stTabs [data-baseweb="tab"] { color: #94A3B8 !important; font-weight: 600; } .stTabs [aria-selected="true"] { color: #F59E0B !important; border-bottom: 2px solid #F59E0B; } /* ── Login hero ── */ .hero-title { text-align: center; font-size: 3.2rem; font-weight: 900; background: linear-gradient(135deg, #F59E0B, #FBBF24, #FDE68A); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; letter-spacing: -1px; margin-bottom: 6px; } .hero-subtitle { text-align: center; color: #94A3B8 !important; font-size: 1rem; font-weight: 400; margin-bottom: 36px; } /* ── Divider ── */ hr { border-color: rgba(245, 158, 11, 0.15) !important; } /* ── Scrollbar ── */ ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: rgba(0,0,0,0.1); } ::-webkit-scrollbar-thumb { background: #F59E0B; border-radius: 6px; } /* ── Progress bar ── */ .stProgress > div > div { background: linear-gradient(90deg, #F59E0B, #FBBF24) !important; } /* ── Spinner text ── */ .stSpinner > div { color: #F59E0B !important; } </style> """, unsafe_allow_html=True) # ================= EGYPT DATA ================= EGYPT_DATA = { "القاهرة": ["قسم أول مدينة نصر", "قسم ثاني مدينة نصر", "مصر الجديدة", "المعادي", "حلوان", "شبرا", "عين شمس"], "الجيزة": ["الدقي", "العجوزة", "الهرم", "فيصل", "6 أكتوبر", "الشيخ زايد", "البدرشين"], "الإسكندرية": ["المنتزة", "شرق", "وسط", "غرب", "الجمرك", "العجمي", "برج العرب"], "القليوبية": ["بنها", "قليوب", "شبرا الخيمة", "الخانكة", "كفر شكر", "طوخ"], "الدقهلية": ["المنصورة", "طلخا", "ميت غمر", "دكرنس", "السنبلاوين", "شربين"], "الشرقية": ["الزقازيق", "بلبيس", "منيا القمح", "أبو حماد", "فاقوس", "العاشر من رمضان"], "المنوفية": ["شبين الكوم", "قويسنا", "بركة السبع", "تلا", "الباجور", "أشمون"], "الغربية": ["طنطا", "المحلة الكبرى", "كفر الزيات", "زفتى", "بسيون", "سمنود"], "البحيرة": ["دمنهور", "كفر الدوار", "إيتاي البارود", "أبو حمص", "رشيد", "كوم حمادة"], "كفر الشيخ": ["كفر الشيخ", "دسوق", "فوه", "مطوبس", "بيلا", "الحامول"], "دمياط": ["دمياط", "فارسكور", "الزرقا", "كفر سعد", "رأس البر"], "بورسعيد": ["بورفؤاد", "الشرق", "العرب", "المناخ", "الضواحي"], "الإسماعيلية": ["الإسماعيلية", "التل الكبير", "فايد", "القنطرة شرق", "القنطرة غرب"], "السويس": ["السويس", "الأربعين", "عتاقة", "الجناين", "فيصل"], "الفيوم": ["الفيوم", "إطسا", "طامية", "سنورس", "يوسف الصديق"], "بني سويف": ["بني سويف", "الواسطى", "ناصر", "ببا", "الفشن", "سمسطا"], "المنيا": ["المنيا", "مغاغة", "بني مزار", "مطاي", "سمالوط", "ملوي"], "أسيوط": ["أسيوط", "ديروط", "القوصية", "منفلوط", "أبو تيج", "صدفا"], "سوهاج": ["سوهاج", "أخميم", "طهطا", "طما", "جرجا", "البلينا"], "قنا": ["قنا", "نجع حمادي", "دشنا", "أبو تشت", "قفط", "نقادة"], "الأقصر": ["الأقصر", "إسنا", "أرمنت", "القرنة"], "أسوان": ["أسوان", "كوم أمبو", "إدفو", "نصر النوبة"], "البحر الأحمر": ["الغردقة", "سفاجا", "القصير", "مرسى علم", "رأس غارب"], "الوادي الجديد": ["الخارجة", "الداخلة", "الفرافرة", "باريس"], "مطروح": ["مرسى مطروح", "العلمين", "الضبعة", "سيوة", "الحمام"], "شمال سيناء": ["العريش", "بئر العبد", "الشيخ زويد", "رفح"], "جنوب سيناء": ["شرم الشيخ", "طور سيناء", "دهب", "نويبع", "طابا"] } GOV_COORDS = { "القاهرة": (30.0444, 31.2357), "الجيزة": (30.0131, 31.2089), "الإسكندرية": (31.2001, 29.9187), "القليوبية": (30.4124, 31.1868), "الدقهلية": (31.0409, 31.3785), "الشرقية": (30.5877, 31.5020), "المنوفية": (30.5972, 30.9876), "الغربية": (30.7865, 31.0004), "البحيرة": (31.0364, 30.4631), "كفر الشيخ": (31.1107, 30.9388), "دمياط": (31.4175, 31.8144), "بورسعيد": (31.2653, 32.3019), "الإسماعيلية": (30.5965, 32.2715), "السويس": (29.9668, 32.5498), "الفيوم": (29.3084, 30.8428), "بني سويف": (29.0744, 31.0979), "المنيا": (28.0871, 30.7618), "أسيوط": (27.1783, 31.1859), "سوهاج": (26.5591, 31.6957), "قنا": (26.1551, 32.7160), "الأقصر": (25.6872, 32.6396), "أسوان": (24.0889, 32.8998), "البحر الأحمر": (27.2579, 33.8116), "الوادي الجديد": (25.4390, 30.5586), "مطروح": (31.3543, 27.2373), "شمال سيناء": (31.1321, 33.8033), "جنوب سيناء": (28.5000, 34.0000) } # ================= MODEL LOADING ================= _original_torch_load = torch.load def _patched_torch_load(f, map_location=None, pickle_module=None, weights_only=True, **kwargs): return _original_torch_load(f, map_location=map_location, weights_only=False, **kwargs) torch.load = _patched_torch_load @st.cache_resource def load_model(): model_path = 'best.pt' if not os.path.exists(model_path): return None try: return YOLO(model_path) except Exception as e: st.error(f"Model Load Error: {e}") return None model = load_model() # ================= HELPERS ================= def convert_to_infrared(image_pil): image_cv = np.array(image_pil) image_cv = cv2.cvtColor(image_cv, cv2.COLOR_RGB2BGR) gray = cv2.cvtColor(image_cv, cv2.COLOR_BGR2GRAY) ir = cv2.applyColorMap(gray, cv2.COLORMAP_JET) return Image.fromarray(cv2.cvtColor(ir, cv2.COLOR_BGR2RGB)) def generate_mock_data(days=30): dates = [datetime.datetime.now() - timedelta(days=x) for x in range(days)] return { 'date': dates, 'energy_output': np.random.uniform(80, 100, days), 'efficiency': np.random.uniform(85, 98, days), 'temperature': np.random.uniform(25, 45, days), 'panel_health': np.random.uniform(90, 100, days) } def run_yolo_on_image(img_pil): """Run YOLO on a PIL image. Returns (label, score, annotated_np).""" if model is None: label = random.choice(["Optimal", "Dust Accumulation", "Micro-Crack", "Surface Obstruction", "Hot Spot"]) score = random.randint(75, 99) return label, score, np.array(img_pil) temp_path = "temp_infer.jpg" img_pil.save(temp_path) res = model.predict(temp_path, conf=0.5, verbose=False) os.remove(temp_path) if len(res[0].boxes) == 0: label, score = "Optimal", 100 else: label = model.names[int(res[0].boxes[0].cls[0])] score = float(res[0].boxes[0].conf[0]) * 100 annotated = cv2.cvtColor(res[0].plot(), cv2.COLOR_BGR2RGB) return label, score, annotated def chart_layout(title=""): return dict( title=dict(text=title, font=dict(color="#E2E8F0", size=13, family="Inter")), template='plotly_dark', paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(15,23,42,0.4)', font=dict(color="#94A3B8", family="Inter"), xaxis=dict(gridcolor='rgba(255,255,255,0.05)', color='#64748B'), yaxis=dict(gridcolor='rgba(255,255,255,0.05)', color='#64748B'), margin=dict(l=10, r=10, t=40, b=10), hovermode='x unified' ) # ================= SESSION STATE ================= for key, val in [('logged_in', False), ('entered_site', False), ('users', {'admin': 'solar2026'}), ('alerts', []), ('captured_frames', [])]: if key not in st.session_state: st.session_state[key] = val # ================= LIVE CAMERA PROCESSOR ================= if WEBRTC_AVAILABLE: class SolarYOLOProcessor(VideoTransformerBase): def __init__(self): self.model = model self.frame_count = 0 self.capture_every = 30 # analyse every N frames self.last_label = "—" self.last_score = 0 def transform(self, frame): img_bgr = frame.to_ndarray(format="bgr24") self.frame_count += 1 if self.frame_count % self.capture_every == 0 and self.model: img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB) pil_img = Image.fromarray(img_rgb) label, score, annotated = run_yolo_on_image(pil_img) self.last_label = label self.last_score = score # store frame for snapshot display st.session_state.captured_frames.append({ "frame": annotated, "label": label, "score": score, "time": datetime.datetime.now().strftime("%H:%M:%S") }) if len(st.session_state.captured_frames) > 6: st.session_state.captured_frames.pop(0) img_bgr = cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR) # Overlay label on frame color = (52, 211, 153) if self.last_label == "Optimal" else (239, 68, 68) cv2.putText(img_bgr, f"{self.last_label} {self.last_score:.0f}%", (14, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.75, color, 2) return img_bgr # ================= LOGIN PAGE ================= # ================= LOGIN PAGE ================= if not st.session_state.logged_in: # ===== CSS ===== st.markdown(""" <style> .stApp { background: linear-gradient(135deg, #0f2027, #203a43, #2c5364); color: white; } /* Header */ .hero { text-align: center; margin-top: 30px; margin-bottom: 10px; } .hero-title { font-size: 36px; font-weight: 700; } .hero-subtitle { font-size: 15px; color: #cfd8dc; } /* Full width glass */ .glass-full { backdrop-filter: blur(18px); background: rgba(255, 255, 255, 0.06); border-radius: 20px; padding: 40px; margin: 20px auto; width: 85%; box-shadow: 0 8px 32px rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.1); } .section-title { font-size: 26px; font-weight: 600; margin-bottom: 20px; } .stTextInput input { border-radius: 10px !important; padding: 12px; border: 1px solid rgba(255,255,255,0.2); background: rgba(255,255,255,0.05); color: white; } .stButton button { border-radius: 12px; padding: 12px; font-weight: 600; background: linear-gradient(90deg, #00c6ff, #0072ff); color: white; border: none; } .stButton button:hover { transform: scale(1.02); transition: 0.2s; } </style> """, unsafe_allow_html=True) # ===== HEADER (رجعناه بشكل احترافي) ===== st.markdown(""" <div class="hero"> <div class="hero-title">☀️ SolarGuard AI</div> <div class="hero-subtitle">Enterprise Solar Intelligence Platform</div> </div> """, unsafe_allow_html=True) # ===== STATE ===== if "auth_mode" not in st.session_state: st.session_state.auth_mode = "login" # ===== MAIN GLASS ===== st.markdown('<div class="glass-full">', unsafe_allow_html=True) # ================= LOGIN ================= if st.session_state.auth_mode == "login": st.markdown('<div class="section-title">🔐 Sign In</div>', unsafe_allow_html=True) username_login = st.text_input("Username", key="username_login") password_login = st.text_input("Password", type="password", key="password_login") if st.button("Sign In", use_container_width=True): if username_login in st.session_state.users and st.session_state.users[username_login] == password_login: st.session_state.logged_in = True st.session_state.current_user = username_login st.success("Login successful!") st.rerun() else: st.error("Invalid credentials") if st.button("Don't have an account? Register"): st.session_state.auth_mode = "register" st.rerun() # ================= REGISTER ================= else: st.markdown('<div class="section-title">✨ Create Account</div>', unsafe_allow_html=True) username_register = st.text_input("Username", key="username_register") password_register = st.text_input("Password", type="password", key="password_register") confirm_password_register = st.text_input("Confirm Password", type="password", key="confirm_password_register") if st.button("Create Account", use_container_width=True): if not username_register or not password_register: st.warning("All fields are required.") elif username_register in st.session_state.users: st.error("Username already exists.") elif password_register != confirm_password_register: st.error("Passwords do not match.") else: st.session_state.users[username_register] = password_register st.success("Account created successfully!") st.session_state.auth_mode = "login" st.rerun() if st.button("Already have an account? Sign In"): st.session_state.auth_mode = "login" st.rerun() st.markdown('</div>', unsafe_allow_html=True) # ================= WELCOME SCREEN ================= elif not st.session_state.entered_site: st.markdown('<div class="hero-title">☀️ SolarGuard AI</div>', unsafe_allow_html=True) st.markdown('<div class="hero-subtitle">Enterprise Solar Intelligence Platform</div>', unsafe_allow_html=True) st.markdown("---") c1, c2, c3, c4 = st.columns(4) c1.metric("Active Farms", "245+") c2.metric("Detection Accuracy", "97%") c3.metric("Active Alerts", "12") c4.metric("Energy Efficiency Gain", "32%") st.markdown("<br>", unsafe_allow_html=True) col_a, col_b, col_c2 = st.columns([1, 1.2, 1]) with col_b: if st.button("Enter Dashboard", use_container_width=True): st.session_state.entered_site = True st.rerun() # ================= MAIN DASHBOARD ================= else: # ── Sidebar ── st.sidebar.markdown('<div class="sidebar-brand">SolarGuard AI</div>', unsafe_allow_html=True) st.sidebar.markdown('<div class="sidebar-edition">Enterprise Edition</div>', unsafe_allow_html=True) menu = st.sidebar.selectbox( "Navigation", [ "Global Operations Dashboard", "AI Panel Analysis", "Video Stream Analysis", "Live Camera Analysis", "Maintenance Location Mapping", "Model Retraining", "System Health Logs", "ESG & Environmental Impact", "Executive Reports", "About", "Contact" ] ) st.sidebar.markdown("---") if st.sidebar.button("Sign Out", use_container_width=True): st.session_state.logged_in = False st.session_state.entered_site = False st.rerun() # ── 1. DASHBOARD ────────────────────────────────────────── if menu == "Global Operations Dashboard": st.markdown("## Global Operations Dashboard") st.markdown('<p class="page-subtitle">Real-time fleet performance and KPI monitoring</p>', unsafe_allow_html=True) c1, c2, c3, c4 = st.columns(4) c1.metric("Total Energy Output", "12,450 kWh", "+5.2%") c2.metric("System Efficiency", "94.2%", "-0.3%") c3.metric("Avg Temperature", "32 °C", "+2 °C") c4.metric("Panel Health Index", "96.8%", "+1.2%") st.markdown("<br>", unsafe_allow_html=True) st.markdown("### Performance Analytics — Last 30 Days") data = generate_mock_data(30) df = pd.DataFrame(data) col1, col2 = st.columns(2) with col1: fig1 = go.Figure() fig1.add_trace(go.Scatter(x=df['date'], y=df['energy_output'], mode='lines+markers', name='Energy Output', line=dict(color='#F59E0B', width=2.5), marker=dict(size=4))) fig1.update_layout(**chart_layout("Energy Output (kWh)")) st.plotly_chart(fig1, use_container_width=True) with col2: fig2 = go.Figure() fig2.add_trace(go.Scatter(x=df['date'], y=df['efficiency'], mode='lines+markers', name='Efficiency', line=dict(color='#34D399', width=2.5), marker=dict(size=4))) fig2.update_layout(**chart_layout("System Efficiency (%)")) st.plotly_chart(fig2, use_container_width=True) st.markdown("### Strategic KPIs") k1, k2, k3 = st.columns(3) with k1: st.info("**Global ROI** — 18.5% Annualized Yield") with k2: st.success("**Operational Uptime** — 99.8% System Reliability") with k3: st.warning("**Efficiency Loss** — −0.3% Environmental Factors") # ── 2. AI PANEL ANALYSIS ────────────────────────────────── elif menu == "AI Panel Analysis": st.markdown("## AI Panel Analysis") st.markdown('<p class="page-subtitle">Multi-spectrum defect detection on solar panel images</p>', unsafe_allow_html=True) files = st.file_uploader("Upload panel images (up to 10)", type=['jpg', 'png', 'jpeg'], accept_multiple_files=True) if files: st.markdown("### Batch Scan Summary") s1, s2, s3, s4, s5 = st.columns(5) s1.metric("Total Assets", len(files)) s2.metric("Optimal Panels", f"{random.randint(7, 10)}") s3.metric("Anomalies Detected", f"{random.randint(0, 3)}") s4.metric("Aggregate Health", f"{random.randint(85, 98)}%") s5.metric("Processing Time", "1.8 s") results_list = [] n = min(len(files), 10) cols = st.columns(min(n, 5)) ir_cols = st.columns(min(n, 5)) for i, file in enumerate(files[:10]): file.seek(0) img = Image.open(file).convert("RGB") img_np = np.array(img) with cols[i % 5]: st.image(img_np, caption=f"Visual — {file.name}", use_column_width=True) infrared_np = np.array(convert_to_infrared(img).convert("RGB")) with ir_cols[i % 5]: st.image(infrared_np, caption=f"Thermal — {file.name}", use_column_width=True) label, score, annotated = run_yolo_on_image(img) results_list.append({ "Asset ID": f"SG-{i+1:03d}", "File": file.name, "Health Score": f"{round(score, 1)}%", "Diagnosis": label, "Risk Level": "Low" if score > 85 else "Elevated" if score > 70 else "Critical" }) st.markdown("### Asset Diagnostic Report") st.dataframe(pd.DataFrame(results_list), use_container_width=True) st.markdown("### Alert Dispatch") ac1, ac2 = st.columns(2) with ac1: wa = st.text_input("WhatsApp Number", placeholder="+201080520164") if st.button("Send WhatsApp Alert"): if wa: st.success(f"Report dispatched to {wa}") else: st.error("Enter a valid number.") with ac2: em = st.text_input("Email Address", placeholder="engineer@company.com") if st.button("Send Email Report"): if em: st.success(f"Report sent to {em}") else: st.error("Enter a valid email.") # ── 3. VIDEO STREAM ANALYSIS ────────────────────────────── elif menu == "Video Stream Analysis": st.markdown("## Video Stream Analysis") st.markdown('<p class="page-subtitle">Frame-by-frame AI inspection of uploaded surveillance footage</p>', unsafe_allow_html=True) uploaded_video = st.file_uploader("Upload video file", type=['mp4', 'avi', 'mov']) if uploaded_video: tfile = "temp_video.mp4" with open(tfile, "wb") as f: f.write(uploaded_video.getbuffer()) cap = cv2.VideoCapture(tfile) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = cap.get(cv2.CAP_PROP_FPS) or 25 duration = total_frames / fps st.info(f"Video loaded — {total_frames} frames / {duration:.1f}s at {fps:.0f} fps") st_frame = st.empty() progress_bar = st.progress(0) status_text = st.empty() bi1, bi2, bi3, bi4 = st.columns(4) metric_anom = bi1.empty() metric_hlth = bi2.empty() metric_chng = bi3.empty() metric_stab = bi4.empty() frame_count = anomalies_found = total_changes = prev_boxes = 0 health_scores = [] while cap.isOpened(): ret, frame = cap.read() if not ret: break current_anomalies = 0 if model: results = model.predict(frame, conf=0.4, verbose=False) annotated = results[0].plot() current_anomalies = len(results[0].boxes) else: annotated = frame if random.random() > 0.95: current_anomalies = random.randint(1, 3) if current_anomalies != prev_boxes: total_changes += 1 prev_boxes = current_anomalies anomalies_found = max(anomalies_found, current_anomalies) frame_rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB) st_frame.image(frame_rgb, use_column_width=True) frame_count += 1 progress_bar.progress(min(frame_count / total_frames, 1.0)) current_sec = frame_count / fps status_text.text(f"Processing {current_sec:.1f}s / {duration:.1f}s — Frame {frame_count}") current_health = max(100 - current_anomalies * 5, 0) health_scores.append(current_health) metric_anom.metric("Anomalies", current_anomalies) metric_hlth.metric("Frame Health", f"{current_health}%") metric_chng.metric("State Changes", total_changes) metric_stab.metric("Stability", "High" if current_health > 80 else "Critical") if frame_count >= 300: st.warning("Showing first 300 frames. Upgrade to full processing for complete analysis.") break cap.release() os.remove(tfile) st.success(f"Analysis complete — Peak anomalies: {anomalies_found} | State changes: {total_changes}") # ── 4. LIVE CAMERA ANALYSIS ─────────────────────────────── elif menu == "Live Camera Analysis": st.markdown("## Live Camera Analysis") st.markdown('<p class="page-subtitle">Real-time AI defect detection via device camera</p>', unsafe_allow_html=True) if WEBRTC_AVAILABLE: col_stream, col_results = st.columns([1.4, 1]) with col_stream: st.markdown("### Live Feed") st.info("Camera feed with automatic AI analysis every 30 frames. Detections are overlaid in real-time.") ctx = webrtc_streamer( key="solar_live", video_processor_factory=SolarYOLOProcessor, rtc_configuration=RTCConfiguration( {"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]} ), media_stream_constraints={"video": True, "audio": False}, ) with col_results: st.markdown("### Captured Detections") if st.session_state.captured_frames: for snap in reversed(st.session_state.captured_frames[-3:]): risk_color = "#34D399" if snap["label"] == "Optimal" else "#EF4444" st.markdown( f'<div style="border:1px solid {risk_color}33; border-radius:10px; padding:10px; margin-bottom:10px;">' f'<span style="color:{risk_color}; font-weight:700;">{snap["label"]}</span>' f'<span style="color:#64748B; font-size:0.8rem; float:right;">{snap["time"]}</span><br>' f'<span style="color:#94A3B8; font-size:0.85rem;">Confidence: {snap["score"]:.1f}%</span>' f'</div>', unsafe_allow_html=True ) st.image(snap["frame"], use_column_width=True) else: st.markdown( '<div style="color:#64748B; text-align:center; padding:40px 0;">Start the camera to begin analysis</div>', unsafe_allow_html=True ) if st.button("Clear Captured Frames"): st.session_state.captured_frames = [] st.rerun() st.markdown("---") st.markdown("### Single-Shot Capture") st.markdown("Alternatively, upload a still image from your camera for immediate analysis.") snap_file = st.file_uploader("Upload camera snapshot", type=['jpg', 'png', 'jpeg'], key="snap_upload") if snap_file: snap_file.seek(0) snap_img = Image.open(snap_file).convert("RGB") label, score, annotated = run_yolo_on_image(snap_img) risk_col = "#34D399" if label == "Optimal" else "#EF4444" sc1, sc2 = st.columns(2) with sc1: st.image(np.array(snap_img), caption="Original", use_column_width=True) with sc2: st.image(annotated, caption=f"Detection Result", use_column_width=True) st.markdown( f'<div style="border:1px solid {risk_col}44; border-radius:12px; padding:16px; margin-top:12px;">' f'<span style="color:{risk_col}; font-size:1.2rem; font-weight:800;">{label}</span>' f'<span style="color:#94A3B8; margin-left:16px;">Confidence: {score:.1f}%</span>' f'</div>', unsafe_allow_html=True ) else: st.error("streamlit-webrtc is not available. Ensure it is installed and the environment supports WebRTC.") st.markdown("### Single-Shot Camera Analysis") st.markdown("Upload an image from your camera or device for AI analysis.") snap_file = st.file_uploader("Upload image", type=['jpg', 'png', 'jpeg'], key="snap_upload_fallback") if snap_file: snap_file.seek(0) snap_img = Image.open(snap_file).convert("RGB") label, score, annotated = run_yolo_on_image(snap_img) risk_col = "#34D399" if label == "Optimal" else "#EF4444" sc1, sc2 = st.columns(2) with sc1: st.image(np.array(snap_img), caption="Original", use_column_width=True) with sc2: st.image(annotated, caption="Detection Result", use_column_width=True) st.markdown( f'<div style="border:1px solid {risk_col}44; border-radius:12px; padding:16px; margin-top:12px;">' f'<span style="color:{risk_col}; font-size:1.2rem; font-weight:800;">{label}</span>' f'<span style="color:#94A3B8; margin-left:16px;">Confidence: {score:.1f}%</span>' f'</div>', unsafe_allow_html=True ) # ── 5. MAINTENANCE MAPPING ──────────────────────────────── elif menu == "Maintenance Location Mapping": st.markdown("## Maintenance Location Mapping") st.markdown('<p class="page-subtitle">Fleet dispatch, technician assignment, and GPS coordination</p>', unsafe_allow_html=True) col1, col2 = st.columns([1, 1]) with col1: st.markdown("### Target Selection") gov = st.selectbox("Governorate", list(EGYPT_DATA.keys())) center = st.selectbox("District / Center", EGYPT_DATA[gov]) address = st.text_input("Street Address or Landmark") st.markdown("---") st.markdown("### Maintenance Details") m_type = st.selectbox("Maintenance Type", ["Routine Cleaning", "Inverter Repair", "Panel Replacement", "Structural Reinforcement", "Emergency Diagnostic"]) priority = st.select_slider("Priority Level", options=["Low", "Medium", "High", "Critical"]) scheduled_date = st.date_input("Scheduled Date", datetime.date.today() + datetime.timedelta(days=1)) technician = st.selectbox("Assign Technician", ["Eng. Ahmed Ali", "Eng. Sarah Hassan", "Eng. Mohamed Ibrahim", "Eng. Mahmoud Zayed"]) with col2: st.markdown("### Site Map") lat, lon = GOV_COORDS.get(gov, (26.8206, 30.8025)) c_lat = lat + random.uniform(-0.05, 0.05) c_lon = lon + random.uniform(-0.05, 0.05) map_data = pd.DataFrame({ 'lat': [c_lat, c_lat+0.02, c_lat-0.02, c_lat+0.01], 'lon': [c_lon, c_lon+0.01, c_lon-0.01, c_lon+0.03], }) st.map(map_data, zoom=11) st.success(f"GPS: {c_lat:.4f}, {c_lon:.4f}") st.info(f"3 technicians active in {center} area.") st.warning(f"Local Temperature: {random.randint(28, 42)} °C — Heat safety protocol advised.") st.markdown("---") if st.button("Generate Work Order & Dispatch", use_container_width=True): with st.spinner("Synchronizing with ERP..."): time.sleep(1.2) st.success(f"Work Order #SG-2026-{random.randint(1000, 9999)} created — {m_type} at {center}, {gov} — Assigned to {technician}") st.download_button("Download Work Order", data=b"Work Order Content", file_name=f"WO_{gov}_{center}.pdf") # ── 6. MODEL RETRAINING ─────────────────────────────────── elif menu == "Model Retraining": st.markdown("## Model Retraining") st.markdown('<p class="page-subtitle">Submit edge cases to improve detection accuracy</p>', unsafe_allow_html=True) uploaded_image = st.file_uploader("Upload edge case image", type=['jpg', 'png', 'jpeg']) if uploaded_image: img_edge = Image.open(uploaded_image).convert("RGB") st.image(np.array(img_edge), caption="Submitted Image", use_column_width=True) correct_label = st.selectbox("Correct Label", ["Optimal", "Dust Accumulation", "Structural Crack", "Obstruction", "Thermal Anomaly"]) if st.button("Submit to Training Dataset"): st.success("Image committed. Model will be updated in the next training cycle.") st.markdown("### Model Performance") perf = pd.DataFrame({ "Metric": ["Accuracy", "Precision", "Recall", "F1-Score"], "Current": ["98.4%", "97.8%", "98.1%", "97.9%"], "Previous": ["97.2%", "96.8%", "97.5%", "97.1%"] }) st.dataframe(perf, use_container_width=True) # ── 7. SYSTEM HEALTH LOGS ───────────────────────────────── elif menu == "System Health Logs": st.markdown("## System Health Logs") st.markdown('<p class="page-subtitle">Immutable performance history and compliance audit trail</p>', unsafe_allow_html=True) data = generate_mock_data(60) df = pd.DataFrame(data) fig = px.line(df, x='date', y='panel_health', color_discrete_sequence=['#F59E0B']) fig.update_layout(**chart_layout("Fleet Panel Health — 60-Day Horizon")) st.plotly_chart(fig, use_container_width=True) st.markdown("### Audit Trail") log = pd.DataFrame({ "Timestamp": ["2024-04-10", "2024-04-05", "2024-03-28", "2024-03-15"], "Operation": ["Routine Cleaning", "Structural Repair", "Fleet Inspection", "Routine Cleaning"], "Assets Affected": [45, 8, 500, 120], "Duration": ["2h", "4h", "8h", "1.5h"], "Compliance": ["Verified", "Verified", "Verified", "Verified"] }) st.dataframe(log, use_container_width=True) # ── 8. ESG ──────────────────────────────────────────────── elif menu == "ESG & Environmental Impact": st.markdown("## ESG & Environmental Impact") st.markdown('<p class="page-subtitle">Carbon offset tracking and sustainability reporting</p>', unsafe_allow_html=True) e1, e2, e3 = st.columns(3) e1.metric("CO₂ Offset (YTD)", "2,450 Tons", "+12.5%") e2.metric("Reforestation Equivalent", "40,800 Trees", "+12.5%") e3.metric("Fossil Fuel Avoided", "1,225 Barrels", "+12.5%") env_data = pd.DataFrame({ "Month": ["Jan", "Feb", "Mar", "Apr"], "CO₂ Avoided (tons)": [580, 620, 650, 600], "Green Energy (MWh)": [1200, 1350, 1450, 1380] }) fig = px.bar(env_data, x='Month', y=['CO₂ Avoided (tons)', 'Green Energy (MWh)'], barmode='group', color_discrete_sequence=['#F59E0B', '#34D399']) fig.update_layout(**chart_layout("Sustainability Metrics by Month")) st.plotly_chart(fig, use_container_width=True) # ── 9. EXECUTIVE REPORTS ────────────────────────────────── elif menu == "Executive Reports": st.markdown("## Executive Reports") st.markdown('<p class="page-subtitle">AI-generated strategic performance summaries</p>', unsafe_allow_html=True) r1, r2, r3 = st.columns(3) r1.metric("Weekly Revenue Yield", "$45,230", "+8.2%") r2.metric("Operational Continuity", "99.8%") r3.metric("Resolution Efficiency", "100%") st.markdown("### Enterprise Scorecard") scorecard = pd.DataFrame({ "KPI": ["Energy Yield", "System Efficiency", "Asset Integrity", "Network Uptime", "Stakeholder Satisfaction"], "Benchmark": ["1,400 kWh", "95%", "95%", "99.5%", "95%"], "Actual": ["1,380 kWh", "94.2%", "96.8%", "99.8%", "98.5%"], "Status": ["Pass", "Pass", "Pass", "Pass", "Pass"] }) st.dataframe(scorecard, use_container_width=True) d1, d2, d3 = st.columns(3) with d1: st.download_button("Export PDF Brief", data=b"PDF", file_name="executive_report.pdf") with d2: st.download_button("Export Excel Ledger", data=b"Excel", file_name="executive_report.xlsx") with d3: if st.button("Dispatch to Stakeholders"): st.success("Report transmitted to executive board.") # ── 10. ABOUT ───────────────────────────────────────────── elif menu == "About": st.markdown("## About SolarGuard AI") st.markdown('<p class="page-subtitle">Enterprise-grade AI for solar asset management</p>', unsafe_allow_html=True) st.markdown('<div class="glass-card">', unsafe_allow_html=True) st.markdown(""" SolarGuard AI is an enterprise-grade intelligence platform engineered for solar energy asset management. By integrating computer vision, predictive analytics, and real-time monitoring, it delivers actionable insights across entire solar fleets. **Core Capabilities** - **Precision Monitoring** — Continuous asset tracking and health diagnostics across distributed fleets. - **AI Defect Detection** — YOLOv8-powered detection of dust, cracks, obstructions, and thermal anomalies. - **Predictive Maintenance** — Machine learning-driven forecasting to prevent downtime before it occurs. - **ESG Reporting** — Integrated environmental impact quantification and carbon credit tracking. - **Executive Intelligence** — Automated performance reporting for board-level decision making. **Contact** - Email: omarramadan88888888g@gmail.com - Phone: +201080520164 """) st.markdown('</div>', unsafe_allow_html=True) # ── 11. CONTACT ─────────────────────────────────────────── elif menu == "Contact": st.markdown("## Contact & Support") st.markdown('<p class="page-subtitle">Reach our technical intelligence team</p>', unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: name = st.text_input("Full Name") email = st.text_input("Email Address") phone = st.text_input("Phone Number") with col2: subject = st.selectbox("Inquiry Type", ["Technical Support", "Strategic Partnership", "Enterprise Sales", "General Feedback"]) priority = st.select_slider("Priority", options=["Standard", "Elevated", "Critical"]) message = st.text_area("Message", height=138) if st.button("Send Message", use_container_width=True): if name and email and message: st.success("Message sent. Our team will respond within 12 business hours.") else: st.error("Please fill in all required fields.")
import streamlit as st
import pandas as pd
import numpy as np
from ultralytics import YOLO
from PIL import Image
import datetime
import os
import random
import cv2
import plotly.graph_objects as go
import plotly.express as px
from datetime import timedelta
import time
import torch
import base64
import io
os.environ['QT_QPA_PLATFORM'] = 'offscreen'
os.environ['YOLO_VERBOSE'] = 'False'
try:
from streamlit_webrtc import webrtc_streamer, VideoTransformerBase, RTCConfiguration
import av
WEBRTC_AVAILABLE = True
except ImportError:
WEBRTC_AVAILABLE = False
# ================= PAGE CONFIG =================
st.set_page_config(
page_title=" SolarGuard AI — Enterprise Intelligence",
page_icon="☀️",
layout="wide",
initial_sidebar_state="expanded"
)
# ================= GLOBAL STYLE =================
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
html, body, [data-testid="stAppViewContainer"] {
font-family: 'Inter', sans-serif;
}
/* ── Dark overlay on background ── */
[data-testid="stAppViewContainer"] {
background-image:
linear-gradient(rgba(4, 12, 24, 0.72), rgba(4, 12, 24, 0.72)),
url("https://solar.com.ng/wp-content/uploads/2024/06/What-Factors-to-Consider-When-Choosing-Solar-Panels-in-Nigeria-750x375.webp");
background-size: cover;
background-position: center;
background-attachment: fixed;
}
/* ── All text defaults ── */
.main, .main p, .main span, .main div, .main label {
color: #F0F4F8 !important;
position: relative;
z-index: 1;
}
/* ── Headings ── */
.main h1 { color: #FFFFFF !important; font-weight: 800; font-size: 2rem; letter-spacing: -0.5px; }
.main h2 {
color: #FFFFFF !important;
font-weight: 700;
font-size: 1.5rem;
border-left: 4px solid #F59E0B;
padding-left: 14px;
margin-bottom: 6px;
letter-spacing: -0.3px;
}
.main h3 {
color: #E2E8F0 !important;
font-weight: 600;
font-size: 1.1rem;
margin-bottom: 12px;
}
.main h4 { color: #CBD5E1 !important; font-weight: 600; }
/* ── Subheader override ── */
[data-testid="stMarkdownContainer"] h2,
[data-testid="stMarkdownContainer"] h3,
[data-testid="stMarkdownContainer"] h4 {
color: #FFFFFF !important;
}
/* ── Page subtitle tag ── */
.page-subtitle {
color: #94A3B8 !important;
font-size: 0.92rem;
font-weight: 400;
margin-top: -4px;
margin-bottom: 28px;
padding-left: 18px;
}
/* ── Glass card ── */
.glass-card {
background: rgba(15, 23, 42, 0.60);