import json
import logging

import joblib
import pandas as pd
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

@app.route("/api/machinePrediction", methods=['GET'])
def home():
    incomingMachineId = request.args.get('machineId')
    modelPath = request.args.get('modelPath')
    column_names = request.args.get('columnNames')
    data_points = request.args.get('dataPoints')

    app.logger.info('Received machine id is %s', incomingMachineId)
    app.logger.info('Model path is %s', modelPath)

    json_object = json.loads(data_points)
    pairs = json_object.items()

    vitals_value = []
    for key, value in pairs:
      vitals_value.append(value)

    modelObj = joblib.load(modelPath)

    data = [vitals_value]
    df = pd.DataFrame(data=data, columns = column_names)

    modelPrediction = modelObj.predict(df)
    app.logger.info('Model prediction is: %s', modelPrediction)

    return jsonify(modelPrediction[0])

if __name__ == "__main__":
    app.run(debug=True)


# To start the server
# python3 app.py

[((9, 6, 9, 21), 'flask.Flask', 'Flask', ({(9, 12, 9, 20): '__name__'}, {}), '(__name__)', False, 'from flask import Flask, jsonify, request\n'), ((10, 0, 10, 9), 'flask_cors.CORS', 'CORS', ({(10, 5, 10, 8): 'app'}, {}), '(app)', False, 'from flask_cors import CORS, cross_origin\n'), ((14, 24, 14, 53), 'flask.request.args.get', 'request.args.get', ({(14, 41, 14, 52): '"""machineId"""'}, {}), "('machineId')", False, 'from flask import Flask, jsonify, request\n'), ((15, 16, 15, 45), 'flask.request.args.get', 'request.args.get', ({(15, 33, 15, 44): '"""modelPath"""'}, {}), "('modelPath')", False, 'from flask import Flask, jsonify, request\n'), ((16, 19, 16, 50), 'flask.request.args.get', 'request.args.get', ({(16, 36, 16, 49): '"""columnNames"""'}, {}), "('columnNames')", False, 'from flask import Flask, jsonify, request\n'), ((17, 18, 17, 48), 'flask.request.args.get', 'request.args.get', ({(17, 35, 17, 47): '"""dataPoints"""'}, {}), "('dataPoints')", False, 'from flask import Flask, jsonify, request\n'), ((22, 18, 22, 41), 'json.loads', 'json.loads', ({(22, 29, 22, 40): 'data_points'}, {}), '(data_points)', False, 'import json\n'), ((29, 15, 29, 37), 'joblib.load', 'joblib.load', ({(29, 27, 29, 36): 'modelPath'}, {}), '(modelPath)', False, 'import joblib\n'), ((32, 9, 32, 56), 'pandas.DataFrame', 'pd.DataFrame', (), '', True, 'import pandas as pd\n'), ((37, 11, 37, 38), 'flask.jsonify', 'jsonify', ({(37, 19, 37, 37): 'modelPrediction[0]'}, {}), '(modelPrediction[0])', False, 'from flask import Flask, jsonify, request\n')]