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¶
import pywhatkit
pywhatkit.playonyt("horror movies")
'https://www.youtube.com/watch?v=HAufl4PX3mI\\\\u0026pp=ygUNaG9ycm9yIG1vdmllcw%3D%3D'
2. Wikipedia¶
Used to extract data from Wikipedia. Getting the summary of any title by using summary method.
import wikipedia
result = wikipedia.summary("LPU Jalandhar")
print(result)
Lovely Professional University (LPU) is a private university located in Chaheru, Phagwara, Punjab, India. The university was established in 2005 by Lovely International Trust, through the Lovely Professional University Act, 2005 (Punjab Act 25 of 2005) and started operation in 2006.
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.
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
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(text)
Say Something: hello aap kaise hain
5. Data and Time¶
import datetime
time = datetime.datetime.now()
time
datetime.datetime(2024, 9, 26, 16, 12, 1, 899412)
import datetime
time = datetime.datetime.now().strftime('%I:%m %p')
print(time)
04:09 PM
import datetime
date = datetime.datetime.now().strftime('%d %b %Y')
print(date)
26 Sep 2024
6. Get your City Temperature¶
complete_url
'https://api.openweathermap.org/data/2.5/weather?q=shimla&appid=e226a2eaa720614632c86b91ec9868ee'
import requests
api_key = "e226a2eaa720614632c86b91ec9868ee"
base_url = "https://api.openweathermap.org/data/2.5/weather?"
city_name="shimla"
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 ")
shimla Temperature (in Celcius unit) = 18.850000000000023 atmospheric pressure (in hPa unit) = 1006 humidity (in percentage) = 84 description = light rain
7. Read Today’s News¶
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 NASA Alerts Of 410-ft Massive Asteroid Approaching Earth Today: Will It Hit? - Times Now Title: 2 As Iran Strike Looms, Israel Hopes For "Abraham Alliance" With US, UK - NDTV Title: 3 Hezbollah fires at least 50 rockets at Israel; Iron Dome activated | VIDEO - Hindustan Times Title: 4 Weather today: Heavy rains to continue in Himachal, Uttarakhand, Kerala; IMD issues red alert in THESE states | Today News - Mint Title: 5 Confusion: Why there was no 'Super Over' in the tied first ODI between India and Sri Lanka - The Times of India Title: 6 Jammu Police details steps for reporting suspicious persons amid rise in terror attacks: ‘Please note down…’ - Hindustan Times Title: 7 Happy Friendship Day 2024 wishes, quotes, WhatsApp messages, images, GIFs, to share with friends and your loved ones | Today News - Mint Title: 8 Paris Olympics 2024 Day 9 (August 4) India full schedule: Lakshya faces Axelsen in semis; Hockey team to play quarters - Hindustan Times Title: 9 Horoscope Today, August 4, 2024: Read your today's astrological predictions - The Times of India Title: 10 'Creamy layer' not snatching pie, signals unfilled SC/ST posts data - The Times of India
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.
import pyjokes
j = pyjokes.get_joke()
print(j)
Child: Dad, why does the sun rise in the east and set in the west? Dad: Son, it's working, don't touch it.
Instruction to use Itronix Solutions Assistant¶
- Read News
- Temeprature in Goa
- Tell me something about “Microsoft CEO”
- Play Karan Arora Python Tutorials
- What’s your name
- What’s the time
- What’s the date
- Crack a Joke
Note: read, temperature, tell me something about, play, name, time, and Joke are the keywords
import requests
import wikipedia
import pyaudio
import speech_recognition as sr
import requests
import json
import pywhatkit
import datetime
import pyjokes
import pyttsx3
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:
n = "My name is Itronix Solutions"
print(n)
engine = pyttsx3.init()
engine.say(n)
engine.runAndWait()
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' in a:
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!
s = "what is your Age"
L = s.split()
if 'name' in L:
print("My Name is Karan Arora")
elif 'Age' in L:
print("I am 40 Years Old")
I am 40 Years Old