You are on page 1of 10

from __future__ import print_function

import warnings
import pyttsx3
import speech_recognition as sr
from gtts import gTTS
import playsound
import os
import calendar
import random
import wikipedia
import webbrowser
import ctypes
import winshell
import pygame
import keyboard
import subprocess
import pyjokes
import smtplib
import requests
import json
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from twilio.rest import Client
import wolframalpha
import time

warnings.filterwarnings("ignore")

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
engine.setProperty('rate', 168)

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

def rec_audio():
recog = sr.Recognizer()

with sr.Microphone() as source:


print("Listening...")
audio = recog.listen(source)

data = " "

try:
data = recog.recognize_google(audio)
print("You said: " + data)

except sr.UnknownValueError:
pass
except sr.RequestError as ex:
print("Request Error from Google Speech Recognition" + ex)

return data

def call(text):
action_call = "assistant" or "Assistant"

text = text.lower()

if action_call in text:
return True

return False

def today_date():
now = datetime.datetime.now()
date_now = datetime.datetime.today()
week_now = calendar.day_name[date_now.weekday()]
month_now = now.month
day_now = now.day

months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]

ordinals = [
"1st",
"2nd",
"3rd",
"4th",
"5th",
"6th",
"7th",
"8th",
"9th",
"10th",
"11th",
"12th",
"13th",
"14th",
"15th",
"16th",
"17th",
"18th",
"19th",
"20th",
"21st",
"22nd",
"23rd",
"24th",
"25th",
"26th",
"27th",
"28th",
"29th",
"30th",
"31st",
]

return f'Today is {week_now}, {months[month_now - 1]} the {ordinals[day_now -


1]}.'

def say_hello(text):
greet = ["hi", "hey", "hola", "greetings", "sup", "hello", "howdy", "what's
good", "hey there", "ahoy"]

response = ["hi", "hey", "hola", "greetings", "sup", "hello", "howdy", "what's


good", "hey there", "ahoy"]

for word in text.split():


if word.lower() in greet:
return random.choice(response) + "."

return ""

# def wiki_person(text):
# list_wiki = text.split()
# for i in range(0, len(list_wiki)):
# if i + 3 <= len(list_wiki) - 1 and list_wiki[i].lower() == "who" and list_wiki[i
+ 1].lower() == "is":
# return list_wiki[i + 2] + " " + list_wiki[i + 3]

def note(text):
date = datetime.datetime.now()
file_name = str(date).replace(":", "-") + "-note.txt"
with open(file_name, "w") as f:
f.write(text)

subprocess.Popen(["notepad.exe", file_name])

def send_email(to, content):


server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()

server.login("pranavkunadharaju@gmail.com", "PraKarMadAbh4!")
server.sendmail("pranavkunadharaju@gmail.com", to, content)
server.close()
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

def google_calendar():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump((creds, token))

service = build('calendar', 'v3', credentials=creds)

return service

def calendar_events(num, service):


talk("These are the events to do today")
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print(f'Getting the upcoming {num} events...')
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=num, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])

if not events:
print('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
events_today = (event['summary'])
start_time = str(start.split("T")[1].split("-")[0])
if int(start_time.split(':')[0]) < 12:
start_time = start_time + "am"
else:
start_time = str(int(start_time.split(":")[0]) - 12)
start_time = start_time + "pm"
talk(f'{events_today} at {start_time}')

# try:
# service = google_calendar()
# calendar_events(10, service)
# except:
# talk("Could not connect to the local internet connection. Please try again
later.")
# exit()

while True:

try:

text = rec_audio()

if call(text):

talk(say_hello(text))

if "date" in text or "day" in text or "month" in text:


get_today = today_date()
print(" " + get_today)
talk(get_today)

elif "time" in text:


now = datetime.datetime.now()
meridiem = ""
if now.hour >= 12:
meridiem = "p.m"
hour = now.hour - 12
else:
meridiem = "a.m"
hour = now.hour

if now.minute < 10:


minute = "0" + str(now.minute)
else:
minute = str(now.minute)
print(" " + "It is " + str(hour) + ":" + minute + " " + meridiem +
" .")
talk(" " + "It is " + str(hour) + ":" + minute + " " + meridiem + "
.")

elif "wikipedia" in text or "Wikipedia" in text:


if "who is" in text:
person = text.replace("who is", "")
info = wikipedia.summary(person, 3)
print(" " + "According To Wikipedia...")
talk("According To Wikipedia...")
print(" " + info)
talk(info)

elif "your name" in text or "who are you" in text or "define yourself"
in text:
print(" " + "I am Levi, your assistant!")
talk("I am Levi, your assistant")

elif "who am i" in text:


print(" " + "You are a human")
talk("You are a human")

elif "why do you exist" in text or "why are you a thing" in text:
print(" " + "Let's just say... it's a secret")
talk("Let's just say, it's a secret")

elif "how are you" in text:


print(" " + "I am fine, thank you")
print(" " + "How about you?")
talk("I am fine, thank you")
talk("How about you?")

elif "open" in text:


if "chrome" in text:
print(" " + "Opening Google Chrome...")
talk("Opening Google Chrome")
os.startfile(
r"C:\Program Files\Google\Chrome\Application\chrome.exe"
)

elif "edge" in text:


print(" " + "Opening Microsoft Edge...")
talk("Opening Microsoft Edge")
os.startfile(
r"C:\Program Files (x86)\Microsoft\Edge\Application\
msedge.exe"
)

elif "python program" in text or "python programs" in text:


print(" " + "Opening PyCharm...")
talk("Opening PyCharm")
os.startfile(
r"C:\Program Files\JetBrains\PyCharm Community Edition
2021.3.2\bin\pycharm64.exe"
)

elif "vs code" in text or "visual studio code" in text or "visual


studio" in text:
print(" " + "Opening VS Code...")
talk("Opening VS Code")
os.startfile(
r"C:\Users\PRANA_pyjzpnl\AppData\Local\Programs\Microsoft
VS Code\Code.exe"
)

elif "youtube" in text:


print(" " + "Opening Youtube...")
talk("Opening Youtube")
webbrowser.open("https://youtube.com/")

elif "google" in text:


print(" " + "Opening Google...")
talk("Opening Google")
webbrowser.open("https://google.com")

elif "stackoverflow" in text or "stack overflow" in text:


print(" " + "Opening Stack Overflow...")
talk("Opening Stack Overflow")
webbrowser.open("https://stackoverflow.com/")

elif "gmail" in text or "email" in text:


if "1" in text or "one" in text:
print(" " + "Opening Email 1...")
talk("Opening Email 1")
webbrowser.open("https://mail.google.com/mail/u/0/#inbox")

elif "2" in text or "two" in text or "to" in text or "too" in


text:
print(" " + "Opening Email 2...")
talk("Opening Email 2")
webbrowser.open("https://mail.google.com/mail/u/1/#inbox")

if "3" in text or "three" in text:


print(" " + "Opening Email 3...")
talk("Opening Email 3")
webbrowser.open("https://mail.google.com/mail/u/3/#inbox")

else:
talk("Sorry, this application or site is currently
unavailable.")

elif "play" in text:


if "music" in text or "song" in text or "songs" in text:
print(" " + "Sure, Playing Music...")
talk("Sure, Playing Music")
music_dir = r'C:\Users\PRANA_pyjzpnl\Music'
songs = os.listdir(music_dir)
d = random.choice(songs)
random = os.path.join(music_dir, d)
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load(random)
pygame.mixer.music.play(loops=0, start=0.0)
print(" " + "Press 'p' to pause")
print(" " + "Press 'r' to resume")
print(" " + "Press 's' to stop")

while True:
if keyboard.read_key() == "p":
print(" " + "Paused")
pygame.mixer.music.pause()

elif keyboard.read_key() == "r":


print(" " + "Resumed")
pygame.mixer.music.unpause()

elif keyboard.read_key() == "s":


print(" " + "Stopped")
pygame.mixer.music.stop()
break

else:
ind = text.lower().split().index("play")
search = text.split()[ind + 1:]
print(" " + "Showing Results For " + str(search) + " On
Youtube")
talk("Showing Results For " + str(search) + " On Youtube")
webbrowser.open(
"https://www.youtube.com/results?search_query=" +
"+".join(search)
)
elif "search" in text:
ind = text.lower().split().index("search")
search = text.split()[ind + 1:]
print(" " + "Here's What I Found For " + str(search))
talk("Here's What I Found For " + str(search))
webbrowser.open(
"https://www.google.com/search?q=" + "+".join(search)
)

elif "change background" in text or "change wallpaper" in text:


img = r'C:\Users\PRANA_pyjzpnl\Wallpapers'
list_img = os.listdir(img)
imgChoice = random.choice(list_img)
randomImg = os.path.join(img, imgChoice)
ctypes.windll.user32.SystemParametersInfoW(20, 0, randomImg, 0)
print(" " + "Your System Background Has Been Changed Successfully")
talk("Your System Background Has Been Changed Successfully")

elif "empty recycle bin" in text or "empty bin" in text or "mt" in


text:
winshell.recycle_bin().empty(
confirm=True, show_progress=False, sound=True
)
print(" " + "Recycle Bin Emptied Successfully")
talk("Recycle Bin Emptied Successfully")

elif "note" in text or "remember this" in text:


print(" " + "Sure, What Would You Like Me To Note Down?")
talk("Sure, What Would You Like Me To Note Down?")
note_text = rec_audio()
note(note_text)
print(" " + "I Have Made A Note Of That")
talk("I Have Made A Note Of That")

elif "joke" in text or "jokes" in text:


talk(pyjokes.get_joke())

elif "where is" in text:


ind = text.lower().split().index("is")
location = text.split()[ind + 1:]
url = "https://www.google.com/maps/place/" + "".join(location)
print(" " + "This is where " + str(location) + " is.")
talk("This is where " + str(location) + "is.")
webbrowser.open(url)

elif "email to computer" in text or "gmail to computer" in text:


try:
talk("What Should I Say?")
content = rec_audio()
to = "pranavkunadharaju@gmail.com"
send_email(to, content)
print(" " + "Email Has Been Sent!")
talk("Email Has Been Sent!")
except Exception as e:
print(e)
print(" " + "I Am Not Able To Send This Email")
talk("I Am Not Able To Send This Email")
elif "mail" in text or "email" in text or "gmail" in text:
try:
talk("What Should I Say?")
content = rec_audio()
talk("Who Should I send It to?")
to = input("Receiver's Email: ")
send_email(to, content)
print(" " + "Email Has Been Sent!")
talk("Email Has Been Sent!")
except Exception as e:
print(e)
print(" " + "I Am Not Able To Send This Email")
talk("I Am Not Able To Send This Email")

elif "weather" in text:


weather_url = "https://api.openweathermap.org/data/2.5/weather?
appid=d69e2560d9d2ae8ee3301ed1e1f2b106&q="
ind = text.split().index("in")
location = text.split()[ind+1:]
location = "".join(location)
url = weather_url + location
js = requests.get(url).json()
if js["cod"] != "404":
weather = js["main"]
temperature = weather["temp"]
temperature = temperature - 273.15
humidity = weather["humidity"]
desc = js["weather"][0]["description"]
weather_response = "The temperature is " +
str(int(temperature)) + " degrees Celsius" + ", the humidity is " \
+ str(humidity) + ", and the weather
description is " + str(desc)
print(" " + weather_response)
talk(weather_response)
else:
print(" " + "City not found")
talk("City not found")

elif "news" in text:


url = ('https://newsapi.org/v2/top-headlines?'
'country=us&'
'apiKey=f932d388b3284a189b1b33b672c72877')
try:
response = requests.get(url)
except:
talk("Please check your internet connection, and try again
later")

news = json.loads(response.text)

for new in news["articles"]:


print(str(new["title"]), "\n")
talk(str(new["title"]))
engine.runAndWait()

print(str(new["description"]), "\n")
talk(str(new["description"]))
engine.runAndWait()
elif "send message" in text or "send a message" in text:
account_sid = "ACe0d63b8ee765213241267d8411d641c7"
auth_token = "c51c81628617e6d9d7108ca2ef55b5ec"
client = Client(account_sid, auth_token)

talk("What should i send?")


message = client.messages.create(
body=rec_audio(), from_="+17655714515", to=input("Receiver's
phone number: ")
)

print(message.sid)
print(" " + "Message sent successfully!")
talk("Message sent successfully")

elif "calculate" in text:


app_id = "24WWHP-PW6WE5WRA3"
client = wolframalpha.Client(app_id)
ind = text.lower().split().index("calculate")
text = text.split()[ind + 1:]
res = client.query(" ".join(text))
answer = next(res.results).text
print(" " + "The answer is " + answer)
talk("The answer is " + answer)

elif "what is" in text or "who is" in text:


app_id = "24WWHP-PW6WE5WRA3"
client = wolframalpha.Client(app_id)
ind = text.lower().split().index("is")
text = text.split()[ind + 1:]
res = client.query(" ".join(text))
answer = next(res.results).text
print(" " + "The answer is " + answer)
talk("The answer is " + answer)

elif "don't listen" in text or "stop listening" in text or "do not


listen" in text:
talk("For how many seconds?")
a = int(rec_audio())
time.sleep(a)
print(" " + str(a) + " seconds completed")
talk(str(a) + " seconds completed")

elif "fine" in text or "good" in text or "well" in text:


print(" " + "That's good")
talk("That's good")

elif "bad" in text or "upset" in text or " ok" in text or "okay" in text or
"not well" in text or "sad" in text:
print(" " + "Oh no, is there anything I can do to help?")
talk("Oh no, is there anything I can do to help?")

except:
talk("Sorry, I don't know that")

if "exit" in text or "quit" in text:


quit()

You might also like