def handle_update_intent(self, message): identity = IdentityManager().get() if not identity.owner: self.speak_dialog("not.paired") else: ConfigurationManager.load_remote() self.speak_dialog("config.updated")
def main(): global ws global loop ws = WebsocketClient() tts.init(ws) 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) 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.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(): global ws global loop ws = WebsocketClient() tts.init(ws) 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) 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.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(): 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 main(): global ws lock = Lock('skills') # prevent multiple instances of this service # Connect this Skill management process to the websocket ws = WebsocketClient() ConfigurationManager.init(ws) ignore_logs = ConfigurationManager.instance().get("ignore_logs") # Listen for messages and echo them for logging def _echo(message): try: _message = json.loads(message) if _message.get("type") in ignore_logs: return if _message.get("type") == "registration": # do not log tokens from registration messages _message["data"]["token"] = None message = json.dumps(_message) except: pass LOG('SKILLS').debug(message) ws.on('message', _echo) ws.on('skill.converse.request', handle_converse_request) # Startup will be called after websocket is full live ws.once('open', _starting_up) ws.run_forever()
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 connect(self, event=None): if event and event.metadata: ssid = event.metadata.get("ssid") connected = self.is_connected(ssid) if connected: LOG.warn("Mycroft is already connected to %s" % ssid) else: self.disconnect() LOG.info("Connecting to: %s" % ssid) nid = wpa(self.iface, 'add_network') wpa(self.iface, 'set_network', nid, 'ssid', '"' + ssid + '"') if event.metadata.__contains__("pass"): psk = '"' + event.metadata.get("pass") + '"' wpa(self.iface, 'set_network', nid, 'psk', psk) else: wpa(self.iface, 'set_network', nid, 'key_mgmt', 'NONE') wpa(self.iface, 'enable', nid) connected = self.get_connected(ssid) if connected: wpa(self.iface, 'save_config') ConfigurationManager.set(self.NAME, 'setup', False, True) self.client.emit( Message("mycroft.wifi.connected", {'connected': connected})) LOG.info("Connection status for %s = %s" % (ssid, connected))
def setup(self): must_upload = self.config.get('must_upload') if must_upload is not None and str2bool(must_upload): ConfigurationManager.set('enclosure', 'must_upload', False) time.sleep(5) self.client.emit( Message("speak", metadata={ 'utterance': "I am currently uploading to the arduino." })) self.client.emit( Message("speak", metadata={ 'utterance': "I will be finished in just a moment." })) self.upload_hex() self.client.emit( Message("speak", metadata={'utterance': "Arduino programing complete."})) must_start_test = self.config.get('must_start_test') if must_start_test is not None and str2bool(must_start_test): ConfigurationManager.set('enclosure', 'must_start_test', False) time.sleep(0.5) # Ensure arduino has booted self.client.emit( Message("speak", metadata={'utterance': "Begining hardware self test."})) self.writer.write("test.begin")
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 __init__(self): self.ws = WebsocketClient() ConfigurationManager.init(self.ws) self.config = ConfigurationManager.instance().get("enclosure") self.__init_serial() self.reader = EnclosureReader(self.serial, self.ws) self.writer = EnclosureWriter(self.serial, self.ws) # Send a message to the Arduino across the serial line asking # for a reply with version info. self.writer.write("system.version") # When the Arduino responds, it will generate this message self.ws.on("enclosure.started", self.on_arduino_responded) self.arduino_responded = False # initiates the web sockets on display manager # NOTE: this is a temporary place to initiate display manager sockets initiate_display_manager_ws() # Start a 5 second timer. If the serial port hasn't received # any acknowledgement of the "system.version" within those # 5 seconds, assume there is nothing on the other end (e.g. # we aren't running a Mark 1 with an Arduino) Timer(5, self.check_for_response).start() # Notifications from mycroft-core self.ws.on("enclosure.notify.no_internet", self.on_no_internet)
def main(): global ws lock = Lock('skills') # prevent multiple instances of this service # Connect this Skill management process to the websocket ws = WebsocketClient() ConfigurationManager.init(ws) ignore_logs = ConfigurationManager.instance().get("ignore_logs") # Listen for messages and echo them for logging def _echo(message): try: _message = json.loads(message) if _message.get("type") in ignore_logs: return if _message.get("type") == "registration": # do not log tokens from registration messages _message["data"]["token"] = None message = json.dumps(_message) except: pass logger.debug(message) ws.on('message', _echo) # Kick off loading of skills ws.once('open', _load_skills) ws.run_forever()
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): super(PlatformPatchSkill, self).__init__(name="PlatformPatchSkill") self.platform_type = ConfigurationManager.instance().get( "enclosure").get("platform") self.platform_build = ConfigurationManager.instance().get( "enclosure").get("platform_build") self.timer = None
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 lock = Lock('skills') # prevent multiple instances of this service # Connect this Skill management process to the websocket ws = WebsocketClient() ConfigurationManager.init(ws) ignore_logs = ConfigurationManager.instance().get("ignore_logs") # Listen for messages and echo them for logging def _echo(message): try: _message = json.loads(message) if _message.get("type") in ignore_logs: return if _message.get("type") == "registration": # do not log tokens from registration messages _message["data"]["token"] = None message = json.dumps(_message) except: pass logger.debug(message) ws.on('message', _echo) # Startup will be called after websocket is full live ws.once('open', _starting_up) ws.run_forever()
def run_patch(self, filename): # In brief, the patch: # - Replaces the crontab (run hourly instead of once a day) # - Updates the GPG key for the Mycroft repo # - Bumps the platform_build to '9' self.log.info("Attempting platform patch...") self.cmd('bash ' + filename) ConfigurationManager.load_local() self.platform_build = 9
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 update(self): if self.config.get("update"): try: self.speak("Upgrading enclosure version") subprocess.check_call("/opt/enclosure/upload.sh") self.speak("Enclosure update completed") ConfigurationManager.save({"enclosure": {"update": False}}) except: self.speak("I cannot upgrade right now, I'll try later")
def __init__(self): self.iface = pyw.winterfaces()[0] self.ap = AccessPoint(self.iface) self.server = None self.ws = WebsocketClient() ConfigurationManager.init(self.ws) self.enclosure = EnclosureAPI(self.ws) self.init_events() self.conn_monitor = None self.conn_monitor_stop = threading.Event()
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 __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__(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 setup(self): must_upload = self.config.get('must_upload') if must_upload is not None and str2bool(must_upload): ConfigurationManager.set('enclosure', 'must_upload', False) self.upload_hex() must_start_test = self.config.get('must_start_test') if must_start_test is not None and str2bool(must_start_test): ConfigurationManager.set('enclosure', 'must_start_test', False) time.sleep(0.5) # Ensure arduino has booted self.writer.write("test.begin")
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): 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 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 __init__(self): self.ws = WebsocketClient() self.ws.on("open", self.on_ws_open) ConfigurationManager.init(self.ws) self.config = ConfigurationManager.instance().get("enclosure") self.__init_serial() self.reader = EnclosureReader(self.serial, self.ws) self.writer = EnclosureWriter(self.serial, self.ws) # initiates the web sockets on display manager # NOTE: this is a temporary place to initiate display manager sockets initiate_display_manager_ws()
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 __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__(self, args): params = self.__build_params(args) if params.config: ConfigurationManager.load_local([params.config]) if exists(params.lib) and isdir(params.lib): sys.path.append(params.lib) sys.path.append(params.dir) self.dir = params.dir self.enable_intent = params.enable_intent self.__init_client(params)
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 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, 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__() # 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 get(phrase, lang=None, context=None): """ Looks up a resource file for the given phrase. If no file is found, the requested phrase is returned as the string. This will use the default language for translations. Args: phrase (str): resource phrase to retrieve/translate lang (str): the language to use context (dict): values to be inserted into the string Returns: str: a randomized and/or translated version of the phrase """ if not lang: from mycroft.configuration import ConfigurationManager lang = ConfigurationManager.instance().get("lang") filename = "text/"+lang.lower()+"/"+phrase+".dialog" template = resolve_resource_file(filename) if not template: logger.debug("Resource file not found: " + filename) return phrase stache = MustacheDialogRenderer() stache.load_template_file("template", template) if not context: context = {} return stache.render("template", context)
def __init__(self, wake_word_recognizer): self.config = ConfigurationManager.instance() listener_config = self.config.get('listener') self.upload_config = listener_config.get('wake_word_upload') self.wake_word_name = listener_config['wake_word'] # The maximum audio in seconds to keep for transcribing a phrase # The wake word must fit in this time num_phonemes = wake_word_recognizer.num_phonemes len_phoneme = listener_config.get('phoneme_duration', 120) / 1000.0 self.TEST_WW_SEC = int(num_phonemes * len_phoneme) self.SAVED_WW_SEC = (10 if self.upload_config['enable'] else self.TEST_WW_SEC) speech_recognition.Recognizer.__init__(self) self.wake_word_recognizer = wake_word_recognizer self.audio = pyaudio.PyAudio() self.multiplier = listener_config.get('multiplier') self.energy_ratio = listener_config.get('energy_ratio') # check the config for the flag to save wake words. self.save_utterances = listener_config.get('record_utterances', False) self.save_wake_words = listener_config.get('record_wake_words') \ or self.upload_config['enable'] or self.config['opt_in'] self.upload_lock = Lock() self.save_wake_words_dir = join(gettempdir(), 'mycroft_wake_words') self.filenames_to_upload = [] self.mic_level_file = os.path.join(get_ipc_directory(), "mic_level") self._stop_signaled = False
def __init__(self, wake_word_recognizer, hot_word_engines=None): if hot_word_engines is None: hot_word_engines = {} self.config = ConfigurationManager.instance() listener_config = self.config.get('listener') self.upload_config = listener_config.get('wake_word_upload') self.wake_word_name = listener_config['wake_word'] # The maximum audio in seconds to keep for transcribing a phrase # The wake word must fit in this time num_phonemes = wake_word_recognizer.num_phonemes len_phoneme = listener_config.get('phoneme_duration', 120) / 1000.0 self.TEST_WW_SEC = int(num_phonemes * len_phoneme) self.SAVED_WW_SEC = (10 if self.upload_config['enable'] else self.TEST_WW_SEC) speech_recognition.Recognizer.__init__(self) self.wake_word_recognizer = wake_word_recognizer self.audio = pyaudio.PyAudio() self.multiplier = listener_config.get('multiplier') self.energy_ratio = listener_config.get('energy_ratio') # check the config for the flag to save wake words. self.save_utterances = listener_config.get('record_utterances', False) self.save_wake_words = listener_config.get('record_wake_words', False) \ or self.upload_config['enable'] or self.config['opt_in'] self.upload_lock = Lock() self.save_wake_words_dir = join(gettempdir(), 'mycroft_wake_words') self.filenames_to_upload = [] self.mic_level_file = os.path.join(get_ipc_directory(), "mic_level") self._stop_signaled = False self.hot_word_engines = hot_word_engines
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, 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 setup(self): must_upload = self.config.get('must_upload') if must_upload is not None and str2bool(must_upload): ConfigurationManager.set('enclosure', 'must_upload', False) time.sleep(5) self.client.emit(Message("speak", metadata={ 'utterance': "I am currently uploading to the arduino."})) self.client.emit(Message("speak", metadata={ 'utterance': "I will be finished in just a moment."})) self.upload_hex() must_start_test = self.config.get('must_start_test') if must_start_test is not None and str2bool(must_start_test): ConfigurationManager.set('enclosure', 'must_start_test', False) time.sleep(0.5) # Ensure arduino has booted self.writer.write("test.begin")
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, 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(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 ws = WebsocketClient() ConfigurationManager.init(ws) def echo(message): try: _message = json.loads(message) if _message.get("type") == "registration": # do not log tokens from registration messages _message["data"]["token"] = None message = json.dumps(_message) except: pass logger.debug(message) ws.on('message', echo) ws.once('open', load_skills_callback) ws.run_forever()
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 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 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_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): self.ws = WebsocketClient() ConfigurationManager.init(self.ws) self.config = ConfigurationManager.instance().get("enclosure") self.__init_serial() self.reader = EnclosureReader(self.serial, self.ws) self.writer = EnclosureWriter(self.serial, self.ws) # Send a message to the Arduino across the serial line asking # for a reply with version info. self.writer.write("system.version") # When the Arduino responds, it will generate this message self.ws.on("enclosure.started", self.on_arduino_responded) self.arduino_responded = False # Start a 5 second timer. If the serial port hasn't received # any acknowledgement of the "system.version" within those # 5 seconds, assume there is nothing on the other end (e.g. # we aren't running a Mark 1 with an Arduino) Timer(5, self.check_for_response).start() # Notifications from mycroft-core self.ws.on("enclosure.notify.no_internet", self.on_no_internet)