server.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. if data.empty:
  30. return(bad_request())
  31. else:
  32. #Load the saved model
  33. print("Loading the model...")
  34. loaded_model = None
  35. with open('./models/'+rgs,'rb') as f:
  36. loaded_model = pickle.load(f)
  37. print("The model has been loaded...doing predictions now...")
  38. predictions = loaded_model.predict(data)
  39. """Add the predictions as Series to a new pandas dataframe
  40. OR
  41. Depending on the use-case, the entire test data appended with the new files
  42. """
  43. prediction_series = list(pd.Series(predictions))
  44. final_predictions = pd.DataFrame({'pred_price': prediction_series}, index=forecast_datetime)
  45. """We can be as creative in sending the responses.
  46. But we need to send the response codes as well.
  47. """
  48. responses = jsonify(predictions=final_predictions.to_json(orient="index", date_format='iso'))
  49. responses.status_code = 200
  50. return (responses)
  51. @app.errorhandler(400)
  52. def bad_request(error=None):
  53. message = {
  54. 'status': 400,
  55. 'message': 'Bad Request: ' + request.url + '--> Please check your data payload...',
  56. }
  57. resp = jsonify(message)
  58. resp.status_code = 400
  59. return resp
  60. if __name__ == '__main__':
  61. app.run(host='0.0.0.0')