-
Notifications
You must be signed in to change notification settings - Fork 0
/
final.py
215 lines (173 loc) · 6.62 KB
/
final.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from datetime import datetime
import asyncio
import base64
import json
import pyaudio
import pvporcupine
import struct
import websockets
import requests
from playsound import playsound
assembly_key = 'ea370242ab8c4e96a77affd669e1bd00'
porcupine_key = "rxNAR+cOa0S34wc6Z0JwTUB3VwBs9UoxyeeRs73k9ddIU1Eeo9lvZg=="
# Audio settings
FRAMES_PER_BUFFER = 3200
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
# AssemblyAI endpoint
URL = "wss://api.assemblyai.com/v2/realtime/ws?sample_rate=16000"
# Initialize PyAudio
p = pyaudio.PyAudio()
def generate_speech(input_text):
url = "https://api.openai.com/v1/audio/speech"
headers = {
"Authorization": "Bearer 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",
"Content-Type": "application/json"
}
payload = {
"model": "tts-1",
"input": input_text,
"voice": "alloy"
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status() # Raise an exception for 4xx or 5xx errors
filename = f'speech-{int(datetime.now().timestamp())}.mp3'
with open(filename, "wb") as f:
f.write(response.content)
playsound(filename)
print("Speech generated successfully.")
except requests.exceptions.RequestException as e:
print("Error generating speech:", e)
# LLM response
def llm_response(q):
"""client = Groq(
api_key="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"
)
chat_completion = client.chat.completions.create(
messages=[
# Set an optional system message. This sets the behavior of the
# assistant and can be used to provide specific instructions for
# how it should behave throughout the conversation.
{
"role": "system",
"content": "you are jarvis: a talking dog for kids. you give 1-2 sentence responses"
},
# Set a user message for the assistant to respond to.
{
"role": "user",
"content": q,
}
],
model="mixtral-8x7b-32768",
)"""
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer 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"
}
data = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": q}
]
}
response = requests.post(url, json=data, headers=headers)
response = response.json()
return response['choices'][0]['message']['content']
async def send_receive(stream):
global final_query
print(f'Connecting websocket to url ${URL}')
silence_counter = 0 # Counter to track consecutive silence detections
async with websockets.connect(
URL,
extra_headers=(("Authorization", assembly_key),),
ping_interval=5,
ping_timeout=20
) as ws:
await asyncio.sleep(0.1)
print("Receiving SessionBegins ...")
session_begins = await ws.recv()
print(session_begins)
print("Sending messages ...")
async def send():
nonlocal silence_counter
while True:
try:
data = stream.read(FRAMES_PER_BUFFER, exception_on_overflow=False)
data = base64.b64encode(data).decode("utf-8")
json_data = json.dumps({"audio_data": str(data)})
await ws.send(json_data)
if silence_counter >= 5: # Adjust this threshold as needed
print("Stopping due to silence.")
break
except websockets.exceptions.ConnectionClosedError as e:
print(e)
break
except Exception as e:
print("Error sending data: ", e)
break
await asyncio.sleep(0.01)
async def receive():
global final_query
nonlocal silence_counter
while True:
try:
result_str = await ws.recv()
result = json.loads(result_str)
print(result['text'])
if result['text'] == "":
silence_counter += 1
else:
silence_counter = 0
final_query += result['text'] + ", "
if silence_counter >= 5: # Adjust this threshold as needed
break
if ("goodbye") in result['text'].lower():
exit()
except websockets.exceptions.ConnectionClosedError as e:
print(e)
break
except Exception as e:
print("Error receiving data: ", e)
break
await asyncio.gather(send(), receive())
def start_listening():
global final_query # Declare it if you plan to use it outside of just sending and receiving
final_query = ""
porcupine = None
audio_stream = None
try:
porcupine = pvporcupine.create(keywords=["jarvis"], access_key=porcupine_key)
audio_stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=porcupine.frame_length
)
print("Listening for wake word...")
while True:
pcm = audio_stream.read(porcupine.frame_length, exception_on_overflow=False)
pcm_unpacked = struct.unpack_from("h" * porcupine.frame_length, pcm)
keyword_index = porcupine.process(pcm_unpacked)
if keyword_index >= 0:
print("Wake word detected! Starting to send audio...")
asyncio.run(send_receive(audio_stream))
print("getting llm reponse...")
llm_resp = llm_response(final_query)
print("llm response: ", llm_resp)
generate_speech(llm_resp)
print(llm_resp)
print("Resuming listening for wake word...")
# The listening loop continues, allowing for the process to start over when the wake word is detected again
finally:
if porcupine is not None:
porcupine.delete()
if audio_stream is not None:
audio_stream.close()
p.terminate()
if __name__ == "__main__":
start_listening()