knowledge.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 # -*- coding: utf-8 -*-
00003 
00004 
00005 import rospy
00006 from docomo_perception.srv import (Knowledge, KnowledgeResponse)
00007 
00008 import json
00009 import requests
00010 import yaml
00011 import threading
00012 
00013 global APIHOST, APIKEY
00014 setting_path = "/var/lib/robot/docomo_knowledge_settings.yaml"
00015 
00016 
00017 class DocomoKnowledgeQANode(object):
00018     def __init__(self):
00019         self.srv = rospy.Service("knowledge", Knowledge, self.serviceCallback)
00020         self.lock = threading.Lock()
00021 
00022     def serviceCallback(self, req):
00023         params = {
00024             "APIKEY" : APIKEY,
00025             "q": req.question
00026             }
00027         self.lock.acquire()
00028         urlres = requests.get(APIHOST, params=params)
00029         self.lock.release()
00030         rospy.loginfo("sent request to %s -> %d", urlres.url, urlres.status_code)
00031         rospy.loginfo("content: %s", urlres.content)
00032         if urlres.status_code is not requests.codes.ok:
00033             rospy.logerr("bad status code: %d", urlres.status_code)
00034             return KnowledgeResponse()
00035         resdic = json.loads(urlres.content)
00036         res = KnowledgeResponse()
00037         if resdic['message']:
00038             res.answer = resdic['message']['textForDisplay']
00039             res.answerForSpeech = resdic['message']['textForSpeech']
00040         return res
00041 
00042 def load_knowledege_settings():
00043     global APIHOST, APIKEY
00044 
00045     try:
00046         with open(setting_path) as f:
00047             key = yaml.load(f)
00048             APIHOST = key['APIHOST']
00049             APIKEY = key['APIKEY']
00050             rospy.loginfo("loaded settings")
00051     except IOError as e:
00052         rospy.logerr('"%s" not found : %s' % (settings_path, e))
00053         exit(-1)
00054     except Exception as e:
00055         rospy.logerr("failed to load settings: %s", e)
00056         rospy.logerr("check if exists valid setting file in %s", settings_path)
00057         exit(-1)
00058 
00059 if __name__ == '__main__':
00060     rospy.init_node("docomo_knowledge_node")
00061     n = DocomoKnowledgeQANode()
00062     load_knowledege_settings()
00063     rospy.spin()


docomo_perception
Author(s): Yuki Furuta
autogenerated on Thu Jun 6 2019 18:03:42