import subprocess import uuid import os from fastapi import FastAPI, Response from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) @app.get("/") def home(): return "Edge TTS CLI Mode Is Running" @app.get("/tts") def tts(text: str, voice: str = "en-US-AriaNeural", rate: str = "+0%"): # Generate a random filename filename = f"/tmp/{uuid.uuid4()}.mp3" # Command to run edge-tts directly from system cmd = ["edge-tts", "--text", text, "--write-media", filename, "--voice", voice, "--rate", rate] try: # Run the command and wait up to 60 seconds subprocess.run(cmd, check=True, timeout=60) # Read the file with open(filename, "rb") as f: data = f.read() # Cleanup os.remove(filename) return Response(content=data, media_type="audio/mpeg") except subprocess.CalledProcessError as e: return Response(content=f"Edge-TTS Failed (Block or Crash): {str(e)}", status_code=500) except Exception as e: return Response(content=f"System Error: {str(e)}", status_code=500)