Building Apps with Streamlit: A Quick Start Guide for Data Scientists.

Building Apps with Streamlit: A Quick Start Guide for Data Scientists.


Introduction

Hook

Imagine a world where you can turn your data analysis scripts into interactive web applications with just a few lines of Python code. No need to dive deep into HTML, CSS, or JavaScript. This is not a dream; this is the reality that Streamlit offers.

Overview

Streamlit is an open-source Python library that has revolutionized the way data scientists and machine learning engineers create and share data applications. Traditionally, creating a web application required extensive knowledge of web development frameworks like Django or Flask, along with proficiency in front-end technologies. Streamlit simplifies this process, enabling users to build and deploy powerful web applications in minutes, using pure Python.

Thesis

In this article, we will explore what makes Streamlit a game-changer for data applications. We’ll compare it with traditional web frameworks like Django and Flask, showcase its unique features, and guide you through building your first Streamlit app. By the end of this post, you’ll understand why Streamlit is quickly becoming the go-to tool for data professionals looking to create interactive web applications effortlessly.

Streamlit vs. Django vs. Flask

Ease of Use

  • Streamlit: Streamlit is designed to be incredibly easy to use, especially for those who are already familiar with Python. Its intuitive API allows you to create interactive applications with minimal code. For example, displaying a data frame or a plot can be done in a single line of code. This makes it ideal for rapid prototyping and iterative development.

An example ?? :

import streamlit as st
import pandas as pd

df = pd.DataFrame({
    'column1': [1, 2, 3],
    'column2': [4, 5, 6]
})

st.write(df)        

  • Django: Django is a full-stack web framework that provides a comprehensive suite of tools for building robust web applications. However, its steep learning curve can be daunting for beginners. Django requires a good understanding of both backend and frontend technologies, and setting up a simple application involves configuring models, views, templates, and URLs.
  • Flask: Flask is a micro web framework that is more lightweight and flexible than Django. It gives developers more control over their application’s components and architecture. While Flask is easier to learn than Django, it still requires knowledge of HTML and other front-end technologies to build fully functional web applications.

Real-time Feedback

  • Streamlit: One of Streamlit’s standout features is its ability to provide real-time feedback. As you make changes to your code, Streamlit automatically updates the app in your browser, allowing for immediate visualization and interaction. This live feedback loop is incredibly valuable for data exploration and model tuning.
  • Django and Flask: Both Django and Flask require a more traditional development approach where changes in the codebase need to be manually refreshed in the browser. While some tools and extensions can provide live reload capabilities, they are not as seamless as Streamlit’s built-in functionality.

Customization and Flexibility

  • Streamlit: While Streamlit excels in simplicity and ease of use, it offers less flexibility in terms of customization compared to Django and Flask. Streamlit apps are designed to follow a linear, top-to-bottom script execution, which can be limiting for complex web applications with multiple routes and states.
  • Django: Django provides extensive customization options through its powerful ORM (Object-Relational Mapping), template engine, and built-in admin interface. It is suitable for building complex, multi-page applications with robust user authentication, authorization, and database interactions.
  • Flask: Flask offers a good balance between simplicity and flexibility. It allows for custom routing, middleware, and integration with various extensions. Developers can structure their Flask applications in numerous ways, making it ideal for both simple and complex projects.

Now let's look at how easy streamlit is to learn.

Getting Started with Streamlit

Installation

Streamlit can be easily installed using pip, Python’s package manager. Follow these simple steps to install Streamlit on your system:

  1. Open Terminal or Command Prompt: Depending on your operating system, open Terminal (for macOS and Linux) or Command Prompt (for Windows).
  2. Install Streamlit: Use the following command to install Streamlit via pip.

pip install streamlit        

3. Verify Installation: Once the installation is complete, you can verify it by checking the Streamlit version.

streamlit --version        

  1. This command should print the installed version of Streamlit to the console.

Hello, Streamlit!

Now that you have Streamlit installed, let’s write your first Streamlit app! Create a new Python file (e.g., hello_streamlit.py) and follow along with the example below.

# Import the Streamlit library
import streamlit as st
# Add a title to your app
st.title("Hello, Streamlit!")

# Write some text to display in the app
st.write("Welcome to your first Streamlit app.")

# Display a simple plot
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)

y = np.sin(x)
plt.plot(x, y)
st.pyplot(plt)        

Here is the out put ?? :

Save the file and navigate to its directory using Terminal or Command Prompt. Then, run the Streamlit app using the following command:

streamlit run hello_streamlit.py        

This command will start a local Streamlit server and open your default web browser to display the app. You should see the title “Hello, Streamlit!” along with the welcome message and a simple plot of the sine function.

Congratulations! You’ve just created and deployed your first Streamlit app. From here, you can explore the Streamlit documentation to learn more about its capabilities and start building more advanced applications.

Now let's get into the real basics of streamlit such that you know which features streamlit holds.

Exploring Streamlit Features

Widgets: Overview of Interactive Widgets for User Input and Visualization

Streamlit provides a variety of widgets that allow users to interact with your app. These widgets can be used to capture user inputs, display data, and create interactive visualizations.

Start by importing streamlit in your environment.

import streamlit as st
#this allows you to use all the streamlit features.        

  1. Text Input: Captures user input as a string.

user_input = st.text_input("Enter your name:") 
st.write(f"Hello, {user_input}!")        

2. Slider: Allows users to select a numeric value from a range.

number = st.slider("Pick a number:", 0, 100) 
st.write(f"You selected: {number}")        

3. Selectbox: Provides a dropdown menu for users to select an option.

option = st.selectbox("Choose a fruit:", ["Apple", "Banana", "Cherry"]) 
st.write(f"You chose: {option}")        

4. Checkbox: Displays a checkbox that can be toggled on or off.

if st.checkbox("Show/Hide"):     
    st.write("Checkbox is checked!")        

5. Radio Buttons: Allows users to select one option from a list.

genre = st.radio("Choose a genre:", ["Comedy", "Drama", "Documentary"]) 
st.write(f"You chose: {genre}")        

6. File Uploader: Enables users to upload files.

uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
    data = uploaded_file.read()
    st.write(data)        

7. Loading…..Progress bar and a spinner.

# creating a progress bar
import time

my_bar = st.progress(0)
for p in range(10):
    my_bar.progress(p + 1)

# creating a spinner
with st.spinner("Loading....."):
    time.sleep(5)
st.success("Finished")        

8. Loading date and time.

import streamlit as st
import datetime
#Date Input
st.subheader("Date Input")
today = st.date_input("Today is:")
# Time Input
st.subheader("Time Input")
time = st.time_input("The time is:")

     OR

# creating a date input
import datetime

today = st.date_input("Today is", datetime.datetime.now())

# creating a time input
the_time = st.time_input("The time is", datetime.time())        

Layouts and Containers: Organizing the App’s Layout for Better User Experience

Streamlit offers several ways to organize and structure your app’s layout to enhance user experience.

  1. Columns: Arrange widgets side by side.

col1, col2, col3 = st.columns(3) 
col1.write("Column 1") 
col2.write("Column 2") 
col3.write("Column 3")        

2. Expander: Create expandable sections for content.

with st.expander("Expand me"):
    st.write("Hello! Here is some hidden content.")        

3. Tabs: Organize content into tabs.

tab1, tab2, tab3 = st.tabs(["Tab 1", "Tab 2", "Tab 3"])
with tab1:
    st.write("Content of Tab 1")
with tab2:
    st.write("Content of Tab 2")
with tab3:
    st.write("Content of Tab 3")        

4. Sidebar: Add a sidebar for additional navigation or inputs.

st.sidebar.title("Sidebar Title")
sidebar_option = st.sidebar.selectbox("Choose an option", ["Option 1", "Option 2"])
st.sidebar.write(f"You chose: {sidebar_option}")        

Media Integration: Incorporating Images, Videos, and Audio into Streamlit Apps

Streamlit makes it easy to incorporate various media types into your app to create a richer user experience.

  1. Images: Display images using the st.image function.

st.image("path/to/your/image.jpg", caption="Sample Image", use_column_width=True)        

2. Videos: Embed videos using the st.video function.

st.video("https://www.youtube.com/watch?v=your_video_id")        

3. Audio: Play audio files using the st.audio function.

st.audio("path/to/your/audio.mp3")        

Check the output ??:

https://youtu.be/VIwOMNbpmLc

Charts and Graphs: Creating Stunning Visualizations Using Libraries like Matplotlib and Plotly

Streamlit supports a wide range of visualization libraries, making it easy to create stunning charts and graphs.

  1. Matplotlib: Create and display Matplotlib charts.

import matplotlib.pyplot as plt
import stramlit as st

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
st.pyplot(fig)        

Output ?

:

2. Seaborn: Generate beautiful statistical plots using Seaborn.

import seaborn as sns# Need to install seaborn before you can run the code using pip command in your terminal
import pandas as pd# Need to install pandas before you can run the code using pip command in your terminal

# Create a DataFrame with the data
data = pd.DataFrame({
    'x': [1, 2, 3, 4],  # X-axis values
    'y': [10, 20, 25, 30]  # Y-axis values
})

# Create a line plot using seaborn
fig = sns.lineplot(x='x', y='y', data=data).get_figure()

# Display the plot
st.pyplot(fig)        
The code snippet provided demonstrates the powerful data visualization capabilities of Seaborn and Pandas for creating a compelling line plot. It begins by importing the necessary libraries and constructing a DataFrame with x and y values, setting the stage for a visually appealing line graph. The key steps are as follows: 1. Import Seaborn and Pandas to utilize their features. 2. Construct a DataFrame with x and y coordinates for plotting. 3. Apply Seaborn’s lineplot() function with the DataFrame and specified x and y columns to generate the plot. 4. Retrieve the figure object from the Seaborn plot using get_figure(). 5. Present the final line plot using Streamlit’s st.pyplot(), integrating the Seaborn graph into the Streamlit interface effortlessly. This concise yet effective snippet showcases the integration of data visualization into a Streamlit app, leveraging Seaborn and Pandas’ capabilities. The resulting line plot is clear and aesthetically pleasing, effectively conveying the data’s trends and correlations, proving invaluable for data analysis and presentation.

3. Plotly: Create interactive plots with Plotly.

import streamlit as st
import plotly.express as px# Need to install plotly before you can run the code using pip command in your terminal 

# Load the iris dataset from Plotly's repository
df = px.data.iris()

# Create a scatter plot of sepal width vs sepal length, colored by species
fig = px.scatter(df, x='sepal_width', y='sepal_length', color='species')

# Display the plot in Streamlit
st.plotly_chart(fig)        

By utilizing these features, you can create highly interactive and visually appealing Streamlit apps that cater to various user needs and preferences.

Output ?? :

Advanced Streamlit Features

State Management: Understanding Session State and Managing User Interactions

Streamlit apps can benefit significantly from maintaining state, especially when dealing with user interactions and dynamic content updates. Session state allows you to store and retrieve information across different user interactions without needing to reload the entire app.

  1. Introduction to Session State: Streamlit’s st.session_state is a dictionary-like object that stores variables across reruns of the app. This is useful for preserving the state of widgets, data, or any other information.

Code sample ?? :

import streamlit as st

if 'count' not in st.session_state:
    st.session_state.count = 0

increment = st.button('Increment')
if increment:
    st.session_state.count += 1

st.write(f"Count: {st.session_state.count}")        

2. Managing Complex Interactions: You can use session state to manage more complex interactions, such as multi-step forms or interactive dashboards.

Code sample ?? :

import streamlit as st

if 'step' not in st.session_state:
    st.session_state.step = 1

if st.session_state.step == 1:
    st.write("Step 1")
    next_button = st.button("Next")
    if next_button:
        st.session_state.step = 2

elif st.session_state.step == 2:
    st.write("Step 2")
    prev_button = st.button("Previous")
    next_button = st.button("Next")
    if prev_button:
        st.session_state.step = 1
    if next_button:
        st.session_state.step = 3

elif st.session_state.step == 3:
    st.write("Step 3")
    prev_button = st.button("Previous")
    if prev_button:
        st.session_state.step = 2        

Caching: Optimizing App Performance with Caching

Streamlit’s caching mechanism helps optimize performance by storing the results of expensive computations and reusing them when the same inputs occur again.

  1. Using @st.cache_data: The @st.cache_data decorator is used to cache data processing functions. This can significantly reduce load times for operations that don't need to be recalculated with the same inputs.

import streamlit as st
import pandas as pd

@st.cache_data
def load_data():
    # Simulate an expensive computation
    df = pd.read_csv("large_dataset.csv")#make sure you have a csv(large_dataset.csv) file save in ythe same directory.
    return df

df = load_data()
st.write(df)        

2. Configuring Cache: You can control the caching behavior with parameters such as ttl (time to live), show_spinner, and suppress_st_warning.

@st.cache_data(ttl=600, show_spinner=False)
def load_data():
    df = pd.read_csv("large_dataset.csv")
    return df        

3. Clearing Cache: Sometimes, you might need to clear the cache manually, for instance, when the underlying data changes.

st.cache_data.clear()        

Authentication: Securing Streamlit Apps with User Authentication

Adding authentication to your Streamlit app ensures that only authorized users can access certain features or data. Streamlit does not have built-in authentication, but you can integrate external authentication mechanisms.

  1. Simple Password Protection: A basic method is to prompt for a password and restrict access based on the correct input.

import streamlit as st

def check_password():
    def password_entered():
        if st.session_state["password"] == "password123":
            st.session_state["password_correct"] = True
            del st.session_state["password"]
        else:
            st.session_state["password_correct"] = False

    if "password_correct" not in st.session_state:
        st.text_input("Password", type="password", on_change=password_entered, key="password")
        return False
    elif not st.session_state["password_correct"]:
        st.text_input("Password", type="password", on_change=password_entered, key="password")
        st.error("Incorrect password")
        return False
    else:
        return True

if check_password():
    st.write("Welcome to the secure section of the app!")        

Using Third-Party Authentication Services: For more robust authentication, you can integrate third-party services like OAuth. Libraries such as auth0 or okta can help with this.

2. Auth0 Example: Integrate Auth0 using a package like auth0-python.

# This is a conceptual example. You'll need to follow Auth0's setup guides for full implementation.
from auth0.v3.authentication import GetToken
from auth0.v3.management import Auth0

# Initialize Auth0 client
auth0 = Auth0('your-auth0-domain', 'your-auth0-client-id', 'your-auth0-client-secret')

# Implement the login flow in your Streamlit app        

3. Using stauth for Simpler Integration: There are simpler packages like stauth designed for Streamlit that can help manage authentication more seamlessly.

import streamlit_authenticator as stauth

names = ['John Doe', 'Jane Smith']
usernames = ['johndoe', 'janesmith']
passwords = ['password1', 'password2']

authenticator = stauth.Authenticate(names, usernames, passwords, 'some_cookie_name', 'some_signature_key')

name, authentication_status = authenticator.login('Login', 'main')

if authentication_status:
    st.write(f'Welcome {name}')
elif authentication_status is False:
    st.error('Username/password is incorrect')
elif authentication_status is None:
    st.warning('Please enter your username and password')        

By leveraging these advanced Streamlit features, you can create more dynamic, efficient, and secure applications. Understanding session state management, optimizing with caching, and securing your apps with authentication are key steps in building professional and robust data applications.



要查看或添加评论,请登录

社区洞察

其他会员也浏览了