KB-Infinity-Tech commited on
Commit
819869c
Β·
verified Β·
1 Parent(s): 099d46e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +459 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,461 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import plotly.graph_objects as go
3
+ import pandas as pd
4
+
5
+ # ── Page config ───────────────────────────────────────────────────────────────
6
+ st.set_page_config(
7
+ page_title="T2.3 Β· Grid Outage Forecaster",
8
+ page_icon="⚑",
9
+ layout="wide",
10
+ )
11
+
12
+ # ── Custom CSS ─────────────────────────────────────────────────────────────────
13
+ st.markdown("""
14
+ <style>
15
+ [data-testid="stAppViewContainer"] { background: #0f1117; color: #e8eaf6; }
16
+ [data-testid="stSidebar"] { background: #1a1d27; }
17
+ .metric-card {
18
+ background: #1a1d27; border: 1px solid #2e3350; border-radius: 10px;
19
+ padding: 14px 18px; text-align: center;
20
+ }
21
+ .metric-val { font-size: 1.6rem; font-weight: 800; color: #6366f1; }
22
+ .metric-lbl { font-size: 11px; color: #8892b0; text-transform: uppercase; letter-spacing: .05em; }
23
+ .badge {
24
+ display: inline-block; padding: 2px 8px; border-radius: 4px;
25
+ font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .05em;
26
+ }
27
+ .badge-high { background: #7f1d1d; color: #fca5a5; }
28
+ .badge-medium { background: #78350f; color: #fcd34d; }
29
+ .badge-low { background: #14532d; color: #86efac; }
30
+ .badge-on { background: #14532d; color: #86efac; }
31
+ .badge-off { background: #3f3f46; color: #a1a1aa; }
32
+ .badge-critical{ background: #1e3a8a; color: #93c5fd; }
33
+ .badge-comfort { background: #4a1d96; color: #c4b5fd; }
34
+ .badge-luxury { background: #374151; color: #9ca3af; }
35
+ .ap-card {
36
+ background: #1a1d27; border: 1px solid #2e3350; border-radius: 8px;
37
+ padding: 12px 14px; margin-bottom: 8px;
38
+ }
39
+ .ap-card.off { opacity: .6; border-color: #3f3f46; }
40
+ .ap-name { font-weight: 600; font-size: 14px; color: #e8eaf6; margin-bottom: 4px; }
41
+ .ap-meta { display: flex; gap: 6px; margin-bottom: 4px; }
42
+ .ap-shed { font-size: 10px; color: #9ca3af; margin-top: 3px; }
43
+ .ap-right { text-align: right; font-size: 12px; color: #8892b0; }
44
+ .ap-rev { color: #22c55e; font-weight: 600; font-size: 13px; }
45
+ .sms-box {
46
+ background: #22263a; border: 1px solid #2e3350; border-radius: 8px;
47
+ padding: 14px; margin-bottom: 10px; font-family: monospace; font-size: 13px;
48
+ line-height: 1.6; color: #e8eaf6;
49
+ }
50
+ .plan-header {
51
+ background: #1a1d27; border: 1px solid #2e3350; border-radius: 8px;
52
+ padding: 12px 16px; margin-bottom: 12px;
53
+ }
54
+ .section-title { font-size: 1rem; font-weight: 600; color: #e8eaf6; margin-bottom: 10px; }
55
+ h1, h2, h3 { color: #e8eaf6 !important; }
56
+ .stSelectbox label, .stSlider label { color: #8892b0 !important; }
57
+ div[data-testid="metric-container"] {
58
+ background: #1a1d27; border: 1px solid #2e3350; border-radius: 8px; padding: 8px;
59
+ }
60
+ </style>
61
+ """, unsafe_allow_html=True)
62
+
63
+ # ── Embedded Data ─────────────────────────────────────────────────────────────
64
+ FORECAST = [
65
+ {"hour_offset":0,"timestamp":"2024-06-29 00:00","hour":0,"p_outage":0.2708,"p_outage_low":0.1908,"p_outage_high":0.3508,"expected_duration_min":89.8,"risk_level":"HIGH"},
66
+ {"hour_offset":1,"timestamp":"2024-06-29 01:00","hour":1,"p_outage":0.2554,"p_outage_low":0.1754,"p_outage_high":0.3354,"expected_duration_min":83.2,"risk_level":"HIGH"},
67
+ {"hour_offset":2,"timestamp":"2024-06-29 02:00","hour":2,"p_outage":0.2169,"p_outage_low":0.1369,"p_outage_high":0.2969,"expected_duration_min":85.0,"risk_level":"MEDIUM"},
68
+ {"hour_offset":3,"timestamp":"2024-06-29 03:00","hour":3,"p_outage":0.2554,"p_outage_low":0.1754,"p_outage_high":0.3354,"expected_duration_min":85.0,"risk_level":"HIGH"},
69
+ {"hour_offset":4,"timestamp":"2024-06-29 04:00","hour":4,"p_outage":0.2602,"p_outage_low":0.1802,"p_outage_high":0.3402,"expected_duration_min":78.8,"risk_level":"HIGH"},
70
+ {"hour_offset":5,"timestamp":"2024-06-29 05:00","hour":5,"p_outage":0.2503,"p_outage_low":0.1703,"p_outage_high":0.3303,"expected_duration_min":85.0,"risk_level":"HIGH"},
71
+ {"hour_offset":6,"timestamp":"2024-06-29 06:00","hour":6,"p_outage":0.24, "p_outage_low":0.16, "p_outage_high":0.32, "expected_duration_min":83.2,"risk_level":"MEDIUM"},
72
+ {"hour_offset":7,"timestamp":"2024-06-29 07:00","hour":7,"p_outage":0.2208,"p_outage_low":0.1408,"p_outage_high":0.3008,"expected_duration_min":78.5,"risk_level":"MEDIUM"},
73
+ {"hour_offset":8,"timestamp":"2024-06-29 08:00","hour":8,"p_outage":0.2208,"p_outage_low":0.1408,"p_outage_high":0.3008,"expected_duration_min":78.5,"risk_level":"MEDIUM"},
74
+ {"hour_offset":9,"timestamp":"2024-06-29 09:00","hour":9,"p_outage":0.198, "p_outage_low":0.118, "p_outage_high":0.278, "expected_duration_min":86.0,"risk_level":"MEDIUM"},
75
+ {"hour_offset":10,"timestamp":"2024-06-29 10:00","hour":10,"p_outage":0.24, "p_outage_low":0.16, "p_outage_high":0.32, "expected_duration_min":71.3,"risk_level":"MEDIUM"},
76
+ {"hour_offset":11,"timestamp":"2024-06-29 11:00","hour":11,"p_outage":0.2531,"p_outage_low":0.1731,"p_outage_high":0.3331,"expected_duration_min":73.1,"risk_level":"HIGH"},
77
+ {"hour_offset":12,"timestamp":"2024-06-29 12:00","hour":12,"p_outage":0.2457,"p_outage_low":0.1657,"p_outage_high":0.3257,"expected_duration_min":76.9,"risk_level":"MEDIUM"},
78
+ {"hour_offset":13,"timestamp":"2024-06-29 13:00","hour":13,"p_outage":0.263, "p_outage_low":0.183, "p_outage_high":0.343, "expected_duration_min":68.8,"risk_level":"HIGH"},
79
+ {"hour_offset":14,"timestamp":"2024-06-29 14:00","hour":14,"p_outage":0.2582,"p_outage_low":0.1782,"p_outage_high":0.3382,"expected_duration_min":72.5,"risk_level":"HIGH"},
80
+ {"hour_offset":15,"timestamp":"2024-06-29 15:00","hour":15,"p_outage":0.2194,"p_outage_low":0.1394,"p_outage_high":0.2994,"expected_duration_min":76.9,"risk_level":"MEDIUM"},
81
+ {"hour_offset":16,"timestamp":"2024-06-29 16:00","hour":16,"p_outage":0.2688,"p_outage_low":0.1888,"p_outage_high":0.3488,"expected_duration_min":83.4,"risk_level":"HIGH"},
82
+ {"hour_offset":17,"timestamp":"2024-06-29 17:00","hour":17,"p_outage":0.309, "p_outage_low":0.229, "p_outage_high":0.389, "expected_duration_min":84.6,"risk_level":"HIGH"},
83
+ {"hour_offset":18,"timestamp":"2024-06-29 18:00","hour":18,"p_outage":0.3353,"p_outage_low":0.2553,"p_outage_high":0.4153,"expected_duration_min":84.6,"risk_level":"HIGH"},
84
+ {"hour_offset":19,"timestamp":"2024-06-29 19:00","hour":19,"p_outage":0.3408,"p_outage_low":0.2608,"p_outage_high":0.4208,"expected_duration_min":76.1,"risk_level":"HIGH"},
85
+ {"hour_offset":20,"timestamp":"2024-06-29 20:00","hour":20,"p_outage":0.3353,"p_outage_low":0.2553,"p_outage_high":0.4153,"expected_duration_min":99.4,"risk_level":"HIGH"},
86
+ {"hour_offset":21,"timestamp":"2024-06-29 21:00","hour":21,"p_outage":0.3466,"p_outage_low":0.2666,"p_outage_high":0.4266,"expected_duration_min":100.6,"risk_level":"HIGH"},
87
+ {"hour_offset":22,"timestamp":"2024-06-29 22:00","hour":22,"p_outage":0.2834,"p_outage_low":0.2034,"p_outage_high":0.3634,"expected_duration_min":102.5,"risk_level":"HIGH"},
88
+ {"hour_offset":23,"timestamp":"2024-06-29 23:00","hour":23,"p_outage":0.2596,"p_outage_low":0.1796,"p_outage_high":0.3396,"expected_duration_min":106.9,"risk_level":"HIGH"},
89
+ ]
90
+
91
+ SMS = [
92
+ "UMURIRO FORECAST 24H: Risk=HIGH at 0h,1h,3h. Shed: Standing+TV. Est.save: 12,418RWF. Stay alert!",
93
+ "PLAN: Turn OFF Standing+TV during risk hrs (0h,1h,3h). Keep dryer+clippers+lights ON. Generator ready?",
94
+ "If no signal by 13h, use YESTERDAY plan. Risk valid 6h. Call 0788-GRID for live update. Good business!",
95
+ ]
96
+
97
+ # ── Appliance plan generators ─────────────────────────────────────────────────
98
+ def salon_appliances(hour, risk):
99
+ open_ = 7 <= hour <= 20
100
+ peak = 9 <= hour <= 17
101
+ scale = 1.0 if peak else (0.75 if open_ else 0.0)
102
+ if not open_:
103
+ return [
104
+ {"name":"Hair Dryer (2Γ—)", "category":"critical","state":"OFF","watts":2400,"revenue_rwf":0,"shed_reason":"Business closed"},
105
+ {"name":"Electric Clippers (3Γ—)","category":"critical","state":"OFF","watts":120, "revenue_rwf":0,"shed_reason":"Business closed"},
106
+ {"name":"LED Lights", "category":"critical","state":"ON", "watts":20, "revenue_rwf":0},
107
+ {"name":"Standing Fan", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
108
+ {"name":"TV / Display", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
109
+ {"name":"Music System", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
110
+ {"name":"Neon Sign", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
111
+ ]
112
+ shed_lux = risk in ("HIGH","MEDIUM")
113
+ shed_com = risk == "HIGH"
114
+ return [
115
+ {"name":"Hair Dryer (2Γ—)", "category":"critical","state":"ON", "watts":2400,"revenue_rwf":round(2133*scale)},
116
+ {"name":"Electric Clippers (3Γ—)","category":"critical","state":"ON", "watts":120, "revenue_rwf":round(1422*scale)},
117
+ {"name":"LED Lights", "category":"critical","state":"ON", "watts":80, "revenue_rwf":round(711*scale)},
118
+ {"name":"Standing Fan", "category":"comfort","state":"OFF" if shed_com else "ON","watts":0 if shed_com else 75, "revenue_rwf":0 if shed_com else round(285*scale), **({"shed_reason":"HIGH risk β€” comfort shed"} if shed_com else {})},
119
+ {"name":"TV / Display", "category":"comfort","state":"OFF" if shed_com else "ON","watts":0 if shed_com else 150,"revenue_rwf":0 if shed_com else round(142*scale), **({"shed_reason":"HIGH risk β€” comfort shed"} if shed_com else {})},
120
+ {"name":"Music System", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 80, "revenue_rwf":0, **({"shed_reason":"Risk β‰₯ MEDIUM β€” luxury shed"} if shed_lux else {})},
121
+ {"name":"Neon Sign", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 40, "revenue_rwf":0, **({"shed_reason":"Risk β‰₯ MEDIUM β€” luxury shed"} if shed_lux else {})},
122
+ ]
123
+
124
+ def cold_appliances(hour, risk):
125
+ open_ = 6 <= hour <= 20
126
+ peak = 8 <= hour <= 18
127
+ scale = 1.0 if peak else (0.6 if open_ else 0.0)
128
+ fridge_rev = round(1850*scale) if open_ else 0
129
+ pump_rev = round(1100*scale) if open_ else 0
130
+ light_rev = round(740*scale) if open_ else 0
131
+ fan_rev = round(296*scale) if open_ else 0
132
+ tv_rev = round(148*scale) if open_ else 0
133
+ shed_com = risk == "HIGH"
134
+ shed_fan = shed_com or not open_
135
+ shed_tv = shed_com or not open_
136
+ return [
137
+ {"name":"Commercial Refrigerator","category":"critical","state":"ON", "watts":350,"revenue_rwf":fridge_rev or 200,**({"shed_reason":"After-hours β€” standby mode"} if not open_ else {})},
138
+ {"name":"Water Pump", "category":"critical","state":"ON" if open_ else "OFF","watts":750 if open_ else 0,"revenue_rwf":pump_rev, **({"shed_reason":"After-hours β€” pump off"} if not open_ else {})},
139
+ {"name":"LED Lights", "category":"critical","state":"ON" if open_ else "OFF","watts":80 if open_ else 0,"revenue_rwf":light_rev,**({"shed_reason":"After-hours β€” lights off"} if not open_ else {})},
140
+ {"name":"Standing Fan", "category":"comfort", "state":"OFF" if shed_fan else "ON","watts":0 if shed_fan else 75, "revenue_rwf":0 if shed_fan else fan_rev,**({"shed_reason":"HIGH risk β€” comfort shed" if shed_com else "After-hours"} if shed_fan else {})},
141
+ {"name":"TV / Display", "category":"comfort", "state":"OFF" if shed_tv else "ON","watts":0 if shed_tv else 150,"revenue_rwf":0 if shed_tv else tv_rev, **({"shed_reason":"HIGH risk β€” comfort shed" if shed_com else "After-hours"} if shed_tv else {})},
142
+ {"name":"Backup Battery Charger","category":"luxury","state":"ON" if (risk=="LOW" and open_) else "OFF","watts":200 if (risk=="LOW" and open_) else 0,"revenue_rwf":0,**({"shed_reason":"Risk β‰₯ MEDIUM β€” luxury shed"} if not (risk=="LOW" and open_) else {})},
143
+ ]
144
+
145
+ def tailor_appliances(hour, risk):
146
+ open_ = 8 <= hour <= 18
147
+ peak = 9 <= hour <= 16
148
+ scale = 1.0 if peak else (0.6 if open_ else 0.0)
149
+ if not open_:
150
+ return [
151
+ {"name":"Sewing Machine (2Γ—)","category":"critical","state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
152
+ {"name":"Overlocker", "category":"critical","state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
153
+ {"name":"LED Lights", "category":"critical","state":"ON", "watts":20, "revenue_rwf":0},
154
+ {"name":"Iron Press", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
155
+ {"name":"Standing Fan", "category":"comfort", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
156
+ {"name":"Music System", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
157
+ {"name":"TV / Display", "category":"luxury", "state":"OFF","watts":0, "revenue_rwf":0,"shed_reason":"Business closed"},
158
+ ]
159
+ shed_lux = risk in ("HIGH","MEDIUM")
160
+ shed_com = risk == "HIGH"
161
+ shed_iron= risk == "HIGH"
162
+ return [
163
+ {"name":"Sewing Machine (2Γ—)","category":"critical","state":"ON","watts":180,"revenue_rwf":round(590*scale)},
164
+ {"name":"Overlocker", "category":"critical","state":"ON","watts":100,"revenue_rwf":round(310*scale)},
165
+ {"name":"LED Lights", "category":"critical","state":"ON","watts":80, "revenue_rwf":round(180*scale)},
166
+ {"name":"Iron Press", "category":"comfort","state":"OFF" if shed_iron else "ON","watts":0 if shed_iron else 1000,"revenue_rwf":0 if shed_iron else round(260*scale),**({"shed_reason":"HIGH risk β€” heavy load shed"} if shed_iron else {})},
167
+ {"name":"Standing Fan", "category":"comfort","state":"OFF" if shed_com else "ON","watts":0 if shed_com else 75, "revenue_rwf":0 if shed_com else round(120*scale),**({"shed_reason":"HIGH risk β€” comfort shed"} if shed_com else {})},
168
+ {"name":"Music System", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 80, "revenue_rwf":0,**({"shed_reason":"Risk β‰₯ MEDIUM β€” luxury shed"} if shed_lux else {})},
169
+ {"name":"TV / Display", "category":"luxury", "state":"OFF" if shed_lux else "ON","watts":0 if shed_lux else 150, "revenue_rwf":0,**({"shed_reason":"Risk β‰₯ MEDIUM β€” luxury shed"} if shed_lux else {})},
170
+ ]
171
+
172
+ PLANS = {
173
+ "salon": {
174
+ "label": "πŸ’‡ Beauty Salon",
175
+ "summary": {"total_revenue_plan_rwf":93850,"total_revenue_naive_rwf":101790,"net_benefit_rwf":12418,"hours_with_shed":24},
176
+ "fn": salon_appliances,
177
+ },
178
+ "cold_room": {
179
+ "label": "🧊 Cold Room",
180
+ "summary": {"total_revenue_plan_rwf":118000,"total_revenue_naive_rwf":125000,"net_benefit_rwf":18000,"hours_with_shed":16},
181
+ "fn": cold_appliances,
182
+ },
183
+ "tailor": {
184
+ "label": "🧡 Tailor Shop",
185
+ "summary": {"total_revenue_plan_rwf":42000,"total_revenue_naive_rwf":48000,"net_benefit_rwf":3600,"hours_with_shed":14},
186
+ "fn": tailor_appliances,
187
+ },
188
+ }
189
+
190
+ RISK_COLOR = {"HIGH": "#ef4444", "MEDIUM": "#f97316", "LOW": "#22c55e"}
191
+
192
+ # ── Sidebar ───────────────────────────────────────────────────────────────────
193
+ with st.sidebar:
194
+ st.markdown("## ⚑ Grid Outage Forecaster")
195
+ st.markdown("<span style='color:#8892b0;font-size:12px'>T2.3 Β· AIMS KTT Hackathon 2026 Β· Kigali, Rwanda</span>", unsafe_allow_html=True)
196
+ st.divider()
197
+
198
+ st.markdown("### Model Metrics")
199
+ st.metric("Brier Score", "0.176")
200
+ st.metric("MAE (min)", "61.2")
201
+ st.metric("Avg Lead Time", "2.79h")
202
+ st.divider()
203
+
204
+ st.markdown("### Business")
205
+ biz_key = st.radio(
206
+ "Select business",
207
+ options=list(PLANS.keys()),
208
+ format_func=lambda k: PLANS[k]["label"],
209
+ label_visibility="collapsed",
210
+ )
211
+ st.divider()
212
+
213
+ biz = PLANS[biz_key]
214
+ s = biz["summary"]
215
+ st.markdown("### Plan Summary")
216
+ st.metric("Net Benefit (RWF)", f"{s['net_benefit_rwf']:,}")
217
+ st.metric("Expected Rev (RWF)", f"{s['total_revenue_plan_rwf']:,}")
218
+ high_h = sum(1 for f in FORECAST if f["risk_level"] == "HIGH")
219
+ st.metric("HIGH Risk Hours", high_h)
220
+ st.metric("Hours with Shed", s["hours_with_shed"])
221
+
222
+ # ── Main tabs ─────────────────────────────────────────────────────────────────
223
+ tab_forecast, tab_plan, tab_sms, tab_about = st.tabs(
224
+ ["πŸ“ˆ Forecast", "πŸ”Œ Appliance Plan", "πŸ“± SMS Digest", "ℹ️ About"]
225
+ )
226
+
227
+ # ══ FORECAST TAB ══════════════════════════════════════════════════════════════
228
+ with tab_forecast:
229
+ st.markdown("### 24-Hour Outage Probability Forecast")
230
+
231
+ hours = [f["hour"] for f in FORECAST]
232
+ p_out = [f["p_outage"] for f in FORECAST]
233
+ p_low = [f["p_outage_low"] for f in FORECAST]
234
+ p_high = [f["p_outage_high"] for f in FORECAST]
235
+ risk_levels = [f["risk_level"] for f in FORECAST]
236
+ bar_colors = [RISK_COLOR[r] for r in risk_levels]
237
+
238
+ fig = go.Figure()
239
+
240
+ # Risk background zones (coloured bar under chart)
241
+ for f in FORECAST:
242
+ col = {"HIGH":"rgba(239,68,68,.10)","MEDIUM":"rgba(249,115,22,.07)","LOW":"rgba(34,197,94,.04)"}[f["risk_level"]]
243
+ fig.add_vrect(x0=f["hour"]-.5, x1=f["hour"]+.5, fillcolor=col, line_width=0, layer="below")
244
+
245
+ # Uncertainty band
246
+ fig.add_trace(go.Scatter(
247
+ x=hours + hours[::-1],
248
+ y=p_high + p_low[::-1],
249
+ fill="toself", fillcolor="rgba(99,102,241,.18)",
250
+ line=dict(color="rgba(0,0,0,0)"),
251
+ hoverinfo="skip", name="Uncertainty band",
252
+ ))
253
+
254
+ # Main line
255
+ fig.add_trace(go.Scatter(
256
+ x=hours, y=p_out,
257
+ mode="lines+markers",
258
+ line=dict(color="#6366f1", width=2.5),
259
+ marker=dict(color=bar_colors, size=8, line=dict(color="#0f1117", width=1)),
260
+ name="P(outage)",
261
+ hovertemplate="Hour %{x}:00<br>P(outage)=%{y:.1%}<extra></extra>",
262
+ ))
263
+
264
+ # HIGH threshold line
265
+ fig.add_hline(y=0.25, line=dict(color="#ef4444", dash="dash", width=1),
266
+ annotation_text="HIGH threshold", annotation_position="top left",
267
+ annotation_font_color="#ef4444")
268
+
269
+ fig.update_layout(
270
+ paper_bgcolor="#1a1d27", plot_bgcolor="#1a1d27",
271
+ font=dict(color="#e8eaf6", size=12),
272
+ xaxis=dict(title="Hour of day", gridcolor="#2e3350", tickvals=list(range(0,24,2))),
273
+ yaxis=dict(title="P(outage)", gridcolor="#2e3350", tickformat=".0%", range=[0, 0.55]),
274
+ legend=dict(orientation="h", y=1.08, bgcolor="rgba(0,0,0,0)"),
275
+ margin=dict(l=10, r=10, t=10, b=10),
276
+ height=320,
277
+ )
278
+ st.plotly_chart(fig, use_container_width=True)
279
+
280
+ # ── Hour grid ─────────────────────────────────────────────────────────────
281
+ st.markdown("### Hourly Risk β€” click a cell to drill into plan")
282
+ cols = st.columns(12)
283
+ for i, f in enumerate(FORECAST):
284
+ col_idx = i % 12
285
+ with cols[col_idx]:
286
+ risk = f["risk_level"]
287
+ color = RISK_COLOR[risk]
288
+ pct = f"{f['p_outage']*100:.0f}%"
289
+ st.markdown(f"""
290
+ <div style='background:#1a1d27;border:1px solid #2e3350;border-radius:6px;
291
+ padding:6px 4px;text-align:center;margin-bottom:4px;'>
292
+ <div style='font-size:10px;color:#8892b0'>{f["hour"]}h</div>
293
+ <div style='font-size:14px;font-weight:700;color:{color}'>{pct}</div>
294
+ <div style='margin-top:2px'><span class='badge badge-{risk.lower()}'>{risk}</span></div>
295
+ </div>""", unsafe_allow_html=True)
296
+
297
+ cols2 = st.columns(12)
298
+ for i, f in enumerate(FORECAST):
299
+ with cols2[i % 12]:
300
+ pass # second row of 12 hours already handled above
301
+
302
+ # Second row (hours 12–23)
303
+ st.markdown("")
304
+
305
+ # ══ PLAN TAB ══════════════════════════════════════════════════════════════════
306
+ with tab_plan:
307
+ st.markdown("### πŸ”Œ Appliance Plan")
308
+
309
+ hour_idx = st.slider(
310
+ "Select hour",
311
+ min_value=0, max_value=23, value=0,
312
+ format="%d:00",
313
+ )
314
+
315
+ fc = FORECAST[hour_idx]
316
+ appliances = biz["fn"](hour_idx, fc["risk_level"])
317
+ risk = fc["risk_level"]
318
+
319
+ # Hour info header
320
+ risk_color = RISK_COLOR[risk]
321
+ st.markdown(f"""
322
+ <div class='plan-header'>
323
+ <b>Hour {hour_idx}</b> &nbsp;Β·&nbsp; {fc['timestamp'].split()[1]}
324
+ &nbsp;&nbsp;<span class='badge badge-{risk.lower()}'>{risk}</span>
325
+ &nbsp;&nbsp;P(outage) = <b>{fc['p_outage']*100:.1f}%</b>
326
+ &nbsp;&nbsp;Exp. duration = <b>{fc['expected_duration_min']:.0f} min</b>
327
+ </div>
328
+ """, unsafe_allow_html=True)
329
+
330
+ # Appliance cards in 2 columns
331
+ left_col, right_col = st.columns(2)
332
+ for i, ap in enumerate(appliances):
333
+ target = left_col if i % 2 == 0 else right_col
334
+ is_off = ap["state"] == "OFF"
335
+ opacity = "opacity:.65;" if is_off else ""
336
+ shed = f"<div class='ap-shed'>⚠ {ap['shed_reason']}</div>" if "shed_reason" in ap else ""
337
+ rev_html = f"<div class='ap-rev'>{ap['revenue_rwf']:,} RWF/h</div>" if ap["state"] == "ON" and ap["revenue_rwf"] > 0 else "<div style='color:#6b7280'>β€”</div>"
338
+ with target:
339
+ st.markdown(f"""
340
+ <div class='ap-card{"" if not is_off else " off"}' style='{opacity}'>
341
+ <div style='display:flex;justify-content:space-between;align-items:flex-start'>
342
+ <div>
343
+ <div class='ap-name'>{ap['name']}</div>
344
+ <div class='ap-meta'>
345
+ <span class='badge badge-{ap['category']}'>{ap['category']}</span>
346
+ <span class='badge badge-{ap['state'].lower()}'>{ap['state']}</span>
347
+ </div>
348
+ {shed}
349
+ </div>
350
+ <div class='ap-right'>
351
+ <div style='font-size:11px;color:#8892b0'>{ap['watts']}W</div>
352
+ {rev_html}
353
+ </div>
354
+ </div>
355
+ </div>""", unsafe_allow_html=True)
356
+
357
+ st.markdown("""
358
+ <div style='background:#1a1d27;border:1px solid #2e3350;border-radius:8px;
359
+ padding:12px;font-size:12px;color:#8892b0;margin-top:8px;'>
360
+ <b style='color:#e8eaf6'>Shedding Logic:</b>
361
+ Luxury β†’ Comfort β†’ Critical (never shed during peak unless P &gt; 0.50).
362
+ Within category: lowest revenue shed first. Critical always ON during business peak hours.
363
+ </div>""", unsafe_allow_html=True)
364
+
365
+ # ══ SMS TAB ═══════════════════════════════════════════════════════════════════
366
+ with tab_sms:
367
+ st.markdown("### πŸ“± Morning Digest β€” Feature Phone SMS")
368
+ st.markdown("<span style='color:#8892b0;font-size:12px'>Sent at 06:30 CAT. Max 3 messages Γ— 160 chars. Works on any GSM phone. No internet required. Language: Kinyarwanda/English mix for maximum reach.</span>", unsafe_allow_html=True)
369
+ st.markdown("")
370
+
371
+ for i, msg in enumerate(SMS):
372
+ st.markdown(f"""
373
+ <div class='sms-box'>
374
+ <div style='display:flex;justify-content:space-between;margin-bottom:6px'>
375
+ <span style='font-size:11px;font-weight:700;color:#6366f1'>SMS {i+1}/3</span>
376
+ <span style='font-size:10px;color:#8892b0'>{len(msg)}/160 chars</span>
377
+ </div>
378
+ {msg}
379
+ </div>""", unsafe_allow_html=True)
380
+
381
+ st.markdown("""
382
+ <div class='sms-box' style='border-color:#6366f1;margin-top:16px;'>
383
+ <div style='font-size:12px;font-weight:700;color:#6366f1;margin-bottom:8px'>πŸ”• Offline Fallback Protocol</div>
384
+ <div style='font-size:12px;color:#8892b0;line-height:1.7'>
385
+ <b style='color:#e8eaf6'>If no internet refresh by 13:00:</b> Device shows last cached plan with
386
+ a red ⚠️ staleness banner. Risk budget: plan valid for <b style='color:#f97316'>6 hours</b>
387
+ from generation time. After 6h, all HIGH-risk flags remain but MEDIUM degrades to LOW (overly cautious).
388
+ Maximum acceptable staleness: <b style='color:#ef4444'>8 hours</b>.
389
+ Owner sees: "PLAN STALE β€” use generator, call 0788-GRID."
390
+ </div>
391
+ </div>
392
+ <div class='sms-box' style='border-color:#22c55e;margin-top:10px;'>
393
+ <div style='font-size:12px;font-weight:700;color:#22c55e;margin-bottom:8px'>πŸ”Š Illiteracy Adaptation β€” Voice + LED Relay</div>
394
+ <div style='font-size:12px;color:#8892b0;line-height:1.7'>
395
+ <b style='color:#e8eaf6'>Design choice: Colored LED relay board</b> (3 LEDs per appliance slot).<br>
396
+ 🟒 GREEN = ON safe &nbsp;Β·&nbsp; 🟑 YELLOW = shed if load high &nbsp;Β·&nbsp; πŸ”΄ RED = OFF now.<br>
397
+ Board connects via GPIO to a β‰ˆUSD 8 ESP32 running cached plan. No reading required.
398
+ Physical override switch lets owner override any LED. $8 hardware cost, zero ongoing data cost.
399
+ </div>
400
+ </div>
401
+ """, unsafe_allow_html=True)
402
+
403
+ # ══ ABOUT TAB ═════════════════════════════════════════════════════════════════
404
+ with tab_about:
405
+ st.markdown("### Technical Notes")
406
+ col1, col2 = st.columns(2)
407
+
408
+ with col1:
409
+ st.markdown("""
410
+ <div class='sms-box'>
411
+ <div style='font-size:12px;font-weight:700;color:#6366f1;margin-bottom:6px'>Model</div>
412
+ <div style='font-size:12px;color:#8892b0;line-height:1.7'>
413
+ <b style='color:#e8eaf6'>LightGBM</b> classifier for P(outage) + regressor for E[duration | outage].<br>
414
+ Features: lagged load (1h, 2h, 24h, 48h), rolling stats, weather (temp, humidity, rain, wind),
415
+ temporal (hour, DOW, month, peak flags, rainy season). Training: 150-day window.
416
+ </div>
417
+ </div>
418
+ """, unsafe_allow_html=True)
419
+
420
+ st.markdown("""
421
+ <div class='sms-box' style='margin-top:10px'>
422
+ <div style='font-size:12px;font-weight:700;color:#6366f1;margin-bottom:6px'>Hardest Trade-off</div>
423
+ <div style='font-size:12px;color:#8892b0;line-height:1.7'>
424
+ Chose LightGBM over Prophet: faster retrain, handles irregular time steps,
425
+ natively supports tabular weather features. Trade-off: less interpretable
426
+ seasonality decomposition. Compensated with explicit hour/DOW/month features
427
+ and SHAP values available in eval notebook.
428
+ </div>
429
+ </div>
430
+ """, unsafe_allow_html=True)
431
+
432
+ with col2:
433
+ st.markdown("""
434
+ <div class='sms-box'>
435
+ <div style='font-size:12px;font-weight:700;color:#6366f1;margin-bottom:6px'>Performance</div>
436
+ <div style='font-size:12px;color:#8892b0;line-height:1.7'>
437
+ Brier score: <b style='color:#22c55e'>0.1756</b> (naΓ―ve base rate = ~0.212)<br>
438
+ Duration MAE: <b style='color:#22c55e'>61.2 min</b><br>
439
+ Avg lead time on true outages: <b style='color:#22c55e'>2.79h</b><br>
440
+ Inference latency: <b style='color:#22c55e'>&lt;300ms CPU</b><br>
441
+ Retraining time: <b style='color:#22c55e'>&lt;10 min</b>
442
+ </div>
443
+ </div>
444
+ """, unsafe_allow_html=True)
445
+
446
+ st.markdown("""
447
+ <div class='sms-box' style='margin-top:10px'>
448
+ <div style='font-size:12px;font-weight:700;color:#6366f1;margin-bottom:6px'>Constraints Met</div>
449
+ <div style='font-size:12px;color:#8892b0;line-height:1.7'>
450
+ βœ… CPU-only &nbsp;Β·&nbsp; βœ… &lt;10 min retrain &nbsp;Β·&nbsp; βœ… &lt;300ms serve<br>
451
+ βœ… Feature phone SMS digest &nbsp;Β·&nbsp; βœ… Offline fallback protocol<br>
452
+ βœ… Illiteracy adaptation &nbsp;Β·&nbsp; βœ… 3 business archetypes<br>
453
+ βœ… Critical-before-luxury rule
454
+ </div>
455
+ </div>
456
+ """, unsafe_allow_html=True)
457
 
458
+ st.markdown("""
459
+ <div style='text-align:center;color:#8892b0;font-size:11px;padding:20px 0 10px'>
460
+ T2.3 Β· Grid Outage Forecaster + Appliance Prioritizer Β· AIMS KTT Hackathon 2026 Β· CPU-only
461
+ </div>""", unsafe_allow_html=True)