Building an AI Assistant with Voice Control using Python
In this tutorial, we will learn how to build an AI assistant with voice control using Python. The assistant will be able to perform various tasks such as searching the web, opening applications, playing music, sending emails, providing information from Wikipedia, setting reminders, and more. We will be using several Python libraries such as pyttsx3, speech_recognition, datetime, wikipedia, webbrowser, os, smtplib, urllib.parse, subprocess, time, and requests.
Prerequisites
To follow along with this tutorial, you will need:
- Python installed on your system (version 3.6 or higher).
- The following Python libraries: pyttsx3, speech_recognition, wikipedia, webbrowser, os, smtplib, urllib.parse, subprocess, time, and requests. You can install them using pip:
pip install pyttsx3 speechrecognition wikipedia requests
Understanding the Code
Let's go through the code step by step and understand each component:
Importing the necessary libraries:
pythonimport pyttsx3 import speech_recognition as sr import datetime import wikipedia import webbrowser import os import smtplib import urllib.parse import subprocess import time import requests
Initializing the pyttsx3 engine:
pythonengine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id)
Defining a function to convert text to speech:
pythondef speak(audio): engine.say(audio) engine.runAndWait()
Creating a function to greet the user based on the current time:
pythondef wishMe(): hour = datetime.datetime.now().hour if 0 <= hour < 12: greeting = "Good Morning!" elif 12 <= hour < 18: greeting = "Good Afternoon!" else: greeting = "Good Evening!" speak(f"{greeting} Hello, I am your AI assistant. How may I assist you?")
Implementing a function to listen to the user's voice command:
pythondef takeCommand(): 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') print(f"User said: {query}\n") return query except Exception as e: print("Say that again, please...") return "None"
Creating a function to search YouTube based on a query:
pythondef searchYouTube(query): base_url = 'https://www.youtube.com/results?search_query=' query = urllib.parse.quote_plus(query) webbrowser.open(base_url + query)
Defining a function to open Google Chrome:
pythondef openChrome(): codePath = r"C:\Program Files\Google\Chrome\Application\chrome.exe" webbrowser.get(codePath).open("google.com")
Creating a function to search Google based on a query:
pythondef searchGoogle(query): base_url = 'https://www.google.com/search?q=' query = urllib.parse.quote_plus(query) webbrowser.open(base_url + query)
Implementing a function to send emails:
pythondef sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login('youremail@gmail.com', 'your-password') server.sendmail('youremail@gmail.com', to, content) server.close()
Defining a function to perform calculations:
pythondef calculate(expression): try: result = eval(expression) speak(f"The result is {result}") except Exception as e: speak("Sorry, I couldn't perform the calculation.")
Creating a function to set reminders:
pythondef setReminder(): speak("What should I remind you about?") reminder = takeCommand() speak("When should I remind you?") reminder_time = takeCommand() # Extract hours and minutes from the reminder time hours, minutes = map(int, reminder_time.split(':')) # Get the current date and time now = datetime.datetime.now() # Set the reminder time with the current date and specified hours and minutes reminder_time = now.replace(hour=hours, minute=minutes, second=0, microsecond=0) # Calculate the time difference between now and the reminder time time_difference = (reminder_time - now).total_seconds() if time_difference <= 0: speak("The reminder time has already passed.") else: speak(f"Reminder set for {reminder_time.strftime('%H:%M')}.") time.sleep(time_difference) speak(f"Reminder: {reminder}")
Implementing a function to process user commands:
pythondef processCommand(command): if 'wikipedia' in command: speak('Searching Wikipedia...') query = command.replace("wikipedia", "") results = wikipedia.summary(query, sentences=2) speak("According to Wikipedia") print(results) speak(results) elif 'open youtube' in command: webbrowser.open("https://www.youtube.com") elif 'open chat' in command: webbrowser.open("https://chat.openai.com") elif 'open google' in command: webbrowser.open("https://www.google.com") # ... more commands ...
Defining a function to get the weather information:
pythondef getWeather(): api_key = "65d2b3204db54b0696140719232506" # Replace with your actual API key base_url = f"http://api.weatherapi.com/v1/current.json?key={api_key}&q=current" response = requests.get(base_url) data = response.json() if 'error' in data: speak("Sorry, I couldn't retrieve the weather information.") else: location = data['location']['name'] temperature = data['current']['temp_c'] condition = data['current']['condition']['text'] speak(f"The current temperature in {location} is {temperature} degrees Celsius with {condition}.")
The main part of the code:
pythonif __name__ == "__main__": wishMe() while True: command = takeCommand().lower() if 'exit' in command: break processCommand(command)
Running the Code
To run the AI assistant program, follow these steps:
Save the code in a Python file with a
.py
extension (e.g.,ai_assistant.py
).Open a terminal or command prompt and navigate to the directory where the Python file is located.
Run the code using the following command:
python ai_assistant.py
Once the program starts running, the AI assistant will greet you and wait for your voice command.
You can give voice commands to the assistant, such as "What's the time?", "Open YouTube", "Search Wikipedia for Python", "Send an email", and more. The assistant will process your command and perform the corresponding task.
To exit the program, say "Exit" or press
Ctrl+C
in the terminal.
Conclusion
Congratulations! You have successfully built an AI assistant with voice control using Python. This assistant can perform various tasks based on your voice commands, such as searching the web, opening applications, playing music, sending emails, providing information from Wikipedia, setting reminders, and retrieving weather information. Feel free to customize and enhance the assistant's functionalities according to your needs. Happy coding!
Comments
Post a Comment