Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,6 +5,7 @@ import joblib
|
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
from datetime import datetime
|
| 7 |
from typing import List
|
|
|
|
| 8 |
|
| 9 |
# Import your utility scripts from the 'src' directory
|
| 10 |
try:
|
|
@@ -306,30 +307,40 @@ else:
|
|
| 306 |
|
| 307 |
|
| 308 |
# --- CRITICAL CUSTOMIZATION (Hourly Targets) ---
|
| 309 |
-
HOURLY_TARGET_COLS = ['target_temp_next_24h', 'target_temp_next_48h', 'target_temp_next_72h',
|
| 310 |
-
'target_temp_next_96h', 'target_temp_next_120h']
|
| 311 |
|
| 312 |
# Load models và data mới
|
| 313 |
-
hourly_data_df = load_hourly_data(file_path="data/
|
| 314 |
hourly_models_24h = load_24_hourly_models() # Dùng 24 mô hình LGBM
|
| 315 |
hourly_agg_model = load_hourly_aggregate_model() # Dùng mô hình Aggregate T+24h
|
| 316 |
|
| 317 |
-
# Tạo input features cho Hourly
|
| 318 |
if not hourly_data_df.empty:
|
| 319 |
HOURLY_FEATURE_COLS = [col for col in hourly_data_df.columns if col not in HOURLY_TARGET_COLS]
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
else:
|
| 322 |
X_test_hourly = pd.DataFrame()
|
| 323 |
|
| 324 |
-
# --- Định nghĩa Hàm Dự đoán 24h Thực tế ---
|
| 325 |
def predict_next_24_hours(input_features: pd.DataFrame, models: dict) -> List[float]:
|
| 326 |
-
|
| 327 |
predictions = []
|
| 328 |
num_horizons = len(models)
|
| 329 |
|
| 330 |
if input_features.empty or not models:
|
| 331 |
# Nếu thiếu model, tạo 24 giá trị giả lập dựa trên nhiệt độ hiện tại (temp)
|
| 332 |
last_temp = input_features['temp'].iloc[-1] if not input_features.empty else 28.0
|
|
|
|
|
|
|
| 333 |
return [last_temp + 1.5 * np.sin(2 * np.pi * (h + 10) / 24) + np.random.normal(0, 0.5)
|
| 334 |
for h in range(num_horizons)]
|
| 335 |
|
|
@@ -337,7 +348,6 @@ def predict_next_24_hours(input_features: pd.DataFrame, models: dict) -> List[fl
|
|
| 337 |
for h in range(1, num_horizons + 1):
|
| 338 |
try:
|
| 339 |
model = models[h]
|
| 340 |
-
# Predict chỉ 1 giá trị
|
| 341 |
pred = model.predict(input_features)[0]
|
| 342 |
predictions.append(pred)
|
| 343 |
except:
|
|
@@ -731,7 +741,6 @@ with tab3:
|
|
| 731 |
else:
|
| 732 |
st.warning("Loading performance data...")
|
| 733 |
|
| 734 |
-
|
| 735 |
# --- TAB 4: Hourly Prediction ---
|
| 736 |
with tab4:
|
| 737 |
st.title("Hourly Prediction (Next 24 Hours) 🌡️")
|
|
@@ -742,25 +751,46 @@ with tab4:
|
|
| 742 |
st.subheader("Forecast Start Time")
|
| 743 |
|
| 744 |
if not X_test_hourly.empty:
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
|
|
|
| 753 |
format="YYYY-MM-DD"
|
| 754 |
)
|
| 755 |
|
| 756 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 757 |
input_features_hourly = X_test_hourly.loc[[latest_time_for_day]]
|
| 758 |
|
| 759 |
st.info(f"The model runs based on data up to the latest known hour: **{latest_time_for_day.strftime('%Y-%m-%d %H:%M:%S')}**")
|
| 760 |
-
|
| 761 |
st.divider()
|
| 762 |
|
| 763 |
-
#
|
| 764 |
predictions_24h = predict_next_24_hours(input_features_hourly, hourly_models_24h)
|
| 765 |
|
| 766 |
# --- TÍNH TOÁN METRIC T+24H CHÍNH XÁC ---
|
|
@@ -768,11 +798,13 @@ with tab4:
|
|
| 768 |
if hourly_agg_model:
|
| 769 |
# Model Aggregated Day 1 (từ file bạn gửi) dự đoán T+24h
|
| 770 |
try:
|
|
|
|
| 771 |
t_plus_24h_metric = hourly_agg_model.predict(input_features_hourly)[0]
|
| 772 |
except Exception as e:
|
| 773 |
-
|
|
|
|
| 774 |
|
| 775 |
-
#
|
| 776 |
st.subheader(f"Summary Forecast for Next Day (Starting {latest_time_for_day.strftime('%H:%M')})")
|
| 777 |
|
| 778 |
forecast_start_ts = latest_time_for_day + pd.Timedelta(hours=1)
|
|
@@ -789,15 +821,19 @@ with tab4:
|
|
| 789 |
# Sử dụng các giá trị từ 24 điểm dự báo để tính Max/Min/Mean 24h
|
| 790 |
if predictions_24h:
|
| 791 |
with col_daily_pred[1]:
|
| 792 |
-
|
|
|
|
| 793 |
with col_daily_pred[2]:
|
|
|
|
| 794 |
st.metric(label="Next 24h Max Temp", value=f"{np.nanmax(predictions_24h):.1f}°C", delta="Peak Heat")
|
| 795 |
-
|
| 796 |
st.markdown("---")
|
| 797 |
|
| 798 |
-
#
|
|
|
|
| 799 |
st.subheader("Hourly Temperature Breakdown (T+1h to T+24h)")
|
| 800 |
|
|
|
|
| 801 |
hourly_index = pd.date_range(start=forecast_start_ts, periods=len(predictions_24h), freq='H')
|
| 802 |
df_hourly_forecast = pd.DataFrame({
|
| 803 |
'Time': hourly_index,
|
|
@@ -823,7 +859,7 @@ with tab4:
|
|
| 823 |
)
|
| 824 |
st.plotly_chart(fig_hourly, use_container_width=True)
|
| 825 |
|
| 826 |
-
#
|
| 827 |
st.markdown("---")
|
| 828 |
with st.expander("🔍 Feature Inspector: Hourly Inputs for the Forecast"):
|
| 829 |
if not input_features_hourly.empty:
|
|
@@ -846,5 +882,6 @@ with tab4:
|
|
| 846 |
st.metric(label=label, value=f"{value:.2f}")
|
| 847 |
else:
|
| 848 |
st.warning("No hourly feature data available for the selected hour.")
|
|
|
|
| 849 |
else:
|
| 850 |
st.warning("Please wait... Loading hourly data or models.")
|
|
|
|
| 5 |
import plotly.graph_objects as go
|
| 6 |
from datetime import datetime
|
| 7 |
from typing import List
|
| 8 |
+
import numpy as np
|
| 9 |
|
| 10 |
# Import your utility scripts from the 'src' directory
|
| 11 |
try:
|
|
|
|
| 307 |
|
| 308 |
|
| 309 |
# --- CRITICAL CUSTOMIZATION (Hourly Targets) ---
|
| 310 |
+
HOURLY_TARGET_COLS = ['target_temp_next_24h', 'target_temp_next_48h', 'target_temp_next_72h',
|
| 311 |
+
'target_temp_next_96h', 'target_temp_next_120h']
|
| 312 |
|
| 313 |
# Load models và data mới
|
| 314 |
+
hourly_data_df = load_hourly_data(file_path="data/final_hourly_features_demo.xlsx - Sheet1.csv") # Dùng tên file features demo chính xác
|
| 315 |
hourly_models_24h = load_24_hourly_models() # Dùng 24 mô hình LGBM
|
| 316 |
hourly_agg_model = load_hourly_aggregate_model() # Dùng mô hình Aggregate T+24h
|
| 317 |
|
| 318 |
+
# Tạo input features cho Hourly
|
| 319 |
if not hourly_data_df.empty:
|
| 320 |
HOURLY_FEATURE_COLS = [col for col in hourly_data_df.columns if col not in HOURLY_TARGET_COLS]
|
| 321 |
+
|
| 322 |
+
# Lấy test set
|
| 323 |
+
X_test_hourly = hourly_data_df.loc[TEST_START_DATE:TEST_END_DATE][HOURLY_FEATURE_COLS].copy()
|
| 324 |
+
|
| 325 |
+
# FIX LỖI 1 (Model Prediction Dtypes): Loại bỏ các cột object (sunrise/sunset)
|
| 326 |
+
columns_to_drop_objects = ['sunrise', 'sunset']
|
| 327 |
+
X_test_hourly = X_test_hourly.drop(columns=columns_to_drop_objects, errors='ignore')
|
| 328 |
+
|
| 329 |
+
HOURLY_FEATURE_COLS = X_test_hourly.columns.tolist() # Cập nhật lại feature list sau khi drop
|
| 330 |
else:
|
| 331 |
X_test_hourly = pd.DataFrame()
|
| 332 |
|
| 333 |
+
# --- Định nghĩa Hàm Dự đoán 24h Thực tế (Giữ nguyên logic bên trong) ---
|
| 334 |
def predict_next_24_hours(input_features: pd.DataFrame, models: dict) -> List[float]:
|
| 335 |
+
# ... (Code hàm này giữ nguyên như lần trước)
|
| 336 |
predictions = []
|
| 337 |
num_horizons = len(models)
|
| 338 |
|
| 339 |
if input_features.empty or not models:
|
| 340 |
# Nếu thiếu model, tạo 24 giá trị giả lập dựa trên nhiệt độ hiện tại (temp)
|
| 341 |
last_temp = input_features['temp'].iloc[-1] if not input_features.empty else 28.0
|
| 342 |
+
# Dùng np đã được import
|
| 343 |
+
np.random.seed(42)
|
| 344 |
return [last_temp + 1.5 * np.sin(2 * np.pi * (h + 10) / 24) + np.random.normal(0, 0.5)
|
| 345 |
for h in range(num_horizons)]
|
| 346 |
|
|
|
|
| 348 |
for h in range(1, num_horizons + 1):
|
| 349 |
try:
|
| 350 |
model = models[h]
|
|
|
|
| 351 |
pred = model.predict(input_features)[0]
|
| 352 |
predictions.append(pred)
|
| 353 |
except:
|
|
|
|
| 741 |
else:
|
| 742 |
st.warning("Loading performance data...")
|
| 743 |
|
|
|
|
| 744 |
# --- TAB 4: Hourly Prediction ---
|
| 745 |
with tab4:
|
| 746 |
st.title("Hourly Prediction (Next 24 Hours) 🌡️")
|
|
|
|
| 751 |
st.subheader("Forecast Start Time")
|
| 752 |
|
| 753 |
if not X_test_hourly.empty:
|
| 754 |
+
min_ts = X_test_hourly.index.min()
|
| 755 |
+
max_ts = X_test_hourly.index.max()
|
| 756 |
+
|
| 757 |
+
# 1. Date Selection
|
| 758 |
+
selected_date = st.date_input(
|
| 759 |
+
"Select the date:",
|
| 760 |
+
value=max_ts.date(), # Mặc định chọn ngày cuối cùng
|
| 761 |
+
min_value=min_ts.date(),
|
| 762 |
+
max_value=max_ts.date(),
|
| 763 |
format="YYYY-MM-DD"
|
| 764 |
)
|
| 765 |
|
| 766 |
+
# 2. Hour Selection (Chỉ show các giờ có sẵn trong ngày đã chọn)
|
| 767 |
+
available_hours_in_day = X_test_hourly[X_test_hourly.index.date == selected_date].index.hour.unique().sort_values()
|
| 768 |
+
|
| 769 |
+
if available_hours_in_day.empty:
|
| 770 |
+
st.warning(f"No hourly data found for {selected_date}. Please select a different date.")
|
| 771 |
+
st.stop()
|
| 772 |
+
|
| 773 |
+
# Chọn giờ: Mặc định chọn giờ muộn nhất trong ngày (latest known hour)
|
| 774 |
+
default_hour = available_hours_in_day.max()
|
| 775 |
+
default_hour_index = available_hours_in_day.get_loc(default_hour)
|
| 776 |
+
|
| 777 |
+
selected_hour = st.selectbox(
|
| 778 |
+
"Select the latest known hour:",
|
| 779 |
+
options=available_hours_in_day.tolist(),
|
| 780 |
+
index=default_hour_index,
|
| 781 |
+
format_func=lambda x: f"{x:02d}:00:00"
|
| 782 |
+
)
|
| 783 |
+
|
| 784 |
+
# Kết hợp ngày và giờ thành Timestamp duy nhất
|
| 785 |
+
latest_time_for_day = pd.to_datetime(f"{selected_date} {selected_hour:02d}:00:00")
|
| 786 |
+
|
| 787 |
+
# Lấy Input Features cho timestamp đã chọn
|
| 788 |
input_features_hourly = X_test_hourly.loc[[latest_time_for_day]]
|
| 789 |
|
| 790 |
st.info(f"The model runs based on data up to the latest known hour: **{latest_time_for_day.strftime('%Y-%m-%d %H:%M:%S')}**")
|
|
|
|
| 791 |
st.divider()
|
| 792 |
|
| 793 |
+
# 3. Chạy Dự đoán Hourly (GỌI HÀM THỰC TẾ)
|
| 794 |
predictions_24h = predict_next_24_hours(input_features_hourly, hourly_models_24h)
|
| 795 |
|
| 796 |
# --- TÍNH TOÁN METRIC T+24H CHÍNH XÁC ---
|
|
|
|
| 798 |
if hourly_agg_model:
|
| 799 |
# Model Aggregated Day 1 (từ file bạn gửi) dự đoán T+24h
|
| 800 |
try:
|
| 801 |
+
# Features đã được dọn dẹp ở Section 4
|
| 802 |
t_plus_24h_metric = hourly_agg_model.predict(input_features_hourly)[0]
|
| 803 |
except Exception as e:
|
| 804 |
+
# Xử lý lỗi model Prediction (đã được sửa lỗi Dtypes, chỉ in lỗi khác nếu có)
|
| 805 |
+
st.error(f"Error predicting T+24h with loaded model: {e}")
|
| 806 |
|
| 807 |
+
# 4. Hiển thị Dự đoán T+24h (Tức là giờ đó ngày mai)
|
| 808 |
st.subheader(f"Summary Forecast for Next Day (Starting {latest_time_for_day.strftime('%H:%M')})")
|
| 809 |
|
| 810 |
forecast_start_ts = latest_time_for_day + pd.Timedelta(hours=1)
|
|
|
|
| 821 |
# Sử dụng các giá trị từ 24 điểm dự báo để tính Max/Min/Mean 24h
|
| 822 |
if predictions_24h:
|
| 823 |
with col_daily_pred[1]:
|
| 824 |
+
# Sử dụng np đã được import
|
| 825 |
+
st.metric(label="Next 24h Average Temp", value=f"{np.nanmean(predictions_24h):.1f}°C")
|
| 826 |
with col_daily_pred[2]:
|
| 827 |
+
# Sử dụng np đã được import
|
| 828 |
st.metric(label="Next 24h Max Temp", value=f"{np.nanmax(predictions_24h):.1f}°C", delta="Peak Heat")
|
| 829 |
+
|
| 830 |
st.markdown("---")
|
| 831 |
|
| 832 |
+
# 5. Graph: Nhiệt độ Từng Giờ
|
| 833 |
+
|
| 834 |
st.subheader("Hourly Temperature Breakdown (T+1h to T+24h)")
|
| 835 |
|
| 836 |
+
# ... (Biểu đồ giữ nguyên)
|
| 837 |
hourly_index = pd.date_range(start=forecast_start_ts, periods=len(predictions_24h), freq='H')
|
| 838 |
df_hourly_forecast = pd.DataFrame({
|
| 839 |
'Time': hourly_index,
|
|
|
|
| 859 |
)
|
| 860 |
st.plotly_chart(fig_hourly, use_container_width=True)
|
| 861 |
|
| 862 |
+
# 6. Hiển thị Features Dùng để Dự đoán (Giữ nguyên)
|
| 863 |
st.markdown("---")
|
| 864 |
with st.expander("🔍 Feature Inspector: Hourly Inputs for the Forecast"):
|
| 865 |
if not input_features_hourly.empty:
|
|
|
|
| 882 |
st.metric(label=label, value=f"{value:.2f}")
|
| 883 |
else:
|
| 884 |
st.warning("No hourly feature data available for the selected hour.")
|
| 885 |
+
|
| 886 |
else:
|
| 887 |
st.warning("Please wait... Loading hourly data or models.")
|