import os import base64 import uvicorn import json from flask import Flask, request, jsonify import edge_tts import asyncio app = Flask(__name__) async def TextToAudioFile(text: str, model: str) -> str: """Converts text to an audio file and returns its base64 encoded string.""" file_path = "Output/main.mp3" # Convert text to audio communicate = edge_tts.Communicate(text, voice=model, pitch='+5Hz', rate='+10%') await communicate.save(file_path) # Read the audio file and encode it to base64 with open(file_path, 'rb') as audio_file: audio_data = audio_file.read() audio_base64 = base64.b64encode(audio_data).decode('utf-8') return audio_base64 @app.route('/tts', methods=['POST']) def tts(): """Handles POST requests for text-to-speech conversion.""" data = request.get_json() model = data.get('model', 'en-GB-SoniaNeural') if not data or 'text' not in data: return jsonify({'error': 'Text is required'}), 400 text = data['text'] # Run the async function in the event loop audio_base64 = asyncio.run(TextToAudioFile(text,model)) return jsonify({'audio': audio_base64}), 200 if __name__ == '__main__': # Run the Flask app app.run(debug=True, port=5000)