Pdf / app.py
wave101828228's picture
Rename main.py to app.py
469967e verified
Raw History Blame Contribute Delete
1.5 kB
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
import sherpa_onnx
import soundfile as sf
import uuid
import os
app = FastAPI(title="K2 Matcha TTS API - Max Quality")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # ganti ke domain frontend lo pas production
allow_methods=["*"],
allow_headers=["*"],
)
# Load model Matcha-TTS (kualitas tertinggi sherpa-onnx untuk English)
tts_config = sherpa_onnx.OfflineTtsConfig(
model=sherpa_onnx.OfflineTtsModelConfig(
matcha=sherpa_onnx.OfflineTtsMatchaModelConfig(
acoustic_model="./matcha-icefall-en_US-ljspeech/model-steps-3.onnx",
vocoder="./vocos-22khz-univ.onnx",
tokens="./matcha-icefall-en_US-ljspeech/tokens.txt",
data_dir="./matcha-icefall-en_US-ljspeech/espeak-ng-data",
),
num_threads=2,
)
)
tts = sherpa_onnx.OfflineTts(tts_config)
os.makedirs("outputs", exist_ok=True)
class TTSRequest(BaseModel):
text: str
speed: float = 1.0
@app.get("/")
def root():
return {"status": "K2 Matcha TTS API is running", "quality": "max"}
@app.post("/tts")
def generate_tts(req: TTSRequest):
audio = tts.generate(req.text, sid=0, speed=req.speed)
filename = f"outputs/{uuid.uuid4().hex}.wav"
sf.write(filename, audio.samples, audio.sample_rate)
return FileResponse(filename, media_type="audio/wav", filename="output.wav")