CoolFace
Apppublic

Do0rMaMu/piper-api-2

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
main.py41 linesDownload Raw Back to root
1from fastapi import FastAPI, Form2from fastapi.responses import StreamingResponse3import io4import wave5from piper.voice import PiperVoice6 7app = FastAPI()8 9# Load the voice model10model_path = 'model.onnx'11voice = PiperVoice.load(model_path)12 13@app.post("/synthesize/")14def synthesize_text(text: str = Form(...)):15    """16    Endpoint to synthesize text to speech.17 18    Args:19        text (str): The text to synthesize.20 21    Returns:22        StreamingResponse: The audio data as a stream.23    """24    audio_buffer = io.BytesIO()25 26    # Synthesize speech and write to an in-memory WAV file27    with wave.open(audio_buffer, 'wb') as wav_file:28        wav_file.setnchannels(1)  # Set the number of audio channels29        wav_file.setsampwidth(2)  # Set sample width to 2 bytes30        wav_file.setframerate(16000)  # Set the sampling rate31        audio = voice.synthesize(text, wav_file)32 33    # Seek to the beginning of the buffer so it can be read from the start34    audio_buffer.seek(0)35 36    return StreamingResponse(audio_buffer, media_type="audio/wav")37 38@app.get("/")39def read_root():40    return {"message": "Welcome to the Piper TTS API. Use /synthesize/ to synthesize speech."}41