Complete Streamlit Advanced Tutorial: Build Production-Ready ML Apps

# Tutorial Lengkap Streamlit Advanced: Build Production-Ready ML Apps Streamlit adalah library Python yang powerful untuk membangun aplikasi web interaktif untuk machine learning dan data science. Tu...

By Ruby Abdullah · · tutorial
StreamlitML AppDashboardPythonWeb DevelopmentMachine Learning

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

Use Cases:
  • 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.setpageconfig(

pagetitle="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")

uploadedfile = st.fileuploader("Upload CSV", type="csv")

if uploadedfile:

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():

Related Articles

Reflex Tutorial: Building Full-Stack Web Apps in Pure Python

Reflex: Membangun Aplikasi Web Full-Stack dengan Python Murni Reflex memungkinkan Anda membangun aplikasi web lengkap — ...

SHAP Tutorial: Explainable AI and Model Interpretability

SHAP - Panduan Praktis Explainable AI dan Interpretabilitas Model Model machine learning makin sering dipakai untuk meng...

PyOD Tutorial: Anomaly and Outlier Detection in Python

Deteksi Anomali di Python dengan PyOD: Panduan Praktis Sebagian besar dataset di dunia nyata mengandung sebagian kecil d...

spaCy Tutorial: Industrial-Strength NLP in Python

spaCy: NLP Kelas Industri di Python spaCy adalah pustaka open-source untuk pemrosesan bahasa alami (NLP) yang dirancang ...