Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
evildevill committed Feb 11, 2023
1 parent 23d7bac commit 5adb9ea
Show file tree
Hide file tree
Showing 27 changed files with 1,335 additions and 2 deletions.
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
References/
env/
.vscode/
__pycache__/
experiments/
*.log
config.py
*.pickle
credentials.json
*note.txt
*.png
*.mp4
*dbs.txt
149 changes: 149 additions & 0 deletions Jarvis/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import speech_recognition as sr
import pyttsx3

from Jarvis.features import date_time
from Jarvis.features import launch_app
from Jarvis.features import website_open
from Jarvis.features import weather
from Jarvis.features import wikipedia
from Jarvis.features import news
from Jarvis.features import send_email
from Jarvis.features import google_search
from Jarvis.features import google_calendar
from Jarvis.features import note
from Jarvis.features import system_stats
from Jarvis.features import loc


engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id)

class JarvisAssistant:
def __init__(self):
pass

def mic_input(self):
"""
Fetch input from mic
return: user's voice input as text if true, false if fail
"""
try:
r = sr.Recognizer()
# r.pause_threshold = 1
# r.adjust_for_ambient_noise(source, duration=1)
with sr.Microphone() as source:
print("Listening....")
r.energy_threshold = 4000
audio = r.listen(source)
try:
print("Recognizing...")
command = r.recognize_google(audio, language='en-in').lower()
print(f'You said: {command}')
except:
print('Please try again')
command = self.mic_input()
return command
except Exception as e:
print(e)
return False


def tts(self, text):
"""
Convert any text to speech
:param text: text(String)
:return: True/False (Play sound if True otherwise write exception to log and return False)
"""
try:
engine.say(text)
engine.runAndWait()
engine.setProperty('rate', 175)
return True
except:
t = "Sorry I couldn't understand and handle this input"
print(t)
return False

def tell_me_date(self):

return date_time.date()

def tell_time(self):

return date_time.time()

def launch_any_app(self, path_of_app):
"""
Launch any windows application
:param path_of_app: path of exe
:return: True is success and open the application, False if fail
"""
return launch_app.launch_app(path_of_app)

def website_opener(self, domain):
"""
This will open website according to domain
:param domain: any domain, example "youtube.com"
:return: True if success, False if fail
"""
return website_open.website_opener(domain)


def weather(self, city):
"""
Return weather
:param city: Any city of this world
:return: weather info as string if True, or False
"""
try:
res = weather.fetch_weather(city)
except Exception as e:
print(e)
res = False
return res

def tell_me(self, topic):
"""
Tells about anything from wikipedia
:param topic: any string is valid options
:return: First 500 character from wikipedia if True, False if fail
"""
return wikipedia.tell_me_about(topic)

def news(self):
"""
Fetch top news of the day from google news
:return: news list of string if True, False if fail
"""
return news.get_news()

def send_mail(self, sender_email, sender_password, receiver_email, msg):

return send_email.mail(sender_email, sender_password, receiver_email, msg)

def google_calendar_events(self, text):
service = google_calendar.authenticate_google()
date = google_calendar.get_date(text)

if date:
return google_calendar.get_events(date, service)
else:
pass

def search_anything_google(self, command):
google_search.google_search(command)

def take_note(self, text):
note.note(text)

def system_info(self):
return system_stats.system_stats()

def location(self, location):
current_loc, target_loc, distance = loc.loc(location)
return current_loc, target_loc, distance

def my_location(self):
city, state, country = loc.my_location()
return city, state, country
Empty file added Jarvis/features/__init__.py
Empty file.
27 changes: 27 additions & 0 deletions Jarvis/features/date_time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import datetime


def date():
"""
Just return date as string
:return: date if success, False if fail
"""
try:
date = datetime.datetime.now().strftime("%b %d %Y")
except Exception as e:
print(e)
date = False
return date


def time():
"""
Just return time as string
:return: time if success, False if fail
"""
try:
time = datetime.datetime.now().strftime("%H:%M:%S")
except Exception as e:
print(e)
time = False
return time
142 changes: 142 additions & 0 deletions Jarvis/features/google_calendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
from __future__ import print_function
import datetime, pytz, pyttsx3, pickle, os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request



MONTHS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]
DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
DAY_EXTENSIONS = ["rd", "th", "st", "nd"]





def speak(text):
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id)
engine.say(text)
engine.runAndWait()
engine.setProperty('rate', 180)




# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']


def authenticate_google():
"""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.pickle 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 get_events(day, service):
# Call the Calendar API
date = datetime.datetime.combine(day, datetime.datetime.min.time())
end_date = datetime.datetime.combine(day, datetime.datetime.max.time())
utc = pytz.UTC
date = date.astimezone(utc)
end_date = end_date.astimezone(utc)



events_result = service.events().list(calendarId='primary', timeMin=date.isoformat(), timeMax=end_date.isoformat(),
singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])

if not events:
speak('No upcoming events found.')
else:
speak(f"You have {len(events)} events on this day.")

for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
start_time = str(start.split("T")[1].split("+")[0]) # get the hour the event starts
if int(start_time.split(":")[0]) < 12: # if the event is in the morning
start_time = start_time + "am"
else:
start_time = str(int(start_time.split(":")[0])-12) # convert 24 hour time to regular
start_time = start_time + "pm"

speak(event["summary"] + " at " + start_time)


def get_date(text):
today = datetime.date.today()

if text.count("today") > 0:
return today

day = -1
day_of_week = -1
month = -1
year = today.year

for word in text.split():
if word in MONTHS:
month = MONTHS.index(word) + 1
elif word in DAYS:
day_of_week = DAYS.index(word)
elif word.isdigit():
day = int(word)
else:
for ext in DAY_EXTENSIONS:
found = word.find(ext)
if found > 0:
try:
day = int(word[:found])
except:
pass

if month < today.month and month != -1:
year = year+1


if month == -1 and day != -1:
if day < today.day:
month = today.month + 1
else:
month = today.month


if month == -1 and day == -1 and day_of_week != -1:
current_day_of_week = today.weekday()
dif = day_of_week - current_day_of_week

if dif < 0:
dif += 7
if text.count("next") >= 1:
dif += 7

return today + datetime.timedelta(dif)

if day != -1:
return datetime.date(month=month, day=day, year=year)
31 changes: 31 additions & 0 deletions Jarvis/features/google_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import re, pyttsx3



def speak(text):
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voices', voices[0].id)
engine.say(text)
engine.runAndWait()
engine.setProperty('rate', 180)


def google_search(command):

reg_ex = re.search('search google for (.*)', command)
search_for = command.split("for", 1)[1]
url = 'https://www.google.com/'
if reg_ex:
subgoogle = reg_ex.group(1)
url = url + 'r/' + subgoogle
speak("Okay sir!")
speak(f"Searching for {subgoogle}")
driver = webdriver.Chrome(
executable_path='driver/chromedriver.exe')
driver.get('https://www.google.com')
search = driver.find_element_by_name('q')
search.send_keys(str(search_for))
search.send_keys(Keys.RETURN)
Loading

0 comments on commit 5adb9ea

Please sign in to comment.