Deploy ML Models with Streamlit - Manojkumar Chandrasekar

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:

Copy

Copy

import streamlit as st

st.title("Test")

Magic

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

Copy

Copy

Explain"""
# 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.

Copy

Copy

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

Data Elements

  1. JSON

    Copy

    Copy

      st.json(dict_or_json_obj)
    
  2. DataFrame

    Copy

    Copy

      st.dataframe(df)
    
  3. Table

    Copy

    Copy

      st.table(df)
    
  4. Metrics

    Copy

    Copy

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

Input Widgets

  1. Text Input

    Copy

    Copy

      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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

     Explain 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

    Copy

    Copy

     Explain 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

    Copy

    Copy

     Explain 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

    Copy

    Copy

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

    Copy

    Copy

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

Layouts

  1. Columns

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

     Explain 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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

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

    Copy

    Copy

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

Control Flow

  1. Forms

    Copy

    Copy

     Explain 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

    Copy

    Copy

      st.rerun()
    
  3. Stop Execution

    Copy

    Copy

      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:

Copy

Copy

Explain[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.

Copy

Copy

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.

    Copy

    Copy

     Explain 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)

    Copy

    Copy

     Explain @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.

    Copy

    Copy

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

Execution

To run the file, run:

Copy

Copy

$ streamlit run app.py

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

0
Subscribe to my newsletter

Read articles from Manojkumar Chandrasekar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manojkumar Chandrasekar
Manojkumar Chandrasekar