Tuesday, May 12, 2020

BUILD YOUR OWN VOICE ASSISTANT LIKE JARVIS

import speech_recognition as sr
import os
import sys
import re
import webbrowser
import smtplib
import requests
import subprocess
from pyowm import OWM
import urllib
import urllib.request
import json
from bs4 import BeautifulSoup as soup
import wikipedia

from time import strftime
def AssistantResponse(audio):
    "speaks audio passed as argument"
    print(audio)
    for line in audio.splitlines():
        os.system("say " + audio)
def myCommand():
    "listens for commands"
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Say something...')
        r.pause_threshold = 1
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
    try:
        command = r.recognize_google(audio).lower()
        print('You said: ' + command + '\n')
    #loop back to continue to listen for commands if unrecognizable speech is received
    except sr.UnknownValueError:
        print('....')
        command = myCommand();
    return command
def assistant(command):
    "if statements for executing commands"
    if 'shutdown' in command:
        AssistantResponse('Bye bye Sir. Have a nice day')
        sys.exit()
#open website
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            AssistantResponse('The website you have requested has been opened for you Sir.')
        else:
            pass
#greetings
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            AssistantResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            AssistantResponse('Hello Sir. Good afternoon')
        else:
            AssistantResponse('Hello Sir. Good evening')
   #joke
    elif 'joke' in command:
        res = requests.get(
                'https://icanhazdadjoke.com/',
                headers={"Accept":"application/json"})
        if res.status_code == requests.codes.ok:
            AssistantResponse(str(res.json()['joke']))
        else:
            AssistantResponse('oops!I ran out of jokes')
#top stories from google news
    elif 'news for today' in command:
        try:
            news_url="https://news.google.com/news/rss"
            Client=urllib.request.urlopen(news_url)
            xml_page=Client.read()
            Client.close()
            soup_page=soup(xml_page,"xml")
            news_list=soup_page.findAll("item")
            for news in news_list[:15]:
                AssistantResponse(news.title.text.encode('utf-8'))
        except Exception as e:
                print(e)
#current weather
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            AssistantResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))
#time
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        AssistantResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))
    elif 'email' in command:
        AssistantResponse('Who is the recipient?')
        recipient = myCommand()
        if 'rajat' in recipient:
            AssistantResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            AssistantResponse('Email has been sent successfuly. You can check your inbox.')
        else:
            AssistantResponse('I don\'t know what you mean!')
#launch any application
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname+".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)
            AssistantResponse('I have launched the desired application')
#p
#change wallpaper
    elif 'change wallpaper' in command:
        folder = '/Users/robinsharma/Downloads/wallpapers/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com
        f = urllib.request.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.request.urlretrieve(photo, "/Users/robinsharma/Downloads/wallpapers/a") # Location where we download the image to.
        subprocess.call(["killall Dock"], shell=True)
        AssistantResponse('wallpaper changed successfully')
#askme anything
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.summary(topic)
                print(ny)
        except Exception as e:
                print(e)
                AssistantResponse(e)
AssistantResponse('Hi User, I am Sofia and I am your personal voice assistant, Please give a command or say "help me" and I will tell you what all I can do for you.')
#loop to continue executing multiple commands
while True:

    assistant(myCommand())

 LINK FOR CHECKING COMPATIBLITY -  https://betaprofiles.com LINK FOR DOWNLOADING PROFILES - https://betaprofiles.com