Andro0s commited on
Commit
9d14874
·
verified ·
1 Parent(s): a67fbaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -113
app.py CHANGED
@@ -1,136 +1,63 @@
1
  import gradio as gr
2
- from TTS.api import TTS
 
3
  import torch
4
- import os
 
5
 
6
- # Configurar device
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
 
9
- # Cargar modelo de español (se descarga automáticamente la primera vez)
10
- print("🔄 Cargando modelo de TTS en español...")
11
- tts = TTS("tts_models/es/css10/vits").to(device)
12
- print("✅ Modelo cargado correctamente")
13
 
14
- def text_to_speech(text, speed=1.0):
15
- """
16
- Convierte texto a voz en español latino
17
- """
 
 
 
 
18
  if not text or not text.strip():
19
- return None, "⚠️ Por favor ingresa algún texto"
20
 
21
- # Limitar longitud para evitar tiempos muy largos
22
- if len(text) > 500:
23
- return None, "⚠️ El texto es muy largo. Máximo 500 caracteres."
24
 
25
  try:
26
- output_path = "output.wav"
27
-
28
- # Generar audio
29
- tts.tts_to_file(
30
- text=text,
31
- file_path=output_path,
32
- speed=speed
33
  )
34
 
35
- return output_path, "✅ ¡Audio generado con éxito!"
 
 
 
 
36
 
37
  except Exception as e:
38
  return None, f"❌ Error: {str(e)}"
39
 
40
- # CSS personalizado para mejorar la apariencia
41
- custom_css = """
42
- .gradio-container {
43
- max-width: 800px !important;
44
- margin: 0 auto;
45
- }
46
- .title {
47
- text-align: center;
48
- color: #2c3e50;
49
- }
50
- """
51
-
52
- # Crear la interfaz
53
- with gr.Blocks(css=custom_css, title="🎙️ TTS Español Latino") as demo:
54
-
55
- gr.Markdown("""
56
- <div class="title">
57
- <h1>🎙️ Lector de Texto a Voz</h1>
58
- <h3>Español Latino - Rápido & Gratis</h3>
59
- </div>
60
-
61
- Escribe cualquier texto y escúchalo en voz alta en segundos.
62
- """)
63
 
64
  with gr.Row():
65
- with gr.Column(scale=2):
66
- text_input = gr.Textbox(
67
- label="📝 Texto a convertir",
68
- placeholder="Escribe o pega aquí tu texto en español...",
69
- lines=4,
70
- max_lines=6
71
- )
72
-
73
- with gr.Row():
74
- speed_slider = gr.Slider(
75
- minimum=0.5,
76
- maximum=1.5,
77
- value=1.0,
78
- step=0.1,
79
- label="⚡ Velocidad de voz"
80
- )
81
-
82
- generate_btn = gr.Button(
83
- "🔊 Generar Voz",
84
- variant="primary",
85
- size="lg"
86
- )
87
-
88
- status_text = gr.Textbox(
89
- label="Estado",
90
- interactive=False,
91
- value="Listo para generar audio"
92
- )
93
-
94
- with gr.Column(scale=1):
95
- audio_output = gr.Audio(
96
- label="🔊 Tu Audio",
97
- type="filepath",
98
- autoplay=False
99
- )
100
-
101
- gr.Markdown("""
102
- ### 💡 Consejos:
103
- - **Máximo**: 500 caracteres
104
- - Usa puntuación para pausas naturales
105
- - Ajusta la velocidad si es necesario
106
- - Funciona mejor con oraciones completas
107
- """)
108
-
109
- # Ejemplos rápidos
110
- gr.Examples(
111
- examples=[
112
- ["Hola, ¿cómo estás? Bienvenido a este lector de texto a voz."],
113
- ["El sol brilla intensamente sobre las playas de México."],
114
- ["La tecnología nos permite crear herramientas increíbles cada día."],
115
- ["¿Podrías repetir eso, por favor? No lo escuché bien."]
116
- ],
117
- inputs=text_input,
118
- label="🎯 Probar con ejemplos"
119
- )
120
 
121
- # Eventos
122
- generate_btn.click(
123
- fn=text_to_speech,
124
- inputs=[text_input, speed_slider],
125
- outputs=[audio_output, status_text]
126
- )
127
 
128
- # Limpiar estado al escribir
129
- text_input.change(
130
- fn=lambda: ("", "⌨️ Escribiendo..."),
131
- outputs=[audio_output, status_text]
132
- )
133
 
134
- # Lanzar
135
  if __name__ == "__main__":
136
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+ from datasets import load_dataset
4
  import torch
5
+ import soundfile as sf
6
+ import numpy as np
7
 
8
+ # Cargar modelo de TTS de Microsoft (pequeño y rápido)
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
 
11
+ print("🔄 Cargando modelo TTS...")
12
+ # Usamos un modelo específico para español más ligero
13
+ synthesizer = pipeline("text-to-speech", "microsoft/speecht5_tts", device=device)
 
14
 
15
+ # Cargar embeddings de speaker para variedad
16
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
17
+ speaker_embeddings = {
18
+ "hombre_1": torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0),
19
+ "mujer_1": torch.tensor(embeddings_dataset[7300]["xvector"]).unsqueeze(0),
20
+ }
21
+
22
+ def text_to_speech(text, speaker="hombre_1"):
23
  if not text or not text.strip():
24
+ return None, "⚠️ Ingresa texto"
25
 
26
+ if len(text) > 200:
27
+ return None, "⚠️ Máximo 200 caracteres"
 
28
 
29
  try:
30
+ # Generar
31
+ speech = synthesizer(
32
+ text,
33
+ forward_params={"speaker_embeddings": speaker_embeddings[speaker]}
 
 
 
34
  )
35
 
36
+ # Guardar
37
+ output_path = "output.wav"
38
+ sf.write(output_path, speech["audio"], samplerate=speech["sampling_rate"])
39
+
40
+ return output_path, "✅ ¡Listo!"
41
 
42
  except Exception as e:
43
  return None, f"❌ Error: {str(e)}"
44
 
45
+ with gr.Blocks(title="🎙️ TTS Local Español") as demo:
46
+ gr.Markdown("# 🎙️ Texto a Voz - Modelo Local")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  with gr.Row():
49
+ text_input = gr.Textbox(label="Texto", lines=3)
50
+ speaker_select = gr.Dropdown(
51
+ choices=["hombre_1", "mujer_1"],
52
+ value="hombre_1",
53
+ label="Voz"
54
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
+ btn = gr.Button("Generar", variant="primary")
57
+ audio = gr.Audio(label="Audio")
58
+ status = gr.Textbox(label="Estado")
 
 
 
59
 
60
+ btn.click(fn=text_to_speech, inputs=[text_input, speaker_select], outputs=[audio, status])
 
 
 
 
61
 
 
62
  if __name__ == "__main__":
63
  demo.launch()