Ejemplo n.º 1
0
def test_test():
    """Test your knowledge about weekdays"""
    translator = Translator()

    text = "It is universally accepted that..."
    tran = translator.translate(text, dest="ru").text
    Speech(text, "en").play()
    Speech(tran, "ru").play()
Ejemplo n.º 2
0
def readText(text):
    """
	Lee un texto
	"""
    lang = "es"
    speech = Speech(text, lang)
    speech.play()
Ejemplo n.º 3
0
    def _hablar(self, mensaje: str) -> None:
        """
        Usa Google Speech para hablar al usuario con una frase aleatoria.
        """

        habla = Speech(mensaje, 'es')
        habla.play()
Ejemplo n.º 4
0
def speak(text):
    print(text)
    if text is None:
        text = "Sorry"
    lang = "en"
    speech = Speech(text, lang)
    return speech
Ejemplo n.º 5
0
def detected_callback():
    print("hotword detected")
    text = "Bonjour monsieur. Comment allez-vous ?"
    lang = "fr"
    speech = Speech(text, lang)
    sox_effects = ("speed", "1.1")
    speech.play(sox_effects)
Ejemplo n.º 6
0
def speak_google_tts(text):
    """ This method implements Text to Speech using the Google Translate TTS.
    It uses Google Speech Python Package.
    :param text: Text which is needed to be spoken
    :return: None
    """
    Speech(text=text, lang='en').play(sox_effects=None)
Ejemplo n.º 7
0
def response(sentence, userID='123', show_details=False):
    results = classify(sentence)
    # if we have a classification then find the matching intent tag
    if results:
        # loop as long as there are matches to process
        while results:
            for i in intents['intents']:
                # find a tag matching the first result
                if i['tag'] == results[0][0]:
                    # set context for this intent if necessary
                    if 'context_set' in i:
                        if show_details: print('context:', i['context_set'])
                        context[userID] = i['context_set']

                    # check if this intent is contextual and applies to this user's conversation
                    if not 'context_filter' in i or \
                        (userID in context and 'context_filter' in i and i['context_filter'] == context[userID]):
                        if show_details: print('tag:', i['tag'])
                        val = random.choice(i['responses'])
                        speech = Speech(val, lang)
                        sox_effects = ("speed", "1.0")
                        speech.play(sox_effects)
                        # a random response from the intent
                        return print(val)

            results.pop(0)
Ejemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser(description="Generate and save a given word's speech.")
    parser.add_argument('--word', type=str, default=None, help='Word to be spoken')
    parser.add_argument('--leo_code', type=str, default=None, help='LEO audio code if you really want the audio from there and the script magic is not working. If the --word argument is given, the output name format will be preserved, otherwise you will get a random_leters.mp3 in your folder.')
    parser.add_argument('--lang', type=str, default='de', help='Language that you want your text to be spoken. Until it does not make any difference besides changing the name of the outputted file.')
    parser.add_argument('--force_google', type=bool, default=False, help='It forces using Google Translate engine (useful when LEO fails to work (aka do wrong stuff))')

    args = parser.parse_args()

    if not args.word and not args.leo_code:
        print("--word or --leo_code have to be provided as argument!")
        exit(1)

    if args.leo_code:
        audio = download_audio_leo(audio_code=args.leo_code)
        output_file = output_text(args.word, args.lang) if args.word else args.leo_code
        with open(f'{output_file}.mp3', 'wb') as f:
            f.write(audio.read())

        print("You forced, but i think LEO worked, check it out! :-)")

    # we try first with LEO, if we dont find anything there, then we use google translate
    elif not get_from_leo(args.word, args.lang) or args.force_google:
        print("We are getting from Google Translate anyways... :-(")
        speech = Speech(args.word, args.lang)
        # save the speech to an MP3 file (no effect is applied)
        speech.save(f"{output_text(args.word, args.lang)}.mp3")
    
    else:
        print("Apparently LEO worked, check it out! :-)")
Ejemplo n.º 9
0
def test_weekdays(amount):
    """Test your knowledge about weekdays"""
    lang = "en"
    result = 0
    weekdays = [
        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday"
    ]

    for idx in range(amount):
        sleep(0.8)
        print("~" * 10)

        rnd = randrange(0, len(weekdays))
        text = weekdays[rnd]

        Speech(text, lang).play()

        test = input("Your answer (Weekday): ")

        if test == text:
            result += 1
            print("You are right.")
        else:
            print(f"The right answer is: {text}")
            sleep(2)

    print("Result:")
    print(f" {amount} - the number of questions")
    print(f" {result} - the number of RIGHT answers")
Ejemplo n.º 10
0
def notice(text, lang='vi'):
    try:
        speech = Speech(text, lang)
        speech.play()
    except Exception:
        print(text)
        print('No network connect! So i can not speak for you!')
Ejemplo n.º 11
0
def speak_object_changes(speech_flag, object_changes, height, width):
    global speech_out_array
    global old_speech_out_array
    old_speech_out_array = speech_out_array
    speech_out_array = []

    for key, object_change in object_changes.items():
        speech_out_str = key
        if "person_name" in object_change:
            speech_out_str = object_change["person_name"]

        if object_change["appeared"] is True:
            speech_out_str += " entered frame at "
            speech_out_str += get_object_position_words(
                object_change["bbox"], height, width)
        elif object_change["disappeared"] is True:
            speech_out_str += " left frame"
        else:
            speech_out_str += " moved to "
            speech_out_str += get_object_position_words(
                object_change["bbox"], height, width)
        speech_out_array.append(speech_out_str)

    output_array = []
    for speech in speech_out_array:

        if speech not in old_speech_out_array:
            output_array.append(speech)

            if speech_flag is True:
                speech = Speech(speech_out_str, LANG)
                speech.play(sox_effects)
    return output_array
Ejemplo n.º 12
0
def callback(recognizer, audio):
    print("callback")
    # received audio data, now we'll recognize it using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        said = recognizer.recognize_google(audio, language="fr-FR")
        print("Google Speech Recognition thinks you said " + mytext)

        if said == 'stop':
            # calling this function requests that the background listener stop listening
            stop_listening(wait_for_stop=False)
            print('the end')
        else:
            speech = Speech(said, "fr")
            sox_effects = ("speed", "1.1")
            speech.play(sox_effects)

    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print(
            "Could not request results from Google Speech Recognition service; {0}"
            .format(e))
Ejemplo n.º 13
0
    def speak(self):
        lang = "en"
        speech = Speech(self.data, lang)

        # you can also apply audio effects while playing (using SoX)
        # see http://sox.sourceforge.net/sox.html#EFFECTS for full effect documentation
        sox_effects = ("tempo", "1.5")
        return speech.play(sox_effects)
Ejemplo n.º 14
0
def textToSpeech(text):
    lang = 'en-US'
    lang = lang.replace('-','_')

    speech = Speech(text, lang)
    sox_effects = ("speed", "1.0")
    sox_effects = ("vol", "0.5")
    speech.play(sox_effects)
Ejemplo n.º 15
0
 def speak(self, text):
     speech = Speech(text, self.language)
     # speech.play(sox_effects=("speed", DEFAULT_SPEED))
     PATH = os.getcwd() + r"\Audio\test.mp3"
     speech.save(PATH)
     # self.play_audio_file(PATH)
     song = AudioSegment.from_mp3(PATH)
     play(song)
Ejemplo n.º 16
0
 def speak(self):
     print("speech: ", self.text)
     if (is_debug_mode):
         lang = "zh-cn"
         self.speech = Speech(self.text, lang)
         self.speech.play()
     else:
         tts.speak(self.text)
Ejemplo n.º 17
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--count',
                        help='How many captchas to generate',
                        type=int)
    parser.add_argument('--output-dir',
                        help='Where to store the generated captchas',
                        type=str)
    parser.add_argument('--symbols',
                        help='File with the symbols to use in captchas',
                        type=str)
    args = parser.parse_args()

    if args.count is None:
        print("Please specify the captcha count to generate")
        exit(1)

    if args.output_dir is None:
        print("Please specify the captcha output directory")
        exit(1)

    if args.symbols is None:
        print("Please specify the captcha symbols file")
        exit(1)

    symbols_file = open(args.symbols, 'r')
    captcha_symbols = symbols_file.readline().strip()
    symbols_file.close()

    print("Generating captchas with symbol set {" + captcha_symbols + "}")

    if not os.path.exists(args.output_dir):
        print("Creating output directory " + args.output_dir)
        os.makedirs(args.output_dir)

    for i in range(args.count):
        captcha_text = ''.join(
            [random.choice(captcha_symbols) for j in range(args.length)])
        #print(captcha_text)
        lang = "en"
        speech = Speech(captcha_text, lang)
        #speech.play()

        #sox_effects = ("speed", "1.5")
        #speech.play(sox_effects)
        image_path = os.path.join(args.output_dir, captcha_text + '.png')
        if os.path.exists(image_path):
            version = 1
            while os.path.exists(
                    os.path.join(args.output_dir,
                                 captcha_text + '_' + str(version) + '.png')):
                version += 1
            image_path = os.path.join(
                args.output_dir, captcha_text + '_' + str(version) + '.png')

        audio_path = os.path.join(args.output_dir, captcha_text + '.mp3')
        speech.save(audio_path)
Ejemplo n.º 18
0
def update_output(n_clicks, value):
    vocab_data = data_loader.get_question_answer_vocab("2")
    qvocab = vocab_data['question_vocab']
    q_map = { vocab_data['question_vocab'][qw] : qw for qw in vocab_data['question_vocab']}
    print('filename::',filen)
    fc7_features = utils.extract_fc7_features(filen, 'Data/vgg16.tfmodel')
    model_options = {
		'num_lstm_layers' : 2,
		'rnn_size' : 512,
		'embedding_size' : 512,
		'word_emb_dropout' : 0.5,
		'image_dropout' : 0.5,
		'fc7_feature_length' : 4096,
		'lstm_steps' : vocab_data['max_question_length'] + 1,
		'q_vocab_size' : len(vocab_data['question_vocab']),
		'ans_vocab_size' : len(vocab_data['answer_vocab'])
	}
    
    question_vocab = vocab_data['question_vocab']
    word_regex = re.compile(r'\w+')
    question_ids = np.zeros((1, vocab_data['max_question_length']), dtype = 'int32')
    print('qst',value)
    question_words = re.findall(word_regex, value)
    base = vocab_data['max_question_length'] - len(question_words)
    for i in range(0, len(question_words)):
        if question_words[i] in question_vocab:
            question_ids[0][base + i] = question_vocab[ question_words[i] ]
        else:
            question_ids[0][base + i] = question_vocab['UNK']
    ans_map = { vocab_data['answer_vocab'][ans] : ans for ans in vocab_data['answer_vocab']}
    model = vis_lstm_model.Vis_lstm_model(model_options)
    input_tensors, t_prediction, t_ans_probab = model.build_generator()
    sess = tf.InteractiveSession()
    saver = tf.train.Saver()
    saver.restore(sess, 'Data/Models/modelnew99.ckpt')
    pred, answer_probab = sess.run([t_prediction, t_ans_probab], feed_dict={
        input_tensors['fc7']:fc7_features,
        input_tensors['sentence']:question_ids,
    })
    print("answerprediction",pred[0])
    #model.summary()
    #plot_model(model,to_file='predictmodel.png')
    print ("Ans:", ans_map[pred[0]])
    answer_probab_tuples = [(-answer_probab[0][idx], idx) for idx in range(len(answer_probab[0]))]
    answer_probab_tuples.sort()
    print ("Top Answers")
    for i in range(1):
        print (ans_map[ answer_probab_tuples[0][1] ])
        #ans=(ans_map[answer_probab_tuples[i][1] ])
        lang = "en"
        text="This is a "+ans_map[ answer_probab_tuples[0][1] ]
        speech = Speech(text, lang)

        sox_effects = ("speed", "0.8")
        speech.play(sox_effects)
        
    return ans_map[answer_probab_tuples[0][1]]
Ejemplo n.º 19
0
def speach(request, id):

    phrase = Phrase.objects.get(pk=id)

    speech = Speech(phrase.original, "en")
    sox_effects = ("speed", "1")
    speech.play(sox_effects)

    return HttpResponse('Speach')
Ejemplo n.º 20
0
 def warning_notification(self, text):
     print(dt.datetime.now().strftime('%b %d, %H:%M:%S'), text)
     while self.warning_notification_output:
         time.sleep(0.5)
     self.warning_notification_output = True
     speech = Speech(text, 'en')
     speech.play()
     time.sleep(3)
     self.warning_notification_output = False
Ejemplo n.º 21
0
 def wrapper(*args, **kwargs):
     t1 = time.time()
     out = fun(*args, **kwargs)
     t2 = time.time()
     text = "It took " + str((t2 - t1)) + " to run the function."
     print(text)
     speech = Speech(text, lang)
     speech.play(None)
     return out
Ejemplo n.º 22
0
async def speak_voice_channel(ctx, *, arg):
    voice_channel = ctx.voice_client

    speech = Speech(arg, "tr")
    save_speech = speech.save("deneme.mp3")
    #speech.play()

    voice_channel.play(discord.FFmpegPCMAudio("deneme.mp3"),
                       after=lambda e: print('done', e))
Ejemplo n.º 23
0
def read(message, print_text=True):
    speech = Speech(message, LANGUAGE)
    if print_text:
        cprint('\n' * (rows // 2) + ' ' * ((columns // 2) -
                                           (len(message) // 2)) + message,
               'red',
               attrs=['bold'])
    sox_effects = ("speed", "1.")
    speech.play(sox_effects)
Ejemplo n.º 24
0
def get_gspeech(text: str):
    if not text:
        return
    speech = Speech(text, 'en')
    filename = os.path.join(cachepath, "cache.mp3")
    speech.save(filename)
    with open(filename, 'rb') as f:
        base64_audio = base64.b64encode(f.read())
    return base64_audio
Ejemplo n.º 25
0
def textToSpeech(text):
    # lang = 'ko_KR'
    global lang
    lang = lang.replace('-','_')

    speech = Speech(text, lang)
    sox_effects = ("speed", "1.0")
    sox_effects = ("vol", "0.05")
    speech.play(sox_effects)
Ejemplo n.º 26
0
def say(text, speed=1.5, lang='en'):
    try:
        speech = Speech(text.replace('\n', ''), lang)
        speech.play()

        sox_effects = ('speed', speed)
        speech.play(sox_effects)
    except TypeError:
        print('Could not read {}'.format(text))
Ejemplo n.º 27
0
def say():
    lang = 'en'
    if request.method == 'POST':
        text = request.args.get('text')
        lang = request.args.get('lang')
        speech = Speech(text, lang)
        speech.play()
        return "pyTalk said {}!".format(text)
    else:
        return "pyTalk say works only on POST"
Ejemplo n.º 28
0
def speak_google_tts(text):
    """ This method implements Text to Speech using the Google Translate TTS.
    It uses Google Speech Python Package.
    :param text: Text which is needed to be spoken
    :return: None
    """
    with tempfile.TemporaryDirectory() as tmpdirname:
        fd, mpiii = tempfile.mkstemp(suffix='.mp3', dir=tmpdirname)
        Speech(text=text, lang=susicfg.get("language")).save(mpiii)
        player.say(mpiii)
Ejemplo n.º 29
0
def textToSpeech(request):
    text = request.GET.get("text", "")
    lang = "ur"
    translation = database.child("DataSet").order_by_key().limit_to_first(
        3).get()
    translator = Translator()
    translatorResult = translator.translate(text, src="en", dest="ur")
    speech = Speech(translatorResult.text, lang)
    sox_effects = ("speed", "1.0")
    speech.play(sox_effects)
    return HttpResponse("1")
Ejemplo n.º 30
0
def shyna_speaks(msg: object) -> object:
    msgs = random.choice(msg.split("|"))
    for i in sent_tokenize(msgs):
        print(i)
        lang = "en"
        speech = Speech(i, lang)
        sox_effects = (
            "speed",
            "1",
        )
        speech.play(sox_effects)