| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import os
- import pandas as pd
- import pickle
- from flask import Flask, jsonify, request
- from .utils import PreProcessing
- app = Flask(__name__)
- @app.route('/')
- def index():
- """ Index Web Page
- """
- return "Modelo Mexico PML Day Ahead Forecast"
- @app.route('/predict', methods=['POST'])
- def apicall():
- """API Call
-
- Pandas dataframe (sent as a payload) from API Call
- """
- prepro = PreProcessing()
- print(request)
- try:
- data_json = request.get_json()
- data = pd.read_json(data_json, orient='index')
- data = prepro.process(data)
- data = data[data.index.date == data.index.max().date()].drop('P', axis=1)
- #Getting the datetime into separated out
- forecast_datetime = data.index
- except Exception as e:
- raise e
-
- rgs = 'lbrprice_model_svr.pkl'
-
- if data.empty:
- return(bad_request())
- else:
- #Load the saved model
- print("Loading the model...")
- loaded_model = None
- with open('./models/'+rgs,'rb') as f:
- loaded_model = pickle.load(f)
- print("The model has been loaded...doing predictions now...")
- predictions = loaded_model.predict(data)
-
- """Add the predictions as Series to a new pandas dataframe
- OR
- Depending on the use-case, the entire test data appended with the new files
- """
- prediction_series = list(pd.Series(predictions))
- final_predictions = pd.DataFrame({'pred_price': prediction_series}, index=forecast_datetime)
-
- """We can be as creative in sending the responses.
- But we need to send the response codes as well.
- """
- responses = jsonify(predictions=final_predictions.to_json(orient="index", date_format='iso'))
- responses.status_code = 200
- return (responses)
- @app.errorhandler(400)
- def bad_request(error=None):
- message = {
- 'status': 400,
- 'message': 'Bad Request: ' + request.url + '--> Please check your data payload...',
- }
- resp = jsonify(message)
- resp.status_code = 400
- return resp
- if __name__ == '__main__':
- app.run(host='0.0.0.0')
|