HirCoir commited on
Commit
631c13e
1 Parent(s): 10de322

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -41
app.py CHANGED
@@ -1,66 +1,55 @@
1
- import argparse
 
 
2
  import subprocess
3
  import os
4
- import sys
5
  import random
6
  import string
7
- import gradio as gr
8
- import tempfile
9
  import re
10
 
 
 
11
  def filter_text(text):
12
- # Expresión regular para permitir solo letras de la A a la Z en mayúsculas y minúsculas,
13
- # letras con acentos utilizadas en español México, números, comas, puntos, paréntesis, dos puntos y espacios
14
- filtered_text = re.sub(r'[^A-Za-zÁÉÍÓÚÜáéíóúü0-9,.\(\):\s]', '', text)
15
- # Eliminar saltos de línea y reemplazar paréntesis por comas
16
  filtered_text = filtered_text.replace('\n', ' ')
17
  filtered_text = filtered_text.replace('(', ',').replace(')', ',')
18
  return filtered_text
19
 
20
  def convert_text_to_speech(parrafo, model):
21
  parrafo_filtrado = filter_text(parrafo)
22
-
23
- # Determinar el directorio base dependiendo de si se ejecuta desde el código fuente o desde el ejecutable congelado
24
- if getattr(sys, 'frozen', False):
25
- # La aplicación se está ejecutando desde un ejecutable congelado
26
- bundle_dir = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(sys.argv[0])))
27
- else:
28
- # La aplicación se está ejecutando desde el código fuente
29
- bundle_dir = os.path.abspath(os.path.dirname(__file__))
30
-
31
- # Generar un nombre de archivo aleatorio
32
  random_name = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) + '.wav'
33
  output_file = os.path.join('.', random_name)
34
-
35
- # Construir la ruta al archivo piper.exe
36
- piper_exe = os.path.join(bundle_dir, 'piper')
37
-
38
- # Verificar si la ruta es válida
39
  if os.path.isfile(piper_exe):
40
- # Ejecutar el comando para generar el archivo de audio
41
  comando = f'echo {parrafo_filtrado} | "{piper_exe}" -m {model} -f {output_file}'
42
  subprocess.run(comando, shell=True)
43
-
44
- # Devolver la ruta al archivo de audio generado
45
  return output_file
46
  else:
47
  return "El archivo piper.exe no se encontró en el directorio correcto."
48
 
49
- # Función para cargar y reproducir el archivo de audio en Gradio
50
- def play_audio(parrafo, model):
51
- output_file = convert_text_to_speech(parrafo, model)
 
 
 
 
 
 
 
 
 
 
 
52
  with open(output_file, 'rb') as audio_file:
53
  audio_content = audio_file.read()
54
- return audio_content
55
-
56
- # Crear la interfaz de Gradio
57
- input_text = gr.Textbox(label="Introduce el texto")
58
- model_options = [
59
- "es_MX-locutor-voice-11400-epoch-high.onnx",
60
- "otro_modelo.onnx",
61
- "es_MX-cortanav3-high.onnx",
62
- "es_MX-gafe-12232-epoch-high.onnx"
63
- ] # Agrega aquí más modelos si es necesario
64
- select_model = gr.Dropdown(model_options, label="Selecciona el modelo")
65
 
66
- gr.Interface(play_audio, inputs=[input_text, select_model], outputs=gr.Audio(), flagging_options=None).launch()
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ from io import BytesIO
3
+ import base64
4
  import subprocess
5
  import os
 
6
  import random
7
  import string
 
 
8
  import re
9
 
10
+ app = Flask(__name__)
11
+
12
  def filter_text(text):
13
+ filtered_text = re.sub(r'[^\w\s,.\(\):\u00C0-\u00FF]', '', text)
 
 
 
14
  filtered_text = filtered_text.replace('\n', ' ')
15
  filtered_text = filtered_text.replace('(', ',').replace(')', ',')
16
  return filtered_text
17
 
18
  def convert_text_to_speech(parrafo, model):
19
  parrafo_filtrado = filter_text(parrafo)
20
+ bundle_dir = os.path.abspath(os.path.dirname(__file__))
21
+ print("Cargando carpeta Modelos desde:", os.path.join(bundle_dir, 'Models'))
 
 
 
 
 
 
 
 
22
  random_name = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) + '.wav'
23
  output_file = os.path.join('.', random_name)
24
+ piper_exe = os.path.join(bundle_dir, './piper.exe')
25
+ print("Ejecutando piper.exe desde:", piper_exe)
26
+
 
 
27
  if os.path.isfile(piper_exe):
 
28
  comando = f'echo {parrafo_filtrado} | "{piper_exe}" -m {model} -f {output_file}'
29
  subprocess.run(comando, shell=True)
 
 
30
  return output_file
31
  else:
32
  return "El archivo piper.exe no se encontró en el directorio correcto."
33
 
34
+ @app.route('/')
35
+ def index():
36
+ model_folder = 'Models'
37
+ bundle_dir = os.path.abspath(os.path.dirname(__file__))
38
+ print("Cargando carpeta Modelos desde:", os.path.join(bundle_dir, model_folder))
39
+ model_options = [file for file in os.listdir(model_folder) if file.endswith('.onnx')]
40
+ return render_template('index.html', model_options=model_options)
41
+
42
+ @app.route('/convert', methods=['POST'])
43
+ def convert_text():
44
+ text = request.form['text']
45
+ model = request.form['model']
46
+ output_file = convert_text_to_speech(text, model)
47
+
48
  with open(output_file, 'rb') as audio_file:
49
  audio_content = audio_file.read()
50
+
51
+ audio_base64 = base64.b64encode(audio_content).decode('utf-8')
52
+ return jsonify({'audio_base64': audio_base64})
 
 
 
 
 
 
 
 
53
 
54
+ if __name__ == '__main__':
55
+ app.run(debug=True, host='0.0.0.0', port=7860)