-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeech_handler.py
More file actions
68 lines (58 loc) · 2.24 KB
/
speech_handler.py
File metadata and controls
68 lines (58 loc) · 2.24 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
# V1
'''import speech_recognition as sr
recognizer = sr.Recognizer()
def listen() -> None:
with sr.Microphone() as source:
print("\n🎙️ Say something...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
return recognizer.recognize_google(audio)'''
# V2
import time
import speech_recognition as sr
recognizer = sr.Recognizer()
def listen(**kwargs) -> str:
with sr.Microphone() as source:
print("\n🎙️ Say something...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# Save the audio to a WAV file for debugging
with open("debug_audio.wav", "wb") as f:
f.write(audio.get_wav_data())
return recognizer.recognize_google(audio_data=audio, **kwargs)
def listen_bylingual(**kwargs) -> str:
with sr.Microphone() as source:
print("\n🎙️ Say something...")
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
# Save the audio to a WAV file for debugging
with open("debug_audio.wav", "wb") as f:
f.write(audio.get_wav_data())
try:
text = recognizer.recognize_google(audio_data=audio, language="en-US",**kwargs)
finally:
for wakeup_call in ["hey", "hello"]:
if wakeup_call in text.lower():
return text
try:
text = recognizer.recognize_google(audio_data=audio, language="ml-IN",**kwargs)
finally:
for wakeup_call in ["എന്നോട് പറയ"]:
if wakeup_call in text:
return text
raise sr.UnknownValueError()
# Test
if __name__ == "__main__":
while True:
try:
text = listen_bylingual()
print("📝 You said:", text)
'''for wakeup_call in ["hey", "hello"]:
if wakeup_call in text.lower():
time.sleep(5)'''
except sr.UnknownValueError or Exception("cannot access local variable 'text' where it is not associated with a value"):
print("❌ Sorry, I couldn't understand that.")
except sr.RequestError as e:
print(f"🔌 Request error: {e}")
except Exception as e:
print(f"⚠️ Error: {e}")