#!/usr/env/python3
# coding: utf-8
# la ligne coding ci-dessus permet d'éviter les erreurs d'accents
# https://openclassrooms.com/forum/sujet/quot-syntaxerror-non-ascii-character-xc3-in-filequot-12536

# documentation projet : http://gangand.net/pp/projets/assistant_vocal/

import speech_recognition as sr
import os

# This script was written by Greg Colburn (ThePony on github). Feel free
# to contact me on FB at https://www.facebook.com/9millionthGreg BUT...
# when contacting me please be sure to tell my WHY you are messaging me!
# donations to keep snacks on hand for my coding spurts are welcome at
# paypal at (colburn greg at.symbol.goes.here ya hoo dot com), thanks

# https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# evite les erreurs du type
# UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)

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

# nouvelle variable unique a utiliser par la suite
# action 'browser' necessite 'site'
exitWord  = ['quitter', 'Quitterie']
cle = {
    'REBOOTER': {
        'action' : 'exec' ,
        'command': 'sudo',
        'args'   : ['reboot'],
        'mots'   : ['redémarrer la machine']
        },

    'FERMER' : {    # Alt-F4
        'action' : 'script' ,
        'script' : 'sleep 2; xdotool keydown alt ; xdotool key F4 ; xdotool keyup alt',
        'mots'   : ['fermer', 'alt F4']
        },

    'EDITION' : {
        'action' : 'exec' ,
        'command': 'geany',
        'args'   : ['/home/pi/Documents/piTalk-master/talking.py'],
        'mots'   : ['édition programme']
        },

    'SAUVEGARDE' : {
        'action' : 'exec' ,
        'command': '/home/pi/Documents/piTalk-master/sauvegarde.sh',
        'args'   : [''],
        'mots'   : ['sauvegarde programme']
        },




    'tmp_foot': {
        'action' : 'script' ,
        'script' : 'chromium-browser "http://gangand.net/ss/sport_euro_2021/i2.php?cpt=foot/euro_2021" & \
chromium-browser "https://www.google.com/search?q=euro+2021+foot" & \
geany ftp://gangand@ftp.cluster015.hosting.ovh.net/www/ss/sport_euro_2021/data/foot/euro_2021.ini &',
        'mots'   : ['sport', 'foot', 'football', 'championnat d\'Europe', 'champion d\'Europe']
        },

    'corona': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net/cc/coro/stats/index.php?device=PC',
        'mots'   : ['Corona', 'corona']
        },

    'domotique' : {
        'action' : 'gpio_domotique' ,
        'mots'   : ['boutique', 'domotique']
        },

    # fichiers
    'fichier_achats_fournitures' : {
        'action' : 'exec' ,
        'command': 's3f',
        'args'   : ['achats', 'fournitures'],
        'mots'   : ['leroy merlin', 'fourniture', 'achats fournitures', 'achat fournitures']
        },

    'fichier' : {
        'action' : 'recherche_fichier' ,
        'command': 's3f',
        'args'   : [''],
        'mots'   : ['chercher fichier', 'recherche pied']
        },

    # radios web
    'france_inter' : {
        'action' : 'exec' ,
        'command': 'vlc',
        'args'   : ['http://direct.franceinter.fr/live/franceinter-midfi.mp3'],
        'mots'   : ['inter', 'france inter', 'France Inter']
        },

    'jeux': {
        'action' : 'exec' ,
        'command': 'pysolfc',
        'mots'   : ['jeu', 'jeux', 'jeu du solitaire'],
        'args'   : ''
        },

    'internet': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net',
        'mots'   : ['internet']
        },

    'libreoffice': {
        'action' : 'exec' ,
        'command': 'libreoffice',
        'mots'   : ['libre', 'libreoffice']
        },

    'lampe_fr': {
        'action' : 'gpio_domotique' ,
        'mots'   : ['allume la lampe']
        },

    'meteo': {
        'action' : 'browser' ,
        'site'   : 'https://www.google.com/search?q=meteo+reims',
        'mots'   : ['quel temps', 'météo']
        },

    'navigateur_fermer_onglet' : {
        'action' : 'script' ,
        'script': 'sleep 2; xdotool keydown ctrl ; xdotool key w ; xdotool keyup ctrl',
        'mots'   : ['fermer onglet', 'mes onglets', 'tomber en anglais', 'mets anglais', 'ferme cette anglais', 'ferme cet onglet', 'morceau de viande', 'viande']
        # onglet : bon morceau de viande
        },

    'navigateur_fermer_2_onglets' : {
        'action' : 'script' ,
        'script': 'sleep 2; xdotool keydown ctrl ; xdotool key w ; xdotool keyup ctrl; sleep 2; xdotool keydown ctrl ; xdotool key w ; xdotool keyup ctrl; ',
        'mots'   : ['deux morceaux de viande', '2 morceaux de viande', 'bonne viande']
        },

    'musique' : {
        'action' : 'exec' ,
        'command': 'vlc',
        # 'args'   : ['/media/fbx/xavbox/type1/', '>/dev/null', '2>&1'],
        'args'   : ['/media/fbx/xavbox/type1/'],
        'mots'   : ['boutique', 'musique']
        },

    'musique_off' : {
        'action' : 'exec' ,
        'command': 'killall',
        'args'   : ['vlc'],
        'mots'   : ['arrête la musique', 'arrêter la musique', 'arrêter musique', 'arrête musique']
        },

    'television_en' : {
        'action' : 'exec' ,
        'command': 'vlc ',
        'args'   : ['http://gangand.net/tt/tv/free_sd.m3u'],
        'mots'   : ['Billy', 'CD', 'DD', 'Siri', 'television']
        },

}

# ## commandes spéciales concernant le pgm même
# REBOOTER  = cle['REBOOTER'  ]['mots']
# EDITION   = cle['EDITION'   ]['mots']
# SAUVEGARDE= cle['SAUVEGARDE']['mots']


# ## temporaire
# t€mp_foot  = cle['tmp_foot']['mots']

# ## commandes vocales
# corona      = cle['corona'      ]['mots']
# domotique   = cle['domotique'   ]['mots']
# internet    = cle['internet'    ]['mots']
# jeux        = cle['jeux'        ]['mots']
# libreoffice = cle['libreoffice' ]['mots']
# meteo       = cle['meteo'       ]['mots']
# ## radio        = cle['radio']['mots']
# france_inter = cle['france_inter']['mots']
# ## france_info  = cle['radios']['france_info' ]['mots']
# musique     = cle['musique'     ]['mots']
# musique_off = cle['musique_off' ]['mots']
# navigateur_fermer_onglet = cle['navigateur_fermer_onglet' ]['mots']
# navigateur_fermer_2_onglets = cle['navigateur_fermer_2_onglets' ]['mots']


print("*" * 50)
for i, j in enumerate(cle):
    print("%15s : %s" % (j, cle[j]['mots']) )
print("*" * 50)
print()


# Voir aussi
# https://stackoverflow.com/questions/36244380/enumerate-for-dictionary-in-pythonw
# for index, (key, value) in enumerate(your_dict.items()):
    # print(index, key, value)

import subprocess

# def date_heure():
    # from datetime import datetime
    # from time import strftime
    # return strftime('%Y-%m-%d %H:%M:%S', datetime.now())

def date_heure():
    # https://waytolearnx.com/2020/06/date-et-heure-en-python.html
    from datetime import datetime
    t = datetime.now()
    # return str(t.year) + ' ' + str(t.month) + ' ' + str(t.hour) + ' ' + str(t.minute) + ' ' + str(t.second)
    # https://docs.python.org/fr/3.5/library/string.html
    # https://stackoverflow.com/questions/339007/how-to-pad-zeroes-to-a-string
    return '{0}-{1:02d}-{2:02d}-{3:02d}-{4:02d}'.format(t.year, t.month, t.hour, t.minute, t.second)

def lancement_original():
    try:
        print("One moment...")
        with m as source: r.adjust_for_ambient_noise(source)
        # The above line takes an ambient sample of noise to set threshhold levels.
        # This may not work on all microphones and should be tweaked as needed
        while True:
            # print("Now Ready, talk to me. (Press Ctrl+c to or say exit or quit to quit)")
            print("Prêt, veuillez parler. (Presser Ctrl+c ou dire quitter pour quitter)")
            with m as source: audio = r.listen(source)
            print(".")
            try:
                # ~ value = r.recognize_google(audio)
                value = r.recognize_google(audio, language="fr-FR")
                # passer en francais
                # https://stackoverflow.com/questions/49732536/how-to-change-the-language-of-google-speech-recognition

                if str is bytes:
                    reply = "{}".format(value).encode("utf-8")
                else:
                    reply = "{}".format(value)
                print("reply = %s " % reply)

                if reply in exitWord:
                    quit()

                elif reply in jeux:             # game anglais
                    print(date_heure(), "jeux")
                    # subprocess.Popen( ['pysolfc', '']).pid
                    tableau = []
                    tableau.append(cle['jeux']['command'])
                    for i in cle['jeux']['args']:
                        tableau.append(i)
                    subprocess.Popen( list(tableau) ).pid


                elif reply in internet:      # internet
                    print(date_heure(), "internet %s" % reply)
                    print("Lancement de chromium-browser http://gangand.net")
                    subprocess.Popen( ['chromium-browser', 'http://gangand.net']).pid

                elif reply in lampe_fr:     # lumiere fr
                    print("lampe_fr %s" % reply)
                    subprocess.Popen( ['chromium-browser', 'https://www.google.com/search?q=domotique+lampe']).pid

                elif reply in meteo:         # meteo fr
                    print(date_heure(), "meteo %s" % reply)
                    # print("Lancement de chromium-browser https://www.google.com/search?q=meteo+reims")
                    # subprocess.Popen( ['chromium-browser', 'https://www.google.com/search?q=meteo+reims']).pid

                    # print("meteo")
                    # subprocess.Popen( ['chromium-browser', 'http://gangand.net/cc/coro/stats/index.php?device=PC']).pid

                    tableau = []
                    choix = cle['meteo']
                    if ( choix['action'] == 'browser' ):
                            subprocess.Popen( ['chromium-browser', choix['site'] ] ).pid
                    else:
                            tableau.append(r['command'])
                            for i in r['args']:
                                tableau.append(i)
                            subprocess.Popen( list(tableau) ).pid

                elif reply in tmp_foot:
                    print(date_heure(), "tmp_foot %s" % reply)
                    tableau = []
                    choix = cle['tmp_foot']
                    if ( choix['action'] == 'browser' ):
                        subprocess.Popen( ['chromium-browser', choix['site'] ] ).pid
                    elif ( choix['action'] == 'script' ):
                        f = open("/tmp/talking.sh", "w")
                        f.write(choix['script'])
                        f.close()
                        subprocess.Popen( ['sh', '/tmp/talking.sh' ] ).pid
                    else:
                        tableau.append(r['command'])
                        for i in r['args']:
                            tableau.append(i)
                        subprocess.Popen( list(tableau) ).pid

                elif reply in navigateur_fermer_onglet:
                    print(date_heure(), "navigateur_fermer_onglet %s" % reply)
                    tableau = []
                    choix = cle['navigateur_fermer_onglet']
                    if ( choix['action'] == 'script' ):
                        f = open("/tmp/talking.sh", "w")
                        f.write(choix['script'])
                        f.close()
                        subprocess.Popen( ['sh', '/tmp/talking.sh' ] ).pid
                    else:
                        tableau.append(r['command'])
                        for i in r['args']:
                            tableau.append(i)
                        subprocess.Popen( list(tableau) ).pid

                elif reply in navigateur_fermer_2_onglets:
                    print(date_heure(), "navigateur_fermer_2_onglets %s" % reply)
                    tableau = []
                    choix = cle['navigateur_fermer_2_onglets']
                    if ( choix['action'] == 'script' ):
                        f = open("/tmp/talking.sh", "w")
                        f.write(choix['script'])
                        f.close()
                        subprocess.Popen( ['sh', '/tmp/talking.sh' ] ).pid
                    else:
                        tableau.append(r['command'])
                        for i in r['args']:
                            tableau.append(i)
                        subprocess.Popen( list(tableau) ).pid

                elif reply in musique:         # music fr
                    print("musique %s" % reply)
                    print("Utiliser exit pour quitter l'assistant vocal sans killer vlc (Ctrl-C le kille)")
                    # commande initiale brute
                    # ~ subprocess.Popen( ['vlc', '/media/fbx/xavbox/type1/', '>/dev/null', '2>&1']).pid


                    # --------------------------------------
                    # OK CI DESSOUS
                    # ~ tableau = []
                    # ~ tableau.append(cle['musique']['command'])
                    # ~ for i in cle['musique']['args']:
                        # ~ tableau.append(i)
                    # ~ subprocess.Popen( list(tableau) ).pid
                    # --------------------------------------
                    tableau = []
                    tableau.append(cle['musique']['command'])
                    for i in cle['musique']['args']:
                        tableau.append(i)
                    subprocess.Popen( list(tableau) ).pid

                elif reply in musique_off:
                    print("musique_off %s" % reply)
                    tableau = []
                    tableau.append(cle['musique_off']['command'])
                    for i in cle['musique_off']['args']:
                        tableau.append(i)
                    subprocess.Popen( list(tableau) ).pid

                # elif reply in corona:
                    # print("corona")
                    # subprocess.Popen( ['firefox-esr', 'http://gangand.net/cc/coro/stats/index.php?device=PC']).pid

                elif reply in corona:
                    print("corona")
                    subprocess.Popen( ['chromium-browser', 'http://gangand.net/cc/coro/stats/index.php?device=PC']).pid

                    tableau = []
                    choix = cle['corona']
                    if ( choix['action'] == 'browser' ):
                            subprocess.Popen( ['chromium-browser', choix['site'] ] ).pid
                    else:
                            tableau.append(r['command'])
                            for i in r['args']:
                                tableau.append(i)
                            subprocess.Popen( list(tableau) ).pid

                elif reply.split()[0] in musique:
                    print("Vous avez dit: %s" % reply)
                    liste = reply.split(' ')
                    print("Recherche de musique ciblée sur %s" % ' '.join(liste[1:]))
                    # recherche_musique = 'https://www.google.com/search?q=' + ('+').join(liste)
                    # print(recherche_google)
                    # subprocess.Popen( ['chromium-browser', recherche_google]).pid

                else:
                    print("You said: %s" % reply)
                    liste = reply.split(' ')
                    recherche_google = 'https://www.google.com/search?q=' + ('+').join(liste)
                    print(recherche_google)
                    subprocess.Popen( ['chromium-browser', recherche_google]).pid

                # else:
                    # print("You said: %s" % reply)
                    # os.system("flite -o /tmp/flite.wav -t %s " % reply)

            except sr.UnknownValueError:
                print("L'API Google API n'a pas compris ...")
            except sr.RequestError as e:
                print("!")
                #print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))

    except KeyboardInterrupt:
        pass


def lancement_intelligent():
    """ Utiliser un fichier .ini
    plus facile à éditer """
    try:
        print("Un instant SVP ...")
        with m as source: r.adjust_for_ambient_noise(source)
        # The above line takes an ambient sample of noise to set threshhold levels.
        # This may not work on all microphones and should be tweaked as needed
        while True:
            print("Prêt, veuillez parler. (Presser Ctrl+c ou dire quitter pour quitter)")
            with m as source: audio = r.listen(source)
            print(".")
            try:
                # value = r.recognize_google(audio)
                value = r.recognize_google(audio, language="fr-FR")
                # passer en francais
                # https://stackoverflow.com/questions/49732536/how-to-change-the-language-of-google-speech-recognition

                if str is bytes:
                    reply = "{}".format(value).encode("utf-8")
                else:
                    reply = "{}".format(value)
                print("reply = %s " % reply)

                if reply in exitWord:
                    quit()

                # for i, j in enumerate(cle):
                    # print("%15s : %s" % (j, cle[j]['mots']) )
#                        musique : ['boutique', 'musique']
#                       tmp_foot : ['sport', 'foot', 'football', "championnat d'Europe", "champion d'Europe"]
#                  television_en : ['Billy', 'CD', 'DD', 'Siri', 'television']
#                      domotique : ['boutique', 'domotique']
#                        EDITION : ['\xc3\xa9dition programme']
#                       lampe_fr : ['allume la lampe']
#                          meteo : ['quel temps', 'm\xc3\xa9t\xc3\xa9o']
#                         corona : ['Corona', 'corona']
#                       REBOOTER : ['red\xc3\xa9marrer la machine']
#                       internet : ['internet']
#                       exitWord : ['quitter', 'Quitterie']
#                    libreoffice : ['libre', 'libreoffice']
#                     SAUVEGARDE : ['sauvegarde programme']
#                   france_inter : ['inter', 'france inter', 'France Inter']
#                    musique_off : ['arr\xc3\xaate la musique', 'arr\xc3\xaater la musique', 'arr\xc3\xaater musique', 'arr\xc3\xaate musique']

                cle_trouvee = False
                for i, j in enumerate(cle):
                    # print("%15s : %s" % (j, cle[j]['mots']) )
                    if reply in cle[j]['mots']:
                        if cle[j]['action'] == 'script':    # quasiment tout peut être scripté, action 'script' à privilégier
                            f = open("/tmp/talking.sh", "w")
                            f.write(cle[j]['script'])
                            f.close()
                            subprocess.Popen( ['sh', '/tmp/talking.sh' ] ).pid
                            cle_trouvee = True
                        break
                if cle_trouvee = False: # recherche internet
                    print("You said: %s" % reply)
                    liste = reply.split(' ')
                    recherche_google = 'https://www.google.com/search?q=' + ('+').join(liste)
                    print(recherche_google)
                    subprocess.Popen( ['chromium-browser', recherche_google]).pid

            except sr.UnknownValueError:
                print("L'API Google API n'a pas compris ...")
            except sr.RequestError as e:
                print("!")
                #print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e))

    except KeyboardInterrupt:
        pass



# lancement_original()
lancement_intelligent()

# 'action' : 'main_pgm'
# 'action' : 'exec' ,
# 'action' : 'script' ,
# 'action' : 'browser' ,
# 'action' : 'gpio_domotique' ,
# 'action' : 'recherche_fichier' ,