HirCoir commited on
Commit
029b0ee
1 Parent(s): 4ff87f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -84
app.py CHANGED
@@ -1,6 +1,4 @@
1
- import logging
2
  from flask import Flask, render_template, request, jsonify, after_this_request
3
- from functools import wraps
4
  from io import BytesIO
5
  import base64
6
  import subprocess
@@ -8,104 +6,67 @@ import os
8
  import random
9
  import string
10
  import re
11
- import sys
12
-
13
- # Configuración del registro
14
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
15
 
16
  app = Flask(__name__)
17
 
18
- # Define el directorio donde se guardan los archivos
19
- file_folder = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
20
- temp_audio_folder = "/home/app/temp_audio/"
21
- model_folder = "/home/app/"
22
- piper_binary_path = "/home/app/piper"
23
-
24
- # Define los nombres asignados a modelos específicos
25
- model_names = {
26
- "Español México | Claude": "es_MX-claude-14947-epoch-high.onnx",
27
- "Español México | Cortana v1": "es_MX-cortana-19669-epoch-high.onnx",
28
- "Español México | TheGevy": "es_MX-gevy-10196-epoch-high.onnx",
29
- "English United States Example": "en_US-ljspeech-high.onnx"
30
- }
31
 
32
  def filter_text(text):
33
- filtered_text = re.sub(r'[^\w\s,.\(\):\u00C0-\u00FF]', '', text) # Filtra caracteres no deseados
34
- filtered_text = filtered_text.replace('\n', ' ') # Reemplaza saltos de línea con espacios
 
35
  return filtered_text
36
 
37
- def convert_text_to_speech(text, model):
38
- filtered_text = filter_text(text)
 
 
 
39
  random_name = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) + '.wav'
40
- output_file = os.path.join(temp_audio_folder, random_name)
41
-
42
- if os.path.isfile(piper_binary_path) and model in model_names:
43
- model_path = os.path.join(model_folder, model_names[model])
44
- if os.path.isfile(model_path):
45
- # Construye el comando para ejecutar Piper
46
- command = f'echo "{filtered_text}" | "{piper_binary_path}" -m {model_path} -f {output_file}'
47
- try:
48
- subprocess.run(command, shell=True, check=True)
49
- return output_file
50
- except subprocess.CalledProcessError as e:
51
- logging.error(f"Error al ejecutar el comando: {e}")
52
- else:
53
- logging.error(f"Modelo '{model}' no encontrado en la ubicación especificada.")
54
  else:
55
- logging.error(f"No se encontró el binario de Piper en la ubicación especificada o modelo no asignado.")
56
- return None
57
 
58
- # Define una función decoradora para restringir el acceso a la ruta /convert
59
- def restrict_access(func):
60
- @wraps(func)
61
- def wrapper(*args, **kwargs):
62
- # Verifica si la solicitud se hizo desde la página index.html
63
- referer = request.headers.get("Referer")
64
- if referer and referer.endswith("/"):
65
- # Permite el acceso a la función si la solicitud proviene de la página index.html
66
- return func(*args, **kwargs)
67
- else:
68
- # Devuelve un mensaje de error o redirecciona a otra página
69
- return "Acceso no autorizado", 403 # Código de respuesta HTTP 403 - Forbidden
70
- return wrapper
71
 
72
  @app.route('/')
73
  def index():
74
- model_options = list(model_names.keys())
75
- # Registra el contenido de la carpeta actual
76
- logging.info("Contents of current folder: %s", os.listdir(file_folder))
 
77
  return render_template('index.html', model_options=model_options)
78
 
79
  @app.route('/convert', methods=['POST'])
80
- @restrict_access
81
  def convert_text():
82
- try:
83
- text = request.form['text']
84
- model = request.form['model']
85
- output_file = convert_text_to_speech(text, model)
86
-
87
- @after_this_request
88
- def remove_file(response):
89
- try:
90
- if output_file and os.path.exists(output_file):
91
- os.remove(output_file)
92
- logging.info("Audio file deleted: %s", output_file)
93
- except Exception as error:
94
- logging.error("Error deleting file: %s", error)
95
- return response
96
-
97
- if output_file:
98
- with open(output_file, 'rb') as audio_file:
99
- audio_content = audio_file.read()
100
-
101
- audio_base64 = base64.b64encode(audio_content).decode('utf-8')
102
- return jsonify({'audio_base64': audio_base64})
103
- else:
104
- return jsonify({'error': 'Error al convertir texto a voz'}), 500 # Internal Server Error
105
- except Exception as e:
106
- logging.error("Error processing request: %s", e)
107
- return jsonify({'error': 'Error interno del servidor'}), 500 # Internal Server Error
108
 
109
  if __name__ == '__main__':
110
- logging.info("Se está iniciando la aplicación.")
111
- app.run(host='0.0.0.0', port=7860, debug=False)
 
 
1
  from flask import Flask, render_template, request, jsonify, after_this_request
 
2
  from io import BytesIO
3
  import base64
4
  import subprocess
 
6
  import random
7
  import string
8
  import re
 
 
 
 
9
 
10
  app = Flask(__name__)
11
 
12
+ # Define the folder where files are saved
13
+ file_folder = '/home/app/'
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def filter_text(text):
16
+ filtered_text = re.sub(r'[^\w\s,.\(\):\u00C0-\u00FF]', '', text)
17
+ filtered_text = filtered_text.replace('\n', ' ')
18
+ filtered_text = filtered_text.replace('(', ',').replace(')', ',')
19
  return filtered_text
20
 
21
+ def convert_text_to_speech(parrafo, model):
22
+ # Limit text to 500 characters
23
+ parrafo = parrafo[:100000]
24
+
25
+ parrafo_filtrado = filter_text(parrafo)
26
  random_name = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) + '.wav'
27
+ output_file = os.path.join(file_folder, random_name)
28
+ app.logger.info("Audio file created at: %s", output_file)
29
+ piper_exe = os.path.join(file_folder, 'piper') # Adjusted the path for piper
30
+
31
+ if os.path.isfile(piper_exe):
32
+ comando = f'echo {parrafo_filtrado} | "{piper_exe}" -m {model} -f {output_file}'
33
+ subprocess.run(comando, shell=True)
34
+ return output_file
 
 
 
 
 
 
35
  else:
36
+ return "The piper.exe file was not found in the correct directory."
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  @app.route('/')
40
  def index():
41
+ model_folder = file_folder # Adjusted the model folder to file_folder
42
+ model_options = [file for file in os.listdir(model_folder) if file.endswith('.onnx')]
43
+ # Log the contents of the current folder
44
+ app.logger.info("Contents of current folder: %s", os.listdir(file_folder))
45
  return render_template('index.html', model_options=model_options)
46
 
47
  @app.route('/convert', methods=['POST'])
 
48
  def convert_text():
49
+ text = request.form['text']
50
+ model = request.form['model']
51
+ output_file = convert_text_to_speech(text, model)
52
+
53
+ @after_this_request
54
+ def remove_file(response):
55
+ try:
56
+ os.remove(output_file)
57
+ app.logger.info("Audio file deleted: %s", output_file)
58
+ except Exception as error:
59
+ app.logger.error("Error deleting file: %s", error)
60
+ return response
61
+
62
+ with open(output_file, 'rb') as audio_file:
63
+ audio_content = audio_file.read()
64
+
65
+ audio_base64 = base64.b64encode(audio_content).decode('utf-8')
66
+
67
+ response = jsonify({'audio_base64': audio_base64})
68
+
69
+ return response
 
 
 
 
 
70
 
71
  if __name__ == '__main__':
72
+ app.run(host='0.0.0.0', port=7860, debug=False)