Example #1
0
def run(args: argparse.Namespace) -> None:
    from rasa_core.utils import print_success

    print_success("Welcome to Rasa! 🤖\n")
    print("To get started quickly, I can assist you to create an "
          "initial project.\n"
          "If you need some help to get from this template to a "
          "bad ass contextual assistant, checkout our quickstart guide"
          "here: https://rasa.com/docs/core/quickstart \n\n"
          "Now let's start! 👇🏽\n")
    path = questionary.text(
        "Please enter a folder path where I should create "
        "the initial project [default: current directory]",
        default=".").ask()

    if not os.path.isdir(path):
        _ask_create_path(path)

    if path is None or not os.path.isdir(path):
        print_cancel()

    if len(os.listdir(path)) > 0:
        _ask_overwrite(path)

    init_project(args, path)
Example #2
0
def train_nlu(config: Text, nlu_data: Text, output: Text,
              train_path: Optional[Text]) -> Optional["Interpreter"]:
    """Trains a NLU model.

    Args:
        config: Path to the config file for NLU.
        nlu_data: Path to the NLU training data.
        output: Output path.
        train_path: If `None` the model will be trained in a temporary
            directory, otherwise in the provided directory.

    Returns:
        If `train_path` is given it returns the path to the model archive,
        otherwise the path to the directory with the trained model files.

    """
    import rasa_nlu
    from rasa_core.utils import print_success

    _train_path = train_path or tempfile.mkdtemp()
    _, nlu_model, _ = rasa_nlu.train(config, nlu_data, _train_path,
                                     project="",
                                     fixed_model_name="nlu")

    if not train_path:
        nlu_data = data.get_nlu_directory(nlu_data)
        output_path = create_output_path(output, prefix="nlu-")
        new_fingerprint = model.model_fingerprint(config, nlu_data=nlu_data)
        model.create_package_rasa(_train_path, output_path, new_fingerprint)
        print_success("Your Rasa NLU model is trained and saved at '{}'."
                      "".format(output_path))

    return nlu_model
Example #3
0
def _display_bot_response(response: Dict):
    from IPython.display import Image, display

    for response_type, value in response.items():
        if response_type == 'text':
            print_success(value)

        if response_type == 'image':
            image = Image(url=value)
            display(image, )
Example #4
0
def _ask_create_path(path: Text) -> None:
    should_create = questionary.confirm("Path '{}' does not exist 🧐. "
                                        "Should I create it?"
                                        "".format(path)).ask()
    if should_create:
        os.makedirs(path)
    else:
        print_success(
            "Ok. Then I stop here. If you need me again, simply type "
            "'rasa init' 🙋🏽‍♀️")
        exit(0)
Example #5
0
def print_train_or_instructions(args: argparse.Namespace, path: Text) -> None:
    print_success("Your bot is ready to go!")
    should_train = questionary.confirm("Do you want me to train an initial "
                                       "model for the bot? 💪🏽").ask()
    if should_train:
        config = os.path.join(path, DEFAULT_CONFIG_PATH)
        training_files = os.path.join(path, DEFAULT_DATA_PATH)
        domain = os.path.join(path, DEFAULT_DOMAIN_PATH)
        output = os.path.join(path, create_output_path())

        args.model = rasa.train(domain, config, training_files, output)

        print_run_or_instructions(args, path)

    else:
        print_success("No problem 👍🏼. You can also train me later by going "
                      "to the project directory and running 'rasa train'."
                      "".format(path))
Example #6
0
def up(args: argparse.Namespace):
    try:
        from rasa_platform import config
        from rasa_platform.api.server import main_local
    except ImportError:
        print_error("Rasa Platform is not installed. The `rasa up` command "
                    "requires an installation of Rasa Platform.")
        sys.exit()

    print_success("Starting Rasa Core")

    p = Process(target=start_core, args=(config.platform_token, ))
    p.start()

    p = Process(target=start_event_service)
    p.start()

    print_success("Starting Rasa Interface...")

    main_local(".")
Example #7
0
def print_run_or_instructions(args: argparse.Namespace, path: Text) -> None:
    from rasa_core import constants

    should_run = questionary.confirm("Do you want to speak to the trained bot "
                                     "on the command line? 🤖").ask()

    if should_run:
        # provide defaults for command line arguments
        attributes = [
            "endpoints", "credentials", "cors", "auth_token", "jwt_secret",
            "jwt_method", "enable_api"
        ]
        for a in attributes:
            setattr(args, a, None)

        args.port = constants.DEFAULT_SERVER_PORT

        shell(args)
    else:
        print_success("Ok 👍🏼. If you want to speak to the bot later, "
                      "change into the project directory and run 'rasa shell'."
                      "".format(path))
Example #8
0
def start_core(platform_token):
    from rasa_core.utils import AvailableEndpoints
    _endpoints = AvailableEndpoints(
        # TODO: make endpoints more configurable, esp ports
        model=EndpointConfig(
            "http://localhost:5002"
            "/api/projects/default/models/tags/production",
            token=platform_token,
            wait_time_between_pulls=1),
        event_broker=EndpointConfig(**{"type": "file"}),
        nlg=EndpointConfig("http://localhost:5002"
                           "/api/nlg",
                           token=platform_token))

    from rasa_core import broker
    _broker = broker.from_endpoint_config(_endpoints.event_broker)

    from rasa_core.tracker_store import TrackerStore
    _tracker_store = TrackerStore.find_tracker_store(None,
                                                     _endpoints.tracker_store,
                                                     _broker)

    from rasa_core.run import load_agent
    _agent = load_agent("models",
                        interpreter=None,
                        tracker_store=_tracker_store,
                        endpoints=_endpoints)
    from rasa_core.run import serve_application
    print_success("About to start core")

    serve_application(
        _agent,
        "rasa",
        5005,
        "credentials.yml",
        "*",
        None,  # TODO: configure auth token
        True)
Example #9
0
def train_core(domain: Text, config: Text, stories: Text, output: Text,
               train_path: Optional[Text]) -> Optional[Text]:
    """Trains a Core model.

    Args:
        domain: Path to the domain file.
        config: Path to the config file for Core.
        stories: Path to the Core training data.
        output: Output path.
        train_path: If `None` the model will be trained in a temporary
            directory, otherwise in the provided directory.

    Returns:
        If `train_path` is given it returns the path to the model archive,
        otherwise the path to the directory with the trained model files.

    """
    import rasa_core.train
    from rasa_core.utils import print_success

    # normal (not compare) training
    core_model = rasa_core.train(domain_file=domain, stories_file=stories,
                                 output_path=os.path.join(train_path, "core"),
                                 policy_config=config)

    if not train_path:
        # Only Core was trained.
        stories = data.get_core_directory(stories)
        output_path = create_output_path(output, prefix="core-")
        new_fingerprint = model.model_fingerprint(config, domain,
                                                  stories=stories)
        model.create_package_rasa(train_path, output_path, new_fingerprint)
        print_success("Your Rasa Core model is trained and saved at '{}'."
                      "".format(output_path))

    return core_model
Example #10
0
def train(domain: Text, config: Text, training_files: Union[Text, List[Text]],
          output: Text = DEFAULT_MODELS_PATH, force_training: bool = False
          ) -> Optional[Text]:
    """Trains a Rasa model (Core and NLU).

    Args:
        domain: Path to the domain file.
        config: Path to the config for Core and NLU.
        training_files: Paths to the training data for Core and NLU.
        output: Output path.
        force_training: If `True` retrain model even if data has not changed.

    Returns:
        Path of the trained model archive.
    """
    from rasa_core.utils import print_success

    train_path = tempfile.mkdtemp()
    old_model = model.get_latest_model(output)
    retrain_core = True
    retrain_nlu = True

    story_directory, nlu_data_directory = data.get_core_nlu_directories(
        training_files)
    new_fingerprint = model.model_fingerprint(config, domain,
                                              nlu_data_directory,
                                              story_directory)
    if not force_training and old_model:
        unpacked = model.unpack_model(old_model)
        old_core, old_nlu = model.get_model_subdirectories(unpacked)
        last_fingerprint = model.fingerprint_from_path(unpacked)

        if not model.core_fingerprint_changed(last_fingerprint,
                                              new_fingerprint):
            target_path = os.path.join(train_path, "core")
            retrain_core = not model.merge_model(old_core, target_path)

        if not model.nlu_fingerprint_changed(last_fingerprint, new_fingerprint):
            target_path = os.path.join(train_path, "nlu")
            retrain_nlu = not model.merge_model(old_nlu, target_path)

    if force_training or retrain_core:
        train_core(domain, config, story_directory, output, train_path)
    else:
        print("Core configuration did not change. No need to retrain "
              "Core model.")

    if force_training or retrain_nlu:
        train_nlu(config, nlu_data_directory, output, train_path)
    else:
        print("NLU configuration did not change. No need to retrain NLU model.")

    if retrain_core or retrain_nlu:
        output = create_output_path(output)
        model.create_package_rasa(train_path, output, new_fingerprint)

        print("Train path: '{}'.".format(train_path))

        print_success("Your bot is trained and ready to take for a spin!")

        return output
    else:
        print("Nothing changed. You can use the old model: '{}'."
              "".format(old_model))

        return old_model
Example #11
0
def print_cancel() -> None:
    print_success("Ok. Then I stop here. If you need me again, simply type "
                  "'rasa init' 🙋🏽‍♀️")
    exit(0)