#
#   python_voz_texto_a_voz_con_piper.py
#
#   Convertir de Texto a Voz (Text To Speech - TTS) usando 'piper'
#
#   Se requiere instalar "piper-tts": https://pypi.org/project/piper-tts/
#       $ pip3 install piper-tts
#   Se requiere instalar "soundfile": https://pypi.org/project/soundfile/
#       $ pip3 install soundfile
#   Se requiere instalar "sounddevice": https://pypi.org/project/sounddevice/
#       $ pip3 install sounddevice
#   Se requiere instalar "simpleaudio": https://pypi.org/project/simpleaudio/
#       $ pip3 install simpleaudio
#
#   Se requiere descargar los modelos de voz previamente (archivos "onnx" junto con su respectivo archivo "json"):
#       https://github.com/OHF-Voice/piper1-gpl
#   Archivos "onnx" en Español:
#       https://huggingface.co/rhasspy/piper-voices/tree/main/es
#
#   Rogelio Ferreira Escutia - marzo 2026
#

# Bibliotecas
from piper.voice import PiperVoice
import os
import wave

# Modelos "onxx"" de voz
#
# Carl: Voz de Hombre en Español (de España)
MODEL_PATH = "es_ES-carlfm-high.onnx"   # https://huggingface.co/friyin/vits-piper-es_ES-carlfm-high/tree/main
# Ald: Voz de Hombre en Español (de México)
MODEL_PATH = "es_MX-ald-medium.onnx"    # https://huggingface.co/rhasspy/piper-voices/tree/a60bfb1358818a92675b3a2d9d48fb8ea47035c1/es/es_MX/ald/medium
# Laura: Voz de Mujer en Español (de México)
MODEL_PATH = "es_MX-laura-high.onnx"    # https://huggingface.co/HirCoir/Piper-TTS-Laura/tree/main
# Claude: Voz de Mujer en Español (de México)
MODEL_PATH = "es_MX-claude-high.onnx"   # https://huggingface.co/rhasspy/piper-voices/tree/main/es/es_MX/claude/high

# Archivo ".wav" de salida
VOICE_OUTPUT_WAV = "voice_output.wav"

# Texto a convertir a ".wav"
texto = "Hola! Soy Ponytron! Tu robot de servicio listo para atenderte!"

def text_to_wav(text, output_path, model_path):
    # Cargar la voz de Piper
    voice = PiperVoice.load(model_path)
    # Sintetizar el texto y guardarlo en un archivo WAV
    with wave.open(output_path, "wb") as wav_file:
        voice.synthesize_wav(text, wav_file)
    print("Archivo '",VOICE_OUTPUT_WAV, "' generado, usando el Modelo: ", MODEL_PATH,"\n")

if __name__ == "__main__":
    print("\nConvertir de Texto a Voz (Text To Speech - TTS) usando 'piper'\n")
    # Verificar que el modelo existe
    if not os.path.exists(MODEL_PATH):
        print("Error: No se encontró el modelo: ", MODEL_PATH)
    else:
        text_to_wav(texto, VOICE_OUTPUT_WAV, MODEL_PATH)
