Codecademy Logo

Build AI Applications with Streamlit

Related learning

  • Learn Streamlit to build and deploy interactive AI applications with Python in this hands-on course.
    • With Certificate
    • Intermediate.
      1 hour

Python Streamlit Magic

Streamlit simplifies creating web apps with Python scripts, no HTML or CSS required. With just a few lines of Python code, you can create fully functional web applications that include titles, text, data tables, and visualizations. Streamlit handles all the web development complexity behind the scenes, allowing data scientists and developers to focus on their Python logic rather than learning web technologies.

import streamlit as st
import pandas as pd
import numpy as np
st.title('My First Streamlit App')
st.write('Hello, World!')
# Create some sample data
data = pd.DataFrame({
'numbers': np.random.randn(20),
'letters': np.random.choice(['A', 'B', 'C'], 20)
})
st.dataframe(data)
st.line_chart(data['numbers'])

Streamlit Interactive Widgets

Widgets are the interactive elements that allow users to provide input to your application. Each widget returns a value that can be used in your Python code, and when users interact with these widgets, Streamlit automatically updates the application with the new values.

# Text input widget
name = st.text_input('What\'s your name?')
# Slider widget
age = st.slider('How old are you?', 13, 100, 25)
# Selectbox widget (dropdown)
genre = st.selectbox('Favorite movie genre:',
['Action', 'Comedy', 'Drama', 'Horror', 'Sci-Fi'])
# Checkbox widget
wants_popcorn = st.checkbox('Do you like popcorn?')
# Button widget
if st.button('Get My Movie Recommendation'):
st.write(f"Hello {name}! Based on your preferences...")

Streamlit Rerun Behavior

Understanding Streamlit’s execution model is crucial for building effective applications. Every widget interaction triggers a complete script rerun, which means regular Python variables get reset to their initial values. This behavior explains why simple variable assignments don’t persist between user interactions.

# This creates a fresh empty list on every interaction!
shopping_list = []
# User input
item = st.text_input('Add item to shopping list:')
if st.button('Add Item'):
shopping_list.append(item) # Gets reset on next interaction
st.write(shopping_list) # Will only show current item

Session State in st.session_state

Session state is Streamlit’s solution for maintaining data across script reruns. By storing values in st.session_state, you can build applications that remember user interactions, accumulate data over time, and maintain complex application states that persist throughout the user’s session.

import streamlit as st
# Initialize session state
if 'shopping_list' not in st.session_state:
st.session_state.shopping_list = []
# User input
item = st.text_input('Add item to shopping list:')
if st.button('Add Item'):
# This persists across reruns!
st.session_state.shopping_list.append(item)
# Display persistent list
st.write("Your shopping list:", st.session_state.shopping_list)

Streamlit Data Display

Streamlit offers versatile methods for showcasing data. Use st.metric() to display vital stats, while st.dataframe() presents interactive tables. Visualize data with built-in chart functions or integrate with libraries like Matplotlib, Seaborn, and Plotly for advanced plotting.

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
# Display a key performance indicator
st.metric(label="Acquisition Growth Rate", value="7%", delta="1.5%")
# Display an interactive table
sample_data = pd.DataFrame({
"Metric": ["Visitors", "Conversions", "Revenue"],
"2022": [1200, 300, 5000],
"2023": [1400, 350, 7500]
})
st.dataframe(sample_data, use_container_width=True)
# Example plot using matplotlib
fig, ax = plt.subplots()
ax.plot(['Q1', 'Q2', 'Q3', 'Q4'], [100, 200, 300, 400], label='2022')
ax.set_title('Quarterly Growth')
ax.set_xlabel('Quarter')
ax.set_ylabel('Growth')
st.pyplot(fig)

Streamlit st.button()

Buttons have unique behavior compared to other widgets - they only return True for the instant they’re clicked, then immediately return False. This makes them perfect for triggering specific actions like form submissions, calculations, or processing steps that should only happen when explicitly requested by the user.

# Button only returns True at the moment of clicking
if st.button('Get My Movie Recommendation'):
# This code only runs when the button is clicked
st.write("Generating recommendation...")
# Processing logic here
# This runs every time the script reruns
st.write("This text always appears")

Streamlit App Organization

As applications grow in complexity, organizing content becomes essential for user experience. Tabs provide a way to group related functionality on a single page, while separate page files create distinct sections with automatic navigation. This organization helps users navigate complex applications without overwhelming them with too much content at once.

# Using tabs for organization
tab1, tab2, tab3 = st.tabs(["📝 Shopping List", "📊 Analytics", "💰 Budget"])
with tab1:
st.header('Current Shopping List')
# Shopping list functionality here
with tab2:
st.header('📊 Shopping Analytics')
# Analytics functionality here
with tab3:
st.header('💰 Budget')
# Budget functionality here

Streamlit st.connection

Streamlit simplifies database integration by providing built-in connection management and smart caching. The ttl (time-to-live) parameter automatically caches query results for specified durations, reducing database load and improving application performance. This makes it easy to build data-driven applications that scale effectively.

import streamlit as st
# Establish a cached database connection
@st.cache_resource
def get_database_connection():
return st.connection('my_db', type='sql', url='sqlite:///data/coffee_shop.db')
# Query with caching (TTL = Time To Live)
top_products = conn.query("""
SELECT
p.name as Drink,
SUM(s.quantity) as Sales,
p.price as Price
FROM sales s
JOIN products p ON s.product_id = p.id
GROUP BY p.id, p.name, p.price
ORDER BY Sales DESC
LIMIT 3
""", ttl=300) # Cache for 5 minutes
st.table(top_products)

Streamlit Models

Streamlit applications can incorporate machine learning models saved in different formats depending on the library used to create them. Understanding the appropriate loading method for each model type enables you to integrate predictions and AI capabilities into your web applications seamlessly.

import joblib
import pickle
import streamlit as st
# Scikit-learn models (most common)
model = joblib.load('sales_forecast_model.pkl')
# Alternative for sklearn using pickle
with open('sales_forecast_model.pkl', 'rb') as f:
model = pickle.load(f)
# PyTorch models
import torch
model = torch.load('model.pth')
# TensorFlow/Keras models
import tensorflow as tf
model = tf.keras.models.load_model('model.h5')
#Write prediction output
st.write(model.predict(data))

Streamlit Caching

Resource caching prevents expensive operations from repeating unnecessarily. While normal variables reset on every script rerun, the @st.cache_resource decorator ensures that costly operations like loading large ML models or establishing database connections happen only once per session, dramatically improving application performance and user experience.

import streamlit as st
import joblib
@st.cache_resource
def load_sales_forecast_model():
"""Load and cache the sales forecasting model"""
try:
# Model loads only once per session!
return joblib.load('models/sales_forecast_model.pkl')
except Exception as e:
st.error(f"Error loading model: {e}")
return None
# This will only load the model once, then reuse it
model = load_sales_forecast_model()
if model:
prediction = model.predict(input_data)
st.write(f"Prediction: {prediction}")

Learn more on Codecademy

  • Learn Streamlit to build and deploy interactive AI applications with Python in this hands-on course.
    • With Certificate
    • Intermediate.
      1 hour