StreamLit - Data Scientists tool for developing web apps
- StreamLit is a tool for Data Scientists and Machine Learning Engineers to create the front end of the web application.
- StreamLit is a wrapper around JavaScript, HTML, and CSS.
- It helps developers with no expertise in JavaScript, HTML, and CSS create interactive web-based front ends for the models.
Also, Check out our Article on:
End-to-End Machine Learning using Streamlit
Pros and Cons of Streamlit
Pros:
- Interactive
- Customizable, and does not require any front end experience.
- Deployment is easy
- Active Community
Cons:
- The front-end interface is fixed, and developers cannot adjust the position of controls.
- Early stages of development.
Getting Started with StreamLit
→ Downloading StreamLit
StreamLit is a Python package and can be downloaded using the pip command.
pip install streamlit
→ Running the app.py file
once you create the .py file go to the directory in CLI and run it in CLI using :
streamlit run app.py
My app name is ‘streamlit-app.py’
After running the app, it will open in as localhost.
Click on the 3 lines at right and select on always rerun or simply write a code and the option will appear, then you can see changes being updated directly to your web app
Setting up the web App
We will use our script named app.py to write the commands. But first, we need to import our streamlit package.
import streamlit as st
import pandas as pd
- Title:
Let’s start with the title of the web app, use your python script to write the codes.
st.title("First StreamLit App")
- Header:
st.header("Abhigyan's App")
- Subheader:
st.subheader("I am a Data Science Researcher at INSAID")
- Text and markdown:
st.text("INSAID: India’s No.1 Online School to Learn Data Science & AI")
st.markdown("[INSAID](https://www.insaid.co/)")
st.markdown()-
It is similar to that of GitHub markdown functionalities. You can check out all the functionalities from this link.
Streamlit also has a function:
st.write()
write() has some unique properties:
- You can pass in multiple arguments, all of which will be written.
- Its behaviour depends on the input types as follows.
- It returns None, so it’s “slot” in the App cannot be reused.
example:
st.write(pd.DataFrame({'A': [1, 2, 3, 4],
'B': [5, 6, 7, 8]}))
Now that the basic, Text part is done, we need to provide interactive buttons too.
Interactive widgets
- Button:
Returns a boolean value
st.button(label)
label → text displayed on the button
example:
if st.button("Start"):
st.text("Hi! Welcome to the Web App")
- Checkbox:
Returns a boolean value.
st.checkbox(label, value = False)
label → text displayed on the check box
value → Preselect checkbox or not.
example:
yes = st.checkbox("Move Forward")if yes:
st.text("Great Choice!")
- Radio:
Returns any option selected.
st.radio(label, options, index = 0)
label → text to explain to the user what the radio is for.
options → accept list or tuple object of the labels for the options.
index → Preselect the object, any integer value can be passed depending on what the preselect yo want to do.
example:
options = ['Beginner', 'Intermediate', 'Master', 'GODLY']
genre = st.radio("How skilled are you at Data Science", options, index = 2)if genre == 'Beginner':
st.text("Keep pushing yourself, if you want a boost check out:")
st.markdown("[INSAID](https://www.insaid.co/)")
elif genre == 'Intermediate':
st.text("Keep learning and you will succeed.")
st.markdown("[INSAID](https://www.insaid.co/)")
elif genre == 'Master':
st.write("Awesome! *Master Shifu* :sunglasses:")
elif genre == 'GODLY':
st.write("Welcome to my webpage")
else:
st.write("You didn't select anything")
- Selectbox:
Returns any option selected
st.selectbox(label, options, index = 0)
label → text to explain to the user what the radio is for.
options → accept list or tuple object of the labels for the options.
index → Preselect the object, any integer value can be passed depending on what the preselect yo want to do.
example:
exp = ["0-1", "2-5", "6-11", "> 12"]
option = st.selectbox("What is your experience level", exp)st.write("You have a experience of:", option)
- Multiselect:
Returns a list of options selected.
st.multiselect(label, options, default = None)
label → text to explain to the user what the Multiselect is for.
options → accept list or tuple object of the labels for the options.
default → list of default values.
example:
mem = ['Father', 'Mother', 'Son', 'Daughter', 'Grand Mother',
'Grand Father']
option = st.multiselect("How many members in your family", mem,
['Father, 'Mother'])st.write('You selected:')
for i in option:
st.write(i)
- Slider:
Returns the current value of the slider widget.
This supports int, float, date, time, and DateTime types.
st.slider(label, min_value, max_value, value, step, format)
label → text to explain to the user what the slider is for.
min_value → Minimum value of the range that is to be provided, by default it is 0.
max_value → Maximum vale of the range that is to be provided, by default it is 100.
step → Stepping interval between values.
format → formatter for int/float supports: %d %e %f %g %i
example:
age = st.slider("How old are you?", 6, 100, 1)
st.write("I am", age, "years old")
Text input:
Returns str type values of the text input widget.
st.text_input(label, value, max_chars, type)
label → text to explain to the user what the text input is for.
value → The text value of the widget that is cast to str.
max_chars → maximum characters for a text.
type → if set to “default” it accepts regualar texts, if set to “password” it masks text.
example:
comp = st.text_input("Your Company name")
st.write("your comany name is", comp)
- Text Area:
Returns str of the current value of the text input.
st.text_area(label, value, height, max_chars)
label → text to explain to the user what the text input is for.
value → The text value of the widget that is cast to str.
height → Desired height of the box.
max_chars → maximum characters for a text.
example:
text = st.text_area("Write about Yourself")
st.write('About you:', text)
Note: In order to include widgets at the side of the webpage. Use
“st.sidebar._______()” fill the blank space with the widget name
Displaying Charts
Streamlit supports many visualization frameworks like matplotlib, Vega lite, deck.gl(maps and 3D), and many more.
Charts like line charts and area charts are native to streamlit.
- Line Chart:
This chart is built around at.altair_chart(). The difference between them is that it is easier to plot as it uses data’s own column and indices to figure out the chart’s spec.
st.line_chart(data, width, height, use_container_width)
data → pandas DataFrame, NumPy array, dictionary.
width → width of the chart
Height → Height of the chart
use_container_width → If True, chart width is set as column width.
example:
chart_data = pd.DataFrame(np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
Click on the 3 dots that appear on the right side of the graph to find multiple options to save the graph as an image.
- Area chart:
st.area_chart(data, width, height, use_container_width)
data → pandas DataFrame, NumPy array, dictionary.
width → width of the chart
Height → Height of the chart
use_container_width → If True, chart width is set as column width.
example:
chart_data = pd.DataFrame(np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.area_chart(chart_data)
- Similarly you can plot bar chart by using the function st.bar_chart().
- Pyplot:
It helps with using matplotlib to plot figures.
st.pyplot(fig, clear_figure)
fig → The figure that needs to be plotted.
clear_figure → If True, the figure will be cleared after being rendered. If False, the figure will not be cleared after being rendered. If left unspecified, we pick a default based on the value of fig.
example:
import matplotlib.pyplot as plt
import numpy as np
arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
st.pyplot(fig)
Display Media
Now, that we saw how to plot in streamlit. Let’s move forward and see how we can display media on our web page.
Embedding images, videos and audio files in streamlit is easy and can be done directly using the functions.
- Image:
It will display an image or list of images.
st.image(image, caption, width, use_column_width, clamp, channels, output_format)
image →
* Monochrome image of shape (w,h) or (w,h,1)
* A colour image of shape (w,h,3) OR an RGBA image of shape (w,h,4)
* A URL to fetch the image from OR an SVG XML string like <svg xmlns=…</svg>
* A list of one of the above, to display multiple images.
caption → Displays the caption of the image. When multiple images are pushed captions should be in the list.
width → Width of the image.
use_column_width → If True, image width is set as column width.
clamp → It True, the pixel values are clamped to a valid range.
channels → If an image is an nd.array, this parameter denotes the format used to represent colour information. For images coming from libraries like OpenCV you should set this to ‘BGR’
output_format → This parameter specifies the format to use when transferring the image data.
example:
st.image(image, caption, use_column_width = True)
These were the few basic functions in streamlit, that helps create amazing interactive web apps that can be shared.
Sharing web apps
After the app is built, we can share it in 3 easy steps:
- Push your app in your GitHub repository, with the requirements.txt will all the packages that need to be installed for a smooth flow of the web app.
- Create an account in share.streamlit.io
- Paste your GitHub repo’s URL after clicking on ‘Deploy an app’.
In the next part, we will have a complete walkthrough of the end-to-end model building and deployment using streamlit.
Also, Check out our Article on:
Follow us for more upcoming future articles related to Data Science, Machine Learning, and Artificial Intelligence.
Also, Do give us a Clap👏 if you find this article useful as your encouragement catalyzes inspiration for and helps to create more cool stuff like this.