File size: 1,268 Bytes
c9f1429 040ed19 c9f1429 069dbf4 c9f1429 040ed19 371feb6 c9f1429 040ed19 c9f1429 040ed19 c9f1429 040ed19 371feb6 040ed19 c9f1429 040ed19 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
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 = "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)
|