How to give input using speech recognition in a element in python - python

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

Related

How i can fix my functions automatic repetition

So i have a voice assistant project i use speech recognition and pytsx3, the problem is the functions repetition, so this is my code
main.py:
import possibilities as ps
clear = lambda: os.system('cls')
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[3].id)
engine.setProperty("rate", 160)
def speak(audio):
engine.say(audio)
engine.runAndWait()
while True:
rec = sr.Recognizer()
with sr.Microphone() as mic:
print("Manini listen...")
audio = rec.listen(mic)
try:
text = rec.recognize_google(audio, language='en')
query = text.lower()
except Exception as e:
print("Manini Listen...")
if 'wikipedia' in query:
ps.wikipediaSer(query)
elif "say" in query:
ps.sayrep(query)
elif 'open youtube' in query:
ps.openyoutube()
possibilties.py:
def wikipediaSer(query):
speak('Searching Wikipedia...')
query = query.replace("wikipedia", "")
results = wikipedia.summary(query, sentences = 2)
speak("According to Wikipedia")
print(results)
speak(results)
def sayrep(query):
say_text = query.replace("say", "")
speak(say_text)
def openyoutube():
speak("Here you go to Youtube\n")
webbrowser.open("youtube.com")
so when I execute the project and say a command Wikipedia par example, Wikipedia code repet 5 times. how I can fix this repetition please.

Open AI davinci does not produce any output (text or audio)

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 tried to make a virtual assistant using python, earlier it was only printing listening. Now it is browsing myntra's website for every command given

'''
on executing the following code, when I am giving any instruction to this voice assistant :
it is not printing whatever i am saying
it is opening myntra's website for every instruction I am giving
'''
import pyttsx3 #text to speech
import speech_recognition as sr #recognizes speech
import wikipedia
import webbrowser
import datetime
import os
import smtplib
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id) #activates voice
def speak(audio):
# enables system to speak
engine.say(audio)
engine.runAndWait()
def wishme():
to take know the current time
hour = int(datetime.datetime.now().hour)
if hour >= 00 and hour < 12:
speak("good morning!")
elif hour >= 12 and hour < 18:
speak("good afternoon!")
else:
speak("good evening!")
speak("I am JARVIS sir , how may i help you ?")
def takeCommand():
'''It takes microphone input from user and returns string output'''
# I added r.adjust_for_ambient_noise(source) and reduced threshold frequency
r = sr.Recognizer() # to recognize the user's voice
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
r.energy_threshold = 50 #to listen low frequency voices
r.adjust_for_ambient_noise(source) #to avoid noise
audio = r.listen(source)
try:
print("Recognizing...")
# to recognize user's voice
query = r.recognize_google(audio , Language = "en-in")
print(f"user said: {query}\n")
except Exception as e:
print("Say that again please...")
return "None"
return query
if __name__ == "__main__":
# speak("Akshima is a good girl")
wishme()
while True:
query = takeCommand().lower()
# logic for executing tasks based on query
# maybe there is an error in this part of the code
if 'wikipedia' in query:
speak('Searching Wikipedia...')
query = query.replace("wikipedia", "")
result = wikipedia.summary(query, sentences=2)
speak("according to wikipedia")
print(result)
speak(result)
elif 'open youtube' in query:
# to open youtube
webbrowser.open("youtube.com")
elif 'open google' in query:
webbrowser.open("google.com") #to open google
elif 'play music' in query:
webbrowser.open("spotify.com")
elif 'open myntra' or 'open any online shopping site ' in query:
webbrowser.open("myntra.com")
elif 'open instagram' in query:
webbrowser.open("instagram.com")
elif 'chill' in query:
webbrowser.open("netflix.com")
elif "the time" in query:
# tell user the current time
strTime = datetime.datetime.now().srtftime("%H:%M:%S")
speak(f"The time is {strTime}\n")
elif 'open code' in query:
#to open vs code
path = "C:\\Users\\HP\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
os.startfile(path)

engine.runandWait() get stuck

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()

Python Speech Recognition not working when the file is converted to exe with pyinstaller

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.

Categories

Resources