0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamlitを用いた簡易解析アプリのテンプレート

Posted at

実験データ(CSV,Txt)などを読み込んで、簡易な解析を行うアプリの要望があります。
そこで、データファイルをアップロード、可視化及び解析、解析グラフの保存の一連の処理を行うStreamlitのひな形を作成しました。テンプレートはこちらにも載せておきます。Streamlit_template
また、StremlitをExe化して配布することもできます。その場合はこちらの記事を参考にしていただければと思います。
StreamlitのEXE化

このテンプレートでは、以下の処理を行います。

  1. CSVデータファイルをアップロード
  2. データを読み込みグラフ表示
  3. 表示したグラフをダウンロード

また、このテンプレートを利用した例はこちらになります。
測定ファイルを読み込んで、可視化し、Fittingを行いその結果を表示・ダウンロードするプログラム

環境

このテンプレートを作成した環境は以下の通りです。

  • windows 11 pro
  • miniconda
  • Python 3.10
  • modules: streamlit, numpy, pandas, matplotlib
  • グラフに日本語表記が必要ならば: japanize_matplotlib

コード

from io import BytesIO
from pathlib import Path
from tempfile import NamedTemporaryFile
import zipfile

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt


def plot_df(df):
    # ファイルの読み込み、可視化、解析の処理を実装します。
    xx = df.iloc[:, 0].values
    yy = df.iloc[:, 1].values

    fig = plt.figure(figsize=(4,3), tight_layout=True)
    ax = fig.add_subplot(1,1,1)
    ax.set_title('CSV Plot')
    ax.plot(xx,yy,'ro-',label='Data')
    ax.legend()
    ax.grid()
    ax.set_xlabel('x')
    ax.set_ylabel('y')
 
    return fig

def main():
    st.title("CSV file Viewer")
    
    download_zip_file = st.empty()
    uploaded_files = st.file_uploader("CSV files upload", accept_multiple_files=True, type=["csv"])

    figures = []
    if uploaded_files:
        for uploaded_file in uploaded_files:
            with NamedTemporaryFile(delete=False) as f:
                fp = Path(f.name)
                fp.write_bytes(uploaded_file.getvalue())
                
                df_ = pd.read_csv(f'{f.name}')

            fp.unlink()
            
            fig = plot_df(df_)
            st.pyplot(fig)
            figures.append((fig, uploaded_file.name))

        def create_zip():
            in_memory = BytesIO()
            with zipfile.ZipFile(in_memory, 'w', zipfile.ZIP_DEFLATED) as zf:
                for fig, name in figures:
                    img_bytes = BytesIO()
                    fig.savefig(img_bytes, format='png')
                    img_bytes.seek(0)
                    zf.writestr(f"{Path(name).stem}.png", img_bytes.read())
            in_memory.seek(0)
            return in_memory

        zip_buffer = create_zip()
        download_zip_file.download_button(
            label="Download (zip)",
            data=zip_buffer,
            file_name='graphs.zip',
            mime='application/zip' )

if __name__ == "__main__":
    main()
    
    # streamlit run .\CSV_viewer.py

実行する場合、ターミナルでtreamlit run .\CSV_viewer.pyと入力してください。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?