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(""" """, 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(""" """, unsafe_allow_html=True) # ===== HEADER (رجعناه بشكل احترافي) ===== st.markdown("""
☀️ SolarGuard AI
Enterprise Solar Intelligence Platform
""", unsafe_allow_html=True) # ===== STATE ===== if "auth_mode" not in st.session_state: st.session_state.auth_mode = "login" # ===== MAIN GLASS ===== st.markdown('
', unsafe_allow_html=True) # ================= LOGIN ================= if st.session_state.auth_mode == "login": st.markdown('
🔐 Sign In
', 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('
✨ Create Account
', 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('
', unsafe_allow_html=True) # ================= WELCOME SCREEN ================= elif not st.session_state.entered_site: st.markdown('
☀️ SolarGuard AI
', unsafe_allow_html=True) st.markdown('
Enterprise Solar Intelligence Platform
', 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("
", 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('', unsafe_allow_html=True) st.sidebar.markdown('', 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('

Real-time fleet performance and KPI monitoring

', 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("
", 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('

Multi-spectrum defect detection on solar panel images

', 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('

Frame-by-frame AI inspection of uploaded surveillance footage

', 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('

Real-time AI defect detection via device camera

', 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'
' f'{snap["label"]}' f'{snap["time"]}
' f'Confidence: {snap["score"]:.1f}%' f'
', unsafe_allow_html=True ) st.image(snap["frame"], use_column_width=True) else: st.markdown( '
Start the camera to begin analysis
', 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'
' f'{label}' f'Confidence: {score:.1f}%' f'
', 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'
' f'{label}' f'Confidence: {score:.1f}%' f'
', unsafe_allow_html=True ) # ── 5. MAINTENANCE MAPPING ──────────────────────────────── elif menu == "Maintenance Location Mapping": st.markdown("## Maintenance Location Mapping") st.markdown('

Fleet dispatch, technician assignment, and GPS coordination

', 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('

Submit edge cases to improve detection accuracy

', 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('

Immutable performance history and compliance audit trail

', 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('

Carbon offset tracking and sustainability reporting

', 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('

AI-generated strategic performance summaries

', 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('

Enterprise-grade AI for solar asset management

', unsafe_allow_html=True) st.markdown('
', 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('
', unsafe_allow_html=True) # ── 11. CONTACT ─────────────────────────────────────────── elif menu == "Contact": st.markdown("## Contact & Support") st.markdown('

Reach our technical intelligence team

', 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.")