Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 104 additions & 93 deletions day1/01_streamlit_UI/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,149 +36,160 @@
st.write(f"こんにちは、{name}さん!")

# ボタン
# st.subheader("ボタン")
# if st.button("クリックしてください"):
# st.success("ボタンがクリックされました!")
st.subheader("ボタン")
if st.button("おめでとう"):
st.balloons()
st.success("happy")

# チェックボックス
# st.subheader("チェックボックス")
# if st.checkbox("チェックを入れると追加コンテンツが表示されます"):
# st.info("これは隠れたコンテンツです!")
st.subheader("チェックボックス")
if st.checkbox("チェックを入れると追加コンテンツが表示されます"):
st.info("これは隠れたコンテンツです!")

# スライダー
# st.subheader("スライダー")
# age = st.slider("年齢", 0, 100, 25)
# st.write(f"あなたの年齢: {age}")
st.subheader("スライダー")
age = st.slider("あなたの年齢は?", 0, 100, 25)
if age < 18:
st.write("未成年")
elif age < 65:
st.write("成人")
else:
st.write("高齢者")

# セレクトボックス
# st.subheader("セレクトボックス")
# option = st.selectbox(
# "好きなプログラミング言語は?",
# ["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
# )
# st.write(f"あなたは{option}を選びました")
st.subheader("セレクトボックス")
option = st.selectbox(
"好きなプログラミング言語は?",
["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
)
st.write(f"あなたは{option}を選びました")

# ============================================
# レイアウト
# ============================================
# st.header("レイアウト")
st.header("レイアウト")

# カラム
# st.subheader("カラムレイアウト")
# col1, col2 = st.columns(2)
# with col1:
# st.write("これは左カラムです")
# st.number_input("数値を入力", value=10)
# with col2:
# st.write("これは右カラムです")
# st.metric("メトリクス", "42", "2%")
st.subheader("カラムレイアウト")
col1, col2 = st.columns(2)
with col1:
st.write("これは左カラムです")
st.number_input("数値を入力", value=10)
with col2:
st.write("これは右カラムです")
st.metric("あなたの入力した数", number)

# タブ
# st.subheader("タブ")
# tab1, tab2 = st.tabs(["第1タブ", "第2タブ"])
# with tab1:
# st.write("これは第1タブの内容です")
# with tab2:
# st.write("これは第2タブの内容です")
st.subheader("タブ")
tab1, tab2 = st.tabs(["第1タブ", "第2タブ"])
with tab1:
st.write("これは第1タブの内容です")
with tab2:
st.write("これは第2タブの内容です")

# エクスパンダー
# st.subheader("エクスパンダー")
# with st.expander("詳細を表示"):
# st.write("これはエクスパンダー内の隠れたコンテンツです")
# st.code("print('Hello, Streamlit!')")
# エクスパンダー
st.subheader("エクスパンダー")
with st.expander("アンケートに答える"):
name = st.text_input("お名前を入力してください")
feedback = st.text_area("ご意見・ご感想")
submit = st.button("送信")
if submit:
st.success(f"{name}さん、ご回答ありがとうございました!")


# ============================================
# データ表示
# ============================================
# st.header("データの表示")
st.header("データの表示")

# サンプルデータフレームを作成
# df = pd.DataFrame({
# '名前': ['田中', '鈴木', '佐藤', '高橋', '伊藤'],
# '年齢': [25, 30, 22, 28, 33],
# '都市': ['東京', '大阪', '福岡', '札幌', '名古屋']
# })
df = pd.DataFrame({
'名前': ['田中', '鈴木', '佐藤', '高橋', '伊藤'],
'年齢': [25, 30, 22, 28, 33],
'都市': ['東京', '大阪', '福岡', '札幌', '名古屋']
})

# データフレーム表示
# st.subheader("データフレーム")
# st.dataframe(df, use_container_width=True)
st.subheader("データフレーム")
st.dataframe(df, use_container_width=True)

# テーブル表示
# st.subheader("テーブル")
# st.table(df)
st.subheader("テーブル")
st.table(df)

# メトリクス表示
# st.subheader("メトリクス")
# col1, col2, col3 = st.columns(3)
# col1.metric("温度", "23°C", "1.5°C")
# col2.metric("湿度", "45%", "-5%")
# col3.metric("気圧", "1013hPa", "0.1hPa")
st.subheader("メトリクス")
col1, col2, col3 = st.columns(3)
col1.metric("温度", "23°C", "1.5°C")
col2.metric("湿度", "45%", "-5%")
col3.metric("気圧", "1013hPa", "0.1hPa")

# ============================================
# グラフ表示
# ============================================
# st.header("グラフの表示")
st.header("グラフの表示")

# ラインチャート
# st.subheader("ラインチャート")
# chart_data = pd.DataFrame(
# np.random.randn(20, 3),
# columns=['A', 'B', 'C'])
# st.line_chart(chart_data)
st.subheader("ラインチャート")
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['A', 'B', 'C'])
st.line_chart(chart_data)

# バーチャート
# st.subheader("バーチャート")
# chart_data = pd.DataFrame({
# 'カテゴリ': ['A', 'B', 'C', 'D'],
# '値': [10, 25, 15, 30]
# }).set_index('カテゴリ')
# st.bar_chart(chart_data)
st.subheader("バーチャート")
chart_data = pd.DataFrame({
'カテゴリ': ['A', 'B', 'C', 'D'],
'値': [10, 25, 15, 30]
}).set_index('カテゴリ')
st.bar_chart(chart_data)

# ============================================
# インタラクティブ機能
# ============================================
# st.header("インタラクティブ機能")
st.header("インタラクティブ機能")

# プログレスバー
# st.subheader("プログレスバー")
# progress = st.progress(0)
# if st.button("進捗をシミュレート"):
# for i in range(101):
# time.sleep(0.01)
# progress.progress(i / 100)
# st.balloons()
st.subheader("プログレスバー")
progress = st.progress(0)
if st.button("進捗をシミュレート"):
for i in range(101):
time.sleep(0.01)
progress.progress(i / 100)
st.balloons()

# ファイルアップロード
# st.subheader("ファイルアップロード")
# uploaded_file = st.file_uploader("ファイルをアップロード", type=["csv", "txt"])
# if uploaded_file is not None:
# # ファイルのデータを表示
# bytes_data = uploaded_file.getvalue()
# st.write(f"ファイルサイズ: {len(bytes_data)} bytes")
#
# # CSVの場合はデータフレームとして読み込む
# if uploaded_file.name.endswith('.csv'):
# df = pd.read_csv(uploaded_file)
# st.write("CSVデータのプレビュー:")
# st.dataframe(df.head())
st.subheader("ファイルアップロード")
uploaded_file = st.file_uploader("ファイルをアップロード", type=["csv", "txt"])
if uploaded_file is not None:
# ファイルのデータを表示
bytes_data = uploaded_file.getvalue()
st.write(f"ファイルサイズ: {len(bytes_data)} bytes")

# CSVの場合はデータフレームとして読み込む
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
st.write("CSVデータのプレビュー:")
st.dataframe(df.head())

# ============================================
# カスタマイズ
# ============================================
# st.header("スタイルのカスタマイズ")
st.header("スタイルのカスタマイズ")

# カスタムCSS
# st.markdown("""
# <style>
# .big-font {
# font-size:20px !important;
# font-weight: bold;
# color: #0066cc;
# }
# </style>
# """, unsafe_allow_html=True)
#
# st.markdown('<p class="big-font">これはカスタムCSSでスタイリングされたテキストです!</p>', unsafe_allow_html=True)
st.markdown("""
<style>
.big-font {
font-size:20px !important;
font-weight: bold;
color: #0066cc;
}
</style>
""", unsafe_allow_html=True)

st.markdown('<p class="big-font">これはカスタムCSSでスタイリングされたテキストです!</p>', unsafe_allow_html=True)

# ============================================
# デモの使用方法
Expand Down
78 changes: 49 additions & 29 deletions day1/02_streamlit_app/ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,7 @@

# --- チャットページのUI ---
def display_chat_page(pipe):
"""チャットページのUIを表示する"""
st.subheader("質問を入力してください")
user_question = st.text_area("質問", key="question_input", height=100, value=st.session_state.get("current_question", ""))
submit_button = st.button("質問を送信")


# セッション状態の初期化(安全のため)
if "current_question" not in st.session_state:
st.session_state.current_question = ""
Expand All @@ -24,37 +20,61 @@ def display_chat_page(pipe):
if "feedback_given" not in st.session_state:
st.session_state.feedback_given = False

# 回答が表示されるべきか判断 (質問があり、回答が生成済みで、まだフィードバックされていない)
if st.session_state.current_question and st.session_state.current_answer:
st.markdown(
f"""
<div style="background-color: #A8D5BA; padding: 12px; border-top-left-radius: 12px; border-top-right-radius: 12px;
border-bottom-left-radius: 12px; border-bottom-right-radius: 2px; max-width: 70%; margin-bottom: 10px;
margin-left: auto; color: #000000; font-size: 16px; font-weight: 500;">
{st.session_state.current_question}
</div>
""",
unsafe_allow_html=True
)

st.markdown(
f"""
<div style="background-color: #E6ECF0; padding: 12px; border-top-left-radius: 12px; border-top-right-radius: 12px;
border-bottom-right-radius: 12px; border-bottom-left-radius: 2px; max-width: 70%; margin-bottom: 10px;
margin-right: auto; color: #000000; font-size: 16px; font-weight: 400;">
{st.session_state.current_answer}
</div>
""",
unsafe_allow_html=True
)
st.info(f"応答時間: {st.session_state.response_time:.2f}秒")

"""チャットページのUIを表示する"""
st.subheader("質問を入力してください")
user_question = st.text_area("質問", key="question_input", height=100, value=st.session_state.get("current_question", ""))
submit_button = st.button("質問を送信")

# 質問が送信された場合
if submit_button and user_question:
st.session_state.current_question = user_question
st.session_state.current_answer = "" # 回答をリセット
st.session_state.feedback_given = False # フィードバック状態もリセット

with st.spinner("モデルが回答を生成中..."):
answer, response_time = generate_response(pipe, user_question)
st.session_state.current_answer = answer
st.session_state.response_time = response_time
# ここでrerunすると回答とフィードバックが一度に表示される
st.rerun()

# 回答が表示されるべきか判断 (質問があり、回答が生成済みで、まだフィードバックされていない)
if st.session_state.current_question and st.session_state.current_answer:
st.subheader("回答:")
st.markdown(st.session_state.current_answer) # Markdownで表示
st.info(f"応答時間: {st.session_state.response_time:.2f}秒")

# フィードバックフォームを表示 (まだフィードバックされていない場合)
if not st.session_state.feedback_given:
display_feedback_form()
else:
# フィードバック送信済みの場合、次の質問を促すか、リセットする
if st.button("次の質問へ"):
# 状態をリセット
st.session_state.current_question = ""
st.session_state.current_answer = ""
st.session_state.response_time = 0.0
st.session_state.feedback_given = False
st.rerun() # 画面をクリア
answer, response_time = generate_response(pipe, user_question)
st.session_state.current_answer = answer
st.session_state.response_time = response_time
# ここでrerunすると回答とフィードバックが一度に表示される
st.rerun()

# フィードバックフォームを表示 (まだフィードバックされていない場合)
if not st.session_state.feedback_given:
display_feedback_form()
else:
# フィードバック送信済みの場合、次の質問を促すか、リセットする
if st.button("次の質問へ"):
# 状態をリセット
st.session_state.current_question = ""
st.session_state.current_answer = ""
st.session_state.response_time = 0.0
st.session_state.feedback_given = False
st.rerun() # 画面をクリア


def display_feedback_form():
Expand Down
1 change: 1 addition & 0 deletions lecture-ai-engineering
Submodule lecture-ai-engineering added at 918e61