File size: 6,973 Bytes
8c9b0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Lead.AI Customer Predictor β€” Live Demo
Predicts customer churn and purchase likelihood for small businesses.
Visit https://www.lead-ai.us for a custom deployment.
"""

import gradio as gr
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
import warnings
warnings.filterwarnings("ignore")

# ── Train demo models ─────────────────────────────────────────────────────────
np.random.seed(99)
n = 3000

tenure      = np.random.randint(1, 60, n)
purchases   = np.random.randint(0, 50, n)
avg_spend   = np.random.uniform(10, 800, n)
support_tix = np.random.randint(0, 15, n)
days_since  = np.random.randint(1, 180, n)
email_opens = np.random.uniform(0, 1, n)

X = np.column_stack([tenure, purchases, avg_spend, support_tix, days_since, email_opens])

# Churn: high support + long since last purchase + low email engagement
churn_score = (support_tix * 0.3 + days_since * 0.01 - purchases * 0.05
               - email_opens * 0.5 - tenure * 0.005)
y_churn     = (churn_score > np.percentile(churn_score, 65)).astype(int)

# Purchase: recent + engaged + history
buy_score   = (purchases * 0.4 + email_opens * 0.3 - days_since * 0.008 + avg_spend * 0.001)
y_buy       = (buy_score > np.percentile(buy_score, 50)).astype(int)

churn_model = GradientBoostingClassifier(n_estimators=100, random_state=42)
churn_model.fit(X, y_churn)

buy_model = GradientBoostingClassifier(n_estimators=100, random_state=42)
buy_model.fit(X, y_buy)

SEGMENTS = {
    (False, True):  ("🌟 High-Value Active",    "This customer is engaged and ready to buy. Prioritize for upsell offers."),
    (False, False): ("βœ… Stable Retained",       "Low churn risk but not currently primed to buy. Nurture with content."),
    (True,  True):  ("⚑ At-Risk, Still Buying", "Buying but showing churn signals. Act now with a retention offer."),
    (True,  False): ("🚨 High Churn Risk",       "This customer is disengaging. Send a personal win-back message today."),
}

def predict_customer(tenure, purchases, avg_spend, support_tickets,
                     days_since_purchase, email_open_rate):
    feats = np.array([[tenure, purchases, avg_spend, support_tickets,
                       days_since_purchase, email_open_rate]])

    churn_prob = churn_model.predict_proba(feats)[0][1]
    buy_prob   = buy_model.predict_proba(feats)[0][1]

    churn_pct  = round(churn_prob * 100, 1)
    buy_pct    = round(buy_prob   * 100, 1)

    is_churn = churn_pct >= 50
    is_buy   = buy_pct   >= 50

    segment, action = SEGMENTS[(is_churn, is_buy)]

    churn_bar = f"{'β–ˆ' * int(churn_pct // 5)}{'β–‘' * (20 - int(churn_pct // 5))} {churn_pct}%"
    buy_bar   = f"{'β–ˆ' * int(buy_pct   // 5)}{'β–‘' * (20 - int(buy_pct   // 5))} {buy_pct}%"

    report  = f"## {segment}\n\n"
    report += f"**Recommended Action:** {action}\n\n"
    report += "---\n\n"
    report += "### Prediction Scores\n\n"
    report += f"**Churn Risk:**    `{churn_bar}`\n\n"
    report += f"**Purchase Likelihood:** `{buy_bar}`\n\n"
    report += "---\n\n"
    report += "### Key Signals\n\n"

    signals = []
    if days_since_purchase > 60:
        signals.append(f"⚠️  Last purchase was **{days_since_purchase} days ago** β€” engagement is dropping")
    if support_tickets >= 5:
        signals.append(f"⚠️  **{support_tickets} support tickets** β€” customer may be frustrated")
    if email_open_rate < 0.2:
        signals.append("⚠️  **Low email engagement** β€” re-engagement campaign recommended")
    if purchases >= 10:
        signals.append(f"βœ“  **{purchases} purchases** β€” loyal customer history")
    if email_open_rate >= 0.5:
        signals.append("βœ“  **High email engagement** β€” customer is paying attention")
    if tenure >= 12:
        signals.append(f"βœ“  **{tenure} months** customer β€” long-term relationship")

    if signals:
        report += "\n".join(signals) + "\n\n"

    report += "---\n\n"
    report += "> ⚠️ Demo model trained on synthetic data. Your production system will learn "
    report += "from your actual customer history for accurate predictions.\n\n"
    report += "**[β†’ Get a Custom Customer Predictor for Your Business](https://www.lead-ai.us)**"

    return report


with gr.Blocks(
    title="Lead.AI Customer Predictor",
    theme=gr.themes.Soft(primary_hue="blue"),
    css=".footer { text-align:center; margin-top:20px; color:#666; }"
) as demo:

    gr.Markdown("""
# 🎯 Lead.AI Customer Predictor
### Know Which Customers Are About to Leave β€” Before They Do

Enter customer data below. The AI will predict churn risk, purchase likelihood,
and tell you exactly what action to take.

> πŸ’Ό This is a live proof-of-concept. [Request a custom system β†’](https://www.lead-ai.us)
""")

    with gr.Row():
        with gr.Column():
            gr.Markdown("### Customer Profile")
            tenure_in    = gr.Slider(1, 60, value=12, step=1,
                                     label="Customer Tenure (months)")
            purchases_in = gr.Slider(0, 50, value=8, step=1,
                                     label="Total Purchases")
            avg_spend_in = gr.Slider(10, 800, value=150, step=5,
                                     label="Average Order Value ($)")
            support_in   = gr.Slider(0, 15, value=1, step=1,
                                     label="Support Tickets (last 90 days)")
            days_in      = gr.Slider(1, 180, value=30, step=1,
                                     label="Days Since Last Purchase")
            email_in     = gr.Slider(0.0, 1.0, value=0.4, step=0.05,
                                     label="Email Open Rate (0 = never, 1 = always)")
            btn          = gr.Button("πŸ” Analyze This Customer", variant="primary", size="lg")

        with gr.Column():
            gr.Markdown("### AI Prediction")
            report_md = gr.Markdown()

    btn.click(
        fn=predict_customer,
        inputs=[tenure_in, purchases_in, avg_spend_in, support_in, days_in, email_in],
        outputs=report_md,
    )

    gr.Examples(
        examples=[
            [2,  1,  45,  8, 90, 0.05],
            [36, 28, 320, 0,  5, 0.75],
            [8,  12, 180, 4, 45, 0.30],
            [18,  3,  90, 0, 120, 0.10],
        ],
        inputs=[tenure_in, purchases_in, avg_spend_in, support_in, days_in, email_in],
        label="Try These Customer Profiles",
    )

    gr.Markdown("""
---
<div class="footer">
🌐 <a href="https://www.lead-ai.us">www.lead-ai.us</a> &nbsp;|&nbsp;
πŸ’» <a href="https://github.com/Lead-AI-US/lead-ai-customer-predictor">GitHub</a> &nbsp;|&nbsp;
πŸ€— <a href="https://huggingface.co/lead-ai-labs">Hugging Face</a>
<br><br>
<strong>Need this running on your real customer data?</strong>
<a href="https://www.lead-ai.us">Request a Custom Lead.AI Setup β†’</a>
</div>
""")

if __name__ == "__main__":
    demo.launch()