def __init__(self, key_phrase="hey mycroft", config=None, lang="en-us"): self.lang = str(lang).lower() self.key_phrase = str(key_phrase).lower() # rough estimate 1 phoneme per 2 chars self.num_phonemes = len(key_phrase) / 2 + 1 if config is None: config = ConfigurationManager.get().get("hot_words", {}) config = config.get(self.key_phrase, {}) self.config = config self.listener_config = ConfigurationManager.get().get("listener", {})
def main(): global skill_response, wait_response, port, lang wait_response = True skill_response = "" global ws ws = WebsocketClient() event_thread = Thread(target=connect) event_thread.setDaemon(True) event_thread.start() ws.on('speak', handle_speak) import tornado.options tornado.options.parse_command_line() config = ConfigurationManager.get().get("websocket") lang = ConfigurationManager.get().get("lang") port = "9090" url = ("http://" + str(ip) + ":" + str(port)) print("*********************************************************") print("* JCASOFT - Mycroft Web Cliento ") print("*") print("* Access from web browser " + url) print("*********************************************************") routes = [ tornado.web.url(r"/", MainHandler, name="main"), tornado.web.url(r"/static/(.*)", tornado.web.StaticFileHandler, {'path': './'}), tornado.web.url(r"/ws", WebSocketHandler) ] settings = { "debug": True, "template_path": os.path.join(os.path.dirname(__file__), "templates"), "static_path": os.path.join(os.path.dirname(__file__), "static"), } application = tornado.web.Application(routes, **settings) httpServer = tornado.httpserver.HTTPServer(application) tornado.options.parse_command_line() httpServer.listen(port) try: tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: logger.exception(e) event_thread.exit() tornado.ioloop.IOLoop.instance().stop() sys.exit()
def main(): global skill_response, wait_response, port, lang wait_response = True skill_response = "" global ws ws = WebsocketClient() event_thread = Thread(target=connect) event_thread.setDaemon(True) event_thread.start() ws.on('speak', handle_speak) import tornado.options tornado.options.parse_command_line() config = ConfigurationManager.get().get("websocket") lang = ConfigurationManager.get().get("lang") host = config.get("host") port = config.get("port") route = config.get("route") validate_param(host, "websocket.host") validate_param(port, "websocket.port") validate_param(route, "websocket.route") url = "http://" + str(ip)+":"+str(port) print "*********************************************************" print "* Access from web browser " + url print "*********************************************************" routes = [ (route, WebsocketEventHandler), tornado.web.url(r"/", MainHandler, name="main"), tornado.web.url(r"/static/(.*)", tornado.web.StaticFileHandler, {'path': './'}), tornado.web.url(r"/ws", WebSocketHandler) ] settings = { "debug": True, "template_path": os.path.join(os.path.dirname(__file__), "templates"), "static_path": os.path.join(os.path.dirname(__file__), "static"), } application = tornado.web.Application(routes, **settings) httpServer = tornado.httpserver.HTTPServer(application) tornado.options.parse_command_line() httpServer.listen(port) tornado.ioloop.IOLoop.instance().start()
def main(): global ws global config ws = WebsocketClient() ConfigurationManager.init(ws) config = ConfigurationManager.get() speech.init(ws) # Setup control of pulse audio setup_pulseaudio_handlers(config.get('Audio').get('pulseaudio')) def echo(message): try: _message = json.loads(message) if 'mycroft.audio.service' not in _message.get('type'): return message = json.dumps(_message) except: pass LOG.debug(message) LOG.info("Staring Audio Services") ws.on('message', echo) ws.once('open', load_services_callback) try: ws.run_forever() except KeyboardInterrupt, e: LOG.exception(e) speech.shutdown() sys.exit()
def __init__(self, path): self.path = path config = ConfigurationManager().get() config_server = config.get("server") self.url = config_server.get("url") self.version = config_server.get("version") self.identity = IdentityManager.get()
def main(): import tornado.options lock = Lock("service") tornado.options.parse_command_line() def reload_hook(): """ Hook to release lock when autoreload is triggered. """ lock.delete() autoreload.add_reload_hook(reload_hook) config = ConfigurationManager.get().get("websocket") host = config.get("host") port = config.get("port") route = config.get("route") validate_param(host, "websocket.host") validate_param(port, "websocket.port") validate_param(route, "websocket.route") routes = [ (route, WebsocketEventHandler) ] application = web.Application(routes, **settings) application.listen(port, host) ioloop.IOLoop.instance().start()
def __init__(self, directory, name): super(SkillSettings, self).__init__() # when skills try to instantiate settings # in __init__, it can erase the settings saved # on disk (settings.json). So this prevents that # This is set to true in core.py after skill init self.allow_overwrite = False self.api = DeviceApi() self.config = ConfigurationManager.get() self.name = name self.directory = directory # set file paths self._settings_path = join(directory, 'settings.json') self._meta_path = join(directory, 'settingsmeta.json') self.is_alive = True self.loaded_hash = hash(str(self)) self._complete_intialization = False self._device_identity = None self._api_path = None self._user_identity = None self.changed_callback = None # if settingsmeta exist if isfile(self._meta_path): self._poll_skill_settings()
def __init__(self, emitter): FallbackSkill.__init__(self) self.config = ConfigurationManager.get()['padatious'] intent_cache = expanduser(self.config['intent_cache']) try: from padatious import IntentContainer except ImportError: logger.error('Padatious not installed. Please re-run dev_setup.sh') try: call([ 'notify-send', 'Padatious not installed', 'Please run build_host_setup and dev_setup again' ]) except OSError: pass return self.container = IntentContainer(intent_cache) self.emitter = emitter self.emitter.on('padatious:register_intent', self.register_intent) self.register_fallback(self.handle_fallback, 5) self.finished_training_event = Event() self.train_delay = self.config['train_delay'] self.train_time = get_time() + self.train_delay self.wait_and_train()
def main(): global ws global loop global config lock = PIDLock("voice") ws = WebsocketClient() config = ConfigurationManager.get() ConfigurationManager.init(ws) loop = RecognizerLoop() loop.on('recognizer_loop:utterance', handle_utterance) loop.on('speak', handle_speak) loop.on('recognizer_loop:record_begin', handle_record_begin) loop.on('recognizer_loop:wakeword', handle_wakeword) loop.on('recognizer_loop:record_end', handle_record_end) loop.on('recognizer_loop:no_internet', handle_no_internet) ws.on('open', handle_open) ws.on('complete_intent_failure', handle_complete_intent_failure) ws.on('recognizer_loop:sleep', handle_sleep) ws.on('recognizer_loop:wake_up', handle_wake_up) ws.on('mycroft.mic.mute', handle_mic_mute) ws.on('mycroft.mic.unmute', handle_mic_unmute) ws.on("mycroft.paired", handle_paired) ws.on('recognizer_loop:audio_output_start', handle_audio_start) ws.on('recognizer_loop:audio_output_end', handle_audio_end) ws.on('mycroft.stop', handle_stop) event_thread = Thread(target=connect) event_thread.setDaemon(True) event_thread.start() try: loop.run() except KeyboardInterrupt, e: LOG.exception(e) sys.exit()
def __init__(self, path): self.path = path config = ConfigurationManager.get() config_server = config.get("server") self.url = config_server.get("url") self.version = config_server.get("version") self.identity = IdentityManager.get()
def create(): """ Factory method to create a TTS engine based on configuration. The configuration file ``mycroft.conf`` contains a ``tts`` section with the name of a TTS module to be read by this method. "tts": { "module": <engine_name> } """ from mycroft.tts.remote_tts import RemoteTTS config = ConfigurationManager.get().get('tts', {}) module = config.get('module', 'mimic') lang = config.get(module).get('lang') voice = config.get(module).get('voice') clazz = TTSFactory.CLASSES.get(module) if issubclass(clazz, RemoteTTS): url = config.get(module).get('url') tts = clazz(lang, voice, url) else: tts = clazz(lang, voice) tts.validator.validate() return tts
def __init__(self): config_core = ConfigurationManager.get() self.lang = str(self.init_language(config_core)) config_stt = config_core.get("stt", {}) self.config = config_stt.get(config_stt.get("module"), {}) self.credential = self.config.get("credential", {}) self.recognizer = Recognizer()
def __init__(self, emitter): FallbackSkill.__init__(self) self.config = ConfigurationManager.get()['padatious'] intent_cache = expanduser(self.config['intent_cache']) try: from padatious import IntentContainer except ImportError: LOG.error('Padatious not installed. Please re-run dev_setup.sh') try: call([ 'notify-send', 'Padatious not installed', 'Please run build_host_setup and dev_setup again' ]) except OSError: pass return ver = get_distribution('padatious').version if ver != PADATIOUS_VERSION: LOG.warning('Using Padatious v' + ver + '. Please re-run ' + 'dev_setup.sh to install ' + PADATIOUS_VERSION) self.container = IntentContainer(intent_cache) self.emitter = emitter self.emitter.on('padatious:register_intent', self.register_intent) self.emitter.on('padatious:register_entity', self.register_entity) self.register_fallback(self.handle_fallback, 5) self.finished_training_event = Event() self.train_delay = self.config['train_delay'] self.train_time = get_time() + self.train_delay self.wait_and_train()
def __init__(self, directory, name): super(SkillSettings, self).__init__() self.api = DeviceApi() self._device_identity = self.api.identity.uuid self.config = ConfigurationManager.get() self.name = name # set file paths self._settings_path = join(directory, 'settings.json') self._meta_path = join(directory, 'settingsmeta.json') self._api_path = "/" + self._device_identity + "/skill" self.is_alive = True self.loaded_hash = hash(str(self)) # if settingsmeta.json exists # this block of code is a control flow for # different scenarios that may arises with settingsmeta if isfile(self._meta_path): LOG.info("settingsmeta.json exist for {}".format(self.name)) settings_meta = self._load_settings_meta() hashed_meta = hash(str(settings_meta) + str(self._device_identity)) # check if hash is different from the saved hashed if self._is_new_hash(hashed_meta): LOG.info("looks like settingsmeta.json " + "has changed for {}".format(self.name)) # TODO: once the delete api for device is created uncomment if self._uuid_exist(): try: LOG.info("a uuid exist for {}".format(self.name) + " deleting old one") old_uuid = self._load_uuid() self._delete_metatdata(old_uuid) except Exception as e: LOG.info(e) LOG.info("sending settingsmeta.json for {}".format(self.name) + " to home.mycroft.ai") new_uuid = self._send_settings_meta(settings_meta, hashed_meta) self._save_uuid(new_uuid) self._save_hash(hashed_meta) else: # if hash is old found_in_backend = False settings = self._get_remote_settings() # checks backend if the settings have been deleted via webUI for skill in settings: if skill["identifier"] == str(hashed_meta): found_in_backend = True # if it's been deleted from webUI resend if found_in_backend is False: LOG.info("seems like it got deleted from home... " + "sending settingsmeta.json for " + "{}".format(self.name)) new_uuid = self._send_settings_meta( settings_meta, hashed_meta) self._save_uuid(new_uuid) self._save_hash(hashed_meta) t = Timer(60, self._poll_skill_settings, [hashed_meta]) t.daemon = True t.start() self.load_skill_settings()
def _load_config(self): """ Load configuration parameters from configuration """ LOG.info("*********loading configuration") config = ConfigurationManager.get() self.config_core = config self._config_hash = hash(str(config)) self.lang = config.get('lang') self.config = config.get('listener') rate = self.config.get('sample_rate') device_index = self.config.get('device_index') self.microphone = MutableMicrophone(device_index, rate, mute=self.mute_calls > 0) # FIXME - channels are not been used self.microphone.CHANNELS = self.config.get('channels') self.wakeword_recognizer = self.create_wake_word_recognizer( rate, self.lang) # TODO - localization self.wakeup_recognizer = self.create_wakeup_recognizer(rate, self.lang) self.hot_word_engines = {} self.create_hot_word_engines() self.wakeup_recognizer = self.create_wakeup_recognizer(rate, self.lang) self.responsive_recognizer = ResponsiveRecognizer( self.wakeword_recognizer, self.hot_word_engines) self.state = RecognizerLoopState()
def main(): global ws global config global pulse ws = WebsocketClient() ConfigurationManager.init(ws) config = ConfigurationManager.get() speech.init(ws) # Setup control of pulse audio if pulsectl and config.get('Audio').get('pulseaudio') == 'mute': pulse = pulsectl.Pulse('Mycroft-audio-service') else: pulse = None def echo(message): try: _message = json.loads(message) if 'mycroft.audio.service' in _message.get('type'): return message = json.dumps(_message) except: pass logger.debug(message) logger.info("Staring Audio Services") ws.on('message', echo) ws.once('open', load_services_callback) try: ws.run_forever() except KeyboardInterrupt, e: logger.exception(e) speech.shutdown() sys.exit()
def main(): global ws global loop global config lock = PIDLock("voice") ws = WebsocketClient() config = ConfigurationManager.get() ConfigurationManager.init(ws) loop = RecognizerLoop() loop.on('recognizer_loop:utterance', handle_utterance) loop.on('speak', handle_speak) loop.on('recognizer_loop:record_begin', handle_record_begin) loop.on('recognizer_loop:wakeword', handle_wakeword) loop.on('recognizer_loop:record_end', handle_record_end) loop.on('recognizer_loop:no_internet', handle_no_internet) ws.on('open', handle_open) ws.on('complete_intent_failure', handle_complete_intent_failure) ws.on('recognizer_loop:sleep', handle_sleep) ws.on('recognizer_loop:wake_up', handle_wake_up) ws.on('mycroft.mic.mute', handle_mic_mute) ws.on('mycroft.mic.unmute', handle_mic_unmute) ws.on("mycroft.paired", handle_paired) ws.on('recognizer_loop:audio_output_start', handle_audio_start) ws.on('recognizer_loop:audio_output_end', handle_audio_end) ws.on('mycroft.stop', handle_stop) event_thread = Thread(target=connect) event_thread.setDaemon(True) event_thread.start() try: loop.run() except KeyboardInterrupt, e: logger.exception(e) sys.exit()
def __init__(self, emitter): FallbackSkill.__init__(self) self.config = ConfigurationManager.get()['padatious'] intent_cache = expanduser(self.config['intent_cache']) try: from padatious import IntentContainer except ImportError: LOG.error('Padatious not installed. Please re-run dev_setup.sh') try: call(['notify-send', 'Padatious not installed', 'Please run build_host_setup and dev_setup again']) except OSError: pass return ver = get_distribution('padatious').version if ver != PADATIOUS_VERSION: LOG.warning('Using Padatious v' + ver + '. Please re-run ' + 'dev_setup.sh to install ' + PADATIOUS_VERSION) self.container = IntentContainer(intent_cache) self.emitter = emitter self.emitter.on('padatious:register_intent', self.register_intent) self.emitter.on('padatious:register_entity', self.register_entity) self.register_fallback(self.handle_fallback, 5) self.finished_training_event = Event() self.train_delay = self.config['train_delay'] self.train_time = get_time() + self.train_delay self.wait_and_train()
def create_hotword(hotword="hey mycroft", config=None, lang="en-us"): LOG.info("creating " + hotword) if not config: config = ConfigurationManager.get().get("hotwords", {}) module = config.get(hotword).get("module", "pocketsphinx") config = config.get(hotword, {"module": module}) clazz = HotWordFactory.CLASSES.get(module) return clazz(hotword, config, lang=lang)
def __init__(self, hmm=None, lm=None, le_dict=None, lang="en-us", emitter=None, debug=False): self.lang = lang self.decoder = None self.listening = False self.emitter = emitter self.event_thread = None self.async_thread = None # get hmm, already in mycroft self.hmm = MYCROFT_ROOT_PATH + '/mycroft/client/speech/recognizer/model/en-us/hmm/' # load wav config self.audioconfig = ConfigurationManager.get() self.reset_decoder() if not debug: ERROR_HANDLER_FUNC = CFUNCTYPE(None, c_char_p, c_int, c_char_p, c_int, c_char_p) def py_error_handler(filename, line, function, err, fmt): ignores = [0, 2, 16, 77] if err not in ignores: print(err, fmt) c_error_handler = ERROR_HANDLER_FUNC(py_error_handler) @contextmanager def noalsaerr(): asound = cdll.LoadLibrary('libasound.so') asound.snd_lib_error_set_handler(c_error_handler) yield asound.snd_lib_error_set_handler(None) with noalsaerr(): self.p = pyaudio.PyAudio() else: self.p = pyaudio.PyAudio() self.stream = self.p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024) if self.emitter is None: self.emitter = MessageBusClient() def connect(): # Once the websocket has connected, just watch it for events self.emitter.run_forever() self.event_thread = Thread(target=connect) self.event_thread.setDaemon(True) self.event_thread.start() sleep(2)
def __init__(self, emitter, config=None): self.emitter = emitter if config is None: config = ConfigurationManager.get() ConfigurationManager.init(self.emitter) config = config.get("wav_client", {"path": "/tmp/mycroft_in.wav"}) self.config = config self.file_consumer = FileConsumer(file_location=self.config["path"], emitter=self.emitter)
def __init__(self, name, emitter=None): self.name = name self.bind(emitter) self.config_core = ConfigurationManager.get() self.config = self.config_core.get(name) self.dialog_renderer = None self.file_system = FileSystemAccess(join('skills', name)) self.registered_intents = [] self.log = getLogger(name)
def __init__(self): self.iface = pyw.winterfaces()[0] self.ap = AccessPoint(self.iface) self.server = None self.client = WebsocketClient() self.enclosure = EnclosureAPI(self.client) self.config = ConfigurationManager.get().get(self.NAME) self.init_events() self.first_setup()
def initialize(self): self.add_event("mycroft.skills.initialized", self.handle_boot_finished) LOG.debug('add event handle boot finished') config = ConfigurationManager.get() base_conf = config.get('FinishedBootingSkill') if base_conf: self.mp3_file = base_conf.get('startup_mp3', None) else: self.mp3_file = None
def initialize(self): self.tts = ConfigurationManager.get().get("tts").get("module") self.audioservice = AudioService(self.emitter) intent = IntentBuilder('HowUseIntent')\ .require('HowUseKeyword') \ .require('SkillNameKeyword') \ .build() self.register_intent(intent, self.handle_how_use)
def __init_client(self, params): config = ConfigurationManager.get().get("messagebus_client") if not params.host: params.host = config.get('host') if not params.port: params.port = config.get('port') self.client = WebsocketClient(host=params.host, port=params.port, ssl=params.use_ssl)
def __init__(self): resetSelf = False try: self.config = ConfigurationManager.get().get("enclosure") platform = self.config.get('platform') if platform is None: # Use the serial port to check if this is a Mycroft # Mark 1 unit. platform = self.detect_platform() if platform == 'unknown': # Since this is a semi-permanent detection, be # certain! Sometimes noise on the serial line # causes a faulty mis-detection on a real # Mycroft Mark 1 platform = self.detect_platform() ConfigurationManager.set('enclosure', 'platform', platform) # After a platform detection, the system is usually # already active, so the message from the loop # has already gone by on the messagebus. So self reset. resetSelf = True except Exception as e: self.disconnect() raise Exception("Exception: Unable to determine platform\n" + str(e)) LOGGER.info("Platform = '" + platform + "'") if platform == "mycroft_mark_1": # We are a mycroft_mark_1 unit, start up the # enclosure client to communicate over the # serial port self.__init_serial() else: self.disconnect() raise Exception("Exception: Not a Mycroft Mark 1, shutting down") self.client = WebsocketClient() self.reader = EnclosureReader(self.serial, self.client) self.writer = EnclosureWriter(self.serial, self.client) # Create helpers to handle the various parts of the enclosure self.eyes = EnclosureEyes(self.client, self.writer) self.mouth = EnclosureMouth(self.client, self.writer) self.system = EnclosureArduino(self.client, self.writer) # TODO: Remove EnclosureWeather once the Skill can send images # directly to the EnclosureAPI. self.weather = EnclosureWeather(self.client, self.writer) self.__register_events() if resetSelf: self.__handle_reset(None)
def __init__(self): self.ws = WebsocketClient() ConfigurationManager.init(self.ws) self.config = ConfigurationManager.get().get("enclosure") self.__init_serial() self.reader = EnclosureReader(self.serial, self.ws) self.writer = EnclosureWriter(self.serial, self.ws) self.writer.write("system.version") self.ws.on("enclosure.start", self.start) self.started = False Timer(5, self.stop).start() # WHY? This at least needs an explaination, this is non-obvious behavior
def __init_client(self, params): config = ConfigurationManager.get().get("websocket") if not params.host: params.host = config.get('host') if not params.port: params.port = config.get('port') self.ws = WebsocketClient(host=params.host, port=params.port, ssl=params.use_ssl)
def __init__(self): self.ws = WebsocketClient() ConfigurationManager.init(self.ws) self.config = ConfigurationManager.get().get("enclosure") self.__init_serial() self.reader = EnclosureReader(self.serial, self.ws) self.writer = EnclosureWriter(self.serial, self.ws) self.writer.write("system.version") self.ws.on("enclosure.start", self.start) self.started = False Timer(5, self.stop).start() # WHY? This at least
def __init__(self, name=None, emitter=None): self.name = name or self.__class__.__name__ self.bind(emitter) self.config_core = ConfigurationManager.get() self.config = self.config_core.get(self.name) self.dialog_renderer = None self.file_system = FileSystemAccess(join('skills', self.name)) self.registered_intents = [] self.log = getLogger(self.name) self.reload_skill = True self.events = []
def __init__(self): self.ws = WebsocketClient() ConfigurationManager.init(self.ws) self.config = ConfigurationManager.get().get("enclosure") self.__init_serial() self.reader = EnclosureReader(self.serial, self.ws) self.writer = EnclosureWriter(self.serial, self.ws) self.writer.write("system.version") self.ws.on("enclosure.start", self.start) self.started = False Timer(5, self.reconnect).start( ) # WHY? This at least needs an explaination, this is non-obvious behavior
def __init__(self, state, queue, emitter, stt, wakeup_recognizer, wakeword_recognizer): super(AudioConsumer, self).__init__() self.daemon = True self.queue = queue self.state = state self.emitter = emitter self.stt = stt self.wakeup_recognizer = wakeup_recognizer self.wakeword_recognizer = wakeword_recognizer self.metrics = MetricsAggregator() self.config = ConfigurationManager.get() emitter.on("recognizer_loop:hotword", self.set_word)
def __init__(self): self.config_api = ConfigurationManager.get().get("ekylibre_api") self.url = "https://{host}/api/v1/".format( host=self.config_api.get('host')) self.user = self.config_api.get('user') self.password = self.config_api.get('password') # self.token = self.config_api.get('token') self.session = requests.Session() # if self.host: # self.session.headers.update({'Host': self.host}) # self.session.mount("https://", TlsAdapter()) # self.session.verify = False self.auth = None self.get_token()
def __init_client(self, params): config = ConfigurationManager.get().get("websocket") if not params.host: params.host = config.get('host') if not params.port: params.port = config.get('port') self.ws = WebsocketClient(host=params.host, port=params.port, ssl=params.use_ssl) # Connect configuration manager to message bus to receive updates ConfigurationManager.init(self.ws)
def __init_serial(self): try: self.config = ConfigurationManager.get().get("enclosure") self.port = self.config.get("port") self.rate = int(self.config.get("rate")) self.timeout = int(self.config.get("timeout")) self.serial = serial.serial_for_url( url=self.port, baudrate=self.rate, timeout=self.timeout) LOGGER.info( "Connected to: " + self.port + " rate: " + str(self.rate) + " timeout: " + str(self.timeout)) except: LOGGER.error( "It is not possible to connect to serial port: " + self.port) raise
def __init__(self): super(RecognizerLoop, self).__init__() config = ConfigurationManager.get() lang = config.get('lang') self.config = config.get('listener') rate = self.config.get('sample_rate') device_index = self.config.get('device_index') self.microphone = MutableMicrophone(device_index, rate) # FIXME - channels are not been used self.microphone.CHANNELS = self.config.get('channels') self.mycroft_recognizer = self.create_mycroft_recognizer(rate, lang) # TODO - localization self.wakeup_recognizer = self.create_wakeup_recognizer(rate, lang) self.remote_recognizer = ResponsiveRecognizer(self.mycroft_recognizer) self.state = RecognizerLoopState()
def __init__(self, host=None, port=None, route=None, ssl=None): config = ConfigurationManager.get().get("websocket") host = host or config.get("host") port = port or config.get("port") route = route or config.get("route") ssl = ssl or config.get("ssl") validate_param(host, "websocket.host") validate_param(port, "websocket.port") validate_param(route, "websocket.route") self.url = WebsocketClient.build_url(host, port, route, ssl) self.emitter = EventEmitter() self.client = self.create_client() self.pool = ThreadPool(10) self.retry = 5
def load_skills_callback(): global ws load_skills(ws) config = ConfigurationManager.get().get("skills") try: ini_third_party_skills_dir = expanduser(config.get("directory")) except AttributeError as e: logger.warning(e.message) for loc in THIRD_PARTY_SKILLS_DIR: if exists(loc): load_skills(client, loc) if ini_third_party_skills_dir and exists(ini_third_party_skills_dir): load_skills(ws, ini_third_party_skills_dir)
def __init__(self, name=None, emitter=None): self.name = name or self.__class__.__name__ # Get directory of skill self._dir = dirname(abspath(sys.modules[self.__module__].__file__)) self.bind(emitter) self.config_core = ConfigurationManager.get() self.config = self.config_core.get(self.name) self.dialog_renderer = None self.vocab_dir = None self.file_system = FileSystemAccess(join('skills', self.name)) self.registered_intents = [] self.log = LOG.create_logger(self.name) self.reload_skill = True self.events = [] self.skill_id = 0
def main(): import tornado.options tornado.options.parse_command_line() config = ConfigurationManager.get().get("websocket") host = config.get("host") port = config.get("port") route = config.get("route") validate_param(host, "websocket.host") validate_param(port, "websocket.port") validate_param(route, "websocket.route") routes = [ (route, WebsocketEventHandler) ] application = web.Application(routes, **settings) application.listen(port, host) ioloop.IOLoop.instance().start()
def _load_config(self): """ Load configuration parameters from configuration """ config = ConfigurationManager.get() self._config_hash = hash(str(config)) lang = config.get('lang') self.config = config.get('listener') rate = self.config.get('sample_rate') device_index = self.config.get('device_index') self.microphone = MutableMicrophone(device_index, rate) # FIXME - channels are not been used self.microphone.CHANNELS = self.config.get('channels') self.mycroft_recognizer = self.create_mycroft_recognizer(rate, lang) # TODO - localization self.wakeup_recognizer = self.create_wakeup_recognizer(rate, lang) self.remote_recognizer = ResponsiveRecognizer(self.mycroft_recognizer) self.state = RecognizerLoopState()
def init(websocket): """ Start speach related handlers """ global ws global tts global tts_hash global config ws = websocket ConfigurationManager.init(ws) config = ConfigurationManager.get() ws.on('mycroft.stop', handle_stop) ws.on('mycroft.audio.speech.stop', handle_stop) ws.on('speak', handle_speak) tts = TTSFactory.create() tts.init(ws) tts_hash = config.get('tts')
def main(): global ws global loop global config global tts global tts_hash lock = PIDLock("voice") ws = WebsocketClient() config = ConfigurationManager.get() tts = TTSFactory.create() tts.init(ws) tts_hash = config.get('tts') ConfigurationManager.init(ws) loop = RecognizerLoop() loop.on('recognizer_loop:utterance', handle_utterance) loop.on('recognizer_loop:record_begin', handle_record_begin) loop.on('recognizer_loop:wakeword', handle_wakeword) loop.on('recognizer_loop:record_end', handle_record_end) loop.on('speak', handle_speak) loop.on('recognizer_loop:no_internet', handle_no_internet) ws.on('open', handle_open) ws.on('speak', handle_speak) ws.on( 'multi_utterance_intent_failure', handle_multi_utterance_intent_failure) ws.on('recognizer_loop:sleep', handle_sleep) ws.on('recognizer_loop:wake_up', handle_wake_up) ws.on('mycroft.mic.mute', handle_mic_mute) ws.on('mycroft.mic.unmute', handle_mic_unmute) ws.on('mycroft.stop', handle_stop) ws.on("mycroft.paired", handle_paired) event_thread = Thread(target=connect) event_thread.setDaemon(True) event_thread.start() try: loop.run() except KeyboardInterrupt, e: logger.exception(e) event_thread.exit() sys.exit()
def main(): import tornado.options tornado.options.parse_command_line() config = ConfigurationManager.get() service_config = config.get("messagebus_service") route = service_config.get('route') validate_param(route, 'route') routes = [ (route, WebsocketEventHandler) ] application = web.Application(routes, **settings) host = service_config.get("host") port = service_config.get("port") validate_param(host, 'host') validate_param(port, 'port') application.listen(port, host) loop = ioloop.IOLoop.instance() loop.start()
def handle_speak(event): """ Handle "speak" message """ config = ConfigurationManager.get() ConfigurationManager.init(ws) global _last_stop_signal # Mild abuse of the signal system to allow other processes to detect # when TTS is happening. See mycroft.util.is_speaking() utterance = event.data['utterance'] if event.data.get('expect_response', False): ws.once('recognizer_loop:audio_output_end', _trigger_expect_response) # This is a bit of a hack for Picroft. The analog audio on a Pi blocks # for 30 seconds fairly often, so we don't want to break on periods # (decreasing the chance of encountering the block). But we will # keep the split for non-Picroft installs since it give user feedback # faster on longer phrases. # # TODO: Remove or make an option? This is really a hack, anyway, # so we likely will want to get rid of this when not running on Mimic if not config.get('enclosure', {}).get('platform') == "picroft": start = time.time() chunks = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?)\s', utterance) for chunk in chunks: try: mute_and_speak(chunk) except KeyboardInterrupt: raise except: LOG.error('Error in mute_and_speak', exc_info=True) if _last_stop_signal > start or check_for_signal('buttonPress'): break else: mute_and_speak(utterance)
def __init__(self, emitter): self.config = ConfigurationManager.get().get('context', {}) self.engine = IntentDeterminationEngine() self.context_keywords = self.config.get('keywords', ['Location']) self.context_max_frames = self.config.get('max_frames', 3) self.context_timeout = self.config.get('timeout', 2) self.context_greedy = self.config.get('greedy', False) self.context_manager = ContextManager(self.context_timeout) self.emitter = emitter self.emitter.on('register_vocab', self.handle_register_vocab) self.emitter.on('register_intent', self.handle_register_intent) self.emitter.on('recognizer_loop:utterance', self.handle_utterance) self.emitter.on('detach_intent', self.handle_detach_intent) self.emitter.on('detach_skill', self.handle_detach_skill) # Context related handlers self.emitter.on('add_context', self.handle_add_context) self.emitter.on('remove_context', self.handle_remove_context) self.emitter.on('clear_context', self.handle_clear_context) # Converse method self.emitter.on('skill.converse.response', self.handle_converse_response) self.active_skills = [] # [skill_id , timestamp] self.converse_timeout = 5 # minutes to prune active_skills
def send(messageToSend, dataToSend=None): """ Send a single message over the websocket. Args: messageToSend (str): Message to send dataToSend (dict): data structure to go along with the message, defaults to empty dict. """ dataToSend = dataToSend or {} # Calculate the standard Mycroft messagebus websocket address config = ConfigurationManager.get().get("websocket") url = WebsocketClient.build_url(config.get("host"), config.get("port"), config.get("route"), config.get("ssl")) # Send the provided message/data ws = create_connection(url) packet = Message(messageToSend, dataToSend).serialize() ws.send(packet) ws.close()
def load_services_callback(): """ Main callback function for loading services. Sets up the globals service and default and registers the event handlers for the subsystem. """ global ws global default global service config = ConfigurationManager.get().get("Audio") service = load_services(config, ws) LOG.info(service) default_name = config.get('default-backend', '') LOG.info('Finding default backend...') for s in service: LOG.info('checking ' + s.name) if s.name == default_name: default = s LOG.info('Found ' + default.name) break else: default = None LOG.info('no default found') LOG.info('Default:' + str(default)) ws.on('mycroft.audio.service.play', _play) ws.on('mycroft.audio.service.pause', _pause) ws.on('mycroft.audio.service.resume', _resume) ws.on('mycroft.audio.service.stop', _stop) ws.on('mycroft.audio.service.next', _next) ws.on('mycroft.audio.service.prev', _prev) ws.on('mycroft.audio.service.track_info', _track_info) ws.on('recognizer_loop:audio_output_start', _lower_volume) ws.on('recognizer_loop:record_begin', _lower_volume) ws.on('recognizer_loop:audio_output_end', _restore_volume) ws.on('recognizer_loop:record_end', _restore_volume) ws.on('mycroft.stop', _stop)
def create(): """ Factory method to create a TTS engine based on configuration. The configuration file ``defaults.ini`` contains a ``tts`` section with the name of a TTS module to be read by this method. [tts] module = <engine_name> """ logging.basicConfig() config = ConfigurationManager.get().get('tts') name = config.get('module') lang = config.get(name + '.lang', None) voice = config.get(name + '.voice') if name == mimic_tts.NAME: tts = mimic_tts.Mimic(lang, voice) mimic_tts.MimicValidator().validate(tts) elif name == google_tts.NAME: tts = google_tts.GoogleTTS(lang, voice) google_tts.GoogleTTSValidator().validate(tts) elif name == mary_tts.NAME: tts = mary_tts.MaryTTS(lang, voice, config[name + '.url']) mary_tts.MaryTTSValidator().validate(tts) elif name == fa_tts.NAME: tts = fa_tts.FATTS(lang, voice, config[name + '.url']) fa_tts.FATTSValidator().validate(tts) elif name == espeak_tts.NAME: tts = espeak_tts.ESpeak(lang, voice) espeak_tts.ESpeakValidator().validate(tts) else: tts = spdsay_tts.SpdSay(lang, voice) spdsay_tts.SpdSayValidator().validate(tts) return tts
from mycroft.client.speech.listener import RecognizerLoop from mycroft.configuration import ConfigurationManager from mycroft.messagebus.client.ws import WebsocketClient from mycroft.messagebus.message import Message from mycroft.tts import tts_factory from mycroft.util.log import getLogger from mycroft.util import kill, connected logger = getLogger("SpeechClient") client = None tts = tts_factory.create() mutex = Lock() loop = None config = ConfigurationManager.get() def handle_record_begin(): logger.info("Begin Recording...") client.emit(Message('recognizer_loop:record_begin')) def handle_record_end(): logger.info("End Recording...") client.emit(Message('recognizer_loop:record_end')) def handle_wakeword(event): logger.info("Wakeword Detected: " + event['utterance']) client.emit(Message('recognizer_loop:wakeword', event))