Andro0s commited on
Commit
b3ce194
·
verified ·
1 Parent(s): 9de2af6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -22
app.py CHANGED
@@ -2,21 +2,45 @@ import gradio as gr
2
  from kokoro import KPipeline
3
  import numpy as np
4
  import torch
 
5
 
6
- # Detectar hardware (Hugging Face Spaces gratuitos usan CPU)
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
- # Inicializamos el pipeline de Kokoro para inglés americano ('a')
10
- # Esto descargará automáticamente el modelo de 82M parámetros
11
  pipeline = KPipeline(lang_code='e', device=device)
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  def tts_pro(text, voice_name):
14
  if not text or not text.strip():
15
  return None
16
 
17
  try:
18
- # Generar audio: devuelve fragmentos (graphenes, phonemes, audio)
19
- generator = pipeline(text, voice=voice_name, speed=1)
 
 
 
 
 
 
 
 
 
20
 
21
  audio_segments = []
22
  for _, _, audio in generator:
@@ -25,30 +49,80 @@ def tts_pro(text, voice_name):
25
  if not audio_segments:
26
  return None
27
 
28
- # Concatenamos los fragmentos de audio en un solo array de numpy
29
  final_audio = np.concatenate(audio_segments)
30
 
31
- # Devolvemos el sample rate (24000) y el audio para Gradio
32
  return (24000, final_audio)
33
 
34
  except Exception as e:
35
  print(f"Error en la generación: {e}")
36
  return None
37
 
38
- # Interfaz de usuario
39
- demo = gr.Interface(
40
- fn=tts_pro,
41
- inputs=[
42
- gr.Textbox(label="Texto", placeholder="Escribe el texto aquí..."),
43
- gr.Dropdown(
44
- ["af_bella", "af_alloy", "af_nova", "af_sarah", "af_sky", "am_adam"],
45
- label="Selecciona Voz",
46
- value="af_bella"
47
- )
48
- ],
49
- outputs=gr.Audio(label="Audio Generado"),
50
- title="Kokoro TTS v1.0 - Aliah Plus"
51
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  if __name__ == "__main__":
54
- demo.launch()
 
 
 
 
 
2
  from kokoro import KPipeline
3
  import numpy as np
4
  import torch
5
+ import os
6
 
7
+ # Detectar hardware
8
  device = "cuda" if torch.cuda.is_available() else "cpu"
9
 
10
+ # Inicializar pipeline - 'e' para español
 
11
  pipeline = KPipeline(lang_code='e', device=device)
12
 
13
+ # Lista COMPLETA de voces del Space original
14
+ VOICES = [
15
+ "af_alloy.pt", "af_aoede.pt", "af_bella.pt", "af_heart.pt", "af_jessica.pt",
16
+ "af_kore.pt", "af_nicole.pt", "af_nova.pt", "af_river.pt", "af_sarah.pt",
17
+ "af_sky.pt", "am_adam.pt", "am_echo.pt", "am_eric.pt", "am_fenrir.pt",
18
+ "am_liam.pt", "am_michael.pt", "am_onyx.pt", "am_puck.pt", "bf_alice.pt",
19
+ "bf_isabella.pt", "bf_lily.pt", "bm_daniel.pt", "bm_fable.pt", "bm_george.pt",
20
+ "bm_lewis.pt", "ef_dora.pt", "em_alex.pt", "em_santa.pt", "ff_siwis.pt",
21
+ "hf_alpha.pt", "hf_beta.pt", "hm_omega.pt", "hm_psi.pt", "if_sara.pt",
22
+ "im_nicola.pt", "jf_alpha.pt", "jf_gongitsune.pt", "jf_nezumi.pt",
23
+ "jf_tebukuro.pt", "jm_kumo.pt", "pf_dora.pt", "pm_alex.pt", "pm_santa.pt",
24
+ "zf_xiaobei.pt", "zf_xiaoni.pt", "zf_xiaoyi.pt", "zm_yunjian.pt",
25
+ "zm_yunxi.pt", "zm_yunxia.pt", "zm_yunyang.pt"
26
+ ]
27
+
28
  def tts_pro(text, voice_name):
29
  if not text or not text.strip():
30
  return None
31
 
32
  try:
33
+ # Verificar si el archivo de voz existe
34
+ voice_path = f"voices/{voice_name}"
35
+
36
+ # Si no está en voices/, buscar en el directorio actual
37
+ if not os.path.exists(voice_path):
38
+ voice_path = voice_name
39
+
40
+ print(f"Usando voz: {voice_path}")
41
+
42
+ # Generar audio - pasar la ruta del archivo .pt como voz
43
+ generator = pipeline(text, voice=voice_path, speed=1.0)
44
 
45
  audio_segments = []
46
  for _, _, audio in generator:
 
49
  if not audio_segments:
50
  return None
51
 
52
+ # Concatenar audio
53
  final_audio = np.concatenate(audio_segments)
54
 
 
55
  return (24000, final_audio)
56
 
57
  except Exception as e:
58
  print(f"Error en la generación: {e}")
59
  return None
60
 
61
+ # Crear la interfaz
62
+ with gr.Blocks(title="Kokoro TTS - Aliah Plus", theme=gr.themes.Soft()) as demo:
63
+ gr.Markdown("# 🎤 Kokoro TTS v1.0")
64
+ gr.Markdown("### Texto a Voz con múltiples voces")
65
+ gr.Markdown("Escribe el texto y selecciona una voz para generar audio.")
66
+
67
+ with gr.Row():
68
+ with gr.Column():
69
+ texto_input = gr.Textbox(
70
+ label="Texto a convertir",
71
+ placeholder="Escribe aquí el texto en español...",
72
+ lines=4,
73
+ max_lines=10
74
+ )
75
+
76
+ voz_seleccionada = gr.Dropdown(
77
+ choices=VOICES,
78
+ label="Selecciona una voz",
79
+ value="af_bella.pt",
80
+ info="Elige entre más de 50 voces diferentes"
81
+ )
82
+
83
+ generar_btn = gr.Button("🎵 Generar Audio", variant="primary")
84
+
85
+ with gr.Column():
86
+ audio_output = gr.Audio(
87
+ label="Audio Generado",
88
+ type="numpy",
89
+ interactive=False
90
+ )
91
+
92
+ # Ejemplos
93
+ gr.Markdown("### Ejemplos rápidos:")
94
+ ejemplos = gr.Examples(
95
+ examples=[
96
+ ["Hola, ¿cómo estás? Soy una voz generada por inteligencia artificial.", "af_bella.pt"],
97
+ ["Bienvenido al sistema de texto a voz más avanzado.", "af_nova.pt"],
98
+ ["La tecnología de síntesis de voz ha avanzado mucho.", "am_adam.pt"]
99
+ ],
100
+ inputs=[texto_input, voz_seleccionada],
101
+ outputs=audio_output,
102
+ fn=tts_pro,
103
+ cache_examples=False
104
+ )
105
+
106
+ # Conectar el botón
107
+ generar_btn.click(
108
+ fn=tts_pro,
109
+ inputs=[texto_input, voz_seleccionada],
110
+ outputs=audio_output
111
+ )
112
+
113
+ # Información adicional
114
+ gr.Markdown("---")
115
+ gr.Markdown("""
116
+ ### 📝 Notas:
117
+ - Las voces están en formato `.pt` y se cargan desde la carpeta `voices/`
118
+ - Tiempo de generación: ~5-10 segundos dependiendo del texto
119
+ - Formato de audio: 24kHz, mono
120
+ - Modelo: Kokoro TTS v1.0
121
+ """)
122
 
123
  if __name__ == "__main__":
124
+ demo.launch(
125
+ share=False,
126
+ server_name="0.0.0.0" if os.getenv('SPACE_ID') else None,
127
+ server_port=7860
128
+ )