SANIDHYAG commited on
Commit
9e3edd6
·
verified ·
1 Parent(s): d893665

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -51
app.py CHANGED
@@ -2,115 +2,163 @@ import streamlit as st
2
  import pandas as pd
3
  import altair as alt
4
  import json
 
5
  from datetime import datetime
6
 
 
 
 
7
  st.set_page_config(page_title="Climate Clock Observatory", layout="wide")
8
- st.title("🌍 Real-Time Climate Clock Observatory")
 
9
 
10
- # Add a refresh button
 
 
 
 
 
 
 
 
 
 
 
 
11
  if st.button("🔁 Refresh Data"):
12
- st.experimental_rerun()
 
13
 
14
- # Load static data from local file
 
 
15
  try:
16
  with open("climate_data.json") as f:
17
  clock = json.load(f)
18
- except Exception as e:
19
  st.error("Failed to load climate data.")
20
  st.stop()
21
 
22
- # 1️⃣ CO₂ Budget Depletion Line Chart (10-year projection)
 
 
23
  st.header("1️⃣ CO₂ Budget Depletion Projection")
24
  try:
25
- co2_clock = clock.get("co2", {})
26
- co2_remaining = float(co2_clock.get("remaining", 0))
27
- co2_rate = float(co2_clock.get("rate", 0))
28
 
29
  years = list(range(datetime.now().year, datetime.now().year + 10))
30
- values = [max(co2_remaining - i * co2_rate, 0) for i in range(10)]
31
- df_proj = pd.DataFrame({"Year": years, "Remaining CO₂ Budget (Gt)": values})
 
 
 
 
32
 
33
- chart = alt.Chart(df_proj).mark_line(point=True).encode(
34
- x='Year:O',
35
- y='Remaining CO₂ Budget (Gt):Q',
36
- tooltip=['Year', 'Remaining CO₂ Budget (Gt)']
37
  ).properties(width=700)
38
  st.altair_chart(chart, use_container_width=True)
 
39
  except Exception as e:
40
- st.warning(f"Could not generate CO₂ projection chart: {e}")
41
 
42
- # 2️⃣ Renewable Energy Share Donut Chart
 
 
43
  st.header("2️⃣ Global Energy Mix – Renewables vs Others")
44
  try:
45
- renewables_clock = clock.get("renewables", {})
46
- percent = float(renewables_clock.get("percentage", 0))
 
47
  energy_df = pd.DataFrame({
48
- 'Type': ['Renewables', 'Other'],
49
- 'Percentage': [percent, 100 - percent]
50
  })
51
 
52
- pie = alt.Chart(energy_df).mark_arc(innerRadius=50).encode(
53
- theta='Percentage:Q',
54
- color='Type:N',
55
- tooltip=['Type', 'Percentage']
56
  ).properties(width=400, height=400)
57
- st.altair_chart(pie, use_container_width=True)
 
58
  except Exception as e:
59
- st.warning(f"Could not load renewable energy chart: {e}")
60
 
61
- # 3️⃣ Lifeline Metrics – Positive Climate Interventions
62
- st.header("3️⃣ Lifeline Metrics Positive Contributions")
 
 
63
  try:
64
  lifelines = clock.get("lifelines", [])
65
  lifeline_df = pd.DataFrame([
66
- {"Label": l.get("label", ""), "Value": float(l.get("value", 0))}
67
- for l in lifelines
68
  ])
69
- bar = alt.Chart(lifeline_df).mark_bar().encode(
 
70
  x=alt.X("Label:N", sort="-y"),
71
  y="Value:Q",
72
  tooltip=["Label", "Value"]
73
  ).properties(width=700)
74
- st.altair_chart(bar, use_container_width=True)
 
75
  except Exception as e:
76
- st.warning(f"Could not generate lifeline chart: {e}")
77
 
78
- # 4️⃣ Climate Deadline Countdown Display
 
 
79
  st.header("4️⃣ Time Left to 1.5°C Threshold")
80
  try:
81
- deadline_clock = clock.get("deadline", {})
82
- deadline_parts = list(map(int, deadline_clock.get("time_left", "0:0:0:0:0").split(":")))
83
- time_left_str = f"{deadline_parts[0]} years, {deadline_parts[1]} months, {deadline_parts[2]} days"
84
- st.success(f"⏳ Estimated Time Remaining Before 1.5°C Limit is Breached: {time_left_str}")
 
85
  except Exception as e:
86
- st.warning(f"Could not show climate deadline: {e}")
87
 
88
- # 5️⃣ Interactive What-If: CO₂ Emission Reduction Simulator
 
 
89
  st.header("5️⃣ CO₂ Budget Simulator – What If We Reduce Emissions?")
90
  try:
91
- st.markdown("📉 Use the slider below to simulate reduced annual emissions and see when we would run out of CO₂ budget.")
92
- new_rate = st.slider("New Annual CO₂ Emission Rate (Gt/year)", min_value=10.0, max_value=45.0, value=co2_rate, step=0.5)
 
93
  sim_years = []
94
- sim_budget = []
95
  budget = co2_remaining
96
  year = datetime.now().year
97
 
98
  while budget > 0 and len(sim_years) < 20:
99
  sim_years.append(year)
100
- sim_budget.append(budget)
101
  budget -= new_rate
102
  year += 1
103
 
104
- sim_df = pd.DataFrame({'Year': sim_years, 'Projected CO₂ Budget (Gt)': sim_budget})
 
 
 
 
105
  sim_chart = alt.Chart(sim_df).mark_line(point=True).encode(
106
- x='Year:O',
107
- y='Projected CO₂ Budget (Gt):Q',
108
- tooltip=['Year', 'Projected CO₂ Budget (Gt)']
109
  ).properties(width=700)
110
  st.altair_chart(sim_chart, use_container_width=True)
 
111
  except Exception as e:
112
- st.warning(f"Could not run simulation: {e}")
113
 
 
114
  # Footer
 
115
  st.markdown("---")
116
- st.caption("Made by Sanidhya and Group Members | Data from Climate Clock API (cached sample)")
 
2
  import pandas as pd
3
  import altair as alt
4
  import json
5
+ import os
6
  from datetime import datetime
7
 
8
+ # ----------------------------------------
9
+ # App Configuration
10
+ # ----------------------------------------
11
  st.set_page_config(page_title="Climate Clock Observatory", layout="wide")
12
+ st.title("🌍 Climate Clock Observatory")
13
+ st.write("This dashboard presents key climate indicators using pseudo real-time data from the Climate Clock API.")
14
 
15
+ # ----------------------------------------
16
+ # Display Last Updated Timestamp
17
+ # ----------------------------------------
18
+ try:
19
+ file_stats = os.stat("climate_data.json")
20
+ last_updated = datetime.fromtimestamp(file_stats.st_mtime).strftime("%Y-%m-%d %H:%M:%S")
21
+ st.caption(f"🕒 Data last updated: {last_updated}")
22
+ except:
23
+ st.caption("🕒 Last updated time not available")
24
+
25
+ # ----------------------------------------
26
+ # Refresh Button (Triggers full rerun)
27
+ # ----------------------------------------
28
  if st.button("🔁 Refresh Data"):
29
+ with st.spinner("Refreshing data..."):
30
+ st.experimental_rerun()
31
 
32
+ # ----------------------------------------
33
+ # Load Local JSON Data
34
+ # ----------------------------------------
35
  try:
36
  with open("climate_data.json") as f:
37
  clock = json.load(f)
38
+ except Exception:
39
  st.error("Failed to load climate data.")
40
  st.stop()
41
 
42
+ # ----------------------------------------
43
+ # 1. CO₂ Budget Depletion Projection (Line Chart)
44
+ # ----------------------------------------
45
  st.header("1️⃣ CO₂ Budget Depletion Projection")
46
  try:
47
+ co2 = clock.get("co2", {})
48
+ co2_remaining = float(co2.get("remaining", 0))
49
+ co2_rate = float(co2.get("rate", 0))
50
 
51
  years = list(range(datetime.now().year, datetime.now().year + 10))
52
+ remaining = [max(co2_remaining - co2_rate * i, 0) for i in range(10)]
53
+
54
+ co2_df = pd.DataFrame({
55
+ "Year": years,
56
+ "Remaining CO₂ Budget (Gt)": remaining
57
+ })
58
 
59
+ chart = alt.Chart(co2_df).mark_line(point=True).encode(
60
+ x="Year:O",
61
+ y="Remaining CO₂ Budget (Gt):Q",
62
+ tooltip=["Year", "Remaining CO₂ Budget (Gt)"]
63
  ).properties(width=700)
64
  st.altair_chart(chart, use_container_width=True)
65
+
66
  except Exception as e:
67
+ st.warning(f"Could not render CO₂ projection chart: {e}")
68
 
69
+ # ----------------------------------------
70
+ # 2. Global Energy Mix (Donut Chart)
71
+ # ----------------------------------------
72
  st.header("2️⃣ Global Energy Mix – Renewables vs Others")
73
  try:
74
+ renewables = clock.get("renewables", {})
75
+ renewable_percent = float(renewables.get("percentage", 0))
76
+
77
  energy_df = pd.DataFrame({
78
+ "Type": ["Renewables", "Other"],
79
+ "Percentage": [renewable_percent, 100 - renewable_percent]
80
  })
81
 
82
+ donut = alt.Chart(energy_df).mark_arc(innerRadius=50).encode(
83
+ theta="Percentage:Q",
84
+ color="Type:N",
85
+ tooltip=["Type", "Percentage"]
86
  ).properties(width=400, height=400)
87
+ st.altair_chart(donut, use_container_width=True)
88
+
89
  except Exception as e:
90
+ st.warning(f"Could not render energy mix chart: {e}")
91
 
92
+ # ----------------------------------------
93
+ # 3. Lifeline Metrics (Bar Chart)
94
+ # ----------------------------------------
95
+ st.header("3️⃣ Lifeline Metrics – Positive Climate Interventions")
96
  try:
97
  lifelines = clock.get("lifelines", [])
98
  lifeline_df = pd.DataFrame([
99
+ {"Label": item.get("label", ""), "Value": float(item.get("value", 0))}
100
+ for item in lifelines
101
  ])
102
+
103
+ lifeline_chart = alt.Chart(lifeline_df).mark_bar().encode(
104
  x=alt.X("Label:N", sort="-y"),
105
  y="Value:Q",
106
  tooltip=["Label", "Value"]
107
  ).properties(width=700)
108
+ st.altair_chart(lifeline_chart, use_container_width=True)
109
+
110
  except Exception as e:
111
+ st.warning(f"Could not render lifeline chart: {e}")
112
 
113
+ # ----------------------------------------
114
+ # 4. Climate Deadline Countdown
115
+ # ----------------------------------------
116
  st.header("4️⃣ Time Left to 1.5°C Threshold")
117
  try:
118
+ deadline = clock.get("deadline", {})
119
+ parts = list(map(int, deadline.get("time_left", "0:0:0:0:0").split(":")))
120
+ display_str = f"{parts[0]} years, {parts[1]} months, {parts[2]} days"
121
+ st.success(f"⏳ Estimated Time Remaining: {display_str}")
122
+
123
  except Exception as e:
124
+ st.warning(f"Could not display climate deadline: {e}")
125
 
126
+ # ----------------------------------------
127
+ # 5. CO₂ Budget Simulator (Interactive Slider)
128
+ # ----------------------------------------
129
  st.header("5️⃣ CO₂ Budget Simulator – What If We Reduce Emissions?")
130
  try:
131
+ st.markdown("Use the slider to simulate reduced emissions and project CO₂ budget timeline.")
132
+ new_rate = st.slider("New Annual CO₂ Emission Rate (Gt/year)", 10.0, 45.0, co2_rate, 0.5)
133
+
134
  sim_years = []
135
+ sim_budgets = []
136
  budget = co2_remaining
137
  year = datetime.now().year
138
 
139
  while budget > 0 and len(sim_years) < 20:
140
  sim_years.append(year)
141
+ sim_budgets.append(budget)
142
  budget -= new_rate
143
  year += 1
144
 
145
+ sim_df = pd.DataFrame({
146
+ "Year": sim_years,
147
+ "Projected CO₂ Budget (Gt)": sim_budgets
148
+ })
149
+
150
  sim_chart = alt.Chart(sim_df).mark_line(point=True).encode(
151
+ x="Year:O",
152
+ y="Projected CO₂ Budget (Gt):Q",
153
+ tooltip=["Year", "Projected CO₂ Budget (Gt)"]
154
  ).properties(width=700)
155
  st.altair_chart(sim_chart, use_container_width=True)
156
+
157
  except Exception as e:
158
+ st.warning(f"Could not run CO₂ simulation: {e}")
159
 
160
+ # ----------------------------------------
161
  # Footer
162
+ # ----------------------------------------
163
  st.markdown("---")
164
+ st.caption("Made by Sanidhya and Group Members | Data based on Climate Clock API (cached sample)")