Build your emotion detection MicroSaaS

Meiyappan Kannappa
7 min readJun 3, 2023

Software as a Service (SaaS) is a software distribution model in which applications are hosted by a vendor or service provider and made available to customers over the Internet. It offers businesses an alternative to traditional on-premise software solutions, allowing them to access applications without having to install and manage them on their own servers. MailChimp is a great SaaS example email marketing service provider.

Vertical SaaS

Vertical SaaS is a type of SaaS solution that focuses on solving a specific problem for a particular industry or vertical market. These solutions are designed to meet the unique needs and requirements of a specific industry, such as healthcare, finance, or education.

An example of a Vertical SaaS product is the Google Cloud Healthcare API. This API is designed specifically for the healthcare industry and provides a range of features for managing electronic health records (EHRs), medical images, and other healthcare-related data.

Horizontal SaaS

Horizontal SaaS is a type of SaaS solution that provides a broad range of features and functionality that can be used by businesses in different industries. These solutions are designed to be flexible and adaptable to meet the needs of a wide range of businesses. Horizontal SaaS products tend to be more generic and less specialized than Vertical SaaS products.

An example of a Horizontal SaaS product is the Salesforce Platform. The API Marketplace provides a range of services that can be used by businesses in different industries to integrate with their applications. These Services include billing & invoicing, lead management, and data analytics. The Salesforce platform is a great example of a Horizontal SaaS product that provides a range of features and functionality that can be used by businesses in different industries.

MicroSaaS

Micro SaaS refers to a small-scale Software as a Service (SaaS) business that offers a specialised solution or tool to a specific niche or target market. Unlike traditional SaaS companies that provide comprehensive software platforms, Micro SaaS focuses on solving a specific problem or catering to a specific need of a smaller audience.

A great example of MicroSaaS is Stripe. Stripe is a payment processing platform that offers a suite of APIs for developers to integrate secure and seamless payment functionality into their applications, websites, or online platforms.

What we will do in this blog?

In this article, we will build an API-based MicroSaaS which will detect the emotion in a given sentence or paragraph. This API will be published in an API Market place like RapidAPI.

Emotion detection is an automated process, powered by machine learning, that identifies and extracts sentiment from data. This data may be from text, audio, or video feeds from any kind of digital source.

Companies need to detect emotion in text because it sets the foundation for many critical business functions. These include:

1. Quality Control

2. Build brand perception

3. Sustainable growth

4. Understanding target audiences better

5. Find patterns in customer motivations

6. Market positioning

7. Finding new opportunities

8. Personalized marketing

9. Effective advertising campaigns

10. Build customer loyalty

Before we understand how to recognise emotion in a text, we need to know what is NLP (Natural Language Processing)

Natural Language Processing (NLP) is a field of AI focused on enabling computers to understand and interact with human language. It involves tasks like text classification, sentiment analysis, machine translation, and chatbots. NLP uses algorithms and techniques to analyse linguistic features, allowing computers to process, interpret, and generate meaningful text-based information.

How to detect emotions from the text?

Emotion detection in text involves using Natural Language Processing (NLP) techniques to analyse and understand the emotional content expressed in written text. Here’s a simplified overview of how it works:

  1. Text Preprocessing: The text is cleaned by removing punctuation, converting it to lowercase, and removing any irrelevant or noisy information.
  2. Feature Extraction: Relevant features are extracted from the text, such as words, phrases, or contextual information, that can provide insights into the emotional content.
  3. Sentiment Analysis: Various approaches can be used, including rule-based methods, machine learning models, or deep learning models, to classify the sentiment of the text such as positive, negative, or neutral.
  4. Emotion Classification: The sentiment analysis output can be further mapped to specific emotions such as joy, sadness, anger, fear, or surprise. This step often involves using pre-defined emotion lexicons or training emotion-specific models.
  5. Contextual Understanding: The context of the text is taken into account, as emotions can be influenced by the surrounding context and linguistic cues.
  6. Evaluation and Fine-tuning: The performance of the emotion detection model is evaluated and refined using labelled datasets or user feedback to improve accuracy and capture subtle nuances of emotions.

We will be using Stanford-nlp to detect emotions in the given text and expose it as API using Spring Boot.

Stanford-Core NLP

CoreNLP natural language processing library in Java! CoreNLP enables users to derive linguistic annotations for text, including token and sentence boundaries, parts of speech, named entities, numeric and time values, dependency and constituency parses, coreference, sentiment, quote attributions, and relations. CoreNLP currently supports 8 languages: Arabic, Chinese, English, French, German, Hungarian, Italian, and Spanish.

The centrepiece of CoreNLP is the pipeline. Pipelines take in raw text, run a series of NLP annotators on the text, and produce a final set of annotations.

https://stanfordnlp.github.io/CoreNLP/index.html
  1. Tokenize: Tokenize means breaking a text into smaller units, such as words or punctuation marks. It helps in dividing the text into manageable parts for analysis.
  2. Ssplit: Ssplit refers to splitting a text into separate sentences. This helps in treating each sentence as a separate unit for analysis.
  3. POS: POS (Part-of-Speech) involves labelling each word with its grammatical category, like noun, verb, adjective, or adverb. It helps in understanding the role of each word in a sentence.
  4. Lemma: Lemma means finding the base or dictionary form of a word. It helps in simplifying words to their standard form, like reducing “running” to “run.”
  5. NER: NER (Named Entity Recognition) involves identifying and classifying named entities, such as names of people, organizations, or locations, in a text.
  6. Depparse: Depparse (Dependency Parsing) means analyzing the grammatical structure of a sentence by understanding the relationships between words and their dependencies.

Lets start creating a spring boot app using https://start.spring.io/ with spring web dependency and other dependencies as needed.

Now add Stanford-nlp dependencies in build.gradle

Time to create a bean and controller.

@Bean
public StanfordCoreNLP stanfordCoreNLP(){
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, parse, sentiment");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
return pipeline;
}
@Autowired
StanfordCoreNLP pipeline;

@PostMapping(path = "detectemotion",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONArray> create(@RequestBody JSONObject data) {
JSONArray array = new JSONArray();
try {
String text = data.get("text").toString();
int sentimentInt;
String sentimentName;

Annotation annotation = pipeline.process(text);
for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
sentimentInt = RNNCoreAnnotations.getPredictedClass(tree);
sentimentName = sentence.get(SentimentCoreAnnotations.SentimentClass.class);
System.out.println(sentimentName + "\t" + sentimentInt + "\t" + sentence);
JSONObject object = new JSONObject();
object.put("sentence",sentence.toString());
object.put("sentimentName",sentimentName.toString());
array.add(object);
}
}catch(Exception e){
e.printStackTrace();
JSONObject object = new JSONObject();
object.put("error","Unable to detect emotion");
array.add(object);
}
return new ResponseEntity<>(array, HttpStatus.ACCEPTED);

}

We will deploy this application in GCP Cloud Run, to expose it via API Marketplace. Dockerfile needs to be created to build it as a Docker image and push it to the container registry or artefact registry.

FROM openjdk:17
EXPOSE 8080
RUN mkdir -p /app/
ADD build/libs/nlpdetect-0.0.1-SNAPSHOT.jar /app/nlpdetect-0.0.1-SNAPSHOT.jar
ENTRYPOINT ["java", "-jar", "/app/nlpdetect-0.0.1-SNAPSHOT.jar"]

Build the docker image and push in to GCP registry using. Ensure to login to GCP using the CLI

 gcloud builds submit --tag gcr.io/<GCP_PROJECT_NAME>/<APP_NAME>:v0.1 .

All set, The built image will be deployed in cloud run. Refer here on the complete steps to build and deploy the application in cloud RUN. Be sure to enable “Allow unauthenticated invocations” while creating service in Cloud Run.

Once the application is deployed in Cloud Run, it will generate an URL.

Expose your API in Rapid API

RapidAPI is an API marketplace that helps developers find and connect directly to the world’s top APIs.

It allows API Providers to distribute and monetize their API, I find this to be a conducive approach for API Based MicroSaaS. Perhaps it also allows and is available by default to test the API functionally and monitor the same.

Login to RapidAPI Studio to publish our API and make it available for consumption. Create a new API project and select to import your API Postman collection.

After project creation, the potman API will be added to the requests section

Go to the Hub Listing page on the left side, Provide the logo and additional description. Finally, save it, our API MicroSaaS is now listed and below is the URL

https://rapidapi.com/MeiyappanKannappa/api/nlp-microsaas

Source code available here https://github.com/MeiyappanKannappa/emotion-detection

Enjoy publishing your API!!!!!

--

--

Meiyappan Kannappa

Technical enthusiast, daydreamer. Design of involute software architecture for digital transformation, sustainability and cost optimization.