ll7098ll commited on
Commit
ef29ed7
·
verified ·
1 Parent(s): b7ce4c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -30
app.py CHANGED
@@ -2,10 +2,11 @@ import os
2
  import time
3
  import google.generativeai as genai
4
  import streamlit as st
 
5
  from streamlit_chat import message
6
 
7
  # Google Generative AI API 설정
8
- genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
9
 
10
  # 모델 설정
11
  generation_config = {
@@ -25,7 +26,6 @@ safety_settings = [
25
  # 전역 변수로 chat_session 초기화
26
  chat_session = None
27
 
28
- # 새로운 채팅 세션 시작 함수
29
  def start_new_chat_session():
30
  global chat_session
31
  chat_session = genai.GenerativeModel(
@@ -39,40 +39,67 @@ def start_new_chat_session():
39
  """,
40
  ).start_chat(history=[])
41
 
42
- # Streamlit UI 설정
43
- st.title("실시간 학습 보조 채팅 앱")
44
 
45
- # 세션 상태를 통해 채팅 히스토리 관리
46
- if "messages" not in st.session_state:
47
- st.session_state.messages = []
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  if "chat_session" not in st.session_state:
49
- start_new_chat_session()
50
  st.session_state.chat_session = chat_session
51
 
52
- # 사용자가 입력한 메시지 처리
53
- user_input = st.text_input("당신: ", key="user_input")
54
- if user_input:
55
- # 사용자 메시지 추가
56
- st.session_state.messages.append({"role": "user", "content": user_input})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- # AI 응답 생성
59
- response = st.session_state.chat_session.send_message(user_input)
60
- ai_message = response.text
61
- st.session_state.messages.append({"role": "assistant", "content": ai_message})
62
 
63
- # 입력 필드 초기화
64
- st.experimental_rerun()
 
65
 
66
- # 채팅 히스토리 표시
67
- for message in st.session_state.messages:
68
- if message["role"] == "user":
69
- message(message["content"], is_user=True)
70
- else:
71
- message(message["content"], is_user=False)
72
 
73
- # 새로운 채팅 세션 버튼
74
- if st.button("새로운 채팅 시작"):
75
  start_new_chat_session()
76
- st.session_state.chat_session = chat_session
77
- st.session_state.messages = []
78
- st.experimental_rerun()
 
2
  import time
3
  import google.generativeai as genai
4
  import streamlit as st
5
+ import re
6
  from streamlit_chat import message
7
 
8
  # Google Generative AI API 설정
9
+ genai.configure(api_key=os.environ["GEMINI_API_KEY"])
10
 
11
  # 모델 설정
12
  generation_config = {
 
26
  # 전역 변수로 chat_session 초기화
27
  chat_session = None
28
 
 
29
  def start_new_chat_session():
30
  global chat_session
31
  chat_session = genai.GenerativeModel(
 
39
  """,
40
  ).start_chat(history=[])
41
 
42
+ # 초기 세션 시작
43
+ start_new_chat_session()
44
 
45
+ # Streamlit 설정
46
+ st.set_page_config(page_title="질문하는 AI 선생님", layout="centered")
47
+
48
+ st.markdown(
49
+ """
50
+ <div style='font-size: 30px; font-weight: bold; text-align: center;'>질문하는 AI 선생님</div>
51
+ <div style='text-align: center; margin-bottom: 20px;'>학습주제를 입력하면, AI가 끊임 없는 질문을 통해 스스로 학습하게 도와줍니다.</div>
52
+ """,
53
+ unsafe_allow_html=True
54
+ )
55
+
56
+ # 채팅 히스토리 관리
57
+ if "history" not in st.session_state:
58
+ st.session_state.history = []
59
+
60
+ # 채팅 세션 초기화
61
  if "chat_session" not in st.session_state:
 
62
  st.session_state.chat_session = chat_session
63
 
64
+ # 사용자 입력 받기
65
+ user_input = st.text_input(
66
+ "입력", key="user_input", placeholder="여기에 학습 목표나 질문을 입력하세요...",
67
+ help="학습 목표를 입력하거나 학습하고자 하는 주제에 대한 질문을 입력하세요."
68
+ )
69
+
70
+ def respond(user_input):
71
+ st.session_state.history.append({"user": user_input, "ai": ""})
72
+ try:
73
+ response = st.session_state.chat_session.send_message(user_input, stream=True)
74
+ full_text = ""
75
+
76
+ # 스트리밍 응답 처리
77
+ for chunk in response:
78
+ chunk_text = chunk.text
79
+
80
+ # 단어 단위로 분리하여 실시간 출력
81
+ for word in chunk_text.split():
82
+ full_text += word + " "
83
+
84
+ # 히스토리 최신 항목 업데이트
85
+ st.session_state.history[-1]["ai"] = full_text
86
+ time.sleep(0.05) # 출력 속도 조절
87
 
88
+ except Exception as e:
89
+ st.session_state.history[-1]["ai"] = f"에러 발생: {str(e)}"
 
 
90
 
91
+ # 응답 생성 및 출력
92
+ if user_input:
93
+ respond(user_input)
94
 
95
+ # 채팅 메시지 출력
96
+ for chat in st.session_state.history:
97
+ if "user" in chat:
98
+ message(chat["user"], is_user=True, key=f"user_{chat['user']}")
99
+ if "ai" in chat:
100
+ message(chat["ai"], is_user=False, key=f"ai_{chat['ai']}")
101
 
102
+ # 초기화 버튼 클릭
103
+ if st.button("초기화"):
104
  start_new_chat_session()
105
+ st.session_state.history = []