Skip to content

A web-based assistant that can perform various tasks such as sending weather updates, your laptop battery percentage, etc to your phone.

License

Notifications You must be signed in to change notification settings

triposat/Marvin-Assistant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

87 Commits
 
 
 
 
 
 

Repository files navigation


Size Prettier License

Introduction:

This project can do any web-related activity effectively, such as sending emails, searching on YouTube and Google, locating places, telling a joke, sending alerts to your phone, battery-related notifications, and so on.

When we run the code, it will display an appealing interface with several options and a next button. Following that, you will see a search box where you can input anything you want, such as google, wikipedia, and so on.

If you enter spelling that does not exist, it will display an error message, and you will be unable to continue. It will display successful messages, warning messages, and pop-up messages for any information.

What can Assistant do?

  • Wish you:

    • It will wish you according to the time, using the datetime module.

    • Using the below code, it will first calculate an hour.

      hour = int(datetime.datetime.now().hour)
    • Following that, it will use some if-and-else loops to determine the ideal timing for the wishes.

      if hour >= 5 and hour < 12:
          print("Good Morning")
      elif hour >= 12 and hour < 17:
          print('Good Afternoon')
      else:
          print('Good Evening')
  • Search on Wikipedia:

    • It will first ask the user for input, and with the help of the Wikipedia module, it performs all the operations.

      Test_string = input(placeholder="Wikipedia Search", required=True)
    • It will initially seek input from the user. It will now check to see whether if the input exists in Wikipedia. If it's in Wikipedia, we'll try to get a summary by providing some relevant keywords.

        Result = wikipedia.summary(Test_string, sentences=2, auto_suggest=False, redirect=True)
    • If it isn't found on Wikipedia, the suggested keywords will be searched using the approach described below.

      Test_string = wikipedia.suggest(Test_string)
  • Search on YouTube:

    • It will first ask the user for input, and with the help of the Webbrowser module, it performs all the operations.

      Test_string = input(placeholder="YouTube Search", required=True)
    • For searching on YouTube, it will now use the open function specified in the webbrowser module.

      webbrowser.open(f"https://www.youtube.com/results?search_query={Test_string}")
  • Search on Google:

    • It will first ask the user for input, and with the help of the Webbrowser module, it performs all the operations.

      Test_string = input(placeholder="YouTube Search", required=True)
    • For searching on Google, it will now use the open function specified in the webbrowser module.

      webbrowser.open(f"https://www.youtube.com/results?search_query={Test_string}")
  • Send Emails:

    • Register User Email ID: By registering, we allow the yagmail to access our Gmail account in consent to send emails. There is a need for an SMTP client to provide the authentication to the client for sending an email.

      yagmail.register("Sender’s Gmail Username", "Sender’s Gmail Password")
    • Connect to SMTP server: To initiate a connection with the SMTP server using the SMTP client, use the command below.

      yag = yagmail.SMTP(“Sender@gmail.com”)
    • Adding Content and Delivering:

      • In 1st argument in send() function, pass the receiver’s email address.
      • Then in the 2nd one, pass the Subject of the Mail your sender is sending.
      • Now in the 3rd one, pass the Content of Mail i.e text or media.

       yag.send(“Reciever@gmail.com”,”Subject Of Mail”,”Content(Text, Media etc)”)
  • Keep Notes:

    • For creating a new note, you need to give a title for a note and the contents to be noted.

    • The assistant uses SQLAlchemy, a database library which uses SQLite in the backend, to store and keep track of the notes

    • If you need to view a note, you need to enter only the title of the note. After entering the title, the contents of the note will be displayed.

    • Creating the database:

      engine = db.create_engine('sqlite:///notes.db')
      metadata = db.MetaData()
      notes = db.Table('notes', metadata, db.Column('Time', db.String(255), nullable=False, primary_key=True), db.Column(
       'Title', db.Text(), nullable=False, primary_key=True), db.Column('Note', db.Text(), default=''))
      metadata.create_all(engine)
    • Enterting a note: While entering a note, this function gets invoked and the new note is saved in the database.

      def enterNote(title,note):
      current_dateTime = str(datetime.now())
      try:   
      connection = engine.connect()     
      query = db.insert(notes).values(Time=current_dateTime,Title=title,Note=note)
      result = connection.execute(query)
      connection.close()
      except Exception as e:
      print(e)
    • Viewing a note: While we need to view a note, this function gets invoked and the note is displayed.

      def displayNote(title):
      try:
      connection = engine.connect()
      s = notes.select().where(notes.columns.Title==title)
      result = connection.execute(s)
      for row in result:
          print(row[2])
      connection.close()
      
      except Exception as e:
      print(e)
  • Time:

    • To find the current time, we'll use the datetime module.

    • We may simply find time using the approach outlined below.

      datetime.datetime.today().strftime("%I:%M %p")
  • Date:

    • To find the current date, we'll use the datetime module.
    • Now, we will simply use %m to get the month number, and then we will use %b to get the month name.

    current_time = datetime.datetime.now()
    datetime_object = datetime.datetime.strptime(str(current_time.month), "%m")
    month_name = datetime_object.strftime("%b")
  • Play music:

    • You just need to enter the name of the song or music (without spaces).

    • In a matter of seconds, the assistant can play the exact song or music.

    • For this, we have used the libraries Pytube for accessing the songs/music and Playsound for playing the song/music.

    • Generating the URL of the song from the song name:

      def generateURL(songName):	
          search_keyword= str(songName)
          html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword)
          video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
      url = "https://www.youtube.com/watch?v=" + video_ids[0]
    • After the generation of the song URL, we can play the song using it:

      def playSong(url):
        yt = YouTube(str(url))
        audio = yt.streams.filter(only_audio=True).first()
        out_file = audio.download()
        base, ext = os.path.splitext(out_file)
        new_file = base + '.mp3'
        os.rename(out_file, new_file)
        playsound(new_file)
  • Send Notification:

    • Go to Pushbullet and obtain the access token.

    • Get your Access Token and use the PushBullet method to create an instance by providing the Access Token in the PushBullet function.

      PushBullet(access_token)
    • Use the push_note function to send data and text inside the function. push_note will take two arguments i.e. data and text. the first argument will work as a Heading in the notification where 2nd argument is a text.

      pb.push_note(data, text)
  • Maths Calculations:

    • The assistant can perform many sorts of mathematical calculations. It will act as verbal calculator

    • Arithmetic operations: addition,subtraction,multiplication,division and finding the square root

    • Trignometrical operations: sin,cos and tan

      Examples:

      command: Hey jarvis, add 5 and 5
      output : 10
      
      command: Hey jarvis, find the product of 6 and 5
      output : 30
      
      command: Hey jarvis, find the square root of 169
      output : 13
      
      command: Hey jarvis, find the sin of 90 degrees
      output : 1.0
      
  • Words Meaning:

    • Load the JSON data

      json.load(open(r"C:\Users\Dell\Downloads\ebooks.json"))
    • To return the definition of the word(entered by user).

    • This function will give an appropriate message, if the word doesn't exist in the data.

    • If user will enter a word with wrong spelling, then we have to give an appropriate message using get_close_matches() function.

  • Weather Notifications:

    • Firstly, get the API key from OpenWeather.org to begin extracting data.

    • User need to create an account on OpenWeather.org, then only can use the APIs.

      api_key = "Your API Key"
      base_url = "https://api.openweathermap.org/data/2.5/weather?"
    • Take City name as input and check whether city name is valid or not, and required=True means field can't be empty.

    • Extract all the data including Temperature, Pressure, Humidity, Weather, and Description.

  • Battery:

    • The psutil function will be used to perform battery-related tasks.

    • First, using the method outlined below, collect all the necessary information about the battery's present state.

      battery = psutil.sensors_battery() # sbattery(percent=93, secsleft=19845, power_plugged=False)
    • After that we will only extract the battery with the uwse of battery function.

      percent = battery.percent
    • Check whether the plug is plugged in or not.

      pluged = battery.power_plugged
  • ShutDown:

    • Shutting down the PC is a straightforward process that can be done with the help of the OS module.

    • The code below will shut off your computer.

      os.system("shutdown /s /t  1")
  • reSTART:

    • reSTARTing down the PC is also a straightforward process that can be done with the help of the OS module.

    • The code below will shut off your computer.

      os.system("shutdown /r /t  1")
  • Search Locations:

    • With the help of the webbrowser module, we can simply search for any place.

    • If a place exists, the code below will look for it.

      webbrowser.open_new_tab("https://www.google.com/maps/place/"+what)
  • Download video:

    • You can download any Youtube video with its URL.

    • Just enter the URL of the Youtube video and the video gets downloaded.

    • It will be saved in the default Downloads folder in your System

    • A library called Pytube is used to download the video.

      def downloadYTVideo(url):
        try:
        youtube = pytube.YouTube(url)
        video = youtube.streams.filter(progressive=True,file_extension='mp4').desc().first()
        path = str(os.path.join(Path.home(),'Downloads')
        video.download(output_path=path)
        except Exception as e:
        print(e)
  • Jokes:

    • We will use the pyjokes module for this.

    • The get_joke function is defined in the pyjokes module: simply pass the languageand category of the joke.

      pyjokes.get_joke(language="en", category="neutral")
  • Take a Photo:

    • The OpenCV module will be used to capture the images.

    • We will capture an image using the VideoCapture function specified in Opencv and read the pixels of the picture using the read function.

      camera = cv2.VideoCapture(0)
      _, image = camera.read()
    • Finally, we'll write the image and save it with a name.

      cv2.imwrite(name+".png", image)
  • Empty Recycle Bin:

    • We'll use the winshell module to empty the recycling bin.

    • The recycle bin ().empty function in the winshell module is empty the recycle bin.

    • The code below will help us in doing this.

      winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)

Output:

Conclusion:

This is how easy it is to create your own desktop assistant. You may add many more functionalities, such as sending messages in Slack, providing data on Covid-19 cases, and so forth. Have fun experimenting with and creating your own Alexa/Siri/Cortana.


© 2021 Satyam Tripathi

About

A web-based assistant that can perform various tasks such as sending weather updates, your laptop battery percentage, etc to your phone.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages