Azie88 commited on
Commit
ce55ba8
β€’
1 Parent(s): 40edf7b

Gradio App w/ soft theme

Browse files
Files changed (1) hide show
  1. app.py +144 -0
app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import joblib, os
5
+
6
+ script_dir = os.path.dirname(os.path.abspath(__file__))
7
+ pipeline_path = os.path.join(script_dir, 'toolkit', 'pipeline.joblib')
8
+ model_path = os.path.join(script_dir, 'toolkit', 'Random Forest Classifier.joblib')
9
+
10
+ # Load transformation pipeline and model
11
+ pipeline = joblib.load(pipeline_path)
12
+ model = joblib.load(model_path)
13
+
14
+ # Create a function to calculate TotalCharges
15
+ def calculate_total_charges(tenure, monthly_charges):
16
+ return tenure * monthly_charges
17
+
18
+ # Create a function that applies the ML pipeline and makes predictions
19
+ def predict(SeniorCitizen, Partner, Dependents, tenure,
20
+ InternetService, OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,
21
+ StreamingTV, StreamingMovies, Contract, PaperlessBilling, PaymentMethod,
22
+ MonthlyCharges):
23
+
24
+ # Calculate TotalCharges
25
+ TotalCharges = calculate_total_charges(tenure, MonthlyCharges)
26
+
27
+ # Create a dataframe with the input data
28
+ input_df = pd.DataFrame({
29
+ 'SeniorCitizen': [SeniorCitizen],
30
+ 'Partner': [Partner],
31
+ 'Dependents': [Dependents],
32
+ 'tenure': [tenure],
33
+ 'InternetService': [InternetService],
34
+ 'OnlineSecurity': [OnlineSecurity],
35
+ 'OnlineBackup': [OnlineBackup],
36
+ 'DeviceProtection': [DeviceProtection],
37
+ 'TechSupport': [TechSupport],
38
+ 'StreamingTV': [StreamingTV],
39
+ 'StreamingMovies': [StreamingMovies],
40
+ 'Contract': [Contract],
41
+ 'PaperlessBilling': [PaperlessBilling],
42
+ 'PaymentMethod': [PaymentMethod],
43
+ 'MonthlyCharges': [MonthlyCharges],
44
+ 'TotalCharges': [TotalCharges]
45
+ })
46
+
47
+ # Selecting categorical and numerical columns separately
48
+ cat_cols = [col for col in input_df.columns if input_df[col].dtype == 'object']
49
+ num_cols = [col for col in input_df.columns if input_df[col].dtype != 'object']
50
+
51
+ X_processed = pipeline.transform(input_df)
52
+
53
+ # Extracting feature names for categorical columns after one-hot encoding
54
+ cat_encoder = pipeline.named_steps['preprocessor'].named_transformers_['cat'].named_steps['onehot']
55
+ cat_feature_names = cat_encoder.get_feature_names_out(cat_cols)
56
+
57
+ # Concatenating numerical and categorical feature names
58
+ feature_names = num_cols + list(cat_feature_names)
59
+
60
+ # Convert X_processed to DataFrame
61
+ final_df = pd.DataFrame(X_processed, columns=feature_names)
62
+
63
+ # Extract the first three columns and remaining columns, then merge
64
+ first_three_columns = final_df.iloc[:, :3]
65
+ remaining_columns = final_df.iloc[:, 3:]
66
+ final_df = pd.concat([remaining_columns, first_three_columns], axis=1)
67
+
68
+ # Make predictions using the model
69
+ prediction = model.predict(final_df)[0]
70
+ prediction_label = "Customer is likely to CHURN πŸ”΄" if prediction == "Yes" else "Customer is NOT likely to CHURN βœ…"
71
+
72
+ return prediction_label
73
+
74
+ input_interface = []
75
+
76
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
77
+
78
+ Title = gr.Label('Customer Churn Prediction App')
79
+
80
+ with gr.Row():
81
+ Title
82
+
83
+ with gr.Row():
84
+ gr.Markdown("This app predicts likelihood of a customer to leave or stay with the company")
85
+
86
+ with gr.Row():
87
+ with gr.Column():
88
+ input_interface_column_1 = [
89
+ gr.components.Radio(['Yes', 'No'], label="Are you a Seniorcitizen?"),
90
+ gr.components.Radio(['Yes', 'No'], label='Do you have Partner?'),
91
+ gr.components.Radio(['No', 'Yes'], label='Do you have any Dependents?'),
92
+ gr.components.Slider(label='Enter lenghth of Tenure in Months', minimum=1, maximum=73, step=1),
93
+ gr.components.Radio(['DSL', 'Fiber optic', 'No Internet'], label='What is your Internet Service?'),
94
+ gr.components.Radio(['No', 'Yes'], label='Do you have Online Security?'),
95
+ gr.components.Radio(['No', 'Yes'], label='Do you have Online Backup?'),
96
+ gr.components.Radio(['No', 'Yes'], label='Do you have Device Protection?')
97
+ ]
98
+
99
+ with gr.Column():
100
+ input_interface_column_2 = [
101
+ gr.components.Radio(['No', 'Yes'], label='Do you have Tech Support?'),
102
+ gr.components.Radio(['No', 'Yes'], label='Do you have Streaming TV?'),
103
+ gr.components.Radio(['No', 'Yes'], label='Do you have Streaming Movies?'),
104
+ gr.components.Radio(['Month-to-month', 'One year', 'Two year'], label='What is your Contract Type?'),
105
+ gr.components.Radio(['Yes', 'No'], label='Do you prefer Paperless Billing?'),
106
+ gr.components.Radio(['Electronic check', 'Mailed check', 'Bank transfer (automatic)', 'Credit card (automatic)'], label='Which PaymentMethod do you prefer?'),
107
+ gr.components.Slider(label="Enter monthly charges", minimum=18.40, maximum=118.65)
108
+ ]
109
+
110
+ with gr.Row():
111
+ input_interface.extend(input_interface_column_1)
112
+ input_interface.extend(input_interface_column_2)
113
+
114
+ with gr.Row():
115
+ predict_btn = gr.Button('Predict')
116
+ output_interface = gr.Label(label="churn")
117
+
118
+ with gr.Accordion("Open for information on inputs", open=False):
119
+ gr.Markdown("""This app receives the following as inputs and processes them to return the prediction on whether a customer, will churn or not.
120
+
121
+ - SeniorCitizen: Whether a customer is a senior citizen or not
122
+ - Partner: Whether the customer has a partner or not (Yes, No)
123
+ - Dependents: Whether the customer has dependents or not (Yes, No)
124
+ - Tenure: Number of months the customer has stayed with the company
125
+ - InternetService: Customer's internet service provider (DSL, Fiber Optic, No)
126
+ - OnlineSecurity: Whether the customer has online security or not (Yes, No, No Internet)
127
+ - OnlineBackup: Whether the customer has online backup or not (Yes, No, No Internet)
128
+ - DeviceProtection: Whether the customer has device protection or not (Yes, No, No internet service)
129
+ - TechSupport: Whether the customer has tech support or not (Yes, No, No internet)
130
+ - StreamingTV: Whether the customer has streaming TV or not (Yes, No, No internet service)
131
+ - StreamingMovies: Whether the customer has streaming movies or not (Yes, No, No Internet service)
132
+ - Contract: The contract term of the customer (Month-to-Month, One year, Two year)
133
+ - PaperlessBilling: Whether the customer has paperless billing or not (Yes, No)
134
+ - Payment Method: The customer's payment method (Electronic check, mailed check, Bank transfer(automatic), Credit card(automatic))
135
+ - MonthlyCharges: The amount charged to the customer monthly
136
+ """)
137
+
138
+ predict_btn.click(fn=predict, inputs=input_interface, outputs=output_interface)
139
+
140
+ app.launch(share=True, server_port=8080, debug=True)
141
+
142
+ # Include the custom CSS file
143
+ app.queue() # Enable queueing for shared links
144
+ app.launch(share=True, inline=False, custom_css="style.css")