【今日のゴール】
RaspberryPiに現在の日時と、天気をしゃべらせる。

【Python】
RaspberryPiの「pi」はPythonのパイ、ということで、Pythonで実装します。
RaspberryPiには最初からPythonが入っているので、特にセットアップの必要はありません。
【やってみる】
事前準備(open_jtalkのインストール)
事前に下記エントリーを参考に、open_jtalkを使った「jsay」コマンドを使えるようにしてください。
Raspberry Piにしゃべらせてみた(OpenJTalk 1.08、.htsvoiceファイル対応)
使用する天気予報API
livedoorの天気予報API「Weather Hacks」を使用します。
Weather Hacks、JSONのAPI仕様はこちら。
実装する
適当なディレクトリに「talk_weather.py」という名前でファイルを作ります。
$ sudo vi talk_weather.py以下のように編集します。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import shlex
import subprocess
from datetime import datetime
import urllib2
import json
CMD_SAY = 'jsay'
def main():
say_datetime()
say_weather()
return
def say_datetime():
d = datetime.now()
text = '%s月%s日、%s時%s分%s秒' % (d.month, d.day, d.hour, d.minute, d.second)
text = CMD_SAY + ' ' + text
print text
proc = subprocess.Popen(shlex.split(text))
proc.communicate()
return
def say_weather():
city = '130010'; # Tokyo
json_url = 'http://weather.livedoor.com/forecast/webservice/json/v1' #API URL
weather_text = u'%sの天気は%sです。'
temperature_text = u'%sの予想最高気温、%s度、予想最低気温、%s度です。'
try:
r = urllib2.urlopen('%s?city=%s' % (json_url, city) )
obj = json.loads( unicode(r.read()) )
title = obj['title']
forecasts = obj['forecasts']
# TODAY
cast = forecasts[0]
today_w_txt = weather_text % (cast['dateLabel'], cast['telop'])
# TOMMOROW
cast = forecasts[1]
temperature = cast['temperature']
tommorow_w_txt = weather_text % (cast['dateLabel'], cast['telop'])
tommorow_t_txt = temperature_text % (cast['dateLabel'], temperature['max']['celsius'], temperature['min']['celsius'])
# SAY
weather_str = title + ' ' + today_w_txt + ' ' + tommorow_w_txt + ' ' + tommorow_t_txt
weather_str = weather_str.encode('utf-8')
text = '''%s '%s' ''' % (CMD_SAY, weather_str)
print text
proc = subprocess.Popen(shlex.split(text))
proc.communicate()
finally:
r.close()
return
### Execute
if __name__ == "__main__":
main()
サーバーにもアップしてありますので、wget で取得することもできます。
$ sudo wget https://raspi.up.seesaa.net/bin/talk_weather.py
実行する
ファイルを保存したら、下記のように実行します。
$ python talk_weather.py
下記のように、現在時刻と天気予報が文字列として出力されるとともに、音声で読み上げます。
※ 音声データの生成に少し時間がかかります。
$ python talk_weather.py jsay 3月13日、17時47分30秒 jsay '東京都 東京 の天気 今日の天気は晴れです。 明日の天気は曇のち晴です。 明日の予想最高気温、13度、予想最低気温、4度です。'
ちなみに
ちなみに東京ではなく、別の地域に変更したい場合は、29行目のcity= の数字を変更します。
29行目 city = '130010'; # ←ここの数字を変更する
地域IDは全国の地点定義表(RSS) の「cityタグ」のidを参照して下さい。(例・佐賀県 伊万里=410020)
タグ:Raspberry Pi

