# Explain the python streamlit framework in detail, which is used to build a beautiful data visualization web app, and practice making a garbage classification app

2022-02-01 11:32:30

Today, I'll explain a Python library Streamlit, It can be built for machine learning and data analysis web app. Its advantage is that it's easy to get started 、 pure Python code 、 High development efficiency 、UI Exquisite .

The picture above is used Streamlit The effect of building an automatic driving model demo, On the left is the parameters of the model , On the right is the effect of the model . By adjusting the parameters on the left , The model on the right will respond in real time .

From this we can see that , For interactive data visualization requirements , You can consider using Streamlit Realization . Especially in learning 、 During the work report , The effect of using it is much better than PPT.

because Streamlit Provides many front-end interactive components , So you can also use it to do some simple web application . Today we will also use it for garbage classification web app.

We used Streamlit I've done two app,《 Plant recognition app》 and 《 Animal identification app》. But it just used Streamlit A small part of the function . Today we will follow Streamlit Official document , Explain it in detail .

## 1. Text component

I'm using Python 3.8 Environmental Science , perform pip install streamlit install . Perform... After installation streamlit hello Check if the installation is successful .

So let's see Streamlit The most basic text component .

Text component is used to display various types of text content on Web pages .Streamlit Can display plain text 、Markdown、 title 、 Code and LaTeX The formula .

import streamlit as st

# markdown
st.markdown('Streamlit is **_really_ cool**.')

#  Set page title
st.title('This is a title')

#  Show the first level title

#  Show secondary title

#  Show me the code , It has a highlight effect
code = '''def hello(): print("Hello, Streamlit!")'''
st.code(code, language='python')

#  Pure text
st.text('This is some text.')

# LaTeX  The formula
st.latex(r''' a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} = \sum_{k=0}^{n-1} ar^k = a \left(\frac{1-r^{n}}{1-r}\right) ''')
Copy code 

The above is Streamlit Supported text presentation components , Code storage my_code.py In file . After coding , perform streamlit run my_code.py ,streamlit It will start web service , Load the specified source file .

After starting , You can see that the command line prints the following information

streamlit run garbage_classifier.py

Local URL: http://localhost:8501
Network URL: http://192.168.10.141:8501
Copy code 

Access in browser http://localhost:8501/ that will do .

When the source code is modified , No need to restart the service , Click the refresh button on the page to load the latest code , Operation and debugging are very convenient .

## 2. Data components

dataframe and table Components can display tables .

import streamlit as st
import pandas as pd
import numpy as np
df = pd.DataFrame(
np.random.randn(50, 5),
columns=('col %d' % i for i in range(5)))

#  Interactive table
st.dataframe(df)
#  Static tables
st.table(df)
Copy code 

dateframe and table Is the difference between the , The former can interact on the form （ Such as ： Sort ）, The latter is just a static display . The data types they support to display include pandas.DataFrame、pandas.Styler、pyarrow.Table、numpy.ndarray、Iterable、dict.

metric Component is used to show the change of indicators , Data analysis is often used .

st.metric(label="Temperature", value="70 °F", delta="1.2 °F")
Copy code 

value The parameter represents the current indicator value ,delta The parameter represents the difference from the previous value , The upward green arrow represents the value compared to the previous value , It's rising , On the contrary, the downward red arrow indicates that it is down compared with the previous value . Of course, the rise and fall color can be through delta_color Parameters to control .

json Components are used to show json Type data

st.json({
'foo': 'bar',
'stuff': [
'stuff 1',
'stuff 2',
],
})
Copy code 

Streamlit Will json Formatting Data , The display is more beautiful , And provide interaction , It can be expanded 、 Retract json Child nodes of .

## 3. Chart components

Streamlit The chart component of consists of two parts , Some are native components , The other part is rendering third-party libraries .

Native components contain only 4 A chart ,line_chart、area_chart 、bar_chart and map, Show the line chart separately 、 Area map 、 Histograms and maps .

chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])

st.line_chart(chart_data)
Copy code 

The above is line_chart An example of , Other charts are used in a similar way .

Streamlit The chart has few parameters that can be set , In addition to data sources , The rest can only set the width and height of the chart .

although Streamlit Fewer native charts , But it can put other Python The diagram of the visualization library is shown in Streamlit On the page . Supported visualization libraries include ：matplotlib.pyplot、Altair、vega-lite、Plotly、Bokeh、PyDeck、Graphviz.

With matplotlib.pyplot For example , Use as follows ：

import matplotlib.pyplot as plt

arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)

st.pyplot(fig)
Copy code 

Write directly with matplotlib.pyplot equally , Just call at the end of the presentation st.pyplot You can show the chart Streamlit On the page . other Python The library is used in a similar way .

## Input components

The three types of components we introduced earlier are output classes 、 Show class . For interactive pages , It is essential to accept user input .

Streamlit The input components provided are basic , We are all on the website 、 Move APP I often see . Include ：

• button： Button
• checkbox： Check box
• selectbox： Drop down radio box
• multiselect： Drop down the multiple selection box
• slider： Slider bar
• select_slider： Selection bar
• text_input： Text input box
• text_area： Text display box
• number_input： Digital input box , Support addition and subtraction buttons
• date_input： Date selection box
• time_input： Time selection box
• color_picker： Color selector

They contain some common parameters ：

• label： What is displayed on the component （ Such as ： The name of the button ）
• key： The current page uniquely identifies a component
• help： Place the mouse on the component to display the description information
• on_click / on_change： Components interact （ Such as ： Input 、 Click on ） Callback function after
• args： The parameters of the callback function
• kwargs： The parameters of the callback function

Let's say selectbox To demonstrate the use of input components

option = st.selectbox(
' A drop-down box ',
(' Option one ', ' Option 2 ', ' Option 3 '))

st.write(' I chose ：', option)
Copy code 

selectbox Show three options , And output the currently selected item （ The first... Is selected by default ）. When we select other options in the page drop-down , The entire page code will be re executed , But the selection status of the component Will remain in option in , therefore , call st.write The selected options will be output .

st.write It is also an output component , You can output strings 、DataFrame、 Various types of data such as ordinary objects .

The use of other components is similar , The component effect diagram is as follows ：

## 5. Multimedia components

Streamlit Defined image、audio and video Used to show pictures 、 Audio and video .

Can display local multimedia , Also through url Show network multimedia .

The usage is the same as the previous components , Garbage sorting in the back APP We will use image Components .

## 6. State component

The status component is used to show the user the running status of the current program , Include ：

• spinner： Wait for the prompt
• balloons： A balloon floats at the bottom of the page , Congratulations
• error： Display error message
• warning： Display alarm information
• info： Display general information
• success： Display success information
• exception： Display exception information （ Code error stack ）

The effect is as follows ：

## 7. Other content

Come here ,Streamlit I've basically finished introducing all the components of , The components are Streamlit Main content .

This section introduces other important contents , Including page layout 、 Control flow and cache .

The page layout . We wrote before Streamlit The components are displayed from top to bottom in the order of code execution ,Streamlit Provides 5 Species layout ：

• sidebar： Sidebar , Such as ： The picture at the beginning of the article , Model parameter selection on the left side of the page
• columns： A column of containers , In the same place columns Internal components , Display from left to right
• expander： Hidden information , Click to expand and display the details , Such as ： Show more
• container： Container containing multiple components
• empty： A container containing a single component

** control flow .** control Streamlit Application execution , Include

• stop： It can make Streamlit The application stops without executing down , Such as ： After the verification code passes , Then run down to show the follow-up content .
• form： Forms ,Streamlit After a component interacts, the page program will be re executed , Sometimes, you need to wait for a group of components to complete the interaction before refreshing （ Such as ： Log in and fill in the user name and password ）, At this point, you need to add these components to form in
• form_submit_button： stay form Use in , Submit Form .

** cache .** This is more critical , Especially students who do machine learning . Has just said , Streamlit After component interaction, the page code will be re executed , If the program contains some complex data processing logic （ Such as ： Read external data 、 Training models ）, It will cause the same data processing logic to be executed repeatedly for each interaction , This causes the page to take too long to load , Influence the experience .

By adding the cache, the results of the first processing can be stored in memory , When the program is re executed, it will read from memory , Without having to reprocess .

It's easy to use , Add... To the functions that need to be cached @st.cache A decorator is fine . We talked about... Two days ago Python Decorator .

DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/'
'streamlit-demo-data/uber-raw-data-sep14.csv.gz')

@st.cache
lowercase = lambda x: str(x).lower()
data.rename(lowercase, axis='columns', inplace=True)
data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
return data
Copy code 

## 8. refuse classification

Finally, explain the garbage classification APP Code for , Several types of components are introduced earlier in this paper APP There are involved .

The garbage classification model I use is Tianxing API , You can go www.tianapi.com/ Registered account , obtain appkey, Opening “ Image garbage classification ” Interface can .

The input of the interface is as follows ：

except key Outside , other 3 Two parameters need to use Streamlit Component implementation , The code is as follows ：

import base64

import requests
import streamlit as st
import pandas as pd
import numpy as np

" picture source ",
)

img_url = None

else:
img_url = st.sidebar.text_input(' picture url')

cls_mode = {' Strict mode ': 0, ' Fuzzy mode ': 1}
mode_name = st.sidebar.radio(' Classification patterns ', cls_mode)
mode = cls_mode[mode_name]
Copy code 

Used 3 Input components , because img and imgurl It's one of two , So we use the drop-down radio control to display only one component .

When you enter a picture , We want to show the pictures on the page

#  Request the results
img_base64 = None

img_base64 = base64_data.decode()

if img_url:
st.image(img_url, caption=' Network picture ')
Copy code 

Use image Multimedia component installation process . If it's a local picture , You need to turn it into base64 Encoded string .

Last , Request interface , Get the classification results

if img_base64 or img_url:
cls_res = get_img_cls_res(img_base64, img_url, mode)
lajitype_to_name = {0: ' Recyclable ', 1: ' Harmful Waste ', 2: ' Kitchen Waste ', 3: ' Other Waste ', 4: ' Can't recognize '}

if cls_res.status_code == 200:
cls_df = pd.DataFrame(cls_res.json()['newslist'])
cls_df[' classification '] = cls_df.index.astype(str) + '-' + cls_df['name'] + '-' + cls_df['lajitype'].apply(lambda x: lajitype_to_name[x])
cls_df[' Degree of confidence '] = cls_df['trust']
cls_df.set_index([" classification "], inplace=True)
print(cls_df)
st.bar_chart(cls_df[[' Degree of confidence ']])
else:
st.write(cls_res)
Copy code 

get_img_cls_res A function is a function that requests an interface

def get_img_cls_res(img_base64, img_url, mode):
url = 'https://api.tianapi.com/txapi/imglajifenlei/index'
'Content-Type': 'application/x-www-form-urlencoded'
}
body = {
'key': 'APPKEY',
'mode': mode
}

if img_base64:
body["img"] = img_base64
if img_url:
body['imgurl'] = img_url

return response
Copy code 

According to the returned data format , Put the data according to confidence （trust） Show it as a histogram

Official account Transcode reply “ refuse classification v2” Get all the code . Today's content basically puts Streamlit Finished. , You can refer to the official documents for details , I believe that after reading this tutorial , It's easy to look at the official documents .