Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import pandas as pd | |
| import modules.plot_map as plot_map | |
| import modules.predict as predict | |
| from datetime import datetime, timedelta | |
| import numpy as np | |
| from modules.model import LSTMModel | |
| import torch | |
| import pickle | |
| with open("min_max_scalers.pkl", "rb") as f: | |
| loaded_scalers = pickle.load(f) | |
| scaler_list = loaded_scalers | |
| model_point = [] | |
| for i in range(55): # hoặc len(models) | |
| # model = torch.load(f"models/lstm_model_full_{i}.pt") | |
| model = LSTMModel(input_size=3, hidden_size=64) | |
| model.load_state_dict(torch.load(f"models/lstm_model_full_{i}.pt")) | |
| model.eval() # để đưa về chế độ đánh giá | |
| model_point.append(model) | |
| # Load dữ liệu | |
| df = pd.read_excel("output/AQI_PM25_VietNam.xlsx") | |
| # df = df[df['Datetime'] == "12:00 25/01/2025"] | |
| df['ID Vị Trí'] = df['Tên'].astype('category').cat.codes | |
| # Lấy danh sách các ID vị trí | |
| name_locations = df["Tên"].unique().tolist() | |
| # available_locations = df["ID Vị Trí"].unique().tolist() | |
| location_mapping = df.set_index('Tên')['ID Vị Trí'].to_dict() | |
| available_times = sorted(df["Datetime"].astype(str).unique().tolist()) | |
| print(name_locations) | |
| SEQ_LEN = 24 | |
| # Hàm tạo bản đồ | |
| def create_map(df, datetime_str): | |
| print(datetime_str) | |
| # df["Datetime"] = pd.to_datetime(df["Datetime"], format="%H:%M %d/%m/%Y", errors='coerce') | |
| # target_time = pd.to_datetime(datetime_str, format="%H:%M %d/%m/%Y") | |
| df = df[df['Datetime'] == datetime_str] | |
| # print(df) | |
| m = plot_map.plot_map(df) | |
| return m._repr_html_() # Xuất HTML của bản đồ | |
| # Hàm dự đoán AQI_PM2.5 cho 1 địa điểm | |
| def predict_aqi(location_id, datetime_str): | |
| print(location_mapping[location_id]) | |
| original_time = datetime.strptime(datetime_str, "%H:%M %d/%m/%Y") | |
| one_hour_later = original_time + timedelta(hours=1) | |
| formatted_time = one_hour_later.strftime("%H:%M %d/%m/%Y") | |
| pred_original, dataframe = predict.infer_and_append_aqi(df, location_mapping[location_id], datetime_str, scaler_list, model_point) | |
| print(dataframe[dataframe["Datetime"]==formatted_time]) | |
| return f"📍 Vị trí {location_id} - 🕒 {datetime_str}\n🔮 Dự đoán AQI_PM2.5 tại - {formatted_time}: {pred_original[0]:.2f}", dataframe[dataframe["Datetime"]==formatted_time] | |
| # Hàm chính hiển thị bản đồ và dữ liệu | |
| def show_map_and_data(datetime_str): | |
| map_html = create_map(df, datetime_str) | |
| return map_html, df[df['Datetime'] == datetime_str] | |
| # Gradio UI | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## 🌍 Bản đồ chất lượng không khí và dự đoán PM2.5") | |
| with gr.Row(): | |
| time_selector = gr.Dropdown( | |
| choices=available_times, | |
| label="🕒 Chọn thời gian (HH:MM dd/mm/yyyy)" | |
| ) | |
| with gr.Row(): | |
| map_display = gr.HTML() | |
| data_display = gr.Dataframe(interactive=False) | |
| btn = gr.Button("📍 Hiển thị bản đồ và dữ liệu hiện tại") | |
| btn.click(fn=show_map_and_data, inputs=[time_selector], outputs=[map_display, data_display]) | |
| gr.Markdown("## 🔍 Dự đoán AQI_PM2.5 tại vị trí cụ thể") | |
| location_selector = gr.Dropdown(choices=name_locations, label="Chọn Vị Trí", value=name_locations[0]) | |
| predict_btn = gr.Button("🔮 Dự đoán") | |
| predict_output = gr.Textbox(label="Kết quả dự đoán") | |
| predict_display = gr.Dataframe(interactive=False) | |
| predict_btn.click(fn=predict_aqi, inputs=[location_selector, time_selector], outputs=[predict_output, predict_display]) | |
| # Chạy | |
| # demo.launch(share=True) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |