Jarvis AI Assistant Python Script


import pyttsx3 #pip install pyttsx3
import datetime
import speech_recognition as sr #pip install speechRecognition
import wikipedia #pip install wikipedia
import webbrowser
# import pyaudio
import os
import random
import smtplib


engine = pyttsx3.init("sapi5")
voices = engine.getProperty("voices")
# print(voices)
# print(voices[0].id)
# print(voices[1].id)
engine.setProperty("voice", voices[1].id)


def speak(audio):
    engine.say(audio)
    engine.runAndWait()
    
def greetMe():
    hour = datetime.datetime.now().hour
    # print(hour)
    # print(type(hour))
    if hour >= 0 and hour < 12:
        print("Good Morning!")
        speak("Good Morning!")
    elif hour >= 12 and hour < 18:
        print("Good Afternoon!")
        speak("Good Afternoon!")
    elif hour >= 18 and hour < 20:
        print("Good Evening!")
        speak("Good Evening!")
    else:
        print("Night approaching!")
        speak("Night approaching!")
        
    print("This is Jarvis, your computer assistant. How can I help you?")  
    speak("This is Jarvis, your computer assistant. How can I help you?")    


def takeCommand():
    """Takes user input thru microphone and gives string output"""
    # print("Plz speak! I am listening...")
    r = sr.Recognizer()
    mic = sr.Microphone()
    with mic as source:
        print("\nPlz speak! I am listening...")
        speak("Plz speak! I am listening...")
        r.adjust_for_ambient_noise(source)
        r.pause_threshold = 1
        userAudio = r.listen(source)
        
    try:
        print("Let me process that....")
        speak("Let me process that....")
        userSaid = r.recognize_google(userAudio, language="en-in")
        # print(type(userSaid))
        print(f"You said: \"{userSaid}\"")
    except:
        print("Plz say again...! I could not hear properly.")
        return "None"

    return userSaid

def sendEmailFunc(to, emailContent):
    # default Gmail SMTP server name is smtp.gmail.com 
    # secure SMTP Gmail ports are 465 (SSL required) and 587 (TLS required)
    server = smtplib.SMTP("smtp.gmail.com", 587) 
    server.ehlo()
    server.starttls()
    server.login("sender-email-here", "password")
    server.sendmail("sender-email-here", to, emailContent)
    server.close()
    

if __name__=="__main__":
    greetMe()
    while True:
    # if 1:
        query = takeCommand().lower()
        if "wikipedia" in query:
            print("Searching wikipedia...")
            speak("Searching wikipedia...")
            print("Plz wait a little.....")
            speak("Plz wait a little.....")
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            print("According to wikipedia... ")
            speak("According to wikipedia... ")
            print(results)
            speak(results)
            
        elif "who are you" in query:
            speak("I am Jarvis, your computer Assistant.")
            
        elif "open youtube" in query:
            webbrowser.open("youtube.com")
            
        elif "open google" in query:
            webbrowser.open("google.com")
            
        elif "open chrome" in query:
            # target from properties
            browser = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
            os.startfile(browser)
            
        elif "play music" in query:
            music_dir = "D:\\MUSIC\\songs\\mix"
            mysongs = os.listdir(music_dir)
            # print(mysongs)
            os.startfile(os.path.join(music_dir, random.choice(mysongs)))
            
        elif 'time now' in query:
            timeNow = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"The time now is {timeNow}")
            
        elif 'today date' in query:
            dateToady = datetime.datetime.now().strftime("%d %B %Y")
            speak(f"The Date is {dateToady}")
        
        elif "open vs code" in query:
            fileLoc = "C:\\Users\\abdur rehman\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            # file target from properties
            os.startfile(fileLoc)
            
        elif "send email" in query:
            try:
                speak("What should I write for you in the email?")
                emailContent = takeCommand()
                to="recipient-email-here"
                sendEmailFunc(to, emailContent)
                speak("The email has been sent successfully.")
            except:
                print("Plz try again. I could not send your email successfully.")
                speak("Plz try again. I could not send your email successfully.")
                
        elif "quit" or "close" in query:
            print("Closing Jarvis...")
            exit()
                
        else:
            print("Sorry! Could not recognize your query.")
            speak("Sorry! Could not recognize your query.")

    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

What is the difference between iostream and iostream.h in cpp?

The Basic Structure of a Full-Stack Web App