#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This file is part of Pymetrick.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

try:
    from pymetrick.version import __author__, __version__, __license__, __copyright__
except ImportError:
    raise ImportError(
        'Failed to find (autogenerated) version.py '
    )

__date__ = '2023-04-22'
__credits__ = ''
__text__ = 'Transformar texto en voz'
__file__ = 'speech.py'

#--- CHANGES ------------------------------------------------------------------
# 2023-04-22 v0.01 PL: - First version

import os, sys
# pip install pyttsx3
from   platform import system
import pyttsx3
import logging
import logging.handlers

'''
DEBUG - debug message
INFO - info message
WARNING - warn message
ERROR - error message
CRITICAL - critical message
'''
LOG_LEVEL_VALUE = {'DEBUG':10,'INFO':20,'WARNING':30,'ERROR':40,'CRITICAL':50}
if str(os.environ.get('PYMETRICK_LOG_LEVEL',None)).upper() in LOG_LEVEL_VALUE:
    LOG_LEVEL = LOG_LEVEL_VALUE[str(os.environ.get('PYMETRICK_LOG_LEVEL')).upper()]
else:
    LOG_LEVEL = 30
LOG_FILENAME = '-'.join([os.path.abspath(__file__).split(os.sep)[len(os.path.abspath(__file__).split(os.sep))-1],])[:-3]
LOG = logging.getLogger(LOG_FILENAME)

if 'LD_LIBRARY_PATH' in list(os.environ.keys()):
    # CGI environment
    sys.stdout = sys.stderr
    logging.basicConfig(stream = sys.stderr, level=LOG_LEVEL, format='%(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
else:
    # not CGI environment
    logging.basicConfig(stream=sys.stderr)
    hdlr = logging.handlers.RotatingFileHandler(filename=LOG_FILENAME+'.log',mode='a', encoding='utf-8', maxBytes=1048576, backupCount=3)
    formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s')
    hdlr.setFormatter(formatter)
    LOG.addHandler(hdlr)
    LOG.setLevel(LOG_LEVEL)
    
class Speech(object):

    def __init__(self, **kwargs):

        try:
        
            self.thisOS = system() # averiguar Sistema operativo actual
            self.engine = pyttsx3.init()    # inicializar motor de voz
            if 'rate' in kwargs:
                self.engine.setProperty('rate', kwargs['rate'])
            else:
                self.engine.setProperty('rate'  ,130)   # Aumentar velocidad 30%
            if 'voice' in kwargs:
                self.engine.setProperty('voice', kwargs['voice'])
            else:
                if self.thisOS == 'Linux':
                    self.engine.setProperty('voice', 'spanish-latin-am+f5') #ASIGNAR Español latino
                    # agregar +f5 para simular voz femenina (1-5)
                if self.thisOS == 'Windows':
                    voices = engine.getProperty('voices')       #getting details of current voice
                    self.engine.setProperty('voice', voices[0].id)  #changing index, changes voices. o for male
                    #self.engine.setProperty('voice', voices[1].id)   #changing index, changes voices. 1 for female

                    #self.engine.setProperty('voice',f'''HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\{voices[0]}''')
            if 'volume' in kwargs:
                self.engine.setProperty('volume', kwargs['volume'])
            else:   
                self.engine.setProperty('volume',1.0)   # Poner el volumen al 100%: Minimo:0, Maximo: 1
        except Exception as e:
            tb = sys.exc_info()[2]
            LOG.error('<%s> in line %s !!!' % (str(e),tb.tb_lineno))


    def say(self,text=None):
        try:
            if text is not None:
                self.engine.say(text)
                self.engine.runAndWait()                 # Esperar a que termine de hablar
                self.engine.stop()                       # Detener motor tts            
        except Exception as e:
            tb = sys.exc_info()[2]
            LOG.error('<%s> in line %s !!!' % (str(e),tb.tb_lineno))            

if __name__ == '__main__' :
    print ('''copyright {0}'''.format( __copyright__))
    print ('''license {0}'''.format( __license__))
    print ('''version {0}'''.format( __version__))
    if len(sys.argv) < 2:
        sys.stderr.write("for help use -h o --help")
    elif sys.argv[1]=='-h' or sys.argv[1]=='--help':
        print (b'''Speech : Transformar texto en voz\n''')
    
