Sentiment Analysis Web App with Python

In this tutorial, I’ll show you how to build a sentiment analysis web app with Python, Streamlit, and Hugging Face Transformers.

Sentiment analysis is the process of determining the emotional tone behind a text document, which can be helpful in several applications, like customer service, brand monitoring, and product reviews.

What is Streamlit?

Streamlit is a fun and exciting Python library that helps you build beautiful and interactive web apps for your data science projects.

With Streamlit, you can create engaging data visualizations, share your work with others, and get immediate feedback on your analysis.

Streamlit makes web app development easy and accessible to everyone, even if you don’t have a lot of experience with web development.

You can build a powerful app with just a few lines of code, and the library takes care of all the heavy lifting for you, from rendering your UI to deploying your app to the cloud.

I have also written a dedicated tutorial on building an image classifier web app using Streamlit.

What is Hugging Face Transformers?

Hugging Face Transformers is an open-source library that provides easy access to pre-trained state-of-the-art natural language processing (NLP) models.

These models are trained on large amounts of data and can be fine-tuned to perform a wide range of NLP tasks, such as sentiment analysis, text classification, and question answering.

With Hugging Face Transformers, developers and researchers can quickly and easily incorporate powerful NLP capabilities into their projects without needing to train their own models from scratch.

The library supports a wide range of languages and model architectures, making it a versatile tool for NLP tasks.

Tools and Technologies

Before we begin to build the sentiment analysis web app with Python, let’s take a quick look at the tools and technologies we’ll be using:

  • Python: A popular programming language that’s widely used for machine learning and web development.
  • Streamlit: An open-source Python library for building interactive web apps.
  • Hugging Face Transformers: A Python library for natural language processing that provides access to pre-trained transformer models.
  • PyTorch: Hugging Face is a PyTorch-based library, and therefore PyTorch needs to be installed to use it

Goal of the Tutorial

Our goal is to create a user-friendly sentiment analysis web app with Python that takes in text input and predicts the sentiment label (positive, neutral, or negative) and score.

We’ll be using the Twitter-RoBERTa-Base sentiment analysis model from Hugging Face Transformers, which is pre-trained on a large corpus of Twitter data.

Now that we have a clear idea of what we’ll be building and what tools we’ll be using, let’s move on to setting up our environment.

Setting up the Environment

Before we start building our sentiment analysis web app with Python, we need to set up our environment with the necessary tools and packages.

Here are the steps you need to follow:

1. Install Python

First, you need to install Python on your system. You can download the latest version of Python from the official website: https://www.python.org/downloads/

2. Install Streamlit

Once you have installed Python, you can use pip (Python’s package manager) to install Streamlit.

Open a terminal or command prompt and run the following command:

pip install streamlit

3. Install Hugging Face Transformers

We also need to install the Hugging Face Transformers library, which provides access to pre-trained transformer models for natural language processing.

You can install it using pip:

pip install transformers

4. Load the Model and Tokenizer

Now that we have all the necessary tools and packages installed, we can load the sentiment analysis model and tokenizer from Hugging Face Transformers.

Here’s the code:

import streamlit as st
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# Load the sentiment analysis model and tokenizer
model_name = "cardiffnlp/twitter-roberta-base-sentiment"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

This code imports the necessary libraries and loads a pre-trained sentiment analysis model and tokenizer from the Hugging Face Transformers library.

Specifically, the AutoTokenizer and AutoModelForSequenceClassification classes are used to automatically download and load a pre-trained model specified by the model_name variable, which in this case is set to "cardiffnlp/twitter-roberta-base-sentiment".

Once the tokenizer and model are loaded, they can be used to analyze sentiment in text inputs.

So now, we’re ready to start building our sentiment analysis web app using Python!

Building the Sentiment Analysis Web App using Python

Now that we have set up our environment and loaded the necessary tools and packages, we can start building our sentiment analyzer web app.

We will be using Streamlit, a Python library that allows us to create interactive web applications with ease.

1. Write the Title of the App

Let’s give our app a title:

st.title('Sentiment Analyzer')

This line of code sets the title of our web app to “Sentiment Analyzer”.

2. Get User Input

Next, we need to get input from the user. We will use a text input widget provided by Streamlit to allow the user to enter a sentence or paragraph to analyze:

input_text = st.text_input('Enter a sentence or paragraph to analyze:')

This code creates a text input widget and assigns it to the input_text variable.

3. Trigger Sentiment Analysis

We will add a button to our web app that the user can click to trigger the sentiment analysis. We will use another widget provided by Streamlit called a button:

if st.button('Analyze'):

To see how our app is looking so far, you can run the app by typing the following command in the terminal after saving the Python file.

streamlit run app.py

You can replace app.py with the name of your Python file.

After adding the title, input field, and button the app should look like this:

Sentiment analysis with Python web app interface

Now that we have built the user interface of the app, let’s make it functional.

4. Perform Sentiment Analysis

We will perform the sentiment analysis when the user clicks the “Analyze” button. We will encode the user’s input using the tokenizer and pass it to the model for prediction:

if st.button('Analyze'):
    # Encode the input text and pass it to the model for prediction
    encoded_input = tokenizer(input_text,
                              padding=True,
                              truncation=True,
                              return_tensors='pt')
    output = model(**encoded_input)

This code encodes the user’s input using the tokenizer, pads the input to the maximum length supported by the model, truncates the input if it is longer than the maximum length, and returns the input as PyTorch tensors.

We then pass the encoded input to the model for prediction and store the output in the output variable.

5. Display Results

Finally, we will display the sentiment analysis results to the user. We will get the predicted label and score from the output of the model and display them along with the predicted label and scores for all three sentiments:

# Add a button to trigger the sentiment analysis
if st.button('Analyze'):
    # Encode the input text and pass it to the model for prediction
    encoded_input = tokenizer(input_text,
                              padding=True,
                              truncation=True,
                              return_tensors='pt')
                              
    output = model(**encoded_input)

    # Get the predicted label and score
    scores = output.logits.detach().numpy()[0]
    labels = ['Negative', 'Neutral', 'Positive']
    label_index = scores.argmax()
    label = labels[label_index]
    score = scores[label_index]


    if label == 'Positive':
        color = 'green'
    elif label == 'Neutral':
        color = 'yellow'
    elif label == 'Negative':
        color = 'red'

    st.markdown(f'<h4>Predicted Sentiment: <span style="color: {color};">{label}</span></h4>', unsafe_allow_html=True)
    
    st.write(f'Predicted Score: {score}')

    # Display the predicted label and scores for all three sentiments
    for i, l in enumerate(labels):
        st.write(f"{l} Score: {scores[i]}")

This code gets the predicted scores for all three sentiments (Negative, Neutral, and Positive) from the output of the model, and gets the predicted label and score.

It then assigns a corresponding color to the label and formats this information using HTML and displays it to the user using the Streamlit markdown and write functions.

So, with these steps completed, we have built our sentiment analyzer web app using Python and Streamlit!

6. Running the Web App

Now that we have created the web app, it’s time to run it using Streamlit.

To do so, we need to open our terminal or command prompt and navigate to the directory where the Python file containing our code is saved.

Once there, we can run the app by typing the following command:

streamlit run app.py

Replace app.py with the name of your Python file if it is different.

After running the command, Streamlit will start a local web server and launch the web app in your default web browser. You should see the title of the app, “Sentiment Analyzer”, at the top of the page.

To use the app, simply enter a sentence or paragraph that you want to analyze into the text input field provided.

Once you have entered your text, click the “Analyze” button. The app will then display the predicted sentiment for the input text, along with the predicted score and the scores for all three sentiments (negative, neutral, and positive).

Sentiment analysis web app, built with Python and Streamlit, in action

You can enter different text and click the “Analyze” button again to see how the predicted sentiment changes. The app will update in real-time to display the new results.

Wrapping Up

Congratulations! You have successfully built and run your own sentiment analysis web app with Python and Streamlit!

So, you learned how to load the sentiment analysis model and tokenizer, define the app, and run it using Streamlit.

With the skills you have gained in this tutorial, you can now apply sentiment analysis to various other tasks, such as analyzing customer feedback or monitoring social media sentiment.

Remember, sentiment analysis is just one of many exciting fields in natural language processing. Keep exploring and experimenting with new models and techniques to unleash the full potential of NLP. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *