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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +118 -125
app.py CHANGED
@@ -5,16 +5,15 @@ 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")
@@ -22,143 +21,137 @@ try:
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)")
 
5
  import os
6
  from datetime import datetime
7
 
8
+ # -------------------------------
9
+ # App Config and Title
10
+ # -------------------------------
11
  st.set_page_config(page_title="Climate Clock Observatory", layout="wide")
12
+ st.title("🌍 Real-Time Climate Clock Observatory")
 
13
 
14
+ # -------------------------------
15
+ # Show Last Updated Timestamp
16
+ # -------------------------------
17
  try:
18
  file_stats = os.stat("climate_data.json")
19
  last_updated = datetime.fromtimestamp(file_stats.st_mtime).strftime("%Y-%m-%d %H:%M:%S")
 
21
  except:
22
  st.caption("🕒 Last updated time not available")
23
 
24
+ # -------------------------------
25
+ # Refresh Button
26
+ # -------------------------------
27
  if st.button("🔁 Refresh Data"):
28
  with st.spinner("Refreshing data..."):
29
  st.experimental_rerun()
30
 
31
+ # -------------------------------
32
+ # Load Climate Data from JSON
33
+ # -------------------------------
34
  try:
35
+ with open("climate_data.json", "r") as f:
36
  clock = json.load(f)
37
+ except Exception as e:
38
+ st.error("Failed to load climate data.")
39
  st.stop()
40
 
41
+ # -------------------------------
42
+ # 1️⃣ CO₂ Budget Depletion Projection
43
+ # -------------------------------
44
  st.header("1️⃣ CO₂ Budget Depletion Projection")
 
 
 
 
45
 
46
+ co2_data = clock.get("co2", {})
47
+ co2_remaining = float(co2_data.get("remaining", 0))
48
+ co2_rate = float(co2_data.get("rate", 0))
49
 
50
+ years = list(range(datetime.now().year, datetime.now().year + 10))
51
+ remaining_budget = [max(co2_remaining - i * co2_rate, 0) for i in range(10)]
52
+ co2_df = pd.DataFrame({"Year": years, "Remaining CO₂ Budget (Gt)": remaining_budget})
 
53
 
54
+ co2_chart = alt.Chart(co2_df).mark_line(point=True).encode(
55
+ x='Year:O',
56
+ y='Remaining CO₂ Budget (Gt):Q',
57
+ tooltip=['Year', 'Remaining CO₂ Budget (Gt)']
58
+ ).properties(width=700)
 
59
 
60
+ st.altair_chart(co2_chart, use_container_width=True)
 
61
 
62
+ # -------------------------------
63
+ # 2️⃣ Global Energy Mix Donut Chart
64
+ # -------------------------------
65
  st.header("2️⃣ Global Energy Mix – Renewables vs Others")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
+ renew_data = clock.get("renewables", {})
68
+ renew_percent = float(renew_data.get("percentage", 0))
69
+ energy_df = pd.DataFrame({
70
+ "Type": ["Renewables", "Other"],
71
+ "Percentage": [renew_percent, 100 - renew_percent]
72
+ })
73
+
74
+ energy_chart = alt.Chart(energy_df).mark_arc(innerRadius=50).encode(
75
+ theta="Percentage:Q",
76
+ color="Type:N",
77
+ tooltip=["Type", "Percentage"]
78
+ ).properties(width=400, height=400)
79
+
80
+ st.altair_chart(energy_chart, use_container_width=True)
81
+
82
+ # -------------------------------
83
+ # 3️⃣ Lifeline Metrics Bar Chart
84
+ # -------------------------------
85
+ st.header("3️⃣ Lifeline Metrics – Positive Contributions")
86
+
87
+ lifelines = clock.get("lifelines", [])
88
+ lifeline_df = pd.DataFrame([
89
+ {"Label": item.get("label", ""), "Value": float(item.get("value", 0))}
90
+ for item in lifelines
91
+ ])
92
+
93
+ lifeline_chart = alt.Chart(lifeline_df).mark_bar().encode(
94
+ x=alt.X("Label:N", sort="-y"),
95
+ y="Value:Q",
96
+ tooltip=["Label", "Value"]
97
+ ).properties(width=700)
98
+
99
+ st.altair_chart(lifeline_chart, use_container_width=True)
100
+
101
+ # -------------------------------
102
+ # 4️⃣ Time Left to 1.5°C Threshold
103
+ # -------------------------------
104
  st.header("4️⃣ Time Left to 1.5°C Threshold")
 
 
 
 
 
 
 
 
105
 
106
+ deadline = clock.get("deadline", {})
107
+ time_parts = deadline.get("time_left", "0:0:0:0:0").split(":")
 
 
108
  try:
109
+ years, months, days = int(time_parts[0]), int(time_parts[1]), int(time_parts[2])
110
+ st.success(f" Estimated time before 1.5°C threshold: {years} years, {months} months, {days} days")
111
+ except:
112
+ st.warning("⚠️ Could not parse climate deadline.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ # -------------------------------
115
+ # 5️⃣ CO₂ Budget Simulator with Slider
116
+ # -------------------------------
117
+ st.header("5️⃣ CO₂ Budget Simulator – What If We Reduce Emissions?")
118
 
119
+ st.markdown("📉 Use the slider below to simulate reduced annual emissions and visualize its impact.")
120
+
121
+ new_rate = st.slider(
122
+ "New Annual CO₂ Emission Rate (Gt/year)",
123
+ min_value=10.0,
124
+ max_value=45.0,
125
+ value=co2_rate,
126
+ step=0.5
127
+ )
128
+
129
+ sim_years = []
130
+ sim_budget = []
131
+ current_budget = co2_remaining
132
+ year = datetime.now().year
133
+
134
+ while current_budget > 0 and len(sim_years) < 20:
135
+ sim_years.append(year)
136
+ sim_budget.append(current_budget)
137
+ current_budget -= new_rate
138
+ year += 1
139
+
140
+ sim_df = pd.DataFrame({
141
+ "Year": sim_years,
142
+ "Projected CO₂ Budget (Gt)": sim_budget
143
+ })
144
+
145
+ sim_chart = alt.Chart(sim_df).mark_line(point=True).encode(
146
+ x="Year:O",
147
+ y="Projected CO₂ Budget (Gt):Q",
148
+ tooltip=["Year", "Projected CO₂ Budget (Gt)"]
149
+ ).properties(width=700)
150
+
151
+ st.altair_chart(sim_chart, use_container_width=True)
152
+
153
+ # -------------------------------
154
  # Footer
155
+ # -------------------------------
156
  st.markdown("---")
157
+ st.caption("Made by Sanidhya and Group Members | Data from Climate Clock API (cached sample)")