Build Your Own Alexa with Python in 2022

Build Your Own Alexa with Python in 2022

Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etc in this course we learn about building 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.

Apply Link Course 1: https://machinelearning.org.in/courses/home/course/build-your-own-virtual-assistant-with-python/9

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("Mehak Alamgir 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 mehak alamgir python tutorial
build your own alexa with python
Build Your Own Alexa with Python in 2022 2

Apply Link Course 2: https://machinelearning.org.in/courses/home/course/learn-advanced-data-cleaning-in-python/10

Learn Advanced Data Cleaning in Python

Requirements

  • python
  • pandas
  • numpy
  • matplotlib

Description

  • Clean and manipulate text data using regular expressions
  • Resolve missing data

Import Library

In [2]:

import numpy as np
import pandas as pd

Read CSV File

In [3]:

data = pd.read_csv('weather_data.csv')
data

Out[3]:

daytemperaturewindspeedevent
01/1/2017326Rain
11/2/2017-999997Sunny
21/3/201728-99999Snow
31/4/2017-9999970
41/5/201732-99999Rain
51/6/2017312Sunny
61/6/20173450

Check Rows and Columns

In [4]:

data.shape

Out[4]:

(7, 4)

Data has 7 Rows and Columns

Check Data Type of Each Column

In [5]:

data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7 entries, 0 to 6
Data columns (total 4 columns):
day            7 non-null object
temperature    7 non-null int64
windspeed      7 non-null int64
event          7 non-null object
dtypes: int64(2), object(2)
memory usage: 352.0+ bytes

Replacing Single Value with NaN

In [6]:

data

Out[6]:

daytemperaturewindspeedevent
01/1/2017326Rain
11/2/2017-999997Sunny
21/3/201728-99999Snow
31/4/2017-9999970
41/5/201732-99999Rain
51/6/2017312Sunny
61/6/20173450

Replace -99999 to NaN

In [7]:

data = data.replace(-99999,value=np.NaN)
data

Out[7]:

daytemperaturewindspeedevent
01/1/201732.06.0Rain
11/2/2017NaN7.0Sunny
21/3/201728.0NaNSnow
31/4/2017NaN7.00
41/5/201732.0NaNRain
51/6/201731.02.0Sunny
61/6/201734.05.00

In [8]:

data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7 entries, 0 to 6
Data columns (total 4 columns):
day            7 non-null object
temperature    5 non-null float64
windspeed      5 non-null float64
event          7 non-null object
dtypes: float64(2), object(2)
memory usage: 352.0+ bytes

Now we have 2 missing values in temperature and windspeed column respectively

Replacing List of Values with Single Value

In [9]:

data

Out[9]:

daytemperaturewindspeedevent
01/1/201732.06.0Rain
11/2/2017NaN7.0Sunny
21/3/201728.0NaNSnow
31/4/2017NaN7.00
41/5/201732.0NaNRain
51/6/201731.02.0Sunny
61/6/201734.05.00

In [10]:

data = data.replace([32.0,7.0],value=99)
data

Out[10]:

daytemperaturewindspeedevent
01/1/201799.06.0Rain
11/2/2017NaN99.0Sunny
21/3/201728.0NaNSnow
31/4/2017NaN99.00
41/5/201799.0NaNRain
51/6/201731.02.0Sunny
61/6/201734.05.00

Replacing Per Column

In [11]:

data

Out[11]:

daytemperaturewindspeedevent
01/1/201799.06.0Rain
11/2/2017NaN99.0Sunny
21/3/201728.0NaNSnow
31/4/2017NaN99.00
41/5/201799.0NaNRain
51/6/201731.02.0Sunny
61/6/201734.05.00

Replace Temperature Column value 99, Windspeed Missing Value (NaN) and Event value 0 with value 100

In [12]:

data.replace({'temperature':99.0,'windspeed':np.nan,'event':'0'},100)

Out[12]:

daytemperaturewindspeedevent
01/1/2017100.06.0Rain
11/2/2017NaN99.0Sunny
21/3/201728.0100.0Snow
31/4/2017NaN99.0100
41/5/2017100.0100.0Rain
51/6/201731.02.0Sunny
61/6/201734.05.0100

Replacing by using Mapping

In [13]:

data

Out[13]:

daytemperaturewindspeedevent
01/1/201799.06.0Rain
11/2/2017NaN99.0Sunny
21/3/201728.0NaNSnow
31/4/2017NaN99.00
41/5/201799.0NaNRain
51/6/201731.02.0Sunny
61/6/201734.05.00

In [14]:

data = data.replace({np.nan:69,'0':'Sunny'})
data

Out[14]:

daytemperaturewindspeedevent
01/1/201799.06.0Rain
11/2/201769.099.0Sunny
21/3/201728.069.0Snow
31/4/201769.099.0Sunny
41/5/201799.069.0Rain
51/6/201731.02.0Sunny
61/6/201734.05.0Sunny

Advance Data Handling Techniques using Regular Expressions

Read Weather Data

In [15]:

data = pd.read_csv('weather2.csv')
data

Out[15]:

daytemperaturewindspeedevent
01/1/201732 F6 mphRain
11/2/2017-99999 F7 mphSunny
21/3/201728 F-99999 mphSnow
31/4/2017-99999 F7 mph0
41/5/201732 F-99999 mphRain
51/6/201731 F2 mphSunny
61/6/201734 F5 mph0

Remove mph from windspeed & F from Temperature

In [16]:

data = data.replace({'temperature':'[A-Za-z]','windspeed':'[A-Za-z]'},'',regex=True)
data

Out[16]:

daytemperaturewindspeedevent
01/1/2017326Rain
11/2/2017-999997Sunny
21/3/201728-99999Snow
31/4/2017-9999970
41/5/201732-99999Rain
51/6/2017312Sunny
61/6/20173450

Replacing Column Values with Another List of Values

In [17]:

d = {'score':['exceptional','average','good','poor','average','exceptional'],
  'student':['Karan','Arpit','Varun','Robin','Akshay','Ankush']}

In [18]:

data = pd.DataFrame(d)
data

Out[18]:

scorestudent
0exceptionalKaran
1averageArpit
2goodVarun
3poorRobin
4averageAkshay
5exceptionalAnkush

Replace the value of Score Column with values 1,2,3,4 Respectively

In [19]:

data = data.replace(['poor','average','good','exceptional'],[1,2,3,4])
data

Out[19]:

scorestudent
04Karan
12Arpit
23Varun
31Robin
42Akshay
54Ankush

Leave a Reply

itronix solutions Previous post Google Digital Marketing & E-commerce Professional Certification Quiz
ios application Next post How to Build an iOS Application? Here’s A Step-by-Step Guide for 2022

Subscribe To My Youtube Channel

Top high paying certificate for 2022

Azekah Daniel For Edition.pk | Muizz Alamgir

Free GuestPost Offer On Our Site

DSTP 2.0 Batch 02 Registration

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected Please Close Your Ad Blocker

We have detected that you are using extensions to block ads. Please disabling these ads blocker to visit site.