Get the weather using the API and let the Raspberry Pi speak!

Last time, I spoke the information obtained by web scraping. This time, let Raspberry Pi speak the weather information using openJtalk!

What you can do with this article

--Get weather information using API --Let the Raspberry Pi speak the weather

Premise

・ Python 3 and OpenJtalk can be used on Raspberry Pi (Installing OpenJtalk is explained in this article, so if you haven't done so already!)

Operating environment

・ Raspberry Pi3 model B ・ OS: Raspbian ・ Python ver3.7

Get weather information with API

In this article, https://openweathermap.org/ Use the API provided by. As for how to use this, my predecessor has done it for me, so please refer to the following article and register. Article 1: https://qiita.com/syunyo/items/b408b8d61f9f73b21da7 Article 2: https://qiita.com/nownabe/items/aeac1ce0977be963a740

Run openJtalk from a python script

From here, we will proceed on the assumption that API registration of Open weather map has been completed. Create a directory as you like.

$ mkdir weatherapi
$ cd weatherapi

First, write the following code so that openJtalk can work with a Python script.

$ vi jtalk.py

Press i to enter edit mode and then copy and paste the following.

jtalk.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess
from datetime import datetime

def jtalk(t):
    open_jtalk=['open_jtalk']
    mech=['-x','/var/lib/mecab/dic/open-jtalk/naist-jdic']
    htsvoice=['-m','/usr/share/hts-voice/mei/mei_normal.htsvoice']
    speed=['-r','1.0']
    outwav=['-ow','open_jtalk.wav']
    cmd=open_jtalk+mech+htsvoice+speed+outwav
    c = subprocess.Popen(cmd,stdin=subprocess.PIPE)
    c.stdin.write(t.encode())
    c.stdin.close()
    c.wait()
    aplay = ['aplay','-q','open_jtalk.wav']
    wr = subprocess.Popen(aplay)

def say_datetime():
    d = datetime.now()
    text = '%s month%s day,%s time%s minutes%s seconds' % (d.month, d.day, d.hour, d.minute, d.second)
    jtalk(text)

if __name__ == '__main__':
    say_datetime()

The code above uses a female voice that is not the default for openJtalk. For those who only install openJtalk htsvoice=['-m','/usr/share/hts-voice/mei/mei_normal.htsvoice'] To htsvoice=['-m','/usr/share/hts-voice/nitech-jp-atr503-m001/nitech_jp_atr503_m001.htsvoice] Please change to.

Speak the weather information obtained by hitting the API

Next, write the code to hit the API in the same directory to speak. In the same way

$ vi weather_api_jtalk.py

Press i to enter edit mode and then copy and paste the following.

weather_api_jtalk.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#open weather map &Audio output weather using openJtalk
#Reference: https://qiita.com/syunyo/items/b408b8d61f9f73b21da7

#API import
import requests
import json

### jtalk import
import jtalk
import time

# API key
apikey = "your api key" #Put your api key here

#List of cities for which you want to check the weather
#cities = ["Sendai,JP", "London,UK", "New York,US"]
cities = ["Sendai,JP"] #Only Sendai this time
#API template
api = "http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={key}"

#Temperature conversion(Kelvin → Celsius)
k2c = lambda k: k - 273.15

#Get the temperature of each city
for name in cities:
    #Get the API URL
    url = api.format(city=name, key=apikey)
    #Actually send a request to the API and get the result
    r = requests.get(url)
    
    #The result is in JSON format, so decode it json-> dictionary
    data = json.loads(r.text)    
    
    #Output result
    
    jtalk.jtalk("Kokon'nichiwa, weather today")
    time.sleep(2)
    print("+city=", data["name"])
    print("|weather=", data["weather"][0]["description"])
    if "rain" in data["weather"][0]["description"]:
        jtalk.jtalk("It's rain.")
    else:
        jtalk.jtalk("It's not rain")
    time.sleep(2)
    print("|Lowest Temperature=", k2c(data["main"]["temp_min"]))
    jtalk.jtalk("The lowest temperature is in Celsius"+str(k2c(data["main"]["temp_min"]))+"How is it?")
    time.sleep(4)
    print("|Highest temperature=", k2c(data["main"]["temp_max"]))
    jtalk.jtalk("The maximum temperature is in degrees Celsius"+str(k2c(data["main"]["temp_max"]))+"How is it?")
    #print("|Humidity=", data["main"]["humidity"])
    #print("|Barometric pressure=", data["main"]["pressure"])
    #print("|Wind direction=", data["wind"]['deg'])
    #print("|Wind speed=", data["wind"]["speed"])
    #print("")
    #print("missing some requested data or some error occurs")

Run

$ python weather_api_jtalk.py

How about that? I always commute by bicycle, so I just want to know if it's raining, so if it's raining, I say "it's raining", otherwise I say "it's not raining". Next, it will inform you of the minimum and maximum temperatures.

There is one caveat here.

I'm a little addicted to it here, so I'll emphasize it.

jtalk.jtalk("Kokon'nichiwa, weather today")
time.sleep(2)

As you can see here, the sleep function is used to stop the execution while uttering with jtalk. If you do not do this, the voice information to be output next will come in while you are talking, and the utterance will be interrupted. So, after jtalk.jtalk (), there is a downtime similar to the time it takes to talk. time.sleep (about the time it will take to speak) Please sandwich.

Summary

This time, I hit the API to get the weather and output it as voice using OpenJtalk. If you use the natural dialogue API, you will be able to have conversations. Then!

Recommended Posts

Get the weather using the API and let the Raspberry Pi speak!
Get weather information using Yahoo! Open Local Platform (YOLP) and let Raspberry Pi talk with AquesTalkPi
How to get followers and followers from python using the Mastodon API
Get news from three major mobile companies using Django and the News API
Sound the buzzer using python on Raspberry Pi 3!
Get temperature and humidity with DHT11 and Raspberry Pi
Gently explain the process of making a simple serverless surveillance camera using Raspberry Pi, Gmail API and Line API
Create a color sensor using a Raspberry Pi and a camera
Using the digital illuminance sensor TSL2561 with Raspberry Pi
Try using the temperature sensor (LM75B) on the Raspberry Pi.
Send and receive Gmail via the Gmail API using Python
Get comments and subscribers with the YouTube Data API
Get all songs of Arashi's song information using Spotify API and verify the index
Input and output display images directly using the frame buffer (/ dev / fb0) on Raspberry Pi
Indoor monitoring using Raspberry Pi
Get data using Ministry of Internal Affairs and Communications API
Try using the Twitter API
I tried connecting Raspberry Pi and conect + with Web API
Create a partition and then install the Raspberry Pi OS
Try using the Twitter API
I tried using the DS18B20 temperature sensor with Raspberry Pi
Try using the PeeringDB 2.0 API
Get product name and lowest price using Amazon Product Advertising API
How to get temperature from switchBot thermo-hygrometer using raspberry Pi
Control the motor with a motor driver using python on Raspberry Pi 3!
Make a simple CO2 incubator using Raspberry PI and CO2 sensor (MH-Z14A)
Weighing instrument using raspberry pi and hx711 (GUI display on Tkinter)
Get and set the value of the dropdown menu using Python and Selenium
Get US stock price from Python with Web API with Raspberry Pi
Create your own IoT platform using raspberry pi and ESP32 (Part 1)
Get Salesforce data using REST API
MQTT on Raspberry Pi and Mac
Get the weather with Python requests
Try using ArUco on Raspberry Pi
Get Amazon data using Keep API # 1 Get data
Get upcoming weather from python weather api
Using a webcam with Raspberry Pi
Get the file path using Pathlib
I tried using the checkio API
I made an npm package to get the ID of the IC card with Raspberry Pi and PaSoRi
Let me show you the performance of the new Raspberry pi zero (v1.3)!
Get GrovePi + sensor value with Raspberry Pi and store it in kintone
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
I connected the thermo sensor to the Raspberry Pi and measured the temperature (Python)
Get and estimate the shape of the head using Dlib and OpenCV with python
The temperature is automatically measured using Raspberry Pi 3 and automatically uploaded to the server (Docker python3 + bottle + MySQL) for viewing!
Pet monitoring with Rekognition and Raspberry pi
Try using the Wunderlist API in Python
I tried using Twitter api and Line api
Buy and sell cryptocurrencies using Zaif API
[Raspberry Pi] Add a thermometer and a hygrometer
Detect "brightness" using python on Raspberry Pi 3!
Try using the Kraken API in Python
Get mail using Gmail API in Java
Tweet using the Twitter API in Python
Get the minutes of the Diet via API
Get BITCOIN LTP information with Raspberry PI
Use the Grove sensor on the Raspberry Pi
Get Youtube data in Python using Youtube Data API
Run servomotor on Raspberry Pi 3 using python
Get holidays with the Google Calendar API