Пример #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
Пример #2
0
        def test_it_should_returns_empty_results_when_not_fitted(self):
            i = SnipsInterpreter('en')

            expect(i.is_ready).to.be.false
            expect(i.parse('a message')).to.be.empty
            expect(i.parse_slot('get_forecast', 'date',
                                'tomorrow')).to.be.empty
Пример #3
0
        def test_it_should_not_try_to_install_language_resources_if_already_installed(
                self):
            i = SnipsInterpreter('doo')

            with patch('importlib.util.find_spec', return_value=True):
                with patch('subprocess.run') as subprocess_mock:
                    expect(i._check_and_install_resources_package()).to.equal(
                        'snips_nlu_doo')
                    subprocess_mock.assert_not_called()
Пример #4
0
        def test_it_should_install_language_resources_if_needed(self):
            i = SnipsInterpreter('doo')

            with patch('importlib.util.find_spec', return_value=False):
                with patch('subprocess.run') as subprocess_mock:
                    pkg = i._check_and_install_resources_package()
                    expect(pkg).to.equal('snips_nlu_doo')

                    cmd = subprocess_mock.call_args[0][0]
                    expect(cmd).to.equal(
                        [sys.executable, '-m', 'snips_nlu', 'download', 'doo'])
Пример #5
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)
Пример #6
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?'
        )
Пример #7
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)
Пример #8
0
  """
    def on_answer(self, text, cards, **meta):
        print(text)

    def on_ask(self, slot, text, choices, **meta):
        print(text)


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
Пример #9
0
import datetime
import os
import sys
from unittest.mock import patch
from sure import expect
from dateutil.parser import parse as dateParse
from dateutil.relativedelta import relativedelta
from pytlas.understanding import Intent, SlotValues, UnitValue

try:
    from pytlas.understanding.snips import SnipsInterpreter, get_entity_value

    # Train the interpreter once to speed up tests
    fitted_interpreter = SnipsInterpreter('en')
    fitted_interpreter.fit_from_file(
        os.path.join(os.path.dirname(__file__), '../__training.json'))

    cached_interpreter = SnipsInterpreter(
        'en',
        os.path.join(os.path.dirname(__file__),
                     '../__snips_interpreter_cache'))
    cached_interpreter.load_from_cache()

    # Each test method will be run on a freshly fitted engine and on a cached one to be sure
    # there is no particular cases
    interpreters = [fitted_interpreter, cached_interpreter]

    class TestSnipsInterpreter:
        def test_it_should_not_try_to_install_language_resources_if_already_installed(
                self):
            i = SnipsInterpreter('doo')