Why is the AI repeating the function? - python

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.

Related

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)

How to manually take user input if user doesn't give voice input in python3

I'm using pyttsx3 and speech_recognition package for Python3 to take user's voice input. But what if the user doesn't give any voice input and after the timeout, user have to give manual input? Please help me with this thing!
import pyttsx3
import speech_recognition as sr
import pyjokes
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
r = sr.Recognizer()
user_jokes = "Set a range in number..."
print(user_jokes)
engine.say(user_jokes)
engine.runAndWait()
with sr.Microphone() as source:
user_jokes_rec = r.listen(source, timeout = 2)
user_jokes_X = r.recognize_google(user_jokes_rec, language='en-US')
if user_jokes_X is None:
user_jokes_X = int(input("Set a range for jokes... "))
for x in range(user_jokes_X):
user_jo = pyjokes.get_joke()
print(user_jo)
engine.say(user_jo)
engine.runAndWait()
In this code, the if condition should satisfy, the value of user_jokes_X is empty or none and user manually inputs a range?
You can just toss the program in a try block like so:
import pyttsx3
import speech_recognition as sr
import pyjokes
engine = pyttsx3.init()
voices = engine.getProperty('voices')
r = sr.Recognizer()
user_jokes = "Set a range in number..."
print(user_jokes)
engine.say(user_jokes)
engine.runAndWait()
try:
with sr.Microphone() as source:
user_jokes_rec = r.listen(source, timeout = 2)
user_jokes_X = r.recognize_google(user_jokes_rec, language='en-US')
except:
user_jokes_X = int(input("Set a range for jokes... "))
for x in range(user_jokes_X):
user_jo = pyjokes.get_joke()
print(user_jo)
engine.say(user_jo)
engine.runAndWait()
Let me know if this solves your problem.
You could try as such: except sr.UnknownValueError as e in the exception shown below since it throws UnknownValueError due to no voice input:
try:
with sr.Microphone() as source:
user_jokes_rec = r.listen(source)
user_jokes_X = r.recognize_google(user_jokes_rec, language='en-US')
except sr.UnknownValueError as e:
user_jokes_X = int(input("Set a range for jokes... "))
`

After running the code, I tell the command to my voice assistant, but he does not respond to it, there are no errors

After running the code, I tell the command to my voice assistant, but he does not respond to it and there are no errors.
I tell my bot “what time is it”, but alas, it doesn’t give anything out after that.
I tried to reinstall python
no mistakes, just not responding
I think the problem is in my Python library
import datetime
import time
import pyttsx3
import speech_recognition as sr
from fuzzywuzzy import fuzz
opts = {
"alias": ("Андрей", "Эндрю", "Andrew"),
"tbr": ("скажи", "расскажи", "покажи", "сколько", "произнеси"),
"cmds": {
"time": ("текущее время", "сейчас времени", "который час"),
}
}
def speak(what):
print(what)
speak_engine.say(what)
speak_engine.runAndWait()
speak_engine.stop()
def callback(recognizer, audio):
try:
voice = recognizer.recognize_google(audio, language="ru-RU").lower()
print("[log] Распознано: " + voice)
except sr.UnknownValueError:
print("[log] Голос не распознан!")
except sr.RequestError as e:
print("[log] Неизвестная ошибка, проверьте интернет!")
if voice.startswith(opts["alias"]):
cmd = voice
for x in opts["alias"]:
cmd = cmd.replace(x, "").strip()
for x in opts["tbr"]:
cmd = cmd.replace(x, "").strip()
# распознаем и выполняем команду
cmd = recognize_cmd(cmd)
execute_cmd(cmd["cmd"])
def recognize_cmd(cmd):
RC = {"cmd": "", "percent": 0}
for c, v in opts["cmds"].items():
for x in v:
vrt = fuzz.ratio(cmd, x)
if vrt > RC["percent"]:
RC["cmd"] = c
RC['percent'] = vrt
return RC
def execute_cmd(cmd):
if cmd == "time":
now = datetime.datetime.now()
speak("Сейчас " + str(now.hour) + ":" + str(now.minute))
r = sr.Recognizer()
m = sr.Microphone(device_index=1)
with m as source:
r.adjust_for_ambient_noise(source)
speak_engine = pyttsx3.init()
speak("Добрый день, создатель")
speak("Слушаю вас ...")
stop_listening = r.listen_in_background(m, callback)
while True: time.sleep(0.1)
The indentation's wrong: in the callback function, recognize_cmd or any other logic that deals with the response will be invoked if and only if recognizer.recognize_google raises the sr.RequestError exception, so you should move said logic one level of indentation up.
EDIT:
Moreover, due to the usage of lower() in voice = recognizer.recognize_google(audio, language="ru-RU").lower(), voice will always be lowercase, so voice.startswith(opts["alias"]) will always be false since each element of opts["alias"] contains an uppercase character: namely, А, Э and A.

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

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

Categories