server.py 2.4 KB

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