Streamlit Python Crash Course

Streamlit Python Tutorial(Crash Course)

In this crash course we will be learning about the Streamlit framework, a very powerful framework for building Machine Learning and Data Science tools and apps. Streamlit allows you to convert your normal python code into beautiful UI which is quite easy and very interactive.

You can do more with as little code as possible. Let us see how to work with streamlit.

The basic structure of our tutorial we be as follows;

  • How to Install Streamlit.
  • Working with Text as title,header,sub-header,text,markdown
  • Working with Colorful Text and Error Messages
  • Widget: Checkbox,Selectbox,Radio button,etc
  • How to receive user input and process them with streamlit?
  • Working with media files eg images,audio,video
  • Doing Plots and Displaying DataFrames,Tables,etc
  • Working with function
  • How to do sidebars in streamlit.

Let us begin.

Installation

To install streamlit, you can either work on your local system or in a virtual environment.

pip install streamlit

Or if you want to use it in a virual environment like pipenv.

pipenv install streamlit

After installation you can then use the CLI to run your app and display it in your default browser on localhost port(eg localhost:8501)

To run your app, you can use

streamlit run app.py

or with pipenv

pipenv run streamlit run app.py
Working with Text

First of all let us import our streamlit in our app.py

import streamlit as st

Then you can do the various aspects

import streamlit as st

# Text/Title
st.title("Streamlit Tutorials")

# Header/Subheader
st.header("This is a header")
st.subheader("This is a subheader")

# Text
st.text("Hello Streamlit")

# Markdown
st.markdown("### This is a Markdown")
Working with Colorful Text and Error Messages
st.success("Successful")

st.info("Information!")

st.warning("This is a warning")

st.error("This is an error Danger")

st.exception("NameError('name three not defined')")
Getting Help Info About Python
# Get Help
st.help(range)
Widget: Checkbox,Selectbox,Radio button,etc

Using widget in streamlit

# Checkbox
if st.checkbox("Show/Hide"):
	st.text("Showing or Hiding Widget")


# Radio Buttons
status = st.radio("What is your status",("Active","Inactive"))

if status == 'Active':
	st.success("You are Active")
else:
	st.warning("Inactive, Activate")

# SelectBox
occupation = st.selectbox("Your Occupation",["Programmer","DataScientist","Doctor","Businessman"])
st.write("You selected this option ",occupation)


# MultiSelect
location = st.multiselect("Where do you work?",("London","New York","Accra","Kiev","Nepal"))
st.write("You selected",len(location),"locations")

# Slider
level = st.slider("What is your level",1,5)


# Buttons
st.button("Simple Button")

if st.button("About"):
	st.text("Streamlit is Cool")
How to receive user input and process them with streamlit?

This is the most input aspect for the end user. How do you receive the users input and do something with it. You can use the st.text_input() to enable you achieve such a functionality.

 

# Receiving User Text Input
firstname = st.text_input("Enter Your Firstname","Type Here..")
if st.button("Submit"):
	result = firstname.title()
	st.success(result)


# Text Area
message = st.text_area("Enter Your message","Type Here..")
if st.button("Submit"):
	result = message.title()
	st.success(result)

# Date Input
import datetime
today = st.date_input("Today is",datetime.datetime.now())

# Time
the_time = st.time_input("The time is",datetime.time())
Working with media files eg images,audio,video
# Images
from PIL import Image
img = Image.open("example.jpeg")
st.image(img,width=300,caption="Simple Image")


# Videos
vid_file = open("example.mp4","rb").read()
# vid_bytes = vid_file.read()
st.video(vid_file)

# Audio
audio_file = open("examplemusic.mp3","rb").read()
st.audio(audio_file,format='audio/mp3')

 

Using the Write Function For More

The st.write() allows us to do more ,not just out put text but also python functions,object,etc

# Writing Text/Super Fxn
st.write("Text with write")

st.write(range(10))

 

Displaying Raw Code and JSON

In case you want to display the raw preformatted code you can use the st.code() or st.echo()

# Displaying Raw Code
st.text("Display Raw Code")
st.code("import numpy as np")

# Display Raw Code 
with st.echo():
# This will also show as a comment
import pandas as pd 
df = pd.DataFrame()

 

 Displaying JSON
# Displaying JSON
st.text("Display JSON")
st.json({'name':"Jesse",'gender':"male"})
Displaying Progressbars,Spinners and Balloons
# Progress Bar
import time
my_bar = st.progress(0)
for p in range(10):
    my_bar.progress(p + 1)


# Spinner
with st.spinner("Waiting .."):
     time.sleep(5)
     st.success("Finished!")


# Balloons
st.balloons()
Working with Data Science (DataFrame,Plot,Tables,etc)

Streamlit has features for working directly with dataframes and plot. You can create nice plot with the

st.pyplot() ,st.line_chart(),st.altair_chart() and more visualizations. You can check the docs for more

# Plot
st.pyplot()

# DataFrames
st.dataframe(df)

# Tables
st.table(df)
Showing Sidebars

With streamlit you can create sidebars with ease. For now you can use any of the functions except st.write,st.echo,st.code with the sidebar method.

You can just add sidebar to the normal methods as below

# SIDEBARS
st.sidebar.header("About")
st.sidebar.text("This is Streamlit Tut")

 

Working with Functions

You can also work with functions and classes in streamlit like how you do any python work. To improve the speed and performance of your functions you can use the @st.cache to hide and cache data.

# Normal Function
def run_fxn():
    return range(100)

st.write(run_fxn())

# To Improve Performance/Speed via caching
@st.cache
def run_fxn():
    return range(100)

st.write(run_fxn())

These are some of the various features and methods of streamlit

You can check the video tutorial of the entire  procedure here

Thanks For Your Time

Jesus Saves

By Jesse E.Agbe(JCharis)

 

Leave a Comment

Your email address will not be published. Required fields are marked *