Sanjayraju30 commited on
Commit
09497f1
·
verified ·
1 Parent(s): 0d1e7aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -129
app.py CHANGED
@@ -2,143 +2,98 @@ import random
2
  import pandas as pd
3
  import streamlit as st
4
  import pydeck as pdk
5
- from datetime import datetime, timedelta
6
 
7
- # ---- Constants ----
8
- POLES_PER_SITE = 12
9
- SITES = {
10
- "Hyderabad": [17.385044, 78.486671],
11
- "Gadwal": [16.2351, 77.8052],
12
- "Kurnool": [15.8281, 78.0373],
13
- "Ballari": [15.1394, 76.9214] # Corrected Ballari location
14
  }
15
 
16
- # ---- Helper Functions ----
17
- def simulate_pole(pole_id, site_name):
18
- lat, lon = SITES[site_name] # FIXED: Use constant location without random offset
19
- solar_kwh = round(random.uniform(3.0, 7.5), 2)
20
- wind_kwh = round(random.uniform(0.5, 2.0), 2)
21
- power_required = round(random.uniform(4.0, 8.0), 2)
22
- total_power = solar_kwh + wind_kwh
23
- power_status = 'Sufficient' if total_power >= power_required else 'Insufficient'
24
-
25
- tilt_angle = round(random.uniform(0, 45), 2)
26
- vibration = round(random.uniform(0, 5), 2)
27
- camera_status = random.choice(['Online', 'Offline'])
28
-
29
- alert_level = 'Green'
30
- anomaly_details = []
31
- if tilt_angle > 30 or vibration > 3:
32
- alert_level = 'Yellow'
33
- anomaly_details.append("Tilt or Vibration threshold exceeded.")
34
- if tilt_angle > 40 or vibration > 4.5:
35
- alert_level = 'Red'
36
- anomaly_details.append("Critical tilt or vibration detected.")
37
-
38
- health_score = max(0, 100 - (tilt_angle + vibration * 10))
39
- timestamp = datetime.now() - timedelta(hours=random.randint(0, 6))
40
 
41
- return {
42
- 'Pole ID': f'{site_name[:3].upper()}-{pole_id:03}',
43
- 'Site': site_name,
44
- 'Latitude': lat,
45
- 'Longitude': lon,
46
- 'Solar (kWh)': solar_kwh,
47
- 'Wind (kWh)': wind_kwh,
48
- 'Power Required (kWh)': power_required,
49
- 'Total Power (kWh)': total_power,
50
- 'Power Status': power_status,
51
- 'Tilt Angle (°)': tilt_angle,
52
- 'Vibration (g)': vibration,
53
- 'Camera Status': camera_status,
54
- 'Health Score': round(health_score, 2),
55
- 'Alert Level': alert_level,
56
- 'Anomalies': "; ".join(anomaly_details),
57
- 'Last Checked': timestamp.strftime('%Y-%m-%d %H:%M:%S')
58
- }
 
 
 
 
 
 
 
 
59
 
60
  # ---- Streamlit UI ----
61
- st.set_page_config(page_title="Smart Pole Monitoring", layout="wide")
62
- st.title("\U0001F30D Smart Renewable Pole Monitoring - Multi-Site")
63
-
64
- selected_site = st.text_input("Enter site to view (Hyderabad, Gadwal, Kurnool, Ballari):", "Hyderabad")
65
 
66
- if selected_site in SITES:
67
- with st.spinner(f"Simulating poles at {selected_site}..."):
68
- poles_data = [simulate_pole(i + 1, site) for site in SITES for i in range(POLES_PER_SITE)]
69
- df = pd.DataFrame(poles_data)
70
- site_df = df[df['Site'] == selected_site]
71
 
72
- # Summary Metrics
73
- col1, col2, col3 = st.columns(3)
74
- col1.metric("Total Poles", site_df.shape[0])
75
- col2.metric("Red Alerts", site_df[site_df['Alert Level'] == 'Red'].shape[0])
76
- col3.metric("Power Insufficiencies", site_df[site_df['Power Status'] == 'Insufficient'].shape[0])
77
 
78
- # Table View
79
- st.subheader(f"\U0001F4CB Pole Data Table for {selected_site}")
80
- with st.expander("Filter Options"):
81
- alert_filter = st.multiselect("Alert Level", options=site_df['Alert Level'].unique(), default=site_df['Alert Level'].unique())
82
- camera_filter = st.multiselect("Camera Status", options=site_df['Camera Status'].unique(), default=site_df['Camera Status'].unique())
83
 
84
- filtered_df = site_df[(site_df['Alert Level'].isin(alert_filter)) & (site_df['Camera Status'].isin(camera_filter))]
85
- st.dataframe(filtered_df, use_container_width=True)
86
-
87
- # Charts
88
- st.subheader("\U0001F4CA Energy Generation Comparison")
89
- st.bar_chart(site_df[['Solar (kWh)', 'Wind (kWh)']].mean())
90
-
91
- st.subheader("\U0001F4C8 Tilt vs. Vibration")
92
- st.scatter_chart(site_df[['Tilt Angle (°)', 'Vibration (g)']])
93
-
94
- # ---- Map Section with Tooltip ----
95
- st.subheader("\U0001F4CD Pole Alert Levels (Green, Yellow, Red)")
96
-
97
- def alert_level_to_color(alert_level):
98
- if alert_level == 'Red':
99
- return [255, 0, 0, 160]
100
- elif alert_level == 'Yellow':
101
- return [255, 255, 0, 160]
102
- else:
103
- return [0, 255, 0, 160]
104
-
105
- if not site_df.empty:
106
- site_df = site_df.copy()
107
- site_df['Color'] = site_df['Alert Level'].apply(alert_level_to_color)
108
-
109
- st.pydeck_chart(pdk.Deck(
110
- initial_view_state=pdk.ViewState(
111
- latitude=SITES[selected_site][0],
112
- longitude=SITES[selected_site][1],
113
- zoom=12,
114
- pitch=50
115
- ),
116
- layers=[
117
- pdk.Layer(
118
- 'ScatterplotLayer',
119
- data=site_df,
120
- get_position='[Longitude, Latitude]',
121
- get_color='Color',
122
- get_radius=100,
123
- pickable=True
124
- )
125
- ],
126
- tooltip={
127
- "html": "<b>Pole ID:</b> {Pole ID}<br/>"
128
- "<b>Health Score:</b> {Health Score}<br/>"
129
- "<b>Alert Level:</b> {Alert Level}<br/>"
130
- "<b>Power Status:</b> {Power Status}<br/>"
131
- "<b>Camera Status:</b> {Camera Status}<br/>"
132
- "<b>Last Checked:</b> {Last Checked}",
133
- "style": {
134
- "backgroundColor": "black",
135
- "color": "white"
136
- }
137
- }
138
- ))
139
 
140
- st.markdown("<h3 style='text-align: center;'>Click on a pole to view details</h3>", unsafe_allow_html=True)
141
- else:
142
- st.info("No poles data available for this site.")
143
- else:
144
- st.warning("Invalid site. Please enter one of: Hyderabad, Gadwal, Kurnool, Ballari")
 
2
  import pandas as pd
3
  import streamlit as st
4
  import pydeck as pdk
 
5
 
6
+ # ---- Fixed Coordinates for Specific Local Areas ----
7
+ AREA_COORDINATES = {
8
+ "Hyderabad": [17.4036, 78.5247], # Ramanthapur
9
+ "Ballari": [15.1468, 76.9237], # Cowl Bazar
10
+ "Gadwal": [16.2315, 77.7965], # Bheem Nagar
11
+ "Kurnool": [15.8281, 78.0373] # Venkata Ramana Colony
 
12
  }
13
 
14
+ POLES_PER_SITE = 12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # ---- Helper Function to Simulate Poles in a Tight Area ----
17
+ def generate_fixed_poles(site_name, center_lat, center_lon):
18
+ poles = []
19
+ for i in range(POLES_PER_SITE):
20
+ lat = center_lat + random.uniform(-0.001, 0.001)
21
+ lon = center_lon + random.uniform(-0.001, 0.001)
22
+ alert_level = random.choices(['Green', 'Yellow', 'Red'], weights=[6, 4, 2])[0]
23
+
24
+ poles.append({
25
+ "Pole ID": f"{site_name[:3].upper()}-{i+1:03}",
26
+ "Site": site_name,
27
+ "Latitude": lat,
28
+ "Longitude": lon,
29
+ "Alert Level": alert_level,
30
+ "Health Score": round(random.uniform(70, 100), 2),
31
+ "Power Status": random.choice(['Sufficient', 'Insufficient']),
32
+ "Camera Status": random.choice(['Online', 'Offline'])
33
+ })
34
+ return poles
35
+
36
+ # ---- Data Preparation ----
37
+ all_poles = []
38
+ for site, coords in AREA_COORDINATES.items():
39
+ all_poles.extend(generate_fixed_poles(site, *coords))
40
+
41
+ df = pd.DataFrame(all_poles)
42
 
43
  # ---- Streamlit UI ----
44
+ st.set_page_config(page_title="Localized Smart Pole View", layout="wide")
45
+ st.title("📍 Smart Pole Monitoring - Specific Neighborhood Areas")
 
 
46
 
47
+ site = st.selectbox("Select a site to view", list(AREA_COORDINATES.keys()))
 
 
 
 
48
 
49
+ # ---- Filtered View ----
50
+ filtered_df = df[df["Site"] == site]
 
 
 
51
 
52
+ # ---- Metrics ----
53
+ col1, col2, col3 = st.columns(3)
54
+ col1.metric("Total Poles", POLES_PER_SITE)
55
+ col2.metric("Red Alerts", filtered_df[filtered_df["Alert Level"] == "Red"].shape[0])
56
+ col3.metric("Offline Cameras", filtered_df[filtered_df["Camera Status"] == "Offline"].shape[0])
57
 
58
+ # ---- Map Color Mapping ----
59
+ def alert_color(alert):
60
+ return {
61
+ "Green": [0, 255, 0, 160],
62
+ "Yellow": [255, 255, 0, 160],
63
+ "Red": [255, 0, 0, 160]
64
+ }[alert]
65
+
66
+ filtered_df = filtered_df.copy()
67
+ filtered_df["Color"] = filtered_df["Alert Level"].apply(alert_color)
68
+
69
+ # ---- Map ----
70
+ st.pydeck_chart(pdk.Deck(
71
+ initial_view_state=pdk.ViewState(
72
+ latitude=AREA_COORDINATES[site][0],
73
+ longitude=AREA_COORDINATES[site][1],
74
+ zoom=15,
75
+ pitch=45
76
+ ),
77
+ layers=[
78
+ pdk.Layer(
79
+ "ScatterplotLayer",
80
+ data=filtered_df,
81
+ get_position='[Longitude, Latitude]',
82
+ get_color='Color',
83
+ get_radius=100,
84
+ pickable=True
85
+ )
86
+ ],
87
+ tooltip={
88
+ "html": "<b>Pole ID:</b> {Pole ID}<br/>"
89
+ "<b>Health Score:</b> {Health Score}<br/>"
90
+ "<b>Alert Level:</b> {Alert Level}<br/>"
91
+ "<b>Camera:</b> {Camera Status}<br/>"
92
+ "<b>Power:</b> {Power Status}",
93
+ "style": {"color": "white", "backgroundColor": "black"}
94
+ }
95
+ ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ # ---- Table View ----
98
+ st.subheader(f"📋 Pole Details in {site}")
99
+ st.dataframe(filtered_df, use_container_width=True)