Akki2228 commited on
Commit
a5b3e42
Β·
verified Β·
1 Parent(s): b686fad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -122
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  import pickle
3
  import numpy as np
4
- import pandas as pd
5
  import matplotlib.pyplot as plt
6
  import matplotlib
7
  matplotlib.use("Agg")
@@ -15,113 +14,84 @@ try:
15
  except:
16
  model = None
17
 
18
- # =========================
19
- # πŸ”Ή Load Dataset (REAL or DUMMY)
20
- # =========================
21
- try:
22
- data = pd.read_csv("churn_data.csv")
23
- except:
24
- np.random.seed(42)
25
- data = pd.DataFrame({
26
- "gender": np.random.choice(["Male","Female"], 300),
27
- "tenure": np.random.randint(1, 60, 300),
28
- "MonthlyCharges": np.random.randint(500, 8000, 300),
29
- "Contract": np.random.choice(["Monthly","Quarterly","Yearly"], 300),
30
- "Churn": np.random.choice([0,1], 300)
31
- })
32
 
33
  # =========================
34
- # πŸ”Ή KPI FUNCTION
35
  # =========================
36
- def get_kpis(df):
37
- total = len(df)
38
- churn_rate = df["Churn"].mean() * 100
39
- avg_spend = df["MonthlyCharges"].mean()
40
- avg_tenure = df["tenure"].mean()
41
-
42
- return f"""
43
- ### πŸ“Š Key Metrics
44
- - Total Customers: **{total}**
45
- - Churn Rate: **{churn_rate:.2f}%**
46
- - Avg Spend: **β‚Ή{avg_spend:.0f}**
47
- - Avg Tenure: **{avg_tenure:.1f} months**
 
 
 
 
 
 
 
 
 
48
  """
49
 
50
- # =========================
51
- # πŸ”Ή FILTER FUNCTION
52
- # =========================
53
- def apply_filters(gender, contract):
54
- df = data.copy()
55
- if gender != "All":
56
- df = df[df["gender"] == gender]
57
- if contract != "All":
58
- df = df[df["Contract"] == contract]
59
- return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- # =========================
62
- # πŸ”Ή CHARTS
63
- # =========================
64
- def churn_dist(df):
65
- fig, ax = plt.subplots()
66
- counts = df["Churn"].value_counts()
67
- ax.bar(["No Churn","Churn"], counts)
68
- ax.set_title("Churn Distribution")
69
- plt.close(fig)
70
- return fig
71
-
72
- def contract_chart(df):
73
- fig, ax = plt.subplots()
74
- pd.crosstab(df["Contract"], df["Churn"]).plot(kind="bar", ax=ax)
75
- ax.set_title("Churn by Contract")
76
- plt.close(fig)
77
- return fig
78
-
79
- def tenure_chart(df):
80
- fig, ax = plt.subplots()
81
- ax.scatter(df["tenure"], df["Churn"])
82
- ax.set_title("Tenure vs Churn")
83
- plt.close(fig)
84
- return fig
85
-
86
- def risk_pie(df):
87
- fig, ax = plt.subplots()
88
- counts = df["Churn"].value_counts()
89
- ax.pie(counts, labels=["No Churn","Churn"], autopct="%1.1f%%")
90
- ax.set_title("Risk Segmentation")
91
- plt.close(fig)
92
- return fig
93
 
94
- # =========================
95
- # πŸ”Ή FEATURE IMPORTANCE
96
- # =========================
97
- def feature_importance():
98
- if model is None or not hasattr(model, "feature_importances_"):
99
- return None
100
-
101
- features = [
102
- "age","gender","tenure","usage","support","delay",
103
- "spend","interaction",
104
- "sub_premium","sub_standard",
105
- "contract_monthly","contract_quarterly"
106
- ]
107
-
108
- fig, ax = plt.subplots()
109
- ax.barh(features, model.feature_importances_)
110
- ax.set_title("Feature Importance")
111
- plt.close(fig)
112
- return fig
113
 
114
  # =========================
115
- # πŸ”Ή PREDICTION
116
  # =========================
117
  def predict_churn(age, gender, tenure, usage, support, delay,
118
- subscription, contract, spend, interaction):
119
 
120
  try:
121
  if model is None:
122
  return "Model not loaded ❌", "", "", None, ""
123
 
124
- # πŸ”Ή Convert inputs safely
125
  age = float(age)
126
  tenure = float(tenure)
127
  usage = float(usage)
@@ -130,11 +100,10 @@ def predict_churn(age, gender, tenure, usage, support, delay,
130
  spend = float(spend)
131
  interaction = float(interaction)
132
 
 
133
  gender_val = 1 if gender == "Female" else 0
134
-
135
  sub_premium = 1 if subscription == "Premium" else 0
136
  sub_standard = 1 if subscription == "Standard" else 0
137
-
138
  contract_monthly = 1 if contract == "Monthly" else 0
139
  contract_quarterly = 1 if contract == "Quarterly" else 0
140
 
@@ -161,14 +130,14 @@ def predict_churn(age, gender, tenure, usage, support, delay,
161
  else:
162
  risk = "🟒 Low Risk"
163
 
164
- # πŸ“Š Probability Chart
165
  fig, ax = plt.subplots()
166
  ax.bar(["No Churn","Churn"], [1-prob, prob])
167
  ax.set_ylim(0,1)
168
  ax.set_title("Prediction Probability")
169
  plt.close(fig)
170
 
171
- # 🧠 Explanation
172
  reasons = []
173
  if delay > 15: reasons.append("High payment delay")
174
  if tenure < 6: reasons.append("Low tenure")
@@ -181,20 +150,35 @@ def predict_churn(age, gender, tenure, usage, support, delay,
181
  except Exception as e:
182
  return f"Error: {str(e)}", "", "", None, ""
183
 
 
184
  # =========================
185
  # 🎨 UI
186
  # =========================
187
  with gr.Blocks() as demo:
188
 
189
- gr.Markdown("# πŸš€ Customer Churn Analytics Dashboard")
190
 
191
  # ---------------------
192
  # πŸ“Š DASHBOARD TAB
193
  # ---------------------
194
  with gr.Tab("πŸ“Š Dashboard"):
195
 
196
- gender_filter = gr.Dropdown(["All","Male","Female"], value="All")
197
- contract_filter = gr.Dropdown(["All","Monthly","Quarterly","Yearly"], value="All")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  kpi_text = gr.Markdown()
200
  chart1 = gr.Plot()
@@ -202,33 +186,21 @@ with gr.Blocks() as demo:
202
  chart3 = gr.Plot()
203
  chart4 = gr.Plot()
204
 
205
- def update_dashboard(g, c):
206
- df = apply_filters(g, c)
207
- return (
208
- get_kpis(df),
209
- churn_dist(df),
210
- contract_chart(df),
211
- tenure_chart(df),
212
- risk_pie(df)
213
- )
214
-
215
- demo.load(update_dashboard, [gender_filter, contract_filter],
216
- [kpi_text, chart1, chart2, chart3, chart4])
217
-
218
- gender_filter.change(update_dashboard, [gender_filter, contract_filter],
219
- [kpi_text, chart1, chart2, chart3, chart4])
220
-
221
- contract_filter.change(update_dashboard, [gender_filter, contract_filter],
222
- [kpi_text, chart1, chart2, chart3, chart4])
223
 
224
  # ---------------------
225
- # πŸ” PREDICTION TAB (UPDATED)
226
  # ---------------------
227
  with gr.Tab("πŸ” Prediction"):
228
 
229
  with gr.Row():
230
  age = gr.Number(value=30, label="Age")
231
- gender = gr.Dropdown(["Male","Female"], value="Male", label="Gender")
232
  tenure = gr.Number(value=12, label="Tenure")
233
  usage = gr.Number(value=10, label="Usage")
234
 
@@ -239,7 +211,7 @@ with gr.Blocks() as demo:
239
  contract = gr.Dropdown(["Monthly","Quarterly","Yearly"], value="Monthly")
240
 
241
  spend = gr.Number(value=2000, label="Total Spend")
242
- interaction = gr.Number(value=20, label="Last Interaction")
243
 
244
  btn = gr.Button("Predict")
245
 
@@ -260,8 +232,21 @@ with gr.Blocks() as demo:
260
  # πŸ“ˆ INSIGHTS TAB
261
  # ---------------------
262
  with gr.Tab("πŸ“ˆ Insights"):
263
- gr.Markdown("### Feature Importance")
264
- gr.Plot(feature_importance())
 
 
 
 
 
 
 
 
 
 
 
 
 
265
 
266
  # =========================
267
  # πŸš€ LAUNCH
 
1
  import gradio as gr
2
  import pickle
3
  import numpy as np
 
4
  import matplotlib.pyplot as plt
5
  import matplotlib
6
  matplotlib.use("Agg")
 
14
  except:
15
  model = None
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # =========================
19
+ # πŸ”Ή DASHBOARD ANALYSIS
20
  # =========================
21
+ def dashboard_analysis(age, gender, tenure, usage, support, delay,
22
+ subscription, contract, spend, interaction):
23
+
24
+ try:
25
+ # Convert inputs
26
+ age = float(age)
27
+ tenure = float(tenure)
28
+ usage = float(usage)
29
+ support = float(support)
30
+ delay = float(delay)
31
+ spend = float(spend)
32
+ interaction = float(interaction)
33
+
34
+ # KPI Summary
35
+ kpi = f"""
36
+ ### πŸ“Š Customer Summary
37
+ - Age: **{age}**
38
+ - Tenure: **{tenure} months**
39
+ - Spend: **β‚Ή{spend}**
40
+ - Contract: **{contract}**
41
+ - Subscription: **{subscription}**
42
  """
43
 
44
+ # Chart 1: Profile
45
+ fig1, ax1 = plt.subplots()
46
+ features = ["Age","Tenure","Usage","Support","Delay"]
47
+ values = [age, tenure, usage, support, delay]
48
+ ax1.bar(features, values)
49
+ ax1.set_title("Customer Profile")
50
+ plt.close(fig1)
51
+
52
+ # Chart 2: Financial
53
+ fig2, ax2 = plt.subplots()
54
+ ax2.bar(["Spend","Interaction"], [spend, interaction])
55
+ ax2.set_title("Financial & Interaction")
56
+ plt.close(fig2)
57
+
58
+ # Chart 3: Risk indicators
59
+ risk_scores = [
60
+ delay/30,
61
+ support/20,
62
+ (6-tenure)/6 if tenure < 6 else 0
63
+ ]
64
+ labels = ["Delay Risk","Support Risk","Tenure Risk"]
65
+
66
+ fig3, ax3 = plt.subplots()
67
+ ax3.bar(labels, risk_scores)
68
+ ax3.set_title("Risk Indicators")
69
+ plt.close(fig3)
70
+
71
+ # Chart 4: Subscription level
72
+ fig4, ax4 = plt.subplots()
73
+ sub_map = {"Basic":1, "Standard":2, "Premium":3}
74
+ ax4.bar(["Subscription Level"], [sub_map[subscription]])
75
+ ax4.set_title("Subscription Level")
76
+ plt.close(fig4)
77
+
78
+ return kpi, fig1, fig2, fig3, fig4
79
 
80
+ except Exception as e:
81
+ return f"Error: {str(e)}", None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  # =========================
85
+ # πŸ”Ή PREDICTION FUNCTION
86
  # =========================
87
  def predict_churn(age, gender, tenure, usage, support, delay,
88
+ subscription, contract, spend, interaction):
89
 
90
  try:
91
  if model is None:
92
  return "Model not loaded ❌", "", "", None, ""
93
 
94
+ # Convert inputs
95
  age = float(age)
96
  tenure = float(tenure)
97
  usage = float(usage)
 
100
  spend = float(spend)
101
  interaction = float(interaction)
102
 
103
+ # Encoding
104
  gender_val = 1 if gender == "Female" else 0
 
105
  sub_premium = 1 if subscription == "Premium" else 0
106
  sub_standard = 1 if subscription == "Standard" else 0
 
107
  contract_monthly = 1 if contract == "Monthly" else 0
108
  contract_quarterly = 1 if contract == "Quarterly" else 0
109
 
 
130
  else:
131
  risk = "🟒 Low Risk"
132
 
133
+ # Probability chart
134
  fig, ax = plt.subplots()
135
  ax.bar(["No Churn","Churn"], [1-prob, prob])
136
  ax.set_ylim(0,1)
137
  ax.set_title("Prediction Probability")
138
  plt.close(fig)
139
 
140
+ # Explanation
141
  reasons = []
142
  if delay > 15: reasons.append("High payment delay")
143
  if tenure < 6: reasons.append("Low tenure")
 
150
  except Exception as e:
151
  return f"Error: {str(e)}", "", "", None, ""
152
 
153
+
154
  # =========================
155
  # 🎨 UI
156
  # =========================
157
  with gr.Blocks() as demo:
158
 
159
+ gr.Markdown("# πŸš€ Customer Churn Interactive Dashboard")
160
 
161
  # ---------------------
162
  # πŸ“Š DASHBOARD TAB
163
  # ---------------------
164
  with gr.Tab("πŸ“Š Dashboard"):
165
 
166
+ with gr.Row():
167
+ d_age = gr.Number(value=30, label="Age")
168
+ d_gender = gr.Dropdown(["Male","Female"], value="Male")
169
+ d_tenure = gr.Number(value=12, label="Tenure")
170
+ d_usage = gr.Number(value=10, label="Usage")
171
+
172
+ with gr.Row():
173
+ d_support = gr.Number(value=2, label="Support Calls")
174
+ d_delay = gr.Number(value=5, label="Payment Delay")
175
+ d_subscription = gr.Dropdown(["Basic","Standard","Premium"], value="Basic")
176
+ d_contract = gr.Dropdown(["Monthly","Quarterly","Yearly"], value="Monthly")
177
+
178
+ d_spend = gr.Number(value=2000, label="Total Spend")
179
+ d_interaction = gr.Number(value=20, label="Interaction")
180
+
181
+ analyze_btn = gr.Button("Analyze Dashboard")
182
 
183
  kpi_text = gr.Markdown()
184
  chart1 = gr.Plot()
 
186
  chart3 = gr.Plot()
187
  chart4 = gr.Plot()
188
 
189
+ analyze_btn.click(
190
+ dashboard_analysis,
191
+ inputs=[d_age, d_gender, d_tenure, d_usage, d_support, d_delay,
192
+ d_subscription, d_contract, d_spend, d_interaction],
193
+ outputs=[kpi_text, chart1, chart2, chart3, chart4]
194
+ )
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
  # ---------------------
197
+ # πŸ” PREDICTION TAB
198
  # ---------------------
199
  with gr.Tab("πŸ” Prediction"):
200
 
201
  with gr.Row():
202
  age = gr.Number(value=30, label="Age")
203
+ gender = gr.Dropdown(["Male","Female"], value="Male")
204
  tenure = gr.Number(value=12, label="Tenure")
205
  usage = gr.Number(value=10, label="Usage")
206
 
 
211
  contract = gr.Dropdown(["Monthly","Quarterly","Yearly"], value="Monthly")
212
 
213
  spend = gr.Number(value=2000, label="Total Spend")
214
+ interaction = gr.Number(value=20, label="Interaction")
215
 
216
  btn = gr.Button("Predict")
217
 
 
232
  # πŸ“ˆ INSIGHTS TAB
233
  # ---------------------
234
  with gr.Tab("πŸ“ˆ Insights"):
235
+
236
+ if model is not None and hasattr(model, "feature_importances_"):
237
+ fig, ax = plt.subplots()
238
+ features = [
239
+ "age","gender","tenure","usage","support","delay",
240
+ "spend","interaction",
241
+ "sub_premium","sub_standard",
242
+ "contract_monthly","contract_quarterly"
243
+ ]
244
+ ax.barh(features, model.feature_importances_)
245
+ ax.set_title("Feature Importance")
246
+ plt.close(fig)
247
+ gr.Plot(fig)
248
+ else:
249
+ gr.Markdown("⚠️ Feature importance not available")
250
 
251
  # =========================
252
  # πŸš€ LAUNCH