Spaces:
Paused
Paused
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, Response, stream_with_context, jsonify
|
| 2 |
+
from kokoro_onnx import Kokoro
|
| 3 |
+
import soundfile as sf
|
| 4 |
+
import io
|
| 5 |
+
|
| 6 |
+
app = Flask(__name__)
|
| 7 |
+
|
| 8 |
+
print("--- STARTUP ---")
|
| 9 |
+
# Because we set the ENV variable in Dockerfile, we don't need arguments here!
|
| 10 |
+
print("Loading Kokoro...")
|
| 11 |
+
kokoro = Kokoro("kokoro-v1.0.int8.onnx", "voices-v1.0.bin")
|
| 12 |
+
print("SUCCESS: Model Loaded!")
|
| 13 |
+
|
| 14 |
+
@app.route("/", methods=["GET"])
|
| 15 |
+
def home():
|
| 16 |
+
return "Kokoro TTS API is Online!"
|
| 17 |
+
|
| 18 |
+
# Universal Route (Accepts /v1 or no /v1)
|
| 19 |
+
@app.route("/audio/speech", methods=["POST"])
|
| 20 |
+
@app.route("/v1/audio/speech", methods=["POST"])
|
| 21 |
+
def generate_speech():
|
| 22 |
+
try:
|
| 23 |
+
data = request.json
|
| 24 |
+
text = data.get("input", "")
|
| 25 |
+
voice = data.get("voice", "af_bella")
|
| 26 |
+
speed = float(data.get("speed", 1.0))
|
| 27 |
+
|
| 28 |
+
def generate_stream():
|
| 29 |
+
samples, sample_rate = kokoro.create(
|
| 30 |
+
text,
|
| 31 |
+
voice=voice,
|
| 32 |
+
speed=speed,
|
| 33 |
+
lang="en-us"
|
| 34 |
+
)
|
| 35 |
+
buffer = io.BytesIO()
|
| 36 |
+
sf.write(buffer, samples, sample_rate, format='WAV')
|
| 37 |
+
buffer.seek(0)
|
| 38 |
+
yield buffer.read()
|
| 39 |
+
|
| 40 |
+
return Response(stream_with_context(generate_stream()), mimetype="audio/wav")
|
| 41 |
+
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"Error: {e}")
|
| 44 |
+
return jsonify({"error": str(e)}), 500
|
| 45 |
+
|
| 46 |
+
@app.route("/v1/models", methods=["GET"])
|
| 47 |
+
@app.route("/models", methods=["GET"])
|
| 48 |
+
def list_models():
|
| 49 |
+
return jsonify({"data": [{"id": "kokoro", "object": "model"}]})
|
| 50 |
+
|
| 51 |
+
@app.route("/v1/audio/voices", methods=["GET"])
|
| 52 |
+
@app.route("/audio/voices", methods=["GET"])
|
| 53 |
+
def list_voices():
|
| 54 |
+
return jsonify({"voices": list(kokoro.get_voices())})
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
app.run(host="0.0.0.0", port=7860)
|