import gradio as gr
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
# 1. Dummy E-commerce Dataset Generator (simulating local data)
def generate_data():
return pd.DataFrame({
"visitor_count": [100, 250, 400, 150, 600, 300, 500, 800],
"cart_adds": [10, 20, 55, 12, 80, 35, 60, 110],
"discount_applied": [0, 1, 0, 0, 1, 0, 1, 1],
"total_sales": [150.0, 320.0, 780.0, 200.0, 1200.0, 450.0, 950.0, 1600.0]
})
df = generate_data()
# 2. Train a lightweight local ML model inside WASM
X = df[["visitor_count", "cart_adds", "discount_applied"]]
y = df["total_sales"]
model = RandomForestRegressor(n_estimators=10, random_state=42)
model.fit(X, y)
# 3. Define prediction function for Gradio UI
def predict_sales(visitors, cart_adds, has_discount):
discount_flag = 1 if has_discount else 0
input_df = pd.DataFrame([[visitors, cart_adds, discount_flag]],
columns=["visitor_count", "cart_adds", "discount_applied"])
prediction = model.predict(input_df)[0]
return f"Estimated Sales: ${prediction:.2f}"
# 4. Build Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("## Local E-commerce Sales Predictor (Runs 100% Client-Side)")
with gr.Row():
visitors = gr.Number(label="Visitor Count", value=300)
cart_adds = gr.Number(label="Cart Additions", value=40)
has_discount = gr.Checkbox(label="Discount Active")
predict_btn = gr.Button("Analyze & Predict")
output = gr.Textbox(label="Model Output")
predict_btn.click(
fn=predict_sales,
inputs=[visitors, cart_adds, has_discount],
outputs=output
)
demo.launch()