server.py 2.0 KB

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