Quickly Generate Dynamic Web Apps for Machine Learning Projects

Quickly Generate Dynamic Web Apps for Machine Learning Projects

1. Streamlit

In one sentence, Streamlit is a library that allows you to write web apps in Python, making it easy to dynamically showcase your machine learning projects.

Advantages

  • You don’t need to know HTML, CSS, JS, etc.; you can write web apps using pure Python.
  • Includes commonly used web components: text boxes, buttons, radio buttons, checkboxes, dropdowns, multimedia (images, videos), and file uploads.

Application Scenarios

  • You can dynamically explore data.
  • You can easily showcase your machine learning results dynamically (can be compared with Jupyter Notebook).

https://github.com/streamlit/streamlit

2. Installation

pip install streamlit
streamlit hello

# Start web app
# streamlit run [filename]
streamlit run app.py

# You can now view your Streamlit app in your browser.
# Local URL: http://localhost:8501

3. Introduction to Basic Components

3.1 Layout

Typically, web layouts use layout CSS, such as the 12-column grid system in Bootstrap; Streamlit has at most two columns, usually one. You can add a sidebar using st.sidebar, which can often serve as a menu for selecting control operations. In a vertical structure, Streamlit lays out in order from top to bottom according to the code sequence.

import streamlit as st
import numpy as np
import time
import pandas as pd
import datetime
# Sidebar
st.sidebar.title('Menu Sidebar')
add_selectbox = st.sidebar.selectbox(
    "This is a dropdown, please choose?",
    ("1", "Home 2", "Mobile 2")
)
# Main Column
st.title('Steamlit Machine Learning Web App')

Quickly Generate Dynamic Web Apps for Machine Learning Projects

3.2 Text

Streamlit provides many text display commands and supports markdown syntax.

st.header('1. Text Display')
st.markdown('Streamlit is **_really_ cool**.')
st.text('This is some text.')
st.subheader('This is a subheader')
st.write("st.write can write many things!")
st.warning('This is a warning')

3.3 Form Controls

Streamlit provides a rich set of form controls, such as buttons, radio buttons, checkboxes, dropdowns, text boxes, and file uploads. Usage is summarized as follows:

  • The function call defines the displayed control, and the return value indicates whether it was triggered, or returns the result; for example, for a button, st.button('Say hello') defines a button, if pressed, it returns True, otherwise False.
st.markdown('- Button')
if st.button('Say hello'):
    st.write('Why hello there')

st.markdown('- Radio Button')
genre = st.radio(
     "What do you like?",
    ('Comedy', 'Drama', 'Documentary'))

st.write('You chose:', genre)
 
st.markdown('- Checkbox')    
agree = st.checkbox('I agree')
if agree:
    st.write('Thank you for agreeing')

st.markdown('- Dropdown') 
option = st.selectbox(
    'What is your preferred contact method?',
   ('Email', 'Home phone', 'Mobile phone'))

st.write('You chose:', option)

st.markdown('- Multi-select Dropdown') 
options = st.multiselect(
    'What are your favorite colors',
    ['Green', 'Yellow', 'Red', 'Blue'],
    ['Yellow', 'Red'])

st.write('You chose:', options)

st.markdown('- Slider') 
values = st.slider(
    'Select a range of values',
    0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)

st.markdown('- Text Input') 
title = st.text_input('Movie title', 'Life of Brian')
st.write('The current movie title is', title)

txt = st.text_area('Text to analyze', '''
    It was the best of times, it was the worst of times, it was
    the age of wisdom, it was the age of foolishness, it was
    the epoch of belief, it was the epoch of incredulity, it
    was the season of Light, it was the season of Darkness, it
    was the spring of hope, it was the winter of despair, (...)
    ''')

st.markdown('- Date and Time')
d = st.date_input(
    "Birthday",
    datetime.date(2019, 7, 6))
st.write('Your birthday is:', d)

t = st.time_input('Alarm', datetime.time(8, 45))
st.write('The alarm is at:', t)

st.markdown('- File Upload')
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
    data = pd.read_csv(uploaded_file)
    st.write(data)

Quickly Generate Dynamic Web Apps for Machine Learning Projects

3.4 Images

Common image libraries are supported, and images can be displayed using st.image.

import cv2
img = cv2.imread('sunrise.jpg')
st.image(img[...,::-1], caption='Sunrise by the mountains',
        use_column_width=True)

3.5 Charts

  • Supports displaying charts from pandas DataFrames (line charts, area charts, and bar charts).
st.subheader('4.1 DataFrame Charts')
@st.cache(persist=True)
def get_data():
    df = pd.DataFrame(
    np.random.randn(200, 3),
    columns=['a', 'b', 'c'])
    return df
df = get_data()
# st.table(df)
st.dataframe(df) 
st.line_chart(df)
st.area_chart(df)
st.bar_chart(df)
  • Also supports displaying charts from matplotlib, which you should be familiar with.
plt.plot(df.a, df.b)
st.pyplot()

Quickly Generate Dynamic Web Apps for Machine Learning Projects

3.6 Caching

In Streamlit, data caching is done using the st.cache decorator, which is applied to functions. The benefit of caching is to avoid reloading data every time the page is refreshed.

@st.cache(persist=True)
def get_data():
    df = pd.DataFrame(
    np.random.randn(200, 3),
    columns=['a', 'b', 'c'])
    return df

4. Dynamic Data Demo

import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Sidebar
st.sidebar.title('Please select filter conditions')
time = st.sidebar.time_input('Greater than time', datetime.time(1, 0))

values = st.sidebar.slider(
    'Speed',
    0.0, 200.0, (25.0, 75.0))
# Main Column
st.title('Data Exploration')
@st.cache(persist=True)
def get_data():
    file = './7000.csv'
    return pd.read_csv(file, header=0)
data = get_data()
# print(values)
display_data = data[data['time'] > str(time)]
display_data = display_data[(display_data['speed'] > values[0]) & (display_data['speed'] < values[1])]
st.line_chart(display_data[['Direction', 'Speed']])

Quickly Generate Dynamic Web Apps for Machine Learning Projects

5. Machine Vision Project Demo

This example uses face detection to demonstrate the presentation of a machine vision project.

  • Function: Upload an image, detect the face frame.
  • The face detection algorithm comes from the MTCNN algorithm in the facenet project https://github.com/davidsandberg/facenet/tree/master/src/align.
  • The layout is a left-right layout, with the left side for uploading and the right side for display.
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import time
import pandas as pd
import datetime
import cv2
from PIL import Image
import io
from face_detect.mtcnn_tf import MTCNN

# Sidebar
st.sidebar.title('Please upload a photo to start detection')
uploaded_file = st.sidebar.file_uploader("", type="jpg")

# Main Column
st.title('Face Detection')
@st.cache()
def init_model():
    mtcnn = MTCNN()
    return mtcnn

detect = init_model()
if uploaded_file is not None:
    # print(uploaded_file)
    data = np.array(Image.open(io.BytesIO(uploaded_file.read())))
    _, bboxs, _, _ = detect.run(data, detect_multiple_faces=True, margin=0)
    # display bbox and landmarks
    for idx, landmark in enumerate(landmarks):
        bbox = bboxs[idx]
        cv2.rectangle(data, (bbox[1], bbox[0]),
                      (bbox[3], bbox[2]), (0, 2255, 0), 2)
    st.image(data, caption='image', use_column_width=False)

Quickly Generate Dynamic Web Apps for Machine Learning Projects

6. Summary

Isn’t it convenient? You can build a web app to showcase your project in no time. I hope this helps you; get started!

  • Remember to use caching for data @st.cache().
  • Streamlit supports matplotlib.
  • Streamlit has beautiful form controls, and the return value of functions is the triggered value.
  • Streamlit supports markdown.

The official provides other complex demos (it is recommended to encapsulate business using functions, this article mainly illustrates functionality using a more intuitive approach).

  • https://github.com/streamlit/demo-face-gan
  • https://github.com/streamlit/demo-self-driving

Author Bio: Wedo Experimenter, Data Analyst; loves life and writing.

Support the Author

Quickly Generate Dynamic Web Apps for Machine Learning Projects

The Python Chinese Community, as a decentralized global technical community, aims to become the spiritual tribe of 200,000 Python Chinese developers globally. It currently covers major mainstream media and collaboration platforms, establishing extensive connections with well-known companies and technical communities such as Alibaba, Tencent, Baidu, Microsoft, Amazon, Open Source China, and CSDN, with tens of thousands of registered members from more than a dozen countries and regions. Members come from government agencies, research institutions, financial institutions, and well-known companies both domestically and internationally, represented by the Ministry of Industry and Information Technology, Tsinghua University, Peking University, Beijing University of Posts and Telecommunications, the People’s Bank of China, the Chinese Academy of Sciences, CICC, Huawei, BAT, Google, Microsoft, etc., with nearly 200,000 developers following across all platforms.

Quickly Generate Dynamic Web Apps for Machine Learning Projects

Recommended Reading:
Understanding Common Caching Issues Under High Concurrency
Developing DApps Based on Ethereum Smart Contracts with Django
Understanding Python Distributed Task Queue Celery
5-Minute Explanation of Chained Calls in Python
Creating a Bitcoin Price Alert Application with Python

Quickly Generate Dynamic Web Apps for Machine Learning Projects

▼ Click to become a community member. If you like it, give it a thumbs up! Click to see!Quickly Generate Dynamic Web Apps for Machine Learning Projects

Leave a Comment