Aissistant

Ai Assistant


we are going to make our own virtual Ai Assistant using Python Language
We can let that Assistant do lots of things for us like We can voice command, we can deliver greetings and we can tell the assistant to open applications for us.

We have provided lines of code and images for example for you to understand you better.

We will use Pycharm IDE as it's easy and convenient to use.

Pycharm



We will start by importing important libraries 

import pyttsx3  # pip install pyttsx3
import datetime  # It's an prebuilt library
import speech_recognition as sr  # pip install SpeechRecognition
import wikipedia
import smtplib
import webbrowser as wb
import psutil
import pyjokes
import os
import pyautogui
import json
from urllib.request import urlopen
import wolframalpha
import time

engine = pyttsx3.init()
wolframalpha_app_id = '99LHQ4-3LA69J466R'

def speak(audio):
    engine.say(audio)
    engine.runAndWait()


def time_():
    Time = datetime.datetime.now().strftime("%I:%M:%S")  # for 12 hours clock
    speak("The current time is")
    speak(Time)


def date_():
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    date = datetime.datetime.now().day
    speak("The current date is")
    speak(date)
    speak(month)
    speak(year)


def wishme():
    speak("Welcome back Yash! Hope you have a good day")
    time_()
    date_()

    # Greetings

    hour = datetime.datetime.now().hour

    if hour >= 6 and hour < 12:
        speak("Good Morning Yash!")
    elif hour >= 12 and hour < 18:
        speak("Good Afternoon Yash!")
    elif hour >= 18 and hour < 24:
        speak("Good Evening Yash!")
    else:
        speak("Good Night Yash!")

    speak("Jravis at your service. Please tell me Yash how can i help you today?")


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='eng-in')
        print(query)

    except Exception as e:
        print(e)
        print("Say that again please....")
        return "None"
    return query


def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()

    server.login('yashv.088@gmail.com', 'YashMech2002')
    server.send('yashv.088@gmail.com', to, content)
    server.close()

def screenshot():
    img = pyautogui.screenshot
    img.save('C:/Users/91916/Pictures/Screenshots/screenshot.png')

def cpu():
    usage = str(psutil.cpu_percent())
    speak('Yash! CPU is at'+usage)

    battery = psutil.sensors_battery()
    speak('Yash! Battery is at')
    speak(battery.percent)

def joke():
    speak(pyjokes.get_joke())

if __name__ == "__main__":

    wishme()
    while True:
        query = TakeCommand().lower()

        if 'time' in query:
            time_()

        elif 'date' in query:
            date_()

        elif 'wikipedia' in query:
            speak("Searching....")
            query = query.replace('wikipedia', '')
            result = wikipedia.summary(query, sentences=5)
            speak('According to wikipedia..')
            print(result)
            speak(result)

        elif 'send email' in query:
            try:
                speak("What should I say?")
                content = TakeCommand()

                speak("Who is the Reciever?")
                reciever = input("Enter Reciever's email :")
                sendEmail(to,content)
                speak('Email has been saved')

            except Exception as e:
                print(e)
                speak("Unable to send Email.")

        elif 'search in chrome' in query:
            speak('What should i search?')
            chromepath = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

            search = TakeCommand().lower()
            wb.get(chromepath).open_new_tab(search+'.com')

        elif 'search youtube' in query:
            speak('sure Yash!')
            search_Term = TakeCommand().lower()
            speak("Here we go to You Tube!")
            wb.open('https://www.youtube.com/results?search_query='+search_Term)

        elif 'search google' in query:
            speak('What should i search?')
            search_Term = TakeCommand().lower()
            speak('Searching')
            wb.open('https://www.google.com/search?q='+search_Term)

        elif 'cpu' in query:
            cpu()

        elif 'joke' in query:
            joke()

        elif 'go offline' in query:
            speak('as you said going offline Yash!')
            quit()

        elif 'word' in query:
            speak('Opening MS word....')
            ms_word = 'C:/Program Files/Microsoft Office/root/Office16/WINWORD.EXE'
            os.startfile(ms_word)

        elif 'excel' in query:
            speak('Opening MS Excel...')
            ms_exc = 'C:/Program Files/Microsoft Office/root/Office16/EXCEL.EXE'
            os.startfile(ms_exc)

        elif 'powerpoint' in query:
            speak('Opening MS power point')
            ms_pp = 'C:/Program Files/Microsoft Office/root/Office16/POWERPNT.EXE'
            os.startfile(ms_pp)

        elif 'wpotify' in query:
            speak('Opening Spotify..')
            spo = 'C:/Users/91916/AppData/Roaming/Spotify/Spotify'
            os.startfile(spo)

        elif 'whatsApp' in query:
            speak('Opening WhatsApp')
            wha = 'C:/Users/91916/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/WhatsApp/WhatsApp'
            os.startfile(wha)

        elif 'write a note' in query:
            speak("What should i write Yash!..")
            notes = TakeCommand()
            file = open('notes.txt','w')
            speak("Yash! Should i include date and time?")
            ans = TakeCommand()
            if 'yes' in ans or 'sure' in ans:
                strTime = datetime.datetime.now().strftime("%H:%M:%S")
                file.write(strTime)
                file.write(':-')
                file.write(notes)
                speak("Done taking notes Yash!")
            else:
                file.write(notes)

        elif 'show note' in query:
            speak('showing notes..')
            file = open("notes.txt",'r')
            print(file.read())
            speak(file.read())

        elif 'screenshot' in query:
            screenshot()

        elif 'remember that' in query:
            speak('What should i remember?')
            memory = TakeCommand()
            speak("You asked me to remember that"+memory)
            remember = open('memory.txt','w')
            remember.write(memory)
            remember.close()

        elif 'do you remember anything' in query:
            remember = open('memory.txt','r')
            speak('you asked me to remember that'+remember.read())

        elif 'where is' in query:
            query = query.replace("where is","")
            location = query
            speak("User said to locate"+location)
            wb.open_new_tab("https://www.google.com/maps/place/"+location)

        elif 'news' in query:
            try:
                jsonObj = urlopen("https://newsapi.org/v2/everything?domains=techcrunch.com,thenextweb.com&apiKey=fded868197784840843d5339f0241224")
                data = json.load(jsonObj)
                i = 1

                speak("Here are some top Headlines from thr tech industry")
                print("===========TOP HEADLINES============"+"\n")
                for item in data['articles']:
                    print(str(i)+'. '+item['title']+'\n')
                    print(item['description']+'\n')
                    speak(item['title'])
                    i += 1

            except Exception as e:
                print(str(e))



        elif 'calculate' in query:
            client = wolframalpha.Client(wolframalpha_app_id)
            indx = query.lower().split().index('calculate')
            query = query.split()[indx + 1:]
            res = client.query(''.join(query))
            answer = next(res.results).text
            print('The Answer is :'+answer)
            speak('The Answer is '+answer)

        elif 'what is' in query or 'who is' in query:

            client = wolframalpha.Client(wolframalpha_app_id)
            res = client.query()

            try:
                print(next(res.results).text)
                speak(next(res.results).text)
            except StopIteration:
                print("No Results")

        elif 'stop listening' in query:
            speak("For how many seconds you want me to stop listening?")
            ans = int(TakeCommand())
            time.sleep(ans)
            print(ans)

        elif 'restart' in query:
            os.system("shutdown /r /t 1")
        elif 'shutdown' in query:
            os.system("shutdown /s /t 1")

        elif 'tell about me' in query:
            speak("Your name is Yash you are studying mechanical engineering and you are interested in machine learning")

       
        elif 'play music' in query:
            songs_dir = 'Y:/Music'
            music = os.listdir(songs_dir)
            speak("Here's your fav song")
            os.startfile(os.path.join(songs_dir, music[3]))

    

This is the code for our AI Assistant we have covered a lot of things in it we hope you all will make your own.


If you have any doubt then you can ask in the comment section.

And Follow us by email and get notifications for free machine learning projects and codes.

Tags: codingpython

Post a Comment

0 Comments

Skip to main content