import os import subprocess from flask import Flask, request, send_file from flask_cors import CORS import io app = Flask(__name__) CORS(app) MODELS = { "en": "en_US-lessac-medium.onnx", "hi": "hi_IN-pratham-medium.onnx", "ur": "ur_PK-fasih-medium.onnx" } @app.route("/", methods=["POST"]) def tts(): data = request.get_json() if not data or "text" not in data: return {"error": "No text provided"}, 400 text = data.get("text").strip() lang = data.get("lang", "en") if lang not in MODELS: return {"error": f"Language '{lang}' not supported. Use: {list(MODELS.keys())}"}, 400 model_file = MODELS[lang] command = [ "piper", "--model", model_file, "--output_file", "-" ] try: proc = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) # Send text stdout_data, stderr_data = proc.communicate(input=text.encode("utf-8")) if proc.returncode != 0: return {"error": stderr_data.decode()}, 500 # Return full audio file return send_file( io.BytesIO(stdout_data), mimetype="audio/wav", as_attachment=False, download_name="speech.wav" ) except Exception as e: return {"error": str(e)}, 500 if __name__ == "__main__": port = int(os.environ.get("PORT", 7860)) app.run(host="0.0.0.0", port=port)