Error while using print command in python 3.3.2 - python

import random
print((((random.randrange(1,12)//(((random.randrange(1,4)))))))+10)
print((((random.randrange(1,12)//(((random.randrange(1,4)))))))+10)
This is my code so far and it successfully generates two random numbers between the desired integers , now i need it to print in the format of,
Strength = 12
Stamina = 14
I tried like this:
import random
print ' strength = '((((random.randrange(1,12)//(((random.randrange(1,4)))))))+10)
print 'stamina ='((((random.randrange(1,12)//(((random.randrange(1,4)))))))+10)
But this returns an error for a reason unknown to me, I have been stuck on this for hours and I would really appreciate it if someone would help me with this problem, THANKS :)

print is a function in python3, use () to wrap your contents and , to separate them. And you don't need soooo many extra ()s:
In [40]: print('stamina =', random.randrange(1,12)//random.randrange(1,4)+10)
#stamina = 14

import speech_recognition as sr
import pyttsx3
listener = sr.Recognizer()
engine = pyttsx3.init()
engine.say('Iam your alexa')
engine.say('what can i do for you')
engine.runAndWait()
try:
with sr.Microphone() as source:
print('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
if 'alexa' in command:
print(command)
except:
pass

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
........................................................................................................................................................................................................................................................................................................................................................................................

Virtual Assistant only takes voice input one time

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)

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

Is there any way to convert words in to numbers of speech_recognition library in python

I have tried for numbers from 1 to 10 and it works well but i need it to work with all the numbers and it is not feasible to write the code for each number.
I also need it to work in sentences too which is not happening in my code.
Help me out guys, please....
This is my code....
import speech_recognition as sr
import time
t = ['one','two','three','four','five','six','seven','eight','nine','ten']
r = sr.Recognizer()
with sr.Microphone() as source:
print('Speak anything: ')
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print('You said : {} '.format(text))
time.sleep(1)
for i in range(0,10):
if (t[i] == text):
print('/n',i)
except:
print('Sorry could not recogonize your voice')
In case you don't want to take Vivek Mehta's suggestion and don't want an additional dependency, you can use a plain dictionary
import speech_recognition as sr
import time
t = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10}
r = sr.Recognizer()
with sr.Microphone() as source:
print('Speak anything: ')
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print('You said : {0} {1} '.format(text, t[text]))
time.sleep(1)
except:
print('Sorry could not recogonize your voice')

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