Streamlitを使って爆速でWebアプリを作ろう!

Streamlitとは?

StreamlitというのはWebアプリのフレームワークの一つです。

Pythonのみで簡単にWebアプリを構築することができるものになります。HTMLやJavaScriptなどを書く必要がないため、一般的なPythonWebアプリを作成する際に使用する他のフレームワークよりも簡単に利用できます。作成したアプリは、Streamlit Cloudで公開することも可能です。

img

Streamlit • A faster way to build and share data apps

Streamlit is an open-source app framework for Machine Learning and Data Science teams. Create beautiful web apps in minutes.

img

streamlit.io

img

目次

    1. Streamlitとは?
  1. ngrokの準備

    1. ngrokとは?
    2. セットアップ
    3. トークンの取得
  2. Google ColaboratoryでStreamlitアプリケーションを実行する方法

  3. コードの解説

ngrokの準備

ngrokとは?

ngrokはローカルサーバーを外部公開できるツールになります。今回はGoogleコラボラトリー上で構築したチャットボットを動かすために使用します。今回使用する範囲では無料で使用ができます。

img

ngrok - Online in One Line

ngrok is the fastest way to put anything onthe internet with a single command.

img

ngrok.com

セットアップ

まずはngrokのサイトにアクセスをしてSignUpをクリックします

img

必要な情報を入力して登録を進めます.

img

登録が完了すると次のような—ボードになります。

img

トークンの取得

左側のメニューのYour Authtokenをクリックしてトークンを取得します。

img

トークンが表示されるのでコピーします。

img

Google ColaboratoryでStreamlitアプリケーションを実行する方法

  1. Google Colaboratoryにアクセス: まず、Google Colaboratoryにアクセスし、新しいノートブックを作成します。
  2. 必要なライブラリのインストール: 最初のセルに以下のコードを入力し、必要なライブラリをインストールします。
!pip install streamlit==1.20.0 
!pip install pyngrok==4.1.1 
import streamlit as st
from pyngrok import ngrok
  1. Streamlitアプリケーションの作成: 次に、新しいセルを作成し、以下のコードを入力してStreamlitアプリケーションを作成します。マジックコマンドを使ってapp.pyというファイルを作成するコードになります。さらなる詳細は後ほどコード解説で説明していきます。今回はirisデータセットを使ってウェブアプリの入力画面でユーザーがで入力したがくの長さや幅などの情報から花の品種を予測する簡単なアプリケーションを作成するコードになります。
%%writefile app.py
import streamlit as st
import pandas as pd
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier

# Irisデータセットの読み込み
iris = datasets.load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names

# 分類器の訓練
clf = RandomForestClassifier()
clf.fit(X, y)

# アプリケーションのタイトルと説明
st.title("Iris Flower Classification")
st.write("このアプリは、アヤメの花の種類を特徴に基づいて予測します。")

# ユーザーの入力の受け取り
sepal_length = st.slider("がく片の長さ", 4.0, 8.0, 5.0)
sepal_width = st.slider("がく片の幅", 2.0, 4.5, 3.0)
petal_length = st.slider("花弁の長さ", 1.0, 7.0, 4.0)
petal_width = st.slider("花弁の幅", 0.1, 2.5, 1.0)

custom_input = st.text_input("カスタム入力", "カンマ区切りで値を入力してください(例:5.1, 3.5, 1.4, 0.2)")

# ユーザーがカスタム入力を行った場合、それを利用
if custom_input and custom_input != "カンマ区切りで値を入力してください(例:5.1, 3.5, 1.4, 0.2)":
    custom_values = [float(x.strip()) for x in custom_input.split(",")]
    if len(custom_values) == 4:
        sepal_length, sepal_width, petal_length, petal_width = custom_values

# 予測結果の表示
features = [[sepal_length, sepal_width, petal_length, petal_width]]
prediction = clf.predict(features)

species = {
    0: "Setosa",
    1: "Versicolor",
    2: "Virginica"
}

st.write("特徴:")
feature_values = dict(zip(feature_names, [sepal_length, sepal_width, petal_length, petal_width]))
st.write(pd.DataFrame(feature_values, index=[0]))

st.write("予測された種類:", species[prediction[0]])
  1. アプリケーションの表示: APIキーを登録して、バックグラウンドジョブとしてアプリケーションを起動します。
!ngrok authtoken ここにAPIキーを入力
!streamlit run app.py &>/dev/null&  # 「&>/dev/null&」により、出力を非表示にしてバックグランドジョブとして実行

最後にngrokを使ってアプリケーションにアクセスできるようにします。

ngrok.kill()  # プロセスの修了
url = ngrok.connect(port="8501")  # 接続

帰ってきたURLがhttpの場合はhttpsでアクセスするようにURLを整形します.

if url.startswith("http://"):
    url = url.replace("http://", "https://", 1)
    print(url)

コードの解説

まず、以下のコードは必要なライブラリのインポートを行っています。

import streamlit as st
import pandas as pd
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier

次に、Irisデータセットを読み込んでいます。

iris = datasets.load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names

その後、ランダムフォレスト分類器を訓練しています。

clf = RandomForestClassifier()
clf.fit(X, y)

アプリケーションのタイトルと説明を表示します。

pythonCopy codest.title("Iris Flower Classification")
st.write("このアプリは、アヤメの花の種類を特徴に基づいて予測します。")

次に、ユーザーからの入力を受け取るためのスライダーやテキスト入力を表示します。

sepal_length = st.slider("がく片の長さ", 4.0, 8.0, 5.0)
sepal_width = st.slider("がく片の幅", 2.0, 4.5, 3.0)
petal_length = st.slider("花弁の長さ", 1.0, 7.0, 4.0)
petal_width = st.slider("花弁の幅", 0.1, 2.5, 1.0)

custom_input = st.text_input("カスタム入力", "カンマ区切りで値を入力してください(例:5.1, 3.5, 1.4, 0.2)")

ユーザーがカスタム入力を行った場合は、入力値を処理します。

if custom_input and custom_input != "カンマ区切りで値を入力してください(例:5.1, 3.5, 1.4, 0.2)":
    custom_values = [float(x.strip()) for x in custom_input.split(",")]
    if len(custom_values) == 4:
        sepal_length, sepal_width, petal_length, petal_width = custom_values

予測結果を表示します。

features = [[sepal_length, sepal_width, petal_length, petal_width]]
prediction = clf.predict(features)

species = {
    0: "Setosa",
    1: "Versicolor",
    2: "Virginica"
}

st.write("特徴:")
feature_values = dict(zip(feature_names, [sepal_length, sepal_width, petal_length, petal_width]))
st.write(pd.DataFrame(feature_values, index=[0]))

st.write("予測された種類:", species[prediction[0]])

特徴の値と予測された種類が表示されます。