server.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os
  2. import pandas as pd
  3. import dill as pickle
  4. from flask import Flask, jsonify, request
  5. from utils import PreProcessing
  6. app = Flask(__name__)
  7. @app.route('/predict', methods=['POST'])
  8. def apicall():
  9. """API Call
  10. Pandas dataframe (sent as a payload) from API Call
  11. """
  12. try:
  13. test_json = request.get_json()
  14. test = pd.read_json(test_json, orient='records')
  15. #To resolve the issue of TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'
  16. test['Dependents'] = [str(x) for x in list(test['Dependents'])]
  17. #Getting the Loan_IDs separated out
  18. loan_ids = test['Loan_ID']
  19. except Exception as e:
  20. raise e
  21. clf = 'model_v1.pk'
  22. if test.empty:
  23. return(bad_request())
  24. else:
  25. #Load the saved model
  26. print("Loading the model...")
  27. loaded_model = None
  28. with open('./models/'+clf,'rb') as f:
  29. loaded_model = pickle.load(f)
  30. print("The model has been loaded...doing predictions now...")
  31. predictions = loaded_model.predict(test)
  32. """Add the predictions as Series to a new pandas dataframe
  33. OR
  34. Depending on the use-case, the entire test data appended with the new files
  35. """
  36. prediction_series = list(pd.Series(predictions))
  37. final_predictions = pd.DataFrame(list(zip(loan_ids, prediction_series)))
  38. """We can be as creative in sending the responses.
  39. But we need to send the response codes as well.
  40. """
  41. responses = jsonify(predictions=final_predictions.to_json(orient="records"))
  42. responses.status_code = 200
  43. return (responses)
  44. @app.errorhandler(400)
  45. def bad_request(error=None):
  46. message = {
  47. 'status': 400,
  48. 'message': 'Bad Request: ' + request.url + '--> Please check your data payload...',
  49. }
  50. resp = jsonify(message)
  51. resp.status_code = 400
  52. return resp