Generative AIBuilding with foundation modelsTools & frameworks

Overview of Streamlit

8 minutes read

As a Data Scientist or AI/ML Engineer, creating web apps to visualize and interact with data can be a daunting task. Normally, you need additional web development experience to build these interfaces. But that's not what you want, right? You just want to focus on the data manipulation tasks.

This is where Streamlit, a Python library, comes in. It simplifies the creation of interactive web applications for machine learning models. Let's see how you can use this library to quickly build user-friendly interfaces without needing extensive web development knowledge.

Setup

To start using Streamlit, you first need to install it in your virtual environment. This can easily be done with pip:

(env) $ python -m pip install streamlit

After installation, you can view a demo app with the following command:

(env) $ streamlit hello

Unfortunately, this demo app isn't very useful. Fortunately, all you need to do is create a normal Python file, import the Streamlit library, and use some Streamlit components, which we discuss next, to build the logic for your app. The following example sets up a simple app with a short title and a welcome message:

import streamlit as st

st.title("My First Streamlit App")
st.write("Welcome to interactive web apps!")

Once you save the app (app.py) , simply run it with the streamlit run command:

(env) $ streamlit run app.py

Streamlit will start a local server and open the web browser, showing your app:

Screenshot showing a simple streamlit application.

Any changes you make will automatically update in real time.

Essential components

Streamlit offers various components to create interactive web interfaces. The most important part of data visualization is displaying data. For this, Streamlit provides the st.write() function for normal text and the st.title() function for your headers. st.write() also accepts other data formats: numbers, Pandas DataFrames, styled DataFrames, and other objects. If you want to create a sub-header, you can use st.subheader().

In the following example, we use the write() function to display a simple Pandas DataFrame:

import streamlit as st
import pandas as pd

st.title("Entries and Amounts")
st.write(
    pd.DataFrame(
        {
            "Entry": [1, 2, 3, 4],
            "Amount": [10, 20, 30, 40],
        }
    )
)

Screenshot showing a dataframe with entries and amounts as visualized by Streamlit

You can also use st.dataframe() for Pandas DataFrames, st.table() for static tables, and st.json() for JSON data. For visualizations, you can use st.pyplot() for Matplotlib figures or st.plotly_chart() for Plotly charts. Additionally, Streamlit provides some input widgets:

  • st.text_input() — for text entry;

  • st.number_input() — for number entry;

  • st.slider() — for numeric ranges;

  • st.selectbox() — for drop-down menus;

  • st.checkbox() — for selecting one or more options from a list of options;

  • st.radio() — for selecting only one option from a list of options.

Let's combine some of these components to create a more complex application:

import streamlit as st
import pandas as pd
import json

st.title("Data Explorer")

# Create a sample DataFrame
df = pd.DataFrame({
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'San Francisco', 'London']
})

st.header("Sample Data")
st.dataframe(df)

st.subheader("Filter by Age")
age_filter = st.slider("Select maximum age", 20, 40, 30)
filtered_df = df[df['Age'] <= age_filter]

st.write(f"Showing data for ages up to {age_filter}:")
st.table(filtered_df)

# JSON data
st.subheader("Sample JSON Data")
sample_json = {
    "name": "Alice",
    "age": 25,
    "city": "New York"
}
st.json(sample_json)

Once you run this application, you'll get the following output:

Sample Streamlit application using various components such as DataFrames, sliders, and JSON data.

These are some common Streamlit components you can use in your application. You can view all components in the API documentation.

Demo application

Now, imagine you are working on a sentiment analysis model that classifies text as positive or negative. You need to create an interface that allows users to input a sentence, and the app processes it using a pre-trained sentiment analysis model and displays the results along with a confidence score. It works by analyzing the input text and determining whether it expresses a positive or negative sentiment based on its training data.

First, we'll need to install the necessary libraries:

(env) $ python -m pip install streamlit
(env) $ python -m pip install torch
(env) $ python -m pip install transformers

Then, we need to create the sentiment analysis app (note that model loading might take a while):

import streamlit as st
from transformers import pipeline

# Load the sentiment analysis model
sentiment_pipeline = pipeline("sentiment-analysis")

st.title("Sentiment Analysis Demo")

# Create a text input for user to enter a sentence
user_input = st.text_input("Enter a sentence to analyze: ", "I love using Streamlit!")

if user_input:
    try:
        # Perform sentiment analysis
        result = sentiment_pipeline(user_input)[0]
        sentiment = result['label']
        score = result['score']

        # Display the results
        st.header("Analysis Result")
        st.write(f"Sentiment: {sentiment}")
        st.write(f"Confidence Score: {score:.2f}")

        # Visualize the confidence score
        st.progress(score)

        # Provide an interpretation
        if sentiment == "POSITIVE":
            st.success("The input text has a positive sentiment.")
        else:
            st.error("The input text has a negative sentiment.")
    except Exception as e:
        st.error(f"An error occurred: {str(e)}")

Once you run the application, for a positive sentiment, you'll get the following output:

Screenshot showing analysis for a positive sentiment identified with a confidence score of 1.00

For a negative sentiment, you'll get the following output:

Screenshot showing analysis for a negative sentiment identified with a confidence score of 1.00

Try it yourself!

Interface customization

Now, let's make our Streamlit app more engaging and user-friendly. You can customize its appearance and add extra features. These include collapsible sidebars, columns, expandable sections, download buttons, and even custom HTML and CSS.

Here's a list of functions you can use for this functionality:

  • st.sidebar() — to create a collapsible sidebar for navigation or additional controls;

  • st.columns() — to create multi-column layouts, improving overall design;

  • st.markdown() — to inject custom CSS to modify the app's appearance with HTML and CSS;

  • st.expander() — to create collapsible sections for additional information or options;

  • st.download_button() — to allow users to download results or data from your app;

In the following example, all these components have been used to enhance the demo application:

Screenshot showing an advanced version of the sentiment analysis app with additional components such as expander, sidebar, and download button.

Looks interesting? Expand here to see the code used to create it.
import streamlit as st
from transformers import pipeline
import pandas as pd

# Custom CSS to improve the app's appearance
st.markdown("""

    """, unsafe_allow_html=True)

# Sidebar for model selection
st.sidebar.title("Model Selection")
model_name = st.sidebar.selectbox("Choose a model", ["distilbert-base-uncased-finetuned-sst-2-english", "roberta-large-mnli"])

# Cache the model loading
@st.cache_resource
def load_model(name):
    return pipeline("sentiment-analysis", model=name)

sentiment_pipeline = load_model(model_name)

st.title("Enhanced Sentiment Analysis Demo")

# Create two columns
col1, col2 = st.columns(2)

with col1:
    st.markdown('Enter your text:', unsafe_allow_html=True)
    user_input = st.text_area("", "I love using Streamlit!")

with col2:
    if user_input:
        result = sentiment_pipeline(user_input)[0]
        sentiment = result['label']
        score = result['score']

        st.markdown('Analysis Result:', unsafe_allow_html=True)
        st.write(f"Sentiment: {sentiment}")
        st.write(f"Confidence Score: {score:.2f}")
        st.progress(score)

        if sentiment == "POSITIVE":
            st.success("Positive sentiment detected!")
        else:
            st.error("Negative sentiment detected!")

# Add some information about the selected model
with st.sidebar.expander("Model Information"):
    st.write(f"Using model: {model_name}")
    st.write("This model analyzes the sentiment of the input text and classifies it as positive or negative.")

# Allow users to download results
if 'result' in locals():
    df = pd.DataFrame([result])
    csv = df.to_csv(index=False)
    st.download_button(
        label="Download results as CSV",
        data=csv,
        file_name="sentiment_analysis_results.csv",
        mime="text/csv",
    )

Additionally, Streamlit also allows you to integrate other advanced features into your application. This includes caching frequently used data, using forms and dialogs, and even connecting to databases. Here are some common functions and decorators to achieve this:

  • @st.cache_data() — a function decorator to store results and improve app performance for computationally intensive operations;

  • @st.dialog — a decorator that denotes a dialog function. This inserts a modal dialog into your app;

  • st.form() — creates a form where you can combine multiple elements together along with a "Submit" button;

  • st.connection() — to create a new connection to a data store or API, or return an existing one;

  • st.session_state — to store and restore state across runs and across pages.

There are a lot more advanced features you can utilize in your app. You can view all of them in the API documentation.

Conclusion

You've learned the following concepts:

  • Streamlit simplifies the creation of interactive web apps for machine learning models.

  • The essential components include text elements, data display elements, and input widgets.

  • Customization options like sidebars, columns, and CSS styling improve the app's appearance and usability.

  • You can utilize advanced features such as caching frequently used data, creating database connections, and even storing/restoring sessions to improve performance.

Now that you've learned about Streamlit, try building a simple app on your own. Start with a basic concept and gradually add more features as you become comfortable with the framework. For inspiration, take a look at Streamlit's gallery of demo apps.

3 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo