#!/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

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()

# anciennes variables
corona      = ['Corona', 'corona']

game        = ['game']

lampe_fr = ['leave me alone', 'Lumia', 'meet me on', 'read me out', 'Romeo', 'Romania', 'rythmia', 'wake me up']

television_en = ['television']

# nouvelle variable unique a utiliser par la suite
# action 'browser' necessite 'site'
cle = {
    'corona': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net',
        'mots'   : ['corona']
        },
    
    'domotique' : { 
        'action' : 'gpio_domotique' ,
        'mots'   : ['boutique', 'domotique']
        },

    'exitWord': {
        'action' : 'main_pgm' ,
        'mots'   : ['quitter', 'Quitterie']
        },

    'game': {
        'action' : 'exec' ,
        'command': 'pysolfc',
        'mots'   : ['jeu', 'jeux', 'jeu du solitaire']
        },
    
    'internet': {
        'action' : 'browser' ,
        'site'   : 'http://gangand.net',
        'mots'   : ['internet']
        },
        
    'libreoffice_fr': {
        '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'   : ['météo', 'quel temps']
        },

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

    'musique_off' : {
        'action' : 'exec' ,
        'command': 'killall',
        'args'   : ['vlc'],
        'mots'   : ['arrête la musique', 'arrêter la 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']
        },

}

exitWord  = cle['exitWord']['mots']

domotique   = cle['domotique']['mots']
internet    = cle['internet']['mots']
# ~ radio        = cle['radio']['mots']
# ~ france_inter = cle['radios']['france_inter']['mots']
# ~ france_info  = cle['radios']['france_info' ]['mots']
meteo       = cle['meteo']['mots']
musique     = cle['musique']['mots']
musique_off = cle['musique_off']['mots']



import subprocess

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("OK, parlez. (Presser Ctrl+c ou dire quitter pour sortir)")
        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)
                
            if reply in exitWord:
                quit()
            
            elif reply in game:             # game anglais
                print("game")
                subprocess.Popen( ['pysolfc', '']).pid
            
            elif reply in internet:      # internet
                print("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
                print("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
                tableau = []
                r = cle['meteo']
                if ( r['action'] == 'browser' ):
                        # ~ print(cle['meteo']['site'])
                        # ~ print(cle['meteo']['site'])
                        # ~ print(cle['meteo']['site'])
                        # ~ print(cle['meteo']['site'])
                        # ~ print(cle['meteo']['site'])
                        subprocess.Popen( ['chromium-browser', r['site'] ] ).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)")
                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.split()[0] in internet:
                print("internet recherche")
                liste = replay.split(' ')[1:]
                recherche_google = ('+').join(liste)
                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
