Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,202 +1,202 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import joblib
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import plotly.graph_objects as go
|
| 6 |
-
|
| 7 |
-
# -----------------------------
|
| 8 |
-
# Load trained model
|
| 9 |
-
# -----------------------------
|
| 10 |
-
MODEL_PATH = "
|
| 11 |
-
model = joblib.load(MODEL_PATH)
|
| 12 |
-
|
| 13 |
-
# IMPORTANT: These must match the training feature columns (X.columns)
|
| 14 |
-
# We'll load them from a saved list if you created one.
|
| 15 |
-
# If you didn't save feature names yet, do Step 2.1 below.
|
| 16 |
-
FEATURES_PATH = "
|
| 17 |
-
feature_columns = joblib.load(FEATURES_PATH)
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# -----------------------------
|
| 21 |
-
# Helper: create input row
|
| 22 |
-
# -----------------------------
|
| 23 |
-
def build_input_row(platform, influencer_category, campaign_type,
|
| 24 |
-
engagements, estimated_reach, campaign_duration_days,
|
| 25 |
-
assumed_cost_usd):
|
| 26 |
-
"""
|
| 27 |
-
Converts UI inputs into a single-row DataFrame with exact feature columns.
|
| 28 |
-
We one-hot encode platform/category/type to match training.
|
| 29 |
-
"""
|
| 30 |
-
|
| 31 |
-
# Base numeric features
|
| 32 |
-
base = {
|
| 33 |
-
"engagements": engagements,
|
| 34 |
-
"estimated_reach": estimated_reach,
|
| 35 |
-
"campaign_duration_days": campaign_duration_days,
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
# Build a raw dataframe with the same pre-encoded columns you had before encoding:
|
| 39 |
-
raw = pd.DataFrame([{
|
| 40 |
-
**base,
|
| 41 |
-
"platform": platform,
|
| 42 |
-
"influencer_category": influencer_category,
|
| 43 |
-
"campaign_type": campaign_type
|
| 44 |
-
}])
|
| 45 |
-
|
| 46 |
-
# One-hot encode like training (drop_first=True)
|
| 47 |
-
encoded = pd.get_dummies(
|
| 48 |
-
raw,
|
| 49 |
-
columns=["platform", "influencer_category", "campaign_type"],
|
| 50 |
-
drop_first=True
|
| 51 |
-
)
|
| 52 |
-
|
| 53 |
-
# Align to training columns (missing columns -> 0, extra -> drop)
|
| 54 |
-
for col in feature_columns:
|
| 55 |
-
if col not in encoded.columns:
|
| 56 |
-
encoded[col] = 0
|
| 57 |
-
encoded = encoded[feature_columns]
|
| 58 |
-
|
| 59 |
-
return encoded
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
# -----------------------------
|
| 63 |
-
# Main prediction function
|
| 64 |
-
# -----------------------------
|
| 65 |
-
def predict_sales_and_roi(platform, influencer_category, campaign_type,
|
| 66 |
-
engagements, estimated_reach, campaign_duration_days,
|
| 67 |
-
assumed_cost_usd):
|
| 68 |
-
"""
|
| 69 |
-
Predict product_sales and compute an *estimated ROI* using user-provided cost.
|
| 70 |
-
ROI = (Predicted Sales - Cost) / Cost
|
| 71 |
-
"""
|
| 72 |
-
|
| 73 |
-
# Guard against zero/negative cost
|
| 74 |
-
if assumed_cost_usd <= 0:
|
| 75 |
-
return "⚠️ Please enter a campaign cost greater than 0.", None
|
| 76 |
-
|
| 77 |
-
X_input = build_input_row(
|
| 78 |
-
platform, influencer_category, campaign_type,
|
| 79 |
-
engagements, estimated_reach, campaign_duration_days,
|
| 80 |
-
assumed_cost_usd
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
# Predict sales
|
| 84 |
-
pred_sales = float(model.predict(X_input)[0])
|
| 85 |
-
|
| 86 |
-
# Compute ROI (as %)
|
| 87 |
-
roi = (pred_sales - assumed_cost_usd) / assumed_cost_usd
|
| 88 |
-
roi_percent = roi * 100.0
|
| 89 |
-
|
| 90 |
-
# Label ROI quality
|
| 91 |
-
if roi_percent >= 50:
|
| 92 |
-
roi_label = "
|
| 93 |
-
elif roi_percent >= 0:
|
| 94 |
-
roi_label = "🟡 Moderate ROI"
|
| 95 |
-
else:
|
| 96 |
-
roi_label = "🔴 Negative ROI"
|
| 97 |
-
|
| 98 |
-
# Build Plotly chart: Cost vs Predicted Sales
|
| 99 |
-
fig = go.Figure()
|
| 100 |
-
fig.add_bar(name="Campaign Cost", x=["Campaign"], y=[assumed_cost_usd])
|
| 101 |
-
fig.add_bar(name="Predicted Sales", x=["Campaign"], y=[pred_sales])
|
| 102 |
-
fig.update_layout(
|
| 103 |
-
barmode="group",
|
| 104 |
-
title="Spend vs Predicted Return",
|
| 105 |
-
xaxis_title="",
|
| 106 |
-
yaxis_title="USD",
|
| 107 |
-
height=420
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
# Suggestions (simple, user-friendly)
|
| 111 |
-
tips = []
|
| 112 |
-
if engagements < 2000:
|
| 113 |
-
tips.append("Increase engagement (better content hook, CTA, posting time).")
|
| 114 |
-
if estimated_reach < 10000:
|
| 115 |
-
tips.append("Improve reach (cross-post, collab posts, hashtags, boosted content).")
|
| 116 |
-
if campaign_duration_days < 7:
|
| 117 |
-
tips.append("Consider longer campaigns (more touchpoints often improves conversions).")
|
| 118 |
-
|
| 119 |
-
if not tips:
|
| 120 |
-
tips_text = "Your inputs look strong. Focus on creative quality + audience match."
|
| 121 |
-
else:
|
| 122 |
-
tips_text = " • " + "\n • ".join(tips)
|
| 123 |
-
|
| 124 |
-
result_md = f"""
|
| 125 |
-
# 📈 Influencer ROI Prediction
|
| 126 |
-
|
| 127 |
-
### Predicted Financial Return
|
| 128 |
-
- **Predicted Product Sales:** `${pred_sales:,.2f}`
|
| 129 |
-
- **Campaign Cost:** `${assumed_cost_usd:,.2f}`
|
| 130 |
-
- **Estimated ROI:** **{roi_percent:,.2f}%** — {roi_label}
|
| 131 |
-
|
| 132 |
-
### What this means
|
| 133 |
-
This prediction helps brands estimate whether a campaign is likely to be profitable **before spending money**.
|
| 134 |
-
|
| 135 |
-
### Suggestions to improve ROI
|
| 136 |
-
{tips_text}
|
| 137 |
-
"""
|
| 138 |
-
|
| 139 |
-
return result_md, fig
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
# -----------------------------
|
| 143 |
-
# UI (modern dashboard feel)
|
| 144 |
-
# -----------------------------
|
| 145 |
-
with gr.Blocks(title="Influencer ROI Prediction Dashboard") as app:
|
| 146 |
-
with gr.Tab("Home"):
|
| 147 |
-
gr.Markdown("""
|
| 148 |
-
# ✨ Influencer ROI Prediction Dashboard
|
| 149 |
-
|
| 150 |
-
This app predicts **financial return (product sales)** from influencer campaign inputs using **Regression ML**.
|
| 151 |
-
|
| 152 |
-
### Why it matters
|
| 153 |
-
Marketing teams can use this to:
|
| 154 |
-
- Compare influencer platforms (Instagram vs TikTok vs YouTube)
|
| 155 |
-
- Estimate sales impact before launching a campaign
|
| 156 |
-
- Run **what-if scenarios** (change budget, duration, engagement)
|
| 157 |
-
|
| 158 |
-
➡️ Go to the **Predict** tab to try it.
|
| 159 |
-
""")
|
| 160 |
-
|
| 161 |
-
with gr.Tab("Predict"):
|
| 162 |
-
gr.Markdown("## 🧠 Predict Sales + Estimated ROI")
|
| 163 |
-
|
| 164 |
-
with gr.Row():
|
| 165 |
-
with gr.Column(scale=2):
|
| 166 |
-
platform = gr.Dropdown(
|
| 167 |
-
choices=["Instagram", "YouTube", "TikTok", "Twitter", "Facebook"],
|
| 168 |
-
value="Instagram",
|
| 169 |
-
label="Platform"
|
| 170 |
-
)
|
| 171 |
-
influencer_category = gr.Dropdown(
|
| 172 |
-
choices=["Micro", "Macro", "Mega", "Nano"],
|
| 173 |
-
value="Micro",
|
| 174 |
-
label="Influencer Category"
|
| 175 |
-
)
|
| 176 |
-
campaign_type = gr.Dropdown(
|
| 177 |
-
choices=["Product Launch", "Brand Awareness", "Seasonal Promo", "Giveaway", "Affiliate"],
|
| 178 |
-
value="Brand Awareness",
|
| 179 |
-
label="Campaign Type"
|
| 180 |
-
)
|
| 181 |
-
|
| 182 |
-
engagements = gr.Number(value=5000, label="Engagements (likes/comments/etc.)")
|
| 183 |
-
estimated_reach = gr.Number(value=50000, label="Estimated Reach")
|
| 184 |
-
campaign_duration_days = gr.Slider(1, 60, value=14, step=1, label="Campaign Duration (days)")
|
| 185 |
-
assumed_cost_usd = gr.Number(value=1000, label="Campaign Cost (USD)")
|
| 186 |
-
|
| 187 |
-
predict_btn = gr.Button("🚀 Predict ROI", variant="primary")
|
| 188 |
-
|
| 189 |
-
with gr.Column(scale=3):
|
| 190 |
-
output_md = gr.Markdown()
|
| 191 |
-
output_plot = gr.Plot()
|
| 192 |
-
|
| 193 |
-
predict_btn.click(
|
| 194 |
-
fn=predict_sales_and_roi,
|
| 195 |
-
inputs=[platform, influencer_category, campaign_type,
|
| 196 |
-
engagements, estimated_reach, campaign_duration_days,
|
| 197 |
-
assumed_cost_usd],
|
| 198 |
-
outputs=[output_md, output_plot]
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
if __name__ == "__main__":
|
| 202 |
-
app.launch()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import joblib
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
|
| 7 |
+
# -----------------------------
|
| 8 |
+
# Load trained model
|
| 9 |
+
# -----------------------------
|
| 10 |
+
MODEL_PATH = "influencer_roi_model.joblib"
|
| 11 |
+
model = joblib.load(MODEL_PATH)
|
| 12 |
+
|
| 13 |
+
# IMPORTANT: These must match the training feature columns (X.columns)
|
| 14 |
+
# We'll load them from a saved list if you created one.
|
| 15 |
+
# If you didn't save feature names yet, do Step 2.1 below.
|
| 16 |
+
FEATURES_PATH = "feature_columns.joblib"
|
| 17 |
+
feature_columns = joblib.load(FEATURES_PATH)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# -----------------------------
|
| 21 |
+
# Helper: create input row
|
| 22 |
+
# -----------------------------
|
| 23 |
+
def build_input_row(platform, influencer_category, campaign_type,
|
| 24 |
+
engagements, estimated_reach, campaign_duration_days,
|
| 25 |
+
assumed_cost_usd):
|
| 26 |
+
"""
|
| 27 |
+
Converts UI inputs into a single-row DataFrame with exact feature columns.
|
| 28 |
+
We one-hot encode platform/category/type to match training.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# Base numeric features
|
| 32 |
+
base = {
|
| 33 |
+
"engagements": engagements,
|
| 34 |
+
"estimated_reach": estimated_reach,
|
| 35 |
+
"campaign_duration_days": campaign_duration_days,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
# Build a raw dataframe with the same pre-encoded columns you had before encoding:
|
| 39 |
+
raw = pd.DataFrame([{
|
| 40 |
+
**base,
|
| 41 |
+
"platform": platform,
|
| 42 |
+
"influencer_category": influencer_category,
|
| 43 |
+
"campaign_type": campaign_type
|
| 44 |
+
}])
|
| 45 |
+
|
| 46 |
+
# One-hot encode like training (drop_first=True)
|
| 47 |
+
encoded = pd.get_dummies(
|
| 48 |
+
raw,
|
| 49 |
+
columns=["platform", "influencer_category", "campaign_type"],
|
| 50 |
+
drop_first=True
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Align to training columns (missing columns -> 0, extra -> drop)
|
| 54 |
+
for col in feature_columns:
|
| 55 |
+
if col not in encoded.columns:
|
| 56 |
+
encoded[col] = 0
|
| 57 |
+
encoded = encoded[feature_columns]
|
| 58 |
+
|
| 59 |
+
return encoded
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# -----------------------------
|
| 63 |
+
# Main prediction function
|
| 64 |
+
# -----------------------------
|
| 65 |
+
def predict_sales_and_roi(platform, influencer_category, campaign_type,
|
| 66 |
+
engagements, estimated_reach, campaign_duration_days,
|
| 67 |
+
assumed_cost_usd):
|
| 68 |
+
"""
|
| 69 |
+
Predict product_sales and compute an *estimated ROI* using user-provided cost.
|
| 70 |
+
ROI = (Predicted Sales - Cost) / Cost
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
# Guard against zero/negative cost
|
| 74 |
+
if assumed_cost_usd <= 0:
|
| 75 |
+
return "⚠️ Please enter a campaign cost greater than 0.", None
|
| 76 |
+
|
| 77 |
+
X_input = build_input_row(
|
| 78 |
+
platform, influencer_category, campaign_type,
|
| 79 |
+
engagements, estimated_reach, campaign_duration_days,
|
| 80 |
+
assumed_cost_usd
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# Predict sales
|
| 84 |
+
pred_sales = float(model.predict(X_input)[0])
|
| 85 |
+
|
| 86 |
+
# Compute ROI (as %)
|
| 87 |
+
roi = (pred_sales - assumed_cost_usd) / assumed_cost_usd
|
| 88 |
+
roi_percent = roi * 100.0
|
| 89 |
+
|
| 90 |
+
# Label ROI quality
|
| 91 |
+
if roi_percent >= 50:
|
| 92 |
+
roi_label = "���� Strong ROI"
|
| 93 |
+
elif roi_percent >= 0:
|
| 94 |
+
roi_label = "🟡 Moderate ROI"
|
| 95 |
+
else:
|
| 96 |
+
roi_label = "🔴 Negative ROI"
|
| 97 |
+
|
| 98 |
+
# Build Plotly chart: Cost vs Predicted Sales
|
| 99 |
+
fig = go.Figure()
|
| 100 |
+
fig.add_bar(name="Campaign Cost", x=["Campaign"], y=[assumed_cost_usd])
|
| 101 |
+
fig.add_bar(name="Predicted Sales", x=["Campaign"], y=[pred_sales])
|
| 102 |
+
fig.update_layout(
|
| 103 |
+
barmode="group",
|
| 104 |
+
title="Spend vs Predicted Return",
|
| 105 |
+
xaxis_title="",
|
| 106 |
+
yaxis_title="USD",
|
| 107 |
+
height=420
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Suggestions (simple, user-friendly)
|
| 111 |
+
tips = []
|
| 112 |
+
if engagements < 2000:
|
| 113 |
+
tips.append("Increase engagement (better content hook, CTA, posting time).")
|
| 114 |
+
if estimated_reach < 10000:
|
| 115 |
+
tips.append("Improve reach (cross-post, collab posts, hashtags, boosted content).")
|
| 116 |
+
if campaign_duration_days < 7:
|
| 117 |
+
tips.append("Consider longer campaigns (more touchpoints often improves conversions).")
|
| 118 |
+
|
| 119 |
+
if not tips:
|
| 120 |
+
tips_text = "Your inputs look strong. Focus on creative quality + audience match."
|
| 121 |
+
else:
|
| 122 |
+
tips_text = " • " + "\n • ".join(tips)
|
| 123 |
+
|
| 124 |
+
result_md = f"""
|
| 125 |
+
# 📈 Influencer ROI Prediction
|
| 126 |
+
|
| 127 |
+
### Predicted Financial Return
|
| 128 |
+
- **Predicted Product Sales:** `${pred_sales:,.2f}`
|
| 129 |
+
- **Campaign Cost:** `${assumed_cost_usd:,.2f}`
|
| 130 |
+
- **Estimated ROI:** **{roi_percent:,.2f}%** — {roi_label}
|
| 131 |
+
|
| 132 |
+
### What this means
|
| 133 |
+
This prediction helps brands estimate whether a campaign is likely to be profitable **before spending money**.
|
| 134 |
+
|
| 135 |
+
### Suggestions to improve ROI
|
| 136 |
+
{tips_text}
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
return result_md, fig
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# -----------------------------
|
| 143 |
+
# UI (modern dashboard feel)
|
| 144 |
+
# -----------------------------
|
| 145 |
+
with gr.Blocks(title="Influencer ROI Prediction Dashboard") as app:
|
| 146 |
+
with gr.Tab("Home"):
|
| 147 |
+
gr.Markdown("""
|
| 148 |
+
# ✨ Influencer ROI Prediction Dashboard
|
| 149 |
+
|
| 150 |
+
This app predicts **financial return (product sales)** from influencer campaign inputs using **Regression ML**.
|
| 151 |
+
|
| 152 |
+
### Why it matters
|
| 153 |
+
Marketing teams can use this to:
|
| 154 |
+
- Compare influencer platforms (Instagram vs TikTok vs YouTube)
|
| 155 |
+
- Estimate sales impact before launching a campaign
|
| 156 |
+
- Run **what-if scenarios** (change budget, duration, engagement)
|
| 157 |
+
|
| 158 |
+
➡️ Go to the **Predict** tab to try it.
|
| 159 |
+
""")
|
| 160 |
+
|
| 161 |
+
with gr.Tab("Predict"):
|
| 162 |
+
gr.Markdown("## 🧠 Predict Sales + Estimated ROI")
|
| 163 |
+
|
| 164 |
+
with gr.Row():
|
| 165 |
+
with gr.Column(scale=2):
|
| 166 |
+
platform = gr.Dropdown(
|
| 167 |
+
choices=["Instagram", "YouTube", "TikTok", "Twitter", "Facebook"],
|
| 168 |
+
value="Instagram",
|
| 169 |
+
label="Platform"
|
| 170 |
+
)
|
| 171 |
+
influencer_category = gr.Dropdown(
|
| 172 |
+
choices=["Micro", "Macro", "Mega", "Nano"],
|
| 173 |
+
value="Micro",
|
| 174 |
+
label="Influencer Category"
|
| 175 |
+
)
|
| 176 |
+
campaign_type = gr.Dropdown(
|
| 177 |
+
choices=["Product Launch", "Brand Awareness", "Seasonal Promo", "Giveaway", "Affiliate"],
|
| 178 |
+
value="Brand Awareness",
|
| 179 |
+
label="Campaign Type"
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
engagements = gr.Number(value=5000, label="Engagements (likes/comments/etc.)")
|
| 183 |
+
estimated_reach = gr.Number(value=50000, label="Estimated Reach")
|
| 184 |
+
campaign_duration_days = gr.Slider(1, 60, value=14, step=1, label="Campaign Duration (days)")
|
| 185 |
+
assumed_cost_usd = gr.Number(value=1000, label="Campaign Cost (USD)")
|
| 186 |
+
|
| 187 |
+
predict_btn = gr.Button("🚀 Predict ROI", variant="primary")
|
| 188 |
+
|
| 189 |
+
with gr.Column(scale=3):
|
| 190 |
+
output_md = gr.Markdown()
|
| 191 |
+
output_plot = gr.Plot()
|
| 192 |
+
|
| 193 |
+
predict_btn.click(
|
| 194 |
+
fn=predict_sales_and_roi,
|
| 195 |
+
inputs=[platform, influencer_category, campaign_type,
|
| 196 |
+
engagements, estimated_reach, campaign_duration_days,
|
| 197 |
+
assumed_cost_usd],
|
| 198 |
+
outputs=[output_md, output_plot]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
app.launch()
|