目次
▼ 下記ページを理解していること。
[Python] [1] タスク指向型対話システム (状態遷移ベースの環境準備:MeCab, SCXML)
▼ Python3.6がインストールされていること。
このページでは、venvの仮想環境(Python3.6)上にNumPyをインストールした環境で、Python対話モード(Pythonインタプリタ)にて実装サンプルを記載している。
※ Python対話モードについては下記を参考。
Python対話モード:[Python] 対話モード (インタプリタ) の使用方法
▼ 対話システムのプログラムについて
この記事で登場するサンプルプログラムは、下記参考文献『Pythonでつくる対話システム』のGitHubサポートページで提供されているプログラムをダウンロードして使用させていただく。
【参考文献】
東中 竜一郎、稲葉 通将、水上 雅博 (2020) 『Pythonでつくる対話システム』株式会社オーム社
【GitHubサポートページ】
https://github.com/dsbook/dsbook
$ pip3 install requests
$ python
>>> import requests
>>>
>>> # 福岡県(県庁)の緯度、経度
>>> lat = 33.60
>>> lon = 130.41
>>>
>>> # 自アカウントのAPIKey
>>> appid = '**********'
>>>
>>> # 現在の天気情報
>>> current_weather_url = 'http://api.openweathermap.org/data/2.5/weather'
>>>
>>> # API呼出し
>>> response = requests.get("{}?lat={}&lon={}&lang=ja&units=metric&APPID={}".format(current_weather_url,lat,lon,appid))
>>>
>>> # 結果出力
>>> response.json()
{'coord': {'lon': 130.41, 'lat': 33.6}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': '曇りがち', 'icon': '04n'}], 'base': 'stations', 'main': {'temp': 25.87, 'feels_like': 29.51, 'temp_min': 24.44, 'temp_max': 27.78, 'pressure': 1010, 'humidity': 83}, 'visibility': 10000, 'wind': {'speed': 2.1, 'deg': 290}, 'clouds': {'all': 75}, 'dt': 1595079741, 'sys': {'type': 1, 'id': 7998, 'country': 'JP', 'sunrise': 1595017250, 'sunset': 1595068076}, 'timezone': 32400, 'id': 1863967, 'name': '福岡市', 'cod': 200}
>>>
$ python
>>> import requests
>>>
>>> # 福岡県(県庁)の緯度、経度
>>> lat = 33.60
>>> lon = 130.41
>>>
>>> # 自アカウントのAPIKey
>>> appid = '**********'
>>>
>>> # 明日以降の天気情報
>>> forecast_url = 'http://api.openweathermap.org/data/2.5/forecast'
>>>
>>> # API呼出し
response = requests.get("{}?lat={}&lon={}&lang=ja&units=metric&APPID={}".format(forecast_url,lat,lon,appid))
>>>
>>> # 結果出力
>>> response.json()["list"][0]
{'dt': 1595084400, 'main': {'temp': 24.97, 'feels_like': 28.68, 'temp_min': 24.37, 'temp_max': 24.97, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1009, 'humidity': 79, 'temp_kf': 0.6}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '厚い雲', 'icon': '04n'}], 'clouds': {'all': 100}, 'wind': {'speed': 0.72, 'deg': 54}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2020-07-18 15:00:00'}
>>>
>>> response.json()["list"][1]
{'dt': 1595095200, 'main': {'temp': 24.65, 'feels_like': 27.75, 'temp_min': 24.41, 'temp_max': 24.65, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1009, 'humidity': 75, 'temp_kf': 0.24}, 'weather': [{'id': 804, 'main': 'Clouds', 'description': '厚い雲', 'icon': '04n'}], 'clouds': {'all': 100}, 'wind': {'speed': 0.79, 'deg': 157}, 'visibility': 10000, 'pop': 0, 'sys': {'pod': 'n'}, 'dt_txt': '2020-07-18 18:00:00'}
>>>
>>> response.json()["list"][2]
{'dt': 1595106000, 'main': {'temp': 24.47, 'feels_like': 26.82, 'temp_min': 24.4, 'temp_max': 24.47, 'pressure': 1010, 'sea_level': 1010, 'grnd_level': 1009, 'humidity': 75, 'temp_kf': 0.07}, 'weather': [{'id': 500, 'main': 'Rain', 'description': '小雨', 'icon': '10d'}], 'clouds': {'all': 100}, 'wind': {'speed': 1.75, 'deg': 161}, 'visibility': 10000, 'pop': 0.54, 'rain': {'3h': 0.25}, 'sys': {'pod': 'd'}, 'dt_txt': '2020-07-18 21:00:00'}
>>>
$ pip3 install python-telegram-bot
>>>
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# アクセストークン(先ほど発行されたアクセストークンに書換えること)
TOKEN = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
class TelegramBot:
def __init__(self, system):
self.system = system
def start(self, bot, update):
# 辞書型 inputにユーザIDを設定
input = {'utt': None, 'sessionId': str(update.message.from_user.id)}
# システムからの最初の発話をinitial_messageから取得し,送信
update.message.reply_text(self.system.initial_message(input)["utt"])
def message(self, bot, update):
# 辞書型 inputにユーザからの発話とユーザIDを設定
input = {'utt': update.message.text, 'sessionId': str(update.message.from_user.id)}
# replyメソッドによりinputから発話を生成
system_output = self.system.reply(input)
# 発話を送信
update.message.reply_text(system_output["utt"])
def run(self):
updater = Updater(TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", self.start))
dp.add_handler(MessageHandler(Filters.text, self.message))
updater.start_polling()
updater.idle()
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram_bot import TelegramBot
# ユーザの入力をそのまま返す対話システム.
class EchoSystem:
def __init__(self):
pass
def initial_message(self, input):
return {'utt': 'こんにちは。対話を始めましょう。', 'end':False}
def reply(self, input):
return {"utt": input['utt'], "end": False}
if __name__ == '__main__':
system = EchoSystem()
bot = TelegramBot(system)
bot.run()
$ python ~/gitlocalrep/dsbook/echo_system.py
/root/gitlocalrep/dsbook/telegram_bot.py:29: TelegramDeprecationWarning: Old Handler API is deprecated - see https://git.io/fxJuV for details
updater = Updater(TOKEN)