Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# main.py
|
| 2 |
+
from fastapi import FastAPI, HTTPException
|
| 3 |
+
from fastapi.responses import Response
|
| 4 |
+
from gtts import gTTS
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
import io
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
app = FastAPI(title="Text-to-Speech API")
|
| 10 |
+
|
| 11 |
+
class TextToSpeechRequest(BaseModel):
|
| 12 |
+
text: str
|
| 13 |
+
lang: str = "en"
|
| 14 |
+
slow: bool = False
|
| 15 |
+
|
| 16 |
+
@app.get("/")
|
| 17 |
+
async def root():
|
| 18 |
+
return {"message": "Text-to-Speech API is running. Use POST /tts to convert text to speech."}
|
| 19 |
+
|
| 20 |
+
@app.post("/tts")
|
| 21 |
+
async def text_to_speech(request: TextToSpeechRequest):
|
| 22 |
+
try:
|
| 23 |
+
# Create a bytes buffer
|
| 24 |
+
audio_buffer = io.BytesIO()
|
| 25 |
+
|
| 26 |
+
# Generate TTS audio
|
| 27 |
+
tts = gTTS(text=request.text, lang=request.lang, slow=request.slow)
|
| 28 |
+
tts.write_to_fp(audio_buffer)
|
| 29 |
+
|
| 30 |
+
# Reset buffer pointer to the beginning
|
| 31 |
+
audio_buffer.seek(0)
|
| 32 |
+
|
| 33 |
+
# Return the audio file
|
| 34 |
+
return Response(
|
| 35 |
+
content=audio_buffer.getvalue(),
|
| 36 |
+
media_type="audio/mp3",
|
| 37 |
+
headers={"Content-Disposition": f"attachment; filename=speech.mp3"}
|
| 38 |
+
)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
|
| 41 |
+
|
| 42 |
+
@app.get("/languages")
|
| 43 |
+
async def get_available_languages():
|
| 44 |
+
# List of commonly supported languages in gTTS
|
| 45 |
+
languages = {
|
| 46 |
+
"en": "English",
|
| 47 |
+
"fr": "French",
|
| 48 |
+
"es": "Spanish",
|
| 49 |
+
"de": "German",
|
| 50 |
+
"it": "Italian",
|
| 51 |
+
"ja": "Japanese",
|
| 52 |
+
"ko": "Korean",
|
| 53 |
+
"pt": "Portuguese",
|
| 54 |
+
"ru": "Russian",
|
| 55 |
+
"zh-CN": "Chinese (Simplified)"
|
| 56 |
+
}
|
| 57 |
+
return languages
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
import uvicorn
|
| 61 |
+
port = int(os.environ.get("PORT", 8000))
|
| 62 |
+
uvicorn.run("main:app", host="0.0.0.0", port=port)
|