Flair delivers state-of-the-art performance in solving NLP problems such as named entity recognition (NER), part-of-speech tagging (PoS), sense disambiguation and text classification. It’s an NLP framework built on top of PyTorch.
In this post, I will cover how to build sentiment analysis Microservice with flair and flask framework.
Step 1: Create Python 3.6 virtualenv
To use Flair you need Python 3.6. We will start by creating a Python 3.6 virtualenv
$ python3.6 -m venv pyeth
Next, we activate the virtualenv
$ source pyeth/bin/activate
Next, you can check Python version
(pyeth) $ python --version
Python 3.6.1
Step 2: Install flair and flask package
To install Flair and Flask we will use pip as shown below
$ pip install flair flask
The above command will install all the required packages needed to build our Microservice. It will also install PyTorch which flair uses to do the heavy lifting.
Step 3: Create a REST API to analyse sentiments
Create a new file called app.py under the application directory.
$ touch app.py
Copy the following source code and paste it in app.py
source file
from flask import abort, Flask, jsonify, request from flair.models import TextClassifier from flair.data import Sentence app = Flask(__name__) classifier = TextClassifier.load('en-sentiment') @app.route('/api/v1/analyzeSentiment', methods=['POST']) def analyzeSentiment(): if not request.json or not 'message' in request.json: abort(400) message = request.json['message'] sentence = Sentence(message) classifier.predict(sentence) print('Sentence sentiment: ', sentence.labels) label = sentence.labels[0] response = {'result': label.value, 'polarity':label.score} return jsonify(response), 200 if __name__ == "__main__": app.run()
The code shown above does the following:
- It imports Flask classes and functions
- Next, we import
TextClassifier
andSentence
classes fromflair
package - Next, we load the model related to sentiment analysis
en-sentiment
. The sentiment analysis model is based on IMDB dataset. When line 7 runs, it will download the sentiment analysis model and store it into the.flair
subfolder of the home directory. This will take few minutes depending on your internet speed. - Next, we defined a POST route mapping to
/api/v1/analyzeSentiment
url. This API endpoint will receive the message in a JSON body. We created an instance of Sentence and and passed it to classifier predict method. The result is in the form of label object that has two fields – value and score.
You can now start the app using python app.py
Once application is started, you can test the REST API using on your favourite REST client. I will show how to make REST API using cURL.
We will first check a positive review I could watch The Marriage over and over again. At 90 minutes, it's just so delightfully heartbreaking
curl --request POST \ --url http://localhost:5000/api/v1/analyzeSentiment \ --header 'content-type: application/json' \ --data '{ "message":"I could watch The Marriage over and over again. At 90 minutes, it'\''s just so delightfully heartbreaking." }'
The response returned by API
{
"polarity": 1.0,
"result": "POSITIVE"
}
Let’s now look at an example of negative sentence Inoffensive and unremarkable
curl --request POST \ --url http://localhost:5000/api/v1/analyzeSentiment \ --header 'content-type: application/json' \ --data '{ "message":"Inoffensive and unremarkable." }'
The response returned by API
{
"polarity": 1.0,
"result": "NEGATIVE"
}
Finally, let’s look at mixed review I don't think Destroyer is a good movie, but it is never boring and often hilarious.
curl --request POST \ --url http://localhost:5000/api/v1/analyzeSentiment \ --header 'content-type: application/json' \ --data '{ "message":"I don'\''t think Destroyer is a good movie, but it is never boring and often hilarious." }'
The response returned by API
{ "polarity": 0.11292144656181335, "result": "NEGATIVE" }
That’s it for today.