Virtual Assistant only takes voice input one time - python

i am coding a virtual assistant, everything is fine it listens to my audio input and responses correctly, but when i run the programme it only takes my command one time and the programme ends. I can't figure out where should I use the while loop so that the programme continues until i ask it to end. I tries addding while loops in different function but none seem to work.
import speech_recognition
import pyttsx3 as tts
import subprocess
import datetime
import webbrowser
import time
now = datetime.datetime.now()
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
x = speaker.getProperty('voices')
speaker.setProperty('voice', x[1].id)
y = speaker.getProperty('rate')
speaker.setProperty('rate' , 175)
def record_audio(ask = False):
with speech_recognition.Microphone() as mic:
if ask:
tts.speak(ask)
print("listening")
recognizer.adjust_for_ambient_noise(mic , 0.05)
audio = recognizer.listen(mic)
try:
voice_data = recognizer.recognize_google(audio , language = "en-IN")
except speech_recognition.UnknownValueError:
tts.speak('Sorry, I did not understand what you just said. Please try again.')
except speech_recognition.RequestError:
tts.speak("Sorry, my speech service is down for the time being. Please try again later.")
return voice_data
def responses(command):
if 'hello' in command:
tts.speak("hello sir, how can I help you.")
elif 'what is your name' in command:
tts.speak("My name is Otto Octavius")
elif 'time' in command:
tts.speak(now.strftime("%I:%M:%S"))
elif 'date' in command:
tts.speak(now.strftime("%Y-%m-%d"))
elif 'open' and 'telegram' in command:
tts.speak("opening telegram")
subprocess.Popen("D:\My Folder\My Softwares\Telegram Desktop\Telegram.exe")
elif 'close' and 'telegram' and 'window' in command:
tts.speak("closing telegram")
subprocess.call(["taskkill","/F","/IM","Telegram.exe"])
elif 'open' and 'binance' in command:
tts.speak("opening binance")
subprocess.Popen("D:\My Folder\My Softwares\Binance\Binance.exe")
elif 'close' and 'binance' in command:
tts.speak('closing binance')
subprocess.call(["taskkill" , "/F" , "IM" , 'Binance.exe'])
elif 'file explorer' in command:
tts.speak("opening file explorer")
webbrowser.open('C:/Users/arfee/Downloads')
elif 'my folder' in command:
tts.speak('opening my folder')
webbrowser.open("D:\My Folder")
elif 'search' in command:
search_object = record_audio("What do you want me to search for?")
url = ("https://www.google.com/search?q=" + search_object)
tts.speak('Searching for ' + search_object)
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open_new_tab(url)
tts.speak("Welcome, how can I help you")
command = record_audio()
responses(command)

Try putting this in an infinite loop -
while True:
command = record_audio()
responses(command)

Related

Code not showing Radar API(geofencing) details because of error [duplicate]

This question already has answers here:
python dictionary keyError
(5 answers)
Closed 11 days ago.
This post was edited and submitted for review 11 days ago and failed to reopen the post:
Original close reason(s) were not resolved
my code on line 152 is giving me KeyError. I suspect it to be an error from radar API or from the os module. API key may also be in question. Please help!
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
import tkinter as tk
from tkinter import *
import turtle
from playsound import playsound
#pip install playsound==1.2.2, pyfiglet, SpeechRecognition, PyAudio, pyttsx3,termcolor
#Wish Happy New Year 2023
import pyfiglet
import time
from termcolor import colored,cprint
wish =['Welcome','To','The','AI','Assistant']
count=0
colors=['green','yellow','magenta','cyan','orange']
playsound('C:/Users/anish/Start_up.mp3',False)
for i in range(1,6):
if(count>4):
count=0
cprint('*'*60,'red')
else:
color=colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width = 150)
cprint(msg,color)
count = count + 1
time.sleep(0.7)
# CODE FOR PROGRAM:
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
newVoiceRate = 145
engine.setProperty('rate',newVoiceRate)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
talk("Talk after the tune!")
playsound("C:/Users/anish/correct-2-46134.mp3",False)
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
print(command)
except:
pass
return command
def run_alexa():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk('sorry, I have a headache')
elif 'are you single' in command:
talk('I am in a relationship with wifi')
elif 'joke' in command:
y = pyjokes.get_joke()
print(y)
talk(y)
elif 'shut up' in command:
LOL = "Haha, you cannot stop me! But, I will stop now. Bye!"
print(LOL)
talk(LOL)
playsound('C:/Users/anish/goodbye-until-next-time-29143.mp3', False)
wish = ['Made', 'By', ' ', 'Me!', 'Thank You!']
count = 0
colors = ['green', 'yellow', 'magenta', 'cyan', 'orange']
for i in range(1, 6):
if (count > 4):
count = 0
cprint('*' * 60, 'red')
else:
color = colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width=150)
cprint(msg, color)
count = count + 1
import time
time.sleep(0.7)
exit()
elif "stop" in command:
STO_P = "Ok, I will stop. Bye!"
print(STO_P)
talk(STO_P)
playsound('C:/Users/anish/goodbye-until-next-time-29143.mp3',False)
wish = ['Made', 'By', ' ', 'Me!', 'Thank You!']
count = 0
colors = ['green', 'yellow', 'magenta', 'cyan', 'orange']
for i in range(1, 6):
if (count > 4):
count = 0
cprint('*' * 60, 'red')
else:
color = colors[count]
msg = pyfiglet.figlet_format(wish[count],
font='starwars',
width=150)
cprint(msg, color)
count = count + 1
import time
time.sleep(0.7)
time.sleep(2)
result = pyfiglet.figlet_format("Built using Python", font="digital")
print(result)
time.sleep(4)
exit()
elif "open" in command:
ope_n = command.replace("open",'')
talk('opening' + ope_n)
from AppOpener import open
open(ope_n)
elif"website" in command:
url = command.replace("website",'')
x = "Opening Website"
chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
webbrowser.register('chrome', None,webbrowser.BackgroundBrowser(chrome_path))
webbrowser.get('chrome').open(url)
print("Okay, just a minute!")
talk(x)
elif "where is" in command:
import os
from radar import RadarClient
# initialize client
radar = RadarClient(os.environ["RADAR_SECRET_KEY"])
# get a geofence by id
geofence = radar.geofences.get(id='123')
# list geofences
radar.geofences.list()
else:
talk('Please say the command again.')
while True:
run_alexa()
I tried changing my radar api key, but not working. Also checked my code!
Maybe it is either the api key, or something wrong with the os module.
I am actually working on a small project, but as one def function controls it, had to paste the entire code.
Inconvenience regretted!
I hope we can solve this as soon as we can!
I have switched to OpenStreetMaps now, but bould still love to know about the issue, ThankYou!!!

UnboundLocalError: local variable 'command' referenced before assignment. error in python program

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import webbrowser
import os
import sys
listener = sr.Recognizer()
engine = pyttsx3.init()
engine.setProperty("rate", 150)
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source, None, 10)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
command = command.replace('alexa', '')
print(command)
except:
pass
return command
def run_alexa():
command = take_command()
print(command)
if 'play' in command:
video = command.replace('play', '')
talk('playing' + video)
pywhatkit.playonyt(video)
elif 'search for' in command:
search = command.replace('search for', '')
talk('searching' + search)
pywhatkit.search(search)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is' + time)
elif 'who is' in command:
person = command.replace('who is', '')
info = wikipedia.summary(person, 3)
print(info)
talk(info)
elif 'what is my name' in command:
talk('your name is yuva dharshan')
elif 'who are you' in command:
talk('i am alexa, your personal voice assistant, you created me to obey\
your orders and execute your orders sir')
elif 'hai' in command:
talk('hi sir how can i help you')
elif 'open youtube' in command:
talk('opening youtube')
webbrowser.open("http://youtube.com", new=1)
elif "open gmail" in command:
talk('opening gmail')
webbrowser.open("https://mail.google.com/mail/u/0/?tab=rm&ogbl#inbox", new=1)
elif 'open facebook' in command:
talk('opening facebook')
webbrowser.open("https://www.facebook.com/", new=1)
elif 'open instagram' in command:
talk('opening insta gram')
webbrowser.open("https://www.instagram.com/", new=1)
elif 'open downloads folder' in command:
talk('opening downloads folder')
path = "C:/Users/yuvad/Downloads"
webbrowser.open(path)
elif 'open control panel' in command:
talk('opening control panel')
os.system('control.exe')
elif ('bye') or ('quit') in command:
sys.exit()
else:
talk("pls say the command again")
while True:
run_alexa()
when I run the program I get this error:
Traceback (most recent call last):
File "C:\Users\yuvad\AppData\Local\Programs\Python\Python37\alexavoiceassistant.py", line 116, in <module>
run_alexa()
File "C:\Users\yuvad\AppData\Local\Programs\Python\Python37\alexavoiceassistant.py", line 38, in run_alexa
command = take_command()
File "C:\Users\yuvad\AppData\Local\Programs\Python\Python37\alexavoiceassistant.py", line 34, in take_command
return command
UnboundLocalError: local variable 'command' referenced before assignment
What happens if your first try/except block catches an exception?
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source, None, 10)
command = listener.recognize_google(voice)
except:
pass
return command
command has not been assigned! But you still try to return it, hence the error.
either something like:
errored = 0
MAXERR = 3
while not command and errored < MAXERR:
try:
...
command = listener.recognize_google(voice)
except Exception: # preferably catch a *special type of exception*
MAXERR += 1
if not command:
raise Exception("Failed to get command")
return command
or return e.g. None to indicate failure:
command = None
try:
command = ...
except Exception:
pass
return command
And then test for None in your main code.
You don't want a bare except: because it catches everything, including the system trying to terminate the process and the user pressing Ctrl-C. At the very least catch Exception, which won't catch those two cases.

How to make your virtual assistant speak when there is "google" in your command?

I am a student and I am making a virtual assistant on Python 3.9. I want my assistant answer my questions when I say "google" in command, but I don't know why its not working. I tried so many ways but it still doesn't work and I don't know how to fix it, so I hope you guys can help me to fix it.
Thanks for any help!
Here is my code:
import speech_recognition
import pyttsx3
robot_ear = speech_recognition.Recognizer()
robot_mouth = pyttsx3.init()
voices = robot_mouth.getProperty('voices')
robot_mouth.setProperty('voice', voices[1].id)
def robot_brain(robot_brain):
print("Jarvis: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
def take_command():
try:
with speech_recognition.Microphone() as mic:
print("Jarvis: I'm Listening")
audio = robot_ear.listen(mic,timeout=6 )
print("Jarvis: ...")
you = robot_ear.recognize_google(audio)
you = you.lower()
if "google" in you:
you = you.replace("google", "")
print(you)
except:
pass
you = ""
print("Boss: " + you)
return you
def run_google():
you = take_command()
print(you)
if "hello" in you:
robot_brain = "hello"
elif "bye" in you:
robot_brain = "bye"
print("Jarvis: " + robot_brain)
robot_mouth.say(robot_brain)
robot_mouth.runAndWait()
else:
robot_brain = "I can't hear you, try again"
while True:
run_google()
please make sure you have all the necessary modules installed.
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def talk(text):
engine.say(text)
engine.runAndWait()
def take_command():
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'google' in command:
command = command.replace('google', '')
print(command)
except:
pass
return command
def run_google():
command = take_command()
print(command)
if 'play' in command:
song = command.replace('play', '')
talk('playing ' + song)
pywhatkit.playonyt(song)
elif 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
talk('Current time is ' + time)
elif 'who the heck is' in command:
person = command.replace('who the heck is', '')
info = wikipedia.summary(person, 1)
print(info)
talk(info)
elif 'date' in command:
talk('sorry, I have a headache')
elif 'are you single' in command:
talk('I am in a relationship with wifi')
elif 'joke' in command:
talk(pyjokes.get_joke())
else:
talk('Please say the command again.')
while True:
run_google()

Python-attribute error with bluebooth

I use google-voice-kit with raspberry pi 3. I try to change the code to connect to bluetooth. The code is:
import aiy.audio
import aiy.cloudspeech
import aiy.voicehat
#import bluetooth
def main():
recognizer = aiy.cloudspeech.get_recognizer()
recognizer.expect_phrase('turn off the light')
recognizer.expect_phrase('turn on the light')
recognizer.expect_phrase('blink')
button = aiy.voicehat.get_button()
led = aiy.voicehat.get_led()
#bd_addr = "E0:31:4B:2C:C6:4E"
#port = 1
#sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
#sock.connect((bd_addr,port))
aiy.audio.get_recorder().start()
while True:
print('Press the button and speak')
button.wait_for_press()
print('Listening...')
text = recognizer.recognize()
if text is None:
print('Sorry, I did not hear you.')
else:
print('You said "', text, '"')
if 'turn on the light' in text:
led.set_state(aiy.voicehat.LED.ON)
#sock.sent([0x00,0xFF,0x01,0x03,0xFF,0xFF,0xFF])
#sock.close()
elif 'turn off the light' in text:
led.set_state(aiy.voicehat.LED.OFF)
elif 'go' in text:
led.set_state(aiy.voicehat.LED.BLINK)
sock.sent([0x00,0xFF,0x01,0x03,0xFF,0xFF,0xFF])
elif 'goodbye' in text:
break
if __name__ == '__main__':
main()
The code which starts with "#" is what I added.
The error is: AttributeError: 'module' object has no attribute 'BluetoothSocket'
I installed the bluetooth and used chmod to change its permissions but it still gives the error. The name of this code is cloudspeech_demo.py. I am certain that i don't have any file which name is the same as this.

Setting Up livestreamer to Automatically Record twitch Streams

I have been looking for a way to record streams whilst not at home as past broadcasts are unsatisfactory to me with all their muted sections. I had a found one site to help get me started but when i went to check for replies to after commenting asking for help and including images of my script i see that my posting got deleted rather than answered. But i digress.
I know how to manually start livestreamer from the command prompt when the stream is live but as aforementioned i am looking for a solution for when i'm not home.
I am sharing what i have in the hopes that someone would be able to identify what is wrong and help me rectify all issues to get this working.
#This script checks if a user on twitch is currently streaming and then records the stream via livestreamer
from urllib.request import urlopen
from urllib.error import URLError
from threading import Timer
import time
import datetime
import json
import sys
import subprocess
import datetime
import os
import configparser
def check_user(user):
""" returns 0: online, 1: offline, 2: not found, 3: error """
global info
url = 'https://api.twitch.tv/kraken/streams/' + user +"/?client_id=###"
try:
info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
if info['stream'] == None:
status = 1
else:
status = 0
except URLError as e:
if e.reason == 'Not Found' or e.reason == 'Unprocessable Entity':
status = 2
else:
status = 3
return status
def format_filename(fname):
# Removes invalid characters from filename
fname = fname.replace("/","")
fname = fname.replace("?","")
fname = fname.replace(":","-")
fname = fname.replace("\\","")
fname = fname.replace("<","")
fname = fname.replace(">","")
fname = fname.replace("*","")
fname = fname.replace("\"","")
fname = fname.replace("|","")
fname = fname.replace(" ","")
return fname
def loopcheck():
while True:
status = check_user(user)
if status == 2:
print("username not found. invalid username?")
elif status == 3:
print(datetime.datetime.now().strftime("%Hh%Mm%Ss")," ","unexpected error. will try again in 5 minutes.")
time.sleep(300)
elif status == 1:
print(user,"currently offline, checking again in",refresh,"seconds")
time.sleep(refresh) # 15 seconds
elif status == 0:
print(user,"online. stop.")
filename = user+" - "+datetime.datetime.now().strftime("%Y-%m-%d %Hh%Mm%Ss")+" - "+(info['stream']).get("channel").get("status")+".mp4"
filename = format_filename(filename)
str1="livestreamer --twitch-oauth-token ### twitch.tv/"+user+" "+quality+" -o "+directory+filename
subprocess.call(str1)
print("Stream is done. Going back to checking..")
time.sleep(15)
def main():
global refresh
global user
global quality
global directory
print("Usage: check.py [refresh] [user] [quality]")
print("Usage: TwitchChecker.py [refresh] [user] [quality]")
refresh = 15.0
str1=""
refresh = 15.0
user = "###"
quality = "best"
directory = "C:\Users\###\Videos\###\\"
if(refresh<15):
print("Check interval should not be lower than 15 seconds")
refresh=15
print("Checking for",user,"every",refresh,"seconds. Record with",quality,"quality.")
loopcheck()
if __name__ == "__main__":
# execute only if run as a script
main()
set /p DUMMY=Hit ENTER to continue...
For the batch file i have:
#echo
C:\Python\python C:\Users\xxx\Videos\xxx\xxx.py
#echo off
All that happens when i click on either of the 2 files is that the command prompt window flashes quickly.
Thankies for any and all help!

Categories