How can i make the python to wait till i complete speaking? - python

I am writing a program to recognise the speech from a microphone and the code will process accordingly. The code I wrote for this purpose is below.
import speech_recognition as sr
import webbrowser
import pyttsx
from time import sleep
engine = pyttsx.init()
engine.setProperty('rate', 70)
r = sr.Recognizer()
def recognize(audio):
try:
return r.recognize(audio)
except LookupError, e:
print e
return ''
with sr.Microphone() as source:
while True:
engine.say("Hi How can i help you ?")
sleep(0.15)
print "Start Speaking"
audio = r.listen(source)
words = recognize(audio)
print("You said " + words)
if words == "Facebook":
engine.say("Shall i open the Facebook page for you ?")
engine.runAndWait()
audio = r.listen(source)
words = recognize(audio)
if words == "Yes":
webbrowser.open('https://www.facebook.com')
elif words == "stop":
break
Here I tried sleep also but before the engine speaks I can see the text Start Speaking getting printed. Instead of Sleep, is there any nice way to capture the speech in microphone and wait till say something or for a long silence?

This method:
engine.runAndWait()
waits for speech to complete. You need to use it not just after engine.say("Shall i open the Facebook page for you ?"), but also after engine.say("Hi How can i help you ?")
instead of sleep

I normally use global variables which are frowned upon but the following is correct I think? The following two def's should help...
# contains reusable print and speech
def output_modes(output):
engine = pyttsx3.init()
print(f"Output: {output}")
engine.say(output)
engine.runAndWait()
# contains reusable grabbing audio
def input_modes():
r1 = sr.Recognizer()
mic1 = sr.Microphone()
with mic1:
try:
output = r1.recognize_google(r1.listen(mic1))
output_modes()
except sr.UnknownValueError:
output = "Unknown Error M1"
output_modes()
except sr.RequestError as e:
output = "Error M2; {0}".format(e)
output_modes()
You should be able to write a While loop that can call on input_modes() to listen or output_modes to speak for example
def interact():
if input == 'Hello':
output = 'Hi there'
output_modes

Related

How do I get my python virtual assistant to only listen once it hears a wake word?

I have a python virtual assistant that is always listening for commands. How can I make it so she only starts listening to commands once she hears the wake word such as Alexa, or in this case Anna. If you have any tips or answers they will be greatly appreciated. Thank you!
import speech_recognition as sr
import pyttsx3
tts = pyttsx3.init()
voices = tts.getProperty('voices')
tts.setProperty('voice', voices[1].id)
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print('Listening...')
r.pause_threshold = 0.5
audio = r.listen(source)
try:
print("Recognizing")
Query = r.recognize_google(audio, language='en-us')
print("the command is printed=", Query)
except Exception as e:
print(e)
print("Say that again")
return "None"
return Query
def Take_query():
while(True):
query = takeCommand().lower()
if "Hello" in query:
tts.say('Hello')
tts.runAndWait()
continue
elif "How are you" in query:
tts.say('I am good')
tts.runAndWait()
continue
if __name__ == '__main__':
Take_query()
Anna will always listen, so you have 2 choices
force the program to ignore any query without Anna
so the program will ignore anything doesn't start with Anna
def takeCommand():
r = sr.Recognizer()
with sr.Microphone() as source:
print('Listening...')
r.pause_threshold = 0.5
audio = r.listen(source)
try:
print("Recognizing")
Query = r.recognize_google(audio, language='en-us')
print("the command is printed=", Query)
except Exception as e:
print(e)
print("Say that again")
return "None"
if Query.startswith("Anna"):
return Query
else:
return "None"
Nested recognition
this is might be better for you, just nest the recognition, first recognize Anna then and only then the command
hope that helps you

I have a problem implementing Iteration from the Excel File to iterate through the rows to check pronunciation of the translated word?

import pyttsx3
import speech_recognition as sr
engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[1].id)
from googletrans import Translator
import pandas as pd
ts = Translator()
df = pd.read_excel('Words.xlsx')
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takeCommand():
listener = sr.Recognizer()
with sr.Microphone() as source:
print("\nListening.......")
listener.pause_threshold = 1
listener.energy_threshold = 400 # This will listen to the louder voice only, so all you need to do is to speak loudly to give the command.
audio = listener.listen(source, timeout=None, phrase_time_limit=2) # It will give you ten seconds to give the argument otherwise it will run again
try:
## Tried making the iteration here but It gave me hard time
print(" Recognising.....")
query = listener.recognize_google(audio, language="es") # Here you can choose the language of your choice
translation = ts.translate(query) # Translates from Spanish to english
print(f" You said --> {translation.text} \n")
speak(trans.text) # Say the Translated word outloud
input() # Just a pause so I can proceed only when I hit enter
except Exception as e:
# print(e)
print("Sorry I didn't Recognise. Please say it again.....")
return "None"
return query
if __name__ == '__main__':
speak("Go Ahead")
while True:
takeCommand()
I need it to say the English word and hear the Spanish word and validate it
Column A
Column B
love
amor
hate
odio
freedom
felicidad
........................................................................................................................................................................................................................................................................................................................................................................................

How to access variable from while loop in python, import it to another .py file and print it

I have two Python files, I want to access variable from while loop while True.
Print it to another python file
main.py
#main.py
import speech_recognition as sr
import pyttsx3
import pywhatkit
import subprocess
import os
import sys
def restart_program():
python = sys.executable
print(python)
os.execl(python, python, *sys.argv)
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("cancle")
print("Exception: " + str(e))
# return Task()
return said.lower()
def Task():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
# audio = r.listen(source, timeout=3)
print("listening...")
said = r.recognize_google(audio)
said = said.lower()
# said = "alexa play a song"
# said = "alexa navigate me"
if 'alexa' in said:
command = said.replace("alexa", "")
print(command)
else:
command = "null"
except:
command = "null"
return command
def process_command(command):
print(command)
if ('cancel' in command or 'nevermind' in command or 'forget it' in command):
speak("Sorry.")
SONG_STRS = ["play a song", "sing"]
for phrase in SONG_STRS:
if phrase in command:
speak("What would you like to play?")
song = get_audio()
if ('cancel' in song or 'nevermind' in song or 'forget it' in song):
speak("Sorry.")
else:
pywhatkit.playonyt(song)
speak("I've done that.")
NAV_STRS = ["navigate me to", "start navigate", "let's go to"]
for phrase in NAV_STRS:
if phrase in command:
speak("Where would you like Go?")
place = get_audio()
if ('cancel' in song or 'nevermind' in song or 'forget it' in song):
speak("Sorry.")
else:
speak("okay, let's go to." + place)
if 'restart' in command or 'reload' in command:
speak("Cake and grief counseling will be available at the conclusion of the test.")
restart_program()
print(place) #and also print here
while True:
command = Task()
process_command(command)
And also print place in main.py.
value.py:
#value.py
x = place #this is variable from main.py --> def process_command
print(x)

Why is the AI repeating the function?

When I say "Friday" "take a screenshot" it takes a screenshot. Everything okay. But it repeats this function. It says "I took a screenshot of your main screen" and takes a screenshot again and again. It is only this function. I tried with other functions but there it repeats it only one time - that is an other problem to fix.
Main code:
import functions as FF
import speakandrecognizefunctions as SRF
import datetime
import pyautogui
WAKE_WORD = "friday"
USER = "user"
PATH = "C://MeineDirection"
def success():
print("Succesful")
def screenshot():
date = datetime.datetime.now()
filename = str(date).replace(":", "-") + "-screenshot.png"
img = pyautogui.screenshot()
img.save(f'{PATH}//screenshots//{filename}')
SRF.speak("I took a screenshot of your main screen " + USER)
while True:
text = SRF.takecommandbackground()
if text.count(WAKE_WORD) > 0:
SRF.speak("Im listening " + USER)
print("\nListening....")
text = SRF.takecommand()
SCREENSHOT_STRS = ["make a screenshot", "take a screenshot", "screenshot"]
for phrase in SCREENSHOT_STRS:
if phrase in text:
screenshot()
success()
Speech recognition code:
import pyttsx3
import speech_recognition as sr
import config
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
WAKE_WORD = "friday"
def speak(text):
engine.say(text)
engine.runAndWait()
def takecommand():
r = sr.Recognizer()
with sr.Microphone() as source:
#r.adjust_for_ambient_noise(source, duration=0.5)
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
speak("I didnt get that !!")
print(f"Exception. Say {WAKE_WORD} and try again " + str(e))
pass
return said.lower()
def takecommandbackground():
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source, duration=0.3)
#print("Ready")
audio = r.listen(source, phrase_time_limit=4)
try:
# print("Recognizing....")
query = r.recognize_google(audio)
#print("user said : ", query)
# speak(query)
except Exception:
#print("Say that again please !! ")
return "none"
return query.lower()
Easy "take a screenshot" will trigger for "take a screenshot" & "screenshot"
Take out "screenshot" from SCREENSHOT_STRS and see what . If that works then you want to break the loop as #jasonharper suggested
You need to break the Loop, because it loops all the Time, or you clear the Text Var.

i'm trying to run this program in Python, but i'm not able to execute def

i'm trying to run this program in Python, but i'm not able to execute def. this is an assistant who shuold be able to catch words from the users and execute orders accordingly
the main question is:
how can I built an run more actions. example:
user said: stevens, what do you think about sports?
the IA (Steven) should be able to catch this string as an input order and execute a function and/or reply accordingly (based upon a pre-existing command line). Possible outputs should be: a. run a mp3 file, print a sentence, run a program
how can I execute def greeting?
this is the whole code:
import gtts
from gtts import gTTS
import warnings
import speech_recognition as sr
import os
import google
import random
warnings.filterwarnings('ignore')
def record_audio():
r = sr.Recognizer()
global data
with sr.Microphone() as source:
print('Say something! ')
audio = r.listen(source)
try:
data = r.recognize_google(audio)
print(data)
except sr.UnknownValueError:
print('I am waiting for your orders')
except sr.RequestError as e:
print('Google speech rec error')
return data
def assistant_responses(text):
print(text)
myobj = gTTS(text= text, lang= 'en', slow=False)
myobj.save('assistant_response.mp3')
os.system('start assistant_response.mp3')
def wake_words(text):
WAKE_WORDS = ['stevens', 'hi stevens']
text = text.lower()
for phrase in WAKE_WORDS:
if phrase in text:
return True
return False
def greeting(text):
GREETING_INPUTS = ['hi', 'hey', 'hola', 'ciao', 'hello', 'good morning']
GREETING_RESPONSES = ['hello sir', 'good morning sir', 'how can i help you sir?']
for word in text.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES) +'.'
return ''
while True:
text = record_audio()
response = greeting(text)
if wake_words(text) == True:
print('Good day sir')
elif greeting(text) == True:
print('Hello sir')
The issue is that you want to have the result of greeting be displayed, but you're not displaying the result anywhere. This is how you currently call greeting:
response = greeting(text)
All this is doing is setting the variable response to something from GREETING_RESPONSES. It's not telling Python to display anything. You have to actually print the response (or do something else with it besides nothing):
response = greeting(text)
print(response)
Or just:
print(greeting(text))

Categories