ll7098ll commited on
Commit
ad90ef7
·
verified ·
1 Parent(s): a6f461f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -47
app.py CHANGED
@@ -1,7 +1,5 @@
1
  import os
2
  import time
3
- import threading
4
-
5
  import gradio as gr
6
  import google.generativeai as genai
7
 
@@ -22,48 +20,32 @@ model = genai.GenerativeModel(
22
  system_instruction="초등학생이 교과 내용에 대해 이해할 수 있게 친절하게 설명하는 선생님. 다양한 예시와 구체적 사례를 들어서 설명. 사진이나 동영상 자료가 있으면 첨부. 출처 표시.",
23
  )
24
 
25
- # 세션 초기화
26
- chat_session = None
27
-
28
- # 출력 텍스트를 저장할 변수
29
- output_text = ""
30
-
31
- def chatbot_worker(input_text):
32
- global chat_session, output_text
33
- if chat_session is None:
34
- chat_session = model.start_chat()
35
-
36
- response = chat_session.send_message(input_text)
37
-
38
- # 실시간 타이핑 효과를 위한 코드
39
- for char in response.text:
40
- output_text += char
41
- time.sleep(0.02) # 타이핑 속도 조절
42
- yield output_text
43
-
44
- yield output_text
45
-
46
- def chatbot(input_text):
47
- global output_text
48
- output_text = ""
49
- thread = threading.Thread(target=chatbot_worker, args=(input_text,))
50
- thread.start()
51
- return output_text
52
-
53
- def clear_session():
54
- global chat_session, output_text
55
- chat_session = None
56
- output_text = ""
57
- return ""
58
-
59
- # Gradio 인터페이스 생성
60
- iface = gr.Interface(
61
- fn=chatbot,
62
- inputs=gr.Textbox(lines=5, placeholder="여기에 질문을 입력하세요..."),
63
- outputs=gr.Textbox(lines=10, placeholder="AI 선생님의 답변이 여기에 나타납니다...", label="AI 설명"),
64
- title="AI 선생님",
65
- description="초등 교과 과정에 대한 질문을 입력해보세요.",
66
- )
67
-
68
- # 초기화 버튼 추가
69
- iface.launch(share=True).queue().button(fn=clear_session, inputs=[], outputs=[iface.components[1]], label="초기화")
 
1
  import os
2
  import time
 
 
3
  import gradio as gr
4
  import google.generativeai as genai
5
 
 
20
  system_instruction="초등학생이 교과 내용에 대해 이해할 수 있게 친절하게 설명하는 선생님. 다양한 예시와 구체적 사례를 들어서 설명. 사진이나 동영상 자료가 있으면 첨부. 출처 표시.",
21
  )
22
 
23
+ def stream_response(message, history):
24
+ response = ""
25
+ for chunk in model.generate_content(message):
26
+ chunk_message = chunk.text
27
+ response += chunk_message
28
+ yield response
29
+ time.sleep(0.05)
30
+
31
+ # 인터페이스 구성
32
+ with gr.Blocks() as interface:
33
+ chatbot = gr.Chatbot()
34
+ msg = gr.Textbox()
35
+ clear = gr.Button("대화 초기화")
36
+
37
+ def user_message(user_message, history):
38
+ return "", history + [[user_message, None]]
39
+
40
+ def bot_message(history):
41
+ bot_message = stream_response(history[-1][0], history)
42
+ history[-1][1] = ""
43
+ return history
44
+
45
+ msg.submit(user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
46
+ bot_message, chatbot, chatbot
47
+ )
48
+ clear.click(lambda: None, None, chatbot, queue=False)
49
+
50
+ # 인터페이스 실행
51
+ interface.launch()