Download app.py from uijnbh/traffic: direct link, hf CLI and curl.
- Browser
- Download file 6.83 kB
-
https://huggingface.co/spaces/uijnbh/traffic/resolve/main/app.py
- Command line
-
hf download hf://spaces/uijnbh/traffic/app.py
-
curl -L -o app.py https://huggingface.co/spaces/uijnbh/traffic/resolve/main/app.py
6.83 kB
| """ | |
| 7 day traffic prediction app with weather overlay | |
| """ | |
| import os | |
| import pickle | |
| import csv | |
| from datetime import datetime, timedelta | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import matplotlib.patches as mpatches | |
| import requests | |
| import gradio as gr | |
| PATH = "" | |
| MPATH = PATH + "models/" | |
| LPPATH = PATH + "label_pipelines/" | |
| FPPATH = PATH + "feature_pipelines/" | |
| EARLIEST_DATE = pd.Timestamp("2021-07-27 00:00:00") | |
| TREND_SLOPE, TREND_CONST = 8.139236772671385, 126125.49286068974 | |
| LON, LAT = -33.886265, 18.595751 | |
| choices = ["Normal Day", "Special Day"] | |
| ROUNDING = -3 | |
| BASE_URL = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/" | |
| MID_URL = "/next7days?unitGroup=metric&include=days&key=" | |
| TIMEOUT = 10 | |
| def load_pickle(path: str): | |
| """ | |
| Load a pickle file | |
| """ | |
| try: | |
| with open(path, "rb") as file: | |
| return pickle.load(file) | |
| except FileNotFoundError as exc: | |
| raise FileNotFoundError(f"No file found at {path}") from exc | |
| def load_objects(): | |
| """ | |
| Load model objects | |
| """ | |
| model_objects = {} | |
| model_objects["model"] = load_pickle(MPATH + "prophet_model.pkl") | |
| model_objects["label_scaler"] = load_pickle(LPPATH + "label_scaler.pkl") | |
| model_objects["feature_scaler"] = load_pickle(FPPATH + "feature_scaler.pkl") | |
| model_objects["feature_encoder"] = load_pickle(FPPATH + "feature_encoder.pkl") | |
| return model_objects | |
| def get_7day_weather(visual_crossing_api_key: str) -> pd.DataFrame: | |
| """ | |
| Get 7 day weather forecast from Visual Crossing | |
| """ | |
| url = ( | |
| f"{BASE_URL}{LON}%2C%20{LAT}{MID_URL}{visual_crossing_api_key}&contentType=csv" | |
| ) | |
| response = requests.request("GET", url, timeout=TIMEOUT) | |
| if response.status_code != 200: | |
| print("Unexpected Status code: ", response.status_code) | |
| return pd.DataFrame() | |
| csv_text = csv.DictReader(response.text.splitlines(), delimiter=",", quotechar='"') | |
| out = pd.DataFrame(csv_text) | |
| out.datetime = pd.to_datetime(out.datetime) | |
| out.loc[ | |
| out.conditions.isin(["Overcast", "Rain, Overcast", "Rain"]), "conditions" | |
| ] = "Rain, Overcast" | |
| out.conditions = out.conditions.str.replace(",", "") | |
| return ( | |
| out[["datetime", "temp", "precip", "windspeed", "conditions"]][1:] | |
| .reset_index(drop=True) | |
| .rename(columns={"datetime": "ds"}) | |
| ) | |
| def predict(model, label_scaler, feature_scaler, feature_encoder, input_data): | |
| """ | |
| Predict future traffic patterns | |
| """ | |
| features_to_scale = ["temp", "precip", "windspeed"] | |
| scaled_features = feature_scaler.transform(input_data[features_to_scale]) | |
| scaled_feature_columns = [f"{col}_s" for col in features_to_scale] | |
| continuous_data = pd.concat( | |
| [ | |
| input_data[["ds"]], | |
| pd.DataFrame(scaled_features, columns=scaled_feature_columns), | |
| ], | |
| axis=1, | |
| ) | |
| encoded_features = feature_encoder.transform(input_data[["flag", "conditions"]]) | |
| encoded_features_df = pd.DataFrame( | |
| encoded_features, | |
| columns=[ | |
| "flag_N", | |
| "flag_W", | |
| "conditions_Partially cloudy", | |
| "conditions_Rain Overcast", | |
| "conditions_Rain Partially cloudy", | |
| ], | |
| ) | |
| column_order = [ | |
| "ds", | |
| "temp_s", | |
| "precip_s", | |
| "windspeed_s", | |
| "flag_N", | |
| "flag_W", | |
| "conditions_Partially cloudy", | |
| "conditions_Rain Overcast", | |
| "conditions_Rain Partially cloudy", | |
| ] | |
| encoded_data = pd.concat([continuous_data, encoded_features_df], axis=1)[ | |
| column_order | |
| ] | |
| encoded_data["yhat"] = model.predict(encoded_data).yhat | |
| encoded_data["yhat_unscaled"] = label_scaler.inverse_transform( | |
| encoded_data[["yhat"]] | |
| ) | |
| encoded_data["days_since_start"] = (encoded_data.ds - EARLIEST_DATE).dt.days | |
| encoded_data["trend"] = encoded_data["days_since_start"] * TREND_SLOPE + TREND_CONST | |
| encoded_data["trended"] = round( | |
| encoded_data["yhat_unscaled"] + encoded_data["trend"], ROUNDING | |
| ) | |
| return encoded_data.trended | |
| def forecast_traffic(*day_selections): | |
| """ | |
| Generate traffic predictions based on user selections | |
| """ | |
| forecast = weather.copy() | |
| forecast["Iflag"] = list(day_selections) | |
| forecast.ds = pd.to_datetime(forecast.ds) | |
| forecast["dow"] = forecast.ds.dt.dayofweek | |
| isweekend = forecast.dow >= 5 | |
| forecast.loc[isweekend, "flag"] = "W" | |
| forecast.loc[~isweekend, "flag"] = "N" | |
| forecast.loc[forecast.Iflag == "Special Day", "flag"] = "I" | |
| forecast["traffic"] = predict( | |
| objects["model"], | |
| objects["label_scaler"], | |
| objects["feature_scaler"], | |
| objects["feature_encoder"], | |
| forecast, | |
| ) | |
| forecast["day"] = forecast.ds.dt.strftime("%A %d/%m/%Y") | |
| colors = [ | |
| ( | |
| "red" | |
| if flag == "I" | |
| else "green" if flag == "W" else "blue" if flag == "N" else "error" | |
| ) | |
| for flag in forecast["flag"] | |
| ] | |
| fig, ax = plt.subplots(figsize=(8, 5)) | |
| ax.bar(forecast.day, forecast.traffic, color=colors) | |
| ax.set_title("Predicted Traffic Volumes for the Next 7 Days", fontsize=14) | |
| plt.xticks(rotation=45, ha="right", fontsize=12) | |
| plt.tight_layout() | |
| blue_patch = mpatches.Patch(color="blue", label="Normal Day") | |
| green_patch = mpatches.Patch(color="green", label="Weekend") | |
| red_patch = mpatches.Patch(color="red", label="Special Day") | |
| ax.legend(handles=[blue_patch, green_patch, red_patch]) | |
| weather_out = weather[["ds", "conditions"]].rename(columns={"ds": "Date"}) | |
| weather_out.Date = weather_out.Date.dt.strftime("%Y-%m-%d") | |
| return ( | |
| fig, | |
| int(forecast.traffic.sum()), | |
| weather_out, | |
| ) | |
| objects = load_objects() | |
| api_key = os.environ["VISUAL_CROSSING_API_KEY"] | |
| today = datetime.today() | |
| daynames = [f'Tomorrow {(today + timedelta(days=1)).strftime("%A, %Y-%m-%d")}'] | |
| for i in range(6): | |
| daynames.append( | |
| f'Day {i+2} {(today + timedelta(days=i+2)).strftime("%A, %Y-%m-%d")}' | |
| ) | |
| weather = get_7day_weather(api_key) | |
| with gr.Blocks() as forecast_app: | |
| with gr.Column(): | |
| with gr.Row(): | |
| day_buttons = [ | |
| gr.Radio(value=choices[0], choices=choices, label=dn) for dn in daynames | |
| ] | |
| btn = gr.Button(value="Refresh") | |
| plot_output = gr.Plot(show_label = False) | |
| text_output = gr.Text(label="Seven Day Traffic Total:") | |
| dataframe_output = gr.DataFrame(label="Weather Forecast:") | |
| forecast_app.load( | |
| forecast_traffic, [*day_buttons], [plot_output, text_output, dataframe_output] | |
| ) | |
| btn.click( | |
| forecast_traffic, [*day_buttons], [plot_output, text_output, dataframe_output] | |
| ) | |
| if __name__ == "__main__": | |
| forecast_app.launch(share=True) | |