24
loading...
This website collects cookies to deliver better user experience
virtualenv
. Python now ships with a pre-installed virtualenv
library. So, to create a virtual environment, you can use the below command:$ python -m venv env
env
. Now, we need to activate the environment using the command:$ . env/Scripts/activate
(env)
in your terminal. Now, we can install the libraries.$ pip install pyttsx3
$ pip install SpeechRecognition
$ pip install pywhatkit
$ pip install wikipedia
$ pip install requests
.env
and add the following content there:USER=Ashutosh
BOTNAME=JARVIS
.env
file, we'll install another module called python-decouple as:$ pip install python-decouple
import pyttsx3
from decouple import config
USERNAME = config('USER')
BOTNAME = config('BOTNAME')
engine = pyttsx3.init('sapi5')
# Set Rate
engine.setProperty('rate', 190)
# Set Volume
engine.setProperty('volume', 1.0)
# Set Voice (Female)
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
engine
using the pyttsx3 module. sapi5
is a Microsoft Speech API that helps us use the voices. Learn more about it here. Next, we are setting the rate
and volume
properties of the speech engine using setProperty
method. Now, we can get the voices from the engine using the getProperty
method. voices
will be a list of voices available in our system. If we print it, we can see as below:[<pyttsx3.voice.Voice object at 0x000001AB9FB834F0>, <pyttsx3.voice.Voice object at 0x000001AB9FB83490>]
voice
property to the female for this tutorial using the setProperty
method. config
method from decouple, we are getting the value of USER
and BOTNAME
from the environment variables.# Text to Speech Conversion
def speak(text):
"""Used to speak whatever text is passed to it"""
engine.say(text)
engine.runAndWait()
speak()
method, the engine speaks whatever text is passed to it using the say()
method. Using the runAndWait()
method, it blocks during the event loop and returns when the commands queue is cleared. from datetime import datetime
# Greet the user
def greet_user():
"""Greets the user according to the time"""
hour = datetime.now().hour
if (hour >= 6) and (hour < 12):
speak(f"Good Morning {USERNAME}")
elif (hour >= 12) and (hour < 16):
speak(f"Good afternoon {USERNAME}")
elif (hour >= 16) and (hour < 19):
speak(f"Good Evening {USERNAME}")
speak(f"I am {BOTNAME}. How may I assist you?")
speech_recognition
module.import speech_recognition as sr
from random import choice
from utils import opening_text
# Takes Input from User
def take_user_input():
"""Takes user input, recognizes it using Speech Recognition module and converts it into text"""
r = sr.Recognizer()
with sr.Microphone() as source:
print('Listening....')
r.pause_threshold = 1
audio = r.listen(source)
try:
print('Recognizing...')
query = r.recognize_google(audio, language='en-in')
if not 'exit' in query or 'stop' in query:
speak(choice(opening_text))
else:
hour = datetime.now().hour
if hour >= 21 and hour < 6:
speak("Good night sir, take care!")
else:
speak('Have a good day sir!')
exit()
except Exception:
speak('Sorry, I could not understand. Could you please say that again?')
query = 'None'
return query
speech_recognition
module as sr
. The Recognizer class within the speech_recognition
module helps us recognize the audio. The same module has a Microphone class that gives us access to the microphone of the device. So with the microphone as the source
, we try to listen to the audio using the listen()
method in the Recognizer class. We have also set the pause_threshold
to 1, i.e., it will not complain even if we pause for one second during we speak.recognize_google()
method from the Recognizer class, we try to recognize the audio. The recognize_google()
method performs speech recognition on the audio passed to it, using the Google Speech Recognition API. We have set the language to en-in
, i.e. English India. It returns the transcript of the audio which is nothing but a string. We've stored it in a variable called query
.utils.py
file which has just one list containing a few statements as:opening_text = [
"Cool, I'm on it sir.",
"Okay sir, I'm working on it.",
"Just a second sir.",
]
opening_text
list. After speaking, we exit from the program.query
to None. In the end, we return the query
. if __name__ == ' __main__':
greet_user()
while True:
query = take_user_input().lower()
print(query)
greet_user()
function. Next, we run a while loop to continuously take input from the user using the take_user_input()
function. For now, we're just printing the query
.main.py
looks like this:import pyttsx3
import speech_recognition as sr
from decouple import config
from datetime import datetime
from random import choice
from utils import opening_text
USERNAME = config('USER')
BOTNAME = config('BOTNAME')
engine = pyttsx3.init('sapi5')
# Set Rate
engine.setProperty('rate', 190)
# Set Volume
engine.setProperty('volume', 1.0)
# Set Voice (Female)
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
# Text to Speech Conversion
def speak(text):
"""Used to speak whatever text is passed to it"""
engine.say(text)
engine.runAndWait()
# Greet the user
def greet_user():
"""Greets the user according to the time"""
hour = datetime.now().hour
if (hour >= 6) and (hour < 12):
speak(f"Good Morning {USERNAME}")
elif (hour >= 12) and (hour < 16):
speak(f"Good afternoon {USERNAME}")
elif (hour >= 16) and (hour < 19):
speak(f"Good Evening {USERNAME}")
speak(f"I am {BOTNAME}. How may I assist you?")
# Takes Input from User
def take_user_input():
"""Takes user input, recognizes it using Speech Recognition module and converts it into text"""
r = sr.Recognizer()
with sr.Microphone() as source:
print('Listening....')
r.pause_threshold = 1
audio = r.listen(source)
try:
print('Recognizing...')
query = r.recognize_google(audio, language='en-in')
if not 'exit' in query or 'stop' in query:
speak(choice(opening_text))
else:
hour = datetime.now().hour
if hour >= 21 and hour < 6:
speak("Good night sir, take care!")
else:
speak('Have a good day sir!')
exit()
except Exception:
speak('Sorry, I could not understand. Could you please say that again?')
query = 'None'
return query
if __name__ == ' __main__':
greet_user()
while True:
query = take_user_input().lower()
print(query)
$ python main.py