ll7098ll commited on
Commit
c93bda6
·
verified ·
1 Parent(s): d919799

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -31
app.py CHANGED
@@ -1,9 +1,11 @@
1
  import os
2
  import time
3
  import google.generativeai as genai
4
- import gradio as gr
5
  import re
 
6
 
 
7
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
8
 
9
  # 모델 설정
@@ -24,7 +26,6 @@ safety_settings = [
24
  # 전역 변수로 chat_session 초기화
25
  chat_session = None
26
 
27
-
28
  def start_new_chat_session():
29
  global chat_session
30
  chat_session = (
@@ -39,18 +40,29 @@ def start_new_chat_session():
39
  .start_chat(history=[])
40
  )
41
 
42
-
43
  # 초기 세션 시작
44
  start_new_chat_session()
45
 
 
 
 
 
46
 
47
- def respond(user_input, history):
48
- global chat_session
49
- history.append((user_input, ""))
50
- yield "", history # 초기 빈 텍스트 출력
51
 
 
 
 
 
 
 
 
 
 
52
  try:
53
- response = chat_session.send_message(user_input, stream=True)
54
  full_text = ""
55
 
56
  # 스트리밍 응답 처리
@@ -66,32 +78,25 @@ def respond(user_input, history):
66
  else:
67
  full_text += sentence
68
 
69
- history[-1] = (user_input, full_text)
70
- yield "", history
71
  time.sleep(0.03) # 출력 속도 조절
72
 
73
  except Exception as e:
74
- yield f"에러 발생: {str(e)}"
75
-
76
 
77
- def clear_chat():
78
- start_new_chat_session()
79
- return []
80
-
81
-
82
- with gr.Blocks() as demo:
83
- gr.Markdown(
84
- "<div style='font-size: 30px; font-weight: bold;'>AI 과학자</div>"
85
- )
86
- gr.Markdown(
87
- "과학에 대해 궁금한 점을 AI 과학자에게 질문하세요, 자유탐구에 대한 조언을 구하세요."
88
- )
89
- chatbot = gr.Chatbot(label="채팅창")
90
- msg = gr.Textbox(label="입력")
91
- clear = gr.Button("초기화")
92
 
93
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
94
- # chatbot 상태 초기화 및 새로운 세션 시작
95
- clear.click(clear_chat, outputs=chatbot, queue=False)
 
 
 
96
 
97
- demo.launch(share=True)
 
 
 
 
1
  import os
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
  # 모델 설정
 
26
  # 전역 변수로 chat_session 초기화
27
  chat_session = None
28
 
 
29
  def start_new_chat_session():
30
  global chat_session
31
  chat_session = (
 
40
  .start_chat(history=[])
41
  )
42
 
 
43
  # 초기 세션 시작
44
  start_new_chat_session()
45
 
46
+ # Streamlit 앱 설정
47
+ st.set_page_config(page_title="AI 과학자", layout="wide")
48
+ st.markdown("<div style='font-size: 30px; font-weight: bold;'>AI 과학자</div>", unsafe_allow_html=True)
49
+ st.markdown("과학에 대해 궁금한 점을 AI 과학자에게 질문하세요, 자유탐구에 대한 조언을 구하세요.")
50
 
51
+ # 채팅 히스토리 관리
52
+ if "history" not in st.session_state:
53
+ st.session_state.history = []
 
54
 
55
+ # 채팅 세션 초기화
56
+ if "chat_session" not in st.session_state:
57
+ st.session_state.chat_session = chat_session
58
+
59
+ # 사용자 입력 받기
60
+ user_input = st.text_input("입력", key="user_input")
61
+
62
+ def respond(user_input):
63
+ st.session_state.history.append({"user": user_input, "ai": ""})
64
  try:
65
+ response = st.session_state.chat_session.send_message(user_input, stream=True)
66
  full_text = ""
67
 
68
  # 스트리밍 응답 처리
 
78
  else:
79
  full_text += sentence
80
 
81
+ # 히스토리 최신 항목 업데이트
82
+ st.session_state.history[-1]["ai"] = full_text
83
  time.sleep(0.03) # 출력 속도 조절
84
 
85
  except Exception as e:
86
+ st.session_state.history[-1]["ai"] = f"에러 발생: {str(e)}"
 
87
 
88
+ # 응답 생성 및 출력
89
+ if user_input:
90
+ respond(user_input)
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ # 채팅 메시지 출력
93
+ for chat in st.session_state.history:
94
+ if "user" in chat:
95
+ message(chat["user"], is_user=True, key=f"user_{chat['user']}")
96
+ if "ai" in chat:
97
+ message(chat["ai"], is_user=False, key=f"ai_{chat['ai']}")
98
 
99
+ # 초기화 버튼 클릭 시
100
+ if st.button("초기화"):
101
+ start_new_chat_session()
102
+ st.session_state.history = []