ll7098ll commited on
Commit
022a7a0
·
verified ·
1 Parent(s): 2eb7796

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -52
app.py CHANGED
@@ -2,80 +2,92 @@ import os
2
  import time
3
 
4
  import google.generativeai as genai
5
- import gradio
6
 
7
- # Google Gemini API 설정
8
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
9
 
10
  # 모델 설정
11
  generation_config = {
12
- "temperature": 0.8,
13
  "top_p": 0.95,
14
  "top_k": 64,
15
- "max_output_tokens": 1024,
16
  "response_mime_type": "text/plain",
17
  }
 
18
  model = genai.GenerativeModel(
19
  model_name="gemini-1.5-pro",
20
  generation_config=generation_config,
21
- system_instruction="""뛰어난 전문성을 갖춘 언어 치료 전문가, 한글 교육 전문가, 한국어 발음 교정 전문가로서 친절하고 공감하는 태도로 사용자와 상담을 진행하세요.""",
22
  )
23
 
24
- # 상담 내용 저장
25
  chat_history = []
26
- chat_session = None
27
 
28
 
29
- def add_message(history, message):
30
- history = history + [(message, None)]
31
- return history, ""
 
 
 
 
32
 
 
 
 
 
 
 
33
 
34
- def predict(message, history):
35
- global chat_session
36
- if chat_session is None:
37
- chat_session = model.start_chat()
38
 
39
- if message.strip() == "":
40
- return history, ""
 
 
 
41
 
42
- history = history + [(message, None)]
43
- response = chat_session.send_message(message).text
44
 
45
- # 타이핑 효과를 위해 한 글자씩 출력
46
- for i in range(len(response) + 1):
 
 
 
47
  time.sleep(0.03)
48
- yield history + [(message, response[:i])]
49
 
 
50
 
51
- def new_session():
52
- global chat_session, chat_history
53
- chat_session = None
54
- chat_history = []
55
- return chat_history
56
-
57
-
58
- def save_history(history):
59
- file_path = "./chat_history.txt"
60
- with open(file_path, "w", encoding="utf-8") as f:
61
- for user_msg, ai_msg in history:
62
- f.write(f"사용자: {user_msg}\n")
63
- if ai_msg:
64
- f.write(f"AI: {ai_msg}\n")
65
- return "상담 내용이 저장되었습니다."
66
-
67
-
68
- with gradio.Interface(
69
- fn=predict,
70
- inputs=[
71
- gradio.components.Textbox(lines=1, placeholder="메시지를 입력하세요"), # gradio.components.Textbox로 변경
72
- gradio.components.State(value=[]), # gradio.components.State로 변경
73
- ],
74
- outputs=[
75
- gradio.components.Chatbot(label="언어 치료 AI 상담 챗봇"), # gradio.components.Chatbot로 변경
76
- gradio.components.Textbox(visible=False), # gradio.components.Textbox로 변경
77
- ],
78
- title="언어 치료 AI 상담 챗봇",
79
- description="AI 언어 치료사와 상담해보세요.",
80
- ) as iface:
81
- iface.launch(share=True)
 
2
  import time
3
 
4
  import google.generativeai as genai
5
+ from gradio import gradio as gr
6
 
7
+ # Google AI Python SDK 설정
8
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
9
 
10
  # 모델 설정
11
  generation_config = {
12
+ "temperature": 1,
13
  "top_p": 0.95,
14
  "top_k": 64,
15
+ "max_output_tokens": 8192,
16
  "response_mime_type": "text/plain",
17
  }
18
+
19
  model = genai.GenerativeModel(
20
  model_name="gemini-1.5-pro",
21
  generation_config=generation_config,
22
+ system_instruction="언어 치료 전문가, 한글 교육 전문가, 한국어 발음 교정 전문가",
23
  )
24
 
25
+ # 대화 기록
26
  chat_history = []
 
27
 
28
 
29
+ def add_to_chat_history(message, speaker):
30
+ """
31
+ 챗봇 대화 기록에 메시지 추가
32
+ """
33
+ global chat_history
34
+ chat_history.append({"speaker": speaker, "message": message})
35
+
36
 
37
+ def clear_chat_history():
38
+ """
39
+ 챗봇 대화 기록 초기화
40
+ """
41
+ global chat_history
42
+ chat_history = []
43
 
 
 
 
 
44
 
45
+ def generate_response(message):
46
+ """
47
+ 사용자 메시지에 대한 응답 생성
48
+ """
49
+ global chat_history
50
 
51
+ chat_session = model.start_chat(history=chat_history)
52
+ response = chat_session.send_message(message)
53
 
54
+ # 한 글자씩 출력 효과를 위한 코드
55
+ typed_response = ""
56
+ for char in response.text:
57
+ typed_response += char
58
+ yield typed_response
59
  time.sleep(0.03)
 
60
 
61
+ add_to_chat_history(response.text, "AI")
62
 
63
+
64
+ def display_chat_history():
65
+ """
66
+ 챗봇 대화 기록 출력
67
+ """
68
+ chat_output = ""
69
+ for message in chat_history:
70
+ chat_output += f"{message['speaker']}: {message['message']}\n"
71
+ return chat_output
72
+
73
+
74
+ with gr.Blocks() as demo:
75
+ # 챗봇 인터페이스 생성
76
+ chatbot = gr.Chatbot()
77
+ msg_input = gr.Textbox(label="메시지 입력")
78
+ clear_button = gr.Button("새로운 상담 시작하기")
79
+
80
+ # 메시지 전송 버튼 클릭 시 이벤트 처리
81
+ msg_input.submit(
82
+ generate_response, msg_input, chatbot, queue=True
83
+ ).then(display_chat_history, chatbot)
84
+
85
+ # 새로운 상담 시작하기 버튼 클릭 시 이벤트 처리
86
+ clear_button.click(
87
+ clear_chat_history,
88
+ None,
89
+ chatbot,
90
+ ).then(lambda: "", chatbot)
91
+
92
+ # 데모 실행
93
+ demo.launch()