Apply Now Apply Now Apply Now
header_logo
Post thumbnail
ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Creating a Sentiment Analysis App with Hugging Face and Streamlit

By Abhishek Pati

The sentiment analysis app is a tool that reads text and determines whether it is positive or negative. It is an effective way to recognize feelings in messages, reviews, or comments, and finding the means to do so is no longer complicated.

Now we are going to use Hugging Face for smart text analysis with AI and Streamlit to write a simple interactive application. Step by step, you will know how to transform the code into a live Sentiment Analysis App, which can analyze any text in real-time.

Quick Answer:

Quick Answer: A Sentiment Analysis app detects if the text is positive, negative, or neutral. Streamlit helps build a simple, interactive app, while Hugging Face provides pre-trained AI models to analyze the text easily.

Table of contents


  1. Understand Sentiment Analysis App with Streamlit and Hugging Face
    • Sentiment Analysis App: Definition
    • How Streamlit and Hugging Face Help Build a Sentiment Analysis App
  2. Prepare Your Setup for Developing the Sentiment Analysis Application
    • Streamlit Installation
    • Connect the Hugging Face model to your Streamlit app
    • Importing Lottie Animations (locally as JSON files)
  3. Step-by-Step Guide to Building the App
    • Step 1: Import required libraries
    • Step 2: Set up the app page
    • Step 3: Load the sentiment model
    • Step 4: Load Lottie animations
    • Step 5: Create input form
    • Step 6: Analyze sentiment on submission
    • Step 7: Run the app
  4. Conclusion
  5. FAQs
    • Can I use this app without an internet connection?
    • Why does the model only show POSITIVE or NEGATIVE sentiment?
    • Can I replace the Lottie animations with my own?

Understand Sentiment Analysis App with Streamlit and Hugging Face

Sentiment Analysis App: Definition

A sentiment analysis app is an application that evaluates the sentiment (whether a sentence or review is positive or negative) by reading and analyzing text.

For example, when a person types something like “This product is amazing”, the application will indicate that as positive sentiment, and when the person types something like “I hate this”, the application will indicate that as negative sentiment.

How Streamlit and Hugging Face Help Build a Sentiment Analysis App

Streamlit

Streamlit is a minimal framework that lets you create a web app with your Python code in a very short time. You never have to learn web design or web programming, such as HTML or CSS. You can make buttons, text boxes, and make results appear on a web page with just a few lines.

Hugging Face

Hugging Face is a platform that provides pretrained AI models, particularly for text interpretation. It assists you with sentiment analysis, translation, and text generation without requiring you to build everything from scratch. You just have to copy their models, and you can do it in a few steps.

Brief Overview: How to develop it?

To create this app, you stage Hugging Face to obtain a pre-trained sentiment analysis model that understands content, and then use Streamlit to create an interactive webpage where individuals can type a sentence.

Once the user types the text, the application forwards it to the Hugging Face model and receives the answer (positive or negative), and displays it on the screen.

💡 Did You Know?

The first sentiment analysis system was created in 2000 by AT&T Labs, paving the way for AI tools like Hugging Face.

Prepare Your Setup for Developing the Sentiment Analysis Application

Follow these steps sequentially to set up your environment for developing the app:

1. Streamlit Installation

To install Streamlit via the command line and run your first app, carefully follow the official guide here: Streamlit Installation

2. Connect the Hugging Face model to your Streamlit app

In your terminal, make sure your virtual environment is activated — you should see something like this:

(.venv) PS E:\Python Project>

This indicates that you are inside your project’s virtual environment. Then, run the following command to install the Hugging Face Transformers library along with PyTorch:

pip install transformers torch

Wait until the installation completes fully before moving to the next step. This ensures your app can access the pre-trained sentiment analysis models.

MDN

3. Importing Lottie Animations (locally as JSON files)

To show animated icons in your app, you can use Lottie animations saved as JSON files. First, install the required packages by running:

pip install streamlit-lottie requests

  • streamlit-lottie lets you display Lottie animations in Streamlit.
  • The requests library lets your app load JSON files from a URL when needed.

Once installed, you can load local JSON files or web animations and display them in your app.

Step-by-Step Guide to Building the App

Follow these simple steps to build your Sentiment Analysis App quickly and easily:

Input: Refer to the screenshot below to see where users enter their text.

Output: Refer to the screenshot below to view the sentiment result and animation.

File Path: E:\Python Project\sentiment-analysis.py

import streamlit as st
from transformers import pipeline
from streamlit_lottie import st_lottie
import requests
import json  
st.set_page_config(page_title="Sentiment App", page_icon="😊")

st.title("Sentiment Analysis App")


@st.cache_resource
def load_model():
    return pipeline("sentiment-analysis")

classifier = load_model()

def load_lottie_url(url):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()


def load_lottie_local(filepath):
    with open(filepath, "r", encoding="utf-8") as f:  
        return json.load(f)



happy_anim = load_lottie_local("HappyBoy.json")   


sad_anim = load_lottie_local("MortyCryLoader.json")      

with st.form("sentiment_form"):
    text = st.text_input("Enter text to analyze:")
    submit = st.form_submit_button("Analyze")

if submit:
    if text:
        result = classifier(text)
        label = result[0]['label']
        score = result[0]['score']

        st.subheader(f"Sentiment: {label}")
        st.write("Confidence:", round(score * 100, 2), "%")

        if label == "POSITIVE":
            st_lottie(happy_anim, height=200, loop=False)
        else:
            st_lottie(sad_anim, height=200, loop=False)
    else:
        st.warning("Please enter some text!")

Step 1: Import required libraries

  • Import Streamlit for the app UI.
  • Import the Transformers pipeline for sentiment analysis.
  • Import st_lottie to show Lottie animations.
  • Import requests and json to work with animation files.
import streamlit as st
from transformers import pipeline
from streamlit_lottie import st_lottie
import requests
import json

Step 2: Set up the app page

  • Set the page title and icon using st.set_page_config.
  • Add the main heading using st.title.
st.set_page_config(page_title="Sentiment App", page_icon="😊")
st.title("Sentiment Analysis App")

Step 3: Load the sentiment model

  • Use pipeline(“sentiment-analysis”) to load a pre-trained model.
  • Cache it with @st.cache_resource to prevent reloading every time.
@st.cache_resource
def load_model():
    return pipeline("sentiment-analysis")
classifier = load_model()

Step 4: Load Lottie animations

  • Create functions to load animations from a URL or a local JSON file.
def load_lottie_url(url):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()
def load_lottie_local(filepath):
    with open(filepath, "r", encoding="utf-8") as f:
        return json.load(f)
  • Load two animations: one for happy, one for sad.
happy_anim = load_lottie_local("HappyBoy.json")
sad_anim = load_lottie_local("MortyCryLoader.json")

Note:

load_lottie_local loads a local JSON animation for Streamlit.

Step 5: Create input form

  • Use st.form so users can type text and submit it.
  • Add a text input and a submit button.
with st.form("sentiment_form"):
    text = st.text_input("Enter text to analyze:")
    submit = st.form_submit_button("Analyze")

Step 6: Analyze sentiment on submission

  • Check if the user entered text.
  • Use the classifier to get sentiment and confidence score.
  • Show the sentiment, confidence, and the correct animation.
if submit:
    if text:
        result = classifier(text)
        label = result[0]['label']
        score = result[0]['score']
        st.subheader(f"Sentiment: {label}")
        st.write("Confidence:", round(score * 100, 2), "%")
        if label == "POSITIVE":
            st_lottie(happy_anim, height=200, loop=False)
        else:
            st_lottie(sad_anim, height=200, loop=False)
    else:
        st.warning("Please enter some text!")

Step 7: Run the app

  • Open the project terminal and run:
streamlit run app.py
  • Replace app.py with your file name (here, sentiment-analysis.py).
streamlit run sentiment-analysis.py
  • The app opens in your browser; type text, analyze it, and see animations.

Step into the future with the HCL GUVI’s Intel & IITM Pravartak Certified AI/ML Course. Gain hands-on AI/ML skills and open doors to high-paying tech careers starting today.

Conclusion

We have configured a full Sentiment Analysis App in this blog guide using Streamlit, a Hugging Face model, and Lottie visual feedback animations, and have shown each step properly, from installation through to the results. With these steps, you will be able to build an interactive application that not only predicts sentiment but also enhances the user experience with animations, all running locally in a smooth virtual environment.

FAQs

Can I use this app without an internet connection?

Yes, but first-time downloads of models or animations require an internet connection. After that, it works fully offline.

Why does the model only show POSITIVE or NEGATIVE sentiment?

The model is trained for binary sentiment, so it predicts only positive or negative results.

MDN

Can I replace the Lottie animations with my own?

Yes, save your JSON animation files locally and load them in the app using load_lottie_local().

Success Stories

Did you enjoy this article?

Schedule 1:1 free counselling

Similar Articles

Loading...
Get in Touch
Chat on Whatsapp
Request Callback
Share logo Copy link
Table of contents Table of contents
Table of contents Articles
Close button

  1. Understand Sentiment Analysis App with Streamlit and Hugging Face
    • Sentiment Analysis App: Definition
    • How Streamlit and Hugging Face Help Build a Sentiment Analysis App
  2. Prepare Your Setup for Developing the Sentiment Analysis Application
    • Streamlit Installation
    • Connect the Hugging Face model to your Streamlit app
    • Importing Lottie Animations (locally as JSON files)
  3. Step-by-Step Guide to Building the App
    • Step 1: Import required libraries
    • Step 2: Set up the app page
    • Step 3: Load the sentiment model
    • Step 4: Load Lottie animations
    • Step 5: Create input form
    • Step 6: Analyze sentiment on submission
    • Step 7: Run the app
  4. Conclusion
  5. FAQs
    • Can I use this app without an internet connection?
    • Why does the model only show POSITIVE or NEGATIVE sentiment?
    • Can I replace the Lottie animations with my own?