edge-tts / server.py
Suryaboss's picture
Upload 4 files
91f7734 verified
from fastapi import FastAPI, Response, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
import edge_tts
import tempfile
import os
app = FastAPI()
# Allow CORS for Next.js to call directly or Server-to-Server
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
# Automatically serve the HTML Tester UI if it exists alongside the server script
html_path = os.path.join(os.path.dirname(__file__), "index.html")
if os.path.exists(html_path):
with open(html_path, "r", encoding="utf-8") as f:
return HTMLResponse(content=f.read())
return {"status": "Edge TTS Proxy is running securely"}
@app.get("/tts")
async def generate_tts(text: str, voice: str = "en-US-JennyNeural", rate: str = "+0%"):
if not text:
raise HTTPException(status_code=400, detail="Missing text parameter")
try:
# edge-tts python library natively bypasses 403 API IP Bans automatically!
communicate = edge_tts.Communicate(text, voice, rate=rate)
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as fp:
temp_path = fp.name
await communicate.save(temp_path)
with open(temp_path, "rb") as f:
audio_data = f.read()
os.remove(temp_path)
return Response(content=audio_data, media_type="audio/mpeg")
except Exception as e:
print(f"Server Error during TTS synthesis: {e}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
# Important: Cloud hosts like Render inject the dynamic port into PORT env var
port = int(os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port)