Exemplo n.º 1
0
    def __init__(self, renderer=None):
        try:
            import RPi.GPIO as GPIO
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(17, GPIO.OUT)
            GPIO.setup(27, GPIO.OUT)
            GPIO.setup(22, GPIO.OUT)
        except ImportError:
            print("Only available for devices with GPIO ports ")
        except RuntimeError:
            pass

        recognizer = Recognizer()
        recognizer.dynamic_energy_threshold = False
        recognizer.energy_threshold = 1000
        self.recognizer = recognizer
        self.microphone = Microphone()
        self.susi = susi
        self.renderer = renderer

        try:
            res = requests.get('http://ip-api.com/json').json()
            self.susi.update_location(
                longitude=res['lon'], latitude=res['lat'], country_name=res['country'], country_code=res['countryCode'])

        except ConnectionError as e:
            logging.error(e)

        self.config = json_config.connect('config.json')

        if self.config['usage_mode'] == 'authenticated':
            try:
                susi.sign_in(email=self.config['login_credentials']['email'],
                             password=self.config['login_credentials']['password'])
            except Exception:
                print('Some error occurred in login. Check you login details in config.json')

        if self.config['hotword_engine'] == 'Snowboy':
            from main.hotword_engine.snowboy_detector import SnowboyDetector
            self.hotword_detector = SnowboyDetector()
        else:
            from main.hotword_engine.sphinx_detector import PocketSphinxDetector
            self.hotword_detector = PocketSphinxDetector()

        if self.config['WakeButton'] == 'enabled':
            print("\nSusi has the wake button enabled")
            if self.config['Device'] == 'RaspberryPi':
                print("\nSusi runs on a RaspberryPi")
                from ..hardware_components import RaspberryPiWakeButton
                self.wake_button = RaspberryPiWakeButton()
            else:
                print("\nSusi is not running on a RaspberryPi")
                self.wake_button = None
        else:
            print("\nSusi has the wake button disabled")
            self.wake_button = None
Exemplo n.º 2
0
    def __init__(self, renderer=None):
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(17, GPIO.OUT)
        GPIO.setup(27, GPIO.OUT)
        GPIO.setup(22, GPIO.OUT)

        recognizer = Recognizer()
        recognizer.dynamic_energy_threshold = False
        recognizer.energy_threshold = 1000
        self.recognizer = recognizer
        self.microphone = Microphone()
        self.susi = susi
        self.renderer = renderer

        try:
            res = requests.get('http://ip-api.com/json').json()
            self.susi.update_location(longitude=res['lon'],
                                      latitude=res['lat'])

        except ConnectionError as e:
            logging.error(e)

        self.config = json_config.connect('config.json')

        if self.config['usage_mode'] == 'authenticated':
            try:
                susi.sign_in(
                    email=self.config['login_credentials']['email'],
                    password=self.config['login_credentials']['password'])
            except Exception:
                print(
                    'Some error occurred in login. Check you login details in config.json'
                )

        if self.config['hotword_engine'] == 'Snowboy':
            from main.hotword_engine import SnowboyDetector
            self.hotword_detector = SnowboyDetector()
        else:
            from main.hotword_engine import PocketSphinxDetector
            self.hotword_detector = PocketSphinxDetector()

        if self.config['wake_button'] == 'enabled':
            if self.config['device'] == 'RaspberryPi':
                from ..hardware_components import RaspberryPiWakeButton
                self.wake_button = RaspberryPiWakeButton()
            else:
                self.wake_button = None
        else:
            self.wake_button = None
Exemplo n.º 3
0
    def main(self, args):
        if len(args) == 1:
            print("""
    Usage:
      susi-config get [ key key ... ]
      susi-config set key=value [ key=value ... ]
      susi-config login
    """)
            sys.exit(1)

        try:
            if args[1] == 'set':
                for kv in args[2:]:
                    k, v = kv.split('=', 2)
                    if k in self.keys_conf:
                        pass
                    else:
                        raise ValueError('unknown key', k)
                    self.get_set(k, v)

            elif args[1] == 'get':
                if len(args) == 2:
                    args = list(self.keys_conf.keys())
                else:
                    args = args[2:]
                ret = []
                for k in args:
                    v = self.get_set(k)
                    if type(v) != type('str'):
                        ret.append(k + " = (unset)")
                    else:
                        ret.append(k + " = " + str(v))
                for i in ret:
                    print(i)

            elif args[1] == 'login':
                import susi_python as susi
                susi.sign_in(self.config['login_credentials']['email'],
                             self.config['login_credentials']['password'],
                             room_name=self.config['room_name'])

            else:
                raise ValueError

        except ValueError as ex:
            print('Invalid input', ex, args)
Exemplo n.º 4
0
def sign_in(email, password):
    response = susi.sign_in(email, password)

    # message from server
    message = response.message
    print('Server' 's Message:' + message)

    # session info
    session = response.session
    print_session_info(session)

    # access-token. Access token can be passed as parameter to queries to identify user
    print('access token:' + response.access_token)

    # valid_seconds. Specifies time in seconds for which token is valid
    print('valid time:' + response.valid_seconds)
Exemplo n.º 5
0
    def __init__(self, renderer=None):
        if GPIO:
            try:
                GPIO.setmode(GPIO.BCM)
                GPIO.setup(27, GPIO.OUT)
                GPIO.setup(22, GPIO.OUT)
            except RuntimeError as e:
                logger.error(e)

        thread1 = Thread(target=self.server_checker, name="ServerCheckerThread")
        thread1.daemon = True
        thread1.start()

        recognizer = Recognizer()
        # this was False in the old state machine, but reading the API docs
        # https://github.com/Uberi/speech_recognition/blob/master/reference/library-reference.rst
        # it seems that True is actually better!
        recognizer.dynamic_energy_threshold = True
        recognizer.energy_threshold = 2000
        self.recognizer = recognizer
        self.susi = susi
        self.renderer = renderer
        self.server_url = "https://127.0.0.1:4000"
        self.action_schduler = ActionScheduler()
        self.action_schduler.start()
        self.event_queue = queue.Queue()
        self.idle = True

        try:
            res = requests.get('http://ip-api.com/json').json()
            self.susi.update_location(
                longitude=res['lon'], latitude=res['lat'],
                country_name=res['country'], country_code=res['countryCode'])

        except ConnectionError as e:
            logger.error(e)

        self.susi_config = SusiConfig()
        self.path_base = self.susi_config.get('path.base')
        self.sound_detection = os.path.abspath(
                                   os.path.join(self.path_base,
                                                self.susi_config.get('path.sound.detection')))
        self.sound_problem = os.path.abspath(
                                   os.path.join(self.path_base,
                                                self.susi_config.get('path.sound.problem')))
        self.sound_error_recognition = os.path.abspath(
                                   os.path.join(self.path_base,
                                                self.susi_config.get('path.sound.error.recognition')))
        self.sound_error_timeout = os.path.abspath(
                                   os.path.join(self.path_base,
                                                self.susi_config.get('path.sound.error.timeout')))

        if self.susi_config.get('susi.mode') == 'authenticated':
            try:
                susi.sign_in(email=self.susi_config.get('susi.user'),
                             password=self.susi_config.get('susi.pass'))
            except Exception as e:
                logger.error('Some error occurred in login. Check you login details with susi-config.\n%s', e)

        if self.susi_config.get('hotword.engine') == 'Snowboy':
            from .hotword_engine.snowboy_detector import SnowboyDetector
            hotword_model = "susi.pmdl"
            if self.susi_config.get('hotword.model'):
                logger.debug("Using configured hotword model: " + self.susi_config.get('hotword.model'))
                hotword_model = self.susi_config.get('hotword_model')
            self.hotword_detector = SnowboyDetector(model=hotword_model)
        else:
            from .hotword_engine.sphinx_detector import PocketSphinxDetector
            self.hotword_detector = PocketSphinxDetector()

        if self.susi_config.get('wakebutton') == 'enabled':
            logger.info("Susi has the wake button enabled")
            if self.susi_config.get('device') == 'RaspberryPi':
                logger.info("Susi runs on a RaspberryPi")
                from .hardware_components.rpi_wake_button import RaspberryPiWakeButton
                self.wake_button = RaspberryPiWakeButton()
            else:
                logger.warning("Susi is not running on a RaspberryPi")
                self.wake_button = None
        else:
            logger.warning("Susi has the wake button disabled")
            self.wake_button = None


        if self.susi_config.get('stt') == 'deepspeech-local':
            self.microphone = Microphone(sample_rate=16000)
        else:
            self.microphone = Microphone()

        if self.hotword_detector is not None:
            self.hotword_detector.subject.subscribe(
                on_next=lambda x: self.hotword_detected_callback())
        if self.wake_button is not None:
            self.wake_button.subject.subscribe(
                on_next=lambda x: self.hotword_detected_callback())
        if self.renderer is not None:
            self.renderer.subject.subscribe(
                on_next=lambda x: self.hotword_detected_callback())
        if self.action_schduler is not None:
            self.action_schduler.subject.subscribe(
                on_next=lambda x: self.queue_event(x))
Exemplo n.º 6
0
import json_config

import susi_python as susi


if __name__ == '__main__':
    config = json_config.connect('config.json')
    susi.sign_in(config['login_credentials']['email'], config['login_credentials']['password'], room_name=config['room_name'])
Exemplo n.º 7
0
    def __init__(self, renderer=None):
        try:
            import RPi.GPIO as GPIO
            GPIO.setmode(GPIO.BCM)
            GPIO.setup(27, GPIO.OUT)
            GPIO.setup(22, GPIO.OUT)
        except ImportError:
            logger.warning("This device doesn't have GPIO port")
        except RuntimeError as e:
            logger.error(e)
            pass
        thread1 = Thread(target=self.server_checker, name="Thread1")
        thread1.daemon = True
        thread1.start()

        recognizer = Recognizer()
        recognizer.dynamic_energy_threshold = False
        recognizer.energy_threshold = 1000
        self.recognizer = recognizer
        self.microphone = Microphone()
        self.susi = susi
        self.renderer = renderer
        self.server_url = "https://127.0.0.1:4000"
        self.action_schduler = ActionScheduler()
        self.action_schduler.start()

        try:
            res = requests.get('http://ip-api.com/json').json()
            self.susi.update_location(
                longitude=res['lon'], latitude=res['lat'],
                country_name=res['country'], country_code=res['countryCode'])

        except ConnectionError as e:
            logger.error(e)

        self.config = json_config.connect('config.json')

        if self.config['usage_mode'] == 'authenticated':
            try:
                susi.sign_in(email=self.config['login_credentials']['email'],
                             password=self.config['login_credentials']['password'])
            except Exception as e:
                logger.error('Some error occurred in login. Check you login details in config.json.\n%s', e)

        if self.config['hotword_engine'] == 'Snowboy':
            from ..hotword_engine.snowboy_detector import SnowboyDetector
            self.hotword_detector = SnowboyDetector()
        else:
            from ..hotword_engine.sphinx_detector import PocketSphinxDetector
            self.hotword_detector = PocketSphinxDetector()

        if self.config['WakeButton'] == 'enabled':
            logger.info("Susi has the wake button enabled")
            if self.config['Device'] == 'RaspberryPi':
                logger.info("Susi runs on a RaspberryPi")
                from ..hardware_components import RaspberryPiWakeButton
                self.wake_button = RaspberryPiWakeButton()
            else:
                logger.warning("Susi is not running on a RaspberryPi")
                self.wake_button = None
        else:
            logger.warning("Susi has the wake button disabled")
            self.wake_button = None
Exemplo n.º 8
0
def main(args):
    if len(args) == 1 or args[1] == "-h" or args[1] == "--help":
        usage(0)

    try:
        if args[1] == 'keys':
            cfg = SusiConfig()
            print(
                "Possible keys (if no options listed then the value is free form):"
            )
            for i in cfg.defaults.keys():
                if 'options' in cfg.defaults[i]:
                    print(
                        f"  {i} -- possible values: {', '.join(cfg.defaults[i]['options'])}"
                    )
                else:
                    print(f"  {i}")

        elif args[1] == 'set':
            cfg = SusiConfig()
            ans = ["Values set to:"]
            for kv in args[2:]:
                k, v = kv.split('=', 2)
                if k in cfg.defaults:
                    pass
                else:
                    raise ValueError('unknown key', k)
                newv = cfg.get_set(k, v)
                ans.append(f"  {k} = {newv} (requested {v})")
            print("\n".join(ans))

        elif args[1] == 'get':
            cfg = SusiConfig()
            if len(args) == 2:
                args = list(cfg.defaults.keys())
            else:
                args = args[2:]
            ret = []
            for k in args:
                v = cfg.get_set(k)
                if type(v) != type('str'):
                    ret.append(k + " = (unset)")
                else:
                    ret.append(k + " = " + str(v))
            for i in ret:
                print(i)

        elif args[1] == 'login':
            cfg = SusiConfig()
            if len(args) > 2:
                raise ValueError("too many arguments for action", 'login')
            import susi_python as susi
            susi.sign_in(cfg.config['susi.user'],
                         cfg.config['susi.pass'],
                         room_name=cfg.config['roomname'])

        elif args[1] == 'init':
            if len(args) == 2:
                force = False
            elif len(args) == 3:
                if args[2] == '-f':
                    force = True
                else:
                    raise ValueError("unsupported option to init", args[2])
            else:
                raise ValueError("unsupported options to init", args[2:])

            cfg = SusiConfig()
            for k, v in cfg.defaults.items():
                if force:
                    cfg.config[k] = v['default']
                else:
                    cfg.config.setdefault(k, v['default'])

        # susi-config install links DIR
        # susi-config install desktop user|system
        # susi-config install systemd user|system
        elif args[1] == 'install':
            if len(args) != 4:
                raise ValueError("incorrect invocation of install action",
                                 args[2:])

            if args[2] == 'links':
                if not os.path.exists(args[3]):
                    raise ValueError("target directory not existing", args[3])
                susiai_bin = os.path.realpath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "../../../bin"))
                if not os.path.isdir(susiai_bin):
                    raise ValueError("cannot find SUSI.AI/bin directory",
                                     susiai_bin)
                for f in os.listdir(susiai_bin):
                    os.symlink(os.path.join(susiai_bin, f),
                               os.path.join(args[3], f))

            elif args[2] == 'desktop':
                if args[3] == 'user' or args[3] == 'raspi':
                    destdir = str(Path.home()) + '/.local/share/applications'
                elif args[3] == 'system':
                    destdir = '/usr/local/share/applications'
                else:
                    raise ValueError("unknown mode for install desktop",
                                     args[3])
                susiai_dir = os.path.realpath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "../../.."))
                if not os.path.isdir(susiai_dir):
                    raise ValueError("cannot find SUSI.AI directory",
                                     susiai_dir)
                susi_linux_dir = os.path.join(susiai_dir, 'susi_linux')
                susi_server_dir = os.path.join(susiai_dir, 'susi_server')
                if not os.path.isdir(susi_linux_dir):
                    raise ValueError(
                        "cannot find SUSI.AI susi_linux directory",
                        susi_linux_dir)
                if not os.path.isdir(susi_server_dir):
                    raise ValueError(
                        "cannot find SUSI.AI susi_server directory",
                        susi_server_dir)
                os.makedirs(destdir, exist_ok=True)
                desktop_files = []
                server_desktop_dir = os.path.join(
                    susi_server_dir, "system-integration/desktop")
                linux_desktop_dir = os.path.join(susi_linux_dir,
                                                 "system-integration/desktop")
                for f in os.listdir(server_desktop_dir):
                    if f.endswith("desktop.in"):
                        desktop_files.append(
                            (f[:-3], os.path.join(server_desktop_dir, f)))
                for f in os.listdir(linux_desktop_dir):
                    if f.endswith("desktop.in"):
                        desktop_files.append(
                            (f[:-3], os.path.join(linux_desktop_dir, f)))
                for f, p in desktop_files:
                    sed(p, os.path.join(destdir, f), '@SUSIDIR@', susiai_dir)

            elif args[2] == 'systemd':
                susiai_dir = os.path.realpath(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 "../../.."))
                systemd_system_dir = __run_pkgconfig(
                    "/lib/systemd/system", 'pkg-config', 'systemd',
                    '--variable=systemdsystemunitdir')
                systemd_user_dir = __run_pkgconfig(
                    "/usr/lib/systemd/user", 'pkg-config', 'systemd',
                    '--variable=systemduserunitdir')
                systemd_home_user = str(Path.home()) + "/.config/systemd/user"
                if args[3] == 'user':
                    os.makedirs(systemd_home_user, exist_ok=True)
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_linux/system-integration/systemd/ss-susi-linux.service.in'
                        ),
                        os.path.join(systemd_home_user,
                                     'ss-susi-linux.service'), '@SUSIDIR@',
                        susiai_dir)
                    destfile = os.path.join(systemd_home_user,
                                            'ss-susi-server.service')
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_server/system-integration/systemd/ss-susi-server.service.in'
                        ), destfile, '@SUSIDIR@', susiai_dir)
                    # we need to remove the line with ^User=
                    with open(destfile, "r") as source:
                        lines = source.readlines()
                    with open(destfile, "w") as dest:
                        for line in lines:
                            if not line.startswith('User='******'system':
                    os.makedirs(systemd_system_dir, exist_ok=True)
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_linux/system-integration/systemd/[email protected]'
                        ),
                        os.path.join(systemd_system_dir,
                                     '[email protected]'), '@SUSIDIR@',
                        susiai_dir)
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_linux/system-integration/systemd/ss-susi-linux.service.in'
                        ),
                        os.path.join(systemd_user_dir,
                                     'ss-susi-linux.service'), destfile,
                        '@SUSIDIR@', susiai_dir)
                    destfile = os.path.join(systemd_system_dir,
                                            'ss-susi-server.service')
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_server/system-integration/systemd/ss-susi-server.service.in'
                        ), destfile, '@SUSIDIR@', susiai_dir)
                    # replace @SUSI_SERVER_USER@
                    # TODO make _susi_server configurable!
                    sed(destfile, destfile, '@SUSI_SERVER_USER@',
                        '_susiserver')
                    # TODO do the rest from install.sh
                    #     $SUDOCMD useradd -r -d /nonexistent $SUSI_SERVER_USER
                    #     $SUDOCMD mkdir -p /var/lib/susi-server/data
                    #     $SUDOCMD chown $SUSI_SERVER_USER:$SUSI_SERVER_USER /var/lib/susi-server/data
                    #     $SUDOCMD ln -s /var/lib/susi-server/data susi_server/data
                    #     $SUDOCMD cp ss-susi-server.service $systemdsystem
                    #     $SUDOCMD systemctl daemon-reload || true
                elif args[3] == 'raspi':
                    os.makedirs(systemd_system_dir, exist_ok=True)
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_linux/system-integration/systemd/[email protected]'
                        ),
                        os.path.join(systemd_system_dir,
                                     '[email protected]'), '@SUSIDIR@',
                        susiai_dir)
                    destfile = os.path.join(systemd_system_dir,
                                            'ss-susi-server.service')
                    sed(
                        os.path.join(
                            susiai_dir,
                            'susi_server/system-integration/systemd/ss-susi-server.service.in'
                        ), destfile, '@SUSIDIR@', susiai_dir)
                    sed(destfile, destfile, '@SUSI_SERVER_USER@', 'pi')
                else:
                    raise ValueError
            else:
                raise ValueError("unknown variant of install action", args[2])

        else:
            raise ValueError("unknown action", args[1])

    except ValueError as ex:
        print("Invalid input: ", ex)
        usage(1)