-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
89 lines (71 loc) · 2.62 KB
/
main.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
import openai
import playsound
import time
import threading
import speech_recognition as sr
import logging
import traceback
from gtts import gTTS
from initialize import init_openai
logging.basicConfig(level=logging.ERROR) # Configures logging to show errors
lang = "en"
init_openai()
# Flag to signal when the text is currently being spoken
is_speaking = threading.Event()
def speak(text: str):
"""
Speak the given text using gTTS (Google Text-to-Speech).
Args:
- text (str): The text to be spoken.
Returns:
- None
"""
is_speaking.set() # Signal that the program is speaking
speech = gTTS(text=text, lang=lang, slow=False, tld="ie")
speech.save("output.mp3")
playsound.playsound("output.mp3") # Play the audio
time.sleep(len(text) * 0.06) # Rough estimation to ensure the event clears after the text is spoken
is_speaking.clear() # Reset the speaking flag
def get_audio():
r = sr.Recognizer()
with sr.Microphone(device_index=1) as source:
print("Listening...")
try:
audio = r.listen(source)
except sr.UnknownValueError:
logging.error("Google Speech Recognition could not understand audio")
return ""
except sr.RequestError as e:
logging.error("Could not request results from Google Speech Recognition service; {0}".format(e))
return ""
said = ""
try:
said = r.recognize_google(audio).lower()
print("You said", said)
if "" in said:
speak("Yes Goddess?")
messages = [
{"role": "system", "content": "You are a sassy assistant"},
{"role": "user", "content": said}
]
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=messages
)
print(completion)
speak(completion.choices[0].message.content)
if "stop" in said:
speak("Okay.")
return "stop"
except sr.UnknownValueError:
logging.error("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
logging.error("Could not request results from Google Speech Recognition service; {0}".format(e))
except Exception as e:
logging.error("An unexpected error occurred: {0}".format(repr(e)))
logging.error(traceback.format_exc()) # This will print the entire stack trace
return said
while True:
result = get_audio()
if result == "stop":
break