from flask import Flask, render_template, request, jsonify, after_this_request from io import BytesIO import base64 import subprocess import os import random import string import re import logging app = Flask(__name__) # Define los nombres asignados a modelos específicos, en caso de no existir no se muestran model_names = { "Español México | Kamora Neuronal": { "model_path": "es_ES-kamora-7539-high.onnx", "replacements": [('\n', '. ')] }, "Español México | Claude": { "model_path": "es_MX-claude-14947-epoch-high.onnx", "replacements": [('(', ','), (')', ','), ('?', ','), ('¿', ','), (':', ','), ('\n', ' ')] } } # Comprueba si los modelos definidos existen en la carpeta de modelos model_folder = '/home/app/' # Asegúrate de definir la ruta correcta a la carpeta de modelos existing_models = [model_name for model_name in model_names.keys() if os.path.isfile(os.path.join(model_folder, model_names[model_name]["model_path"]))] def multiple_replace(text, replacements): # Iterar sobre cada par de remplazo for old, new in replacements: text = text.replace(old, new) return text def filter_text(text, model_name): if model_name in model_names: replacements = model_names[model_name]["replacements"] # Realizar reemplazos específicos del modelo filtered_text = multiple_replace(text, replacements) # Escapar todos los caracteres especiales dentro de las comillas filtered_text = re.sub(r'(["\'])', lambda m: "\\" + m.group(0), filtered_text) return filtered_text else: logging.error(f"No se encontró el modelo '{model_name}'.") return None # Define una función para convertir texto a voz def convert_text_to_speech(text, model_name): filtered_text = filter_text(text, model_name)[:500] # Limitar el texto a 500 caracteres if filtered_text is None: return None random_name = ''.join(random.choices(string.ascii_letters + string.digits, k=8)) + '.wav' output_file = os.path.join(file_folder, random_name) app.logger.info("Audio file created at: %s", output_file) piper_exe = os.path.join(file_folder, 'piper') # Ajusta la ruta para piper if os.path.isfile(piper_exe): comando = f'echo {filtered_text} | "{piper_exe}" -m {model_name} -f {output_file}' subprocess.run(comando, shell=True) return output_file else: return "No se encontró el archivo piper.exe en el directorio correcto." @app.route('/') def index(): model_options = existing_models app.logger.info("Contents of current folder: %s", os.listdir(file_folder)) return render_template('index.html', model_options=model_options) @app.route('/convert', methods=['POST']) def convert_text(): text = request.form['text'] model = request.form['model'] output_file = convert_text_to_speech(text, model) @after_this_request def remove_file(response): try: os.remove(output_file) app.logger.info("Audio file deleted: %s", output_file) except Exception as error: app.logger.error("Error deleting file: %s", error) return response if output_file is None: return "Error: No se pudo generar el archivo de audio." with open(output_file, 'rb') as audio_file: audio_content = audio_file.read() audio_base64 = base64.b64encode(audio_content).decode('utf-8') response = jsonify({'audio_base64': audio_base64}) return response if __name__ == '__main__': app.run(host='0.0.0.0', port=7860, debug=False)