File size: 10,904 Bytes
d25d5d9
 
 
 
e5eab30
 
d25d5d9
e5eab30
308d819
e5eab30
 
 
 
 
 
d25d5d9
308d819
 
a5b3e42
308d819
a5b3e42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15dfebb
a5b3e42
15dfebb
 
 
a5b3e42
15dfebb
 
 
308d819
e5eab30
15dfebb
a5b3e42
15dfebb
a5b3e42
15dfebb
a5b3e42
 
 
 
15dfebb
a5b3e42
15dfebb
 
a5b3e42
 
 
15dfebb
a5b3e42
15dfebb
 
 
a5b3e42
15dfebb
 
a5b3e42
 
 
 
 
 
15dfebb
a5b3e42
15dfebb
 
 
 
 
 
 
a5b3e42
 
 
 
 
308d819
a5b3e42
 
308d819
 
 
a5b3e42
308d819
 
a5b3e42
e5eab30
0b2eb15
15dfebb
e5eab30
308d819
e5eab30
15dfebb
b686fad
 
 
 
 
 
 
 
a5b3e42
0b2eb15
15dfebb
0b2eb15
 
15dfebb
0b2eb15
 
d25d5d9
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2eb15
d25d5d9
15dfebb
0b2eb15
e5eab30
 
 
 
 
d25d5d9
15dfebb
 
 
 
 
 
d25d5d9
15dfebb
0b2eb15
74c4919
0b2eb15
74c4919
0b2eb15
74c4919
0b2eb15
15dfebb
308d819
15dfebb
 
 
 
 
 
 
308d819
15dfebb
308d819
 
a5b3e42
e5eab30
 
15dfebb
 
0b2eb15
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b2eb15
 
308d819
d25d5d9
a5b3e42
e5eab30
308d819
e5eab30
 
d25d5d9
a5b3e42
308d819
15dfebb
308d819
15dfebb
308d819
 
a5b3e42
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b3e42
 
 
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b3e42
 
308d819
 
15dfebb
 
 
 
 
308d819
a5b3e42
 
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5b3e42
308d819
15dfebb
a5b3e42
15dfebb
308d819
 
 
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308d819
 
74c4919
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c4919
308d819
74c4919
308d819
 
 
15dfebb
 
 
 
74c4919
308d819
 
15dfebb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308d819
c2380b0
15dfebb
308d819
15dfebb
308d819
a5b3e42
 
15dfebb
a5b3e42
15dfebb
a5b3e42
15dfebb
 
 
 
 
 
 
 
 
 
 
 
a5b3e42
15dfebb
 
 
 
 
 
a5b3e42
15dfebb
a5b3e42
15dfebb
a5b3e42
15dfebb
a5b3e42
15dfebb
 
 
74c4919
308d819
15dfebb
308d819
e5eab30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import gradio as gr
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("Agg")

# =========================
# πŸ”Ή Load Model
# =========================
try:
    with open("DecisionTreeClassifier.pkl", "rb") as f:
        model = pickle.load(f)
except:
    model = None


# =========================
# πŸ”Ή DASHBOARD ANALYSIS
# =========================
def dashboard_analysis(age, gender, tenure, usage, support, delay,
                      subscription, contract, spend, interaction):

    try:
        # Convert inputs
        age = float(age)
        tenure = float(tenure)
        usage = float(usage)
        support = float(support)
        delay = float(delay)
        spend = float(spend)
        interaction = float(interaction)

        # KPI Summary
        kpi = f"""
### πŸ“Š Customer Summary
- Age: **{age}**
- Gender: **{gender}**
- Tenure: **{tenure} months**
- Usage: **{usage}**
- Support Calls: **{support}**
- Payment Delay: **{delay}**
- Subscription: **{subscription}**
- Contract Type: **{contract}**
- Total Spend: **β‚Ή{spend}**
- Interaction Score: **{interaction}**
"""

        # Chart 1: Customer Profile
        fig1, ax1 = plt.subplots()
        features = ["Age", "Tenure", "Usage", "Support", "Delay"]
        values = [age, tenure, usage, support, delay]

        ax1.bar(features, values)
        ax1.set_title("Customer Profile")
        plt.close(fig1)

        # Chart 2: Financial & Interaction
        fig2, ax2 = plt.subplots()

        ax2.bar(["Spend", "Interaction"], [spend, interaction])
        ax2.set_title("Financial & Interaction")
        plt.close(fig2)

        # Chart 3: Risk Indicators
        risk_scores = [
            delay / 30,
            support / 20,
            (6 - tenure) / 6 if tenure < 6 else 0
        ]

        labels = ["Delay Risk", "Support Risk", "Tenure Risk"]

        fig3, ax3 = plt.subplots()
        ax3.bar(labels, risk_scores)
        ax3.set_title("Risk Indicators")
        plt.close(fig3)

        # Chart 4: Subscription Level
        fig4, ax4 = plt.subplots()

        sub_map = {
            "Basic": 1,
            "Standard": 2,
            "Premium": 3
        }

        ax4.bar(["Subscription Level"], [sub_map[subscription]])
        ax4.set_title("Subscription Level")
        plt.close(fig4)

        return kpi, fig1, fig2, fig3, fig4

    except Exception as e:
        return f"Error: {str(e)}", None, None, None, None


# =========================
# πŸ”Ή PREDICTION FUNCTION
# =========================
def predict_churn(age, gender, tenure, usage, support, delay,
                  subscription, contract, spend, interaction):

    try:

        if model is None:
            return "Model not loaded ❌", "", "", None, ""

        # Convert Inputs
        age = float(age)
        tenure = float(tenure)
        usage = float(usage)
        support = float(support)
        delay = float(delay)
        spend = float(spend)
        interaction = float(interaction)

        # Encoding
        gender_val = 1 if gender == "Female" else 0

        sub_premium = 1 if subscription == "Premium" else 0
        sub_standard = 1 if subscription == "Standard" else 0

        contract_monthly = 1 if contract == "Monthly" else 0
        contract_quarterly = 1 if contract == "Quarterly" else 0

        # Model Input
        input_data = np.array([[
            age,
            gender_val,
            tenure,
            usage,
            support,
            delay,
            spend,
            interaction,
            sub_premium,
            sub_standard,
            contract_monthly,
            contract_quarterly
        ]])

        # Prediction
        pred = model.predict(input_data)[0]

        if hasattr(model, "predict_proba"):
            prob = model.predict_proba(input_data)[0][1]
        else:
            prob = 0.5

        # Result
        result = (
            "⚠️ Likely to Churn"
            if pred == 1
            else "βœ… Stable Customer"
        )

        # Risk Level
        if prob > 0.7:
            risk = "πŸ”΄ High Risk"
        elif prob > 0.4:
            risk = "🟠 Medium Risk"
        else:
            risk = "🟒 Low Risk"

        # Probability Chart
        fig, ax = plt.subplots()

        ax.bar(
            ["No Churn", "Churn"],
            [1 - prob, prob]
        )

        ax.set_ylim(0, 1)
        ax.set_title("Prediction Probability")

        plt.close(fig)

        # Explanation
        reasons = []

        if delay > 15:
            reasons.append("High payment delay")

        if tenure < 6:
            reasons.append("Low tenure")

        if support > 5:
            reasons.append("Too many support calls")

        explanation = (
            "\n".join(reasons)
            if reasons
            else "No strong risk indicators"
        )

        return (
            result,
            f"{prob * 100:.2f}%",
            risk,
            fig,
            explanation
        )

    except Exception as e:
        return f"Error: {str(e)}", "", "", None, ""


# =========================
# 🎨 UI
# =========================
with gr.Blocks() as demo:

    gr.Markdown("# πŸš€ Customer Churn Interactive Dashboard")

    # =====================================================
    # πŸ“Š DASHBOARD TAB
    # =====================================================
    with gr.Tab("πŸ“Š Dashboard"):

        with gr.Row():

            d_age = gr.Number(
                value=30,
                label="Age"
            )

            d_gender = gr.Dropdown(
                ["Male", "Female"],
                value="Male",
                label="Gender"
            )

            d_tenure = gr.Number(
                value=12,
                label="Tenure"
            )

            d_usage = gr.Number(
                value=10,
                label="Usage"
            )

        with gr.Row():

            d_support = gr.Number(
                value=2,
                label="Support Calls"
            )

            d_delay = gr.Number(
                value=5,
                label="Payment Delay"
            )

            d_subscription = gr.Dropdown(
                ["Basic", "Standard", "Premium"],
                value="Basic",
                label="Subscription"
            )

            d_contract = gr.Dropdown(
                ["Monthly", "Quarterly", "Yearly"],
                value="Monthly",
                label="Contract Type"
            )

        d_spend = gr.Number(
            value=2000,
            label="Total Spend"
        )

        d_interaction = gr.Number(
            value=20,
            label="Interaction"
        )

        analyze_btn = gr.Button("Analyze Dashboard")

        kpi_text = gr.Markdown()

        chart1 = gr.Plot(label="Customer Profile")
        chart2 = gr.Plot(label="Financial Analysis")
        chart3 = gr.Plot(label="Risk Indicators")
        chart4 = gr.Plot(label="Subscription Analysis")

        analyze_btn.click(
            dashboard_analysis,
            inputs=[
                d_age,
                d_gender,
                d_tenure,
                d_usage,
                d_support,
                d_delay,
                d_subscription,
                d_contract,
                d_spend,
                d_interaction
            ],
            outputs=[
                kpi_text,
                chart1,
                chart2,
                chart3,
                chart4
            ]
        )

    # =====================================================
    # πŸ” PREDICTION TAB
    # =====================================================
    with gr.Tab("πŸ” Prediction"):

        with gr.Row():

            age = gr.Number(
                value=30,
                label="Age"
            )

            gender = gr.Dropdown(
                ["Male", "Female"],
                value="Male",
                label="Gender"
            )

            tenure = gr.Number(
                value=12,
                label="Tenure"
            )

            usage = gr.Number(
                value=10,
                label="Usage"
            )

        with gr.Row():

            support = gr.Number(
                value=2,
                label="Support Calls"
            )

            delay = gr.Number(
                value=5,
                label="Payment Delay"
            )

            subscription = gr.Dropdown(
                ["Basic", "Standard", "Premium"],
                value="Basic",
                label="Subscription"
            )

            contract = gr.Dropdown(
                ["Monthly", "Quarterly", "Yearly"],
                value="Monthly",
                label="Contract Type"
            )

        spend = gr.Number(
            value=2000,
            label="Total Spend"
        )

        interaction = gr.Number(
            value=20,
            label="Interaction"
        )

        btn = gr.Button("Predict")

        result = gr.Textbox(label="Prediction")
        prob = gr.Textbox(label="Probability")
        risk = gr.Textbox(label="Risk Level")
        graph = gr.Plot(label="Prediction Graph")
        explanation = gr.Textbox(
            label="Why this prediction?"
        )

        btn.click(
            predict_churn,
            inputs=[
                age,
                gender,
                tenure,
                usage,
                support,
                delay,
                subscription,
                contract,
                spend,
                interaction
            ],
            outputs=[
                result,
                prob,
                risk,
                graph,
                explanation
            ]
        )

    # =====================================================
    # πŸ“ˆ INSIGHTS TAB
    # =====================================================
    with gr.Tab("πŸ“ˆ Insights"):

        if model is not None and hasattr(model, "feature_importances_"):

            fig, ax = plt.subplots()

            features = [
                "Age",
                "Gender",
                "Tenure",
                "Usage",
                "Support",
                "Delay",
                "Spend",
                "Interaction",
                "Premium Subscription",
                "Standard Subscription",
                "Monthly Contract",
                "Quarterly Contract"
            ]

            ax.barh(
                features,
                model.feature_importances_
            )

            ax.set_title("Feature Importance")

            plt.close(fig)

            gr.Plot(fig)

        else:
            gr.Markdown(
                "⚠️ Feature importance not available"
            )

# =========================
# πŸš€ Launch App
# =========================
demo.launch(debug=True)