【streamlit】PythonでインタラクティブなWebアプリを簡単作成:徹底解説
Pythonを使ってインタラクティブなWebアプリケーションを開発したいと思ったことはありませんか?従来のWebフレームワーク、例えばFlaskやDjangoは強力ですが、学習曲線が長く、特にデータサイエンティストや機械学習エンジニアにとっては、本質的なモデル開発以外の部分に多くの時間を費やすことになりがちです。
そんな悩みを解決してくれるのが、PythonライブラリのStreamlitです。Streamlitは、複雑なフロントエンドの知識がなくても、Pythonスクリプトだけで美しく、インタラクティブなWebアプリケーションを簡単に作成できることを目指して設計されています。
この記事では、Streamlitの基本的な概念から高度な機能、そして実践的なサンプルコードまで、詳細に解説していきます。Streamlitをマスターして、あなたのアイデアを迅速にWebアプリケーションとして実現しましょう。
目次
-
Streamlitとは?
- 1.1 Streamlitの概要と特徴
- 1.2 なぜStreamlitを使うのか?(メリットとデメリット)
- 1.3 Streamlitのインストールと実行環境
-
Streamlitの基本要素
- 2.1 Hello World! – 最初のStreamlitアプリ
- 2.2 テキストの表示:
st.write
,st.title
,st.header
,st.subheader
- 2.3 データフレームの表示:
st.dataframe
,st.table
- 2.4 Markdownの活用:
st.markdown
- 2.5 コードの表示:
st.code
- 2.6 画像と動画の表示:
st.image
,st.video
- 2.7 オーディオの再生:
st.audio
-
インタラクティブなウィジェット
- 3.1 ボタン:
st.button
- 3.2 チェックボックス:
st.checkbox
- 3.3 ラジオボタン:
st.radio
- 3.4 セレクトボックス:
st.selectbox
,st.multiselect
- 3.5 スライダー:
st.slider
,st.select_slider
- 3.6 テキスト入力:
st.text_input
,st.text_area
- 3.7 数値入力:
st.number_input
- 3.8 日付入力:
st.date_input
,st.time_input
- 3.9 ファイルアップロード:
st.file_uploader
- 3.10 カラピッカー:
st.color_picker
- 3.1 ボタン:
-
レイアウトとデザイン
- 4.1 サイドバー:
st.sidebar
- 4.2 カラムレイアウト:
st.columns
- 4.3 タブ:
st.tabs
- 4.4 エクスパンダー:
st.expander
- 4.5 コンテナ:
st.container
- 4.6 テーマ設定:
st.set_page_config
- 4.1 サイドバー:
-
キャッシュとセッションステート
- 5.1 キャッシュ:
@st.cache_data
- 5.2 セッションステート:
st.session_state
- 5.1 キャッシュ:
-
グラフの描画
- 6.1 Matplotlib:
st.pyplot
- 6.2 Plotly:
st.plotly_chart
- 6.3 Altair:
st.altair_chart
- 6.4 Bokeh:
st.bokeh_chart
- 6.1 Matplotlib:
-
Streamlitの高度な機能
- 7.1 カスタムコンポーネント
- 7.2 Streamlit Components API
- 7.3 デバッグとエラー処理
- 7.4 外部ライブラリとの連携
-
実践的なStreamlitアプリ開発
- 8.1 データ可視化アプリ
- 8.2 機械学習モデルのデプロイアプリ
- 8.3 ダッシュボードアプリ
-
Streamlitのデプロイ
- 9.1 Streamlit Community Cloud
- 9.2 Heroku
- 9.3 Docker
-
まとめと今後の展望
1. Streamlitとは?
1.1 Streamlitの概要と特徴
Streamlitは、PythonのみでインタラクティブなWebアプリケーションを構築できる、オープンソースのフレームワークです。データサイエンティストや機械学習エンジニアが、自身のモデルや分析結果を簡単に共有し、インタラクティブに探索できるようにすることを目的としています。
従来のWeb開発のように、HTML、CSS、JavaScriptといったフロントエンド技術の知識は必須ではありません。Pythonの知識があれば、すぐにWebアプリケーションを作成できます。
Streamlitの主な特徴は以下の通りです。
- シンプルで直感的なAPI: Pythonのコードを記述するだけで、WebアプリケーションのUIを定義できます。
- 高速なプロトタイピング: わずかなコードで、アイデアを迅速にWebアプリケーションとして実現できます。
- インタラクティブなウィジェット: スライダー、ボタン、テキスト入力など、様々なウィジェットを簡単に組み込むことができます。
- 自動的なリフレッシュ: コードを変更すると、Streamlitアプリは自動的にリフレッシュされます。
- クラウドへの簡単なデプロイ: Streamlit Community Cloudなど、さまざまなプラットフォームに簡単にデプロイできます。
1.2 なぜStreamlitを使うのか?(メリットとデメリット)
Streamlitを使うメリットは数多くあります。
- 学習コストが低い: フロントエンドの知識が不要なため、Pythonの知識があればすぐに使い始めることができます。
- 開発速度が速い: 少ないコードで、迅速にWebアプリケーションを開発できます。
- インタラクティブなアプリケーションを簡単に作成できる: 豊富なウィジェットが用意されており、ユーザーとのインタラクションを簡単に実装できます。
- データサイエンス・機械学習分野との親和性が高い: PandasやNumPyなどのデータサイエンスライブラリとの連携が容易です。
- デプロイが容易: Streamlit Community Cloudを使えば、簡単にアプリケーションを公開できます。
一方、デメリットも存在します。
- カスタマイズの自由度が低い: フロントエンドのカスタマイズには限界があります。高度なデザインや複雑なUIを実現したい場合は、他のフレームワークを検討する必要があります。
- 大規模なアプリケーションには不向き: Streamlitは、小規模なアプリケーションやプロトタイピングに適しています。大規模なアプリケーションには、より高度なフレームワークが適している場合があります。
- リアルタイム性の高いアプリケーションには不向き: Streamlitは、ステートフルなアプリケーションに適していますが、リアルタイム性の高いアプリケーションには不向きです。
1.3 Streamlitのインストールと実行環境
Streamlitを使用するには、まずPythonがインストールされている必要があります。まだインストールされていない場合は、Python公式サイトからダウンロードしてインストールしてください。
Streamlitは、pipを使って簡単にインストールできます。
bash
pip install streamlit
インストールが完了したら、以下のコマンドでStreamlitアプリを実行できます。
bash
streamlit run your_app.py
your_app.py
は、あなたのStreamlitアプリのPythonファイル名に置き換えてください。
2. Streamlitの基本要素
2.1 Hello World! – 最初のStreamlitアプリ
Streamlitの基本を理解するために、まずは「Hello World!」を表示する簡単なアプリを作成してみましょう。
hello_world.py
というファイルを作成し、以下のコードを記述します。
“`python
import streamlit as st
st.write(“Hello, World!”)
“`
上記のコードを保存し、ターミナルで以下のコマンドを実行します。
bash
streamlit run hello_world.py
ブラウザが自動的に開き、「Hello, World!」と表示されます。
2.2 テキストの表示:st.write
, st.title
, st.header
, st.subheader
Streamlitでは、様々な方法でテキストを表示できます。
st.write()
:最も汎用的なテキスト表示関数です。文字列だけでなく、数値、リスト、辞書、Pandas DataFrameなど、様々なデータ型を表示できます。
“`python
import streamlit as st
st.write(“This is a paragraph of text.”)
st.write(123)
st.write([“a”, “b”, “c”])
“`
st.title()
:ページのタイトルを表示します。
“`python
import streamlit as st
st.title(“My Streamlit App”)
“`
st.header()
:セクションの見出しを表示します。
“`python
import streamlit as st
st.header(“Section 1”)
“`
st.subheader()
:サブセクションの見出しを表示します。
“`python
import streamlit as st
st.subheader(“Subsection 1.1”)
“`
2.3 データフレームの表示:st.dataframe
, st.table
Streamlitは、Pandas DataFrameを簡単に表示できます。
st.dataframe()
:インタラクティブなデータフレームを表示します。ソート、フィルタリング、編集などの機能が利用できます。
“`python
import streamlit as st
import pandas as pd
data = {‘col1’: [1, 2, 3], ‘col2’: [4, 5, 6]}
df = pd.DataFrame(data)
st.dataframe(df)
“`
st.table()
:静的なテーブルを表示します。インタラクティブな機能はありません。
“`python
import streamlit as st
import pandas as pd
data = {‘col1’: [1, 2, 3], ‘col2’: [4, 5, 6]}
df = pd.DataFrame(data)
st.table(df)
“`
2.4 Markdownの活用:st.markdown
Streamlitでは、Markdown形式でテキストを記述できます。st.markdown()
関数を使用します。
“`python
import streamlit as st
st.markdown(“””
This is a heading
This is a paragraph of text with bold and italic formatting.
- List item 1
- List item 2
“””)
“`
2.5 コードの表示:st.code
Streamlitでは、コードを美しく表示できます。st.code()
関数を使用します。
“`python
import streamlit as st
code = “””
import streamlit as st
st.write(“Hello, World!”)
“””
st.code(code, language=”python”)
“`
2.6 画像と動画の表示:st.image
, st.video
Streamlitでは、画像と動画を表示できます。
st.image()
:画像を表示します。ローカルファイル、URL、PIL Imageオブジェクトなどを指定できます。
“`python
import streamlit as st
from PIL import Image
image = Image.open(“image.jpg”) # Replace with your image path
st.image(image, caption=”My Image”)
st.image(“https://via.placeholder.com/150″, caption=”Placeholder Image”)
“`
st.video()
:動画を表示します。ローカルファイルまたはURLを指定できます。
“`python
import streamlit as st
st.video(“video.mp4”) # Replace with your video path
“`
2.7 オーディオの再生:st.audio
Streamlitでは、オーディオファイルを再生できます。st.audio()
関数を使用します。
“`python
import streamlit as st
st.audio(“audio.mp3”) # Replace with your audio path
“`
3. インタラクティブなウィジェット
Streamlitの最大の魅力は、豊富なインタラクティブなウィジェットを使って、ユーザーとのインタラクションを簡単に実装できることです。
3.1 ボタン:st.button
ボタンをクリックすると、何らかのアクションを実行できます。
“`python
import streamlit as st
if st.button(“Click me”):
st.write(“Button clicked!”)
“`
3.2 チェックボックス:st.checkbox
チェックボックスの状態に応じて、何らかのアクションを実行できます。
“`python
import streamlit as st
if st.checkbox(“Show message”):
st.write(“Checkbox is checked!”)
“`
3.3 ラジオボタン:st.radio
複数の選択肢から1つを選択できます。
“`python
import streamlit as st
options = [“Option 1”, “Option 2”, “Option 3”]
selected_option = st.radio(“Select an option”, options)
st.write(f”You selected: {selected_option}”)
“`
3.4 セレクトボックス:st.selectbox
, st.multiselect
複数の選択肢から1つ(または複数)を選択できます。
st.selectbox()
:複数の選択肢から1つを選択できます。
“`python
import streamlit as st
options = [“Option 1”, “Option 2”, “Option 3”]
selected_option = st.selectbox(“Select an option”, options)
st.write(f”You selected: {selected_option}”)
“`
st.multiselect()
:複数の選択肢から複数を選択できます。
“`python
import streamlit as st
options = [“Option 1”, “Option 2”, “Option 3”]
selected_options = st.multiselect(“Select options”, options)
st.write(f”You selected: {selected_options}”)
“`
3.5 スライダー:st.slider
, st.select_slider
範囲内の値をスライダーで選択できます。
st.slider()
:数値のスライダーを表示します。
“`python
import streamlit as st
age = st.slider(“How old are you?”, 0, 130, 25)
st.write(f”You are {age} years old.”)
“`
st.select_slider()
:文字列または日付のスライダーを表示します。
“`python
import streamlit as st
options = [“A”, “B”, “C”, “D”, “E”]
selected_option = st.select_slider(“Select a letter”, options=options)
st.write(f”You selected: {selected_option}”)
“`
3.6 テキスト入力:st.text_input
, st.text_area
テキストを入力できます。
st.text_input()
:1行のテキストを入力できます。
“`python
import streamlit as st
name = st.text_input(“Enter your name”, “John Doe”)
st.write(f”Hello, {name}!”)
“`
st.text_area()
:複数行のテキストを入力できます。
“`python
import streamlit as st
text = st.text_area(“Enter your text”, “This is a text area.”)
st.write(f”You entered: {text}”)
“`
3.7 数値入力:st.number_input
数値を入力できます。
“`python
import streamlit as st
number = st.number_input(“Enter a number”, min_value=0, max_value=100, value=50)
st.write(f”You entered: {number}”)
“`
3.8 日付入力:st.date_input
, st.time_input
日付や時刻を入力できます。
st.date_input()
:日付を入力できます。
“`python
import streamlit as st
import datetime
today = datetime.date.today()
selected_date = st.date_input(“Select a date”, today)
st.write(f”You selected: {selected_date}”)
“`
st.time_input()
:時刻を入力できます。
“`python
import streamlit as st
import datetime
now = datetime.time()
selected_time = st.time_input(“Select a time”, now)
st.write(f”You selected: {selected_time}”)
“`
3.9 ファイルアップロード:st.file_uploader
ファイルをアップロードできます。
“`python
import streamlit as st
uploaded_file = st.file_uploader(“Choose a file”)
if uploaded_file is not None:
# To read file as bytes:
bytes_data = uploaded_file.read()
st.write(“Uploaded file:”, uploaded_file.name)
“`
3.10 カラピッカー:st.color_picker
色を選択できます。
“`python
import streamlit as st
color = st.color_picker(“Pick a color”, “#00f900″)
st.write(f”You selected: {color}”)
“`
4. レイアウトとデザイン
Streamlitでは、アプリケーションのレイアウトを柔軟に制御できます。
4.1 サイドバー:st.sidebar
ウィジェットをサイドバーに配置できます。
“`python
import streamlit as st
age = st.sidebar.slider(“How old are you?”, 0, 130, 25)
st.write(f”You are {age} years old.”)
“`
4.2 カラムレイアウト:st.columns
複数のカラムを作成し、ウィジェットを横に並べて配置できます。
“`python
import streamlit as st
col1, col2, col3 = st.columns(3)
with col1:
st.header(“Column 1”)
st.write(“Content of column 1”)
with col2:
st.header(“Column 2”)
st.write(“Content of column 2”)
with col3:
st.header(“Column 3”)
st.write(“Content of column 3”)
“`
4.3 タブ:st.tabs
タブを作成し、コンテンツを整理できます。
“`python
import streamlit as st
tab1, tab2, tab3 = st.tabs([“Tab 1”, “Tab 2”, “Tab 3”])
with tab1:
st.header(“Tab 1”)
st.write(“Content of tab 1”)
with tab2:
st.header(“Tab 2”)
st.write(“Content of tab 2”)
with tab3:
st.header(“Tab 3”)
st.write(“Content of tab 3”)
“`
4.4 エクスパンダー:st.expander
折りたたみ可能なコンテンツを表示できます。
“`python
import streamlit as st
with st.expander(“See explanation”):
st.write(“This is a hidden explanation.”)
“`
4.5 コンテナ:st.container
複数の要素をグループ化できます。
“`python
import streamlit as st
with st.container():
st.write(“This is inside the container”)
st.button(“Click me”)
“`
4.6 テーマ設定:st.set_page_config
ページのタイトル、アイコン、レイアウトなどを設定できます。
“`python
import streamlit as st
st.set_page_config(
page_title=”My Streamlit App”,
page_icon=”🧊”,
layout=”wide”,
initial_sidebar_state=”expanded”,
)
“`
5. キャッシュとセッションステート
Streamlitでは、キャッシュとセッションステートを使って、アプリケーションのパフォーマンスを向上させることができます。
5.1 キャッシュ:@st.cache_data
キャッシュを使用すると、計算コストの高い関数を一度だけ実行し、結果を保存できます。これにより、同じ入力で関数が再度呼び出された場合に、結果を再計算する必要がなくなります。
“`python
import streamlit as st
import time
@st.cache_data
def expensive_function(a, b):
time.sleep(2) # Simulate expensive computation
return a + b
a = st.number_input(“Enter a”)
b = st.number_input(“Enter b”)
result = expensive_function(a, b)
st.write(f”Result: {result}”)
“`
5.2 セッションステート:st.session_state
セッションステートを使用すると、ユーザーセッション間でデータを保持できます。これにより、ウィジェットの状態を保存し、ページをリロードしても状態が維持されます。
“`python
import streamlit as st
if “counter” not in st.session_state:
st.session_state.counter = 0
def increment_counter():
st.session_state.counter += 1
st.button(“Increment”, on_click=increment_counter)
st.write(f”Counter: {st.session_state.counter}”)
“`
6. グラフの描画
Streamlitは、様々なグラフ描画ライブラリとの連携をサポートしています。
6.1 Matplotlib:st.pyplot
Matplotlibを使用してグラフを描画し、st.pyplot()
関数で表示できます。
“`python
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
st.pyplot(fig)
“`
6.2 Plotly:st.plotly_chart
Plotlyを使用してインタラクティブなグラフを描画し、st.plotly_chart()
関数で表示できます。
“`python
import streamlit as st
import plotly.express as px
import pandas as pd
data = {‘x’: [1, 2, 3, 4, 5], ‘y’: [2, 4, 1, 3, 5]}
df = pd.DataFrame(data)
fig = px.line(df, x=”x”, y=”y”, title=”Plotly Line Chart”)
st.plotly_chart(fig)
“`
6.3 Altair:st.altair_chart
Altairを使用して宣言的なグラフを描画し、st.altair_chart()
関数で表示できます。
“`python
import streamlit as st
import altair as alt
import pandas as pd
data = {‘x’: [1, 2, 3, 4, 5], ‘y’: [2, 4, 1, 3, 5]}
df = pd.DataFrame(data)
chart = alt.Chart(df).mark_line().encode(
x=’x’,
y=’y’
)
st.altair_chart(chart, use_container_width=True)
“`
6.4 Bokeh:st.bokeh_chart
Bokehを使用してインタラクティブなグラフを描画し、st.bokeh_chart()
関数で表示できます。
“`python
import streamlit as st
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
source = ColumnDataSource(data=dict(
x=[1, 2, 3, 4, 5],
y=[2, 4, 1, 3, 5],
))
p = figure(title=”Bokeh Line Chart”)
p.line(‘x’, ‘y’, source=source, line_width=2)
st.bokeh_chart(p, use_container_width=True)
“`
7. Streamlitの高度な機能
7.1 カスタムコンポーネント
Streamlit Components APIを使用すると、JavaScript、React、Vue.jsなどのフロントエンド技術を使用して、独自のカスタムコンポーネントを作成できます。これにより、Streamlitの標準ウィジェットでは実現できない高度なUIを実装できます。
7.2 Streamlit Components API
Streamlit Components APIを使用すると、Streamlitアプリとカスタムコンポーネントの間でデータをやり取りできます。これにより、コンポーネントの状態をStreamlitアプリで管理したり、Streamlitアプリからコンポーネントにデータを送信したりできます。
7.3 デバッグとエラー処理
Streamlitは、デバッグとエラー処理のための機能を提供しています。エラーメッセージを表示したり、例外をキャッチしたりできます。
7.4 外部ライブラリとの連携
Streamlitは、様々な外部ライブラリとの連携をサポートしています。例えば、OpenCVを使って画像処理を行ったり、TensorFlowやPyTorchを使って機械学習モデルを構築したりできます。
8. 実践的なStreamlitアプリ開発
8.1 データ可視化アプリ
CSVファイルをアップロードして、データを可視化するStreamlitアプリを作成します。
“`python
import streamlit as st
import pandas as pd
import plotly.express as px
st.title(“Data Visualization App”)
uploaded_file = st.file_uploader(“Choose a CSV file”)
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.dataframe(df)
numeric_columns = df.select_dtypes(include=['number']).columns.tolist()
column_x = st.selectbox("Select column for x-axis", numeric_columns)
column_y = st.selectbox("Select column for y-axis", numeric_columns)
fig = px.scatter(df, x=column_x, y=column_y, title="Scatter Plot")
st.plotly_chart(fig)
“`
8.2 機械学習モデルのデプロイアプリ
事前にトレーニングされた機械学習モデルをデプロイし、ユーザーからの入力に基づいて予測を行うStreamlitアプリを作成します。
“`python
import streamlit as st
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
Sample data for demonstration
data = {‘feature1’: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
‘feature2’: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
‘target’: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]}
df = pd.DataFrame(data)
Train a simple model
X = df[[‘feature1’, ‘feature2’]]
y = df[‘target’]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier()
model.fit(X_train, y_train)
st.title(“Machine Learning Model Deployment App”)
feature1 = st.number_input(“Enter feature 1”)
feature2 = st.number_input(“Enter feature 2”)
input_data = pd.DataFrame([[feature1, feature2]], columns=[‘feature1’, ‘feature2’])
prediction = model.predict(input_data)[0]
st.write(f”Prediction: {prediction}”)
“`
8.3 ダッシュボードアプリ
複数のグラフやウィジェットを組み合わせて、ダッシュボードアプリを作成します。
“`python
import streamlit as st
import pandas as pd
import plotly.express as px
import numpy as np
st.title(“Interactive Dashboard”)
Generate sample data
np.random.seed(42)
data = {
‘date’: pd.date_range(‘2023-01-01’, periods=100),
‘sales’: np.random.randint(50, 200, 100),
‘customers’: np.random.randint(10, 50, 100)
}
df = pd.DataFrame(data)
Sidebar filters
start_date = st.sidebar.date_input(“Start Date”, df[‘date’].min())
end_date = st.sidebar.date_input(“End Date”, df[‘date’].max())
Filter data based on selected date range
filtered_df = df[(df[‘date’] >= pd.to_datetime(start_date)) & (df[‘date’] <= pd.to_datetime(end_date))]
Metrics
total_sales = filtered_df[‘sales’].sum()
avg_customers = filtered_df[‘customers’].mean()
col1, col2 = st.columns(2)
with col1:
st.metric(“Total Sales”, f”${total_sales}”)
with col2:
st.metric(“Average Customers”, f”{avg_customers:.2f}”)
Charts
fig_sales = px.line(filtered_df, x=’date’, y=’sales’, title=”Sales Trend”)
fig_customers = px.bar(filtered_df, x=’date’, y=’customers’, title=”Customers Trend”)
st.plotly_chart(fig_sales, use_container_width=True)
st.plotly_chart(fig_customers, use_container_width=True)
Data table
st.header(“Data Table”)
st.dataframe(filtered_df)
“`
9. Streamlitのデプロイ
Streamlitアプリをデプロイする方法はいくつかあります。
9.1 Streamlit Community Cloud
Streamlit Community Cloudは、Streamlitアプリを無料でデプロイできる最も簡単な方法です。GitHubリポジトリと連携し、コードを変更すると自動的にアプリが更新されます。
9.2 Heroku
Herokuは、クラウドベースのプラットフォームで、Streamlitアプリをデプロイできます。Procfile
とrequirements.txt
を作成する必要があります。
9.3 Docker
Dockerを使用すると、Streamlitアプリをコンテナ化して、様々な環境にデプロイできます。
10. まとめと今後の展望
Streamlitは、PythonだけでインタラクティブなWebアプリケーションを簡単に作成できる強力なフレームワークです。データサイエンティストや機械学習エンジニアが、自身のモデルや分析結果を迅速に共有し、インタラクティブに探索できるようにするのに役立ちます。
Streamlitは、常に進化しており、新しい機能が続々と追加されています。今後の展望としては、より高度なUIコンポーネントの追加、より洗練されたレイアウト機能の提供、そして大規模なアプリケーションに対応するためのパフォーマンス改善などが期待されます。
Streamlitをマスターして、あなたのアイデアをWebアプリケーションとして迅速に実現しましょう!