Example #1
0
def get_agent_for_user(user):
    agent = agents_by_user.get(user.id)

    if not agent:
        logging.info('Agent does not exist for "%s", creating it' % user.id)

        interpreter = SnipsInterpreter(user.profile.language[:2],
                                       CONFIG.getpath(CACHE_DIR))
        interpreter.fit_from_skill_data()

        agent = Agent(interpreter, uid=user.id)

        agents_by_user[user.id] = agent
    else:
        logging.info('Agent found matching this user!')

    user_settings = user.setting_set.all()
    user_settings_dict = {
        setting.name: setting.value
        for setting in user_settings
    }

    # Update agent meta with user settings
    agent.meta.update(user_settings_dict)

    return agent
Example #2
0
def create_skill_agent(
        skill_folder: str,
        lang='en',
        additional_skills=[]) -> Agent:  # pylint: disable=dangerous-default-value
    """Create an agent specifically targeted at the specified skill folder. It makes
    it easy to write skill tests using a specific mock object as the Agent model.

    It will spawn a SnipsInterpreter and fit data only for the skill being tested.

    Args:
      skill_folder (str): Absolute path of the skill folder to be tested
      lang (str): Optional language used by the interpreter
      additional_skills (list of str): Additional skills to be loaded and interpreted

    Returns:
      Agent: Agent with a specific mock model to make assertions simplier

    """
    import_path = os.path.dirname(skill_folder)
    skill_name = os.path.basename(skill_folder)

    # Start by importing the skill
    if import_path not in sys.path:
        sys.path.append(import_path)

    import_or_reload(skill_name)

    # And instantiate an interpreter
    skills_to_load = [skill_name] + additional_skills

    interpreter = SnipsInterpreter(lang)
    interpreter.fit_from_skill_data(skills_to_load)

    # Filter handlers for targeted skill only
    handlers_data = GLOBAL_HANDLERS._data  # pylint: disable=W0212
    handlers = HandlersStore({
        k: v
        for (k, v) in handlers_data.items()
        if get_root_package_name(v.__module__) in skills_to_load
    })

    return Agent(interpreter, model=AgentModelMock(), handlers_store=handlers)
Example #3
0
def instantiate_and_fit_interpreter(training_file=None):  # pragma: no cover
    if not training_file:
        import_skills(CONFIG.getpath(SKILLS_DIR), CONFIG.getbool(WATCH))

    try:
        from pytlas.understanding.snips import SnipsInterpreter  # pylint: disable=import-outside-toplevel

        interpreter = SnipsInterpreter(CONFIG.get(LANGUAGE),
                                       CONFIG.getpath(CACHE_DIR))

        if training_file:
            interpreter.fit_from_file(training_file)
        else:
            interpreter.fit_from_skill_data()

        return interpreter
    except ImportError:
        logging.critical(
            'Could not import the "snips" interpreter, is "snips-nlu" installed?'
        )
Example #4
0
    def create(self, uid: str) -> Agent:
        cache_dir, conf_path = get_config_directories_path(
            self._directory, uid)
        meta = {}

        if os.path.isfile(conf_path):
            store = SettingsStore()
            store.load_from_file(conf_path)
            meta = store.to_dict()
            self._logger.info('Using settings from "%s"', conf_path)
        else:
            cache_dir = self._default_cache_dir
            self._logger.warning(
                'Could not find a pytlas.ini file in "%s", using the default one',
                conf_path)

        interpreter = SnipsInterpreter(meta.get(
            to_env_key(DEFAULT_SECTION, LANGUAGE_KEY), DEFAULT_LANGUAGE),
                                       cache_directory=cache_dir)
        interpreter.fit_from_skill_data()
        return Agent(interpreter, **meta)
Example #5
0

if __name__ == '__main__':

    # The last piece is the `Interpreter`. This is the part responsible for human
    # language parsing. It parses raw human sentences into something more useful for
    # the program.

    interpreter = SnipsInterpreter('en',
                                   cache_directory=os.path.join(
                                       os.path.dirname(__file__), 'cache'))

    # Train the interpreter using training data register with the `training` decorator
    # or `pytlas.training.register` function.

    interpreter.fit_from_skill_data()

    # The `Agent` uses the model given to call appropriate lifecycle hooks.

    agent = Agent(interpreter, model=Client())

    # With this next line, this is what happenned:
    #
    # - The message is parsed by the `SnipsInterpreter`
    # - A 'lights_on' intents is retrieved and contains 'kitchen' and 'bedroom' as the 'room' slot values
    # - Since the `Agent` is asleep, it will transition to the 'lights_on' state immediately
    # - Transitioning to this state call the appropriate handler (at the beginning of this file)
    # - 'Turning lights on in kitchen, bedroom' is printed to the terminal by the `Client.on_answer` defined above
    # - `done` is called by the skill so the agent transitions back to the 'asleep' state

    agent.parse('turn the lights on in kitchen and bedroom please')