josegoji commited on
Commit
c99bb2c
verified
1 Parent(s): 92db0a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -112
app.py CHANGED
@@ -1,112 +1,98 @@
1
- import re
2
- import pandas as pd
3
- import pickle
4
- import numpy as np
5
- from sklearn.preprocessing import MinMaxScaler
6
- import joblib
7
- from io import StringIO
8
- import gradio as gr
9
- import os
10
- import sys
11
- from json import load
12
- from skforecast.utils import load_forecaster
13
- from skforecast.preprocessing import RollingFeatures
14
- from sklearn.preprocessing import MinMaxScaler
15
- from sklearn.preprocessing import FunctionTransformer
16
- from sklearn.pipeline import Pipeline
17
- from exog_creation import create_exog
18
- import contextlib
19
- import warnings
20
- # Funci贸n para cargar el archivo CSV y mostrar las primeras 5 filas
21
- def load_csv(input_file):
22
- try:
23
- # Leer el archivo CSV
24
- df = pd.read_csv(input_file)
25
-
26
- # Verificar si el DataFrame est谩 vac铆o
27
- if df.empty:
28
- return "El archivo subido est谩 vac铆o o no tiene datos v谩lidos."
29
-
30
- # Retornar las primeras 5 filas como tabla HTML
31
- # return df.head().to_html()
32
- return df
33
- except Exception as e:
34
- return f"Error al procesar el archivo: {e}"
35
-
36
- def set_datetime_index(df):
37
- df['datetime'] = pd.to_datetime(df['datetime'])
38
- df = df.set_index('datetime')
39
- df = df.asfreq('h')
40
- return df
41
-
42
- def load_model(name):
43
- current_dir = os.getcwd()
44
- ROOT_PATH = os.path.dirname(current_dir)
45
- sys.path.insert(1, ROOT_PATH)
46
- import root
47
- model = load_forecaster(root.DIR_DATA_ANALYTICS + name,
48
- verbose=True)
49
- return model
50
-
51
- def load_pipeline(name):
52
- with open('pipeline.pkl', 'rb') as file:
53
- pipeline = pickle.load(file)
54
- return pipeline
55
-
56
-
57
- def flujo(input_file):
58
-
59
- warnings.filterwarnings("ignore")
60
-
61
- datos = load_csv("archivo.csv")
62
-
63
- datos = set_datetime_index(datos)
64
-
65
- datos_exog = create_exog(datos)
66
-
67
- # Redirigir stdout a os.devnull para suprimir cualquier impresi贸n
68
- sys.stdout = open(os.devnull, 'w')
69
-
70
- # Cargar el modelo
71
- forecaster = load_model('tree_model.joblib')
72
-
73
- # Restaurar stdout a la consola
74
- sys.stdout = sys.__stdout__
75
-
76
- exog_selectec = ['temperature', 'rain', 'surface_pressure', 'cloudcover_total', 'windspeed_10m', 'winddirection_10m', 'shortwave_radiation', 'euros_per_mwh', 'installed_capacity', 'hour_sin', 'poly_month_sin__week_sin', 'poly_month_sin__week_cos', 'poly_month_sin__day_of_week_sin', 'poly_month_sin__day_of_week_cos', 'poly_month_sin__hour_sin', 'poly_month_sin__hour_cos', 'poly_month_sin__sunrise_hour_cos', 'poly_month_cos__week_sin', 'poly_month_cos__day_of_week_sin', 'poly_month_cos__day_of_week_cos', 'poly_month_cos__hour_sin', 'poly_month_cos__hour_cos', 'poly_month_cos__sunset_hour_sin', 'poly_week_sin__week_cos', 'poly_week_sin__day_of_week_sin', 'poly_week_sin__day_of_week_cos', 'poly_week_sin__hour_sin', 'poly_week_sin__hour_cos', 'poly_week_sin__sunrise_hour_cos', 'poly_week_sin__sunset_hour_cos', 'poly_week_cos__day_of_week_sin', 'poly_week_cos__day_of_week_cos', 'poly_week_cos__hour_sin', 'poly_week_cos__hour_cos', 'poly_week_cos__sunrise_hour_sin', 'poly_week_cos__sunrise_hour_cos', 'poly_week_cos__sunset_hour_sin', 'poly_day_of_week_sin__day_of_week_cos', 'poly_day_of_week_sin__hour_sin', 'poly_day_of_week_sin__hour_cos', 'poly_day_of_week_sin__sunrise_hour_sin', 'poly_day_of_week_sin__sunrise_hour_cos', 'poly_day_of_week_sin__sunset_hour_sin', 'poly_day_of_week_sin__sunset_hour_cos', 'poly_day_of_week_cos__hour_sin', 'poly_day_of_week_cos__hour_cos', 'poly_day_of_week_cos__sunrise_hour_sin', 'poly_day_of_week_cos__sunrise_hour_cos', 'poly_day_of_week_cos__sunset_hour_sin', 'poly_day_of_week_cos__sunset_hour_cos', 'poly_hour_sin__hour_cos', 'poly_hour_sin__sunrise_hour_sin', 'poly_hour_sin__sunrise_hour_cos', 'poly_hour_sin__sunset_hour_sin', 'poly_hour_sin__sunset_hour_cos', 'poly_hour_cos__sunrise_hour_sin', 'poly_hour_cos__sunrise_hour_cos', 'poly_hour_cos__sunset_hour_sin', 'poly_hour_cos__sunset_hour_cos']
77
-
78
- predictions = forecaster.predict(steps=24, exog = datos_exog[exog_selectec])
79
-
80
- datos['target'] = predictions
81
-
82
- target_column = 'target'
83
-
84
- columns_order = [target_column] + [col for col in datos.columns if col != target_column]
85
-
86
- datos = datos[columns_order]
87
-
88
- pipeline = load_pipeline('pipeline.pkl')
89
-
90
- pred_scaled = pipeline.inverse_transform(datos)
91
-
92
- pred_scaled_df = pd.DataFrame(pred_scaled, columns=datos.columns, index=datos.index)
93
-
94
- df_reset = pred_scaled_df.reset_index()
95
-
96
- df_target = df_reset[['datetime', 'target']]
97
-
98
-
99
- return df_target.to_html()
100
-
101
- # Crear la interfaz con Gradio
102
- interface = gr.Interface(
103
- fn=flujo, # Funci贸n principal
104
- inputs=gr.File(label="Sube tu archivo CSV"), # Entrada de archivo
105
- outputs="html", # Salida como tabla HTML
106
- title="Prediccion geenracion de energia",
107
- description="Sube un archivo CSV y perdice la geenracion de energia."
108
- )
109
-
110
- interface.launch(share = True)
111
-
112
-
 
1
+ import pandas as pd
2
+ import seaborn as sns
3
+ from sklearn.model_selection import train_test_split
4
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
5
+ from sklearn.compose import ColumnTransformer
6
+ from sklearn.pipeline import Pipeline
7
+ from sklearn.ensemble import RandomForestRegressor
8
+ import gradio as gr
9
+
10
+ # Load the diamonds dataset
11
+ diamonds = sns.load_dataset("diamonds")
12
+
13
+ # Prepare the features and target
14
+ X = diamonds.drop("price", axis=1)
15
+ y = diamonds["price"]
16
+
17
+ # Split the data
18
+ X_train, X_test, y_train, y_test = train_test_split(
19
+ X, y, test_size=0.2, random_state=42
20
+ )
21
+
22
+ # Define the preprocessing steps
23
+ numeric_features = ["carat", "depth", "table", "x", "y", "z"]
24
+ categorical_features = ["cut", "color", "clarity"]
25
+
26
+ preprocessor = ColumnTransformer(
27
+ transformers=[
28
+ ("num", StandardScaler(), numeric_features),
29
+ ("cat", OneHotEncoder(drop="first"), categorical_features),
30
+ ]
31
+ )
32
+
33
+
34
+ # Create a pipeline with preprocessing and model
35
+ model = Pipeline(
36
+ [
37
+ ("preprocessor", preprocessor),
38
+ ("regressor", RandomForestRegressor(n_estimators=100, random_state=42)),
39
+ ]
40
+ )
41
+
42
+ # Fit the model
43
+ model.fit(X_train, y_train)
44
+
45
+ # Create the Gradio interface
46
+ def predict_price(carat, cut, color, clarity, depth, table, x, y, z):
47
+
48
+ input_data = pd.DataFrame(
49
+ {
50
+ "carat": [carat],
51
+ "cut": [cut],
52
+ "color": [color],
53
+ "clarity": [clarity],
54
+ "depth": [depth],
55
+ "table": [table],
56
+ "x": [x],
57
+ "y": [y],
58
+ "z": [z],
59
+ }
60
+ )
61
+
62
+ prediction = model.predict(input_data)[0]
63
+ return f"Predicted Price: ${prediction:.2f}"
64
+
65
+ iface = gr.Interface(
66
+ fn=predict_price,
67
+ inputs=[
68
+ gr.Slider(
69
+ minimum=diamonds["carat"].min(),
70
+ maximum=diamonds["carat"].max(),
71
+ label="Carat",
72
+ ),
73
+ gr.Dropdown(["Fair", "Good", "Very Good", "Premium", "Ideal"], label="Cut"),
74
+ gr.Dropdown(["D", "E", "F", "G", "H", "I", "J"], label="Color"),
75
+ gr.Dropdown(
76
+ ["I1", "SI2", "SI1", "VS2", "VS1", "VVS2", "VVS1", "IF"], label="Clarity"
77
+ ),
78
+ gr.Slider(
79
+ minimum=diamonds["depth"].min(),
80
+ maximum=diamonds["depth"].max(),
81
+ label="Depth",
82
+ ),
83
+ gr.Slider(
84
+ minimum=diamonds["table"].min(),
85
+ maximum=diamonds["table"].max(),
86
+ label="Table",
87
+ ),
88
+ gr.Slider(minimum=diamonds["x"].min(), maximum=diamonds["x"].max(), label="X"),
89
+ gr.Slider(minimum=diamonds["y"].min(), maximum=diamonds["y"].max(), label="Y"),
90
+ gr.Slider(minimum=diamonds["z"].min(), maximum=diamonds["z"].max(), label="Z"),
91
+ ],
92
+ outputs="text",
93
+ title="Diamond Price Predictor",
94
+ description="Enter the characteristics of a diamond to predict its price.",
95
+ )
96
+ iface.launch(share=True)
97
+
98
+