Thursday , November 21 2024
Don't Buy Alexa! Build Your Own. Create a Virtual Assistant with Python | Python Project

Build a Virtual Assistant Using Python

Build a Virtual Assistant Using Python

Build Own Alexa In Python

Don’t Buy Alexa – Build Your Own ALEXA using Python

Alexa Has Only 2 Tasks:

1. Listening

Listening to your command is the most basic functionality of any virtual assistant, like: “Hey Alexa, play music,” “Hey Alexa, what’s the time?”
Alexa has to listen to your command, understand it, and then do some action.

2. Speaking

Once Alexa listens and understands your command, it performs some action based on it. While doing that, it responds to you by speaking otherwise it’ll be jobless.

Install Packages

pip install pywhatkit pip install wikipedia pip install pyttsx3 pip install speechrecognition pip install pyaudio pip install pyjokes

1. PyWhatKit

PyWhatKit is a Simple and Powerful WhatsApp Automation Library with many useful Features

Features

  • Sending Message to a WhatsApp Group or Contact
  • Sending Image to a WhatsApp Group or Contact
  • Converting an Image to ASCII Art
  • Converting a String to Handwriting
  • Playing YouTube Videos
  • Sending Mails with HTML Code

Play “Karan Python Tutorials” on YouTube

In [ ]:
import pywhatkit
pywhatkit.playonyt("Karan Python Tutorials")

2. Wikipedia

Used to extract data from Wikipedia. Getting the summary of any title by using summary method.

In [3]:
import wikipedia
result = wikipedia.summary("Microsoft CEO")
print(result)
Satya Narayana Nadella (Telugu: సత్యనారాయణ నాదెళ్ల, ; born 19 August 1967) is an Indian American business executive. He is the executive chairman and CEO of Microsoft, succeeding Steve Ballmer in 2014 as CEO and John W. Thompson in 2021 as chairman. Before becoming CEO, he was the executive vice president of Microsoft's cloud and enterprise group, responsible for building and running the company's computing platforms.

3. Text To Speech: pyttsx3

pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline, and is compatible with both Python 2 and 3.

In [19]:
import pyttsx3
engine = pyttsx3.init()
engine.say("Welcome to Machine Learning Tutorials")
engine.runAndWait()

4 . Speech Recognition in Python using Google Speech API

This library performs speech recognition. It’ll help the assistant listen to our commands, understand them, and act accordingly. Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc

Note: Kindly use python 3.6.8 because pyaudio doesn’t works on python version greater than 3.6

In [2]:
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
    print("Say Something:")
    audio = r.listen(source)
    text = r.recognize_google(audio)
print("You Said:",text)
Say Something:
You Said: welcome to machine learning tutorials

5. Data and Time

In [15]:
import datetime
time = datetime.datetime.now().strftime('%I:%m %p')
print(time)
11:05 AM
In [20]:
import datetime
date = datetime.datetime.now().strftime('%d %b %Y')
print(date)
19 May 2022

6. Get your City Temperature

In [30]:
api_key = "e226a2eaa720614632c86b91ec9868ee"
base_url = "https://api.openweathermap.org/data/2.5/weather?"

city_name="goa"
print(city_name)

complete_url = base_url + "q=" + city_name + "&appid=" + api_key
response = requests.get(complete_url) 

x = response.json() 
if x["cod"] != "404": 
    y = x["main"] 
    current_temperature = y["temp"] 
    current_pressure = y["pressure"] 
    current_humidiy = y["humidity"] 
    z = x["weather"] 
    weather_description = z[0]["description"] 
    print(" Temperature (in Celcius unit) = " +
                    str(int(current_temperature)-273.15) + 
          "\n atmospheric pressure (in hPa unit) = " +
                    str(current_pressure) +
          "\n humidity (in percentage) = " +
                    str(current_humidiy) +
          "\n description = " +
                    str(weather_description)) 
else: 
    print(" City Not Found ") 
goa
 Temperature (in Celcius unit) = 28.850000000000023
 atmospheric pressure (in hPa unit) = 1007
 humidity (in percentage) = 91
 description = overcast clouds

7. Read Today’s News

In [32]:
import requests
import json
a=requests.get("https://newsapi.org/v2/top-headlines?country=in&apiKey=9fe4be099c6c417a8c00b56ee67f9db5") 
b=json.loads(a.text)
for i in range(10):
    my_data=b['articles'][i]['title']
    print ("Title:",i+1,my_data)
Title: 1 Motorola edge 30, world's thinnest 5G smartphone goes on sale from today 12 pm - ANI News
Title: 2 Gyanvapi mosque row Live Updates: SC defers hearing to Friday, asks Varanasi court to not proceed with trial today - The Indian Express
Title: 3 Garena Free Fire: List of FF Redeem Codes for 19 May? - The Quint
Title: 4 BREAKING| GST Council Recommendations Not Binding On Centre & States; Both Centre & States Can Legislate... - Live Law - Indian Legal News
Title: 5 Coronavirus: From severity to risk factors, 6 things you should know about long COVID - Times of India
Title: 6 One COVID-19 Symptom That Only Appears At Night | TheHealthSite.com - TheHealthSite
Title: 7 BREAKING| Sec 138 NI Act- Set Up Pilot Courts With Retired Judges For Cheque Bounce Cases In 5 States... - Live Law - Indian Legal News
Title: 8 Pornography racket: Shilpa Shetty’s husband Raj Kundra in big trouble, ED registers money laundering case against him - Times of India
Title: 9 Half a million Indians flee floods in northeast brought by rain - CNN
Title: 10 At UN, India's Covid Vaccine Swipe At West As It Defends Wheat Export Ban - NDTV

8. Crack Jokes

Pyjokes is a python library that is used to create one-line jokes for programmers. Informally, it can also be referred as a fun python library which is pretty simple to use.

In [38]:
import pyjokes
j = pyjokes.get_joke()
print(j)
Pirates go 'arg!', computer pirates go 'argv!'

Instruction to use Itronix Solutions Assistant

  1. Read News
  2. Temeprature in Goa
  3. Tell me something about “Microsoft CEO”
  4. Play Karan Arora Python Tutorials
  5. What’s your name
  6. What’s the time
  7. What’s the date
  8. Crack a Joke

Note: read, temperature, tell me something about, play, name, time, and Joke are the keywords

In [43]:
import requests
import wikipedia
import pyaudio
import speech_recognition as sr 
import requests
import json
import pywhatkit
import datetime
import pyjokes

api_key = "e226a2eaa720614632c86b91ec9868ee"
base_url = "https://api.openweathermap.org/data/2.5/weather?"

r=sr.Recognizer()
with sr.Microphone() as source:
    print("Say something!")
    audio = r.listen(source)
    a = r.recognize_google(audio)
    a=a.lower()
    print("Check: "+a)

if 'play' in a: 
    a = a[5:]
    pywhatkit.playonyt(a)
    
elif 'news' in a:
    a=requests.get("https://newsapi.org/v2/top-headlines?country=in&apiKey=9fe4be099c6c417a8c00b56ee67f9db5") 
    b=json.loads(a.text)
    for i in range(10):
        my_data=b['articles'][i]['title']
        print ("Title:",i+1,my_data)

elif 'name' in a:
    print("My name is Itronix Solutions")

elif 'date' in a:
    date = datetime.datetime.now().strftime('%d %b %Y')
    print(date)

elif 'time' in a:
    time = datetime.datetime.now().strftime('%I:%m %p')
    print(time)

elif 'joke':
    j = pyjokes.get_joke()
    print(j)

elif 'tell' in a:
    a=a.split()
    a=a[4:]
    search=' '.join(a)
    print (wikipedia.summary(search))

elif 'temperature' in a:
    city_name=str(a.split()[-1:][0])
    print(city_name)
    complete_url = base_url + "q=" + city_name + "&appid=" + api_key
    response = requests.get(complete_url) 

    x = response.json() 
    if x["cod"] != "404": 
        y = x["main"] 
        current_temperature = y["temp"] 
        current_pressure = y["pressure"] 
        current_humidiy = y["humidity"] 
        z = x["weather"] 
        weather_description = z[0]["description"] 
        print(" Temperature (in Celcius unit) = " +
                        str(int(current_temperature)-273.15) + 
              "\n atmospheric pressure (in hPa unit) = " +
                        str(current_pressure) +
              "\n humidity (in percentage) = " +
                        str(current_humidiy) +
              "\n description = " +
                        str(weather_description)) 
    else: 
        print(" City Not Found ") 
else:
    print("Itronix Assistant Couldn't Understand")
Say something!
Check: play karan arora python tutorials

About Machine Learning

Check Also

Microsoft Shopping Advertising Certification Exam Answers

Microsoft Shopping Advertising Certification Exam Answers – 100% Correct Question:1 When a new shopping campaign …

Leave a Reply

Your email address will not be published. Required fields are marked *