# Deploy ML Models with Streamlit

[Streamlit](http://github.com/streamlit/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:

[![](https://cdn.hashnode.com/res/hashnode/image/upload/v1713929603148/6636ecdf-057e-4072-984c-026f85b8ccbc.png align="center")](https://skin-cancer-check.streamlit.app/)

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

# [Creating](https://github.com/Siddhesh-Agarwal/Skin-Cancer-Detection)

[To begin, create a `app.py` file or use a template. In your `app.py` file simply type:](https://github.com/Siddhesh-Agarwal/Skin-Cancer-Detection)

```python
import streamlit as st

st.title("Test")
```

## Magic

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

```python
"""
# 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.

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

### Data Elements

1. JSON
    
    ```python
    st.json(dict_or_json_obj)
    ```
    
2. DataFrame
    
    ```python
    st.dataframe(df)
    ```
    
3. Table
    
    ```python
    st.table(df)
    ```
    
4. Metrics
    
    ```python
    st.metric("Temperature", "39°C", "1°C")
    st.metric("Wind", "12 kmph", "-8%")
    ```
    

### Input Widgets

1. Text Input
    
    ```python
    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
    
    ```python
    age = st.number_input("Enter your age", min_value=18, max_value=120)
    st.write("Your Age is:", age)
    ```
    
3. Slider
    
    ```python
    age = st.slider("Enter your age", min_value=18, max_value=120)
    st.write("Your Age is:", age)
    ```
    
4. Date Input
    
    ```python
    from datetime import date
    
    bday = st.date_input("When's your birthday", date(2019, 7, 6))
    st.write('Your birthday is:', bday)
    ```
    
5. Button
    
    ```python
    if st.button("Click me"):
        st.write("Well Done")
    ```
    
6. Radio
    
    ```python
    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
    
    ```python
    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
    
    ```python
    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
    
    ```python
    toggle = st.toggle("Display Dataframe")
    if toggle:
        st.write(df)
    ```
    
10. File Uploader
    
    ```python
    file = st.file_uploader("Upload a file")
    ```
    

### Layouts

1. Columns
    
    ```python
    cols = st.columns(2)
    with cols[0]:
        st.write("This is Column 1")
    with cols[1]:
        st.write("This is Column 2")
    ```
    
2. Container
    
    ```python
    c = st.container()
    st.write("Line 3")
    c.write("Line 1")
    c.write("Line 2")
    ```
    
3. Expander
    
    ```python
    with st.expander("Click to Open"):
        st.write("Here is some more content")
    ```
    
4. Sidebar
    
    ```python
    with st.sidebar:
        st.write("This will be displayed in the sidebar")
    ```
    
5. Tabs
    
    ```python
    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
    
    ```python
    with st.spinner("Loading..."):
        perform_task()
    ```
    
2. Toast
    
    ```python
    st.toast("Process completed successfully!")
    ```
    
3. Balloons / Snow
    
    ```python
    st.balloons()
    st.snow()
    ```
    
4. status boxes
    
    ```python
    st.success("Success")
    st.info("Information")
    st.warning("Warning")
    st.error("Error")
    ```
    

### Control Flow

1. Forms
    
    ```python
    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
    
    ```python
    st.rerun()
    ```
    
3. Stop Execution
    
    ```python
    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:

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

> Learn More: [config.toml - Streamlit Docs](https://docs.streamlit.io/develop/api-reference/configuration/config.toml)

## [Secrets](https://docs.streamlit.io/develop/api-reference/configuration/config.toml)

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

```ini
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.
    
    ```python
    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)
    
    ```python
    @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.
    
    ```python
    model = load_model()
    st.write(model.predict(img))
    ```
    

---

# Execution

To run the file, run:

```sh
$ streamlit run app.py
```

> **NOTE**: You can learn about the different components in streamlit through their [official docs](https://docs.streamlit.io/).
