Example #1
0
 def get_config(cls):
     # FIXME: Replace this as soon as we have a config module
     config = {}
     # HMM dir
     # Try to get hmm_dir from config
     profile_path = jasperpath.config('profile.yml')
     if os.path.exists(profile_path):
         with open(profile_path, 'r') as f:
             profile = yaml.safe_load(f)
             if 'ivona-tts' in profile:
                 if 'access_key' in profile['ivona-tts']:
                     config['access_key'] = \
                         profile['ivona-tts']['access_key']
                 if 'secret_key' in profile['ivona-tts']:
                     config['secret_key'] = \
                         profile['ivona-tts']['secret_key']
                 if 'region' in profile['ivona-tts']:
                     config['region'] = profile['ivona-tts']['region']
                 if 'voice' in profile['ivona-tts']:
                     config['voice'] = profile['ivona-tts']['voice']
                 if 'speech_rate' in profile['ivona-tts']:
                     config['speech_rate'] = \
                         profile['ivona-tts']['speech_rate']
                 if 'sentence_break' in profile['ivona-tts']:
                     config['sentence_break'] = \
                         profile['ivona-tts']['sentence_break']
     return config
    def _compile_vocabulary(self, phrases):
        prefix = 'jasper'
        tmpdir = tempfile.mkdtemp()

        lexicon_file = jasperpath.data('julius-stt', 'VoxForge.tgz')
        lexicon_archive_member = 'VoxForge/VoxForgeDict'
        profile_path = jasperpath.config('profile.yml')
        if os.path.exists(profile_path):
            with open(profile_path, 'r') as f:
                profile = yaml.safe_load(f)
                if 'julius' in profile:
                    if 'lexicon' in profile['julius']:
                        lexicon_file = profile['julius']['lexicon']
                    if 'lexicon_archive_member' in profile['julius']:
                        lexicon_archive_member = \
                            profile['julius']['lexicon_archive_member']

        lexicon = JuliusVocabulary.VoxForgeLexicon(lexicon_file,
                                                   lexicon_archive_member)

        # Create grammar file
        tmp_grammar_file = os.path.join(tmpdir,
                                        os.extsep.join([prefix, 'grammar']))
        with open(tmp_grammar_file, 'w') as f:
            grammar = self._get_grammar(phrases)
            for definition in grammar.pop('S'):
                f.write("%s: %s\n" % ('S', ' '.join(definition)))
            for name, definitions in grammar.items():
                for definition in definitions:
                    f.write("%s: %s\n" % (name, ' '.join(definition)))

        # Create voca file
        tmp_voca_file = os.path.join(tmpdir, os.extsep.join([prefix, 'voca']))
        with open(tmp_voca_file, 'w') as f:
            for category, words in self._get_word_defs(lexicon,
                                                       phrases).items():
                f.write("%% %s\n" % category)
                for word, phoneme in words:
                    f.write("%s\t\t\t%s\n" % (word, phoneme))

        # mkdfa.pl
        olddir = os.getcwd()
        os.chdir(tmpdir)
        cmd = ['mkdfa.pl', str(prefix)]
        with tempfile.SpooledTemporaryFile() as out_f:
            subprocess.call(cmd, stdout=out_f, stderr=out_f)
            out_f.seek(0)
            for line in out_f.read().splitlines():
                line = line.strip()
                if line:
                    self._logger.debug(line)
        os.chdir(olddir)

        tmp_dfa_file = os.path.join(tmpdir, os.extsep.join([prefix, 'dfa']))
        tmp_dict_file = os.path.join(tmpdir, os.extsep.join([prefix, 'dict']))
        shutil.move(tmp_dfa_file, self.dfa_file)
        shutil.move(tmp_dict_file, self.dict_file)

        shutil.rmtree(tmpdir)
Example #3
0
    def __init__(self):
        self._logger = logging.getLogger(__name__)

        # Create config dir if it does not exist yet
        if not os.path.exists(jasperpath.CONFIG_PATH):
            try:
                os.makedirs(jasperpath.CONFIG_PATH)
            except OSError:
                self._logger.error("Could not create config dir: '%s'",
                                   jasperpath.CONFIG_PATH,
                                   exc_info=True)
                raise

        # Check if config dir is writable
        if not os.access(jasperpath.CONFIG_PATH, os.W_OK):
            self._logger.critical(
                "Config dir %s is not writable. Jasper " +
                "won't work correctly.", jasperpath.CONFIG_PATH)

        configfile = jasperpath.config('profile.yml')

        # Read config
        self._logger.debug("Trying to read config file: '%s'", configfile)
        try:
            with open(configfile, "r") as f:
                self.config = yaml.safe_load(f)
        except OSError:
            self._logger.error("Can't open config file: '%s'", configfile)
            raise

        try:
            stt_engine_slug = self.config['stt_engine']
        except KeyError:
            stt_engine_slug = 'sphinx'
            logger.warning(
                "stt_engine not specified in profile, defaulting " + "to '%s'",
                stt_engine_slug)
        stt_engine_class = stt.get_engine_by_slug(stt_engine_slug)

        try:
            slug = self.config['stt_passive_engine']
            stt_passive_engine_class = stt.get_engine_by_slug(slug)
        except KeyError:
            stt_passive_engine_class = stt_engine_class

        try:
            tts_engine_slug = self.config['tts_engine']
        except KeyError:
            tts_engine_slug = tts.get_default_engine_slug()
            logger.warning(
                "tts_engine not specified in profile, defaulting " + "to '%s'",
                tts_engine_slug)
        tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)

        # Initialize Mic
        self.mic = Mic(tts_engine_class.get_instance(),
                       stt_passive_engine_class.get_passive_instance(),
                       stt_engine_class.get_active_instance())
Example #4
0
  def __init__(self):

    self.profile_path = jasperpath.config('profile.yml')
    if os.path.exists(self.profile_path):
      with open(self.profile_path, 'r') as f:
        self.profile = yaml.safe_load(f)

    threading.Thread.__init__(self)
    self.start()
Example #5
0
 def get_instance(cls, vocabulary_name, phrases):
     config = cls.get_config()
     if cls.VOCABULARY_TYPE:
         vocabulary = cls.VOCABULARY_TYPE(
             vocabulary_name, path=jasperpath.config('vocabularies'))
         if not vocabulary.matches_phrases(phrases):
             vocabulary.compile(phrases)
         config['vocabulary'] = vocabulary
     instance = cls(**config)
     return instance
Example #6
0
 def get_instance(cls, vocabulary_name, phrases):
     config = cls.get_config()
     if cls.VOCABULARY_TYPE:
         vocabulary = cls.VOCABULARY_TYPE(vocabulary_name,
                                          path=jasperpath.config(
                                              'vocabularies'))
         if not vocabulary.matches_phrases(phrases):
             vocabulary.compile(phrases)
         config['vocabulary'] = vocabulary
     instance = cls(**config)
     return instance
Example #7
0
 def get_config(cls):
     # FIXME: Replace this as soon as we have a config module
     config = {}
     # HMM dir
     # Try to get hmm_dir from config
     profile_path = jasperpath.config('profile.yml')
     if os.path.exists(profile_path):
         with open(profile_path, 'r') as f:
             profile = yaml.safe_load(f)
             if 'keys' in profile and 'GOOGLE_SPEECH' in profile['keys']:
                 config['api_key'] = profile['keys']['GOOGLE_SPEECH']
     return config
Example #8
0
    def get_config(cls):
        # FIXME: Replace this as soon as we have a config module
        config = {}
        # HMM dir
        # Try to get hmm_dir from config
        profile_path = jasperpath.config('profile.yml')
        if os.path.exists(profile_path):
            with open(profile_path, 'r') as f:
                profile = yaml.safe_load(f)
                if 'pico-tts' in profile and 'language' in profile['pico-tts']:
                    config['language'] = profile['pico-tts']['language']

        return config
Example #9
0
 def get_config(cls):
     # FIXME: Replace this as soon as we have a config module
     config = {}
     # Try to get wit.ai Auth token from config
     profile_path = jasperpath.config('profile.yml')
     if os.path.exists(profile_path):
         with open(profile_path, 'r') as f:
             profile = yaml.safe_load(f)
             if 'witai-stt' in profile:
                 if 'access_token' in profile['witai-stt']:
                     config['access_token'] = \
                         profile['witai-stt']['access_token']
     return config
Example #10
0
 def get_config(cls):
     # FIXME: Replace this as soon as we have a config module
     config = {}
     # Try to get AT&T app_key/app_secret from config
     profile_path = jasperpath.config('profile.yml')
     if os.path.exists(profile_path):
         with open(profile_path, 'r') as f:
             profile = yaml.safe_load(f)
             if 'att-stt' in profile:
                 if 'app_key' in profile['att-stt']:
                     config['app_key'] = profile['att-stt']['app_key']
                 if 'app_secret' in profile['att-stt']:
                     config['app_secret'] = profile['att-stt']['app_secret']
     return config
Example #11
0
    def get_config(cls):
        # FIXME: Replace this as soon as pull request
        # jasperproject/jasper-client#128 has been merged

        conf = {"fst_model": os.path.join(jasperpath.APP_PATH, os.pardir, "phonetisaurus", "g014b2b.fst")}
        # Try to get fst_model from config
        profile_path = jasperpath.config("profile.yml")
        if os.path.exists(profile_path):
            with open(profile_path, "r") as f:
                profile = yaml.safe_load(f)
                if "pocketsphinx" in profile:
                    if "fst_model" in profile["pocketsphinx"]:
                        conf["fst_model"] = profile["pocketsphinx"]["fst_model"]
                    if "nbest" in profile["pocketsphinx"]:
                        conf["nbest"] = int(profile["pocketsphinx"]["nbest"])
        return conf
Example #12
0
    def get_config(cls):
        # FIXME: Replace this as soon as we have a config module
        config = {}
        # HMM dir
        # Try to get hmm_dir from config
        profile_path = jasperpath.config('profile.yml')

        if os.path.exists(profile_path):
            with open(profile_path, 'r') as f:
                profile = yaml.safe_load(f)
                try:
                    config['hmm_dir'] = profile['pocketsphinx']['hmm_dir']
                except KeyError:
                    pass

        return config
Example #13
0
 def get_config(cls):
     # FIXME: Replace this as soon as we have a config module
     config = {}
     # Try to get baidu_yuyin config from config
     profile_path = jasperpath.config('profile.yml')
     if os.path.exists(profile_path):
         with open(profile_path, 'r') as f:
             profile = yaml.safe_load(f)
             if 'baidu_yuyin' in profile:
                 if 'api_key' in profile['baidu_yuyin']:
                     config['api_key'] = \
                         profile['baidu_yuyin']['api_key']
                 if 'secret_key' in profile['baidu_yuyin']:
                     config['secret_key'] = \
                         profile['baidu_yuyin']['secret_key']
     return config
Example #14
0
    def get_config(cls):
        # FIXME: Replace this as soon as we have a config module
        config = {}
        # HMM dir
        # Try to get hmm_dir from config
        profile_path = jasperpath.config('profile.yml')

        if os.path.exists(profile_path):
            with open(profile_path, 'r') as f:
                profile = yaml.safe_load(f)
                try:
                    config['hmm_dir'] = profile['pocketsphinx']['hmm_dir']
                except KeyError:
                    pass

        return config
Example #15
0
    def get_config(cls):
        # FIXME: Replace this as soon as we have a config module
        config = {}
        # HMM dir
        # Try to get hmm_dir from config
        profile_path = jasperpath.config('profile.yml')

        if os.path.exists(profile_path):
            with open(profile_path, 'r') as f:
                profile = yaml.safe_load(f)
                if 'julius' in profile:
                    if 'hmmdefs' in profile['julius']:
                        config['hmmdefs'] = profile['julius']['hmmdefs']
                    if 'tiedlist' in profile['julius']:
                        config['tiedlist'] = profile['julius']['tiedlist']
        return config
Example #16
0
def run(start, end, input, mic=None):
    wpm = computeWpm(start, end, input, mic)
    
    wpm_file = jasperpath.config("wpm.txt")
    if os.path.isfile(wpm_file):
        with open(wpm_file, "r") as f:
            wpms = [float(value) for value in f.readlines()]
    else:
        wpms = []
    
    wpms.append(wpm)
    wilko = sum(wpms) / float(len(wpms))
    message = "The current Wilko is %1.2f words per minute" %wilko
    print message
    if mic:
        mic.say(message)
        
    with open(wpm_file, "a") as f:
        f.write(str(wpm) + "\n")
Example #17
0
 def get_config(cls):
     # FIXME: Replace this as soon as we have a config module
     config = {}
     # HMM dir
     # Try to get hmm_dir from config
     profile_path = jasperpath.config('profile.yml')
     if os.path.exists(profile_path):
         with open(profile_path, 'r') as f:
             profile = yaml.safe_load(f)
             if 'espeak-tts' in profile:
                 if 'voice' in profile['espeak-tts']:
                     config['voice'] = profile['espeak-tts']['voice']
                 if 'pitch_adjustment' in profile['espeak-tts']:
                     config['pitch_adjustment'] = \
                         profile['espeak-tts']['pitch_adjustment']
                 if 'words_per_minute' in profile['espeak-tts']:
                     config['words_per_minute'] = \
                         profile['espeak-tts']['words_per_minute']
     return config
Example #18
0
    def get_config(cls):
        # FIXME: Replace this as soon as pull request
        # jasperproject/jasper-client#128 has been merged

        conf = {
            'fst_model':
            os.path.join(jasperpath.APP_PATH, os.pardir, 'phonetisaurus',
                         'g014b2b.fst')
        }
        # Try to get fst_model from config
        profile_path = jasperpath.config('profile.yml')
        if os.path.exists(profile_path):
            with open(profile_path, 'r') as f:
                profile = yaml.safe_load(f)
                if 'pocketsphinx' in profile:
                    if 'fst_model' in profile['pocketsphinx']:
                        conf['fst_model'] = \
                            profile['pocketsphinx']['fst_model']
                    if 'nbest' in profile['pocketsphinx']:
                        conf['nbest'] = int(profile['pocketsphinx']['nbest'])
        return conf
Example #19
0
    def __init__(self):
        self._logger = logging.getLogger(__name__)

        # Create config dir if it does not exist yet
        if not os.path.exists(jasperpath.CONFIG_PATH):
            try:
                os.makedirs(jasperpath.CONFIG_PATH)
            except OSError:
                self._logger.error("Could not create config dir: '%s'",
                                   jasperpath.CONFIG_PATH, exc_info=True)
                raise

        # Check if config dir is writable
        if not os.access(jasperpath.CONFIG_PATH, os.W_OK):
            self._logger.critical("Config dir %s is not writable. Jasper " +
                                  "won't work correctly.",
                                  jasperpath.CONFIG_PATH)

        # FIXME: For backwards compatibility, move old config file to newly
        #        created config dir
        old_configfile = os.path.join(jasperpath.LIB_PATH, 'profile.yml')
        new_configfile = jasperpath.config('profile.yml')
        if os.path.exists(old_configfile):
            if os.path.exists(new_configfile):
                self._logger.warning("Deprecated profile file found: '%s'. " +
                                     "Please remove it.", old_configfile)
            else:
                self._logger.warning("Deprecated profile file found: '%s'. " +
                                     "Trying to copy it to new location '%s'.",
                                     old_configfile, new_configfile)
                try:
                    shutil.copy2(old_configfile, new_configfile)
                except shutil.Error:
                    self._logger.error("Unable to copy config file. " +
                                       "Please copy it manually.",
                                       exc_info=True)
                    raise

        # Read config
        self._logger.debug("Trying to read config file: '%s'", new_configfile)
        try:
            with open(new_configfile, "r") as f:
                self.config = yaml.safe_load(f)
        except OSError:
            self._logger.error("Can't open config file: '%s'", new_configfile)
            raise

        try:
            stt_engine_slug = self.config['stt_engine']
        except KeyError:
            stt_engine_slug = 'sphinx'
            logger.warning("stt_engine not specified in profile, defaulting " +
                           "to '%s'", stt_engine_slug)
        stt_engine_class = stt.get_engine_by_slug(stt_engine_slug)

        try:
            slug = self.config['stt_passive_engine']
            stt_passive_engine_class = stt.get_engine_by_slug(slug)
        except KeyError:
            stt_passive_engine_class = stt_engine_class

        try:
            tts_engine_slug = self.config['tts_engine']
        except KeyError:
            tts_engine_slug = tts.get_default_engine_slug()
            logger.warning("tts_engine not specified in profile, defaulting " +
                           "to '%s'", tts_engine_slug)
        tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)

        # Initialize Mic
        self.mic = Mic(tts_engine_class.get_instance(),
                       stt_passive_engine_class.get_passive_instance(),
                       stt_engine_class.get_active_instance())
Example #20
0
    def __init__(self):
        self._logger = logging.getLogger(__name__)
        
        # Create config dir if it does not exist yet
        if not os.path.exists(jasperpath.CONFIG_PATH):
            try:
                os.makedirs(jasperpath.CONFIG_PATH)
            except OSError:
                self._logger.error("Could not create config dir: '%s'", jasperpath.CONFIG_PATH, exc_info=True)
                raise

        # Check if config dir is writable
        if not os.access(jasperpath.CONFIG_PATH, os.W_OK):
            self._logger.critical("Config dir %s is not writable. Jasper won't work correctly.")

        # FIXME: For backwards compatibility, move old config file to newly created config dir
        old_configfile = os.path.join(jasperpath.LIB_PATH, 'profile.yml')
        new_configfile = jasperpath.config('profile.yml')
        if os.path.exists(old_configfile):
            if os.path.exists(new_configfile):
                self._logger.warning("Deprecated profile file found: '%s'. Please remove it.", old_configfile)
            else:
                self._logger.warning("Deprecated profile file found: '%s'. Trying to copy it to new location '%s'.", old_configfile, new_configfile)
                try:
                    shutil.copy2(old_configfile, new_configfile)
                except shutil.Error:
                    self._logger.error("Unable to copy config file. Please copy it manually.", exc_info=True)
                    raise

        # Read config
        self._logger.debug("Trying to read config file: '%s'", new_configfile)
        try:
            with open(new_configfile, "r") as f:
                self.config = yaml.safe_load(f)
        except OSError:
            self._logger.error("Can't open config file: '%s'", new_configfile)
            raise

        try:
            api_key = self.config['keys']['GOOGLE_SPEECH']
        except KeyError:
            api_key = None

        try:
            stt_engine_type = self.config['stt_engine']
        except KeyError:
            stt_engine_type = "sphinx"
            self._logger.warning("stt_engine not specified in profile, defaulting to '%s'", stt_engine_type)

        try:
            tts_engine_slug = self.config['tts_engine']
        except KeyError:
            tts_engine_slug = tts.get_default_engine_slug()
            logger.warning("tts_engine not specified in profile, defaulting to '%s'", tts_engine_slug)
        tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)

        # Compile dictionary
        sentences, dictionary, languagemodel = [jasperpath.config(filename) for filename in ("sentences.txt", "dictionary.dic", "languagemodel.lm")]
        vocabcompiler.compile(sentences, dictionary, languagemodel)

        # Initialize Mic
        self.mic = Mic(tts_engine_class(), stt.PocketSphinxSTT(), stt.newSTTEngine(stt_engine_type, api_key=api_key))
    def __init__(self):
        self._logger = logging.getLogger(__name__)

        # Create config dir if it does not exist yet
        if not os.path.exists(jasperpath.CONFIG_PATH):
            try:
                os.makedirs(jasperpath.CONFIG_PATH)
            except OSError:
                self._logger.error("Could not create config dir: '%s'",
                                   jasperpath.CONFIG_PATH, exc_info=True)
                raise

        # Check if config dir is writable
        if not os.access(jasperpath.CONFIG_PATH, os.W_OK):
            self._logger.critical("Config dir %s is not writable. Jasper " +
                                  "won't work correctly.",
                                  jasperpath.CONFIG_PATH)

        # FIXME: For backwards compatibility, move old config file to newly
        #        created config dir
        old_configfile = os.path.join(jasperpath.LIB_PATH, 'profile.yml')
        new_configfile = jasperpath.config('profile.yml')
        if os.path.exists(old_configfile):
            if os.path.exists(new_configfile):
                self._logger.warning("Deprecated profile file found: '%s'. " +
                                     "Please remove it.", old_configfile)
            else:
                self._logger.warning("Deprecated profile file found: '%s'. " +
                                     "Trying to copy it to new location '%s'.",
                                     old_configfile, new_configfile)
                try:
                    shutil.copy2(old_configfile, new_configfile)
                except shutil.Error:
                    self._logger.error("Unable to copy config file. " +
                                       "Please copy it manually.",
                                       exc_info=True)
                    raise

        # Read config
        self._logger.debug("Trying to read config file: '%s'", new_configfile)
        try:
            with open(new_configfile, "r") as f:
                self.config = yaml.safe_load(f)
        except OSError:
            self._logger.error("Can't open config file: '%s'", new_configfile)
            raise

        try:
            stt_engine_slug = self.config['stt_engine']
        except KeyError:
            stt_engine_slug = 'sphinx'
            logger.warning("stt_engine not specified in profile, defaulting " +
                           "to '%s'", stt_engine_slug)
        stt_engine_class = stt.get_engine_by_slug(stt_engine_slug)

        try:
            slug = self.config['stt_passive_engine']
            stt_passive_engine_class = stt.get_engine_by_slug(slug)
        except KeyError:
            stt_passive_engine_class = stt_engine_class

        try:
            tts_engine_slug = self.config['tts_engine']
        except KeyError:
            tts_engine_slug = tts.get_default_engine_slug()
            logger.warning("tts_engine not specified in profile, defaulting " +
                           "to '%s'", tts_engine_slug)
        tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)

        # Initialize Mic
        self.mic = Mic(tts_engine_class.get_instance(),
                       stt_passive_engine_class.get_passive_instance(),
                       stt_engine_class.get_active_instance())
 def save_profile(self):
     output_file = open(jasperpath.config('profile.yml'), 'w')
     yaml.dump(self.profile, output_file, default_flow_style=False)
def getNewProfile(mic, profile):
	
	#This line bug !
	mic.say('Who are you?')
	input = raw_input("Your name : ")
	
	if input=='':
		profile_file='profile.yml'
	else:
		profile_file='profile-'+input+'.yml'
	
	mic.say('Hello '+input+" . You're the new user now" )
	
	#TODO replace by directly reading the config file and changing the var profile 
	#argument = list()
	#argument.append(sys.argv[0])
	#for arg in sys.argv[1:]:
#		argument.append(arg)
	
	logger = logging.getLogger(__name__)

	# FIXME: For backwards compatibility, move old config file to newly
	#        created config dir
	old_configfile = os.path.join(jasperpath.LIB_PATH, profile_file)
	new_configfile = jasperpath.config(profile_file)
	if os.path.exists(old_configfile):
		if os.path.exists(new_configfile):
			logger.warning("Deprecated profile file found: '%s'. " +
									"Please remove it.", old_configfile)
		else:
			logger.warning("Deprecated profile file found: '%s'. " +
									"Trying to copy it to new location '%s'.",
									old_configfile, new_configfile)
			try:
				shutil.copy2(old_configfile, new_configfile)
			except shutil.Error:
				logger.error("Unable to copy config file. " +
									"Please copy it manually.",
									exc_info=True)
				raise

	# Read config
	logger.debug("Trying to read config file: '%s'", new_configfile)
	try:
		with open(new_configfile, "r") as f:
			#Where the magic is. Clear the dict and then update it
			profile.clear()
			profile.update(yaml.safe_load(f))
	except OSError:
		logger.error("Can't open config file: '%s'", new_configfile)
		raise


	try:
		api_key = profile['keys']['GOOGLE_SPEECH']
	except KeyError:
		api_key = None

	try:
		stt_engine_type = profile['stt_engine']
	except KeyError:
		stt_engine_type = "sphinx"
		logger.warning("stt_engine not specified in profile, " +
								"defaulting to '%s'", stt_engine_type)

	try:
		tts_engine_slug = profile['tts_engine']
	except KeyError:
		tts_engine_slug = tts.get_default_engine_slug()
		logger.warning("tts_engine not specified in profile, defaulting " +
						"to '%s'", tts_engine_slug)
	tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)

	#TODO To test !
	flag=0
	for arg in sys.argv[1:]:
		if(arg == '--local'):
			from client.local_mic import Mic
			flag=1
	if flag==0:
		from client.mic import Mic

	# Initialize Mic
	mic = Mic(tts_engine_class(),
					stt.PocketSphinxSTT(**stt.PocketSphinxSTT.get_config()),
					stt.newSTTEngine(stt_engine_type, api_key=api_key))
Example #24
0
        s = socket.create_connection((host, 80), 2)
    except:
        return False
    else:
        return True

if __name__ == "__main__":
    print "==========================================================="
    print " JASPER The Talking Computer                               "
    print " Copyright 2013 Shubhro Saha & Charlie Marsh               "
    print "==========================================================="

    speaker = client.speaker.newSpeaker()
    speaker.say("Hello.... I am Jasper... Please wait one moment.")

    for directory in [jasperpath.CONFIG_PATH, jasperpath.config("sentences"), jasperpath.config("languagemodels"), jasperpath.config("dictionaries")]:
        if not os.path.exists(directory):
            try:
                os.mkdir(directory)
            except OSError(errno, strerror):
                print("Can't create configdir '%s': %s" % (directory, strerror))
                speaker.say("Hello, I could not access the configuration directory or one of its subdirectories. Please check if you have the right permissions.")
                sys.exit(1)


    if args.checknetwork:
        if has_network_connection():
            print "CONNECTED TO INTERNET"
        else:
            print "COULD NOT CONNECT TO NETWORK"
            traceback.print_exc()
Example #25
0
def getNewProfile(mic, profile):

    #This line bug !
    mic.say('Who are you?')
    input = raw_input("Your name : ")

    if input == '':
        profile_file = 'profile.yml'
    else:
        profile_file = 'profile-' + input + '.yml'

    mic.say('Hello ' + input + " . You're the new user now")

    #TODO replace by directly reading the config file and changing the var profile
    #argument = list()
    #argument.append(sys.argv[0])
    #for arg in sys.argv[1:]:
    #		argument.append(arg)

    logger = logging.getLogger(__name__)

    # FIXME: For backwards compatibility, move old config file to newly
    #        created config dir
    old_configfile = os.path.join(jasperpath.LIB_PATH, profile_file)
    new_configfile = jasperpath.config(profile_file)
    if os.path.exists(old_configfile):
        if os.path.exists(new_configfile):
            logger.warning(
                "Deprecated profile file found: '%s'. " + "Please remove it.",
                old_configfile)
        else:
            logger.warning(
                "Deprecated profile file found: '%s'. " +
                "Trying to copy it to new location '%s'.", old_configfile,
                new_configfile)
            try:
                shutil.copy2(old_configfile, new_configfile)
            except shutil.Error:
                logger.error("Unable to copy config file. " +
                             "Please copy it manually.",
                             exc_info=True)
                raise

    # Read config
    logger.debug("Trying to read config file: '%s'", new_configfile)
    try:
        with open(new_configfile, "r") as f:
            #Where the magic is. Clear the dict and then update it
            profile.clear()
            profile.update(yaml.safe_load(f))
    except OSError:
        logger.error("Can't open config file: '%s'", new_configfile)
        raise

    try:
        api_key = profile['keys']['GOOGLE_SPEECH']
    except KeyError:
        api_key = None

    try:
        stt_engine_type = profile['stt_engine']
    except KeyError:
        stt_engine_type = "sphinx"
        logger.warning(
            "stt_engine not specified in profile, " + "defaulting to '%s'",
            stt_engine_type)

    try:
        tts_engine_slug = profile['tts_engine']
    except KeyError:
        tts_engine_slug = tts.get_default_engine_slug()
        logger.warning(
            "tts_engine not specified in profile, defaulting " + "to '%s'",
            tts_engine_slug)
    tts_engine_class = tts.get_engine_by_slug(tts_engine_slug)

    #TODO To test !
    flag = 0
    for arg in sys.argv[1:]:
        if (arg == '--local'):
            from client.local_mic import Mic
            flag = 1
    if flag == 0:
        from client.mic import Mic

    # Initialize Mic
    mic = Mic(tts_engine_class(),
              stt.PocketSphinxSTT(**stt.PocketSphinxSTT.get_config()),
              stt.newSTTEngine(stt_engine_type, api_key=api_key))
Example #26
0
def getCurrentWilko():
    wpm_file = jasperpath.config("wpm.txt")
    with open(wpm_file, "r") as f:
        wpms = [float(value) for value in f.readlines()]

    return sum(wpms) / float(len(wpms))
Example #27
0
def run():
    profile = {}

    print("Welcome to the profile populator. If, at any step, you'd prefer " +
          "not to enter the requested information, just hit 'Enter' with a " +
          "blank field to continue.")

    def simple_request(var, cleanVar, cleanInput=None):
        user_input = input(cleanVar + ": ")
        if user_input:
            if cleanInput:
                user_input = cleanInput(user_input)
            profile[var] = user_input

    # name
    simple_request('first_name', 'First name')
    simple_request('last_name', 'Last name')

    # phone number
    def clean_number(s):
        return re.sub(r'[^0-9]', '', s)

    phone_number = clean_number(input("\nPhone number (no country " +
                                          "code). Any dashes or spaces will " +
                                          "be removed for you: "))
    profile['phone_number'] = phone_number

    # carrier
    print("\nPhone carrier (for sending text notifications).")
    print("If you have a US phone number, you can enter one of the " +
          "following: 'AT&T', 'Verizon', 'T-Mobile' (without the quotes). " +
          "If your carrier isn't listed or you have an international " +
          "number, go to http://www.emailtextmessages.com and enter the " +
          "email suffix for your carrier (e.g., for Virgin Mobile, enter " +
          "'vmobl.com'; for T-Mobile Germany, enter 't-d1-sms.de').")
    carrier = input('Carrier: ')
    if carrier == 'AT&T':
        profile['carrier'] = 'txt.att.net'
    elif carrier == 'Verizon':
        profile['carrier'] = 'vtext.com'
    elif carrier == 'T-Mobile':
        profile['carrier'] = 'tmomail.net'
    else:
        profile['carrier'] = carrier

    # location
    def verifyLocation(place):
        feed = feedparser.parse('http://rss.wunderground.com/auto/rss_full/' +
                                place)
        numEntries = len(feed['entries'])
        if numEntries == 0:
            return False
        else:
            print("Location saved as " + feed['feed']['description'][33:])
            return True

    print("\nLocation should be a 5-digit US zipcode (e.g., 08544). If you " +
          "are outside the US, insert the name of your nearest big " +
          "town/city.  For weather requests.")
    location = input("Location: ")
    while location and not verifyLocation(location):
        print("Weather not found. Please try another location.")
        location = input("Location: ")
    if location:
        profile['location'] = location

    # timezone
    print("\nPlease enter a timezone from the list located in the TZ* " +
          "column at http://en.wikipedia.org/wiki/" +
          "List_of_tz_database_time_zones, or none at all.")
    tz = input("Timezone: ")
    while tz:
        try:
            timezone(tz)
            profile['timezone'] = tz
            break
        except:
            print("Not a valid timezone. Try again.")
            tz = input("Timezone: ")

    response = input("\nWould you prefer to have notifications sent by " +
                         "email (E) or text message (T)? ")
    while not response or (response != 'E' and response != 'T'):
        response = input("Please choose email (E) or text message (T): ")
    profile['prefers_email'] = (response == 'E')

    stt_engines = {
        "sphinx": None,
        "google": "GOOGLE_SPEECH"
    }

    response = input(('\nIf you would like to choose a specific STT ' +
                     'engine, please specify which.\nAvailable ' +
                     'implementations: {0}. (Press Enter to default ' +
                     'to PocketSphinx): ').format(stt_engines.keys()))
    if (response in stt_engines):
        profile["stt_engine"] = response
        api_key_name = stt_engines[response]
        if api_key_name:
            key = input("\nPlease enter your API key: ")
            profile["keys"] = {api_key_name: key}
    else:
        print("Unrecognized STT engine. Available implementations: %s"
              % stt_engines.keys())
        profile["stt_engine"] = "sphinx"

    # write to profile
    print("Writing to profile...")
    if not os.path.exists(jasperpath.CONFIG_PATH):
        os.makedirs(jasperpath.CONFIG_PATH)
    outputFile = open(jasperpath.config("profile.yml"), "w")
    yaml.dump(profile, outputFile, default_flow_style=False)
    print("Done.")
 def save_profile(self):
     output_file = open(jasperpath.config("profile.yml"), "w")
     yaml.dump(self.profile, output_file, default_flow_style=False)