Implement Serverless Text Sentiment Analysis using Azure Text Analysis API
Tags: cognitiveservices, javascript, serverless, azure
Published: 2019-12-10 13:52:11

As part of the [day 5](https://25daysofserverless.com/calendar/5) task for the Microsoft Azure [#25daysofserverless](https://twitter.com/search?q=%2325DaysOfServerless) challenge on twitter, I implemented language and sentiment analysis using Azure Text Analytics API. 

For the task, you are expected to determine if a child has been nice or naughty based on messages sent to Santa. Of course, these are children from different parts of the world hence different countries. In this article, you will learn "how to implement text sentiment analysis" using "Azure Text Analytics". 

We would be using:
- Nodejs
- Visual Studio Code
- Azure Functions
- Azure Text Analytics
- Postman for testing
- Axios for https requests

First, we need to create a serverless function using Azure. For more details on how to do this using VSCode, visit [this link](https://docs.microsoft.com/en-gb/azure/azure-functions/functions-create-first-function-vs-code?WT.mc_id=25daysofserverless-github-cxa). 

Next, we obtain our configuration keys from the Azure portal. The keys are required to access the Text Analytics API. To get this key, you can:

Create a cognitive service resource: analytics through the Azure portal.
![Cognitve service dashboard](https://lh3.googleusercontent.com/3cfb7MDWqnWpQrd48ygFX14S2MDwDoJ8sLthGGg8tskfQF5lFia-IhPlil64E7zhydUPcEckKoqJGsen_zhpCBXrQKKgYvZjhpvmWCCMxzWKgpgdC6KJSxrCf7DC6qagcNCwUx-v)

or follow [this link](https://azure.microsoft.com/en-gb/try/cognitive-services/#lang) to cognitive services and generate your trial key valid for 7 days.

Then add these keys to your env file or configuration file. 

![config file](https://lh3.googleusercontent.com/7HGIVo8t-JZVToEvju5Ivg3Y84voahgHQlQnq_wN4YmaoVbrvfomziZX2rP0wz6iXlYObsO6edYflVD1bbIMZ0xD7IhVUM3TsEaR_MSLvW1FAcuuVX2wNbbBDdMULLNd8-ZHdbTp)

Now that we are done with the setup, we will proceed to create the functions that will handle the analysis. They are divided into two:
- Determine the language
- Determine the sentiment

To store this functions, I created a different file named congnitives.js so as to abstract these functions from my main code. 

First, I ensure that I have the proper keys to hit my api endpoint. If the key is missing, an error is thrown and we assign the path for fetching languages and sentiments from the API. {% gist https://gist.github.com/Je-ni/ea839e647f7f873b9920d279c946cd4c %}

I created an asynchronous function get_language that takes in an object with a property 'documents' that holds the text to be analysed in JSON format as a parameter.
{% gist https://gist.github.com/Je-ni/bfd22b2bbacf28102c6c1c85721b7383 %}

Then specified the endpoint to be used for the request. Next, I set the headers with content-type and my subscription key.

NB: Ensure that the content-type set is of JSON format as that is what the text analytics API accepts.

Then, using axios, I await my post request to the URL, specifying the text as the body and then set the headers. 

Subsequently, I create another asynchronous function that analyses a given document and provides the sentiment. the sentiment score ranges from 0 to 1 with numbers closer to 1 being positive while the ones closer to zero are negative. Then I export the two functions.

## Implementation

{% gist https://gist.github.com/Je-ni/0aad7cdbe0b1caa33b14c6f3e630786f %}

I import the two functions I had created in cognitives.js using object destructuring. 

I fetch the list of messages to be analyzed, in my case, using a URL which returned them as an array of objects.
Then I looped through the array to obtain the particular data needed for the language analysis and stored them in the format shown below:
Next, I call the get_language function, which I await because the result is needed for further processing. A successful response is returned in JSON, as shown in the following example: 

![get_language response](https://lh6.googleusercontent.com/nXnawqUi1XcDWqGQWH-sQvybFE7y7t09qHuHWN68kp-5bPGUPfiG0q9W9OqhhqHwUcRf1q3muYYWyfxi2Ml2pSgIJC8UrtdXa3kCodFD)

I proceed to do store the data in the format required for sentiment analysis, call the get_sentiment function and expect a response as shown:
![get_sentiment response](https://lh4.googleusercontent.com/dSwHf8Ladwcdk9Fgf10tczIygh4_zqweN5ICxzm7syhRPlrDOY5fojwkp8J4qNgPML_6hxRdkGbyHMDh9G44Ht7WO1rEWKn6iwdT03U)

After sentiment analysis, using the results, I can now classify the letters and kids as naughty or nice. Sentiment is positive if closer to 1 and negative if close to 0. Hence if score is greater than or equal to 0.5, it is classified as nice. Otherwise, it will be classified as naughty.
.
This I send back to Santa🎅 and Santa is happy 🤩🤩.

If you have any questions or comments, feel free. Don't forget to leave thumbs up if you found the article helpful.

Follow me on Twitter [@dera_jo](https://twitter.com/dera_jo)