def train_classificator(): trainer = Trainer(RasaNLUConfig(CONF.get_value('nlu-config-file-path'))) training_data = load_data(CONF.get_value('nlu-training-data-path')) trainer.train(training_data) trainer.persist( CONF.get_value('models-directory'), fixed_model_name=CONF.get_value('classification-model-name'))
def _auth(*args, **kw): event = request.get_json() logger.debug("received %s", event) logger.debug("configuratioon token: %s", CONF.get_value("hangouts-api-key")) if event.get('token') != CONF.get_value("hangouts-api-key"): return get_error_response('Wrong token', 401) return func(*args, **kw)
def get_leave_entitlement(employee, year): request_body = { 'employeeId': employee.get('employeeId'), 'year': year, 'homeOffice': employee.get('homeOffice').get('name') } jwt_token = jwt.encode(request_body, CONF.get_value('leave-api-key'), algorithm='HS256') return requests.get( CONF.get_value('leave-api-url') + 'leave-entitlement', headers={'Authorization': 'Bearer %s' % jwt_token.decode("utf-8")})
def background_task(): while 1: logger.debug("loading agent ...") dialog.get_agent() interval = int(CONF.get_value('warming-up-agent-interval')) time.sleep(interval)
def get_leaves(employee_id, start_date=None): url = BASE_API_URL + 'leave?employee_ids=' + employee_id if start_date: url += '&start_date=' + start_date return requests.get( url, headers={'Authorization': CONF.get_value('backend-api-token')})
def post_leave(leave): url = BASE_API_URL + 'leave' response = requests.post( url, json=leave, headers={'Authorization': CONF.get_value('backend-api-token')}) return response.status_code == 201
def run(): output_file = "/tmp/graph.png" stories_file = CONF.get_value('stories-file') agent = dialog.get_agent() agent.visualize(stories_file, output_file=output_file, max_history=2) print("File generated: {}".format(output_file))
def send_bot_message(msg, sender_id=None): logger.debug('Send bot message to chatbase msg=%s sender_id=%s', msg, sender_id) _add_message( Message( api_key=CONF.get_value('chatbase-api-key'), message=msg, type='agent', platform='chatbot', user_id=sender_id, ))
def send_not_handled_message(msg, sender_id=None): logger.debug('Send not handled message to chatbase msg=%s sender_id=%s', msg, sender_id) _add_message( Message( api_key=CONF.get_value('chatbase-api-key'), message=msg, user_id=sender_id, type='user', platform='chatbot', not_handled=True, ))
def send_user_message(msg, intent, sender_id): logger.debug('Send user message to chatbase msg=%s intent=%s sender_id=%s', msg, intent, sender_id) _add_message( Message( api_key=CONF.get_value('chatbase-api-key'), message=msg, type='user', platform='chatbot', intent=intent, user_id=sender_id, ))
def background_task(): interval = int(CONF.get_value('analytics-send-period')) while 1: logger.debug( "send a batch of %d messages to chatbase and then sleep for %ds", len(_MESSAGES.messages), interval) with _MESSAGES_LOCK: if _MESSAGES.messages: response = _MESSAGES.send() logger.debug("chatbat returned %s -> %s", response.status_code, response.content) _MESSAGES.messages = [] time.sleep(interval)
def train_dialog_online(classificator, input_channel): agent = Agent(CONF.get_value('domain-file'), policies=[MemoizationPolicy(), KerasPolicy()], interpreter=classificator) agent.train_online(CONF.get_value('stories-file'), input_channel=input_channel, max_history=CONF.get_value('dialog-model-max-history'), batch_size=CONF.get_value('dialog-model-batch-size'), epochs=CONF.get_value('dialog-model-epochs'), max_training_samples=CONF.get_value( 'dialog-model-max-training-samples')) return agent
def get_employee(email): url = BASE_API_URL + 'people/' + _login_name(email) return requests.get( url, headers={'Authorization': CONF.get_value('backend-api-token')})
def load_agent(classificator): logger.info('loading context model from: %s', CONF.get_value('dialog-model-path')) return Agent.load(CONF.get_value('dialog-model-path'), interpreter=classificator)
def load_classificator(): return RasaNLUInterpreter(CONF.get_value('classification-model-path'))
def _get_client(): global _CLIENT if not _CLIENT: _CLIENT = redis.from_url(CONF.get_value('redis-url')) return _CLIENT
def set_employee(id, info): info = json.dumps(info) _get_client().set(_get_key(id), info, ex=CONF.get_value('redis-expire-time'))
#!/usr/bin/env python import pprint from chatbot.config import CONF from rasa_core.interpreter import RasaNLUInterpreter interpreter = RasaNLUInterpreter(CONF.get_value('classification-model-path')) while 1: text = input('Enter text: ') pprint.pprint(interpreter.parse(text))
def test_load_config_from_file(): with _setup_environ('HANGOUTS_API_KEY', ''): assert "secret-api-key" == CONF.get_value("hangouts-api-key")
def train_dialog(): train_dialogue_model(CONF.get_value('domain-file'), CONF.get_value('stories-file'), CONF.get_value('dialog-model-path'))
def test_load_config_from_environment_value(): with _setup_environ('HANGOUTS_API_KEY', 'foobar'): assert "foobar" == CONF.get_value("hangouts-api-key")
import logging import requests from chatbot.backend import decorators from chatbot.config import CONF logger = logging.getLogger(__name__) BASE_API_URL = CONF.get_value('backend-api-base-url') def _login_name(email): return email.split('@')[0] @decorators.valid_response def get_employee(email): url = BASE_API_URL + 'people/' + _login_name(email) return requests.get( url, headers={'Authorization': CONF.get_value('backend-api-token')}) @decorators.valid_response def get_leaves(employee_id, start_date=None): url = BASE_API_URL + 'leave?employee_ids=' + employee_id if start_date: url += '&start_date=' + start_date return requests.get( url, headers={'Authorization': CONF.get_value('backend-api-token')})
}, }, "thread": { "type": "object", "required": ["name"], "properties": { "name": {"type": "string"}, } } } } } } @app.route("/" + CONF.get_value("messenger-endpoint"), methods=['POST']) @middlewares.is_json @middlewares.authenticate @middlewares.validate(SCHEMA) @middlewares.fill_session def on_event(): """Handles an event from Hangouts Chat.""" event = request.get_json() if event.get('type') == 'ADDED_TO_SPACE': logger.debug('Retrieve and send welcome text') message = dialog.get_welcome_message( dialog.get_agent(), ) response = get_success_response(message)
import logging import time import threading from chatbase.base_message import Message, MessageSet from chatbot.config import CONF logger = logging.getLogger(__name__) _MESSAGES = MessageSet(api_key=CONF.get_value('chatbase-api-key'), ) _MESSAGES_LOCK = threading.RLock() def _add_message(msg): with _MESSAGES_LOCK: _MESSAGES.append_message(msg) def start_batch_sender(): def background_task(): interval = int(CONF.get_value('analytics-send-period')) while 1: logger.debug( "send a batch of %d messages to chatbase and then sleep for %ds", len(_MESSAGES.messages), interval) with _MESSAGES_LOCK: if _MESSAGES.messages: response = _MESSAGES.send() logger.debug("chatbat returned %s -> %s", response.status_code, response.content)