Complete Streamlit Advanced Tutorial: Build Production-Ready ML Apps
Streamlit is a powerful Python library for building interactive web applications for machine learning and data science. This advanced tutorial covers production patterns, performance optimization, and enterprise features.
Why Streamlit for Production?
Streamlit Advantages:- Rapid development: Build apps in hours, not days
- Pure Python: No frontend knowledge required
- Interactive widgets: Rich UI components
- Easy deployment: Streamlit Cloud, Docker, Kubernetes
- Active ecosystem: Community components and integrations
- ML model demos and dashboards
- Data exploration tools
- Internal analytics apps
- Customer-facing applications
- Prototyping and MVPs
Installation
pip install streamlit
With additional features
pip install streamlit-extras
pip install streamlit-aggrid
pip install plotly
Verify installation
streamlit --version
App Architecture
1. Multi-Page Apps
# pages/1Home.py
import streamlit as st
st.set
pageconfig(
page
title="ML Dashboard",
pageicon="🤖",
layout="wide",
)
st.title("Welcome to ML Dashboard")
st.write("Navigate using the sidebar")
# pages/2DataExplorer.py
import streamlit as st
import pandas as pd
st.title("Data Explorer")
uploaded
file = st.fileuploader("Upload CSV", type="csv")
if uploaded
file:
df = pd.readcsv(uploadedfile)
st.dataframe(df)
# pages/3ModelInference.py
import streamlit as st
st.title("Model Inference")
Model inference code here
2. Session State Management
import streamlit as st
Initialize session state
if 'counter' not in st.sessionstate:
st.sessionstate.counter = 0
if 'userdata' not in st.sessionstate:
st.sessionstate.userdata = {}
Update session state
def increment():
st.sessionstate.counter += 1
st.button("Increment", onclick=increment)
st.write(f"Counter: {st.sessionstate.counter}")
Store user data
name = st.textinput("Name", key="nameinput")
if name:
st.sessionstate.userdata['name'] = name
Access across pages
st.write(st.sessionstate.userdata)
3. Callbacks and Events
import streamlit as st
Callback function
def onsubmit():
st.sessionstate.submitted = True
st.sessionstate.result = f"Hello, {st.sessionstate.namefield}!"
Form with callback
with st.form("myform"):
st.textinput("Name", key="namefield")
submitted = st.formsubmitbutton("Submit", onclick=onsubmit)
if st.sessionstate.get('submitted'):
st.success(st.sessionstate.result)
Multiple callbacks
def clearform():
st.sessionstate.namefield = ""
st.sessionstate.submitted = False
st.button("Clear", onclick=clearform)
Caching and Performance
1. Cache Data
import streamlit as st
import pandas as pd
@st.cachedata(ttl=3600) # Cache for 1 hour
def loaddata(url):
"""Load and cache data"""
return pd.readcsv(url)
@st.cachedata(showspinner="Loading data...")
def expensivecomputation(df):
"""Expensive computation with spinner"""
# Simulate long computation
import time
time.sleep(5)
return df.describe()
Use cached functions
df = loaddata("https://example.com/data.csv")
stats = expensivecomputation(df)
2. Cache Resources
import streamlit as st
from transformers import pipeline
import joblib
@st.cacheresource
def loadmodel():
"""Cache ML model (singleton)"""
return joblib.load("model.joblib")
@st.cacheresource
def loadllm():