『30 Days of Streamlit』を3日でやってみた #1 (Day1〜Day10) #30DaysOfStreamlit

2024.04.30

近年、データ分析界隈で「Streamlit」がとても人気です。Streamlitは、Pythonを使ってデータサイエンスやAI/機械学習のWebアプリケーションを素早く開発できるオープンソースのフレームワークで、Pythonでデータ処理や機械学習モデルを実装した後、専門的なWeb開発スキルがなくても、それを簡単にWebアプリ化してエンドユーザーに届けることができる代物となっています。データサイエンスの成果をビジネスに素早く活用する上で、非常に有用なツールだと言えます。

このStreamlit、有志の手によって『30 Days of Streamlit』というコンテンツが展開されています。タイトルの通り全30日間のハンズオンカリキュラムが用意されており、難易度は初級、中級、上級の3段階に分かれています。

  • 1~7日目:
    • ローカルとクラウドのコーディング環境のセットアップ、Streamlit ライブラリのインストール、最初の Streamlit Hello World アプリの構築など、初級者向けのタスクをカバー。
  • 8~23日目:
    • より中級者向けのトピックを扱う
    • 各日は、簡単なStreamlitアプリの作成とデプロイに使用するStreamlit コマンドを取り上げる
      • 例:st.download_button コマンドを使用する簡単なアプリの作成
  • 24~30日目:
    • より高度なテーマを扱う
    • セッション・ステートや、Streamlitアプリの効率的なデータ・メモリ処理などについて学部

当エントリでは、この『30 Days of Streamlit』の内容を実践した記録を共有したいと思います。当初は『30日分まとめて1日で終わらすぜぇ』と思っていましたが流石に物量的に無理でした。結果的に1日約3時間x3日間で10時間程掛かった形となりました。3日間に渡って実践したのでエントリも10日分を1エントリとして3本に分けて紹介したいと思います。

目次

 

実践記録(Day1〜Day10)

 

Day 1: Streamlit環境設定

condaのインストール

ここではpyenvを使って今回の実践専用のPython実行環境を用意する形で臨みました。

pyenv導入の上でminicondaの最新バージョンをインストール。

% pyenv install miniconda3-4.7.12
Downloading Miniconda3-4.7.12-MacOSX-x86_64.sh...
-> https://repo.anaconda.com/miniconda/Miniconda3-4.7.12-MacOSX-x86_64.sh
Installing Miniconda3-4.7.12-MacOSX-x86_64...
Collecting package metadata (current_repodata.json): done
Solving environment: done


==> WARNING: A newer version of conda exists. <==
  current version: 4.7.12
  latest version: 24.3.0

Please update conda by running

    $ conda update -n base -c defaults conda



## Package Plan ##

  environment location: /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12

  added / updated specs:
    - conda=4.7.12
    - pip


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    ca-certificates-2024.3.11  |       hecd8cb5_0         128 KB
    certifi-2020.6.20          |     pyhd3eb1b0_3         155 KB
    openssl-1.1.1w             |       hca72f7f_0         2.8 MB
    ------------------------------------------------------------
                                           Total:         3.1 MB

The following packages will be UPDATED:

  ca-certificates                               2019.8.28-0 --> 2024.3.11-hecd8cb5_0
  certifi            pkgs/main/osx-64::certifi-2019.9.11-p~ --> pkgs/main/noarch::certifi-2020.6.20-pyhd3eb1b0_3
  openssl                                 1.1.1d-h1de35cc_2 --> 1.1.1w-hca72f7f_0



Downloading and Extracting Packages
ca-certificates-2024 | 128 KB    | ######################################################################################################################################### | 100% 
openssl-1.1.1w       | 2.8 MB    | ######################################################################################################################################### | 100% 
certifi-2020.6.20    | 155 KB    | ######################################################################################################################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
Installed Miniconda3-4.7.12-MacOSX-x86_64 to /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12

環境切り替えも以下の形で済ませました。

% pyenv global miniconda3-4.7.12 
% pyenv rehash
% pyenv versions
  system
  3.9.18
  3.11.5
  3.11.9
* miniconda3-4.7.12 (set by /Users/xxxxxxxxxx/.pyenv/version)
% python --version 
Python 3.7.4

conda環境作成

% conda create -n stenv python=3.7
Collecting package metadata (current_repodata.json): done
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: done


==> WARNING: A newer version of conda exists. <==
  current version: 4.7.12
  latest version: 24.3.0

Please update conda by running

    $ conda update -n base -c defaults conda



## Package Plan ##

  environment location: /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/envs/stenv

  added / updated specs:
    - python=3.7


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    certifi-2022.12.7          |   py37hecd8cb5_0         151 KB
    libffi-3.4.4               |       hecd8cb5_0         132 KB
    ncurses-6.4                |       hcec6c5f_0        1018 KB
    pip-22.3.1                 |   py37hecd8cb5_0         2.7 MB
    python-3.7.16              |       h218abb5_0        23.5 MB
    readline-8.2               |       hca72f7f_0         328 KB
    setuptools-65.6.3          |   py37hecd8cb5_0         1.1 MB
    sqlite-3.41.2              |       h6c40b1e_0         1.2 MB
    tk-8.6.12                  |       h5d9f67b_0         3.1 MB
    wheel-0.38.4               |   py37hecd8cb5_0          65 KB
    xz-5.4.6                   |       h6c40b1e_0         373 KB
    zlib-1.2.13                |       h4dc903c_0          96 KB
    ------------------------------------------------------------
                                           Total:        33.7 MB

The following NEW packages will be INSTALLED:

  ca-certificates    pkgs/main/osx-64::ca-certificates-2024.3.11-hecd8cb5_0
  certifi            pkgs/main/osx-64::certifi-2022.12.7-py37hecd8cb5_0
  libffi             pkgs/main/osx-64::libffi-3.4.4-hecd8cb5_0
  ncurses            pkgs/main/osx-64::ncurses-6.4-hcec6c5f_0
  openssl            pkgs/main/osx-64::openssl-1.1.1w-hca72f7f_0
  pip                pkgs/main/osx-64::pip-22.3.1-py37hecd8cb5_0
  python             pkgs/main/osx-64::python-3.7.16-h218abb5_0
  readline           pkgs/main/osx-64::readline-8.2-hca72f7f_0
  setuptools         pkgs/main/osx-64::setuptools-65.6.3-py37hecd8cb5_0
  sqlite             pkgs/main/osx-64::sqlite-3.41.2-h6c40b1e_0
  tk                 pkgs/main/osx-64::tk-8.6.12-h5d9f67b_0
  wheel              pkgs/main/osx-64::wheel-0.38.4-py37hecd8cb5_0
  xz                 pkgs/main/osx-64::xz-5.4.6-h6c40b1e_0
  zlib               pkgs/main/osx-64::zlib-1.2.13-h4dc903c_0


Proceed ([y]/n)? y


Downloading and Extracting Packages
sqlite-3.41.2        | 1.2 MB    | ######################################################################################################################################### | 100% 
zlib-1.2.13          | 96 KB     | ######################################################################################################################################### | 100% 
certifi-2022.12.7    | 151 KB    | ######################################################################################################################################### | 100% 
wheel-0.38.4         | 65 KB     | ######################################################################################################################################### | 100% 
python-3.7.16        | 23.5 MB   | ######################################################################################################################################### | 100% 
libffi-3.4.4         | 132 KB    | ######################################################################################################################################### | 100% 
tk-8.6.12            | 3.1 MB    | ######################################################################################################################################### | 100% 
ncurses-6.4          | 1018 KB   | ######################################################################################################################################### | 100% 
setuptools-65.6.3    | 1.1 MB    | ######################################################################################################################################### | 100% 
readline-8.2         | 328 KB    | ######################################################################################################################################### | 100% 
xz-5.4.6             | 373 KB    | ######################################################################################################################################### | 100% 
pip-22.3.1           | 2.7 MB    | ######################################################################################################################################### | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
#
# To activate this environment, use
#
#     $ conda activate stenv
#
# To deactivate an active environment, use
#
#     $ conda deactivate

conda環境アクティベート

所定のコマンドをそのまま実行したらエラーになりました。

% conda activate stenv

CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
To initialize your shell, run

    $ conda init <SHELL_NAME>

Currently supported shells are:
  - bash
  - fish
  - tcsh
  - xonsh
  - zsh
  - powershell

See 'conda init --help' for more information and options.

IMPORTANT: You may need to close and restart your shell after running 'conda init'.

初期化を行った上でターミナルを再起動。

% conda init zsh
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/condabin/conda
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/bin/conda
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/bin/conda-env
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/bin/activate
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/bin/deactivate
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/etc/profile.d/conda.sh
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/etc/fish/conf.d/conda.fish
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/shell/condabin/Conda.psm1
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/shell/condabin/conda-hook.ps1
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/lib/python3.7/site-packages/xontrib/conda.xsh
no change     /Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/etc/profile.d/conda.csh
modified      /Users/xxxxxxxxxx/.zshrc

==> For changes to take effect, close and re-open your current shell. <==

プロンプト表示に(base)と付くようになりました。コマンドconda activate stenvを実行するとプロンプト表示も(base)から(stenv)に変わっています。

(base) xxxxxxxxxx@XXXXXXXXXX streamlit-in-30-days % pwd
/Users/xxxxxxxxxx/Desktop/programs/streamlit-in-30-days
(base) xxxxxxxxxx@XXXXXXXXXX streamlit-in-30-days % 
(base) xxxxxxxxxx@XXXXXXXXXX streamlit-in-30-days % 
(base) xxxxxxxxxx@XXXXXXXXXX streamlit-in-30-days % conda activate stenv
(stenv) xxxxxxxxxx@XXXXXXXXXX streamlit-in-30-days %
% pip install streamlit
Collecting streamlit
  Using cached streamlit-1.23.1-py2.py3-none-any.whl (8.9 MB)
:
:
Successfully installed MarkupSafe-2.1.5 altair-5.0.1 attrs-23.2.0 backports.zoneinfo-0.2.1 blinker-1.6.3 cachetools-5.3.3 charset-normalizer-3.3.2 click-8.1.7 decorator-5.1.1 gitdb-4.0.11 gitpython-3.1.43 idna-3.7 importlib-metadata-6.7.0 importlib-resources-5.12.0 jinja2-3.1.3 jsonschema-4.17.3 markdown-it-py-2.2.0 mdurl-0.1.2 numpy-1.21.6 packaging-23.2 pandas-1.3.5 pillow-9.5.0 pkgutil-resolve-name-1.3.10 protobuf-4.24.4 pyarrow-12.0.1 pydeck-0.8.1b1 pygments-2.17.2 pympler-1.0.1 pyrsistent-0.19.3 python-dateutil-2.9.0.post0 pytz-2024.1 pytz-deprecation-shim-0.1.0.post0 requests-2.31.0 rich-13.7.1 six-1.16.0 smmap-5.0.1 streamlit-1.23.1 tenacity-8.2.3 toml-0.10.2 toolz-0.12.1 tornado-6.2 typing-extensions-4.7.1 tzdata-2024.1 tzlocal-4.3.1 urllib3-2.0.7 validators-0.20.0 zipp-3.15.0

% streamlit --version  
Streamlit, version 1.23.1
% streamlit hello    

  Welcome to Streamlit. Check out our demo in your browser.

  Local URL: http://localhost:8501
  Network URL: http://xxx.xxx.xx.xx:8501

  Ready to create your own Python apps super quickly?
  Head over to https://docs.streamlit.io

  May you create awesome apps!


  For better performance, install the Watchdog module:

  $ xcode-select --install
  $ pip install watchdog

 

Day 2: 最初のStreamlitアプリを構築

ここでは最初のStreamlitアプリを構築するうえでのIDEの準備について言及されています。まぁエディタは何でも良いよと記載されていたので、ここではVSCodeを使って臨むことにしました。VSCodeをインストールし、併せてPython実行ができるようにプラグインを適宜導入しておいてください。

VSCode上で当該環境のPythonスクリプトを動かすために、インタプリタ設定を行います。該当する環境のPython実行パスを控えておいてください。

% which python
/Users/xxxxxxxxxx/.pyenv/versions/miniconda3-4.7.12/envs/stenv/bin/python

VSCodeを起動、画面右下にあるPythonインタプリター部分(Pythonバージョン情報が表示されている箇所)をクリック。インタプリターの選択ウィザードが表示されるので『インタープリターパスの入力』を選択。

パス入力ウインドウが表示されるので上記で控えたパス情報を入力します。これで準備完了。

IDE上で以下の内容をファイルとして作成。

streamlit_app.py

import streamlit as st

st.write('Hello world!')

ターミナルで以下コマンドを実行。

% streamlit run streamlit_app.py

  You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://xxx.xxx.xx.xx:8501

  For better performance, install the Watchdog module:

  $ xcode-select --install
  $ pip install watchdog
            

  A new version of Streamlit is available.

  See what's new at https://discuss.streamlit.io/c/announcements

  Enter the following command to upgrade:
  $ pip install streamlit --upgrade

アプリがウインドウとして立ち上がりました。

 

Day 3: ボタンウィジェットの実装

Streamlitで用意提供されているボタンウィジェットを使った実践。ボタンを押下するとラベル表記内容が変わるというものです。

実装したコード:

day3_st.button.py

import streamlit as st

st.header('st.button')

if st.button('Say hello'):
     st.write('Why hello there')
else:
     st.write('Goodbye')

アプリケーション起動:

% streamlit run day3_st.button.py

ボタン押下前の状況はこの内容ですが、

ボタンを押下するとラベル表記内容が変わりました。

 

Day 4: Ken Jee と Streamlit アプリを構築

「いやそもそもKen Jeeって誰?」って感じではありますが。この「30 Days of Streamlit」に関係する人なのでしょうか。

What is 30 days of Streamlit?
We're kicking off #30DaysOfStreamlit—a social challenge for getting up to speed on building and deploying Streamlit apps. Each day a new challenge will be released for participants to tackle. Inspired by Ken Jee’s #66daysofdata, the #100daysofcode challenge, and Kaggle’s #30DaysofML, this initiative is a fun opportunity to learn, create, share, and earn.

----
30 days of Streamlitとは?
#30DaysOfStreamlit は、Streamlitアプリの構築とデプロイをスピードアップするためのソーシャル・チャレンジです。毎日新しいチャレンジが公開され、参加者はそれに取り組みます。Ken Jeeの #66daysofdata、 #100daysofcodeチャレンジ、 Kaggleの#30DaysofMLにインスパイアされたこのイニシアチブは、学び、創造し、共有し、稼ぐ楽しい機会です。

30 Days of Streamlit

あ、当企画の下敷きになった部分の発案者ってことなのですね。サーセン。

ということで関連動画はこちら。観ておきましょう。

 

Day 5: st.writeの実践

Streamlit アプリにテキストと引数を書き込むことができるst.writeという機能に関する実践。

実装コード:

day5_st.write.py

import numpy as np
import altair as alt
import pandas as pd
import streamlit as st

st.header('st.write')

# Example 1

st.write('Hello, *World!* :sunglasses:')

# Example 2

st.write(1234)

# Example 3

df = pd.DataFrame({
     'first column': [1, 2, 3, 4],
     'second column': [10, 20, 30, 40]
     })
st.write(df)

# Example 4

st.write('Below is a DataFrame:', df, 'Above is a dataframe.')

# Example 5

df2 = pd.DataFrame(
     np.random.randn(200, 3),
     columns=['a', 'b', 'c'])
c = alt.Chart(df2).mark_circle().encode(
     x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
st.write(c)

アプリケーション起動:

% streamlit run day5_st.write.py

起動したブラウザでは以下のような表示がなされました。実に様々な表現をいい感じにやってくれてますね。

 

Day 6: Streamlit アプリを GitHub にアップロード

このステップは、GitHubにStreamlitをアップロードするための前段階、準備としてGitHubアカウントの用意とリポジトリの作成をしておきましょうね、という内容になっています。

対応するGitHubリポジトリを用意。リポジトリ名はstreamlit-helloworld、公開範囲は(自分で確認出来さえすれば良いや、ってことで)プライベートとしました。(※後述するStreamlit Community Cloudとの連携には、パブリックなリポジトリが必要となるようです。なのでこのリポジトリもプライベートからパブリックへと公開範囲を変更しました)

ファイルがアップロードできるぞ、というところまで確認。

 

Day 7: Streamlit Community Cloud を使用した Streamlit アプリのデプロイ

Streamlit アプリを簡単にデプロイするためのホスティングサービスである「Streamlit Community Cloud」に関する説明と、アプリのデプロイに関する案内。Google または GitHub アカウントでログインするだけで、Streamlit Community Cloud に簡単にサインアップできるようです。

Streamlit Community Cloud上でのアカウント連携、ログインまで済ませ、トップ画面に遷移出来ました。

 

Day 8: st.sliderの実装

スライダー入力ウィジェットを表示できるst.sliderを使ったアプリケーションの実装。ユーザーがスライダーウィジェットを調整して値を選択すると、アプリはその選択した値を出力する...というものです。

実装コード:

day08_st.slider.py

import streamlit as st
from datetime import time, datetime

st.header('st.slider')

# Example 1

st.subheader('Slider')

age = st.slider('How old are you?', 0, 130, 25)
st.write("I'm ", age, 'years old')

# Example 2

st.subheader('Range slider')

values = st.slider(
     'Select a range of values',
     0.0, 100.0, (25.0, 75.0))
st.write('Values:', values)

# Example 3

st.subheader('Range time slider')

appointment = st.slider(
     "Schedule your appointment:",
     value=(time(11, 30), time(12, 45)))
st.write("You're scheduled for:", appointment)

# Example 4

st.subheader('Datetime slider')

start_time = st.slider(
     "When do you start?",
     value=datetime(2020, 1, 1, 9, 30),
     format="MM/DD/YY - hh:mm")
st.write("Start time:", start_time)

アプリケーション起動:

% streamlit run day08_st.slider.py

起動したブラウザでは以下のようなスライダーバーが表示されました。

 

Day 9: st.line_chartの実装

折れ線グラフを表示することができるst.line_chartを使った実装。

実装コード:

day09_st.line_chart.py

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

st.header('Line chart')

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

st.line_chart(chart_data)

アプリケーション起動:

% streamlit run day09_st.line_chart.py

起動したブラウザでは以下のような折れ線グラフを表示する事ができました。メニューから画像保存などもできる模様。

 

Day 10: st.selectboxの実装

SELECTボックス、プルダウンを表示できるst.selectboxを使った実装。

実装コード:

day09_st.line_chart.py

import streamlit as st

st.header('st.selectbox')

option = st.selectbox(
     'What is your favorite color?',
     ('Blue', 'Red', 'Green'))

st.write('Your favorite color is ', option)

アプリケーション起動:

% streamlit run day10_st.selectbox.py

起動したブラウザでは以下のようなプルダウンが表示されました。

選択肢を変更すると、対応してラベル部分の表示も変わります。

 

まとめ

という訳でStreamlitハンズオン『30 Days of Streamlit』を3日でやってみた、の1日目の実践内容の紹介でした。