Spaces:
Sleeping
Sleeping
Created new App.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import joblib
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
|
| 7 |
+
# --- 1. DATA & MODEL LOADING ---
|
| 8 |
+
# Load your model and feature list
|
| 9 |
+
model = joblib.load("sales_model.joblib")
|
| 10 |
+
feature_names = joblib.load("feature_names.joblib")
|
| 11 |
+
|
| 12 |
+
# Load your CSV for EDA charts
|
| 13 |
+
df = pd.read_csv("sales_data.csv")
|
| 14 |
+
df['date'] = pd.to_datetime(df['date'])
|
| 15 |
+
|
| 16 |
+
# --- 2. PREDICTION LOGIC ---
|
| 17 |
+
def predict_sales(u_date, u_brand, u_region, u_price, u_promo, u_stock):
|
| 18 |
+
target_date = pd.to_datetime(u_date)
|
| 19 |
+
|
| 20 |
+
# Initialize input row with zeros matching training features
|
| 21 |
+
input_row = pd.DataFrame(0, index=[0], columns=feature_names)
|
| 22 |
+
|
| 23 |
+
# Fill Time Features
|
| 24 |
+
input_row['month'] = target_date.month
|
| 25 |
+
input_row['day_of_week'] = target_date.weekday()
|
| 26 |
+
input_row['is_weekend'] = 1 if target_date.weekday() >= 5 else 0
|
| 27 |
+
|
| 28 |
+
# Fill Numerical Features
|
| 29 |
+
input_row['price_unit'] = u_price
|
| 30 |
+
input_row['promotion'] = 1 if u_promo else 0
|
| 31 |
+
input_row['stock_ava'] = u_stock
|
| 32 |
+
|
| 33 |
+
# Fill Categorical Features (One-Hot Encoding match)
|
| 34 |
+
brand_col = f"brand_{u_brand}"
|
| 35 |
+
region_col = f"region_{u_region}"
|
| 36 |
+
|
| 37 |
+
if brand_col in input_row.columns: input_row[brand_col] = 1
|
| 38 |
+
if region_col in input_row.columns: input_row[region_col] = 1
|
| 39 |
+
|
| 40 |
+
# Predict
|
| 41 |
+
prediction = model.predict(input_row)[0]
|
| 42 |
+
# Ensure no negative sales
|
| 43 |
+
prediction = max(0, int(prediction))
|
| 44 |
+
revenue = prediction * u_price
|
| 45 |
+
|
| 46 |
+
return f"{prediction} Units", f"${revenue:,.2f}"
|
| 47 |
+
|
| 48 |
+
# --- 3. EDA CHART FUNCTIONS ---
|
| 49 |
+
def plot_weekly_trends():
|
| 50 |
+
df['weekday'] = df['date'].dt.day_name()
|
| 51 |
+
order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
|
| 52 |
+
weekly_avg = df.groupby('weekday')['units_sold'].mean().reindex(order).reset_index()
|
| 53 |
+
fig = px.bar(weekly_avg, x='weekday', y='units_sold', color='units_sold',
|
| 54 |
+
title="Average Units Sold by Day of Week", color_continuous_scale='Blues')
|
| 55 |
+
return fig
|
| 56 |
+
|
| 57 |
+
def plot_price_elasticity():
|
| 58 |
+
fig = px.scatter(df, x="price_unit", y="units_sold", color="promotion",
|
| 59 |
+
trendline="ols", title="Price vs. Units Sold (Elasticity)")
|
| 60 |
+
return fig
|
| 61 |
+
|
| 62 |
+
def plot_regional_share():
|
| 63 |
+
fig = px.sunburst(df, path=['region', 'category'], values='units_sold',
|
| 64 |
+
title="Regional Sales Distribution by Category")
|
| 65 |
+
return fig
|
| 66 |
+
|
| 67 |
+
def plot_correlation():
|
| 68 |
+
corr = df[['price_unit', 'stock_ava', 'units_sold', 'promotion']].corr()
|
| 69 |
+
fig = px.imshow(corr, text_auto=True, title="Feature Correlation Heatmap",
|
| 70 |
+
color_continuous_scale='RdBu_r')
|
| 71 |
+
return fig
|
| 72 |
+
|
| 73 |
+
# --- 4. GRADIO UI LAYOUT ---
|
| 74 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 75 |
+
gr.Markdown("# ๐ฅ Smart Sales & Revenue Intelligence")
|
| 76 |
+
gr.Markdown("Predict future performance and explore historical data patterns.")
|
| 77 |
+
|
| 78 |
+
with gr.Tabs():
|
| 79 |
+
# TAB 1: PREDICTOR
|
| 80 |
+
with gr.TabItem("๐ฎ Sales Forecast"):
|
| 81 |
+
with gr.Row():
|
| 82 |
+
with gr.Column():
|
| 83 |
+
gr.Markdown("### Input Parameters")
|
| 84 |
+
u_date = gr.DateTime(label="Select Target Date")
|
| 85 |
+
u_brand = gr.Dropdown(sorted(df['brand'].unique().tolist()), label="Brand")
|
| 86 |
+
u_region = gr.Dropdown(sorted(df['region'].unique().tolist()), label="Region")
|
| 87 |
+
u_price = gr.Number(label="Unit Price ($)", value=2.50)
|
| 88 |
+
u_promo = gr.Checkbox(label="Is Promotion Active?")
|
| 89 |
+
u_stock = gr.Slider(0, 500, label="Stock Availability", value=150)
|
| 90 |
+
predict_btn = gr.Button("Generate Prediction", variant="primary")
|
| 91 |
+
|
| 92 |
+
with gr.Column():
|
| 93 |
+
gr.Markdown("### Model Output")
|
| 94 |
+
out_sales = gr.Textbox(label="Predicted Sales Volume")
|
| 95 |
+
out_rev = gr.Textbox(label="Estimated Gross Revenue")
|
| 96 |
+
|
| 97 |
+
gr.Markdown("---")
|
| 98 |
+
gr.Info("Note: Predictions are based on historical XGBoost training patterns.")
|
| 99 |
+
|
| 100 |
+
predict_btn.click(
|
| 101 |
+
predict_sales,
|
| 102 |
+
inputs=[u_date, u_brand, u_region, u_price, u_promo, u_stock],
|
| 103 |
+
outputs=[out_sales, out_rev]
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# TAB 2: DATA EXPLORATION
|
| 107 |
+
with gr.TabItem("๐ EDA Dashboard"):
|
| 108 |
+
with gr.Row():
|
| 109 |
+
gr.Plot(plot_weekly_trends())
|
| 110 |
+
gr.Plot(plot_correlation())
|
| 111 |
+
with gr.Row():
|
| 112 |
+
gr.Plot(plot_price_elasticity())
|
| 113 |
+
gr.Plot(plot_regional_share())
|
| 114 |
+
|
| 115 |
+
with gr.Accordion("View Raw Data Snippet", open=False):
|
| 116 |
+
gr.DataFrame(df.head(10))
|
| 117 |
+
|
| 118 |
+
# --- 5. LAUNCH ---
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
demo.launch()
|