Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Form
|
2 |
+
from fastapi.responses import FileResponse
|
3 |
+
import wave
|
4 |
+
from piper.voice import PiperVoice
|
5 |
+
import os
|
6 |
+
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# Load the voice model
|
10 |
+
model_path = 'model.onnx'
|
11 |
+
voice = PiperVoice.load(model_path)
|
12 |
+
|
13 |
+
@app.post("/synthesize/")
|
14 |
+
def 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 |
+
FileResponse: The WAV file containing the synthesized speech.
|
23 |
+
"""
|
24 |
+
output_file = "output.wav"
|
25 |
+
|
26 |
+
# Synthesize speech and save to a WAV file
|
27 |
+
with wave.open(output_file, 'wb') as wav_file:
|
28 |
+
audio = voice.synthesize(text, wav_file)
|
29 |
+
|
30 |
+
# Ensure the file exists and return it as a response
|
31 |
+
if os.path.exists(output_file):
|
32 |
+
return FileResponse(output_file, media_type='audio/wav', filename='output.wav')
|
33 |
+
else:
|
34 |
+
return {"error": "Failed to generate audio."}
|
35 |
+
|
36 |
+
@app.get("/")
|
37 |
+
def read_root():
|
38 |
+
return {"message": "Welcome to the Piper TTS API. Use /synthesize/ to synthesize speech."}
|