File size: 3,879 Bytes
7a3e8ee 1c681f7 7a3e8ee 1c681f7 7a3e8ee 1c681f7 7a3e8ee 1c681f7 6884152 1c681f7 7a3e8ee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | import gradio as gr
import spaces
import torch
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from datetime import datetime, timedelta
# Generate random historical data
def generate_sample_data(n_samples=1000):
# Generate dates
start_date = datetime(2020, 1, 1)
dates = [start_date + timedelta(days=x) for x in range(n_samples)]
# Generate stations
stations = ['Station A', 'Station B', 'Station C', 'Station D']
# Generate fuel types
fuel_types = ['Gasoline', 'Diesel', 'Premium']
data = []
for date in dates:
for station in stations:
for fuel_type in fuel_types:
# Generate random sales with some patterns
base_sale = np.random.normal(1000, 200)
# Add seasonality
seasonal_factor = 1 + 0.2 * np.sin(2 * np.pi * date.timetuple().tm_yday / 365)
# Add station variation
station_factor = 0.8 + 0.4 * stations.index(station) / len(stations)
# Add fuel type variation
fuel_factor = 0.7 + 0.6 * fuel_types.index(fuel_type) / len(fuel_types)
sales = base_sale * seasonal_factor * station_factor * fuel_factor
data.append({
'date': date,
'station': station,
'fuel_type': fuel_type,
'sales': max(0, sales),
'day_of_week': date.weekday(),
'month': date.month
})
return pd.DataFrame(data)
# Train the model
def train_model():
df = generate_sample_data()
# Feature engineering
X = pd.get_dummies(df[['station', 'fuel_type', 'day_of_week', 'month']])
y = df['sales']
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train model
model = RandomForestRegressor(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
return model, X.columns
# Global variables
model, feature_columns = train_model()
# Prediction function
@spaces.GPU
def predict_sales(station, fuel_type, date_str):
try:
# Parse the date
date = datetime.strptime(date_str, '%Y-%m-%d')
# Create feature vector
input_data = pd.DataFrame({
'day_of_week': [date.weekday()],
'month': [date.month],
'station': [station],
'fuel_type': [fuel_type]
})
# One-hot encode
input_encoded = pd.get_dummies(input_data)
# Align features with training data
input_final = pd.DataFrame(columns=feature_columns)
input_final.loc[0] = 0
for col in input_encoded.columns:
if col in input_final.columns:
input_final[col] = input_encoded[col]
# Make prediction
prediction = model.predict(input_final)[0]
#return f"Predicted sales for {fuel_type} at {station} on {date_str}: {prediction:.2f} units"
return f"{prediction:.2f}"
except Exception as e:
return f"Error: {str(e)}"
# Gradio interface
demo = gr.Interface(
fn=predict_sales,
inputs=[
gr.Dropdown(
choices=['Station A', 'Station B', 'Station C', 'Station D'],
label="Station"
),
gr.Dropdown(
choices=['Gasoline', 'Diesel', 'Premium'],
label="Fuel Type"
),
gr.Textbox(
label="Date (YYYY-MM-DD)",
placeholder="2023-12-31"
)
],
outputs=gr.Text(),
title="Fuel Sales Forecasting",
description="Predict fuel sales for a specific station and fuel type"
)
demo.launch()
|