server.py 2.1 KB

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