#Output of speech recognizer with espeak text output
#and appending to a file named in the argument
#Fuer Deutsche Spracherkennung
#addition by Gerald Schuller, April. 2019

"""
python speech recognition:
https://pypi.python.org/pypi/SpeechRecognition/
sudo pip(3) install SpeechRecognition
sudo apt install flac
sudo apt install python.pyaudio
sudo apt install espeak
#Eventuell update von pyaudio:
pip show pyaudio
sudo apt-get install portaudio19-dev
sudo apt-get install python-all-dev
sudo pip install --upgrade pyaudio
"""

import speech_recognition as sr
import os
import sys

#Opens file of 1st argument in append mode:
filename=sys.argv[1]
print("filename= ", filename)
textfile=open(filename, "a")

r = sr.Recognizer()
m = sr.Microphone()

try:
    os.system('espeak -vde -s 140 '+'"Sprache-zu Text program"')
    print("Ende mit Control-C ")
    os.system('espeak -vde -s 140 '+'"Ende mit Control - C"')
    print("Einen Moment der Stille bitte...")
    os.system('espeak -vde -s 140 '+'"Einen Moment der Stille bitte...."')
    with m as source: r.adjust_for_ambient_noise(source)
    print("Set minimum energy threshold to {}".format(r.energy_threshold))
    while True:
        print("Sag etwas!")
        os.system('espeak -vde -s 140 '+'"Ich höre"')
        with m as source: audio = r.listen(source)
        print("Okay, Erkenne ...")
        try:
            # recognize speech using Google Speech Recognition
            #rectext = r.recognize_google(audio)
            rectext  = r.recognize_google(audio, language='de-DE')

            # we need some special handling here to correctly print unicode characters to standard output
            if str is bytes: # this version of Python uses bytes for strings (Python 2)
                print(u"Du sagtest {}".format(rectext).encode("utf-8"))
                os.system('espeak -vde -s 140 '+'"'+rectext +'"')
            else: # this version of Python uses unicode for strings (Python 3+)
                print("Du sagtest {}".format(rectext))
                os.system('espeak -vde -s 140 '+'"'+rectext +'"')
            #First letter in capital letter and in the end add a '.'
            textfile.write(rectext[0].upper()+rectext[1:]+'. ');

        except sr.UnknownValueError:
            print("Oh, dass hab ich nicht verstanden")
            os.system('espeak -vde -s 140 '+'"Bitte wiederholen"')
        except sr.RequestError as e:
            print("Oh, Fehler vom Google Speech Recognition service; {0}".format(e))
            os.system('espeak -vde -s 140 '+'"Oh, Fehler vom Google Speech Recognition service"')
except KeyboardInterrupt:
    textfile.close()
    pass
