示例#1
0
def eval(file_name, choice):
    text = list()
    if choice == 1:
        text.append(recognize(file_name))
    else:
        with open(file_name, "rt") as f:
            lines = f.readlines()
            print(lines)
            for line in lines:
                text.append(line)
    nb_count = 0
    svm_count = 0
    print(text)
    total = len(text)
    for i in text:
        if analyse(i) <= 0.1:
            if predict_nb(i) == 'suicidal':
                nb_count = nb_count + 1
            if predict_svm(i) == 'suicidal':
                svm_count = svm_count + 1
    avg_count = (nb_count + svm_count) / 2
    if choice == 1:
        if avg_count == 1:
            return 'Potentially suicidal content.'
        else:
            return 'No suicidal content found.'
    else:
        print(avg_count)
        print(total)
        percentage = (avg_count / total) * 100
        return percentage
示例#2
0
def detectedCallback():

    arduino.write('1'.encode())

    try:
        play_audio_file(select(config.get('wav', 'listening')))

        reqText = speech.recognize()
        if (reqText):
            # submit request
            logger.info('Request: {0}'.format(reqText))
            response = requests.post(config.get('core_service', 'url'),
                                     json={'text': reqText})

            data = response.json()
            logger.info('Response: {0}'.format(data))
            speech.say(data.get('say'), local_tts)

            media = data.get('play')
            if (media):
                process = play_audio_file_async(media, 0.05)
                logger.debug('Playing media file: {0}'.format(media))
                logger.debug('pid={0}'.format(str(process.pid)))
    except Exception as e:
        logger.exception("message")

    arduino.write('0'.encode())
示例#3
0
def getSpeech():
    # Record an audio file using sound.Recorder:
    recorder = sound.Recorder('speech.m4a')
    recorder.record()
    # Record for 3 seconds
    for i in range(3):
        sound.play_effect('game:Beep')
        time.sleep(1)

    # Stop recording
    recorder.stop()
    time.sleep(1)

    result = 'no speech detected'
    try:
        speechDetect = speech.recognize('speech.m4a')
        result = speechDetect[0][0]
        #print('=== Details ===')
        # print(result)
        #print('=== Transcription ===')
        # print(result[0][0])
    except RuntimeError as e:
        print('Speech recognition failed: %s' % (e,))
        sound.play_effect('game:Error')

    return result
示例#4
0
def recognize(rec, mic):
    running = True
    result  = ""
    print("[main] Recognizing...")

    mic.record()

    result = speech.recognize(mic.save())
    time.sleep(1)

    return result
示例#5
0
def speech_recognition():
    from speech import recognize
    if 'file' not in request.files:
        abort(400)
    file = request.files['file']
    if file.filename == '':
        abort(400)
    prefix = os.path.join(app.config['UPLOAD_FOLDER'],
                          datetime.now().strftime("%Y-%m-%d_%H%M%S_%f"))
    webm_filename = prefix + '.webm'
    ogg_filename = prefix + '.ogg'
    file.save(webm_filename)
    os.system('ffmpeg -i {} -vn -acodec copy {}'.format(
        webm_filename, ogg_filename))
    return recognize(ogg_filename)
def anything_else():
	import time, sound
	speech.say("Mr. {Name} is there anything else I may help you with?", "en-UK")
	time.sleep(3)
	rec = sound.Recorder("audio.m4a")
	rec.record()
	time.sleep(3)
	rec.stop()
	result = speech.recognize("audio.m4a")[0][0]
	if result == "Yes":
		speech.say("Oops that is the end of my code sir, but I did hear yes", "en-UK")
	elif result == "No":
		speech.say("That is the end of my code sir, but I did hear no.", "en-UK")
	else:
		speech.say("I did not hear a response, so I will assume you are ready for the day,", "en-UK")
示例#7
0
def face():
    print("Thread started")
    global img
    global words

    while True:
        img = "tim/idle_face.png"
        words = speech.recognize()

        if words != None:
            print(words)
            img = "tim/open_mouth.png"
            audio_thread = threading.Thread(target=tts("Noodle"),
                                            args=(),
                                            daemon=True)
            audio_thread.start()
示例#8
0
def listen():
    global command
    global index
    recorder = sound.Recorder('speech.m4a')
    while 'exit' not in command:
        speech.say('listening')
        print('listening')
        recorder.record()
        time.sleep(3)
        recorder.stop()
        try:
            text = speech.recognize('speech.m4a')
            [command, index] = stadardize_command(text[0][0], index)
            print(command)
        except:
            pass
示例#9
0
def recognize(rec, mic):
    result  = ""
    print("[main] Recognizing...")

    # Indicate start of recording with LED and animation    
    gpio.output(LED_PIN, 1)
    # Send appropriate command to Animation module through FIFO
    subprocess.check_output('echo "1" > ../speechToAnimation.fifo', shell=True)
    subprocess.check_output('echo "1" >> ../speechToAnimation.log', shell=True)
    # Record audio 
    mic.record()
    # Indicate end of recording 
    gpio.output(LED_PIN, 0)
    subprocess.check_output('echo "2" > ../speechToAnimation.fifo', shell=True)
    subprocess.check_output('echo "2" >> ../speechToAnimation.log', shell=True)

    # Recognize any speech in the recorded audio
    result = speech.recognize(mic.save())
    # Delay of 2s before next recognition
    time.sleep(2)

    return result
示例#10
0
    async def start(self, instance, value):
        duration, = self.duration.value

        rec = sound.Recorder('recorded.m4a')
        rec.record()
        print(f'Recording for {duration}...')
        await self.async_lib.sleep(duration)
        rec.stop()
        await self.async_lib.sleep(0.1)
        result = speech.recognize('recorded.m4a')
        if len(result):
            full_text, full_info = result[0]
            await self.text.write([full_text])
            await self.confidence.write(
                [min(info['confidence'] for info in full_info)])
            for info in full_info:
                print('@ {timestamp} {duration} sec'
                      'heard: {substring} ({confidence})'
                      ''.format(**info))

        else:
            await self.text.write([str(result)])
示例#11
0
#for windows ONLY
import speech
import sound
from random_word import RandomWords
r = RandomWords()
playing = True
words = 0
inaccuracy = 0
for i in range(10):
    words += 1
    Word = True
    word = r.get_random_word()
    while Word:
        speech.say(word, 'es_ES')
        r = sound.Recorder('audio.m4a')
        print("3")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        time.sleep(1)
        print(word)
        r.record(3)
        text = speech.recognize('audio.m4a', 'en')[0][0]
        if text == word:
            Word = False
        else:
            inaccuracy += 1
            print("try again")
print(inaccuracy / words)
# https://forum.omz-software.com/topic/3862/speech-sound-module-q-s/4

import speech, sound, time
rec = sound.Recorder("audio.m4a")
rec.record()
time.sleep(3)
rec.stop()
result = speech.recognize("audio.m4a")
print(result)
示例#13
0
def main():
    # initialize
    drink_status = False
    drunk_level = 0
    bill = 0

    while (drink_status == False):
        # display menu
        print("++++")
        print("Menu")
        print("")
        for drink in staff_action["menu"]["drink"].keys():
            print(drink)
        print("++++")

        # take a order
        speech.say("ご注文をどうぞ!", 'ja-JP')
        time.sleep(1.8)
        recorder = sound.Recorder('speech.m4a')
        recorder.record()
        dialogs.alert('注文が終わったらボタンをタップしてください.',
                      '',
                      'Finish',
                      hide_cancel_button=True)
        recorder.stop()

        # replay
        voice = sound.Player('speech.m4a')
        voice.play()
        time.sleep(5.0)

        # recognize order
        try:
            result = speech.recognize('speech.m4a', 'ja-JP')
        except RuntimeError as e:
            print("recognition failed: %s" % (e, ))

        # order done
        hit = False
        for candidate in staff_action["menu"]["drink"].keys():
            if candidate in result[0][0]:
                string = 'お待たせしました、' + candidate + 'です!'
                speech.say(string, 'ja-JP')
                print(string)

                # add bill and drunk_level
                bill += staff_action["menu"]["drink"][candidate]["price"]
                drunk_level += staff_action["menu"]["drink"][candidate]["alc"]

                hit = True
                break
        if not hit:
            string = "申し訳ありません、当店には取りあつかいがありません。"
            speech.say(string, 'ja-JP')
            print(string)

        # check drunk_level
        if (drunk_level >= drunk_threshold):
            string = "あ、お茶をお出ししますね。"
            speech.say(string, 'ja-JP')
            string = "お会計は" + str(bill) + "円です。お気をつけておかえりください。"
            speech.say(string, 'ja-JP')
            drink_status = True

        time.sleep(2.0)