Repository navigation
Expand file tree
/
Copy pathlistener.py
More file actions
437 lines (357 loc) · 17.1 KB
/
Copy pathlistener.py
File metadata and controls
437 lines (357 loc) · 17.1 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
"""
Listener module for Stonic voice assistant
Handles sound detection and speech recognition
"""
import os
import pyaudio
import wave
import time
import math
import speech_recognition as sr
import logging
import threading
import numpy as np
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
from config import SPEECH_SETTINGS, USER_NAME
from utils import log_command
logger = logging.getLogger("Stonic.Listener")
class SoundDetector:
"""Class to detect sound (clap/loud noise) to activate the assistant"""
def __init__(self, threshold=0.15, silence_duration=1.0, format=pyaudio.paInt16, channels=1, rate=44100, chunk=1024):
"""
Initialize the sound detector
Args:
threshold (float): Volume threshold for sound detection (0.0 to 1.0)
silence_duration (float): Duration of silence before considering it a new sound (seconds)
format: PyAudio format
channels (int): Number of audio channels
rate (int): Audio sample rate
chunk (int): Audio chunk size
"""
self.threshold = threshold
self.silence_duration = silence_duration
self.format = format
self.channels = channels
self.rate = rate
self.chunk = chunk
self.p = None
self.stream = None
self.is_running = False
self.callback = None
self.last_sound_time = 0
# For clap detection
self.clap_min_amplitude = 0.15 # Minimum amplitude to consider as a clap
self.clap_max_duration = 0.15 # Maximum duration of a clap sound in seconds
self.clap_cooldown = 0.5 # Minimum time between clap detections
self.last_clap_time = 0
self.is_clap_candidate = False
self.clap_start_time = 0
logger.info(f"SoundDetector initialized with threshold {threshold}")
def start(self, callback=None):
"""
Start listening for sounds
Args:
callback (function): Function to call when sound is detected
"""
self.callback = callback
# Start in a separate thread
self.is_running = True
self.listen_thread = threading.Thread(target=self._listen_for_sound)
self.listen_thread.daemon = True
self.listen_thread.start()
logger.info("Sound detection started")
def stop(self):
"""Stop listening for sounds"""
self.is_running = False
if self.stream:
self.stream.stop_stream()
self.stream.close()
if self.p:
self.p.terminate()
logger.info("Sound detection stopped")
def _listen_for_sound(self):
"""Internal method to listen for sounds"""
self.p = pyaudio.PyAudio()
self.stream = self.p.open(
format=self.format,
channels=self.channels,
rate=self.rate,
input=True,
frames_per_buffer=self.chunk
)
logger.info("Listening for sounds...")
while self.is_running:
try:
data = self.stream.read(self.chunk, exception_on_overflow=False)
amplitude = self._get_audio_amplitude(data)
# If the amplitude exceeds the threshold
current_time = time.time()
# Check for clap pattern
if amplitude > self.clap_min_amplitude:
# If we're not already tracking a potential clap
if not self.is_clap_candidate:
self.is_clap_candidate = True
self.clap_start_time = current_time
# If we're already in a clap and it's been too long, reset
elif current_time - self.clap_start_time > self.clap_max_duration:
self.is_clap_candidate = False
# If amplitude drops after a spike (end of clap)
elif self.is_clap_candidate and amplitude < self.clap_min_amplitude:
clap_duration = current_time - self.clap_start_time
# Check if this is a valid clap (short duration)
if clap_duration < self.clap_max_duration and current_time - self.last_clap_time > self.clap_cooldown:
logger.info(f"Clap detected! Amplitude: {amplitude:.4f}, Duration: {clap_duration:.3f}s")
self.last_clap_time = current_time
# Call the callback in a safe way
if self.callback:
try:
# Use a separate thread for the callback to avoid blocking
callback_thread = threading.Thread(target=self.callback)
callback_thread.daemon = True
callback_thread.start()
except Exception as e:
logger.error(f"Error in clap callback: {e}")
# Reset clap tracking
self.is_clap_candidate = False
# Small sleep to reduce CPU usage
time.sleep(0.01)
except Exception as e:
logger.error(f"Error in sound detection: {e}")
time.sleep(0.1)
def _get_audio_amplitude(self, data):
"""
Calculate the amplitude (volume) of audio data
Args:
data (bytes): Audio data
Returns:
float: Amplitude (0.0 to 1.0)
"""
# Convert bytes to integers
count = len(data) // 2
format = f"{count}h"
shorts = np.frombuffer(data, dtype=np.int16)
# Get the RMS (root mean square) amplitude
sum_squares = 0
for sample in shorts:
n = sample * (1.0 / 32768.0) # Normalize to -1.0 to 1.0
sum_squares += n * n
rms = math.sqrt(sum_squares / count)
# Also check for peak amplitude which is better for clap detection
peak = np.max(np.abs(shorts)) / 32768.0
# Use a combination of RMS and peak for better clap detection
# Claps have high peak-to-RMS ratio
combined_amplitude = (peak * 0.7) + (rms * 0.3)
return combined_amplitude
class VoiceRecognizer:
"""Class for enhanced speech recognition with error handling and optimizations"""
def __init__(self):
"""Initialize the voice recognizer with optimized settings"""
self.recognizer = sr.Recognizer()
# Load settings from config
self.timeout = SPEECH_SETTINGS.get("timeout", 5)
self.phrase_time_limit = SPEECH_SETTINGS.get("phrase_time_limit", 5)
self.energy_threshold = SPEECH_SETTINGS.get("energy_threshold", 1500)
self.dynamic_energy_threshold = SPEECH_SETTINGS.get("dynamic_energy_threshold", True)
self.dynamic_energy_adjustment_damping = SPEECH_SETTINGS.get("dynamic_energy_adjustment_damping", 0.15)
self.dynamic_energy_adjustment_ratio = SPEECH_SETTINGS.get("dynamic_energy_adjustment_ratio", 1.5)
self.pause_threshold = SPEECH_SETTINGS.get("pause_threshold", 0.5)
self.ambient_noise_adjustment_duration = SPEECH_SETTINGS.get("ambient_noise_adjustment_duration", 1.0)
self.primary_language = SPEECH_SETTINGS.get("primary_language", "en-IN")
self.secondary_language = SPEECH_SETTINGS.get("secondary_language", "en-US")
self.use_fallback_language = SPEECH_SETTINGS.get("use_fallback_language", True)
self.default_microphone_index = SPEECH_SETTINGS.get("default_microphone_index", None)
self.use_whisper = SPEECH_SETTINGS.get("use_whisper", False)
self.whisper_model = SPEECH_SETTINGS.get("whisper_model", "base")
# Configure recognizer with settings
self.recognizer.energy_threshold = self.energy_threshold
self.recognizer.dynamic_energy_threshold = self.dynamic_energy_threshold
self.recognizer.dynamic_energy_adjustment_damping = self.dynamic_energy_adjustment_damping
self.recognizer.dynamic_energy_adjustment_ratio = self.dynamic_energy_adjustment_ratio
self.recognizer.pause_threshold = self.pause_threshold
# Microphone selection
self.available_mics = None
self.microphone = None
self.setup_microphone()
logger.info(f"VoiceRecognizer initialized with energy_threshold={self.energy_threshold}, "
f"pause_threshold={self.pause_threshold}")
def setup_microphone(self, device_index=None):
"""
Set up the microphone with specified device
Args:
device_index: Optional specific microphone index to use
"""
try:
# Use config default if not specified
if device_index is None:
device_index = self.default_microphone_index
# Get available microphones
self.available_mics = sr.Microphone.list_microphone_names()
logger.info(f"Available microphones: {self.available_mics}")
# Create microphone instance
if device_index is not None:
self.microphone = sr.Microphone(device_index=device_index)
logger.info(f"Using microphone device at index {device_index}")
else:
self.microphone = sr.Microphone()
logger.info("Using default microphone")
# Adjust for ambient noise once during setup
with self.microphone as source:
logger.info(f"Adjusting for ambient noise (duration: {self.ambient_noise_adjustment_duration}s)...")
self.recognizer.adjust_for_ambient_noise(source, duration=self.ambient_noise_adjustment_duration)
logger.info(f"Ambient noise adjustment complete. Energy threshold: {self.recognizer.energy_threshold}")
except Exception as e:
logger.error(f"Error setting up microphone: {e}")
# Fallback to default microphone
try:
self.microphone = sr.Microphone()
logger.info("Falling back to default microphone")
except Exception as e2:
logger.error(f"Failed to initialize microphone: {e2}")
self.microphone = None
def get_available_microphones(self):
"""Get list of available microphones"""
if self.available_mics is None:
self.available_mics = sr.Microphone.list_microphone_names()
return self.available_mics
def listen(self, timeout=None, phrase_time_limit=None):
"""
Listen for a voice command
Args:
timeout: Override default timeout
phrase_time_limit: Override default phrase time limit
Returns:
str: Recognized text, or None if recognition failed
"""
if self.microphone is None:
logger.error("No microphone available")
return None
# Use provided values or defaults
timeout = timeout or self.timeout
phrase_time_limit = phrase_time_limit or self.phrase_time_limit
try:
with self.microphone as source:
logger.info(f"Listening (timeout={timeout}s, phrase_limit={phrase_time_limit}s)...")
# Periodically readjust for ambient noise to handle changing environments
if random.random() < 0.2: # 20% chance to readjust
self.recognizer.adjust_for_ambient_noise(source, duration=0.5)
logger.debug(f"Readjusted for ambient noise. Energy threshold: {self.recognizer.energy_threshold}")
# Listen for audio input
try:
audio = self.recognizer.listen(
source,
timeout=timeout,
phrase_time_limit=phrase_time_limit
)
logger.info("Audio captured, recognizing...")
return self._recognize_audio(audio)
except sr.WaitTimeoutError:
logger.info("Listening timed out")
return None
except Exception as e:
logger.error(f"Error during audio capture: {e}")
return None
def _recognize_audio(self, audio):
"""
Recognize speech from audio data
Args:
audio: Audio data from recognizer.listen
Returns:
str: Recognized text or None
"""
# Try using Whisper if enabled (offline)
if self.use_whisper:
try:
import whisper
model = whisper.load_model(self.whisper_model)
# Save audio to temporary file for Whisper
temp_file = "temp_audio.wav"
with open(temp_file, "wb") as f:
f.write(audio.get_wav_data())
# Perform recognition with Whisper
result = model.transcribe(temp_file)
# Clean up temp file
try:
os.remove(temp_file)
except:
pass
if result["text"]:
recognized_text = result["text"].strip()
logger.info(f"Whisper recognized: '{recognized_text}'")
return recognized_text
else:
logger.info("Whisper couldn't recognize speech")
except Exception as e:
logger.error(f"Error using Whisper: {e}")
# Fall back to Google recognition
# Try Google Web Speech API with primary language
try:
recognized_text = self.recognizer.recognize_google(
audio, language=self.primary_language
)
logger.info(f"Google recognized ({self.primary_language}): '{recognized_text}'")
return recognized_text
except sr.UnknownValueError:
logger.info(f"Google couldn't recognize speech in {self.primary_language}")
except sr.RequestError as e:
logger.error(f"Google speech service error: {e}")
return None
# Try fallback language if enabled
if self.use_fallback_language:
try:
recognized_text = self.recognizer.recognize_google(
audio, language=self.secondary_language
)
logger.info(f"Google recognized fallback ({self.secondary_language}): '{recognized_text}'")
return recognized_text
except sr.UnknownValueError:
logger.info(f"Google couldn't recognize speech in {self.secondary_language}")
except sr.RequestError as e:
logger.error(f"Google speech service error: {e}")
return None
def listen_continuously(self, callback, stop_event=None):
"""
Listen continuously for commands in a background thread
Args:
callback: Function to call with recognized text
stop_event: Threading event to signal stopping
"""
if stop_event is None:
stop_event = threading.Event()
def listen_thread():
logger.info("Starting continuous listening...")
while not stop_event.is_set():
try:
result = self.listen()
if result:
callback(result)
except Exception as e:
logger.error(f"Error in continuous listening: {e}")
time.sleep(0.5) # Prevent CPU spikes on repeated errors
# Small delay between recognition attempts
time.sleep(0.1)
logger.info("Stopped continuous listening")
thread = threading.Thread(target=listen_thread)
thread.daemon = True
thread.start()
return stop_event # Return the event so caller can stop listening
# Helper function to initialize and use the voice recognizer
def initialize_voice_recognition():
"""Initialize and return the voice recognizer"""
return VoiceRecognizer()
# For testing this module independently
if __name__ == "__main__":
import random
logging.basicConfig(level=logging.INFO)
recognizer = VoiceRecognizer()
def handle_speech(text):
print(f"Recognized: {text}")
stop_event = recognizer.listen_continuously(handle_speech)
try:
print("Listening continuously. Press Ctrl+C to stop.")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Stopping...")
stop_event.set()
time.sleep(1) # Give time for thread to exit