-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.py
More file actions
206 lines (156 loc) · 5.29 KB
/
app.py
File metadata and controls
206 lines (156 loc) · 5.29 KB
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
import requests
import json
import numpy as np
import pyaudio
import os
from dotenv import load_dotenv
import pvporcupine
from lights import Lights
import time
import audioop
import wave
from websocket import create_connection
import traceback
import subprocess
load_dotenv()
OLLAMA_URL = 'http://10.0.0.10:11434/api/generate'
OLLAMA_MODEL = "llama3:latest"
OLLAMA_SYSTEM = "Limit your responses to three sentences. You are a voice assistant. Please refrain from providing unnecessary information."
VOSK_URL = "ws://10.0.0.10:2700"
PIPER_URL = "http://10.0.0.10:5000"
porcupine = pvporcupine.create(
access_key=os.environ.get("PICOVOICE_KEY"),
keyword_paths=[os.environ.get("PICOVOICE_MODEL_PATH")]
)
RESPEAKER_INDEX = 1
lights = Lights()
def listen_for_wake_word():
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=16000,
input=True,
input_device_index = RESPEAKER_INDEX,
frames_per_buffer=512)
print("Listening for wake word...")
try:
while True:
pcm = np.frombuffer(stream.read(512), dtype=np.int16)
keyword_index = porcupine.process(pcm)
if keyword_index >= 0:
print("Wake word detected!")
return True
finally:
stream.stop_stream()
stream.close()
p.terminate()
def record_prompt():
THRESHOLD = 25000
SILENCE_DURATION = 3
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
input=True,
input_device_index=1,
frames_per_buffer=1024)
print("Recording...")
silence_start_time = None
silence_counter = 0
frames = []
while True:
data = stream.read(1024)
frames.append(data)
rms = audioop.rms(data, 2)
if rms < THRESHOLD:
if silence_start_time is None:
silence_start_time = time.time()
else:
silence_counter = time.time() - silence_start_time
else:
silence_start_time = None
silence_counter = 0
if silence_counter >= SILENCE_DURATION:
print("Silence detected, stopping recording.")
break
stream.stop_stream()
stream.close()
p.terminate()
output_filename = "output.wav"
with wave.open(output_filename, 'wb') as wf:
wf.setnchannels(1)
wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
wf.setframerate(44100)
wf.writeframes(b''.join(frames))
print(f"Recording saved to {output_filename}")
def perform_stt():
ws = create_connection(VOSK_URL)
wf = wave.open("output.wav", "rb")
ws.send('{ "config" : { "sample_rate" : %d } }' % (wf.getframerate()))
buffer_size = int(wf.getframerate() * 0.2)
try:
while True:
data = wf.readframes(buffer_size)
if len(data) == 0:
break
ws.send_binary(data)
response = ws.recv()
response_json = json.loads(response)
if "text" in response_json and response_json["text"]:
return response_json["text"]
ws.send('{"eof" : 1}')
except Exception as err:
print(''.join(traceback.format_exception(type(err), err, err.__traceback__)))
def generate_response(prompt):
payload = {
"model": OLLAMA_MODEL,
"prompt": prompt,
"system": OLLAMA_SYSTEM,
"stream": False
}
with requests.post(OLLAMA_URL, json=payload) as response:
if response.status_code == 200:
return response.json().get("response", "No response received.")
else:
return f"Error: {response.status_code} - {response.text}"
def stream_tts(text):
params = {"text": text}
with requests.get(PIPER_URL, params=params, stream=True) as response:
if response.status_code != 200:
print(f"Error: {response.status_code} - {response.text}")
return
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=22050,
output=True,
output_device_index = RESPEAKER_INDEX,
frames_per_buffer=1024)
for chunk in response.iter_content(chunk_size=1024):
if chunk:
int_data = np.frombuffer(chunk, dtype=np.int16)
stream.write(int_data.tobytes())
stream.stop_stream()
stream.close()
p.terminate()
if __name__ == "__main__":
subprocess.run(["amixer", "-c", "1", "sset", "Speaker", "100%"])
while True:
try:
if listen_for_wake_word():
lights.fade_in()
record_prompt()
#user_input = input(">> ")
#if user_input.lower() == "exit":
# break
user_input = perform_stt()
print(user_input)
response = generate_response(user_input)
print(response)
stream_tts(response)
lights.fade_out()
time.sleep(1)
except KeyboardInterrupt:
break
lights.off()
time.sleep(1)