CoolFace
Apppublic

Campfireman/temperature_pred

sourceHugging Faceapache-2.0updated 4y agoView on Hugging Face
0likes
app.py127 linesDownload Raw Back to root
1import gradio as gr2import hopsworks3import joblib4import pandas as pd5import numpy as np6import folium7import sklearn.preprocessing as proc8import json9import time10from datetime import timedelta, datetime11from branca.element import Figure12 13from functions import decode_features, get_weather_data, get_weather_df, get_weather_json_quick14##################15 16def greet(total_pred_days):    17    str1 = ""18    19    if(total_pred_days == ""):20        return "Empty input"21    22    count = int(total_pred_days) 23    if count > 14:24        str1 += "Warning: 14 days at most. " + '\n'25        count = 1426    if count <0:27        str1 = "Invalid input."28        return str129    count = count + 130    31    X = pd.DataFrame()32    33    for i in range(count+1):34        # Get, rename column and rescale35        next_day_date = datetime.today() + timedelta(days=i)36        next_day = next_day_date.strftime ('%Y-%m-%d')37        json = get_weather_json_quick(next_day)38        temp = get_weather_data(json)39        X = X.append(temp, ignore_index=True)40    41    42    # X reshape43    44    X.drop('preciptype', inplace = True, axis = 1)45    X.drop('severerisk', inplace = True, axis = 1)46    X.drop('stations', inplace = True, axis = 1)47    X.drop('sunrise', inplace = True, axis = 1)48    X.drop('sunset', inplace = True, axis = 1)49    X.drop('moonphase', inplace = True, axis = 1)50    X.drop('description', inplace = True, axis = 1)51    X.drop('icon', inplace = True, axis = 1)52    X = X.drop(columns=["sunriseEpoch", "sunsetEpoch", "source", "datetimeEpoch"]).fillna(0) 53    X = X.rename(columns={'pressure':'sealevelpressure'})54    55    # Merge X and query56    #Y = X.append(Q, ignore_index=True)57    58    # Data scaling59    X = X.drop(columns = ['conditions', "datetime", "temp", "tempmax", "tempmin"])60    category_cols = ['conditions']61    cat_std_cols = ['feelslikemax','feelslikemin','feelslike','dew','humidity','precip','precipprob','precipcover','snow','snowdepth','windgust','windspeed','winddir','sealevelpressure','cloudcover','visibility','solarradiation','solarenergy','uvindex']62    scaler_std = proc.StandardScaler()63    X.insert(19,"conditions",0)64    X.insert(0,"name",0)65    66    X[cat_std_cols] = scaler_std.fit_transform(X[cat_std_cols])67    X[category_cols] = scaler_std.fit_transform(X[category_cols])68    69    # Predict70    preds = model.predict(X[0:count])71    preds1= model1.predict(X[0:count])72    preds2= model2.predict(X[0:count])73    74    for x in range(count):75        if (x != 0):76            str1 += (datetime.now() + timedelta(days=x)).strftime('%Y-%m-%d') + " predicted temperature: " +str(float(preds[len(preds) - count + x]))+ "\npredicted max temperature: " +str(float(preds1[len(preds1) - count + x]))+ "\npredicted min temperature: " +str(float(preds2[len(preds2) - count + x]))+"\n"77    78    return str179 80#######################################################81# Preparations82project = hopsworks.login()83mr=project.get_model_registry()84 85# fs = project.get_feature_store()86# weather_fg = fs.get_or_create_feature_group(87#     name = 'weather_fg',88#     version = 189# )90# 91# query = weather_fg.select_all()92# Q = query.read()93 94model = mr.get_model("temp_model_new", version=1)95model_dir=model.download()96 97model1 = mr.get_model("tempmax_model_new", version=1) 98model_dir1=model1.download()99 100model2 = mr.get_model("tempmin_model_new", version=1)101model_dir2=model2.download()102 103model = joblib.load(model_dir + "/model_temp_new.pkl")104model1 = joblib.load(model_dir1 + "/model_tempmax_new.pkl")105model2 = joblib.load(model_dir2+ "/model_tempmin_new.pkl")106 107 108########################################################109# Gradio Interface110#demo = gr.Interface(fn=greet, inputs = "text", outputs="text")111 112with gr.Blocks() as demo:113    with gr.Row():114        with gr.Column():115            days = gr.Slider(116                label="How many days do you want to predict the temperature of? ", value=1, minimum=1, maximum=15, step=1117            )118        with gr.Column():119            output = gr.Textbox(120                label="Predicted results: "121            )122        days.change(greet, days, output)123        124    125if __name__ == "__main__":126    demo.launch()127