server.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import os
  2. import pandas as pd
  3. import 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. prepro = PreProcessing()
  13. print(request)
  14. try:
  15. data_json = request.get_json()
  16. data = pd.read_json(data_json, orient='index')
  17. data = prepro.process(data)
  18. data = data[data.index.date == data.index.max().date()].drop('P', axis=1)
  19. #Getting the datetime into separated out
  20. forecast_datetime = data.index
  21. except Exception as e:
  22. raise e
  23. rgs = 'lbrprice_model_svr.pkl'
  24. if data.empty:
  25. return(bad_request())
  26. else:
  27. #Load the saved model
  28. print("Loading the model...")
  29. loaded_model = None
  30. with open('./models/'+rgs,'rb') as f:
  31. loaded_model = pickle.load(f)
  32. print("The model has been loaded...doing predictions now...")
  33. predictions = loaded_model.predict(data)
  34. """Add the predictions as Series to a new pandas dataframe
  35. OR
  36. Depending on the use-case, the entire test data appended with the new files
  37. """
  38. prediction_series = list(pd.Series(predictions))
  39. final_predictions = pd.DataFrame({'pred_price': prediction_series}, index=forecast_datetime)
  40. """We can be as creative in sending the responses.
  41. But we need to send the response codes as well.
  42. """
  43. responses = jsonify(predictions=final_predictions.to_json(orient="index", date_format='iso'))
  44. responses.status_code = 200
  45. return (responses)
  46. @app.errorhandler(400)
  47. def bad_request(error=None):
  48. message = {
  49. 'status': 400,
  50. 'message': 'Bad Request: ' + request.url + '--> Please check your data payload...',
  51. }
  52. resp = jsonify(message)
  53. resp.status_code = 400
  54. return resp
  55. if __name__ == '__main__':
  56. app.run()