Skip to main content
Article
sentiment-analysisdashboardbrand-monitoringnlpstreamlitpythonhugging-faceroberta

Build a Real-Time Sentiment Dashboard with RoBERTa

Use a pre-trained RoBERTa model to analyze text sentiment. This guide shows how to wrap the 'cardiffnlp/twitter-roberta-base-sentiment' model and build an interactive dashboard with Streamlit to visualize sentiment scores in real-time.

beginner15 min4 steps
The play
  1. Install Dependencies
    Set up your Python environment. You'll need `transformers` and `torch` to run the model, `scipy` for post-processing, and `streamlit` to build the interactive web dashboard.
  2. Load the Pre-Trained Model
    Download and load the `twitter-roberta-base-sentiment` model and its corresponding tokenizer from the Hugging Face Hub. This model is specifically fine-tuned for sentiment on short texts like social media posts.
  3. Create a Sentiment Scoring Function
    Define a function that takes raw text, tokenizes it for the model, runs inference, and uses a softmax function to convert the output logits into a human-readable probability distribution for negative, neutral, and positive sentiment.
  4. Build the Streamlit Dashboard UI
    Use Streamlit to create the user interface for your Sentiment Dashboard. Add a title, a text area for user input, and a button. When the button is clicked, it will trigger the sentiment analysis function.
Starter code
import streamlit as st
import pandas as pd
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from scipy.special import softmax

# --- Model Loading (cached for performance) ---
@st.cache_resource
def load_model():
    MODEL = "cardiffnlp/twitter-roberta-base-sentiment"
    tokenizer = AutoTokenizer.from_pretrained(MODEL)
    model = AutoModelForSequenceClassification.from_pretrained(MODEL)
    return tokenizer, model

tokenizer, model = load_model()

# --- Sentiment Scoring Function ---
def get_sentiment_scores(text):
    """Analyzes text and returns sentiment scores."""
    encoded_input = tokenizer(text, return_tensors='pt')
    output = model(**encoded_input)
    scores = output[0][0].detach().numpy()
    scores = softmax(scores)
    labels = ['negative', 'neutral', 'positive']
    return dict(zip(labels, scores))

# --- Streamlit App UI ---
st.set_page_config(layout="wide")
st.title("Sentiment Dashboard")
st.markdown("Analyze text sentiment in real-time using a fine-tuned RoBERTa model.")

user_input = st.text_area("Enter Text for Analysis (e.g., a tweet, review, or comment):", "Streamlit makes building data apps so easy!", height=150)

if st.button("Analyze Sentiment"):
    if user_input:
        with st.spinner('Analyzing...'):
            scores = get_sentiment_scores(user_input)
            
            # Find the dominant sentiment
            dominant_sentiment = max(scores, key=scores.get)
            dominant_score = scores[dominant_sentiment]

            st.subheader("Analysis Results")
            col1, col2 = st.columns(2)

            with col1:
                st.metric(
                    label="Dominant Sentiment", 
                    value=dominant_sentiment.capitalize(),
                    help=f"The highest score was {dominant_score:.2%}"
                )
                st.write("**Full Score Distribution:**")
                st.write(scores)

            with col2:
                st.write("**Score Visualization:**")
                chart_data = pd.DataFrame([scores])
                st.bar_chart(chart_data)
    else:
        st.warning("Please enter some text to analyze.")

# To run: 
# 1. Save this code as `app.py`
# 2. Run `pip install streamlit pandas transformers torch scipy`
# 3. Run `streamlit run app.py` in your terminal
Build a Real-Time Sentiment Dashboard with RoBERTa — Action Pack