Example #1
0
    def test_two_clients(self):
        cli = Client('AAAAB3NzaC', botname='generic', port=PORT, test=True)
        cli2 = Client('AAAAB3NzaC', botname='sophia', port=PORT, test=True)
        while not cli.ping():
            time.sleep(1)
        cli.do_conn('localhost:' + PORT)
        cli2.do_conn('localhost:' + PORT)
        response = cli.ask('hello sophia')
        self.assertTrue(response.get('text') == 'Hi there from generic')

        response = cli2.ask('hello sophia')
        self.assertTrue(response.get('text') == 'Hi there from sophia')
Example #2
0
    def test_prologue(self):
        cli = Client('AAAAB3NzaC', username='******', port=PORT, test=True)
        while not cli.ping():
            time.sleep(1)
        cli.do_conn('localhost:' + PORT)
        cli.do_select('generic')
        response = cli.ask('hello sophia')
        self.assertTrue(response.get('text') == 'Hi there from generic')

        cli.do_select('sophia')
        response = cli.ask('hello sophia')
        self.assertTrue(response.get('text') == 'Hi there from sophia')
Example #3
0
    def test_prologue(self):
        from chatbot.client import Client
        cli = Client('test_client', 'AAAAB3NzaC', test=True)
        cli.do_port(PORT)
        while not cli.ping():
            time.sleep(1)
        cli.do_conn('localhost:' + PORT)
        cli.do_select('generic')
        ret, response = cli.ask('hello sophia')
        self.assertTrue(ret == 0)
        self.assertTrue(response.get('text') == 'Hi there from generic')

        cli.do_select('sophia')
        ret, response = cli.ask('hello sophia')
        self.assertTrue(ret == 0)
        self.assertTrue(response.get('text') == 'Hi there from sophia')
Example #4
0
    def __init__(self):
        self.botname = rospy.get_param('botname', 'sophia')
        self.client = Client(HR_CHATBOT_AUTHKEY,
                             self.botname,
                             response_listener=self,
                             stdout=Console())
        self.client.chatbot_url = rospy.get_param('chatbot_url',
                                                  'http://localhost:8001')
        # chatbot now saves a bit of simple state to handle sentiment analysis
        # after formulating a response it saves it in a buffer if S.A. active
        # It has a simple state transition - initialized in wait_client
        # after getting client if S.A. active go to wait_emo
        # in affect_express call back publish response and reset to wait_client
        self._response_buffer = ''
        self._state = 'wait_client'
        # argumment must be  to activate sentiment analysis
        self._sentiment_active = False
        # sentiment dictionary
        self.polarity = Polarity()
        self._polarity_threshold = 0.2
        self.speech = False
        self.enable = True
        self.mute = False
        self.insert_behavior = False
        self._locker = Locker()
        try:
            self.mongodb = get_mongodb()
        except Exception as ex:
            self.mongodb = MongoDB()

        self.node_name = rospy.get_name()
        self.output_dir = os.path.join(
            HR_CHATBOT_REQUEST_DIR,
            dt.datetime.strftime(dt.datetime.utcnow(), '%Y%m%d'))
        if not os.path.isdir(self.output_dir):
            os.makedirs(self.output_dir)
        self.requests_fname = os.path.join(self.output_dir,
                                           '{}.csv'.format(str(uuid.uuid1())))

        self.input_stack = []
        self.timer = None
        self.delay_response = rospy.get_param('delay_response', False)
        self.recover = False
        self.delay_time = rospy.get_param('delay_time', 5)

        self.run_id = rospy.get_param('/run_id', '')
        self.client.set_run_id(self.run_id)
        logger.info("Set run_id %s", self.run_id)

        rospy.Subscriber('chatbot_speech', ChatMessage, self._request_callback)
        rospy.Subscriber('speech_events', String,
                         self._speech_event_callback)  # robot starts to speak
        rospy.Subscriber('chat_events', String,
                         self._chat_event_callback)  # user starts to speak

        rospy.Subscriber('audio_sensors', audiodata,
                         self._audio_sensors_callback)
        self.tts_ctrl_pub = rospy.Publisher('tts_control',
                                            String,
                                            queue_size=1)

        self._response_publisher = rospy.Publisher('chatbot_responses',
                                                   TTS,
                                                   queue_size=1)

        # send communication non-verbal blink message to behavior
        self._blink_publisher = rospy.Publisher('chatbot_blink',
                                                String,
                                                queue_size=1)

        # Perceived emotional content; and emotion to express
        # Perceived: based on what chatbot heard, this is how robot should
        # feel.  Expressed: the emotional content that the chatbot should
        # put into what it says.
        self._affect_publisher = rospy.Publisher('chatbot_affect_perceive',
                                                 String,
                                                 queue_size=1)

        # Echo chat messages as plain strings.
        self._echo_publisher = rospy.Publisher('perceived_text',
                                               String,
                                               queue_size=1)
        rospy.Subscriber('chatbot_speech', ChatMessage, self._echo_callback)
        rospy.set_param('node_status/chatbot', 'running')

        self.btree_publisher = rospy.Publisher('/behavior_switch',
                                               String,
                                               queue_size=1)

        self._gesture_publisher = rospy.Publisher('/blender_api/set_gesture',
                                                  SetGesture,
                                                  queue_size=1)
        self._look_at_publisher = rospy.Publisher(
            '/blender_api/set_face_target', Target, queue_size=1)

        # r2_perception
        self._perception_assign_publisher = rospy.Publisher(
            'perception/api/assign', Assign, queue_size=1)
        self._perception_forget_publisher = rospy.Publisher(
            'perception/api/forget', Forget, queue_size=1)
        self._perception_forget_all_publisher = rospy.Publisher(
            'perception/api/forget_all', ForgetAll, queue_size=1)
        self._perception_state_subscriber = rospy.Subscriber(
            'perception/state', State, self._perception_state_callback)

        self.perception_users = {}
        self.face_cache = []
        self.main_face = None
        self.faces = {}  # faceid(session) -> face
        self.current_user = None
Example #5
0
File: ai.py Project: weeksjr/HEAD
    def __init__(self):
        self.botname = rospy.get_param('botname', 'sophia')
        self.client = Client(HR_CHATBOT_AUTHKEY,
                             response_listener=self,
                             botname=self.botname,
                             stdout=Console())
        self.client.chatbot_url = rospy.get_param('chatbot_url',
                                                  'http://localhost:8001')
        # chatbot now saves a bit of simple state to handle sentiment analysis
        # after formulating a response it saves it in a buffer if S.A. active
        # It has a simple state transition - initialized in wait_client
        # after getting client if S.A. active go to wait_emo
        # in affect_express call back publish response and reset to wait_client
        self._response_buffer = ''
        self._state = 'wait_client'
        # argumment must be  to activate sentiment analysis
        self._sentiment_active = False
        # sentiment dictionary
        self.polarity = Polarity()
        self._polarity_threshold = 0.2
        self.speech = False
        self.enable = True
        self.mute = False
        self.node_name = rospy.get_name()
        self.output_dir = os.path.join(
            HR_CHATBOT_REQUEST_DIR,
            dt.datetime.strftime(dt.datetime.now(), '%Y%m%d'))
        if not os.path.isdir(self.output_dir):
            os.makedirs(self.output_dir)
        self.requests_fname = os.path.join(self.output_dir,
                                           '{}.csv'.format(str(uuid.uuid1())))

        self.input_stack = []
        self.condition = threading.Condition()
        self.respond_worker = threading.Thread(target=self.process_input)
        self.respond_worker.daemon = True
        self.respond_worker.start()
        self.delay_response = rospy.get_param('delay_response', False)
        self.delay_time = rospy.get_param('delay_time', 5)

        rospy.Subscriber('chatbot_speech', ChatMessage, self._request_callback)
        rospy.Subscriber('speech_events', String, self._speech_event_callback)
        rospy.Subscriber('audio_sensors', audiodata,
                         self._audio_sensors_callback)
        self.tts_ctrl_pub = rospy.Publisher('tts_control',
                                            String,
                                            queue_size=1)

        self._response_publisher = rospy.Publisher('chatbot_responses',
                                                   String,
                                                   queue_size=1)

        # send communication non-verbal blink message to behavior
        self._blink_publisher = rospy.Publisher('chatbot_blink',
                                                String,
                                                queue_size=1)

        # Perceived emotional content; and emotion to express
        # Perceived: based on what chatbot heard, this is how robot should
        # feel.  Expressed: the emotional content that the chatbot should
        # put into what it says.
        self._affect_publisher = rospy.Publisher('chatbot_affect_perceive',
                                                 String,
                                                 queue_size=1)

        # Echo chat messages as plain strings.
        self._echo_publisher = rospy.Publisher('perceived_text',
                                               String,
                                               queue_size=1)
        rospy.Subscriber('chatbot_speech', ChatMessage, self._echo_callback)
        rospy.set_param('node_status/chatbot', 'running')

        # the first message gets lost with using topic_tools
        try:
            rospy.wait_for_service('tts_select', 5)
            rospy.sleep(0.1)
            self._response_publisher.publish(String(' '))
        except Exception as ex:
            logger.error(ex)
Example #6
0
    def run(self):
        while True:
            time.sleep(0.2)
            messages = self.sc.rtm_read()
            if not messages:
                continue
            for message in messages:
                if message['type'] != u'message':
                    continue
                if message.get('subtype') == u'bot_message':
                    continue
                usr_obj = self.sc.api_call('users.info',
                                           token=SLACKTEST_TOKEN,
                                           user=message['user'])
                if not usr_obj['ok']:
                    continue
                profile = usr_obj['user']['profile']
                name = profile.get('first_name') or profile.get('email')
                question = message.get('text')
                channel = message.get('channel')

                sid = self.session_manager.get_sid(name, self.botname)
                session = self.session_manager.get_session(sid)
                if session is not None:
                    assert hasattr(session.session_context, 'client')
                    client = session.session_context.client
                else:
                    client = Client(HR_CHATBOT_AUTHKEY,
                                    username=name,
                                    botname=self.botname,
                                    host=self.host,
                                    port=self.port,
                                    response_listener=self)
                    client.set_marker('Slack')
                    if self.weights:
                        client.set_weights(self.weights)
                    self.session_manager.add_session(name, self.botname,
                                                     client.session)
                    session = self.session_manager.get_session(client.session)
                    if session is not None:
                        session.session_context.client = client
                        session.session_context.channel = channel
                        self.info(
                            channel,
                            "Session <{url}/v2.0/session_history?session={sid}&Auth={auth}|{sid}>"
                            .format(url=CHATBOT_SERVER_URL,
                                    sid=session.sid,
                                    auth=HR_CHATBOT_AUTHKEY))
                    else:
                        self.error(channel, "Can't get session")
                        continue

                logger.info("Question {}".format(question))
                if question in [':+1:', ':slightly_smiling_face:', ':)', 'gd']:
                    ret, _ = client._rate('good')
                    if ret:
                        logger.info("Rate good")
                        answer = 'Thanks for rating'
                        color = 'good'
                    else:
                        logger.info("Rate failed")
                        answer = 'Rating failed'
                        color = 'danger'
                    attachments = [{
                        'title': answer,
                        'color': color,
                        'fallback': answer
                    }]
                    self.send_message(channel, attachments)
                    continue
                if question in [':-1:', ':disappointed:', ':(', 'bd']:
                    ret, _ = client._rate('bad')
                    if ret:
                        logger.info("Rate bad")
                        answer = 'Thanks for rating'
                        color = 'good'
                    else:
                        logger.info("Rate failed")
                        answer = 'Rating failed'
                        color = 'danger'
                    attachments = [{
                        'title': answer,
                        'color': color,
                        'fallback': answer
                    }]
                    self.send_message(channel, attachments)
                    continue

                try:
                    client.ask(question)
                except Exception as ex:
                    self.error(channel, ex.message)

                # session could change after ask
                if client.session != session.sid:
                    self.session_manager.remove_session(session.sid)
                    self.session_manager.add_session(name, self.botname,
                                                     client.session)
                    session = self.session_manager.get_session(client.session)
                    session.session_context.client = client
                    session.session_context.channel = channel
                    self.info(
                        channel,
                        "Session <{url}/v2.0/session_history?session={sid}&Auth={auth}|{sid}>"
                        .format(url=CHATBOT_SERVER_URL,
                                sid=session.sid,
                                auth=HR_CHATBOT_AUTHKEY))
                    logger.info("Session is updated")
Example #7
0
from chatbot.client import Client

HR_CHATBOT_AUTHKEY = os.environ.get('HR_CHATBOT_AUTHKEY', 'AAAAB3NzaC')

if __name__ == '__main__':
    logging.basicConfig()
    logging.getLogger().setLevel(logging.WARN)

    parser = argparse.ArgumentParser('Chatbot Client')
    parser.add_argument('botname', help='botname')
    parser.add_argument('-u', '--user', help='user name')
    parser.add_argument('-k',
                        '--key',
                        default=HR_CHATBOT_AUTHKEY,
                        help='client key')
    parser.add_argument('--host', default='localhost', help='server host')
    parser.add_argument('-p',
                        '--port',
                        default=8001,
                        type=int,
                        help='server port')

    options = parser.parse_args()

    client = Client(options.key,
                    options.botname,
                    username=options.user,
                    host=options.host,
                    port=options.port)
    client.cmdloop()
Example #8
0
#!/usr/bin/env python

import os
import sys
import logging
import argparse
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CWD, 'src'))

from chatbot.client import Client

HR_CHATBOT_AUTHKEY = os.environ.get('HR_CHATBOT_AUTHKEY', 'AAAAB3NzaD')

if __name__ == '__main__':
    logging.basicConfig()
    logging.getLogger().setLevel(logging.WARN)

    parser = argparse.ArgumentParser(
        description='Run the chatbot client')
    parser.add_argument(
        'botname', help='Name of the bot')
    parser.add_argument(
        'host', help='Host of the chatbot server')
    args = parser.parse_args()

    client = Client(HR_CHATBOT_AUTHKEY, botname=args.botname, host=args.host)
    client.cmdloop()
Example #9
0
#!/usr/bin/env python

import os
import sys
import logging

CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CWD, '../src'))

from chatbot.client import Client

HR_CHATBOT_AUTHKEY = os.environ.get('HR_CHATBOT_AUTHKEY', 'AAAAB3NzaC')

if __name__ == '__main__':
    logging.basicConfig()
    logging.getLogger().setLevel(logging.WARN)
    if len(sys.argv) > 1:
        client = Client(HR_CHATBOT_AUTHKEY, botname=sys.argv[1])
    else:
        client = Client(HR_CHATBOT_AUTHKEY)
    client.cmdloop()
Example #10
0
#!/usr/bin/env python

import os
import sys
import logging
import argparse
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CWD, '../src'))

from chatbot.client import Client

HR_CHATBOT_AUTHKEY = os.environ.get('HR_CHATBOT_AUTHKEY', 'AAAAB3NzaC')

if __name__ == '__main__':
    logging.basicConfig()
    logging.getLogger().setLevel(logging.WARN)

    parser = argparse.ArgumentParser('Chatbot Client')
    parser.add_argument('botname', help='botname')
    parser.add_argument('-u', '--user', help='user name')
    parser.add_argument('-k',
                        '--key',
                        default=HR_CHATBOT_AUTHKEY,
                        help='client key')

    options = parser.parse_args()

    client = Client(options.key, options.botname, username=options.user)
    client.cmdloop()
Example #11
0
#!/usr/bin/env python

import os
import sys
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CWD, '../src'))

from chatbot.client import Client
from chatbot.client import get_default_username

if __name__ == '__main__':
    client = Client(get_default_username(), 'AAAAB3NzaC')
    client.cmdloop()