Deploy ML Models with Streamlit

Deploy ML Models with Streamlit

ยท

4 min read

Streamlit is an open-source Python library that can make and deploy beautiful-looking web apps in a few minutes. It has been quite a handy tool for deploying ML models without creating API endpoints in Flask or FastAPI.

Today, I will talk about some streamlit functions I have used that could help you too! For Demo, this is what a streamlit app looks like:

Source: Siddhesh-Agarwal/Skin-Cancer-Detection: A web app to detect Skin cancer using pictures of moles and other marks on skin (github.com)

Creating

To begin, create a app.py file or use a template. In your app.py file simply type:

import streamlit as st

st.title("Test")

Magic

Anything written in the Python script between triple quotes (""")will be rendered as markdown text!

"""
# Heading 1
## Heading 2
### Heading 3

1. Ordered list 1
2. Ordered list 2
3. Ordered list 3
"""

Components

Write

Described as the "Swiss Army knife of Streamlit commands", `st.write()` is one of the most versatile functions to display any data type.

st.write("_Hello_ *World*")
st.write(df)

Data Elements

  1. JSON

     st.json(dict_or_json_obj)
    
  2. DataFrame

     st.dataframe(df)
    
  3. Table

     st.table(df)
    
  4. Metrics

     st.metric("Temperature", "39ยฐC", "1ยฐC")
     st.metric("Wind", "12 kmph", "-8%")
    

Input Widgets

  1. Text Input

     name = st.text_input("Enter you name")
     password = st.text_input("Enter the password", type="password")
     st.write(f"Your name is {name} and your password is {password}")
    
  2. Number Input

     age = st.number_input("Enter your age", min_value=18, max_value=120)
     st.write("Your Age is:", age)
    
  3. Slider

     age = st.slider("Enter your age", min_value=18, max_value=120)
     st.write("Your Age is:", age)
    
  4. Date Input

     from datetime import date
    
     bday = st.date_input("When's your birthday", date(2019, 7, 6))
     st.write('Your birthday is:', bday)
    
  5. Button

     if st.button("Click me"):
         st.write("Well Done")
    
  6. Radio

     food_items = ["Pizza ๐Ÿ•", "Burger ๐Ÿ”", "Spaghetti ๐Ÿ"]
     food = st.radio("What do you want to eat?", food_items)
     if food:
         st.write(f"You are eating {food}!")
    
  7. Select Box

     food_items = ["Pizza ๐Ÿ•", "Burger ๐Ÿ”", "Spaghetti ๐Ÿ"]
     food = st.selectbox("What do you want to eat?", food_items)
     if food:
         st.write(f"You are eating {food}!")
    
  8. Multiselect

     food_items = ["Pizza ๐Ÿ•", "Burger ๐Ÿ”", "Spaghetti ๐Ÿ"]
     food = st.multiselect("What do you want to eat?", food_items)
     if food:
         st.markdown(f"You are eating {', '.join(food)}!")
    
  9. Toggle

     toggle = st.toggle("Display Dataframe")
     if toggle:
         st.write(df)
    
  10. File Uploader

    file = st.file_uploader("Upload a file")
    

Layouts

  1. Columns

     cols = st.columns(2)
     with cols[0]:
         st.write("This is Column 1")
     with cols[1]:
         st.write("This is Column 2")
    
  2. Container

     c = st.container()
     st.write("Line 3")
     c.write("Line 1")
     c.write("Line 2")
    
  3. Expander

     with st.expander("Click to Open"):
         st.write("Here is some more content")
    
  4. Sidebar

     with st.sidebar:
         st.write("This will be displayed in the sidebar")
    
  5. Tabs

     tabs = st.tabs(["Milk", "Cookies"])
     with tabs[0]:
         st.write("You chose Milk ๐Ÿฅ›")
     with tabs[1]:
         st.write("You chose Cookies ๐Ÿช")
    

Status Elements

  1. Spinner

     with st.spinner("Loading..."):
         perform_task()
    
  2. Toast

     st.toast("Process completed successfully!")
    
  3. Balloons / Snow

     st.balloons()
     st.snow()
    
  4. status boxes

     st.success("Success")
     st.info("Information")
     st.warning("Warning")
     st.error("Error")
    

Control Flow

  1. Forms

     with st.form(key='some_form'):
         name = st.text_input("Name")
         age = st.number_input("Age")
         if st.form_submit_button("Submit"):
             st.balloons()
    
  2. Rerun

     st.rerun()
    
  3. Stop Execution

     st.stop()
    

Configuration

Streamlit allows the configuration of colour along with some other things. To customize, create a .streamlit/config.toml file. You can do something like this to change the classic black-and-white style to something more colourful:

[theme]
primaryColor="#F63366"
backgroundColor="#FCF2E5"
secondaryBackgroundColor="#F8E4C7"
textColor="#302730"

Learn More: config.toml - Streamlit Docs

Secrets

To manage secrets (like environment variables and API Keys), Streamlit has a custom solution. A special file (./.streamlit/secrets.toml) keeps all the secrets.

OPENAI_API_KEY="<OPENAI_API_KEY_HERE>"

Deployment

  1. The first step is to identify the input taken by the model and input those details.

     pic = st.file_uploader(
         label="Upload a picture",
         type=["png", "jpg", "jpeg"],
         accept_multiple_files=False,
         help="Upload a picture of a cat or dog",
     )
    
  2. The second step is to preprocess the image to fit the model (this preprocessing depends on your model.

  3. The next step is to load your model (TIP: cache the model to prevent loading time for subsequent runs)

     @st.cache_resource
     def load_model():
         model = tf.keras.models.load_model("./model/model.h5")
         return model
    
  4. Pass the processed image to the model and display the output.

     model = load_model()
     st.write(model.predict(img))
    

Execution

To run the file, run:

$ streamlit run app.py

NOTE: You can learn about the different components in streamlit through their official docs.

ย