-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn-test.py
82 lines (72 loc) · 2.68 KB
/
n-test.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
import os
import openai
from dotenv import load_dotenv
import time
import speech_recognition as sr
import pyttsx3
import numpy as np
# from os.path import join, dirname
# import matplotlib.pyplot as plt
# ^ matplotlib is great for visualising data and for testing purposes but usually not needed for production
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
model = 'gpt-3.5-turbo'
# Set up the speech recognition and text-to-speech engines
r = sr.Recognizer()
engine = pyttsx3.init()
voice = engine.getProperty('voices')[0]
engine.setProperty('voice', voice.id)
name = "Jonas"
greetings = [f"whats up master {name}",
"yeah?",
"Well, hello there, Master of Puns and Jokes - how's it going today?",
f"Ahoy there, Captain {name}! How's the ship sailing?",
f"Bonjour, Monsieur {name}! Comment ça va? Wait, why the hell am I speaking French?" ]
# Listen for the wake word "hey pos"
def listen_for_wake_word(source):
print("Listening for 'Hey POS'...")
while True:
audio = r.listen(source)
try:
text = r.recognize_google(audio)
if "hey pos" in text.lower():
print("Wake word detected.")
engine.say(np.random.choice(greetings))
engine.runAndWait()
listen_and_respond(source)
break
except sr.UnknownValueError:
pass
# Listen for input and respond with OpenAI API
def listen_and_respond(source):
print("Listening...")
while True:
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print(f"You said: {text}")
if not text:
continue
# Send input to OpenAI API
response = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": f"{text}"}])
response_text = response.choices[0].message.content
print(f"OpenAI response: {response_text}")
# Speak the response
engine.say(response_text)
engine.runAndWait()
if not audio:
listen_for_wake_word(source)
except sr.UnknownValueError:
time.sleep(2)
print("Silence found, shutting up, listening...")
listen_for_wake_word(source)
break
except sr.RequestError as e:
print(f"Could not request results; {e}")
engine.say(f"Could not request results; {e}")
engine.runAndWait()
listen_for_wake_word(source)
break
# Use the default microphone as the audio source
with sr.Microphone() as source:
listen_for_wake_word(source)