AbdullahImran commited on
Commit
2bb7850
·
1 Parent(s): 091a7e7
Files changed (1) hide show
  1. streamlit_app.py +38 -7
streamlit_app.py CHANGED
@@ -385,7 +385,7 @@ def create_enhanced_plot(hist_years, series_co2, fut_years, pred3, country):
385
  return fig
386
 
387
 
388
- def forecast_by_country(data):
389
  st.markdown('<h2 style="color: #1f77b4; text-align: center;">🌍 Climate Intelligence Dashboard</h2>',
390
  unsafe_allow_html=True)
391
 
@@ -413,7 +413,7 @@ def forecast_by_country(data):
413
  if not country:
414
  return
415
 
416
- df_ct = df_agri[df_agri['Area'] == country].sort_values('Year')
417
  latest_year = int(df_ct['Year'].max())
418
 
419
  # Create three columns for models
@@ -483,28 +483,59 @@ def forecast_by_country(data):
483
  country_features = data["country_features"]
484
  country_vec = np.zeros(len(country_features))
485
 
 
 
 
 
 
 
486
  for i, name in enumerate(country_features):
487
  if name == f"Country_{country}":
488
  country_vec[i] = 1
 
489
  break
490
 
 
 
 
 
 
 
491
  if not dfc.empty:
492
  year_cols = [c for c in dfc.columns if c.isdigit()]
493
- series_co2 = dfc.iloc[0][year_cols].astype(float).values
 
 
 
 
 
494
  inp3 = model3.input_shape
495
- window3 = inp3[1]
 
 
 
 
 
 
 
496
 
497
  if len(series_co2) >= window3:
498
  recent3 = series_co2[-window3:]
 
 
 
 
499
  with st.spinner("🔄 CO₂ forecasting..."):
500
  pred3 = forecast_model3(model3, scaler3, recent3, country_vec)
501
 
502
  avg_forecast = np.mean(pred3)
503
  create_animated_metric("Avg CO₂ Forecast", f"{avg_forecast:.2f}", "💨")
504
  else:
505
- st.info(f"⚠️ Need ≥{window3} years")
 
 
506
  else:
507
- st.error("❌ CO₂ data unavailable")
508
 
509
  # Interactive Parameter Tuning
510
  st.markdown("---")
@@ -560,7 +591,7 @@ def forecast_by_country(data):
560
  '💨 Predicted CO₂': [f"{val:.2f}" for val in pred3],
561
  '📈 Trend': ['↗️' if i == 0 or pred3[i] > pred3[i - 1] else '↘️' for i in range(len(pred3))]
562
  })
563
- st.dataframe(forecast_df, use_container_width=True)
564
 
565
 
566
  def about_page():
 
385
  return fig
386
 
387
 
388
+ def forecast_by_country(data, df_ct=None):
389
  st.markdown('<h2 style="color: #1f77b4; text-align: center;">🌍 Climate Intelligence Dashboard</h2>',
390
  unsafe_allow_html=True)
391
 
 
413
  if not country:
414
  return
415
 
416
+ df_ct = df_agri[df_ct['Area'] == country].sort_values('Year')
417
  latest_year = int(df_ct['Year'].max())
418
 
419
  # Create three columns for models
 
483
  country_features = data["country_features"]
484
  country_vec = np.zeros(len(country_features))
485
 
486
+ # --- START DEBUG PRINTS FOR COUNTRY VEC ---
487
+ print(f"DEBUG_M3: Selected Country: {country}")
488
+ print(f"DEBUG_M3: country_features (from load_all): {country_features[:5]}... ({len(country_features)} total)")
489
+ # --- END DEBUG PRINTS ---
490
+
491
+ found_country_in_features = False # New flag
492
  for i, name in enumerate(country_features):
493
  if name == f"Country_{country}":
494
  country_vec[i] = 1
495
+ found_country_in_features = True # Set flag
496
  break
497
 
498
+ # --- START DEBUG PRINTS FOR COUNTRY VEC ---
499
+ if not found_country_in_features:
500
+ print(f"DEBUG_M3: WARNING! '{country}' not found in country_features for one-hot encoding!")
501
+ print(f"DEBUG_M3: Generated country_vec (sum should be 1.0): {np.sum(country_vec)}")
502
+ # --- END DEBUG PRINTS ---
503
+
504
  if not dfc.empty:
505
  year_cols = [c for c in dfc.columns if c.isdigit()]
506
+
507
+ # Convert year columns to numeric, handling potential errors and ensuring order
508
+ series_co2_raw = dfc.iloc[0][year_cols].astype(float)
509
+ # Drop any remaining NaNs in the series (should be filled from preprocessing, but safety check)
510
+ series_co2 = series_co2_raw.dropna().values
511
+
512
  inp3 = model3.input_shape
513
+ window3 = inp3[1] # Expected window size from model's input shape
514
+
515
+ # --- START DEBUG PRINTS FOR SERIES_CO2 ---
516
+ print(f"DEBUG_M3: Original year_cols in df_co2: {year_cols}")
517
+ print(f"DEBUG_M3: Raw series_co2 (first 5, last 5): {series_co2[:5]} ... {series_co2[-5:]}")
518
+ print(f"DEBUG_M3: Length of series_co2: {len(series_co2)}")
519
+ print(f"DEBUG_M3: Model3 input window (window3): {window3}")
520
+ # --- END DEBUG PRINTS ---
521
 
522
  if len(series_co2) >= window3:
523
  recent3 = series_co2[-window3:]
524
+ # --- START DEBUG PRINTS FOR RECENT3 ---
525
+ print(f"DEBUG_M3: Recent {window3} values for prediction: {recent3}")
526
+ # --- END DEBUG PRINTS ---
527
+
528
  with st.spinner("🔄 CO₂ forecasting..."):
529
  pred3 = forecast_model3(model3, scaler3, recent3, country_vec)
530
 
531
  avg_forecast = np.mean(pred3)
532
  create_animated_metric("Avg CO₂ Forecast", f"{avg_forecast:.2f}", "💨")
533
  else:
534
+ st.info(f"⚠️ Need ≥{window3} years of CO₂ data for {country}. Found {len(series_co2)} years.")
535
+ else:
536
+ st.info(f"⚠️ No CO₂ data found for {country}.")
537
  else:
538
+ st.error("❌ CO₂ data unavailable. Please check CO2_Emissions_1960-2018.csv.")
539
 
540
  # Interactive Parameter Tuning
541
  st.markdown("---")
 
591
  '💨 Predicted CO₂': [f"{val:.2f}" for val in pred3],
592
  '📈 Trend': ['↗️' if i == 0 or pred3[i] > pred3[i - 1] else '↘️' for i in range(len(pred3))]
593
  })
594
+ st.dataframe(forecast_df, use_container_width=True)
595
 
596
 
597
  def about_page():