Skip to content

Commit

Permalink
add A3RT chat engine
Browse files Browse the repository at this point in the history
  • Loading branch information
ayfujii committed Jun 2, 2021
1 parent f8de3bd commit a5c20df
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 34 deletions.
21 changes: 20 additions & 1 deletion chaplus_ros/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ ROS package for https://www.chaplus.jp/

## Tutorials

1) Obtain API keys for chaplus service, goto https://chaplus.work and acreate accoutn, then reqeust [beta program](https://forms.gle/DQWXdXzUH4MnE5wv6)
1) Obtain API keys for chaplus service, go to https://www.chaplus.jp/api

You can also create account via https://chaplus.work and reqeust [beta program](https://forms.gle/DQWXdXzUH4MnE5wv6)

2) Put API key as json file under `` `rospack find chaplus_ros`/apikey.json ``
```
Expand Down Expand Up @@ -50,4 +52,21 @@ Example with google speech recognition. This demo requires [google_cloud_credent
```
<param name="/speech_recognition/google_cloud_credentials_json"
value="/home/k-okada/Downloads/eternal-byte-236613-4bc6962824d1.json" />
```

## Use other chat API
### A3RT
If you want to use [A3RT](https://a3rt.recruit-tech.co.jp/product/talkAPI)
1) Get A3RT APIKey
Please access https://a3rt.recruit-tech.co.jp/product/talkAPI/registered/ and enter your information.

2) Write A3RT API key in json file under `` `rospack find chaplus_ros`/apikey.json ``
```
{"apikey": "0123456789",
"apikey_a3rt": "abcdefgh"}
```

3) raunch with A3RT option
```
roslaunch chaplus_ros google_example.launch chatbot_engine:=A3RT
```
2 changes: 2 additions & 0 deletions chaplus_ros/apikey.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{"apikey": "0123456789",
"apikey_a3rt": "abcdefgh"}
16 changes: 14 additions & 2 deletions chaplus_ros/sample/google_example.launch
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
<launch>

<!-- you can choose chatbot_engine "Chaplus" or "A3RT" currently-->
<arg name="chatbot_engine" default="Chaplus" />

<!-- start talker
subscribe /robotsound_jp sound_play/SoundRequest -->
<include file="$(find aques_talk)/launch/aques_talk.launch" />
Expand All @@ -10,9 +14,13 @@
<arg name="continuous" value="true" />
<arg name="engine" default="GoogleCloud" />
<arg name="language" value="ja" />
<arg name="n_channel" value="2" />
<arg name="depth" value="16" />
<arg name="sample_rate" value="44100" />
<arg name="device" value="hw:0,0" />
</include>
<param name="/speech_recognition/google_cloud_credentials_json"
value="/home/k-okada/Downloads/eternal-byte-236613-4bc6962824d1.json" />
value="/home/a-fujii/Downloads/eternal-byte-236613-4bc6962824d1.json" />
<!--
<param name="/speech_recognition/diarizationConfig"
type="yaml"
Expand All @@ -33,6 +41,10 @@
<!-- start chaplus
subscribe /request and publish /response -->
<node pkg="chaplus_ros" type="chaplus_ros.py" name="chaplus_ros"
output="screen" />
output="screen" >
<rosparam subst_value="true">
chatbot_engine: $(arg chatbot_engine)
</rosparam>
</node>

</launch>
100 changes: 69 additions & 31 deletions chaplus_ros/scripts/chaplus_ros.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import requests
import json
import sys
import re

if sys.version_info.major == 2:
reload(sys)
Expand All @@ -51,7 +52,8 @@ class ChaplusROS(object):

def __init__(self):

# APIKEYの部分は自分のAPI鍵を代入してください
self.chatbot_engine = rospy.get_param("~chatbot_engine", "Chaplus")
# please write your apikey to chaplus_ros/apikey.json
r = rospkg.RosPack()
apikey_path = rospy.get_param(
"~chaplus_apikey_file", r.get_path('chaplus_ros')+"/apikey.json")
Expand All @@ -65,43 +67,79 @@ def __init__(self):
"echo '{\"apikey\": \00000000\"}' > `rospack find chaplus_ros`/apikey.json")
sys.exit(e)

self.headers = {'content-type': 'text/json'}
self.url = 'https://www.chaplus.jp/v1/chat?apikey={}'.format(
apikey_json['apikey'])
if self.chatbot_engine=="Chaplus":
self.headers = {'content-type': 'text/json'}
self.url = 'https://www.chaplus.jp/v1/chat?apikey={}'.format(
apikey_json['apikey'])

elif self.chatbot_engine=="A3RT":
self.apikey = apikey_json['apikey_a3rt']
self.endpoint = "https://api.a3rt.recruit-tech.co.jp/talk/v1/smalltalk"

else:
rospy.logerr("please use chatbot_engine Chaplus or A3RT")
sys.exit(1)

# define pub/sub
self.pub = rospy.Publisher('response', String, queue_size=1)
rospy.Subscriber("request", String, self.topic_cb)

def topic_cb(self, msg):
# chaplusを利用
try:
rospy.loginfo("received {}".format(msg.data))
self.data = json.dumps({'utterance': msg.data})
response = requests.post(
url=self.url, headers=self.headers, data=self.data)
response_json = response.json()
if not response_json.has_key('bestResponse'):
raise Exception(response_json)
except Exception as e:
rospy.logerr("Failed to reqeust url={}, headers={}, data={}".format(
self.url, self.headers, self.data))
rospy.logerr(e)
return None

# convert to string for print out
if sys.version_info.major == 2:
rospy.logdebug(str(json.dumps(response_json, indent=2,
ensure_ascii=False, encoding='unicode-escape')))
else: # pytyon3
rospy.logdebug(json.dumps(
response_json, indent=2, ensure_ascii=False))

# publish best response
best_response = response_json['bestResponse']['utterance']
rospy.loginfo("returns best response {}".format(best_response))
self.pub.publish(String(best_response))
# use chaplus
if self.chatbot_engine=="Chaplus":
try:
rospy.loginfo("received {}".format(msg.data))
self.data = json.dumps({'utterance': msg.data})
response = requests.post(
url=self.url, headers=self.headers, data=self.data)
response_json = response.json()
if not response_json.has_key('bestResponse'):
best_response = "ごめんなさい、よくわからないです"
else:
best_response = response_json['bestResponse']['utterance']
except Exception as e:
rospy.logerr("Failed to reqeust url={}, headers={}, data={}".format(
self.url, self.headers, self.data))
rospy.logerr(e)
best_response = "ごめんなさい、よくわからないです"
rospy.loginfo("chaplus: returns best response {}".format(best_response))

#use A3RT
elif self.chatbot_engine=="A3RT":
try:
rospy.loginfo("received {}".format(msg.data))
params = {"apikey": self.apikey, "query": msg.data,}
response = requests.post(self.endpoint, params)
response_json = response.json()
if not response_json.has_key('results'):
best_response = "ごめんなさい、よくわからないです"
else:
best_response = response_json["results"][0]["reply"]
except Exception as e:
rospy.logerr("Failed to reqeust url={}, data={}".format(
self.endpoint, msg.data))
rospy.logerr(e)
best_response = "ごめんなさい、よくわからないです"
rospy.loginfo("a3rt: returns best response {}".format(best_response))

else:
rospy.logerr("please use chatbot_engine Chaplus or A3RT")

if response_json is not None:
# convert to string for print out
if sys.version_info.major == 2:
rospy.logdebug(str(json.dumps(response_json, indent=2,
ensure_ascii=False, encoding='unicode-escape')))
else: # pytyon3
rospy.logdebug(json.dumps(
response_json, indent=2, ensure_ascii=False))

#publish response
best_response=best_response.replace("『", "")
best_response=best_response.replace("』", "")
best_response=best_response.replace("!", "。")
best_response=best_response.replace("〜", "ー")
self.pub.publish(String(best_response))

if __name__ == '__main__':
rospy.init_node('chaplus_ros')
Expand Down

0 comments on commit a5c20df

Please sign in to comment.