My script just stop and get stuck after engine.runandWait()... If someone has any idea of how to make it continue I would appreciate !
It seems that the answer isn't in the script itself because I tried scripts that are super simple... I also tried to uninstall and reinstall portaudio, pyaudio and pyttsx3
Here is my script :
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import time
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.setProperty('voices', "french")
def talk(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
def take_command():
command = ''
try:
with sr.Microphone() as source:
print("...")
voice = listener.listen(source)
command = listener.recognize_google(voice,language = 'fr-FR')
command = command.lower()
except:
talk("Je me mets en veille")
pass
return command
def run_jeff(run):
command = take_command()
if 'youtube' in command:
command = command.replace('youtube','')
command = command.replace('ouvre','')
pywhatkit.playonyt(command)
elif "stop" in command:
talk("Je vais dodo")
run = False
elif 'bonjour' in command or 'salut' in command :
talk('Bonjour, comment allez-vous ?')
talk(info)
elif 'blague' in command :
talk(pyjokes.get_joke())
else :
talk("Pouvez-vous répétez je n'ai pas compris ?")
print(command)
run = True
while True:
run_jeff(run)
if run == False:
exit()
In the def talk section, you can remove the first line and in the while True statement, delete if run == False, and add a elif statement to the take command sections saying elif 'thank you' in command: exit(the name of your assistant). Try it
Here is a short pyttsx testing program.
Save it as 'pyttsx_test.py' then run it.
If your version is working correctly it will speak the code and print it to shell.
"""pyttsx_test.py
I am a text to speech test
"""
import pyttsx3
engine = pyttsx3.Engine()
engine.setProperty( "rate", 200 )
engine.setProperty( "volume", 1.0 )
engine.say( 'say something' )
engine.runAndWait()
with open( 'pyttsx_test.py', mode='rt') as files:
lines = files.readlines()
lines = [ x.strip(' ') for x in lines ] # remove un-necessary spaces
lines = [ x for x in lines if x!='\n'] # remove empty lines
for a in lines:
print( a, end ='' )
engine.say( a )
engine.runAndWait()
You should change your input device using device_index. (default=0)
with sr.Microphone(device_index=0) as source:
You can see all your devices using:
for index, name in enumerate(sr.Microphone.list_microphone_names()):
print(f'{index}, {name}')
Every time you initiate the engine or "init()" you have to set property again. You duplicated your lines and used it wrong.
if you wish it to work delete thoes lines -
engine = pyttsx3.init()
voices = engine.setProperty('voices', "french")
def talk(text):
engine = pyttsx3.init()
engine.say(text)
engine.runAndWait()
and replace them with this -
def talk(text):
engine = pyttsx3.init()
voices = engine.setProperty('voices', "french")
engine.say(text)
engine.runAndWait()
Related
I have the following piece of code:
import openai
import pyttsx3
import speech_recognition as sr
from api_key import API_KEY
openai.api_key = API_KEY
engine = pyttsx3.init()
r = sr.Recognizer()
mic = sr.Microphone(device_index=1)
print(sr.Microphone.list_microphone_names())
conversation = ""
user_name = "Josode"
while True:
with mic as source:
print("\nlistening... speak clearly into mic.")
r.adjust_for_ambient_noise(source, duration=0.2)
audio = r.listen(source)
print("no longer listening.\n")
try:
user_input = r.recognize_google(audio)
except:
continue
prompt = user_name + ": " + user_input + "\n Ava:"
conversation += prompt
response = openai.Completion.create(engine="text-davinci-002", prompt=conversation, max_tokens=100)
response_str = response["choices"][0]["text"].replace("\n", "")
response_str = response_str.split(user_name + ": ", 1)[0].split("Ava: ", 1)[0]
conversation += response_str + "\n"
print(response_str)
engine.say(response_str)
engine.runAndWait()
When I run the file, I get just listening... speak clearly into mic.
no longer listening. with no output from davinci.
Also, the mic print is ['LG FULL HD', 'Ari Chan’s AirPods', 'Ari Chan’s AirPods', 'MacBook Pro Microphone', 'MacBook Pro Speakers']. I am using index 1
API key is correct and imported. I have an account at Open AI and can use playground without a problem.
Do you see something that I don't see? It should work
Most probably you are getting an exception in r.recognize_google(audio) so it forces continue again and again without any output, try to add something like this to debug it:
import traceback
...
try:
user_input = r.recognize_google(audio)
except:
print(traceback.format_exc())
continue
I created a voice assistant using python neuralintents module. but it didn't give a way to use responses in intents.json to give a feedback for user. Instead it is mapping response to a function.
Is there any way to use responses in intents.json.
I got this by watching this tutorial :
https://youtu.be/SXsyLdKkKX0
Github repo :
https://github.com/NeuralNine/neuralintents
Source code from video
from email.mime import audio
from fileinput import filename
from neuralintents import GenericAssistant
import speech_recognition
import pyttsx3 as tts
import sys
import webbrowser
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
speaker.setProperty('rate', 150)
todo_list = ['Go shopping', 'Clean Room', 'Recpard Videos']
def create_note():
global recognizer
speaker.say("What do you want to write into your note")
speaker.runAndWait()
done = False
while not done:
try:
with speech_recognition.Microphone as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
note = recognizer.recognize_google(audio)
note = note.lower()
speaker.say("Choose a filename!")
speaker.runAndWait()
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
filename = recognizer.recognize_google(audio)
filename = filename.lower()
with open(filename, 'w') as f:
f.write(note)
done = True
speaker.say(f"I sucessfully created the note {filename}")
speaker.runAndWait
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
speaker.say("I did not understand you! Please try again!")
speaker.runAndWait()
def add_todo():
global recognizer
speaker.say("What doto do you want to add?")
speaker.runAndWait()
done = False
while not done:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
item = recognizer.recognize_google(audio)
item = item.lower()
todo_list.append(item)
done = True
speaker.say(f"I added {item} to the to do list!")
speaker.runAndWait()
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
speaker.say("I did not understand. Please try again!")
speaker.runAndWait()
def show_todos():
speaker.say("The items in your to do list are following")
for item in todo_list:
speaker.say(item)
speaker.runAndWait()
def hello():
speaker.say("Hello. What can I do for you?")
speaker.runAndWait()
def exitt():
speaker.say("Bye")
speaker.runAndWait()
sys.exit(0)
mapppings = {
"greeting": hello,
"create_note": create_note,
"add_todos": add_todo,
"show_todos": show_todos,
"goodbye": exitt,
}
assistant = GenericAssistant('intents.json', intent_methods=mapppings)
assistant.train_model()
assistant.save_model()
def talk(text):
engine = tts.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine. setProperty("rate", 150)
engine.say(text)
engine.runAndWait()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
command = recognizer.recognize_google(audio)
command = command.lower()
assistant.request(command)
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
if you want the assistant to speak the response you call the function talk and pass assistant.request(command) as parameter, but if you have bindings for adding todo ect. u first call the assistant.request(command) alone and after that you chec if the request has any response and if it does you pass the response to the talk function
def talk(text):
engine = tts.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine. setProperty("rate", 150)
engine.say(text)
engine.runAndWait()
while True:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
command = recognizer.recognize_google(audio)
command = command.lower()
assistant.request(command)
if(assistant.request(command))
talk(assistant.request(command))
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
I am working on a project to create a voice assistant using Python 3.10 in pycharm. When the program starts, an error appears:
Traceback (most recent call last):
File "D:\alexa.py", line 56, in <module>
query = takecommand().lower()
File "D:\alexa.py", line 37, in takecommand
with sr.Microphone() as source:
File "C:\Users\(redacted)\PycharmProjects\pythonProject8\venv\lib\site-
packages\speech_recognition\__init__.py", line 86, in __init__
device_info = audio.get_device_info_by_index(device_index) if device_index is not None else
audio.get_default_input_device_info()
File "C:\Users\(redacted)\PycharmProjects\pythonProject8\venv\lib\site-packages\pyaudio.py",
line 949, in get_default_input_device_info
device_index = pa.get_default_input_device()
OSError: No Default Input Device Available
Process finished with exit code 1
Code:
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os.path
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)
def speak(audio):
engine.say(audio)
def wishme():
hour = int(datetime.datetime.now().hour)
if hour>=0 and hour<12:
speak('Доброе утро')
elif hour>12 and hour<18:
speak('Добрый день')
else:
speak('Добрый вечер')
speak(' Я Алекса, ваш голосовой помощник. Теперь многие вещи проще делать говоря со мной ')
def takecommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print('Слушаю...')
r.pause_threshold = 2
audio = r.listen(source)
try:
print('Распознование...')
query = r.recognize_google(audio,language = 'en-in')
print(f'User said: {query}\n')
except Exception as e :
print('Повторите это снова пожалуйста...')
return 'Ничего'
return query
if __name__ == '__main__' :
wishme()
while True:
query = takecommand().lower()
if 'википедия' in query :
speak('Поиск в Википедии....')
query = query.replace('википедия','')
results = wikipedia.summary(query, sentences = 5)
print(results)
speak(results)
elif 'открой ютуб' in query :
webbrowser.open('youtube.com')
elif 'открой гугл' in query :
webbrowser.open('google.com')
elif 'открой вконтакте' in query:
webbrowser.open('vk.com')
elif 'открой почту' in query:
webbrowser.open('mail.ru')
elif 'время' in query :
strtime = datetime.datetime.now().strftime('%H:%M:%S')
speak(f'сейчас {strtime}')
elif 'пайчарм' in query :
codepath = 'C:\Program Files\JetBrains\PyCharm Community
Edition2021.3.2\bin\pycharm64'
os.startfile(codepath)
elif 'выход' in query:
speak('хорошо, пожалуйста позовите меня если вам понадобиться моя помощь')
quit()
I tried to fix the mistake, but nothing comes out. It's only clear to me that there is no default device available, but I still don't understand how to fix it, given that there is not only this error. What can I try next?
First take a look at this solution. And also (not sure about this) check if you have an audio device (like a microphone) installed and then check that device's driver is installed correctly.
I created a Voice Assistant using speech recognition and GTTS modules in Python. The code works perfectly fine when run from script. But when I converted it using pyinstaller --onefile Speak.py(The name of the file) it stopped working. It is using my microphone but its not responding to anything. Suppose if I say hey google which is the wake up keyword it simply doesnt respond. I tried after a while but of no use. Can anyone please help me???
Code:
"from gtts import gTTS
import speech_recognition as sr
import os
import playsound
from datetime import datetime
import webbrowser
keeprunning = True
WAKING = "HEY GOOGLE"
def chec(cond, tex):
if cond in tex:
return True
else:
return False
def speak(text):
speaker = gTTS(text = text, lang = "en")
speaker.save("Voice.mp3")
playsound.playsound("voice.mp3")
os.remove("Voice.mp3")
def cleanify(text, wtremove, wtremove2=""):
try:
text = text.replace(wtremove)
except:
if not wtremove2 == "":
text = text.replace(wtremove2, "")
return text
#Main controlling part here(Oof!)
def Control(comnd):
if chec("SEARCH", comnd) or chec("GOOGLE", comnd):
comnd = cleanify(comnd, "SEARCH", "GOOGLE")
webbrowser.open(f"https://google.com/search?q={comnd.lower()}")
elif chec("WHO ARE YOU", comnd):
speak("I am your virtual assistant, google")
keepcontrol()
elif chec("TIME", comnd):
t = datetime.now()
t = time.strptime(t.strftime("%H:%S"), "%H:%M")
tt = time.strftime( "%I:%M %p", t )
speak(f"The current time is {tt}")
elif chec("NOTE", comnd) or chec("REMEMBER", comnd) or chec("JOT", comnd):
try:
text = comnd.replace("NOTE")
except:
try:
text = text.replace("REMEMBER")
except:
text = text.replace("JOT")
try:
with open("This_File_Name_Is_Very_Big_Because_I_dont_Want_to_overwrite_anyother_files_so_forgive_me_plz.txt", "rt") as file:
previous = file.read()
except:
with open("This_File_Name_Is_Very_Big_Because_I_dont_want_to_overwrite_any_other_files_so_forgive_me_plz.txt", "wt") as file:
ttw = f"""
•{text.lower()}
"""
file.write(previous + ttw)
previous = ""
with open("Notes.txt", "wt") as file:
ttw = previous + " •" + text
file.write(ttw)
speak("Got it! I noted it down")
elif chec("OPEN", comnd):
web = cleanify(comnd, "OPEN")
bruh = cleanify(web, ".com")
speak(f"Opening {bruh}")
print(comnd)
web = cleanify(comnd, "OPEN")
if web == "":
web = listen()
else:
if "https://" in web:
webbrowser.open(web.lower())
else:
web = "https://" + web
webbrowser.open(web.lower())
keepcontrol()
#Main controlling part ends
def listen():
r = sr.Recognizer()
with sr.Microphone() as source:
listen = r.listen(source)
try:
text = r.recognize_google(listen)
return text.upper()
except Exception as e:
if not e == "":
return ""
keepcontrol()
else:
speak("Sorry we couldnt catch that, please try again")
keepcontrol()
def keepcontrol():
while keeprunning:
text = listen()
if not text == None:
if text.count(WAKING) == 1:
speak("I am listening..")
text = listen()
if not text == None and not text == "":
Control(text)
else:
speak("Sorry i did not get that. Try again in a few seconds")
keepcontrol()
elif chec("QUIT", text):
exit()
elif chec("", text):
keepcontrol()
else:
speak("Sorry we didnt get that right. Please try again.")
speak("I am booting up...")
keepcontrol()
"
When you have converted it into exe,I think you have forgot to put files that you have used to build the assistant in the folder.
When your exe get converted, just simply copy those files(the files you have used) in the same folder in which you have kept your exe.
Hope it will work.
import speech_recognition as sr
import pyttsx3
import string
import random
#Text To Speech
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
#print(voices)
engine.setProperty('voice',voices[0].id)
engine.setProperty('rate', 145) #you can replace it to incease or decrease dound speed default(200)
def speak(audio): #here audio is var which contain text
engine.say(audio)
engine.runAndWait()
#now convert audio to text
def takecom():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listning....")
audio = r.listen(source)
try:
print("Recognising....")
text = r.recognize_google(audio,language='en-in')
print(text)
except Exception:
speak("error...")
print("Network connection error")
return "none"
return text
#for main function
if __name__ == "__main__":
while True:
query = takecom().lower()
if 'create password' in query or 'c' in query :
if __name__ == "__main__":
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
speak('what do you want to keep the length of the password type here')
plen =int(input('what is the length of the password')) #p
s=[]
s.extend(list(s1))
s.extend(list(s2))
s.extend(list(s3))
s.extend(list(s4))
print("Your password is:")
print("".join(random.sample(s,plen)))
speak("".join(random.sample(s,plen)))
elif query == 'none':
continue
elif 'exit' in query or 'abort' in query or 'stop' in query or 'bye' in query or 'quit' in query:
ex_exit = 'ok byy'
speak(ex_exit)
exit()
When i run this code every thing work fine but it ask to write the length of the password and when i write to length in it then the code proceed but i don't want to write anything in it is there any way so that i can give a voice input in the function plen (#p) to do the program work with the help of voice command.
I am using python 3.8
Oh god finally i got answer of my question by my own.
let's see the answer
In the line plen =int(input('what is the length of the password')) #p
we need to change this code to plen =int(takecom()) show that the word which we will speak will get directly converted into input in it and the code will work properly with voice command.
Here is the final code
import speech_recognition as sr
import pyttsx3
import string
import random
#Text To Speech
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
#print(voices)
engine.setProperty('voice',voices[0].id)
engine.setProperty('rate', 145) #you can replace it to incease or decrease dound speed default(200)
def speak(audio): #here audio is var which contain text
engine.say(audio)
engine.runAndWait()
#now convert audio to text
def takecom():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listning....")
audio = r.listen(source)
try:
print("Recognising....")
text = r.recognize_google(audio,language='en-in')
print(text)
except Exception:
speak("error...")
print("Network connection error")
return "none"
return text
#for main function
if __name__ == "__main__":
while True:
query = takecom().lower()
if 'create password' in query or 'c' in query :
if __name__ == "__main__":
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
speak('what do you want to keep the length of the password type here')
plen =int(takecom()) #p
s=[]
s.extend(list(s1))
s.extend(list(s2))
s.extend(list(s3))
s.extend(list(s4))
print("Your password is:")
print("".join(random.sample(s,plen)))
speak("".join(random.sample(s,plen)))
elif query == 'none':
continue
elif 'exit' in query or 'abort' in query or 'stop' in query or 'bye' in query or 'quit' in query:
ex_exit = 'ok byy'
speak(ex_exit)
exit()
just change ↓
plen =int(input('what is the length of the password')) #p
to ↓
plen =int(takecom()) #p