Have Alexa run Python to give you a sense of the future

Introduction

It's a strange title, but it's said that running a program written in Python in a conversation with Alexa gives a sense of the future.

Isn't the point of this article interesting to have Alexa do it as a way to run Python? I've included a light code example to tell you, but it doesn't describe how to make Alexa skills in detail.

This is the 22nd day article of Trusted Advent Calendar.

AI assistants

The evolution of AI Assistant has been remarkable these days, and it has become more and more pervasive in our lives for some people.

Various AI assistants such as Apple's Siri, Google's Google Assistant, and Amazon's Alexa are everywhere.

I recommend ** Alexa **, and I'll take care of the lighting, TV, air conditioning, and music playback.

Have Alexa run Python

Alexa has a built-in feature called the Alexa skill, which allows you to check the weather forecast, play music, and more.

By the way, you can develop this Alexa skill yourself using the ** Alexa Skills Kit **.

The flow of Alexa skills is as follows. While there is a conversation between a person and Alexa, let Lambda do the processing.

kouseizu.png

The Alexa Skills Kit Lambda can currently be written in Node.js or Python.

** You can write the Python program you want to run in Lambda and have Alexa run it. ** **

It may be obvious to anyone who knows Alexa skills, but it's pretty amazing.

About the future

It's a bit off the beaten track, but there are many ways to run Python, such as running a Python file or calling it from the console. As the level goes up, there are a number of ways to upload it to the server and run it on a schedule, make it a website, or make it an API.

However, none (in my opinion) has a sense of the future. The future in me is "** J.A.R.V.I.S ** * 1 that appears in Iron Man".

J.A.R.V.I.S is an artificial intelligence that has a sense of the future, such as assisting people's lives through conversations and examining data.

So, if you can run the program while talking to Alexa, you will have a sense of the future.

Let's run Python on Alexa.

Have Alexa run Python

The official video (Japanese) explains the development of the Alexa Skills Kit in detail, so it is recommended to watch it. Alexa Dojo

In this article, I'll show you an example of incorporating "the process of crawling/scraping news sites and listing article titles on the console," which you often see in Python beginners, into your Alexa skill.

Common crawling/scraping process

The following is the source for crawling/scraping the titles of Yahoo! News that you often see. (The site structure of Yahoo! News changes from time to time. The following is the source that works as of December 18, 2020.)

scraping.py


import requests
from bs4 import BeautifulSoup
 
# yahoo!Get news response
response = requests.get('https://news.yahoo.co.jp')

#Create Beautiful Soup
html = BeautifulSoup(response.content, 'html.parser')

#Extract topics
for a in html.select('#uamods-topics div div div ul li a'):
  #Output processing
  print(list(a.strings)[0])

Execution result (some mosaics are applied)

Japan's first 18-day vaccine approval application
Niigata confused by snow Injured people and power outages
Hydrogen country strategy as fuel for thermal power generation
Self-restraint at the end of the year
Kicking another person's dog * Arresting a man
Sharapova engaged with a businessman
Rooney son 11 years old Man U join
Member drinking Overheating discussions over participation

Try incorporating it into your Alexa skill

When you start developing with the Alexa Skills Kit, you'll have a program for the Alexa version of Hello World. This time, we'll incorporate the scraping process into the program and let Alexa speak the scraping results.

Below, I will explain the key points when writing the Alexa Skills Kit in Pyhon.

About external libraries that need to be installed

External libraries (such as pip3 install) that need to be installed when developing with the Alexa Skills Kit must be written in advance.

A file called requirements.txt is prepared, so let's describe the external library to be used.

This time, you need to install requests and BeautifulSoup, so I will write them down.

requirements.txt


requests==2.25.1
beautifulsoup4==4.9.3

Incorporate Alexa crawling/scraping process

As mentioned earlier, when you start development, a file called lambda_function.py contains sample processing for Hello World.

Among them is the following class that controls the behavior of the first Alexa when talking to Alexa, so we will incorporate scraping processing into it so that Alexa can talk about the scraping result.

lambda_function.py


class LaunchRequestHandler(AbstractRequestHandler):
    """Handler for Skill Launch."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool

        return ask_utils.is_request_type("LaunchRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        speak_output = "Welcome, you can say Hello or Help. Which would you like to try?"

        return (
            handler_input.response_builder
                .speak(speak_output)
                .ask(speak_output)
                .response
        )

** First of all, Alexa speaks the string set in the argument of response_builder.speak (), which is returned by the handle function. ** ** It's very easy, isn't it? The point is, if you can set what you want the string to say, you can achieve the goal of letting Alexa speak.

Let's change the argument of speak () to set the result of scraping Yahoo! News.

lambda_function.py


class LaunchRequestHandler(AbstractRequestHandler):
    """Handler for Skill Launch."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool

        return ask_utils.is_request_type("LaunchRequest")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response        
        speak_output = self.getYahooNewsTopics()
        
        return (
            handler_input.response_builder
                .speak(speak_output)
                .response
        )
    
    def getYahooNewsTopics(self):
        # yahoo!Get news response
        response = requests.get('https://news.yahoo.co.jp')
        
        #Create Beautiful Soup
        html = BeautifulSoup(response.content, 'html.parser')
        
        topics = '<p>Yahoo News topics.</p>'
        
        #Extract topics
        for a in html.select('#uamods-topics div div div ul li a'):
            #Set title
            topics += '<p>{}</p>'.format(list(a.strings)[0])
        
        return topics

Added a function called getYahooNewsTopics () to return the scraped result as a string.

It's almost the same as the original crawling/scraping process, but with some ingenuity for Alexa.

By setting <p> </p> for each title, Alexa will take a breather.

Also, response_builder.ask () has been removed. You can use it to write a process that interacts with Alexa, but this time it's not necessary because you just have the news results read.

Now you've created a process that lets Alexa speak.

Let Alexa speak

The interesting thing about the Alexa Tools Kit is that once you write the code, it's ready to use. It is possible to call the process created earlier from a terminal already equipped with Alexa and let Alexa speak.

The following is a little strange on the test screen of the Alexa Tools Kit, but Alexa speaks comfortably what is written on the test screen.

スクリーンショット 2020-12-19 16.54.00.png

I was able to get Alexa to speak the process I wrote in Python.

If you're studying but don't like the results on the console, I recommend Alexa to talk to you because it's futuristic and interesting.

After all, programming is a future-like thing, so it's not interesting unless you have a sense of the future.

Also, in this program, I talked about Yahoo! News topics, but it's much easier and better to have Alexa talk to me than to actually open my smartphone and fly to the site to check it.

If this is the case, it would be nice to be practical even for scraping processing for beginners.

Summary

Having Alexa run a Python program gave me a sense of the future.

If you make it a process that interacts with Alexa, you can do various things depending on your ingenuity, such as having you read the text you are interested in after being taught the title.

Why not start learning Python from a new direction with Alexa?

It seems that the future will come when J.A.R.V.I.S will be realized in a few years.

reference

Recommended Posts

Have Alexa run Python to give you a sense of the future
Python Note: The mystery of assigning a variable to a variable
Make a note of what you want to do in the future with Raspberry Pi
A Python script that allows you to check the status of the server from your browser
A story that struggled to handle the Python package of PocketSphinx
How to check the memory size of a variable in Python
Create a shell script to run the python file multiple times
If you give a list with the default argument of the function ...
How to check the memory size of a dictionary in Python
[Python3] Define a decorator to measure the execution time of a function
[python] A note that started to understand the behavior of matplotlib.pyplot
[Python] A simple function to find the center coordinates of a circle
[Python] A program that rotates the contents of the list to the left
Give a title to the ipywidgets tab
Run the Python interpreter in a script
[python] [meta] Is the type of python a type?
The story of blackjack A processing (python)
How to run a Maya Python script
If you want a singleton in python, think of the module as a singleton
[Python] A program that calculates the number of socks to be paired
Python Note: When you want to know the attributes of an object
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Python] If you want to draw a scatter plot of multiple clusters
Try using n to downgrade the version of Node.js you have installed
Allow Slack to notify you of the end of a time-consuming program process
Python code to determine the monthly signal of a relative strength investment
I made a program to check the size of a file in Python
Python: I want to measure the processing time of a function neatly
I made a function to see the movement of a two-dimensional array (Python)
How to run the practice code of the book "Creating a profitable AI with Python" on Google Colaboratory
[You have to know it! ] I tried to set up a Python environment profitably by making full use of the privileges of university students.
Various ways to read the last line of a csv file in Python
How to pass the execution result of a shell command in a list in Python
How to calculate the volatility of a brand
Defense Techniques When You Have to Fight the Performance of Unfamiliar Applications (Part 2)
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
Get the caller of a function in Python
Make a copy of the list in Python
Until you run the changefinder sample in python
[python] How to sort by the Nth Mth element of a multidimensional array
Test the number of times you have thrown a query (sql) in django
A note about the python version of python virtualenv
Why does Python have to write a colon?
Visualize the timeline of the number of issues on GitHub assigned to you in Python
Build a python environment to learn the theory and implementation of deep learning
What you want to memorize with the basic "string manipulation" grammar of python
[Python] A rough understanding of the logging module
Python script to get a list of input examples for the AtCoder contest
Output in the form of a python array
A python amateur tries to summarize the list ②
I made a script to record the active window using win32gui of Python
A discussion of the strengths and weaknesses of Python
[Python] Throw a message to the slack channel
I didn't have to write a decorator in the class Thank you contextmanager
How to get a list of files in the same directory with python
[Introduction to Python] How to get the index of data with a for statement
What to do if the Microsoft Store opens even if you run python on Windows
How to identify the element with the smallest number of characters in a Python list?
[Introduction to Python] Basic usage of the library scipy that you absolutely must know
About the usefulness of the Python Counter class-You don't have to count it yourself anymore-
[Python] You can save an object to a file by using the pickle module.