server.py 2.0 KB

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