harishsohani commited on
Commit
ac08d9b
·
verified ·
1 Parent(s): 8717edf

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import joblib
2
+ import pandas as pd
3
+ from flask import Flask, request, jsonify
4
+
5
+ # Initialize Flask app with a name
6
+ cust_churn_predictor_api = Flask ("Customer Churn Predictor Week1")
7
+
8
+ # Load the trained churn prediction model
9
+ model = joblib.load ("churn_prediction_model_v2_0.joblib")
10
+
11
+ # Define a route for the home page
12
+ @cust_churn_predictor_api.get ('/')
13
+ def home ():
14
+ return "Welcome to the Customer Churn Prediction Week1 API!"
15
+
16
+ # Define an endpoint to predict churn for a single customer
17
+ @cust_churn_predictor_api.post ('/v1/customer')
18
+ def predict_churn ():
19
+ # Get JSON data from the request
20
+ customer_data = request.get_json ()
21
+
22
+ # Extract relevant customer features from the input data
23
+ sample = {
24
+ 'SeniorCitizen' : customer_data ['SeniorCitizen'],
25
+ 'tenure' : customer_data ['tenure'],
26
+ 'MonthlyCharges' : customer_data ['MonthlyCharges'],
27
+ 'TotalCharges' : customer_data ['TotalCharges'],
28
+ 'Partner' : customer_data ['Partner'],
29
+ 'Dependents' : customer_data ['Dependents'],
30
+ 'PhoneService' : customer_data ['PhoneService'],
31
+ 'InternetService' : customer_data ['InternetService'],
32
+ 'Contract' : customer_data ['Contract'],
33
+ 'PaymentMethod' : customer_data ['PaymentMethod']
34
+ }
35
+
36
+ # Convert the extracted data into a DataFrame
37
+ input_data = pd.DataFrame ([sample])
38
+
39
+ # Make a churn prediction using the trained model
40
+ prediction = model.predict (input_data).tolist ()[0]
41
+
42
+ # Map prediction result to a human-readable label
43
+ prediction_label = "churn" if prediction == 1 else "not churn"
44
+
45
+ # Return the prediction as a JSON response
46
+ return jsonify ({'Prediction': prediction_label})
47
+
48
+ # Define an endpoint to predict churn for a batch of customers
49
+ @cust_churn_predictor_api.post ('/v1/customerbatch')
50
+ def predict_churn_batch ():
51
+ # Get the uploaded CSV file from the request
52
+ file = request.files ['file']
53
+
54
+ # Read the file into a DataFrame
55
+ input_data = pd.read_csv (file)
56
+
57
+ # Make predictions for the batch data and convert raw predictions into a readable format
58
+ predictions = [
59
+ 'Churn' if x == 1
60
+ else "Not Churn"
61
+ for x in model.predict (input_data.drop ("customerID",axis=1)).tolist ()
62
+ ]
63
+
64
+ cust_id_list = input_data.CustomerId.values.tolist ()
65
+ output_dict = dict(zip (cust_id_list, predictions))
66
+
67
+ return output_dict
68
+
69
+ # Run the Flask app in debug mode
70
+ if __name__ == '__main__':
71
+ app.run(debug=True)