Skip to content

Instantly share code, notes, and snippets.

@deepak-karkala
Created December 28, 2020 14:32
Show Gist options
  • Select an option

  • Save deepak-karkala/cc0a89aae96b934e192fb4db81f698cf to your computer and use it in GitHub Desktop.

Select an option

Save deepak-karkala/cc0a89aae96b934e192fb4db81f698cf to your computer and use it in GitHub Desktop.

Revisions

  1. deepak-karkala created this gist Dec 28, 2020.
    39 changes: 39 additions & 0 deletions flask_restapi_predict.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    # REST API Service to get Price Predictions for Airbnb listings
    @app.route("/predict", methods=["POST"])
    def predict():

    # initialize the data dictionary that will be returned from the view
    data = {"success": False}

    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
    data["predictions"] = []

    parser = reqparse.RequestParser()
    parser.add_argument('country', type=str, help='Country')
    parser.add_argument('city', type=str, help='City')
    parser.add_argument('neighbourhood', type=str, help='Neighbourhood')
    parser.add_argument('roomtype', type=str, help='Room type')
    args = parser.parse_args()

    # Create input to Model from form data
    df_input = pd.DataFrame([[country, city, neighbourhood, propertytype, roomtype, bedtype,
    cancellationpolicy, hostresponsetime, accommodates, num_bedrooms, num_beds,
    min_nights, availability_30, availability_60, availability_90, availability_365,
    num_reviews, reviews_per_month, review_scores_rating, review_scores_accuracy,
    review_scores_cleanliness, review_scores_checkin, review_scores_communication,
    review_scores_location, review_scores_value, host_response_rate,
    ]], dtype=float)

    # Inference: Get prediction from Model
    prediction_price = model.predict(df_input)[0]
    prediction_price = round(prediction_price)

    # Add prediction results to JSON data
    r = {"prediction_price": prediction_price, "features": features}
    data["predictions"].append(r)
    # indicate that the request was a success
    data["success"] = True

    # return the data dictionary as a JSON response
    return flask.jsonify(data)