import asyncio from fastapi import FastAPI, HTTPException from fastapi.responses import StreamingResponse from pydantic import BaseModel import edge_tts app = FastAPI() class TTSRequest(BaseModel): text: str voice: str = "en-US-AvaNeural" async def generate_audio_stream(text: str, voice: str): try: communicate = edge_tts.Communicate(text, voice) async for chunk in communicate.stream(): if chunk["type"] == "audio": yield chunk["data"] except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/v1/tts") async def text_to_speech(request: TTSRequest): if not request.text.strip(): raise HTTPException(status_code=400, detail="Text cannot be empty") return StreamingResponse( generate_audio_stream(request.text, request.voice), media_type="audio/mpeg" ) # Root endpoint for checking if the API is awake @app.get("/") def home(): return {"status": "Edge TTS API is running on Hugging Face Spaces!"} if __name__ == "__main__": import uvicorn # Hugging Face Spaces strictly requires port 7860 uvicorn.run(app, host="0.0.0.0", port=7860)