Ejemplo n.º 1
0
async def test_callbacks_intent(mocker):
    """Test intent callbacks."""
    app = HermesApp("Test NluIntent", mqtt_client=mocker.MagicMock())

    # Mock intent callback and apply on_intent decorator.
    intent_handler = mocker.MagicMock()
    app.on_intent(INTENT_NAME)(intent_handler)

    intent_handler2 = mocker.MagicMock()
    app.on_intent(INTENT_NAME2, INTENT_NAME3)(intent_handler2)

    # Simulate app.run() without the MQTT client.
    app._subscribe_callbacks()

    # Simulate detected intent GetTime.
    await app.on_raw_message(INTENT_TOPIC, NLU_INTENT.to_json())
    # Check whether intent_handler has been called with the right Rhasspy Hermes object.
    intent_handler.assert_called_once_with(NLU_INTENT)
    intent_handler2.assert_not_called()

    # Simulate intent GetTemperature.
    intent_handler.reset_mock()
    intent_handler2.reset_mock()
    await app.on_raw_message(INTENT_TOPIC2, NLU_INTENT2.to_json())
    # Check whether intent_handler2 has been called with the right Rhasspy Hermes object.
    intent_handler2.assert_called_once_with(NLU_INTENT2)
    intent_handler.assert_not_called()

    # Simulate intent GetWeather.
    intent_handler.reset_mock()
    intent_handler2.reset_mock()
    # Check whether intent_handler2 has been called with the right Rhasspy Hermes object.
    await app.on_raw_message(INTENT_TOPIC3, NLU_INTENT3.to_json())
    intent_handler2.assert_called_once_with(NLU_INTENT3)
    intent_handler.assert_not_called()
Ejemplo n.º 2
0
def test_if_cli_arguments_overwrite_init_arguments(mocker):
    """Test whether arguments from the command line overwrite arguments to a HermesApp object."""
    mocker.patch(
        "sys.argv",
        [
            "rhasspy-hermes-app-test",
            "--host",
            "rhasspy.home",
            "--port",
            "1883",
            "--username",
            "rhasspy-hermes-app",
            "--password",
            "test",
        ],
    )
    app = HermesApp(
        "Test arguments in init",
        mqtt_client=mocker.MagicMock(),
        host="rhasspy.local",
        port=8883,
        username="******",
        password="******",
    )

    assert app.args.host == "rhasspy.home"
    assert app.args.port == 1883
    assert app.args.username == "rhasspy-hermes-app"
    assert app.args.password == "test"
Ejemplo n.º 3
0
def test_default_arguments(mocker):
    """Test whether default arguments are set up correctly in a HermesApp object."""
    app = HermesApp("Test default arguments", mqtt_client=mocker.MagicMock())

    assert app.args.host == "localhost"
    assert app.args.port == 1883
    assert app.args.tls == False
    assert app.args.username is None
    assert app.args.password is None
Ejemplo n.º 4
0
def test_arguments_in_init(mocker):
    """Test whether arguments are set up correctly while initializing a HermesApp object."""
    app = HermesApp(
        "Test arguments in init",
        mqtt_client=mocker.MagicMock(),
        host="rhasspy.home",
        port=8883,
        tls=True,
        username="******",
        password="******",
    )

    assert app.args.host == "rhasspy.home"
    assert app.args.port == 8883
    assert app.args.tls == True
    assert app.args.username == "rhasspy-hermes-app"
    assert app.args.password == "test"
def test_if_cli_arguments_overwrite_init_arguments_with_argument_parser(
        mocker):
    """Test whether arguments from the command line overwrite arguments to a HermesApp object
    if the user supplies their own ArgumentParser object."""
    mocker.patch(
        "sys.argv",
        [
            "rhasspy-hermes-app-test",
            "--host",
            "rhasspy.home",
            "--port",
            "1883",
            "--username",
            "rhasspy-hermes-app",
            "--password",
            "test",
            "--test-argument",
            "foobar",
            "--test-flag",
        ],
    )
    parser = argparse.ArgumentParser(prog="rhasspy-hermes-app-test")
    parser.add_argument("--test-argument", default="foo")
    parser.add_argument("--test-flag", action="store_true")

    app = HermesApp(
        "Test arguments in init",
        parser=parser,
        mqtt_client=mocker.MagicMock(),
        host="rhasspy.local",
        port=8883,
        username="******",
        password="******",
        test_argument="bar",
    )

    assert app.args.host == "rhasspy.home"
    assert app.args.port == 1883
    assert app.args.username == "rhasspy-hermes-app"
    assert app.args.password == "test"
    assert app.args.test_argument == "foobar"
    assert app.args.test_flag is True
Ejemplo n.º 6
0
async def test_callbacks_intent_not_recognized(mocker):
    """Test intent not recognized callbacks."""
    app = HermesApp("Test intentNotRecognized", mqtt_client=mocker.MagicMock())

    # Mock callback and apply on_intent_not_recognized decorator.
    inr = mocker.MagicMock()
    app.on_intent_not_recognized(inr)

    # Simulate app.run() without the MQTT client.
    app._subscribe_callbacks()

    # Simulate intent not recognized message.
    await app.on_raw_message(INR_TOPIC, INR.to_json())

    # Check whether callback has been called with the right Rhasspy Hermes object.
    inr.assert_called_once_with(INR)
Ejemplo n.º 7
0
def test_arguments_from_cli(mocker):
    """Test whether arguments from the command line are set up correctly in a HermesApp object."""
    mocker.patch(
        "sys.argv",
        [
            "rhasspy-hermes-app-test",
            "--host",
            "rhasspy.home",
            "--port",
            "8883",
            "--tls",
            "--username",
            "rhasspy-hermes-app",
            "--password",
            "test",
        ],
    )
    app = HermesApp("Test arguments in init", mqtt_client=mocker.MagicMock())

    assert app.args.host == "rhasspy.home"
    assert app.args.port == 8883
    assert app.args.tls == True
    assert app.args.username == "rhasspy-hermes-app"
    assert app.args.password == "test"
Ejemplo n.º 8
0
async def test_callbacks_hotword(mocker):
    """Test hotword callbacks."""
    app = HermesApp("Test HotwordDetected", mqtt_client=mocker.MagicMock())

    # Mock wake callback and apply on_hotword decorator.
    wake = mocker.MagicMock()
    app.on_hotword(wake)

    # Simulate app.run() without the MQTT client.
    app._subscribe_callbacks()

    # Check whether callback has been added to the app.
    assert len(app._callbacks_hotword) == 1
    assert app._callbacks_hotword[0] == wake

    # Simulate detected hotword.
    await app.on_raw_message(HOTWORD_TOPIC, HOTWORD_PAYLOAD)

    # Check whether callback has been called with the right Rhasspy Hermes object.
    wake.assert_called_once_with(HotwordDetected.from_json(HOTWORD_PAYLOAD))
Ejemplo n.º 9
0
async def test_callbacks_hotword(mocker):
    """Test hotword callbacks."""
    app = HermesApp("Test HotwordDetected", mqtt_client=mocker.MagicMock())

    # Mock wake callback and apply on_hotword decorator.
    wake = mocker.MagicMock()
    app.on_hotword(wake)

    # Simulate app.run() without the MQTT client.
    app._subscribe_callbacks()

    # Simulate detected hotword.
    await app.on_raw_message(HOTWORD_TOPIC, HOTWORD.to_json())

    # Check whether callback has been called with the right Rhasspy Hermes object.
    wake.assert_called_once_with(HOTWORD)

    # Simulate another detected hotword.
    wake.reset_mock()
    await app.on_raw_message(HOTWORD_TOPIC2, HOTWORD2.to_json())

    # Check whether callback has been called with the right Rhasspy Hermes object.
    wake.assert_called_once_with(HOTWORD2)
Ejemplo n.º 10
0
import json, os
import io, configparser

from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp

from gasoline import Gasoline

app = HermesApp("GasolineApp")


def read_configuration_file():
    try:
        cp = configparser.ConfigParser()
        with io.open(os.path.dirname(__file__) + "/config.ini",
                     encoding="utf-8") as f:
            cp.read_file(f)
        return {
            section:
            {option_name: option
             for option_name, option in cp.items(section)}
            for section in cp.sections()
        }
    except (IOError, configparser.Error):
        return dict()


def read_language_file(language):
    try:
        print(os.path.dirname(__file__) + '/' + language + '.json')
        with open(os.path.dirname(__file__) + '/' + language + ".json",
Ejemplo n.º 11
0
from rhasspyhermes_app import EndSession, HermesApp

_LOGGER = logging.getLogger("WeatherApp")

host = os.getenv("MQTT_HOST", "localhost")
port = int(os.getenv("MQTT_PORT", "1883"))
username = os.getenv("MQTT_USERNAME")
password = os.getenv("MQTT_PASSWORD")

owm_key = os.getenv("OWM_KEY")
owm_default_geolocation = os.getenv("OWM_DEFAULT_GEOLOCATION",
                                    "52.5065133,13.1445612")

app = HermesApp("WeatherApp",
                host=host,
                port=port,
                username=username,
                password=password)

config_dict = config.get_default_config()
config_dict['language'] = 'de'

owm = OWM(owm_key, config_dict)
mgr = owm.weather_manager()
city_id_registry = owm.city_id_registry()


def get_slot(intent: NluIntent, slot_name: str, default=None):
    """extracts the value of a slot"""

    slot = next(filter(lambda slot: slot.slot_name == slot_name, intent.slots),
Ejemplo n.º 12
0
import json, os
import io, configparser

from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp

from dateService import DateService

app = HermesApp("DateApp")


def read_configuration_file():
    try:
        cp = configparser.ConfigParser()
        with io.open(os.getcwd() + "/" + os.path.dirname(__file__) +
                     "/config.ini",
                     encoding="utf-8") as f:
            cp.read_file(f)
        return {
            section:
            {option_name: option
             for option_name, option in cp.items(section)}
            for section in cp.sections()
        }
    except (IOError, configparser.Error):
        return dict()


def read_language_file(language):
    try:
        messages_json_content = open(os.getcwd() + "/" +
Ejemplo n.º 13
0
"""Example app to react to an intent to tell you the time."""
import logging
from datetime import datetime

from rhasspyhermes.nlu import NluIntent

from rhasspyhermes_app import EndSession, HermesApp

_LOGGER = logging.getLogger("TimeApp")

app = HermesApp("TimeApp")


@app.on_intent("GetTime")
def get_time(intent: NluIntent):
    """Tell the time."""
    now = datetime.now().strftime("%H %M")
    return EndSession(f"It's {now}")


app.run()
import json, os
import io, configparser

from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp

from calculator import Calculator

app = HermesApp("CalculatorApp")


def read_configuration_file():
    try:
        cp = configparser.ConfigParser()
        with io.open(os.getcwd() + "/" + os.path.dirname(__file__) +
                     "/config.ini",
                     encoding="utf-8") as f:
            cp.read_file(f)
        return {
            section:
            {option_name: option
             for option_name, option in cp.items(section)}
            for section in cp.sections()
        }
    except (IOError, configparser.Error):
        return dict()


def read_language_file(language):
    try:
        messages_json_content = open(os.getcwd() + "/" +
Ejemplo n.º 15
0
from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp
from rhasspy_weather import weather

_LOGGER = logging.getLogger("SkillListener")


config = configparser.ConfigParser()
config.read('config.ini')
client = config["mqtt"]["client"]
server = config["mqtt"]["server"]
port = config["mqtt"].getint("port")
user = config["mqtt"]["user"]
password = config["mqtt"]["password"]

app = HermesApp(client, host=server, port=port, username=user, password=password)


@app.on_intent("GetTime")
async def get_time(intent: NluIntent):
    """Tell the time."""
    return EndSession(rhasspy_datetime.get_time(config_path=config["rhasspy_datetime"]["config"]))


@app.on_intent("GetDate")
async def get_date(intent: NluIntent):
    """Tell the date."""
    return EndSession(rhasspy_datetime.get_date(config_path=config["rhasspy_datetime"]["config"]))


@app.on_intent("GetWeekday")
Ejemplo n.º 16
0
"""Example app that shows how to continue a session."""
import logging

from rhasspyhermes.nlu import NluIntent

from rhasspyhermes_app import ContinueSession, EndSession, HermesApp

_LOGGER = logging.getLogger("ContinueApp")

app = HermesApp("ContinueApp")


@app.on_intent("Yes")
async def yes(intent: NluIntent):
    """The user confirms."""
    if intent.custom_data == "TurnOffLight":
        response = "OK, turning off the light"
    elif intent.custom_data == "TurnOnLight":
        response = "OK, turning on the light"
    else:
        response = "We can!"

    return EndSession(response)


@app.on_intent("No")
async def no(intent: NluIntent):
    """The user says no."""
    return EndSession()

Ejemplo n.º 17
0
"""Example app to react to an intent to tell you the time."""
import json
import logging

import aiohttp  # pylint: disable=import-error
from rhasspyhermes.nlu import NluIntent

from rhasspyhermes_app import EndSession, HermesApp

_LOGGER = logging.getLogger("AdviceApp")

app = HermesApp("AdviceApp")
"""
This is JUST an example!
None of the authors, contributors, administrators, or anyone else connected with Rhasspy_Hermes_App,
in any way whatsoever, can be responsible for your use of the api endpoint.
"""
URL = "https://api.adviceslip.com/advice"


@app.on_intent("GetAdvice")
async def get_advice(intent: NluIntent):
    """Giving life advice."""
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(URL) as response:
                data = await response.read()
                message = json.loads(data)
                return EndSession(str(message["slip"]["advice"]))
    except aiohttp.ClientConnectionError:
        _LOGGER.exception("No Connection could be established.")
Ejemplo n.º 18
0
import json, os
import io, configparser

from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp

from jokes import Jokes

app = HermesApp("JokesApp")


def read_configuration_file():
    try:
        cp = configparser.ConfigParser()
        with io.open(os.path.dirname(__file__) + "/config.ini",
                     encoding="utf-8") as f:
            cp.read_file(f)
        return {
            section:
            {option_name: option
             for option_name, option in cp.items(section)}
            for section in cp.sections()
        }
    except (IOError, configparser.Error):
        return dict()


def read_language_file(language):
    try:
        with open(os.path.dirname(__file__) + '/' + language + ".json",
                  'r') as myfile:
Ejemplo n.º 19
0
"""Example app using topic for receiving raw MQTT messages."""
import logging

from rhasspyhermes_app import HermesApp, TopicData

_LOGGER = logging.getLogger("RawTopicApp")

app = HermesApp("RawTopicApp")


@app.on_topic("hermes/hotword/{hotword}/detected")
async def test_topic1(data: TopicData, payload: bytes):
    """Receive topic with template."""
    _LOGGER.debug(
        "topic1: %s, hotword: %s, payload: %s",
        data.topic,
        data.data.get("hotword"),
        payload.decode("utf-8"),
    )


@app.on_topic("hermes/dialogueManager/sessionStarted")
async def test_topic2(data: TopicData, payload: bytes):
    """Receive verbatim topic."""
    _LOGGER.debug("topic2: %s, payload: %s", data.topic,
                  payload.decode("utf-8"))


@app.on_topic("hermes/tts/+")
async def test_topic3(data: TopicData, payload: bytes):
    """Receive topic with wildcard."""
Ejemplo n.º 20
0
import json, os
import io, configparser

from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp

from radio import Radio

app = HermesApp("RadioApp")


def read_configuration_file():
    try:
        cp = configparser.ConfigParser()
        with io.open(os.path.dirname(__file__) + "/config.ini",
                     encoding="utf-8") as f:
            cp.read_file(f)
        return {
            section:
            {option_name: option
             for option_name, option in cp.items(section)}
            for section in cp.sections()
        }
    except (IOError, configparser.Error):
        return dict()


def read_language_file(language):
    try:
        print(os.path.dirname(__file__) + '/' + language + '.json')
        with open(os.path.dirname(__file__) + '/' + language + ".json",
Ejemplo n.º 21
0
import asyncio

from rhasspyhermes.nlu import NluIntent
from rhasspyhermes_app import EndSession, HermesApp

#Some Logging Stuff
logger = logging.getLogger("Hermes_Hass_App")
log_stream = logging.StreamHandler()
log_stream.setLevel(logging.WARNING)
logger_format = logging.Formatter(
    '%(filename)s,%(lineno)s - %(levelname)s - %(message)s')
log_stream.setFormatter(logger_format)
logger.addHandler(log_stream)

loop = asyncio.get_event_loop()
app = HermesApp("HassApp")

hass = HassHandler()

services = loop.run_until_complete(hass.ws.fetch_services())


@app.on_intent(['hassapp.' + service for service in services])
def hass_TurnOn(intent: NluIntent):
    try:
        text = hass.handle_service_intent(intent) or None
    except:
        pass
    else:
        text = "Passing no Entity is not yet supported"
    return EndSession(text)