| 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() |
|
|
| |
| app.add_middleware( |
| CORSMiddleware, |
| allow_origins=["*"], |
| allow_methods=["*"], |
| allow_headers=["*"], |
| ) |
|
|
| @app.get("/") |
| def read_root(): |
| |
| 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: |
| |
| 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 |
| |
| port = int(os.environ.get("PORT", 8000)) |
| uvicorn.run(app, host="0.0.0.0", port=port) |
|
|