Ejemplo n.º 1
0
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'))
Ejemplo n.º 2
0
    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)
Ejemplo n.º 3
0
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")})
Ejemplo n.º 4
0
    def background_task():
        while 1:
            logger.debug("loading agent ...")
            dialog.get_agent()

            interval = int(CONF.get_value('warming-up-agent-interval'))
            time.sleep(interval)
Ejemplo n.º 5
0
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')})
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
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))
Ejemplo n.º 8
0
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,
        ))
Ejemplo n.º 9
0
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,
        ))
Ejemplo n.º 10
0
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,
        ))
Ejemplo n.º 11
0
    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)
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
def get_employee(email):
    url = BASE_API_URL + 'people/' + _login_name(email)
    return requests.get(
        url, headers={'Authorization': CONF.get_value('backend-api-token')})
Ejemplo n.º 14
0
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)
Ejemplo n.º 15
0
def load_classificator():
    return RasaNLUInterpreter(CONF.get_value('classification-model-path'))
Ejemplo n.º 16
0
def _get_client():
    global _CLIENT
    if not _CLIENT:
        _CLIENT = redis.from_url(CONF.get_value('redis-url'))
    return _CLIENT
Ejemplo n.º 17
0
def set_employee(id, info):
    info = json.dumps(info)
    _get_client().set(_get_key(id), info, ex=CONF.get_value('redis-expire-time'))
Ejemplo n.º 18
0
#!/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))
Ejemplo n.º 19
0
def test_load_config_from_file():
    with _setup_environ('HANGOUTS_API_KEY', ''):
        assert "secret-api-key" == CONF.get_value("hangouts-api-key")
Ejemplo n.º 20
0
def train_dialog():
    train_dialogue_model(CONF.get_value('domain-file'),
                         CONF.get_value('stories-file'),
                         CONF.get_value('dialog-model-path'))
Ejemplo n.º 21
0
def test_load_config_from_environment_value():
    with _setup_environ('HANGOUTS_API_KEY', 'foobar'):
        assert "foobar" == CONF.get_value("hangouts-api-key")
Ejemplo n.º 22
0
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')})
Ejemplo n.º 23
0
                    },
                },
                "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)
Ejemplo n.º 24
0
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)