🔐

Streamlitを使って、スプレッドシートをバックエンドにした社内運用できるデータアプリを作る手順

に公開

本記事では、Streamlitを使ってスプレッドシートをバックエンドにした社内運用できるデータアプリを構築する手順をご紹介します。Streamlitがどのようなケースに相性が良いのかという点についても掘り下げてご紹介します。

前回の記事では、スプレッドシートをバックエンドにしたデータアプリを構築する複数の方法をご紹介しました。今回は、そのときに紹介したコードベースのフレームワークの1つ、Streamlitを取り上げて、社内運用するためのデータアプリの構築手順を説明したいと思います。
前回の記事はこちらです。
https://zenn.dev/morph_tech_blog/articles/531f394ec497e4

具体的なアプリの構築手順

Google Cloud / Google Sheet側の設定

https://youtu.be/U0I00Ycqcbc

1. Google Sheet APIを有効にする

Google Developers Consoleにログインし、新規プロジェクトを作成、Google Sheets APIを有効化してください。

2. サービスアカウントを発行し、JSONをダウンロード

API とサービス > 認証情報 のページから、新規のサービスアカウントを発行します。

サービスアカウントの「キー」タブから新規のキーを作成、JSON形式でダウンロードしておきます。

3. 対象のスプレッドシートにサービスアカウントを招待する

スプレッドシートの「共有」ボタンから、サービスアカウントを追加します。これによってサービースアカウントから当該のスプレッドシートのデータにアクセスすることができるようになります。

Streamlit側の設定・構築

ここでは、以下のようなディレクトリ構造とし、Streamlitアプリを構築します。

project-name/
│
├── app.py               
└── service_key.json    
  1. Projectディレクトリに移動し、Streamlitフレームワークをインストールします。
cd project-name
pip install streamlit
  1. 共通操作2で取得したjsonファイルを service_key.json として配置します。
  2. app.py にコードを記述し、Srtreamlitアプリを構築します。
import streamlit as st
from google.oauth2 import service_account
import gspread
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime

# Add a title to the app
st.title('Dashboard')

# Google Sheets Authentication
scopes = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'
]
credentials = service_account.Credentials.from_service_account_file( "./service_key.json", scopes=scopes
)
gc = gspread.authorize(credentials)

# Get data from Google Sheets
SP_SHEET_KEY = '{Sheet ID}' # sheet id (which can be found in the URL of the Google Sheet, after https://docs.google.com/spreadsheets/d/)
sh = gc.open_by_key(SP_SHEET_KEY)
SP_SHEET = 'test' # Sheet name
worksheet = sh.worksheet(SP_SHEET)
data = worksheet.get_all_values() # Get all data from the sheet
df = pd.DataFrame(data[1:], columns=data[0]) # Convert data to DataFrame

# Display original DataFrame (limited to 100 rows with scrolling)
st.subheader('Original Data')
st.dataframe(df.head(100), height=400)  # height parameter adds scrolling capability

# Check if 'Created Date' column exists
if 'Created Date' in df.columns:
    # Convert to datetime format (adjust format as needed)
    df['Created Date'] = pd.to_datetime(df['Created Date'])
    
    # Group by date and count records
    count_by_date = df.groupby(df['Created Date'].dt.date).size().reset_index()
    count_by_date.columns = ['Created Date', 'Count']
    
    # Sort by Created Date in descending order
    count_by_date = count_by_date.sort_values('Created Date', ascending=False)
    
    # Create two columns for side-by-side display
    st.subheader('Record Count by Date')
    col1, col2 = st.columns([3, 2])  # Adjust the ratio to make the first column wider
    
    # Display grouped DataFrame in the first column
    with col1:
        st.dataframe(count_by_date.head(100), height=400)
    
    # Create line chart in the second column
    with col2:
        # For the chart, we need to sort by date in ascending order
        chart_data = count_by_date.sort_values('Created Date', ascending=True)
        st.line_chart(chart_data.set_index('Created Date'))
else:
    st.error("'Created Date' column not found in the DataFrame. Please check the column name.")
    st.write("Available columns:", df.columns.tolist())
  1. ターミナルで以下を実行し、3で構築したアプリをブラウザで確認してみます。
streamlit run app.py

output

社内運用のために必要な認証機能の追加

Streamlitアプリの社内運用で必要になるのが、アプリへの認証機能です。ここでは、3パターンの認証機能を付与する手段をお伝えします。利用するアプリの少なければ1つ目の方法でもよいかもしれませんが、利用するアプリが複数ある、または今後増える見込みの場合は2や3の方法がおすすめです。

  1. アプリ個別に認証機能を実装する
    Streamlitのバージョン1.42.0からOpenID Connect(OIDC)によるユーザー認証機能が追加されました。このビルトインの認証機能を使って実装することが可能です。
  • メリット:柔軟な認証機能の実装が可能
  • デメリット:個別に実装が必要なため、工数が増える

公式ドキュメント:https://docs.streamlit.io/develop/concepts/connections/authentication

  1. Snowflake in Streamlitを利用する
    Snowflake in StreamlitはSnowflakeのプラットフォーム上でStreamlitアプリを構築する機能です。Snowflakeへの認証がStreamlitアプリへも適用されるため認証機能の個別実装が不要です。
  • メリット:認証機能のアプリへの個別実装が不要
  • デメリット:Snowflakeアカウントを発行する必要がある / 利用できるStreamlitコンポーネントが限られる(OSSで利用できるものより少ない)

公式ドキュメント:https://docs.snowflake.com/ja/developer-guide/streamlit/about-streamlit

  1. Morphを利用する
    MorphはStreamlitをデプロイ可能なクラウドプラットフォームです。構築したStreamlitアプリのデプロイ先をMorphにすることで、Morphのビルトインの認証機能がStreamlitアプリに適用されるため、認証機能の個別実装が不要です。
  • メリット:認証機能のアプリへの個別実装が不要 / 構築したアプリの一元的な管理が可能
  • デメリット:利用する外部サービスが増える(Morph)

公式ドキュメント:https://www.morph-data.io/ja

まとめ

Streamlitは、Pythonに慣れているデータサイエンティストやアナリストが、機械学習やAIを活用したデータアプリケーションを構築するときに最適です。具体的には、LLMを活用した業務自動化ツールや需要予測ツール、社内ドキュメントを参照して回答するチャットボットの作成などが適合するユースケースになります。活用できる範囲は幅広いので、ぜひ、皆様も試してみてください!

Morphテックブログ

Discussion