File size: 10,893 Bytes
03e39f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import numpy as np
import pickle
import os
import sqlite3


def create_database():
    # Connecting to the SQLite database
    conn = sqlite3.connect('churndatabase.db')
    cursor = conn.cursor()

    # Create customer_churn table
    cursor.execute("""
    CREATE TABLE customer_churn (
        customer_id INT PRIMARY KEY,
        gender VARCHAR(10),
        age INT,
        marital_status VARCHAR(10),
        dependents INT,
        contract_type VARCHAR(10),
        internet_service VARCHAR(20),
        phone_service VARCHAR(3),
        multiple_lines VARCHAR(3),
        online_security VARCHAR(3),
        online_backup VARCHAR(3),
        device_protection VARCHAR(3),
        tech_support VARCHAR(3),
        streaming_tv VARCHAR(3),
        streaming_movies VARCHAR(3),
        monthly_charges NUMBER(8, 2),
        total_charges NUMBER(10, 2),
        churn_status VARCHAR(3)
    )
    """)

    # Create customer_churn_full table
    cursor.execute("""
    CREATE TABLE customer_churn_full (
        customer_id INT PRIMARY KEY,
        gender VARCHAR(10),
        age INT,
        marital_status VARCHAR(10),
        dependents INT,
        contract_type VARCHAR(10),
        internet_service VARCHAR(20),
        phone_service VARCHAR(3),
        multiple_lines VARCHAR(3),
        online_security VARCHAR(3),
        online_backup VARCHAR(3),
        device_protection VARCHAR(3),
        tech_support VARCHAR(3),
        streaming_tv VARCHAR(3),
        streaming_movies VARCHAR(3),
        monthly_charges NUMBER(8, 2),
        total_charges NUMBER(10, 2),
        churn_status VARCHAR(3),
        call_duration_minutes INT,
        latitude NUMBER(9, 6),
        longitude NUMBER(9, 6)
    )
    """)

    # Insert data into customer_churn table
    cursor.execute("""
    INSERT INTO customer_churn
    SELECT
        TRUNC(RANDOM() * 1000000) AS customer_id,
        CASE WHEN RANDOM() < 0.5 THEN 'Male' ELSE 'Female' END AS gender,
        TRUNC(RANDOM() * 60 + 18) AS age,
        CASE WHEN RANDOM() < 0.5 THEN 'Married' ELSE 'Single' END AS marital_status,
        TRUNC(RANDOM() * 5) AS dependents,
        CASE WHEN RANDOM() < 0.5 THEN 'Monthly' ELSE 'Yearly' END AS contract_type,
        CASE WHEN RANDOM() < 0.5 THEN 'DSL' ELSE 'Fiber Optic' END AS internet_service,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS phone_service,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS multiple_lines,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS online_security,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS online_backup,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS device_protection,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS tech_support,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS streaming_tv,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS streaming_movies,
        ROUND(RANDOM() * 100, 2) AS monthly_charges,
        ROUND(RANDOM() * 1000, 2) AS total_charges,
        CASE WHEN RANDOM() < 0.2 THEN 'Yes' ELSE 'No' END AS churn_status
    FROM
        (SELECT 1)
    CROSS JOIN
        (SELECT 1)
    LIMIT
        500
    """)

    # Insert data into customer_churn_full table
    cursor.execute("""
    INSERT INTO customer_churn_full
    SELECT
        TRUNC(RANDOM() * 1000000) AS customer_id,
        CASE WHEN RANDOM() < 0.5 THEN 'Male' ELSE 'Female' END AS gender,
        TRUNC(RANDOM() * 60 + 18) AS age,
        CASE WHEN RANDOM() < 0.5 THEN 'Married' ELSE 'Single' END AS marital_status,
        TRUNC(RANDOM() * 5) AS dependents,
        CASE WHEN RANDOM() < 0.5 THEN 'Monthly' ELSE 'Yearly' END AS contract_type,
        CASE WHEN RANDOM() < 0.5 THEN 'DSL' ELSE 'Fiber Optic' END AS internet_service,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS phone_service,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS multiple_lines,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS online_security,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS online_backup,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS device_protection,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS tech_support,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS streaming_tv,
        CASE WHEN RANDOM() < 0.5 THEN 'Yes' ELSE 'No' END AS streaming_movies,
        ROUND(RANDOM() * 100, 2) AS monthly_charges,
        ROUND(RANDOM() * 1000, 2) AS total_charges,
        CASE WHEN RANDOM() < 0.2 THEN 'Yes' ELSE 'No' END AS churn_status,
        TRUNC(RANDOM() * 1200) AS call_duration_minutes,
        ROUND(RANDOM() * 180 - 90, 6) AS latitude,
        ROUND(RANDOM() * 360 - 180, 6) AS longitude
    FROM
        (SELECT 1)
    CROSS JOIN
        (SELECT 1)
    LIMIT
        500
    """)

    conn.commit()
    conn.close()

create_database()

#Loading ML Components
DIRPATH = os.path.dirname(os.path.realpath(__file__))
ml_join= os.path.join(DIRPATH,'ml_components.pkl')
with open(ml_join,"rb") as f:
    loaded_model_components = pickle.load(f)

# Extracting ML components
model = loaded_model_components['model']
encoder = loaded_model_components['encoder']
scaler = loaded_model_components['scaler']

#To predict churn
def predict_churn(gender, SeniorCitizen, Partner, Dependents, PhoneService, MultipleLines,
                InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,
                StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod,
                tenure, MonthlyCharges, TotalCharges):
    
    #Encoding categorical features
    encoded_data = encoder.transform([[gender, SeniorCitizen, Partner, Dependents, PhoneService, MultipleLines,
                                    InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,
                                    StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod]])
    
    num_data = np.array([[tenure, MonthlyCharges, TotalCharges]])
    scaled_num_data = scaler.transform(num_data)
    
    combined_data = np.hstack((encoded_data, scaled_num_data))
        
    #Making predictions using fitted model
    model_output = model.predict_proba(combined_data)
    prob_churn = float(model_output[0][1])
    return {'Churn Probability': prob_churn}

with gr.Blocks(css="""
        background-color: #6db05d;
        padding: 2rem;
        border: 2px solid #e86347;
    }
    .gradio-input {
        border: 1px solid #ccc000;
        padding: 0.5rem;
        border-radius: 0.5rem;
        font-size: 1rem;
    }
    .gradio-label {
        font-weight: bold;
        margin-bottom: 0.5rem;
    }
    .gradio-markdown h1 {
        font-size: 4rem;
        font-family: 'Georgia', serif;
        margin-top: 0;
        margin-bottom: 0.5rem;
        color: white;
        background-color: #1E90FF;
        padding: 1rem;
        border-radius: 0.5rem;
        text-align: center;
    }
    .gradio-markdown h2 {
        font-size: 2rem;
        font-family: 'DejaVu Sans Mono', monospace;
        text-align: center;
        margin-top: 0;
        margin-bottom: 0.5rem;
        color: white;
        background-color: #4169E1;
        padding: 0.5rem 1rem;
        border-radius: 0.5rem;
    }
    .gradio-accordion {
        background-color: #6db05d;
        border-radius: 0.75rem;
        padding: 1rem;
        margin-bottom: 1rem;
        text-align: left;
    }
""") as test:

    gr.Markdown("# CHURN PREDICTION")
    gr.Markdown("## Using machine learning and Oracle SQL")
    gr.Markdown("### By Hitesh Beeraka and Yash Singhvi")
    with gr.Row():
        with gr.Column(scale=2):
            with gr.Accordion(label="Personal Information", open=False):
                gender = gr.Radio(choices=['Male', 'Female'], label='Gender', interactive=True)
                SeniorCitizen = gr.Radio(choices=['Yes', 'No'], label='SeniorCitizen', interactive=True)
                Partner = gr.Radio(choices=['Yes', 'No'], label='Partner', interactive=True)
                Dependents = gr.Radio(choices=['Yes', 'No'], label='Dependents', interactive=True)
        with gr.Column(scale=2):
            with gr.Accordion(label="Phone and Internet Services", open=False):
                PhoneService = gr.Radio(choices=['Yes', 'No'], label='PhoneService', interactive=True)
                MultipleLines = gr.Radio(choices=['Yes', 'No'], label='MultipleLines', interactive=True)
                InternetService = gr.Radio(choices=['Fiber optic', 'No', 'DSL'], label='InternetService', interactive=True)
    with gr.Row():
        with gr.Column(scale=2):
            with gr.Accordion(label="Security and Support Services", open=False):
                OnlineSecurity = gr.Radio(choices=['Yes', 'No'], label='OnlineSecurity', interactive=True)
                OnlineBackup = gr.Radio(choices=['Yes', 'No'], label='OnlineBackup', interactive=True)
                DeviceProtection = gr.Radio(choices=['Yes', 'No'], label='DeviceProtection', interactive=True)
                TechSupport = gr.Radio(choices=['Yes', 'No'], label='TechSupport', interactive=True)
        with gr.Column(scale=2):
            with gr.Accordion(label="Entertainment Services", open=False):
                StreamingTV = gr.Radio(choices=['Yes', 'No'], label='StreamingTV', interactive=True)
                StreamingMovies = gr.Radio(choices=['Yes', 'No'], label='StreamingMovies', interactive=True)
    with gr.Row():
        with gr.Column(scale=2):
            with gr.Accordion(label="Contract and Billing Information", open=False):
                Contract = gr.Radio(choices=['Month-to-month', 'One year', 'Two year'], label='Contract', interactive=True)
                PaperlessBilling = gr.Radio(choices=['Yes', 'No'], label='PaperlessBilling', interactive=True)
                PaymentMethod = gr.Radio(choices=['Electronic check', 'Mailed check', 'Credit card (automatic)', 'Bank transfer (automatic)'], label='PaymentMethod', interactive=True)
        with gr.Column(scale=2):
            with gr.Accordion(label="Charges and Tenure", open=False):
                tenure = gr.Number(label='Tenure', interactive=True)
                MonthlyCharges = gr.Number(label='MonthlyCharges', interactive=True)
                TotalCharges = gr.Number(label='TotalCharges', interactive=True)
    
    output = gr.Label(label="Churn Probability")
    submit_btn = gr.Button("Predict")
    submit_btn.click(
        fn=predict_churn,
        inputs=[gender, SeniorCitizen, Partner, Dependents, PhoneService, MultipleLines, InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport, StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod, tenure, MonthlyCharges, TotalCharges],
        outputs=output
    )
test.launch(inbrowser=True, show_error=True,share=True)