0

Code used to create the restful api webservice

import numpy as np
import pandas as pd
#need to "conda install flask" for this to work
from flask import Flask, abort, jsonify, request
import pickle

Text_classification_model = pickle.load(open(r"D:\Sentiment_Analysis_Project\Deb\Sentiment_Analysis\Linear_SVC_TEXT_CLASSI_Final_82per_Model.pkl", "rb"))

app = Flask(__name__)

#@app.route("/")
#def hello():
#    return "Hello"

@app.route("/")
def make_predict():
    #all kinds of error checking should go here
    data = request.get_json(force=True)
    #convert our json to a numpy array
    predict_request = data['Clean_Text_Body']
    predict_request = np.array[predict_request]

    #np.array goes in to Linear SVC model, prediction comes out
    y_hat = Text_classification_model.predict(predict_request)

    #return our prediction
    output = [y_hat[0]]
    return jsonify(results=output)

if __name__ == '__main__':
    app.run()

when this is being called as a .py file it is getting executed properly and displaying "http://localhost:5000/" as the url properly.

Later when i am trying to post a data in to the model using the following code,

import json
import requests

url = "http://localhost:8082/"
data = json.dumps({'Clean_Text_Body':"the product was amazing i just love it"})
headers = {'accept-language': 'en', 'content-type': 'application/json'}
r = requests.post(url, data = data, headers=headers)
Output = json.loads(r.text)['Output'] ##error section
# o/p is string eg: "4"
print("results == ", Output)

it is giving the following error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python\Anaconda\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Python\Anaconda\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python\Anaconda\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The model used is a Linear SVC model for sentiment classification which is trained on text which has two levels 'positive' and 'negative'

The model predicts whether the text/string has a positive or a negative sentiment.

Deb
  • 17
  • 1
  • 7
  • Try adding `methods=['GET', 'POST']` in the route decorator. I think you problem has nothing to do with your model and ML, the problem comes from flask. It is a common problem, see here : https://stackoverflow.com/search?q=Working+outside+of+request+context – Hugo May 16 '18 at 07:51
  • Possible duplicate of [RuntimeError: working outside of request context When request used in first line of method](https://stackoverflow.com/questions/36666128/runtimeerror-working-outside-of-request-context-when-request-used-in-first-line) – Hugo May 16 '18 at 07:53
  • `@app.route("/", methods=['GET','POST'])` , it is still giving the same error after adding methods in the route decorator. – Deb May 16 '18 at 08:02

1 Answers1

0

You are using the wrong request fonction !

You want to use this one : http://docs.python-requests.org/en/master/

not the flask request object! You don't need to use the from flask import Flask,request,jsonify in your second script !

You need to use import requests

and then requests.post()

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Hugo
  • 1,106
  • 15
  • 25
  • `import json import requests url = "http://localhost:5000/" data = json.dumps({'Clean_Text_Body':"The product was amazing, i just love it"}) headers = {'accept-language': 'en', 'content-type': 'application/json'} r = requests.post(url, data = data, headers=headers)` **I did the modification as mentioned above, while r is getting executed but when i print** `print("results == ", json.loads(r.text)['results'])` **it is giving the following error** `JSONDecodeError: Expecting value: line 1 column 1 (char 0)` @Hugo – Deb May 16 '18 at 09:52
  • This is another problem. Your first problem is **solved**. Try using a tool like Postman to check if you server is responding correctly. For this new error, you have plenty of help on SO, e.g. : https://stackoverflow.com/questions/16573332/jsondecodeerror-expecting-value-line-1-column-1-char-0 – Hugo May 16 '18 at 10:04
  • tried through postman as well as terminal. nothing works for this problem. – Deb May 17 '18 at 05:32