간단하게 사용자의 음성을 듣고 파일에 기록한후에 다시 재생하는 코드를 만들었다.
Chat GPT에서 받은 답변을 출력하도록 변경하면 음성비서가 완성될 듯 하다.
모듈 설치
pip install SpeechRecognition
conda install pyaudio -y
pip install gtts
pip install playsound==1.2.2
pip openai
파이썬 코드
파일에서 읽어오기 위해서 test.txt 파일을 만들고 응답을 기록하기 위해서 response.txt를 만든다음에
아래와 같은 코드를 작성해서 실행한다.
openai.api_key = 'your openapi key'
이곳에는 openapi에서 받아 놓은 키를 넣는다.
from gtts import gTTS
from playsound import playsound
import speech_recognition as sr
import os
import openai
openai.api_key = 'your openapi key'
os.chdir(os.path.dirname(os.path.abspath(__file__)))
try:
#while True :
r = sr.Recognizer()
with sr.Microphone() as source:
print("음성을 입력하세요.")
audio = r.record(source, offset=1, duration=3)
try:
print("음성변환: "+ r.recognize_google(audio, language='ko-KR'))
with open('test.txt', 'w', encoding='utf-8') as f:
f.write(r.recognize_google(audio, language='ko-KR'))
except sr.UnknownValueError:
print("오디오를 이해할수 없습니다.")
except sr.RequestError as e:
print(f"에러가 발생했습니다. 에러원인: {e}")
except KeyboardInterrupt:
pass
file_path = 'test.txt'
with open(file_path, 'rt', encoding='utf8') as f :
read_file = f.read()
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role":"user","content":read_file}]
)
print(completion.choices[0].message.content)
with open('response.txt', 'w', encoding='utf-8') as f:
f.write(completion.choices[0].message.content)
tts = gTTS(completion.choices[0].message.content, lang='ko')
tts.save("test.mp3")
playsound("test.mp3")
gpt가 상황에 맞게 대답을 해준다.
개인 비서가 완성되었다.
gTTS가 한국어로는 남자 밖에 지원하지 않아서 다른 음성 변환 모듈을 사용해서 여자 목소리를 지원해야 겠다.
'Chat GPT' 카테고리의 다른 글
티스토리 API 사용을 위한 준비 (0) | 2023.07.06 |
---|---|
스테이블 디퓨전으로 그림 그리기 (0) | 2023.07.03 |
이미지 크롤링을 해보자 (0) | 2023.07.03 |
댓글