-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch03_voicebot.py
173 lines (143 loc) · 6.96 KB
/
ch03_voicebot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
##### 기본 정보 입력 #####
import streamlit as st
# audiorecorder 패키지 추가
from audiorecorder import audiorecorder
# OpenAI 패키기 추가
import openai
# 파일 삭제를 위한 패키지 추가
import os
# 시간 정보를 위핸 패키지 추가
from datetime import datetime
# 오디오 array 비교를 위한 numpy 패키지 추가
import numpy as np
# TTS 패키기 추가
from gtts import gTTS
# 음원파일 재생을 위한 패키지 추가
import base64
##### 기능 구현 함수 #####
def STT(audio):
# 파일 저장
filename='input.mp3'
wav_file = open(filename, "wb")
wav_file.write(audio.tobytes())
wav_file.close()
# 음원 파일 열기
audio_file = open(filename, "rb")
#Whisper 모델을 활용해 텍스트 얻기
transcript = openai.Audio.transcribe("whisper-1", audio_file)
audio_file.close()
# 파일 삭제
os.remove(filename)
return transcript["text"]
def ask_gpt(prompt, model):
response = openai.ChatCompletion.create(model=model, messages=prompt)
system_message = response["choices"][0]["message"]
return system_message["content"]
def TTS(response):
# gTTS 를 활용하여 음성 파일 생성
filename = "output.mp3"
tts = gTTS(text=response,lang="ko")
tts.save(filename)
# 음원 파일 자동 재성
with open(filename, "rb") as f:
data = f.read()
b64 = base64.b64encode(data).decode()
md = f"""
<audio autoplay="True">
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
</audio>
"""
st.markdown(md,unsafe_allow_html=True,)
# 파일 삭제
os.remove(filename)
##### 메인 함수 #####
def main():
# 기본 설정
st.set_page_config(
page_title="AI 컨설턴트 피터 드러커와 함께하는 기업 살리기 프로젝트",
layout="wide")
flag_start = False
# session state 초기화
if "chat" not in st.session_state:
st.session_state["chat"] = []
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "system", "content": "You are a thoughtful like a management consultant like Peter Drucker or Philip Kotler. Respond to all input in 25 words and answer in korea"}]
if "check_audio" not in st.session_state:
st.session_state["check_audio"] = []
# 제목
st.header("AI 컨설턴트 피터 드러커와 함께하는 기업 살리기 프로젝트")
# 구분선
st.markdown("---")
# 기본 설명
with st.expander("AI 경영컨설턴트 음성 비서 프로그램에 관하여", expanded=True):
st.write(
"""
- AI 컨설턴트 피터 드러커와 함께하는 기업 살리기 프로젝트.
- AI를 활용한 행동관찰모형과 마케팅전략 컨설팅을 제공해 줄 수 있는,
- 피터 드러커의 책과 논문을 학습시켜 만들었습니다.
- Initiative / Narrative (새로운 일을 객관적으로 주도하고 성공 스토리를 제공)
-------------------------------------------------------------------
- 음성비서 프로그램의 UI는 스트림릿을 활용했습니다.
- STT(Speech-To-Text)는 OpenAI의 Whisper AI를 활용했습니다.
- 답변은 OpenAI의 GPT 모델을 활용했습니다.
- TTS(Text-To-Speech)는 구글의 Google Translate TTS를 활용했습니다.
"""
)
st.markdown("")
# 사이드바 생성
with st.sidebar:
# Open AI API 키 입력받기
openai.api_key = st.text_input(label="OPENAI API 키", placeholder="Enter Your API Key", value="", type="password")
st.markdown("---")
# GPT 모델을 선택하기 위한 라디오 버튼 생성
model = st.radio(label="GPT 모델",options=["gpt-4", "gpt-3.5-turbo"])
st.markdown("---")
# 리셋 버튼 생성
if st.button(label="초기화"):
# 리셋 코드
st.session_state["chat"] = []
st.session_state["messages"] = [{"role": "system", "content": "You are a thoughtful like a management consultant like Peter Drucker. Respond to all input in 25 words and answer in korea"}]
# 기능 구현 공간
col1, col2 = st.columns(2)
with col1:
# 왼쪽 영역 작성
st.subheader("질문하기")
# 음성 녹음 아이콘 추가
audio = audiorecorder("클릭하여 녹음하기", "녹음중...")
if len(audio) > 0 and not np.array_equal(audio,st.session_state["check_audio"]):
# 음성 재생
st.audio(audio.tobytes())
# 음원 파일에서 텍스트 추출
question = STT(audio)
# 채팅을 시각화하기 위해 질문 내용 저장
now = datetime.now().strftime("%H:%M")
st.session_state["chat"] = st.session_state["chat"]+ [("user",now, question)]
# GPT 모델에 넣을 프롬프트를 위해 질문 내용 저장
st.session_state["messages"] = st.session_state["messages"]+ [{"role": "user", "content": question}]
# audio 버퍼 확인을 위해 현 시점 오디오 정보 저장
st.session_state["check_audio"] = audio
flag_start =True
with col2:
# 오른쪽 영역 작성
st.subheader("질문/답변")
if flag_start:
#ChatGPT에게 답변 얻기
response = ask_gpt(st.session_state["messages"], model)
# GPT 모델에 넣을 프롬프트를 위해 답변 내용 저장
st.session_state["messages"] = st.session_state["messages"]+ [{"role": "system", "content": response}]
# 채팅 시각화를 위한 답변 내용 저장
now = datetime.now().strftime("%H:%M")
st.session_state["chat"] = st.session_state["chat"]+ [("bot",now, response)]
# 채팅 형식으로 시각화 하기
for sender, time, message in st.session_state["chat"]:
if sender == "user":
st.write(f'<div style="display:flex;align-items:center;"><div style="background-color:#007AFF;color:white;border-radius:12px;padding:8px 12px;margin-right:8px;">{message}</div><div style="font-size:0.8rem;color:gray;">{time}</div></div>', unsafe_allow_html=True)
st.write("")
else:
st.write(f'<div style="display:flex;align-items:center;justify-content:flex-end;"><div style="background-color:lightgray;border-radius:12px;padding:8px 12px;margin-left:8px;">{message}</div><div style="font-size:0.8rem;color:gray;">{time}</div></div>', unsafe_allow_html=True)
st.write("")
# gTTS 를 활용하여 음성 파일 생성 및 재생
TTS(response)
if __name__=="__main__":
main()