Python AI Assistant

# to open os related functions.
import os

# To open any site on browser
import webbrowser

# To use wikipedia commands 
import wikipedia

# Speech recognition module for recognising speech for AI
import speech_recognition as sr

# This module give the time of the day.
import datetime

# pyttsx3 is module which is use to give voice and get back from pc.
import pyttsx3

# windows contain inbuilt voices that is sapi5.
engine = pyttsx3.init('sapi5'

voices = engine.getProperty('voices')

# Voices available in pc appear by index number.
# Only one voice available in my pc. (Can Download new voices.)
engine.setProperty('voices' , voices[0].id)




def speak(audio): 

    '''
    Fist AI need audio to command hence speak function.
    '''

    #Say is use to speak.
    engine.say(audio)

    # This is part of pyttsx3
    engine.runAndWait()


def wishme():

    '''
    AI will greet the user according to the time.
    '''
    
    # Tells the hour of the day.
    hour = int(datetime.datetime.now().hour)

    if hour >= 0 and hour <= 12:
        speak("Hello , Good Morning !")

    elif hour >= 12 and hour <= 18:
        speak("Hello ,Good Afternoon !")

    else:
        speak("Hello ,Good Evening !")

    speak(' I am friday, Your virtual assistant , How may i help ?')


def takeCommand():

    '''
    Take command by speech recognition engine by Google. And print it in string.
    '''

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening . . . ")
# Pausethreshold - Seconds for non speaking audiobefore a phrase considered complete.
        r.pausethreshold = 1
        audio = r.listen(source)

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

    except Exception as e:
        # Print function print error if that happens.
        # To avoid it after testing we can comment it.
        #print(e)
        print("Say that again Please . . .")
        return "None" 

    return query   


if __name__ == '__main__':
    wishme()
    while True:

        #Use lower() for all commands in same format.
        query = takeCommand().lower()

        #Logic for executing tasks based on query.
        if 'wikipedia' in query:
            speak("Searching Wikipedia . . .")
            query = query.replace("Wikipedia" , "")
            results = wikipedia.summary (query , sentences=1)
            print("According to the wikipedia ")
            print(results.encode("utf-8"))
            speak(results)
            

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

        elif 'open google' in query:

            webbrowser.open("www.google.com")

        elif 'open stackoverflow' in query:

            webbrowser.open("www.stackoverflow.com")

        elif 'time' in query:

            strtime = datetime.datetime.now().strftime('%H:%M:%S')
            print(f"The time is {strtime}")
            speak(f"The time is {strtime}")

        elif 'open code'in query:

            code_path = "C:\\Users\\Rohit.DESKTOP-HFVKOUD\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            speak("Opening vs code")
            os.startfile(code_path)

        elif 'quit' in query:
            
            print("Good Bye sir , Have a Nice Day.")
            speak('good bye sir, Have a Nice Day.')
            quit()

 

Comments