-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
368 lines (308 loc) · 12.2 KB
/
api.py
File metadata and controls
368 lines (308 loc) · 12.2 KB
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
from flask import Flask, request, jsonify
# Cross-Origin Resource Sharing (CORS)
# Modern browsers apply the "same-origin policy", which blocks web pages from
# making requests to a different origin than the one that served the page.
# This helps prevent malicious sites from reading sensitive data from another
# site you are logged into.
#
# However, there are many legitimate cases where cross-origin requests are
# needed. One example is:
#
## Single-Page Applications (SPA) hosted at example-frontend.com need to call
## APIs hosted at api.example-backend.com.
#
# To support this safely, CORS lets servers explicitly allow such requests.
from flask_cors import CORS
import joblib
import pandas as pd
app = Flask(__name__)
# CORS(
# app,
# resources={r"/api/*": {
# "origins": [
# "https://127.0.0.1",
# "https://localhost"
# ]
# }},
# methods=["GET", "POST", "OPTIONS"],
# allow_headers=["Content-Type"]
# )
CORS(
app, supports_credentials=False,
resources={r"/api/*": { # This means CORS will only apply to routes that start with /api/
"origins": [
"https://127.0.0.1", "https://localhost",
"https://127.0.0.1:443", "https://localhost:443",
"http://127.0.0.1", "http://localhost",
"http://127.0.0.1:5000", "http://localhost:5000",
"http://127.0.0.1:5500", "http://localhost:5500"
]
}},
methods=["GET", "POST", "OPTIONS"],
allow_headers=["Content-Type"])
# CORS(app, supports_credentials=False,
# origins=["*"])
# Load different models
# joblib is used to load a trained model so that the API can serve ML predictions
decisiontree_classifier_baseline = joblib.load('./model/decisiontree_classifier_baseline.pkl')
decisiontree_regressor_optimum = joblib.load('./model/decisiontree_regressor_optimum.pkl')
naive_bayes_classifier = joblib.load('./model/naive_Bayes_classifier_optimum.pkl')
knn_classifier = joblib.load('./model/knn_classifier_optimum.pkl')
svm_classifier = joblib.load('./model/support_vector_classifier_optimum.pkl')
random_forest_classifier = joblib.load('./model/random_forest_classifier_optimum.pkl')
label_encoders_1b = joblib.load('./model/label_encoders_1b.pkl')
label_encoders_2 = joblib.load('./model/label_encoders_2.pkl')
label_encoders_4 = joblib.load('./model/label_encoders_4.pkl')
scaler_4 = joblib.load('./model/scaler_4.pkl')
# Defines an HTTP endpoint
@app.route('/api/v1/models/decision-tree-classifier/predictions', methods=['POST'])
def predict_decision_tree_classifier():
# Accepts JSON data sent by a client (browser, curl, Postman, etc.)
data = request.get_json()
# Create a DataFrame with the correct feature names
new_data = pd.DataFrame([{
'monthly_fee': data.get('monthly_fee'),
'customer_age': data.get('customer_age'),
'support_calls': data.get('support_calls')
}])
# Define the expected feature order (based on the order used during training)
expected_features = [
'monthly_fee',
'customer_age',
'support_calls'
]
# Reorder and select only the expected columns
new_data = new_data[expected_features]
# Performs a prediction using the already trained machine learning model
prediction = decisiontree_classifier_baseline.predict(new_data)[0]
# Returns the result as a JSON response:
return jsonify({'Predicted Class = ': int(prediction)})
# *1* Sample JSON POST values
# {
# "monthly_fee": 60,
# "customer_age": 30,
# "support_calls": 1
# }
# *2.a.* Sample cURL POST values (without HTTPS in NGINX and Gunicorn)
# curl -X POST http://127.0.0.1:5000/api/v1/models/decision-tree-classifier/predictions \
# -H "Content-Type: application/json" \
# -d "{\"monthly_fee\": 60, \"customer_age\": 30, \"support_calls\": 1}"
# *2.b.* Sample cURL POST values (with HTTPS in NGINX and Gunicorn)
# curl --insecure -X POST https://127.0.0.1/api/v1/models/decision-tree-classifier/predictions \
# -H "Content-Type: application/json" \
# -d "{\"monthly_fee\": 60, \"customer_age\": 30, \"support_calls\": 1}"
# *3* Sample PowerShell values:
# $body = @{
# monthly_fee = 60
# customer_age = 30
# support_calls = 1
# } | ConvertTo-Json
# Invoke-RestMethod -Uri http://127.0.0.1:5000/api/v1/models/decision-tree-classifier/predictions `
# -Method POST `
# -Body $body `
# -ContentType "application/json"
@app.route('/api/v1/models/decision-tree-regressor/predictions', methods=['POST'])
def predict_decision_tree_regressor():
data = request.get_json()
# Expected input keys:
# 'PaymentDate', 'CustomerType', 'BranchSubCounty',
# 'ProductCategoryName', 'QuantityOrdered', 'Percenta3geProfitPerUnit'
# Create a DataFrame based on the input
new_data = pd.DataFrame([data])
# Convert PaymentDate to datetime
new_data['PaymentDate'] = pd.to_datetime(new_data['PaymentDate'])
# Identify all datetime columns
datetime_columns = new_data.select_dtypes(include=['datetime64']).columns
categorical_cols = new_data.select_dtypes(exclude=['int64', 'float64', 'datetime64[ns]']).columns
# Encode categorical columns
for col in categorical_cols:
if col in new_data:
new_data[col] = label_encoders_1b[col].transform(new_data[col])
# Feature engineering for date
new_data['PaymentDate_year'] = new_data['PaymentDate'].dt.year # type: ignore
new_data['PaymentDate_month'] = new_data['PaymentDate'].dt.month # type: ignore
new_data['PaymentDate_day'] = new_data['PaymentDate'].dt.day # type: ignore
new_data['PaymentDate_dayofweek'] = new_data['PaymentDate'].dt.dayofweek # type: ignore
new_data = new_data.drop(columns=datetime_columns)
# Define the expected feature order (based on the order used during training)
expected_features = [
'CustomerType',
'BranchSubCounty',
'ProductCategoryName',
'QuantityOrdered',
'PaymentDate_year',
'PaymentDate_month',
'PaymentDate_day',
'PaymentDate_dayofweek'
]
# Reorder and select only the expected columns
new_data = new_data[expected_features]
# Predict
prediction = decisiontree_regressor_optimum.predict(new_data)[0]
return jsonify({'Predicted Percentage Profit per Unit = ': float(prediction)})
# *1* Sample JSON POST values
# {
# "CustomerType": "Business",
# "BranchSubCounty": "Kilimani",
# "ProductCategoryName": "Meat-Based Dishes",
# "QuantityOrdered": 8,
# "PaymentDate": "2027-11-13"
# }
# *2.a.* Sample cURL POST values
# curl -X POST http://127.0.0.1:5000/api/v1/models/decision-tree-regressor/predictions \
# -H "Content-Type: application/json" \
# -d "{\"CustomerType\": \"Business\",
# \"BranchSubCounty\": \"Kilimani\",
# \"ProductCategoryName\": \"Meat-Based Dishes\",
# \"QuantityOrdered\": 8,
# \"PaymentDate\": \"2027-11-13\"}"
# *2.b.* Sample cURL POST values
# curl --insecure -X POST https://127.0.0.1/api/v1/models/decision-tree-regressor/predictions \
# -H "Content-Type: application/json" \
# -d "{\"CustomerType\": \"Business\",
# \"BranchSubCounty\": \"Kilimani\",
# \"ProductCategoryName\": \"Meat-Based Dishes\",
# \"QuantityOrdered\": 8,
# \"PaymentDate\": \"2027-11-13\"}"
# *3* Sample PowerShell values:
# $body = @{
# PaymentDate = "2027-11-13"
# CustomerType = "Business"
# BranchSubCounty = "Kilimani"
# ProductCategoryName = "Meat-Based Dishes"
# QuantityOrdered = 8
# } | ConvertTo-Json
# Invoke-RestMethod -Uri http://127.0.0.1:5000/api/v1/models/decision-tree-regressor/predictions `
# -Method POST `
# -Body $body `
# -ContentType "application/json"
@app.route('/api/v1/models/naive-bayes-classifier/predictions', methods=['POST'])
def predict_naive_bayes_classifier():
data = request.get_json()
new_data = pd.DataFrame([{
'monthly_fee': data.get('monthly_fee'),
'customer_age': data.get('customer_age'),
'support_calls': data.get('support_calls')
}])
expected_features = [
'monthly_fee',
'customer_age',
'support_calls'
]
new_data = new_data[expected_features]
prediction = naive_bayes_classifier.predict(new_data)[0]
return jsonify({'Predicted Class = ': int(prediction)})
# *1* Sample JSON POST values
# {
# "monthly_fee": 60,
# "customer_age": 30,
# "support_calls": 1
# }
@app.route('/api/v1/models/knn-classifier/predictions', methods=['POST'])
def predict_knn_classifier():
data = request.get_json()
new_data = pd.DataFrame([{
'monthly_fee': data.get('monthly_fee'),
'customer_age': data.get('customer_age'),
'support_calls': data.get('support_calls')
}])
expected_features = [
'monthly_fee',
'customer_age',
'support_calls'
]
new_data = new_data[expected_features]
# Scale the data before prediction (KNN requires scaling)
new_data_scaled = scaler_4.transform(new_data)
prediction = knn_classifier.predict(new_data_scaled)[0]
return jsonify({'Predicted Class = ': int(prediction)})
# *1* Sample JSON POST values
# {
# "monthly_fee": 60,
# "customer_age": 30,
# "support_calls": 1
# }
@app.route('/api/v1/models/svm-classifier/predictions', methods=['POST'])
def predict_svm_classifier():
data = request.get_json()
new_data = pd.DataFrame([{
'monthly_fee': data.get('monthly_fee'),
'customer_age': data.get('customer_age'),
'support_calls': data.get('support_calls')
}])
expected_features = [
'monthly_fee',
'customer_age',
'support_calls'
]
new_data = new_data[expected_features]
# Scale the data before prediction (SVM requires scaling)
new_data_scaled = scaler_4.transform(new_data)
prediction = svm_classifier.predict(new_data_scaled)[0]
return jsonify({'Predicted Class = ': int(prediction)})
# *1* Sample JSON POST values
# {
# "monthly_fee": 60,
# "customer_age": 30,
# "support_calls": 1
# }
@app.route('/api/v1/models/random-forest-classifier/predictions', methods=['POST'])
def predict_random_forest_classifier():
data = request.get_json()
new_data = pd.DataFrame([{
'monthly_fee': data.get('monthly_fee'),
'customer_age': data.get('customer_age'),
'support_calls': data.get('support_calls')
}])
expected_features = [
'monthly_fee',
'customer_age',
'support_calls'
]
new_data = new_data[expected_features]
prediction = random_forest_classifier.predict(new_data)[0]
return jsonify({'Predicted Class = ': int(prediction)})
# *1* Sample JSON POST values
# {
# "monthly_fee": 60,
# "customer_age": 30,
# "support_calls": 1
# }
@app.route('/api/v1/models/association-rules-recommender/recommendations', methods=['POST'])
def predict_association_rules_recommender():
data = request.get_json()
# Expected input: a product purchased
product = data.get('product')
# Since association rules require specific handling,
# this is a placeholder that returns a mock recommendation
# In a real scenario, you would load association rules and find products related to the input product
# For now, we'll return a simple structure
recommendations = {
'product_purchased': product,
'recommended_products': [
'Product A',
'Product B',
'Product C'
],
'confidence': 0.85
}
return jsonify(recommendations)
# *1* Sample JSON POST values
# {
# "product": "Bread"
# }
# (e.g., `python api.py`), and not if you import api.py from another script or test.
# __name__ is a special variable in Python. When you run a script directly,
# __name__ is set to '__main__'. If the script is imported, __name__ is set to
# the module's name.
# if __name__ == '__main__': checks if the script is being run directly.
# app.run(debug=True) starts the Flask development server with debugging enabled.
# This means:
## The server will automatically reload if you make code changes.
## You get detailed error messages in the browser if something goes wrong.
if __name__ == '__main__':
app.run(debug=True)
# if __name__ == '__main__':
# app.run(debug=False)
# if __name__ == "__main__":
# app.run(ssl_context=("cert.pem", "key.pem"), debug=True)