Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
✦ Beginner ⏱ 30 min

😊 Build a Sentiment Analysis Dashboard with HuggingFace

🎯 What You'll Build

A sentiment analysis dashboard that classifies customer reviews as positive, negative, or neutral using a free HuggingFace model, with a Streamlit UI to upload and analyse in bulk.

📋 What You'll Need

1

Sentiment classification with transformers

A pre-trained DistilBERT model classifies text as POSITIVE or NEGATIVE with a confidence score.

from transformers import pipeline

# Downloads ~700 MB on first run, then cached locally
sentiment = pipeline(
    'sentiment-analysis',
    model='distilbert-base-uncased-finetuned-sst-2-english',
    truncation=True,
    max_length=512,
)

reviews = [
    "The product quality exceeded my expectations. Fast delivery too!",
    "Terrible customer service. Waited 3 weeks and still no refund.",
    "It is okay. Nothing special but does the job.",
    "Absolutely love this! Best purchase I have made this year.",
    "Would not recommend. Broke after two weeks of light use.",
]

results = sentiment(reviews)
for review, r in zip(reviews, results):
    print(f"[{r['label']:8}  {r['score']:.2%}]  {review[:60]}")
[POSITIVE  99.82%]  The product quality exceeded my expectations. Fast deli
[NEGATIVE  99.97%]  Terrible customer service. Waited 3 weeks and still no
[POSITIVE  56.34%]  It is okay. Nothing special but does the job.
[POSITIVE  99.92%]  Absolutely love this! Best purchase I have made this ye
[NEGATIVE  99.86%]  Would not recommend. Broke after two weeks of light use.
2

Build a Streamlit dashboard

A simple UI to upload a CSV of reviews and see the sentiment breakdown.

# app.py
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from transformers import pipeline

@st.cache_resource
def load_model():
    return pipeline(
        'sentiment-analysis',
        model='distilbert-base-uncased-finetuned-sst-2-english',
        truncation=True, max_length=512,
    )

st.title("Sentiment Analysis Dashboard")
st.write("Upload a CSV with a `review` column to analyse customer sentiment.")

uploaded = st.file_uploader("Choose a CSV file", type='csv')

if uploaded:
    df = pd.read_csv(uploaded)

    if 'review' not in df.columns:
        st.error("CSV must have a 'review' column"); st.stop()

    st.write(f"Analysing {len(df)} reviews...")
    sentiment = load_model()

    with st.spinner("Running sentiment analysis..."):
        results = sentiment(df['review'].tolist())

    df['Sentiment'] = [r['label'] for r in results]
    df['Score']     = [round(r['score'], 3) for r in results]

    # Summary counts
    counts = df['Sentiment'].value_counts()
    col1, col2 = st.columns(2)
    col1.metric("Positive", counts.get('POSITIVE',0))
    col2.metric("Negative", counts.get('NEGATIVE',0))

    # Pie chart
    fig, ax = plt.subplots()
    ax.pie(counts, labels=counts.index, autopct='%1.0f%%',
           colors=['#22c55e','#ef4444'])
    st.pyplot(fig)

    # Full table
    st.dataframe(df[['review','Sentiment','Score']])
    st.download_button("Download Results", df.to_csv(index=False), "results.csv")
# Run with:
streamlit run app.py
💡 Tip: DistilBERT only classifies POSITIVE or NEGATIVE. For 3-class (positive/negative/neutral) or 5-star rating prediction, try cardiffnlp/twitter-roberta-base-sentiment-latest — it supports three classes and is better on short social media text.

🎉 You Did It!

A functional analytics tool ready for a real business use case. Upload a month of product reviews, see the trend, identify the most negative feedback, and filter for low-confidence predictions that need human review.

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.