예제 #1
0
    def load(cls, filename, action_factory=None):
        if not os.path.isfile(filename):
            raise Exception(
                    "Failed to load domain specification from '{}'. "
                    "File not found!".format(os.path.abspath(filename)))

        cls.validate_domain_yaml(filename)
        data = read_yaml_file(filename)
        utter_templates = cls.collect_templates(data.get("templates", {}))
        if not action_factory:
            action_factory = data.get("action_factory", None)
        topics = [Topic(name) for name in data.get("topics", [])]
        slots = cls.collect_slots(data.get("slots", {}))
        additional_arguments = data.get("config", {})
        return TemplateDomain(
                data.get("intents", []),
                data.get("entities", []),
                slots,
                utter_templates,
                data.get("actions", []),
                data.get("action_names", []),
                action_factory,
                topics,
                **additional_arguments
        )
예제 #2
0
def _create_external_channels(channel, credentials_file):
    # type: (Optional[Text], Optional[Text]) -> List[InputChannel]

    # the commandline input channel is the only one that doesn't need any
    # credentials
    print(channel, credentials_file, "external_chanlles son3")

    if channel == "cmdline":
        from rasa_core.channels import RestInput
        return [RestInput()]

    if channel is None and credentials_file is None:
        # if there is no configuration at all, we'll run without a channel
        return []
    elif credentials_file is None:
        # if there is a channel, but no configuration, this can't be right
        _raise_missing_credentials_exception(channel)

    all_credentials = read_yaml_file(credentials_file)
    print(all_credentials)

    if channel:
        print("1")
        return [_create_single_channel(channel, all_credentials)]
    else:
        print("2")
        return [_create_single_channel(c, k)
                for c, k in all_credentials.items()]
예제 #3
0
def _create_external_channel(channel, port, credentials_file):
    if credentials_file is None:
        _raise_missing_credentials_exception(channel)

    credentials = read_yaml_file(credentials_file)
    if channel == "facebook":
        input_blueprint = FacebookInput(credentials.get("verify"),
                                        credentials.get("secret"),
                                        credentials.get("page-access-token"))
    elif channel == "slack":
        input_blueprint = SlackInput(credentials.get("slack_token"),
                                     credentials.get("slack_channel"))
    elif channel == "telegram":
        input_blueprint = TelegramInput(credentials.get("access_token"),
                                        credentials.get("verify"),
                                        credentials.get("webhook_url"))
    elif channel == "mattermost":
        input_blueprint = MattermostInput(credentials.get("url"),
                                          credentials.get("team"),
                                          credentials.get("user"),
                                          credentials.get("pw"))
    elif channel == "twilio":
        input_blueprint = TwilioInput(credentials.get("account_sid"),
                                      credentials.get("auth_token"),
                                      credentials.get("twilio_number"))
    else:
        Exception("This script currently only supports the facebook,"
                  " telegram, mattermost and slack connectors.")

    return HttpInputChannel(port, None, input_blueprint)
예제 #4
0
    def __init__(self,
                 endpoint_file="endpoints.yml",
                 host="mongodb://localhost:27017",
                 db="chatbot",
                 username=None,
                 password=None,
                 auth_source="admin",
                 collection="pages"):
        from pymongo.database import Database
        from pymongo import MongoClient

        try:
            auth = read_yaml_file(endpoint_file)["tracker_store"]
            if auth["type"] == "mongod":
                host = auth["url"]
                db = auth["db"]
                username = auth["username"]
                password = auth["password"]
                auth_source = auth["auth_source"]
        except:
            pass

        self.client = MongoClient(
            host,
            username=username,
            password=password,
            authSource=auth_source,
            # delay connect until process forking is done
            connect=False)

        self.db = Database(self.client, db)
        self.collection = collection
예제 #5
0
파일: run.py 프로젝트: githubclj/rasa_core
def _create_external_channel(channel, port, credentials_file):
    if credentials_file is None:
        _raise_missing_credentials_exception(channel)

    credentials = read_yaml_file(credentials_file)
    if channel == "facebook":
        input_blueprint = FacebookInput(
                credentials.get("verify"),
                credentials.get("secret"),
                credentials.get("page-access-token"))
    elif channel == "slack":
        input_blueprint = SlackInput(
                credentials.get("slack_token"),
                credentials.get("slack_channel"))
    elif channel == "telegram":
        input_blueprint = TelegramInput(
                credentials.get("access_token"),
                credentials.get("verify"),
                credentials.get("webhook_url"))
    elif channel == "mattermost":
        input_blueprint = MattermostInput(
                credentials.get("url"),
                credentials.get("team"),
                credentials.get("user"),
                credentials.get("pw"))
    elif channel == "twilio":
        input_blueprint = TwilioInput(
                credentials.get("account_sid"),
                credentials.get("auth_token"),
                credentials.get("twilio_number"))
    else:
        Exception("This script currently only supports the facebook,"
                  " telegram, mattermost and slack connectors.")

    return HttpInputChannel(port, None, input_blueprint)
예제 #6
0
def load(config_file: Optional[Text]) -> List['Policy']:
    """Load policy data stored in the specified file."""

    if config_file and os.path.isfile(config_file):
        config_data = utils.read_yaml_file(config_file)
    else:
        raise ValueError("You have to provide a valid path to a config file. "
                         "The file '{}' could not be found."
                         "".format(os.path.abspath(config_file)))

    return PolicyEnsemble.from_dict(config_data)
예제 #7
0
def load(config_file):
    # type: (Optional[Text], Dict[Text, Any], int) -> List[Policy]
    """Load policy data stored in the specified file. fallback_args and
    max_history are typically command line arguments. They take precedence
    over the arguments specified in the config yaml.
    """
    if config_file:
        config_data = utils.read_yaml_file(config_file)
    else:
        raise ValueError("You have to provide a config file")

    return PolicyEnsemble.from_dict(config_data)
예제 #8
0
def _create_external_channels(channel, credentials_file):
    # type: (Optional[Text], Optional[Text]) -> List[InputChannel]

    if credentials_file:
        all_credentials = read_yaml_file(credentials_file)
    else:
        all_credentials = {}

    if channel:
        return [_create_single_channel(channel, all_credentials.get(channel))]
    else:
        return [
            _create_single_channel(c, k) for c, k in all_credentials.items()
        ]
예제 #9
0
def _create_facebook_channel(channel, port, credentials_file):
    if credentials_file is None:
        raise Exception("To use the facebook input channel, you need to "
                        "pass a credentials file using '--credentials'. "
                        "The argument should be a file path pointing to"
                        "a yml file containing the facebook authentication"
                        "information. Details in the docs: "
                        "https://core.rasa.ai/facebook.html")
    credentials = read_yaml_file(credentials_file)
    input_blueprint = FacebookInput(credentials.get("verify"),
                                    credentials.get("secret"),
                                    credentials.get("page-access-token"))

    return HttpInputChannel(port, None, input_blueprint)
예제 #10
0
def create_http_input_channels(channel, credentials_file):
    # type: (Optional[Text], Optional[Text]) -> List[InputChannel]
    """Instantiate the chosen input channel."""

    if credentials_file:
        all_credentials = read_yaml_file(credentials_file)
    else:
        all_credentials = {}

    if channel:
        return [_create_single_channel(channel, all_credentials.get(channel))]
    else:
        return [
            _create_single_channel(c, k) for c, k in all_credentials.items()
        ]
예제 #11
0
def load(config_file, fallback_args, max_history):
    # type: (Optional[Text], Dict[Text, Any], int) -> List[Policy]
    """Load policy data stored in the specified file. fallback_args and
    max_history are typically command line arguments. They take precedence
    over the arguments specified in the config yaml.
    """

    if config_file is None:
        return PolicyEnsemble.default_policies(fallback_args, max_history)

    config_data = utils.read_yaml_file(config_file)
    config_data = handle_precedence_and_defaults(config_data, fallback_args,
                                                 max_history)

    return PolicyEnsemble.from_dict(config_data)
예제 #12
0
파일: run.py 프로젝트: zh2010/rasa_core
def _create_external_channel(channel, port, credentials_file):
    if credentials_file is None:
        _raise_missing_credentials_Exception(channel)

    credentials = read_yaml_file(credentials_file)
    if channel == "facebook":
        input_blueprint = FacebookInput(credentials.get("verify"),
                                        credentials.get("secret"),
                                        credentials.get("page-access-token"))
    elif channel == "slack":
        input_blueprint = SlackInput(credentials.get("slack_token"),
                                     credentials.get("slack_channel"))
    else:
        Exception("This script currently only supports the facebook "
                  "and slack connectors.")

    return HttpInputChannel(port, None, input_blueprint)
예제 #13
0
    def validate_domain_yaml(cls, filename):
        """Validate domain yaml."""
        from pykwalify.core import Core

        log = logging.getLogger('pykwalify')
        log.setLevel(logging.WARN)

        schema_file = pkg_resources.resource_filename(__name__,
                                                      "schemas/domain.yml")
        c = Core(source_data=utils.read_yaml_file(filename),
                 schema_files=[schema_file])
        try:
            c.validate(raise_exception=True)
        except SchemaError:
            raise ValueError("Failed to validate your domain yaml '{}'. "
                             "Make sure the file is correct, to do so"
                             "take a look at the errors logged during "
                             "validation previous to this exception. "
                             "".format(os.path.abspath(filename)))
예제 #14
0
파일: run.py 프로젝트: osustarg/rasa_core
def create_input_channel(channel, port, credentials_file):
    """Instantiate the chosen input channel."""

    if channel == "facebook":
        if credentials_file is None:
            raise Exception("To use the facebook input channel, you need to "
                            "pass a credentials file using '--credentials'. "
                            "The argument should be a file path pointing to"
                            "a yml file containing the facebook authentication"
                            "information. Details in the docs: "
                            "https://core.rasa.ai/facebook.html")
        credentials = read_yaml_file(credentials_file)
        input_blueprint = FacebookInput(credentials.get("verify"),
                                        credentials.get("secret"),
                                        credentials.get("page-tokens"), True)
        return HttpInputChannel(port, None, input_blueprint)
    elif channel == "cmdline":
        return ConsoleInputChannel()
    else:
        raise Exception("Unknown input channel for running main.")
예제 #15
0
def test_interactive_domain_persistence(mock_endpoint, tmpdir):
    # Test method interactive._write_domain_to_file

    tracker_dump = "data/test_trackers/tracker_moodbot.json"
    tracker_json = utils.read_json_file(tracker_dump)

    events = tracker_json.get("events", [])

    domain_path = tmpdir.join("interactive_domain_save.yml").strpath

    url = '{}/domain'.format(mock_endpoint.url)
    httpretty.register_uri(httpretty.GET, url, body='{}')

    httpretty.enable()
    interactive._write_domain_to_file(domain_path, events, mock_endpoint)
    httpretty.disable()

    saved_domain = utils.read_yaml_file(domain_path)

    for default_action in default_actions():
        assert default_action.name() not in saved_domain["actions"]
예제 #16
0
async def test_interactive_domain_persistence(mock_endpoint, tmpdir):
    # Test method interactive._write_domain_to_file

    tracker_dump = "data/test_trackers/tracker_moodbot.json"
    tracker_json = utils.read_json_file(tracker_dump)

    events = tracker_json.get("events", [])

    domain_path = tmpdir.join("interactive_domain_save.yml").strpath

    url = '{}/domain'.format(mock_endpoint.url)
    with aioresponses() as mocked:
        mocked.get(url, payload={})

        await interactive._write_domain_to_file(domain_path, events,
                                                mock_endpoint)

    saved_domain = utils.read_yaml_file(domain_path)

    for default_action in default_actions():
        assert default_action.name() not in saved_domain["actions"]
예제 #17
0
파일: run.py 프로젝트: rohitjun08/rasa_core
def _create_external_channels(channel, credentials_file):
    # type: (Optional[Text], Optional[Text]) -> List[InputChannel]

    # the commandline input channel is the only one that doesn't need any
    # credentials
    if channel == "cmdline":
        from rasa_core.channels import RestInput
        return [RestInput()]

    if channel is None and credentials_file is None:
        # if there is no configuration at all, we'll run without a channel
        return []
    elif credentials_file is None:
        # if there is a channel, but no configuration, this can't be right
        _raise_missing_credentials_exception(channel)

    all_credentials = read_yaml_file(credentials_file)

    if channel:
        return [_create_single_channel(channel, all_credentials.get(channel))]
    else:
        return [_create_single_channel(c, k)
                for c, k in all_credentials.items()]
예제 #18
0
def run_core(core_model_path, nlu_model_path, action_endpoint_url,
             slack_token):
    logging.basicConfig(filename=logfile, level=logging.DEBUG)
    nlu_interpreter = RasaNLUInterpreter(nlu_model_path)
    action_endpoint = EndpointConfig(url=action_endpoint_url)
    agent = Agent.load(core_model_path,
                       interpreter=nlu_interpreter,
                       action_endpoint=action_endpoint)
    input_channel = SlackInput(slack_token)
    agent.handle_channels([input_channel], 5004, serve_forever=True)

    print("Your bot is ready to talk! Type your messages here or send 'stop'")
    while True:
        a = input()
        if a == 'stop':
            break
        responses = agent.handle_text(a)
        for response in responses:
            print(response["text"])
    return agent


if __name__ == '__main__':
    actionConfig = utils.read_yaml_file('endpoints.yml')
    slackConfig = utils.read_yaml_file('credentials.yml')
    train_core('domain.yml', 'models/dialogue', 'data/stories.md',
               'policy.yml')
    run_core('models/dialogue', 'models/current/nlu',
             actionConfig["action_endpoint"]["url"],
             slackConfig["slack"]["slack_token"])
예제 #19
0
    agent.persist(model_path)
    return agent


def run_core(core_model_path, nlu_model_path, action_endpoint_url):
    logging.basicConfig(filename=logfile, level=logging.DEBUG)
    nlu_interpreter = RasaNLUInterpreter(nlu_model_path)
    action_endpoint = EndpointConfig(url=action_endpoint_url)
    agent = Agent.load(core_model_path,
                       interpreter=nlu_interpreter,
                       action_endpoint=action_endpoint)

    print(
        "Sera is ready to talk! Type your messages here or send 'stop' to STOP!"
    )
    while True:
        a = input()
        if a == 'stop':
            break
        responses = agent.handle_text(a)
        for response in responses:
            print(response["text"])
    return agent


if __name__ == '__main__':
    actionConfig = utils.read_yaml_file('endpoints.yml')
    # train_core('domain.yml', './models/dialogue', './data/stories.md')
    run_core('./models/dialogue', './models/nlu/default/weathernlu',
             actionConfig["action_endpoint"]["url"])