Build a Web-Based Mood Analyzer Using Azure Text Analytics API

OVERVIEW
In a previous blogpost I built a web-based tool to identify superheroes using Azure Custom Vision API and many people reached out and requested more blogs of the same kind, so, here it is!
In this blogpost I will dive with you into how you can deploy and consume the Azure Text Analytics API through your apps by building a simple app that accepts text, sends it to the API for processing and output detected language, key phrases, and sentiment.
This can be useful, for example, if you want to analyze the tone of a writer through an article to determine if the overall tone was negative or positive, or perhaps tweets related to a certain hashtag, and other endless possibilities.
Requirements
Demo
STEP 1
To start things up, visit portal.azure.com and sign-in with your Azure account.
STEP 2
Click on “Create Resource” then click “Text Analytics” from the “AI + Machine Learning” section.

STEP 3
Create a “Resource Group” by clicking “create new” then fill in the details and click “Create”.
STEP 4
Wait till it says “Your deployment is complete” then click “Go to resource”.

STEP 5
Go ahead and copy the “Key” and “Endpoint” from under the “Quickstart” section, as you are gonna need them in the next step.
STEP 6
It’s time to get our hands dirty by writing some code, but don’t worry as I will make it a piece of cake!
You first need to create a folder and call it anything, then create 3 files inside, 1 HTML and call it index.html, 1 CSS and call it style.css and 1 JS and call it script.js
We first need to write some HTML and give some of our elements some ids namely called (“myFile”, “input”, “results”, “language”, “keyPhrases”, and “sentiment”) so that we can pull and push data to the user interface later on using JavaScript (JS).
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Mood Analyzer: Text Analytics API</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="page">
<div class="container">
<h2>Mood Analyzer</h2>
<h4>Using Microsoft Azure Cognitive Services: Text Analytics API</h4>
<div class="form">
<input id="myFile" type="file"/>
<textarea id="input" placeholder="Write a phrase or insert an article here" /></textarea>
<button id="analyseButton">Analyze</button>
<div class="results">
<div class="result" >
<h4>Language: </h4>
<p id="language"></p>
</div>
<div class="result" >
<h4>Key Phrases: </h4>
<p id="keyPhrases"></p>
</div>
<div class="result" >
<h4>Sentiment: </h4>
<p id="sentiment"></p>
</div>
</div>
</div>
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
We then need to make our user interface look a little bit better, so we need to add some CSS.
@import url(https://fonts.googleapis.com/css?family=Raleway:300);
body {
background: #2A293E;
font-family: 'Raleway', sans-serif;
}
body h4 {
line-height: 1.4em;
}
.page {
font-family: 'Raleway', sans-serif;
margin: auto;
padding: 8% 0 0;
width: 600px;
}
.page .container {
background: #9E1030;
color: #BCBCBE;
border-radius: 5px;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.3), 0 5px 5px 0 rgba(0, 0, 0, 0.3);
margin: 20px 0;
max-width: 600px;
padding: 45px;
position: relative;
text-align: center;
z-index: 1;
}
.page .container input {
background: #ffffff;
border: 0;
border-radius: 5px;
box-sizing: border-box;
font-size: 14px;
margin: 0 0 15px;
outline: 0;
padding: 15px;
width: 100%;
}
.page .container button {
background: #006E51;
border: 0;
border-radius: 5px;
color: #EADEDB;
cursor: pointer;
font-size: 14px;
outline: 0;
padding: 15px;
text-transform: uppercase;
transition: all 0.4 ease;
width: 100%;
}
.page .container button:hover {
background: #BCBCBE;
color: #2A293E;
}
.page .container.results {
display: none;
text-align: left;
}
.page .container.results #displayImage,
.page .container.results #response {
width: 100%;
}
.page .container.results #response {
text-align: left;
}
textarea {
border-radius: 5px;
padding: 5px;
height: 30vh;
width: 97.5%;
}
.results {
text-align: left;
}
br {
display: none;
}
p {
color: gray;
}
The most important part is the JavaScript code as it controls everything within our tool from pulling and pushing data to the user interface to sending and receiving from the API.
document.getElementById("analyseButton").addEventListener("click", analyze);
function analyze() {
keyPhrases();
language();
sentiment();
}
function language() {
var reqBody = {
documents: [{
language: "en",
id: 1,
text: document.getElementById("input").value
}]
};
var myHeader = new Headers({
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": "ACCESS_KEY"
});
var initObject = {
method: "POST",
body: JSON.stringify(reqBody),
headers: myHeader
};
var request = new Request("https://testtextanal.cognitiveservices.azure.com/text/analytics/v2.1/languages?",
initObject
);
fetch(request)
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(new Error(response.statusText));
}
})
.then(function (response) {
document.getElementById("language").innerHTML =
"<h5>" + response.documents[0].detectedLanguages[0].name + "</h5>";
})
.catch(function (err) {
alert(err);
document.getElementById("output").innerHTML = "";
});
}
function keyPhrases() {
var reqBody = {
documents: [{
language: "en",
id: 1,
text: document.getElementById("input").value
}]
};
var myHeader = new Headers({
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": "ACCESS_KEY"
});
var initObject = {
method: "POST",
body: JSON.stringify(reqBody),
headers: myHeader
};
var request = new Request("https://testtextanal.cognitiveservices.azure.com/text/analytics/v2.1/keyPhrases",
initObject
);
fetch(request)
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(new Error(response.statusText));
}
})
.then(function (response) {
document.getElementById("keyPhrases").innerHTML =
"<h5>" +
response.documents[0].keyPhrases.length +
"</h5>" +
"</br>" +
response.documents[0].keyPhrases;
})
.catch(function (err) {
alert(err);
document.getElementById("output").innerHTML = "";
});
}
function sentiment() {
var reqBody = {
documents: [{
language: "en",
id: 1,
text: document.getElementById("input").value
}]
};
var myHeader = new Headers({
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": "ACCESS_KEY"
});
var initObject = {
method: "POST",
body: JSON.stringify(reqBody),
headers: myHeader
};
var request = new Request("https://testtextanal.cognitiveservices.azure.com/text/analytics/v2.1/sentiment?",
initObject
);
fetch(request)
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(new Error(response.statusText));
}
})
.then(function (response) {
var sentiment = response.documents[0].score;
document.getElementById("sentiment").innerHTML =
"<h5>" +
sentiment +
"</h5>"
})
.catch(function (err) {
alert(err);
document.getElementById("sentiment").innerHTML = "Error";
});
}
var input = document.getElementById("myFile");
var output = document.getElementById("input");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
You need to make sure the endpoints you are using in the JavaScript code are right, and to replace all the “ACCESS_KEY” with your own “key” as per those you copied in the previous step from the Azure portal!
STEP 7
It’s time to test our very own web-based tool and make sure it’s working, right?
I will go ahead and choose a text file including a quote by Tony Stark aka Iron Man replying to Steve Rogers aka Captain America saying “Genius, billionaire, playboy, philanthropist.” in The Avengers (2012).
We finally got a solution working like a charm that leverages 3 services (Detect Language, Key Phrases and Sentiment) all through one web-based tool!
Resources
If you want to go above and beyond, here are some resources to help you out!
Summary
I went from deploying a resource instance of the Text Analytics API to going live with web-based A.I. tool in just a few minutes, and I can’t stop thinking about what else could be built using such a service.
Imagine how this could be used for example in fields such as academics to analyze researches or even by companies in the world of social media to classify user behavior, and what not.
Thanks! 😄