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()