AI Voice Assistant Python

👤 Sharing: AI
```python
import speech_recognition as sr
import pyttsx3
import datetime
import wikipedia
import webbrowser
import os
import smtplib  # For sending emails (if you want to add that functionality)
import random

# Initialize text-to-speech engine
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)  # You can change the voice (0 for male, 1 for female, etc.)
engine.setProperty('rate', 150)  # Adjust speech rate (words per minute)

# Function to speak
def speak(text):
    engine.say(text)
    engine.runAndWait()

# Function to greet the user
def wish_me():
    hour = int(datetime.datetime.now().hour)
    if 0 <= hour < 12:
        speak("Good Morning!")
    elif 12 <= hour < 18:
        speak("Good Afternoon!")
    else:
        speak("Good Evening!")

    speak("I am your AI assistant. How can I help you?")

# Function to take command from the user
def take_command():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1  # Pause for 1 second to detect end of phrase
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        print(e)  # Print the exception message
        print("Say that again please...")
        return "None"
    return query


# Function to send email (requires configuration and enabling "less secure app access" in Gmail or using app passwords)
def send_email(to, content):
    # WARNING:  Sending emails via Python requires proper authentication and security measures.
    #  This example requires enabling "less secure app access" in Gmail, which is NOT recommended.
    #  Use app passwords or a more secure method for real-world applications.
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('your_email@gmail.com', 'your_password')  # Replace with your email and password
    server.sendmail('your_email@gmail.com', to, content)
    server.close()


# Main program execution
if __name__ == "__main__":
    wish_me()
    while True:
        query = take_command().lower()

        # Logic for executing tasks based on the query
        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            try:
                results = wikipedia.summary(query, sentences=2)
                speak("According to Wikipedia")
                print(results)
                speak(results)
            except wikipedia.exceptions.PageError:
                speak("Sorry, I couldn't find anything on Wikipedia about that.")
            except wikipedia.exceptions.DisambiguationError as e:
                speak("There are multiple possible results for that query.  Could you be more specific?")
                print(e)

        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            webbrowser.open("stackoverflow.com")

        elif 'play music' in query:
            music_dir = 'C:\\Users\\YourUsername\\Music' #Replace with your music directory
            songs = os.listdir(music_dir)
            if songs:
                random_song = random.choice(songs)
                os.startfile(os.path.join(music_dir, random_song))
            else:
                speak("No music found in the specified directory.")


        elif 'the time' in query:
            str_time = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"The time is {str_time}")

        elif 'open code' in query:
            code_path = "C:\\Users\\YourUsername\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" #Replace with your Visual Studio Code path
            os.startfile(code_path)

        elif 'send email' in query:
            try:
                speak("To whom should I send the email?")
                to = input("Enter recipient's email address: ")  #Take input from console for recipient
                speak("What should I say in the email?")
                content = take_command()
                send_email(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry, I wasn't able to send the email.")


        elif 'how are you' in query:
            speak("I am doing well, thank you for asking!")

        elif 'what can you do' in query:
            speak("I can perform various tasks, such as searching Wikipedia, opening websites like YouTube and Google, playing music, telling you the time, opening code editors, and even sending emails. How can I assist you today?")


        elif 'exit' in query or 'quit' in query or 'stop' in query:
            speak("Goodbye! Have a great day.")
            break

        else:
            speak("I am sorry, I didn't understand that.  Could you please repeat your request?")
```
👁️ Viewed: 21

Comments