Simple voice-controlled assistant using the SpeechRecognition and pyttsx3 libraries. The assistant can understand voice commands, respond to queries, and perform certain actions. Let's break down the code:
required packages or dependencies
pip3 install gtts
pip3 install pyttsx3
sudo apt-get install espeak
sudo apt-get install libespeak1
pip3 install SpeechRecognition
sudo apt-get install python3-dev
sudo apt-get install portaudio19-dev
pip3 install pyaudio
import random
import pyttsx3
import speech_recognition as sr
import platform
import subprocess
class Assistant:
def __init__(self, name, voice_rate=150):
self.name = name
self.engine = pyttsx3.init(driverName='sapi5' if platform.system().lower() == 'windows' else 'espeak')
self.recognizer = sr.Recognizer()
self.engine.setProperty('rate', voice_rate)
self.set_female_voice()
def set_female_voice(self):
voices = self.engine.getProperty('voices')
for voice in voices:
if "female" in voice.name.lower():
self.engine.setProperty('voice', voice.id)
return
def greet(self):
print(f"Hello! I'm {self.name}, your assistant. How can I help you today?")
def get_voice_input(self):
with sr.Microphone() as source:
print("Listening...")
audio = self.recognizer.listen(source)
try:
print("Recognizing...")
query = self.recognizer.recognize_google(audio)
print(f"You: {query}")
return query
except sr.UnknownValueError:
print("Sorry, I didn't catch that. Can you please repeat?")
return self.get_voice_input()
except sr.RequestError as e:
print(f"Could not request results from Google Speech Recognition service; {e}")
return None
def respond_to_query(self, query):
# Add your own logic here to handle different types of questions
if "tor naam" in query.lower():
return f"My name is {self.name}."
elif "a" in query.lower():
return "Hello Pratap kemon Acho"
elif "how are you" in query.lower():
return "I'm just a computer program, but thanks for asking!"
elif "stop" in query.lower():
return "Hi Hiyea baby Don't Go. Do not Open The door"
elif "bangla" in query.lower():
return "Ami Bangla jani,Kintu Sir, Ami Besi kichu sekhai ni"
elif "who i am" in query.lower():
return "No Sir by the way whats your name"
elif "terminal" in query.lower():
return subprocess.run(["gnome-terminal"])
elif "close terminal" in query.lower():
return subprocess.run(["pkill", "gnome-terminal"])
elif "bhalo" in query.lower():
return "Thank u sir"
elif "open sublime" in query.lower():
return subprocess.run(["subl"])
elif "close sublime" in query.lower():
return subprocess.run(["pkill", "subl"])
else:
return "I'm not sure I understand. Can you please provide more details?"
def speak(self, text):
self.engine.say(text)
self.engine.runAndWait()
# Usage
if __name__ == "__main__":
assistant_name = "Dipankar and It's my 0.1 version"
voice_speed = 130 # Adjust this value to control the voice speed
my_assistant = Assistant(assistant_name, voice_speed)
while True:
my_assistant.greet()
user_input = my_assistant.get_voice_input()
if user_input is not None and user_input.lower() in ["exit", "quit", "bye"]:
print(f"{assistant_name}: Goodbye!")
break
response = my_assistant.respond_to_query(user_input)
print(f"{assistant_name}: {response}")
my_assistant.speak(response)
Assistant
Initialization:
__init__
method sets up the assistant with a name and initializes the text-to-speech engine (pyttsx3
), speech recognizer (SpeechRecognition
), and voice rate.Voice Configuration:
set_female_voice
method selects a female voice if available.Greeting:
greet
method prints a welcome message.Voice Input:
get_voice_input
method uses the microphone to capture audio and utilizes Google's Speech Recognition service to convert it into text.Query Response:
respond_to_query
method interprets the user's query and provides a predefined response. It includes responses for greetings, asking about the assistant's name, checking the user's well-being, handling terminal commands (e.g., opening/closing the terminal, Sublime Text), and more.Text-to-Speech:
speak
method uses the text-to-speech engine to convert text into spoken words.Assistant
class named my_assistant
.respond_to_query
method.No module named PIL Install PIL module: If you haven't installed PIL yet, install it using pip, the..
Lambda is a small and anonymous function in Python, where you can use many arguments but only ..
Connect with mysql database using python Install the mysql-connector-python-rf - $..
Insert data into MySQL table using Python. Install mysqlclient Open Terminal..
Get the latest news and updates by signing up to our daily newsletter.We won't sell your email or spam you !