[Streamlit] I hate JavaScript, so I make a web application only with Python

Front (SPA) Development Project I have two playing managers and a development leader, but I hate JavaScript to death. It's a script that runs on the browser, so it can't be helped, and async-await made it a lot more convenient, but I still don't like asynchronous processing.

Java, Python, and other languages I've touched for a certain period of time usually feel like "everyone is different and everyone is good", but I think I really hate it because only JavaScript doesn't.

By the way, I hate CSS more.

I think that building a machine learning model is often implemented in Python, but when it comes to making even a small demo app, the front side must be built in HTML, JavaScript, and CSS.

Jupyter Notebook may be an option, but it's less free-speech than a web app, and seeing code cells looks a bit messy.

Regardless of whether I dislike it or not, I think that there are quite a few people who have trouble with front development. ~~ ... are you there? ~~ The library called Streamlit that I touched during the holidays in July was extremely convenient, so this time I will try to make a web application with Python ** "only" ** using this!

What is Streamlit

A web application framework developed by Streamlit. It supports major graph libraries (and OpenCV), and as mentioned in HP, it is easy to make data visualization apps and AI demo apps with just Python. Can be built into. There is no need to embed HTML in your code.

Streamlit’s open-source app framework is the easiest way for data scientists and machine learning engineers to create beautiful, performant apps in only a few hours! All in pure Python. All for free.

Reference is substantial, and it takes just over an hour (with conception) from the time you start reading how to use it to the time you create the demo app that I will introduce. did not.

This time, we will visualize the number of infected people every day using the data of Tokyo Metropolitan Government New Coronavirus Infection Control Site.

Introduction

Install Streamlit. This time, matplotlib is also used for the graph library, so install it together.

After the installation is complete, check if you can see the demo page with the following command.

streamlit hello

The demo page will be launched at [http: // localhost: 8501 /](http: // localhost: 8501 /).

streamlit_hello.png

Visualization of table data

Get Daily Infected Persons Data and display the data frame. You can display the table by simply converting the read data into a DataFrame and plunging it into `st.write```. Processing that you do not want to execute each time, such as reading data, is cached by adding `@ st.cache```, and in the second and subsequent executions, the cache is used if there are no changes to arguments or external variables.


import streamlit as st
import pandas as pd
import requests

@st.cache
def get_covid_df(url):
    response_json = requests.get(url).json()
    df = pd.DataFrame(response_json['data'])
    return df

url = 'https://raw.githubusercontent.com/tokyo-metropolitan-gov/covid19/development/data/daily_positive_detail.json'
df_covid = get_covid_df(url)

"""
#COVID in Tokyo-19 Number of infected people
Tokyo Metropolitan Government New Coronavirus Infection Control Site[Github](https://github.com/tokyo-metropolitan-gov/covid19)Get data from
"""

st.write(df_covid)

Once you have done this, start the app with the following command.

streamlit run app.py

As with the installation, the app will be launched at [http: // localhost: 8501 /](http: // localhost: 8501 /).

01_table.png

You can also sort in ascending or descending order.

02_sorted.png

Try to draw a graph

Display the graph plotted using matplotlib. Basically the same as for table data, after drawing a graph with matplotlib, just insert the figure object into `` `st.write```.


import matplotlib.pyplot as plt
import matplotlib.dates as mdates

"""
#Number of infected people per day
"""


x = [
    datetime.datetime.strptime(diagnosed_date, '%Y-%m-%d')
    for diagnosed_date in df_covid['diagnosed_date'].values
]
y_count = df_covid['count'].values

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y_count)

xfmt = mdates.DateFormatter('%m/%d')
xloc = mdates.DayLocator(interval=20)

ax.xaxis.set_major_locator(xloc)
ax.xaxis.set_major_formatter(xfmt)
st.write(fig)

When you update the source, you will be asked if you want to rerun the code, so press Rerun.

03_source_change.png

Of the data acquired earlier, I was able to display a graph plotting the number of infected people.

04_matplotlib.png

Make it an interactive app using WEB UI

Up to this point, there is not much difference from visualizing with Jupyter, so we will implement an interaction that seems to be a WEB application.

After the data acquisition process, add the display process of the component that specifies the date range to narrow down the data frame. Add a UI component with ``` st. Component name`` for body and ``st.sidebar. Component name` `` for sidebar.


url = 'https://raw.githubusercontent.com/tokyo-metropolitan-gov/covid19/development/data/daily_positive_detail.json'
df_covid = get_covid_df(url)

diagnosed_date_list = df_covid['diagnosed_date'].values
str_maxdate = diagnosed_date_list[len(diagnosed_date_list)-1]
mindate = datetime.datetime.strptime(diagnosed_date_list[0], '%Y-%m-%d')
maxdate = datetime.datetime.strptime(str_maxdate, '%Y-%m-%d')

selected_date = st.sidebar.date_input(
    "Please enter the period you want to display",
    [mindate, maxdate],
    min_value=mindate,
    max_value=maxdate
)

str_startdate = selected_date[0].strftime('%Y-%m-%d')
str_enddate = selected_date[1].strftime(
    '%Y-%m-%d') if len(selected_date) == 2 else str_maxdate

"""
#COVID in Tokyo-19 Number of infected people
Tokyo Metropolitan Government New Coronavirus Infection Control Site[Github](https://github.com/tokyo-metropolitan-gov/covid19)Get data from
"""

df_selected = df_covid.query(
    f'"{str_startdate}" <= diagnosed_date <= "{str_enddate}"')
st.write(df_selected)

When I rerun, I see the dated component in the sidebar.

05_sidebar.png

You can narrow down the contents of data frames and graphs by specifying the start date and end date.

06_date_range.png

Finally, I would like to add an option to display the average number of infected people per week.


"""
#Number of infected people per day
"""


x = [
    datetime.datetime.strptime(diagnosed_date, '%Y-%m-%d')
    for diagnosed_date in df_selected['diagnosed_date'].values
]
y_count = df_selected['count'].values

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y_count)

wac_shown = st.sidebar.checkbox('Also displays the average number of infected people per week')
if wac_shown:
    y_weekly_average_count = df_selected['weekly_average_count'].values
    ax.plot(x, y_weekly_average_count)

xfmt = mdates.DateFormatter('%m/%d')
xloc = mdates.DayLocator(interval=20)

ax.xaxis.set_major_locator(xloc)
ax.xaxis.set_major_formatter(xfmt)
st.write(fig)

After rerun, a checkbox will be added to the sidebar.

07_checkbox.png

By checking it, the average number of infected people per week will be additionally drawn.

08_add_average.png

Impressions

――I could really make a web application only with Python With this demo app, I was able to implement it in 70 lines. The learning cost was low, and it was great to say the least that I didn't have to write any code on the front side.

――You can't make an app with an elaborate design The concept is not to be aware of the front side, so there is not much freedom in the UI. There is only a simple layout of body + sidebar, and if you want to implement "my UI", you should write the code on the front side obediently. It's more like a framework for demo apps than for making a decent product.

This time I was only visualizing the data, but I wanted to make an AI demo app using this.

Recommended Posts

[Streamlit] I hate JavaScript, so I make a web application only with Python
[Python] A quick web application with Bottle!
Run a Python web application with Docker
Let's make a web framework with Python! (1)
Let's make a web framework with Python! (2)
I made a WEB application with Django
If you know Python, you can make a web application with Django
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
I want to make a game with Python
I tried using "Streamlit" which can do the Web only with Python
I want to make a web application using React and Python flask
I tried to make a simple mail sending application with tkinter of Python
[ES Lab] I tried to develop a WEB application with Python and Flask ②
Make a fortune with Python
Web application with Python + Flask ② ③
Web application with Python + Flask ④
Let's make a GUI with python.
I tried web scraping with python.
I tried "Streamlit" which turns the Python code into a web application as it is
I made a fortune with Python.
Make a recommender system with python
Build a web application with Django
Let's make a graph with python! !!
I made a daemon with Python
[5th] I tried to make a certain authenticator-like tool with python
Let's make a WEB application for phone book with flask Part 1
[2nd] I tried to make a certain authenticator-like tool with python
[3rd] I tried to make a certain authenticator-like tool with python
Let's make a WEB application for phone book with flask Part 2
I tried to make a periodical process with Selenium and Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
Let's make a WEB application for phone book with flask Part 3
[4th] I tried to make a certain authenticator-like tool with python
Homework was a pain, so I do management accounting with Python
[1st] I tried to make a certain authenticator-like tool with python
Let's make a WEB application for phone book with flask Part 4
Let's make a web chat using WebSocket with AWS serverless (Python)!
I made a segment tree with python, so I will introduce it
I made a character counter with Python
I drew a heatmap with seaborn [Python]
Daemonize a Python web app with Supervisor
Let's make a voice slowly with Python
I tried a functional language with Python
What I did with a Python array
I made a Hex map with Python
I tried to make a Web API
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
I made a roguelike game with Python
I tried benchmarking a web application framework
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
Python: I tried to make a flat / flat_map just right with a generator
I made a web application in Python that converts Markdown to HTML
I tried to make a calculator with Tkinter so I will write it
I tried to discriminate a 6-digit number with a number discrimination application made with python
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
I was addicted to trying Cython with PyCharm, so make a note
Publish a web application for viewing data created with Streamlit on heroku