Skip to main content

Building an AI Assistant with Voice Control using Python

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:

  1. Importing the necessary libraries:

    python
    import 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
  2. Initializing the pyttsx3 engine:

    python
    engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id)
  3. Defining a function to convert text to speech:

    python
    def speak(audio): engine.say(audio) engine.runAndWait()
  4. Creating a function to greet the user based on the current time:

    python
    def 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?")
  5. Implementing a function to listen to the user's voice command:

    python
    def 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"
  6. Creating a function to search YouTube based on a query:

    python
    def searchYouTube(query): base_url = 'https://www.youtube.com/results?search_query=' query = urllib.parse.quote_plus(query) webbrowser.open(base_url + query)
  7. Defining a function to open Google Chrome:

    python
    def openChrome(): codePath = r"C:\Program Files\Google\Chrome\Application\chrome.exe" webbrowser.get(codePath).open("google.com")
  8. Creating a function to search Google based on a query:

    python
    def searchGoogle(query): base_url = 'https://www.google.com/search?q=' query = urllib.parse.quote_plus(query) webbrowser.open(base_url + query)
  9. Implementing a function to send emails:

    python
    def 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()
  10. Defining a function to perform calculations:

    python
    def calculate(expression): try: result = eval(expression) speak(f"The result is {result}") except Exception as e: speak("Sorry, I couldn't perform the calculation.")
  11. Creating a function to set reminders:

    python
    def 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}")
  12. Implementing a function to process user commands:

    python
    def 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 ...
  13. Defining a function to get the weather information:

    python
    def 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}.")
  14. The main part of the code:

    python
    if __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:

  1. Save the code in a Python file with a .py extension (e.g., ai_assistant.py).

  2. Open a terminal or command prompt and navigate to the directory where the Python file is located.

  3. Run the code using the following command:

    python ai_assistant.py
  4. Once the program starts running, the AI assistant will greet you and wait for your voice command.

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

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

Popular posts from this blog

Guardians of the Galaxy Vol. 3 Movie Download Hindi Filmyzilla Filmywap 720p 480p 1080p Full HD

  Guardians of the Galaxy Vol. 3 Movie Download Hindi Filmyzilla Filmywap 720p 480p 1080p Full HD: Hi everybody and thus welcome to our new blog! Hence, here, we will examine the exceptionally expected Wonder hero film, “Guardians of the Galaxy Vol. 3”. Meanwhile, coordinated by James Gunn, this film is the third portion in then the “Guardians of the Galaxy Vol. 3” in this manner the setting, then trailed by the parts, the notable cast of characters, thus for example, Peter Tuft/Star-Expert, Gamora, Drax, Rocket, and Groot. Therefore, the film follows the Guardians as they keep on exploring the world and face new dangers. As a result, with the destiny of the universe in question, then the group should cooperate to make all the difference. Hence, the fans of the past movies can anticipate a similar mix of activity, humor, and heart that made the establishment so famous. Here, we will talk about how to download “ Guardians of the Galaxy Vol. 3“ and then, at that point, from notable...

Ant-Man and the Wasp: Quantumania" Review: A Quantum-Powered Marvel Adventure

  Introduction: "Ant-Man and the Wasp: Quantumania" is the highly anticipated sequel to the superhero films "Ant-Man" (2015) and "Ant-Man and the Wasp" (2018). Directed by Peyton Reed and produced by Marvel Studios, the film brings back the lovable heroes, Scott Lang (played by Paul Rudd) and Hope van Dyne (played by Evangeline Lilly), as they embark on a new quantum-powered adventure. In this detailed review, we will delve into the film's strengths, weaknesses, and analyze its potential profitability and quality as a Marvel production. Plot and Storytelling: "Ant-Man and the Wasp: Quantumania" picks up after the events of "Avengers: Endgame" and explores the further possibilities of the Quantum Realm. The story revolves around Scott Lang's continued struggles to balance his superhero duties with his personal life. As new threats arise, the team, including Hope, Hank Pym (played by Michael Douglas), and the scene-stealing Luis (...