Spaces:
Running
Running
File size: 21,638 Bytes
706f4dc 091a7e7 706f4dc 091a7e7 706f4dc 091a7e7 706f4dc 091a7e7 706f4dc 091a7e7 706f4dc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 |
import streamlit as st
import tensorflow as tf
import joblib
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import pickle
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
# Dark theme configuration
st.set_page_config(
page_title="AuraClima - AI Climate Intelligence",
page_icon="🌍",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for dark theme and styling
st.markdown("""
<style>
.stApp {
background: linear-gradient(135deg, #0c1017 0%, #1a1f2e 100%);
color: #ffffff;
}
.main-header {
text-align: center;
background: linear-gradient(135deg, #1f77b4, #FF7F0E);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-size: 3.5rem;
font-weight: 800;
margin-bottom: 1rem;
text-shadow: 0 0 30px rgba(31, 119, 180, 0.3);
}
.subtitle {
text-align: center;
color: #FF7F0E;
font-size: 1.5rem;
font-style: italic;
margin-bottom: 2rem;
text-shadow: 0 0 20px rgba(255, 127, 14, 0.2);
}
.model-card {
background: linear-gradient(145deg, #1e2530, #2a3441);
border-radius: 15px;
padding: 20px;
margin: 15px 0;
border: 1px solid rgba(31, 119, 180, 0.3);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
}
.metric-container {
background: linear-gradient(135deg, #1f77b4, #2a9fd6);
border-radius: 12px;
padding: 15px;
text-align: center;
margin: 10px 0;
box-shadow: 0 4px 20px rgba(31, 119, 180, 0.4);
}
.metric-value {
font-size: 2rem;
font-weight: bold;
color: #ffffff;
}
.metric-label {
color: #e0e6ed;
font-size: 0.9rem;
margin-top: 5px;
}
.ai-badge {
background: linear-gradient(45deg, #FF7F0E, #ff9a3c);
color: white;
padding: 5px 15px;
border-radius: 20px;
font-size: 0.8rem;
font-weight: bold;
display: inline-block;
margin: 5px;
box-shadow: 0 2px 10px rgba(255, 127, 14, 0.3);
}
.sidebar .sidebar-content {
background: linear-gradient(180deg, #1a1f2e, #0c1017);
}
.stSelectbox > div > div {
background-color: #2a3441;
border: 1px solid #1f77b4;
border-radius: 8px;
}
.stSlider > div > div {
background: linear-gradient(90deg, #1f77b4, #FF7F0E);
}
.stButton > button {
background: linear-gradient(135deg, #1f77b4, #FF7F0E);
color: white;
border: none;
border-radius: 8px;
padding: 10px 20px;
font-weight: bold;
transition: all 0.3s ease;
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(31, 119, 180, 0.4);
}
.forecast-section {
background: rgba(31, 119, 180, 0.1);
border-radius: 15px;
padding: 20px;
margin: 20px 0;
border-left: 4px solid #1f77b4;
}
</style>
""", unsafe_allow_html=True)
@st.cache_resource
def load_all():
base = os.path.dirname(__file__)
models_dir = os.path.join(base, "models")
data_dir = os.path.join(base, "data")
# Load models
model1 = tf.keras.models.load_model(os.path.join(models_dir, "model1.keras"))
model2 = tf.keras.models.load_model(os.path.join(models_dir, "model2.keras"))
model3 = tf.keras.models.load_model(os.path.join(models_dir, "model3.keras"))
# Load scalers
scaler1 = joblib.load(os.path.join(models_dir, "scaler1.save"))
scalerX2 = joblib.load(os.path.join(models_dir, "scalerX2.save"))
scalerY2 = joblib.load(os.path.join(models_dir, "scalerY2.save"))
scaler3 = joblib.load(os.path.join(models_dir, "scaler3.save"))
# Load feature columns list for model2
with open(os.path.join(models_dir, "feature_cols2.list"), "rb") as f:
feature_cols2 = pickle.load(f)
# Load CSV data if present
df_agri = None
agri_path = os.path.join(data_dir, "Agrofood_co2_emission.csv")
if os.path.exists(agri_path):
df_agri = pd.read_csv(agri_path)
df_co2 = None
co2_path = os.path.join(data_dir, "CO2_Emissions_1960-2018.csv")
if os.path.exists(co2_path):
df_co2 = pd.read_csv(co2_path)
if 'Country Name' not in df_co2.columns:
st.error(f"Expected 'Country Name' in CO2 CSV, found: {df_co2.columns.tolist()}")
df_co2 = None
else:
dummies = pd.get_dummies(df_co2['Country Name'], prefix='Country')
country_features = dummies.columns.tolist()
df_co2 = pd.concat([df_co2, dummies], axis=1)
else:
country_features = None
return {
"model1": model1, "model2": model2, "model3": model3,
"scaler1": scaler1, "scalerX2": scalerX2, "scalerY2": scalerY2, "scaler3": scaler3, # <--- Ensure scaler3 is returned
"feature_cols2": feature_cols2, "df_agri": df_agri, "df_co2": df_co2,
"country_features": country_features,
}
def forecast_model1(model, scaler, recent_values):
arr = np.array(recent_values).reshape(-1, 1)
scaled = scaler.transform(arr).flatten()
inp = scaled.reshape((1, len(scaled), 1))
scaled_pred = model.predict(inp, verbose=0)[0, 0]
pred = scaler.inverse_transform([[scaled_pred]])[0, 0]
return pred
def predict_model2(model, scalerX, scalerY, feature_array):
X = np.array(feature_array).reshape(1, -1)
Xs = scalerX.transform(X)
ys = model.predict(Xs, verbose=0)
ypred = scalerY.inverse_transform(ys.reshape(-1, 1)).flatten()[0]
return ypred
def forecast_model3(model, scaler, recent_series, country_vec):
window = len(recent_series)
# co2_scaled = scaler.transform(np.array(recent_series).reshape(-1, 1)).flatten()
co2_col = np.array(recent_series).reshape(window, 1)
country_mat = np.tile(country_vec.reshape(1, -1), (window, 1))
# Concatenate raw CO2 values with country vector
seq = np.concatenate([co2_col, country_mat], axis=1)
# Reshape input for LSTM
inp = seq.reshape(1, window, seq.shape[1])
# Make prediction - model outputs raw, unscaled values
ypred_raw_output = model.predict(inp, verbose=0).flatten()
# --- PREVIOUSLY INCORRECT INVERSE TRANSFORM REMOVED ---
# ypred = scaler.inverse_transform(ypred_scaled.reshape(-1, 1)).flatten()
# The model's output is already the final, unscaled prediction
ypred = ypred_raw_output
return ypred
def create_animated_metric(label, value, icon="🎯"):
st.markdown(f"""
<div class="metric-container">
<div style="font-size: 1.2rem;">{icon}</div>
<div class="metric-value">{value}</div>
<div class="metric-label">{label}</div>
</div>
""", unsafe_allow_html=True)
def sidebar_nav():
st.sidebar.markdown("""
<div style="text-align: center; padding: 20px;">
<div style="font-size: 4rem;">🌍</div>
<h1 style="color: #1f77b4; margin: 10px 0;">AuraClima</h1>
<p style="color: #FF7F0E; font-style: italic; margin-bottom: 20px;">
"See the unseen, act on the future"
</p>
<div class="ai-badge">🤖 AI-Powered</div>
<div class="ai-badge">⚡ Real-time</div>
</div>
""", unsafe_allow_html=True)
st.sidebar.markdown("---")
page = st.sidebar.radio("🚀 Navigate", ["🏠 Home", "🌍 Climate Intelligence", "ℹ️ About"],
label_visibility="collapsed")
return page
def home_page():
# Centered title
st.markdown('<h1 class="main-header">🌍 AuraClima</h1>', unsafe_allow_html=True)
# AI Features showcase
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="model-card">
<div style="text-align: center;">
<div style="font-size: 3rem; margin-bottom: 10px;">🌱</div>
<h3 style="color: #1f77b4;">Agricultural AI</h3>
<p style="color: #e0e6ed;">LSTM Time Series Forecasting</p>
<div class="ai-badge">Neural Network</div>
</div>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="model-card">
<div style="text-align: center;">
<div style="font-size: 3rem; margin-bottom: 10px;">📊</div>
<h3 style="color: #FF7F0E;">Feature Analysis</h3>
<p style="color: #e0e6ed;">Multi-variate Regression</p>
<div class="ai-badge">Deep Learning</div>
</div>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="model-card">
<div style="text-align: center;">
<div style="font-size: 3rem; margin-bottom: 10px;">💨</div>
<h3 style="color: #1f77b4;">CO₂ Intelligence</h3>
<p style="color: #e0e6ed;">Sequence-to-Sequence</p>
<div class="ai-badge">Advanced LSTM</div>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
st.markdown("""
<div style="text-align: center; padding: 30px;">
<h3 style="color: #1f77b4;">🚀 Advanced AI Climate Modeling</h3>
<p style="color: #e0e6ed; font-size: 1.1rem; max-width: 600px; margin: 0 auto;">
Leverage cutting-edge machine learning to forecast climate patterns, emissions, and environmental trends.
Our AI models process complex data to provide actionable insights for a sustainable future.
</p>
</div>
""", unsafe_allow_html=True)
def create_enhanced_plot(hist_years, series_co2, fut_years, pred3, country):
# Create subplot with secondary y-axis for better visualization
fig = make_subplots(
rows=1, cols=1,
subplot_titles=[f"🌍 AI Climate Intelligence: {country}"],
specs=[[{"secondary_y": False}]]
)
# Historical data
fig.add_trace(
go.Scatter(
x=hist_years,
y=series_co2,
mode='lines+markers',
name='Historical Emissions',
line=dict(color='#1f77b4', width=3),
marker=dict(size=6, color='#1f77b4'),
hovertemplate='<b>Year:</b> %{x}<br><b>CO₂:</b> %{y:.2f}<extra></extra>'
)
)
# Forecast data
fig.add_trace(
go.Scatter(
x=fut_years,
y=pred3,
mode='lines+markers',
name='AI Forecast',
line=dict(color='#FF7F0E', width=4, dash='dash'),
marker=dict(size=8, color='#FF7F0E', symbol='diamond'),
hovertemplate='<b>Year:</b> %{x}<br><b>Predicted CO₂:</b> %{y:.2f}<extra></extra>'
)
)
# Connection line
fig.add_trace(
go.Scatter(
x=[hist_years[-1], fut_years[0]],
y=[series_co2[-1], pred3[0]],
mode='lines',
name='Transition',
line=dict(color='#2ca02c', width=2, dash='dot'),
showlegend=False
)
)
# Update layout with dark theme
fig.update_layout(
title=dict(
text=f"<b>CO₂ Emissions Forecast for {country}</b>",
x=0.5,
font=dict(size=18, color='white')
),
xaxis_title="Year",
yaxis_title="CO₂ Emissions",
plot_bgcolor='rgba(0,0,0,0)',
paper_bgcolor='rgba(0,0,0,0)',
font=dict(color='white'),
legend=dict(
bgcolor='rgba(30, 37, 48, 0.8)',
bordercolor='#1f77b4',
borderwidth=1
),
hovermode='x unified'
)
# Update axes
fig.update_xaxes(
gridcolor='rgba(31, 119, 180, 0.2)',
griddash='dash',
showgrid=True
)
fig.update_yaxes(
gridcolor='rgba(31, 119, 180, 0.2)',
griddash='dash',
showgrid=True
)
return fig
def forecast_by_country(data):
st.markdown('<h2 style="color: #1f77b4; text-align: center;">🌍 Climate Intelligence Dashboard</h2>',
unsafe_allow_html=True)
model1, scaler1 = data["model1"], data["scaler1"]
model2, scalerX2, scalerY2, feature_cols2 = data["model2"], data["scalerX2"], data["scalerY2"], data[
"feature_cols2"]
model3, scaler3 = data["model3"], data["scaler3"]
df_agri, df_co2 = data["df_agri"], data["df_co2"]
if df_agri is None:
st.error("🚨 Agricultural dataset not found. Climate Intelligence unavailable.")
return
countries = sorted(df_agri['Area'].dropna().unique())
# Enhanced country selector
st.markdown("""
<div style="text-align: center; margin: 20px 0;">
<h4 style="color: #FF7F0E;">🎯 Select Country for AI Analysis</h4>
</div>
""", unsafe_allow_html=True)
country = st.selectbox("", countries, label_visibility="collapsed")
if not country:
return
df_ct = df_agri[df_agri['Area'] == country].sort_values('Year')
latest_year = int(df_ct['Year'].max())
# Create three columns for models
st.markdown("---")
st.markdown('<h3 style="color: #1f77b4; text-align: center;">🤖 AI Model Predictions</h3>', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
# Model 1 - LSTM Forecast
with col1:
st.markdown("""
<div class="forecast-section">
<h4 style="color: #1f77b4;">🌱 LSTM Time Series</h4>
<p style="color: #e0e6ed; font-size: 0.9rem;">Neural network analyzing temporal patterns</p>
</div>
""", unsafe_allow_html=True)
inp1 = model1.input_shape
window1 = inp1[1]
series1 = df_ct.set_index('Year')['total_emission']
years1 = sorted(series1.index)
if len(years1) >= window1:
recent_vals = series1.loc[years1[-window1:]].values
with st.spinner("🔄 AI Processing..."):
pred1 = forecast_model1(model1, scaler1, recent_vals)
create_animated_metric("Next Year Emission", f"{pred1:.2f}", "🌱")
else:
st.info(f"⚠️ Need ≥{window1} years of data")
# Model 2 - Feature Analysis
with col2:
st.markdown("""
<div class="forecast-section">
<h4 style="color: #FF7F0E;">📊 Feature Analysis</h4>
<p style="color: #e0e6ed; font-size: 0.9rem;">Multi-variate regression modeling</p>
</div>
""", unsafe_allow_html=True)
row_latest = df_ct[df_ct['Year'] == latest_year].iloc[0]
feature_array = []
for col in feature_cols2:
if col.startswith("Area_"):
feature_array.append(1.0 if col == f"Area_{country}" else 0.0)
else:
val = row_latest.get(col, 0.0)
feature_array.append(float(val))
try:
with st.spinner("🔄 Analyzing features..."):
pred2 = predict_model2(model2, scalerX2, scalerY2, feature_array)
create_animated_metric("Feature Prediction", f"{pred2:.2f}", "📊")
except Exception as e:
st.error(f"❌ Model error: {e}")
# Model 3 - CO2 Intelligence
with col3:
st.markdown("""
<div class="forecast-section">
<h4 style="color: #1f77b4;">💨 CO₂ Intelligence</h4>
<p style="color: #e0e6ed; font-size: 0.9rem;">Advanced sequence modeling</p>
</div>
""", unsafe_allow_html=True)
if df_co2 is not None:
dfc = df_co2[df_co2['Country Name'] == country]
country_features = data["country_features"]
country_vec = np.zeros(len(country_features))
for i, name in enumerate(country_features):
if name == f"Country_{country}":
country_vec[i] = 1
break
if not dfc.empty:
year_cols = [c for c in dfc.columns if c.isdigit()]
series_co2 = dfc.iloc[0][year_cols].astype(float).values
inp3 = model3.input_shape
window3 = inp3[1]
if len(series_co2) >= window3:
recent3 = series_co2[-window3:]
with st.spinner("🔄 CO₂ forecasting..."):
pred3 = forecast_model3(model3, scaler3, recent3, country_vec)
avg_forecast = np.mean(pred3)
create_animated_metric("Avg CO₂ Forecast", f"{avg_forecast:.2f}", "💨")
else:
st.info(f"⚠️ Need ≥{window3} years")
else:
st.error("❌ CO₂ data unavailable")
# Interactive Parameter Tuning
st.markdown("---")
st.markdown('<h3 style="color: #FF7F0E; text-align: center;">⚙️ Interactive Parameter Tuning</h3>',
unsafe_allow_html=True)
with st.expander("🎛️ Adjust Model Parameters", expanded=False):
st.markdown("**Modify features to explore different scenarios:**")
tweaked = []
cols_numeric = [c for c in feature_cols2 if not c.startswith("Area_")]
cols = st.columns(2)
for i, col in enumerate(feature_cols2):
if col.startswith("Area_"):
tweaked.append(feature_array[i])
else:
series_col = df_agri[col].dropna().astype(float)
if not series_col.empty:
mn, mx = float(series_col.min()), float(series_col.max())
default = feature_array[i]
slider_val = cols[i % 2].slider(f"🔧 {col}", mn, mx, default, key=f"slider_{col}")
tweaked.append(slider_val)
else:
tweaked.append(feature_array[i])
if st.button("🚀 Run Enhanced Prediction"):
try:
with st.spinner("🤖 AI recalculating..."):
pred2b = predict_model2(model2, scalerX2, scalerY2, tweaked)
create_animated_metric("Adjusted Prediction", f"{pred2b:.2f}", "🎯")
except Exception as e:
st.error(f"❌ Error: {e}")
# Enhanced CO2 Visualization
if df_co2 is not None and not dfc.empty and len(series_co2) >= window3:
st.markdown("---")
st.markdown('<h3 style="color: #1f77b4; text-align: center;">📈 Advanced CO₂ Visualization</h3>',
unsafe_allow_html=True)
hist_years = list(map(int, year_cols))
last_year = hist_years[-1]
fut_years = [last_year + i + 1 for i in range(len(pred3))]
# Create enhanced interactive plot
fig = create_enhanced_plot(hist_years, series_co2, fut_years, pred3, country)
st.plotly_chart(fig, use_container_width=True)
# Forecast summary table
st.markdown('<h4 style="color: #FF7F0E;">📋 Detailed Forecast Summary</h4>', unsafe_allow_html=True)
forecast_df = pd.DataFrame({
'🗓️ Year': fut_years,
'💨 Predicted CO₂': [f"{val:.2f}" for val in pred3],
'📈 Trend': ['↗️' if i == 0 or pred3[i] > pred3[i - 1] else '↘️' for i in range(len(pred3))]
})
st.dataframe(forecast_df, use_container_width=True)
def about_page():
st.markdown('<h1 class="main-header">🌍 AuraClima</h1>', unsafe_allow_html=True)
st.markdown('<p class="subtitle">Advanced AI Climate Intelligence Platform</p>', unsafe_allow_html=True)
st.markdown("""
<div class="model-card">
<h3 style="color: #1f77b4;">🎯 Mission</h3>
<p style="color: #e0e6ed;">
AuraClima leverages cutting-edge artificial intelligence to forecast climate patterns and emissions,
empowering decision-makers to "See the unseen, act on the future."
</p>
</div>
""", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.markdown("""
<div class="model-card">
<h4 style="color: #FF7F0E;">🤖 Technology Stack</h4>
<div class="ai-badge">TensorFlow</div>
<div class="ai-badge">LSTM Networks</div>
<div class="ai-badge">Neural Networks</div>
<div class="ai-badge">Time Series</div>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="model-card">
<h4 style="color: #1f77b4;">🎨 Brand Identity</h4>
<p style="color: #e0e6ed;">
<strong>Primary:</strong> <span style="color: #1f77b4;">Blue (#1f77b4)</span><br>
<strong>Secondary:</strong> <span style="color: #FF7F0E;">Orange (#FF7F0E)</span>
</p>
</div>
""", unsafe_allow_html=True)
st.markdown("""
<div style="text-align: center; margin-top: 30px;">
<p style="color: #e0e6ed;">
<strong>Developed by:</strong> Abdullah Imran<br>
<strong>Contact:</strong> [email protected]
</p>
</div>
""", unsafe_allow_html=True)
# Main Application
def main():
# Load resources once
data = load_all()
# Sidebar navigation
page = sidebar_nav()
# Page routing
if page == "🏠 Home":
home_page()
elif page == "🌍 Climate Intelligence":
forecast_by_country(data)
elif page == "ℹ️ About":
about_page()
if __name__ == "__main__":
main()
|