User Tools

Site Tools


informatica:inteligencia_artificial:tts

This is an old revision of the document!


Español en Mac

git clone https://github.com/jpgallegoar/Spanish-F5.git
python3.11 -m venv venv
source venv/bin/activate
python -m pip install torch torchvision torchaudio
python -m pip install soundfile librosa gradio_client
python -m pip install -e .

Esta parte es sobretodo por Mac y la memoria compartida:

En el fichero Spanish-F5/src/f5_tts/infer/utils_infer.py línea 342 substituimos:

audio, sr = torchaudio.load(ref_audio)

Por:

import soundfile as sf
import torch

data, sr = sf.read(ref_audio)
audio = torch.FloatTensor(data).unsqueeze(0) if data.ndim == 1 else torch.FloatTensor(data).T

Ahora lo arrancamos y la primera vez tarda mucho porque se descarga el modelo:

./venv/bin/f5-tts_infer-gradio --port 7860 --host 127.0.0.1

Poner el ejecutable de ffmpeg en el path. Lo descargamos de https://evermeet.cx/ffmpeg/:

cp ffmpeg Spanish-F5/venv/bin/ffmpeg
chmod +x Spanish-F5/venv/bin/ffmpeg

Para ver la api:

python -c "from gradio_client import Client; print(Client('http://127.0.0.1:7860/').view_api())"

Levantar el servidor sin conexión a internet

GRADIO_ANALYTICS_ENABLED=False ./venv/bin/f5-tts_infer-gradio --port 7860 --host 127.0.0.1  

fichero generar_voz.py

import os
import sys
from gradio_client import Client, handle_file

# 1. Detectar automáticamente la carpeta de este experimento
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

ruta_audio_ref = os.path.join(BASE_DIR, "voz.wav")
ruta_texto_ref = os.path.join(BASE_DIR, "voz.txt")

# Verificar los argumentos de la línea de comandos (Script, Entrada, Salida)
if len(sys.argv) < 3:
    print("❌ Error: Faltan argumentos.")
    print("Uso correcto: python generar_voz.py <fichero_entrada.txt> <fichero_salida.mp3>")
    sys.exit(1)

# Capturar los nombres pasados por parámetro
nombre_entrada = sys.argv[1]
nombre_salida_mp3 = sys.argv[2]

ruta_entrada_texto = os.path.join(BASE_DIR, nombre_entrada)
ruta_salida_mp3 = os.path.join(BASE_DIR, nombre_salida_mp3)
ruta_temporal_wav = os.path.join(BASE_DIR, "temp_salida.wav")

# Verificar que los archivos base existan
if not os.path.exists(ruta_audio_ref) or not os.path.exists(ruta_texto_ref):
    print(f"❌ Error: No se encuentra 'voz.wav' o 'voz.txt' en: {BASE_DIR}")
    sys.exit(1)

if not os.path.exists(ruta_entrada_texto):
    print(f"❌ Error: No se encuentra el archivo de entrada '{nombre_entrada}' en: {BASE_DIR}")
    sys.exit(1)

# 2. Conectar al Gradio local
client = Client("http://127.0.0.1:7860/")

# 3. Leer textos
with open(ruta_texto_ref, "r", encoding="utf-8") as f:
    texto_referencia = f.read().strip()

with open(ruta_entrada_texto, "r", encoding="utf-8") as f:
    nuevo_texto = f.read().strip()

if not nuevo_texto:
    print(f"⚠️ El archivo '{nombre_entrada}' está vacío.")
    sys.exit(1)

print(f"📖 Leyendo: {nombre_entrada}")
print(f"🗣️ Texto: \"{nuevo_texto}\"")
print(f"📥 Procesando en Spanish-F5...")

try:
    # 4. Llamada a la API
    resultado = client.predict(
        handle_file(ruta_audio_ref),   # ref_audio_orig
        texto_referencia,              # ref_text
        nuevo_texto,                   # gen_text
        "F5-TTS",                      # model
        False,                         # remove_silence
        0.15,                          # cross_fade_duration
        0.88,                          # speed
        api_name="/infer"
    )

    ruta_temporal_gradio = resultado[0]

    # 5. Guardar el WAV temporal de la IA
    if os.path.exists(ruta_temporal_wav):
        os.remove(ruta_temporal_wav)
    os.rename(ruta_temporal_gradio, ruta_temporal_wav)

    # 6. Convertir a MP3 usando el ffmpeg de tu entorno virtual
    print(f"🎵 Convirtiendo a MP3...")
    ruta_ffmpeg = os.path.abspath(os.path.join(BASE_DIR, "..", "..", "venv", "bin", "ffmpeg"))

    # Si no estuviera ahí, buscamos en el PATH general que ya reparamos
    if not os.path.exists(ruta_ffmpeg):
        ruta_ffmpeg = "ffmpeg"

    if os.path.exists(ruta_salida_mp3):
        os.remove(ruta_salida_mp3)

    comando_ffmpeg = f'{ruta_ffmpeg} -i "{ruta_temporal_wav}" -codec:a libmp3lame -qscale:a 2 "{ruta_salida_mp3}" -loglevel error'
    os.system(comando_ffmpeg)

    # Limpiar el archivo temporal
    if os.path.exists(ruta_temporal_wav):
        os.remove(ruta_temporal_wav)

    print(f"✅ ¡Éxito! Archivo MP3 generado en: {ruta_salida_mp3}")

except Exception as e:
    print(f"❌ Error: {e}")

Uso:

python generar_voz.py entrada.txt salida.mp3

COQUI TTS

instalamos pyenv para poder tener python 3.11

curl https://pyenv.run | bash

Metemos esto en .bashrc

# Load pyenv automatically by appending
# the following to 
# ~/.bash_profile if it exists, otherwise ~/.profile (for login shells)
# and ~/.bashrc (for interactive shells) :

export PYENV_ROOT="$HOME/.pyenv"
[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init - bash)"

# Restart your shell for the changes to take effect.

# Load pyenv-virtualenv automatically by adding
# the following to ~/.bashrc:

eval "$(pyenv virtualenv-init -)"

Cambiamos a python 3.11

pyenv install 3.11.9
pyenv global 3.11.9

Reiniciar shell

git clone https://github.com/idiap/coqui-ai-TTS.git
cd coqui-ai-TTS

Nos aseguramos versión 3.11 de python

python --version

Creamos entorno virtual

python -m venv venv --clear
source venv/bin/activate
pip install -U pip setuptools wheel
pip install --no-cache-dir torch torchaudio torchcodec
pip install -e .

Podemos listar los modelos:

tts --list_models

Ahora ya funciona, la primera vez se descarga el modelo y tarda bastante:

tts   --text "Hola, esto es una prueba de Coqui TTS funcionando en español."   --model_name tts_models/es/css10/vits   --out_path salida.wav

Entrenar COQUI TTS

tts \
  --model_name tts_models/multilingual/multi-dataset/xtts_v2 \
  --text "Hola, estoy probando mi propia voz clonada" \
  --speaker_wav /ruta/a/tu_audio.wav \
  --language_idx es \
  --out_path salida.wav
informatica/inteligencia_artificial/tts.1782464696.txt.gz · Last modified: by jose