Python Streamlit

Streamlit公式 Streamlit資料

Streamlit

PythonのみでWebページを作成できる。特にデータの可視化に使用。

インストール

pip install streamlit

サンプル

ソースの作成

stsample.py に作成

例1:表示のみ

import streamlit as st

st.title('Sample Site')
st.write('こんにちは')

例2:入力して処理をする例

import streamlit as st

st.title('Sample Site')

txt = st.text_input('入力:')
btn = st.button("ボタン")
if btn:
   st.text(txt + "を入力しました")

実行

コマンドラインで「streamlit run ソースファイル名」。

streamlit run stsample.py

初回実行時にはメールアドレスを聞かれる場合があるが、入力せずEnterを押す。

自動的に、http://localhost:8501/ が起動。

VSCodeでの実行

左側のボタンの「実行とデバッグ」を押し、「launch.jsonファイルを作成します」をクリック。「モジュール Pythonモジュールを '-m'で呼び出しデバッグする。を選択。モジュールパッケージ名に「Steamlit」と付ける。launch.jsonファイルが開かれるので以下を記述する
{
    // IntelliSense を使用して利用可能な属性を学べます。
    // 既存の属性の説明をホバーして表示します。
    // 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python モジュール",
            "type": "python",
            "request": "launch",
            "module": "streamlit",
            "justMyCode": true,
            "args": ["run", "${file}"]
        }
    ]
}

実行するには、Steamlitのファイルを開いた状態で、[実行]-[デバッグの開始]を選ぶ。

終了するにはCtrl+Cを押す。

基本

st.title('タイトル')
st.header('ヘッダ')
st.subheader('サブヘッダ')
st.caption('キャプション')
st.text('テキスト')
st.code("#コード\na=10")
st.error('エラーメッセージ')
st.warning('警告メッセージ')
st.info('情報メッセージ')
st.success('成功メッセージ')

なお、変数名は、Jyupiterと同じくそのまま書くと表示される

データ可視化

データフレームの表示

import pandas as pd
df =  pd.read_csv("data/j2.csv")
df

グラフ表示

DataFrameで作成した図を表示

import pandas as pd
import seaborn as sns
sns.set(font=["Meiryo"])

ax = df["勝点"].plot.bar()
st.pyplot(ax.get_figure())

メトリクス表示

気温など可変するデータの表示

st.metric("ラベル", "値", "増分")

st.metric("気温", "15.2℃", "1.2℃")

フォーム

ボタン

ボタンが押されたときのみ表示

btn = st.button("ボタン")
if btn:
   st.text("ボタンが押されました")

ボタンが押されたときに表示を変える

btn = st.button("ボタン2")
if btn:
   st.text("Push!")
else:
   st.text("None push")

チェックボックス

if st.checkbox("チェックボックス"):
   st.text("チェックしました。")

ラジオボタン

radio = st.radio("ラジオボタン", ["男", "女"])
st.text(radio)

セレクトボックス

sel = st.selectbox("セレクトボックス", ["1", "2", "3"])
st.text(sel)

※最初の選択肢はindexに指定する。

sel = st.sidebar.selectbox("セレクトボックス", ["男性", "女性"], index=1)
st.text(sel)

スライダー

ラベル、最小値、最大値、初期値で指定

age = st.slider('年齢', 0, 130, 30)
st.text(age)

入力

txt = st.text_input('ラベル', '初期値')
st.text(txt)

ファイル

f = st.file_uploader('ファイルアップロード')

# 情報表示
st.text(f)

# テキストファイルを読み込んで表示
if f is not None:
    data = f.getvalue()
    text = data.decode('utf-8')
    st.text(text)

画像ファイルの場合

f = st.file_uploader('ファイルアップロード')

if f is not None:
    # 表示
    st.image(f.getvalue())

サイドバー

st.sidebarの後に通常の記述を行う。
ただし、

st.sidebar.subheader('サイドバー')
st.sidebar.text('サイド')

横並び

col1, col2, col3 = st.columns(3)

with col1:
	st.header("cat")

with col2:
	st.header("dog")

with col3:
	st.header("rabbit")

画像

st.image(ファイル名 または URL)

データフレーム内の画像URLを表示に

# 列 image_url を元に列 imageにhtmlを保存
df['image'] = ''
for index in df.index:
    url = df.loc[index, 'image_url']
    df.loc[index,'image'] = f""

# html表示
st.markdown(
    df.to_html(escape=False),
    unsafe_allow_html=True,
)

画像データをPILで読み込んで表示

# 読み込んで表示する場合
from PIL import Image
img = Image.open('cat1.jpg')
st.image(img, )

OpenCVの場合

import cv2
img = cv2.imread('cat1.jpg')
st.image(img, channels='BGR')

st.imageのオプション

width
use_column_widthTrueにすると最大幅に合わせる
captionキャプション名
channels'RGB'または'BGR'

マークダウン

markdown関数でマークダウン記法を記述できる。

st.markdown('これは**太字**です')

st.markdown('[リンクの例](http://www.yahoo.co.jp)')

また、引数 unsafe_allow_html をTrueにすると、HTMLも記述可能。

st.markdown('ここは太字です',unsafe_allow_html=True)

複数ページでの構成

pagesフォルダを作り、そこにstreamlitの.pyファイルを配置すると自動的にサイドバーに表示される。