Speech Recognition Request Failed: Service Unavailable - python-3.x

I'm creating a simple virtual assistant but I keep getting an error saying recognition request failed service unavailable.
Might the problem be that I cannot be able to access the google speech api?
I'm not sure.
Here is my code
import pyttsx3
import os
from time import sleep
import playsound
import speech_recognition as sr
voiceEngine = pyttsx3.init()
# rate
voiceEngine.setProperty('rate', 150)
# voice
voices = voiceEngine.getProperty('voices')
voiceEngine.setProperty('voice', voices[1].id)
def speak(text):
voiceEngine.say(text)
voiceEngine.runAndWait()
def takeCommand():
print('\nListening...')
recog = sr.Recognizer()
with sr.Microphone() as source:
print("Listening to the user")
recog.pause_threshold = 1
userInput = recog.listen(source)
try:
print("Recognizing the command")
command = recog.recognize_google(userInput, language ='en-in')
print(f"Command is: {command}\n")
except Exception as e:
print(e)
print("Unable to Recognize the voice.")
return "None"
return command
def wish():
print("Wishing.")
time = int(datetime.datetime.now().hour)
if time>= 0 and time<12:
speak("Good Morning!")
elif time<18:
speak("Good Afternoon!")
else:
speak("Good Evening!")
speak("I am your Voice Assistant, DIVA")
print("I am your Voice Assistant, DIVA")
os.system('cls')
wish()
while True:
for j in range(5):
speak("What can I do for you")
command = takeCommand().lower()
print(command)
if command:
break
if "DIVA" in command:
wish()
else:
speak("Sorry, I am not able to understand you")
When I run it I get this error
Wishing.
I am your Voice Assistant, DIVA
Listening...
Listening to the user
Recognizing the command
recognition request failed: Service Unavailable
Unable to Recognize the voice.
Any help will be highly appreciated. Thanks.

Related

i am trying to make a voice assistant to control my room and the response times are very slow

I got a basic code on the internet and edited it to fit my requirements, on the hardware side I used Arduino uno, relays, and esp8266 esp01 wifi module, and controlled it using blynk and ifttt
the problem is that the assistant is very slow, I first thought that maybe google text to speech is the problem so I tried the pyttsx3 module to do that offline but that didn't help.
so I thought maybe the if statements are a problem so I made each one of them into a function and tried multi-threading but that didn't help either...
so I thought that it has to listen and process all I speak .. so I added a trigger word so only after the trigger word is used it starts to listen for commands,
sometimes it will work properly at first then get slower
I don't know what else to do
here is the code I am using:
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import requests
import time
import smtplib
from goto import goto, label
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishMe():
speak("Hello sir ,Assistant booting up")
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 0.5
audio = r.listen(source)
print("saving")
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"User said: {query}\n")
except Exception as e:
print(e)
print("Say that again please...")
return
return query
i=0
j=0
if __name__ == "__main__":
wishMe()
while True:
print("iteration jarvis",i)
i=i+1
r = sr.Recognizer()
with sr.Microphone() as source:
print("waiting...")
r.pause_threshold = 0.5
audio = r.listen(source)
try:
query = r.recognize_google(audio, language='en-in')
print(f"User said: {query}\n")
if 'Jarvis' in query:
query=takeCommand().lower()
except Exception as e:
print(e)
print("jaris not called")
continue
print("iteration command",j)
j=j+1
if 'how are you' in query:
speak("good")
elif 'open google' in query:
webbrowser.open("google.com")
speak("There you go!")
elif 'lights on' in query:
requests.post("https://maker.ifttt.com/trigger/light_on/with/key/d*************")
speak("ok sure")
elif 'lights off' in query:
requests.post("https://maker.ifttt.com/trigger/lights_off/with/key/d************")
speak("with pleasure")
elif 'play music' in query:
music_dir = 'D:\\Non Critical\\songs\\Favorite Songs2'
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir, songs[0]))
elif 'stop listening' in query:
speak("going offline")
exit()
You might want to only initialize your recognizer once.
I took the liberty of cleaning up and refactoring the code a little too.
from itertools import count
import pyttsx3
import speech_recognition as sr
import webbrowser
import os
import requests
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[0].id)
recognizer = sr.Recognizer()
recognizer.pause_threshold = 0.5
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takeCommand():
with sr.Microphone() as source:
print("Listening...")
audio = recognizer.listen(source)
print("saving")
print("Recognizing...")
query = recognizer.recognize_google(audio, language="en-in")
print(f"User said: {query}\n")
return query
def process_query(query):
if "how are you" in query:
speak("good")
elif "open google" in query:
webbrowser.open("google.com")
speak("There you go!")
elif "lights on" in query:
requests.post("https://maker.ifttt.com/trigger/light_on/with/key/d*************")
speak("ok sure")
elif "lights off" in query:
requests.post("https://maker.ifttt.com/trigger/lights_off/with/key/d************")
speak("with pleasure")
elif "play music" in query:
music_dir = "D:\\Non Critical\\songs\\Favorite Songs2"
songs = os.listdir(music_dir)
print(songs)
os.startfile(os.path.join(music_dir, songs[0]))
elif "stop listening" in query:
speak("going offline")
exit()
def main():
speak("Hello sir ,Assistant booting up")
for iteration in count(1):
print("iteration jarvis", iteration)
try:
query = takeCommand()
except Exception as e:
print(e)
speak("Recognition error: {}".format(e))
else:
try:
process_query(query)
except Exception as e:
print(e)
speak("Processing error: {}".format(e))
if __name__ == "__main__":
main()

My Pyttsx3 module is not saying anything Text to speech fucntion is not working not getting any audio output

I have intsalled pyttsx3 2.7v and python 3.7v in pycharm
My code : Speak funtion is not returning audio output
import pyttsx3
engine = pyttsx3.init("dummy")
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(text):
print('Rex:' + text)
engine.say(text)
engine.runAndWait()
print("On")
speak("This programe is runniing perfectly")
print("End")
Output
On
Rex:This programe is runniing perfectly
End
Process finished with exit code 0
This is very easy, I have worked with Pyttsx3. Try the below program.
import pyttsx3
engine = pyttsx3.init('sapi5') # <--- sapi 5 is for Windows
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) # <--- voice id can be male(0) or female(1)
def speak(audio):
engine.say(audio)
engine.runAndWait()
There is no need for print statements.

Python3 SPEECH to TEXT

I am a 12 year old kid and am a beginner at programming. It would be great if someone could help be. below I have the code for my speech recognition application, I am on MAC OS CATALINA and the same error keeps on coming up, It prints out "say something", and then once I say something nothing happens and it stays frozen, once I stop the code running I get this error.
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("SAY SOMETHING")
audio = r.listen(source)
print("THANK YOU")
try:
print("TEXT: "+r.recognize_google(audio))
except:
print("SORRY I DONT KNOW WHAT YOU MEAN")
This is the error I get when I stop the code, once it is paused at SAY SOMETHING for a long time.
Traceback (most recent call last):
File "/Users/anishnagariya/PycharmProjects/HelloWorld/Tester.py", line 8, in <module>
print("THANK YOU")
File "/Users/anishnagariya/PycharmProjects/AI/HelloWorld/lib/python3.7/site-packages/speech_recognition/__init__.py", line 620, in listen
buffer = source.stream.read(source.CHUNK)
File "/Users/anishnagariya/PycharmProjects/AI/HelloWorld/lib/python3.7/site-packages/speech_recognition/__init__.py", line 161, in read
return self.pyaudio_stream.read(size, exception_on_overflow=False)
File "/Users/anishnagariya/PycharmProjects/AI/HelloWorld/lib/python3.7/site-packages/pyaudio.py", line 608, in read
return pa.read_stream(self._stream, num_frames, exception_on_overflow)
KeyboardInterrupt
Process finished with exit code 1
I would advise going through the documentation for the speech recognition module you're using:
https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst
Check this part specifically:
https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst#recognizer_instanceenergy_threshold--300---type-float
The energy threshold is described as such:
Represents the energy level threshold for sounds. Values below this threshold are considered silence, and values above this threshold are considered speech. Can be changed.
You can set the threshold like this:
r.energy_threshold = 4000
Or you can do this which will adjust the threshold dynamically based on sound currently from the environment.
r.dynamic_energy_threshold = True
Also ensure your microphone is working properly
Edit:
https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst#recognizer_instancelistensource-audiosource-timeout-unionfloat-none--none-phrase_time_limit-unionfloat-none--none-snowboy_configuration-uniontuplestr-iterablestr-none--none---audiodata
Set a timeout &/or pause duration for the listen call.
import speech_recognition as sr
r = sr.Recognizer()
while True:
with sr.Microphone() as source:
print("SAY SOMETHING")
try:
audio = r.listen(source, timeout=3)
print("THANK YOU")
break
except sr.WaitTimeoutError:
print("timed out")
try:
print("TEXT: "+r.recognize_google(audio))
except:
print("SORRY I DONT KNOW WHAT YOU MEAN")
Depending on your microphone quality you will probably need to set some thresholds:
import speech_recognition as sr
r = sr.Recognizer()
r.energy_threshold = 1000
r.pause_threshold = 0.5
with sr.Microphone() as source:
print("SAY SOMETHING")
audio = r.listen(source)
print("THANK YOU")
try:
print("TEXT: " + r.recognize_google(audio))
except sr.UnknownValueError:
print("SORRY I DONT KNOW WHAT YOU MEAN")
It is also not good practice to have a bare except clause sr.UnknownValueError is the standard error for unknown speech in the speech_recognition library

Why is my code not reaching the While Loop to register my Voice Assistant Wakeword?

I'm creating a Voice Assistant using Python. I'm using pyttsx3 for Text-to-Speech and I have a wakeword set up to activate the Voice Assistant. I'm using the Voice Assistant to do things such as read my calendar and such in a While Loop. But suddenly, the wakeword stops working. What is stopping my code from reaching the While Loop and the rest of the code?
Here is some of the code for my project:
from __future__ import print_function
import subprocess
import pytz
import speech_recognition as sr
import pyttsx3
import time
import os
import datetime
import pickle
import os.path
def speak(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said.lower()
WAKE = "Jarvis"
print("Jarvis is ready")
while True:
print("Jarvis is listening...")
text = get_audio()
if text.count(WAKE) > 0:
speak("Hello Sir, what would you like?")
text = get_audio()
DONE = ["never mind", "goodbye", "I'm done now"]
for phrase in DONE:
if phrase in text:
speak("Alright sir. Goodbye!")
quit()
NOTE_STRS = ["make a note", "write this down", "remember this"]
for phrase in NOTE_STRS:
if phrase in text:
speak("Sure. What would you like me to write down?")
note_text = get_audio()
note(note_text)
speak("Done Sir. I've made a note of that.")
TIME = ["time"]
for phrase in TIME:
if phrase in text:
import datetime
now = datetime.datetime.now()
speak("The current time is %d hours %d minutes" % (now.hour, now.minute))
Please tell me if any code is missing and I can send it to help solve the problem!
HyperionBlaze - What is happening with authenticate_google(). Is there any exception on that call?

python3 error JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock in Ubuntu

Im trying to do speech recognition but every time I run it I get this error.
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for -1, skipping unlock
Here is my code.
from gtts import gTTS
import playsound as ps
import speech_recognition as sr
sr.Microphone.list_microphone_names()
text=('text')
mic = sr.Microphone(device_index=20)
r = sr.Recognizer()
with mic as source:
audio = r.listen(source)
re = r.recognize_google(audio)
def rSpeak():
tts = gTTS(text)
tts.save('hello.mp3')
ps.playsound('hello.mp3', True)
rSpeak()
any help very appreciated
You should try to speak using this:
import pyttsx3
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(audio):
engine.say(audio)
engine.runAndWait()
speak('Hello, Sir.')
And if you want to recognize a voice then go with this:
import speech_recognition as sr
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as mic:
print("Listening...")
r.adjust_for_ambient_noise(mic)
audio = r.listen(mic)
try:
print("Recognizing...")
query = r.recognize_google(audio, language='en-in')
print(f"User said: {query}\n")
except Exception:
print("Say that again please...")
return "None"
return query
query = takeCommand().lower() #lower() is used to keep all your queries in lowercase.
And then you can match your query variable to match with the command you want to follow.

Resources